sis-tools 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1531 @@
1
+ 'use strict';
2
+
3
+ // src/types.ts
4
+ function toSchema(tool) {
5
+ const required = Object.entries(tool.parameters).filter(([, v]) => v.required !== false).map(([k]) => k);
6
+ return {
7
+ name: tool.name,
8
+ description: tool.description,
9
+ parameters: {
10
+ type: "object",
11
+ properties: tool.parameters,
12
+ required
13
+ }
14
+ };
15
+ }
16
+ function toOpenAISchema(tool) {
17
+ return {
18
+ type: "function",
19
+ function: toSchema(tool)
20
+ };
21
+ }
22
+ function toAnthropicSchema(tool) {
23
+ const schema = toSchema(tool);
24
+ return {
25
+ name: schema.name,
26
+ description: schema.description,
27
+ input_schema: schema.parameters
28
+ };
29
+ }
30
+
31
+ // src/embeddings/base.ts
32
+ function buildToolText(name, description, semanticHints, examples) {
33
+ const parts = [`${name}: ${description}`];
34
+ if (semanticHints?.length) {
35
+ parts.push(`Related: ${semanticHints.join(", ")}`);
36
+ }
37
+ if (examples?.length) {
38
+ const queries = examples.map((ex) => ex.query).filter(Boolean);
39
+ if (queries.length) {
40
+ parts.push(`Examples: ${queries.join("; ")}`);
41
+ }
42
+ }
43
+ return parts.join(" | ");
44
+ }
45
+
46
+ // src/embeddings/openai.ts
47
+ var DEFAULT_DIMENSIONS = {
48
+ "text-embedding-3-small": 1536,
49
+ "text-embedding-3-large": 3072,
50
+ "text-embedding-ada-002": 1536
51
+ };
52
+ var OpenAIEmbeddings = class {
53
+ client = null;
54
+ model;
55
+ apiKey;
56
+ dimensions;
57
+ constructor(options = {}) {
58
+ const { model = "text-embedding-3-small", apiKey, dimensions } = options;
59
+ this.model = model;
60
+ this.apiKey = apiKey;
61
+ this.dimensions = dimensions ?? DEFAULT_DIMENSIONS[model] ?? 1536;
62
+ }
63
+ async ensureClient() {
64
+ if (this.client) {
65
+ return this.client;
66
+ }
67
+ try {
68
+ const mod = await import('openai');
69
+ const OpenAI = mod?.OpenAI ?? mod?.default?.OpenAI ?? mod?.default;
70
+ if (!OpenAI) {
71
+ throw new Error("OpenAI export not found");
72
+ }
73
+ this.client = new OpenAI({ apiKey: this.apiKey });
74
+ return this.client;
75
+ } catch {
76
+ throw new Error(
77
+ "OpenAI provider requires the openai package. Install with: npm install openai"
78
+ );
79
+ }
80
+ }
81
+ async embed(text) {
82
+ const client = await this.ensureClient();
83
+ const params = {
84
+ model: this.model,
85
+ input: text
86
+ };
87
+ if (this.model.includes("text-embedding-3")) {
88
+ params.dimensions = this.dimensions;
89
+ }
90
+ const response = await client.embeddings.create(params);
91
+ return response.data[0].embedding;
92
+ }
93
+ async embedBatch(texts) {
94
+ const client = await this.ensureClient();
95
+ const params = {
96
+ model: this.model,
97
+ input: texts
98
+ };
99
+ if (this.model.includes("text-embedding-3")) {
100
+ params.dimensions = this.dimensions;
101
+ }
102
+ const response = await client.embeddings.create(params);
103
+ const sorted = [...response.data].sort(
104
+ (a, b) => a.index - b.index
105
+ );
106
+ return sorted.map((item) => item.embedding);
107
+ }
108
+ };
109
+
110
+ // src/embeddings/cohere.ts
111
+ var DEFAULT_DIMENSIONS2 = {
112
+ "embed-english-v3.0": 1024,
113
+ "embed-multilingual-v3.0": 1024,
114
+ "embed-english-light-v3.0": 384,
115
+ "embed-multilingual-light-v3.0": 384
116
+ };
117
+ var CohereEmbeddings = class {
118
+ client = null;
119
+ model;
120
+ inputType;
121
+ apiKey;
122
+ dimensions;
123
+ constructor(options = {}) {
124
+ const {
125
+ model = "embed-english-v3.0",
126
+ apiKey,
127
+ inputType = "search_query"
128
+ } = options;
129
+ this.model = model;
130
+ this.inputType = inputType;
131
+ this.apiKey = apiKey;
132
+ this.dimensions = DEFAULT_DIMENSIONS2[model] ?? 1024;
133
+ }
134
+ async ensureClient() {
135
+ if (this.client) {
136
+ return this.client;
137
+ }
138
+ try {
139
+ const mod = await import('cohere-ai');
140
+ const CohereClient = mod?.CohereClient ?? mod?.default?.CohereClient ?? mod?.default;
141
+ if (!CohereClient) {
142
+ throw new Error("CohereClient export not found");
143
+ }
144
+ this.client = new CohereClient({ token: this.apiKey });
145
+ return this.client;
146
+ } catch {
147
+ throw new Error(
148
+ "Cohere provider requires the cohere-ai package. Install with: npm install cohere-ai"
149
+ );
150
+ }
151
+ }
152
+ async embed(text) {
153
+ const client = await this.ensureClient();
154
+ const response = await client.embed({
155
+ texts: [text],
156
+ model: this.model,
157
+ inputType: this.inputType
158
+ });
159
+ return response.embeddings[0];
160
+ }
161
+ async embedBatch(texts) {
162
+ const client = await this.ensureClient();
163
+ const response = await client.embed({
164
+ texts,
165
+ model: this.model,
166
+ inputType: this.inputType
167
+ });
168
+ return response.embeddings;
169
+ }
170
+ };
171
+
172
+ // src/embeddings/google.ts
173
+ var DEFAULT_DIMENSIONS3 = {
174
+ "text-embedding-004": 768,
175
+ "text-embedding-preview-0815": 768
176
+ };
177
+ var GoogleEmbeddings = class {
178
+ client = null;
179
+ model;
180
+ apiKey;
181
+ dimensions;
182
+ constructor(options = {}) {
183
+ const { model = "text-embedding-004", apiKey } = options;
184
+ this.model = model;
185
+ this.apiKey = apiKey;
186
+ this.dimensions = DEFAULT_DIMENSIONS3[model] ?? 768;
187
+ }
188
+ async ensureClient() {
189
+ if (this.client) {
190
+ return this.client;
191
+ }
192
+ try {
193
+ const mod = await import('@google/generative-ai');
194
+ const GoogleGenerativeAI = mod?.GoogleGenerativeAI ?? mod?.default?.GoogleGenerativeAI ?? mod?.default;
195
+ if (!GoogleGenerativeAI) {
196
+ throw new Error("GoogleGenerativeAI export not found");
197
+ }
198
+ this.client = new GoogleGenerativeAI(this.apiKey || process.env.GOOGLE_API_KEY);
199
+ return this.client;
200
+ } catch {
201
+ throw new Error(
202
+ "Google provider requires @google/generative-ai. Install with: npm install @google/generative-ai"
203
+ );
204
+ }
205
+ }
206
+ async embed(text) {
207
+ const client = await this.ensureClient();
208
+ const model = client.getGenerativeModel({ model: this.model });
209
+ const result = await model.embedContent(text);
210
+ return result.embedding.values;
211
+ }
212
+ async embedBatch(texts) {
213
+ const client = await this.ensureClient();
214
+ const model = client.getGenerativeModel({ model: this.model });
215
+ const results = await Promise.all(
216
+ texts.map((text) => model.embedContent(text))
217
+ );
218
+ return results.map((r) => r.embedding.values);
219
+ }
220
+ };
221
+
222
+ // src/embeddings/index.ts
223
+ function getProvider(name, options = {}) {
224
+ switch (name) {
225
+ case "openai":
226
+ return new OpenAIEmbeddings(options);
227
+ case "cohere":
228
+ return new CohereEmbeddings(options);
229
+ case "google":
230
+ return new GoogleEmbeddings(options);
231
+ default:
232
+ throw new Error(
233
+ `Unknown provider: ${name}. Available: openai, cohere, google`
234
+ );
235
+ }
236
+ }
237
+
238
+ // src/scoring.ts
239
+ var CosineSimilarity = class {
240
+ compute(a, b) {
241
+ if (a.length !== b.length) {
242
+ throw new Error(`Vector dimensions must match: ${a.length} !== ${b.length}`);
243
+ }
244
+ let dotProduct = 0;
245
+ let normA = 0;
246
+ let normB = 0;
247
+ for (let i = 0; i < a.length; i++) {
248
+ dotProduct += a[i] * b[i];
249
+ normA += a[i] * a[i];
250
+ normB += b[i] * b[i];
251
+ }
252
+ normA = Math.sqrt(normA);
253
+ normB = Math.sqrt(normB);
254
+ if (normA === 0 || normB === 0) {
255
+ return 0;
256
+ }
257
+ return dotProduct / (normA * normB);
258
+ }
259
+ };
260
+ var EuclideanSimilarity = class {
261
+ compute(a, b) {
262
+ if (a.length !== b.length) {
263
+ throw new Error(`Vector dimensions must match: ${a.length} !== ${b.length}`);
264
+ }
265
+ let sumSquares = 0;
266
+ for (let i = 0; i < a.length; i++) {
267
+ const diff = a[i] - b[i];
268
+ sumSquares += diff * diff;
269
+ }
270
+ const distance = Math.sqrt(sumSquares);
271
+ return 1 / (1 + distance);
272
+ }
273
+ };
274
+ var DotProductSimilarity = class {
275
+ compute(a, b) {
276
+ if (a.length !== b.length) {
277
+ throw new Error(`Vector dimensions must match: ${a.length} !== ${b.length}`);
278
+ }
279
+ let dotProduct = 0;
280
+ for (let i = 0; i < a.length; i++) {
281
+ dotProduct += a[i] * b[i];
282
+ }
283
+ return dotProduct;
284
+ }
285
+ };
286
+ var PriorityScoring = class {
287
+ maxScore;
288
+ constructor(maxScore = 1) {
289
+ this.maxScore = maxScore;
290
+ }
291
+ score(similarity, tool) {
292
+ const priority = tool.metadata.priority ?? 1;
293
+ const boosted = similarity * priority;
294
+ return Math.min(boosted, this.maxScore);
295
+ }
296
+ };
297
+ var WeightedScoring = class {
298
+ similarityWeight;
299
+ priorityWeight;
300
+ maxScore;
301
+ constructor(similarityWeight = 0.8, priorityWeight = 0.2, maxScore = 1) {
302
+ this.similarityWeight = similarityWeight;
303
+ this.priorityWeight = priorityWeight;
304
+ this.maxScore = maxScore;
305
+ }
306
+ score(similarity, tool) {
307
+ const priority = tool.metadata.priority ?? 1;
308
+ const normalizedPriority = Math.min(priority / 2, 1);
309
+ const weighted = this.similarityWeight * similarity + this.priorityWeight * normalizedPriority;
310
+ return Math.min(weighted, this.maxScore);
311
+ }
312
+ };
313
+ var TagBoostScoring = class {
314
+ boostTags;
315
+ boostFactor;
316
+ maxScore;
317
+ constructor(boostTags = [], boostFactor = 1.5, maxScore = 1) {
318
+ this.boostTags = new Set(boostTags);
319
+ this.boostFactor = boostFactor;
320
+ this.maxScore = maxScore;
321
+ }
322
+ score(similarity, tool) {
323
+ const toolTags = new Set(tool.metadata.tags ?? []);
324
+ const hasMatchingTag = [...toolTags].some((tag) => this.boostTags.has(tag));
325
+ const boosted = hasMatchingTag ? similarity * this.boostFactor : similarity;
326
+ return Math.min(boosted, this.maxScore);
327
+ }
328
+ };
329
+ var CompositeScoring = class {
330
+ scorers;
331
+ constructor(scorers) {
332
+ this.scorers = scorers;
333
+ }
334
+ score(similarity, tool) {
335
+ let currentScore = similarity;
336
+ for (const scorer of this.scorers) {
337
+ currentScore = scorer.score(currentScore, tool);
338
+ }
339
+ return currentScore;
340
+ }
341
+ };
342
+ var DEFAULT_SIMILARITY = new CosineSimilarity();
343
+ var DEFAULT_SCORING = new PriorityScoring();
344
+
345
+ // src/store.ts
346
+ var VectorStore = class {
347
+ tools = [];
348
+ embeddings = [];
349
+ /**
350
+ * Add a tool with its embedding to the store
351
+ */
352
+ add(tool, embedding) {
353
+ tool.embedding = embedding;
354
+ this.tools.push(tool);
355
+ this.embeddings.push(embedding);
356
+ }
357
+ /**
358
+ * Add multiple tools with embeddings
359
+ */
360
+ addBatch(tools, embeddings) {
361
+ for (let i = 0; i < tools.length; i++) {
362
+ this.add(tools[i], embeddings[i]);
363
+ }
364
+ }
365
+ /**
366
+ * Search for similar tools
367
+ *
368
+ * @param queryEmbedding - The query embedding vector
369
+ * @param topK - Maximum number of results
370
+ * @param threshold - Minimum score to include
371
+ * @param similarityFn - Custom similarity function (defaults to cosine)
372
+ * @param scoringFn - Custom scoring function (defaults to priority scoring)
373
+ */
374
+ search(queryEmbedding, topK = 5, threshold = 0, similarityFn, scoringFn) {
375
+ if (this.tools.length === 0) {
376
+ return [];
377
+ }
378
+ const simFn = similarityFn ?? DEFAULT_SIMILARITY;
379
+ const scoreFn = scoringFn ?? DEFAULT_SCORING;
380
+ const matches = [];
381
+ for (let i = 0; i < this.tools.length; i++) {
382
+ const tool = this.tools[i];
383
+ const embedding = this.embeddings[i];
384
+ const similarity = simFn.compute(queryEmbedding, embedding);
385
+ const finalScore = scoreFn.score(similarity, tool);
386
+ if (finalScore >= threshold) {
387
+ matches.push({ tool, score: finalScore });
388
+ }
389
+ }
390
+ matches.sort((a, b) => b.score - a.score);
391
+ return matches.slice(0, topK);
392
+ }
393
+ /**
394
+ * Remove a tool by name
395
+ */
396
+ remove(toolName) {
397
+ const index = this.tools.findIndex((t) => t.name === toolName);
398
+ if (index !== -1) {
399
+ this.tools.splice(index, 1);
400
+ this.embeddings.splice(index, 1);
401
+ return true;
402
+ }
403
+ return false;
404
+ }
405
+ /**
406
+ * Remove all tools from the store
407
+ */
408
+ clear() {
409
+ this.tools = [];
410
+ this.embeddings = [];
411
+ }
412
+ /**
413
+ * Get a tool by name
414
+ */
415
+ get(toolName) {
416
+ return this.tools.find((t) => t.name === toolName);
417
+ }
418
+ /**
419
+ * Number of tools in the store
420
+ */
421
+ get size() {
422
+ return this.tools.length;
423
+ }
424
+ /**
425
+ * Check if a tool exists by name
426
+ */
427
+ has(toolName) {
428
+ return this.tools.some((t) => t.name === toolName);
429
+ }
430
+ /**
431
+ * Get all tools
432
+ */
433
+ getAll() {
434
+ return [...this.tools];
435
+ }
436
+ };
437
+
438
+ // src/formatters.ts
439
+ var RawFormatter = class {
440
+ name = "raw";
441
+ format(tool) {
442
+ return tool.schema;
443
+ }
444
+ };
445
+ var OpenAIFormatter = class {
446
+ name = "openai";
447
+ format(tool) {
448
+ return {
449
+ type: "function",
450
+ function: tool.schema
451
+ };
452
+ }
453
+ };
454
+ var AnthropicFormatter = class {
455
+ name = "anthropic";
456
+ format(tool) {
457
+ return {
458
+ name: tool.schema.name,
459
+ description: tool.schema.description,
460
+ input_schema: tool.schema.parameters
461
+ };
462
+ }
463
+ };
464
+ var GeminiFormatter = class {
465
+ name = "gemini";
466
+ format(tool) {
467
+ return {
468
+ name: tool.schema.name,
469
+ description: tool.schema.description,
470
+ parameters: tool.schema.parameters
471
+ };
472
+ }
473
+ };
474
+ var MistralFormatter = class {
475
+ name = "mistral";
476
+ format(tool) {
477
+ return {
478
+ type: "function",
479
+ function: {
480
+ name: tool.schema.name,
481
+ description: tool.schema.description,
482
+ parameters: tool.schema.parameters
483
+ }
484
+ };
485
+ }
486
+ };
487
+ var LlamaFormatter = class {
488
+ name = "llama";
489
+ format(tool) {
490
+ return {
491
+ type: "function",
492
+ function: {
493
+ name: tool.schema.name,
494
+ description: tool.schema.description,
495
+ parameters: tool.schema.parameters
496
+ }
497
+ };
498
+ }
499
+ };
500
+ var CohereFormatter = class {
501
+ name = "cohere";
502
+ format(tool) {
503
+ const params = tool.schema.parameters;
504
+ const properties = params.properties;
505
+ const required = new Set(params.required);
506
+ const parameterDefinitions = {};
507
+ for (const [name, prop] of Object.entries(properties)) {
508
+ parameterDefinitions[name] = {
509
+ type: prop.type ?? "string",
510
+ description: prop.description ?? "",
511
+ required: required.has(name)
512
+ };
513
+ }
514
+ return {
515
+ name: tool.schema.name,
516
+ description: tool.schema.description,
517
+ parameter_definitions: parameterDefinitions
518
+ };
519
+ }
520
+ };
521
+ var MinimalFormatter = class {
522
+ name = "minimal";
523
+ format(tool) {
524
+ return {
525
+ name: tool.schema.name,
526
+ description: tool.schema.description
527
+ };
528
+ }
529
+ };
530
+ var VerboseFormatter = class {
531
+ name = "verbose";
532
+ format(tool) {
533
+ return {
534
+ name: tool.name,
535
+ schema: tool.schema,
536
+ score: tool.score,
537
+ hasHandler: tool.handler !== void 0
538
+ };
539
+ }
540
+ };
541
+ var formatters = /* @__PURE__ */ new Map();
542
+ function registerFormatter(formatter) {
543
+ formatters.set(formatter.name, formatter);
544
+ }
545
+ function unregisterFormatter(name) {
546
+ return formatters.delete(name);
547
+ }
548
+ function getFormatter(name) {
549
+ const formatter = formatters.get(name);
550
+ if (!formatter) {
551
+ const available = Array.from(formatters.keys()).join(", ");
552
+ throw new Error(`Unknown formatter '${name}'. Available: ${available}`);
553
+ }
554
+ return formatter;
555
+ }
556
+ function listFormatters() {
557
+ return Array.from(formatters.keys());
558
+ }
559
+ function hasFormatter(name) {
560
+ return formatters.has(name);
561
+ }
562
+ function formatTools(tools, formatter) {
563
+ const fmt = typeof formatter === "string" ? getFormatter(formatter) : formatter;
564
+ if (fmt.formatBatch) {
565
+ return fmt.formatBatch(tools);
566
+ }
567
+ return tools.map((tool) => fmt.format(tool));
568
+ }
569
+ function registerDefaults() {
570
+ const defaults = [
571
+ new RawFormatter(),
572
+ new OpenAIFormatter(),
573
+ new AnthropicFormatter(),
574
+ new GeminiFormatter(),
575
+ new MistralFormatter(),
576
+ new LlamaFormatter(),
577
+ new CohereFormatter(),
578
+ new MinimalFormatter(),
579
+ new VerboseFormatter()
580
+ ];
581
+ for (const formatter of defaults) {
582
+ registerFormatter(formatter);
583
+ }
584
+ }
585
+ registerDefaults();
586
+
587
+ // src/hooks.ts
588
+ var HookType = /* @__PURE__ */ ((HookType2) => {
589
+ HookType2["PRE_REGISTER"] = "pre_register";
590
+ HookType2["POST_REGISTER"] = "post_register";
591
+ HookType2["PRE_EMBED"] = "pre_embed";
592
+ HookType2["POST_EMBED"] = "post_embed";
593
+ HookType2["PRE_RESOLVE"] = "pre_resolve";
594
+ HookType2["POST_RESOLVE"] = "post_resolve";
595
+ HookType2["PRE_SEARCH"] = "pre_search";
596
+ HookType2["POST_SEARCH"] = "post_search";
597
+ HookType2["PRE_EXECUTE"] = "pre_execute";
598
+ HookType2["POST_EXECUTE"] = "post_execute";
599
+ return HookType2;
600
+ })(HookType || {});
601
+ function createContext(hookType, data = {}) {
602
+ return {
603
+ hookType,
604
+ data,
605
+ cancelled: false,
606
+ error: null
607
+ };
608
+ }
609
+ function cancelContext(context, reason) {
610
+ context.cancelled = true;
611
+ if (reason) {
612
+ context.data.cancelReason = reason;
613
+ }
614
+ }
615
+ function setContextError(context, error) {
616
+ context.error = error;
617
+ context.cancelled = true;
618
+ }
619
+ function createHook(hookType, fn, priority = 0) {
620
+ return {
621
+ hookType,
622
+ priority,
623
+ execute: fn
624
+ };
625
+ }
626
+ var HookRegistry = class {
627
+ hooks = /* @__PURE__ */ new Map();
628
+ constructor() {
629
+ for (const type of Object.values(HookType)) {
630
+ this.hooks.set(type, []);
631
+ }
632
+ }
633
+ /**
634
+ * Register a hook
635
+ */
636
+ register(hook) {
637
+ const hooks = this.hooks.get(hook.hookType) ?? [];
638
+ hooks.push(hook);
639
+ hooks.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
640
+ this.hooks.set(hook.hookType, hooks);
641
+ }
642
+ /**
643
+ * Register a function as a hook
644
+ */
645
+ on(hookType, fn, priority = 0) {
646
+ const hook = createHook(hookType, fn, priority);
647
+ this.register(hook);
648
+ return hook;
649
+ }
650
+ /**
651
+ * Unregister a hook
652
+ */
653
+ unregister(hook) {
654
+ const hooks = this.hooks.get(hook.hookType) ?? [];
655
+ const index = hooks.indexOf(hook);
656
+ if (index !== -1) {
657
+ hooks.splice(index, 1);
658
+ return true;
659
+ }
660
+ return false;
661
+ }
662
+ /**
663
+ * Clear hooks
664
+ */
665
+ clear(hookType) {
666
+ if (hookType) {
667
+ this.hooks.set(hookType, []);
668
+ } else {
669
+ for (const type of Object.values(HookType)) {
670
+ this.hooks.set(type, []);
671
+ }
672
+ }
673
+ }
674
+ /**
675
+ * Get all hooks for a type
676
+ */
677
+ getHooks(hookType) {
678
+ return [...this.hooks.get(hookType) ?? []];
679
+ }
680
+ /**
681
+ * Check if any hooks are registered for a type
682
+ */
683
+ hasHooks(hookType) {
684
+ return (this.hooks.get(hookType) ?? []).length > 0;
685
+ }
686
+ /**
687
+ * Run all hooks of a given type
688
+ */
689
+ async run(hookType, context) {
690
+ const hooks = this.hooks.get(hookType) ?? [];
691
+ for (const hook of hooks) {
692
+ if (context.cancelled) {
693
+ break;
694
+ }
695
+ try {
696
+ const result = hook.execute(context);
697
+ if (result instanceof Promise) {
698
+ context = await result;
699
+ } else {
700
+ context = result;
701
+ }
702
+ } catch (error) {
703
+ setContextError(context, error);
704
+ break;
705
+ }
706
+ }
707
+ return context;
708
+ }
709
+ };
710
+ var LoggingHook = class {
711
+ hookType;
712
+ priority = 0;
713
+ logger;
714
+ constructor(hookType, logger) {
715
+ this.hookType = hookType;
716
+ this.logger = logger ?? console.log;
717
+ }
718
+ execute(context) {
719
+ this.logger(`[${this.hookType}] data=${JSON.stringify(context.data)}`);
720
+ return context;
721
+ }
722
+ };
723
+ var TimingHook = class {
724
+ hookType;
725
+ priority = 0;
726
+ preHook;
727
+ postHook;
728
+ timingKey;
729
+ constructor(preHook, postHook, timingKey = "timing") {
730
+ this.preHook = preHook;
731
+ this.postHook = postHook;
732
+ this.hookType = preHook;
733
+ this.timingKey = timingKey;
734
+ }
735
+ execute(context) {
736
+ if (context.hookType === this.preHook) {
737
+ context.data[`${this.timingKey}Start`] = performance.now();
738
+ } else if (context.hookType === this.postHook) {
739
+ const start = context.data[`${this.timingKey}Start`];
740
+ if (start) {
741
+ const duration = performance.now() - start;
742
+ context.data[`${this.timingKey}Ms`] = duration;
743
+ }
744
+ }
745
+ return context;
746
+ }
747
+ };
748
+ var MetricsHook = class {
749
+ hookType;
750
+ priority = 0;
751
+ count = 0;
752
+ errors = 0;
753
+ constructor(hookType) {
754
+ this.hookType = hookType;
755
+ }
756
+ execute(context) {
757
+ this.count++;
758
+ if (context.error) {
759
+ this.errors++;
760
+ }
761
+ return context;
762
+ }
763
+ reset() {
764
+ this.count = 0;
765
+ this.errors = 0;
766
+ }
767
+ };
768
+ var CachingHook = class {
769
+ hookType = "pre_resolve" /* PRE_RESOLVE */;
770
+ priority = 100;
771
+ // Run early to check cache
772
+ cache = /* @__PURE__ */ new Map();
773
+ maxSize;
774
+ constructor(maxSize = 100) {
775
+ this.maxSize = maxSize;
776
+ }
777
+ execute(context) {
778
+ if (context.hookType === "pre_resolve" /* PRE_RESOLVE */) {
779
+ const query = context.data.query;
780
+ if (query && this.cache.has(query)) {
781
+ context.data.cachedResults = this.cache.get(query);
782
+ context.data.cacheHit = true;
783
+ }
784
+ } else if (context.hookType === "post_resolve" /* POST_RESOLVE */) {
785
+ const query = context.data.query;
786
+ const results = context.data.results;
787
+ if (query && results && !this.cache.has(query)) {
788
+ if (this.cache.size >= this.maxSize) {
789
+ const firstKey = this.cache.keys().next().value;
790
+ if (firstKey) {
791
+ this.cache.delete(firstKey);
792
+ }
793
+ }
794
+ this.cache.set(query, results);
795
+ }
796
+ }
797
+ return context;
798
+ }
799
+ clearCache() {
800
+ this.cache.clear();
801
+ }
802
+ get cacheSize() {
803
+ return this.cache.size;
804
+ }
805
+ };
806
+
807
+ // src/validators.ts
808
+ function createValidationResult(valid, errors = [], warnings = []) {
809
+ return { valid, errors, warnings };
810
+ }
811
+ function mergeValidationResults(a, b) {
812
+ return {
813
+ valid: a.valid && b.valid,
814
+ errors: [...a.errors, ...b.errors],
815
+ warnings: [...a.warnings, ...b.warnings]
816
+ };
817
+ }
818
+ var ValidationError = class extends Error {
819
+ result;
820
+ constructor(result) {
821
+ super(`Validation failed: ${result.errors.join(", ")}`);
822
+ this.name = "ValidationError";
823
+ this.result = result;
824
+ }
825
+ };
826
+ var ALLOWED_TYPES = /* @__PURE__ */ new Set([
827
+ "string",
828
+ "integer",
829
+ "number",
830
+ "boolean",
831
+ "array",
832
+ "object",
833
+ "null"
834
+ ]);
835
+ var ToolSchemaValidator = class {
836
+ options;
837
+ constructor(options = {}) {
838
+ this.options = {
839
+ requireDescription: options.requireDescription ?? true,
840
+ requireParameters: options.requireParameters ?? false,
841
+ minDescriptionLength: options.minDescriptionLength ?? 0,
842
+ maxDescriptionLength: options.maxDescriptionLength ?? 1e3
843
+ };
844
+ }
845
+ validate(tool) {
846
+ const errors = [];
847
+ const warnings = [];
848
+ if (!tool.name) {
849
+ errors.push("Tool name is required");
850
+ } else if (!/^[\w-]+$/.test(tool.name)) {
851
+ warnings.push(`Tool name '${tool.name}' contains special characters`);
852
+ }
853
+ if (this.options.requireDescription && !tool.description) {
854
+ errors.push("Tool description is required");
855
+ } else if (tool.description) {
856
+ if (tool.description.length < this.options.minDescriptionLength) {
857
+ errors.push(
858
+ `Description must be at least ${this.options.minDescriptionLength} characters`
859
+ );
860
+ }
861
+ if (tool.description.length > this.options.maxDescriptionLength) {
862
+ errors.push(
863
+ `Description must be at most ${this.options.maxDescriptionLength} characters`
864
+ );
865
+ }
866
+ }
867
+ if (this.options.requireParameters && Object.keys(tool.parameters).length === 0) {
868
+ errors.push("Tool parameters are required");
869
+ }
870
+ for (const [name, param] of Object.entries(tool.parameters)) {
871
+ if (param.type && !ALLOWED_TYPES.has(param.type)) {
872
+ errors.push(`Parameter '${name}' has invalid type '${param.type}'`);
873
+ }
874
+ }
875
+ return createValidationResult(errors.length === 0, errors, warnings);
876
+ }
877
+ };
878
+ var ParameterValidator = class {
879
+ options;
880
+ constructor(options = {}) {
881
+ this.options = {
882
+ strict: options.strict ?? false,
883
+ allowExtra: options.allowExtra ?? true
884
+ };
885
+ }
886
+ validate(data) {
887
+ const { tool, params } = data;
888
+ const errors = [];
889
+ const warnings = [];
890
+ if (!tool) {
891
+ errors.push("Tool is required for parameter validation");
892
+ return createValidationResult(false, errors, warnings);
893
+ }
894
+ const properties = tool.parameters;
895
+ if (this.options.strict) {
896
+ for (const [name, param] of Object.entries(properties)) {
897
+ if (param.required !== false && !(name in params)) {
898
+ errors.push(`Missing required parameter: ${name}`);
899
+ }
900
+ }
901
+ }
902
+ for (const [name, value] of Object.entries(params)) {
903
+ if (!(name in properties)) {
904
+ if (!this.options.allowExtra) {
905
+ errors.push(`Unknown parameter: ${name}`);
906
+ } else {
907
+ warnings.push(`Extra parameter provided: ${name}`);
908
+ }
909
+ continue;
910
+ }
911
+ const param = properties[name];
912
+ const typeError = this.checkType(name, value, param.type);
913
+ if (typeError) {
914
+ errors.push(typeError);
915
+ }
916
+ }
917
+ return createValidationResult(errors.length === 0, errors, warnings);
918
+ }
919
+ checkType(name, value, expectedType) {
920
+ if (!expectedType) return null;
921
+ const typeMap = {
922
+ string: (v) => typeof v === "string",
923
+ integer: (v) => Number.isInteger(v),
924
+ number: (v) => typeof v === "number",
925
+ boolean: (v) => typeof v === "boolean",
926
+ array: (v) => Array.isArray(v),
927
+ object: (v) => typeof v === "object" && v !== null && !Array.isArray(v),
928
+ null: (v) => v === null
929
+ };
930
+ const checker = typeMap[expectedType];
931
+ if (checker && !checker(value)) {
932
+ return `Parameter '${name}' expected ${expectedType}, got ${typeof value}`;
933
+ }
934
+ return null;
935
+ }
936
+ };
937
+ var ResultValidator = class {
938
+ options;
939
+ constructor(options = {}) {
940
+ this.options = {
941
+ strict: options.strict ?? false
942
+ };
943
+ }
944
+ validate(data) {
945
+ const { tool, result } = data;
946
+ const errors = [];
947
+ const warnings = [];
948
+ if (!tool) {
949
+ errors.push("Tool is required for result validation");
950
+ return createValidationResult(false, errors, warnings);
951
+ }
952
+ if (tool.returns) {
953
+ const expectedType = tool.returns.type;
954
+ const typeError = this.checkReturnType(result, expectedType);
955
+ if (typeError) {
956
+ if (this.options.strict) {
957
+ errors.push(typeError);
958
+ } else {
959
+ warnings.push(typeError);
960
+ }
961
+ }
962
+ }
963
+ return createValidationResult(errors.length === 0, errors, warnings);
964
+ }
965
+ checkReturnType(value, expectedType) {
966
+ if (!expectedType) return null;
967
+ const typeMap = {
968
+ string: (v) => typeof v === "string",
969
+ integer: (v) => Number.isInteger(v),
970
+ number: (v) => typeof v === "number",
971
+ boolean: (v) => typeof v === "boolean",
972
+ array: (v) => Array.isArray(v),
973
+ object: (v) => typeof v === "object" && v !== null && !Array.isArray(v),
974
+ null: (v) => v === null
975
+ };
976
+ const checker = typeMap[expectedType];
977
+ if (checker && !checker(value)) {
978
+ return `Result expected ${expectedType}, got ${typeof value}`;
979
+ }
980
+ return null;
981
+ }
982
+ };
983
+ var EmbeddingValidator = class {
984
+ options;
985
+ constructor(options = {}) {
986
+ this.options = options;
987
+ }
988
+ validate(embedding) {
989
+ const errors = [];
990
+ const warnings = [];
991
+ if (!Array.isArray(embedding)) {
992
+ errors.push("Embedding must be an array");
993
+ return createValidationResult(false, errors, warnings);
994
+ }
995
+ if (embedding.length === 0) {
996
+ errors.push("Embedding cannot be empty");
997
+ return createValidationResult(false, errors, warnings);
998
+ }
999
+ if (this.options.expectedDimensions !== void 0 && embedding.length !== this.options.expectedDimensions) {
1000
+ errors.push(
1001
+ `Embedding dimensions mismatch: expected ${this.options.expectedDimensions}, got ${embedding.length}`
1002
+ );
1003
+ }
1004
+ for (let i = 0; i < embedding.length; i++) {
1005
+ if (typeof embedding[i] !== "number") {
1006
+ errors.push(`Embedding value at index ${i} is not numeric`);
1007
+ break;
1008
+ }
1009
+ }
1010
+ if (this.options.checkNormalization && errors.length === 0) {
1011
+ let sumSquares = 0;
1012
+ for (const val of embedding) {
1013
+ sumSquares += val * val;
1014
+ }
1015
+ const norm = Math.sqrt(sumSquares);
1016
+ if (Math.abs(norm - 1) > 0.01) {
1017
+ warnings.push(`Embedding is not normalized (norm=${norm.toFixed(4)})`);
1018
+ }
1019
+ }
1020
+ return createValidationResult(errors.length === 0, errors, warnings);
1021
+ }
1022
+ };
1023
+ var CompositeValidator = class {
1024
+ validators;
1025
+ constructor(validators) {
1026
+ this.validators = validators;
1027
+ }
1028
+ validate(data) {
1029
+ let result = createValidationResult(true);
1030
+ for (const validator of this.validators) {
1031
+ const subResult = validator.validate(data);
1032
+ result = mergeValidationResults(result, subResult);
1033
+ }
1034
+ return result;
1035
+ }
1036
+ };
1037
+ var ValidatorRegistry = class {
1038
+ schemaValidators = [];
1039
+ parameterValidators = [];
1040
+ resultValidators = [];
1041
+ embeddingValidators = [];
1042
+ addSchemaValidator(validator) {
1043
+ this.schemaValidators.push(validator);
1044
+ }
1045
+ addParameterValidator(validator) {
1046
+ this.parameterValidators.push(validator);
1047
+ }
1048
+ addResultValidator(validator) {
1049
+ this.resultValidators.push(validator);
1050
+ }
1051
+ addEmbeddingValidator(validator) {
1052
+ this.embeddingValidators.push(validator);
1053
+ }
1054
+ validateTool(tool) {
1055
+ let result = createValidationResult(true);
1056
+ for (const validator of this.schemaValidators) {
1057
+ const subResult = validator.validate(tool);
1058
+ result = mergeValidationResults(result, subResult);
1059
+ }
1060
+ return result;
1061
+ }
1062
+ validateParams(tool, params) {
1063
+ let result = createValidationResult(true);
1064
+ for (const validator of this.parameterValidators) {
1065
+ const subResult = validator.validate({ tool, params });
1066
+ result = mergeValidationResults(result, subResult);
1067
+ }
1068
+ return result;
1069
+ }
1070
+ validateResult(tool, resultValue) {
1071
+ let result = createValidationResult(true);
1072
+ for (const validator of this.resultValidators) {
1073
+ const subResult = validator.validate({ tool, result: resultValue });
1074
+ result = mergeValidationResults(result, subResult);
1075
+ }
1076
+ return result;
1077
+ }
1078
+ validateEmbedding(embedding) {
1079
+ let result = createValidationResult(true);
1080
+ for (const validator of this.embeddingValidators) {
1081
+ const subResult = validator.validate(embedding);
1082
+ result = mergeValidationResults(result, subResult);
1083
+ }
1084
+ return result;
1085
+ }
1086
+ clear() {
1087
+ this.schemaValidators = [];
1088
+ this.parameterValidators = [];
1089
+ this.resultValidators = [];
1090
+ this.embeddingValidators = [];
1091
+ }
1092
+ };
1093
+ function createStrictValidator() {
1094
+ const registry = new ValidatorRegistry();
1095
+ registry.addSchemaValidator(
1096
+ new ToolSchemaValidator({
1097
+ requireDescription: true,
1098
+ minDescriptionLength: 10
1099
+ })
1100
+ );
1101
+ registry.addParameterValidator(new ParameterValidator({ strict: true }));
1102
+ registry.addResultValidator(new ResultValidator({ strict: true }));
1103
+ return registry;
1104
+ }
1105
+ function createLenientValidator() {
1106
+ const registry = new ValidatorRegistry();
1107
+ registry.addSchemaValidator(
1108
+ new ToolSchemaValidator({
1109
+ requireDescription: false,
1110
+ minDescriptionLength: 0
1111
+ })
1112
+ );
1113
+ registry.addParameterValidator(
1114
+ new ParameterValidator({
1115
+ strict: false,
1116
+ allowExtra: true
1117
+ })
1118
+ );
1119
+ registry.addResultValidator(new ResultValidator({ strict: false }));
1120
+ return registry;
1121
+ }
1122
+
1123
+ // src/sis.ts
1124
+ var SIS = class {
1125
+ _embeddings;
1126
+ _vectorStore;
1127
+ _pendingTools;
1128
+ _defaultTopK;
1129
+ _defaultThreshold;
1130
+ _initialized;
1131
+ _remoteUrl;
1132
+ _projectId;
1133
+ // Customization systems
1134
+ _similarity;
1135
+ _scoring;
1136
+ _hooks;
1137
+ _validators;
1138
+ _validateOnRegister;
1139
+ _validateOnExecute;
1140
+ constructor(options = {}) {
1141
+ const {
1142
+ embeddingProvider = "openai",
1143
+ defaultTopK = 5,
1144
+ defaultThreshold = 0.3,
1145
+ providerOptions = {},
1146
+ similarity,
1147
+ scoring,
1148
+ validators,
1149
+ validateOnRegister = false,
1150
+ validateOnExecute = false
1151
+ } = options;
1152
+ if (typeof embeddingProvider === "string") {
1153
+ this._embeddings = getProvider(embeddingProvider, providerOptions);
1154
+ } else {
1155
+ this._embeddings = embeddingProvider;
1156
+ }
1157
+ this._vectorStore = new VectorStore();
1158
+ this._pendingTools = [];
1159
+ this._defaultTopK = defaultTopK;
1160
+ this._defaultThreshold = defaultThreshold;
1161
+ this._initialized = false;
1162
+ this._remoteUrl = options.remoteUrl;
1163
+ this._projectId = options.projectId;
1164
+ this._similarity = similarity ?? DEFAULT_SIMILARITY;
1165
+ this._scoring = scoring ?? DEFAULT_SCORING;
1166
+ this._hooks = new HookRegistry();
1167
+ this._validators = validators;
1168
+ this._validateOnRegister = validateOnRegister;
1169
+ this._validateOnExecute = validateOnExecute;
1170
+ }
1171
+ // Properties for accessing customization systems
1172
+ /** Get the hook registry for registering middleware */
1173
+ get hooks() {
1174
+ return this._hooks;
1175
+ }
1176
+ /** Get the validator registry */
1177
+ get validators() {
1178
+ return this._validators;
1179
+ }
1180
+ /** Get the current similarity function */
1181
+ get similarity() {
1182
+ return this._similarity;
1183
+ }
1184
+ /** Set a new similarity function */
1185
+ set similarity(fn) {
1186
+ this._similarity = fn;
1187
+ }
1188
+ /** Get the current scoring function */
1189
+ get scoring() {
1190
+ return this._scoring;
1191
+ }
1192
+ /** Set a new scoring function */
1193
+ set scoring(fn) {
1194
+ this._scoring = fn;
1195
+ }
1196
+ /** Register a hook */
1197
+ registerHook(hook) {
1198
+ this._hooks.register(hook);
1199
+ }
1200
+ /** Unregister a hook */
1201
+ unregisterHook(hook) {
1202
+ return this._hooks.unregister(hook);
1203
+ }
1204
+ /**
1205
+ * Register a tool programmatically
1206
+ */
1207
+ register(options) {
1208
+ const tool = {
1209
+ name: options.name,
1210
+ description: options.description,
1211
+ parameters: options.parameters ?? {},
1212
+ semanticHints: options.semanticHints ?? [],
1213
+ examples: options.examples ?? [],
1214
+ handler: options.handler,
1215
+ metadata: options.metadata ?? {}
1216
+ };
1217
+ if (this._validateOnRegister && this._validators) {
1218
+ const result = this._validators.validateTool(tool);
1219
+ if (!result.valid) {
1220
+ throw new ValidationError(result);
1221
+ }
1222
+ }
1223
+ this._pendingTools.push(tool);
1224
+ return tool;
1225
+ }
1226
+ /**
1227
+ * Store (upsert) a tool with a precomputed embedding.
1228
+ *
1229
+ * This bypasses the embedding provider, allowing custom embedding workflows.
1230
+ */
1231
+ store(options) {
1232
+ const tool = {
1233
+ name: options.name,
1234
+ description: options.description,
1235
+ parameters: options.parameters ?? {},
1236
+ semanticHints: options.semanticHints ?? [],
1237
+ examples: options.examples ?? [],
1238
+ handler: options.handler,
1239
+ metadata: options.metadata ?? {}
1240
+ };
1241
+ if (this._validateOnRegister && this._validators) {
1242
+ const result = this._validators.validateTool(tool);
1243
+ if (!result.valid) {
1244
+ throw new ValidationError(result);
1245
+ }
1246
+ }
1247
+ if (this._validators) {
1248
+ const embeddingResult = this._validators.validateEmbedding(options.embedding);
1249
+ if (!embeddingResult.valid) {
1250
+ throw new ValidationError(embeddingResult);
1251
+ }
1252
+ }
1253
+ if (options.embedding.length !== this._embeddings.dimensions) {
1254
+ throw new Error(
1255
+ `Embedding dimensions must match provider: ${options.embedding.length} !== ${this._embeddings.dimensions}`
1256
+ );
1257
+ }
1258
+ if (this._vectorStore.has(tool.name)) {
1259
+ this._vectorStore.remove(tool.name);
1260
+ }
1261
+ this._vectorStore.add(tool, options.embedding);
1262
+ return tool;
1263
+ }
1264
+ /**
1265
+ * Initialize embeddings for all pending tools
1266
+ */
1267
+ async initialize() {
1268
+ if (this._pendingTools.length === 0) {
1269
+ this._initialized = true;
1270
+ return;
1271
+ }
1272
+ let ctx = createContext("pre_embed" /* PRE_EMBED */, { tools: this._pendingTools });
1273
+ ctx = await this._hooks.run("pre_embed" /* PRE_EMBED */, ctx);
1274
+ if (ctx.cancelled) {
1275
+ return;
1276
+ }
1277
+ const texts = this._pendingTools.map(
1278
+ (tool) => buildToolText(
1279
+ tool.name,
1280
+ tool.description,
1281
+ tool.semanticHints,
1282
+ tool.examples
1283
+ )
1284
+ );
1285
+ const embeddings = await this._embeddings.embedBatch(texts);
1286
+ this._vectorStore.addBatch(this._pendingTools, embeddings);
1287
+ ctx = createContext("post_embed" /* POST_EMBED */, {
1288
+ tools: this._pendingTools,
1289
+ embeddings
1290
+ });
1291
+ await this._hooks.run("post_embed" /* POST_EMBED */, ctx);
1292
+ this._pendingTools = [];
1293
+ this._initialized = true;
1294
+ }
1295
+ /**
1296
+ * Resolve tools for a query
1297
+ */
1298
+ async resolve(query, options = {}) {
1299
+ if (!this._initialized) {
1300
+ await this.initialize();
1301
+ }
1302
+ const topK = options.topK ?? this._defaultTopK;
1303
+ const threshold = options.threshold ?? this._defaultThreshold;
1304
+ const format = options.format ?? "raw";
1305
+ let ctx = createContext("pre_resolve" /* PRE_RESOLVE */, {
1306
+ query,
1307
+ topK,
1308
+ threshold,
1309
+ format
1310
+ });
1311
+ ctx = await this._hooks.run("pre_resolve" /* PRE_RESOLVE */, ctx);
1312
+ if (ctx.cancelled) {
1313
+ if (ctx.data.cachedResults) {
1314
+ return ctx.data.cachedResults;
1315
+ }
1316
+ return [];
1317
+ }
1318
+ const finalQuery = ctx.data.query ?? query;
1319
+ const finalTopK = ctx.data.topK ?? topK;
1320
+ const finalThreshold = ctx.data.threshold ?? threshold;
1321
+ if (this._remoteUrl && this._projectId) {
1322
+ const response = await fetch(
1323
+ `${this._remoteUrl}/v1/projects/${this._projectId}/resolve`,
1324
+ {
1325
+ method: "POST",
1326
+ headers: { "Content-Type": "application/json" },
1327
+ body: JSON.stringify({ query: finalQuery, top_k: finalTopK, threshold: finalThreshold })
1328
+ }
1329
+ );
1330
+ if (!response.ok) {
1331
+ throw new Error(`Remote resolution failed: ${response.statusText}`);
1332
+ }
1333
+ const data = await response.json();
1334
+ const results2 = data.results;
1335
+ return this.formatResults(results2, format);
1336
+ }
1337
+ const queryEmbedding = await this._embeddings.embed(finalQuery);
1338
+ let searchCtx = createContext("pre_search" /* PRE_SEARCH */, {
1339
+ query: finalQuery,
1340
+ queryEmbedding,
1341
+ topK: finalTopK,
1342
+ threshold: finalThreshold
1343
+ });
1344
+ searchCtx = await this._hooks.run("pre_search" /* PRE_SEARCH */, searchCtx);
1345
+ const matches = this._vectorStore.search(
1346
+ queryEmbedding,
1347
+ finalTopK,
1348
+ finalThreshold,
1349
+ this._similarity,
1350
+ this._scoring
1351
+ );
1352
+ let postSearchCtx = createContext("post_search" /* POST_SEARCH */, {
1353
+ query: finalQuery,
1354
+ matches
1355
+ });
1356
+ postSearchCtx = await this._hooks.run("post_search" /* POST_SEARCH */, postSearchCtx);
1357
+ const finalMatches = postSearchCtx.data.matches ?? matches;
1358
+ const resolved = finalMatches.map((match) => ({
1359
+ name: match.tool.name,
1360
+ schema: toSchema(match.tool),
1361
+ score: match.score,
1362
+ handler: match.tool.handler
1363
+ }));
1364
+ const results = this.formatResults(resolved, format);
1365
+ let postCtx = createContext("post_resolve" /* POST_RESOLVE */, {
1366
+ query: finalQuery,
1367
+ results,
1368
+ resolved
1369
+ });
1370
+ postCtx = await this._hooks.run("post_resolve" /* POST_RESOLVE */, postCtx);
1371
+ return postCtx.data.results ?? results;
1372
+ }
1373
+ /**
1374
+ * Format results based on format option
1375
+ */
1376
+ formatResults(resolved, format) {
1377
+ if (format === "raw") {
1378
+ return resolved;
1379
+ }
1380
+ if (typeof format === "object" && "format" in format) {
1381
+ return formatTools(resolved, format);
1382
+ }
1383
+ if (typeof format === "string") {
1384
+ if (hasFormatter(format)) {
1385
+ return formatTools(resolved, format);
1386
+ }
1387
+ if (format === "openai") {
1388
+ return resolved.map((r) => ({
1389
+ type: "function",
1390
+ function: r.schema
1391
+ }));
1392
+ }
1393
+ if (format === "anthropic") {
1394
+ return resolved.map((r) => ({
1395
+ name: r.schema.name,
1396
+ description: r.schema.description,
1397
+ input_schema: r.schema.parameters
1398
+ }));
1399
+ }
1400
+ throw new Error(`Unknown format: ${format}`);
1401
+ }
1402
+ return resolved;
1403
+ }
1404
+ /**
1405
+ * Resolve the single best matching tool
1406
+ */
1407
+ async resolveOne(query, threshold) {
1408
+ const results = await this.resolve(query, { topK: 1, threshold });
1409
+ return results.length > 0 ? results[0] : null;
1410
+ }
1411
+ /**
1412
+ * Get a registered tool by name
1413
+ */
1414
+ getTool(name) {
1415
+ return this._vectorStore.get(name);
1416
+ }
1417
+ /**
1418
+ * List all registered tool names
1419
+ */
1420
+ listTools() {
1421
+ return this._vectorStore.getAll().map((t) => t.name);
1422
+ }
1423
+ /**
1424
+ * Number of registered tools
1425
+ */
1426
+ get toolCount() {
1427
+ return this._vectorStore.size + this._pendingTools.length;
1428
+ }
1429
+ /**
1430
+ * Execute a tool by name
1431
+ */
1432
+ async execute(toolName, params) {
1433
+ const tool = this._vectorStore.get(toolName);
1434
+ if (!tool) {
1435
+ throw new Error(`Tool not found: ${toolName}`);
1436
+ }
1437
+ if (!tool.handler) {
1438
+ throw new Error(`Tool has no handler: ${toolName}`);
1439
+ }
1440
+ let ctx = createContext("pre_execute" /* PRE_EXECUTE */, {
1441
+ tool,
1442
+ toolName,
1443
+ params
1444
+ });
1445
+ ctx = await this._hooks.run("pre_execute" /* PRE_EXECUTE */, ctx);
1446
+ if (ctx.cancelled) {
1447
+ if (ctx.error) {
1448
+ throw ctx.error;
1449
+ }
1450
+ return null;
1451
+ }
1452
+ if (this._validateOnExecute && this._validators) {
1453
+ const paramsResult = this._validators.validateParams(tool, params);
1454
+ if (!paramsResult.valid) {
1455
+ throw new ValidationError(paramsResult);
1456
+ }
1457
+ }
1458
+ const result = await tool.handler(params);
1459
+ if (this._validateOnExecute && this._validators) {
1460
+ const resultValidation = this._validators.validateResult(tool, result);
1461
+ if (!resultValidation.valid) {
1462
+ throw new ValidationError(resultValidation);
1463
+ }
1464
+ }
1465
+ let postCtx = createContext("post_execute" /* POST_EXECUTE */, {
1466
+ tool,
1467
+ toolName,
1468
+ params,
1469
+ result
1470
+ });
1471
+ postCtx = await this._hooks.run("post_execute" /* POST_EXECUTE */, postCtx);
1472
+ return postCtx.data.result ?? result;
1473
+ }
1474
+ };
1475
+
1476
+ exports.AnthropicFormatter = AnthropicFormatter;
1477
+ exports.CachingHook = CachingHook;
1478
+ exports.CohereEmbeddings = CohereEmbeddings;
1479
+ exports.CohereFormatter = CohereFormatter;
1480
+ exports.CompositeScoring = CompositeScoring;
1481
+ exports.CompositeValidator = CompositeValidator;
1482
+ exports.CosineSimilarity = CosineSimilarity;
1483
+ exports.DEFAULT_SCORING = DEFAULT_SCORING;
1484
+ exports.DEFAULT_SIMILARITY = DEFAULT_SIMILARITY;
1485
+ exports.DotProductSimilarity = DotProductSimilarity;
1486
+ exports.EmbeddingValidator = EmbeddingValidator;
1487
+ exports.EuclideanSimilarity = EuclideanSimilarity;
1488
+ exports.GeminiFormatter = GeminiFormatter;
1489
+ exports.GoogleEmbeddings = GoogleEmbeddings;
1490
+ exports.HookRegistry = HookRegistry;
1491
+ exports.HookType = HookType;
1492
+ exports.LlamaFormatter = LlamaFormatter;
1493
+ exports.LoggingHook = LoggingHook;
1494
+ exports.MetricsHook = MetricsHook;
1495
+ exports.MinimalFormatter = MinimalFormatter;
1496
+ exports.MistralFormatter = MistralFormatter;
1497
+ exports.OpenAIEmbeddings = OpenAIEmbeddings;
1498
+ exports.OpenAIFormatter = OpenAIFormatter;
1499
+ exports.ParameterValidator = ParameterValidator;
1500
+ exports.PriorityScoring = PriorityScoring;
1501
+ exports.RawFormatter = RawFormatter;
1502
+ exports.ResultValidator = ResultValidator;
1503
+ exports.SIS = SIS;
1504
+ exports.TagBoostScoring = TagBoostScoring;
1505
+ exports.TimingHook = TimingHook;
1506
+ exports.ToolSchemaValidator = ToolSchemaValidator;
1507
+ exports.ValidationError = ValidationError;
1508
+ exports.ValidatorRegistry = ValidatorRegistry;
1509
+ exports.VectorStore = VectorStore;
1510
+ exports.VerboseFormatter = VerboseFormatter;
1511
+ exports.WeightedScoring = WeightedScoring;
1512
+ exports.cancelContext = cancelContext;
1513
+ exports.createContext = createContext;
1514
+ exports.createHook = createHook;
1515
+ exports.createLenientValidator = createLenientValidator;
1516
+ exports.createStrictValidator = createStrictValidator;
1517
+ exports.createValidationResult = createValidationResult;
1518
+ exports.formatTools = formatTools;
1519
+ exports.getFormatter = getFormatter;
1520
+ exports.getProvider = getProvider;
1521
+ exports.hasFormatter = hasFormatter;
1522
+ exports.listFormatters = listFormatters;
1523
+ exports.mergeValidationResults = mergeValidationResults;
1524
+ exports.registerFormatter = registerFormatter;
1525
+ exports.setContextError = setContextError;
1526
+ exports.toAnthropicSchema = toAnthropicSchema;
1527
+ exports.toOpenAISchema = toOpenAISchema;
1528
+ exports.toSchema = toSchema;
1529
+ exports.unregisterFormatter = unregisterFormatter;
1530
+ //# sourceMappingURL=index.cjs.map
1531
+ //# sourceMappingURL=index.cjs.map