@almadar/integrations 2.22.0 → 2.23.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.
@@ -1,11 +1,216 @@
1
- import { createRequire } from 'module';
2
1
  import { createLogger } from '@almadar/logger';
3
2
  import { integratorsRegistry } from '@almadar/core/patterns';
3
+ import Stripe2 from 'stripe';
4
+ import { google } from 'googleapis';
5
+ import twilio from 'twilio';
6
+ import sgMail from '@sendgrid/mail';
7
+ import { Resend } from 'resend';
8
+ import { getAvailableProvider, LLMClient, EmbeddingClient } from '@almadar/llm';
9
+ import { z } from 'zod';
10
+ import { execSync, spawn } from 'child_process';
11
+ import { mkdtempSync, writeFileSync, rmSync, promises } from 'fs';
12
+ import { join } from 'path';
13
+ import { tmpdir } from 'os';
14
+ import { Pool } from 'pg';
15
+ import { createRequire } from 'module';
4
16
 
5
- // src/runtime/RuntimeIntegrationManager.ts
17
+ // src/types.ts
18
+ var IntegrationError = class extends Error {
19
+ constructor(message, code = "UNKNOWN_ERROR", details) {
20
+ super(message);
21
+ this.name = "IntegrationError";
22
+ this.code = code;
23
+ this.details = details;
24
+ }
25
+ toJSON() {
26
+ return {
27
+ name: this.name,
28
+ message: this.message,
29
+ code: this.code,
30
+ integration: this.integration,
31
+ action: this.action,
32
+ details: this.details
33
+ };
34
+ }
35
+ };
36
+ var ConsoleLogger = class {
37
+ constructor(_level = "info") {
38
+ this.log = createLogger("almadar:integrations");
39
+ }
40
+ debug(message, meta) {
41
+ this.log.debug(message, meta);
42
+ }
43
+ info(message, meta) {
44
+ this.log.info(message, meta);
45
+ }
46
+ warn(message, meta) {
47
+ this.log.warn(message, meta);
48
+ }
49
+ error(message, meta) {
50
+ this.log.error(message, meta);
51
+ }
52
+ };
53
+ function validateParams(integration, action, params) {
54
+ const typedRegistry = integratorsRegistry;
55
+ const registry = typedRegistry.integrators[integration];
56
+ if (!registry) {
57
+ return {
58
+ valid: false,
59
+ errors: [
60
+ {
61
+ param: "integration",
62
+ message: `Unknown integration: ${integration}`
63
+ }
64
+ ]
65
+ };
66
+ }
67
+ const actionDef = registry.actions.find((a) => a.name === action);
68
+ if (!actionDef) {
69
+ return {
70
+ valid: false,
71
+ errors: [{ param: "action", message: `Unknown action: ${action}` }]
72
+ };
73
+ }
74
+ const errors = [];
75
+ for (const paramDef of actionDef.params) {
76
+ if (paramDef.required && !(paramDef.name in params)) {
77
+ errors.push({
78
+ param: paramDef.name,
79
+ message: `Missing required parameter: ${paramDef.name}`
80
+ });
81
+ }
82
+ if (paramDef.name in params) {
83
+ const value = params[paramDef.name];
84
+ const expectedType = paramDef.type;
85
+ const actualType = typeof value;
86
+ if (expectedType === "number" && actualType !== "number") {
87
+ errors.push({
88
+ param: paramDef.name,
89
+ message: `Expected ${expectedType}, got ${actualType}`
90
+ });
91
+ }
92
+ if (expectedType === "string" && actualType !== "string") {
93
+ errors.push({
94
+ param: paramDef.name,
95
+ message: `Expected ${expectedType}, got ${actualType}`
96
+ });
97
+ }
98
+ if (expectedType === "array" && !Array.isArray(value)) {
99
+ errors.push({
100
+ param: paramDef.name,
101
+ message: `Expected array, got ${actualType}`
102
+ });
103
+ }
104
+ if (expectedType === "object" && (actualType !== "object" || Array.isArray(value) || value === null)) {
105
+ errors.push({
106
+ param: paramDef.name,
107
+ message: `Expected object, got ${actualType}`
108
+ });
109
+ }
110
+ }
111
+ }
112
+ return {
113
+ valid: errors.length === 0,
114
+ errors
115
+ };
116
+ }
117
+
118
+ // src/core/retry.ts
119
+ async function withRetry(fn, config) {
120
+ const {
121
+ maxAttempts,
122
+ backoffMs,
123
+ maxBackoffMs = 3e4,
124
+ retryableErrors
125
+ } = config;
126
+ let lastError;
127
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
128
+ try {
129
+ return await fn();
130
+ } catch (error) {
131
+ lastError = error;
132
+ if (error && typeof error === "object" && "code" in error && retryableErrors) {
133
+ const integrationError = error;
134
+ if (!retryableErrors.includes(integrationError.code)) {
135
+ throw error;
136
+ }
137
+ }
138
+ if (attempt === maxAttempts) {
139
+ throw error;
140
+ }
141
+ const delay = Math.min(
142
+ backoffMs * Math.pow(2, attempt - 1),
143
+ maxBackoffMs
144
+ );
145
+ await new Promise((resolve) => setTimeout(resolve, delay));
146
+ }
147
+ }
148
+ throw lastError;
149
+ }
150
+
151
+ // src/core/BaseIntegration.ts
152
+ var BaseIntegration = class {
153
+ constructor(config) {
154
+ this.config = config;
155
+ this.logger = config.logger || new ConsoleLogger();
156
+ }
157
+ /**
158
+ * Validate action params against registry
159
+ */
160
+ validateParams(action, params) {
161
+ return validateParams(this.config.name, action, params);
162
+ }
163
+ /**
164
+ * Handle errors uniformly
165
+ */
166
+ handleError(action, error) {
167
+ this.logger.error(`Integration error in ${this.config.name}.${action}`, {
168
+ error: error instanceof Error ? error : new Error(String(error))
169
+ });
170
+ const integrationError = error instanceof Error ? error : new Error(String(error));
171
+ return {
172
+ success: false,
173
+ error: integrationError,
174
+ metadata: this.createMetadata(action, 0, 0)
175
+ };
176
+ }
177
+ /**
178
+ * Create metadata for result
179
+ */
180
+ createMetadata(action, duration, retries = 0) {
181
+ return {
182
+ integration: this.config.name,
183
+ action,
184
+ duration,
185
+ retries,
186
+ timestamp: Date.now()
187
+ };
188
+ }
189
+ /**
190
+ * Execute with retry logic
191
+ */
192
+ async executeWithRetry(fn) {
193
+ if (!this.config.retry) {
194
+ return fn();
195
+ }
196
+ return withRetry(fn, {
197
+ maxAttempts: this.config.retry.maxAttempts,
198
+ backoffMs: this.config.retry.backoffMs,
199
+ maxBackoffMs: this.config.retry.maxBackoffMs,
200
+ retryableErrors: [
201
+ "TIMEOUT_ERROR",
202
+ "NETWORK_ERROR",
203
+ "RATE_LIMIT_ERROR"
204
+ ]
205
+ });
206
+ }
207
+ };
6
208
 
7
209
  // src/registry.ts
8
210
  var INTEGRATION_REGISTRY = {};
211
+ function registerIntegration(name, constructor) {
212
+ INTEGRATION_REGISTRY[name] = constructor;
213
+ }
9
214
  function getIntegration(name) {
10
215
  return INTEGRATION_REGISTRY[name];
11
216
  }
@@ -76,198 +281,3270 @@ var IntegrationFactory = class {
76
281
  this.configs.clear();
77
282
  }
78
283
  };
