@mondaydotcomorg/atp-runtime 0.19.7 → 0.19.8

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.js CHANGED
@@ -1,17 +1,1764 @@
1
- export * from './llm/index.js';
2
- export * from './progress/index.js';
3
- export * from './cache/index.js';
4
- export * from './utils.js';
5
- export * from './approval/index.js';
6
- export * from './embedding/index.js';
7
- export * from './registry.js';
8
- export * from './metadata/index.js';
9
- export { log, initializeLogger, shutdownLogger } from './log/index.js';
10
- export { GENERATED_METADATA } from './metadata/generated.js';
11
- export { initializeExecutionState, setClientLLMCallback, setPauseForClient, shouldPauseForClient, setReplayMode, getCallSequenceNumber, isReplayMode, storeAPICallResult, getAPICallResults, clearAPICallResults, setAPIResultCache, getAPIResultFromCache, storeAPIResultInCache, cleanupExecutionState, cleanupOldExecutionStates, resetAllExecutionState, getExecutionStateStats, } from './llm/index.js';
12
- export { initializeCache } from './cache/index.js';
13
- export { initializeApproval } from './approval/index.js';
14
- export { setProgressCallback } from './progress/index.js';
15
- export { initializeVectorStore, clearVectorStore, getVectorStore } from './embedding/index.js';
16
- export { PauseExecutionError, isPauseError, pauseForCallback, CallbackType, LLMOperation, EmbeddingOperation, ApprovalOperation, ToolOperation, } from './pause/index.js';
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
+ import pino from 'pino';
3
+ import NodeCache from 'node-cache';
4
+
5
+ var __defProp = Object.defineProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+
8
+ // src/pause/types.ts
9
+ var CallbackType;
10
+ (function(CallbackType2) {
11
+ CallbackType2["LLM"] = "llm";
12
+ CallbackType2["APPROVAL"] = "approval";
13
+ CallbackType2["EMBEDDING"] = "embedding";
14
+ CallbackType2["TOOL"] = "tool";
15
+ })(CallbackType || (CallbackType = {}));
16
+ var LLMOperation;
17
+ (function(LLMOperation2) {
18
+ LLMOperation2["CALL"] = "call";
19
+ LLMOperation2["EXTRACT"] = "extract";
20
+ LLMOperation2["CLASSIFY"] = "classify";
21
+ })(LLMOperation || (LLMOperation = {}));
22
+ var EmbeddingOperation;
23
+ (function(EmbeddingOperation2) {
24
+ EmbeddingOperation2["EMBED"] = "embed";
25
+ EmbeddingOperation2["SEARCH"] = "search";
26
+ })(EmbeddingOperation || (EmbeddingOperation = {}));
27
+ var ApprovalOperation;
28
+ (function(ApprovalOperation2) {
29
+ ApprovalOperation2["REQUEST"] = "request";
30
+ })(ApprovalOperation || (ApprovalOperation = {}));
31
+ var ToolOperation;
32
+ (function(ToolOperation2) {
33
+ ToolOperation2["CALL"] = "call";
34
+ })(ToolOperation || (ToolOperation = {}));
35
+ var PauseExecutionError = class extends Error {
36
+ static {
37
+ __name(this, "PauseExecutionError");
38
+ }
39
+ type;
40
+ operation;
41
+ payload;
42
+ constructor(type, operation, payload) {
43
+ super(`Execution paused: waiting for ${type}.${operation}`);
44
+ this.name = "PauseExecutionError";
45
+ this.type = type;
46
+ this.operation = operation;
47
+ this.payload = payload;
48
+ }
49
+ };
50
+
51
+ // src/pause/index.ts
52
+ function pauseForCallback(type, operation, payload) {
53
+ throw new PauseExecutionError(type, operation, payload);
54
+ }
55
+ __name(pauseForCallback, "pauseForCallback");
56
+ function isPauseError(error) {
57
+ return error instanceof PauseExecutionError;
58
+ }
59
+ __name(isPauseError, "isPauseError");
60
+
61
+ // src/metadata/decorators.ts
62
+ function RuntimeAPI(name, description) {
63
+ return function(constructor) {
64
+ constructor.API_NAME = name;
65
+ constructor.API_DESCRIPTION = description;
66
+ return constructor;
67
+ };
68
+ }
69
+ __name(RuntimeAPI, "RuntimeAPI");
70
+ function RuntimeMethod(description, paramDescriptions) {
71
+ return function(target, propertyKey, descriptor) {
72
+ if (!target.constructor.__methods) {
73
+ target.constructor.__methods = {};
74
+ }
75
+ target.constructor.__methods[propertyKey] = {
76
+ description,
77
+ paramDescriptions: paramDescriptions || {}
78
+ };
79
+ return descriptor;
80
+ };
81
+ }
82
+ __name(RuntimeMethod, "RuntimeMethod");
83
+ var logger = null;
84
+ function initializeLogger(config) {
85
+ const pinoLevel = config?.level === "none" ? "silent" : config?.level ?? "info";
86
+ const options = {
87
+ level: pinoLevel,
88
+ timestamp: pino.stdTimeFunctions.isoTime,
89
+ formatters: {
90
+ level: /* @__PURE__ */ __name((label) => {
91
+ return {
92
+ level: label
93
+ };
94
+ }, "level")
95
+ },
96
+ redact: {
97
+ paths: config?.redact ?? [
98
+ "apiKey",
99
+ "password",
100
+ "*.apiKey",
101
+ "*.password",
102
+ "authorization"
103
+ ],
104
+ censor: "[REDACTED]"
105
+ }
106
+ };
107
+ if (config?.pretty) {
108
+ logger = pino({
109
+ ...options,
110
+ transport: {
111
+ target: "pino-pretty",
112
+ options: {
113
+ colorize: true,
114
+ translateTime: "SYS:standard",
115
+ ignore: "pid,hostname"
116
+ }
117
+ }
118
+ });
119
+ } else if (config?.destination && config.destination !== "stdout") {
120
+ logger = pino(options, pino.destination(config.destination));
121
+ } else {
122
+ logger = pino(options);
123
+ }
124
+ }
125
+ __name(initializeLogger, "initializeLogger");
126
+ function getLogger() {
127
+ if (!logger) {
128
+ initializeLogger({
129
+ level: "info",
130
+ pretty: false
131
+ });
132
+ }
133
+ return logger;
134
+ }
135
+ __name(getLogger, "getLogger");
136
+ var log = {
137
+ /**
138
+ * Logs an informational message
139
+ */
140
+ info(message, data) {
141
+ const l = getLogger();
142
+ if (data) {
143
+ l.info(data, message);
144
+ } else {
145
+ l.info(message);
146
+ }
147
+ },
148
+ /**
149
+ * Logs a warning message
150
+ */
151
+ warn(message, data) {
152
+ const l = getLogger();
153
+ if (data) {
154
+ l.warn(data, message);
155
+ } else {
156
+ l.warn(message);
157
+ }
158
+ },
159
+ /**
160
+ * Logs an error message
161
+ */
162
+ error(message, data) {
163
+ const l = getLogger();
164
+ if (data) {
165
+ l.error(data, message);
166
+ } else {
167
+ l.error(message);
168
+ }
169
+ },
170
+ /**
171
+ * Logs a debug message
172
+ */
173
+ debug(message, data) {
174
+ const l = getLogger();
175
+ if (data) {
176
+ l.debug(data, message);
177
+ } else {
178
+ l.debug(message);
179
+ }
180
+ },
181
+ /**
182
+ * Logs a fatal error message
183
+ */
184
+ fatal(message, data) {
185
+ const l = getLogger();
186
+ if (data) {
187
+ l.fatal(data, message);
188
+ } else {
189
+ l.fatal(message);
190
+ }
191
+ },
192
+ /**
193
+ * Creates a child logger with additional context
194
+ */
195
+ child(bindings) {
196
+ const childLogger = getLogger().child(bindings);
197
+ return {
198
+ info: /* @__PURE__ */ __name((message, data) => {
199
+ if (data) {
200
+ childLogger.info(data, message);
201
+ } else {
202
+ childLogger.info(message);
203
+ }
204
+ }, "info"),
205
+ warn: /* @__PURE__ */ __name((message, data) => {
206
+ if (data) {
207
+ childLogger.warn(data, message);
208
+ } else {
209
+ childLogger.warn(message);
210
+ }
211
+ }, "warn"),
212
+ error: /* @__PURE__ */ __name((message, data) => {
213
+ if (data) {
214
+ childLogger.error(data, message);
215
+ } else {
216
+ childLogger.error(message);
217
+ }
218
+ }, "error"),
219
+ debug: /* @__PURE__ */ __name((message, data) => {
220
+ if (data) {
221
+ childLogger.debug(data, message);
222
+ } else {
223
+ childLogger.debug(message);
224
+ }
225
+ }, "debug"),
226
+ fatal: /* @__PURE__ */ __name((message, data) => {
227
+ if (data) {
228
+ childLogger.fatal(data, message);
229
+ } else {
230
+ childLogger.fatal(message);
231
+ }
232
+ }, "fatal"),
233
+ child: log.child
234
+ };
235
+ }
236
+ };
237
+ function shutdownLogger() {
238
+ logger = null;
239
+ }
240
+ __name(shutdownLogger, "shutdownLogger");
241
+
242
+ // src/llm/replay.ts
243
+ var executionStates = /* @__PURE__ */ new Map();
244
+ var MAX_EXECUTION_STATES = 100;
245
+ var operationCounter = 0;
246
+ var CLEANUP_CHECK_INTERVAL = 50;
247
+ var executionContext = new AsyncLocalStorage();
248
+ var currentExecutionId = null;
249
+ function setCurrentExecutionId(executionId) {
250
+ currentExecutionId = executionId;
251
+ }
252
+ __name(setCurrentExecutionId, "setCurrentExecutionId");
253
+ function clearCurrentExecutionId() {
254
+ currentExecutionId = null;
255
+ }
256
+ __name(clearCurrentExecutionId, "clearCurrentExecutionId");
257
+ function getCurrentState() {
258
+ let executionId = currentExecutionId;
259
+ if (!executionId) {
260
+ executionId = executionContext.getStore() || null;
261
+ }
262
+ if (!executionId) {
263
+ throw new Error("No execution context set. Executor must call setCurrentExecutionId() before runtime API calls.");
264
+ }
265
+ operationCounter++;
266
+ if (operationCounter >= CLEANUP_CHECK_INTERVAL) {
267
+ operationCounter = 0;
268
+ autoCleanup();
269
+ }
270
+ let state = executionStates.get(executionId);
271
+ if (!state) {
272
+ log.warn("State not initialized, creating with default. This should not happen.", {
273
+ executionId
274
+ });
275
+ state = {
276
+ shouldPauseForClient: false,
277
+ replayResults: void 0,
278
+ callSequenceNumber: 0,
279
+ apiCallResults: [],
280
+ apiResultCache: void 0,
281
+ createdAt: Date.now()
282
+ };
283
+ executionStates.set(executionId, state);
284
+ }
285
+ return state;
286
+ }
287
+ __name(getCurrentState, "getCurrentState");
288
+ function initializeExecutionState(shouldPause) {
289
+ const executionId = currentExecutionId || executionContext.getStore();
290
+ if (!executionId) {
291
+ throw new Error("No execution context set. Executor must call setCurrentExecutionId() before initializeExecutionState().");
292
+ }
293
+ const existingState = executionStates.get(executionId);
294
+ if (existingState) {
295
+ existingState.shouldPauseForClient = shouldPause;
296
+ if (!existingState.apiCallResults) {
297
+ existingState.apiCallResults = [];
298
+ }
299
+ if (!existingState.apiResultCache) {
300
+ existingState.apiResultCache = void 0;
301
+ }
302
+ return;
303
+ }
304
+ const state = {
305
+ shouldPauseForClient: shouldPause,
306
+ replayResults: void 0,
307
+ callSequenceNumber: 0,
308
+ apiCallResults: [],
309
+ apiResultCache: void 0,
310
+ createdAt: Date.now()
311
+ };
312
+ executionStates.set(executionId, state);
313
+ }
314
+ __name(initializeExecutionState, "initializeExecutionState");
315
+ function runInExecutionContext(executionId, fn) {
316
+ return executionContext.run(executionId, fn);
317
+ }
318
+ __name(runInExecutionContext, "runInExecutionContext");
319
+ function setPauseForClient(pause) {
320
+ const executionId = currentExecutionId || executionContext.getStore();
321
+ if (!executionId) {
322
+ throw new Error("No execution context set. Executor must call setCurrentExecutionId() before setPauseForClient().");
323
+ }
324
+ const state = executionStates.get(executionId);
325
+ if (!state) {
326
+ throw new Error("Execution state not initialized. Call initializeExecutionState() first.");
327
+ }
328
+ state.shouldPauseForClient = pause;
329
+ }
330
+ __name(setPauseForClient, "setPauseForClient");
331
+ function shouldPauseForClient() {
332
+ const state = getCurrentState();
333
+ return state.shouldPauseForClient;
334
+ }
335
+ __name(shouldPauseForClient, "shouldPauseForClient");
336
+ function setReplayMode(results) {
337
+ const state = getCurrentState();
338
+ state.replayResults = results;
339
+ state.callSequenceNumber = 0;
340
+ }
341
+ __name(setReplayMode, "setReplayMode");
342
+ function getCallSequenceNumber() {
343
+ const state = getCurrentState();
344
+ return state.callSequenceNumber;
345
+ }
346
+ __name(getCallSequenceNumber, "getCallSequenceNumber");
347
+ function nextSequenceNumber() {
348
+ const state = getCurrentState();
349
+ const current = state.callSequenceNumber;
350
+ state.callSequenceNumber++;
351
+ return current;
352
+ }
353
+ __name(nextSequenceNumber, "nextSequenceNumber");
354
+ function getCachedResult(sequenceNumber) {
355
+ const state = getCurrentState();
356
+ if (state.replayResults && state.replayResults.has(sequenceNumber)) {
357
+ return state.replayResults.get(sequenceNumber);
358
+ }
359
+ return void 0;
360
+ }
361
+ __name(getCachedResult, "getCachedResult");
362
+ function isReplayMode() {
363
+ return getCurrentState().replayResults !== void 0;
364
+ }
365
+ __name(isReplayMode, "isReplayMode");
366
+ function storeAPICallResult(record) {
367
+ const state = getCurrentState();
368
+ state.apiCallResults.push(record);
369
+ }
370
+ __name(storeAPICallResult, "storeAPICallResult");
371
+ function getAPICallResults() {
372
+ const state = getCurrentState();
373
+ return state.apiCallResults;
374
+ }
375
+ __name(getAPICallResults, "getAPICallResults");
376
+ function clearAPICallResults() {
377
+ const state = getCurrentState();
378
+ state.apiCallResults = [];
379
+ }
380
+ __name(clearAPICallResults, "clearAPICallResults");
381
+ function setAPIResultCache(cache2) {
382
+ const state = getCurrentState();
383
+ state.apiResultCache = cache2;
384
+ }
385
+ __name(setAPIResultCache, "setAPIResultCache");
386
+ function getAPIResultFromCache(operation) {
387
+ const state = getCurrentState();
388
+ return state.apiResultCache?.get(operation);
389
+ }
390
+ __name(getAPIResultFromCache, "getAPIResultFromCache");
391
+ function storeAPIResultInCache(operation, result) {
392
+ const state = getCurrentState();
393
+ if (!state.apiResultCache) {
394
+ state.apiResultCache = /* @__PURE__ */ new Map();
395
+ }
396
+ state.apiResultCache.set(operation, result);
397
+ }
398
+ __name(storeAPIResultInCache, "storeAPIResultInCache");
399
+ function cleanupExecutionState(executionId) {
400
+ executionStates.delete(executionId);
401
+ if (currentExecutionId === executionId) {
402
+ currentExecutionId = null;
403
+ }
404
+ }
405
+ __name(cleanupExecutionState, "cleanupExecutionState");
406
+ function autoCleanup() {
407
+ if (executionStates.size <= MAX_EXECUTION_STATES) {
408
+ return;
409
+ }
410
+ const entries = Array.from(executionStates.entries()).sort((a, b) => a[1].createdAt - b[1].createdAt);
411
+ const toRemove = executionStates.size - MAX_EXECUTION_STATES;
412
+ for (let i = 0; i < toRemove; i++) {
413
+ const entry = entries[i];
414
+ if (entry) {
415
+ executionStates.delete(entry[0]);
416
+ }
417
+ }
418
+ }
419
+ __name(autoCleanup, "autoCleanup");
420
+ function cleanupOldExecutionStates(maxAgeMs = 36e5) {
421
+ const now = Date.now();
422
+ let cleaned = 0;
423
+ for (const [executionId, state] of executionStates.entries()) {
424
+ const age = now - state.createdAt;
425
+ if (age > maxAgeMs) {
426
+ executionStates.delete(executionId);
427
+ cleaned++;
428
+ }
429
+ }
430
+ return cleaned;
431
+ }
432
+ __name(cleanupOldExecutionStates, "cleanupOldExecutionStates");
433
+ function resetAllExecutionState() {
434
+ executionStates.clear();
435
+ currentExecutionId = null;
436
+ }
437
+ __name(resetAllExecutionState, "resetAllExecutionState");
438
+ function getExecutionStateStats() {
439
+ const now = Date.now();
440
+ const executionIds = Array.from(executionStates.keys());
441
+ let oldestAge = null;
442
+ let newestAge = null;
443
+ for (const state of executionStates.values()) {
444
+ const age = now - state.createdAt;
445
+ if (oldestAge === null || age > oldestAge) {
446
+ oldestAge = age;
447
+ }
448
+ if (newestAge === null || age < newestAge) {
449
+ newestAge = age;
450
+ }
451
+ }
452
+ return {
453
+ totalStates: executionStates.size,
454
+ oldestStateAge: oldestAge,
455
+ newestStateAge: newestAge,
456
+ executionIds
457
+ };
458
+ }
459
+ __name(getExecutionStateStats, "getExecutionStateStats");
460
+
461
+ // src/llm/callback.ts
462
+ var clientLLMCallback;
463
+ function setClientLLMCallback(callback) {
464
+ clientLLMCallback = callback;
465
+ }
466
+ __name(setClientLLMCallback, "setClientLLMCallback");
467
+ function getClientLLMCallback() {
468
+ return clientLLMCallback;
469
+ }
470
+ __name(getClientLLMCallback, "getClientLLMCallback");
471
+
472
+ // src/llm/index.ts
473
+ function _ts_decorate(decorators, target, key, desc) {
474
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
475
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
476
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
477
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
478
+ }
479
+ __name(_ts_decorate, "_ts_decorate");
480
+ function _ts_metadata(k, v) {
481
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
482
+ }
483
+ __name(_ts_metadata, "_ts_metadata");
484
+ var LLMAPI = class LLMAPI2 {
485
+ static {
486
+ __name(this, "LLMAPI");
487
+ }
488
+ /**
489
+ * Makes a standard LLM call
490
+ * Always pauses execution and routes to client-provided LLM
491
+ */
492
+ async call(options) {
493
+ const currentSequence = nextSequenceNumber();
494
+ const cachedResult = getCachedResult(currentSequence);
495
+ if (cachedResult !== void 0) {
496
+ return cachedResult;
497
+ }
498
+ pauseForCallback(CallbackType.LLM, LLMOperation.CALL, {
499
+ prompt: options.prompt,
500
+ options,
501
+ sequenceNumber: currentSequence
502
+ });
503
+ }
504
+ /**
505
+ * Extracts structured data using LLM
506
+ * Always pauses execution and routes to client-provided LLM
507
+ */
508
+ async extract(options) {
509
+ const currentSequence = nextSequenceNumber();
510
+ const cachedResult = getCachedResult(currentSequence);
511
+ if (cachedResult !== void 0) {
512
+ return cachedResult;
513
+ }
514
+ pauseForCallback(CallbackType.LLM, LLMOperation.EXTRACT, {
515
+ prompt: options.prompt,
516
+ schema: options.schema,
517
+ options,
518
+ sequenceNumber: currentSequence
519
+ });
520
+ }
521
+ /**
522
+ * Classifies text into one of the provided categories
523
+ * Always pauses execution and routes to client-provided LLM
524
+ */
525
+ async classify(options) {
526
+ const currentSequence = nextSequenceNumber();
527
+ const cachedResult = getCachedResult(currentSequence);
528
+ if (cachedResult !== void 0) {
529
+ return cachedResult;
530
+ }
531
+ pauseForCallback(CallbackType.LLM, LLMOperation.CLASSIFY, {
532
+ text: options.text,
533
+ categories: options.categories,
534
+ options,
535
+ sequenceNumber: currentSequence
536
+ });
537
+ }
538
+ };
539
+ _ts_decorate([
540
+ RuntimeMethod("Make an LLM call with a prompt", {
541
+ options: {
542
+ description: "LLM call options including prompt",
543
+ type: "LLMCallOptions"
544
+ }
545
+ }),
546
+ _ts_metadata("design:type", Function),
547
+ _ts_metadata("design:paramtypes", [
548
+ typeof LLMCallOptions === "undefined" ? Object : LLMCallOptions
549
+ ]),
550
+ _ts_metadata("design:returntype", Promise)
551
+ ], LLMAPI.prototype, "call", null);
552
+ _ts_decorate([
553
+ RuntimeMethod("Extract structured data from text using an LLM", {
554
+ options: {
555
+ description: "Extraction options with JSON schema",
556
+ type: "LLMExtractOptions"
557
+ }
558
+ }),
559
+ _ts_metadata("design:type", Function),
560
+ _ts_metadata("design:paramtypes", [
561
+ typeof LLMExtractOptions === "undefined" ? Object : LLMExtractOptions
562
+ ]),
563
+ _ts_metadata("design:returntype", Promise)
564
+ ], LLMAPI.prototype, "extract", null);
565
+ _ts_decorate([
566
+ RuntimeMethod("Classify text into one of the provided categories", {
567
+ options: {
568
+ description: "Classification options with categories",
569
+ type: "LLMClassifyOptions"
570
+ }
571
+ }),
572
+ _ts_metadata("design:type", Function),
573
+ _ts_metadata("design:paramtypes", [
574
+ typeof LLMClassifyOptions === "undefined" ? Object : LLMClassifyOptions
575
+ ]),
576
+ _ts_metadata("design:returntype", Promise)
577
+ ], LLMAPI.prototype, "classify", null);
578
+ LLMAPI = _ts_decorate([
579
+ RuntimeAPI("llm", "LLM API - Large Language Model calls using client-provided LLM (requires client.provideLLM())")
580
+ ], LLMAPI);
581
+ var llm = new LLMAPI();
582
+
583
+ // src/progress/index.ts
584
+ function _ts_decorate2(decorators, target, key, desc) {
585
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
586
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
587
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
588
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
589
+ }
590
+ __name(_ts_decorate2, "_ts_decorate");
591
+ function _ts_metadata2(k, v) {
592
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
593
+ }
594
+ __name(_ts_metadata2, "_ts_metadata");
595
+ var progressCallback = null;
596
+ function setProgressCallback(callback) {
597
+ progressCallback = callback;
598
+ }
599
+ __name(setProgressCallback, "setProgressCallback");
600
+ var ProgressAPI = class ProgressAPI2 {
601
+ static {
602
+ __name(this, "ProgressAPI");
603
+ }
604
+ /**
605
+ * Report progress with message and completion fraction
606
+ */
607
+ report(message, fraction) {
608
+ if (progressCallback) {
609
+ try {
610
+ progressCallback(message, fraction);
611
+ } catch (error) {
612
+ log.error("Progress callback error", {
613
+ error
614
+ });
615
+ }
616
+ }
617
+ }
618
+ };
619
+ _ts_decorate2([
620
+ RuntimeMethod("Report progress with message and completion fraction", {
621
+ message: {
622
+ description: "Progress message"
623
+ },
624
+ fraction: {
625
+ description: "Completion fraction (0-1)"
626
+ }
627
+ }),
628
+ _ts_metadata2("design:type", Function),
629
+ _ts_metadata2("design:paramtypes", [
630
+ String,
631
+ Number
632
+ ]),
633
+ _ts_metadata2("design:returntype", void 0)
634
+ ], ProgressAPI.prototype, "report", null);
635
+ ProgressAPI = _ts_decorate2([
636
+ RuntimeAPI("progress", "Progress API - Report execution progress to clients")
637
+ ], ProgressAPI);
638
+ var progress = new ProgressAPI();
639
+ var MemoryCacheBackend = class {
640
+ static {
641
+ __name(this, "MemoryCacheBackend");
642
+ }
643
+ cache;
644
+ constructor(config) {
645
+ this.cache = new NodeCache({
646
+ stdTTL: config?.defaultTTL ?? 600,
647
+ checkperiod: config?.checkPeriod ?? 120,
648
+ maxKeys: config?.maxKeys ?? 1e3,
649
+ useClones: false
650
+ });
651
+ }
652
+ async get(key) {
653
+ const value = this.cache.get(key);
654
+ return value ?? null;
655
+ }
656
+ async set(key, value, ttl) {
657
+ if (ttl) {
658
+ this.cache.set(key, value, ttl);
659
+ } else {
660
+ this.cache.set(key, value);
661
+ }
662
+ }
663
+ async delete(key) {
664
+ this.cache.del(key);
665
+ }
666
+ async has(key) {
667
+ return this.cache.has(key);
668
+ }
669
+ async clear() {
670
+ this.cache.flushAll();
671
+ }
672
+ };
673
+ var RedisCacheBackend = class {
674
+ static {
675
+ __name(this, "RedisCacheBackend");
676
+ }
677
+ client;
678
+ connected = false;
679
+ constructor(config) {
680
+ import('ioredis').then((Redis) => {
681
+ this.client = new Redis.default({
682
+ host: config.host,
683
+ port: config.port,
684
+ password: config.password,
685
+ db: config.db ?? 0,
686
+ retryStrategy: /* @__PURE__ */ __name((times) => {
687
+ if (times > 3) {
688
+ return null;
689
+ }
690
+ return Math.min(times * 100, 2e3);
691
+ }, "retryStrategy"),
692
+ lazyConnect: true
693
+ });
694
+ this.client.connect().then(() => {
695
+ this.connected = true;
696
+ }).catch(() => {
697
+ this.connected = false;
698
+ });
699
+ }).catch(() => {
700
+ throw new Error("ioredis package not installed. Install it with: yarn add ioredis");
701
+ });
702
+ }
703
+ async get(key) {
704
+ if (!this.connected) {
705
+ log.warn("Redis Cache not connected, cannot get key", {
706
+ key
707
+ });
708
+ return null;
709
+ }
710
+ try {
711
+ const value = await this.client.get(key);
712
+ return value ? JSON.parse(value) : null;
713
+ } catch (error) {
714
+ log.error("Redis Cache failed to get key", {
715
+ key,
716
+ error: error instanceof Error ? error.message : error
717
+ });
718
+ return null;
719
+ }
720
+ }
721
+ async set(key, value, ttl) {
722
+ if (!this.connected) {
723
+ log.warn("Redis Cache not connected, cannot set key", {
724
+ key
725
+ });
726
+ return;
727
+ }
728
+ try {
729
+ const serialized = JSON.stringify(value);
730
+ if (ttl) {
731
+ await this.client.setex(key, ttl, serialized);
732
+ } else {
733
+ await this.client.set(key, serialized);
734
+ }
735
+ } catch (error) {
736
+ log.error("Redis Cache failed to set key", {
737
+ key,
738
+ error: error instanceof Error ? error.message : error
739
+ });
740
+ }
741
+ }
742
+ async delete(key) {
743
+ if (!this.connected) {
744
+ log.warn("Redis Cache not connected, cannot delete key", {
745
+ key
746
+ });
747
+ return;
748
+ }
749
+ try {
750
+ await this.client.del(key);
751
+ } catch (error) {
752
+ log.error("Redis Cache failed to delete key", {
753
+ key,
754
+ error: error instanceof Error ? error.message : error
755
+ });
756
+ }
757
+ }
758
+ async has(key) {
759
+ if (!this.connected) {
760
+ log.warn("Redis Cache not connected, cannot check key", {
761
+ key
762
+ });
763
+ return false;
764
+ }
765
+ try {
766
+ const exists = await this.client.exists(key);
767
+ return exists === 1;
768
+ } catch (error) {
769
+ log.error("Redis Cache failed to check key", {
770
+ key,
771
+ error: error instanceof Error ? error.message : error
772
+ });
773
+ return false;
774
+ }
775
+ }
776
+ async clear() {
777
+ if (!this.connected) {
778
+ log.warn("Redis Cache not connected, cannot clear cache");
779
+ return;
780
+ }
781
+ try {
782
+ await this.client.flushdb();
783
+ } catch (error) {
784
+ log.error("Redis Cache failed to clear cache", {
785
+ error: error instanceof Error ? error.message : error
786
+ });
787
+ }
788
+ }
789
+ };
790
+ var cacheBackend = new MemoryCacheBackend();
791
+ function initializeCache(config) {
792
+ if (config.type === "redis" && config.redis) {
793
+ cacheBackend = new RedisCacheBackend(config.redis);
794
+ } else {
795
+ cacheBackend = new MemoryCacheBackend({
796
+ maxKeys: config.maxKeys,
797
+ defaultTTL: config.defaultTTL,
798
+ checkPeriod: config.checkPeriod
799
+ });
800
+ }
801
+ }
802
+ __name(initializeCache, "initializeCache");
803
+ function getCacheBackend() {
804
+ return cacheBackend;
805
+ }
806
+ __name(getCacheBackend, "getCacheBackend");
807
+
808
+ // src/cache/index.ts
809
+ function _ts_decorate3(decorators, target, key, desc) {
810
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
811
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
812
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
813
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
814
+ }
815
+ __name(_ts_decorate3, "_ts_decorate");
816
+ function _ts_metadata3(k, v) {
817
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
818
+ }
819
+ __name(_ts_metadata3, "_ts_metadata");
820
+ var CacheAPI = class CacheAPI2 {
821
+ static {
822
+ __name(this, "CacheAPI");
823
+ }
824
+ /**
825
+ * Gets a value from cache
826
+ */
827
+ async get(key) {
828
+ return getCacheBackend().get(key);
829
+ }
830
+ /**
831
+ * Sets a value in cache with optional TTL in seconds
832
+ */
833
+ async set(key, value, ttl) {
834
+ return getCacheBackend().set(key, value, ttl);
835
+ }
836
+ /**
837
+ * Deletes a value from cache
838
+ */
839
+ async delete(key) {
840
+ return getCacheBackend().delete(key);
841
+ }
842
+ /**
843
+ * Checks if a key exists in cache
844
+ */
845
+ async has(key) {
846
+ return getCacheBackend().has(key);
847
+ }
848
+ /**
849
+ * Clears all cache entries
850
+ */
851
+ async clear() {
852
+ return getCacheBackend().clear();
853
+ }
854
+ };
855
+ _ts_decorate3([
856
+ RuntimeMethod("Get a value from cache by key", {
857
+ key: {
858
+ description: "Cache key"
859
+ }
860
+ }),
861
+ _ts_metadata3("design:type", Function),
862
+ _ts_metadata3("design:paramtypes", [
863
+ String
864
+ ]),
865
+ _ts_metadata3("design:returntype", Promise)
866
+ ], CacheAPI.prototype, "get", null);
867
+ _ts_decorate3([
868
+ RuntimeMethod("Set a value in cache with optional TTL", {
869
+ key: {
870
+ description: "Cache key"
871
+ },
872
+ value: {
873
+ description: "Value to cache",
874
+ type: "unknown"
875
+ },
876
+ ttl: {
877
+ description: "Time to live in seconds",
878
+ optional: true
879
+ }
880
+ }),
881
+ _ts_metadata3("design:type", Function),
882
+ _ts_metadata3("design:paramtypes", [
883
+ String,
884
+ Object,
885
+ Number
886
+ ]),
887
+ _ts_metadata3("design:returntype", Promise)
888
+ ], CacheAPI.prototype, "set", null);
889
+ _ts_decorate3([
890
+ RuntimeMethod("Delete a value from cache", {
891
+ key: {
892
+ description: "Cache key to delete"
893
+ }
894
+ }),
895
+ _ts_metadata3("design:type", Function),
896
+ _ts_metadata3("design:paramtypes", [
897
+ String
898
+ ]),
899
+ _ts_metadata3("design:returntype", Promise)
900
+ ], CacheAPI.prototype, "delete", null);
901
+ _ts_decorate3([
902
+ RuntimeMethod("Check if a key exists in cache", {
903
+ key: {
904
+ description: "Cache key to check"
905
+ }
906
+ }),
907
+ _ts_metadata3("design:type", Function),
908
+ _ts_metadata3("design:paramtypes", [
909
+ String
910
+ ]),
911
+ _ts_metadata3("design:returntype", Promise)
912
+ ], CacheAPI.prototype, "has", null);
913
+ _ts_decorate3([
914
+ RuntimeMethod("Clear all cache entries"),
915
+ _ts_metadata3("design:type", Function),
916
+ _ts_metadata3("design:paramtypes", []),
917
+ _ts_metadata3("design:returntype", Promise)
918
+ ], CacheAPI.prototype, "clear", null);
919
+ CacheAPI = _ts_decorate3([
920
+ RuntimeAPI("cache", "Cache API - Store and retrieve data with optional TTL")
921
+ ], CacheAPI);
922
+ var cache = new CacheAPI();
923
+
924
+ // src/utils.ts
925
+ var utils = {
926
+ async sleep(ms) {
927
+ return new Promise((resolve) => setTimeout(resolve, ms));
928
+ },
929
+ async retry(fn, options) {
930
+ let lastError;
931
+ for (let attempt = 1; attempt <= options.maxAttempts; attempt++) {
932
+ try {
933
+ return await fn();
934
+ } catch (error) {
935
+ lastError = error;
936
+ if (attempt < options.maxAttempts) {
937
+ await this.sleep(options.delayMs);
938
+ }
939
+ }
940
+ }
941
+ throw lastError;
942
+ },
943
+ async parallel(tasks) {
944
+ return Promise.all(tasks.map((task) => task()));
945
+ },
946
+ async sequence(tasks) {
947
+ const results = [];
948
+ for (const task of tasks) {
949
+ results.push(await task());
950
+ }
951
+ return results;
952
+ }
953
+ };
954
+
955
+ // src/approval/handler.ts
956
+ var approvalHandler = null;
957
+ function initializeApproval(handler) {
958
+ approvalHandler = handler;
959
+ }
960
+ __name(initializeApproval, "initializeApproval");
961
+ function getApprovalHandler() {
962
+ return approvalHandler;
963
+ }
964
+ __name(getApprovalHandler, "getApprovalHandler");
965
+
966
+ // src/approval/index.ts
967
+ function _ts_decorate4(decorators, target, key, desc) {
968
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
969
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
970
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
971
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
972
+ }
973
+ __name(_ts_decorate4, "_ts_decorate");
974
+ function _ts_metadata4(k, v) {
975
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
976
+ }
977
+ __name(_ts_metadata4, "_ts_metadata");
978
+ var ApprovalAPI = class ApprovalAPI2 {
979
+ static {
980
+ __name(this, "ApprovalAPI");
981
+ }
982
+ /**
983
+ * Request approval from a human
984
+ */
985
+ async request(message, context) {
986
+ const currentSequence = nextSequenceNumber();
987
+ const cachedResult = getCachedResult(currentSequence);
988
+ if (cachedResult !== void 0) {
989
+ return cachedResult;
990
+ }
991
+ const shouldPause = shouldPauseForClient();
992
+ if (shouldPause) {
993
+ pauseForCallback(CallbackType.APPROVAL, ApprovalOperation.REQUEST, {
994
+ message,
995
+ context,
996
+ sequenceNumber: currentSequence
997
+ });
998
+ }
999
+ const handler = getApprovalHandler();
1000
+ if (!handler) {
1001
+ throw new Error("Approval handler not configured. Human approval is required but no handler is set.");
1002
+ }
1003
+ const approvalRequest = {
1004
+ message,
1005
+ context,
1006
+ timeout: 3e5
1007
+ };
1008
+ let timeoutId = null;
1009
+ const timeoutPromise = new Promise((_, reject) => {
1010
+ timeoutId = setTimeout(() => reject(new Error("Approval request timed out")), approvalRequest.timeout);
1011
+ });
1012
+ try {
1013
+ const response = await Promise.race([
1014
+ handler(approvalRequest),
1015
+ timeoutPromise
1016
+ ]);
1017
+ if (timeoutId) clearTimeout(timeoutId);
1018
+ return {
1019
+ ...response,
1020
+ timestamp: Date.now()
1021
+ };
1022
+ } catch (error) {
1023
+ if (timeoutId) clearTimeout(timeoutId);
1024
+ throw new Error(`Approval request failed: ${error instanceof Error ? error.message : "Unknown error"}`);
1025
+ }
1026
+ }
1027
+ };
1028
+ _ts_decorate4([
1029
+ RuntimeMethod("Request approval from a human", {
1030
+ message: {
1031
+ description: "The message to display to the user"
1032
+ },
1033
+ context: {
1034
+ description: "Optional context information about what needs approval",
1035
+ optional: true,
1036
+ type: "Record<string, unknown>"
1037
+ }
1038
+ }),
1039
+ _ts_metadata4("design:type", Function),
1040
+ _ts_metadata4("design:paramtypes", [
1041
+ String,
1042
+ typeof Record === "undefined" ? Object : Record
1043
+ ]),
1044
+ _ts_metadata4("design:returntype", Promise)
1045
+ ], ApprovalAPI.prototype, "request", null);
1046
+ ApprovalAPI = _ts_decorate4([
1047
+ RuntimeAPI("approval", "Approval API - Request explicit human approval for sensitive operations")
1048
+ ], ApprovalAPI);
1049
+ var approval = new ApprovalAPI();
1050
+
1051
+ // src/embedding/utils.ts
1052
+ function cosineSimilarity(vec1, vec2) {
1053
+ if (vec1.length !== vec2.length) {
1054
+ throw new Error(`Vectors must have the same length (${vec1.length} vs ${vec2.length})`);
1055
+ }
1056
+ let dotProduct = 0;
1057
+ let norm1 = 0;
1058
+ let norm2 = 0;
1059
+ for (let i = 0; i < vec1.length; i++) {
1060
+ dotProduct += vec1[i] * vec2[i];
1061
+ norm1 += vec1[i] * vec1[i];
1062
+ norm2 += vec2[i] * vec2[i];
1063
+ }
1064
+ const denominator = Math.sqrt(norm1) * Math.sqrt(norm2);
1065
+ if (denominator === 0) {
1066
+ return 0;
1067
+ }
1068
+ return dotProduct / denominator;
1069
+ }
1070
+ __name(cosineSimilarity, "cosineSimilarity");
1071
+ function generateEmbeddingId(index = 0) {
1072
+ return `emb_${Date.now()}_${index}_${Math.random().toString(36).slice(2)}`;
1073
+ }
1074
+ __name(generateEmbeddingId, "generateEmbeddingId");
1075
+
1076
+ // src/embedding/vector-store.ts
1077
+ var VectorStore = class {
1078
+ static {
1079
+ __name(this, "VectorStore");
1080
+ }
1081
+ records = /* @__PURE__ */ new Map();
1082
+ queryEmbedding = null;
1083
+ /**
1084
+ * Store embeddings from client response
1085
+ */
1086
+ store(id, text, embedding2, metadata) {
1087
+ this.records.set(id, {
1088
+ id,
1089
+ text,
1090
+ embedding: embedding2,
1091
+ metadata
1092
+ });
1093
+ }
1094
+ /**
1095
+ * Store multiple embeddings
1096
+ */
1097
+ storeBatch(records) {
1098
+ for (const record of records) {
1099
+ this.records.set(record.id, record);
1100
+ }
1101
+ }
1102
+ /**
1103
+ * Set the query embedding for search
1104
+ */
1105
+ setQueryEmbedding(embedding2) {
1106
+ this.queryEmbedding = embedding2;
1107
+ }
1108
+ /**
1109
+ * Search stored embeddings by similarity to query
1110
+ */
1111
+ search(options) {
1112
+ if (!this.queryEmbedding) {
1113
+ throw new Error("No query embedding set. Call embed() with query first.");
1114
+ }
1115
+ const topK = options.topK ?? 5;
1116
+ const minSimilarity = options.minSimilarity ?? 0;
1117
+ const results = [];
1118
+ for (const record of this.records.values()) {
1119
+ if (options.filter && record.metadata) {
1120
+ let matches = true;
1121
+ for (const [key, value] of Object.entries(options.filter)) {
1122
+ if (record.metadata[key] !== value) {
1123
+ matches = false;
1124
+ break;
1125
+ }
1126
+ }
1127
+ if (!matches) continue;
1128
+ }
1129
+ const similarity = cosineSimilarity(this.queryEmbedding, record.embedding);
1130
+ if (similarity >= minSimilarity) {
1131
+ results.push({
1132
+ id: record.id,
1133
+ text: record.text,
1134
+ similarity,
1135
+ metadata: record.metadata
1136
+ });
1137
+ }
1138
+ }
1139
+ results.sort((a, b) => b.similarity - a.similarity);
1140
+ return results.slice(0, topK);
1141
+ }
1142
+ /**
1143
+ * Get all stored embeddings
1144
+ */
1145
+ getAll() {
1146
+ return Array.from(this.records.values());
1147
+ }
1148
+ /**
1149
+ * Get embedding by ID
1150
+ */
1151
+ get(id) {
1152
+ return this.records.get(id);
1153
+ }
1154
+ /**
1155
+ * Clear all stored embeddings
1156
+ */
1157
+ clear() {
1158
+ this.records.clear();
1159
+ this.queryEmbedding = null;
1160
+ }
1161
+ /**
1162
+ * Get count of stored embeddings
1163
+ */
1164
+ count() {
1165
+ return this.records.size;
1166
+ }
1167
+ };
1168
+ var vectorStores = /* @__PURE__ */ new Map();
1169
+ var currentVectorStoreExecutionId = null;
1170
+ function setVectorStoreExecutionId(executionId) {
1171
+ currentVectorStoreExecutionId = executionId;
1172
+ }
1173
+ __name(setVectorStoreExecutionId, "setVectorStoreExecutionId");
1174
+ function clearVectorStoreExecutionId() {
1175
+ currentVectorStoreExecutionId = null;
1176
+ }
1177
+ __name(clearVectorStoreExecutionId, "clearVectorStoreExecutionId");
1178
+ function initializeVectorStore(executionId) {
1179
+ const id = executionId || currentVectorStoreExecutionId;
1180
+ if (!id) {
1181
+ throw new Error("No execution ID set for vector store");
1182
+ }
1183
+ vectorStores.set(id, new VectorStore());
1184
+ }
1185
+ __name(initializeVectorStore, "initializeVectorStore");
1186
+ function clearVectorStore(executionId) {
1187
+ const id = executionId || currentVectorStoreExecutionId;
1188
+ if (!id) return;
1189
+ const store = vectorStores.get(id);
1190
+ if (store) {
1191
+ store.clear();
1192
+ vectorStores.delete(id);
1193
+ }
1194
+ }
1195
+ __name(clearVectorStore, "clearVectorStore");
1196
+ function getVectorStore(executionId) {
1197
+ const id = executionId || currentVectorStoreExecutionId;
1198
+ if (!id) {
1199
+ throw new Error("No execution ID set for vector store");
1200
+ }
1201
+ let store = vectorStores.get(id);
1202
+ if (!store) {
1203
+ store = new VectorStore();
1204
+ vectorStores.set(id, store);
1205
+ }
1206
+ return store;
1207
+ }
1208
+ __name(getVectorStore, "getVectorStore");
1209
+
1210
+ // src/embedding/index.ts
1211
+ function _ts_decorate5(decorators, target, key, desc) {
1212
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1213
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1214
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1215
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1216
+ }
1217
+ __name(_ts_decorate5, "_ts_decorate");
1218
+ function _ts_metadata5(k, v) {
1219
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1220
+ }
1221
+ __name(_ts_metadata5, "_ts_metadata");
1222
+ var EmbeddingAPI = class EmbeddingAPI2 {
1223
+ static {
1224
+ __name(this, "EmbeddingAPI");
1225
+ }
1226
+ /**
1227
+ * Request client to generate embedding and store it
1228
+ * For batch inputs, returns array of IDs for stored embeddings
1229
+ */
1230
+ async embed(input, metadata) {
1231
+ const isBatch = Array.isArray(input);
1232
+ const texts = isBatch ? input : [
1233
+ input
1234
+ ];
1235
+ const ids = texts.map((_, i) => generateEmbeddingId(i));
1236
+ const currentSequence = nextSequenceNumber();
1237
+ const cachedResult = getCachedResult(currentSequence);
1238
+ if (cachedResult !== void 0 && cachedResult !== null) {
1239
+ const vectorStore = getVectorStore();
1240
+ const embedding2 = cachedResult;
1241
+ for (let i = 0; i < texts.length; i++) {
1242
+ vectorStore.store(ids[i], texts[i], embedding2, metadata);
1243
+ }
1244
+ return isBatch ? ids : ids[0];
1245
+ }
1246
+ if (shouldPauseForClient()) {
1247
+ pauseForCallback(CallbackType.EMBEDDING, EmbeddingOperation.EMBED, {
1248
+ text: isBatch ? texts.join("\n") : texts[0],
1249
+ input,
1250
+ ids,
1251
+ metadata,
1252
+ sequenceNumber: currentSequence
1253
+ });
1254
+ }
1255
+ throw new Error("Embedding service not provided by client");
1256
+ }
1257
+ /**
1258
+ * Search stored embeddings by similarity
1259
+ * Query must be embedded first via embed()
1260
+ */
1261
+ async search(query, options) {
1262
+ const currentSequence = nextSequenceNumber();
1263
+ const vectorStore = getVectorStore();
1264
+ const cachedQueryEmbedding = getCachedResult(currentSequence);
1265
+ if (cachedQueryEmbedding !== void 0 && cachedQueryEmbedding !== null) {
1266
+ vectorStore.setQueryEmbedding(cachedQueryEmbedding);
1267
+ const searchOptions = {
1268
+ ...options,
1269
+ query
1270
+ };
1271
+ if (options?.collection) {
1272
+ searchOptions.filter = {
1273
+ ...searchOptions.filter,
1274
+ collection: options.collection
1275
+ };
1276
+ }
1277
+ return vectorStore.search(searchOptions);
1278
+ }
1279
+ if (shouldPauseForClient()) {
1280
+ pauseForCallback(CallbackType.EMBEDDING, EmbeddingOperation.SEARCH, {
1281
+ query,
1282
+ options: {
1283
+ ...options,
1284
+ query
1285
+ },
1286
+ sequenceNumber: currentSequence
1287
+ });
1288
+ }
1289
+ throw new Error("Embedding service not provided by client");
1290
+ }
1291
+ /**
1292
+ * Calculate cosine similarity between two embedding vectors
1293
+ * This is a utility function that doesn't require client interaction
1294
+ */
1295
+ similarity(embedding1, embedding2) {
1296
+ return cosineSimilarity(embedding1, embedding2);
1297
+ }
1298
+ /**
1299
+ * Get all stored embeddings (useful for debugging)
1300
+ */
1301
+ getAll() {
1302
+ return getVectorStore().getAll();
1303
+ }
1304
+ /**
1305
+ * Get count of stored embeddings
1306
+ */
1307
+ count() {
1308
+ return getVectorStore().count();
1309
+ }
1310
+ };
1311
+ _ts_decorate5([
1312
+ RuntimeMethod("Request client to generate and store embeddings", {
1313
+ input: {
1314
+ description: "Text(s) to embed",
1315
+ type: "string | string[]"
1316
+ },
1317
+ metadata: {
1318
+ description: "Optional metadata to store with embeddings",
1319
+ optional: true,
1320
+ type: "Record<string, unknown>"
1321
+ }
1322
+ }),
1323
+ _ts_metadata5("design:type", Function),
1324
+ _ts_metadata5("design:paramtypes", [
1325
+ Object,
1326
+ typeof Record === "undefined" ? Object : Record
1327
+ ]),
1328
+ _ts_metadata5("design:returntype", Promise)
1329
+ ], EmbeddingAPI.prototype, "embed", null);
1330
+ _ts_decorate5([
1331
+ RuntimeMethod("Search stored embeddings by similarity", {
1332
+ query: {
1333
+ description: "Search query text (will be embedded by client)"
1334
+ },
1335
+ options: {
1336
+ description: "Search options (topK, minSimilarity, filter)",
1337
+ optional: true,
1338
+ type: "SearchOptions"
1339
+ }
1340
+ }),
1341
+ _ts_metadata5("design:type", Function),
1342
+ _ts_metadata5("design:paramtypes", [
1343
+ String,
1344
+ typeof Omit === "undefined" ? Object : Omit
1345
+ ]),
1346
+ _ts_metadata5("design:returntype", Promise)
1347
+ ], EmbeddingAPI.prototype, "search", null);
1348
+ _ts_decorate5([
1349
+ RuntimeMethod("Calculate cosine similarity between two embedding vectors", {
1350
+ embedding1: {
1351
+ description: "First embedding vector",
1352
+ type: "number[]"
1353
+ },
1354
+ embedding2: {
1355
+ description: "Second embedding vector",
1356
+ type: "number[]"
1357
+ }
1358
+ }),
1359
+ _ts_metadata5("design:type", Function),
1360
+ _ts_metadata5("design:paramtypes", [
1361
+ Array,
1362
+ Array
1363
+ ]),
1364
+ _ts_metadata5("design:returntype", Number)
1365
+ ], EmbeddingAPI.prototype, "similarity", null);
1366
+ _ts_decorate5([
1367
+ RuntimeMethod("Get all stored embeddings"),
1368
+ _ts_metadata5("design:type", Function),
1369
+ _ts_metadata5("design:paramtypes", []),
1370
+ _ts_metadata5("design:returntype", Array)
1371
+ ], EmbeddingAPI.prototype, "getAll", null);
1372
+ _ts_decorate5([
1373
+ RuntimeMethod("Get count of stored embeddings"),
1374
+ _ts_metadata5("design:type", Function),
1375
+ _ts_metadata5("design:paramtypes", []),
1376
+ _ts_metadata5("design:returntype", Number)
1377
+ ], EmbeddingAPI.prototype, "count", null);
1378
+ EmbeddingAPI = _ts_decorate5([
1379
+ RuntimeAPI("embedding", "Embedding API - Client-side embedding with server-side vector storage")
1380
+ ], EmbeddingAPI);
1381
+ var embedding = new EmbeddingAPI();
1382
+
1383
+ // src/metadata/generated.ts
1384
+ var GENERATED_METADATA = [
1385
+ {
1386
+ "name": "approval",
1387
+ "description": "Approval API - Request explicit human approval for sensitive operations",
1388
+ "methods": [
1389
+ {
1390
+ "name": "request",
1391
+ "description": "Request approval from a human",
1392
+ "params": [
1393
+ {
1394
+ "name": "message",
1395
+ "type": "string",
1396
+ "description": "The message to display to the user",
1397
+ "optional": false
1398
+ },
1399
+ {
1400
+ "name": "context",
1401
+ "type": "Record<string, unknown>",
1402
+ "description": "Optional context information about what needs approval",
1403
+ "optional": true
1404
+ }
1405
+ ],
1406
+ "returns": "Promise<ApprovalResponse>"
1407
+ }
1408
+ ]
1409
+ },
1410
+ {
1411
+ "name": "cache",
1412
+ "description": "Cache API - Store and retrieve data with optional TTL",
1413
+ "methods": [
1414
+ {
1415
+ "name": "get",
1416
+ "description": "Get a value from cache by key",
1417
+ "params": [
1418
+ {
1419
+ "name": "key",
1420
+ "type": "string",
1421
+ "description": "Cache key",
1422
+ "optional": false
1423
+ }
1424
+ ],
1425
+ "returns": "Promise<T | null>"
1426
+ },
1427
+ {
1428
+ "name": "set",
1429
+ "description": "Set a value in cache with optional TTL",
1430
+ "params": [
1431
+ {
1432
+ "name": "key",
1433
+ "type": "string",
1434
+ "description": "Cache key",
1435
+ "optional": false
1436
+ },
1437
+ {
1438
+ "name": "value",
1439
+ "type": "unknown",
1440
+ "description": "Value to cache",
1441
+ "optional": false
1442
+ },
1443
+ {
1444
+ "name": "ttl",
1445
+ "type": "number",
1446
+ "description": "Time to live in seconds",
1447
+ "optional": true
1448
+ }
1449
+ ],
1450
+ "returns": "Promise<void>"
1451
+ },
1452
+ {
1453
+ "name": "delete",
1454
+ "description": "Delete a value from cache",
1455
+ "params": [
1456
+ {
1457
+ "name": "key",
1458
+ "type": "string",
1459
+ "description": "Cache key to delete",
1460
+ "optional": false
1461
+ }
1462
+ ],
1463
+ "returns": "Promise<void>"
1464
+ },
1465
+ {
1466
+ "name": "has",
1467
+ "description": "Check if a key exists in cache",
1468
+ "params": [
1469
+ {
1470
+ "name": "key",
1471
+ "type": "string",
1472
+ "description": "Cache key to check",
1473
+ "optional": false
1474
+ }
1475
+ ],
1476
+ "returns": "Promise<boolean>"
1477
+ },
1478
+ {
1479
+ "name": "clear",
1480
+ "description": "Clear all cache entries",
1481
+ "params": [],
1482
+ "returns": "Promise<void>"
1483
+ }
1484
+ ]
1485
+ },
1486
+ {
1487
+ "name": "embedding",
1488
+ "description": "Embedding API - Client-side embedding with server-side vector storage",
1489
+ "methods": [
1490
+ {
1491
+ "name": "embed",
1492
+ "description": "Request client to generate and store embeddings",
1493
+ "params": [
1494
+ {
1495
+ "name": "input",
1496
+ "type": "string | string[]",
1497
+ "description": "Text(s) to embed",
1498
+ "optional": false
1499
+ },
1500
+ {
1501
+ "name": "metadata",
1502
+ "type": "Record<string, unknown>",
1503
+ "description": "Optional metadata to store with embeddings",
1504
+ "optional": true
1505
+ }
1506
+ ],
1507
+ "returns": "Promise<string | string[]>"
1508
+ },
1509
+ {
1510
+ "name": "search",
1511
+ "description": "Search stored embeddings by similarity",
1512
+ "params": [
1513
+ {
1514
+ "name": "query",
1515
+ "type": "string",
1516
+ "description": "Search query text (will be embedded by client)",
1517
+ "optional": false
1518
+ },
1519
+ {
1520
+ "name": "options",
1521
+ "type": "Omit<SearchOptions, 'query'>",
1522
+ "description": "Search options (topK, minSimilarity, filter)",
1523
+ "optional": true
1524
+ }
1525
+ ],
1526
+ "returns": "Promise<SearchResult[]>"
1527
+ },
1528
+ {
1529
+ "name": "similarity",
1530
+ "description": "Calculate cosine similarity between two embedding vectors",
1531
+ "params": [
1532
+ {
1533
+ "name": "embedding1",
1534
+ "type": "number[]",
1535
+ "description": "First embedding vector",
1536
+ "optional": false
1537
+ },
1538
+ {
1539
+ "name": "embedding2",
1540
+ "type": "number[]",
1541
+ "description": "Second embedding vector",
1542
+ "optional": false
1543
+ }
1544
+ ],
1545
+ "returns": "number"
1546
+ },
1547
+ {
1548
+ "name": "getAll",
1549
+ "description": "Get all stored embeddings",
1550
+ "params": [],
1551
+ "returns": "EmbeddingRecord[]"
1552
+ },
1553
+ {
1554
+ "name": "count",
1555
+ "description": "Get count of stored embeddings",
1556
+ "params": [],
1557
+ "returns": "number"
1558
+ }
1559
+ ]
1560
+ },
1561
+ {
1562
+ "name": "llm",
1563
+ "description": "LLM API - Large Language Model calls using client-provided LLM (requires client.provideLLM())",
1564
+ "methods": [
1565
+ {
1566
+ "name": "call",
1567
+ "description": "Make an LLM call with a prompt",
1568
+ "params": [
1569
+ {
1570
+ "name": "options",
1571
+ "type": "LLMCallOptions",
1572
+ "description": "LLM call options including prompt",
1573
+ "optional": false
1574
+ }
1575
+ ],
1576
+ "returns": "Promise<string>"
1577
+ },
1578
+ {
1579
+ "name": "extract",
1580
+ "description": "Extract structured data from text using an LLM",
1581
+ "params": [
1582
+ {
1583
+ "name": "options",
1584
+ "type": "LLMExtractOptions",
1585
+ "description": "Extraction options with JSON schema",
1586
+ "optional": false
1587
+ }
1588
+ ],
1589
+ "returns": "Promise<T>"
1590
+ },
1591
+ {
1592
+ "name": "classify",
1593
+ "description": "Classify text into one of the provided categories",
1594
+ "params": [
1595
+ {
1596
+ "name": "options",
1597
+ "type": "LLMClassifyOptions",
1598
+ "description": "Classification options with categories",
1599
+ "optional": false
1600
+ }
1601
+ ],
1602
+ "returns": "Promise<string>"
1603
+ }
1604
+ ]
1605
+ },
1606
+ {
1607
+ "name": "progress",
1608
+ "description": "Progress API - Report execution progress to clients",
1609
+ "methods": [
1610
+ {
1611
+ "name": "report",
1612
+ "description": "Report progress with message and completion fraction",
1613
+ "params": [
1614
+ {
1615
+ "name": "message",
1616
+ "type": "string",
1617
+ "description": "Progress message",
1618
+ "optional": false
1619
+ },
1620
+ {
1621
+ "name": "fraction",
1622
+ "type": "number",
1623
+ "description": "Completion fraction (0-1)",
1624
+ "optional": false
1625
+ }
1626
+ ],
1627
+ "returns": "void"
1628
+ }
1629
+ ]
1630
+ }
1631
+ ];
1632
+ var TYPE_REGISTRY = [
1633
+ {
1634
+ "name": "ApprovalResponse",
1635
+ "definition": "export interface ApprovalResponse<T = unknown> {\n approved: boolean;\n response?: T;\n timestamp: number;\n}"
1636
+ },
1637
+ {
1638
+ "name": "SearchOptions",
1639
+ "definition": "interface SearchOptions {\n query: string;\n topK?: number;\n minSimilarity?: number;\n filter?: Record<string, unknown>;\n}"
1640
+ },
1641
+ {
1642
+ "name": "SearchResult",
1643
+ "definition": "interface SearchResult {\n id: string;\n text: string;\n similarity: number;\n metadata?: Record<string, unknown>;\n}"
1644
+ },
1645
+ {
1646
+ "name": "EmbeddingRecord",
1647
+ "definition": "interface EmbeddingRecord {\n id: string;\n text: string;\n embedding: number[];\n metadata?: Record<string, unknown>;\n}"
1648
+ },
1649
+ {
1650
+ "name": "LLMCallOptions",
1651
+ "definition": "interface LLMCallOptions {\n prompt: string;\n context?: Record<string, unknown>;\n model?: string;\n maxTokens?: number;\n temperature?: number;\n systemPrompt?: string;\n}"
1652
+ },
1653
+ {
1654
+ "name": "LLMExtractOptions",
1655
+ "definition": "interface LLMExtractOptions {\n prompt: string;\n context?: Record<string, unknown>;\n schema: unknown;\n}"
1656
+ },
1657
+ {
1658
+ "name": "LLMClassifyOptions",
1659
+ "definition": "interface LLMClassifyOptions {\n text: string;\n categories: string[];\n context?: Record<string, unknown>;\n}"
1660
+ }
1661
+ ];
1662
+
1663
+ // src/registry.ts
1664
+ function getAllAPIs() {
1665
+ return GENERATED_METADATA;
1666
+ }
1667
+ __name(getAllAPIs, "getAllAPIs");
1668
+ function getAPI(name) {
1669
+ return GENERATED_METADATA.find((api) => api.name === name);
1670
+ }
1671
+ __name(getAPI, "getAPI");
1672
+
1673
+ // src/metadata/index.ts
1674
+ function generateRuntimeTypes(apis, options) {
1675
+ let filteredApis = apis;
1676
+ if (options?.requestedApis && options.requestedApis.length > 0) {
1677
+ const requestedApis = options.requestedApis.map((api) => apis.find((a) => a.name === api));
1678
+ filteredApis = requestedApis.filter((api) => api !== void 0);
1679
+ } else if (options?.clientServices) {
1680
+ filteredApis = apis.filter((api) => {
1681
+ if (api.name === "llm" && !options.clientServices.hasLLM) return false;
1682
+ if (api.name === "approval" && !options.clientServices.hasApproval) return false;
1683
+ if (api.name === "embedding" && !options.clientServices.hasEmbedding) return false;
1684
+ if (api.name === "progress") return false;
1685
+ return true;
1686
+ });
1687
+ } else {
1688
+ filteredApis = apis.filter((api) => api.name === "cache");
1689
+ }
1690
+ let typescript = "// Runtime SDK Type Definitions\n\n";
1691
+ const usedTypes = /* @__PURE__ */ new Set();
1692
+ for (const api of filteredApis) {
1693
+ for (const method of api.methods) {
1694
+ const allTypes = [
1695
+ method.returns,
1696
+ ...method.params.map((p) => p.type)
1697
+ ].join(" ");
1698
+ const typeMatches = allTypes.match(/\b[A-Z][a-zA-Z]+\b/g);
1699
+ if (typeMatches) {
1700
+ typeMatches.forEach((t) => usedTypes.add(t));
1701
+ }
1702
+ }
1703
+ }
1704
+ for (const type of TYPE_REGISTRY) {
1705
+ const typeNameMatch = type.definition.match(/(?:interface|type)\s+([A-Z][a-zA-Z]+)/);
1706
+ const typeName = typeNameMatch?.[1];
1707
+ if (typeName && usedTypes.has(typeName)) {
1708
+ typescript += `${type.definition}
1709
+
1710
+ `;
1711
+ }
1712
+ }
1713
+ typescript += "// Runtime SDK\ndeclare const atp: {\n";
1714
+ for (const api of filteredApis) {
1715
+ typescript += ` /**
1716
+ `;
1717
+ for (const line of api.description.split("\n")) {
1718
+ typescript += ` * ${line}
1719
+ `;
1720
+ }
1721
+ typescript += ` */
1722
+ `;
1723
+ typescript += ` ${api.name}: {
1724
+ `;
1725
+ for (const method of api.methods) {
1726
+ typescript += ` /**
1727
+ `;
1728
+ typescript += ` * ${method.description}
1729
+ `;
1730
+ for (const param of method.params) {
1731
+ if (param.description) {
1732
+ typescript += ` * @param ${param.name} - ${param.description}
1733
+ `;
1734
+ }
1735
+ }
1736
+ if (method.returns !== "void") {
1737
+ const returnDesc = method.returns.startsWith("Promise") ? "Promise resolving to result" : "Result value";
1738
+ typescript += ` * @returns ${returnDesc}
1739
+ `;
1740
+ }
1741
+ typescript += ` */
1742
+ `;
1743
+ const paramStrings = method.params.map((p) => {
1744
+ const optional = p.optional ? "?" : "";
1745
+ const type = p.type.includes("\n") ? p.type.replace(/\n/g, "\n ") : p.type;
1746
+ return `${p.name}${optional}: ${type}`;
1747
+ });
1748
+ typescript += ` ${method.name}(${paramStrings.join(", ")}): ${method.returns};
1749
+ `;
1750
+ typescript += `
1751
+ `;
1752
+ }
1753
+ typescript += ` };
1754
+
1755
+ `;
1756
+ }
1757
+ typescript += "};\n\n";
1758
+ return typescript;
1759
+ }
1760
+ __name(generateRuntimeTypes, "generateRuntimeTypes");
1761
+
1762
+ export { ApprovalOperation, CallbackType, EmbeddingOperation, GENERATED_METADATA, LLMOperation, MemoryCacheBackend, PauseExecutionError, RedisCacheBackend, RuntimeAPI, RuntimeMethod, ToolOperation, VectorStore, approval, cache, cleanupExecutionState, cleanupOldExecutionStates, clearAPICallResults, clearCurrentExecutionId, clearVectorStore, clearVectorStoreExecutionId, cosineSimilarity, embedding, generateEmbeddingId, generateRuntimeTypes, getAPI, getAPICallResults, getAPIResultFromCache, getAllAPIs, getCachedResult, getCallSequenceNumber, getClientLLMCallback, getExecutionStateStats, getVectorStore, initializeApproval, initializeCache, initializeExecutionState, initializeLogger, initializeVectorStore, isPauseError, isReplayMode, llm, log, nextSequenceNumber, pauseForCallback, progress, resetAllExecutionState, runInExecutionContext, setAPIResultCache, setClientLLMCallback, setCurrentExecutionId, setPauseForClient, setProgressCallback, setReplayMode, setVectorStoreExecutionId, shouldPauseForClient, shutdownLogger, storeAPICallResult, storeAPIResultInCache, utils };
1763
+ //# sourceMappingURL=index.js.map
17
1764
  //# sourceMappingURL=index.js.map