@frontmcp/plugin-codecall 1.10.8 → 1.10.9-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.mjs CHANGED
@@ -1,2514 +1,9 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __decorateClass = (decorators, target, key, kind) => {
4
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
5
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
6
- if (decorator = decorators[i])
7
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
8
- if (kind && result) __defProp(target, key, result);
9
- return result;
10
- };
11
-
12
- // plugins/plugin-codecall/src/codecall.plugin.ts
13
- import CachePlugin from "@frontmcp/plugin-cache";
14
- import {
15
- DynamicPlugin,
16
- FrontMcpLogger,
17
- FrontMcpToolTokens,
18
- isEntryGatedBy,
19
- ListToolsHook,
20
- Plugin,
21
- resolveToolVisibility,
22
- ScopeEntry,
23
- ToolHook,
24
- ToolNotFoundError
25
- } from "@frontmcp/sdk";
26
-
27
- // plugins/plugin-codecall/src/codecall.types.ts
28
- import { z } from "@frontmcp/lazy-zod";
29
- var directCallsFilterSchema = z.custom((val) => typeof val === "function", {
30
- message: "filter must be a function with signature (tool: DirectCallsFilterToolInfo) => boolean"
31
- });
32
- var includeToolsFilterSchema = z.custom((val) => typeof val === "function", {
33
- message: "includeTools must be a function with signature (tool: IncludeToolsFilterToolInfo) => boolean"
34
- });
35
- var codeCallModeSchema = z.enum(["codecall_only", "codecall_opt_in", "metadata_driven"]).default("codecall_only");
36
- var codeCallVmPresetSchema = z.enum(["locked_down", "secure", "balanced", "experimental"]).default("secure");
37
- var DEFAULT_VM_OPTIONS = {
38
- preset: "secure"
39
- };
40
- var codeCallVmOptionsSchema = z.object({
41
- /**
42
- * CSP-like preset; see README.
43
- * @default 'secure'
44
- */
45
- preset: codeCallVmPresetSchema,
46
- /**
47
- * Timeout for script execution in milliseconds
48
- * Defaults vary by preset
49
- */
50
- timeoutMs: z.number().positive().optional(),
51
- /**
52
- * Allow `for` loops besides `for-of`; false refuses every loop but `for-of` before the script runs.
53
- * The sandbox always refuses `while`, `do-while` and `for-in`.
54
- * Defaults vary by preset
55
- */
56
- allowLoops: z.boolean().optional(),
57
- /**
58
- * Maximum number of steps (if applicable)
59
- * Defaults vary by preset
60
- */
61
- maxSteps: z.number().positive().optional(),
62
- /**
63
- * List of disabled builtin functions
64
- * Defaults vary by preset
65
- */
66
- disabledBuiltins: z.array(z.string()).optional(),
67
- /**
68
- * List of disabled global variables
69
- * Defaults vary by preset
70
- */
71
- disabledGlobals: z.array(z.string()).optional(),
72
- /**
73
- * @deprecated Has no effect: scripts never get `console`, and one that uses it is refused before it runs.
74
- * Scripts log with `mcpLog(level, message)`.
75
- */
76
- allowConsole: z.boolean().optional(),
77
- /**
78
- * Maximum nesting depth for sanitized output values
79
- * Prevents deeply nested objects from causing stack overflow
80
- * @default varies by preset (secure: 50)
81
- */
82
- maxSanitizeDepth: z.number().positive().optional(),
83
- /**
84
- * Maximum properties per object in sanitized output values
85
- * Limits array sizes and object keys in return values
86
- * @default varies by preset (secure: 2000)
87
- */
88
- maxSanitizeProperties: z.number().positive().optional(),
89
- /**
90
- * Calls a script may make to one tool within about 2 seconds; one more stops the script with
91
- * `[RAPID_ENUMERATION]`. Calls made through `parallel()` count. The sandbox's message says "in 5s",
92
- * but it keeps only the last 2 seconds of calls.
93
- * @default 30
94
- */
95
- rapidEnumerationThreshold: z.number().int().positive().optional(),
96
- /**
97
- * Per-tool values of `rapidEnumerationThreshold`, by tool name, e.g. `{ 'users:get': 100 }`.
98
- */
99
- rapidEnumerationOverrides: z.record(z.string(), z.number().int().positive()).optional()
100
- }).default(() => DEFAULT_VM_OPTIONS);
101
- var codeCallDirectCallsOptionsSchema = z.object({
102
- /**
103
- * Enable/disable the `codecall.invoke` meta-tool.
104
- */
105
- enabled: z.boolean(),
106
- /**
107
- * Optional allowlist of tool names.
108
- */
109
- allowedTools: z.array(z.string()).optional(),
110
- /**
111
- * Optional advanced filter function.
112
- * Signature: (tool: DirectCallsFilterToolInfo) => boolean
113
- */
114
- filter: directCallsFilterSchema.optional()
115
- });
116
- var embeddingStrategySchema = z.enum(["tfidf", "ml"]).default("tfidf");
117
- var synonymExpansionConfigSchema = z.object({
118
- /**
119
- * Enable/disable synonym expansion for TF-IDF search.
120
- * When enabled, queries are expanded with synonyms to improve relevance.
121
- * For example, "add user" will also match tools containing "create user".
122
- * @default true
123
- */
124
- enabled: z.boolean().default(true),
125
- /**
126
- * Additional synonym groups beyond the defaults.
127
- * Each group is an array of related terms that should be treated as equivalent.
128
- * @example [['customer', 'client', 'buyer'], ['order', 'purchase', 'transaction']]
129
- */
130
- additionalSynonyms: z.array(z.array(z.string())).optional(),
131
- /**
132
- * Replace default synonyms entirely with additionalSynonyms.
133
- * @default false
134
- */
135
- replaceDefaults: z.boolean().default(false),
136
- /**
137
- * Maximum number of synonym expansions per term.
138
- * Prevents query explosion for terms with many synonyms.
139
- * @default 5
140
- */
141
- maxExpansionsPerTerm: z.number().positive().default(5)
142
- }).default({ enabled: true, replaceDefaults: false, maxExpansionsPerTerm: 5 });
143
- var DEFAULT_EMBEDDING_OPTIONS = {
144
- strategy: "tfidf",
145
- modelName: "Xenova/all-MiniLM-L6-v2",
146
- cacheDir: "./.cache/transformers",
147
- useHNSW: false,
148
- synonymExpansion: { enabled: true, replaceDefaults: false, maxExpansionsPerTerm: 5 }
149
- };
150
- var codeCallEmbeddingOptionsSchema = z.object({
151
- /**
152
- * Embedding strategy to use for tool search
153
- * - 'tfidf': Lightweight, synchronous TF-IDF based search (no ML models required)
154
- * - 'ml': ML-based semantic search using transformers.js (better quality, requires model download)
155
- * @default 'tfidf'
156
- */
157
- strategy: embeddingStrategySchema.optional(),
158
- /**
159
- * Model name for ML-based embeddings (only used when strategy='ml')
160
- * @default 'Xenova/all-MiniLM-L6-v2'
161
- */
162
- modelName: z.string().optional(),
163
- /**
164
- * Cache directory for ML models (only used when strategy='ml')
165
- * @default './.cache/transformers'
166
- */
167
- cacheDir: z.string().optional(),
168
- /**
169
- * Enable HNSW index for faster search (only used when strategy='ml')
170
- * When enabled, provides O(log n) search instead of O(n) brute-force
171
- * @default false
172
- */
173
- useHNSW: z.boolean().optional(),
174
- /**
175
- * Synonym expansion configuration for TF-IDF search.
176
- * When enabled, queries like "add user" will match tools for "create user".
177
- * Only applies when strategy is 'tfidf' (ML already handles semantic similarity).
178
- * Set to false to disable, or provide a config object to customize.
179
- * @default { enabled: true }
180
- */
181
- synonymExpansion: z.union([z.literal(false), synonymExpansionConfigSchema]).optional()
182
- }).optional().transform((opts) => ({
183
- strategy: opts?.strategy ?? DEFAULT_EMBEDDING_OPTIONS.strategy,
184
- modelName: opts?.modelName ?? DEFAULT_EMBEDDING_OPTIONS.modelName,
185
- cacheDir: opts?.cacheDir ?? DEFAULT_EMBEDDING_OPTIONS.cacheDir,
186
- useHNSW: opts?.useHNSW ?? DEFAULT_EMBEDDING_OPTIONS.useHNSW,
187
- synonymExpansion: opts?.synonymExpansion ?? DEFAULT_EMBEDDING_OPTIONS.synonymExpansion
188
- }));
189
- var codeCallSidecarOptionsSchema = z.object({
190
- /**
191
- * Enable pass-by-reference support via sidecar
192
- * When enabled, large strings are automatically lifted to a sidecar
193
- * and resolved at the callTool boundary
194
- * @default false
195
- */
196
- enabled: z.boolean().default(false),
197
- /**
198
- * Maximum total size of all stored references in bytes
199
- * @default 16MB (from security level)
200
- */
201
- maxTotalSize: z.number().positive().optional(),
202
- /**
203
- * Maximum size of a single reference in bytes
204
- * @default 4MB (from security level)
205
- */
206
- maxReferenceSize: z.number().positive().optional(),
207
- /**
208
- * Threshold in bytes to trigger extraction from source code
209
- * Strings larger than this are lifted to the sidecar
210
- * @default 64KB (from security level)
211
- */
212
- extractionThreshold: z.number().positive().optional(),
213
- /**
214
- * Maximum expanded size when resolving references for tool calls
215
- * @default 8MB (from security level)
216
- */
217
- maxResolvedSize: z.number().positive().optional(),
218
- /**
219
- * Whether to allow composite handles from string concatenation
220
- * If false, concatenating references throws an error
221
- * @default false (strict mode)
222
- */
223
- allowComposites: z.boolean().optional(),
224
- /**
225
- * Maximum script length (in characters) when sidecar is disabled
226
- * Prevents large inline data from being embedded in script
227
- * If null, no limit is enforced
228
- * @default 64KB
229
- */
230
- maxScriptLengthWhenDisabled: z.number().positive().nullable().default(64 * 1024)
231
- }).default(() => ({
232
- enabled: false,
233
- maxScriptLengthWhenDisabled: 64 * 1024
234
- }));
235
- var codeCallPluginOptionsObjectSchema = z.object({
236
- /**
237
- * CodeCall mode
238
- * @default 'codecall_only'
239
- */
240
- mode: codeCallModeSchema,
241
- /**
242
- * App IDs that CodeCall manages. When set, `codecall_only` mode only hides tools
243
- * from these apps — tools from other apps remain visible in list_tools.
244
- * When unset (default), all tools in the server are affected.
245
- * @example ['ecommerce'] — only hide ecommerce app tools, keep calc tools visible
246
- */
247
- appIds: z.array(z.string()).optional(),
248
- /**
249
- * Search results per query when a `codecall:search` call names no `topK`
250
- * @default 8
251
- */
252
- topK: z.number().positive().default(8),
253
- /**
254
- * Most tool definitions one `codecall:describe` call returns; a call that would describe more is refused
255
- * @default 8
256
- */
257
- maxDefinitions: z.number().int().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/providers/code-call.config.ts
295
- import { BaseConfig, Provider, ProviderScope } from "@frontmcp/sdk";
296
- var CodeCallConfig = class extends BaseConfig {
297
- constructor(options = {}) {
298
- const parsedConfig = codeCallPluginOptionsSchema.parse(options);
299
- const resolvedVm = resolveVmOptions(parsedConfig.vm);
300
- super({ ...parsedConfig, resolvedVm });
301
- }
302
- };
303
- CodeCallConfig = __decorateClass([
304
- Provider({
305
- name: "codecall:config",
306
- description: "CodeCall plugin configuration with validated defaults",
307
- scope: ProviderScope.GLOBAL
308
- })
309
- ], CodeCallConfig);
310
- var MAX_ITERATIONS_PER_LOOP = 1e4;
311
- function maxToolCallsOf(vmOptions) {
312
- return vmOptions.maxSteps || 100;
313
- }
314
- var SANDBOX_RAPID_ENUMERATION_THRESHOLD = 30;
315
- function rapidEnumerationThresholdOf(vmOptions) {
316
- return vmOptions.rapidEnumerationThreshold ?? SANDBOX_RAPID_ENUMERATION_THRESHOLD;
317
- }
318
- function resolveVmOptions(vmOptions) {
319
- const preset = vmOptions?.preset ?? "secure";
320
- const base = presetDefaults(preset);
321
- return {
322
- ...base,
323
- ...vmOptions,
324
- disabledBuiltins: vmOptions?.disabledBuiltins ?? base.disabledBuiltins,
325
- disabledGlobals: vmOptions?.disabledGlobals ?? base.disabledGlobals
326
- };
327
- }
328
- function presetDefaults(preset) {
329
- switch (preset) {
330
- case "locked_down":
331
- return {
332
- preset,
333
- timeoutMs: 2e3,
334
- allowLoops: false,
335
- allowConsole: false,
336
- maxSteps: 2e3,
337
- disabledBuiltins: ["eval", "Function", "AsyncFunction"],
338
- disabledGlobals: [
339
- "require",
340
- "process",
341
- "fetch",
342
- "setTimeout",
343
- "setInterval",
344
- "setImmediate",
345
- "global",
346
- "globalThis"
347
- ],
348
- maxSanitizeDepth: 10,
349
- maxSanitizeProperties: 1e3
350
- };
351
- case "balanced":
352
- return {
353
- preset,
354
- timeoutMs: 5e3,
355
- allowLoops: true,
356
- allowConsole: true,
357
- maxSteps: 1e4,
358
- disabledBuiltins: ["eval", "Function", "AsyncFunction"],
359
- disabledGlobals: ["require", "process", "fetch"],
360
- maxSanitizeDepth: 50,
361
- maxSanitizeProperties: 5e3
362
- };
363
- case "experimental":
364
- return {
365
- preset,
366
- timeoutMs: 1e4,
367
- allowLoops: true,
368
- allowConsole: true,
369
- maxSteps: 2e4,
370
- disabledBuiltins: ["eval", "Function", "AsyncFunction"],
371
- disabledGlobals: ["require", "process"],
372
- maxSanitizeDepth: 100,
373
- maxSanitizeProperties: 2e4
374
- };
375
- case "secure":
376
- default:
377
- return {
378
- preset: "secure",
379
- timeoutMs: 3500,
380
- allowLoops: false,
381
- allowConsole: true,
382
- maxSteps: 5e3,
383
- disabledBuiltins: ["eval", "Function", "AsyncFunction"],
384
- disabledGlobals: [
385
- "require",
386
- "process",
387
- "fetch",
388
- "setTimeout",
389
- "setInterval",
390
- "setImmediate",
391
- "global",
392
- "globalThis"
393
- ],
394
- maxSanitizeDepth: 50,
395
- maxSanitizeProperties: 2e3
396
- };
397
- }
398
- }
399
-
400
- // plugins/plugin-codecall/src/security/codecall-dispatch.ts
401
- import { getRunningTool } from "@frontmcp/sdk";
402
- var CODECALL_DISPATCH = /* @__PURE__ */ Symbol("frontmcp.codecall.dispatch");
403
- function asCodeCallDispatch(ctx) {
404
- return Object.defineProperty(ctx, CODECALL_DISPATCH, { value: true, enumerable: false });
405
- }
406
- function isInProcessDispatch(ctx) {
407
- if (getRunningTool()) return true;
408
- if (typeof ctx !== "object" || ctx === null) return false;
409
- const marks = ctx;
410
- return marks[CODECALL_DISPATCH] === true || marks.internalCall === true;
411
- }
412
-
413
- // plugins/plugin-codecall/src/security/codecall-tool-policy.ts
414
- var BLOCKED_NAMESPACE_PATTERNS = Object.freeze([/^system:/, /^internal:/, /^__/]);
415
- function isOfferedToCaller(availableWhen, surface) {
416
- const offered = availableWhen?.surface;
417
- return offered === void 0 || surface === void 0 || offered.includes(surface);
418
- }
419
- var ALLOWED = { allowed: true };
420
- function deny(reason) {
421
- return { allowed: false, reason };
422
- }
423
- function codeCallAppIdOf(scope, entry) {
424
- const lineage = scope?.tools?.lineageOf?.(entry) ?? [];
425
- const owners = entry.owner ? [...lineage, entry.owner] : lineage;
426
- return owners.find((owner) => owner.kind === "app")?.id;
427
- }
428
- function toCodeCallPolicyTool(entry, requestedName, scope) {
429
- const { metadata } = entry;
430
- return {
431
- name: entry.name || entry.fullName,
432
- fullName: entry.fullName,
433
- aliases: requestedName ? [requestedName] : void 0,
434
- appId: codeCallAppIdOf(scope, entry),
435
- description: metadata?.description,
436
- tags: metadata?.tags,
437
- // `internal` tools refuse every external tools/call, CodeCall's included, so no surface may offer them.
438
- hidden: metadata?.hideFromDiscovery === true || metadata?.visibility === "hidden" || metadata?.visibility === "internal",
439
- codecall: metadata?.codecall,
440
- annotations: metadata?.annotations,
441
- metadata
442
- };
443
- }
444
- function isPlainData(value) {
445
- if (Array.isArray(value)) return true;
446
- const proto = Object.getPrototypeOf(value);
447
- return proto === Object.prototype || proto === null;
448
- }
449
- function readOnlyCopy(value, copies) {
450
- if (typeof value !== "object" || value === null || !isPlainData(value)) return value;
451
- const existing = copies.get(value);
452
- if (existing !== void 0) return existing;
453
- const copy = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
454
- copies.set(value, copy);
455
- for (const key of Reflect.ownKeys(value)) {
456
- if (!Object.prototype.propertyIsEnumerable.call(value, key)) continue;
457
- Object.defineProperty(copy, key, {
458
- value: readOnlyCopy(Reflect.get(value, key), copies),
459
- enumerable: true,
460
- writable: true,
461
- configurable: true
462
- });
463
- }
464
- return Object.freeze(copy);
465
- }
466
- function toToolFilterInfo(tool) {
467
- const copies = /* @__PURE__ */ new WeakMap();
468
- const annotations = readOnlyCopy(tool.annotations, copies);
469
- const metadata = tool.metadata ? readOnlyCopy({ ...tool.metadata, ...annotations ? { annotations: tool.annotations } : {} }, copies) : void 0;
470
- return {
471
- name: tool.name,
472
- fullName: tool.fullName,
473
- appId: tool.appId,
474
- source: tool.codecall?.source,
475
- description: tool.description,
476
- tags: readOnlyCopy(tool.codecall?.tags ?? tool.tags, copies),
477
- annotations,
478
- metadata
479
- };
480
- }
481
- function ownNamesOf(tool) {
482
- return [tool.name, tool.fullName].filter((candidate) => !!candidate);
483
- }
484
- function checkCodeCallToolPolicy(tool, config) {
485
- const { name } = tool;
486
- const spellings = [...ownNamesOf(tool), ...tool.aliases ?? []];
487
- if (spellings.some((candidate) => candidate.startsWith("codecall:"))) {
488
- return deny("CodeCall meta-tools are not callable from CodeCall");
489
- }
490
- for (const candidate of spellings) {
491
- if (BLOCKED_NAMESPACE_PATTERNS.some((pattern) => pattern.test(candidate))) {
492
- return deny(`Tool "${candidate}" is in a namespace CodeCall never calls`);
493
- }
494
- }
495
- if (tool.hidden === true) {
496
- return deny(`Tool "${name}" is hidden from discovery`);
497
- }
498
- const enabled = tool.codecall?.enabledInCodeCall;
499
- switch (config.mode) {
500
- case "codecall_only":
501
- case "metadata_driven":
502
- if (enabled === false) {
503
- return deny(`Tool "${name}" sets enabledInCodeCall: false`);
504
- }
505
- break;
506
- case "codecall_opt_in":
507
- if (enabled !== true) {
508
- return deny(`Tool "${name}" has not opted in to CodeCall`);
509
- }
510
- break;
511
- default:
512
- return deny(`Unknown CodeCall mode: ${String(config.mode)}`);
513
- }
514
- if (config.includeTools && !config.includeTools(toToolFilterInfo(tool))) {
515
- return deny(`Tool "${name}" is excluded by the includeTools filter`);
516
- }
517
- return ALLOWED;
518
- }
519
- function denyUnknownTool(name) {
520
- return deny(`Tool "${name}" is not available through CodeCall`);
521
- }
522
- function resolveCodeCallTool(scope, name) {
523
- const typedScope = scope;
524
- const alias = /[-_]/.test(name) ? name.includes("_") ? name.replace(/_/g, "-") : name.replace(/-/g, "_") : void 0;
525
- const candidates = alias ? [name, alias] : [name];
526
- const matches = (entry) => candidates.includes(entry.fullName) || candidates.includes(entry.name);
527
- const local = typedScope.tools?.getTools(true)?.find(matches);
528
- if (local) return local;
529
- const registries = typedScope.providers?.getRegistries?.("AppRegistry") ?? [];
530
- for (const registry of registries) {
531
- for (const app of registry.getApps()) {
532
- if (!app.isRemote) continue;
533
- const remote = app.tools.getTools(true).find(matches);
534
- if (remote) return remote;
535
- }
536
- }
537
- return void 0;
538
- }
539
- function checkDirectCallPolicy(tool, directCalls) {
540
- if (!directCalls) return ALLOWED;
541
- if (directCalls.enabled === false) {
542
- return deny("Direct tool invocation is disabled");
543
- }
544
- const { allowedTools } = directCalls;
545
- if (allowedTools && !ownNamesOf(tool).some((ownName) => allowedTools.includes(ownName))) {
546
- return deny(`Tool "${tool.name}" is not in the direct-call allowlist`);
547
- }
548
- if (directCalls.filter && !directCalls.filter(toToolFilterInfo(tool))) {
549
- return deny(`Tool "${tool.name}" is excluded by the directCalls filter`);
550
- }
551
- return ALLOWED;
552
- }
553
- function readCodeCallPolicyConfig(config) {
554
- return {
555
- // An absent mode means an unparsed/partial config, not a hostile one: fall back to the
556
- // schema's own documented default rather than denying every call. An unrecognised mode
557
- // still fails closed inside the policy's switch.
558
- mode: config.get("mode") ?? "codecall_only",
559
- includeTools: config.get("includeTools")
560
- };
561
- }
562
- function checkCodeCallToolAccess(scope, config, name, options = {}) {
563
- const entry = resolveCodeCallTool(scope, name);
564
- if (!entry) return denyUnknownTool(name);
565
- if (!isOfferedToCaller(entry.metadata?.availableWhen, options.surface)) {
566
- return deny(`Tool "${name}" is not offered on the caller's surface "${options.surface}"`);
567
- }
568
- const policyTool = toCodeCallPolicyTool(entry, name, scope);
569
- const baseDecision = checkCodeCallToolPolicy(policyTool, readCodeCallPolicyConfig(config));
570
- if (!baseDecision.allowed) return baseDecision;
571
- if (options.directCall) {
572
- const directDecision = checkDirectCallPolicy(
573
- policyTool,
574
- config.get("directCalls")
575
- );
576
- if (!directDecision.allowed) return directDecision;
577
- }
578
- return { allowed: true, entry };
579
- }
580
-
581
- // plugins/plugin-codecall/src/utils/client-error-message.ts
582
- var EMBEDDED_STACK_FRAME_RE = /\n[ \t]*at\s[^\n]*/g;
583
- var QUOTED_PATH_RE = /(['"`])((?:~?\/|[A-Za-z]:[\\/]|\\\\)[^\s'"`\\/][^'"`\n]*)\1/g;
584
- var URL_RE = /\b[A-Za-z][A-Za-z0-9+.-]{1,31}:\/\/(?:[^\s'"`<>,;]|[,;](?!~?\/|[A-Za-z]:[\\/]|\\\\))*/g;
585
- var QUERY_PATH_VALUE_RE = /([?&][^=&#]*=)(?:~?\/|[A-Za-z]:[\\/]|\\\\)[^&#]*/g;
586
- var POSIX_SEGMENT = String.raw`[^\s/\\'"\x60<>|,;:()\[\]{}]+`;
587
- var WINDOWS_SEGMENT = String.raw`[^\s/\\'"\x60<>|,;:*?]+`;
588
- function segments(segment, separator) {
589
- const spaced = `${segment}(?: ${segment}){0,2}`;
590
- return `(?:(?:${spaced}${separator})+(?:${segment})?|${segment})`;
591
- }
592
- var UNQUOTED_PATH_RE = new RegExp(
593
- [
594
- String.raw`(?<![\w.~/\\)\]-])~?/+${segments(POSIX_SEGMENT, "/+")}`,
595
- String.raw`(?<![\w\\/])[A-Za-z]:[\\/]+${segments(WINDOWS_SEGMENT, String.raw`[\\/]+`)}?`,
596
- String.raw`(?<![\w\\])\\\\${segments(WINDOWS_SEGMENT, String.raw`[\\/]+`)}`
597
- ].join("|"),
598
- "g"
599
- );
600
- function redactPaths(text) {
601
- return text.replace(QUOTED_PATH_RE, "$1[path]$1").replace(UNQUOTED_PATH_RE, "[path]");
602
- }
603
- function toClientErrorMessage(message) {
604
- if (!message) return "";
605
- return redactAbsolutePaths(message.replace(EMBEDDED_STACK_FRAME_RE, ""));
606
- }
607
- function redactAbsolutePaths(text) {
608
- let result = "";
609
- let last = 0;
610
- for (const match of text.matchAll(URL_RE)) {
611
- const start = match.index ?? 0;
612
- result += redactPaths(text.slice(last, start));
613
- result += /^file:/i.test(match[0]) ? "[path]" : match[0].replace(QUERY_PATH_VALUE_RE, "$1[path]");
614
- last = start + match[0].length;
615
- }
616
- return result + redactPaths(text.slice(last));
617
- }
618
-
619
- // plugins/plugin-codecall/src/errors/tool-call.errors.ts
620
- var TOOL_CALL_ERROR_CODES = {
621
- NOT_FOUND: "NOT_FOUND",
622
- VALIDATION: "VALIDATION",
623
- EXECUTION: "EXECUTION",
624
- TIMEOUT: "TIMEOUT",
625
- ACCESS_DENIED: "ACCESS_DENIED",
626
- RATE_LIMITED: "RATE_LIMITED",
627
- SELF_REFERENCE: "SELF_REFERENCE"
628
- };
629
- function createToolCallError(code, toolName, rawMessage) {
630
- const sanitizedMessage = getSanitizedMessage(code, toolName, rawMessage);
631
- return Object.freeze({
632
- code,
633
- message: sanitizedMessage,
634
- toolName
635
- });
636
- }
637
- function getSanitizedMessage(code, toolName, rawMessage) {
638
- switch (code) {
639
- case TOOL_CALL_ERROR_CODES.NOT_FOUND:
640
- return `Tool "${toolName}" was not found`;
641
- case TOOL_CALL_ERROR_CODES.VALIDATION:
642
- return rawMessage ? sanitizeValidationMessage(rawMessage) : `Input validation failed for tool "${toolName}"`;
643
- case TOOL_CALL_ERROR_CODES.EXECUTION:
644
- return `Tool "${toolName}" execution failed`;
645
- case TOOL_CALL_ERROR_CODES.TIMEOUT:
646
- return `Tool "${toolName}" execution timed out`;
647
- case TOOL_CALL_ERROR_CODES.ACCESS_DENIED:
648
- return `Access denied for tool "${toolName}"`;
649
- case TOOL_CALL_ERROR_CODES.RATE_LIMITED:
650
- return `Tool "${toolName}" was rate limited`;
651
- case TOOL_CALL_ERROR_CODES.SELF_REFERENCE:
652
- return `Cannot call CodeCall tools from within AgentScript`;
653
- default:
654
- return `An error occurred while calling "${toolName}"`;
655
- }
656
- }
657
- function sanitizeValidationMessage(message) {
658
- let sanitized = toClientErrorMessage(message);
659
- sanitized = sanitized.replace(/\bat line \d+/gi, "");
660
- sanitized = sanitized.replace(/\bline \d+/gi, "");
661
- sanitized = sanitized.replace(/:\d+:\d+/g, "");
662
- if (sanitized.length > 200) {
663
- sanitized = sanitized.substring(0, 200) + "...";
664
- }
665
- return sanitized.trim();
666
- }
667
- var SelfReferenceError = class extends Error {
668
- code = TOOL_CALL_ERROR_CODES.SELF_REFERENCE;
669
- toolName;
670
- constructor(toolName) {
671
- super(`Self-reference attack: Attempted to call CodeCall tool "${toolName}" from within AgentScript`);
672
- this.name = "SelfReferenceError";
673
- this.toolName = toolName;
674
- Object.freeze(this);
675
- }
676
- };
677
-
678
- // plugins/plugin-codecall/src/security/self-reference-guard.ts
679
- var CODECALL_TOOL_PREFIX = "codecall:";
680
- var BLOCKED_CODECALL_TOOLS = Object.freeze(
681
- /* @__PURE__ */ new Set(["codecall:search", "codecall:describe", "codecall:execute", "codecall:invoke"])
682
- );
683
- function isBlockedSelfReference(toolName) {
684
- const normalizedName = toolName.toLowerCase().trim();
685
- if (normalizedName.startsWith(CODECALL_TOOL_PREFIX)) {
686
- return true;
687
- }
688
- if (BLOCKED_CODECALL_TOOLS.has(toolName)) {
689
- return true;
690
- }
691
- return false;
692
- }
693
- function assertNotSelfReference(toolName) {
694
- if (isBlockedSelfReference(toolName)) {
695
- throw new SelfReferenceError(toolName);
696
- }
697
- }
698
-
699
- // plugins/plugin-codecall/src/services/audit-logger.service.ts
700
- import { Provider as Provider2, ProviderScope as ProviderScope2 } from "@frontmcp/sdk";
701
- var AUDIT_EVENT_TYPES = {
702
- /** Script execution started */
703
- EXECUTION_START: "codecall:execution:start",
704
- /** Script execution completed successfully */
705
- EXECUTION_SUCCESS: "codecall:execution:success",
706
- /** Script execution failed */
707
- EXECUTION_FAILURE: "codecall:execution:failure",
708
- /** Script execution timed out */
709
- EXECUTION_TIMEOUT: "codecall:execution:timeout",
710
- /** Tool call initiated from script */
711
- TOOL_CALL_START: "codecall:tool:call:start",
712
- /** Tool call completed successfully */
713
- TOOL_CALL_SUCCESS: "codecall:tool:call:success",
714
- /** Tool call failed */
715
- TOOL_CALL_FAILURE: "codecall:tool:call:failure",
716
- /** Self-reference attack blocked */
717
- SECURITY_SELF_REFERENCE: "codecall:security:self-reference",
718
- /** Tool access denied */
719
- SECURITY_ACCESS_DENIED: "codecall:security:access-denied",
720
- /** AST validation failed (blocked code pattern) */
721
- SECURITY_AST_BLOCKED: "codecall:security:ast-blocked",
722
- /** Search performed */
723
- SEARCH_PERFORMED: "codecall:search:performed",
724
- /** Tool described */
725
- DESCRIBE_PERFORMED: "codecall:describe:performed",
726
- /** Direct invoke performed */
727
- INVOKE_PERFORMED: "codecall:invoke:performed"
728
- };
729
- var AuditLoggerService = class {
730
- listeners = /* @__PURE__ */ new Set();
731
- executionCounter = 0;
732
- /**
733
- * Subscribe to audit events.
734
- *
735
- * @param listener - Function to call when events occur
736
- * @returns Unsubscribe function
737
- */
738
- subscribe(listener) {
739
- this.listeners.add(listener);
740
- return () => {
741
- this.listeners.delete(listener);
742
- };
743
- }
744
- /**
745
- * Generate a unique execution ID.
746
- */
747
- generateExecutionId() {
748
- const timestamp = Date.now().toString(36);
749
- const counter = (++this.executionCounter).toString(36).padStart(4, "0");
750
- const random = Math.random().toString(36).substring(2, 8);
751
- return `exec_${timestamp}_${counter}_${random}`;
752
- }
753
- /**
754
- * Log execution start.
755
- */
756
- logExecutionStart(executionId, script) {
757
- this.emit({
758
- type: AUDIT_EVENT_TYPES.EXECUTION_START,
759
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
760
- executionId,
761
- data: {
762
- scriptHash: this.hashScript(script),
763
- scriptLength: script.length
764
- }
765
- });
766
- }
767
- /**
768
- * Log execution success.
769
- */
770
- logExecutionSuccess(executionId, script, durationMs, toolCallCount) {
771
- this.emit({
772
- type: AUDIT_EVENT_TYPES.EXECUTION_SUCCESS,
773
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
774
- executionId,
775
- durationMs,
776
- data: {
777
- scriptHash: this.hashScript(script),
778
- scriptLength: script.length,
779
- toolCallCount
780
- }
781
- });
782
- }
783
- /**
784
- * Log execution failure.
785
- */
786
- logExecutionFailure(executionId, script, durationMs, error) {
787
- this.emit({
788
- type: AUDIT_EVENT_TYPES.EXECUTION_FAILURE,
789
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
790
- executionId,
791
- durationMs,
792
- data: {
793
- scriptHash: this.hashScript(script),
794
- scriptLength: script.length,
795
- error: this.sanitizeError(error)
796
- }
797
- });
798
- }
799
- /**
800
- * Log execution timeout.
801
- */
802
- logExecutionTimeout(executionId, script, durationMs) {
803
- this.emit({
804
- type: AUDIT_EVENT_TYPES.EXECUTION_TIMEOUT,
805
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
806
- executionId,
807
- durationMs,
808
- data: {
809
- scriptHash: this.hashScript(script),
810
- scriptLength: script.length
811
- }
812
- });
813
- }
814
- /**
815
- * Log tool call start.
816
- */
817
- logToolCallStart(executionId, toolName, callDepth) {
818
- this.emit({
819
- type: AUDIT_EVENT_TYPES.TOOL_CALL_START,
820
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
821
- executionId,
822
- data: {
823
- toolName,
824
- callDepth
825
- }
826
- });
827
- }
828
- /**
829
- * Log tool call success.
830
- */
831
- logToolCallSuccess(executionId, toolName, callDepth, durationMs) {
832
- this.emit({
833
- type: AUDIT_EVENT_TYPES.TOOL_CALL_SUCCESS,
834
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
835
- executionId,
836
- durationMs,
837
- data: {
838
- toolName,
839
- callDepth
840
- }
841
- });
842
- }
843
- /**
844
- * Log tool call failure.
845
- */
846
- logToolCallFailure(executionId, toolName, callDepth, durationMs, errorCode) {
847
- this.emit({
848
- type: AUDIT_EVENT_TYPES.TOOL_CALL_FAILURE,
849
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
850
- executionId,
851
- durationMs,
852
- data: {
853
- toolName,
854
- callDepth,
855
- errorCode
856
- }
857
- });
858
- }
859
- /**
860
- * Log security event: self-reference blocked.
861
- */
862
- logSecuritySelfReference(executionId, toolName) {
863
- this.emit({
864
- type: AUDIT_EVENT_TYPES.SECURITY_SELF_REFERENCE,
865
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
866
- executionId,
867
- data: {
868
- blocked: toolName,
869
- reason: "Self-reference attack: attempted to call CodeCall tool from within AgentScript"
870
- }
871
- });
872
- }
873
- /**
874
- * Log security event: access denied.
875
- */
876
- logSecurityAccessDenied(executionId, toolName, reason) {
877
- this.emit({
878
- type: AUDIT_EVENT_TYPES.SECURITY_ACCESS_DENIED,
879
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
880
- executionId,
881
- data: {
882
- blocked: toolName,
883
- reason: this.sanitizeError(reason)
884
- }
885
- });
886
- }
887
- /**
888
- * Log security event: AST validation blocked.
889
- */
890
- logSecurityAstBlocked(executionId, pattern, reason) {
891
- this.emit({
892
- type: AUDIT_EVENT_TYPES.SECURITY_AST_BLOCKED,
893
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
894
- executionId,
895
- data: {
896
- blocked: pattern,
897
- reason: this.sanitizeError(reason)
898
- }
899
- });
900
- }
901
- /**
902
- * Log search operation.
903
- */
904
- logSearch(executionId, query, resultCount, durationMs) {
905
- this.emit({
906
- type: AUDIT_EVENT_TYPES.SEARCH_PERFORMED,
907
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
908
- executionId,
909
- durationMs,
910
- data: {
911
- queryLength: query.length,
912
- resultCount
913
- }
914
- });
915
- }
916
- /**
917
- * Log describe operation.
918
- */
919
- logDescribe(executionId, toolNames, durationMs) {
920
- this.emit({
921
- type: AUDIT_EVENT_TYPES.DESCRIBE_PERFORMED,
922
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
923
- executionId,
924
- durationMs,
925
- data: {
926
- toolCount: toolNames.length,
927
- toolNames: toolNames.slice(0, 10)
928
- // Limit to first 10 for audit
929
- }
930
- });
931
- }
932
- /**
933
- * Log invoke operation.
934
- */
935
- logInvoke(executionId, toolName, success, durationMs) {
936
- this.emit({
937
- type: AUDIT_EVENT_TYPES.INVOKE_PERFORMED,
938
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
939
- executionId,
940
- durationMs,
941
- data: {
942
- toolName,
943
- success
944
- }
945
- });
946
- }
947
- /**
948
- * Emit an audit event to all listeners.
949
- */
950
- emit(event) {
951
- const frozenEvent = Object.freeze({ ...event, data: Object.freeze({ ...event.data }) });
952
- for (const listener of this.listeners) {
953
- try {
954
- listener(frozenEvent);
955
- } catch {
956
- }
957
- }
958
- }
959
- /**
960
- * Create a simple hash of the script for identification.
961
- * Uses a fast, non-cryptographic hash for performance.
962
- */
963
- hashScript(script) {
964
- let hash = 0;
965
- for (let i = 0; i < script.length; i++) {
966
- const char = script.charCodeAt(i);
967
- hash = (hash << 5) - hash + char;
968
- hash = hash & hash;
969
- }
970
- return `sh_${(hash >>> 0).toString(16).padStart(8, "0")}`;
971
- }
972
- /**
973
- * Sanitize error messages to remove sensitive information.
974
- */
975
- sanitizeError(error) {
976
- if (!error) return "Unknown error";
977
- let sanitized = toClientErrorMessage(error);
978
- sanitized = sanitized.replace(/:\d+:\d+/g, "");
979
- if (sanitized.length > 200) {
980
- sanitized = sanitized.substring(0, 200) + "...";
981
- }
982
- return sanitized.trim();
983
- }
984
- };
985
- AuditLoggerService = __decorateClass([
986
- Provider2({
987
- name: "codecall:audit-logger",
988
- scope: ProviderScope2.GLOBAL
989
- })
990
- ], AuditLoggerService);
991
-
992
- // plugins/plugin-codecall/src/services/tool-search.service.ts
993
- import { TFIDFVectoria, VectoriaDB } from "vectoriadb";
994
-
995
- // plugins/plugin-codecall/src/services/synonym-expansion.service.ts
996
- var DEFAULT_SYNONYM_GROUPS = [
997
- // ===========================================================================
998
- // 1. CORE DATA OPERATIONS (CRUD+)
999
- // ===========================================================================
1000
- // Creation / Instantiation
1001
- [
1002
- "create",
1003
- "add",
1004
- "new",
1005
- "insert",
1006
- "make",
1007
- "append",
1008
- "register",
1009
- "generate",
1010
- "produce",
1011
- "build",
1012
- "construct",
1013
- "provision",
1014
- "instantiate",
1015
- "define",
1016
- "compose",
1017
- "draft"
1018
- ],
1019
- // Destructive Removal
1020
- [
1021
- "delete",
1022
- "remove",
1023
- "destroy",
1024
- "drop",
1025
- "erase",
1026
- "clear",
1027
- "purge",
1028
- "discard",
1029
- "eliminate",
1030
- "nuke",
1031
- "unbind",
1032
- "unregister"
1033
- ],
1034
- // Retrieval / Access
1035
- ["get", "fetch", "retrieve", "read", "obtain", "load", "pull", "access", "grab", "snag", "receive"],
1036
- // Modification
1037
- [
1038
- "update",
1039
- "edit",
1040
- "modify",
1041
- "change",
1042
- "patch",
1043
- "alter",
1044
- "revise",
1045
- "refresh",
1046
- "correct",
1047
- "amend",
1048
- "adjust",
1049
- "tweak",
1050
- "rectify",
1051
- "refine"
1052
- ],
1053
- // Viewing / Listing
1054
- [
1055
- "list",
1056
- "show",
1057
- "display",
1058
- "enumerate",
1059
- "browse",
1060
- "view",
1061
- "peek",
1062
- "index",
1063
- "catalog",
1064
- "survey",
1065
- "inspect",
1066
- "ls",
1067
- "dir"
1068
- ],
1069
- // Searching / Discovery
1070
- [
1071
- "find",
1072
- "search",
1073
- "lookup",
1074
- "query",
1075
- "locate",
1076
- "filter",
1077
- "scan",
1078
- "explore",
1079
- "investigate",
1080
- "detect",
1081
- "scout",
1082
- "seek"
1083
- ],
1084
- // Soft Delete / Archival
1085
- ["archive", "shelve", "retire", "hide", "suppress", "mute"],
1086
- ["unarchive", "restore", "recover", "undelete", "unhide"],
1087
- // ===========================================================================
1088
- // 2. STATE & LIFECYCLE
1089
- // ===========================================================================
1090
- // Activation
1091
- [
1092
- "enable",
1093
- "activate",
1094
- "start",
1095
- "turn on",
1096
- "switch on",
1097
- "boot",
1098
- "init",
1099
- "initialize",
1100
- "setup",
1101
- "spin up",
1102
- "resume",
1103
- "unpause"
1104
- ],
1105
- // Deactivation
1106
- [
1107
- "disable",
1108
- "deactivate",
1109
- "stop",
1110
- "turn off",
1111
- "switch off",
1112
- "shutdown",
1113
- "halt",
1114
- "kill",
1115
- "terminate",
1116
- "suspend",
1117
- "pause",
1118
- "cease"
1119
- ],
1120
- // Execution
1121
- ["run", "execute", "invoke", "trigger", "launch", "call", "perform", "operate", "handle", "process", "fire"],
1122
- // Reset cycles
1123
- ["restart", "reboot", "reset", "reload", "bounce", "recycle", "refresh"],
1124
- // Validation & Check
1125
- ["validate", "verify", "check", "confirm", "assert", "test", "audit", "assess", "healthcheck", "ping"],
1126
- // Analysis & Math
1127
- [
1128
- "analyze",
1129
- "interpret",
1130
- "diagnose",
1131
- "evaluate",
1132
- "review",
1133
- "summarize",
1134
- "count",
1135
- "calculate",
1136
- "compute",
1137
- "measure",
1138
- "aggregate",
1139
- "summarise"
1140
- ],
1141
- // ===========================================================================
1142
- // 3. TRANSFER, IO & MANIPULATION
1143
- // ===========================================================================
1144
- // Duplication
1145
- ["copy", "duplicate", "clone", "replicate", "mirror", "fork", "repro"],
1146
- // Movement
1147
- ["move", "transfer", "migrate", "relocate", "rename", "shift", "mv", "slide"],
1148
- // Persistence
1149
- ["save", "store", "write", "persist", "commit", "stash", "record", "log"],
1150
- // Synchronization
1151
- ["sync", "synchronize", "resync", "reconcile", "align", "pair"],
1152
- // Import/Export
1153
- ["import", "ingest", "upload", "push", "feed"],
1154
- ["export", "download", "dump", "backup", "extract"],
1155
- // Connection
1156
- ["connect", "link", "bind", "attach", "join", "bridge", "associate", "mount", "map"],
1157
- ["disconnect", "unlink", "unbind", "detach", "leave", "dissociate", "unmount", "unmap"],
1158
- // ===========================================================================
1159
- // 4. DEVOPS, SECURITY & TECHNICAL
1160
- // ===========================================================================
1161
- // Auth
1162
- ["login", "log in", "sign in", "authenticate", "auth"],
1163
- ["logout", "log out", "sign out", "disconnect"],
1164
- // Permissions
1165
- ["approve", "authorize", "grant", "permit", "allow", "sanction", "whitelist"],
1166
- ["deny", "reject", "revoke", "forbid", "block", "ban", "blacklist"],
1167
- // Encryption
1168
- ["encrypt", "secure", "lock", "seal", "protect", "scramble", "hash"],
1169
- ["decrypt", "unlock", "unseal", "reveal", "decode"],
1170
- // Deployment
1171
- ["deploy", "release", "ship", "publish", "roll out", "promote", "distribute", "install"],
1172
- // Development
1173
- ["debug", "troubleshoot", "fix", "repair", "resolve", "trace"],
1174
- ["compile", "transpile", "build", "assemble", "package", "bundle", "minify"],
1175
- // ===========================================================================
1176
- // 5. COMMERCE & BUSINESS LOGIC
1177
- // ===========================================================================
1178
- // Financial Transactions
1179
- ["buy", "purchase", "order", "pay", "checkout", "spend"],
1180
- ["sell", "refund", "reimburse", "charge", "invoice", "bill"],
1181
- ["subscribe", "upgrade", "upsell"],
1182
- ["unsubscribe", "cancel", "downgrade"],
1183
- // Scheduling
1184
- ["schedule", "book", "appoint", "reserve", "plan", "calendar"],
1185
- ["reschedule", "postpone", "delay", "defer"],
1186
- // ===========================================================================
1187
- // 6. COMMUNICATION & SOCIAL
1188
- // ===========================================================================
1189
- // Outbound
1190
- [
1191
- "send",
1192
- "dispatch",
1193
- "deliver",
1194
- "transmit",
1195
- "post",
1196
- "broadcast",
1197
- "notify",
1198
- "alert",
1199
- "email",
1200
- "text",
1201
- "message",
1202
- "chat"
1203
- ],
1204
- // Social Interactions
1205
- ["reply", "respond", "answer", "retort"],
1206
- ["share", "forward", "retweet", "repost"],
1207
- ["like", "favorite", "star", "upvote", "heart"],
1208
- ["dislike", "downvote"],
1209
- ["follow", "watch", "track"],
1210
- ["unfollow", "ignore", "mute"],
1211
- // ===========================================================================
1212
- // 7. COMMON ENTITIES (NOUNS)
1213
- // ===========================================================================
1214
- // Users & Roles
1215
- [
1216
- "user",
1217
- "account",
1218
- "member",
1219
- "profile",
1220
- "identity",
1221
- "customer",
1222
- "principal",
1223
- "admin",
1224
- "operator",
1225
- "client",
1226
- "employee",
1227
- "staff"
1228
- ],
1229
- ["role", "group", "team", "squad", "unit", "department"],
1230
- // Data Artifacts
1231
- ["file", "document", "attachment", "blob", "asset", "object", "resource", "content", "media"],
1232
- ["image", "picture", "photo", "screenshot"],
1233
- ["video", "clip", "recording", "footage"],
1234
- // System Artifacts
1235
- ["message", "notification", "alert", "event", "signal", "webhook", "ping"],
1236
- ["log", "trace", "metric", "telemetry", "audit trail", "history"],
1237
- ["settings", "config", "configuration", "preferences", "options", "params", "env", "environment", "variables"],
1238
- ["permission", "privilege", "access right", "policy", "rule", "scope"],
1239
- // Business Artifacts
1240
- ["organization", "company", "tenant", "workspace", "org", "project", "repo", "repository"],
1241
- ["product", "item", "sku", "inventory", "stock"],
1242
- ["task", "ticket", "issue", "bug", "story", "epic", "todo", "job", "workitem"],
1243
- // Identification
1244
- ["id", "identifier", "key", "uuid", "guid", "token", "hash", "fingerprint"]
1245
- ];
1246
- var SynonymExpansionService = class {
1247
- synonymMap;
1248
- maxExpansions;
1249
- constructor(config = {}) {
1250
- this.maxExpansions = config.maxExpansionsPerTerm ?? 5;
1251
- const groups = config.replaceDefaults ? config.additionalSynonyms || [] : [...DEFAULT_SYNONYM_GROUPS, ...config.additionalSynonyms || []];
1252
- this.synonymMap = this.buildSynonymMap(groups);
1253
- }
1254
- /**
1255
- * Build a bidirectional synonym map from groups.
1256
- * Each term maps to all other terms in its group(s).
1257
- */
1258
- buildSynonymMap(groups) {
1259
- const map = /* @__PURE__ */ new Map();
1260
- for (const group of groups) {
1261
- const normalizedGroup = group.map((term) => term.toLowerCase());
1262
- for (const term of normalizedGroup) {
1263
- if (!map.has(term)) {
1264
- map.set(term, /* @__PURE__ */ new Set());
1265
- }
1266
- const synonyms = map.get(term);
1267
- for (const synonym of normalizedGroup) {
1268
- if (synonym !== term) {
1269
- synonyms.add(synonym);
1270
- }
1271
- }
1272
- }
1273
- }
1274
- return map;
1275
- }
1276
- /**
1277
- * Get synonyms for a single term.
1278
- * Returns empty array if no synonyms found.
1279
- *
1280
- * @example
1281
- * getSynonyms('add') // ['create', 'new', 'insert', 'make']
1282
- */
1283
- getSynonyms(term) {
1284
- const normalized = term.toLowerCase();
1285
- const synonyms = this.synonymMap.get(normalized);
1286
- if (!synonyms) {
1287
- return [];
1288
- }
1289
- return Array.from(synonyms).slice(0, this.maxExpansions);
1290
- }
1291
- /**
1292
- * Expand a query string by adding synonyms for each term.
1293
- * Returns the expanded query string with original terms and their synonyms.
1294
- *
1295
- * @example
1296
- * expandQuery('add user') // 'add create new insert make user account member profile'
1297
- */
1298
- expandQuery(query) {
1299
- const terms = query.toLowerCase().split(/\s+/).filter((term) => term.length > 1);
1300
- const expandedTerms = [];
1301
- for (const term of terms) {
1302
- expandedTerms.push(term);
1303
- const synonyms = this.getSynonyms(term);
1304
- expandedTerms.push(...synonyms);
1305
- }
1306
- return expandedTerms.join(" ");
1307
- }
1308
- /**
1309
- * Check if synonym expansion is available for any term in the query.
1310
- */
1311
- hasExpansions(query) {
1312
- const terms = query.toLowerCase().split(/\s+/);
1313
- return terms.some((term) => this.synonymMap.has(term));
1314
- }
1315
- /**
1316
- * Get statistics about the synonym dictionary.
1317
- */
1318
- getStats() {
1319
- const termCount = this.synonymMap.size;
1320
- let totalSynonyms = 0;
1321
- for (const synonyms of this.synonymMap.values()) {
1322
- totalSynonyms += synonyms.size;
1323
- }
1324
- return {
1325
- termCount,
1326
- avgSynonymsPerTerm: termCount > 0 ? totalSynonyms / termCount : 0
1327
- };
1328
- }
1329
- };
1330
-
1331
- // plugins/plugin-codecall/src/services/tool-search.service.ts
1332
- var STOP_WORDS = /* @__PURE__ */ new Set([
1333
- // Articles & Determiners
1334
- "the",
1335
- "a",
1336
- "an",
1337
- "this",
1338
- "that",
1339
- "these",
1340
- "those",
1341
- // Prepositions
1342
- "in",
1343
- "on",
1344
- "at",
1345
- "to",
1346
- "for",
1347
- "of",
1348
- "with",
1349
- "by",
1350
- "from",
1351
- "into",
1352
- "over",
1353
- "after",
1354
- "before",
1355
- "between",
1356
- "under",
1357
- "about",
1358
- "against",
1359
- "during",
1360
- "through",
1361
- // Conjunctions
1362
- "and",
1363
- "or",
1364
- "but",
1365
- "nor",
1366
- "so",
1367
- "yet",
1368
- "as",
1369
- "than",
1370
- "if",
1371
- "because",
1372
- "while",
1373
- "when",
1374
- "where",
1375
- "unless",
1376
- // Pronouns (Subject/Object/Possessive)
1377
- "i",
1378
- "me",
1379
- "my",
1380
- "mine",
1381
- "myself",
1382
- "you",
1383
- "your",
1384
- "yours",
1385
- "yourself",
1386
- "he",
1387
- "him",
1388
- "his",
1389
- "himself",
1390
- "she",
1391
- "her",
1392
- "hers",
1393
- "herself",
1394
- "it",
1395
- "its",
1396
- "itself",
1397
- "we",
1398
- "us",
1399
- "our",
1400
- "ours",
1401
- "ourselves",
1402
- "they",
1403
- "them",
1404
- "their",
1405
- "theirs",
1406
- "themselves",
1407
- "who",
1408
- "whom",
1409
- "whose",
1410
- "which",
1411
- "what",
1412
- // Auxiliary/Linking Verbs (State of being is usually noise, Action is signal)
1413
- "is",
1414
- "was",
1415
- "are",
1416
- "were",
1417
- "been",
1418
- "be",
1419
- "being",
1420
- "have",
1421
- "has",
1422
- "had",
1423
- "having",
1424
- "do",
1425
- "does",
1426
- "did",
1427
- "doing",
1428
- // "do" is usually auxiliary ("do you have..."). "run" or "execute" is better.
1429
- "will",
1430
- "would",
1431
- "shall",
1432
- "should",
1433
- "can",
1434
- "could",
1435
- "may",
1436
- "might",
1437
- "must",
1438
- // Quantifiers / Adverbs of degree
1439
- "all",
1440
- "any",
1441
- "both",
1442
- "each",
1443
- "few",
1444
- "more",
1445
- "most",
1446
- "other",
1447
- "some",
1448
- "such",
1449
- "no",
1450
- "nor",
1451
- "not",
1452
- "only",
1453
- "own",
1454
- "same",
1455
- "too",
1456
- "very",
1457
- "just",
1458
- "even",
1459
- // Conversational / Chat Fillers (Common in LLM prompts)
1460
- "please",
1461
- "pls",
1462
- "plz",
1463
- "thanks",
1464
- "thank",
1465
- "thx",
1466
- "hello",
1467
- "hi",
1468
- "hey",
1469
- "ok",
1470
- "okay",
1471
- "yes",
1472
- "no",
1473
- "actually",
1474
- "basically",
1475
- "literally",
1476
- "maybe",
1477
- "perhaps",
1478
- "now",
1479
- "then",
1480
- "here",
1481
- "there",
1482
- "again",
1483
- "once",
1484
- "back",
1485
- // "back" can be tricky, but usually implies direction not action
1486
- // Meta/Structural words
1487
- "example",
1488
- "context",
1489
- "optionally",
1490
- "optional",
1491
- // Users rarely search for "optional", they search for the thing itself.
1492
- "etc",
1493
- "ie",
1494
- "eg"
1495
- ]);
1496
- var DEFAULT_EMBEDDING_MODEL = "Xenova/all-MiniLM-L6-v2";
1497
- function messageOf(error) {
1498
- return error instanceof Error ? error.message : String(error);
1499
- }
1500
- var ToolSearchService = class _ToolSearchService {
1501
- static MAX_SUBSCRIPTION_RETRIES = 100;
1502
- static INITIAL_RETRY_DELAY_MS = 10;
1503
- static MAX_RETRY_DELAY_MS = 1e3;
1504
- vectorDB;
1505
- strategy;
1506
- initialized = false;
1507
- mlInitialized = false;
1508
- config;
1509
- scope;
1510
- unsubscribe;
1511
- synonymService = null;
1512
- synonymExpansion;
1513
- /** The reindex in progress: later tool changes queue behind it and `search()` waits for it. */
1514
- indexing;
1515
- // Subscription tracking for async initialization
1516
- subscriptionPromise;
1517
- subscriptionResolved = false;
1518
- subscriptionResolve = null;
1519
- subscriptionReject = null;
1520
- retryTimeoutId = null;
1521
- disposed = false;
1522
- /** `availableWhen` of each indexed tool, by indexed name, for per-caller surface filtering. */
1523
- availabilityByTool = /* @__PURE__ */ new Map();
1524
- constructor(config = {}, scope) {
1525
- this.scope = scope;
1526
- const embeddingOptions = config.embeddingOptions || {
1527
- strategy: "tfidf",
1528
- modelName: DEFAULT_EMBEDDING_MODEL,
1529
- cacheDir: "./.cache/transformers",
1530
- useHNSW: false,
1531
- synonymExpansion: { enabled: true, replaceDefaults: false, maxExpansionsPerTerm: 5 }
1532
- };
1533
- this.strategy = config.strategy || embeddingOptions.strategy || "tfidf";
1534
- this.config = {
1535
- strategy: this.strategy,
1536
- embeddingOptions,
1537
- defaultTopK: config.defaultTopK ?? 8,
1538
- defaultSimilarityThreshold: config.defaultSimilarityThreshold ?? 0,
1539
- mode: config.mode ?? "codecall_only",
1540
- includeTools: config.includeTools
1541
- };
1542
- const validModes = ["codecall_only", "codecall_opt_in", "metadata_driven"];
1543
- if (!validModes.includes(this.config.mode)) {
1544
- throw new Error(`Invalid CodeCall mode: ${this.config.mode}. Valid modes: ${validModes.join(", ")}`);
1545
- }
1546
- if (this.strategy === "ml") {
1547
- this.vectorDB = new VectoriaDB({
1548
- modelName: embeddingOptions.modelName || DEFAULT_EMBEDDING_MODEL,
1549
- cacheDir: embeddingOptions.cacheDir || "./.cache/transformers",
1550
- defaultTopK: this.config.defaultTopK,
1551
- defaultSimilarityThreshold: this.config.defaultSimilarityThreshold,
1552
- useHNSW: embeddingOptions.useHNSW || false
1553
- });
1554
- } else {
1555
- this.vectorDB = this.createTfidfIndex();
1556
- }
1557
- this.synonymExpansion = config.synonymExpansion ?? embeddingOptions.synonymExpansion;
1558
- if (this.strategy === "tfidf") {
1559
- this.synonymService = this.createSynonymService();
1560
- }
1561
- this.subscriptionPromise = new Promise((resolve, reject) => {
1562
- this.subscriptionResolve = resolve;
1563
- this.subscriptionReject = reject;
1564
- });
1565
- this.setupSubscription();
1566
- }
1567
- createTfidfIndex() {
1568
- return new TFIDFVectoria({
1569
- defaultTopK: this.config.defaultTopK,
1570
- defaultSimilarityThreshold: this.config.defaultSimilarityThreshold
1571
- });
1572
- }
1573
- createSynonymService() {
1574
- const synonymExpansion = this.synonymExpansion;
1575
- if (synonymExpansion === false || synonymExpansion?.enabled === false) return null;
1576
- return new SynonymExpansionService(synonymExpansion ?? {});
1577
- }
1578
- /**
1579
- * Ensures the service is subscribed to tool changes before proceeding.
1580
- * Public methods should call this before accessing tools.
1581
- */
1582
- async ensureSubscribed() {
1583
- if (this.subscriptionResolved) {
1584
- return;
1585
- }
1586
- await this.subscriptionPromise;
1587
- }
1588
- /**
1589
- * Sets up subscription to tool changes with exponential backoff retry.
1590
- * Handles the case where scope.tools may not be available yet during plugin initialization.
1591
- */
1592
- setupSubscription(retryCount = 0, delayMs = _ToolSearchService.INITIAL_RETRY_DELAY_MS) {
1593
- if (this.scope.tools) {
1594
- this.subscribeToToolChanges();
1595
- return;
1596
- }
1597
- if (retryCount >= _ToolSearchService.MAX_SUBSCRIPTION_RETRIES) {
1598
- this.scope.logger.warn(
1599
- "ToolSearchService: scope.tools not available after max retries. Tool search will return incomplete results until tools are registered."
1600
- );
1601
- this.markSubscribed();
1602
- return;
1603
- }
1604
- const nextDelay = Math.min(delayMs * 2, _ToolSearchService.MAX_RETRY_DELAY_MS);
1605
- this.retryTimeoutId = setTimeout(() => {
1606
- this.retryTimeoutId = null;
1607
- if (this.disposed) {
1608
- return;
1609
- }
1610
- this.setupSubscription(retryCount + 1, nextDelay);
1611
- }, delayMs);
1612
- }
1613
- /**
1614
- * Subscribes to tool changes once scope.tools is available.
1615
- */
1616
- subscribeToToolChanges() {
1617
- this.unsubscribe = this.scope.tools.subscribe({ immediate: true }, (event) => {
1618
- this.queueReindex(event.snapshot);
1619
- });
1620
- this.markSubscribed();
1621
- }
1622
- /** Reindex from `tools` once the reindex in progress (if any) is done; a failure is logged, never thrown. */
1623
- queueReindex(tools) {
1624
- const reindex = () => this.handleToolChange(tools);
1625
- const run = (this.indexing ? this.indexing.then(reindex) : reindex()).catch((error) => {
1626
- this.scope.logger.warn(`CodeCall tool search could not index the tools: ${messageOf(error)}`);
1627
- });
1628
- this.indexing = run;
1629
- void run.then(() => {
1630
- if (this.indexing === run) this.indexing = void 0;
1631
- });
1632
- }
1633
- /**
1634
- * Marks the subscription as resolved, allowing pending operations to proceed.
1635
- */
1636
- markSubscribed() {
1637
- this.subscriptionResolved = true;
1638
- if (this.subscriptionResolve) {
1639
- this.subscriptionResolve();
1640
- this.subscriptionResolve = null;
1641
- }
1642
- }
1643
- /**
1644
- * Handles tool change events by reindexing all tools from the snapshot. The new index replaces the
1645
- * current one only once it is built, and a tool that can't be read is skipped, so the other tools
1646
- * stay searchable.
1647
- */
1648
- async handleToolChange(tools) {
1649
- if (tools.length > 0 && !this.mlInitialized && this.strategy === "ml" && this.vectorDB instanceof VectoriaDB) {
1650
- try {
1651
- await this.vectorDB.initialize();
1652
- this.mlInitialized = true;
1653
- } catch (error) {
1654
- this.fallBackToTfidf(error);
1655
- }
1656
- }
1657
- const availabilityByTool = /* @__PURE__ */ new Map();
1658
- const documents = tools.flatMap((tool) => this.toDocuments(tool, availabilityByTool));
1659
- await this.replaceIndex(documents);
1660
- this.availabilityByTool = availabilityByTool;
1661
- this.initialized = true;
1662
- }
1663
- /** The tool's search document, or none when CodeCall may not execute it or it can't be read. */
1664
- toDocuments(tool, availabilityByTool) {
1665
- try {
1666
- if (!this.shouldIndexTool(tool)) return [];
1667
- const toolName = tool.name;
1668
- const document = {
1669
- id: toolName,
1670
- text: this.extractSearchableText(tool),
1671
- metadata: {
1672
- id: toolName,
1673
- toolName,
1674
- qualifiedName: tool.fullName || toolName,
1675
- appId: this.extractAppId(tool),
1676
- toolInstance: tool
1677
- }
1678
- };
1679
- availabilityByTool.set(toolName, tool.metadata.availableWhen);
1680
- return [document];
1681
- } catch (error) {
1682
- this.scope.logger.warn(`CodeCall tool search skipped tool "${tool.name}": ${messageOf(error)}`);
1683
- return [];
1684
- }
1685
- }
1686
- /** Index `documents` in place of the current contents; embeddings that fail fall back to TF-IDF. */
1687
- async replaceIndex(documents) {
1688
- if (this.vectorDB instanceof VectoriaDB) {
1689
- try {
1690
- this.vectorDB.clear();
1691
- if (documents.length > 0) await this.vectorDB.addMany(documents);
1692
- return;
1693
- } catch (error) {
1694
- this.fallBackToTfidf(error);
1695
- }
1696
- }
1697
- const index = this.createTfidfIndex();
1698
- index.addDocuments(documents);
1699
- index.reindex();
1700
- this.vectorDB = index;
1701
- }
1702
- /** The embedding model could not be loaded or used: search with TF-IDF for the rest of the process. */
1703
- fallBackToTfidf(error) {
1704
- const modelName = this.config.embeddingOptions.modelName || DEFAULT_EMBEDDING_MODEL;
1705
- this.scope.logger.warn(
1706
- `CodeCall could not use embedding model "${modelName}" (${messageOf(error)}); tool search uses TF-IDF instead`
1707
- );
1708
- this.strategy = "tfidf";
1709
- this.vectorDB = this.createTfidfIndex();
1710
- this.synonymService = this.createSynonymService();
1711
- }
1712
- /**
1713
- * Whether a tool belongs in the search index: exactly when CodeCall may execute it.
1714
- * The decision is `codecall:execute`'s own, so search cannot show a tool execution refuses
1715
- * or hide one it runs (GHSA-6w3j-82v5-6qrr).
1716
- */
1717
- shouldIndexTool(tool) {
1718
- return checkCodeCallToolPolicy(toCodeCallPolicyTool(tool, void 0, this.scope), this.config).allowed;
1719
- }
1720
- /**
1721
- * Initializes the search service by indexing all tools from the registry.
1722
- * NOTE: This method is now a no-op. Initialization is handled reactively
1723
- * via subscription to tool change events in the constructor.
1724
- * This method exists for interface compatibility.
1725
- */
1726
- async initialize() {
1727
- }
1728
- /**
1729
- * Cleanup subscription and pending retries when service is destroyed
1730
- */
1731
- dispose() {
1732
- this.disposed = true;
1733
- if (this.retryTimeoutId) {
1734
- clearTimeout(this.retryTimeoutId);
1735
- this.retryTimeoutId = null;
1736
- }
1737
- if (this.subscriptionReject) {
1738
- this.subscriptionReject(new Error("ToolSearchService disposed before subscription completed"));
1739
- this.subscriptionReject = null;
1740
- this.subscriptionResolve = null;
1741
- }
1742
- if (this.unsubscribe) {
1743
- this.unsubscribe();
1744
- this.unsubscribe = void 0;
1745
- }
1746
- }
1747
- /**
1748
- * Extracts searchable text from a tool instance.
1749
- * Uses term weighting to improve relevance:
1750
- * - Description terms are heavily weighted (most important for semantic matching)
1751
- * - Tool name parts are tokenized and weighted
1752
- * - Tags provide additional context
1753
- */
1754
- extractSearchableText(tool) {
1755
- const parts = [];
1756
- if (tool.name) {
1757
- const nameParts = tool.name.split(/[:\-_.]/).filter(Boolean);
1758
- for (const part of nameParts) {
1759
- parts.push(part, part);
1760
- }
1761
- }
1762
- if (tool.metadata.description) {
1763
- const description = tool.metadata.description;
1764
- parts.push(description, description, description);
1765
- const keyTerms = description.toLowerCase().split(/\s+/).filter((word) => word.length >= 4 && !this.isStopWord(word));
1766
- parts.push(...keyTerms);
1767
- }
1768
- if (tool.metadata.tags && tool.metadata.tags.length > 0) {
1769
- for (const tag of tool.metadata.tags) {
1770
- parts.push(tag, tag);
1771
- }
1772
- }
1773
- if (tool.rawInputSchema && typeof tool.rawInputSchema === "object") {
1774
- const schema = tool.rawInputSchema;
1775
- if (schema.properties) {
1776
- parts.push(...Object.keys(schema.properties));
1777
- }
1778
- }
1779
- const examples = tool.metadata?.examples;
1780
- if (examples && Array.isArray(examples)) {
1781
- for (const ex of examples) {
1782
- if (ex.description) {
1783
- parts.push(ex.description, ex.description);
1784
- }
1785
- if (ex.input && typeof ex.input === "object") {
1786
- for (const [key, value] of Object.entries(ex.input)) {
1787
- parts.push(key);
1788
- if (typeof value === "string") {
1789
- parts.push(value);
1790
- }
1791
- }
1792
- }
1793
- }
1794
- }
1795
- return parts.join(" ");
1796
- }
1797
- /**
1798
- * Checks if a word is a common stop word that should not receive extra weighting.
1799
- * Uses module-level STOP_WORDS constant to avoid recreating the Set on each call.
1800
- */
1801
- isStopWord(word) {
1802
- return STOP_WORDS.has(word);
1803
- }
1804
- /**
1805
- * Extracts app ID from tool's owner lineage
1806
- */
1807
- extractAppId(tool) {
1808
- return codeCallAppIdOf(this.scope, tool);
1809
- }
1810
- /**
1811
- * Searches for tools matching the query
1812
- * Implements the ToolSearch interface
1813
- */
1814
- async search(query, options = {}) {
1815
- await this.ensureSubscribed();
1816
- await this.indexing;
1817
- const { topK = this.config.defaultTopK, appIds, excludeToolNames = [], surface } = options;
1818
- const minScore = this.config.defaultSimilarityThreshold;
1819
- const filter = (metadata) => {
1820
- if (excludeToolNames.includes(metadata.toolName)) {
1821
- return false;
1822
- }
1823
- if (!isOfferedToCaller(metadata.toolInstance.metadata.availableWhen, surface)) {
1824
- return false;
1825
- }
1826
- if (appIds && appIds.length > 0) {
1827
- if (!metadata.appId || !appIds.includes(metadata.appId)) {
1828
- return false;
1829
- }
1830
- }
1831
- return true;
1832
- };
1833
- const effectiveQuery = this.synonymService ? this.synonymService.expandQuery(query) : query;
1834
- const results = await this.vectorDB.search(effectiveQuery, {
1835
- topK,
1836
- threshold: minScore,
1837
- filter
1838
- });
1839
- return results.map((result) => ({
1840
- toolName: result.metadata.toolName,
1841
- appId: result.metadata.appId,
1842
- description: result.metadata.toolInstance.metadata.description || "",
1843
- relevanceScore: result.score
1844
- }));
1845
- }
1846
- /**
1847
- * Gets all indexed tool names
1848
- */
1849
- getAllToolNames() {
1850
- if (this.vectorDB instanceof VectoriaDB) {
1851
- return this.vectorDB.getAll().map((doc) => doc.id);
1852
- } else {
1853
- return this.vectorDB.getAllDocumentIds();
1854
- }
1855
- }
1856
- /**
1857
- * Gets the total number of indexed tools, or of those a caller on `surface` may reach
1858
- */
1859
- getTotalCount(surface) {
1860
- if (surface !== void 0) {
1861
- return this.getAllToolNames().filter((toolName) => this.hasTool(toolName, surface)).length;
1862
- }
1863
- if (this.vectorDB instanceof VectoriaDB) {
1864
- return this.vectorDB.size();
1865
- } else {
1866
- return this.vectorDB.getDocumentCount();
1867
- }
1868
- }
1869
- /**
1870
- * Checks if a tool exists in the index, for a caller on `surface` when given
1871
- */
1872
- hasTool(toolName, surface) {
1873
- const indexed = this.vectorDB instanceof VectoriaDB ? this.vectorDB.has(toolName) : this.vectorDB.hasDocument(toolName);
1874
- return indexed && isOfferedToCaller(this.availabilityByTool.get(toolName), surface);
1875
- }
1876
- /**
1877
- * Clears the entire index
1878
- */
1879
- clear() {
1880
- this.vectorDB.clear();
1881
- this.availabilityByTool = /* @__PURE__ */ new Map();
1882
- this.initialized = false;
1883
- }
1884
- /**
1885
- * Get the current embedding strategy
1886
- */
1887
- getStrategy() {
1888
- return this.strategy;
1889
- }
1890
- /**
1891
- * Check if the service is initialized
1892
- */
1893
- isInitialized() {
1894
- return this.initialized;
1895
- }
1896
- };
1897
-
1898
- // plugins/plugin-codecall/src/services/enclave.service.ts
1899
- import {
1900
- Enclave
1901
- } from "@enclave-vm/core";
1902
- import { Provider as Provider3, ProviderScope as ProviderScope3 } from "@frontmcp/sdk";
1903
-
1904
- // plugins/plugin-codecall/src/security/script-policy.ts
1905
- import {
1906
- ForbiddenLoopRule,
1907
- JSAstValidator,
1908
- ValidationSeverity
1909
- } from "@enclave-vm/ast";
1910
- var AGENTSCRIPT_PARSE_OPTIONS = {
1911
- ecmaVersion: "latest",
1912
- sourceType: "script",
1913
- allowReturnOutsideFunction: true,
1914
- allowAwaitOutsideFunction: true
1915
- };
1916
- var PARSE_ATTEMPTS = [
1917
- { wrap: (code) => code, parseOptions: AGENTSCRIPT_PARSE_OPTIONS, lineOffset: 0 },
1918
- { wrap: (code) => code, parseOptions: { ...AGENTSCRIPT_PARSE_OPTIONS, sourceType: "module" }, lineOffset: 0 },
1919
- {
1920
- wrap: (code) => `async function __temp__() {
1
+ var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __decorateClass=(decorators,target,key,kind)=>{var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target;for(var i=decorators.length-1,decorator;i>=0;i--)if(decorator=decorators[i])result=(kind?decorator(target,key,result):decorator(result))||result;if(kind&&result)__defProp(target,key,result);return result};import CachePlugin from"@frontmcp/plugin-cache";import{DynamicPlugin,FrontMcpLogger,FrontMcpToolTokens,isEntryGatedBy,ListToolsHook,Plugin,resolveToolVisibility,ScopeEntry,ToolHook,ToolNotFoundError}from"@frontmcp/sdk";import{z}from"@frontmcp/lazy-zod";var directCallsFilterSchema=z.custom(val=>typeof val==="function",{message:"filter must be a function with signature (tool: DirectCallsFilterToolInfo) => boolean"});var includeToolsFilterSchema=z.custom(val=>typeof val==="function",{message:"includeTools must be a function with signature (tool: IncludeToolsFilterToolInfo) => boolean"});var codeCallModeSchema=z.enum(["codecall_only","codecall_opt_in","metadata_driven"]).default("codecall_only");var codeCallVmPresetSchema=z.enum(["locked_down","secure","balanced","experimental"]).default("secure");var DEFAULT_VM_OPTIONS={preset:"secure"};var codeCallVmOptionsSchema=z.object({preset:codeCallVmPresetSchema,timeoutMs:z.number().positive().optional(),allowLoops:z.boolean().optional(),maxSteps:z.number().positive().optional(),disabledBuiltins:z.array(z.string()).optional(),disabledGlobals:z.array(z.string()).optional(),allowConsole:z.boolean().optional(),maxSanitizeDepth:z.number().positive().optional(),maxSanitizeProperties:z.number().positive().optional(),rapidEnumerationThreshold:z.number().int().positive().optional(),rapidEnumerationOverrides:z.record(z.string(),z.number().int().positive()).optional()}).default(()=>DEFAULT_VM_OPTIONS);var codeCallDirectCallsOptionsSchema=z.object({enabled:z.boolean(),allowedTools:z.array(z.string()).optional(),filter:directCallsFilterSchema.optional()});var embeddingStrategySchema=z.enum(["tfidf","ml"]).default("tfidf");var synonymExpansionConfigSchema=z.object({enabled:z.boolean().default(true),additionalSynonyms:z.array(z.array(z.string())).optional(),replaceDefaults:z.boolean().default(false),maxExpansionsPerTerm:z.number().positive().default(5)}).default({enabled:true,replaceDefaults:false,maxExpansionsPerTerm:5});var DEFAULT_EMBEDDING_OPTIONS={strategy:"tfidf",modelName:"Xenova/all-MiniLM-L6-v2",cacheDir:"./.cache/transformers",useHNSW:false,synonymExpansion:{enabled:true,replaceDefaults:false,maxExpansionsPerTerm:5}};var codeCallEmbeddingOptionsSchema=z.object({strategy:embeddingStrategySchema.optional(),modelName:z.string().optional(),cacheDir:z.string().optional(),useHNSW:z.boolean().optional(),synonymExpansion:z.union([z.literal(false),synonymExpansionConfigSchema]).optional()}).optional().transform(opts=>({strategy:opts?.strategy??DEFAULT_EMBEDDING_OPTIONS.strategy,modelName:opts?.modelName??DEFAULT_EMBEDDING_OPTIONS.modelName,cacheDir:opts?.cacheDir??DEFAULT_EMBEDDING_OPTIONS.cacheDir,useHNSW:opts?.useHNSW??DEFAULT_EMBEDDING_OPTIONS.useHNSW,synonymExpansion:opts?.synonymExpansion??DEFAULT_EMBEDDING_OPTIONS.synonymExpansion}));var codeCallSidecarOptionsSchema=z.object({enabled:z.boolean().default(false),maxTotalSize:z.number().positive().optional(),maxReferenceSize:z.number().positive().optional(),extractionThreshold:z.number().positive().optional(),maxResolvedSize:z.number().positive().optional(),allowComposites:z.boolean().optional(),maxScriptLengthWhenDisabled:z.number().positive().nullable().default(64*1024)}).default(()=>({enabled:false,maxScriptLengthWhenDisabled:64*1024}));var codeCallPluginOptionsObjectSchema=z.object({mode:codeCallModeSchema,appIds:z.array(z.string()).optional(),topK:z.number().positive().default(8),maxDefinitions:z.number().int().positive().default(8),includeTools:includeToolsFilterSchema.optional(),directCalls:codeCallDirectCallsOptionsSchema.optional(),vm:codeCallVmOptionsSchema,embedding:codeCallEmbeddingOptionsSchema,sidecar:codeCallSidecarOptionsSchema});var DEFAULT_PLUGIN_OPTIONS={mode:"codecall_only",topK:8,maxDefinitions:8,vm:DEFAULT_VM_OPTIONS,embedding:DEFAULT_EMBEDDING_OPTIONS,sidecar:{enabled:false,maxScriptLengthWhenDisabled:64*1024}};var codeCallPluginOptionsSchema=codeCallPluginOptionsObjectSchema.prefault(DEFAULT_PLUGIN_OPTIONS);import{BaseConfig,Provider,ProviderScope}from"@frontmcp/sdk";var CodeCallConfig=class extends BaseConfig{constructor(options={}){const parsedConfig=codeCallPluginOptionsSchema.parse(options);const resolvedVm=resolveVmOptions(parsedConfig.vm);super({...parsedConfig,resolvedVm})}};CodeCallConfig=__decorateClass([Provider({name:"codecall:config",description:"CodeCall plugin configuration with validated defaults",scope:ProviderScope.GLOBAL})],CodeCallConfig);var MAX_ITERATIONS_PER_LOOP=1e4;function maxToolCallsOf(vmOptions){return vmOptions.maxSteps||100}var SANDBOX_RAPID_ENUMERATION_THRESHOLD=30;function rapidEnumerationThresholdOf(vmOptions){return vmOptions.rapidEnumerationThreshold??SANDBOX_RAPID_ENUMERATION_THRESHOLD}function resolveVmOptions(vmOptions){const preset=vmOptions?.preset??"secure";const base=presetDefaults(preset);return{...base,...vmOptions,disabledBuiltins:vmOptions?.disabledBuiltins??base.disabledBuiltins,disabledGlobals:vmOptions?.disabledGlobals??base.disabledGlobals}}function presetDefaults(preset){switch(preset){case"locked_down":return{preset,timeoutMs:2e3,allowLoops:false,allowConsole:false,maxSteps:2e3,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process","fetch","setTimeout","setInterval","setImmediate","global","globalThis"],maxSanitizeDepth:10,maxSanitizeProperties:1e3};case"balanced":return{preset,timeoutMs:5e3,allowLoops:true,allowConsole:true,maxSteps:1e4,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process","fetch"],maxSanitizeDepth:50,maxSanitizeProperties:5e3};case"experimental":return{preset,timeoutMs:1e4,allowLoops:true,allowConsole:true,maxSteps:2e4,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process"],maxSanitizeDepth:100,maxSanitizeProperties:2e4};case"secure":default:return{preset:"secure",timeoutMs:3500,allowLoops:false,allowConsole:true,maxSteps:5e3,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process","fetch","setTimeout","setInterval","setImmediate","global","globalThis"],maxSanitizeDepth:50,maxSanitizeProperties:2e3}}}import{getRunningTool}from"@frontmcp/sdk";var CODECALL_DISPATCH=Symbol("frontmcp.codecall.dispatch");function asCodeCallDispatch(ctx){return Object.defineProperty(ctx,CODECALL_DISPATCH,{value:true,enumerable:false})}function isInProcessDispatch(ctx){if(getRunningTool())return true;if(typeof ctx!=="object"||ctx===null)return false;const marks=ctx;return marks[CODECALL_DISPATCH]===true||marks.internalCall===true}var BLOCKED_NAMESPACE_PATTERNS=Object.freeze([/^system:/,/^internal:/,/^__/]);function isOfferedToCaller(availableWhen,surface){const offered=availableWhen?.surface;return offered===void 0||surface===void 0||offered.includes(surface)}var ALLOWED={allowed:true};function deny(reason){return{allowed:false,reason}}function codeCallAppIdOf(scope,entry){const lineage=scope?.tools?.lineageOf?.(entry)??[];const owners=entry.owner?[...lineage,entry.owner]:lineage;return owners.find(owner=>owner.kind==="app")?.id}function toCodeCallPolicyTool(entry,requestedName,scope){const{metadata}=entry;return{name:entry.name||entry.fullName,fullName:entry.fullName,aliases:requestedName?[requestedName]:void 0,appId:codeCallAppIdOf(scope,entry),description:metadata?.description,tags:metadata?.tags,hidden:metadata?.hideFromDiscovery===true||metadata?.visibility==="hidden"||metadata?.visibility==="internal",codecall:metadata?.codecall,annotations:metadata?.annotations,metadata}}function isPlainData(value){if(Array.isArray(value))return true;const proto=Object.getPrototypeOf(value);return proto===Object.prototype||proto===null}function readOnlyCopy(value,copies){if(typeof value!=="object"||value===null||!isPlainData(value))return value;const existing=copies.get(value);if(existing!==void 0)return existing;const copy=Array.isArray(value)?[]:Object.create(Object.getPrototypeOf(value));copies.set(value,copy);for(const key of Reflect.ownKeys(value)){if(!Object.prototype.propertyIsEnumerable.call(value,key))continue;Object.defineProperty(copy,key,{value:readOnlyCopy(Reflect.get(value,key),copies),enumerable:true,writable:true,configurable:true})}return Object.freeze(copy)}function toToolFilterInfo(tool){const copies=new WeakMap;const annotations=readOnlyCopy(tool.annotations,copies);const metadata=tool.metadata?readOnlyCopy({...tool.metadata,...annotations?{annotations:tool.annotations}:{}},copies):void 0;return{name:tool.name,fullName:tool.fullName,appId:tool.appId,source:tool.codecall?.source,description:tool.description,tags:readOnlyCopy(tool.codecall?.tags??tool.tags,copies),annotations,metadata}}function ownNamesOf(tool){return[tool.name,tool.fullName].filter(candidate=>!!candidate)}function checkCodeCallToolPolicy(tool,config){const{name}=tool;const spellings=[...ownNamesOf(tool),...tool.aliases??[]];if(spellings.some(candidate=>candidate.startsWith("codecall:"))){return deny("CodeCall meta-tools are not callable from CodeCall")}for(const candidate of spellings){if(BLOCKED_NAMESPACE_PATTERNS.some(pattern=>pattern.test(candidate))){return deny(`Tool "${candidate}" is in a namespace CodeCall never calls`)}}if(tool.hidden===true){return deny(`Tool "${name}" is hidden from discovery`)}const enabled=tool.codecall?.enabledInCodeCall;switch(config.mode){case"codecall_only":case"metadata_driven":if(enabled===false){return deny(`Tool "${name}" sets enabledInCodeCall: false`)}break;case"codecall_opt_in":if(enabled!==true){return deny(`Tool "${name}" has not opted in to CodeCall`)}break;default:return deny(`Unknown CodeCall mode: ${String(config.mode)}`)}if(config.includeTools&&!config.includeTools(toToolFilterInfo(tool))){return deny(`Tool "${name}" is excluded by the includeTools filter`)}return ALLOWED}function denyUnknownTool(name){return deny(`Tool "${name}" is not available through CodeCall`)}function resolveCodeCallTool(scope,name){const typedScope=scope;const alias=/[-_]/.test(name)?name.includes("_")?name.replace(/_/g,"-"):name.replace(/-/g,"_"):void 0;const candidates=alias?[name,alias]:[name];const matches=entry=>candidates.includes(entry.fullName)||candidates.includes(entry.name);const local=typedScope.tools?.getTools(true)?.find(matches);if(local)return local;const registries=typedScope.providers?.getRegistries?.("AppRegistry")??[];for(const registry of registries){for(const app of registry.getApps()){if(!app.isRemote)continue;const remote=app.tools.getTools(true).find(matches);if(remote)return remote}}return void 0}function checkDirectCallPolicy(tool,directCalls){if(!directCalls)return ALLOWED;if(directCalls.enabled===false){return deny("Direct tool invocation is disabled")}const{allowedTools}=directCalls;if(allowedTools&&!ownNamesOf(tool).some(ownName=>allowedTools.includes(ownName))){return deny(`Tool "${tool.name}" is not in the direct-call allowlist`)}if(directCalls.filter&&!directCalls.filter(toToolFilterInfo(tool))){return deny(`Tool "${tool.name}" is excluded by the directCalls filter`)}return ALLOWED}function readCodeCallPolicyConfig(config){return{mode:config.get("mode")??"codecall_only",includeTools:config.get("includeTools")}}function checkCodeCallToolAccess(scope,config,name,options={}){const entry=resolveCodeCallTool(scope,name);if(!entry)return denyUnknownTool(name);if(!isOfferedToCaller(entry.metadata?.availableWhen,options.surface)){return deny(`Tool "${name}" is not offered on the caller's surface "${options.surface}"`)}const policyTool=toCodeCallPolicyTool(entry,name,scope);const baseDecision=checkCodeCallToolPolicy(policyTool,readCodeCallPolicyConfig(config));if(!baseDecision.allowed)return baseDecision;if(options.directCall){const directDecision=checkDirectCallPolicy(policyTool,config.get("directCalls"));if(!directDecision.allowed)return directDecision}return{allowed:true,entry}}var EMBEDDED_STACK_FRAME_RE=/\n[ \t]*at\s[^\n]*/g;var QUOTED_PATH_RE=/(['"`])((?:~?\/|[A-Za-z]:[\\/]|\\\\)[^\s'"`\\/][^'"`\n]*)\1/g;var URL_RE=/\b[A-Za-z][A-Za-z0-9+.-]{1,31}:\/\/(?:[^\s'"`<>,;]|[,;](?!~?\/|[A-Za-z]:[\\/]|\\\\))*/g;var QUERY_PATH_VALUE_RE=/([?&][^=&#]*=)(?:~?\/|[A-Za-z]:[\\/]|\\\\)[^&#]*/g;var POSIX_SEGMENT=String.raw`[^\s/\\'"\x60<>|,;:()\[\]{}]+`;var WINDOWS_SEGMENT=String.raw`[^\s/\\'"\x60<>|,;:*?]+`;function segments(segment,separator){const spaced=`${segment}(?: ${segment}){0,2}`;return`(?:(?:${spaced}${separator})+(?:${segment})?|${segment})`}var UNQUOTED_PATH_RE=new RegExp([String.raw`(?<![\w.~/\\)\]-])~?/+${segments(POSIX_SEGMENT,"/+")}`,String.raw`(?<![\w\\/])[A-Za-z]:[\\/]+${segments(WINDOWS_SEGMENT,String.raw`[\\/]+`)}?`,String.raw`(?<![\w\\])\\\\${segments(WINDOWS_SEGMENT,String.raw`[\\/]+`)}`].join("|"),"g");function redactPaths(text){return text.replace(QUOTED_PATH_RE,"$1[path]$1").replace(UNQUOTED_PATH_RE,"[path]")}function toClientErrorMessage(message){if(!message)return"";return redactAbsolutePaths(message.replace(EMBEDDED_STACK_FRAME_RE,""))}function redactAbsolutePaths(text){let result="";let last=0;for(const match of text.matchAll(URL_RE)){const start=match.index??0;result+=redactPaths(text.slice(last,start));result+=/^file:/i.test(match[0])?"[path]":match[0].replace(QUERY_PATH_VALUE_RE,"$1[path]");last=start+match[0].length}return result+redactPaths(text.slice(last))}var TOOL_CALL_ERROR_CODES={NOT_FOUND:"NOT_FOUND",VALIDATION:"VALIDATION",EXECUTION:"EXECUTION",TIMEOUT:"TIMEOUT",ACCESS_DENIED:"ACCESS_DENIED",RATE_LIMITED:"RATE_LIMITED",SELF_REFERENCE:"SELF_REFERENCE"};function createToolCallError(code,toolName,rawMessage){const sanitizedMessage=getSanitizedMessage(code,toolName,rawMessage);return Object.freeze({code,message:sanitizedMessage,toolName})}function getSanitizedMessage(code,toolName,rawMessage){switch(code){case TOOL_CALL_ERROR_CODES.NOT_FOUND:return`Tool "${toolName}" was not found`;case TOOL_CALL_ERROR_CODES.VALIDATION:return rawMessage?sanitizeValidationMessage(rawMessage):`Input validation failed for tool "${toolName}"`;case TOOL_CALL_ERROR_CODES.EXECUTION:return`Tool "${toolName}" execution failed`;case TOOL_CALL_ERROR_CODES.TIMEOUT:return`Tool "${toolName}" execution timed out`;case TOOL_CALL_ERROR_CODES.ACCESS_DENIED:return`Access denied for tool "${toolName}"`;case TOOL_CALL_ERROR_CODES.RATE_LIMITED:return`Tool "${toolName}" was rate limited`;case TOOL_CALL_ERROR_CODES.SELF_REFERENCE:return`Cannot call CodeCall tools from within AgentScript`;default:return`An error occurred while calling "${toolName}"`}}function sanitizeValidationMessage(message){let sanitized=toClientErrorMessage(message);sanitized=sanitized.replace(/\bat line \d+/gi,"");sanitized=sanitized.replace(/\bline \d+/gi,"");sanitized=sanitized.replace(/:\d+:\d+/g,"");if(sanitized.length>200){sanitized=sanitized.substring(0,200)+"..."}return sanitized.trim()}var SelfReferenceError=class extends Error{code=TOOL_CALL_ERROR_CODES.SELF_REFERENCE;toolName;constructor(toolName){super(`Self-reference attack: Attempted to call CodeCall tool "${toolName}" from within AgentScript`);this.name="SelfReferenceError";this.toolName=toolName;Object.freeze(this)}};var CODECALL_TOOL_PREFIX="codecall:";var BLOCKED_CODECALL_TOOLS=Object.freeze(new Set(["codecall:search","codecall:describe","codecall:execute","codecall:invoke"]));function isBlockedSelfReference(toolName){const normalizedName=toolName.toLowerCase().trim();if(normalizedName.startsWith(CODECALL_TOOL_PREFIX)){return true}if(BLOCKED_CODECALL_TOOLS.has(toolName)){return true}return false}function assertNotSelfReference(toolName){if(isBlockedSelfReference(toolName)){throw new SelfReferenceError(toolName)}}import{Provider as Provider2,ProviderScope as ProviderScope2}from"@frontmcp/sdk";var AUDIT_EVENT_TYPES={EXECUTION_START:"codecall:execution:start",EXECUTION_SUCCESS:"codecall:execution:success",EXECUTION_FAILURE:"codecall:execution:failure",EXECUTION_TIMEOUT:"codecall:execution:timeout",TOOL_CALL_START:"codecall:tool:call:start",TOOL_CALL_SUCCESS:"codecall:tool:call:success",TOOL_CALL_FAILURE:"codecall:tool:call:failure",SECURITY_SELF_REFERENCE:"codecall:security:self-reference",SECURITY_ACCESS_DENIED:"codecall:security:access-denied",SECURITY_AST_BLOCKED:"codecall:security:ast-blocked",SEARCH_PERFORMED:"codecall:search:performed",DESCRIBE_PERFORMED:"codecall:describe:performed",INVOKE_PERFORMED:"codecall:invoke:performed"};var AuditLoggerService=class{listeners=new Set;executionCounter=0;subscribe(listener){this.listeners.add(listener);return()=>{this.listeners.delete(listener)}}generateExecutionId(){const timestamp=Date.now().toString(36);const counter=(++this.executionCounter).toString(36).padStart(4,"0");const random=Math.random().toString(36).substring(2,8);return`exec_${timestamp}_${counter}_${random}`}logExecutionStart(executionId,script){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_START,timestamp:new Date().toISOString(),executionId,data:{scriptHash:this.hashScript(script),scriptLength:script.length}})}logExecutionSuccess(executionId,script,durationMs,toolCallCount){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_SUCCESS,timestamp:new Date().toISOString(),executionId,durationMs,data:{scriptHash:this.hashScript(script),scriptLength:script.length,toolCallCount}})}logExecutionFailure(executionId,script,durationMs,error){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_FAILURE,timestamp:new Date().toISOString(),executionId,durationMs,data:{scriptHash:this.hashScript(script),scriptLength:script.length,error:this.sanitizeError(error)}})}logExecutionTimeout(executionId,script,durationMs){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_TIMEOUT,timestamp:new Date().toISOString(),executionId,durationMs,data:{scriptHash:this.hashScript(script),scriptLength:script.length}})}logToolCallStart(executionId,toolName,callDepth){this.emit({type:AUDIT_EVENT_TYPES.TOOL_CALL_START,timestamp:new Date().toISOString(),executionId,data:{toolName,callDepth}})}logToolCallSuccess(executionId,toolName,callDepth,durationMs){this.emit({type:AUDIT_EVENT_TYPES.TOOL_CALL_SUCCESS,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolName,callDepth}})}logToolCallFailure(executionId,toolName,callDepth,durationMs,errorCode){this.emit({type:AUDIT_EVENT_TYPES.TOOL_CALL_FAILURE,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolName,callDepth,errorCode}})}logSecuritySelfReference(executionId,toolName){this.emit({type:AUDIT_EVENT_TYPES.SECURITY_SELF_REFERENCE,timestamp:new Date().toISOString(),executionId,data:{blocked:toolName,reason:"Self-reference attack: attempted to call CodeCall tool from within AgentScript"}})}logSecurityAccessDenied(executionId,toolName,reason){this.emit({type:AUDIT_EVENT_TYPES.SECURITY_ACCESS_DENIED,timestamp:new Date().toISOString(),executionId,data:{blocked:toolName,reason:this.sanitizeError(reason)}})}logSecurityAstBlocked(executionId,pattern,reason){this.emit({type:AUDIT_EVENT_TYPES.SECURITY_AST_BLOCKED,timestamp:new Date().toISOString(),executionId,data:{blocked:pattern,reason:this.sanitizeError(reason)}})}logSearch(executionId,query,resultCount,durationMs){this.emit({type:AUDIT_EVENT_TYPES.SEARCH_PERFORMED,timestamp:new Date().toISOString(),executionId,durationMs,data:{queryLength:query.length,resultCount}})}logDescribe(executionId,toolNames,durationMs){this.emit({type:AUDIT_EVENT_TYPES.DESCRIBE_PERFORMED,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolCount:toolNames.length,toolNames:toolNames.slice(0,10)}})}logInvoke(executionId,toolName,success,durationMs){this.emit({type:AUDIT_EVENT_TYPES.INVOKE_PERFORMED,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolName,success}})}emit(event){const frozenEvent=Object.freeze({...event,data:Object.freeze({...event.data})});for(const listener of this.listeners){try{listener(frozenEvent)}catch{}}}hashScript(script){let hash=0;for(let i=0;i<script.length;i++){const char=script.charCodeAt(i);hash=(hash<<5)-hash+char;hash=hash&hash}return`sh_${(hash>>>0).toString(16).padStart(8,"0")}`}sanitizeError(error){if(!error)return"Unknown error";let sanitized=toClientErrorMessage(error);sanitized=sanitized.replace(/:\d+:\d+/g,"");if(sanitized.length>200){sanitized=sanitized.substring(0,200)+"..."}return sanitized.trim()}};AuditLoggerService=__decorateClass([Provider2({name:"codecall:audit-logger",scope:ProviderScope2.GLOBAL})],AuditLoggerService);import{TFIDFVectoria,VectoriaDB}from"vectoriadb";var DEFAULT_SYNONYM_GROUPS=[["create","add","new","insert","make","append","register","generate","produce","build","construct","provision","instantiate","define","compose","draft"],["delete","remove","destroy","drop","erase","clear","purge","discard","eliminate","nuke","unbind","unregister"],["get","fetch","retrieve","read","obtain","load","pull","access","grab","snag","receive"],["update","edit","modify","change","patch","alter","revise","refresh","correct","amend","adjust","tweak","rectify","refine"],["list","show","display","enumerate","browse","view","peek","index","catalog","survey","inspect","ls","dir"],["find","search","lookup","query","locate","filter","scan","explore","investigate","detect","scout","seek"],["archive","shelve","retire","hide","suppress","mute"],["unarchive","restore","recover","undelete","unhide"],["enable","activate","start","turn on","switch on","boot","init","initialize","setup","spin up","resume","unpause"],["disable","deactivate","stop","turn off","switch off","shutdown","halt","kill","terminate","suspend","pause","cease"],["run","execute","invoke","trigger","launch","call","perform","operate","handle","process","fire"],["restart","reboot","reset","reload","bounce","recycle","refresh"],["validate","verify","check","confirm","assert","test","audit","assess","healthcheck","ping"],["analyze","interpret","diagnose","evaluate","review","summarize","count","calculate","compute","measure","aggregate","summarise"],["copy","duplicate","clone","replicate","mirror","fork","repro"],["move","transfer","migrate","relocate","rename","shift","mv","slide"],["save","store","write","persist","commit","stash","record","log"],["sync","synchronize","resync","reconcile","align","pair"],["import","ingest","upload","push","feed"],["export","download","dump","backup","extract"],["connect","link","bind","attach","join","bridge","associate","mount","map"],["disconnect","unlink","unbind","detach","leave","dissociate","unmount","unmap"],["login","log in","sign in","authenticate","auth"],["logout","log out","sign out","disconnect"],["approve","authorize","grant","permit","allow","sanction","whitelist"],["deny","reject","revoke","forbid","block","ban","blacklist"],["encrypt","secure","lock","seal","protect","scramble","hash"],["decrypt","unlock","unseal","reveal","decode"],["deploy","release","ship","publish","roll out","promote","distribute","install"],["debug","troubleshoot","fix","repair","resolve","trace"],["compile","transpile","build","assemble","package","bundle","minify"],["buy","purchase","order","pay","checkout","spend"],["sell","refund","reimburse","charge","invoice","bill"],["subscribe","upgrade","upsell"],["unsubscribe","cancel","downgrade"],["schedule","book","appoint","reserve","plan","calendar"],["reschedule","postpone","delay","defer"],["send","dispatch","deliver","transmit","post","broadcast","notify","alert","email","text","message","chat"],["reply","respond","answer","retort"],["share","forward","retweet","repost"],["like","favorite","star","upvote","heart"],["dislike","downvote"],["follow","watch","track"],["unfollow","ignore","mute"],["user","account","member","profile","identity","customer","principal","admin","operator","client","employee","staff"],["role","group","team","squad","unit","department"],["file","document","attachment","blob","asset","object","resource","content","media"],["image","picture","photo","screenshot"],["video","clip","recording","footage"],["message","notification","alert","event","signal","webhook","ping"],["log","trace","metric","telemetry","audit trail","history"],["settings","config","configuration","preferences","options","params","env","environment","variables"],["permission","privilege","access right","policy","rule","scope"],["organization","company","tenant","workspace","org","project","repo","repository"],["product","item","sku","inventory","stock"],["task","ticket","issue","bug","story","epic","todo","job","workitem"],["id","identifier","key","uuid","guid","token","hash","fingerprint"]];var SynonymExpansionService=class{synonymMap;maxExpansions;constructor(config={}){this.maxExpansions=config.maxExpansionsPerTerm??5;const groups=config.replaceDefaults?config.additionalSynonyms||[]:[...DEFAULT_SYNONYM_GROUPS,...config.additionalSynonyms||[]];this.synonymMap=this.buildSynonymMap(groups)}buildSynonymMap(groups){const map=new Map;for(const group of groups){const normalizedGroup=group.map(term=>term.toLowerCase());for(const term of normalizedGroup){if(!map.has(term)){map.set(term,new Set)}const synonyms=map.get(term);for(const synonym of normalizedGroup){if(synonym!==term){synonyms.add(synonym)}}}}return map}getSynonyms(term){const normalized=term.toLowerCase();const synonyms=this.synonymMap.get(normalized);if(!synonyms){return[]}return Array.from(synonyms).slice(0,this.maxExpansions)}expandQuery(query){const terms=query.toLowerCase().split(/\s+/).filter(term=>term.length>1);const expandedTerms=[];for(const term of terms){expandedTerms.push(term);const synonyms=this.getSynonyms(term);expandedTerms.push(...synonyms)}return expandedTerms.join(" ")}hasExpansions(query){const terms=query.toLowerCase().split(/\s+/);return terms.some(term=>this.synonymMap.has(term))}getStats(){const termCount=this.synonymMap.size;let totalSynonyms=0;for(const synonyms of this.synonymMap.values()){totalSynonyms+=synonyms.size}return{termCount,avgSynonymsPerTerm:termCount>0?totalSynonyms/termCount:0}}};var STOP_WORDS=new Set(["the","a","an","this","that","these","those","in","on","at","to","for","of","with","by","from","into","over","after","before","between","under","about","against","during","through","and","or","but","nor","so","yet","as","than","if","because","while","when","where","unless","i","me","my","mine","myself","you","your","yours","yourself","he","him","his","himself","she","her","hers","herself","it","its","itself","we","us","our","ours","ourselves","they","them","their","theirs","themselves","who","whom","whose","which","what","is","was","are","were","been","be","being","have","has","had","having","do","does","did","doing","will","would","shall","should","can","could","may","might","must","all","any","both","each","few","more","most","other","some","such","no","nor","not","only","own","same","too","very","just","even","please","pls","plz","thanks","thank","thx","hello","hi","hey","ok","okay","yes","no","actually","basically","literally","maybe","perhaps","now","then","here","there","again","once","back","example","context","optionally","optional","etc","ie","eg"]);var DEFAULT_EMBEDDING_MODEL="Xenova/all-MiniLM-L6-v2";function messageOf(error){return error instanceof Error?error.message:String(error)}var ToolSearchService=class _ToolSearchService{static MAX_SUBSCRIPTION_RETRIES=100;static INITIAL_RETRY_DELAY_MS=10;static MAX_RETRY_DELAY_MS=1e3;vectorDB;strategy;initialized=false;mlInitialized=false;config;scope;unsubscribe;synonymService=null;synonymExpansion;indexing;subscriptionPromise;subscriptionResolved=false;subscriptionResolve=null;subscriptionReject=null;retryTimeoutId=null;disposed=false;availabilityByTool=new Map;constructor(config={},scope){this.scope=scope;const embeddingOptions=config.embeddingOptions||{strategy:"tfidf",modelName:DEFAULT_EMBEDDING_MODEL,cacheDir:"./.cache/transformers",useHNSW:false,synonymExpansion:{enabled:true,replaceDefaults:false,maxExpansionsPerTerm:5}};this.strategy=config.strategy||embeddingOptions.strategy||"tfidf";this.config={strategy:this.strategy,embeddingOptions,defaultTopK:config.defaultTopK??8,defaultSimilarityThreshold:config.defaultSimilarityThreshold??0,mode:config.mode??"codecall_only",includeTools:config.includeTools};const validModes=["codecall_only","codecall_opt_in","metadata_driven"];if(!validModes.includes(this.config.mode)){throw new Error(`Invalid CodeCall mode: ${this.config.mode}. Valid modes: ${validModes.join(", ")}`)}if(this.strategy==="ml"){this.vectorDB=new VectoriaDB({modelName:embeddingOptions.modelName||DEFAULT_EMBEDDING_MODEL,cacheDir:embeddingOptions.cacheDir||"./.cache/transformers",defaultTopK:this.config.defaultTopK,defaultSimilarityThreshold:this.config.defaultSimilarityThreshold,useHNSW:embeddingOptions.useHNSW||false})}else{this.vectorDB=this.createTfidfIndex()}this.synonymExpansion=config.synonymExpansion??embeddingOptions.synonymExpansion;if(this.strategy==="tfidf"){this.synonymService=this.createSynonymService()}this.subscriptionPromise=new Promise((resolve,reject)=>{this.subscriptionResolve=resolve;this.subscriptionReject=reject});this.setupSubscription()}createTfidfIndex(){return new TFIDFVectoria({defaultTopK:this.config.defaultTopK,defaultSimilarityThreshold:this.config.defaultSimilarityThreshold})}createSynonymService(){const synonymExpansion=this.synonymExpansion;if(synonymExpansion===false||synonymExpansion?.enabled===false)return null;return new SynonymExpansionService(synonymExpansion??{})}async ensureSubscribed(){if(this.subscriptionResolved){return}await this.subscriptionPromise}setupSubscription(retryCount=0,delayMs=_ToolSearchService.INITIAL_RETRY_DELAY_MS){if(this.scope.tools){this.subscribeToToolChanges();return}if(retryCount>=_ToolSearchService.MAX_SUBSCRIPTION_RETRIES){this.scope.logger.warn("ToolSearchService: scope.tools not available after max retries. Tool search will return incomplete results until tools are registered.");this.markSubscribed();return}const nextDelay=Math.min(delayMs*2,_ToolSearchService.MAX_RETRY_DELAY_MS);this.retryTimeoutId=setTimeout(()=>{this.retryTimeoutId=null;if(this.disposed){return}this.setupSubscription(retryCount+1,nextDelay)},delayMs)}subscribeToToolChanges(){this.unsubscribe=this.scope.tools.subscribe({immediate:true},event=>{this.queueReindex(event.snapshot)});this.markSubscribed()}queueReindex(tools){const reindex=()=>this.handleToolChange(tools);const run=(this.indexing?this.indexing.then(reindex):reindex()).catch(error=>{this.scope.logger.warn(`CodeCall tool search could not index the tools: ${messageOf(error)}`)});this.indexing=run;void run.then(()=>{if(this.indexing===run)this.indexing=void 0})}markSubscribed(){this.subscriptionResolved=true;if(this.subscriptionResolve){this.subscriptionResolve();this.subscriptionResolve=null}}async handleToolChange(tools){if(tools.length>0&&!this.mlInitialized&&this.strategy==="ml"&&this.vectorDB instanceof VectoriaDB){try{await this.vectorDB.initialize();this.mlInitialized=true}catch(error){this.fallBackToTfidf(error)}}const availabilityByTool=new Map;const documents=tools.flatMap(tool=>this.toDocuments(tool,availabilityByTool));await this.replaceIndex(documents);this.availabilityByTool=availabilityByTool;this.initialized=true}toDocuments(tool,availabilityByTool){try{if(!this.shouldIndexTool(tool))return[];const toolName=tool.name;const document={id:toolName,text:this.extractSearchableText(tool),metadata:{id:toolName,toolName,qualifiedName:tool.fullName||toolName,appId:this.extractAppId(tool),toolInstance:tool}};availabilityByTool.set(toolName,tool.metadata.availableWhen);return[document]}catch(error){this.scope.logger.warn(`CodeCall tool search skipped tool "${tool.name}": ${messageOf(error)}`);return[]}}async replaceIndex(documents){if(this.vectorDB instanceof VectoriaDB){try{this.vectorDB.clear();if(documents.length>0)await this.vectorDB.addMany(documents);return}catch(error){this.fallBackToTfidf(error)}}const index=this.createTfidfIndex();index.addDocuments(documents);index.reindex();this.vectorDB=index}fallBackToTfidf(error){const modelName=this.config.embeddingOptions.modelName||DEFAULT_EMBEDDING_MODEL;this.scope.logger.warn(`CodeCall could not use embedding model "${modelName}" (${messageOf(error)}); tool search uses TF-IDF instead`);this.strategy="tfidf";this.vectorDB=this.createTfidfIndex();this.synonymService=this.createSynonymService()}shouldIndexTool(tool){return checkCodeCallToolPolicy(toCodeCallPolicyTool(tool,void 0,this.scope),this.config).allowed}async initialize(){}dispose(){this.disposed=true;if(this.retryTimeoutId){clearTimeout(this.retryTimeoutId);this.retryTimeoutId=null}if(this.subscriptionReject){this.subscriptionReject(new Error("ToolSearchService disposed before subscription completed"));this.subscriptionReject=null;this.subscriptionResolve=null}if(this.unsubscribe){this.unsubscribe();this.unsubscribe=void 0}}extractSearchableText(tool){const parts=[];if(tool.name){const nameParts=tool.name.split(/[:\-_.]/).filter(Boolean);for(const part of nameParts){parts.push(part,part)}}if(tool.metadata.description){const description=tool.metadata.description;parts.push(description,description,description);const keyTerms=description.toLowerCase().split(/\s+/).filter(word=>word.length>=4&&!this.isStopWord(word));parts.push(...keyTerms)}if(tool.metadata.tags&&tool.metadata.tags.length>0){for(const tag of tool.metadata.tags){parts.push(tag,tag)}}if(tool.rawInputSchema&&typeof tool.rawInputSchema==="object"){const schema=tool.rawInputSchema;if(schema.properties){parts.push(...Object.keys(schema.properties))}}const examples=tool.metadata?.examples;if(examples&&Array.isArray(examples)){for(const ex of examples){if(ex.description){parts.push(ex.description,ex.description)}if(ex.input&&typeof ex.input==="object"){for(const[key,value]of Object.entries(ex.input)){parts.push(key);if(typeof value==="string"){parts.push(value)}}}}}return parts.join(" ")}isStopWord(word){return STOP_WORDS.has(word)}extractAppId(tool){return codeCallAppIdOf(this.scope,tool)}async search(query,options={}){await this.ensureSubscribed();await this.indexing;const{topK=this.config.defaultTopK,appIds,excludeToolNames=[],surface}=options;const minScore=this.config.defaultSimilarityThreshold;const filter=metadata=>{if(excludeToolNames.includes(metadata.toolName)){return false}if(!isOfferedToCaller(metadata.toolInstance.metadata.availableWhen,surface)){return false}if(appIds&&appIds.length>0){if(!metadata.appId||!appIds.includes(metadata.appId)){return false}}return true};const effectiveQuery=this.synonymService?this.synonymService.expandQuery(query):query;const results=await this.vectorDB.search(effectiveQuery,{topK,threshold:minScore,filter});return results.map(result=>({toolName:result.metadata.toolName,appId:result.metadata.appId,description:result.metadata.toolInstance.metadata.description||"",relevanceScore:result.score}))}getAllToolNames(){if(this.vectorDB instanceof VectoriaDB){return this.vectorDB.getAll().map(doc=>doc.id)}else{return this.vectorDB.getAllDocumentIds()}}getTotalCount(surface){if(surface!==void 0){return this.getAllToolNames().filter(toolName=>this.hasTool(toolName,surface)).length}if(this.vectorDB instanceof VectoriaDB){return this.vectorDB.size()}else{return this.vectorDB.getDocumentCount()}}hasTool(toolName,surface){const indexed=this.vectorDB instanceof VectoriaDB?this.vectorDB.has(toolName):this.vectorDB.hasDocument(toolName);return indexed&&isOfferedToCaller(this.availabilityByTool.get(toolName),surface)}clear(){this.vectorDB.clear();this.availabilityByTool=new Map;this.initialized=false}getStrategy(){return this.strategy}isInitialized(){return this.initialized}};import{Enclave}from"@enclave-vm/core";import{Provider as Provider3,ProviderScope as ProviderScope3}from"@frontmcp/sdk";import{ForbiddenLoopRule,JSAstValidator,ValidationSeverity}from"@enclave-vm/ast";var AGENTSCRIPT_PARSE_OPTIONS={ecmaVersion:"latest",sourceType:"script",allowReturnOutsideFunction:true,allowAwaitOutsideFunction:true};var PARSE_ATTEMPTS=[{wrap:code=>code,parseOptions:AGENTSCRIPT_PARSE_OPTIONS,lineOffset:0},{wrap:code=>code,parseOptions:{...AGENTSCRIPT_PARSE_OPTIONS,sourceType:"module"},lineOffset:0},{wrap:code=>`async function __temp__() {
1921
2
  ${code}
1922
- }`,
1923
- parseOptions: AGENTSCRIPT_PARSE_OPTIONS,
1924
- lineOffset: 1
1925
- }
1926
- ];
1927
- var NON_REFERENCE_KEYS = /* @__PURE__ */ new Set(["type", "loc", "start", "end", "range", "label"]);
1928
- function isAstNode(value) {
1929
- return typeof value === "object" && value !== null && typeof value.type === "string";
1930
- }
1931
- function isPropertyName(parent, key) {
1932
- if (!parent || parent["computed"]) return false;
1933
- if (parent.type === "MemberExpression") return key === "property";
1934
- return key === "key" && ["Property", "MethodDefinition", "PropertyDefinition"].includes(parent.type);
1935
- }
1936
- function visitIdentifierReferences(node, visit, parent, key = "") {
1937
- if (node.type === "Identifier") {
1938
- if (!isPropertyName(parent, key)) visit(node);
1939
- return;
1940
- }
1941
- for (const [childKey, child] of Object.entries(node)) {
1942
- if (NON_REFERENCE_KEYS.has(childKey)) continue;
1943
- const children = Array.isArray(child) ? child : [child];
1944
- for (const childNode of children) {
1945
- if (isAstNode(childNode)) visitIdentifierReferences(childNode, visit, node, childKey);
1946
- }
1947
- }
1948
- }
1949
- var DisallowedGlobalsRule = class {
1950
- constructor(messages) {
1951
- this.messages = messages;
1952
- }
1953
- messages;
1954
- name = "codecall-disallowed-globals";
1955
- description = "Globals CodeCall scripts may not use";
1956
- defaultSeverity = ValidationSeverity.ERROR;
1957
- enabledByDefault = true;
1958
- validate(context) {
1959
- visitIdentifierReferences(context.ast, (identifier) => {
1960
- const message = identifier.name === void 0 ? void 0 : this.messages.get(identifier.name);
1961
- if (message === void 0) return;
1962
- context.report({
1963
- code: "DISALLOWED_IDENTIFIER",
1964
- message,
1965
- location: identifier.loc ? { line: identifier.loc.start.line, column: identifier.loc.start.column } : void 0,
1966
- data: { identifier: identifier.name }
1967
- });
1968
- });
1969
- }
1970
- };
1971
- function disallowedGlobalMessages({ disabledBuiltins, disabledGlobals }) {
1972
- return new Map([
1973
- ...disabledBuiltins.map((name) => [name, `${name} is disabled by vm.disabledBuiltins`]),
1974
- ...disabledGlobals.map((name) => [name, `${name} is disabled by vm.disabledGlobals`]),
1975
- ["console", "console is not available in CodeCall scripts; use mcpLog(level, message)"]
1976
- ]);
1977
- }
1978
- function scriptPolicyRules(options) {
1979
- const rules = [new DisallowedGlobalsRule(disallowedGlobalMessages(options))];
1980
- if (!options.allowLoops) {
1981
- rules.push(
1982
- new ForbiddenLoopRule({
1983
- allowFor: false,
1984
- allowForOf: true,
1985
- allowWhile: false,
1986
- allowDoWhile: false,
1987
- allowForIn: false,
1988
- message: "Only for-of loops are allowed (vm.allowLoops is false)"
1989
- })
1990
- );
1991
- }
1992
- return rules;
1993
- }
1994
- async function findScriptPolicyIssues(code, options) {
1995
- const validator = new JSAstValidator(scriptPolicyRules(options));
1996
- for (const attempt of PARSE_ATTEMPTS) {
1997
- const result = await validator.validate(attempt.wrap(code), {
1998
- parseOptions: attempt.parseOptions,
1999
- preScan: { enabled: false }
2000
- });
2001
- if (result.parseError) continue;
2002
- return result.issues.map(
2003
- (issue) => issue.location && attempt.lineOffset > 0 ? { ...issue, location: { ...issue.location, line: issue.location.line - attempt.lineOffset } } : issue
2004
- );
2005
- }
2006
- return [];
2007
- }
2008
-
2009
- // plugins/plugin-codecall/src/utils/build-tool-namespaces.ts
2010
- var IDENT_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
2011
- var PROTOTYPE_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
2012
- var RESERVED_NAMESPACES = /* @__PURE__ */ new Set([
2013
- "console",
2014
- "Math",
2015
- "JSON",
2016
- "Object",
2017
- "Array",
2018
- "String",
2019
- "Number",
2020
- "Boolean",
2021
- "Promise",
2022
- "Symbol",
2023
- "Map",
2024
- "Set",
2025
- "WeakMap",
2026
- "WeakSet",
2027
- "Date",
2028
- "Error",
2029
- "RegExp",
2030
- "globalThis",
2031
- "global",
2032
- "window",
2033
- "self",
2034
- "undefined",
2035
- "null",
2036
- "true",
2037
- "false",
2038
- "callTool",
2039
- "getTool",
2040
- "mcpLog",
2041
- "mcpNotify"
2042
- ]);
2043
- var UNBINDABLE_NAMESPACES = new Set(
2044
- [
2045
- // Reserved words and strict-mode restricted bindings
2046
- "break case catch class const continue debugger default delete do else enum export extends finally for",
2047
- "function if import in instanceof new return super switch this throw try typeof var void while with yield",
2048
- "let static implements interface package private protected public await eval arguments NaN Infinity",
2049
- // AgentScript globals
2050
- "parallel isNaN isFinite parseInt parseFloat encodeURI encodeURIComponent decodeURI decodeURIComponent",
2051
- // Identifiers the AgentScript validator refuses
2052
- "process require module exports Buffer Function AsyncFunction GeneratorFunction Reflect Proxy TypeError",
2053
- "ReferenceError SyntaxError RangeError URIError EvalError AggregateError fetch XMLHttpRequest WebSocket",
2054
- "localStorage sessionStorage indexedDB crypto performance structuredClone AbortController AbortSignal",
2055
- "MessageChannel MessagePort BroadcastChannel TextEncoder TextDecoder Intl setTimeout setInterval",
2056
- "setImmediate clearTimeout clearInterval clearImmediate queueMicrotask WebAssembly Worker SharedWorker",
2057
- "ServiceWorker WeakRef FinalizationRegistry BigInt Atomics SharedArrayBuffer ArrayBuffer DataView",
2058
- "importScripts ShadowRealm Iterator AsyncIterator"
2059
- ].join(" ").split(" ")
2060
- );
2061
- var UNCALLABLE_METHODS = new Set(
2062
- [
2063
- "process require module exports Buffer eval Function AsyncFunction GeneratorFunction arguments RegExp",
2064
- "Promise Symbol Proxy Reflect Error TypeError ReferenceError SyntaxError RangeError URIError EvalError",
2065
- "AggregateError fetch XMLHttpRequest WebSocket localStorage sessionStorage indexedDB crypto performance",
2066
- "structuredClone AbortController AbortSignal MessageChannel MessagePort BroadcastChannel TextEncoder",
2067
- "TextDecoder Intl setTimeout setInterval setImmediate clearTimeout clearInterval clearImmediate",
2068
- "queueMicrotask WebAssembly Worker SharedWorker ServiceWorker WeakMap WeakSet WeakRef FinalizationRegistry",
2069
- "Map Set Atomics SharedArrayBuffer importScripts ShadowRealm Iterator AsyncIterator"
2070
- ].join(" ").split(" ")
2071
- );
2072
- var SANDBOX_TOOL_NAME_RE = /^[a-zA-Z][a-zA-Z0-9:._-]*$/;
2073
- var MAX_SANDBOX_TOOL_NAME_LENGTH = 256;
2074
- function isBindableNamespace(ns, reservedGlobals) {
2075
- return IDENT_RE.test(ns) && !PROTOTYPE_KEYS.has(ns) && !ns.startsWith("__") && !RESERVED_NAMESPACES.has(ns) && !UNBINDABLE_NAMESPACES.has(ns) && !reservedGlobals.has(ns);
2076
- }
2077
- function isBindableMethod(ns, method, toolName) {
2078
- return IDENT_RE.test(method) && !PROTOTYPE_KEYS.has(method) && !method.startsWith("__") && !UNCALLABLE_METHODS.has(method) && toolName === `${ns}.${method}` && toolName.length <= MAX_SANDBOX_TOOL_NAME_LENGTH && SANDBOX_TOOL_NAME_RE.test(toolName);
2079
- }
2080
- function buildToolNamespaces(tools) {
2081
- const namespaces = /* @__PURE__ */ Object.create(null);
2082
- const skipped = [];
2083
- for (const tool of tools) {
2084
- const name = tool?.name;
2085
- if (typeof name !== "string" || name.length === 0) continue;
2086
- const dot = name.indexOf(".");
2087
- if (dot <= 0 || dot === name.length - 1) {
2088
- skipped.push({ name, reason: "no-namespace-prefix" });
2089
- continue;
2090
- }
2091
- const ns = name.slice(0, dot);
2092
- const method = name.slice(dot + 1);
2093
- if (!IDENT_RE.test(ns) || !IDENT_RE.test(method)) {
2094
- skipped.push({ name, reason: "invalid-identifier" });
2095
- continue;
2096
- }
2097
- if (PROTOTYPE_KEYS.has(ns) || PROTOTYPE_KEYS.has(method)) {
2098
- skipped.push({ name, reason: "prototype-key" });
2099
- continue;
2100
- }
2101
- if (RESERVED_NAMESPACES.has(ns) || UNBINDABLE_NAMESPACES.has(ns) || ns.startsWith("__")) {
2102
- skipped.push({ name, reason: "reserved-namespace" });
2103
- continue;
2104
- }
2105
- if (!isBindableMethod(ns, method, name)) {
2106
- skipped.push({ name, reason: "unsupported-name" });
2107
- continue;
2108
- }
2109
- const bucket = namespaces[ns] ?? (namespaces[ns] = /* @__PURE__ */ Object.create(null));
2110
- if (Object.prototype.hasOwnProperty.call(bucket, method)) {
2111
- skipped.push({ name, reason: "duplicate-method" });
2112
- continue;
2113
- }
2114
- bucket[method] = name;
2115
- }
2116
- return { namespaces, skipped };
2117
- }
2118
- function toSandboxToolNamespaces(namespaces, reservedGlobals = []) {
2119
- if (!namespaces) return void 0;
2120
- const reserved = new Set(reservedGlobals);
2121
- const bindable = /* @__PURE__ */ Object.create(null);
2122
- let count = 0;
2123
- for (const ns of Object.keys(namespaces)) {
2124
- if (!isBindableNamespace(ns, reserved)) continue;
2125
- const methods = namespaces[ns];
2126
- const bucket = /* @__PURE__ */ Object.create(null);
2127
- let methodCount = 0;
2128
- for (const method of Object.keys(methods)) {
2129
- const toolName = methods[method];
2130
- if (typeof toolName !== "string" || !isBindableMethod(ns, method, toolName)) continue;
2131
- bucket[method] = toolName;
2132
- methodCount += 1;
2133
- }
2134
- if (methodCount > 0) {
2135
- bindable[ns] = bucket;
2136
- count += 1;
2137
- }
2138
- }
2139
- return count > 0 ? bindable : void 0;
2140
- }
2141
-
2142
- // plugins/plugin-codecall/src/utils/script-lines.ts
2143
- import { isWrappedInMain, transformAgentScript } from "@enclave-vm/ast";
2144
- import * as acorn from "acorn";
2145
- var PARSE_OPTIONS = { ecmaVersion: "latest", locations: true };
2146
- var NON_CHILD_KEYS = /* @__PURE__ */ new Set(["type", "loc", "start", "end", "range"]);
2147
- function isNode(value) {
2148
- return typeof value === "object" && value !== null && typeof value.type === "string";
2149
- }
2150
- function isAddedByTransform(node) {
2151
- if (node.type === "VariableDeclaration") {
2152
- const [declaration] = node["declarations"] ?? [];
2153
- const id = declaration?.["id"];
2154
- return typeof id?.["name"] === "string" && id["name"].startsWith("__iter_");
2155
- }
2156
- if (node.type === "IfStatement") {
2157
- const right = node["test"]?.["right"];
2158
- return right?.type === "Identifier" && right["name"] === "__maxIterations";
2159
- }
2160
- return false;
2161
- }
2162
- function parseScript(script) {
2163
- try {
2164
- return { body: parseBody(script, "script"), offset: 0 };
2165
- } catch {
2166
- try {
2167
- return { body: parseBody(script, "module"), offset: 0 };
2168
- } catch {
2169
- const wrapped = parseBody(`async function __temp__() {
3
+ }`,parseOptions:AGENTSCRIPT_PARSE_OPTIONS,lineOffset:1}];var NON_REFERENCE_KEYS=new Set(["type","loc","start","end","range","label"]);function isAstNode(value){return typeof value==="object"&&value!==null&&typeof value.type==="string"}function isPropertyName(parent,key){if(!parent||parent["computed"])return false;if(parent.type==="MemberExpression")return key==="property";return key==="key"&&["Property","MethodDefinition","PropertyDefinition"].includes(parent.type)}function visitIdentifierReferences(node,visit,parent,key=""){if(node.type==="Identifier"){if(!isPropertyName(parent,key))visit(node);return}for(const[childKey,child]of Object.entries(node)){if(NON_REFERENCE_KEYS.has(childKey))continue;const children=Array.isArray(child)?child:[child];for(const childNode of children){if(isAstNode(childNode))visitIdentifierReferences(childNode,visit,node,childKey)}}}var DisallowedGlobalsRule=class{constructor(messages){this.messages=messages}messages;name="codecall-disallowed-globals";description="Globals CodeCall scripts may not use";defaultSeverity=ValidationSeverity.ERROR;enabledByDefault=true;validate(context){visitIdentifierReferences(context.ast,identifier=>{const message=identifier.name===void 0?void 0:this.messages.get(identifier.name);if(message===void 0)return;context.report({code:"DISALLOWED_IDENTIFIER",message,location:identifier.loc?{line:identifier.loc.start.line,column:identifier.loc.start.column}:void 0,data:{identifier:identifier.name}})})}};function disallowedGlobalMessages({disabledBuiltins,disabledGlobals}){return new Map([...disabledBuiltins.map(name=>[name,`${name} is disabled by vm.disabledBuiltins`]),...disabledGlobals.map(name=>[name,`${name} is disabled by vm.disabledGlobals`]),["console","console is not available in CodeCall scripts; use mcpLog(level, message)"]])}function scriptPolicyRules(options){const rules=[new DisallowedGlobalsRule(disallowedGlobalMessages(options))];if(!options.allowLoops){rules.push(new ForbiddenLoopRule({allowFor:false,allowForOf:true,allowWhile:false,allowDoWhile:false,allowForIn:false,message:"Only for-of loops are allowed (vm.allowLoops is false)"}))}return rules}async function findScriptPolicyIssues(code,options){const validator=new JSAstValidator(scriptPolicyRules(options));for(const attempt of PARSE_ATTEMPTS){const result=await validator.validate(attempt.wrap(code),{parseOptions:attempt.parseOptions,preScan:{enabled:false}});if(result.parseError)continue;return result.issues.map(issue=>issue.location&&attempt.lineOffset>0?{...issue,location:{...issue.location,line:issue.location.line-attempt.lineOffset}}:issue)}return[]}var IDENT_RE=/^[A-Za-z_$][A-Za-z0-9_$]*$/;var PROTOTYPE_KEYS=new Set(["__proto__","constructor","prototype"]);var RESERVED_NAMESPACES=new Set(["console","Math","JSON","Object","Array","String","Number","Boolean","Promise","Symbol","Map","Set","WeakMap","WeakSet","Date","Error","RegExp","globalThis","global","window","self","undefined","null","true","false","callTool","getTool","mcpLog","mcpNotify"]);var UNBINDABLE_NAMESPACES=new Set(["break case catch class const continue debugger default delete do else enum export extends finally for","function if import in instanceof new return super switch this throw try typeof var void while with yield","let static implements interface package private protected public await eval arguments NaN Infinity","parallel isNaN isFinite parseInt parseFloat encodeURI encodeURIComponent decodeURI decodeURIComponent","process require module exports Buffer Function AsyncFunction GeneratorFunction Reflect Proxy TypeError","ReferenceError SyntaxError RangeError URIError EvalError AggregateError fetch XMLHttpRequest WebSocket","localStorage sessionStorage indexedDB crypto performance structuredClone AbortController AbortSignal","MessageChannel MessagePort BroadcastChannel TextEncoder TextDecoder Intl setTimeout setInterval","setImmediate clearTimeout clearInterval clearImmediate queueMicrotask WebAssembly Worker SharedWorker","ServiceWorker WeakRef FinalizationRegistry BigInt Atomics SharedArrayBuffer ArrayBuffer DataView","importScripts ShadowRealm Iterator AsyncIterator"].join(" ").split(" "));var UNCALLABLE_METHODS=new Set(["process require module exports Buffer eval Function AsyncFunction GeneratorFunction arguments RegExp","Promise Symbol Proxy Reflect Error TypeError ReferenceError SyntaxError RangeError URIError EvalError","AggregateError fetch XMLHttpRequest WebSocket localStorage sessionStorage indexedDB crypto performance","structuredClone AbortController AbortSignal MessageChannel MessagePort BroadcastChannel TextEncoder","TextDecoder Intl setTimeout setInterval setImmediate clearTimeout clearInterval clearImmediate","queueMicrotask WebAssembly Worker SharedWorker ServiceWorker WeakMap WeakSet WeakRef FinalizationRegistry","Map Set Atomics SharedArrayBuffer importScripts ShadowRealm Iterator AsyncIterator"].join(" ").split(" "));var SANDBOX_TOOL_NAME_RE=/^[a-zA-Z][a-zA-Z0-9:._-]*$/;var MAX_SANDBOX_TOOL_NAME_LENGTH=256;function isBindableNamespace(ns,reservedGlobals){return IDENT_RE.test(ns)&&!PROTOTYPE_KEYS.has(ns)&&!ns.startsWith("__")&&!RESERVED_NAMESPACES.has(ns)&&!UNBINDABLE_NAMESPACES.has(ns)&&!reservedGlobals.has(ns)}function isBindableMethod(ns,method,toolName){return IDENT_RE.test(method)&&!PROTOTYPE_KEYS.has(method)&&!method.startsWith("__")&&!UNCALLABLE_METHODS.has(method)&&toolName===`${ns}.${method}`&&toolName.length<=MAX_SANDBOX_TOOL_NAME_LENGTH&&SANDBOX_TOOL_NAME_RE.test(toolName)}function buildToolNamespaces(tools){const namespaces=Object.create(null);const skipped=[];for(const tool of tools){const name=tool?.name;if(typeof name!=="string"||name.length===0)continue;const dot=name.indexOf(".");if(dot<=0||dot===name.length-1){skipped.push({name,reason:"no-namespace-prefix"});continue}const ns=name.slice(0,dot);const method=name.slice(dot+1);if(!IDENT_RE.test(ns)||!IDENT_RE.test(method)){skipped.push({name,reason:"invalid-identifier"});continue}if(PROTOTYPE_KEYS.has(ns)||PROTOTYPE_KEYS.has(method)){skipped.push({name,reason:"prototype-key"});continue}if(RESERVED_NAMESPACES.has(ns)||UNBINDABLE_NAMESPACES.has(ns)||ns.startsWith("__")){skipped.push({name,reason:"reserved-namespace"});continue}if(!isBindableMethod(ns,method,name)){skipped.push({name,reason:"unsupported-name"});continue}const bucket=namespaces[ns]??(namespaces[ns]=Object.create(null));if(Object.prototype.hasOwnProperty.call(bucket,method)){skipped.push({name,reason:"duplicate-method"});continue}bucket[method]=name}return{namespaces,skipped}}function toSandboxToolNamespaces(namespaces,reservedGlobals=[]){if(!namespaces)return void 0;const reserved=new Set(reservedGlobals);const bindable=Object.create(null);let count=0;for(const ns of Object.keys(namespaces)){if(!isBindableNamespace(ns,reserved))continue;const methods=namespaces[ns];const bucket=Object.create(null);let methodCount=0;for(const method of Object.keys(methods)){const toolName=methods[method];if(typeof toolName!=="string"||!isBindableMethod(ns,method,toolName))continue;bucket[method]=toolName;methodCount+=1}if(methodCount>0){bindable[ns]=bucket;count+=1}}return count>0?bindable:void 0}import{isWrappedInMain,transformAgentScript}from"@enclave-vm/ast";import*as acorn from"acorn";var PARSE_OPTIONS={ecmaVersion:"latest",locations:true};var NON_CHILD_KEYS=new Set(["type","loc","start","end","range"]);function isNode(value){return typeof value==="object"&&value!==null&&typeof value.type==="string"}function isAddedByTransform(node){if(node.type==="VariableDeclaration"){const[declaration]=node["declarations"]??[];const id=declaration?.["id"];return typeof id?.["name"]==="string"&&id["name"].startsWith("__iter_")}if(node.type==="IfStatement"){const right=node["test"]?.["right"];return right?.type==="Identifier"&&right["name"]==="__maxIterations"}return false}function parseScript(script){try{return{body:parseBody(script,"script"),offset:0}}catch{try{return{body:parseBody(script,"module"),offset:0}}catch{const wrapped=parseBody(`async function __temp__() {
2170
4
  ${script}
2171
- }`, "script");
2172
- const fn = wrapped[0];
2173
- const block = fn?.["body"];
2174
- return { body: block?.["body"] ?? [], offset: 1 };
2175
- }
2176
- }
2177
- }
2178
- function parseBody(code, sourceType) {
2179
- const program = acorn.parse(code, { ...PARSE_OPTIONS, sourceType });
2180
- return program["body"] ?? [];
2181
- }
2182
- function treesOf(script) {
2183
- try {
2184
- const wrap = !isWrappedInMain(script);
2185
- const printed = parseBody(transformAgentScript(script, { wrapInMain: wrap }), "script");
2186
- const { body, offset } = parseScript(script);
2187
- if (!wrap) return { printed, script: body, offset };
2188
- const main = printed[0]?.["body"];
2189
- return { printed: main?.["body"] ?? [], script: body, offset };
2190
- } catch {
2191
- return void 0;
2192
- }
2193
- }
2194
- function pairLists(printed, script, depth, out, offset) {
2195
- const kept = printed.filter((node) => !(isNode(node) && isAddedByTransform(node)));
2196
- if (kept.length !== script.length) return;
2197
- kept.forEach((node, index) => {
2198
- const own = script[index];
2199
- if (isNode(node) && isNode(own)) pairNodes(node, own, depth, out, offset);
2200
- });
2201
- }
2202
- function pairNodes(printed, script, depth, out, offset) {
2203
- if (printed.type === "ReturnStatement" && script.type === "ExpressionStatement") {
2204
- record(printed, script, depth, out, offset);
2205
- const argument = printed["argument"];
2206
- const expression = script["expression"];
2207
- if (isNode(argument) && isNode(expression)) pairNodes(argument, expression, depth + 1, out, offset);
2208
- return;
2209
- }
2210
- if (printed.type !== script.type) return;
2211
- record(printed, script, depth, out, offset);
2212
- for (const key of Object.keys(printed)) {
2213
- if (NON_CHILD_KEYS.has(key)) continue;
2214
- const printedChild = printed[key];
2215
- const scriptChild = script[key];
2216
- if (Array.isArray(printedChild) && Array.isArray(scriptChild)) {
2217
- pairLists(printedChild, scriptChild, depth + 1, out, offset);
2218
- } else if (isNode(printedChild) && isNode(scriptChild)) {
2219
- pairNodes(printedChild, scriptChild, depth + 1, out, offset);
2220
- }
2221
- }
2222
- }
2223
- function record(printed, script, depth, out, offset) {
2224
- if (!printed.loc || !script.loc) return;
2225
- out.push({
2226
- printedStart: printed.loc.start.line,
2227
- printedEnd: printed.loc.end.line,
2228
- scriptLine: script.loc.start.line - offset,
2229
- depth
2230
- });
2231
- }
2232
- function validatedLineMapper(script) {
2233
- const trees = treesOf(script);
2234
- if (!trees) return () => void 0;
2235
- const pairs = [];
2236
- pairLists(trees.printed, trees.script, 0, pairs, trees.offset);
2237
- return (printedLine) => {
2238
- const starting = pairs.filter((pair) => pair.printedStart === printedLine);
2239
- const candidates = starting.length > 0 ? starting : pairs.filter((pair) => pair.printedStart <= printedLine && printedLine <= pair.printedEnd);
2240
- const best = candidates.reduce(
2241
- (deepest, pair) => !deepest || pair.depth > deepest.depth ? pair : deepest,
2242
- void 0
2243
- );
2244
- return best && best.scriptLine >= 1 ? best.scriptLine : void 0;
2245
- };
2246
- }
2247
- var ISSUE_LINE_RE = / \(line (\d+)\)/g;
2248
- function withScriptLines(message, script) {
2249
- if (!message.includes("(line ")) return message;
2250
- const lineOf = validatedLineMapper(script);
2251
- return message.replace(ISSUE_LINE_RE, (_match, printed) => {
2252
- const line = lineOf(Number(printed));
2253
- return line === void 0 ? "" : ` (line ${line})`;
2254
- });
2255
- }
2256
-
2257
- // plugins/plugin-codecall/src/services/enclave.service.ts
2258
- function toolFailureMessage(error, toolName) {
2259
- if (typeof error === "string" && error) return error;
2260
- const message = error?.message;
2261
- return typeof message === "string" && message ? message : `Tool call failed: ${toolName}`;
2262
- }
2263
- function toolFailureName(error) {
2264
- const name = error && typeof error === "object" ? error.name : void 0;
2265
- return typeof name === "string" && name ? name.slice(0, 128) : "ToolError";
2266
- }
2267
- var ITERATION_LIMIT_PREFIX = "Maximum iteration limit exceeded";
2268
- var ITERATION_LIMIT_ERROR = {
2269
- name: "Error",
2270
- message: `${ITERATION_LIMIT_PREFIX} (${MAX_ITERATIONS_PER_LOOP}). This limit prevents infinite loops.`
2271
- };
2272
- var PARSE_FAILURE_PREFIX = "Failed to parse AgentScript code: ";
2273
- var PARSE_POSITION_RE = /\((\d+):(\d+)\)$/;
2274
- function parseFailureOf(message) {
2275
- const match = PARSE_POSITION_RE.exec(message);
2276
- const line = match ? Number(match[1]) - 1 : 0;
2277
- if (!match || line < 1) return { message };
2278
- const column = Number(match[2]);
2279
- return { message: `${message.slice(0, match.index)}(${line}:${column})`, location: { line, column } };
2280
- }
2281
- var ScriptTooLargeError = class extends Error {
2282
- code = "SCRIPT_TOO_LARGE";
2283
- scriptLength;
2284
- maxLength;
2285
- constructor(scriptLength, maxLength) {
2286
- super(
2287
- `Script length (${scriptLength} characters) exceeds maximum allowed length (${maxLength} characters). Enable sidecar to handle large data, or reduce script size.`
2288
- );
2289
- this.name = "ScriptTooLargeError";
2290
- this.scriptLength = scriptLength;
2291
- this.maxLength = maxLength;
2292
- }
2293
- };
2294
- var EnclaveService = class {
2295
- vmOptions;
2296
- sidecarOptions;
2297
- constructor(config) {
2298
- const all = config.getAll();
2299
- this.vmOptions = all.resolvedVm;
2300
- this.sidecarOptions = all.sidecar;
2301
- }
2302
- /**
2303
- * Execute AgentScript code in the enclave
2304
- *
2305
- * @param code - The AgentScript code to execute (raw, not transformed)
2306
- * @param environment - The VM environment with callTool, getTool, etc.
2307
- * @returns Execution result with success/error and logs
2308
- * @throws ScriptTooLargeError if script exceeds max length and sidecar is disabled
2309
- */
2310
- async execute(code, environment) {
2311
- const logs = [];
2312
- if (!this.sidecarOptions.enabled && this.sidecarOptions.maxScriptLengthWhenDisabled !== null) {
2313
- const maxLength = this.sidecarOptions.maxScriptLengthWhenDisabled;
2314
- if (code.length > maxLength) {
2315
- throw new ScriptTooLargeError(code.length, maxLength);
2316
- }
2317
- }
2318
- const policyIssues = await findScriptPolicyIssues(code, this.vmOptions);
2319
- if (policyIssues.length > 0) {
2320
- return {
2321
- success: false,
2322
- error: {
2323
- message: `AgentScript validation failed:
2324
- ${policyIssues.map((issue) => `${issue.code}${issue.location ? ` (line ${issue.location.line})` : ""}: ${issue.message}`).join("\n")}`,
2325
- name: "ValidationError",
2326
- code: "VALIDATION_ERROR",
2327
- blockedPatterns: [...new Set(policyIssues.map((issue) => issue.code))]
2328
- },
2329
- logs,
2330
- timedOut: false,
2331
- stats: { duration: 0, toolCallCount: 0, iterationCount: 0 }
2332
- };
2333
- }
2334
- const toolFailures = [];
2335
- const toolHandler = async (toolName, args) => {
2336
- try {
2337
- return await environment.callTool(toolName, args);
2338
- } catch (error) {
2339
- const code2 = error?.code;
2340
- toolFailures.push({
2341
- toolName,
2342
- name: toolFailureName(error),
2343
- message: toolFailureMessage(error, toolName),
2344
- ...typeof code2 === "string" ? { code: code2 } : {}
2345
- });
2346
- throw error;
2347
- }
2348
- };
2349
- const sidecar = this.sidecarOptions.enabled ? {
2350
- enabled: true,
2351
- maxTotalSize: this.sidecarOptions.maxTotalSize,
2352
- maxReferenceSize: this.sidecarOptions.maxReferenceSize,
2353
- extractionThreshold: this.sidecarOptions.extractionThreshold,
2354
- maxResolvedSize: this.sidecarOptions.maxResolvedSize,
2355
- allowComposites: this.sidecarOptions.allowComposites
2356
- } : void 0;
2357
- const { mcpLog, mcpNotify } = environment;
2358
- const globals = {
2359
- // Provide getTool as a custom global
2360
- getTool: environment.getTool,
2361
- // Provide logging functions if available
2362
- ...mcpLog ? {
2363
- mcpLog: (level, message, metadata) => {
2364
- mcpLog(level, message, metadata);
2365
- logs.push(`[mcp:${level}] ${message}`);
2366
- }
2367
- } : {},
2368
- ...mcpNotify ? {
2369
- mcpNotify: (event, payload) => {
2370
- mcpNotify(event, payload);
2371
- logs.push(`[notify] ${event}`);
2372
- }
2373
- } : {}
2374
- // Note: enclave-vm v2.0.0+ provides its own __safe_console internally with rate limiting
2375
- // and output size limits. Passing console in globals causes "Cannot redefine property"
2376
- // errors due to Double VM architecture. Console output from user scripts goes to stdout
2377
- // via enclave's internal console, not to this logs array. Only mcpLog/mcpNotify are captured.
2378
- };
2379
- const { rapidEnumerationThreshold, rapidEnumerationOverrides } = this.vmOptions;
2380
- const options = {
2381
- timeout: this.vmOptions.timeoutMs,
2382
- maxToolCalls: maxToolCallsOf(this.vmOptions),
2383
- maxIterations: MAX_ITERATIONS_PER_LOOP,
2384
- maxSanitizeDepth: this.vmOptions.maxSanitizeDepth,
2385
- maxSanitizeProperties: this.vmOptions.maxSanitizeProperties,
2386
- toolHandler,
2387
- validate: true,
2388
- transform: true,
2389
- sidecar,
2390
- // Error stacks name no host file, whatever stage raised them.
2391
- sanitizeStackTraces: true,
2392
- // Allow functions in globals since we intentionally provide getTool, mcpLog, mcpNotify, and console
2393
- allowFunctionsInGlobals: true,
2394
- globals,
2395
- // Tool namespaces (`acme.getUser()` for a tool named `acme.getUser`) are built by the sandbox
2396
- // itself: a method call is exactly `callTool('acme.getUser', args, options)`, with the
2397
- // sandbox's tool-call cap, rate limit, suspicious-sequence checks and `throwOnError`.
2398
- toolNamespaces: toSandboxToolNamespaces(environment.toolNamespaces, Object.keys(globals)),
2399
- doubleVm: {
2400
- parentValidation: {
2401
- ...rapidEnumerationThreshold !== void 0 && { rapidEnumerationThreshold },
2402
- ...rapidEnumerationOverrides !== void 0 && { rapidEnumerationOverrides }
2403
- }
2404
- }
2405
- };
2406
- const enclave = createEnclave(options);
2407
- try {
2408
- const result = await enclave.run(code);
2409
- return this.mapEnclaveResult(result, logs, toolFailures, code);
2410
- } finally {
2411
- enclave.dispose();
2412
- }
2413
- }
2414
- /**
2415
- * Map Enclave ExecutionResult to EnclaveExecutionResult
2416
- */
2417
- mapEnclaveResult(result, logs, toolFailures = [], script = "") {
2418
- const stats = {
2419
- duration: result.stats.duration,
2420
- toolCallCount: result.stats.toolCallCount,
2421
- iterationCount: result.stats.iterationCount
2422
- };
2423
- if (result.success) {
2424
- return { success: true, result: result.value, logs, timedOut: false, stats };
2425
- }
2426
- const reportedError = result.error ?? { name: "Error", message: "Script execution failed" };
2427
- const toolFailure = [...toolFailures].reverse().find((failure) => failure.message === reportedError.message && failure.name === reportedError.name);
2428
- const error = !toolFailure && reportedError.message?.startsWith(ITERATION_LIMIT_PREFIX) ? { ...reportedError, ...ITERATION_LIMIT_ERROR } : reportedError;
2429
- if (error.code === "ENCLAVE_ERROR" && error.message?.startsWith(PARSE_FAILURE_PREFIX)) {
2430
- const { message, location } = parseFailureOf(error.message);
2431
- return {
2432
- success: false,
2433
- error: { message, name: "SyntaxError", code: "SYNTAX_ERROR", ...location ? { location } : {} },
2434
- logs,
2435
- timedOut: false,
2436
- stats
2437
- };
2438
- }
2439
- if (toolFailure) {
2440
- return {
2441
- success: false,
2442
- error: {
2443
- message: error.message,
2444
- name: error.name,
2445
- ...toolFailure.code ? { code: toolFailure.code } : {},
2446
- toolName: toolFailure.toolName
2447
- },
2448
- logs,
2449
- timedOut: false,
2450
- stats
2451
- };
2452
- }
2453
- const timedOut = error.message?.includes("timed out") || error.code === "TIMEOUT";
2454
- if (error.code === "VALIDATION_ERROR") {
2455
- const issues = error.data?.issues ?? [];
2456
- const blockedPatterns = [...new Set(issues.map((issue) => issue.code).filter((code) => !!code))];
2457
- return {
2458
- success: false,
2459
- error: {
2460
- // The enclave names lines of the code it validated (the script wrapped and printed again),
2461
- // not the script's own.
2462
- message: withScriptLines(error.message, script),
2463
- name: "ValidationError",
2464
- code: error.code,
2465
- ...blockedPatterns.length > 0 ? { blockedPatterns } : {}
2466
- },
2467
- logs,
2468
- timedOut: false,
2469
- stats
2470
- };
2471
- }
2472
- return {
2473
- success: false,
2474
- error: {
2475
- message: error.message,
2476
- name: error.name,
2477
- stack: error.stack,
2478
- code: error.code
2479
- },
2480
- logs,
2481
- timedOut,
2482
- stats
2483
- };
2484
- }
2485
- };
2486
- EnclaveService = __decorateClass([
2487
- Provider3({
2488
- name: "codecall:enclave",
2489
- description: "Executes AgentScript code in a secure enclave",
2490
- scope: ProviderScope3.GLOBAL
2491
- })
2492
- ], EnclaveService);
2493
- function createEnclave(options) {
2494
- try {
2495
- return new Enclave(options);
2496
- } catch (error) {
2497
- if (!options.toolNamespaces || !(error instanceof TypeError) || !error.message.startsWith("Invalid toolNamespaces")) {
2498
- throw error;
2499
- }
2500
- return new Enclave({ ...options, toolNamespaces: void 0 });
2501
- }
2502
- }
2503
-
2504
- // plugins/plugin-codecall/src/tools/search.tool.ts
2505
- import { getCallSurface, Tool, ToolContext } from "@frontmcp/sdk";
2506
-
2507
- // plugins/plugin-codecall/src/tools/search.schema.ts
2508
- import { z as z2 } from "@frontmcp/lazy-zod";
2509
- var DEFAULT_MIN_RELEVANCE_SCORE = 0.1;
2510
- function buildSearchToolDescription(topK) {
2511
- return `Find tools by splitting user request into atomic actions.
5
+ }`,"script");const fn=wrapped[0];const block=fn?.["body"];return{body:block?.["body"]??[],offset:1}}}}function parseBody(code,sourceType){const program=acorn.parse(code,{...PARSE_OPTIONS,sourceType});return program["body"]??[]}function treesOf(script){try{const wrap=!isWrappedInMain(script);const printed=parseBody(transformAgentScript(script,{wrapInMain:wrap}),"script");const{body,offset}=parseScript(script);if(!wrap)return{printed,script:body,offset};const main=printed[0]?.["body"];return{printed:main?.["body"]??[],script:body,offset}}catch{return void 0}}function pairLists(printed,script,depth,out,offset){const kept=printed.filter(node=>!(isNode(node)&&isAddedByTransform(node)));if(kept.length!==script.length)return;kept.forEach((node,index)=>{const own=script[index];if(isNode(node)&&isNode(own))pairNodes(node,own,depth,out,offset)})}function pairNodes(printed,script,depth,out,offset){if(printed.type==="ReturnStatement"&&script.type==="ExpressionStatement"){record(printed,script,depth,out,offset);const argument=printed["argument"];const expression=script["expression"];if(isNode(argument)&&isNode(expression))pairNodes(argument,expression,depth+1,out,offset);return}if(printed.type!==script.type)return;record(printed,script,depth,out,offset);for(const key of Object.keys(printed)){if(NON_CHILD_KEYS.has(key))continue;const printedChild=printed[key];const scriptChild=script[key];if(Array.isArray(printedChild)&&Array.isArray(scriptChild)){pairLists(printedChild,scriptChild,depth+1,out,offset)}else if(isNode(printedChild)&&isNode(scriptChild)){pairNodes(printedChild,scriptChild,depth+1,out,offset)}}}function record(printed,script,depth,out,offset){if(!printed.loc||!script.loc)return;out.push({printedStart:printed.loc.start.line,printedEnd:printed.loc.end.line,scriptLine:script.loc.start.line-offset,depth})}function validatedLineMapper(script){const trees=treesOf(script);if(!trees)return()=>void 0;const pairs=[];pairLists(trees.printed,trees.script,0,pairs,trees.offset);return printedLine=>{const starting=pairs.filter(pair=>pair.printedStart===printedLine);const candidates=starting.length>0?starting:pairs.filter(pair=>pair.printedStart<=printedLine&&printedLine<=pair.printedEnd);const best=candidates.reduce((deepest,pair)=>!deepest||pair.depth>deepest.depth?pair:deepest,void 0);return best&&best.scriptLine>=1?best.scriptLine:void 0}}var ISSUE_LINE_RE=/ \(line (\d+)\)/g;function withScriptLines(message,script){if(!message.includes("(line "))return message;const lineOf=validatedLineMapper(script);return message.replace(ISSUE_LINE_RE,(_match,printed)=>{const line=lineOf(Number(printed));return line===void 0?"":` (line ${line})`})}function toolFailureMessage(error,toolName){if(typeof error==="string"&&error)return error;const message=error?.message;return typeof message==="string"&&message?message:`Tool call failed: ${toolName}`}function toolFailureName(error){const name=error&&typeof error==="object"?error.name:void 0;return typeof name==="string"&&name?name.slice(0,128):"ToolError"}var ITERATION_LIMIT_PREFIX="Maximum iteration limit exceeded";var ITERATION_LIMIT_ERROR={name:"Error",message:`${ITERATION_LIMIT_PREFIX} (${MAX_ITERATIONS_PER_LOOP}). This limit prevents infinite loops.`};var PARSE_FAILURE_PREFIX="Failed to parse AgentScript code: ";var PARSE_POSITION_RE=/\((\d+):(\d+)\)$/;function parseFailureOf(message){const match=PARSE_POSITION_RE.exec(message);const line=match?Number(match[1])-1:0;if(!match||line<1)return{message};const column=Number(match[2]);return{message:`${message.slice(0,match.index)}(${line}:${column})`,location:{line,column}}}var ScriptTooLargeError=class extends Error{code="SCRIPT_TOO_LARGE";scriptLength;maxLength;constructor(scriptLength,maxLength){super(`Script length (${scriptLength} characters) exceeds maximum allowed length (${maxLength} characters). Enable sidecar to handle large data, or reduce script size.`);this.name="ScriptTooLargeError";this.scriptLength=scriptLength;this.maxLength=maxLength}};var EnclaveService=class{vmOptions;sidecarOptions;constructor(config){const all=config.getAll();this.vmOptions=all.resolvedVm;this.sidecarOptions=all.sidecar}async execute(code,environment){const logs=[];if(!this.sidecarOptions.enabled&&this.sidecarOptions.maxScriptLengthWhenDisabled!==null){const maxLength=this.sidecarOptions.maxScriptLengthWhenDisabled;if(code.length>maxLength){throw new ScriptTooLargeError(code.length,maxLength)}}const policyIssues=await findScriptPolicyIssues(code,this.vmOptions);if(policyIssues.length>0){return{success:false,error:{message:`AgentScript validation failed:
6
+ ${policyIssues.map(issue=>`${issue.code}${issue.location?` (line ${issue.location.line})`:""}: ${issue.message}`).join("\n")}`,name:"ValidationError",code:"VALIDATION_ERROR",blockedPatterns:[...new Set(policyIssues.map(issue=>issue.code))]},logs,timedOut:false,stats:{duration:0,toolCallCount:0,iterationCount:0}}}const toolFailures=[];const toolHandler=async(toolName,args)=>{try{return await environment.callTool(toolName,args)}catch(error){const code2=error?.code;toolFailures.push({toolName,name:toolFailureName(error),message:toolFailureMessage(error,toolName),...typeof code2==="string"?{code:code2}:{}});throw error}};const sidecar=this.sidecarOptions.enabled?{enabled:true,maxTotalSize:this.sidecarOptions.maxTotalSize,maxReferenceSize:this.sidecarOptions.maxReferenceSize,extractionThreshold:this.sidecarOptions.extractionThreshold,maxResolvedSize:this.sidecarOptions.maxResolvedSize,allowComposites:this.sidecarOptions.allowComposites}:void 0;const{mcpLog,mcpNotify}=environment;const globals={getTool:environment.getTool,...mcpLog?{mcpLog:(level,message,metadata)=>{mcpLog(level,message,metadata);logs.push(`[mcp:${level}] ${message}`)}}:{},...mcpNotify?{mcpNotify:(event,payload)=>{mcpNotify(event,payload);logs.push(`[notify] ${event}`)}}:{}};const{rapidEnumerationThreshold,rapidEnumerationOverrides}=this.vmOptions;const options={timeout:this.vmOptions.timeoutMs,maxToolCalls:maxToolCallsOf(this.vmOptions),maxIterations:MAX_ITERATIONS_PER_LOOP,maxSanitizeDepth:this.vmOptions.maxSanitizeDepth,maxSanitizeProperties:this.vmOptions.maxSanitizeProperties,toolHandler,validate:true,transform:true,sidecar,sanitizeStackTraces:true,allowFunctionsInGlobals:true,globals,toolNamespaces:toSandboxToolNamespaces(environment.toolNamespaces,Object.keys(globals)),doubleVm:{parentValidation:{...rapidEnumerationThreshold!==void 0&&{rapidEnumerationThreshold},...rapidEnumerationOverrides!==void 0&&{rapidEnumerationOverrides}}}};const enclave=createEnclave(options);try{const result=await enclave.run(code);return this.mapEnclaveResult(result,logs,toolFailures,code)}finally{enclave.dispose()}}mapEnclaveResult(result,logs,toolFailures=[],script=""){const stats={duration:result.stats.duration,toolCallCount:result.stats.toolCallCount,iterationCount:result.stats.iterationCount};if(result.success){return{success:true,result:result.value,logs,timedOut:false,stats}}const reportedError=result.error??{name:"Error",message:"Script execution failed"};const toolFailure=[...toolFailures].reverse().find(failure=>failure.message===reportedError.message&&failure.name===reportedError.name);const error=!toolFailure&&reportedError.message?.startsWith(ITERATION_LIMIT_PREFIX)?{...reportedError,...ITERATION_LIMIT_ERROR}:reportedError;if(error.code==="ENCLAVE_ERROR"&&error.message?.startsWith(PARSE_FAILURE_PREFIX)){const{message,location}=parseFailureOf(error.message);return{success:false,error:{message,name:"SyntaxError",code:"SYNTAX_ERROR",...location?{location}:{}},logs,timedOut:false,stats}}if(toolFailure){return{success:false,error:{message:error.message,name:error.name,...toolFailure.code?{code:toolFailure.code}:{},toolName:toolFailure.toolName},logs,timedOut:false,stats}}const timedOut=error.message?.includes("timed out")||error.code==="TIMEOUT";if(error.code==="VALIDATION_ERROR"){const issues=error.data?.issues??[];const blockedPatterns=[...new Set(issues.map(issue=>issue.code).filter(code=>!!code))];return{success:false,error:{message:withScriptLines(error.message,script),name:"ValidationError",code:error.code,...blockedPatterns.length>0?{blockedPatterns}:{}},logs,timedOut:false,stats}}return{success:false,error:{message:error.message,name:error.name,stack:error.stack,code:error.code},logs,timedOut,stats}}};EnclaveService=__decorateClass([Provider3({name:"codecall:enclave",description:"Executes AgentScript code in a secure enclave",scope:ProviderScope3.GLOBAL})],EnclaveService);function createEnclave(options){try{return new Enclave(options)}catch(error){if(!options.toolNamespaces||!(error instanceof TypeError)||!error.message.startsWith("Invalid toolNamespaces")){throw error}return new Enclave({...options,toolNamespaces:void 0})}}import{getCallSurface,Tool,ToolContext}from"@frontmcp/sdk";import{z as z2}from"@frontmcp/lazy-zod";var DEFAULT_MIN_RELEVANCE_SCORE=.1;function buildSearchToolDescription(topK){return`Find tools by splitting user request into atomic actions.
2512
7
 
2513
8
  DECOMPOSE: "delete users and send email" \u2192 queries: ["delete user", "send email"]
2514
9
  DECOMPOSE: "get order and refund" \u2192 queries: ["get order", "calculate refund"]
@@ -2525,140 +20,7 @@ INPUT:
2525
20
 
2526
21
  OUTPUT: Flat deduplicated tool list. relevanceScore: 0.5+=good, 0.7+=strong match.
2527
22
 
2528
- FLOW: search \u2192 describe \u2192 execute/invoke`;
2529
- }
2530
- var searchToolDescription = buildSearchToolDescription(codeCallPluginOptionsSchema.parse({}).topK);
2531
- var searchToolInputSchema = {
2532
- queries: z2.array(z2.string().min(2).max(256)).min(1).max(10).describe("Atomic action queries. Split complex requests into simple actions."),
2533
- appIds: z2.array(z2.string()).max(10).optional().describe("Filter by app IDs"),
2534
- excludeToolNames: z2.array(z2.string()).max(50).optional().describe("Skip already-known tool names"),
2535
- topK: z2.number().int().positive().max(50).optional().describe("Results per query (defaults to the server's CodeCall topK, 8 unless configured)"),
2536
- minRelevanceScore: z2.number().min(0).max(1).optional().default(DEFAULT_MIN_RELEVANCE_SCORE).describe(`Minimum relevance threshold (default ${DEFAULT_MIN_RELEVANCE_SCORE})`)
2537
- };
2538
- var searchToolOutputSchema = z2.object({
2539
- tools: z2.array(
2540
- z2.object({
2541
- name: z2.string().describe('Tool name (e.g., "users:list")'),
2542
- appId: z2.string().optional().describe("App ID"),
2543
- description: z2.string().describe("What this tool does"),
2544
- relevanceScore: z2.number().min(0).max(1).describe("Match score (0-1)"),
2545
- matchedQueries: z2.array(z2.string()).describe("Which queries matched this tool")
2546
- })
2547
- ).describe("Deduplicated tools sorted by relevance"),
2548
- warnings: z2.array(
2549
- z2.object({
2550
- type: z2.enum(["excluded_tool_not_found", "no_results", "low_relevance"]).describe("Warning type"),
2551
- message: z2.string().describe("Warning message"),
2552
- affectedTools: z2.array(z2.string()).optional().describe("Affected tool names")
2553
- })
2554
- ).describe("Search warnings"),
2555
- totalAvailableTools: z2.number().int().nonnegative().describe("Total tools in index")
2556
- });
2557
-
2558
- // plugins/plugin-codecall/src/tools/search.tool.ts
2559
- var SearchTool = class extends ToolContext {
2560
- async execute(input) {
2561
- const { queries, appIds, excludeToolNames = [], topK, minRelevanceScore = DEFAULT_MIN_RELEVANCE_SCORE } = input;
2562
- const searchService = this.get(ToolSearchService);
2563
- const warnings = [];
2564
- const audit = this.tryGet(AuditLoggerService);
2565
- const executionId = audit ? audit.generateExecutionId() : "";
2566
- const startedAt = Date.now();
2567
- const surface = getCallSurface();
2568
- const nonExistentExcludedTools = excludeToolNames.filter(
2569
- (toolName) => !searchService.hasTool(toolName, surface)
2570
- );
2571
- if (nonExistentExcludedTools.length > 0) {
2572
- warnings.push({
2573
- type: "excluded_tool_not_found",
2574
- message: `Excluded tools not found: ${nonExistentExcludedTools.join(", ")}`,
2575
- affectedTools: nonExistentExcludedTools
2576
- });
2577
- }
2578
- const toolMap = /* @__PURE__ */ new Map();
2579
- let lowRelevanceCount = 0;
2580
- for (const query of queries) {
2581
- const searchResults = await searchService.search(query, {
2582
- topK,
2583
- appIds,
2584
- excludeToolNames,
2585
- surface
2586
- });
2587
- for (const result of searchResults) {
2588
- if (result.relevanceScore < minRelevanceScore) {
2589
- lowRelevanceCount++;
2590
- continue;
2591
- }
2592
- const existing = toolMap.get(result.toolName);
2593
- if (existing) {
2594
- existing.matchedQueries.push(query);
2595
- existing.relevanceScore = Math.max(existing.relevanceScore, result.relevanceScore);
2596
- } else {
2597
- toolMap.set(result.toolName, {
2598
- name: result.toolName,
2599
- appId: result.appId,
2600
- description: result.description,
2601
- relevanceScore: result.relevanceScore,
2602
- matchedQueries: [query]
2603
- });
2604
- }
2605
- }
2606
- }
2607
- const tools = Array.from(toolMap.values()).sort((a, b) => b.relevanceScore - a.relevanceScore).map((tool) => ({
2608
- name: tool.name,
2609
- appId: tool.appId,
2610
- description: tool.description,
2611
- relevanceScore: tool.relevanceScore,
2612
- matchedQueries: tool.matchedQueries
2613
- }));
2614
- if (tools.length === 0) {
2615
- warnings.push({
2616
- type: "no_results",
2617
- message: `No tools found for queries: ${queries.join(", ")}${appIds?.length ? ` in apps: ${appIds.join(", ")}` : ""}`
2618
- });
2619
- }
2620
- if (lowRelevanceCount > 0 && tools.length > 0) {
2621
- warnings.push({
2622
- type: "low_relevance",
2623
- message: `${lowRelevanceCount} result(s) filtered due to relevance below ${minRelevanceScore}`
2624
- });
2625
- }
2626
- audit?.logSearch(executionId, queries.join(" "), tools.length, Date.now() - startedAt);
2627
- return {
2628
- tools,
2629
- warnings,
2630
- totalAvailableTools: searchService.getTotalCount(surface)
2631
- };
2632
- }
2633
- };
2634
- SearchTool = __decorateClass([
2635
- Tool({
2636
- name: "codecall:search",
2637
- cache: {
2638
- ttl: 60,
2639
- // 1 minute
2640
- slideWindow: false
2641
- },
2642
- codecall: {
2643
- enabledInCodeCall: false,
2644
- visibleInListTools: true
2645
- },
2646
- description: searchToolDescription,
2647
- inputSchema: searchToolInputSchema,
2648
- outputSchema: searchToolOutputSchema,
2649
- annotations: {
2650
- readOnlyHint: true,
2651
- openWorldHint: true
2652
- }
2653
- })
2654
- ], SearchTool);
2655
-
2656
- // plugins/plugin-codecall/src/tools/search-skills.tool.ts
2657
- import { filterServableSkills, Tool as Tool2, ToolContext as ToolContext2 } from "@frontmcp/sdk";
2658
-
2659
- // plugins/plugin-codecall/src/tools/search-skills.schema.ts
2660
- import { z as z3 } from "@frontmcp/lazy-zod";
2661
- var searchSkillsToolDescription = `Search for EXECUTABLE skills. Each result returns the skill's description, tags, and the openapi operation IDs it can call from within AgentScript.
23
+ FLOW: search \u2192 describe \u2192 execute/invoke`}var searchToolDescription=buildSearchToolDescription(codeCallPluginOptionsSchema.parse({}).topK);var searchToolInputSchema={queries:z2.array(z2.string().min(2).max(256)).min(1).max(10).describe("Atomic action queries. Split complex requests into simple actions."),appIds:z2.array(z2.string()).max(10).optional().describe("Filter by app IDs"),excludeToolNames:z2.array(z2.string()).max(50).optional().describe("Skip already-known tool names"),topK:z2.number().int().positive().max(50).optional().describe("Results per query (defaults to the server's CodeCall topK, 8 unless configured)"),minRelevanceScore:z2.number().min(0).max(1).optional().default(DEFAULT_MIN_RELEVANCE_SCORE).describe(`Minimum relevance threshold (default ${DEFAULT_MIN_RELEVANCE_SCORE})`)};var searchToolOutputSchema=z2.object({tools:z2.array(z2.object({name:z2.string().describe('Tool name (e.g., "users:list")'),appId:z2.string().optional().describe("App ID"),description:z2.string().describe("What this tool does"),relevanceScore:z2.number().min(0).max(1).describe("Match score (0-1)"),matchedQueries:z2.array(z2.string()).describe("Which queries matched this tool")})).describe("Deduplicated tools sorted by relevance"),warnings:z2.array(z2.object({type:z2.enum(["excluded_tool_not_found","no_results","low_relevance"]).describe("Warning type"),message:z2.string().describe("Warning message"),affectedTools:z2.array(z2.string()).optional().describe("Affected tool names")})).describe("Search warnings"),totalAvailableTools:z2.number().int().nonnegative().describe("Total tools in index")});var SearchTool=class extends ToolContext{async execute(input){const{queries,appIds,excludeToolNames=[],topK,minRelevanceScore=DEFAULT_MIN_RELEVANCE_SCORE}=input;const searchService=this.get(ToolSearchService);const warnings=[];const audit=this.tryGet(AuditLoggerService);const executionId=audit?audit.generateExecutionId():"";const startedAt=Date.now();const surface=getCallSurface();const nonExistentExcludedTools=excludeToolNames.filter(toolName=>!searchService.hasTool(toolName,surface));if(nonExistentExcludedTools.length>0){warnings.push({type:"excluded_tool_not_found",message:`Excluded tools not found: ${nonExistentExcludedTools.join(", ")}`,affectedTools:nonExistentExcludedTools})}const toolMap=new Map;let lowRelevanceCount=0;for(const query of queries){const searchResults=await searchService.search(query,{topK,appIds,excludeToolNames,surface});for(const result of searchResults){if(result.relevanceScore<minRelevanceScore){lowRelevanceCount++;continue}const existing=toolMap.get(result.toolName);if(existing){existing.matchedQueries.push(query);existing.relevanceScore=Math.max(existing.relevanceScore,result.relevanceScore)}else{toolMap.set(result.toolName,{name:result.toolName,appId:result.appId,description:result.description,relevanceScore:result.relevanceScore,matchedQueries:[query]})}}}const tools=Array.from(toolMap.values()).sort((a,b)=>b.relevanceScore-a.relevanceScore).map(tool=>({name:tool.name,appId:tool.appId,description:tool.description,relevanceScore:tool.relevanceScore,matchedQueries:tool.matchedQueries}));if(tools.length===0){warnings.push({type:"no_results",message:`No tools found for queries: ${queries.join(", ")}${appIds?.length?` in apps: ${appIds.join(", ")}`:""}`})}if(lowRelevanceCount>0&&tools.length>0){warnings.push({type:"low_relevance",message:`${lowRelevanceCount} result(s) filtered due to relevance below ${minRelevanceScore}`})}audit?.logSearch(executionId,queries.join(" "),tools.length,Date.now()-startedAt);return{tools,warnings,totalAvailableTools:searchService.getTotalCount(surface)}}};SearchTool=__decorateClass([Tool({name:"codecall:search",cache:{ttl:60,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:searchToolDescription,inputSchema:searchToolInputSchema,outputSchema:searchToolOutputSchema,annotations:{readOnlyHint:true,openWorldHint:true}})],SearchTool);import{filterServableSkills,Tool as Tool2,ToolContext as ToolContext2}from"@frontmcp/sdk";import{z as z3}from"@frontmcp/lazy-zod";var searchSkillsToolDescription=`Search for EXECUTABLE skills. Each result returns the skill's description, tags, and the openapi operation IDs it can call from within AgentScript.
2662
24
 
2663
25
  DECOMPOSE complex requests into atomic queries. AVOID re-searching: use excludeSkillNames.
2664
26
 
@@ -2671,146 +33,7 @@ INPUT:
2671
33
 
2672
34
  OUTPUT: Flat deduplicated executable skill list. Each entry includes the operationIds the skill is allowed to call (via the markdown harvester). The agent can use those operationIds directly in execute() AgentScript via the generated namespaces (e.g. acme.getOrder({...})).
2673
35
 
2674
- FLOW: searchSkills \u2192 describe \u2192 execute`;
2675
- var searchSkillsToolInputSchema = {
2676
- queries: z3.array(z3.string().min(2).max(256)).min(1).max(10).describe("Atomic skill queries. Split complex requests into simple actions."),
2677
- tags: z3.array(z3.string().min(1).max(64)).max(16).optional().describe("Filter to skills with any of these tags"),
2678
- excludeSkillNames: z3.array(z3.string()).max(50).optional().describe("Skip already-known skill names"),
2679
- topK: z3.number().int().positive().max(50).optional().default(5).describe("Results per query (default 5)"),
2680
- minRelevanceScore: z3.number().min(0).max(1).optional().default(0.1).describe("Minimum relevance threshold (default 0.1)")
2681
- };
2682
- var referencedOperationSchema = z3.object({
2683
- spec: z3.string().describe('OpenAPI spec id (e.g. "acme")'),
2684
- operationId: z3.string().describe('OpenAPI operation id (e.g. "getOrder")')
2685
- });
2686
- var skillSearchHitSchema = z3.object({
2687
- name: z3.string().describe("Skill name"),
2688
- description: z3.string().describe("Short description of what the skill does"),
2689
- tags: z3.array(z3.string()).describe("Tags carried by the skill"),
2690
- /**
2691
- * OpenAPI operations the skill is allowed to call. Inlined so the agent
2692
- * can author AgentScript from a single search response.
2693
- */
2694
- operations: z3.array(referencedOperationSchema).describe("OpenAPI operations the skill can call"),
2695
- /** Decorator-declared tools (for skills built the legacy way). */
2696
- tools: z3.array(z3.string()).describe("Tool names the skill declares (if any)"),
2697
- relevanceScore: z3.number().min(0).max(1).describe("Match score (0-1)"),
2698
- matchedQueries: z3.array(z3.string()).describe("Which queries matched this skill"),
2699
- source: z3.enum(["local", "external"]).describe("Where the skill was loaded from")
2700
- });
2701
- var searchSkillsToolOutputSchema = z3.object({
2702
- skills: z3.array(skillSearchHitSchema).describe("Deduplicated executable skills, sorted by relevance"),
2703
- warnings: z3.array(
2704
- z3.object({
2705
- type: z3.enum(["no_results", "low_relevance", "excluded_skill_not_found"]).describe("Warning type"),
2706
- message: z3.string().describe("Warning message"),
2707
- affectedSkills: z3.array(z3.string()).optional().describe("Affected skill names")
2708
- })
2709
- ).describe("Search warnings"),
2710
- totalExecutableSkills: z3.number().int().nonnegative().describe("Total executable skills available")
2711
- });
2712
-
2713
- // plugins/plugin-codecall/src/tools/search-skills.tool.ts
2714
- var SearchSkillsTool = class extends ToolContext2 {
2715
- async execute(input) {
2716
- const { queries, tags, excludeSkillNames = [], topK = 5, minRelevanceScore = 0.1 } = input;
2717
- const skillRegistry = this.scope.skills;
2718
- const executableSkills = await filterServableSkills(this.scope, skillRegistry.getExecutableSkills());
2719
- const executableSet = new Set(executableSkills.map((s) => s.name));
2720
- const totalExecutableSkills = executableSkills.length;
2721
- const warnings = [];
2722
- const nonExistentExcluded = excludeSkillNames.filter((n) => !executableSet.has(n));
2723
- if (nonExistentExcluded.length > 0) {
2724
- warnings.push({
2725
- type: "excluded_skill_not_found",
2726
- message: `Excluded skills not found: ${nonExistentExcluded.join(", ")}`,
2727
- affectedSkills: nonExistentExcluded
2728
- });
2729
- }
2730
- const matches = /* @__PURE__ */ new Map();
2731
- let lowRelevanceCount = 0;
2732
- const excludedSet = new Set(excludeSkillNames);
2733
- const perQueryResults = await Promise.all(
2734
- queries.map(
2735
- (query) => skillRegistry.search(query, { topK, tags, minScore: minRelevanceScore }).then((results) => ({ query, results }))
2736
- )
2737
- );
2738
- for (const { query, results } of perQueryResults) {
2739
- for (const result of results) {
2740
- const name = result.metadata.name;
2741
- if (!executableSet.has(name)) continue;
2742
- if (excludedSet.has(name)) continue;
2743
- if (result.score < minRelevanceScore) {
2744
- lowRelevanceCount++;
2745
- continue;
2746
- }
2747
- const existing = matches.get(name);
2748
- if (existing) {
2749
- existing.matchedQueries.push(query);
2750
- existing.relevanceScore = Math.max(existing.relevanceScore, result.score);
2751
- } else {
2752
- const ops = result.metadata.referencedOperations ?? [];
2753
- const toolNames = (result.metadata.tools ?? []).map((t) => {
2754
- if (typeof t === "string") return t;
2755
- if (typeof t === "object" && t !== null && "name" in t) return t.name;
2756
- return null;
2757
- }).filter((n) => typeof n === "string");
2758
- matches.set(name, {
2759
- name,
2760
- description: result.metadata.description,
2761
- tags: result.metadata.tags ?? [],
2762
- operations: ops.map((op) => ({ spec: op.spec, operationId: op.operationId })),
2763
- tools: toolNames,
2764
- relevanceScore: result.score,
2765
- matchedQueries: [query],
2766
- source: result.source
2767
- });
2768
- }
2769
- }
2770
- }
2771
- const skills = Array.from(matches.values()).sort((a, b) => b.relevanceScore - a.relevanceScore);
2772
- if (skills.length === 0) {
2773
- warnings.push({
2774
- type: "no_results",
2775
- message: `No executable skills found for queries: ${queries.join(", ")}${tags?.length ? ` with tags: ${tags.join(", ")}` : ""}`
2776
- });
2777
- }
2778
- if (lowRelevanceCount > 0 && skills.length > 0) {
2779
- warnings.push({
2780
- type: "low_relevance",
2781
- message: `${lowRelevanceCount} result(s) filtered due to relevance below ${minRelevanceScore}`
2782
- });
2783
- }
2784
- return { skills, warnings, totalExecutableSkills };
2785
- }
2786
- };
2787
- SearchSkillsTool = __decorateClass([
2788
- Tool2({
2789
- name: "codecall:searchSkills",
2790
- cache: {
2791
- ttl: 60,
2792
- slideWindow: false
2793
- },
2794
- codecall: {
2795
- enabledInCodeCall: false,
2796
- visibleInListTools: true
2797
- },
2798
- description: searchSkillsToolDescription,
2799
- inputSchema: searchSkillsToolInputSchema,
2800
- outputSchema: searchSkillsToolOutputSchema,
2801
- annotations: {
2802
- readOnlyHint: true,
2803
- openWorldHint: true
2804
- }
2805
- })
2806
- ], SearchSkillsTool);
2807
-
2808
- // plugins/plugin-codecall/src/tools/search-knowledge.tool.ts
2809
- import { filterServableSkills as filterServableSkills2, Tool as Tool3, ToolContext as ToolContext3 } from "@frontmcp/sdk";
2810
-
2811
- // plugins/plugin-codecall/src/tools/search-knowledge.schema.ts
2812
- import { z as z4 } from "@frontmcp/lazy-zod";
2813
- var searchKnowledgeToolDescription = `Search for KNOWLEDGE-ONLY skills \u2014 domain context the agent should read before deciding what to do. These skills have no tools and no openapi operation refs; they are pure prose / references / examples.
36
+ FLOW: searchSkills \u2192 describe \u2192 execute`;var searchSkillsToolInputSchema={queries:z3.array(z3.string().min(2).max(256)).min(1).max(10).describe("Atomic skill queries. Split complex requests into simple actions."),tags:z3.array(z3.string().min(1).max(64)).max(16).optional().describe("Filter to skills with any of these tags"),excludeSkillNames:z3.array(z3.string()).max(50).optional().describe("Skip already-known skill names"),topK:z3.number().int().positive().max(50).optional().default(5).describe("Results per query (default 5)"),minRelevanceScore:z3.number().min(0).max(1).optional().default(.1).describe("Minimum relevance threshold (default 0.1)")};var referencedOperationSchema=z3.object({spec:z3.string().describe('OpenAPI spec id (e.g. "acme")'),operationId:z3.string().describe('OpenAPI operation id (e.g. "getOrder")')});var skillSearchHitSchema=z3.object({name:z3.string().describe("Skill name"),description:z3.string().describe("Short description of what the skill does"),tags:z3.array(z3.string()).describe("Tags carried by the skill"),operations:z3.array(referencedOperationSchema).describe("OpenAPI operations the skill can call"),tools:z3.array(z3.string()).describe("Tool names the skill declares (if any)"),relevanceScore:z3.number().min(0).max(1).describe("Match score (0-1)"),matchedQueries:z3.array(z3.string()).describe("Which queries matched this skill"),source:z3.enum(["local","external"]).describe("Where the skill was loaded from")});var searchSkillsToolOutputSchema=z3.object({skills:z3.array(skillSearchHitSchema).describe("Deduplicated executable skills, sorted by relevance"),warnings:z3.array(z3.object({type:z3.enum(["no_results","low_relevance","excluded_skill_not_found"]).describe("Warning type"),message:z3.string().describe("Warning message"),affectedSkills:z3.array(z3.string()).optional().describe("Affected skill names")})).describe("Search warnings"),totalExecutableSkills:z3.number().int().nonnegative().describe("Total executable skills available")});var SearchSkillsTool=class extends ToolContext2{async execute(input){const{queries,tags,excludeSkillNames=[],topK=5,minRelevanceScore=.1}=input;const skillRegistry=this.scope.skills;const executableSkills=await filterServableSkills(this.scope,skillRegistry.getExecutableSkills());const executableSet=new Set(executableSkills.map(s=>s.name));const totalExecutableSkills=executableSkills.length;const warnings=[];const nonExistentExcluded=excludeSkillNames.filter(n=>!executableSet.has(n));if(nonExistentExcluded.length>0){warnings.push({type:"excluded_skill_not_found",message:`Excluded skills not found: ${nonExistentExcluded.join(", ")}`,affectedSkills:nonExistentExcluded})}const matches=new Map;let lowRelevanceCount=0;const excludedSet=new Set(excludeSkillNames);const perQueryResults=await Promise.all(queries.map(query=>skillRegistry.search(query,{topK,tags,minScore:minRelevanceScore}).then(results=>({query,results}))));for(const{query,results}of perQueryResults){for(const result of results){const name=result.metadata.name;if(!executableSet.has(name))continue;if(excludedSet.has(name))continue;if(result.score<minRelevanceScore){lowRelevanceCount++;continue}const existing=matches.get(name);if(existing){existing.matchedQueries.push(query);existing.relevanceScore=Math.max(existing.relevanceScore,result.score)}else{const ops=result.metadata.referencedOperations??[];const toolNames=(result.metadata.tools??[]).map(t=>{if(typeof t==="string")return t;if(typeof t==="object"&&t!==null&&"name"in t)return t.name;return null}).filter(n=>typeof n==="string");matches.set(name,{name,description:result.metadata.description,tags:result.metadata.tags??[],operations:ops.map(op=>({spec:op.spec,operationId:op.operationId})),tools:toolNames,relevanceScore:result.score,matchedQueries:[query],source:result.source})}}}const skills=Array.from(matches.values()).sort((a,b)=>b.relevanceScore-a.relevanceScore);if(skills.length===0){warnings.push({type:"no_results",message:`No executable skills found for queries: ${queries.join(", ")}${tags?.length?` with tags: ${tags.join(", ")}`:""}`})}if(lowRelevanceCount>0&&skills.length>0){warnings.push({type:"low_relevance",message:`${lowRelevanceCount} result(s) filtered due to relevance below ${minRelevanceScore}`})}return{skills,warnings,totalExecutableSkills}}};SearchSkillsTool=__decorateClass([Tool2({name:"codecall:searchSkills",cache:{ttl:60,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:searchSkillsToolDescription,inputSchema:searchSkillsToolInputSchema,outputSchema:searchSkillsToolOutputSchema,annotations:{readOnlyHint:true,openWorldHint:true}})],SearchSkillsTool);import{filterServableSkills as filterServableSkills2,Tool as Tool3,ToolContext as ToolContext3}from"@frontmcp/sdk";import{z as z4}from"@frontmcp/lazy-zod";var searchKnowledgeToolDescription=`Search for KNOWLEDGE-ONLY skills \u2014 domain context the agent should read before deciding what to do. These skills have no tools and no openapi operation refs; they are pure prose / references / examples.
2814
37
 
2815
38
  USE WHEN: the agent needs background to interpret a request, validate eligibility, or recall a procedure that isn't yet executable.
2816
39
 
@@ -2823,781 +46,36 @@ INPUT:
2823
46
 
2824
47
  OUTPUT: Deduplicated knowledge skill list with description + tags. To read the body, follow up with describe(skillName) or the skill:// resource URI.
2825
48
 
2826
- FLOW: searchKnowledge \u2192 describe (for body) \u2192 continue with searchSkills`;
2827
- var searchKnowledgeToolInputSchema = {
2828
- queries: z4.array(z4.string().min(2).max(256)).min(1).max(10).describe("Atomic context queries."),
2829
- tags: z4.array(z4.string().min(1).max(64)).max(16).optional().describe("Filter to skills with any of these tags"),
2830
- excludeSkillNames: z4.array(z4.string()).max(50).optional().describe("Skip already-loaded knowledge skill names"),
2831
- topK: z4.number().int().positive().max(50).optional().default(5).describe("Results per query (default 5)"),
2832
- minRelevanceScore: z4.number().min(0).max(1).optional().default(0.1).describe("Minimum relevance threshold (default 0.1)")
2833
- };
2834
- var knowledgeHitSchema = z4.object({
2835
- name: z4.string().describe("Skill name"),
2836
- description: z4.string().describe("Short description of what the knowledge covers"),
2837
- tags: z4.array(z4.string()).describe("Tags carried by the skill"),
2838
- relevanceScore: z4.number().min(0).max(1).describe("Match score (0-1)"),
2839
- matchedQueries: z4.array(z4.string()).describe("Which queries matched this knowledge"),
2840
- source: z4.enum(["local", "external"]).describe("Where the skill was loaded from")
2841
- });
2842
- var searchKnowledgeToolOutputSchema = z4.object({
2843
- knowledge: z4.array(knowledgeHitSchema).describe("Deduplicated knowledge skills, sorted by relevance"),
2844
- warnings: z4.array(
2845
- z4.object({
2846
- type: z4.enum(["no_results", "low_relevance", "excluded_skill_not_found"]).describe("Warning type"),
2847
- message: z4.string().describe("Warning message"),
2848
- affectedSkills: z4.array(z4.string()).optional().describe("Affected skill names")
2849
- })
2850
- ).describe("Search warnings"),
2851
- totalKnowledgeSkills: z4.number().int().nonnegative().describe("Total knowledge-only skills available")
2852
- });
2853
-
2854
- // plugins/plugin-codecall/src/tools/search-knowledge.tool.ts
2855
- var SearchKnowledgeTool = class extends ToolContext3 {
2856
- async execute(input) {
2857
- const { queries, tags, excludeSkillNames = [], topK = 5, minRelevanceScore = 0.1 } = input;
2858
- const skillRegistry = this.scope.skills;
2859
- const knowledgeSkills = await filterServableSkills2(this.scope, skillRegistry.getKnowledgeOnlySkills());
2860
- const knowledgeSet = new Set(knowledgeSkills.map((s) => s.name));
2861
- const totalKnowledgeSkills = knowledgeSkills.length;
2862
- const warnings = [];
2863
- const nonExistentExcluded = excludeSkillNames.filter((n) => !knowledgeSet.has(n));
2864
- if (nonExistentExcluded.length > 0) {
2865
- warnings.push({
2866
- type: "excluded_skill_not_found",
2867
- message: `Excluded knowledge skills not found: ${nonExistentExcluded.join(", ")}`,
2868
- affectedSkills: nonExistentExcluded
2869
- });
2870
- }
2871
- const matches = /* @__PURE__ */ new Map();
2872
- let lowRelevanceCount = 0;
2873
- const excludedSet = new Set(excludeSkillNames);
2874
- const perQueryResults = await Promise.all(
2875
- queries.map(
2876
- (query) => skillRegistry.search(query, { topK, tags, minScore: minRelevanceScore }).then((results) => ({ query, results }))
2877
- )
2878
- );
2879
- for (const { query, results } of perQueryResults) {
2880
- for (const result of results) {
2881
- const name = result.metadata.name;
2882
- if (!knowledgeSet.has(name)) continue;
2883
- if (excludedSet.has(name)) continue;
2884
- if (result.score < minRelevanceScore) {
2885
- lowRelevanceCount++;
2886
- continue;
2887
- }
2888
- const existing = matches.get(name);
2889
- if (existing) {
2890
- existing.matchedQueries.push(query);
2891
- existing.relevanceScore = Math.max(existing.relevanceScore, result.score);
2892
- } else {
2893
- matches.set(name, {
2894
- name,
2895
- description: result.metadata.description,
2896
- tags: result.metadata.tags ?? [],
2897
- relevanceScore: result.score,
2898
- matchedQueries: [query],
2899
- source: result.source
2900
- });
2901
- }
2902
- }
2903
- }
2904
- const knowledge = Array.from(matches.values()).sort((a, b) => b.relevanceScore - a.relevanceScore);
2905
- if (knowledge.length === 0) {
2906
- warnings.push({
2907
- type: "no_results",
2908
- message: `No knowledge skills found for queries: ${queries.join(", ")}${tags?.length ? ` with tags: ${tags.join(", ")}` : ""}`
2909
- });
2910
- }
2911
- if (lowRelevanceCount > 0 && knowledge.length > 0) {
2912
- warnings.push({
2913
- type: "low_relevance",
2914
- message: `${lowRelevanceCount} result(s) filtered due to relevance below ${minRelevanceScore}`
2915
- });
2916
- }
2917
- return { knowledge, warnings, totalKnowledgeSkills };
2918
- }
2919
- };
2920
- SearchKnowledgeTool = __decorateClass([
2921
- Tool3({
2922
- name: "codecall:searchKnowledge",
2923
- cache: {
2924
- ttl: 60,
2925
- slideWindow: false
2926
- },
2927
- codecall: {
2928
- enabledInCodeCall: false,
2929
- visibleInListTools: true
2930
- },
2931
- description: searchKnowledgeToolDescription,
2932
- inputSchema: searchKnowledgeToolInputSchema,
2933
- outputSchema: searchKnowledgeToolOutputSchema,
2934
- annotations: {
2935
- readOnlyHint: true,
2936
- openWorldHint: true
2937
- }
2938
- })
2939
- ], SearchKnowledgeTool);
2940
-
2941
- // plugins/plugin-codecall/src/tools/describe.tool.ts
2942
- import { toJSONSchema, z as z6, ZodType } from "@frontmcp/lazy-zod";
2943
- import { getCallSurface as getCallSurface2, InvalidInputError, Tool as Tool4, ToolContext as ToolContext4 } from "@frontmcp/sdk";
2944
-
2945
- // plugins/plugin-codecall/src/utils/describe.utils.ts
2946
- var INTENT_PATTERNS = {
2947
- create: /^(create|add|new|insert|make|append|register|generate|produce|build|construct|provision|instantiate|define|compose|draft)/i,
2948
- delete: /^(delete|remove|destroy|drop|erase|clear|purge|discard|eliminate|unbind|unregister)/i,
2949
- get: /^(get|fetch|retrieve|read|obtain|load|pull|access|grab|receive)/i,
2950
- update: /^(update|edit|modify|change|patch|set|alter|revise|adjust|amend|correct|fix|refresh|sync|upgrade|downgrade)/i,
2951
- list: /^(list|all|index|enumerate|show|display|view|browse|scan|inventory)/i,
2952
- search: /^(search|find|query|lookup|locate|discover|explore|seek|match|filter)/i
2953
- };
2954
- function detectToolIntent(toolName, description) {
2955
- const parts = toolName.split(":");
2956
- const actionPart = parts.length > 1 ? parts[parts.length - 1] : toolName;
2957
- for (const [intent, pattern] of Object.entries(INTENT_PATTERNS)) {
2958
- if (pattern.test(actionPart)) {
2959
- return intent;
2960
- }
2961
- }
2962
- if (description) {
2963
- const descLower = description.toLowerCase();
2964
- if (/creates?\s|adding\s|inserts?/i.test(descLower)) return "create";
2965
- if (/deletes?\s|removes?\s|destroys?/i.test(descLower)) return "delete";
2966
- if (/gets?\s|fetche?s?\s|retrieves?/i.test(descLower)) return "get";
2967
- if (/updates?\s|modif(?:y|ies)\s|edits?/i.test(descLower)) return "update";
2968
- if (/lists?\s|shows?\s|displays?/i.test(descLower)) return "list";
2969
- if (/search(?:es)?\s|find(?:s)?\s|quer(?:y|ies)/i.test(descLower)) return "search";
2970
- }
2971
- return "unknown";
2972
- }
2973
- function generateBasicExample(toolName, inputSchema) {
2974
- const params = generateSampleParams(inputSchema);
2975
- const paramsStr = params ? JSON.stringify(params, null, 2) : "{}";
2976
- return {
2977
- description: `Basic usage of ${toolName}`,
2978
- code: `const result = await callTool('${toolName}', ${paramsStr});
2979
- return result;`
2980
- };
2981
- }
2982
- function generateSampleParams(schema) {
2983
- if (!schema || schema.type !== "object" || !schema.properties) {
2984
- return null;
2985
- }
2986
- const params = {};
2987
- const required = new Set(schema.required || []);
2988
- for (const [key, propSchema] of Object.entries(schema.properties)) {
2989
- if (typeof propSchema === "boolean") continue;
2990
- if (!required.has(key)) continue;
2991
- params[key] = getSampleValue(propSchema, key);
2992
- }
2993
- return Object.keys(params).length > 0 ? params : null;
2994
- }
2995
- function fitString(schema, value) {
2996
- let fitted = value;
2997
- if (schema.maxLength !== void 0 && fitted.length > schema.maxLength) {
2998
- fitted = fitted.slice(0, Math.max(0, schema.maxLength));
2999
- }
3000
- if (schema.minLength !== void 0 && fitted.length < schema.minLength) {
3001
- fitted = fitted.padEnd(schema.minLength, "x");
3002
- }
3003
- return fitted;
3004
- }
3005
- function isFreeTextString(schema) {
3006
- return schema?.type === "string" && schema.enum === void 0 && schema.const === void 0 && schema.default === void 0 && schema.pattern === void 0 && schema.format === void 0;
3007
- }
3008
- function acceptsNumber(schema, value) {
3009
- if (schema.const !== void 0) return schema.const === value;
3010
- if (schema.enum !== void 0) return schema.enum.includes(value);
3011
- if (schema.minimum !== void 0 && value < schema.minimum) return false;
3012
- if (schema.maximum !== void 0 && value > schema.maximum) return false;
3013
- return true;
3014
- }
3015
- function pickNumber(schema, preferred) {
3016
- const accepted = preferred.find((value) => acceptsNumber(schema, value));
3017
- if (accepted !== void 0) return accepted;
3018
- const named = [schema.const, schema.enum?.[0], schema.minimum, schema.maximum].find(
3019
- (value) => typeof value === "number" && acceptsNumber(schema, value)
3020
- );
3021
- return named;
3022
- }
3023
- function formatInlineArgs(args) {
3024
- const entries = Object.entries(args).map(([key, value]) => {
3025
- const name = /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key);
3026
- const plain = typeof value === "string" && [...value].every((ch) => ch !== "'" && ch !== "\\" && ch >= " ");
3027
- const literal = plain ? `'${value}'` : JSON.stringify(value);
3028
- return `${name}: ${literal}`;
3029
- });
3030
- return entries.length > 0 ? `{ ${entries.join(", ")} }` : "{}";
3031
- }
3032
- function getSampleValue(schema, key) {
3033
- if (schema.default !== void 0) {
3034
- return schema.default;
3035
- }
3036
- if (schema.enum && schema.enum.length > 0) {
3037
- return schema.enum[0];
3038
- }
3039
- if (schema.const !== void 0) {
3040
- return schema.const;
3041
- }
3042
- const type = Array.isArray(schema.type) ? schema.type[0] : schema.type;
3043
- switch (type) {
3044
- case "string":
3045
- if (key.toLowerCase().includes("id")) return fitString(schema, "abc123");
3046
- if (key.toLowerCase().includes("email")) return fitString(schema, "user@example.com");
3047
- if (key.toLowerCase().includes("name")) return fitString(schema, "Example");
3048
- if (key.toLowerCase().includes("url")) return fitString(schema, "https://example.com");
3049
- return fitString(schema, "string");
3050
- case "number":
3051
- case "integer":
3052
- if (key.toLowerCase().includes("limit")) return 10;
3053
- if (key.toLowerCase().includes("offset")) return 0;
3054
- if (key.toLowerCase().includes("page")) return 1;
3055
- return 0;
3056
- case "boolean":
3057
- return true;
3058
- case "array":
3059
- return [];
3060
- case "object":
3061
- return {};
3062
- default:
3063
- return null;
3064
- }
3065
- }
3066
- var PAGINATION_PROPERTIES = ["limit", "offset", "page", "pagesize", "cursor"];
3067
- function isPaginationProperty(name) {
3068
- return PAGINATION_PROPERTIES.includes(name.toLowerCase());
3069
- }
3070
- function hasPaginationParams(schema) {
3071
- if (!schema || schema.type !== "object" || !schema.properties) {
3072
- return false;
3073
- }
3074
- return Object.keys(schema.properties).some(isPaginationProperty);
3075
- }
3076
- function inputProperties(schema) {
3077
- if (!schema || schema.type !== "object" || !schema.properties) {
3078
- return {};
3079
- }
3080
- const properties = {};
3081
- for (const [key, propSchema] of Object.entries(schema.properties)) {
3082
- if (typeof propSchema !== "boolean") properties[key] = propSchema;
3083
- }
3084
- return properties;
3085
- }
3086
- function buildExampleArgs(schema, keys, values = {}) {
3087
- const properties = inputProperties(schema);
3088
- const args = {};
3089
- for (const key of [...keys, ...schema?.required ?? []]) {
3090
- const propSchema = properties[key];
3091
- if (!propSchema || key in args) continue;
3092
- args[key] = key in values ? values[key] : getSampleValue(propSchema, key);
3093
- }
3094
- return args;
3095
- }
3096
- function formatExampleArgs(args) {
3097
- return Object.keys(args).length > 0 ? JSON.stringify(args, null, 2) : "{}";
3098
- }
3099
- function getFilterProperties(schema) {
3100
- if (!schema || schema.type !== "object" || !schema.properties) {
3101
- return [];
3102
- }
3103
- return Object.keys(schema.properties).filter(
3104
- (p) => p.toLowerCase().includes("filter") || p.toLowerCase().includes("query") || p.toLowerCase().includes("search") || p.toLowerCase() === "status" || p.toLowerCase() === "type" || p.toLowerCase() === "role"
3105
- );
3106
- }
3107
- function generatePaginationExample(toolName, inputSchema) {
3108
- const description = `Pagination example for ${toolName}`;
3109
- const props = Object.keys(inputProperties(inputSchema));
3110
- const limitKey = props.find((p) => p.toLowerCase() === "limit");
3111
- const offsetKey = props.find((p) => p.toLowerCase() === "offset");
3112
- if (limitKey && offsetKey) {
3113
- const properties = inputProperties(inputSchema);
3114
- const limit = pickNumber(properties[limitKey], [10]);
3115
- const firstOffset = pickNumber(properties[offsetKey], [0]);
3116
- const values = {};
3117
- if (limit !== void 0) values[limitKey] = limit;
3118
- if (firstOffset !== void 0) values[offsetKey] = firstOffset;
3119
- const firstPage = buildExampleArgs(inputSchema, [limitKey, offsetKey], values);
3120
- const nextOffset = [limit ?? 10, 10, 20, ...properties[offsetKey].enum ?? []].find(
3121
- (value) => typeof value === "number" && value !== firstPage[offsetKey] && acceptsNumber(properties[offsetKey], value)
3122
- );
3123
- if (nextOffset !== void 0) {
3124
- const secondPage = { ...firstPage, [offsetKey]: nextOffset };
3125
- return {
3126
- description,
3127
- code: `// Fetch first page
49
+ FLOW: searchKnowledge \u2192 describe (for body) \u2192 continue with searchSkills`;var searchKnowledgeToolInputSchema={queries:z4.array(z4.string().min(2).max(256)).min(1).max(10).describe("Atomic context queries."),tags:z4.array(z4.string().min(1).max(64)).max(16).optional().describe("Filter to skills with any of these tags"),excludeSkillNames:z4.array(z4.string()).max(50).optional().describe("Skip already-loaded knowledge skill names"),topK:z4.number().int().positive().max(50).optional().default(5).describe("Results per query (default 5)"),minRelevanceScore:z4.number().min(0).max(1).optional().default(.1).describe("Minimum relevance threshold (default 0.1)")};var knowledgeHitSchema=z4.object({name:z4.string().describe("Skill name"),description:z4.string().describe("Short description of what the knowledge covers"),tags:z4.array(z4.string()).describe("Tags carried by the skill"),relevanceScore:z4.number().min(0).max(1).describe("Match score (0-1)"),matchedQueries:z4.array(z4.string()).describe("Which queries matched this knowledge"),source:z4.enum(["local","external"]).describe("Where the skill was loaded from")});var searchKnowledgeToolOutputSchema=z4.object({knowledge:z4.array(knowledgeHitSchema).describe("Deduplicated knowledge skills, sorted by relevance"),warnings:z4.array(z4.object({type:z4.enum(["no_results","low_relevance","excluded_skill_not_found"]).describe("Warning type"),message:z4.string().describe("Warning message"),affectedSkills:z4.array(z4.string()).optional().describe("Affected skill names")})).describe("Search warnings"),totalKnowledgeSkills:z4.number().int().nonnegative().describe("Total knowledge-only skills available")});var SearchKnowledgeTool=class extends ToolContext3{async execute(input){const{queries,tags,excludeSkillNames=[],topK=5,minRelevanceScore=.1}=input;const skillRegistry=this.scope.skills;const knowledgeSkills=await filterServableSkills2(this.scope,skillRegistry.getKnowledgeOnlySkills());const knowledgeSet=new Set(knowledgeSkills.map(s=>s.name));const totalKnowledgeSkills=knowledgeSkills.length;const warnings=[];const nonExistentExcluded=excludeSkillNames.filter(n=>!knowledgeSet.has(n));if(nonExistentExcluded.length>0){warnings.push({type:"excluded_skill_not_found",message:`Excluded knowledge skills not found: ${nonExistentExcluded.join(", ")}`,affectedSkills:nonExistentExcluded})}const matches=new Map;let lowRelevanceCount=0;const excludedSet=new Set(excludeSkillNames);const perQueryResults=await Promise.all(queries.map(query=>skillRegistry.search(query,{topK,tags,minScore:minRelevanceScore}).then(results=>({query,results}))));for(const{query,results}of perQueryResults){for(const result of results){const name=result.metadata.name;if(!knowledgeSet.has(name))continue;if(excludedSet.has(name))continue;if(result.score<minRelevanceScore){lowRelevanceCount++;continue}const existing=matches.get(name);if(existing){existing.matchedQueries.push(query);existing.relevanceScore=Math.max(existing.relevanceScore,result.score)}else{matches.set(name,{name,description:result.metadata.description,tags:result.metadata.tags??[],relevanceScore:result.score,matchedQueries:[query],source:result.source})}}}const knowledge=Array.from(matches.values()).sort((a,b)=>b.relevanceScore-a.relevanceScore);if(knowledge.length===0){warnings.push({type:"no_results",message:`No knowledge skills found for queries: ${queries.join(", ")}${tags?.length?` with tags: ${tags.join(", ")}`:""}`})}if(lowRelevanceCount>0&&knowledge.length>0){warnings.push({type:"low_relevance",message:`${lowRelevanceCount} result(s) filtered due to relevance below ${minRelevanceScore}`})}return{knowledge,warnings,totalKnowledgeSkills}}};SearchKnowledgeTool=__decorateClass([Tool3({name:"codecall:searchKnowledge",cache:{ttl:60,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:searchKnowledgeToolDescription,inputSchema:searchKnowledgeToolInputSchema,outputSchema:searchKnowledgeToolOutputSchema,annotations:{readOnlyHint:true,openWorldHint:true}})],SearchKnowledgeTool);import{toJSONSchema,z as z6,ZodType}from"@frontmcp/lazy-zod";import{getCallSurface as getCallSurface2,InvalidInputError,Tool as Tool4,ToolContext as ToolContext4}from"@frontmcp/sdk";var INTENT_PATTERNS={create:/^(create|add|new|insert|make|append|register|generate|produce|build|construct|provision|instantiate|define|compose|draft)/i,delete:/^(delete|remove|destroy|drop|erase|clear|purge|discard|eliminate|unbind|unregister)/i,get:/^(get|fetch|retrieve|read|obtain|load|pull|access|grab|receive)/i,update:/^(update|edit|modify|change|patch|set|alter|revise|adjust|amend|correct|fix|refresh|sync|upgrade|downgrade)/i,list:/^(list|all|index|enumerate|show|display|view|browse|scan|inventory)/i,search:/^(search|find|query|lookup|locate|discover|explore|seek|match|filter)/i};function detectToolIntent(toolName,description){const parts=toolName.split(":");const actionPart=parts.length>1?parts[parts.length-1]:toolName;for(const[intent,pattern]of Object.entries(INTENT_PATTERNS)){if(pattern.test(actionPart)){return intent}}if(description){const descLower=description.toLowerCase();if(/creates?\s|adding\s|inserts?/i.test(descLower))return"create";if(/deletes?\s|removes?\s|destroys?/i.test(descLower))return"delete";if(/gets?\s|fetche?s?\s|retrieves?/i.test(descLower))return"get";if(/updates?\s|modif(?:y|ies)\s|edits?/i.test(descLower))return"update";if(/lists?\s|shows?\s|displays?/i.test(descLower))return"list";if(/search(?:es)?\s|find(?:s)?\s|quer(?:y|ies)/i.test(descLower))return"search"}return"unknown"}function generateBasicExample(toolName,inputSchema){const params=generateSampleParams(inputSchema);const paramsStr=params?JSON.stringify(params,null,2):"{}";return{description:`Basic usage of ${toolName}`,code:`const result = await callTool('${toolName}', ${paramsStr});
50
+ return result;`}}function generateSampleParams(schema){if(!schema||schema.type!=="object"||!schema.properties){return null}const params={};const required=new Set(schema.required||[]);for(const[key,propSchema]of Object.entries(schema.properties)){if(typeof propSchema==="boolean")continue;if(!required.has(key))continue;params[key]=getSampleValue(propSchema,key)}return Object.keys(params).length>0?params:null}function fitString(schema,value){let fitted=value;if(schema.maxLength!==void 0&&fitted.length>schema.maxLength){fitted=fitted.slice(0,Math.max(0,schema.maxLength))}if(schema.minLength!==void 0&&fitted.length<schema.minLength){fitted=fitted.padEnd(schema.minLength,"x")}return fitted}function isFreeTextString(schema){return schema?.type==="string"&&schema.enum===void 0&&schema.const===void 0&&schema.default===void 0&&schema.pattern===void 0&&schema.format===void 0}function acceptsNumber(schema,value){if(schema.const!==void 0)return schema.const===value;if(schema.enum!==void 0)return schema.enum.includes(value);if(schema.minimum!==void 0&&value<schema.minimum)return false;if(schema.maximum!==void 0&&value>schema.maximum)return false;return true}function pickNumber(schema,preferred){const accepted=preferred.find(value=>acceptsNumber(schema,value));if(accepted!==void 0)return accepted;const named=[schema.const,schema.enum?.[0],schema.minimum,schema.maximum].find(value=>typeof value==="number"&&acceptsNumber(schema,value));return named}function formatInlineArgs(args){const entries=Object.entries(args).map(([key,value])=>{const name=/^[A-Za-z_$][\w$]*$/.test(key)?key:JSON.stringify(key);const plain=typeof value==="string"&&[...value].every(ch=>ch!=="'"&&ch!=="\\"&&ch>=" ");const literal=plain?`'${value}'`:JSON.stringify(value);return`${name}: ${literal}`});return entries.length>0?`{ ${entries.join(", ")} }`:"{}"}function getSampleValue(schema,key){if(schema.default!==void 0){return schema.default}if(schema.enum&&schema.enum.length>0){return schema.enum[0]}if(schema.const!==void 0){return schema.const}const type=Array.isArray(schema.type)?schema.type[0]:schema.type;switch(type){case"string":if(key.toLowerCase().includes("id"))return fitString(schema,"abc123");if(key.toLowerCase().includes("email"))return fitString(schema,"user@example.com");if(key.toLowerCase().includes("name"))return fitString(schema,"Example");if(key.toLowerCase().includes("url"))return fitString(schema,"https://example.com");return fitString(schema,"string");case"number":case"integer":if(key.toLowerCase().includes("limit"))return 10;if(key.toLowerCase().includes("offset"))return 0;if(key.toLowerCase().includes("page"))return 1;return 0;case"boolean":return true;case"array":return[];case"object":return{};default:return null}}var PAGINATION_PROPERTIES=["limit","offset","page","pagesize","cursor"];function isPaginationProperty(name){return PAGINATION_PROPERTIES.includes(name.toLowerCase())}function hasPaginationParams(schema){if(!schema||schema.type!=="object"||!schema.properties){return false}return Object.keys(schema.properties).some(isPaginationProperty)}function inputProperties(schema){if(!schema||schema.type!=="object"||!schema.properties){return{}}const properties={};for(const[key,propSchema]of Object.entries(schema.properties)){if(typeof propSchema!=="boolean")properties[key]=propSchema}return properties}function buildExampleArgs(schema,keys,values={}){const properties=inputProperties(schema);const args={};for(const key of[...keys,...schema?.required??[]]){const propSchema=properties[key];if(!propSchema||key in args)continue;args[key]=key in values?values[key]:getSampleValue(propSchema,key)}return args}function formatExampleArgs(args){return Object.keys(args).length>0?JSON.stringify(args,null,2):"{}"}function getFilterProperties(schema){if(!schema||schema.type!=="object"||!schema.properties){return[]}return Object.keys(schema.properties).filter(p=>p.toLowerCase().includes("filter")||p.toLowerCase().includes("query")||p.toLowerCase().includes("search")||p.toLowerCase()==="status"||p.toLowerCase()==="type"||p.toLowerCase()==="role")}function generatePaginationExample(toolName,inputSchema){const description=`Pagination example for ${toolName}`;const props=Object.keys(inputProperties(inputSchema));const limitKey=props.find(p=>p.toLowerCase()==="limit");const offsetKey=props.find(p=>p.toLowerCase()==="offset");if(limitKey&&offsetKey){const properties=inputProperties(inputSchema);const limit=pickNumber(properties[limitKey],[10]);const firstOffset=pickNumber(properties[offsetKey],[0]);const values={};if(limit!==void 0)values[limitKey]=limit;if(firstOffset!==void 0)values[offsetKey]=firstOffset;const firstPage=buildExampleArgs(inputSchema,[limitKey,offsetKey],values);const nextOffset=[limit??10,10,20,...properties[offsetKey].enum??[]].find(value=>typeof value==="number"&&value!==firstPage[offsetKey]&&acceptsNumber(properties[offsetKey],value));if(nextOffset!==void 0){const secondPage={...firstPage,[offsetKey]:nextOffset};return{description,code:`// Fetch first page
3128
51
  const page1 = await callTool('${toolName}', ${formatExampleArgs(firstPage)});
3129
52
 
3130
53
  // Fetch second page
3131
54
  const page2 = await callTool('${toolName}', ${formatExampleArgs(secondPage)});
3132
55
 
3133
56
  // Combine results
3134
- return [...page1.items, ...page2.items];`
3135
- };
3136
- }
3137
- return {
3138
- description,
3139
- code: `const page = await callTool('${toolName}', ${formatExampleArgs(firstPage)});
3140
- return page.items || page;`
3141
- };
3142
- }
3143
- const args = buildExampleArgs(inputSchema, props.filter(isPaginationProperty));
3144
- return {
3145
- description,
3146
- code: `const page = await callTool('${toolName}', ${formatExampleArgs(args)});
3147
- return page.items || page;`
3148
- };
3149
- }
3150
- function extractEntityName(toolName) {
3151
- const parts = toolName.split(":");
3152
- const entity = parts.length > 1 ? parts[0] : toolName;
3153
- return entity.endsWith("s") && !entity.endsWith("ss") ? entity.slice(0, -1) : entity;
3154
- }
3155
- function generateCreateExample(toolName, inputSchema) {
3156
- const entity = extractEntityName(toolName);
3157
- const params = generateSampleParams(inputSchema);
3158
- const paramsStr = params ? JSON.stringify(params, null, 2) : "{ /* required fields */ }";
3159
- return {
3160
- description: `Create a new ${entity}`,
3161
- code: `const result = await callTool('${toolName}', ${paramsStr});
3162
- return result;`
3163
- };
3164
- }
3165
- function idArgs(schema, idParam) {
3166
- const idSchema = inputProperties(schema)[idParam];
3167
- const values = isFreeTextString(idSchema) ? { [idParam]: fitString(idSchema, "abc123") } : {};
3168
- return buildExampleArgs(schema, [idParam], values);
3169
- }
3170
- function generateGetExample(toolName, inputSchema) {
3171
- const entity = extractEntityName(toolName);
3172
- const idParam = findIdParameter(inputSchema);
3173
- if (idParam) {
3174
- return {
3175
- description: `Get ${entity} by ${idParam}`,
3176
- code: `const ${entity} = await callTool('${toolName}', ${formatInlineArgs(idArgs(inputSchema, idParam))});
3177
- return ${entity};`
3178
- };
3179
- }
3180
- const params = generateSampleParams(inputSchema);
3181
- const paramsStr = params ? JSON.stringify(params, null, 2) : "{}";
3182
- return {
3183
- description: `Get ${entity} details`,
3184
- code: `const ${entity} = await callTool('${toolName}', ${paramsStr});
3185
- return ${entity};`
3186
- };
3187
- }
3188
- function generateListExample(toolName, inputSchema) {
3189
- const entity = extractEntityName(toolName);
3190
- return {
3191
- description: `List all ${entity}s`,
3192
- code: `const result = await callTool('${toolName}', ${formatExampleArgs(buildExampleArgs(inputSchema, []))});
3193
- return result.items || result;`
3194
- };
3195
- }
3196
- function generateUpdateExample(toolName, inputSchema) {
3197
- const entity = extractEntityName(toolName);
3198
- const idParam = findIdParameter(inputSchema);
3199
- const updateFields = generateUpdateFields(inputSchema);
3200
- const fieldsStr = updateFields ? JSON.stringify(updateFields, null, 2).replace(/\n/g, "\n ") : "{ /* fields to update */ }";
3201
- if (idParam) {
3202
- const identifiers = formatInlineArgs(idArgs(inputSchema, idParam)).slice(2, -2);
3203
- return {
3204
- description: `Update ${entity} by ${idParam}`,
3205
- code: `const updated = await callTool('${toolName}', {
57
+ return [...page1.items, ...page2.items];`}}return{description,code:`const page = await callTool('${toolName}', ${formatExampleArgs(firstPage)});
58
+ return page.items || page;`}}const args=buildExampleArgs(inputSchema,props.filter(isPaginationProperty));return{description,code:`const page = await callTool('${toolName}', ${formatExampleArgs(args)});
59
+ return page.items || page;`}}function extractEntityName(toolName){const parts=toolName.split(":");const entity=parts.length>1?parts[0]:toolName;return entity.endsWith("s")&&!entity.endsWith("ss")?entity.slice(0,-1):entity}function generateCreateExample(toolName,inputSchema){const entity=extractEntityName(toolName);const params=generateSampleParams(inputSchema);const paramsStr=params?JSON.stringify(params,null,2):"{ /* required fields */ }";return{description:`Create a new ${entity}`,code:`const result = await callTool('${toolName}', ${paramsStr});
60
+ return result;`}}function idArgs(schema,idParam){const idSchema=inputProperties(schema)[idParam];const values=isFreeTextString(idSchema)?{[idParam]:fitString(idSchema,"abc123")}:{};return buildExampleArgs(schema,[idParam],values)}function generateGetExample(toolName,inputSchema){const entity=extractEntityName(toolName);const idParam=findIdParameter(inputSchema);if(idParam){return{description:`Get ${entity} by ${idParam}`,code:`const ${entity} = await callTool('${toolName}', ${formatInlineArgs(idArgs(inputSchema,idParam))});
61
+ return ${entity};`}}const params=generateSampleParams(inputSchema);const paramsStr=params?JSON.stringify(params,null,2):"{}";return{description:`Get ${entity} details`,code:`const ${entity} = await callTool('${toolName}', ${paramsStr});
62
+ return ${entity};`}}function generateListExample(toolName,inputSchema){const entity=extractEntityName(toolName);return{description:`List all ${entity}s`,code:`const result = await callTool('${toolName}', ${formatExampleArgs(buildExampleArgs(inputSchema,[]))});
63
+ return result.items || result;`}}function generateUpdateExample(toolName,inputSchema){const entity=extractEntityName(toolName);const idParam=findIdParameter(inputSchema);const updateFields=generateUpdateFields(inputSchema);const fieldsStr=updateFields?JSON.stringify(updateFields,null,2).replace(/\n/g,"\n "):"{ /* fields to update */ }";if(idParam){const identifiers=formatInlineArgs(idArgs(inputSchema,idParam)).slice(2,-2);return{description:`Update ${entity} by ${idParam}`,code:`const updated = await callTool('${toolName}', {
3206
64
  ${identifiers},
3207
65
  ...${fieldsStr}
3208
66
  });
3209
- return updated;`
3210
- };
3211
- }
3212
- return {
3213
- description: `Update ${entity}`,
3214
- code: `const updated = await callTool('${toolName}', ${fieldsStr});
3215
- return updated;`
3216
- };
3217
- }
3218
- function generateDeleteExample(toolName, inputSchema) {
3219
- const entity = extractEntityName(toolName);
3220
- const idParam = findIdParameter(inputSchema);
3221
- if (idParam) {
3222
- return {
3223
- description: `Delete ${entity} by ${idParam}`,
3224
- code: `const result = await callTool('${toolName}', ${formatInlineArgs(idArgs(inputSchema, idParam))});
3225
- return result;`
3226
- };
3227
- }
3228
- const params = generateSampleParams(inputSchema);
3229
- const paramsStr = params ? JSON.stringify(params, null, 2) : "{ /* identifier */ }";
3230
- return {
3231
- description: `Delete ${entity}`,
3232
- code: `const result = await callTool('${toolName}', ${paramsStr});
3233
- return result;`
3234
- };
3235
- }
3236
- function generateSearchExample(toolName, inputSchema) {
3237
- const entity = extractEntityName(toolName);
3238
- const searchParam = findQueryParameter(inputSchema) ?? getFilterProperties(inputSchema)[0];
3239
- const searchSchema = searchParam ? inputProperties(inputSchema)[searchParam] : void 0;
3240
- const required = new Set(inputSchema?.required ?? []);
3241
- const unfillable = searchSchema?.type === "string" && (searchSchema.pattern !== void 0 || searchSchema.format !== void 0) && searchSchema.enum === void 0 && searchSchema.const === void 0 && searchSchema.default === void 0 && !required.has(searchParam ?? "");
3242
- const args = searchParam && !unfillable ? buildExampleArgs(
3243
- inputSchema,
3244
- [searchParam],
3245
- isFreeTextString(searchSchema) && searchSchema ? { [searchParam]: fitString(searchSchema, "search term") } : {}
3246
- ) : buildExampleArgs(inputSchema, []);
3247
- return {
3248
- description: `Search for ${entity}s`,
3249
- code: `const results = await callTool('${toolName}', ${formatExampleArgs(args)});
3250
- return results.items || results;`
3251
- };
3252
- }
3253
- function findIdParameter(schema) {
3254
- if (!schema || schema.type !== "object" || !schema.properties) {
3255
- return null;
3256
- }
3257
- const props = Object.keys(schema.properties);
3258
- const required = new Set(schema.required || []);
3259
- const idPatterns = ["id", "Id", "ID", "_id", "uuid", "key"];
3260
- for (const pattern of idPatterns) {
3261
- const found = props.find((p) => (p === pattern || p.endsWith(pattern)) && required.has(p));
3262
- if (found) return found;
3263
- }
3264
- for (const pattern of idPatterns) {
3265
- const found = props.find((p) => p === pattern || p.endsWith(pattern));
3266
- if (found) return found;
3267
- }
3268
- return null;
3269
- }
3270
- function findQueryParameter(schema) {
3271
- if (!schema || schema.type !== "object" || !schema.properties) {
3272
- return null;
3273
- }
3274
- const props = Object.keys(schema.properties);
3275
- const queryPatterns = ["query", "search", "q", "term", "keyword", "filter"];
3276
- for (const pattern of queryPatterns) {
3277
- const found = props.find((p) => p.toLowerCase() === pattern || p.toLowerCase().includes(pattern));
3278
- if (found) return found;
3279
- }
3280
- return null;
3281
- }
3282
- function generateUpdateFields(schema) {
3283
- if (!schema || schema.type !== "object" || !schema.properties) {
3284
- return null;
3285
- }
3286
- const fields = {};
3287
- const idPatterns = ["id", "Id", "ID", "_id", "uuid", "key"];
3288
- for (const [key, propSchema] of Object.entries(schema.properties)) {
3289
- if (typeof propSchema === "boolean") continue;
3290
- const isIdField = idPatterns.some((p) => key === p || key.endsWith(p));
3291
- if (isIdField) continue;
3292
- if (Object.keys(fields).length < 2) {
3293
- fields[key] = getSampleValue(propSchema, key);
3294
- }
3295
- }
3296
- return Object.keys(fields).length > 0 ? fields : null;
3297
- }
3298
- function generateSmartExample(toolName, inputSchema, description) {
3299
- const intent = detectToolIntent(toolName, description);
3300
- switch (intent) {
3301
- case "create":
3302
- return generateCreateExample(toolName, inputSchema);
3303
- case "get":
3304
- return generateGetExample(toolName, inputSchema);
3305
- case "list":
3306
- return hasPaginationParams(inputSchema) ? generatePaginationExample(toolName, inputSchema) : generateListExample(toolName, inputSchema);
3307
- case "update":
3308
- return generateUpdateExample(toolName, inputSchema);
3309
- case "delete":
3310
- return generateDeleteExample(toolName, inputSchema);
3311
- case "search":
3312
- return generateSearchExample(toolName, inputSchema);
3313
- default:
3314
- return generateBasicExample(toolName, inputSchema);
3315
- }
3316
- }
3317
-
3318
- // plugins/plugin-codecall/src/utils/plain-json.ts
3319
- function toPlainJson(value) {
3320
- try {
3321
- const serialized = JSON.stringify(value);
3322
- if (serialized === void 0) return void 0;
3323
- return JSON.parse(serialized);
3324
- } catch {
3325
- return void 0;
3326
- }
3327
- }
3328
-
3329
- // plugins/plugin-codecall/src/utils/mcp-result.ts
3330
- function extractResultFromCallToolResult(mcpResult) {
3331
- if (mcpResult.isError) {
3332
- const errorContent = mcpResult.content?.[0];
3333
- if (errorContent && "text" in errorContent) {
3334
- throw new Error(errorContent.text);
3335
- }
3336
- throw new Error("Tool execution failed");
3337
- }
3338
- const content = mcpResult.content;
3339
- if (!content || content.length === 0) {
3340
- return void 0;
3341
- }
3342
- if (content.length === 1 && content[0].type === "text") {
3343
- try {
3344
- return JSON.parse(content[0].text);
3345
- } catch {
3346
- return content[0].text;
3347
- }
3348
- }
3349
- return toPlainJson(content);
3350
- }
3351
-
3352
- // plugins/plugin-codecall/src/tools/describe.schema.ts
3353
- import { z as z5 } from "@frontmcp/lazy-zod";
3354
- import { ToolAnnotationsSchema } from "@frontmcp/protocol";
3355
- var describeToolDescription = `Get input/output schemas for tools from search results.
67
+ return updated;`}}return{description:`Update ${entity}`,code:`const updated = await callTool('${toolName}', ${fieldsStr});
68
+ return updated;`}}function generateDeleteExample(toolName,inputSchema){const entity=extractEntityName(toolName);const idParam=findIdParameter(inputSchema);if(idParam){return{description:`Delete ${entity} by ${idParam}`,code:`const result = await callTool('${toolName}', ${formatInlineArgs(idArgs(inputSchema,idParam))});
69
+ return result;`}}const params=generateSampleParams(inputSchema);const paramsStr=params?JSON.stringify(params,null,2):"{ /* identifier */ }";return{description:`Delete ${entity}`,code:`const result = await callTool('${toolName}', ${paramsStr});
70
+ return result;`}}function generateSearchExample(toolName,inputSchema){const entity=extractEntityName(toolName);const searchParam=findQueryParameter(inputSchema)??getFilterProperties(inputSchema)[0];const searchSchema=searchParam?inputProperties(inputSchema)[searchParam]:void 0;const required=new Set(inputSchema?.required??[]);const unfillable=searchSchema?.type==="string"&&(searchSchema.pattern!==void 0||searchSchema.format!==void 0)&&searchSchema.enum===void 0&&searchSchema.const===void 0&&searchSchema.default===void 0&&!required.has(searchParam??"");const args=searchParam&&!unfillable?buildExampleArgs(inputSchema,[searchParam],isFreeTextString(searchSchema)&&searchSchema?{[searchParam]:fitString(searchSchema,"search term")}:{}):buildExampleArgs(inputSchema,[]);return{description:`Search for ${entity}s`,code:`const results = await callTool('${toolName}', ${formatExampleArgs(args)});
71
+ return results.items || results;`}}function findIdParameter(schema){if(!schema||schema.type!=="object"||!schema.properties){return null}const props=Object.keys(schema.properties);const required=new Set(schema.required||[]);const idPatterns=["id","Id","ID","_id","uuid","key"];for(const pattern of idPatterns){const found=props.find(p=>(p===pattern||p.endsWith(pattern))&&required.has(p));if(found)return found}for(const pattern of idPatterns){const found=props.find(p=>p===pattern||p.endsWith(pattern));if(found)return found}return null}function findQueryParameter(schema){if(!schema||schema.type!=="object"||!schema.properties){return null}const props=Object.keys(schema.properties);const queryPatterns=["query","search","q","term","keyword","filter"];for(const pattern of queryPatterns){const found=props.find(p=>p.toLowerCase()===pattern||p.toLowerCase().includes(pattern));if(found)return found}return null}function generateUpdateFields(schema){if(!schema||schema.type!=="object"||!schema.properties){return null}const fields={};const idPatterns=["id","Id","ID","_id","uuid","key"];for(const[key,propSchema]of Object.entries(schema.properties)){if(typeof propSchema==="boolean")continue;const isIdField=idPatterns.some(p=>key===p||key.endsWith(p));if(isIdField)continue;if(Object.keys(fields).length<2){fields[key]=getSampleValue(propSchema,key)}}return Object.keys(fields).length>0?fields:null}function generateSmartExample(toolName,inputSchema,description){const intent=detectToolIntent(toolName,description);switch(intent){case"create":return generateCreateExample(toolName,inputSchema);case"get":return generateGetExample(toolName,inputSchema);case"list":return hasPaginationParams(inputSchema)?generatePaginationExample(toolName,inputSchema):generateListExample(toolName,inputSchema);case"update":return generateUpdateExample(toolName,inputSchema);case"delete":return generateDeleteExample(toolName,inputSchema);case"search":return generateSearchExample(toolName,inputSchema);default:return generateBasicExample(toolName,inputSchema)}}function toPlainJson(value){try{const serialized=JSON.stringify(value);if(serialized===void 0)return void 0;return JSON.parse(serialized)}catch{return void 0}}function extractResultFromCallToolResult(mcpResult){if(mcpResult.isError){const errorContent=mcpResult.content?.[0];if(errorContent&&"text"in errorContent){throw new Error(errorContent.text)}throw new Error("Tool execution failed")}const content=mcpResult.content;if(!content||content.length===0){return void 0}if(content.length===1&&content[0].type==="text"){try{return JSON.parse(content[0].text)}catch{return content[0].text}}return toPlainJson(content)}import{z as z5}from"@frontmcp/lazy-zod";import{ToolAnnotationsSchema}from"@frontmcp/protocol";var describeToolDescription=`Get input/output schemas for tools from search results.
3356
72
 
3357
73
  INPUT: toolNames: string[] - tool names from search, at most the server's maxDefinitions (8 unless configured) per call
3358
74
  OUTPUT per tool: inputSchema (JSON Schema), outputSchema (JSON Schema), usageExamples (up to 5 callTool examples)
3359
75
 
3360
76
  IMPORTANT: If notFound array is non-empty \u2192 re-search with corrected queries.
3361
- FLOW: search \u2192 describe \u2192 execute/invoke`;
3362
- var describeToolInputSchema = {
3363
- toolNames: z5.array(z5.string()).min(1).superRefine((toolNames, ctx) => {
3364
- const seen = /* @__PURE__ */ new Set();
3365
- const duplicates = /* @__PURE__ */ new Set();
3366
- for (const name of toolNames) {
3367
- if (seen.has(name)) {
3368
- duplicates.add(name);
3369
- }
3370
- seen.add(name);
3371
- }
3372
- if (duplicates.size > 0) {
3373
- ctx.addIssue({
3374
- code: z5.ZodIssueCode.custom,
3375
- message: `Duplicate tool names are not allowed: ${Array.from(duplicates).join(", ")}`
3376
- });
3377
- }
3378
- }).describe(
3379
- 'Array of unique tool names (from codecall:search results) to fetch their detailed schemas and usage examples. Example: ["users:list", "billing:getInvoice"]'
3380
- )
3381
- };
3382
- var describeToolOutputSchema = z5.object({
3383
- tools: z5.array(
3384
- z5.object({
3385
- name: z5.string().describe("Tool name to be used in callTool() within codecall:execute scripts"),
3386
- appId: z5.string().describe("The app ID this tool belongs to"),
3387
- description: z5.string().describe("Detailed description of what this tool does"),
3388
- inputSchema: z5.record(z5.string(), z5.unknown()).nullable().describe("JSON Schema object describing the tool input parameters"),
3389
- outputSchema: z5.record(z5.string(), z5.unknown()).nullable().describe("JSON Schema object describing the tool output structure"),
3390
- annotations: ToolAnnotationsSchema.optional().describe("MCP tool annotations (metadata)"),
3391
- usageExamples: z5.array(
3392
- z5.object({
3393
- description: z5.string().describe("Description of what this example demonstrates"),
3394
- code: z5.string().describe(
3395
- 'JavaScript code example showing how to call this tool using callTool(). Format: const result = await callTool("tool:name", { ...params });'
3396
- )
3397
- })
3398
- ).max(5).describe("Up to 5 practical examples of how to use this tool in a codecall:execute script")
3399
- })
3400
- ).describe("Array of tool descriptions with schemas and usage examples"),
3401
- notFound: z5.array(z5.string()).optional().describe("Tool names that were requested but not found in the index. Check these for typos.")
3402
- });
3403
-
3404
- // plugins/plugin-codecall/src/tools/describe.tool.ts
3405
- var DescribeTool = class extends ToolContext4 {
3406
- async execute(input) {
3407
- const { toolNames } = input;
3408
- const audit = this.tryGet(AuditLoggerService);
3409
- const executionId = audit ? audit.generateExecutionId() : "";
3410
- const startedAt = Date.now();
3411
- const config = this.get(CodeCallConfig);
3412
- const maxDefinitions = config.get("maxDefinitions");
3413
- const tools = [];
3414
- const notFound = [];
3415
- const surface = getCallSurface2();
3416
- for (const toolName of toolNames) {
3417
- if (isBlockedSelfReference(toolName)) {
3418
- notFound.push(toolName);
3419
- continue;
3420
- }
3421
- const access = checkCodeCallToolAccess(this.scope, config, toolName, { surface });
3422
- if (!access.allowed) {
3423
- audit?.logSecurityAccessDenied(executionId, toolName, access.reason);
3424
- notFound.push(toolName);
3425
- continue;
3426
- }
3427
- const tool = access.entry;
3428
- if (tools.length >= maxDefinitions) {
3429
- throw new InvalidInputError(
3430
- `codecall:describe describes at most ${maxDefinitions} tools per call; describe the rest in another call`
3431
- );
3432
- }
3433
- const appId = this.extractAppId(tool);
3434
- const inputSchema = this.getInputSchema(tool);
3435
- const outputSchema = this.toJsonSchema(tool.rawOutputSchema ?? tool.outputSchema);
3436
- const usageExamples = this.generateExamples(tool, inputSchema ?? void 0);
3437
- tools.push({
3438
- name: tool.name,
3439
- appId,
3440
- description: tool.metadata?.description || `Tool: ${tool.name}`,
3441
- inputSchema: inputSchema || null,
3442
- outputSchema: outputSchema || null,
3443
- annotations: tool.metadata?.annotations,
3444
- usageExamples
3445
- });
3446
- }
3447
- audit?.logDescribe(executionId, toolNames, Date.now() - startedAt);
3448
- return {
3449
- tools,
3450
- notFound: notFound.length > 0 ? notFound : void 0
3451
- };
3452
- }
3453
- /**
3454
- * Get the input schema for a tool, converting from Zod to JSON Schema.
3455
- * This ensures that property descriptions from .describe() are included.
3456
- *
3457
- * Priority:
3458
- * 1. Convert from tool.inputSchema (Zod) to get descriptions
3459
- * 2. Fall back to rawInputSchema if conversion fails
3460
- * 3. Return null if no schema available
3461
- */
3462
- getInputSchema(tool) {
3463
- if (tool.inputSchema && typeof tool.inputSchema === "object" && Object.keys(tool.inputSchema).length > 0) {
3464
- try {
3465
- const firstValue = Object.values(tool.inputSchema)[0];
3466
- if (firstValue instanceof ZodType) {
3467
- return toJSONSchema(z6.object(tool.inputSchema));
3468
- }
3469
- } catch {
3470
- }
3471
- }
3472
- if (tool.rawInputSchema) {
3473
- return tool.rawInputSchema;
3474
- }
3475
- return null;
3476
- }
3477
- /**
3478
- * Convert a schema to JSON Schema format.
3479
- * Handles Zod schemas, raw shapes, and already-JSON-Schema objects.
3480
- *
3481
- * Uses Zod v4's built-in z.toJSONSchema() for conversion.
3482
- */
3483
- toJsonSchema(schema) {
3484
- if (!schema) {
3485
- return null;
3486
- }
3487
- if (schema instanceof ZodType) {
3488
- try {
3489
- return toJSONSchema(schema);
3490
- } catch {
3491
- return null;
3492
- }
3493
- }
3494
- if (typeof schema === "object" && schema !== null && !Array.isArray(schema)) {
3495
- const obj = schema;
3496
- const firstValue = Object.values(obj)[0];
3497
- if (firstValue instanceof ZodType) {
3498
- try {
3499
- return toJSONSchema(z6.object(obj));
3500
- } catch {
3501
- return null;
3502
- }
3503
- }
3504
- if ("type" in obj || "properties" in obj || "$schema" in obj) {
3505
- return schema;
3506
- }
3507
- }
3508
- if (typeof schema === "string") {
3509
- return null;
3510
- }
3511
- if (Array.isArray(schema)) {
3512
- return null;
3513
- }
3514
- return null;
3515
- }
3516
- /**
3517
- * Extract app ID from tool metadata or owner.
3518
- */
3519
- extractAppId(tool) {
3520
- if (tool.metadata?.codecall?.appId) {
3521
- return tool.metadata.codecall.appId;
3522
- }
3523
- if (tool.metadata?.source) {
3524
- return tool.metadata.source;
3525
- }
3526
- if (tool.owner?.id) {
3527
- return tool.owner.id;
3528
- }
3529
- const nameParts = tool.name?.split(":");
3530
- if (nameParts && nameParts.length > 1) {
3531
- return nameParts[0];
3532
- }
3533
- return "unknown";
3534
- }
3535
- /**
3536
- * Generate up to 5 usage examples for a tool.
3537
- *
3538
- * Priority:
3539
- * 1. User-provided examples from @Tool decorator metadata (up to 5)
3540
- * 2. Without any, one smart intent-based example built from the input schema. It is never added
3541
- * next to the tool's own examples: those show how the tool is called, and a generated one
3542
- * only guesses (#647).
3543
- * 3. Returns at least 1 example
3544
- */
3545
- generateExamples(tool, inputSchema) {
3546
- const result = [];
3547
- const examples = tool.metadata?.examples;
3548
- if (examples && Array.isArray(examples)) {
3549
- for (const ex of examples.slice(0, 5)) {
3550
- result.push({
3551
- description: ex.description || "Example usage",
3552
- code: `const result = await callTool('${tool.name}', ${JSON.stringify(ex.input, null, 2)});
3553
- return result;`
3554
- });
3555
- }
3556
- }
3557
- if (result.length === 0) {
3558
- result.push(generateSmartExample(tool.name, inputSchema, tool.metadata?.description));
3559
- }
3560
- return result.slice(0, 5);
3561
- }
3562
- };
3563
- DescribeTool = __decorateClass([
3564
- Tool4({
3565
- name: "codecall:describe",
3566
- cache: {
3567
- ttl: 60,
3568
- // 1 minute
3569
- slideWindow: false
3570
- },
3571
- codecall: {
3572
- enabledInCodeCall: false,
3573
- visibleInListTools: true
3574
- },
3575
- description: describeToolDescription,
3576
- inputSchema: describeToolInputSchema,
3577
- outputSchema: describeToolOutputSchema,
3578
- annotations: {
3579
- readOnlyHint: true,
3580
- openWorldHint: true
3581
- }
3582
- })
3583
- ], DescribeTool);
3584
-
3585
- // plugins/plugin-codecall/src/tools/execute.tool.ts
3586
- import { getCallSurface as getCallSurface3, Tool as Tool5, ToolContext as ToolContext5 } from "@frontmcp/sdk";
3587
-
3588
- // plugins/plugin-codecall/src/tools/execute.schema.ts
3589
- import { z as z7 } from "@frontmcp/lazy-zod";
3590
- var MIN_EXECUTE_SCRIPT_LENGTH = 'return callTool("a",{})'.length;
3591
- var ALWAYS_BLOCKED_NAMES = ["eval", "require", "fetch", "setTimeout", "process", "globalThis"];
3592
- function buildExecuteToolDescription(vmOptions) {
3593
- const loops = vmOptions.allowLoops ? "for, for-of" : "for-of";
3594
- const blockedLoops = vmOptions.allowLoops ? "while, do-while" : "while, do-while, for";
3595
- const blockedNames = /* @__PURE__ */ new Set([...ALWAYS_BLOCKED_NAMES, ...vmOptions.disabledBuiltins, ...vmOptions.disabledGlobals]);
3596
- const namespaces = ["Math", "JSON"].filter((name) => !blockedNames.has(name)).map((name) => `${name}.*, `);
3597
- const timeoutSeconds = vmOptions.timeoutMs / 1e3;
3598
- const maxToolCalls = maxToolCallsOf(vmOptions);
3599
- const callsPerTool = rapidEnumerationThresholdOf(vmOptions);
3600
- return `Execute AgentScript (safe JS subset) for multi-tool orchestration.
77
+ FLOW: search \u2192 describe \u2192 execute/invoke`;var describeToolInputSchema={toolNames:z5.array(z5.string()).min(1).superRefine((toolNames,ctx)=>{const seen=new Set;const duplicates=new Set;for(const name of toolNames){if(seen.has(name)){duplicates.add(name)}seen.add(name)}if(duplicates.size>0){ctx.addIssue({code:z5.ZodIssueCode.custom,message:`Duplicate tool names are not allowed: ${Array.from(duplicates).join(", ")}`})}}).describe('Array of unique tool names (from codecall:search results) to fetch their detailed schemas and usage examples. Example: ["users:list", "billing:getInvoice"]')};var describeToolOutputSchema=z5.object({tools:z5.array(z5.object({name:z5.string().describe("Tool name to be used in callTool() within codecall:execute scripts"),appId:z5.string().describe("The app ID this tool belongs to"),description:z5.string().describe("Detailed description of what this tool does"),inputSchema:z5.record(z5.string(),z5.unknown()).nullable().describe("JSON Schema object describing the tool input parameters"),outputSchema:z5.record(z5.string(),z5.unknown()).nullable().describe("JSON Schema object describing the tool output structure"),annotations:ToolAnnotationsSchema.optional().describe("MCP tool annotations (metadata)"),usageExamples:z5.array(z5.object({description:z5.string().describe("Description of what this example demonstrates"),code:z5.string().describe('JavaScript code example showing how to call this tool using callTool(). Format: const result = await callTool("tool:name", { ...params });')})).max(5).describe("Up to 5 practical examples of how to use this tool in a codecall:execute script")})).describe("Array of tool descriptions with schemas and usage examples"),notFound:z5.array(z5.string()).optional().describe("Tool names that were requested but not found in the index. Check these for typos.")});var DescribeTool=class extends ToolContext4{async execute(input){const{toolNames}=input;const audit=this.tryGet(AuditLoggerService);const executionId=audit?audit.generateExecutionId():"";const startedAt=Date.now();const config=this.get(CodeCallConfig);const maxDefinitions=config.get("maxDefinitions");const tools=[];const notFound=[];const surface=getCallSurface2();for(const toolName of toolNames){if(isBlockedSelfReference(toolName)){notFound.push(toolName);continue}const access=checkCodeCallToolAccess(this.scope,config,toolName,{surface});if(!access.allowed){audit?.logSecurityAccessDenied(executionId,toolName,access.reason);notFound.push(toolName);continue}const tool=access.entry;if(tools.length>=maxDefinitions){throw new InvalidInputError(`codecall:describe describes at most ${maxDefinitions} tools per call; describe the rest in another call`)}const appId=this.extractAppId(tool);const inputSchema=this.getInputSchema(tool);const outputSchema=this.toJsonSchema(tool.rawOutputSchema??tool.outputSchema);const usageExamples=this.generateExamples(tool,inputSchema??void 0);tools.push({name:tool.name,appId,description:tool.metadata?.description||`Tool: ${tool.name}`,inputSchema:inputSchema||null,outputSchema:outputSchema||null,annotations:tool.metadata?.annotations,usageExamples})}audit?.logDescribe(executionId,toolNames,Date.now()-startedAt);return{tools,notFound:notFound.length>0?notFound:void 0}}getInputSchema(tool){if(tool.inputSchema&&typeof tool.inputSchema==="object"&&Object.keys(tool.inputSchema).length>0){try{const firstValue=Object.values(tool.inputSchema)[0];if(firstValue instanceof ZodType){return toJSONSchema(z6.object(tool.inputSchema))}}catch{}}if(tool.rawInputSchema){return tool.rawInputSchema}return null}toJsonSchema(schema){if(!schema){return null}if(schema instanceof ZodType){try{return toJSONSchema(schema)}catch{return null}}if(typeof schema==="object"&&schema!==null&&!Array.isArray(schema)){const obj=schema;const firstValue=Object.values(obj)[0];if(firstValue instanceof ZodType){try{return toJSONSchema(z6.object(obj))}catch{return null}}if("type"in obj||"properties"in obj||"$schema"in obj){return schema}}if(typeof schema==="string"){return null}if(Array.isArray(schema)){return null}return null}extractAppId(tool){if(tool.metadata?.codecall?.appId){return tool.metadata.codecall.appId}if(tool.metadata?.source){return tool.metadata.source}if(tool.owner?.id){return tool.owner.id}const nameParts=tool.name?.split(":");if(nameParts&&nameParts.length>1){return nameParts[0]}return"unknown"}generateExamples(tool,inputSchema){const result=[];const examples=tool.metadata?.examples;if(examples&&Array.isArray(examples)){for(const ex of examples.slice(0,5)){result.push({description:ex.description||"Example usage",code:`const result = await callTool('${tool.name}', ${JSON.stringify(ex.input,null,2)});
78
+ return result;`})}}if(result.length===0){result.push(generateSmartExample(tool.name,inputSchema,tool.metadata?.description))}return result.slice(0,5)}};DescribeTool=__decorateClass([Tool4({name:"codecall:describe",cache:{ttl:60,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:describeToolDescription,inputSchema:describeToolInputSchema,outputSchema:describeToolOutputSchema,annotations:{readOnlyHint:true,openWorldHint:true}})],DescribeTool);import{getCallSurface as getCallSurface3,Tool as Tool5,ToolContext as ToolContext5}from"@frontmcp/sdk";import{z as z7}from"@frontmcp/lazy-zod";var MIN_EXECUTE_SCRIPT_LENGTH='return callTool("a",{})'.length;var ALWAYS_BLOCKED_NAMES=["eval","require","fetch","setTimeout","process","globalThis"];function buildExecuteToolDescription(vmOptions){const loops=vmOptions.allowLoops?"for, for-of":"for-of";const blockedLoops=vmOptions.allowLoops?"while, do-while":"while, do-while, for";const blockedNames=new Set([...ALWAYS_BLOCKED_NAMES,...vmOptions.disabledBuiltins,...vmOptions.disabledGlobals]);const namespaces=["Math","JSON"].filter(name=>!blockedNames.has(name)).map(name=>`${name}.*, `);const timeoutSeconds=vmOptions.timeoutMs/1e3;const maxToolCalls=maxToolCallsOf(vmOptions);const callsPerTool=rapidEnumerationThresholdOf(vmOptions);return`Execute AgentScript (safe JS subset) for multi-tool orchestration.
3601
79
 
3602
80
  API: await callTool(name, args, opts?)
3603
81
  - Default: throws on error
@@ -3617,377 +95,7 @@ BLOCKED: ${blockedLoops}, console (use mcpLog), function decl, ${[...blockedName
3617
95
 
3618
96
  ERRORS: NOT_FOUND | VALIDATION | EXECUTION | TIMEOUT | ACCESS_DENIED | RATE_LIMITED
3619
97
  STATUS: ok | syntax_error | illegal_access | runtime_error | tool_error | timeout
3620
- LIMITS: ${MAX_ITERATIONS_PER_LOOP} iterations per loop, ${timeoutSeconds}s timeout, ${maxToolCalls} tool calls, ${callsPerTool} calls to one tool per 2s (parallel() included)`;
3621
- }
3622
- var executeToolDescription = buildExecuteToolDescription(resolveVmOptions());
3623
- var executeToolInputSchema = {
3624
- script: z7.string().min(MIN_EXECUTE_SCRIPT_LENGTH).max(100 * 1024).describe(
3625
- "JavaScript code to execute in the sandbox. Must return a value (implicitly or via explicit return). Use callTool(name, input) to invoke tools."
3626
- ),
3627
- allowedTools: z7.array(z7.string()).optional().describe(
3628
- '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"]'
3629
- )
3630
- };
3631
- var syntaxErrorPayloadSchema = z7.object({
3632
- message: z7.string(),
3633
- location: z7.object({
3634
- line: z7.number(),
3635
- column: z7.number()
3636
- }).optional()
3637
- });
3638
- var illegalAccessErrorPayloadSchema = z7.object({
3639
- message: z7.string(),
3640
- kind: z7.union([
3641
- z7.literal("IllegalBuiltinAccess"),
3642
- z7.literal("DisallowedGlobal"),
3643
- z7.string()
3644
- // same as your original type: 'A' | 'B' | string
3645
- ])
3646
- });
3647
- var runtimeErrorPayloadSchema = z7.object({
3648
- source: z7.literal("script"),
3649
- message: z7.string(),
3650
- name: z7.string().optional(),
3651
- /** @deprecated Never set: stack traces name server files, so results don't carry them. */
3652
- stack: z7.string().optional()
3653
- });
3654
- var toolErrorPayloadSchema = z7.object({
3655
- source: z7.literal("tool"),
3656
- toolName: z7.string(),
3657
- /**
3658
- * @deprecated Never set: the sandbox resolves sidecar references in a call's arguments before
3659
- * the tool sees them, so they may hold data the script itself never had.
3660
- */
3661
- toolInput: z7.unknown().optional(),
3662
- message: z7.string(),
3663
- code: z7.string().optional(),
3664
- /** @deprecated Never set: the enclave's error data is not sanitized for clients. */
3665
- details: z7.unknown().optional()
3666
- });
3667
- var timeoutErrorPayloadSchema = z7.object({
3668
- message: z7.string()
3669
- });
3670
- var codeCallOkResultSchema = z7.object({
3671
- status: z7.literal("ok"),
3672
- result: z7.unknown(),
3673
- logs: z7.array(z7.string()).optional()
3674
- });
3675
- var codeCallSyntaxErrorResultSchema = z7.object({
3676
- status: z7.literal("syntax_error"),
3677
- error: syntaxErrorPayloadSchema
3678
- });
3679
- var codeCallIllegalAccessResultSchema = z7.object({
3680
- status: z7.literal("illegal_access"),
3681
- error: illegalAccessErrorPayloadSchema
3682
- });
3683
- var codeCallRuntimeErrorResultSchema = z7.object({
3684
- status: z7.literal("runtime_error"),
3685
- error: runtimeErrorPayloadSchema
3686
- });
3687
- var codeCallToolErrorResultSchema = z7.object({
3688
- status: z7.literal("tool_error"),
3689
- error: toolErrorPayloadSchema
3690
- });
3691
- var codeCallTimeoutResultSchema = z7.object({
3692
- status: z7.literal("timeout"),
3693
- error: timeoutErrorPayloadSchema
3694
- });
3695
- var executeToolOutputSchema = z7.discriminatedUnion("status", [
3696
- codeCallOkResultSchema,
3697
- codeCallSyntaxErrorResultSchema,
3698
- codeCallIllegalAccessResultSchema,
3699
- codeCallRuntimeErrorResultSchema,
3700
- codeCallToolErrorResultSchema,
3701
- codeCallTimeoutResultSchema
3702
- ]);
3703
-
3704
- // plugins/plugin-codecall/src/tools/execute.tool.ts
3705
- function getErrorCode(error) {
3706
- if (!(error instanceof Error)) {
3707
- return TOOL_CALL_ERROR_CODES.EXECUTION;
3708
- }
3709
- const { code, statusCode } = error;
3710
- if (code === "INVALID_INPUT") {
3711
- return TOOL_CALL_ERROR_CODES.VALIDATION;
3712
- }
3713
- if (statusCode === 429) {
3714
- return TOOL_CALL_ERROR_CODES.RATE_LIMITED;
3715
- }
3716
- if (error.name === "ZodError" || error.message?.includes("validation")) {
3717
- return TOOL_CALL_ERROR_CODES.VALIDATION;
3718
- }
3719
- if (error.message?.includes("timeout") || error.message?.includes("timed out")) {
3720
- return TOOL_CALL_ERROR_CODES.TIMEOUT;
3721
- }
3722
- if (error.name === "ToolNotFoundError" || error.message?.includes("not found")) {
3723
- return TOOL_CALL_ERROR_CODES.NOT_FOUND;
3724
- }
3725
- return TOOL_CALL_ERROR_CODES.EXECUTION;
3726
- }
3727
- function publicMessageOf(error) {
3728
- const { getPublicMessage } = error;
3729
- return typeof getPublicMessage === "function" ? getPublicMessage.call(error) : error.message;
3730
- }
3731
- var ExecuteTool = class extends ToolContext5 {
3732
- /**
3733
- * Resolve the server-side CodeCall policy for a tool name (GHSA-6w3j-82v5-6qrr).
3734
- *
3735
- * Shares its decision with discovery and with `codecall:invoke`, so the three cannot
3736
- * diverge. A name matching no registered tool is denied rather than passed through —
3737
- * otherwise it would skip every metadata-driven check and reach `tools:call-tool`
3738
- * unexamined.
3739
- */
3740
- checkToolPolicy(name, surface) {
3741
- return checkCodeCallToolAccess(this.scope, this.get(CodeCallConfig), name, { surface });
3742
- }
3743
- async execute(input) {
3744
- const { script, allowedTools } = input;
3745
- const callerSurface = getCallSurface3();
3746
- const audit = this.tryGet(AuditLoggerService);
3747
- const executionId = audit ? audit.generateExecutionId() : "";
3748
- const callDepth = 1;
3749
- let toolCallCount = 0;
3750
- const allowedToolSet = allowedTools ? new Set(allowedTools) : null;
3751
- const environment = {
3752
- callTool: async (name, toolInput, options) => {
3753
- const throwOnError = options?.throwOnError !== false;
3754
- if (isBlockedSelfReference(name)) {
3755
- audit?.logSecuritySelfReference(executionId, name);
3756
- }
3757
- assertNotSelfReference(name);
3758
- const decision = this.checkToolPolicy(name, callerSurface);
3759
- if (!decision.allowed) {
3760
- audit?.logSecurityAccessDenied(executionId, name, decision.reason);
3761
- const error = createToolCallError(TOOL_CALL_ERROR_CODES.ACCESS_DENIED, name, decision.reason);
3762
- if (throwOnError) {
3763
- throw error;
3764
- }
3765
- return { success: false, error };
3766
- }
3767
- if (allowedToolSet && !allowedToolSet.has(name)) {
3768
- audit?.logSecurityAccessDenied(executionId, name, "not in the caller-supplied allowedTools list");
3769
- const error = createToolCallError(TOOL_CALL_ERROR_CODES.ACCESS_DENIED, name);
3770
- if (throwOnError) {
3771
- throw error;
3772
- }
3773
- return { success: false, error };
3774
- }
3775
- toolCallCount += 1;
3776
- audit?.logToolCallStart(executionId, name, callDepth);
3777
- const toolCallStartedAt = Date.now();
3778
- try {
3779
- const request = {
3780
- method: "tools/call",
3781
- params: {
3782
- name,
3783
- arguments: toolInput
3784
- }
3785
- };
3786
- const ctx = asCodeCallDispatch({
3787
- authInfo: this.authInfo,
3788
- surface: callerSurface
3789
- });
3790
- const mcpResult = await this.scope.runFlow("tools:call-tool", { request, ctx });
3791
- if (!mcpResult) {
3792
- audit?.logToolCallFailure(
3793
- executionId,
3794
- name,
3795
- callDepth,
3796
- Date.now() - toolCallStartedAt,
3797
- TOOL_CALL_ERROR_CODES.EXECUTION
3798
- );
3799
- const error = createToolCallError(TOOL_CALL_ERROR_CODES.EXECUTION, name, "Flow returned no result");
3800
- if (throwOnError) {
3801
- throw error;
3802
- }
3803
- return { success: false, error };
3804
- }
3805
- const result = extractResultFromCallToolResult(mcpResult);
3806
- audit?.logToolCallSuccess(executionId, name, callDepth, Date.now() - toolCallStartedAt);
3807
- if (throwOnError) {
3808
- return result;
3809
- }
3810
- return { success: true, data: result };
3811
- } catch (error) {
3812
- const errorCode = getErrorCode(error);
3813
- const rawMessage = error instanceof Error ? publicMessageOf(error) : void 0;
3814
- audit?.logToolCallFailure(executionId, name, callDepth, Date.now() - toolCallStartedAt, errorCode);
3815
- const sanitizedError = createToolCallError(errorCode, name, rawMessage);
3816
- if (throwOnError) {
3817
- throw sanitizedError;
3818
- }
3819
- return { success: false, error: sanitizedError };
3820
- }
3821
- },
3822
- getTool: (name) => {
3823
- try {
3824
- if (isBlockedSelfReference(name)) {
3825
- audit?.logSecuritySelfReference(executionId, name);
3826
- return void 0;
3827
- }
3828
- const introspectionAccess = this.checkToolPolicy(name, callerSurface);
3829
- if (!introspectionAccess.allowed) {
3830
- audit?.logSecurityAccessDenied(executionId, name, introspectionAccess.reason);
3831
- return void 0;
3832
- }
3833
- if (allowedToolSet && !allowedToolSet.has(name)) return void 0;
3834
- const tool = introspectionAccess.entry;
3835
- return toPlainJson({
3836
- name: tool.name,
3837
- description: tool.metadata?.description,
3838
- inputSchema: tool.getInputJsonSchema?.() ?? null,
3839
- outputSchema: tool.getOutputJsonSchema?.() ?? null
3840
- });
3841
- } catch {
3842
- return void 0;
3843
- }
3844
- },
3845
- console: this.get(CodeCallConfig).get("resolvedVm.allowConsole") ? console : void 0,
3846
- mcpLog: (level, message, metadata) => {
3847
- this.logger?.[level](message, metadata);
3848
- },
3849
- mcpNotify: (event, payload) => {
3850
- this.logger?.debug("Notification sent", { event, payload });
3851
- }
3852
- };
3853
- try {
3854
- const policyConfig = readCodeCallPolicyConfig(this.get(CodeCallConfig));
3855
- const callableTools = this.scope.tools.getTools(true).filter(
3856
- (tool) => checkCodeCallToolPolicy(toCodeCallPolicyTool(tool, void 0, this.scope), policyConfig).allowed
3857
- );
3858
- const { namespaces, skipped } = buildToolNamespaces(callableTools);
3859
- environment.toolNamespaces = namespaces;
3860
- if (skipped.length > 0) {
3861
- this.logger?.debug?.("codecall: tools skipped during namespace generation", {
3862
- count: skipped.length,
3863
- // Cap the debug payload so a huge skip list doesn't bloat logs.
3864
- sample: skipped.slice(0, 25)
3865
- });
3866
- }
3867
- } catch (error) {
3868
- this.logger?.warn?.("codecall: failed to build tool namespaces", {
3869
- error: error instanceof Error ? error.message : String(error)
3870
- });
3871
- }
3872
- const enclaveService = this.get(EnclaveService);
3873
- const config = this.get(CodeCallConfig);
3874
- const startedAt = Date.now();
3875
- const elapsed = (reported) => reported ?? Date.now() - startedAt;
3876
- audit?.logExecutionStart(executionId, script);
3877
- try {
3878
- const executionResult = await enclaveService.execute(script, environment);
3879
- const durationMs = elapsed(executionResult.stats?.duration);
3880
- if (executionResult.timedOut) {
3881
- audit?.logExecutionTimeout(executionId, script, durationMs);
3882
- return {
3883
- status: "timeout",
3884
- error: {
3885
- message: `Script execution timed out after ${config.getAll().resolvedVm.timeoutMs}ms`
3886
- }
3887
- };
3888
- }
3889
- if (!executionResult.success) {
3890
- const error = executionResult.error;
3891
- if (error.code === "SYNTAX_ERROR") {
3892
- audit?.logExecutionFailure(executionId, script, durationMs, error.message);
3893
- return {
3894
- status: "syntax_error",
3895
- error: {
3896
- message: toClientErrorMessage(error.message) || "Syntax error in script",
3897
- ...error.location ? { location: error.location } : {}
3898
- }
3899
- };
3900
- }
3901
- if (error.code === "VALIDATION_ERROR" || error.name === "ValidationError") {
3902
- audit?.logSecurityAstBlocked(executionId, error.blockedPatterns?.join(", ") ?? "UNKNOWN", error.message);
3903
- audit?.logExecutionFailure(executionId, script, durationMs, error.message);
3904
- return {
3905
- status: "illegal_access",
3906
- error: {
3907
- kind: "IllegalBuiltinAccess",
3908
- message: error.message
3909
- }
3910
- };
3911
- }
3912
- if (error.toolName) {
3913
- audit?.logExecutionFailure(executionId, script, durationMs, error.message);
3914
- return {
3915
- status: "tool_error",
3916
- error: {
3917
- source: "tool",
3918
- toolName: error.toolName,
3919
- message: toClientErrorMessage(error.message),
3920
- code: error.code
3921
- // No `details`: the enclave's error data is not sanitized for clients. No `toolInput`:
3922
- // the arguments the tool saw may hold sidecar-resolved data the script never had.
3923
- }
3924
- };
3925
- }
3926
- audit?.logExecutionFailure(executionId, script, durationMs, error.message);
3927
- return {
3928
- status: "runtime_error",
3929
- error: {
3930
- source: "script",
3931
- message: toClientErrorMessage(error.message),
3932
- name: error.name
3933
- }
3934
- };
3935
- }
3936
- audit?.logExecutionSuccess(executionId, script, durationMs, toolCallCount);
3937
- return {
3938
- status: "ok",
3939
- result: executionResult.result,
3940
- logs: executionResult.logs.length > 0 ? executionResult.logs : void 0
3941
- };
3942
- } catch (error) {
3943
- const errorName = error instanceof Error ? error.name : "Error";
3944
- const errorMessage = error instanceof Error ? error.message : String(error);
3945
- audit?.logExecutionFailure(executionId, script, elapsed(), errorMessage);
3946
- const errorLoc = error.loc;
3947
- if (errorName === "SyntaxError" || errorMessage?.includes("syntax")) {
3948
- return {
3949
- status: "syntax_error",
3950
- error: {
3951
- message: toClientErrorMessage(errorMessage) || "Syntax error in script",
3952
- location: errorLoc ? { line: errorLoc.line, column: errorLoc.column } : void 0
3953
- }
3954
- };
3955
- }
3956
- return {
3957
- status: "runtime_error",
3958
- error: {
3959
- source: "script",
3960
- message: toClientErrorMessage(errorMessage) || "An unexpected error occurred during script execution",
3961
- name: errorName
3962
- }
3963
- };
3964
- }
3965
- }
3966
- };
3967
- ExecuteTool = __decorateClass([
3968
- Tool5({
3969
- name: "codecall:execute",
3970
- cache: {
3971
- ttl: 0,
3972
- // No caching - each execution is unique
3973
- slideWindow: false
3974
- },
3975
- codecall: {
3976
- enabledInCodeCall: false,
3977
- visibleInListTools: true
3978
- },
3979
- description: executeToolDescription,
3980
- inputSchema: executeToolInputSchema,
3981
- outputSchema: executeToolOutputSchema
3982
- })
3983
- ], ExecuteTool);
3984
-
3985
- // plugins/plugin-codecall/src/tools/invoke.tool.ts
3986
- import { getCallSurface as getCallSurface4, Tool as Tool6, ToolContext as ToolContext6 } from "@frontmcp/sdk";
3987
-
3988
- // plugins/plugin-codecall/src/tools/invoke.schema.ts
3989
- import { z as z8 } from "@frontmcp/lazy-zod";
3990
- var invokeToolDescription = `Call ONE tool directly. Returns standard MCP CallToolResult.
98
+ LIMITS: ${MAX_ITERATIONS_PER_LOOP} iterations per loop, ${timeoutSeconds}s timeout, ${maxToolCalls} tool calls, ${callsPerTool} calls to one tool per 2s (parallel() included)`}var executeToolDescription=buildExecuteToolDescription(resolveVmOptions());var executeToolInputSchema={script:z7.string().min(MIN_EXECUTE_SCRIPT_LENGTH).max(100*1024).describe("JavaScript code to execute in the sandbox. Must return a value (implicitly or via explicit return). Use callTool(name, input) to invoke tools."),allowedTools:z7.array(z7.string()).optional().describe('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"]')};var syntaxErrorPayloadSchema=z7.object({message:z7.string(),location:z7.object({line:z7.number(),column:z7.number()}).optional()});var illegalAccessErrorPayloadSchema=z7.object({message:z7.string(),kind:z7.union([z7.literal("IllegalBuiltinAccess"),z7.literal("DisallowedGlobal"),z7.string()])});var runtimeErrorPayloadSchema=z7.object({source:z7.literal("script"),message:z7.string(),name:z7.string().optional(),stack:z7.string().optional()});var toolErrorPayloadSchema=z7.object({source:z7.literal("tool"),toolName:z7.string(),toolInput:z7.unknown().optional(),message:z7.string(),code:z7.string().optional(),details:z7.unknown().optional()});var timeoutErrorPayloadSchema=z7.object({message:z7.string()});var codeCallOkResultSchema=z7.object({status:z7.literal("ok"),result:z7.unknown(),logs:z7.array(z7.string()).optional()});var codeCallSyntaxErrorResultSchema=z7.object({status:z7.literal("syntax_error"),error:syntaxErrorPayloadSchema});var codeCallIllegalAccessResultSchema=z7.object({status:z7.literal("illegal_access"),error:illegalAccessErrorPayloadSchema});var codeCallRuntimeErrorResultSchema=z7.object({status:z7.literal("runtime_error"),error:runtimeErrorPayloadSchema});var codeCallToolErrorResultSchema=z7.object({status:z7.literal("tool_error"),error:toolErrorPayloadSchema});var codeCallTimeoutResultSchema=z7.object({status:z7.literal("timeout"),error:timeoutErrorPayloadSchema});var executeToolOutputSchema=z7.discriminatedUnion("status",[codeCallOkResultSchema,codeCallSyntaxErrorResultSchema,codeCallIllegalAccessResultSchema,codeCallRuntimeErrorResultSchema,codeCallToolErrorResultSchema,codeCallTimeoutResultSchema]);function getErrorCode(error){if(!(error instanceof Error)){return TOOL_CALL_ERROR_CODES.EXECUTION}const{code,statusCode}=error;if(code==="INVALID_INPUT"){return TOOL_CALL_ERROR_CODES.VALIDATION}if(statusCode===429){return TOOL_CALL_ERROR_CODES.RATE_LIMITED}if(error.name==="ZodError"||error.message?.includes("validation")){return TOOL_CALL_ERROR_CODES.VALIDATION}if(error.message?.includes("timeout")||error.message?.includes("timed out")){return TOOL_CALL_ERROR_CODES.TIMEOUT}if(error.name==="ToolNotFoundError"||error.message?.includes("not found")){return TOOL_CALL_ERROR_CODES.NOT_FOUND}return TOOL_CALL_ERROR_CODES.EXECUTION}function publicMessageOf(error){const{getPublicMessage}=error;return typeof getPublicMessage==="function"?getPublicMessage.call(error):error.message}var ExecuteTool=class extends ToolContext5{checkToolPolicy(name,surface){return checkCodeCallToolAccess(this.scope,this.get(CodeCallConfig),name,{surface})}async execute(input){const{script,allowedTools}=input;const callerSurface=getCallSurface3();const audit=this.tryGet(AuditLoggerService);const executionId=audit?audit.generateExecutionId():"";const callDepth=1;let toolCallCount=0;const allowedToolSet=allowedTools?new Set(allowedTools):null;const environment={callTool:async(name,toolInput,options)=>{const throwOnError=options?.throwOnError!==false;if(isBlockedSelfReference(name)){audit?.logSecuritySelfReference(executionId,name)}assertNotSelfReference(name);const decision=this.checkToolPolicy(name,callerSurface);if(!decision.allowed){audit?.logSecurityAccessDenied(executionId,name,decision.reason);const error=createToolCallError(TOOL_CALL_ERROR_CODES.ACCESS_DENIED,name,decision.reason);if(throwOnError){throw error}return{success:false,error}}if(allowedToolSet&&!allowedToolSet.has(name)){audit?.logSecurityAccessDenied(executionId,name,"not in the caller-supplied allowedTools list");const error=createToolCallError(TOOL_CALL_ERROR_CODES.ACCESS_DENIED,name);if(throwOnError){throw error}return{success:false,error}}toolCallCount+=1;audit?.logToolCallStart(executionId,name,callDepth);const toolCallStartedAt=Date.now();try{const request={method:"tools/call",params:{name,arguments:toolInput}};const ctx=asCodeCallDispatch({authInfo:this.authInfo,surface:callerSurface});const mcpResult=await this.scope.runFlow("tools:call-tool",{request,ctx});if(!mcpResult){audit?.logToolCallFailure(executionId,name,callDepth,Date.now()-toolCallStartedAt,TOOL_CALL_ERROR_CODES.EXECUTION);const error=createToolCallError(TOOL_CALL_ERROR_CODES.EXECUTION,name,"Flow returned no result");if(throwOnError){throw error}return{success:false,error}}const result=extractResultFromCallToolResult(mcpResult);audit?.logToolCallSuccess(executionId,name,callDepth,Date.now()-toolCallStartedAt);if(throwOnError){return result}return{success:true,data:result}}catch(error){const errorCode=getErrorCode(error);const rawMessage=error instanceof Error?publicMessageOf(error):void 0;audit?.logToolCallFailure(executionId,name,callDepth,Date.now()-toolCallStartedAt,errorCode);const sanitizedError=createToolCallError(errorCode,name,rawMessage);if(throwOnError){throw sanitizedError}return{success:false,error:sanitizedError}}},getTool:name=>{try{if(isBlockedSelfReference(name)){audit?.logSecuritySelfReference(executionId,name);return void 0}const introspectionAccess=this.checkToolPolicy(name,callerSurface);if(!introspectionAccess.allowed){audit?.logSecurityAccessDenied(executionId,name,introspectionAccess.reason);return void 0}if(allowedToolSet&&!allowedToolSet.has(name))return void 0;const tool=introspectionAccess.entry;return toPlainJson({name:tool.name,description:tool.metadata?.description,inputSchema:tool.getInputJsonSchema?.()??null,outputSchema:tool.getOutputJsonSchema?.()??null})}catch{return void 0}},console:this.get(CodeCallConfig).get("resolvedVm.allowConsole")?console:void 0,mcpLog:(level,message,metadata)=>{this.logger?.[level](message,metadata)},mcpNotify:(event,payload)=>{this.logger?.debug("Notification sent",{event,payload})}};try{const policyConfig=readCodeCallPolicyConfig(this.get(CodeCallConfig));const callableTools=this.scope.tools.getTools(true).filter(tool=>checkCodeCallToolPolicy(toCodeCallPolicyTool(tool,void 0,this.scope),policyConfig).allowed);const{namespaces,skipped}=buildToolNamespaces(callableTools);environment.toolNamespaces=namespaces;if(skipped.length>0){this.logger?.debug?.("codecall: tools skipped during namespace generation",{count:skipped.length,sample:skipped.slice(0,25)})}}catch(error){this.logger?.warn?.("codecall: failed to build tool namespaces",{error:error instanceof Error?error.message:String(error)})}const enclaveService=this.get(EnclaveService);const config=this.get(CodeCallConfig);const startedAt=Date.now();const elapsed=reported=>reported??Date.now()-startedAt;audit?.logExecutionStart(executionId,script);try{const executionResult=await enclaveService.execute(script,environment);const durationMs=elapsed(executionResult.stats?.duration);if(executionResult.timedOut){audit?.logExecutionTimeout(executionId,script,durationMs);return{status:"timeout",error:{message:`Script execution timed out after ${config.getAll().resolvedVm.timeoutMs}ms`}}}if(!executionResult.success){const error=executionResult.error;if(error.code==="SYNTAX_ERROR"){audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"syntax_error",error:{message:toClientErrorMessage(error.message)||"Syntax error in script",...error.location?{location:error.location}:{}}}}if(error.code==="VALIDATION_ERROR"||error.name==="ValidationError"){audit?.logSecurityAstBlocked(executionId,error.blockedPatterns?.join(", ")??"UNKNOWN",error.message);audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"illegal_access",error:{kind:"IllegalBuiltinAccess",message:error.message}}}if(error.toolName){audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"tool_error",error:{source:"tool",toolName:error.toolName,message:toClientErrorMessage(error.message),code:error.code}}}audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"runtime_error",error:{source:"script",message:toClientErrorMessage(error.message),name:error.name}}}audit?.logExecutionSuccess(executionId,script,durationMs,toolCallCount);return{status:"ok",result:executionResult.result,logs:executionResult.logs.length>0?executionResult.logs:void 0}}catch(error){const errorName=error instanceof Error?error.name:"Error";const errorMessage=error instanceof Error?error.message:String(error);audit?.logExecutionFailure(executionId,script,elapsed(),errorMessage);const errorLoc=error.loc;if(errorName==="SyntaxError"||errorMessage?.includes("syntax")){return{status:"syntax_error",error:{message:toClientErrorMessage(errorMessage)||"Syntax error in script",location:errorLoc?{line:errorLoc.line,column:errorLoc.column}:void 0}}}return{status:"runtime_error",error:{source:"script",message:toClientErrorMessage(errorMessage)||"An unexpected error occurred during script execution",name:errorName}}}}};ExecuteTool=__decorateClass([Tool5({name:"codecall:execute",cache:{ttl:0,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:executeToolDescription,inputSchema:executeToolInputSchema,outputSchema:executeToolOutputSchema})],ExecuteTool);import{getCallSurface as getCallSurface4,Tool as Tool6,ToolContext as ToolContext6}from"@frontmcp/sdk";import{z as z8}from"@frontmcp/lazy-zod";var invokeToolDescription=`Call ONE tool directly. Returns standard MCP CallToolResult.
3991
99
 
3992
100
  USE invoke: single tool, no transformation
3993
101
  USE execute: multiple tools, loops, filtering, joining
@@ -3996,304 +104,4 @@ INPUT: tool (string), input (object matching tool schema)
3996
104
  OUTPUT: MCP CallToolResult (same as standard tool call)
3997
105
  ERRORS: tool_not_found (\u2192 re-search) | validation_error | execution_error | permission_denied
3998
106
 
3999
- FLOW: search \u2192 describe \u2192 invoke`;
4000
- var invokeToolInputSchema = {
4001
- tool: z8.string().describe(
4002
- 'The name of the tool to invoke (e.g., "users:getById", "billing:getInvoice"). Must be a tool you discovered via codecall:search.'
4003
- ),
4004
- input: z8.record(z8.string(), z8.unknown()).describe(
4005
- "The input parameters for the tool. Structure must match the tool's input schema (check codecall:describe for schema details)."
4006
- )
4007
- };
4008
-
4009
- // plugins/plugin-codecall/src/tools/invoke.tool.ts
4010
- function buildErrorResult(message) {
4011
- return {
4012
- content: [{ type: "text", text: message }],
4013
- isError: true
4014
- };
4015
- }
4016
- var InvokeTool = class extends ToolContext6 {
4017
- async execute(input) {
4018
- const { tool: toolName, input: toolInput } = input;
4019
- const audit = this.tryGet(AuditLoggerService);
4020
- const executionId = audit ? audit.generateExecutionId() : "";
4021
- const startedAt = Date.now();
4022
- if (isBlockedSelfReference(toolName)) {
4023
- audit?.logSecuritySelfReference(executionId, toolName);
4024
- return buildErrorResult(
4025
- `Tool "${toolName}" cannot be invoked directly. CodeCall tools are internal and not accessible via codecall:invoke.`
4026
- );
4027
- }
4028
- const surface = getCallSurface4();
4029
- const decision = checkCodeCallToolAccess(this.scope, this.get(CodeCallConfig), toolName, {
4030
- directCall: true,
4031
- surface
4032
- });
4033
- if (!decision.allowed) {
4034
- audit?.logSecurityAccessDenied(executionId, toolName, decision.reason);
4035
- return buildErrorResult(`Tool "${toolName}" is not available. Use codecall:search to discover available tools.`);
4036
- }
4037
- const request = {
4038
- method: "tools/call",
4039
- params: {
4040
- name: toolName,
4041
- arguments: toolInput
4042
- }
4043
- };
4044
- const ctx = asCodeCallDispatch({
4045
- authInfo: this.authInfo,
4046
- surface
4047
- });
4048
- const result = await this.scope.runFlow("tools:call-tool", { request, ctx });
4049
- if (!result) {
4050
- audit?.logInvoke(executionId, toolName, false, Date.now() - startedAt);
4051
- return buildErrorResult(`Tool "${toolName}" not found. Use codecall:search to discover available tools.`);
4052
- }
4053
- audit?.logInvoke(executionId, toolName, true, Date.now() - startedAt);
4054
- return result;
4055
- }
4056
- };
4057
- InvokeTool = __decorateClass([
4058
- Tool6({
4059
- name: "codecall:invoke",
4060
- cache: {
4061
- ttl: 0,
4062
- // No caching - each invocation is unique
4063
- slideWindow: false
4064
- },
4065
- codecall: {
4066
- enabledInCodeCall: false,
4067
- visibleInListTools: true
4068
- },
4069
- description: invokeToolDescription,
4070
- inputSchema: invokeToolInputSchema
4071
- })
4072
- ], InvokeTool);
4073
-
4074
- // plugins/plugin-codecall/src/codecall.plugin.ts
4075
- function auditLogFields(event) {
4076
- const { executionId, durationMs, data } = event;
4077
- return durationMs === void 0 ? { executionId, ...data } : { executionId, durationMs, ...data };
4078
- }
4079
- function callContextOf(flowCtx) {
4080
- const rawInput = flowCtx.rawInput;
4081
- return typeof rawInput === "object" && rawInput !== null ? rawInput.ctx : void 0;
4082
- }
4083
- var CodeCallPlugin = class extends DynamicPlugin {
4084
- options;
4085
- cachedLogger;
4086
- getLogger() {
4087
- if (!this.cachedLogger) {
4088
- this.cachedLogger = this.get(FrontMcpLogger).child("CodeCall");
4089
- }
4090
- return this.cachedLogger;
4091
- }
4092
- constructor(options = {}) {
4093
- super();
4094
- this.options = codeCallPluginOptionsSchema.parse(options);
4095
- }
4096
- /**
4097
- * Dynamic providers allow you to configure the plugin with custom options
4098
- * without touching the plugin decorator.
4099
- */
4100
- static dynamicProviders(options) {
4101
- const parsedOptions = codeCallPluginOptionsSchema.parse(options);
4102
- const config = new CodeCallConfig(parsedOptions);
4103
- return [
4104
- {
4105
- name: "codecall:config",
4106
- provide: CodeCallConfig,
4107
- useValue: config
4108
- },
4109
- {
4110
- name: "codecall:enclave",
4111
- provide: EnclaveService,
4112
- inject: () => [CodeCallConfig],
4113
- useFactory: async (cfg) => {
4114
- return new EnclaveService(cfg);
4115
- }
4116
- },
4117
- {
4118
- // GHSA-adjacent: production.mdx promised operators these events and nothing emitted them,
4119
- // because the service was never registered. The subscription lives here, in the factory,
4120
- // for a reason: there is no provider teardown hook in the SDK, so subscribing anywhere
4121
- // per-request would grow the listener Set for the life of the process.
4122
- name: "codecall:audit-logger",
4123
- provide: AuditLoggerService,
4124
- inject: () => [ScopeEntry],
4125
- useFactory: (scope) => {
4126
- const audit = new AuditLoggerService();
4127
- const logger = scope.logger.child("codecall:audit");
4128
- audit.subscribe((event) => logger.info(event.type, auditLogFields(event)));
4129
- return audit;
4130
- }
4131
- },
4132
- {
4133
- name: "codecall:tool-search",
4134
- provide: ToolSearchService,
4135
- inject: () => [ScopeEntry],
4136
- useFactory: async (scope) => {
4137
- return new ToolSearchService(
4138
- {
4139
- embeddingOptions: parsedOptions.embedding,
4140
- defaultTopK: parsedOptions.topK,
4141
- mode: parsedOptions.mode,
4142
- includeTools: parsedOptions["includeTools"]
4143
- },
4144
- scope
4145
- );
4146
- }
4147
- }
4148
- ];
4149
- }
4150
- /**
4151
- * The CodeCall meta-tools. `codecall:search` and `codecall:execute` describe the `topK` and the
4152
- * script limits these options give, since the model plans its calls from those descriptions.
4153
- */
4154
- static dynamicTools(options) {
4155
- const config = new CodeCallConfig(codeCallPluginOptionsSchema.parse(options)).getAll();
4156
- class ConfiguredSearchTool extends SearchTool {
4157
- }
4158
- class ConfiguredExecuteTool extends ExecuteTool {
4159
- }
4160
- Reflect.defineMetadata(
4161
- FrontMcpToolTokens.description,
4162
- buildSearchToolDescription(config.topK),
4163
- ConfiguredSearchTool
4164
- );
4165
- Reflect.defineMetadata(
4166
- FrontMcpToolTokens.description,
4167
- buildExecuteToolDescription(config.resolvedVm),
4168
- ConfiguredExecuteTool
4169
- );
4170
- return [
4171
- ConfiguredSearchTool,
4172
- SearchSkillsTool,
4173
- SearchKnowledgeTool,
4174
- DescribeTool,
4175
- ConfiguredExecuteTool,
4176
- InvokeTool
4177
- ];
4178
- }
4179
- async adjustListTools(flowCtx) {
4180
- const logger = this.getLogger();
4181
- const { resolvedTools } = flowCtx.state;
4182
- logger.verbose("adjustListTools hook called", { mode: this.options.mode });
4183
- logger.verbose("adjustListTools: tools before filter", { count: resolvedTools?.length ?? 0 });
4184
- if (!resolvedTools || resolvedTools.length === 0) {
4185
- logger.verbose("adjustListTools: no tools to filter, returning early");
4186
- return;
4187
- }
4188
- const scope = this.tryGetScope();
4189
- const filteredTools = resolvedTools.filter(
4190
- ({ tool }) => !this.judges(scope, { tool }) || this.shouldShowInListTools(tool, this.options.mode)
4191
- );
4192
- logger.verbose("adjustListTools: tools after filter", { count: filteredTools.length });
4193
- flowCtx.state.set("resolvedTools", filteredTools);
4194
- }
4195
- async refuseDirectCallOfHiddenTool(flowCtx) {
4196
- const { tool } = flowCtx.state;
4197
- if (!tool || tool.owner?.kind === "scope") return;
4198
- if (this.isDirectlyCallable(tool)) return;
4199
- if (isInProcessDispatch(callContextOf(flowCtx))) return;
4200
- this.getLogger().verbose("refused a direct tools/call of a tool CodeCall hides", { tool: tool.fullName });
4201
- throw new ToolNotFoundError(flowCtx.state.input?.name ?? tool.name);
4202
- }
4203
- /**
4204
- * Whether a client may call the tool directly: it is listed, and a tool the SDK keeps out of `tools/list`
4205
- * (`visibility: 'hidden'`) also opts in with `visibleInListTools: true`, in every mode.
4206
- */
4207
- isDirectlyCallable(tool) {
4208
- if (!this.managesApp(tool)) return true;
4209
- if (!this.shouldShowInListTools(tool, this.options.mode)) return false;
4210
- if (resolveToolVisibility(tool.metadata) !== "hidden") return true;
4211
- return this.getCodeCallMetadata(tool)?.visibleInListTools === true;
4212
- }
4213
- /** Whether the tool's app is one `appIds` puts under `codecall_only`; every app is, without `appIds`. */
4214
- managesApp(tool) {
4215
- const managedAppIds = this.options.appIds;
4216
- if (this.options.mode !== "codecall_only" || !managedAppIds || managedAppIds.length === 0) return true;
4217
- const toolOwnerAppId = tool.owner?.kind === "app" ? tool.owner.id : void 0;
4218
- return toolOwnerAppId !== void 0 && managedAppIds.includes(toolOwnerAppId);
4219
- }
4220
- /** Whether this instance's direct-call gate runs for the tool, so the listing hides only what that gate refuses. */
4221
- judges(scope, entry) {
4222
- return !scope?.hooks || isEntryGatedBy(scope, entry, this);
4223
- }
4224
- tryGetScope() {
4225
- try {
4226
- return this.get(ScopeEntry);
4227
- } catch {
4228
- return void 0;
4229
- }
4230
- }
4231
- /**
4232
- * Determine if a tool should be visible in list_tools based on mode.
4233
- *
4234
- * When `appIds` is configured, `codecall_only` mode only hides tools from
4235
- * those specific apps — tools from other apps remain visible.
4236
- *
4237
- * @param tool - The tool entry to check
4238
- * @param mode - The current CodeCall mode
4239
- * @returns true if tool should be visible
4240
- */
4241
- shouldShowInListTools(tool, mode) {
4242
- if (this.isCodeCallTool(tool)) {
4243
- return true;
4244
- }
4245
- const codecallMeta = this.getCodeCallMetadata(tool);
4246
- switch (mode) {
4247
- case "codecall_only":
4248
- return !this.managesApp(tool) || codecallMeta?.visibleInListTools === true;
4249
- case "codecall_opt_in":
4250
- case "metadata_driven":
4251
- return codecallMeta?.visibleInListTools !== false;
4252
- default:
4253
- return true;
4254
- }
4255
- }
4256
- /**
4257
- * Check if a tool is a CodeCall meta-tool.
4258
- * CodeCall meta-tools always remain visible.
4259
- */
4260
- isCodeCallTool(tool) {
4261
- const name = tool.name || tool.fullName;
4262
- return typeof name === "string" && name.startsWith("codecall:");
4263
- }
4264
- /**
4265
- * Extract CodeCall-specific metadata from a tool.
4266
- */
4267
- getCodeCallMetadata(tool) {
4268
- return tool.metadata?.["codecall"];
4269
- }
4270
- };
4271
- __decorateClass([
4272
- ListToolsHook.Did("resolveConflicts", { priority: 1e3 })
4273
- ], CodeCallPlugin.prototype, "adjustListTools", 1);
4274
- __decorateClass([
4275
- ToolHook.Did("findTool", { priority: 10, appliesTo: "uncovered-apps" })
4276
- ], CodeCallPlugin.prototype, "refuseDirectCallOfHiddenTool", 1);
4277
- CodeCallPlugin = __decorateClass([
4278
- Plugin({
4279
- name: "codecall",
4280
- description: "CodeCall plugin: AgentScript-based meta-tools for orchestrating MCP tools",
4281
- providers: [],
4282
- plugins: [CachePlugin]
4283
- })
4284
- ], CodeCallPlugin);
4285
- export {
4286
- AUDIT_EVENT_TYPES,
4287
- AuditLoggerService,
4288
- CodeCallPlugin,
4289
- codeCallDirectCallsOptionsSchema,
4290
- codeCallEmbeddingOptionsSchema,
4291
- codeCallModeSchema,
4292
- codeCallPluginOptionsSchema,
4293
- codeCallSidecarOptionsSchema,
4294
- codeCallVmOptionsSchema,
4295
- codeCallVmPresetSchema,
4296
- CodeCallPlugin as default,
4297
- embeddingStrategySchema,
4298
- synonymExpansionConfigSchema
4299
- };
107
+ FLOW: search \u2192 describe \u2192 invoke`;var invokeToolInputSchema={tool:z8.string().describe('The name of the tool to invoke (e.g., "users:getById", "billing:getInvoice"). Must be a tool you discovered via codecall:search.'),input:z8.record(z8.string(),z8.unknown()).describe("The input parameters for the tool. Structure must match the tool's input schema (check codecall:describe for schema details).")};function buildErrorResult(message){return{content:[{type:"text",text:message}],isError:true}}var InvokeTool=class extends ToolContext6{async execute(input){const{tool:toolName,input:toolInput}=input;const audit=this.tryGet(AuditLoggerService);const executionId=audit?audit.generateExecutionId():"";const startedAt=Date.now();if(isBlockedSelfReference(toolName)){audit?.logSecuritySelfReference(executionId,toolName);return buildErrorResult(`Tool "${toolName}" cannot be invoked directly. CodeCall tools are internal and not accessible via codecall:invoke.`)}const surface=getCallSurface4();const decision=checkCodeCallToolAccess(this.scope,this.get(CodeCallConfig),toolName,{directCall:true,surface});if(!decision.allowed){audit?.logSecurityAccessDenied(executionId,toolName,decision.reason);return buildErrorResult(`Tool "${toolName}" is not available. Use codecall:search to discover available tools.`)}const request={method:"tools/call",params:{name:toolName,arguments:toolInput}};const ctx=asCodeCallDispatch({authInfo:this.authInfo,surface});const result=await this.scope.runFlow("tools:call-tool",{request,ctx});if(!result){audit?.logInvoke(executionId,toolName,false,Date.now()-startedAt);return buildErrorResult(`Tool "${toolName}" not found. Use codecall:search to discover available tools.`)}audit?.logInvoke(executionId,toolName,true,Date.now()-startedAt);return result}};InvokeTool=__decorateClass([Tool6({name:"codecall:invoke",cache:{ttl:0,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:invokeToolDescription,inputSchema:invokeToolInputSchema})],InvokeTool);function auditLogFields(event){const{executionId,durationMs,data}=event;return durationMs===void 0?{executionId,...data}:{executionId,durationMs,...data}}function callContextOf(flowCtx){const rawInput=flowCtx.rawInput;return typeof rawInput==="object"&&rawInput!==null?rawInput.ctx:void 0}var CodeCallPlugin=class extends DynamicPlugin{options;cachedLogger;getLogger(){if(!this.cachedLogger){this.cachedLogger=this.get(FrontMcpLogger).child("CodeCall")}return this.cachedLogger}constructor(options={}){super();this.options=codeCallPluginOptionsSchema.parse(options)}static dynamicProviders(options){const parsedOptions=codeCallPluginOptionsSchema.parse(options);const config=new CodeCallConfig(parsedOptions);return[{name:"codecall:config",provide:CodeCallConfig,useValue:config},{name:"codecall:enclave",provide:EnclaveService,inject:()=>[CodeCallConfig],useFactory:async cfg=>{return new EnclaveService(cfg)}},{name:"codecall:audit-logger",provide:AuditLoggerService,inject:()=>[ScopeEntry],useFactory:scope=>{const audit=new AuditLoggerService;const logger=scope.logger.child("codecall:audit");audit.subscribe(event=>logger.info(event.type,auditLogFields(event)));return audit}},{name:"codecall:tool-search",provide:ToolSearchService,inject:()=>[ScopeEntry],useFactory:async scope=>{return new ToolSearchService({embeddingOptions:parsedOptions.embedding,defaultTopK:parsedOptions.topK,mode:parsedOptions.mode,includeTools:parsedOptions["includeTools"]},scope)}}]}static dynamicTools(options){const config=new CodeCallConfig(codeCallPluginOptionsSchema.parse(options)).getAll();class ConfiguredSearchTool extends SearchTool{}class ConfiguredExecuteTool extends ExecuteTool{}Reflect.defineMetadata(FrontMcpToolTokens.description,buildSearchToolDescription(config.topK),ConfiguredSearchTool);Reflect.defineMetadata(FrontMcpToolTokens.description,buildExecuteToolDescription(config.resolvedVm),ConfiguredExecuteTool);return[ConfiguredSearchTool,SearchSkillsTool,SearchKnowledgeTool,DescribeTool,ConfiguredExecuteTool,InvokeTool]}async adjustListTools(flowCtx){const logger=this.getLogger();const{resolvedTools}=flowCtx.state;logger.verbose("adjustListTools hook called",{mode:this.options.mode});logger.verbose("adjustListTools: tools before filter",{count:resolvedTools?.length??0});if(!resolvedTools||resolvedTools.length===0){logger.verbose("adjustListTools: no tools to filter, returning early");return}const scope=this.tryGetScope();const filteredTools=resolvedTools.filter(({tool})=>!this.judges(scope,{tool})||this.shouldShowInListTools(tool,this.options.mode));logger.verbose("adjustListTools: tools after filter",{count:filteredTools.length});flowCtx.state.set("resolvedTools",filteredTools)}async refuseDirectCallOfHiddenTool(flowCtx){const{tool}=flowCtx.state;if(!tool||tool.owner?.kind==="scope")return;if(this.isDirectlyCallable(tool))return;if(isInProcessDispatch(callContextOf(flowCtx)))return;this.getLogger().verbose("refused a direct tools/call of a tool CodeCall hides",{tool:tool.fullName});throw new ToolNotFoundError(flowCtx.state.input?.name??tool.name)}isDirectlyCallable(tool){if(!this.managesApp(tool))return true;if(!this.shouldShowInListTools(tool,this.options.mode))return false;if(resolveToolVisibility(tool.metadata)!=="hidden")return true;return this.getCodeCallMetadata(tool)?.visibleInListTools===true}managesApp(tool){const managedAppIds=this.options.appIds;if(this.options.mode!=="codecall_only"||!managedAppIds||managedAppIds.length===0)return true;const toolOwnerAppId=tool.owner?.kind==="app"?tool.owner.id:void 0;return toolOwnerAppId!==void 0&&managedAppIds.includes(toolOwnerAppId)}judges(scope,entry){return!scope?.hooks||isEntryGatedBy(scope,entry,this)}tryGetScope(){try{return this.get(ScopeEntry)}catch{return void 0}}shouldShowInListTools(tool,mode){if(this.isCodeCallTool(tool)){return true}const codecallMeta=this.getCodeCallMetadata(tool);switch(mode){case"codecall_only":return!this.managesApp(tool)||codecallMeta?.visibleInListTools===true;case"codecall_opt_in":case"metadata_driven":return codecallMeta?.visibleInListTools!==false;default:return true}}isCodeCallTool(tool){const name=tool.name||tool.fullName;return typeof name==="string"&&name.startsWith("codecall:")}getCodeCallMetadata(tool){return tool.metadata?.["codecall"]}};__decorateClass([ListToolsHook.Did("resolveConflicts",{priority:1e3})],CodeCallPlugin.prototype,"adjustListTools",1);__decorateClass([ToolHook.Did("findTool",{priority:10,appliesTo:"uncovered-apps"})],CodeCallPlugin.prototype,"refuseDirectCallOfHiddenTool",1);CodeCallPlugin=__decorateClass([Plugin({name:"codecall",description:"CodeCall plugin: AgentScript-based meta-tools for orchestrating MCP tools",providers:[],plugins:[CachePlugin]})],CodeCallPlugin);export{AUDIT_EVENT_TYPES,AuditLoggerService,CodeCallPlugin,codeCallDirectCallsOptionsSchema,codeCallEmbeddingOptionsSchema,codeCallModeSchema,codeCallPluginOptionsSchema,codeCallSidecarOptionsSchema,codeCallVmOptionsSchema,codeCallVmPresetSchema,CodeCallPlugin as default,embeddingStrategySchema,synonymExpansionConfigSchema};