79
- var ConsoleLogger = class {
80
- constructor(_level = "info") {
81
- this.log = createLogger("almadar:integrations");
284
+
285
+ // src/integrations/stripe/index.ts
286
+ var STRIPE_API_VERSION = "2025-02-24.acacia";
287
+ function isoFromUnix(seconds) {
288
+ return new Date(seconds * 1e3).toISOString();
289
+ }
290
+ function priceToTier(priceId, prices) {
291
+ if (priceId === prices.solo) return "solo";
292
+ if (priceId === prices.teams) return "teams";
293
+ return null;
294
+ }
295
+ function mapStatus(status) {
296
+ switch (status) {
297
+ case "active":
298
+ case "past_due":
299
+ case "canceled":
300
+ case "incomplete":
301
+ case "incomplete_expired":
302
+ case "trialing":
303
+ case "unpaid":
304
+ return status;
305
+ case "paused":
306
+ return "unpaid";
307
+ default: {
308
+ return "incomplete";
309
+ }
82
310
  }
83
- debug(message, meta) {
84
- this.log.debug(message, meta);
311
+ }
312
+ function shapeSubscription(sub, prices) {
313
+ const firstItem = sub.items.data[0];
314
+ const priceId = firstItem?.price.id ?? "";
315
+ const quantity = firstItem?.quantity ?? 1;
316
+ const customerId = typeof sub.customer === "string" ? sub.customer : sub.customer.id;
317
+ return {
318
+ subscriptionId: sub.id,
319
+ customerId,
320
+ status: mapStatus(sub.status),
321
+ priceId,
322
+ quantity,
323
+ currentPeriodStart: isoFromUnix(sub.current_period_start),
324
+ currentPeriodEnd: isoFromUnix(sub.current_period_end),
325
+ cancelAtPeriodEnd: sub.cancel_at_period_end,
326
+ tier: priceToTier(priceId, prices)
327
+ };
328
+ }
329
+ function shapeCustomer(customer) {
330
+ return {
331
+ customerId: customer.id,
332
+ email: customer.email ?? null,
333
+ almadarUid: customer.metadata?.almadarUid ?? null
334
+ };
335
+ }
336
+ var StripeIntegration = class extends BaseIntegration {
337
+ constructor(config) {
338
+ super(config);
339
+ const apiKey = config.env.STRIPE_SECRET_KEY;
340
+ if (!apiKey) {
341
+ throw new Error("STRIPE_SECRET_KEY not configured");
342
+ }
343
+ this.client = new Stripe2(apiKey, {
344
+ apiVersion: STRIPE_API_VERSION
345
+ });
346
+ this.prices = {
347
+ solo: config.env.STRIPE_PRICE_SOLO ?? "",
348
+ teams: config.env.STRIPE_PRICE_TEAMS ?? ""
349
+ };
350
+ this.logger.info("Stripe integration initialized");
85
351
  }
86
- info(message, meta) {
87
- this.log.info(message, meta);
352
+ /** Provisioned Price IDs the integration was constructed with. */
353
+ getPrices() {
354
+ return this.prices;
88
355
  }
89
- warn(message, meta) {
90
- this.log.warn(message, meta);
356
+ async execute(action, params) {
357
+ const validation = this.validateParams(action, params);
358
+ if (!validation.valid) {
359
+ return {
360
+ success: false,
361
+ error: {
362
+ name: "IntegrationError",
363
+ message: "Validation failed",
364
+ code: "VALIDATION_ERROR",
365
+ details: validation.errors
366
+ },
367
+ metadata: this.createMetadata(action, 0)
368
+ };
369
+ }
370
+ const startTime = Date.now();
371
+ const retries = 0;
372
+ try {
373
+ let data;
374
+ switch (action) {
375
+ case "createPaymentIntent":
376
+ data = await this.executeWithRetry(
377
+ () => this.createPaymentIntent(params)
378
+ );
379
+ break;
380
+ case "confirmPayment":
381
+ data = await this.executeWithRetry(() => this.confirmPayment(params));
382
+ break;
383
+ case "refund":
384
+ data = await this.executeWithRetry(() => this.refund(params));
385
+ break;
386
+ default:
387
+ throw new Error(`Unknown action: ${action}`);
388
+ }
389
+ return {
390
+ success: true,
391
+ data,
392
+ metadata: this.createMetadata(action, Date.now() - startTime, retries)
393
+ };
394
+ } catch (error) {
395
+ return this.handleError(action, error);
396
+ }
91
397
  }
92
- error(message, meta) {
93
- this.log.error(message, meta);
398
+ async createPaymentIntent(params) {
399
+ const { amount, currency, metadata } = params;
400
+ this.logger.debug("Creating payment intent", {
401
+ amount: Number(amount),
402
+ currency: String(currency ?? "")
403
+ });
404
+ return await this.client.paymentIntents.create({
405
+ amount,
406
+ currency,
407
+ metadata
408
+ });
94
409
  }
95
- };
96
- function validateParams(integration, action, params) {
97
- const typedRegistry = integratorsRegistry;
98
- const registry = typedRegistry.integrators[integration];
99
- if (!registry) {
100
- return {
101
- valid: false,
102
- errors: [
103
- {
104
- param: "integration",
105
- message: `Unknown integration: ${integration}`
106
- }
107
- ]
108
- };
410
+ async confirmPayment(params) {
411
+ const { paymentIntentId } = params;
412
+ this.logger.debug("Confirming payment", {
413
+ paymentIntentId: String(paymentIntentId ?? "")
414
+ });
415
+ return await this.client.paymentIntents.confirm(paymentIntentId);
109
416
  }
110
- const actionDef = registry.actions.find((a) => a.name === action);
111
- if (!actionDef) {
112
- return {
113
- valid: false,
114
- errors: [{ param: "action", message: `Unknown action: ${action}` }]
417
+ async refund(params) {
418
+ const { paymentIntentId, amount } = params;
419
+ this.logger.debug("Creating refund", {
420
+ paymentIntentId: String(paymentIntentId ?? ""),
421
+ amount: Number(amount)
422
+ });
423
+ return await this.client.refunds.create({
424
+ payment_intent: paymentIntentId,
425
+ amount
426
+ });
427
+ }
428
+ // ───────────────────────────────────────────────────────────────────
429
+ // Typed action surface — canonical Almadar shapes only.
430
+ // ───────────────────────────────────────────────────────────────────
431
+ /** Look up an existing customer by Stripe ID. */
432
+ async getCustomer(customerId) {
433
+ this.logger.debug("Fetching customer", { customerId });
434
+ const customer = await this.client.customers.retrieve(customerId);
435
+ if (customer.deleted === true) return null;
436
+ return shapeCustomer(customer);
437
+ }
438
+ /**
439
+ * Create a Stripe Customer for the given Almadar user. `almadarUid` is
440
+ * stored as Stripe metadata so webhook handlers can resolve back to
441
+ * the right `users/{uid}` document.
442
+ */
443
+ async createCustomer(input) {
444
+ this.logger.debug("Creating customer", { almadarUid: input.almadarUid });
445
+ const customer = await this.client.customers.create({
446
+ email: input.email,
447
+ name: input.displayName ?? void 0,
448
+ metadata: { almadarUid: input.almadarUid }
449
+ });
450
+ return shapeCustomer(customer);
451
+ }
452
+ /**
453
+ * Create a Stripe-hosted Checkout Session for the given tier. Client
454
+ * redirects the user to the returned `url`; on success Stripe fires
455
+ * `customer.subscription.created`, which the apps/builder webhook
456
+ * handler turns into a `users/{uid}.tier` write.
457
+ */
458
+ async createCheckoutSession(input) {
459
+ const price = input.tier === "solo" ? this.prices.solo : this.prices.teams;
460
+ if (!price) {
461
+ throw new Error(`STRIPE_PRICE_${input.tier.toUpperCase()} not configured`);
462
+ }
463
+ this.logger.debug("Creating Checkout session", {
464
+ tier: input.tier,
465
+ quantity: input.quantity,
466
+ hasCustomer: input.customerId !== null
467
+ });
468
+ const session = await this.client.checkout.sessions.create({
469
+ mode: "subscription",
470
+ customer: input.customerId ?? void 0,
471
+ line_items: [{ price, quantity: input.quantity }],
472
+ success_url: input.successUrl,
473
+ cancel_url: input.cancelUrl,
474
+ subscription_data: {
475
+ metadata: input.metadata
476
+ },
477
+ automatic_tax: { enabled: true },
478
+ allow_promotion_codes: true
479
+ });
480
+ return {
481
+ url: session.url ?? "",
482
+ sessionId: session.id,
483
+ customerId: typeof session.customer === "string" ? session.customer : session.customer?.id ?? null
484
+ };
485
+ }
486
+ /** Create a Billing Portal session for self-service plan management. */
487
+ async createBillingPortalSession(input) {
488
+ this.logger.debug("Creating Portal session", { customerId: input.customerId });
489
+ const session = await this.client.billingPortal.sessions.create({
490
+ customer: input.customerId,
491
+ return_url: input.returnUrl
492
+ });
493
+ return {
494
+ url: session.url,
495
+ customerId: input.customerId
496
+ };
497
+ }
498
+ /** Fetch a subscription and shape it into the canonical form. */
499
+ async getSubscription(subscriptionId) {
500
+ this.logger.debug("Fetching subscription", { subscriptionId });
501
+ const sub = await this.client.subscriptions.retrieve(subscriptionId);
502
+ return shapeSubscription(sub, this.prices);
503
+ }
504
+ /**
505
+ * Create a subscription directly (server-side, no Checkout). Used by
506
+ * P13.3 Solo → Teams upgrade flow.
507
+ */
508
+ async createSubscription(input) {
509
+ const price = input.tier === "solo" ? this.prices.solo : this.prices.teams;
510
+ if (!price) {
511
+ throw new Error(`STRIPE_PRICE_${input.tier.toUpperCase()} not configured`);
512
+ }
513
+ this.logger.debug("Creating subscription", {
514
+ customerId: input.customerId,
515
+ tier: input.tier,
516
+ quantity: input.quantity
517
+ });
518
+ const sub = await this.client.subscriptions.create({
519
+ customer: input.customerId,
520
+ items: [{ price, quantity: input.quantity }],
521
+ metadata: input.metadata,
522
+ proration_behavior: "create_prorations",
523
+ automatic_tax: { enabled: true }
524
+ });
525
+ return shapeSubscription(sub, this.prices);
526
+ }
527
+ /**
528
+ * Update quantity or cancel-at-period-end. Used for Teams seat resize
529
+ * and Solo → Teams transition.
530
+ */
531
+ async updateSubscription(input) {
532
+ this.logger.debug("Updating subscription", { subscriptionId: input.subscriptionId });
533
+ const update = {
534
+ proration_behavior: "create_prorations"
535
+ };
536
+ if (typeof input.quantity === "number") {
537
+ const existing = await this.client.subscriptions.retrieve(input.subscriptionId);
538
+ const itemId = existing.items.data[0]?.id;
539
+ if (itemId !== void 0) {
540
+ update.items = [{ id: itemId, quantity: input.quantity }];
541
+ }
542
+ }
543
+ if (typeof input.cancelAtPeriodEnd === "boolean") {
544
+ update.cancel_at_period_end = input.cancelAtPeriodEnd;
545
+ }
546
+ const sub = await this.client.subscriptions.update(
547
+ input.subscriptionId,
548
+ update
549
+ );
550
+ return shapeSubscription(sub, this.prices);
551
+ }
552
+ /**
553
+ * Cancel a subscription. Defaults to `atPeriodEnd: true` so the user
554
+ * keeps access until the current period ends.
555
+ */
556
+ async cancelSubscription(input) {
557
+ this.logger.debug("Canceling subscription", {
558
+ subscriptionId: input.subscriptionId,
559
+ atPeriodEnd: input.atPeriodEnd
560
+ });
561
+ if (input.atPeriodEnd) {
562
+ const sub2 = await this.client.subscriptions.update(input.subscriptionId, {
563
+ cancel_at_period_end: true
564
+ });
565
+ return shapeSubscription(sub2, this.prices);
566
+ }
567
+ const sub = await this.client.subscriptions.cancel(input.subscriptionId);
568
+ return shapeSubscription(sub, this.prices);
569
+ }
570
+ };
571
+ registerIntegration("stripe", StripeIntegration);
572
+ var YouTubeIntegration = class extends BaseIntegration {
573
+ constructor(config) {
574
+ super(config);
575
+ const apiKey = config.env.YOUTUBE_API_KEY;
576
+ if (!apiKey) {
577
+ throw new Error("YOUTUBE_API_KEY not configured");
578
+ }
579
+ this.client = google.youtube({
580
+ version: "v3",
581
+ auth: apiKey
582
+ });
583
+ this.logger.info("YouTube integration initialized");
584
+ }
585
+ async execute(action, params) {
586
+ const validation = this.validateParams(action, params);
587
+ if (!validation.valid) {
588
+ return {
589
+ success: false,
590
+ error: {
591
+ name: "IntegrationError",
592
+ message: "Validation failed",
593
+ code: "VALIDATION_ERROR",
594
+ details: validation.errors
595
+ },
596
+ metadata: this.createMetadata(action, 0)
597
+ };
598
+ }
599
+ const startTime = Date.now();
600
+ let retries = 0;
601
+ try {
602
+ let data;
603
+ switch (action) {
604
+ case "search":
605
+ data = await this.executeWithRetry(() => this.search(params));
606
+ break;
607
+ case "getVideo":
608
+ data = await this.executeWithRetry(() => this.getVideo(params));
609
+ break;
610
+ case "getChannel":
611
+ data = await this.executeWithRetry(() => this.getChannel(params));
612
+ break;
613
+ default:
614
+ throw new Error(`Unknown action: ${action}`);
615
+ }
616
+ return {
617
+ success: true,
618
+ data,
619
+ metadata: this.createMetadata(action, Date.now() - startTime, retries)
620
+ };
621
+ } catch (error) {
622
+ return this.handleError(action, error);
623
+ }
624
+ }
625
+ async search(params) {
626
+ const { query, maxResults, type } = params;
627
+ this.logger.debug("Searching YouTube", { query: String(query ?? ""), maxResults: Number(maxResults ?? 10), type: String(type ?? "") });
628
+ const response = await this.client.search.list({
629
+ part: ["snippet"],
630
+ q: query,
631
+ maxResults: maxResults || 10,
632
+ type: type ? [type] : void 0
633
+ });
634
+ return response.data.items?.map((item) => ({
635
+ videoId: item.id?.videoId,
636
+ title: item.snippet?.title,
637
+ thumbnail: item.snippet?.thumbnails?.default?.url,
638
+ description: item.snippet?.description
639
+ }));
640
+ }
641
+ async getVideo(params) {
642
+ const { videoId } = params;
643
+ this.logger.debug("Getting video details", { videoId: String(videoId ?? "") });
644
+ const response = await this.client.videos.list({
645
+ part: ["snippet", "statistics"],
646
+ id: [videoId]
647
+ });
648
+ const video = response.data.items?.[0];
649
+ if (!video) {
650
+ throw new Error(`Video not found: ${videoId}`);
651
+ }
652
+ return {
653
+ title: video.snippet?.title,
654
+ description: video.snippet?.description,
655
+ viewCount: video.statistics?.viewCount,
656
+ likeCount: video.statistics?.likeCount
657
+ };
658
+ }
659
+ async getChannel(params) {
660
+ const { channelId } = params;
661
+ this.logger.debug("Getting channel details", { channelId: String(channelId ?? "") });
662
+ const response = await this.client.channels.list({
663
+ part: ["snippet", "statistics"],
664
+ id: [channelId]
665
+ });
666
+ const channel = response.data.items?.[0];
667
+ if (!channel) {
668
+ throw new Error(`Channel not found: ${channelId}`);
669
+ }
670
+ return {
671
+ name: channel.snippet?.title,
672
+ description: channel.snippet?.description,
673
+ subscriberCount: channel.statistics?.subscriberCount
674
+ };
675
+ }
676
+ };
677
+ registerIntegration("youtube", YouTubeIntegration);
678
+ var TwilioIntegration = class extends BaseIntegration {
679
+ constructor(config) {
680
+ super(config);
681
+ const accountSid = config.env.TWILIO_ACCOUNT_SID;
682
+ const authToken = config.env.TWILIO_AUTH_TOKEN;
683
+ this.phoneNumber = config.env.TWILIO_PHONE_NUMBER || "";
684
+ if (!accountSid || !authToken) {
685
+ throw new Error("TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN not configured");
686
+ }
687
+ this.client = twilio(accountSid, authToken);
688
+ this.logger.info("Twilio integration initialized");
689
+ }
690
+ async execute(action, params) {
691
+ const validation = this.validateParams(action, params);
692
+ if (!validation.valid) {
693
+ return {
694
+ success: false,
695
+ error: {
696
+ name: "IntegrationError",
697
+ message: "Validation failed",
698
+ code: "VALIDATION_ERROR",
699
+ details: validation.errors
700
+ },
701
+ metadata: this.createMetadata(action, 0)
702
+ };
703
+ }
704
+ const startTime = Date.now();
705
+ let retries = 0;
706
+ try {
707
+ let data;
708
+ switch (action) {
709
+ case "sendSMS":
710
+ data = await this.executeWithRetry(() => this.sendSMS(params));
711
+ break;
712
+ case "sendWhatsApp":
713
+ data = await this.executeWithRetry(() => this.sendWhatsApp(params));
714
+ break;
715
+ default:
716
+ throw new Error(`Unknown action: ${action}`);
717
+ }
718
+ return {
719
+ success: true,
720
+ data,
721
+ metadata: this.createMetadata(action, Date.now() - startTime, retries)
722
+ };
723
+ } catch (error) {
724
+ return this.handleError(action, error);
725
+ }
726
+ }
727
+ async sendSMS(params) {
728
+ const { to, body } = params;
729
+ this.logger.debug("Sending SMS", { to: String(to ?? "") });
730
+ const message = await this.client.messages.create({
731
+ from: this.phoneNumber,
732
+ to,
733
+ body
734
+ });
735
+ return {
736
+ sid: message.sid,
737
+ status: message.status
738
+ };
739
+ }
740
+ async sendWhatsApp(params) {
741
+ const { to, body } = params;
742
+ this.logger.debug("Sending WhatsApp message", { to: String(to ?? "") });
743
+ const message = await this.client.messages.create({
744
+ from: `whatsapp:${this.phoneNumber}`,
745
+ to: `whatsapp:${to}`,
746
+ body
747
+ });
748
+ return {
749
+ sid: message.sid,
750
+ status: message.status
751
+ };
752
+ }
753
+ };
754
+ registerIntegration("twilio", TwilioIntegration);
755
+ var EmailIntegration = class extends BaseIntegration {
756
+ constructor(config) {
757
+ super(config);
758
+ this.provider = config.env.PROVIDER || "sendgrid";
759
+ this.fromEmail = config.env.FROM_EMAIL || "noreply@example.com";
760
+ if (this.provider === "sendgrid") {
761
+ const apiKey = config.env.SENDGRID_API_KEY;
762
+ if (!apiKey) {
763
+ throw new Error("SENDGRID_API_KEY not configured");
764
+ }
765
+ sgMail.setApiKey(apiKey);
766
+ } else if (this.provider === "resend") {
767
+ const apiKey = config.env.RESEND_API_KEY;
768
+ if (!apiKey) {
769
+ throw new Error("RESEND_API_KEY not configured");
770
+ }
771
+ this.resendClient = new Resend(apiKey);
772
+ }
773
+ this.logger.info(`Email integration initialized (${this.provider})`);
774
+ }
775
+ async execute(action, params) {
776
+ const validation = this.validateParams(action, params);
777
+ if (!validation.valid) {
778
+ return {
779
+ success: false,
780
+ error: {
781
+ name: "IntegrationError",
782
+ message: "Validation failed",
783
+ code: "VALIDATION_ERROR",
784
+ details: validation.errors
785
+ },
786
+ metadata: this.createMetadata(action, 0)
787
+ };
788
+ }
789
+ const startTime = Date.now();
790
+ let retries = 0;
791
+ try {
792
+ let data;
793
+ switch (action) {
794
+ case "send":
795
+ data = await this.executeWithRetry(() => this.send(params));
796
+ break;
797
+ default:
798
+ throw new Error(`Unknown action: ${action}`);
799
+ }
800
+ return {
801
+ success: true,
802
+ data,
803
+ metadata: this.createMetadata(action, Date.now() - startTime, retries)
804
+ };
805
+ } catch (error) {
806
+ return this.handleError(action, error);
807
+ }
808
+ }
809
+ async send(params) {
810
+ const { to, subject, body, from } = params;
811
+ this.logger.debug("Sending email", { to: String(to), subject: String(subject), provider: this.provider });
812
+ if (this.provider === "sendgrid") {
813
+ return await this.sendViaSendGrid(
814
+ to,
815
+ subject,
816
+ body,
817
+ from || this.fromEmail
818
+ );
819
+ } else if (this.provider === "resend") {
820
+ return await this.sendViaResend(
821
+ to,
822
+ subject,
823
+ body,
824
+ from || this.fromEmail
825
+ );
826
+ }
827
+ throw new Error(`Unknown email provider: ${this.provider}`);
828
+ }
829
+ async sendViaSendGrid(to, subject, body, from) {
830
+ const msg = {
831
+ to,
832
+ from,
833
+ subject,
834
+ html: body
835
+ };
836
+ const response = await sgMail.send(msg);
837
+ return {
838
+ id: response[0].headers["x-message-id"],
839
+ status: "sent"
840
+ };
841
+ }
842
+ async sendViaResend(to, subject, body, from) {
843
+ if (!this.resendClient) {
844
+ throw new Error("Resend client not initialized");
845
+ }
846
+ const response = await this.resendClient.emails.send({
847
+ from,
848
+ to,
849
+ subject,
850
+ html: body
851
+ });
852
+ return {
853
+ id: response.data?.id,
854
+ status: "sent"
855
+ };
856
+ }
857
+ };
858
+ registerIntegration("email", EmailIntegration);
859
+ var LLMIntegration = class extends BaseIntegration {
860
+ constructor(config) {
861
+ super(config);
862
+ this.client = null;
863
+ this.embeddings = null;
864
+ const configuredProvider = config.env.PROVIDER;
865
+ this.provider = configuredProvider || getAvailableProvider() || "anthropic";
866
+ this.logger.info(`LLM integration initialized (provider: ${this.provider})`);
867
+ }
868
+ /**
869
+ * Lazily create client — avoids throwing on construction if API key is missing.
870
+ * The client will throw a clear error when actually used without a key.
871
+ */
872
+ getClient() {
873
+ if (!this.client) {
874
+ this.client = new LLMClient({
875
+ provider: this.provider,
876
+ temperature: 0.7,
877
+ trackTokens: true
878
+ });
879
+ }
880
+ return this.client;
881
+ }
882
+ /**
883
+ * Lazily create the embeddings client. Embeddings route through a dedicated
884
+ * embedding model (default OpenRouter `baai/bge-base-en-v1.5`, matching
885
+ * `@almadar/curation-core`), independent of the chat provider/key, because
886
+ * most chat providers do not expose an embeddings endpoint. Override via
887
+ * `EMBEDDING_PROVIDER` / `EMBEDDING_MODEL` / `EMBEDDING_API_KEY`.
888
+ */
889
+ getEmbeddings() {
890
+ if (!this.embeddings) {
891
+ this.embeddings = new EmbeddingClient({
892
+ provider: this.config.env.EMBEDDING_PROVIDER ?? "openrouter",
893
+ model: this.config.env.EMBEDDING_MODEL ?? "baai/bge-base-en-v1.5",
894
+ apiKey: this.config.env.EMBEDDING_API_KEY
895
+ });
896
+ }
897
+ return this.embeddings;
898
+ }
899
+ async execute(action, params) {
900
+ const validation = this.validateParams(action, params);
901
+ if (!validation.valid) {
902
+ return {
903
+ success: false,
904
+ error: {
905
+ name: "IntegrationError",
906
+ message: "Validation failed",
907
+ code: "VALIDATION_ERROR",
908
+ details: validation.errors
909
+ },
910
+ metadata: this.createMetadata(action, 0)
911
+ };
912
+ }
913
+ const startTime = Date.now();
914
+ try {
915
+ let data;
916
+ switch (action) {
917
+ case "generate":
918
+ data = await this.executeWithRetry(() => this.generate(params));
919
+ break;
920
+ case "classify":
921
+ data = await this.executeWithRetry(() => this.classify(params));
922
+ break;
923
+ case "extract":
924
+ data = await this.executeWithRetry(() => this.extract(params));
925
+ break;
926
+ case "summarize":
927
+ data = await this.executeWithRetry(() => this.summarize(params));
928
+ break;
929
+ case "embed":
930
+ data = await this.executeWithRetry(() => this.embed(params));
931
+ break;
932
+ default:
933
+ throw new Error(`Unknown action: ${action}`);
934
+ }
935
+ return {
936
+ success: true,
937
+ data,
938
+ metadata: this.createMetadata(action, Date.now() - startTime)
939
+ };
940
+ } catch (error) {
941
+ return this.handleError(action, error);
942
+ }
943
+ }
944
+ async generate(params) {
945
+ const {
946
+ systemPrompt,
947
+ userPrompt,
948
+ model,
949
+ temperature,
950
+ maxTokens
951
+ } = params;
952
+ this.logger.debug("Generating content", { model, temperature });
953
+ const client = model ? new LLMClient({ provider: this.provider, model, temperature: temperature ?? 0.7 }) : this.getClient();
954
+ const response = await client.callWithMetadata({
955
+ systemPrompt: systemPrompt || "You are a helpful assistant.",
956
+ userPrompt,
957
+ maxTokens: maxTokens ?? 1024,
958
+ temperature,
959
+ skipSchemaValidation: true
960
+ });
961
+ return {
962
+ content: response.data,
963
+ usage: response.usage ? {
964
+ promptTokens: response.usage.promptTokens,
965
+ completionTokens: response.usage.completionTokens,
966
+ totalTokens: response.usage.totalTokens
967
+ } : { tokens: 0 }
968
+ };
969
+ }
970
+ async classify(params) {
971
+ const { text, categories, model } = params;
972
+ this.logger.debug("Classifying text", { categories: categories.join(", ") });
973
+ const ClassificationSchema = z.object({
974
+ category: z.enum(categories),
975
+ confidence: z.number().min(0).max(1),
976
+ reasoning: z.string()
977
+ });
978
+ const client = model ? new LLMClient({ provider: this.provider, model, temperature: 0.1 }) : this.getClient();
979
+ const result = await client.call({
980
+ systemPrompt: `You are a text classifier. Classify the given text into one of these categories: ${categories.join(", ")}. Return JSON with: category, confidence (0-1), and reasoning.`,
981
+ userPrompt: text,
982
+ schema: ClassificationSchema,
983
+ temperature: 0.1
984
+ });
985
+ return result;
986
+ }
987
+ async extract(params) {
988
+ const { text, schema, model } = params;
989
+ this.logger.debug("Extracting structured data", { schema: String(schema ?? "") });
990
+ const ExtractSchema = z.record(z.unknown());
991
+ const client = model ? new LLMClient({ provider: this.provider, model, temperature: 0.2 }) : this.getClient();
992
+ const schemaDescription = JSON.stringify(schema, null, 2);
993
+ const result = await client.call({
994
+ systemPrompt: `You are a structured data extractor. Extract data from the given text according to this schema:
995
+
996
+ ${schemaDescription}
997
+
998
+ Return ONLY valid JSON matching the schema.`,
999
+ userPrompt: text,
1000
+ schema: ExtractSchema,
1001
+ temperature: 0.2,
1002
+ skipSchemaValidation: true
1003
+ });
1004
+ return result;
1005
+ }
1006
+ async summarize(params) {
1007
+ const { text, maxLength, style, model } = params;
1008
+ this.logger.debug("Summarizing text", { maxLength, style });
1009
+ const SummarySchema = z.object({
1010
+ summary: z.string(),
1011
+ keyPoints: z.array(z.string())
1012
+ });
1013
+ const styleInstructions = style === "bullet" ? "Use bullet points." : style === "detailed" ? "Be thorough and detailed." : "Be concise.";
1014
+ const lengthInstructions = maxLength ? `Keep the summary under ${maxLength} words.` : "";
1015
+ const client = model ? new LLMClient({ provider: this.provider, model, temperature: 0.3 }) : this.getClient();
1016
+ const result = await client.call({
1017
+ systemPrompt: `You are a text summarizer. ${styleInstructions} ${lengthInstructions} Return JSON with: summary (string) and keyPoints (array of strings).`,
1018
+ userPrompt: text,
1019
+ schema: SummarySchema,
1020
+ temperature: 0.3
1021
+ });
1022
+ return result;
1023
+ }
1024
+ async embed(params) {
1025
+ const { texts } = params;
1026
+ if (!Array.isArray(texts)) {
1027
+ throw new Error("llm.embed: `texts` must be an array of strings");
1028
+ }
1029
+ this.logger.debug("Embedding texts", { count: texts.length });
1030
+ const batch = await this.getEmbeddings().embedBatch(texts);
1031
+ return { embeddings: batch.embeddings };
1032
+ }
1033
+ };
1034
+ registerIntegration("llm", LLMIntegration);
1035
+
1036
+ // src/integrations/ml/index.ts
1037
+ var INFERRED_EVENT = "INFERRED";
1038
+ var INFER_FAILED_EVENT = "INFER_FAILED";
1039
+ var DEFAULT_TIMEOUT_MS = 6e4;
1040
+ function isServiceParams(value) {
1041
+ return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
1042
+ }
1043
+ function extractInferResult(response) {
1044
+ const emitted = (response.effectResults ?? []).find(
1045
+ (result) => result.effect === "emit" && result.success && isServiceParams(result.data) && result.data.event === INFERRED_EVENT
1046
+ );
1047
+ if (!emitted || !isServiceParams(emitted.data)) {
1048
+ return null;
1049
+ }
1050
+ const payload = emitted.data.payload;
1051
+ if (!isServiceParams(payload)) {
1052
+ return null;
1053
+ }
1054
+ if (!("output" in payload) || typeof payload.confidence !== "number" || !Array.isArray(payload.violations)) {
1055
+ return null;
1056
+ }
1057
+ return {
1058
+ output: payload.output,
1059
+ confidence: payload.confidence,
1060
+ violations: payload.violations
1061
+ };
1062
+ }
1063
+ var MLIntegration = class extends BaseIntegration {
1064
+ constructor(config) {
1065
+ super(config);
1066
+ const baseUrl = config.env.MASAR_URL;
1067
+ const traitPrefix = config.env.MASAR_ML_TRAIT;
1068
+ if (!baseUrl || !traitPrefix) {
1069
+ throw new Error(
1070
+ "ML integration requires MASAR_URL (serving orbital host) and MASAR_ML_TRAIT (kebab-case trait name of its /events route) to be configured"
1071
+ );
1072
+ }
1073
+ this.eventsUrl = `${baseUrl.replace(/\/+$/, "")}/api/${traitPrefix}/events`;
1074
+ this.timeoutMs = config.env.MASAR_ML_TIMEOUT_MS ? Number(config.env.MASAR_ML_TIMEOUT_MS) : DEFAULT_TIMEOUT_MS;
1075
+ this.logger.info("ML integration initialized", { eventsUrl: this.eventsUrl });
1076
+ }
1077
+ async execute(action, params) {
1078
+ const validation = this.validateParams(action, params);
1079
+ if (!validation.valid) {
1080
+ return {
1081
+ success: false,
1082
+ error: {
1083
+ name: "IntegrationError",
1084
+ message: "Validation failed",
1085
+ code: "VALIDATION_ERROR",
1086
+ details: validation.errors
1087
+ },
1088
+ metadata: this.createMetadata(action, 0)
1089
+ };
1090
+ }
1091
+ const startTime = Date.now();
1092
+ try {
1093
+ let data;
1094
+ switch (action) {
1095
+ case "infer":
1096
+ data = await this.executeWithRetry(() => this.infer(params));
1097
+ break;
1098
+ default:
1099
+ throw new Error(`Unknown action: ${action}`);
1100
+ }
1101
+ return {
1102
+ success: true,
1103
+ data,
1104
+ metadata: this.createMetadata(action, Date.now() - startTime)
1105
+ };
1106
+ } catch (error) {
1107
+ return this.handleError(action, error);
1108
+ }
1109
+ }
1110
+ async infer(params) {
1111
+ const { model, input } = params;
1112
+ this.logger.debug("Running ML inference", { model });
1113
+ const response = await this.postEvent(model, input);
1114
+ if (!response.success) {
1115
+ throw new IntegrationError(
1116
+ `ML service reported failure: ${response.error ?? "unknown error"}`,
1117
+ "SERVICE_ERROR",
1118
+ { model, response }
1119
+ );
1120
+ }
1121
+ const failed = (response.effectResults ?? []).find(
1122
+ (result) => result.effect === "emit" && isServiceParams(result.data) && result.data.event === INFER_FAILED_EVENT
1123
+ );
1124
+ if (failed) {
1125
+ throw new IntegrationError(
1126
+ `ML service could not infer: ${failed.error ?? "model unavailable"}`,
1127
+ "SERVICE_ERROR",
1128
+ { model, response }
1129
+ );
1130
+ }
1131
+ const inferred = extractInferResult(response);
1132
+ if (!inferred) {
1133
+ throw new IntegrationError(
1134
+ "ML service response did not include a valid inference result",
1135
+ "SERVICE_ERROR",
1136
+ { model, response }
1137
+ );
1138
+ }
1139
+ return inferred;
1140
+ }
1141
+ async postEvent(model, input) {
1142
+ const controller = new AbortController();
1143
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
1144
+ let httpResponse;
1145
+ try {
1146
+ httpResponse = await fetch(this.eventsUrl, {
1147
+ method: "POST",
1148
+ headers: { "Content-Type": "application/json" },
1149
+ body: JSON.stringify({ event: "INFER", payload: { model, input } }),
1150
+ signal: controller.signal
1151
+ });
1152
+ } catch (error) {
1153
+ if (error instanceof DOMException && error.name === "AbortError") {
1154
+ throw new IntegrationError(
1155
+ `ML service request timed out after ${this.timeoutMs}ms (model may be cold-starting)`,
1156
+ "TIMEOUT_ERROR",
1157
+ { model, eventsUrl: this.eventsUrl }
1158
+ );
1159
+ }
1160
+ throw new IntegrationError(
1161
+ `ML service request failed: ${error instanceof Error ? error.message : String(error)}`,
1162
+ "NETWORK_ERROR",
1163
+ { model, eventsUrl: this.eventsUrl }
1164
+ );
1165
+ } finally {
1166
+ clearTimeout(timer);
1167
+ }
1168
+ if (!httpResponse.ok) {
1169
+ const body = await httpResponse.text().catch(() => "");
1170
+ throw new IntegrationError(
1171
+ `ML service responded with status ${httpResponse.status}`,
1172
+ "SERVICE_ERROR",
1173
+ { model, status: httpResponse.status, body }
1174
+ );
1175
+ }
1176
+ try {
1177
+ return await httpResponse.json();
1178
+ } catch (error) {
1179
+ throw new IntegrationError(
1180
+ `ML service returned a malformed response body: ${error instanceof Error ? error.message : String(error)}`,
1181
+ "SERVICE_ERROR",
1182
+ { model }
1183
+ );
1184
+ }
1185
+ }
1186
+ };
1187
+ registerIntegration("ml", MLIntegration);
1188
+
1189
+ // src/integrations/deepagent/index.ts
1190
+ var DeepAgentIntegration = class extends BaseIntegration {
1191
+ constructor(config) {
1192
+ super(config);
1193
+ this.apiUrl = config.env.DEEPAGENT_API_URL || "http://localhost:3000";
1194
+ this.apiKey = config.env.DEEPAGENT_API_KEY || "";
1195
+ this.logger.info("DeepAgent integration initialized", { apiUrl: this.apiUrl });
1196
+ }
1197
+ async execute(action, params) {
1198
+ const validation = this.validateParams(action, params);
1199
+ if (!validation.valid) {
1200
+ return {
1201
+ success: false,
1202
+ error: {
1203
+ name: "IntegrationError",
1204
+ message: "Validation failed",
1205
+ code: "VALIDATION_ERROR",
1206
+ details: validation.errors
1207
+ },
1208
+ metadata: this.createMetadata(action, 0)
1209
+ };
1210
+ }
1211
+ const startTime = Date.now();
1212
+ let retries = 0;
1213
+ try {
1214
+ let data;
1215
+ switch (action) {
1216
+ case "sendMessage":
1217
+ data = await this.executeWithRetry(() => this.sendMessage(params));
1218
+ break;
1219
+ case "cancelGeneration":
1220
+ data = await this.executeWithRetry(
1221
+ () => this.cancelGeneration(params)
1222
+ );
1223
+ break;
1224
+ case "validateSchema":
1225
+ data = await this.executeWithRetry(() => this.validateSchema(params));
1226
+ break;
1227
+ case "compileSchema":
1228
+ data = await this.executeWithRetry(() => this.compileSchema(params));
1229
+ break;
1230
+ case "getThreadHistory":
1231
+ data = await this.executeWithRetry(
1232
+ () => this.getThreadHistory(params)
1233
+ );
1234
+ break;
1235
+ default:
1236
+ throw new Error(`Unknown action: ${action}`);
1237
+ }
1238
+ return {
1239
+ success: true,
1240
+ data,
1241
+ metadata: this.createMetadata(action, Date.now() - startTime, retries)
1242
+ };
1243
+ } catch (error) {
1244
+ return this.handleError(action, error);
1245
+ }
1246
+ }
1247
+ async sendMessage(params) {
1248
+ const { message, threadId, skill, context } = params;
1249
+ this.logger.debug("Sending message to DeepAgent", { threadId: String(threadId ?? ""), skill: String(skill ?? "") });
1250
+ const response = await this.request("/api/agent/message", {
1251
+ message,
1252
+ threadId,
1253
+ skill,
1254
+ context
1255
+ });
1256
+ return response;
1257
+ }
1258
+ async cancelGeneration(params) {
1259
+ const { threadId } = params;
1260
+ this.logger.debug("Cancelling generation", { threadId: String(threadId ?? "") });
1261
+ const response = await this.request("/api/agent/cancel", {
1262
+ threadId
1263
+ });
1264
+ return response;
1265
+ }
1266
+ async validateSchema(params) {
1267
+ const { schema } = params;
1268
+ this.logger.debug("Validating schema");
1269
+ const response = await this.request("/api/schema/validate", {
1270
+ schema
1271
+ });
1272
+ return response;
1273
+ }
1274
+ async compileSchema(params) {
1275
+ const { schema, shell } = params;
1276
+ this.logger.debug("Compiling schema", { shell: String(shell ?? "") });
1277
+ const response = await this.request("/api/schema/compile", {
1278
+ schema,
1279
+ shell
1280
+ });
1281
+ return response;
1282
+ }
1283
+ async getThreadHistory(params) {
1284
+ const { threadId } = params;
1285
+ this.logger.debug("Getting thread history", { threadId: String(threadId ?? "") });
1286
+ const response = await this.request("/api/agent/history", {
1287
+ threadId
1288
+ });
1289
+ return response;
1290
+ }
1291
+ async request(endpoint, body) {
1292
+ const url = `${this.apiUrl}${endpoint}`;
1293
+ const response = await fetch(url, {
1294
+ method: "POST",
1295
+ headers: {
1296
+ "Content-Type": "application/json",
1297
+ ...this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {}
1298
+ },
1299
+ body: JSON.stringify(body)
1300
+ });
1301
+ if (!response.ok) {
1302
+ throw new Error(
1303
+ `DeepAgent request failed: ${response.status} ${response.statusText}`
1304
+ );
1305
+ }
1306
+ return await response.json();
1307
+ }
1308
+ };
1309
+ registerIntegration("deepagent", DeepAgentIntegration);
1310
+ async function execGit(args, cwd, env) {
1311
+ return new Promise((resolve, reject) => {
1312
+ const proc = spawn("git", args, {
1313
+ cwd,
1314
+ env: { ...process.env, ...env },
1315
+ stdio: "pipe"
1316
+ });
1317
+ let stdout = "";
1318
+ let stderr = "";
1319
+ proc.stdout?.on("data", (data) => {
1320
+ stdout += data.toString();
1321
+ });
1322
+ proc.stderr?.on("data", (data) => {
1323
+ stderr += data.toString();
1324
+ });
1325
+ proc.on("close", (code) => {
1326
+ if (code === 0) {
1327
+ resolve({ stdout, stderr });
1328
+ } else {
1329
+ reject(
1330
+ new IntegrationError(
1331
+ `Git command failed: ${args.join(" ")}
1332
+ ${stderr}`,
1333
+ "SERVICE_ERROR",
1334
+ { code, stderr }
1335
+ )
1336
+ );
1337
+ }
1338
+ });
1339
+ proc.on("error", (error) => {
1340
+ reject(
1341
+ new IntegrationError(
1342
+ `Failed to execute git: ${error.message}`,
1343
+ "SERVICE_ERROR",
1344
+ { error }
1345
+ )
1346
+ );
1347
+ });
1348
+ });
1349
+ }
1350
+ async function cloneRepo(params, token) {
1351
+ const { repoUrl, targetDir, branch, depth = 1 } = params;
1352
+ const authUrl = injectTokenIntoUrl(repoUrl, token);
1353
+ const args = ["clone"];
1354
+ if (depth > 0) {
1355
+ args.push("--depth", depth.toString());
1356
+ }
1357
+ if (branch) {
1358
+ args.push("--branch", branch);
1359
+ }
1360
+ args.push(authUrl, targetDir);
1361
+ try {
1362
+ await execGit(args, process.cwd());
1363
+ await scrubTokenFromRemote(targetDir, repoUrl);
1364
+ } catch (error) {
1365
+ throw new IntegrationError(
1366
+ `Failed to clone repository: ${error instanceof Error ? error.message : String(error)}`,
1367
+ "SERVICE_ERROR",
1368
+ { repoUrl, error }
1369
+ );
1370
+ }
1371
+ }
1372
+ async function createBranch(params, workDir) {
1373
+ const { branchName, baseBranch } = params;
1374
+ const cwd = params.workDir || workDir;
1375
+ try {
1376
+ if (baseBranch) {
1377
+ await execGit(["checkout", baseBranch], cwd);
1378
+ }
1379
+ await execGit(["checkout", "-b", branchName], cwd);
1380
+ } catch (error) {
1381
+ throw new IntegrationError(
1382
+ `Failed to create branch: ${error instanceof Error ? error.message : String(error)}`,
1383
+ "SERVICE_ERROR",
1384
+ { branchName, baseBranch, error }
1385
+ );
1386
+ }
1387
+ }
1388
+ async function commit(params, workDir) {
1389
+ const { message, files } = params;
1390
+ const cwd = params.workDir || workDir;
1391
+ try {
1392
+ if (files && files.length > 0) {
1393
+ await execGit(["add", ...files], cwd);
1394
+ } else {
1395
+ await execGit(["add", "."], cwd);
1396
+ }
1397
+ await execGit(["commit", "-m", message], cwd);
1398
+ } catch (error) {
1399
+ throw new IntegrationError(
1400
+ `Failed to commit: ${error instanceof Error ? error.message : String(error)}`,
1401
+ "SERVICE_ERROR",
1402
+ { message, error }
1403
+ );
1404
+ }
1405
+ }
1406
+ async function push(params, workDir, token) {
1407
+ const { branchName, force = false } = params;
1408
+ const cwd = params.workDir || workDir;
1409
+ const protectedBranches = ["main", "master", "production", "prod"];
1410
+ if (force && protectedBranches.includes(branchName.toLowerCase())) {
1411
+ throw new IntegrationError(
1412
+ `Force push to protected branch '${branchName}' is not allowed`,
1413
+ "VALIDATION_ERROR"
1414
+ );
1415
+ }
1416
+ try {
1417
+ const credHelper = await createTempCredentialHelper(token);
1418
+ const args = ["push"];
1419
+ if (force) {
1420
+ args.push("--force");
1421
+ }
1422
+ args.push("-u", "origin", branchName);
1423
+ await execGit(args, cwd, {
1424
+ GIT_ASKPASS: credHelper,
1425
+ GIT_TERMINAL_PROMPT: "0"
1426
+ });
1427
+ await promises.unlink(credHelper);
1428
+ } catch (error) {
1429
+ throw new IntegrationError(
1430
+ `Failed to push: ${error instanceof Error ? error.message : String(error)}`,
1431
+ "SERVICE_ERROR",
1432
+ { branchName, error }
1433
+ );
1434
+ }
1435
+ }
1436
+ function injectTokenIntoUrl(repoUrl, token) {
1437
+ const url = new URL(repoUrl);
1438
+ url.username = "x-access-token";
1439
+ url.password = token;
1440
+ return url.toString();
1441
+ }
1442
+ async function scrubTokenFromRemote(workDir, originalUrl) {
1443
+ try {
1444
+ const url = new URL(originalUrl);
1445
+ url.username = "";
1446
+ url.password = "";
1447
+ const cleanUrl = url.toString();
1448
+ await execGit(["remote", "set-url", "origin", cleanUrl], workDir);
1449
+ } catch (error) {
1450
+ console.error("Warning: Failed to scrub token from remote URL:", error);
1451
+ }
1452
+ }
1453
+ async function createTempCredentialHelper(token) {
1454
+ const tmpDir = process.env.TMPDIR || "/tmp";
1455
+ const helperPath = join(tmpDir, `git-cred-${Date.now()}.sh`);
1456
+ const script = `#!/bin/sh
1457
+ echo "${token}"`;
1458
+ await promises.writeFile(helperPath, script, { mode: 448 });
1459
+ return helperPath;
1460
+ }
1461
+
1462
+ // src/integrations/github/github-api.ts
1463
+ async function githubFetch(endpoint, config, options = {}) {
1464
+ const url = `https://api.github.com${endpoint}`;
1465
+ const headers = {
1466
+ "Authorization": `Bearer ${config.token}`,
1467
+ "Accept": "application/vnd.github+json",
1468
+ "X-GitHub-Api-Version": "2022-11-28",
1469
+ ...options.headers
1470
+ };
1471
+ try {
1472
+ const response = await fetch(url, {
1473
+ ...options,
1474
+ headers
1475
+ });
1476
+ const rateLimit = {
1477
+ remaining: parseInt(response.headers.get("x-ratelimit-remaining") || "0", 10),
1478
+ limit: parseInt(response.headers.get("x-ratelimit-limit") || "5000", 10),
1479
+ reset: parseInt(response.headers.get("x-ratelimit-reset") || "0", 10)
1480
+ };
1481
+ if (!response.ok) {
1482
+ const error = await response.json().catch(() => ({ message: response.statusText }));
1483
+ if (response.status === 429) {
1484
+ throw new IntegrationError(
1485
+ "GitHub API rate limit exceeded",
1486
+ "RATE_LIMIT_ERROR",
1487
+ { rateLimit, error }
1488
+ );
1489
+ }
1490
+ if (response.status === 401 || response.status === 403) {
1491
+ throw new IntegrationError(
1492
+ `GitHub API authentication failed: ${error.message || response.statusText}`,
1493
+ "AUTH_ERROR",
1494
+ { status: response.status, error }
1495
+ );
1496
+ }
1497
+ throw new IntegrationError(
1498
+ `GitHub API request failed: ${error.message || response.statusText}`,
1499
+ "SERVICE_ERROR",
1500
+ { status: response.status, error }
1501
+ );
1502
+ }
1503
+ const data = await response.json();
1504
+ return { data, rateLimit };
1505
+ } catch (error) {
1506
+ if (error instanceof IntegrationError) {
1507
+ throw error;
1508
+ }
1509
+ throw new IntegrationError(
1510
+ `GitHub API request failed: ${error instanceof Error ? error.message : String(error)}`,
1511
+ "NETWORK_ERROR",
1512
+ { error }
1513
+ );
1514
+ }
1515
+ }
1516
+ async function createPR(params, config) {
1517
+ const { title, body, baseBranch, headBranch, draft = false } = params;
1518
+ const endpoint = `/repos/${config.owner}/${config.repo}/pulls`;
1519
+ const { data } = await githubFetch(endpoint, config, {
1520
+ method: "POST",
1521
+ body: JSON.stringify({
1522
+ title,
1523
+ body,
1524
+ base: baseBranch,
1525
+ head: headBranch,
1526
+ draft
1527
+ })
1528
+ });
1529
+ return data;
1530
+ }
1531
+ async function getPRComments(params, config) {
1532
+ const { prNumber } = params;
1533
+ const endpoint = `/repos/${config.owner}/${config.repo}/pulls/${prNumber}/comments`;
1534
+ const { data } = await githubFetch(endpoint, config);
1535
+ return data;
1536
+ }
1537
+ async function listIssues(params, config) {
1538
+ const { state = "open", labels = [], limit = 30 } = params;
1539
+ const queryParams = new URLSearchParams({
1540
+ state,
1541
+ per_page: Math.min(limit, 100).toString()
1542
+ });
1543
+ if (labels.length > 0) {
1544
+ queryParams.append("labels", labels.join(","));
1545
+ }
1546
+ const endpoint = `/repos/${config.owner}/${config.repo}/issues?${queryParams}`;
1547
+ const { data } = await githubFetch(endpoint, config);
1548
+ return data;
1549
+ }
1550
+ async function getIssue(params, config) {
1551
+ const { issueNumber } = params;
1552
+ const issueEndpoint = `/repos/${config.owner}/${config.repo}/issues/${issueNumber}`;
1553
+ const { data: issue } = await githubFetch(issueEndpoint, config);
1554
+ const commentsEndpoint = `/repos/${config.owner}/${config.repo}/issues/${issueNumber}/comments`;
1555
+ const { data: comments } = await githubFetch(commentsEndpoint, config);
1556
+ return { issue, comments };
1557
+ }
1558
+ function parseRepoUrl(repoUrl) {
1559
+ try {
1560
+ const url = new URL(repoUrl);
1561
+ const pathParts = url.pathname.split("/").filter(Boolean);
1562
+ if (pathParts.length < 2) {
1563
+ throw new Error("Invalid repository URL format");
1564
+ }
1565
+ const owner = pathParts[0];
1566
+ const repo = pathParts[1].replace(/\.git$/, "");
1567
+ return { owner, repo };
1568
+ } catch (error) {
1569
+ throw new IntegrationError(
1570
+ `Failed to parse repository URL: ${repoUrl}`,
1571
+ "VALIDATION_ERROR",
1572
+ { error }
1573
+ );
1574
+ }
1575
+ }
1576
+
1577
+ // src/integrations/github/index.ts
1578
+ var GitHubIntegration = class extends BaseIntegration {
1579
+ constructor(config) {
1580
+ super(config);
1581
+ this.token = config.env.GITHUB_TOKEN;
1582
+ if (!this.token) {
1583
+ throw new Error("GITHUB_TOKEN not configured");
1584
+ }
1585
+ this.owner = config.env.GITHUB_OWNER || "";
1586
+ this.repo = config.env.GITHUB_REPO || "";
1587
+ this.workDir = config.env.GITHUB_WORK_DIR || process.cwd();
1588
+ this.logger.info("GitHub integration initialized", {
1589
+ owner: this.owner,
1590
+ repo: this.repo
1591
+ });
1592
+ }
1593
+ /**
1594
+ * Execute a GitHub action
1595
+ */
1596
+ async execute(action, params) {
1597
+ const validation = this.validateParams(action, params);
1598
+ if (!validation.valid) {
1599
+ return {
1600
+ success: false,
1601
+ error: {
1602
+ name: "IntegrationError",
1603
+ message: "Validation failed",
1604
+ code: "VALIDATION_ERROR",
1605
+ details: validation.errors
1606
+ },
1607
+ metadata: this.createMetadata(action, 0)
1608
+ };
1609
+ }
1610
+ const startTime = Date.now();
1611
+ let retries = 0;
1612
+ try {
1613
+ let data;
1614
+ switch (action) {
1615
+ case "cloneRepo":
1616
+ data = await this.executeWithRetry(
1617
+ () => this.cloneRepo(params)
1618
+ );
1619
+ break;
1620
+ case "createBranch":
1621
+ data = await this.executeWithRetry(
1622
+ () => this.createBranch(params)
1623
+ );
1624
+ break;
1625
+ case "commit":
1626
+ data = await this.executeWithRetry(
1627
+ () => this.commit(params)
1628
+ );
1629
+ break;
1630
+ case "push":
1631
+ data = await this.executeWithRetry(
1632
+ () => this.push(params)
1633
+ );
1634
+ break;
1635
+ case "createPR":
1636
+ data = await this.executeWithRetry(
1637
+ () => this.createPR(params)
1638
+ );
1639
+ break;
1640
+ case "getPRComments":
1641
+ data = await this.executeWithRetry(
1642
+ () => this.getPRComments(params)
1643
+ );
1644
+ break;
1645
+ case "listIssues":
1646
+ data = await this.executeWithRetry(
1647
+ () => this.listIssues(params)
1648
+ );
1649
+ break;
1650
+ case "getIssue":
1651
+ data = await this.executeWithRetry(
1652
+ () => this.getIssue(params)
1653
+ );
1654
+ break;
1655
+ default:
1656
+ throw new Error(`Unknown GitHub action: ${action}`);
1657
+ }
1658
+ return {
1659
+ success: true,
1660
+ data,
1661
+ metadata: this.createMetadata(action, Date.now() - startTime, retries)
1662
+ };
1663
+ } catch (error) {
1664
+ return this.handleError(action, error);
1665
+ }
1666
+ }
1667
+ /**
1668
+ * Clone a repository
1669
+ */
1670
+ async cloneRepo(params) {
1671
+ this.logger.debug("Cloning repository", { repoUrl: params.repoUrl });
1672
+ if (!this.owner || !this.repo) {
1673
+ const parsed = parseRepoUrl(params.repoUrl);
1674
+ this.owner = parsed.owner;
1675
+ this.repo = parsed.repo;
1676
+ }
1677
+ await cloneRepo(params, this.token);
1678
+ return {
1679
+ message: `Successfully cloned ${params.repoUrl} to ${params.targetDir}`
1680
+ };
1681
+ }
1682
+ /**
1683
+ * Create a branch
1684
+ */
1685
+ async createBranch(params) {
1686
+ this.logger.debug("Creating branch", { branchName: params.branchName });
1687
+ await createBranch(params, this.workDir);
1688
+ return {
1689
+ message: `Successfully created branch: ${params.branchName}`
1690
+ };
1691
+ }
1692
+ /**
1693
+ * Commit changes
1694
+ */
1695
+ async commit(params) {
1696
+ this.logger.debug("Committing changes", { message: params.message });
1697
+ await commit(params, this.workDir);
1698
+ return {
1699
+ message: `Successfully committed changes: ${params.message}`
1700
+ };
1701
+ }
1702
+ /**
1703
+ * Push branch
1704
+ */
1705
+ async push(params) {
1706
+ this.logger.debug("Pushing branch", { branchName: params.branchName });
1707
+ await push(params, this.workDir, this.token);
1708
+ return {
1709
+ message: `Successfully pushed branch: ${params.branchName}`
1710
+ };
1711
+ }
1712
+ /**
1713
+ * Create a pull request
1714
+ */
1715
+ async createPR(params) {
1716
+ this.logger.debug("Creating pull request", { title: params.title });
1717
+ const apiConfig = this.getAPIConfig();
1718
+ const pr = await createPR(params, apiConfig);
1719
+ this.logger.info("Pull request created", { number: pr.number, url: pr.url });
1720
+ return pr;
1721
+ }
1722
+ /**
1723
+ * Get PR comments
1724
+ */
1725
+ async getPRComments(params) {
1726
+ this.logger.debug("Getting PR comments", { prNumber: params.prNumber });
1727
+ const apiConfig = this.getAPIConfig();
1728
+ const comments = await getPRComments(params, apiConfig);
1729
+ return { comments };
1730
+ }
1731
+ /**
1732
+ * List issues
1733
+ */
1734
+ async listIssues(params) {
1735
+ this.logger.debug("Listing issues", { state: params.state, labels: params.labels?.join(", "), limit: params.limit });
1736
+ const apiConfig = this.getAPIConfig();
1737
+ const issues = await listIssues(params, apiConfig);
1738
+ return { issues };
1739
+ }
1740
+ /**
1741
+ * Get issue details
1742
+ */
1743
+ async getIssue(params) {
1744
+ this.logger.debug("Getting issue", { issueNumber: params.issueNumber });
1745
+ const apiConfig = this.getAPIConfig();
1746
+ const result = await getIssue(params, apiConfig);
1747
+ return result;
1748
+ }
1749
+ /**
1750
+ * Get API config for GitHub API calls
1751
+ */
1752
+ getAPIConfig() {
1753
+ if (!this.owner || !this.repo) {
1754
+ throw new Error(
1755
+ "GitHub owner and repo must be configured. Either set GITHUB_OWNER/GITHUB_REPO or clone a repository first."
1756
+ );
1757
+ }
1758
+ return {
1759
+ token: this.token,
1760
+ owner: this.owner,
1761
+ repo: this.repo
1762
+ };
1763
+ }
1764
+ };
1765
+ registerIntegration("github", GitHubIntegration);
1766
+ var CLIIntegration = class extends BaseIntegration {
1767
+ constructor(config) {
1768
+ super(config);
1769
+ this.logger.info("CLI integration initialized");
1770
+ }
1771
+ async execute(action, params) {
1772
+ const startTime = Date.now();
1773
+ try {
1774
+ let data;
1775
+ switch (action) {
1776
+ case "validate":
1777
+ data = await this.validate(params);
1778
+ break;
1779
+ default:
1780
+ throw new Error(`Unknown CLI action: ${action}`);
1781
+ }
1782
+ return {
1783
+ success: true,
1784
+ data,
1785
+ metadata: this.createMetadata(action, Date.now() - startTime)
1786
+ };
1787
+ } catch (error) {
1788
+ return this.handleError(action, error);
1789
+ }
1790
+ }
1791
+ async validate(params) {
1792
+ const { schema } = params;
1793
+ if (!schema || typeof schema !== "string") {
1794
+ throw new Error('validate requires a "schema" parameter (string)');
1795
+ }
1796
+ const tempDir = mkdtempSync(join(tmpdir(), "almadar-validate-"));
1797
+ const schemaPath = join(tempDir, "schema.orb");
1798
+ try {
1799
+ writeFileSync(schemaPath, schema, "utf-8");
1800
+ this.logger.debug("Validating schema", { path: schemaPath });
1801
+ const output = execSync(
1802
+ `npx @almadar/cli validate "${schemaPath}" --format=json`,
1803
+ {
1804
+ encoding: "utf-8",
1805
+ timeout: 3e4,
1806
+ cwd: tempDir,
1807
+ stdio: ["pipe", "pipe", "pipe"]
1808
+ }
1809
+ );
1810
+ const result = JSON.parse(output.trim());
1811
+ return {
1812
+ valid: result.valid ?? true,
1813
+ errors: result.errors || [],
1814
+ warnings: result.warnings || [],
1815
+ summary: result.summary || ""
1816
+ };
1817
+ } catch (error) {
1818
+ const execError = error;
1819
+ if (execError.stdout) {
1820
+ try {
1821
+ const result = JSON.parse(execError.stdout.trim());
1822
+ return {
1823
+ valid: false,
1824
+ errors: result.errors || [],
1825
+ warnings: result.warnings || [],
1826
+ summary: result.summary || ""
1827
+ };
1828
+ } catch {
1829
+ }
1830
+ }
1831
+ throw new Error(
1832
+ `CLI validation failed: ${execError.message || String(error)}`
1833
+ );
1834
+ } finally {
1835
+ try {
1836
+ rmSync(tempDir, { recursive: true, force: true });
1837
+ } catch {
1838
+ }
1839
+ }
1840
+ }
1841
+ };
1842
+ registerIntegration("cli", CLIIntegration);
1843
+
1844
+ // src/integrations/redis/index.ts
1845
+ var RedisIntegration = class extends BaseIntegration {
1846
+ constructor(config) {
1847
+ super(config);
1848
+ this.store = /* @__PURE__ */ new Map();
1849
+ this.locks = /* @__PURE__ */ new Map();
1850
+ this.channels = /* @__PURE__ */ new Map();
1851
+ const redisUrl = config.env.REDIS_URL;
1852
+ if (redisUrl) {
1853
+ this.logger.warn(
1854
+ "REDIS_URL is configured but real Redis client is not yet implemented. Falling back to in-memory store.",
1855
+ { redisUrl }
1856
+ );
1857
+ }
1858
+ this.logger.info("Redis integration initialized (in-memory backend)");
1859
+ }
1860
+ async execute(action, params) {
1861
+ const validation = this.validateParams(action, params);
1862
+ if (!validation.valid) {
1863
+ return {
1864
+ success: false,
1865
+ error: {
1866
+ name: "IntegrationError",
1867
+ message: "Validation failed",
1868
+ code: "VALIDATION_ERROR",
1869
+ details: validation.errors
1870
+ },
1871
+ metadata: this.createMetadata(action, 0)
1872
+ };
1873
+ }
1874
+ const startTime = Date.now();
1875
+ try {
1876
+ let data;
1877
+ switch (action) {
1878
+ case "get":
1879
+ data = await this.executeWithRetry(() => this.getKey(params));
1880
+ break;
1881
+ case "set":
1882
+ data = await this.executeWithRetry(() => this.setKey(params));
1883
+ break;
1884
+ case "delete":
1885
+ data = await this.executeWithRetry(() => this.deleteKey(params));
1886
+ break;
1887
+ case "lock":
1888
+ data = await this.executeWithRetry(() => this.acquireLock(params));
1889
+ break;
1890
+ case "unlock":
1891
+ data = await this.executeWithRetry(() => this.releaseLock(params));
1892
+ break;
1893
+ case "increment":
1894
+ data = await this.executeWithRetry(() => this.incrementKey(params));
1895
+ break;
1896
+ case "expire":
1897
+ data = await this.executeWithRetry(() => this.expireKey(params));
1898
+ break;
1899
+ case "publish":
1900
+ data = await this.executeWithRetry(() => this.publishMessage(params));
1901
+ break;
1902
+ case "subscribe":
1903
+ data = await this.executeWithRetry(
1904
+ () => this.subscribeChannel(params)
1905
+ );
1906
+ break;
1907
+ default:
1908
+ throw new Error(`Unknown action: ${action}`);
1909
+ }
1910
+ return {
1911
+ success: true,
1912
+ data,
1913
+ metadata: this.createMetadata(action, Date.now() - startTime)
1914
+ };
1915
+ } catch (error) {
1916
+ return this.handleError(action, error);
1917
+ }
1918
+ }
1919
+ // ---------------------------------------------------------------------------
1920
+ // Helpers
1921
+ // ---------------------------------------------------------------------------
1922
+ /** Remove expired entries on access and return whether a key is alive. */
1923
+ isAlive(key) {
1924
+ const entry = this.store.get(key);
1925
+ if (!entry) return false;
1926
+ if (entry.expiresAt !== void 0 && Date.now() > entry.expiresAt) {
1927
+ this.store.delete(key);
1928
+ return false;
1929
+ }
1930
+ return true;
1931
+ }
1932
+ /** Generate a unique lock identifier. */
1933
+ generateLockId() {
1934
+ return `lock_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
1935
+ }
1936
+ // ---------------------------------------------------------------------------
1937
+ // Actions
1938
+ // ---------------------------------------------------------------------------
1939
+ async getKey(params) {
1940
+ const key = params.key;
1941
+ this.logger.debug("Cache GET", { key });
1942
+ if (!this.isAlive(key)) {
1943
+ return { value: null };
1944
+ }
1945
+ const entry = this.store.get(key);
1946
+ return { value: entry ? entry.value : null };
1947
+ }
1948
+ async setKey(params) {
1949
+ const key = params.key;
1950
+ const value = params.value;
1951
+ const ttl = params.ttl;
1952
+ this.logger.debug("Cache SET", { key, ttl });
1953
+ const entry = { value };
1954
+ if (ttl !== void 0 && ttl > 0) {
1955
+ entry.expiresAt = Date.now() + ttl * 1e3;
1956
+ }
1957
+ this.store.set(key, entry);
1958
+ return { ok: true };
1959
+ }
1960
+ async deleteKey(params) {
1961
+ const key = params.key;
1962
+ this.logger.debug("Cache DELETE", { key });
1963
+ const existed = this.store.has(key);
1964
+ this.store.delete(key);
1965
+ return { deleted: existed };
1966
+ }
1967
+ async acquireLock(params) {
1968
+ const key = params.key;
1969
+ const ttl = params.ttl ?? 3e4;
1970
+ this.logger.debug("Cache LOCK", { key, ttl });
1971
+ const existingLockId = this.locks.get(key);
1972
+ if (existingLockId) {
1973
+ if (this.isAlive(`__lock:${key}`)) {
1974
+ return { acquired: false, lockId: "" };
1975
+ }
1976
+ this.locks.delete(key);
1977
+ this.store.delete(`__lock:${key}`);
1978
+ }
1979
+ const lockId = this.generateLockId();
1980
+ this.locks.set(key, lockId);
1981
+ this.store.set(`__lock:${key}`, {
1982
+ value: lockId,
1983
+ expiresAt: Date.now() + ttl
1984
+ });
1985
+ return { acquired: true, lockId };
1986
+ }
1987
+ async releaseLock(params) {
1988
+ const key = params.key;
1989
+ const lockId = params.lockId;
1990
+ this.logger.debug("Cache UNLOCK", { key, lockId });
1991
+ const currentLockId = this.locks.get(key);
1992
+ if (currentLockId !== lockId) {
1993
+ return { released: false };
1994
+ }
1995
+ this.locks.delete(key);
1996
+ this.store.delete(`__lock:${key}`);
1997
+ return { released: true };
1998
+ }
1999
+ async incrementKey(params) {
2000
+ const key = params.key;
2001
+ const by = params.by ?? 1;
2002
+ this.logger.debug("Cache INCR", { key, by });
2003
+ let current = 0;
2004
+ if (this.isAlive(key)) {
2005
+ const entry = this.store.get(key);
2006
+ if (entry) {
2007
+ current = typeof entry.value === "number" ? entry.value : 0;
2008
+ }
2009
+ }
2010
+ const newValue = current + by;
2011
+ const existing = this.store.get(key);
2012
+ this.store.set(key, {
2013
+ value: newValue,
2014
+ expiresAt: existing?.expiresAt
2015
+ });
2016
+ return { value: newValue };
2017
+ }
2018
+ async expireKey(params) {
2019
+ const key = params.key;
2020
+ const ttl = params.ttl;
2021
+ this.logger.debug("Cache EXPIRE", { key, ttl });
2022
+ if (!this.isAlive(key)) {
2023
+ return { set: false };
2024
+ }
2025
+ const entry = this.store.get(key);
2026
+ if (!entry) {
2027
+ return { set: false };
2028
+ }
2029
+ entry.expiresAt = Date.now() + ttl * 1e3;
2030
+ this.store.set(key, entry);
2031
+ return { set: true };
2032
+ }
2033
+ async publishMessage(params) {
2034
+ const channel = params.channel;
2035
+ const message = params.message;
2036
+ this.logger.debug("Cache PUBLISH", { channel });
2037
+ const subscribers = this.channels.get(channel);
2038
+ if (!subscribers || subscribers.size === 0) {
2039
+ return { receivers: 0 };
2040
+ }
2041
+ for (const callback of subscribers) {
2042
+ try {
2043
+ callback(message);
2044
+ } catch (err) {
2045
+ this.logger.error("Subscriber callback error", {
2046
+ channel,
2047
+ error: err instanceof Error ? err.message : String(err)
2048
+ });
2049
+ }
2050
+ }
2051
+ return { receivers: subscribers.size };
2052
+ }
2053
+ async subscribeChannel(params) {
2054
+ const channel = params.channel;
2055
+ this.logger.debug("Cache SUBSCRIBE", { channel });
2056
+ if (!this.channels.has(channel)) {
2057
+ this.channels.set(channel, /* @__PURE__ */ new Set());
2058
+ }
2059
+ return { subscribed: true };
2060
+ }
2061
+ };
2062
+ registerIntegration("redis", RedisIntegration);
2063
+
2064
+ // src/integrations/queue/index.ts
2065
+ var QueueIntegration = class extends BaseIntegration {
2066
+ constructor(config) {
2067
+ super(config);
2068
+ /** Map from queue name to ordered list of job IDs */
2069
+ this.queues = /* @__PURE__ */ new Map();
2070
+ /** Map from job ID to job data */
2071
+ this.jobs = /* @__PURE__ */ new Map();
2072
+ this.logger.info("Queue integration initialized (in-memory backend)");
2073
+ }
2074
+ async execute(action, params) {
2075
+ const validation = this.validateParams(action, params);
2076
+ if (!validation.valid) {
2077
+ return {
2078
+ success: false,
2079
+ error: {
2080
+ name: "IntegrationError",
2081
+ message: "Validation failed",
2082
+ code: "VALIDATION_ERROR",
2083
+ details: validation.errors
2084
+ },
2085
+ metadata: this.createMetadata(action, 0)
2086
+ };
2087
+ }
2088
+ const startTime = Date.now();
2089
+ try {
2090
+ let data;
2091
+ switch (action) {
2092
+ case "enqueue":
2093
+ data = await this.executeWithRetry(() => this.enqueue(params));
2094
+ break;
2095
+ case "dequeue":
2096
+ data = await this.executeWithRetry(() => this.dequeue(params));
2097
+ break;
2098
+ case "status":
2099
+ data = await this.executeWithRetry(() => this.status(params));
2100
+ break;
2101
+ case "complete":
2102
+ data = await this.executeWithRetry(() => this.complete(params));
2103
+ break;
2104
+ case "fail":
2105
+ data = await this.executeWithRetry(() => this.failJob(params));
2106
+ break;
2107
+ case "cancel":
2108
+ data = await this.executeWithRetry(() => this.cancel(params));
2109
+ break;
2110
+ case "size":
2111
+ data = await this.executeWithRetry(() => this.size(params));
2112
+ break;
2113
+ default:
2114
+ throw new Error(`Unknown action: ${action}`);
2115
+ }
2116
+ return {
2117
+ success: true,
2118
+ data,
2119
+ metadata: this.createMetadata(action, Date.now() - startTime)
2120
+ };
2121
+ } catch (error) {
2122
+ return this.handleError(action, error);
2123
+ }
2124
+ }
2125
+ // ---------------------------------------------------------------------------
2126
+ // Helpers
2127
+ // ---------------------------------------------------------------------------
2128
+ /** Generate a unique job identifier. */
2129
+ generateJobId() {
2130
+ return `job_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
2131
+ }
2132
+ /** Get or create the queue array for a given queue name. */
2133
+ getQueue(name) {
2134
+ let queue = this.queues.get(name);
2135
+ if (!queue) {
2136
+ queue = [];
2137
+ this.queues.set(name, queue);
2138
+ }
2139
+ return queue;
2140
+ }
2141
+ // ---------------------------------------------------------------------------
2142
+ // Actions
2143
+ // ---------------------------------------------------------------------------
2144
+ async enqueue(params) {
2145
+ const queueName = params.queue;
2146
+ const payload = params.payload;
2147
+ const delay = params.delay ?? 0;
2148
+ const priority = params.priority ?? 0;
2149
+ this.logger.debug("Queue ENQUEUE", { queue: queueName, delay, priority });
2150
+ const jobId = this.generateJobId();
2151
+ const job = {
2152
+ id: jobId,
2153
+ queue: queueName,
2154
+ payload,
2155
+ priority,
2156
+ status: "pending",
2157
+ enqueuedAt: Date.now(),
2158
+ delay
115
2159
  };
2160
+ this.jobs.set(jobId, job);
2161
+ const queue = this.getQueue(queueName);
2162
+ let insertIndex = queue.length;
2163
+ for (let i = 0; i < queue.length; i++) {
2164
+ const existingJob = this.jobs.get(queue[i]);
2165
+ if (existingJob && existingJob.priority < priority) {
2166
+ insertIndex = i;
2167
+ break;
2168
+ }
2169
+ }
2170
+ queue.splice(insertIndex, 0, jobId);
2171
+ return { jobId, position: insertIndex };
116
2172
  }
117
- const errors = [];
118
- for (const paramDef of actionDef.params) {
119
- if (paramDef.required && !(paramDef.name in params)) {
120
- errors.push({
121
- param: paramDef.name,
122
- message: `Missing required parameter: ${paramDef.name}`
2173
+ async dequeue(params) {
2174
+ const queueName = params.queue;
2175
+ this.logger.debug("Queue DEQUEUE", { queue: queueName });
2176
+ const queue = this.getQueue(queueName);
2177
+ const now = Date.now();
2178
+ for (let i = 0; i < queue.length; i++) {
2179
+ const job = this.jobs.get(queue[i]);
2180
+ if (!job || job.status !== "pending") continue;
2181
+ const readyAt = job.enqueuedAt + job.delay;
2182
+ if (now < readyAt) continue;
2183
+ job.status = "processing";
2184
+ queue.splice(i, 1);
2185
+ return {
2186
+ job: {
2187
+ id: job.id,
2188
+ payload: job.payload,
2189
+ enqueuedAt: job.enqueuedAt,
2190
+ priority: job.priority
2191
+ }
2192
+ };
2193
+ }
2194
+ return { job: null };
2195
+ }
2196
+ async status(params) {
2197
+ const jobId = params.jobId;
2198
+ this.logger.debug("Queue STATUS", { jobId });
2199
+ const job = this.jobs.get(jobId);
2200
+ if (!job) {
2201
+ return { status: "pending", job: null };
2202
+ }
2203
+ return {
2204
+ status: job.status,
2205
+ job: {
2206
+ id: job.id,
2207
+ payload: job.payload,
2208
+ enqueuedAt: job.enqueuedAt,
2209
+ priority: job.priority
2210
+ }
2211
+ };
2212
+ }
2213
+ async complete(params) {
2214
+ const jobId = params.jobId;
2215
+ const result = params.result;
2216
+ this.logger.debug("Queue COMPLETE", { jobId });
2217
+ const job = this.jobs.get(jobId);
2218
+ if (!job || job.status !== "processing") {
2219
+ return { completed: false };
2220
+ }
2221
+ job.status = "completed";
2222
+ job.result = result;
2223
+ return { completed: true };
2224
+ }
2225
+ async failJob(params) {
2226
+ const jobId = params.jobId;
2227
+ const error = params.error;
2228
+ this.logger.debug("Queue FAIL", { jobId });
2229
+ const job = this.jobs.get(jobId);
2230
+ if (!job || job.status !== "processing") {
2231
+ return { failed: false };
2232
+ }
2233
+ job.status = "failed";
2234
+ job.error = error;
2235
+ return { failed: true };
2236
+ }
2237
+ async cancel(params) {
2238
+ const jobId = params.jobId;
2239
+ this.logger.debug("Queue CANCEL", { jobId });
2240
+ const job = this.jobs.get(jobId);
2241
+ if (!job || job.status !== "pending") {
2242
+ return { cancelled: false };
2243
+ }
2244
+ const queue = this.queues.get(job.queue);
2245
+ if (queue) {
2246
+ const idx = queue.indexOf(jobId);
2247
+ if (idx !== -1) {
2248
+ queue.splice(idx, 1);
2249
+ }
2250
+ }
2251
+ this.jobs.delete(jobId);
2252
+ return { cancelled: true };
2253
+ }
2254
+ async size(params) {
2255
+ const queueName = params.queue;
2256
+ this.logger.debug("Queue SIZE", { queue: queueName });
2257
+ let pending = 0;
2258
+ let processing = 0;
2259
+ for (const job of this.jobs.values()) {
2260
+ if (job.queue !== queueName) continue;
2261
+ if (job.status === "pending") pending++;
2262
+ if (job.status === "processing") processing++;
2263
+ }
2264
+ return { size: pending + processing, pending, processing };
2265
+ }
2266
+ };
2267
+ registerIntegration("queue", QueueIntegration);
2268
+
2269
+ // src/integrations/otel/index.ts
2270
+ function randomHexId(bytes) {
2271
+ const arr = [];
2272
+ for (let i = 0; i < bytes; i++) {
2273
+ arr.push(Math.floor(Math.random() * 256).toString(16).padStart(2, "0"));
2274
+ }
2275
+ return arr.join("");
2276
+ }
2277
+ var OtelIntegration = class extends BaseIntegration {
2278
+ constructor(config) {
2279
+ super(config);
2280
+ this.spans = /* @__PURE__ */ new Map();
2281
+ this.metrics = /* @__PURE__ */ new Map();
2282
+ this.logger.info("OTel integration initialized (in-memory backend)");
2283
+ }
2284
+ async execute(action, params) {
2285
+ const validation = this.validateParams(action, params);
2286
+ if (!validation.valid) {
2287
+ return {
2288
+ success: false,
2289
+ error: {
2290
+ name: "IntegrationError",
2291
+ message: "Validation failed",
2292
+ code: "VALIDATION_ERROR",
2293
+ details: validation.errors
2294
+ },
2295
+ metadata: this.createMetadata(action, 0)
2296
+ };
2297
+ }
2298
+ const startTime = Date.now();
2299
+ try {
2300
+ let data;
2301
+ switch (action) {
2302
+ case "startSpan":
2303
+ data = await this.executeWithRetry(() => this.startSpan(params));
2304
+ break;
2305
+ case "endSpan":
2306
+ data = await this.executeWithRetry(() => this.endSpan(params));
2307
+ break;
2308
+ case "addEvent":
2309
+ data = await this.executeWithRetry(() => this.addEvent(params));
2310
+ break;
2311
+ case "recordMetric":
2312
+ data = await this.executeWithRetry(() => this.recordMetric(params));
2313
+ break;
2314
+ case "getSpan":
2315
+ data = await this.executeWithRetry(() => this.getSpan(params));
2316
+ break;
2317
+ case "getMetrics":
2318
+ data = await this.executeWithRetry(() => this.getAllMetrics());
2319
+ break;
2320
+ default:
2321
+ throw new Error(`Unknown action: ${action}`);
2322
+ }
2323
+ return {
2324
+ success: true,
2325
+ data,
2326
+ metadata: this.createMetadata(action, Date.now() - startTime)
2327
+ };
2328
+ } catch (error) {
2329
+ return this.handleError(action, error);
2330
+ }
2331
+ }
2332
+ // ---------------------------------------------------------------------------
2333
+ // Actions
2334
+ // ---------------------------------------------------------------------------
2335
+ async startSpan(params) {
2336
+ const name = params.name;
2337
+ const attributes = params.attributes ?? {};
2338
+ const spanId = randomHexId(8);
2339
+ const traceId = params.traceId ?? randomHexId(16);
2340
+ const span = {
2341
+ spanId,
2342
+ traceId,
2343
+ name,
2344
+ startTime: Date.now(),
2345
+ attributes,
2346
+ events: []
2347
+ };
2348
+ this.spans.set(spanId, span);
2349
+ this.logger.debug("Span started", { spanId, traceId, name });
2350
+ return { spanId, traceId };
2351
+ }
2352
+ async endSpan(params) {
2353
+ const spanId = params.spanId;
2354
+ const status = params.status;
2355
+ const span = this.spans.get(spanId);
2356
+ if (!span) {
2357
+ this.logger.warn("endSpan called for unknown span", { spanId });
2358
+ return { ended: false };
2359
+ }
2360
+ span.endTime = Date.now();
2361
+ if (status) {
2362
+ span.status = status;
2363
+ }
2364
+ this.logger.debug("Span ended", { spanId, status, duration: span.endTime - span.startTime });
2365
+ return { ended: true };
2366
+ }
2367
+ async addEvent(params) {
2368
+ const spanId = params.spanId;
2369
+ const name = params.name;
2370
+ const attributes = params.attributes;
2371
+ const span = this.spans.get(spanId);
2372
+ if (!span) {
2373
+ this.logger.warn("addEvent called for unknown span", { spanId });
2374
+ return { added: false };
2375
+ }
2376
+ span.events.push({
2377
+ name,
2378
+ timestamp: Date.now(),
2379
+ attributes
2380
+ });
2381
+ this.logger.debug("Event added to span", { spanId, eventName: name });
2382
+ return { added: true };
2383
+ }
2384
+ async recordMetric(params) {
2385
+ const name = params.name;
2386
+ const value = params.value;
2387
+ const type = params.type ?? "counter";
2388
+ const labels = params.labels ?? {};
2389
+ const existing = this.metrics.get(name);
2390
+ if (existing) {
2391
+ switch (type) {
2392
+ case "counter":
2393
+ existing.value += value;
2394
+ break;
2395
+ case "gauge":
2396
+ existing.value = value;
2397
+ break;
2398
+ case "histogram":
2399
+ existing.values.push(value);
2400
+ break;
2401
+ }
2402
+ existing.labels = labels;
2403
+ } else {
2404
+ this.metrics.set(name, {
2405
+ name,
2406
+ type,
2407
+ value: type === "histogram" ? 0 : value,
2408
+ values: type === "histogram" ? [value] : [],
2409
+ labels
2410
+ });
2411
+ }
2412
+ this.logger.debug("Metric recorded", { name, value, type });
2413
+ return { recorded: true };
2414
+ }
2415
+ async getSpan(params) {
2416
+ const spanId = params.spanId;
2417
+ const span = this.spans.get(spanId);
2418
+ return span ?? null;
2419
+ }
2420
+ async getAllMetrics() {
2421
+ const result = {};
2422
+ for (const [key, metric] of this.metrics) {
2423
+ result[key] = metric;
2424
+ }
2425
+ return result;
2426
+ }
2427
+ };
2428
+ registerIntegration("otel", OtelIntegration);
2429
+
2430
+ // src/integrations/oauth/index.ts
2431
+ var PROVIDER_AUTH_URLS = {
2432
+ google: "https://accounts.google.com/o/oauth2/v2/auth",
2433
+ github: "https://github.com/login/oauth/authorize",
2434
+ auth0: "https://auth.example.com/authorize"
2435
+ };
2436
+ var OAuthIntegration = class extends BaseIntegration {
2437
+ constructor(config) {
2438
+ super(config);
2439
+ /** Maps state token -> provider for pending authorization flows */
2440
+ this.states = /* @__PURE__ */ new Map();
2441
+ /** Maps access token -> token set */
2442
+ this.tokens = /* @__PURE__ */ new Map();
2443
+ /** Maps refresh token -> access token for refresh lookups */
2444
+ this.refreshIndex = /* @__PURE__ */ new Map();
2445
+ /** Maps access token -> mock user session */
2446
+ this.sessions = /* @__PURE__ */ new Map();
2447
+ this.logger.info("OAuth integration initialized (mock backend)");
2448
+ }
2449
+ async execute(action, params) {
2450
+ const validation = this.validateParams(action, params);
2451
+ if (!validation.valid) {
2452
+ return {
2453
+ success: false,
2454
+ error: {
2455
+ name: "IntegrationError",
2456
+ message: "Validation failed",
2457
+ code: "VALIDATION_ERROR",
2458
+ details: validation.errors
2459
+ },
2460
+ metadata: this.createMetadata(action, 0)
2461
+ };
2462
+ }
2463
+ const startTime = Date.now();
2464
+ try {
2465
+ let data;
2466
+ switch (action) {
2467
+ case "authorize":
2468
+ data = await this.executeWithRetry(() => this.authorize(params));
2469
+ break;
2470
+ case "token":
2471
+ data = await this.executeWithRetry(() => this.token(params));
2472
+ break;
2473
+ case "refresh":
2474
+ data = await this.executeWithRetry(() => this.refresh(params));
2475
+ break;
2476
+ case "revoke":
2477
+ data = await this.executeWithRetry(() => this.revoke(params));
2478
+ break;
2479
+ case "userinfo":
2480
+ data = await this.executeWithRetry(() => this.userinfo(params));
2481
+ break;
2482
+ default:
2483
+ throw new Error(`Unknown action: ${action}`);
2484
+ }
2485
+ return {
2486
+ success: true,
2487
+ data,
2488
+ metadata: this.createMetadata(action, Date.now() - startTime)
2489
+ };
2490
+ } catch (error) {
2491
+ return this.handleError(action, error);
2492
+ }
2493
+ }
2494
+ // ---------------------------------------------------------------------------
2495
+ // Helpers
2496
+ // ---------------------------------------------------------------------------
2497
+ /** Generate a random hex token of the given byte length. */
2498
+ generateToken(bytes = 32) {
2499
+ const chars = "abcdef0123456789";
2500
+ let result = "";
2501
+ for (let i = 0; i < bytes * 2; i++) {
2502
+ result += chars[Math.floor(Math.random() * chars.length)];
2503
+ }
2504
+ return result;
2505
+ }
2506
+ /** Generate a mock user profile from a provider and access token. */
2507
+ generateMockUser(provider, sub) {
2508
+ return {
2509
+ sub,
2510
+ email: `user-${sub.slice(0, 8)}@${provider}.example.com`,
2511
+ name: `Mock User (${provider})`,
2512
+ picture: `https://${provider}.example.com/avatar/${sub.slice(0, 8)}.png`
2513
+ };
2514
+ }
2515
+ // ---------------------------------------------------------------------------
2516
+ // Actions
2517
+ // ---------------------------------------------------------------------------
2518
+ async authorize(params) {
2519
+ const provider = params.provider;
2520
+ const scopes = params.scopes;
2521
+ const redirectUri = params.redirectUri;
2522
+ this.logger.debug("OAuth AUTHORIZE", { provider, scopes: scopes.join(", "), redirectUri });
2523
+ const state = this.generateToken(16);
2524
+ this.states.set(state, provider);
2525
+ const baseUrl = PROVIDER_AUTH_URLS[provider];
2526
+ const queryParams = new URLSearchParams({
2527
+ response_type: "code",
2528
+ scope: scopes.join(" "),
2529
+ redirect_uri: redirectUri,
2530
+ state,
2531
+ client_id: this.config.env.CLIENT_ID ?? "mock-client-id"
2532
+ });
2533
+ const authUrl = `${baseUrl}?${queryParams.toString()}`;
2534
+ return { authUrl, state };
2535
+ }
2536
+ async token(params) {
2537
+ const code = params.code;
2538
+ const state = params.state;
2539
+ this.logger.debug("OAuth TOKEN", { code, state });
2540
+ const provider = this.states.get(state);
2541
+ if (!provider) {
2542
+ throw new Error(
2543
+ `Invalid or expired state token: ${state}`
2544
+ );
2545
+ }
2546
+ this.states.delete(state);
2547
+ const accessToken = this.generateToken(32);
2548
+ const refreshToken = this.generateToken(32);
2549
+ const expiresIn = 3600;
2550
+ const tokenSet = {
2551
+ accessToken,
2552
+ refreshToken,
2553
+ expiresAt: Date.now() + expiresIn * 1e3
2554
+ };
2555
+ this.tokens.set(accessToken, tokenSet);
2556
+ this.refreshIndex.set(refreshToken, accessToken);
2557
+ const sub = this.generateToken(8);
2558
+ this.sessions.set(accessToken, this.generateMockUser(provider, sub));
2559
+ return { accessToken, refreshToken, expiresIn, tokenType: "bearer" };
2560
+ }
2561
+ async refresh(params) {
2562
+ const refreshToken = params.refreshToken;
2563
+ this.logger.debug("OAuth REFRESH", { refreshToken: refreshToken.slice(0, 8) + "..." });
2564
+ const oldAccessToken = this.refreshIndex.get(refreshToken);
2565
+ if (!oldAccessToken) {
2566
+ throw new Error("Invalid refresh token");
2567
+ }
2568
+ const userInfo = this.sessions.get(oldAccessToken);
2569
+ this.tokens.delete(oldAccessToken);
2570
+ this.sessions.delete(oldAccessToken);
2571
+ const newAccessToken = this.generateToken(32);
2572
+ const expiresIn = 3600;
2573
+ const tokenSet = {
2574
+ accessToken: newAccessToken,
2575
+ refreshToken,
2576
+ expiresAt: Date.now() + expiresIn * 1e3
2577
+ };
2578
+ this.tokens.set(newAccessToken, tokenSet);
2579
+ this.refreshIndex.set(refreshToken, newAccessToken);
2580
+ if (userInfo) {
2581
+ this.sessions.set(newAccessToken, userInfo);
2582
+ }
2583
+ return { accessToken: newAccessToken, expiresIn };
2584
+ }
2585
+ async revoke(params) {
2586
+ const token = params.token;
2587
+ this.logger.debug("OAuth REVOKE", { token: token.slice(0, 8) + "..." });
2588
+ const tokenSet = this.tokens.get(token);
2589
+ if (tokenSet) {
2590
+ this.refreshIndex.delete(tokenSet.refreshToken);
2591
+ this.tokens.delete(token);
2592
+ this.sessions.delete(token);
2593
+ return { revoked: true };
2594
+ }
2595
+ const accessToken = this.refreshIndex.get(token);
2596
+ if (accessToken) {
2597
+ this.tokens.delete(accessToken);
2598
+ this.sessions.delete(accessToken);
2599
+ this.refreshIndex.delete(token);
2600
+ return { revoked: true };
2601
+ }
2602
+ return { revoked: false };
2603
+ }
2604
+ async userinfo(params) {
2605
+ const accessToken = params.accessToken;
2606
+ this.logger.debug("OAuth USERINFO", { accessToken: accessToken.slice(0, 8) + "..." });
2607
+ const tokenSet = this.tokens.get(accessToken);
2608
+ if (!tokenSet) {
2609
+ throw new Error("Invalid access token");
2610
+ }
2611
+ if (Date.now() > tokenSet.expiresAt) {
2612
+ this.tokens.delete(accessToken);
2613
+ this.sessions.delete(accessToken);
2614
+ throw new Error("Access token expired");
2615
+ }
2616
+ const userInfo = this.sessions.get(accessToken);
2617
+ if (!userInfo) {
2618
+ throw new Error("No session found for access token");
2619
+ }
2620
+ return userInfo;
2621
+ }
2622
+ };
2623
+ registerIntegration("oauth", OAuthIntegration);
2624
+
2625
+ // src/integrations/storage/index.ts
2626
+ var StorageIntegration = class extends BaseIntegration {
2627
+ constructor(config) {
2628
+ super(config);
2629
+ this.objects = /* @__PURE__ */ new Map();
2630
+ const storageUrl = config.env.STORAGE_URL;
2631
+ if (storageUrl) {
2632
+ this.logger.warn(
2633
+ "STORAGE_URL is configured but real storage client is not yet implemented. Falling back to in-memory store.",
2634
+ { storageUrl }
2635
+ );
2636
+ }
2637
+ this.logger.info("Storage integration initialized (in-memory backend)");
2638
+ }
2639
+ async execute(action, params) {
2640
+ const validation = this.validateParams(action, params);
2641
+ if (!validation.valid) {
2642
+ return {
2643
+ success: false,
2644
+ error: {
2645
+ name: "IntegrationError",
2646
+ message: "Validation failed",
2647
+ code: "VALIDATION_ERROR",
2648
+ details: validation.errors
2649
+ },
2650
+ metadata: this.createMetadata(action, 0)
2651
+ };
2652
+ }
2653
+ const startTime = Date.now();
2654
+ try {
2655
+ let data;
2656
+ switch (action) {
2657
+ case "upload":
2658
+ data = await this.executeWithRetry(() => this.upload(params));
2659
+ break;
2660
+ case "download":
2661
+ data = await this.executeWithRetry(() => this.download(params));
2662
+ break;
2663
+ case "list":
2664
+ data = await this.executeWithRetry(() => this.list(params));
2665
+ break;
2666
+ case "delete":
2667
+ data = await this.executeWithRetry(() => this.deleteObject(params));
2668
+ break;
2669
+ case "getSignedUrl":
2670
+ data = await this.executeWithRetry(() => this.getSignedUrl(params));
2671
+ break;
2672
+ default:
2673
+ throw new Error(`Unknown action: ${action}`);
2674
+ }
2675
+ return {
2676
+ success: true,
2677
+ data,
2678
+ metadata: this.createMetadata(action, Date.now() - startTime)
2679
+ };
2680
+ } catch (error) {
2681
+ return this.handleError(action, error);
2682
+ }
2683
+ }
2684
+ // ---------------------------------------------------------------------------
2685
+ // Helpers
2686
+ // ---------------------------------------------------------------------------
2687
+ /** Build a composite key from bucket and object key. */
2688
+ compositeKey(bucket, key) {
2689
+ return `${bucket}/${key}`;
2690
+ }
2691
+ /** Generate a deterministic etag from content. */
2692
+ generateEtag(content) {
2693
+ const raw = typeof content === "string" ? content : JSON.stringify(content);
2694
+ let hash = 0;
2695
+ for (let i = 0; i < raw.length; i++) {
2696
+ const ch = raw.charCodeAt(i);
2697
+ hash = (hash << 5) - hash + ch | 0;
2698
+ }
2699
+ return `"${Math.abs(hash).toString(16).padStart(8, "0")}"`;
2700
+ }
2701
+ /** Compute the byte size of content. */
2702
+ computeSize(content) {
2703
+ if (typeof content === "string") {
2704
+ return new TextEncoder().encode(content).byteLength;
2705
+ }
2706
+ return JSON.stringify(content).length;
2707
+ }
2708
+ // ---------------------------------------------------------------------------
2709
+ // Actions
2710
+ // ---------------------------------------------------------------------------
2711
+ async upload(params) {
2712
+ const bucket = params.bucket;
2713
+ const key = params.key;
2714
+ const content = params.content;
2715
+ const contentType = params.contentType ?? "application/octet-stream";
2716
+ const metadata = params.metadata ?? {};
2717
+ this.logger.debug("Storage UPLOAD", { bucket, key, contentType });
2718
+ const size = this.computeSize(content);
2719
+ const etag = this.generateEtag(content);
2720
+ const obj = {
2721
+ content,
2722
+ contentType,
2723
+ size,
2724
+ metadata,
2725
+ lastModified: Date.now(),
2726
+ etag
2727
+ };
2728
+ this.objects.set(this.compositeKey(bucket, key), obj);
2729
+ return { key, bucket, size, etag };
2730
+ }
2731
+ async download(params) {
2732
+ const bucket = params.bucket;
2733
+ const key = params.key;
2734
+ this.logger.debug("Storage DOWNLOAD", { bucket, key });
2735
+ const obj = this.objects.get(this.compositeKey(bucket, key));
2736
+ if (!obj) {
2737
+ throw new Error(`Object not found: ${bucket}/${key}`);
2738
+ }
2739
+ return {
2740
+ content: obj.content,
2741
+ contentType: obj.contentType,
2742
+ size: obj.size,
2743
+ metadata: obj.metadata
2744
+ };
2745
+ }
2746
+ async list(params) {
2747
+ const bucket = params.bucket;
2748
+ const prefix = params.prefix ?? "";
2749
+ const maxKeys = params.maxKeys ?? 1e3;
2750
+ this.logger.debug("Storage LIST", { bucket, prefix, maxKeys });
2751
+ const bucketPrefix = `${bucket}/`;
2752
+ const fullPrefix = `${bucket}/${prefix}`;
2753
+ const results = [];
2754
+ for (const [compositeKey, obj] of this.objects) {
2755
+ if (!compositeKey.startsWith(fullPrefix)) continue;
2756
+ const objectKey = compositeKey.slice(bucketPrefix.length);
2757
+ results.push({
2758
+ key: objectKey,
2759
+ size: obj.size,
2760
+ lastModified: obj.lastModified
123
2761
  });
124
2762
  }
125
- if (paramDef.name in params) {
126
- const value = params[paramDef.name];
127
- const expectedType = paramDef.type;
128
- const actualType = typeof value;
129
- if (expectedType === "number" && actualType !== "number") {
130
- errors.push({
131
- param: paramDef.name,
132
- message: `Expected ${expectedType}, got ${actualType}`
133
- });
134
- }
135
- if (expectedType === "string" && actualType !== "string") {
136
- errors.push({
137
- param: paramDef.name,
138
- message: `Expected ${expectedType}, got ${actualType}`
139
- });
140
- }
141
- if (expectedType === "array" && !Array.isArray(value)) {
142
- errors.push({
143
- param: paramDef.name,
144
- message: `Expected array, got ${actualType}`
145
- });
2763
+ results.sort((a, b) => a.key.localeCompare(b.key));
2764
+ const truncated = results.length > maxKeys;
2765
+ return {
2766
+ keys: results.slice(0, maxKeys),
2767
+ truncated
2768
+ };
2769
+ }
2770
+ async deleteObject(params) {
2771
+ const bucket = params.bucket;
2772
+ const key = params.key;
2773
+ this.logger.debug("Storage DELETE", { bucket, key });
2774
+ const existed = this.objects.has(this.compositeKey(bucket, key));
2775
+ this.objects.delete(this.compositeKey(bucket, key));
2776
+ return { deleted: existed };
2777
+ }
2778
+ async getSignedUrl(params) {
2779
+ const bucket = params.bucket;
2780
+ const key = params.key;
2781
+ const expiresIn = params.expiresIn ?? 3600;
2782
+ const operation = params.operation ?? "get";
2783
+ this.logger.debug("Storage GET_SIGNED_URL", { bucket, key, expiresIn, operation });
2784
+ const expiresAt = Date.now() + expiresIn * 1e3;
2785
+ const token = Math.random().toString(36).slice(2, 18);
2786
+ const url = `https://storage.mock.local/${bucket}/${key}?X-Amz-Algorithm=MOCK-HMAC-SHA256&X-Amz-Expires=${expiresIn}&X-Amz-SignedHeaders=host&X-Amz-Signature=${token}&operation=${operation}`;
2787
+ return { url, expiresAt };
2788
+ }
2789
+ };
2790
+ registerIntegration("storage", StorageIntegration);
2791
+
2792
+ // src/integrations/docker/index.ts
2793
+ var DockerIntegration = class extends BaseIntegration {
2794
+ constructor(config) {
2795
+ super(config);
2796
+ this.containers = /* @__PURE__ */ new Map();
2797
+ this.images = /* @__PURE__ */ new Map();
2798
+ const dockerHost = config.env.DOCKER_HOST;
2799
+ if (dockerHost) {
2800
+ this.logger.warn(
2801
+ "DOCKER_HOST is configured but real Docker client is not yet implemented. Falling back to in-memory simulation.",
2802
+ { dockerHost }
2803
+ );
2804
+ }
2805
+ this.logger.info("Docker integration initialized (in-memory simulation)");
2806
+ }
2807
+ async execute(action, params) {
2808
+ const validation = this.validateParams(action, params);
2809
+ if (!validation.valid) {
2810
+ return {
2811
+ success: false,
2812
+ error: {
2813
+ name: "IntegrationError",
2814
+ message: "Validation failed",
2815
+ code: "VALIDATION_ERROR",
2816
+ details: validation.errors
2817
+ },
2818
+ metadata: this.createMetadata(action, 0)
2819
+ };
2820
+ }
2821
+ const startTime = Date.now();
2822
+ try {
2823
+ let data;
2824
+ switch (action) {
2825
+ case "build":
2826
+ data = await this.executeWithRetry(() => this.build(params));
2827
+ break;
2828
+ case "run":
2829
+ data = await this.executeWithRetry(() => this.run(params));
2830
+ break;
2831
+ case "stop":
2832
+ data = await this.executeWithRetry(() => this.stop(params));
2833
+ break;
2834
+ case "remove":
2835
+ data = await this.executeWithRetry(() => this.removeContainer(params));
2836
+ break;
2837
+ case "logs":
2838
+ data = await this.executeWithRetry(() => this.logs(params));
2839
+ break;
2840
+ case "status":
2841
+ data = await this.executeWithRetry(() => this.status(params));
2842
+ break;
2843
+ case "list":
2844
+ data = await this.executeWithRetry(() => this.list(params));
2845
+ break;
2846
+ default:
2847
+ throw new Error(`Unknown action: ${action}`);
2848
+ }
2849
+ return {
2850
+ success: true,
2851
+ data,
2852
+ metadata: this.createMetadata(action, Date.now() - startTime)
2853
+ };
2854
+ } catch (error) {
2855
+ return this.handleError(action, error);
2856
+ }
2857
+ }
2858
+ // ---------------------------------------------------------------------------
2859
+ // Helpers
2860
+ // ---------------------------------------------------------------------------
2861
+ /** Generate a random hex container/image ID. */
2862
+ generateId() {
2863
+ const segments = [];
2864
+ for (let i = 0; i < 16; i++) {
2865
+ segments.push(Math.floor(Math.random() * 256).toString(16).padStart(2, "0"));
2866
+ }
2867
+ return segments.join("");
2868
+ }
2869
+ /** Find a container by ID (prefix match supported). */
2870
+ findContainer(containerId) {
2871
+ const exact = this.containers.get(containerId);
2872
+ if (exact) return exact;
2873
+ for (const [id, container] of this.containers) {
2874
+ if (id.startsWith(containerId)) {
2875
+ return container;
2876
+ }
2877
+ }
2878
+ return void 0;
2879
+ }
2880
+ /** Generate realistic log lines for a container. */
2881
+ generateLogLines(container, count) {
2882
+ const lines = [...container.logs];
2883
+ const baseTime = container.startedAt ?? container.createdAt;
2884
+ while (lines.length < count) {
2885
+ const ts = new Date(baseTime + lines.length * 1e3).toISOString();
2886
+ lines.push(`${ts} [info] Container ${container.name} \u2014 heartbeat #${lines.length + 1}`);
2887
+ }
2888
+ return lines;
2889
+ }
2890
+ // ---------------------------------------------------------------------------
2891
+ // Actions
2892
+ // ---------------------------------------------------------------------------
2893
+ async build(params) {
2894
+ const dockerfile = params.dockerfile ?? "Dockerfile";
2895
+ const tag = params.tag;
2896
+ const context = params.context ?? ".";
2897
+ const buildArgs = params.buildArgs ?? {};
2898
+ this.logger.debug("Docker BUILD", { dockerfile, tag, context, buildArgs });
2899
+ const imageId = `sha256:${this.generateId()}`;
2900
+ const size = 15e7 + Math.floor(Math.random() * 35e7);
2901
+ const buildTime = 2e3 + Math.floor(Math.random() * 8e3);
2902
+ const image = {
2903
+ id: imageId,
2904
+ tag,
2905
+ dockerfile,
2906
+ size,
2907
+ createdAt: Date.now()
2908
+ };
2909
+ this.images.set(tag, image);
2910
+ return { imageId, tag, size, buildTime };
2911
+ }
2912
+ async run(params) {
2913
+ const image = params.image;
2914
+ const name = params.name ?? `container-${this.generateId().slice(0, 12)}`;
2915
+ const rawPorts = params.ports ?? [];
2916
+ const env = params.env ?? {};
2917
+ const rawVolumes = params.volumes ?? [];
2918
+ const command = params.command ?? "";
2919
+ this.logger.debug("Docker RUN", { image, name, ports: rawPorts.map((p) => `${p.host}:${p.container}`).join(", "), volumes: rawVolumes.map((v) => `${v.host}:${v.container}`).join(", "), command });
2920
+ const containerId = this.generateId();
2921
+ const ports = rawPorts.map((p) => ({
2922
+ host: p.host,
2923
+ container: p.container,
2924
+ protocol: p.protocol ?? "tcp"
2925
+ }));
2926
+ const volumes = rawVolumes.map((v) => ({
2927
+ host: v.host,
2928
+ container: v.container
2929
+ }));
2930
+ const container = {
2931
+ id: containerId,
2932
+ name,
2933
+ image,
2934
+ status: "running",
2935
+ ports,
2936
+ env,
2937
+ volumes,
2938
+ command,
2939
+ labels: {},
2940
+ createdAt: Date.now(),
2941
+ startedAt: Date.now(),
2942
+ stoppedAt: null,
2943
+ logs: [
2944
+ `${(/* @__PURE__ */ new Date()).toISOString()} [info] Starting container ${name} from image ${image}`,
2945
+ `${(/* @__PURE__ */ new Date()).toISOString()} [info] Container ${name} is now running`
2946
+ ]
2947
+ };
2948
+ this.containers.set(containerId, container);
2949
+ return {
2950
+ containerId,
2951
+ name,
2952
+ status: container.status,
2953
+ ports
2954
+ };
2955
+ }
2956
+ async stop(params) {
2957
+ const containerId = params.containerId;
2958
+ this.logger.debug("Docker STOP", { containerId });
2959
+ const container = this.findContainer(containerId);
2960
+ if (!container) {
2961
+ throw new Error(`Container not found: ${containerId}`);
2962
+ }
2963
+ if (container.status !== "running" && container.status !== "paused") {
2964
+ throw new Error(`Container ${containerId} is not running (current status: ${container.status})`);
2965
+ }
2966
+ container.status = "exited";
2967
+ container.stoppedAt = Date.now();
2968
+ container.logs.push(
2969
+ `${(/* @__PURE__ */ new Date()).toISOString()} [info] Container ${container.name} stopped`
2970
+ );
2971
+ return {
2972
+ containerId: container.id,
2973
+ status: container.status,
2974
+ stoppedAt: container.stoppedAt
2975
+ };
2976
+ }
2977
+ async removeContainer(params) {
2978
+ const containerId = params.containerId;
2979
+ const force = params.force ?? false;
2980
+ this.logger.debug("Docker REMOVE", { containerId, force });
2981
+ const container = this.findContainer(containerId);
2982
+ if (!container) {
2983
+ throw new Error(`Container not found: ${containerId}`);
2984
+ }
2985
+ if (container.status === "running" && !force) {
2986
+ throw new Error(
2987
+ `Container ${containerId} is running. Stop it first or use force=true.`
2988
+ );
2989
+ }
2990
+ this.containers.delete(container.id);
2991
+ return { containerId: container.id, removed: true };
2992
+ }
2993
+ async logs(params) {
2994
+ const containerId = params.containerId;
2995
+ const tail = params.tail ?? 100;
2996
+ const since = params.since ?? void 0;
2997
+ this.logger.debug("Docker LOGS", { containerId, tail, since });
2998
+ const container = this.findContainer(containerId);
2999
+ if (!container) {
3000
+ throw new Error(`Container not found: ${containerId}`);
3001
+ }
3002
+ let logLines = this.generateLogLines(container, tail);
3003
+ if (since) {
3004
+ const sinceMs = new Date(since).getTime();
3005
+ logLines = logLines.filter((line) => {
3006
+ const timestampMatch = /^\d{4}-\d{2}-\d{2}T[\d:.]+Z/.exec(line);
3007
+ if (!timestampMatch) return true;
3008
+ return new Date(timestampMatch[0]).getTime() >= sinceMs;
3009
+ });
3010
+ }
3011
+ const tailedLines = logLines.slice(-tail);
3012
+ return {
3013
+ containerId: container.id,
3014
+ logs: tailedLines,
3015
+ lineCount: tailedLines.length
3016
+ };
3017
+ }
3018
+ async status(params) {
3019
+ const containerId = params.containerId;
3020
+ this.logger.debug("Docker STATUS", { containerId });
3021
+ const container = this.findContainer(containerId);
3022
+ if (!container) {
3023
+ throw new Error(`Container not found: ${containerId}`);
3024
+ }
3025
+ return {
3026
+ containerId: container.id,
3027
+ name: container.name,
3028
+ image: container.image,
3029
+ status: container.status,
3030
+ ports: container.ports,
3031
+ createdAt: container.createdAt,
3032
+ startedAt: container.startedAt,
3033
+ stoppedAt: container.stoppedAt
3034
+ };
3035
+ }
3036
+ async list(params) {
3037
+ const showAll = params.all ?? false;
3038
+ const filterByLabel = params.filterByLabel ?? void 0;
3039
+ this.logger.debug("Docker LIST", { all: showAll, filterByLabel });
3040
+ let entries = Array.from(this.containers.values());
3041
+ if (!showAll) {
3042
+ entries = entries.filter((c) => c.status === "running");
3043
+ }
3044
+ if (filterByLabel) {
3045
+ const [labelKey, labelValue] = filterByLabel.split("=");
3046
+ entries = entries.filter((c) => {
3047
+ if (labelValue !== void 0) {
3048
+ return c.labels[labelKey] === labelValue;
3049
+ }
3050
+ return labelKey in c.labels;
3051
+ });
3052
+ }
3053
+ entries.sort((a, b) => b.createdAt - a.createdAt);
3054
+ const containers = entries.map((c) => ({
3055
+ id: c.id,
3056
+ name: c.name,
3057
+ image: c.image,
3058
+ status: c.status,
3059
+ ports: c.ports,
3060
+ createdAt: c.createdAt
3061
+ }));
3062
+ return { containers, total: containers.length };
3063
+ }
3064
+ };
3065
+ registerIntegration("docker", DockerIntegration);
3066
+
3067
+ // src/integrations/database/sql-guard.ts
3068
+ var DENIED_KEYWORDS = /* @__PURE__ */ new Set(["INSERT", "UPDATE", "DELETE", "MERGE", "INTO", "FOR"]);
3069
+ function isWordChar(ch) {
3070
+ return ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" || ch >= "0" && ch <= "9" || ch === "_" || ch === "$";
3071
+ }
3072
+ function skipSingleQuoted(sql, start, eString) {
3073
+ let i = start + 1;
3074
+ while (i < sql.length) {
3075
+ if (eString && sql[i] === "\\") {
3076
+ i += 2;
3077
+ continue;
3078
+ }
3079
+ if (sql[i] === "'") {
3080
+ if (sql[i + 1] === "'") {
3081
+ i += 2;
3082
+ continue;
146
3083
  }
147
- if (expectedType === "object" && (actualType !== "object" || Array.isArray(value) || value === null)) {
148
- errors.push({
149
- param: paramDef.name,
150
- message: `Expected object, got ${actualType}`
151
- });
3084
+ return i + 1;
3085
+ }
3086
+ i++;
3087
+ }
3088
+ return sql.length;
3089
+ }
3090
+ function skipDoubleQuoted(sql, start) {
3091
+ let i = start + 1;
3092
+ while (i < sql.length) {
3093
+ if (sql[i] === '"') {
3094
+ if (sql[i + 1] === '"') {
3095
+ i += 2;
3096
+ continue;
152
3097
  }
3098
+ return i + 1;
153
3099
  }
3100
+ i++;
154
3101
  }
155
- return {
156
- valid: errors.length === 0,
157
- errors
158
- };
3102
+ return sql.length;
159
3103
  }
160
-
161
- // src/core/retry.ts
162
- async function withRetry(fn, config) {
163
- const {
164
- maxAttempts,
165
- backoffMs,
166
- maxBackoffMs = 3e4,
167
- retryableErrors
168
- } = config;
169
- let lastError;
170
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
171
- try {
172
- return await fn();
173
- } catch (error) {
174
- lastError = error;
175
- if (error && typeof error === "object" && "code" in error && retryableErrors) {
176
- const integrationError = error;
177
- if (!retryableErrors.includes(integrationError.code)) {
178
- throw error;
3104
+ function matchDollarTag(sql, start) {
3105
+ let i = start + 1;
3106
+ if (sql[i] === "$") return "$$";
3107
+ const first = sql[i];
3108
+ if (!first || !(first >= "a" && first <= "z" || first >= "A" && first <= "Z" || first === "_")) {
3109
+ return void 0;
3110
+ }
3111
+ i++;
3112
+ while (i < sql.length && isWordChar(sql[i]) && sql[i] !== "$") i++;
3113
+ if (sql[i] !== "$") return void 0;
3114
+ return sql.slice(start, i + 1);
3115
+ }
3116
+ function sanitizeSql(sql) {
3117
+ const out = [];
3118
+ let i = 0;
3119
+ while (i < sql.length) {
3120
+ const ch = sql[i];
3121
+ if (ch === "-" && sql[i + 1] === "-") {
3122
+ while (i < sql.length && sql[i] !== "\n") i++;
3123
+ out.push(" ");
3124
+ continue;
3125
+ }
3126
+ if (ch === "/" && sql[i + 1] === "*") {
3127
+ let depth = 1;
3128
+ i += 2;
3129
+ while (i < sql.length && depth > 0) {
3130
+ if (sql[i] === "/" && sql[i + 1] === "*") {
3131
+ depth++;
3132
+ i += 2;
3133
+ } else if (sql[i] === "*" && sql[i + 1] === "/") {
3134
+ depth--;
3135
+ i += 2;
3136
+ } else {
3137
+ i++;
179
3138
  }
180
3139
  }
181
- if (attempt === maxAttempts) {
182
- throw error;
3140
+ out.push(" ");
3141
+ continue;
3142
+ }
3143
+ if (ch === "'") {
3144
+ let j = i - 1;
3145
+ while (j >= 0 && (sql[j] === " " || sql[j] === " " || sql[j] === "\n" || sql[j] === "\r")) j--;
3146
+ const prev = j >= 0 ? sql[j] : "";
3147
+ const eString = (prev === "e" || prev === "E") && (j === 0 || !isWordChar(sql[j - 1]));
3148
+ i = skipSingleQuoted(sql, i, eString);
3149
+ out.push("''");
3150
+ continue;
3151
+ }
3152
+ if (ch === '"') {
3153
+ i = skipDoubleQuoted(sql, i);
3154
+ out.push('""');
3155
+ continue;
3156
+ }
3157
+ if (ch === "$") {
3158
+ const tag = matchDollarTag(sql, i);
3159
+ if (tag) {
3160
+ const close = sql.indexOf(tag, i + tag.length);
3161
+ i = close === -1 ? sql.length : close + tag.length;
3162
+ out.push("$$");
3163
+ continue;
183
3164
  }
184
- const delay = Math.min(
185
- backoffMs * Math.pow(2, attempt - 1),
186
- maxBackoffMs
187
- );
188
- await new Promise((resolve) => setTimeout(resolve, delay));
189
3165
  }
3166
+ out.push(ch);
3167
+ i++;
190
3168
  }
191
- throw lastError;
3169
+ return out.join("");
192
3170
  }
193
-
194
- // src/core/BaseIntegration.ts
195
- var BaseIntegration = class {
196
- constructor(config) {
197
- this.config = config;
198
- this.logger = config.logger || new ConsoleLogger();
3171
+ function assertReadOnlySelect(sql) {
3172
+ const sanitized = sanitizeSql(sql);
3173
+ const statements = sanitized.split(";").map((s) => s.trim()).filter((s) => s.length > 0);
3174
+ if (statements.length === 0) {
3175
+ return { ok: false, reason: "Empty statement" };
199
3176
  }
200
- /**
201
- * Validate action params against registry
202
- */
203
- validateParams(action, params) {
204
- return validateParams(this.config.name, action, params);
3177
+ if (statements.length > 1) {
3178
+ return { ok: false, reason: "Only a single statement is allowed" };
205
3179
  }
206
- /**
207
- * Handle errors uniformly
208
- */
209
- handleError(action, error) {
210
- this.logger.error(`Integration error in ${this.config.name}.${action}`, {
211
- error: error instanceof Error ? error : new Error(String(error))
3180
+ const words = (statements[0].match(/\b[A-Za-z_][A-Za-z0-9_]*\b/g) ?? []).map(
3181
+ (w) => w.toUpperCase()
3182
+ );
3183
+ const first = words[0];
3184
+ if (first !== "SELECT" && first !== "WITH") {
3185
+ return { ok: false, reason: "Only SELECT statements are allowed" };
3186
+ }
3187
+ const denied = words.find((w) => DENIED_KEYWORDS.has(w));
3188
+ if (denied) {
3189
+ return { ok: false, reason: `Keyword not allowed in a read-only query: ${denied}` };
3190
+ }
3191
+ return { ok: true };
3192
+ }
3193
+
3194
+ // src/integrations/database/index.ts
3195
+ var DEFAULT_STATEMENT_TIMEOUT_MS = 1e4;
3196
+ var PG_QUERY_CANCELED = "57014";
3197
+ var PostgresDriver = class {
3198
+ constructor(connectionString, statementTimeoutMs) {
3199
+ this.pool = new Pool({
3200
+ connectionString,
3201
+ statement_timeout: statementTimeoutMs,
3202
+ query_timeout: statementTimeoutMs
212
3203
  });
213
- const integrationError = error instanceof Error ? error : new Error(String(error));
214
- return {
215
- success: false,
216
- error: integrationError,
217
- metadata: this.createMetadata(action, 0, 0)
218
- };
219
3204
  }
220
- /**
221
- * Create metadata for result
222
- */
223
- createMetadata(action, duration, retries = 0) {
3205
+ async query(sql, params) {
3206
+ const result = await this.pool.query(sql, [...params]);
224
3207
  return {
225
- integration: this.config.name,
226
- action,
227
- duration,
228
- retries,
229
- timestamp: Date.now()
3208
+ rows: result.rows,
3209
+ rowCount: result.rowCount ?? result.rows.length
230
3210
  };
231
3211
  }
232
- /**
233
- * Execute with retry logic
234
- */
235
- async executeWithRetry(fn) {
236
- if (!this.config.retry) {
237
- return fn();
3212
+ async end() {
3213
+ await this.pool.end();
3214
+ }
3215
+ };
3216
+ function mapDriverError(error) {
3217
+ if (error instanceof IntegrationError) return error;
3218
+ const code = error.code;
3219
+ if (code === PG_QUERY_CANCELED) {
3220
+ return new IntegrationError("Statement timeout exceeded", "TIMEOUT_ERROR");
3221
+ }
3222
+ const message = error instanceof Error ? error.message : String(error);
3223
+ return new IntegrationError(message, "SERVICE_ERROR");
3224
+ }
3225
+ var DatabaseIntegration = class extends BaseIntegration {
3226
+ constructor(config) {
3227
+ super(config);
3228
+ this.drivers = /* @__PURE__ */ new Map();
3229
+ const fromEnv = config.env.DATABASE_STATEMENT_TIMEOUT_MS;
3230
+ if (fromEnv) {
3231
+ const parsed = Number(fromEnv);
3232
+ if (!Number.isFinite(parsed) || parsed <= 0) {
3233
+ throw new Error(`Invalid DATABASE_STATEMENT_TIMEOUT_MS: ${fromEnv}`);
3234
+ }
3235
+ this.statementTimeoutMs = parsed;
3236
+ } else {
3237
+ this.statementTimeoutMs = config.timeout ?? DEFAULT_STATEMENT_TIMEOUT_MS;
238
3238
  }
239
- return withRetry(fn, {
240
- maxAttempts: this.config.retry.maxAttempts,
241
- backoffMs: this.config.retry.backoffMs,
242
- maxBackoffMs: this.config.retry.maxBackoffMs,
243
- retryableErrors: [
244
- "TIMEOUT_ERROR",
245
- "NETWORK_ERROR",
246
- "RATE_LIMIT_ERROR"
247
- ]
3239
+ this.logger.info("Database integration initialized", {
3240
+ statementTimeoutMs: this.statementTimeoutMs
248
3241
  });
249
3242
  }
3243
+ async execute(action, params) {
3244
+ const validation = this.validateParams(action, params);
3245
+ if (!validation.valid) {
3246
+ return {
3247
+ success: false,
3248
+ error: {
3249
+ name: "IntegrationError",
3250
+ message: "Validation failed",
3251
+ code: "VALIDATION_ERROR",
3252
+ details: validation.errors
3253
+ },
3254
+ metadata: this.createMetadata(action, 0)
3255
+ };
3256
+ }
3257
+ const startTime = Date.now();
3258
+ try {
3259
+ let data;
3260
+ switch (action) {
3261
+ case "query":
3262
+ data = await this.executeWithRetry(() => this.runQuery(params));
3263
+ break;
3264
+ default:
3265
+ throw new Error(`Unknown action: ${action}`);
3266
+ }
3267
+ return {
3268
+ success: true,
3269
+ data,
3270
+ metadata: this.createMetadata(action, Date.now() - startTime)
3271
+ };
3272
+ } catch (error) {
3273
+ return this.handleError(action, error);
3274
+ }
3275
+ }
3276
+ async runQuery(params) {
3277
+ const guard = assertReadOnlySelect(params.sql);
3278
+ if (!guard.ok) {
3279
+ throw new IntegrationError(
3280
+ `Read-only violation: ${guard.reason ?? "not a SELECT statement"}`,
3281
+ "VALIDATION_ERROR"
3282
+ );
3283
+ }
3284
+ const driver = this.driverFor(params.connectionRef);
3285
+ this.logger.debug("Database QUERY", { connectionRef: params.connectionRef });
3286
+ try {
3287
+ return await driver.query(params.sql, params.params ?? []);
3288
+ } catch (error) {
3289
+ throw mapDriverError(error);
3290
+ }
3291
+ }
3292
+ /** Resolve (and cache) the driver for a connection reference. */
3293
+ driverFor(connectionRef) {
3294
+ const connectionString = process.env[connectionRef];
3295
+ if (!connectionString) {
3296
+ throw new IntegrationError(
3297
+ `Connection reference "${connectionRef}" is not set in the environment`,
3298
+ "AUTH_ERROR"
3299
+ );
3300
+ }
3301
+ const cached = this.drivers.get(connectionString);
3302
+ if (cached) return cached;
3303
+ const driver = new PostgresDriver(connectionString, this.statementTimeoutMs);
3304
+ this.drivers.set(connectionString, driver);
3305
+ return driver;
3306
+ }
250
3307
  };
3308
+ registerIntegration("database", DatabaseIntegration);
251
3309
 
252
- // src/types.ts
253
- var IntegrationError = class extends Error {
254
- constructor(message, code = "UNKNOWN_ERROR", details) {
255
- super(message);
256
- this.name = "IntegrationError";
257
- this.code = code;
258
- this.details = details;
3310
+ // src/integrations/wikimedia/index.ts
3311
+ var WIKI_ENDPOINT = "https://en.wikipedia.org/w/api.php";
3312
+ var DEFAULT_UA = "Almadar/1.0 (https://almadar.dev)";
3313
+ var DEFAULT_TIMEOUT_MS2 = 6e3;
3314
+ var EXTRACT_CHAR_CAP = 2e3;
3315
+ var WikimediaIntegration = class extends BaseIntegration {
3316
+ constructor(config) {
3317
+ super(config);
3318
+ this.userAgent = config.env?.WIKIMEDIA_USER_AGENT ?? DEFAULT_UA;
3319
+ this.timeoutMs = Number(config.env?.WIKIMEDIA_TIMEOUT_MS ?? DEFAULT_TIMEOUT_MS2);
3320
+ this.logger.info("Wikimedia integration initialized");
259
3321
  }
260
- toJSON() {
261
- return {
262
- name: this.name,
263
- message: this.message,
264
- code: this.code,
265
- integration: this.integration,
266
- action: this.action,
267
- details: this.details
3322
+ async execute(action, params) {
3323
+ const validation = this.validateParams(action, params);
3324
+ if (!validation.valid) {
3325
+ return {
3326
+ success: false,
3327
+ error: {
3328
+ name: "IntegrationError",
3329
+ message: "Validation failed",
3330
+ code: "VALIDATION_ERROR",
3331
+ details: validation.errors
3332
+ },
3333
+ metadata: this.createMetadata(action, 0)
3334
+ };
3335
+ }
3336
+ const startTime = Date.now();
3337
+ try {
3338
+ let data;
3339
+ switch (action) {
3340
+ case "getPage":
3341
+ data = await this.executeWithRetry(() => this.getPage(params));
3342
+ break;
3343
+ default:
3344
+ throw new Error(`Unknown action: ${action}`);
3345
+ }
3346
+ return { success: true, data, metadata: this.createMetadata(action, Date.now() - startTime) };
3347
+ } catch (error) {
3348
+ return this.handleError(action, error);
3349
+ }
3350
+ }
3351
+ /** Look up a title on Wikipedia: description, portrait, lead extract. Empty fields on miss. */
3352
+ async getPage(params) {
3353
+ const title = String(params.title ?? "").trim();
3354
+ if (!title) return {};
3355
+ const url = `${WIKI_ENDPOINT}?action=query&format=json&redirects=1&prop=pageimages|description|extracts&explaintext=1&exintro=1&piprop=thumbnail&pithumbsize=240&titles=${encodeURIComponent(title)}`;
3356
+ const ctrl = new AbortController();
3357
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
3358
+ try {
3359
+ const res = await fetch(url, { headers: { "User-Agent": this.userAgent }, signal: ctrl.signal });
3360
+ if (!res.ok) return {};
3361
+ const data = await res.json();
3362
+ const pages = data.query?.pages;
3363
+ if (!pages) return {};
3364
+ const page = Object.values(pages)[0];
3365
+ if (!page || page.missing !== void 0) return {};
3366
+ const extract = typeof page.extract === "string" ? page.extract.slice(0, EXTRACT_CHAR_CAP).trim() : void 0;
3367
+ return {
3368
+ title: page.title,
3369
+ description: page.description ?? (typeof page.extract === "string" ? page.extract.split(".")[0] : void 0),
3370
+ portraitUrl: page.thumbnail?.source,
3371
+ extract
3372
+ };
3373
+ } finally {
3374
+ clearTimeout(timer);
3375
+ }
3376
+ }
3377
+ };
3378
+ registerIntegration("wikimedia", WikimediaIntegration);
3379
+
3380
+ // src/integrations/iconify/index.ts
3381
+ var ICONIFY_API = "https://api.iconify.design";
3382
+ var DEFAULT_UA2 = "Almadar/1.0 (https://almadar.dev)";
3383
+ var DEFAULT_TIMEOUT_MS3 = 6e3;
3384
+ var IconifyIntegration = class extends BaseIntegration {
3385
+ constructor(config) {
3386
+ super(config);
3387
+ this.userAgent = config.env?.ICONIFY_USER_AGENT ?? DEFAULT_UA2;
3388
+ this.timeoutMs = Number(config.env?.ICONIFY_TIMEOUT_MS ?? DEFAULT_TIMEOUT_MS3);
3389
+ this.logger.info("Iconify integration initialized");
3390
+ }
3391
+ async execute(action, params) {
3392
+ const validation = this.validateParams(action, params);
3393
+ if (!validation.valid) {
3394
+ return {
3395
+ success: false,
3396
+ error: {
3397
+ name: "IntegrationError",
3398
+ message: "Validation failed",
3399
+ code: "VALIDATION_ERROR",
3400
+ details: validation.errors
3401
+ },
3402
+ metadata: this.createMetadata(action, 0)
3403
+ };
3404
+ }
3405
+ const startTime = Date.now();
3406
+ try {
3407
+ let data;
3408
+ switch (action) {
3409
+ case "svgExists":
3410
+ data = await this.executeWithRetry(() => this.svgExists(params));
3411
+ break;
3412
+ case "search":
3413
+ data = await this.executeWithRetry(() => this.search(params));
3414
+ break;
3415
+ case "getIconBody":
3416
+ data = await this.executeWithRetry(() => this.getIconBody(params));
3417
+ break;
3418
+ default:
3419
+ throw new Error(`Unknown action: ${action}`);
3420
+ }
3421
+ return { success: true, data, metadata: this.createMetadata(action, Date.now() - startTime) };
3422
+ } catch (error) {
3423
+ return this.handleError(action, error);
3424
+ }
3425
+ }
3426
+ async svgExists(params) {
3427
+ const path = String(params.path ?? "");
3428
+ if (!path) return { exists: false };
3429
+ return { exists: await this.headOk(`${ICONIFY_API}/${path}`) };
3430
+ }
3431
+ async search(params) {
3432
+ const query = String(params.query ?? "");
3433
+ if (!query) return { icons: [] };
3434
+ const limit = Number(params.limit ?? 1);
3435
+ const data = await this.getJson(`${ICONIFY_API}/search?query=${encodeURIComponent(query)}&limit=${limit}`);
3436
+ return { icons: data?.icons ?? [] };
3437
+ }
3438
+ async getIconBody(params) {
3439
+ const iconId = String(params.iconId ?? "");
3440
+ const [prefix, name] = iconId.split(":");
3441
+ if (!prefix || !name) return { body: null };
3442
+ const data = await this.getJson(`${ICONIFY_API}/${prefix}.json?icons=${encodeURIComponent(name)}`);
3443
+ return { body: data?.icons?.[name]?.body ?? data?.aliases?.[name]?.body ?? null };
3444
+ }
3445
+ async headOk(url) {
3446
+ const ctrl = new AbortController();
3447
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
3448
+ try {
3449
+ const res = await fetch(url, { method: "GET", headers: { "User-Agent": this.userAgent }, signal: ctrl.signal });
3450
+ return res.ok;
3451
+ } catch {
3452
+ return false;
3453
+ } finally {
3454
+ clearTimeout(timer);
3455
+ }
3456
+ }
3457
+ async getJson(url) {
3458
+ const ctrl = new AbortController();
3459
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
3460
+ try {
3461
+ const res = await fetch(url, { headers: { "User-Agent": this.userAgent }, signal: ctrl.signal });
3462
+ if (!res.ok) return null;
3463
+ return await res.json();
3464
+ } catch {
3465
+ return null;
3466
+ } finally {
3467
+ clearTimeout(timer);
3468
+ }
3469
+ }
3470
+ };
3471
+ registerIntegration("iconify", IconifyIntegration);
3472
+
3473
+ // src/integrations/arxiv/index.ts
3474
+ var ARXIV_ENDPOINT = "https://export.arxiv.org/api/query";
3475
+ var DEFAULT_TIMEOUT_MS4 = 1e4;
3476
+ var DEFAULT_MAX_RESULTS = 8;
3477
+ function parseAtom(xml) {
3478
+ const entries = [];
3479
+ for (const block of xml.split("<entry>").slice(1)) {
3480
+ const grab = (tag) => {
3481
+ const m = block.match(new RegExp(`<${tag}[^>]*>([\\s\\S]*?)</${tag}>`, "i"));
3482
+ return m ? m[1].replace(/<[^>]+>/g, "").trim() : "";
268
3483
  };
3484
+ const id = grab("id");
3485
+ const title = grab("title").replace(/\s+/g, " ");
3486
+ const summary = grab("summary").replace(/\s+/g, " ");
3487
+ const published = grab("published");
3488
+ const authors = Array.from(block.matchAll(/<author>\s*<name>([^<]+)<\/name>/g)).map((m) => m[1].trim());
3489
+ const linkMatch = block.match(/<link[^>]*rel="alternate"[^>]*href="([^"]+)"/i);
3490
+ const url = linkMatch ? linkMatch[1] : id;
3491
+ if (id || title) entries.push({ id, title, summary, authors, published, url });
3492
+ }
3493
+ return entries;
3494
+ }
3495
+ var ArxivIntegration = class extends BaseIntegration {
3496
+ constructor(config) {
3497
+ super(config);
3498
+ this.timeoutMs = Number(config.env?.ARXIV_TIMEOUT_MS ?? DEFAULT_TIMEOUT_MS4);
3499
+ this.logger.info("arXiv integration initialized");
3500
+ }
3501
+ async execute(action, params) {
3502
+ const validation = this.validateParams(action, params);
3503
+ if (!validation.valid) {
3504
+ return {
3505
+ success: false,
3506
+ error: {
3507
+ name: "IntegrationError",
3508
+ message: "Validation failed",
3509
+ code: "VALIDATION_ERROR",
3510
+ details: validation.errors
3511
+ },
3512
+ metadata: this.createMetadata(action, 0)
3513
+ };
3514
+ }
3515
+ const startTime = Date.now();
3516
+ try {
3517
+ let data;
3518
+ switch (action) {
3519
+ case "search":
3520
+ data = await this.executeWithRetry(() => this.search(params));
3521
+ break;
3522
+ default:
3523
+ throw new Error(`Unknown action: ${action}`);
3524
+ }
3525
+ return { success: true, data, metadata: this.createMetadata(action, Date.now() - startTime) };
3526
+ } catch (error) {
3527
+ return this.handleError(action, error);
3528
+ }
3529
+ }
3530
+ async search(params) {
3531
+ const query = String(params.query ?? "").trim();
3532
+ if (!query) return { results: [] };
3533
+ const maxResults = Number(params.maxResults ?? DEFAULT_MAX_RESULTS);
3534
+ const url = `${ARXIV_ENDPOINT}?search_query=${encodeURIComponent(`all:${query}`)}&start=0&max_results=${maxResults}&sortBy=relevance`;
3535
+ const ctrl = new AbortController();
3536
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
3537
+ try {
3538
+ const res = await fetch(url, { headers: { "Accept": "application/atom+xml" }, signal: ctrl.signal });
3539
+ if (!res.ok) return { results: [] };
3540
+ const xml = await res.text();
3541
+ return { results: parseAtom(xml) };
3542
+ } finally {
3543
+ clearTimeout(timer);
3544
+ }
269
3545
  }
270
3546
  };
3547
+ registerIntegration("arxiv", ArxivIntegration);
271
3548
 
272
3549
  // src/mocks/MockIntegration.ts
273
3550
  var MockIntegration = class extends BaseIntegration {
@@ -356,6 +3633,35 @@ function generateMockFromShape(shape) {
356
3633
  var RuntimeIntegrationManager = class {
357
3634
  constructor() {
358
3635
  this.factory = new IntegrationFactory();
3636
+ this.installNotConfiguredFallback();
3637
+ }
3638
+ /**
3639
+ * Wrap `factory.execute` so an unknown/unconfigured service echoes its
3640
+ * params instead of throwing. This makes the manager safe to install as a
3641
+ * default `callService` handler (e.g. the playground sidecar) without every
3642
+ * service being configured. REAL execution errors (API failures, bad
3643
+ * params, schema violations) still propagate so the circuit's failure
3644
+ * events fire — only the two "not set up" errors (`Unknown integration`,
3645
+ * `Integration not configured`) are caught. Subsumes the broader wrapper
3646
+ * that previously lived inside `configureMockMode`.
3647
+ */
3648
+ installNotConfiguredFallback() {
3649
+ const originalExecute = this.factory.execute.bind(this.factory);
3650
+ this.factory.execute = async (integration, action, params) => {
3651
+ try {
3652
+ return await originalExecute(integration, action, params);
3653
+ } catch (err) {
3654
+ const msg = err instanceof Error ? err.message : String(err);
3655
+ if (/Unknown integration|not configured/i.test(msg)) {
3656
+ return {
3657
+ success: true,
3658
+ data: { ...params, _mock: true, _service: integration, _action: action },
3659
+ metadata: { integration, action, duration: 0, retries: 0, timestamp: Date.now() }
3660
+ };
3661
+ }
3662
+ throw err;
3663
+ }
3664
+ };
359
3665
  }
360
3666
  /**
361
3667
  * Configure from environment variables.
@@ -407,20 +3713,16 @@ var RuntimeIntegrationManager = class {
407
3713
  }
408
3714
  });
409
3715
  }
410
- if (env.ANTHROPIC_API_KEY) {
411
- this.factory.configure("llm", {
412
- env: {
413
- PROVIDER: "anthropic",
414
- ANTHROPIC_API_KEY: env.ANTHROPIC_API_KEY
415
- }
416
- });
417
- } else if (env.OPENAI_API_KEY) {
418
- this.factory.configure("llm", {
419
- env: {
420
- PROVIDER: "openai",
421
- OPENAI_API_KEY: env.OPENAI_API_KEY
422
- }
423
- });
3716
+ const llmEnv = {};
3717
+ for (const k of ["ANTHROPIC_API_KEY", "OPENAI_API_KEY", "DEEPSEEK_API_KEY", "KIMI_API_KEY", "OPEN_ROUTER_API_KEY"]) {
3718
+ if (env[k]) llmEnv[k] = env[k];
3719
+ }
3720
+ if (env.PROVIDER) llmEnv.PROVIDER = env.PROVIDER;
3721
+ for (const k of ["EMBEDDING_PROVIDER", "EMBEDDING_MODEL", "EMBEDDING_API_KEY"]) {
3722
+ if (env[k]) llmEnv[k] = env[k];
3723
+ }
3724
+ if (Object.keys(llmEnv).length > 0) {
3725
+ this.factory.configure("llm", { env: llmEnv });
424
3726
  }
425
3727
  if (env.MASAR_URL && env.MASAR_ML_TRAIT) {
426
3728
  this.factory.configure("ml", {
@@ -468,18 +3770,6 @@ var RuntimeIntegrationManager = class {
468
3770
  this.factory.configure(serviceName, { env: {} });
469
3771
  this.factory.registerInstance(serviceName, mock);
470
3772
  }
471
- const originalExecute = this.factory.execute.bind(this.factory);
472
- this.factory.execute = async (integration, action, params) => {
473
- try {
474
- return await originalExecute(integration, action, params);
475
- } catch {
476
- return {
477
- success: true,
478
- data: { ...params, _mock: true, _service: integration, _action: action },
479
- metadata: { integration, action, duration: 0, retries: 0, timestamp: Date.now() }
480
- };
481
- }
482
- };
483
3773
  }
484
3774
  /**
485
3775
  * Load services registry from @almadar/core/patterns.