@signaliz/sdk 1.0.1 → 1.0.4

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.
@@ -0,0 +1,4714 @@
1
+ // src/errors.ts
2
+ var SignalizError = class extends Error {
3
+ constructor(data) {
4
+ super(data.message);
5
+ this.name = "SignalizError";
6
+ this.code = data.code;
7
+ this.errorType = data.errorType;
8
+ this.retryAfter = data.retryAfter;
9
+ this.details = data.details;
10
+ }
11
+ get isRetryable() {
12
+ return this.errorType === "rate_limited" || this.errorType === "timeout" || this.errorType === "provider_error";
13
+ }
14
+ };
15
+ function parseError(status, body) {
16
+ if (body?.error && typeof body.error === "object") {
17
+ return new SignalizError({
18
+ code: body.error.code || `HTTP_${status}`,
19
+ message: body.error.message || `Request failed with status ${status}`,
20
+ errorType: mapErrorType(body.error.code, status),
21
+ retryAfter: body.error.retry_after,
22
+ details: body.error.details
23
+ });
24
+ }
25
+ return new SignalizError({
26
+ code: `HTTP_${status}`,
27
+ message: body?.message || body?.error || `Request failed with status ${status}`,
28
+ errorType: mapErrorType(void 0, status)
29
+ });
30
+ }
31
+ function mapErrorType(code, status) {
32
+ if (code === "RATE_LIMITED" || status === 429) return "rate_limited";
33
+ if (code === "VALIDATION_ERROR" || status === 400) return "validation";
34
+ if (code === "NOT_FOUND" || status === 404) return "not_found";
35
+ if (code === "AUTH_EXPIRED" || status === 401) return "auth_expired";
36
+ if (code === "INSUFFICIENT_CREDITS" || status === 402) return "insufficient_credits";
37
+ if (code === "TIMEOUT" || status === 504) return "timeout";
38
+ if (status >= 500) return "provider_error";
39
+ return "unknown";
40
+ }
41
+
42
+ // src/client.ts
43
+ var DEFAULT_BASE_URL = "https://api.signaliz.com/functions/v1";
44
+ var DEFAULT_TIMEOUT = 12e4;
45
+ var DEFAULT_MAX_RETRIES = 3;
46
+ var HttpClient = class {
47
+ constructor(config) {
48
+ this.baseUrl = config.baseUrl?.replace(/\/$/, "") || DEFAULT_BASE_URL;
49
+ this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
50
+ this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
51
+ this.apiKey = config.apiKey;
52
+ this.clientId = config.clientId;
53
+ this.clientSecret = config.clientSecret;
54
+ if (!this.apiKey && !(this.clientId && this.clientSecret)) {
55
+ throw new Error("Signaliz: provide either apiKey or clientId + clientSecret");
56
+ }
57
+ }
58
+ async request(functionName, body, method = "POST") {
59
+ let lastError;
60
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
61
+ let timer;
62
+ try {
63
+ const token = await this.getToken();
64
+ const url = new URL(`${this.baseUrl}/${functionName}`);
65
+ if (method === "GET") {
66
+ for (const [key, value] of Object.entries(body)) {
67
+ if (value === void 0 || value === null) continue;
68
+ url.searchParams.set(key, String(value));
69
+ }
70
+ }
71
+ const controller = new AbortController();
72
+ timer = setTimeout(() => controller.abort(), this.timeout);
73
+ const init = {
74
+ method,
75
+ headers: {
76
+ "Content-Type": "application/json",
77
+ Authorization: `Bearer ${token}`
78
+ },
79
+ signal: controller.signal
80
+ };
81
+ if (method === "POST") {
82
+ init.body = JSON.stringify(body);
83
+ }
84
+ const res = await fetch(url, init);
85
+ if (!res.ok) {
86
+ const errBody = await res.json().catch(() => ({}));
87
+ const err = parseError(res.status, errBody);
88
+ if (err.isRetryable && attempt < this.maxRetries) {
89
+ const wait = err.retryAfter ? err.retryAfter * 1e3 : Math.min(1e3 * Math.pow(2, attempt), 1e4);
90
+ await sleep(wait);
91
+ lastError = err;
92
+ continue;
93
+ }
94
+ throw err;
95
+ }
96
+ return await res.json();
97
+ } catch (e) {
98
+ if (e instanceof SignalizError) throw e;
99
+ if (e.name === "AbortError") {
100
+ const timeout = new SignalizError({
101
+ code: "TIMEOUT",
102
+ message: `Request timed out after ${this.timeout}ms`,
103
+ errorType: "timeout"
104
+ });
105
+ if (attempt < this.maxRetries) {
106
+ lastError = timeout;
107
+ await sleep(1e3 * Math.pow(2, attempt));
108
+ continue;
109
+ }
110
+ throw timeout;
111
+ }
112
+ lastError = e;
113
+ if (attempt < this.maxRetries) {
114
+ await sleep(1e3 * Math.pow(2, attempt));
115
+ continue;
116
+ }
117
+ } finally {
118
+ if (timer) clearTimeout(timer);
119
+ }
120
+ }
121
+ throw lastError || new Error("Request failed after retries");
122
+ }
123
+ /** Convenience wrapper for POST-based edge function calls */
124
+ async post(functionName, body) {
125
+ return this.request(functionName, body, "POST");
126
+ }
127
+ /** Convenience wrapper for GET-based edge function calls with query params */
128
+ async get(functionName, query = {}) {
129
+ return this.request(functionName, query, "GET");
130
+ }
131
+ /** JSON-RPC call to the MCP server */
132
+ async mcp(method, params = {}) {
133
+ let lastError;
134
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
135
+ let timer;
136
+ try {
137
+ const token = await this.getToken();
138
+ const url = `${this.baseUrl}/signaliz-mcp`;
139
+ const controller = new AbortController();
140
+ timer = setTimeout(() => controller.abort(), this.timeout);
141
+ const res = await fetch(url, {
142
+ method: "POST",
143
+ headers: {
144
+ "Content-Type": "application/json",
145
+ Authorization: `Bearer ${token}`
146
+ },
147
+ body: JSON.stringify({
148
+ jsonrpc: "2.0",
149
+ id: Date.now(),
150
+ method,
151
+ params: normalizeMcpParams(method, params)
152
+ }),
153
+ signal: controller.signal
154
+ });
155
+ const text = await res.text();
156
+ const data = safeJson(text);
157
+ if (!res.ok) {
158
+ const err = parseError(res.status, data ?? { message: text });
159
+ if (err.isRetryable && attempt < this.maxRetries) {
160
+ lastError = err;
161
+ await sleep(err.retryAfter ? err.retryAfter * 1e3 : Math.min(1e3 * Math.pow(2, attempt), 1e4));
162
+ continue;
163
+ }
164
+ throw err;
165
+ }
166
+ if (!data) {
167
+ throw new SignalizError({
168
+ code: "INVALID_JSON",
169
+ message: "MCP response was not valid JSON",
170
+ errorType: "provider_error",
171
+ details: { responseText: text.slice(0, 500) }
172
+ });
173
+ }
174
+ const responseError = isRecord(data) && isRecord(data.error) ? data.error : null;
175
+ if (responseError) {
176
+ const err = new SignalizError({
177
+ code: firstString(responseError.code, isRecord(responseError.data) ? responseError.data.error_code : void 0) || "MCP_ERROR",
178
+ message: firstString(responseError.message) || "MCP request failed",
179
+ errorType: mapMcpErrorType(responseError),
180
+ retryAfter: isRecord(responseError.data) && typeof responseError.data.retry_after === "number" ? responseError.data.retry_after : void 0,
181
+ details: isRecord(responseError.data) ? responseError.data : void 0
182
+ });
183
+ if (err.isRetryable && attempt < this.maxRetries) {
184
+ lastError = err;
185
+ await sleep(err.retryAfter ? err.retryAfter * 1e3 : Math.min(1e3 * Math.pow(2, attempt), 1e4));
186
+ continue;
187
+ }
188
+ throw err;
189
+ }
190
+ return unwrapMcpResponse(data);
191
+ } catch (e) {
192
+ if (e instanceof SignalizError && !e.isRetryable) throw e;
193
+ if (e.name === "AbortError") {
194
+ lastError = new SignalizError({
195
+ code: "TIMEOUT",
196
+ message: `MCP request timed out after ${this.timeout}ms`,
197
+ errorType: "timeout"
198
+ });
199
+ } else {
200
+ lastError = e;
201
+ }
202
+ if (attempt < this.maxRetries) {
203
+ await sleep(Math.min(1e3 * Math.pow(2, attempt), 1e4));
204
+ continue;
205
+ }
206
+ } finally {
207
+ if (timer) clearTimeout(timer);
208
+ }
209
+ }
210
+ throw lastError || new Error("MCP request failed after retries");
211
+ }
212
+ async getToken() {
213
+ if (this.apiKey) return this.apiKey;
214
+ if (this.accessToken) return this.accessToken;
215
+ const res = await fetch("https://api.signaliz.com/token", {
216
+ method: "POST",
217
+ headers: { "Content-Type": "application/json" },
218
+ body: JSON.stringify({
219
+ grant_type: "client_credentials",
220
+ client_id: this.clientId,
221
+ client_secret: this.clientSecret
222
+ })
223
+ });
224
+ if (!res.ok) {
225
+ throw new SignalizError({
226
+ code: "AUTH_FAILED",
227
+ message: "Failed to obtain access token",
228
+ errorType: "auth_expired"
229
+ });
230
+ }
231
+ const data = await res.json();
232
+ this.accessToken = data.access_token;
233
+ return this.accessToken;
234
+ }
235
+ };
236
+ function sleep(ms) {
237
+ return new Promise((r) => setTimeout(r, ms));
238
+ }
239
+ function safeJson(text) {
240
+ try {
241
+ return JSON.parse(text);
242
+ } catch {
243
+ return null;
244
+ }
245
+ }
246
+ function normalizeMcpParams(method, params) {
247
+ if (method !== "tools/call") return params;
248
+ const args = params.arguments;
249
+ if (!args || typeof args !== "object" || Array.isArray(args)) return params;
250
+ return {
251
+ ...params,
252
+ arguments: {
253
+ output_format: "json",
254
+ ...args
255
+ }
256
+ };
257
+ }
258
+ function isRecord(value) {
259
+ return typeof value === "object" && value !== null;
260
+ }
261
+ function firstString(...values) {
262
+ const value = values.find((item) => typeof item === "string" && item.length > 0);
263
+ return typeof value === "string" ? value : void 0;
264
+ }
265
+ function firstPayloadError(payload) {
266
+ const errors = payload.errors;
267
+ const first = Array.isArray(errors) ? errors[0] : void 0;
268
+ return isRecord(first) ? first : {};
269
+ }
270
+ function unwrapMcpResponse(data) {
271
+ const result = isRecord(data) ? data.result : void 0;
272
+ if (isRecord(result) && result.structuredContent !== void 0) {
273
+ return unwrapMcpPayload(result.structuredContent);
274
+ }
275
+ const content = isRecord(result) ? result.content : void 0;
276
+ const firstContent = Array.isArray(content) ? content[0] : void 0;
277
+ const text = isRecord(firstContent) ? firstContent.text : void 0;
278
+ if (typeof text === "string") {
279
+ const parsed = safeJson(text);
280
+ return unwrapMcpPayload(parsed ?? text);
281
+ }
282
+ return unwrapMcpPayload(result);
283
+ }
284
+ function unwrapMcpPayload(payload) {
285
+ if (isRecord(payload)) {
286
+ if (payload.ok === true && Object.prototype.hasOwnProperty.call(payload, "result")) {
287
+ return payload.result;
288
+ }
289
+ if (payload.ok === false) {
290
+ const first = firstPayloadError(payload);
291
+ const code = firstString(first.code, payload.error_code, payload.code) || (payload.approval_required ? "APPROVAL_REQUIRED" : "MCP_ERROR");
292
+ throw new SignalizError({
293
+ code,
294
+ message: firstString(first.message, payload.message, payload.summary, payload.error) || "MCP request failed",
295
+ errorType: mapErrorTypeFromCode(code),
296
+ details: {
297
+ ...payload,
298
+ ...isRecord(first.details) ? first.details : {}
299
+ }
300
+ });
301
+ }
302
+ if (payload.success === true && Object.prototype.hasOwnProperty.call(payload, "data")) {
303
+ return payload.data;
304
+ }
305
+ if (payload.success === false) {
306
+ const first = firstPayloadError(payload);
307
+ const code = firstString(first.code, payload.error_code) || (payload.approval_required ? "APPROVAL_REQUIRED" : "MCP_ERROR");
308
+ throw new SignalizError({
309
+ code,
310
+ message: firstString(first.message, payload.message, payload.summary) || "MCP request failed",
311
+ errorType: mapErrorTypeFromCode(code),
312
+ details: {
313
+ ...payload,
314
+ ...isRecord(first.details) ? first.details : {}
315
+ }
316
+ });
317
+ }
318
+ }
319
+ return payload;
320
+ }
321
+ function mapMcpErrorType(error) {
322
+ const errorRecord = isRecord(error) ? error : {};
323
+ const data = isRecord(errorRecord.data) ? errorRecord.data : {};
324
+ const code = String(data.error_code || errorRecord.code || "");
325
+ const message = String(errorRecord.message || "").toLowerCase();
326
+ if (code === "429" || message.includes("rate limit")) return "rate_limited";
327
+ if (code === "401" || code === "AUTH_001" || message.includes("auth")) return "auth_expired";
328
+ if (code === "400" || code === "-32602" || message.includes("invalid")) return "validation";
329
+ if (code === "404" || message.includes("not found")) return "not_found";
330
+ if (message.includes("timeout") || message.includes("timed out")) return "timeout";
331
+ return "unknown";
332
+ }
333
+ function mapErrorTypeFromCode(code) {
334
+ if (!code) return "unknown";
335
+ if (code === "RATE_LIMITED") return "rate_limited";
336
+ if (code === "INVALID_ARGUMENT" || code === "VALIDATION_ERROR" || code === "VALIDATION_001" || code === "APPROVAL_REQUIRED" || code === "WEBHOOK_APPROVAL_REQUIRED" || code === "TARGET_LIMIT_EXCEEDED") return "validation";
337
+ if (code === "AUTH_REQUIRED" || code === "AUTH_001") return "auth_expired";
338
+ if (code === "QUOTA_EXCEEDED") return "insufficient_credits";
339
+ if (code === "BUILD_NOT_READY" || code === "ARTIFACT_NOT_READY") return "not_found";
340
+ if (code === "BUILD_FAILED" || code === "INTERNAL_ERROR") return "provider_error";
341
+ return "unknown";
342
+ }
343
+
344
+ // src/resources/emails.ts
345
+ var Emails = class {
346
+ constructor(client) {
347
+ this.client = client;
348
+ }
349
+ /** Find and verify an email address for a person at a company */
350
+ async find(params) {
351
+ const body = {
352
+ company_domain: params.companyDomain
353
+ };
354
+ if (params.fullName) body.full_name = params.fullName;
355
+ if (params.firstName) body.first_name = params.firstName;
356
+ if (params.lastName) body.last_name = params.lastName;
357
+ if (params.linkedinUrl) body.linkedin_url = params.linkedinUrl;
358
+ if (params.companyName) body.company_name = params.companyName;
359
+ const data = await this.client.mcp("tools/call", {
360
+ name: "find_emails_with_verification",
361
+ arguments: body
362
+ });
363
+ return {
364
+ email: data.email,
365
+ firstName: data.first_name,
366
+ lastName: data.last_name,
367
+ confidence: data.confidence ?? data.confidence_score ?? 0,
368
+ verificationStatus: data.verification_status ?? "unknown",
369
+ providerUsed: data.provider_used ?? data.source ?? "unknown"
370
+ };
371
+ }
372
+ /** Verify a single email address */
373
+ async verify(email) {
374
+ const data = await this.client.mcp("tools/call", {
375
+ name: "verify_email",
376
+ arguments: { email }
377
+ });
378
+ return {
379
+ email: data.email ?? email,
380
+ isValid: data.is_valid ?? false,
381
+ isDeliverable: data.is_deliverable ?? false,
382
+ isCatchAll: data.is_catch_all ?? false,
383
+ provider: data.provider,
384
+ confidenceScore: data.confidence_score ?? 0,
385
+ verificationSource: data.verification_source
386
+ };
387
+ }
388
+ /** Submit up to 5,000 contacts for async find + verify processing. */
389
+ async findBatch(contacts) {
390
+ const data = await this.client.mcp("tools/call", {
391
+ name: "find_and_verify_emails",
392
+ arguments: {
393
+ contacts: contacts.map((contact) => ({
394
+ full_name: contact.fullName,
395
+ first_name: contact.firstName,
396
+ last_name: contact.lastName,
397
+ company_domain: contact.companyDomain,
398
+ linkedin_url: contact.linkedinUrl,
399
+ company_name: contact.companyName
400
+ }))
401
+ }
402
+ });
403
+ return mapBatchJob(data, "find_and_verify_emails");
404
+ }
405
+ /** Submit up to 5,000 email addresses for async verification. */
406
+ async verifyBatch(emails) {
407
+ const data = await this.client.mcp("tools/call", {
408
+ name: "verify_emails",
409
+ arguments: { emails }
410
+ });
411
+ return mapBatchJob(data, "verify_emails");
412
+ }
413
+ /** Poll a batch email job returned by findBatch or verifyBatch. */
414
+ async checkStatus(jobId, opts) {
415
+ return this.client.mcp("tools/call", {
416
+ name: "check_job_status",
417
+ arguments: {
418
+ job_id: jobId,
419
+ page: opts?.page,
420
+ page_size: opts?.pageSize,
421
+ include_partial_results: opts?.includePartialResults
422
+ }
423
+ });
424
+ }
425
+ };
426
+ function mapBatchJob(data, fallbackCapability) {
427
+ return {
428
+ jobId: data.job_id,
429
+ status: data.status,
430
+ capability: data.capability ?? fallbackCapability,
431
+ itemsTotal: data.items_total ?? data.total ?? 0,
432
+ message: data.message ?? "",
433
+ estimatedTimeSeconds: data.estimated_time_seconds,
434
+ skippedCount: data.skipped_count,
435
+ queuePosition: data.queue_position,
436
+ estimatedStartTime: data.estimated_start_time
437
+ };
438
+ }
439
+
440
+ // src/resources/signals.ts
441
+ var Signals = class {
442
+ constructor(client) {
443
+ this.client = client;
444
+ }
445
+ /** Enrich a company with actionable signals (V1) */
446
+ async enrich(params) {
447
+ const args = {
448
+ company_name: params.companyName
449
+ };
450
+ if (params.domain) args.domain = params.domain;
451
+ if (params.researchPrompt) args.research_prompt = params.researchPrompt;
452
+ if (params.signalTypes) args.signal_types = params.signalTypes;
453
+ const data = await this.client.mcp("tools/call", {
454
+ name: "enrich_company_signals",
455
+ arguments: args
456
+ });
457
+ return {
458
+ companyName: data.company_name ?? params.companyName,
459
+ signals: (data.signals ?? []).map((s) => ({
460
+ title: s.title,
461
+ signalType: s.signal_type,
462
+ confidenceScore: s.confidence_score ?? 0,
463
+ detectedAt: s.detected_at ?? "",
464
+ url: s.url,
465
+ content: s.content ?? ""
466
+ })),
467
+ totalSignals: data.total_signals ?? data.signals?.length ?? 0,
468
+ fromCache: data.from_cache ?? false
469
+ };
470
+ }
471
+ /** Enrich a company with actionable signals (V2 — clean response + online mode) */
472
+ async enrichV2(params) {
473
+ const args = {};
474
+ if (params.companyName) args.company_name = params.companyName;
475
+ if (params.domain) args.domain = params.domain;
476
+ if (params.companyDomain) args.company_domain = params.companyDomain;
477
+ if (params.researchPrompt) args.research_prompt = params.researchPrompt;
478
+ if (params.signalTypes) args.signal_types = params.signalTypes;
479
+ if (params.online !== void 0) args.online = params.online;
480
+ if (params.targetSignalCount) args.target_signal_count = params.targetSignalCount;
481
+ if (params.lookbackDays) args.lookback_days = params.lookbackDays;
482
+ if (params.model) args.model = params.model;
483
+ if (params.enableDeepSearch) args.enable_deep_search = params.enableDeepSearch;
484
+ if (params.enableOutreachIntelligence) args.enable_outreach_intelligence = params.enableOutreachIntelligence;
485
+ if (params.enablePredictiveIntelligence) args.enable_predictive_intelligence = params.enablePredictiveIntelligence;
486
+ if (params.icpId) args.icp_id = params.icpId;
487
+ if (params.cacheTtlHours !== void 0) args.cache_ttl_hours = params.cacheTtlHours;
488
+ if (params.skipCache) args.skip_cache = params.skipCache;
489
+ const data = await this.client.post("company-signal-enrichment-v2", args);
490
+ return {
491
+ success: data.success ?? false,
492
+ company: {
493
+ name: data.company?.name ?? null,
494
+ domain: data.company?.domain ?? null
495
+ },
496
+ signals: (data.signals ?? []).map((s) => ({
497
+ id: s.id,
498
+ title: s.title,
499
+ type: s.type,
500
+ content: s.content ?? "",
501
+ date: s.date ?? null,
502
+ sourceUrl: s.source_url ?? null,
503
+ sourceType: s.source_type ?? "unknown",
504
+ confidence: s.confidence ?? null
505
+ })),
506
+ signalCount: data.signal_count ?? 0,
507
+ intelligence: data.intelligence ? {
508
+ executiveSummary: data.intelligence.executive_summary ?? null,
509
+ keyThemes: data.intelligence.key_themes ?? [],
510
+ relevanceScore: data.intelligence.relevance_score ?? null,
511
+ outreach: data.intelligence.outreach ? {
512
+ urgencyScore: data.intelligence.outreach.urgency_score ?? null,
513
+ bestTiming: data.intelligence.outreach.best_timing ?? null,
514
+ primaryAngle: data.intelligence.outreach.primary_angle ?? null,
515
+ ctas: data.intelligence.outreach.ctas ? {
516
+ soft: data.intelligence.outreach.ctas.soft,
517
+ direct: data.intelligence.outreach.ctas.direct,
518
+ valueFirst: data.intelligence.outreach.ctas.value_first
519
+ } : null,
520
+ conversationStarters: data.intelligence.outreach.conversation_starters ?? []
521
+ } : null,
522
+ predictions: (data.intelligence.predictions ?? []).map((p) => ({
523
+ prediction: p.prediction,
524
+ confidence: p.confidence,
525
+ targetPersona: p.target_persona ?? null,
526
+ recommendedAction: p.recommended_action ?? null
527
+ }))
528
+ } : null,
529
+ credits: {
530
+ charged: data.credits?.charged ?? 0,
531
+ billingType: data.credits?.billing_type ?? "unknown",
532
+ breakdown: {
533
+ signalCredits: data.credits?.breakdown?.signal_credits ?? 0,
534
+ modelCostUsd: data.credits?.breakdown?.model_cost_usd ?? 0,
535
+ modelCredits: data.credits?.breakdown?.model_credits ?? 0,
536
+ explanation: data.credits?.breakdown?.explanation ?? ""
537
+ }
538
+ },
539
+ metadata: {
540
+ version: data.metadata?.version ?? "",
541
+ model: data.metadata?.model ?? "",
542
+ online: data.metadata?.online ?? false,
543
+ processingTimeMs: data.metadata?.processing_time_ms ?? 0
544
+ }
545
+ };
546
+ }
547
+ };
548
+
549
+ // src/resources/systems.ts
550
+ var Systems = class {
551
+ constructor(client) {
552
+ this.client = client;
553
+ }
554
+ /** Create a new pipeline/system */
555
+ async create(params) {
556
+ const data = await this.client.mcp("tools/call", {
557
+ name: "create_system",
558
+ arguments: {
559
+ name: params.name,
560
+ description: params.description,
561
+ capabilities: params.capabilities,
562
+ field_mappings: params.fieldMappings
563
+ }
564
+ });
565
+ return {
566
+ id: data.system_id ?? data.id,
567
+ name: data.name ?? params.name,
568
+ status: data.status ?? "created",
569
+ nodeCount: data.node_count ?? params.capabilities.length,
570
+ createdAt: data.created_at ?? (/* @__PURE__ */ new Date()).toISOString()
571
+ };
572
+ }
573
+ /** Run a system with input data */
574
+ async run(systemId, params) {
575
+ const data = await this.client.mcp("tools/call", {
576
+ name: "run_system",
577
+ arguments: {
578
+ system_id: systemId,
579
+ input_data: params.data,
580
+ async: params.async ?? false
581
+ }
582
+ });
583
+ return {
584
+ runId: data.run_id ?? data.id,
585
+ status: data.status ?? "running",
586
+ totalRows: data.total_rows,
587
+ completedRows: data.completed_rows ?? 0,
588
+ creditsUsed: data.credits_used ?? 0
589
+ };
590
+ }
591
+ /** Get a system by ID */
592
+ async get(systemId) {
593
+ const data = await this.client.mcp("tools/call", {
594
+ name: "get_system",
595
+ arguments: { system_id: systemId }
596
+ });
597
+ return {
598
+ id: data.id ?? systemId,
599
+ name: data.name,
600
+ status: data.status,
601
+ nodeCount: data.node_count ?? 0,
602
+ createdAt: data.created_at
603
+ };
604
+ }
605
+ /** List all systems */
606
+ async list() {
607
+ const data = await this.client.mcp("tools/call", {
608
+ name: "list_systems",
609
+ arguments: {}
610
+ });
611
+ return (data.systems ?? data ?? []).map((s) => ({
612
+ id: s.id,
613
+ name: s.name,
614
+ status: s.status,
615
+ nodeCount: s.node_count ?? 0,
616
+ createdAt: s.created_at
617
+ }));
618
+ }
619
+ };
620
+
621
+ // src/resources/runs.ts
622
+ var Runs = class {
623
+ constructor(client) {
624
+ this.client = client;
625
+ }
626
+ /** Get run status across Trigger, batch, and dataplane runs. */
627
+ async get(runId) {
628
+ const data = await this.client.mcp("tools/call", {
629
+ name: "get_run",
630
+ arguments: { run_id: runId }
631
+ });
632
+ return normalizeRunResult(data, runId);
633
+ }
634
+ /** Poll until a run completes. Returns final result. */
635
+ async waitForCompletion(runId, pollIntervalMs = 2e3) {
636
+ while (true) {
637
+ const run = await this.get(runId);
638
+ if (isTerminalRunStatus(run.status)) {
639
+ return run;
640
+ }
641
+ await new Promise((r) => setTimeout(r, pollIntervalMs));
642
+ }
643
+ }
644
+ /**
645
+ * Stream run progress as an async iterator.
646
+ * Usage: for await (const event of signaliz.runs.stream(runId)) { ... }
647
+ */
648
+ async *stream(runId, pollIntervalMs = 1500) {
649
+ let lastCompleted = -1;
650
+ while (true) {
651
+ const run = await this.get(runId);
652
+ const event = {
653
+ runId,
654
+ status: run.status,
655
+ completedRows: run.completedRows ?? 0,
656
+ totalRows: run.totalRows ?? 0,
657
+ creditsUsed: run.creditsUsed ?? 0
658
+ };
659
+ if (event.completedRows !== lastCompleted) {
660
+ lastCompleted = event.completedRows;
661
+ yield event;
662
+ }
663
+ if (isTerminalRunStatus(run.status)) {
664
+ return;
665
+ }
666
+ await new Promise((r) => setTimeout(r, pollIntervalMs));
667
+ }
668
+ }
669
+ };
670
+ function normalizeRunResult(data, fallbackRunId) {
671
+ const progress = data?.progress && typeof data.progress === "object" ? data.progress : {};
672
+ const status = String(data?.status ?? data?.trigger_status ?? "unknown").toLowerCase();
673
+ const totalRows = numberOrUndefined(
674
+ data?.total_rows ?? data?.totalRows ?? data?.items_total ?? progress.items_total ?? progress.total ?? data?.results_count
675
+ );
676
+ const completedRows = numberOrUndefined(
677
+ data?.completed_rows ?? data?.completedRows ?? progress.items_completed ?? progress.items_succeeded ?? progress.completed ?? data?.results_count
678
+ );
679
+ return {
680
+ runId: data?.run_id ?? data?.job_id ?? fallbackRunId,
681
+ status,
682
+ totalRows,
683
+ completedRows: completedRows ?? 0,
684
+ creditsUsed: numberOrUndefined(data?.credits_used ?? data?.creditsUsed ?? data?.credits_consumed) ?? 0,
685
+ completed: data?.completed ?? isTerminalRunStatus(status),
686
+ retryEligible: data?.retry_eligible,
687
+ triggerStatus: data?.trigger_status,
688
+ output: data?.output ?? data?.results ?? data?.results_preview,
689
+ error: data?.error ?? data?.error_message,
690
+ message: data?.message,
691
+ recoveryGuidance: data?.recovery_guidance,
692
+ raw: data
693
+ };
694
+ }
695
+ function numberOrUndefined(value) {
696
+ const number = Number(value);
697
+ return Number.isFinite(number) ? number : void 0;
698
+ }
699
+ function isTerminalRunStatus(status) {
700
+ return [
701
+ "completed",
702
+ "failed",
703
+ "cancelled",
704
+ "canceled",
705
+ "crashed",
706
+ "timed_out",
707
+ "interrupted",
708
+ "system_failure"
709
+ ].includes(String(status || "").toLowerCase());
710
+ }
711
+
712
+ // src/resources/http.ts
713
+ var Http = class {
714
+ constructor(client) {
715
+ this.client = client;
716
+ }
717
+ /** Proxy an HTTP request through Signaliz */
718
+ async request(params) {
719
+ const data = await this.client.mcp("tools/call", {
720
+ name: "http_request",
721
+ arguments: {
722
+ url: params.url,
723
+ method: params.method,
724
+ headers: params.headers,
725
+ body: params.body ? JSON.stringify(params.body) : void 0
726
+ }
727
+ });
728
+ return {
729
+ statusCode: data.status_code ?? data.statusCode ?? 200,
730
+ headers: data.headers ?? {},
731
+ body: data.body ?? data.response ?? data
732
+ };
733
+ }
734
+ };
735
+
736
+ // src/resources/campaigns.ts
737
+ var Campaigns = class {
738
+ constructor(client) {
739
+ this.client = client;
740
+ }
741
+ // ── First-class shorthand API ──────────────────────────────────────────────
742
+ /**
743
+ * Start an async Campaign Build.
744
+ * Returns immediately with a pollable campaign_build_id.
745
+ *
746
+ * ```ts
747
+ * const result = await signaliz.campaigns.build({ name: 'Q3 SaaS', prompt: '...' });
748
+ * console.log(result.campaignBuildId);
749
+ * ```
750
+ */
751
+ async build(request, options) {
752
+ return this.buildCampaign(request, options);
753
+ }
754
+ /** Scope an agency/client campaign into a markdown brief plus build_campaign dry-run args. */
755
+ async scope(request) {
756
+ return this.scopeCampaign(request);
757
+ }
758
+ /** Get a concise status snapshot — ideal for polling loops. */
759
+ async status(campaignBuildId) {
760
+ return this.getCampaignBuildStatus(campaignBuildId);
761
+ }
762
+ /** Get the full campaign build record including delivery details. */
763
+ async get(campaignBuildId) {
764
+ const data = await this.callMcp("get_campaign_build", {
765
+ campaign_build_id: campaignBuildId
766
+ });
767
+ return mapStatus(data);
768
+ }
769
+ /** Retrieve paginated rows from a completed build. */
770
+ async rows(campaignBuildId, options) {
771
+ return this.getCampaignBuildRows(campaignBuildId, options);
772
+ }
773
+ /** List all artifacts (CSV exports, etc.) for a build. */
774
+ async artifacts(campaignBuildId) {
775
+ return this.listCampaignBuildArtifacts(campaignBuildId);
776
+ }
777
+ /** Cancel a queued or running build. */
778
+ async cancel(campaignBuildId, reason) {
779
+ return this.cancelCampaignBuild(campaignBuildId, reason);
780
+ }
781
+ /**
782
+ * Poll until a campaign build reaches a terminal status.
783
+ *
784
+ * ```ts
785
+ * const final = await signaliz.campaigns.wait(buildId, {
786
+ * onProgress: (s) => console.log(`${s.recordsProcessed}/${s.recordsTotal}`),
787
+ * });
788
+ * ```
789
+ */
790
+ async wait(campaignBuildId, options) {
791
+ return this.waitForCompletion(campaignBuildId, {
792
+ intervalMs: options?.intervalMs,
793
+ timeoutMs: options?.timeoutMs,
794
+ onStatus: options?.onProgress
795
+ });
796
+ }
797
+ // ── Full method names (kept for backward-compat) ───────────────────────────
798
+ async scopeCampaign(request) {
799
+ const data = await this.callMcp("scope_campaign", scopeArgs(request));
800
+ return mapScope(data);
801
+ }
802
+ async buildCampaign(request, options) {
803
+ const args = buildArgs(request);
804
+ if (options?.idempotencyKey) {
805
+ args.idempotency_key = options.idempotencyKey;
806
+ }
807
+ const data = await this.callMcp("build_campaign", args);
808
+ return {
809
+ campaignBuildId: data.campaign_build_id ?? null,
810
+ campaignId: data.campaign_id ?? null,
811
+ campaignObject: data.campaign_object ?? null,
812
+ status: data.dry_run ? "dry_run" : data.status ?? "queued",
813
+ currentPhase: data.dry_run ? "plan" : data.current_phase ?? "acquisition",
814
+ nextPollAfterSeconds: data.next_poll_after_seconds ?? 10,
815
+ message: data.message ?? data.summary ?? "",
816
+ dryRun: data.dry_run === true,
817
+ requestedTargetCount: data.requested_target_count,
818
+ plannedTargetCount: data.planned_target_count,
819
+ estimatedCredits: data.estimated_credits,
820
+ estimatedDurationSeconds: data.estimated_duration_seconds,
821
+ targetLimitApplied: data.target_limit_applied,
822
+ targetLimitReason: data.target_limit_reason,
823
+ maxSupportedTargetCount: data.max_supported_target_count,
824
+ brainContext: data.brain_context ?? {},
825
+ providerRoute: mapProviderRoute(data)
826
+ };
827
+ }
828
+ async getCampaignBuildStatus(campaignBuildId) {
829
+ const data = await this.callMcp("get_campaign_build_status", {
830
+ campaign_build_id: campaignBuildId
831
+ });
832
+ return mapStatus(data);
833
+ }
834
+ async listCampaignBuildArtifacts(campaignBuildId) {
835
+ const data = await this.callMcp("list_campaign_build_artifacts", {
836
+ campaign_build_id: campaignBuildId
837
+ });
838
+ return (data.artifacts ?? []).map(mapArtifact);
839
+ }
840
+ async getCampaignBuildRows(campaignBuildId, options) {
841
+ const args = { campaign_build_id: campaignBuildId };
842
+ if (options?.limit) args.page_size = options.limit;
843
+ if (options?.cursor) args.cursor = options.cursor;
844
+ const filters = {};
845
+ if (options?.segment) filters.segment = options.segment;
846
+ if (options?.rowStatus) filters.row_status = options.rowStatus;
847
+ if (options?.qualified !== void 0) filters.qualified = options.qualified;
848
+ if (Object.keys(filters).length > 0) args.filters = filters;
849
+ const data = await this.callMcp("get_campaign_build_rows", args);
850
+ return {
851
+ campaignBuildId: data.campaign_build_id,
852
+ rows: (data.rows ?? []).map((r, i) => ({
853
+ index: r.index ?? i,
854
+ status: r.status ?? r.row_status ?? "unknown",
855
+ qualified: r.qualified ?? true,
856
+ segment: r.segment ?? null,
857
+ data: r.data ?? r
858
+ })),
859
+ count: data.count ?? 0,
860
+ pageSize: data.page_size ?? 50,
861
+ nextCursor: data.next_cursor ?? null,
862
+ hasMore: data.has_more ?? false
863
+ };
864
+ }
865
+ async approveCampaignDelivery(campaignBuildId, destinationType, options) {
866
+ const args = {
867
+ campaign_build_id: campaignBuildId,
868
+ destination_type: destinationType
869
+ };
870
+ if (options?.destinationId) args.destination_id = options.destinationId;
871
+ if (options?.destinationConfig) args.destination_config = options.destinationConfig;
872
+ const data = await this.callMcp("approve_campaign_delivery", args);
873
+ return {
874
+ campaignBuildId: data.campaign_build_id,
875
+ destinationType: data.destination_type ?? destinationType,
876
+ status: data.status ?? "approved",
877
+ message: data.message ?? "",
878
+ deliveryId: data.delivery_id,
879
+ deliveryIds: data.delivery_ids,
880
+ approvedCount: data.approved_count
881
+ };
882
+ }
883
+ async cancelCampaignBuild(campaignBuildId, reason) {
884
+ const data = await this.callMcp("cancel_campaign_build", {
885
+ campaign_build_id: campaignBuildId,
886
+ reason: reason ?? "Canceled by user"
887
+ });
888
+ return {
889
+ campaignBuildId: data.campaign_build_id,
890
+ status: data.status ?? "canceled",
891
+ reason: data.reason ?? reason ?? "",
892
+ message: data.message ?? ""
893
+ };
894
+ }
895
+ async waitForCompletion(campaignBuildId, options) {
896
+ const interval = options?.intervalMs ?? 5e3;
897
+ const timeout = options?.timeoutMs ?? 6e5;
898
+ const start = Date.now();
899
+ while (true) {
900
+ const s = await this.getCampaignBuildStatus(campaignBuildId);
901
+ options?.onStatus?.(s);
902
+ if (["completed", "failed", "canceled"].includes(s.status)) {
903
+ return s;
904
+ }
905
+ if (Date.now() - start > timeout) {
906
+ throw new Error(`Campaign build ${campaignBuildId} timed out after ${timeout}ms (status: ${s.status})`);
907
+ }
908
+ await new Promise((r) => setTimeout(r, interval));
909
+ }
910
+ }
911
+ // ── Internal helpers ─────────────────────────────────────────────────────────
912
+ async callMcp(tool, args) {
913
+ return this.client.mcp("tools/call", { name: tool, arguments: args });
914
+ }
915
+ };
916
+ function mapStatus(data) {
917
+ return {
918
+ campaignBuildId: data.campaign_build_id,
919
+ campaignId: data.campaign_id ?? null,
920
+ campaignObject: data.campaign_object ?? null,
921
+ name: data.name,
922
+ status: data.status,
923
+ currentPhase: data.current_phase,
924
+ currentPhaseStatus: data.current_phase_status,
925
+ phases: data.phases ?? [],
926
+ recordsTotal: data.records_total ?? 0,
927
+ recordsProcessed: data.records_processed ?? 0,
928
+ recordsSucceeded: data.records_succeeded ?? 0,
929
+ recordsFailed: data.records_failed ?? 0,
930
+ warnings: data.warnings ?? [],
931
+ errors: data.errors ?? [],
932
+ artifactCount: data.artifact_count ?? 0,
933
+ providerRoute: mapProviderRoute(data),
934
+ nextAction: data.next_action ?? "",
935
+ createdAt: data.created_at,
936
+ updatedAt: data.updated_at,
937
+ completedAt: data.completed_at
938
+ };
939
+ }
940
+ function mapProviderRoute(data) {
941
+ const brainContext = recordOrNull(data?.brain_context);
942
+ const plan = recordOrNull(data?.provider_route_plan) ?? recordOrNull(brainContext?.provider_route_plan);
943
+ const summary = recordOrNull(data?.provider_route_summary) ?? recordOrNull(brainContext?.provider_route_summary) ?? recordOrNull(plan?.summary);
944
+ const blockers = stringArray(data?.provider_route_blockers ?? brainContext?.provider_route_blockers ?? plan?.blockers);
945
+ const warnings = stringArray(data?.provider_route_warnings ?? brainContext?.provider_route_warnings ?? plan?.warnings);
946
+ const ready = booleanOrNull(data?.provider_route_ready ?? brainContext?.provider_route_ready ?? plan?.ready);
947
+ const label = typeof data?.provider_route_label === "string" ? data.provider_route_label : typeof brainContext?.provider_route_label === "string" ? brainContext.provider_route_label : providerRouteLabel(summary, ready);
948
+ if (!plan && !summary && ready === null && blockers.length === 0 && warnings.length === 0 && !label) {
949
+ return null;
950
+ }
951
+ return {
952
+ plan,
953
+ summary,
954
+ ready,
955
+ label: label || "attached",
956
+ blockers,
957
+ warnings
958
+ };
959
+ }
960
+ function recordOrNull(value) {
961
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
962
+ }
963
+ function stringArray(value) {
964
+ return Array.isArray(value) ? value.map((item) => String(item || "").trim()).filter(Boolean) : [];
965
+ }
966
+ function booleanOrNull(value) {
967
+ return typeof value === "boolean" ? value : null;
968
+ }
969
+ function numberOrNull(value) {
970
+ const parsed = Number(value);
971
+ return Number.isFinite(parsed) ? parsed : null;
972
+ }
973
+ function providerRouteLabel(summary, ready) {
974
+ if (!summary) return ready === true ? "ready" : ready === false ? "blocked" : "";
975
+ const totalLayers = numberOrNull(summary.total_layers);
976
+ const readyLayers = numberOrNull(summary.ready_layers);
977
+ const customProviderLayers = numberOrNull(summary.custom_provider_layers);
978
+ const signalizDefaultLayers = numberOrNull(summary.signaliz_default_layers);
979
+ const fallbackLayers = numberOrNull(summary.fallback_layers);
980
+ const blockedLayers = numberOrNull(summary.blocked_layers);
981
+ return [
982
+ totalLayers === null || readyLayers === null ? ready === true ? "ready" : ready === false ? "blocked" : null : `${readyLayers}/${totalLayers} layers ready`,
983
+ customProviderLayers !== null ? `${customProviderLayers} custom` : null,
984
+ signalizDefaultLayers !== null ? `${signalizDefaultLayers} Signaliz default` : null,
985
+ fallbackLayers !== null ? `${fallbackLayers} fallback` : null,
986
+ blockedLayers !== null ? `${blockedLayers} blocked` : null
987
+ ].filter(Boolean).join(", ");
988
+ }
989
+ function mapArtifact(a) {
990
+ return {
991
+ id: a.id,
992
+ campaignBuildId: a.campaign_build_id,
993
+ artifactType: a.artifact_type,
994
+ destination: a.destination,
995
+ storagePath: a.storage_path,
996
+ signedUrl: a.signed_url,
997
+ rowCount: a.row_count ?? 0,
998
+ checksum: a.checksum,
999
+ metadata: a.metadata ?? {},
1000
+ createdAt: a.created_at
1001
+ };
1002
+ }
1003
+ function mapScope(data) {
1004
+ return {
1005
+ campaignScopeId: data.campaign_scope_id,
1006
+ clientName: data.client_name,
1007
+ campaignName: data.campaign_name,
1008
+ approach: data.approach,
1009
+ approachLabel: data.approach_label,
1010
+ goal: data.goal,
1011
+ targetCount: data.target_count,
1012
+ icp: data.icp ?? {},
1013
+ personas: data.personas ?? [],
1014
+ sourceStrategy: data.source_strategy ?? [],
1015
+ qualificationPlan: data.qualification_plan ?? [],
1016
+ signalPlan: data.signal_plan ?? [],
1017
+ copyPlan: data.copy_plan ?? {},
1018
+ deliveryPlan: data.delivery_plan ?? {},
1019
+ brainPreflight: data.brain_preflight ?? {},
1020
+ recommendedSignalizTools: data.recommended_signaliz_tools ?? [],
1021
+ buildCampaignArgs: data.build_campaign_args ?? {},
1022
+ mcpFlow: data.mcp_flow ?? [],
1023
+ missingInputs: data.missing_inputs ?? [],
1024
+ estimatedCredits: data.estimated_credits ?? 0,
1025
+ campaignMarkdown: data.campaign_markdown ?? ""
1026
+ };
1027
+ }
1028
+ function scopeArgs(request) {
1029
+ const args = {
1030
+ prompt: request.prompt
1031
+ };
1032
+ if (request.clientName) args.client_name = request.clientName;
1033
+ if (request.clientContext) args.client_context = request.clientContext;
1034
+ if (request.campaignGoal) args.campaign_goal = request.campaignGoal;
1035
+ if (request.targetCount) args.target_count = request.targetCount;
1036
+ if (request.destinations) args.destinations = request.destinations;
1037
+ if (request.knownAccounts) args.known_accounts = request.knownAccounts;
1038
+ if (request.offers) args.offers = request.offers;
1039
+ if (request.proofPoints) args.proof_points = request.proofPoints;
1040
+ if (request.sourceDocs) args.source_docs = request.sourceDocs;
1041
+ if (request.approvalPolicy) args.approval_policy = request.approvalPolicy;
1042
+ return args;
1043
+ }
1044
+ function buildArgs(request) {
1045
+ const args = {
1046
+ name: request.name,
1047
+ prompt: request.prompt
1048
+ };
1049
+ if (request.gtmCampaignId) args.gtm_campaign_id = request.gtmCampaignId;
1050
+ if (request.description) args.description = request.description;
1051
+ if (request.targetCount) args.target_count = request.targetCount;
1052
+ if (request.dryRun !== void 0) args.dry_run = request.dryRun;
1053
+ if (request.allowDownscale !== void 0) args.allow_downscale = request.allowDownscale;
1054
+ if (request.confirmSpend !== void 0) args.confirm_spend = request.confirmSpend;
1055
+ if (request.dedupKeys) args.dedup_keys = request.dedupKeys;
1056
+ if (request.brainPreflight) args.brain_preflight = request.brainPreflight;
1057
+ if (request.brainDefaults) args.brain_defaults = request.brainDefaults;
1058
+ if (request.deliveryRisk) args.delivery_risk = request.deliveryRisk;
1059
+ if (request.icp) {
1060
+ args.icp = {
1061
+ personas: request.icp.personas,
1062
+ industries: request.icp.industries,
1063
+ company_sizes: request.icp.companySizes,
1064
+ geographies: request.icp.geographies,
1065
+ keywords: request.icp.keywords,
1066
+ exclusions: request.icp.exclusions,
1067
+ require_verified_email: request.icp.requireVerifiedEmail
1068
+ };
1069
+ }
1070
+ if (request.policy) {
1071
+ args.policy = {
1072
+ max_credits: request.policy.maxCredits,
1073
+ verify_emails: request.policy.verifyEmails,
1074
+ model: request.policy.model
1075
+ };
1076
+ }
1077
+ if (request.signals) {
1078
+ args.signals = {
1079
+ enabled: request.signals.enabled,
1080
+ types: request.signals.types,
1081
+ custom_prompt: request.signals.customPrompt,
1082
+ confidence_threshold: request.signals.confidenceThreshold,
1083
+ lookback_days: request.signals.lookbackDays
1084
+ };
1085
+ }
1086
+ if (request.qualification) {
1087
+ args.qualification = {
1088
+ enabled: request.qualification.enabled,
1089
+ model: request.qualification.model
1090
+ };
1091
+ }
1092
+ if (request.copy) {
1093
+ args.copy = {
1094
+ enabled: request.copy.enabled,
1095
+ tone: request.copy.tone,
1096
+ max_body_words: request.copy.maxBodyWords,
1097
+ sender_context: request.copy.senderContext,
1098
+ offer_context: request.copy.offerContext,
1099
+ model: request.copy.model
1100
+ };
1101
+ }
1102
+ if (request.delivery) {
1103
+ args.delivery = {
1104
+ enabled: request.delivery.enabled,
1105
+ destination_type: request.delivery.destinationType,
1106
+ approval_required: request.delivery.approvalRequired,
1107
+ include_disqualified: request.delivery.includeDisqualified,
1108
+ destination_config: request.delivery.destinationConfig
1109
+ };
1110
+ }
1111
+ if (request.enhancers) {
1112
+ const e = {};
1113
+ if (request.enhancers.clay) {
1114
+ e.clay = {
1115
+ enabled: request.enhancers.clay.enabled,
1116
+ mode: request.enhancers.clay.mode,
1117
+ table_id: request.enhancers.clay.tableId,
1118
+ enrichment_fields: request.enhancers.clay.enrichmentFields,
1119
+ api_key_env: request.enhancers.clay.apiKeyEnv
1120
+ };
1121
+ }
1122
+ if (request.enhancers.octave) {
1123
+ e.octave = {
1124
+ enabled: request.enhancers.octave.enabled,
1125
+ mode: request.enhancers.octave.mode,
1126
+ copy_agent_id: request.enhancers.octave.copyAgentId,
1127
+ qualification_agent_id: request.enhancers.octave.qualificationAgentId,
1128
+ api_key_env: request.enhancers.octave.apiKeyEnv
1129
+ };
1130
+ }
1131
+ args.enhancers = e;
1132
+ }
1133
+ return args;
1134
+ }
1135
+
1136
+ // src/resources/campaign-builder-agent.ts
1137
+ var DEFAULT_SIGNALIZ_CAMPAIGN_BUILDER_DEFAULTS = {
1138
+ requireVerifiedEmail: true,
1139
+ dedupKeys: ["email", "linkedin_url", "company_domain"],
1140
+ allowDownscale: true,
1141
+ signals: {
1142
+ enabled: true,
1143
+ types: ["funding", "hiring", "technology", "news"],
1144
+ confidenceThreshold: 0.7,
1145
+ lookbackDays: 90
1146
+ },
1147
+ qualification: {
1148
+ enabled: true
1149
+ },
1150
+ copy: {
1151
+ enabled: true,
1152
+ tone: "direct",
1153
+ maxBodyWords: 125
1154
+ },
1155
+ delivery: {
1156
+ enabled: true,
1157
+ destinationType: "json",
1158
+ approvalRequired: true
1159
+ }
1160
+ };
1161
+ var CampaignBuilderAgent = class {
1162
+ constructor(client) {
1163
+ this.client = client;
1164
+ }
1165
+ async createPlan(request, options = {}) {
1166
+ const warnings = [];
1167
+ const workspaceContext = request.workspaceContext ?? await this.getWorkspaceContext(warnings);
1168
+ const scopeResult = options.scopeCampaign === false ? void 0 : await this.scopeCampaign(request, warnings);
1169
+ if (options.discoverCapabilities !== false) {
1170
+ await this.discoverPlannedRoutes(request, warnings);
1171
+ }
1172
+ return createCampaignBuilderAgentPlan(request, {
1173
+ workspaceContext,
1174
+ scopeBuildArgs: asRecord(scopeResult?.build_campaign_args ?? scopeResult?.buildCampaignArgs),
1175
+ warnings
1176
+ });
1177
+ }
1178
+ async dryRunPlan(plan, options) {
1179
+ let args = buildCampaignArgs({
1180
+ ...plan.buildRequest,
1181
+ dryRun: true,
1182
+ confirmSpend: false
1183
+ });
1184
+ if (plan.buildRequest.gtmCampaignId) {
1185
+ const prepare = await this.callMcp(
1186
+ "gtm_campaign_build_execution_prepare",
1187
+ buildExecutionPrepareArgs(plan.buildRequest, true, false)
1188
+ );
1189
+ const blockers = arrayOfStrings(prepare?.blockers) ?? [];
1190
+ if (prepare?.ready_to_launch === false || blockers.length > 0) {
1191
+ throw new Error(`Campaign builder dry-run prepare is blocked: ${blockers.join(", ") || "not ready to dry run"}`);
1192
+ }
1193
+ const preparedArgs = asRecord(prepare?.build_campaign_arguments ?? prepare?.buildCampaignArguments);
1194
+ if (Object.keys(preparedArgs).length > 0) {
1195
+ args = {
1196
+ ...preparedArgs,
1197
+ dry_run: true,
1198
+ confirm_spend: false
1199
+ };
1200
+ }
1201
+ }
1202
+ if (options?.idempotencyKey) args.idempotency_key = options.idempotencyKey;
1203
+ const data = await this.callMcp("build_campaign", args);
1204
+ return mapBuildResult(data, true);
1205
+ }
1206
+ async buildApprovedPlan(plan, approval, options) {
1207
+ const missing = getMissingCampaignBuilderApprovals(plan, approval);
1208
+ if (missing.length > 0) {
1209
+ throw new Error(`Campaign builder approval is incomplete: ${missing.map((a) => a.label).join(", ")}`);
1210
+ }
1211
+ let args = buildCampaignArgs({
1212
+ ...plan.buildRequest,
1213
+ dryRun: false,
1214
+ confirmSpend: true
1215
+ });
1216
+ if (plan.buildRequest.gtmCampaignId) {
1217
+ const prepare = await this.callMcp(
1218
+ "gtm_campaign_build_execution_prepare",
1219
+ buildExecutionPrepareArgs(plan.buildRequest, false, true)
1220
+ );
1221
+ const blockers = arrayOfStrings(prepare?.blockers) ?? [];
1222
+ if (prepare?.ready_to_launch === false || blockers.length > 0) {
1223
+ throw new Error(`Campaign builder execution prepare is blocked: ${blockers.join(", ") || "not ready to launch"}`);
1224
+ }
1225
+ const preparedArgs = asRecord(prepare?.build_campaign_arguments ?? prepare?.buildCampaignArguments);
1226
+ if (Object.keys(preparedArgs).length > 0) {
1227
+ args = {
1228
+ ...preparedArgs,
1229
+ dry_run: false,
1230
+ confirm_spend: true
1231
+ };
1232
+ }
1233
+ }
1234
+ args.required_approvals = plan.approvals.map((item) => item.id);
1235
+ if (options?.idempotencyKey) args.idempotency_key = options.idempotencyKey;
1236
+ const data = await this.callMcp("build_campaign", args);
1237
+ return mapBuildResult(data, false);
1238
+ }
1239
+ async getWorkspaceContext(warnings) {
1240
+ try {
1241
+ const workspace = await this.callMcp("get_workspace", {});
1242
+ return {
1243
+ workspaceId: stringValue(workspace.workspace_id ?? workspace.id),
1244
+ workspaceName: stringValue(workspace.workspace_name ?? workspace.name),
1245
+ plan: stringValue(workspace.plan ?? workspace.plan_name),
1246
+ creditsRemaining: numberOrUndefined2(workspace.credits_remaining ?? workspace.credit_balance ?? workspace.credits)
1247
+ };
1248
+ } catch (error) {
1249
+ warnings.push(`Workspace context lookup failed: ${errorMessage(error)}`);
1250
+ return {};
1251
+ }
1252
+ }
1253
+ async scopeCampaign(request, warnings) {
1254
+ try {
1255
+ return await this.callMcp("scope_campaign", {
1256
+ prompt: request.goal,
1257
+ client_name: request.clientName,
1258
+ client_context: request.clientContext,
1259
+ campaign_goal: request.goal,
1260
+ target_count: request.targetCount,
1261
+ approval_policy: request.approvalPolicy?.requireHumanApproval ? "human_required" : "standard"
1262
+ });
1263
+ } catch (error) {
1264
+ warnings.push(`Campaign scope lookup failed: ${errorMessage(error)}`);
1265
+ return void 0;
1266
+ }
1267
+ }
1268
+ async discoverPlannedRoutes(request, warnings) {
1269
+ const providers = new Set(
1270
+ [...request.integrations ?? [], ...routesFromCustomerTools(request.customerTools ?? [])].filter((route) => route.provider !== "signaliz").map((route) => route.provider)
1271
+ );
1272
+ for (const provider of providers) {
1273
+ try {
1274
+ await this.callMcp("discover_capabilities", {
1275
+ query: `campaign builder ${provider} ${request.goal}`,
1276
+ category: "campaign"
1277
+ });
1278
+ } catch (error) {
1279
+ warnings.push(`Capability discovery for ${provider} failed: ${errorMessage(error)}`);
1280
+ }
1281
+ }
1282
+ }
1283
+ async callMcp(tool, args) {
1284
+ return this.client.mcp("tools/call", { name: tool, arguments: compact(args) });
1285
+ }
1286
+ };
1287
+ function createCampaignBuilderAgentPlan(request, context = {}) {
1288
+ const defaults = mergeDefaults(request.signalizDefaults);
1289
+ const targetCount = request.targetCount ?? numberOrUndefined2(context.scopeBuildArgs?.target_count) ?? 100;
1290
+ const campaignName = request.campaignName ?? stringValue(context.scopeBuildArgs?.name) ?? titleFromGoal(request.goal);
1291
+ const workspaceContext = context.workspaceContext ?? request.workspaceContext ?? {};
1292
+ const memory = normalizeMemory(request);
1293
+ const routes = normalizeRoutes(request);
1294
+ const estimatedCredits = estimateCredits(request, defaults, targetCount);
1295
+ const buildRequest = createBuildRequest(request, defaults, targetCount, campaignName, context.scopeBuildArgs, routes, memory, context.scopeBrainPreflight);
1296
+ const brainPreflight = asRecord(buildRequest.brainPreflight);
1297
+ const approvals = deriveApprovals(request, routes, memory, estimatedCredits, defaults.delivery?.approvalRequired !== false);
1298
+ return {
1299
+ planId: `cbp_${hashString(JSON.stringify({ goal: request.goal, campaignName, targetCount, routes }))}`,
1300
+ campaignName,
1301
+ goal: request.goal,
1302
+ targetCount,
1303
+ workspaceContext,
1304
+ memory,
1305
+ defaults: {
1306
+ requireVerifiedEmail: defaults.requireVerifiedEmail,
1307
+ dedupKeys: defaults.dedupKeys,
1308
+ allowDownscale: defaults.allowDownscale
1309
+ },
1310
+ routes,
1311
+ approvals,
1312
+ buildRequest,
1313
+ brainPreflight,
1314
+ mcpFlow: createMcpFlow(request, buildRequest, routes, memory, approvals),
1315
+ estimatedCredits,
1316
+ warnings: context.warnings ?? []
1317
+ };
1318
+ }
1319
+ function getMissingCampaignBuilderApprovals(plan, approval) {
1320
+ if (approval.planId !== plan.planId) {
1321
+ return plan.approvals;
1322
+ }
1323
+ const approvedTypes = new Set(approval.approvedTypes);
1324
+ const approvedRoutes = new Set(approval.approvedRouteIds ?? []);
1325
+ return plan.approvals.filter((required) => {
1326
+ if (!required.blocking) return false;
1327
+ if (!approvedTypes.has(required.type)) return true;
1328
+ if (required.routeId && !approvedRoutes.has(required.routeId)) return true;
1329
+ if (required.type === "spend" && required.estimatedCredits && approval.spendLimitCredits !== void 0) {
1330
+ return approval.spendLimitCredits < required.estimatedCredits;
1331
+ }
1332
+ return false;
1333
+ });
1334
+ }
1335
+ function createCampaignBuilderApproval(plan, input) {
1336
+ return {
1337
+ ...input,
1338
+ planId: plan.planId,
1339
+ approvedAt: (/* @__PURE__ */ new Date()).toISOString()
1340
+ };
1341
+ }
1342
+ function mergeDefaults(overrides) {
1343
+ return {
1344
+ ...DEFAULT_SIGNALIZ_CAMPAIGN_BUILDER_DEFAULTS,
1345
+ ...overrides,
1346
+ signals: { ...DEFAULT_SIGNALIZ_CAMPAIGN_BUILDER_DEFAULTS.signals, ...overrides?.signals },
1347
+ qualification: { ...DEFAULT_SIGNALIZ_CAMPAIGN_BUILDER_DEFAULTS.qualification, ...overrides?.qualification },
1348
+ copy: { ...DEFAULT_SIGNALIZ_CAMPAIGN_BUILDER_DEFAULTS.copy, ...overrides?.copy },
1349
+ delivery: { ...DEFAULT_SIGNALIZ_CAMPAIGN_BUILDER_DEFAULTS.delivery, ...overrides?.delivery }
1350
+ };
1351
+ }
1352
+ function normalizeMemory(request) {
1353
+ const configured = request.memory ?? {};
1354
+ const queries = configured.queries && configured.queries.length > 0 ? configured.queries : [{
1355
+ query: request.goal,
1356
+ scopes: ["workspace", configured.useNetworkPatterns ? "network_patterns" : "operator_notes"],
1357
+ topK: 8,
1358
+ rationale: "Seed the campaign plan with prior ICP, angle, source, and reply-performance patterns."
1359
+ }];
1360
+ return {
1361
+ enabled: configured.enabled !== false,
1362
+ queries,
1363
+ useWorkspaceHistory: configured.useWorkspaceHistory !== false,
1364
+ useNetworkPatterns: configured.useNetworkPatterns === true,
1365
+ privacyMode: configured.privacyMode ?? (configured.useNetworkPatterns ? "anonymized_patterns" : "workspace_only")
1366
+ };
1367
+ }
1368
+ function normalizeRoutes(request) {
1369
+ const routes = [
1370
+ {
1371
+ id: "signaliz-source",
1372
+ layer: "source",
1373
+ provider: "signaliz",
1374
+ mode: "required",
1375
+ toolName: "generate_leads",
1376
+ rationale: "Use Signaliz fresh workspace acquisition as the default source of truth."
1377
+ },
1378
+ {
1379
+ id: "signaliz-verify",
1380
+ layer: "qualification",
1381
+ provider: "signaliz",
1382
+ mode: "required",
1383
+ toolName: "find_and_verify_emails",
1384
+ rationale: "Require verified contactability before sequence delivery."
1385
+ },
1386
+ {
1387
+ id: "signaliz-signals",
1388
+ layer: "enrichment",
1389
+ provider: "signaliz",
1390
+ mode: "if_available",
1391
+ toolName: "enrich_company_signals",
1392
+ rationale: "Attach current buying signals and evidence for qualification and copy."
1393
+ }
1394
+ ];
1395
+ routes.push(...routesFromCustomerTools(request.customerTools ?? []));
1396
+ routes.push(...request.integrations ?? []);
1397
+ return routes.map((route, index) => ({
1398
+ ...route,
1399
+ id: route.id ?? `${route.provider}-${route.layer}-${index + 1}`,
1400
+ mode: route.mode ?? "if_available"
1401
+ }));
1402
+ }
1403
+ function routesFromCustomerTools(tools) {
1404
+ return tools.flatMap(
1405
+ (tool) => tool.useForLayers.map((layer) => ({
1406
+ layer,
1407
+ provider: tool.provider,
1408
+ mode: tool.mode ?? "if_available",
1409
+ mcpServerName: tool.mcpServerName,
1410
+ label: tool.label,
1411
+ approvalRequired: tool.approvalRequired,
1412
+ gtmLayers: tool.gtmLayerCapabilities,
1413
+ routingPolicy: tool.routingPolicy,
1414
+ providerCapability: tool.providerCapability,
1415
+ config: {
1416
+ ...tool.config,
1417
+ available_tools: tool.availableTools
1418
+ },
1419
+ rationale: `${tool.label ?? tool.provider} is customer-provided for ${layer}.`
1420
+ }))
1421
+ );
1422
+ }
1423
+ function createBuildRequest(request, defaults, targetCount, campaignName, scopeBuildArgs, routes = [], memory, scopeBrainPreflight) {
1424
+ const buildRequest = {
1425
+ name: campaignName,
1426
+ prompt: request.goal,
1427
+ description: buildDescription(request),
1428
+ targetCount,
1429
+ dryRun: true,
1430
+ allowDownscale: defaults.allowDownscale,
1431
+ confirmSpend: false,
1432
+ dedupKeys: defaults.dedupKeys,
1433
+ icp: {
1434
+ ...request.icp,
1435
+ geographies: request.icp?.geographies ?? request.constraints?.geographies,
1436
+ exclusions: [...request.icp?.exclusions ?? [], ...request.constraints?.exclusions ?? []],
1437
+ requireVerifiedEmail: request.icp?.requireVerifiedEmail ?? defaults.requireVerifiedEmail
1438
+ },
1439
+ policy: {
1440
+ maxCredits: defaults.maxCredits,
1441
+ verifyEmails: defaults.requireVerifiedEmail
1442
+ },
1443
+ signals: defaults.signals,
1444
+ qualification: defaults.qualification,
1445
+ copy: defaults.copy,
1446
+ delivery: defaults.delivery,
1447
+ enhancers: enhancerConfig(request)
1448
+ };
1449
+ const scoped = asRecord(scopeBuildArgs);
1450
+ buildRequest.gtmCampaignId = request.gtmCampaignId ?? stringValue(scoped.gtm_campaign_id ?? scoped.gtmCampaignId);
1451
+ if (typeof scoped.name === "string") buildRequest.name = scoped.name;
1452
+ if (typeof scoped.prompt === "string") buildRequest.prompt = scoped.prompt;
1453
+ if (typeof scoped.target_count === "number") buildRequest.targetCount = scoped.target_count;
1454
+ const brainDefaults = asRecord(request.brainDefaults ?? scoped.brain_defaults ?? scoped.brainDefaults);
1455
+ if (Object.keys(brainDefaults).length > 0) buildRequest.brainDefaults = brainDefaults;
1456
+ const deliveryRisk = asRecord(request.deliveryRisk ?? scoped.delivery_risk ?? scoped.deliveryRisk);
1457
+ if (Object.keys(deliveryRisk).length > 0) buildRequest.deliveryRisk = deliveryRisk;
1458
+ const scopedBrainPreflight = asRecord(scoped.brain_preflight);
1459
+ const providedBrainPreflight = Object.keys(scopedBrainPreflight).length > 0 ? scopedBrainPreflight : asRecord(scopeBrainPreflight);
1460
+ buildRequest.brainPreflight = Object.keys(providedBrainPreflight).length > 0 ? providedBrainPreflight : createBrainPreflight(request, buildRequest, routes, memory ?? normalizeMemory(request));
1461
+ return buildRequest;
1462
+ }
1463
+ function createBrainPreflight(request, buildRequest, routes, memory) {
1464
+ const layers = uniqueStrings([
1465
+ "icp",
1466
+ "email_finding",
1467
+ "email_verification",
1468
+ ...routes.flatMap(gtmLayersForRoute),
1469
+ buildRequest.delivery?.destinationType === "webhook" ? "destination_export" : void 0,
1470
+ ["instantly", "smartlead", "heyreach"].some((provider) => routes.some((route) => route.provider === provider)) ? "sender" : void 0,
1471
+ memory.enabled ? "feedback" : void 0
1472
+ ]);
1473
+ const providerChain = uniqueStrings(["signaliz", ...routes.map((route) => route.provider)]);
1474
+ const targetIcp = compact({
1475
+ personas: buildRequest.icp?.personas,
1476
+ industries: buildRequest.icp?.industries,
1477
+ company_sizes: buildRequest.icp?.companySizes,
1478
+ geographies: buildRequest.icp?.geographies,
1479
+ keywords: buildRequest.icp?.keywords,
1480
+ exclusions: buildRequest.icp?.exclusions,
1481
+ require_verified_email: buildRequest.icp?.requireVerifiedEmail
1482
+ });
1483
+ const learningArgs = compact({
1484
+ campaign_brief: request.goal,
1485
+ target_icp: targetIcp,
1486
+ layers,
1487
+ provider_chain: providerChain,
1488
+ lead_source: providerChain[0] ?? "signaliz",
1489
+ include_memory: memory.enabled,
1490
+ include_network: memory.useNetworkPatterns,
1491
+ write_mode: "dry_run",
1492
+ limit: 25
1493
+ });
1494
+ const defaultsArgs = compact({
1495
+ campaign_brief: request.goal,
1496
+ target_icp: targetIcp,
1497
+ layers,
1498
+ include_global: memory.useNetworkPatterns,
1499
+ include_memory: memory.enabled,
1500
+ write_campaign: false,
1501
+ limit: 25
1502
+ });
1503
+ const riskArgs = compact({
1504
+ provider_chain: providerChain,
1505
+ lead_source: providerChain[0] ?? "signaliz",
1506
+ target_icp: targetIcp,
1507
+ include_global: memory.useNetworkPatterns,
1508
+ limit: 25
1509
+ });
1510
+ return {
1511
+ required: true,
1512
+ policy: "Run read-only GTM Brain preflight before build_campaign so learned defaults, memory, and deliverability risk stay attached to the build.",
1513
+ layers,
1514
+ target_icp: targetIcp,
1515
+ provider_chain: providerChain,
1516
+ lead_source: providerChain[0] ?? "signaliz",
1517
+ tool_sequence: [
1518
+ { tool: "gtm_brain_learning_cycle_plan", purpose: "Plan the Brain learning loop for this campaign.", arguments: learningArgs },
1519
+ { tool: "gtm_brain_seed_defaults", purpose: "Seed campaign defaults from workspace memory and safe aggregate patterns.", arguments: defaultsArgs },
1520
+ { tool: "gtm_brain_delivery_risk", purpose: "Check deliverability risk before launch or external writes.", arguments: riskArgs }
1521
+ ]
1522
+ };
1523
+ }
1524
+ function gtmLayersForBuilderLayer(layer) {
1525
+ const map = {
1526
+ workspace_context: ["customer_data"],
1527
+ memory: ["feedback"],
1528
+ source: ["find_company", "find_people", "lead_generation"],
1529
+ enrichment: ["company_enrichment"],
1530
+ qualification: ["qualification"],
1531
+ copy: ["copy_enrichment"],
1532
+ delivery: ["destination_export"],
1533
+ feedback: ["feedback"],
1534
+ approval: ["approval"]
1535
+ };
1536
+ return map[layer] ?? ["custom"];
1537
+ }
1538
+ function gtmLayersForRoute(route) {
1539
+ const explicitLayers = uniqueStrings([
1540
+ route.gtmLayer,
1541
+ ...route.gtmLayers ?? [],
1542
+ ...route.providerCapability?.layerCapabilities ?? []
1543
+ ]);
1544
+ return explicitLayers.length > 0 ? explicitLayers : gtmLayersForBuilderLayer(route.layer);
1545
+ }
1546
+ function enhancerConfig(request) {
1547
+ const routes = [...request.integrations ?? [], ...routesFromCustomerTools(request.customerTools ?? [])];
1548
+ const octave = routes.find((route) => route.provider === "octave");
1549
+ const clay = routes.find((route) => route.provider === "clay_webhook");
1550
+ if (!octave && !clay) return void 0;
1551
+ return {
1552
+ octave: octave ? {
1553
+ enabled: octave.mode !== "disabled",
1554
+ mode: octave.mode === "required" ? "required" : "if_available",
1555
+ copyAgentId: stringValue(octave.config?.copy_agent_id ?? octave.config?.copyAgentId),
1556
+ qualificationAgentId: stringValue(octave.config?.qualification_agent_id ?? octave.config?.qualificationAgentId)
1557
+ } : void 0,
1558
+ clay: clay ? {
1559
+ enabled: clay.mode !== "disabled",
1560
+ mode: clay.mode === "required" ? "required" : "if_available",
1561
+ tableId: stringValue(clay.config?.table_id ?? clay.config?.tableId),
1562
+ enrichmentFields: arrayOfStrings(clay.config?.enrichment_fields ?? clay.config?.enrichmentFields)
1563
+ } : void 0
1564
+ };
1565
+ }
1566
+ function deriveApprovals(request, routes, memory, estimatedCredits, deliveryApprovalRequired) {
1567
+ const policy = request.approvalPolicy ?? {};
1568
+ const requireFor = new Set(policy.requireApprovalFor ?? ["spend", "external_write", "customer_tool", "delivery", "launch"]);
1569
+ const approvals = [];
1570
+ if (memory.enabled && memory.useNetworkPatterns && requireFor.has("memory_retrieval")) {
1571
+ approvals.push({
1572
+ id: "approval-memory-network",
1573
+ type: "memory_retrieval",
1574
+ label: "Use anonymized network memory",
1575
+ reason: "The plan will consult cross-workspace patterns instead of only private workspace history.",
1576
+ blocking: true
1577
+ });
1578
+ }
1579
+ if (estimatedCredits > (policy.maxCreditsWithoutApproval ?? 0) && requireFor.has("spend")) {
1580
+ approvals.push({
1581
+ id: "approval-spend",
1582
+ type: "spend",
1583
+ label: "Approve campaign spend",
1584
+ reason: `Estimated campaign work may use up to ${estimatedCredits} credits.`,
1585
+ blocking: true,
1586
+ estimatedCredits
1587
+ });
1588
+ }
1589
+ for (const route of routes) {
1590
+ const isCustomerTool = route.provider !== "signaliz";
1591
+ const isWriteLayer = route.layer === "delivery" || route.layer === "feedback";
1592
+ if (isCustomerTool && route.approvalRequired !== false && requireFor.has("customer_tool")) {
1593
+ approvals.push({
1594
+ id: `approval-tool-${route.id}`,
1595
+ type: "customer_tool",
1596
+ label: `Use ${route.label ?? route.provider}`,
1597
+ reason: route.rationale ?? `${route.provider} is part of the campaign plan.`,
1598
+ blocking: route.mode === "required" || policy.requireHumanApproval === true,
1599
+ routeId: route.id,
1600
+ provider: route.provider
1601
+ });
1602
+ }
1603
+ if (isWriteLayer && route.provider !== "csv" && requireFor.has("external_write")) {
1604
+ approvals.push({
1605
+ id: `approval-write-${route.id}`,
1606
+ type: "external_write",
1607
+ label: `Approve ${route.provider} write`,
1608
+ reason: "External delivery, sync, sequencer, or feedback writes must be explicitly approved.",
1609
+ blocking: true,
1610
+ routeId: route.id,
1611
+ provider: route.provider
1612
+ });
1613
+ }
1614
+ }
1615
+ if (deliveryApprovalRequired && requireFor.has("delivery")) {
1616
+ approvals.push({
1617
+ id: "approval-delivery",
1618
+ type: "delivery",
1619
+ label: "Approve delivery destination",
1620
+ reason: "Delivery remains gated until the destination, field map, suppression rules, and send limits are reviewed.",
1621
+ blocking: true
1622
+ });
1623
+ }
1624
+ if (requireFor.has("launch")) {
1625
+ approvals.push({
1626
+ id: "approval-launch",
1627
+ type: "launch",
1628
+ label: "Launch campaign build",
1629
+ reason: "The dry-run plan must be accepted before spendful build execution.",
1630
+ blocking: true
1631
+ });
1632
+ }
1633
+ return dedupeApprovals(approvals);
1634
+ }
1635
+ function createMcpFlow(request, buildRequest, routes, memory, approvals) {
1636
+ const steps = [
1637
+ {
1638
+ id: "workspace-context",
1639
+ phase: "workspace_context",
1640
+ tool: "get_workspace",
1641
+ arguments: {},
1642
+ readOnly: true,
1643
+ approvalRequired: false
1644
+ }
1645
+ ];
1646
+ if (memory.enabled) {
1647
+ for (const [index, query] of memory.queries.entries()) {
1648
+ steps.push({
1649
+ id: `memory-${index + 1}`,
1650
+ phase: "memory",
1651
+ tool: "gtm_memory_search",
1652
+ arguments: buildGtmMemorySearchArgs(request, routes, query),
1653
+ readOnly: true,
1654
+ approvalRequired: memory.useNetworkPatterns
1655
+ });
1656
+ }
1657
+ }
1658
+ for (const route of routes) {
1659
+ steps.push({
1660
+ id: `route-${route.id}`,
1661
+ phase: route.layer,
1662
+ tool: route.toolName ?? "discover_capabilities",
1663
+ arguments: {
1664
+ provider: route.provider,
1665
+ mcp_server_name: route.mcpServerName,
1666
+ mode: route.mode,
1667
+ config: route.config
1668
+ },
1669
+ readOnly: !["delivery", "feedback"].includes(route.layer),
1670
+ approvalRequired: route.approvalRequired === true || route.layer === "delivery" || route.layer === "feedback"
1671
+ });
1672
+ }
1673
+ steps.push({
1674
+ id: "scope-campaign",
1675
+ phase: "plan",
1676
+ tool: "scope_campaign",
1677
+ arguments: {
1678
+ prompt: request.goal,
1679
+ client_name: request.clientName,
1680
+ client_context: request.clientContext,
1681
+ target_count: request.targetCount
1682
+ },
1683
+ readOnly: true,
1684
+ approvalRequired: false
1685
+ });
1686
+ const brainPreflight = asRecord(buildRequest.brainPreflight);
1687
+ const brainToolSequence = Array.isArray(brainPreflight.tool_sequence) ? brainPreflight.tool_sequence.map((step) => asRecord(step)).filter((step) => typeof step.tool === "string") : [];
1688
+ for (const [index, brainStep] of brainToolSequence.entries()) {
1689
+ steps.push({
1690
+ id: `brain-preflight-${index + 1}`,
1691
+ phase: "plan",
1692
+ tool: String(brainStep.tool),
1693
+ arguments: asRecord(brainStep.arguments),
1694
+ readOnly: true,
1695
+ approvalRequired: memory.useNetworkPatterns === true
1696
+ });
1697
+ }
1698
+ if (buildRequest.gtmCampaignId) {
1699
+ steps.push({
1700
+ id: "dry-run-prepare",
1701
+ phase: "plan",
1702
+ tool: "gtm_campaign_build_execution_prepare",
1703
+ arguments: buildExecutionPrepareArgs(buildRequest, true, false),
1704
+ readOnly: true,
1705
+ approvalRequired: false
1706
+ });
1707
+ }
1708
+ steps.push({
1709
+ id: "dry-run-build",
1710
+ phase: "plan",
1711
+ tool: "build_campaign",
1712
+ arguments: {
1713
+ ...buildCampaignArgs({ ...buildRequest, dryRun: true, confirmSpend: false }),
1714
+ dry_run: true
1715
+ },
1716
+ readOnly: true,
1717
+ approvalRequired: false
1718
+ });
1719
+ if (buildRequest.gtmCampaignId) {
1720
+ steps.push({
1721
+ id: "execution-prepare",
1722
+ phase: "launch",
1723
+ tool: "gtm_campaign_build_execution_prepare",
1724
+ arguments: buildExecutionPrepareArgs(buildRequest, false, true),
1725
+ readOnly: true,
1726
+ approvalRequired: approvals.some((approval) => approval.blocking)
1727
+ });
1728
+ }
1729
+ steps.push({
1730
+ id: "approved-build",
1731
+ phase: "launch",
1732
+ tool: "build_campaign",
1733
+ arguments: {
1734
+ ...buildCampaignArgs({ ...buildRequest, dryRun: false, confirmSpend: true }),
1735
+ required_approvals: approvals.map((approval) => approval.id)
1736
+ },
1737
+ readOnly: false,
1738
+ approvalRequired: approvals.some((approval) => approval.blocking)
1739
+ });
1740
+ return steps.map((step) => ({ ...step, arguments: compact(step.arguments) }));
1741
+ }
1742
+ function buildGtmMemorySearchArgs(request, routes, query) {
1743
+ const layers = uniqueStrings(routes.flatMap(gtmLayersForRoute));
1744
+ const providerChain = uniqueStrings(routes.map((route) => route.provider));
1745
+ return compact({
1746
+ query: query.query,
1747
+ limit: query.topK,
1748
+ target_icp: request.icp ? buildGtmTargetIcpContext(request.icp) : void 0,
1749
+ layers: layers.length > 0 ? layers : void 0,
1750
+ provider_chain: providerChain.length > 0 ? providerChain : void 0,
1751
+ days: 180
1752
+ });
1753
+ }
1754
+ function buildGtmTargetIcpContext(icp) {
1755
+ return compact({
1756
+ roles: icp.personas,
1757
+ personas: icp.personas,
1758
+ industries: icp.industries,
1759
+ company_sizes: icp.companySizes,
1760
+ geographies: icp.geographies,
1761
+ keywords: icp.keywords,
1762
+ exclusions: icp.exclusions,
1763
+ require_verified_email: icp.requireVerifiedEmail
1764
+ });
1765
+ }
1766
+ function buildCampaignArgs(request) {
1767
+ const args = {
1768
+ name: request.name,
1769
+ prompt: request.prompt
1770
+ };
1771
+ if (request.description) args.description = request.description;
1772
+ if (request.targetCount) args.target_count = request.targetCount;
1773
+ if (request.dryRun !== void 0) args.dry_run = request.dryRun;
1774
+ if (request.allowDownscale !== void 0) args.allow_downscale = request.allowDownscale;
1775
+ if (request.confirmSpend !== void 0) args.confirm_spend = request.confirmSpend;
1776
+ if (request.dedupKeys) args.dedup_keys = request.dedupKeys;
1777
+ if (request.brainPreflight) args.brain_preflight = request.brainPreflight;
1778
+ if (request.brainDefaults) args.brain_defaults = request.brainDefaults;
1779
+ if (request.deliveryRisk) args.delivery_risk = request.deliveryRisk;
1780
+ if (request.icp) {
1781
+ args.icp = compact({
1782
+ personas: request.icp.personas,
1783
+ industries: request.icp.industries,
1784
+ company_sizes: request.icp.companySizes,
1785
+ geographies: request.icp.geographies,
1786
+ keywords: request.icp.keywords,
1787
+ exclusions: request.icp.exclusions,
1788
+ require_verified_email: request.icp.requireVerifiedEmail
1789
+ });
1790
+ }
1791
+ if (request.policy) {
1792
+ args.policy = compact({
1793
+ max_credits: request.policy.maxCredits,
1794
+ verify_emails: request.policy.verifyEmails,
1795
+ model: request.policy.model
1796
+ });
1797
+ }
1798
+ if (request.signals) {
1799
+ args.signals = compact({
1800
+ enabled: request.signals.enabled,
1801
+ types: request.signals.types,
1802
+ custom_prompt: request.signals.customPrompt,
1803
+ confidence_threshold: request.signals.confidenceThreshold,
1804
+ lookback_days: request.signals.lookbackDays
1805
+ });
1806
+ }
1807
+ if (request.qualification) {
1808
+ args.qualification = compact({
1809
+ enabled: request.qualification.enabled,
1810
+ model: request.qualification.model
1811
+ });
1812
+ }
1813
+ if (request.copy) {
1814
+ args.copy = compact({
1815
+ enabled: request.copy.enabled,
1816
+ tone: request.copy.tone,
1817
+ max_body_words: request.copy.maxBodyWords,
1818
+ sender_context: request.copy.senderContext,
1819
+ offer_context: request.copy.offerContext,
1820
+ model: request.copy.model
1821
+ });
1822
+ }
1823
+ if (request.delivery) {
1824
+ args.delivery = compact({
1825
+ enabled: request.delivery.enabled,
1826
+ destination_type: request.delivery.destinationType,
1827
+ approval_required: request.delivery.approvalRequired,
1828
+ include_disqualified: request.delivery.includeDisqualified,
1829
+ destination_config: request.delivery.destinationConfig
1830
+ });
1831
+ }
1832
+ if (request.enhancers) {
1833
+ args.enhancers = compact({
1834
+ clay: request.enhancers.clay && compact({
1835
+ enabled: request.enhancers.clay.enabled,
1836
+ mode: request.enhancers.clay.mode,
1837
+ table_id: request.enhancers.clay.tableId,
1838
+ enrichment_fields: request.enhancers.clay.enrichmentFields,
1839
+ api_key_env: request.enhancers.clay.apiKeyEnv
1840
+ }),
1841
+ octave: request.enhancers.octave && compact({
1842
+ enabled: request.enhancers.octave.enabled,
1843
+ mode: request.enhancers.octave.mode,
1844
+ copy_agent_id: request.enhancers.octave.copyAgentId,
1845
+ qualification_agent_id: request.enhancers.octave.qualificationAgentId,
1846
+ api_key_env: request.enhancers.octave.apiKeyEnv
1847
+ })
1848
+ });
1849
+ }
1850
+ return compact(args);
1851
+ }
1852
+ function buildExecutionPrepareArgs(request, dryRun, confirmSpend) {
1853
+ const buildArgs2 = buildCampaignArgs(request);
1854
+ return compact({
1855
+ campaign_id: request.gtmCampaignId,
1856
+ target_count: buildArgs2.target_count,
1857
+ allow_downscale: buildArgs2.allow_downscale,
1858
+ dry_run: dryRun,
1859
+ confirm_spend: confirmSpend,
1860
+ include_brain_context: true,
1861
+ require_delivery_risk_clearance: true,
1862
+ delivery_risk: buildArgs2.delivery_risk,
1863
+ dedup_keys: buildArgs2.dedup_keys,
1864
+ policy: buildArgs2.policy,
1865
+ signals: buildArgs2.signals,
1866
+ qualification: buildArgs2.qualification,
1867
+ copy: buildArgs2.copy,
1868
+ delivery: buildArgs2.delivery,
1869
+ enhancers: buildArgs2.enhancers
1870
+ });
1871
+ }
1872
+ function mapBuildResult(data, dryRun) {
1873
+ return {
1874
+ campaignBuildId: data.campaign_build_id ?? null,
1875
+ campaignId: data.campaign_id ?? null,
1876
+ campaignObject: data.campaign_object ?? null,
1877
+ status: dryRun || data.dry_run ? "dry_run" : data.status ?? "queued",
1878
+ currentPhase: dryRun || data.dry_run ? "plan" : data.current_phase ?? "acquisition",
1879
+ nextPollAfterSeconds: data.next_poll_after_seconds ?? 10,
1880
+ message: data.message ?? data.summary ?? "",
1881
+ dryRun: dryRun || data.dry_run === true,
1882
+ requestedTargetCount: data.requested_target_count,
1883
+ plannedTargetCount: data.planned_target_count,
1884
+ estimatedCredits: data.estimated_credits,
1885
+ estimatedDurationSeconds: data.estimated_duration_seconds,
1886
+ targetLimitApplied: data.target_limit_applied,
1887
+ targetLimitReason: data.target_limit_reason,
1888
+ maxSupportedTargetCount: data.max_supported_target_count,
1889
+ brainContext: data.brain_context ?? {},
1890
+ providerRoute: mapProviderRoute2(data)
1891
+ };
1892
+ }
1893
+ function mapProviderRoute2(data) {
1894
+ const brainContext = asRecord(data?.brain_context);
1895
+ const plan = nullableRecord(data?.provider_route_plan) ?? nullableRecord(brainContext.provider_route_plan);
1896
+ const summary = nullableRecord(data?.provider_route_summary) ?? nullableRecord(brainContext.provider_route_summary) ?? nullableRecord(plan?.summary);
1897
+ const blockers = arrayOfStrings(data?.provider_route_blockers ?? brainContext.provider_route_blockers ?? plan?.blockers) ?? [];
1898
+ const warnings = arrayOfStrings(data?.provider_route_warnings ?? brainContext.provider_route_warnings ?? plan?.warnings) ?? [];
1899
+ const ready = typeof data?.provider_route_ready === "boolean" ? data.provider_route_ready : typeof brainContext.provider_route_ready === "boolean" ? brainContext.provider_route_ready : typeof plan?.ready === "boolean" ? plan.ready : null;
1900
+ const label = typeof data?.provider_route_label === "string" ? data.provider_route_label : typeof brainContext.provider_route_label === "string" ? brainContext.provider_route_label : providerRouteLabel2(summary, ready);
1901
+ if (!plan && !summary && ready === null && blockers.length === 0 && warnings.length === 0 && !label) {
1902
+ return null;
1903
+ }
1904
+ return {
1905
+ plan,
1906
+ summary,
1907
+ ready,
1908
+ label: label || "attached",
1909
+ blockers,
1910
+ warnings
1911
+ };
1912
+ }
1913
+ function nullableRecord(value) {
1914
+ const record = asRecord(value);
1915
+ return Object.keys(record).length > 0 ? record : null;
1916
+ }
1917
+ function providerRouteLabel2(summary, ready) {
1918
+ if (!summary) return ready === true ? "ready" : ready === false ? "blocked" : "";
1919
+ const totalLayers = numberOrNull2(summary.total_layers);
1920
+ const readyLayers = numberOrNull2(summary.ready_layers);
1921
+ const customProviderLayers = numberOrNull2(summary.custom_provider_layers);
1922
+ const signalizDefaultLayers = numberOrNull2(summary.signaliz_default_layers);
1923
+ const fallbackLayers = numberOrNull2(summary.fallback_layers);
1924
+ const blockedLayers = numberOrNull2(summary.blocked_layers);
1925
+ return [
1926
+ totalLayers === null || readyLayers === null ? ready === true ? "ready" : ready === false ? "blocked" : null : `${readyLayers}/${totalLayers} layers ready`,
1927
+ customProviderLayers !== null ? `${customProviderLayers} custom` : null,
1928
+ signalizDefaultLayers !== null ? `${signalizDefaultLayers} Signaliz default` : null,
1929
+ fallbackLayers !== null ? `${fallbackLayers} fallback` : null,
1930
+ blockedLayers !== null ? `${blockedLayers} blocked` : null
1931
+ ].filter(Boolean).join(", ");
1932
+ }
1933
+ function numberOrNull2(value) {
1934
+ const parsed = Number(value);
1935
+ return Number.isFinite(parsed) ? parsed : null;
1936
+ }
1937
+ function estimateCredits(request, defaults, targetCount) {
1938
+ if (typeof defaults.maxCredits === "number") return defaults.maxCredits;
1939
+ const signalCredits = defaults.signals?.enabled === false ? 0 : targetCount * 2;
1940
+ const copyCredits = defaults.copy?.enabled === false ? 0 : targetCount;
1941
+ const requiredCustomerToolPremium = [...request.integrations ?? [], ...routesFromCustomerTools(request.customerTools ?? [])].filter((route) => route.mode === "required" && ["octave", "ai_ark", "clay_webhook"].includes(route.provider)).length * Math.ceil(targetCount / 25);
1942
+ return signalCredits + copyCredits + requiredCustomerToolPremium;
1943
+ }
1944
+ function buildDescription(request) {
1945
+ const parts = [
1946
+ request.clientName ? `Client: ${request.clientName}` : void 0,
1947
+ request.clientContext ? `Context: ${request.clientContext}` : void 0,
1948
+ request.constraints?.deliverabilityNotes?.length ? `Deliverability: ${request.constraints.deliverabilityNotes.join("; ")}` : void 0,
1949
+ "Agent-built campaign plan layered on Signaliz kernel and existing MCP tools."
1950
+ ];
1951
+ return parts.filter(Boolean).join("\n");
1952
+ }
1953
+ function dedupeApprovals(approvals) {
1954
+ const seen = /* @__PURE__ */ new Set();
1955
+ return approvals.filter((approval) => {
1956
+ const key = `${approval.type}:${approval.routeId ?? approval.provider ?? approval.id}`;
1957
+ if (seen.has(key)) return false;
1958
+ seen.add(key);
1959
+ return true;
1960
+ });
1961
+ }
1962
+ function compact(record) {
1963
+ return Object.fromEntries(
1964
+ Object.entries(record).filter(([, value]) => value !== void 0 && value !== null && value !== "")
1965
+ );
1966
+ }
1967
+ function asRecord(value) {
1968
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
1969
+ }
1970
+ function stringValue(value) {
1971
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1972
+ }
1973
+ function numberOrUndefined2(value) {
1974
+ const parsed = Number(value);
1975
+ return Number.isFinite(parsed) ? parsed : void 0;
1976
+ }
1977
+ function arrayOfStrings(value) {
1978
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : void 0;
1979
+ }
1980
+ function uniqueStrings(values) {
1981
+ const seen = /* @__PURE__ */ new Set();
1982
+ const out = [];
1983
+ for (const value of values) {
1984
+ if (!value) continue;
1985
+ const key = value.trim();
1986
+ if (!key || seen.has(key)) continue;
1987
+ seen.add(key);
1988
+ out.push(key);
1989
+ }
1990
+ return out;
1991
+ }
1992
+ function titleFromGoal(goal) {
1993
+ const words = goal.replace(/[^a-zA-Z0-9 ]/g, " ").trim().split(/\s+/).slice(0, 7);
1994
+ return words.length > 0 ? words.map((word) => word[0]?.toUpperCase() + word.slice(1)).join(" ") : "Agent Built Campaign";
1995
+ }
1996
+ function hashString(input) {
1997
+ let hash = 0;
1998
+ for (let i = 0; i < input.length; i++) {
1999
+ hash = (hash << 5) - hash + input.charCodeAt(i) | 0;
2000
+ }
2001
+ return Math.abs(hash).toString(36);
2002
+ }
2003
+ function errorMessage(error) {
2004
+ return error instanceof Error ? error.message : String(error);
2005
+ }
2006
+
2007
+ // src/resources/icps.ts
2008
+ var Icps = class {
2009
+ constructor(client) {
2010
+ this.client = client;
2011
+ }
2012
+ /** List all ICPs in the workspace */
2013
+ async list(opts) {
2014
+ const data = await this.client.mcp("tools/call", {
2015
+ name: "list_icps",
2016
+ arguments: {
2017
+ include_source_playbook_data: opts?.includeSourcePlaybookData ?? opts?.includeOctaveData ?? false
2018
+ }
2019
+ });
2020
+ return data.icps ?? [];
2021
+ }
2022
+ /** Get full ICP details by ID */
2023
+ async get(icpId) {
2024
+ return this.client.mcp("tools/call", {
2025
+ name: "get_icp",
2026
+ arguments: { icp_id: icpId }
2027
+ });
2028
+ }
2029
+ /** Import connected source playbooks as ICPs */
2030
+ async importFromPlaybooks(playbookIds) {
2031
+ return this.client.mcp("tools/call", {
2032
+ name: "import_icps_from_playbooks",
2033
+ arguments: playbookIds?.length ? { playbook_ids: playbookIds } : {}
2034
+ });
2035
+ }
2036
+ /** @deprecated Use importFromPlaybooks. */
2037
+ async importFromOctave(playbookIds) {
2038
+ return this.importFromPlaybooks(playbookIds);
2039
+ }
2040
+ };
2041
+
2042
+ // src/resources/leads.ts
2043
+ var Leads = class {
2044
+ constructor(client) {
2045
+ this.client = client;
2046
+ }
2047
+ /**
2048
+ * Generate B2B leads from a natural-language prompt.
2049
+ * Returns a job_id — poll with `runs.get(jobId)` or `check_job_status`.
2050
+ */
2051
+ async generate(params) {
2052
+ const data = await this.client.mcp("tools/call", {
2053
+ name: "generate_leads",
2054
+ arguments: {
2055
+ prompt: params.prompt,
2056
+ max_leads: params.maxLeads,
2057
+ verify_emails: params.verifyEmails,
2058
+ file_name: params.fileName,
2059
+ model: params.model,
2060
+ company_domains: params.companyDomains,
2061
+ completeness_mode: params.completenessMode,
2062
+ lookalike_expansion: params.lookalikeExpansion,
2063
+ confirm_spend: params.confirmSpend
2064
+ }
2065
+ });
2066
+ return mapJobResult(data);
2067
+ }
2068
+ /**
2069
+ * Generate local business leads via Google Maps + email scraping.
2070
+ * Returns a job_id — poll with `runs.get(jobId)` or `check_job_status`.
2071
+ */
2072
+ async generateLocal(params) {
2073
+ const data = await this.client.mcp("tools/call", {
2074
+ name: "generate_local_leads",
2075
+ arguments: {
2076
+ prompt: params.prompt,
2077
+ target_verified: params.targetVerified ?? params.maxLeads,
2078
+ verify_emails: params.verifyEmails,
2079
+ file_name: params.fileName,
2080
+ confirm_spend: params.confirmSpend
2081
+ }
2082
+ });
2083
+ return mapJobResult(data);
2084
+ }
2085
+ /**
2086
+ * List curated native GTM data sources with data-cost guardrails.
2087
+ */
2088
+ async listNativeGtmCapabilities(category) {
2089
+ const data = await this.client.mcp("tools/call", {
2090
+ name: "list_native_gtm_capabilities",
2091
+ arguments: category ? { category } : {}
2092
+ });
2093
+ return data.capabilities ?? [];
2094
+ }
2095
+ /**
2096
+ * Run a curated native GTM capability. Returns a job_id; poll with `runs.get(jobId)`
2097
+ * or `checkStatus(jobId)`.
2098
+ */
2099
+ async runNativeGtmCapability(params) {
2100
+ const data = await this.client.mcp("tools/call", {
2101
+ name: "run_native_gtm_capability",
2102
+ arguments: {
2103
+ capability: params.capability,
2104
+ query: params.query,
2105
+ urls: params.urls,
2106
+ place_ids: params.placeIds,
2107
+ max_results: params.maxResults,
2108
+ mode: params.mode,
2109
+ since: params.since,
2110
+ location: params.location,
2111
+ country_code: params.countryCode,
2112
+ confirm_spend: params.confirmSpend
2113
+ }
2114
+ });
2115
+ return mapJobResult(data);
2116
+ }
2117
+ /**
2118
+ * Free-text router: pass an intent like "pull youtube subscribers of @joshwhitfieldai"
2119
+ * and get back the top GTM capability matches with suggested args ready to run.
2120
+ */
2121
+ async findGtmCapability(intent) {
2122
+ const data = await this.client.mcp("tools/call", {
2123
+ name: "find_gtm_capability",
2124
+ arguments: { intent }
2125
+ });
2126
+ return { matches: data.matches ?? [], intent: data.intent ?? intent };
2127
+ }
2128
+ /**
2129
+ * Check the status of a lead generation job.
2130
+ */
2131
+ async checkStatus(jobId) {
2132
+ return this.client.mcp("tools/call", {
2133
+ name: "check_job_status",
2134
+ arguments: { job_id: jobId }
2135
+ });
2136
+ }
2137
+ };
2138
+ function mapJobResult(data) {
2139
+ return {
2140
+ jobId: data.job_id,
2141
+ status: data.status,
2142
+ capability: data.capability,
2143
+ prompt: data.prompt,
2144
+ source: data.source,
2145
+ targetVerified: data.target_verified,
2146
+ maxLeads: data.max_leads ?? data.max_results,
2147
+ verifyEmails: data.verify_emails ?? false,
2148
+ message: data.message,
2149
+ estimatedTimeSeconds: data.estimated_time_seconds
2150
+ };
2151
+ }
2152
+
2153
+ // src/resources/execution-reference.ts
2154
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2155
+ var PREFIXED_RE = /^(op|routine|tick|routine_tick|trigger|trigger_run|run|dataplane|dataplane_run|queue|queue_job|job|event|execution_event|replay|replay_run):(.+)$/i;
2156
+ var FIELD_KIND_MAP = {
2157
+ op_id: "op",
2158
+ opId: "op",
2159
+ routine_id: "routine",
2160
+ routineId: "routine",
2161
+ tick_id: "routine_tick",
2162
+ tickId: "routine_tick",
2163
+ routineTickId: "routine_tick",
2164
+ run_id: "trigger_run",
2165
+ runId: "trigger_run",
2166
+ trigger_run_id: "trigger_run",
2167
+ triggerRunId: "trigger_run",
2168
+ dataplane_run_id: "dataplane_run",
2169
+ dataplaneRunId: "dataplane_run",
2170
+ job_id: "queue_job",
2171
+ jobId: "queue_job",
2172
+ queue_job_id: "queue_job",
2173
+ queueJobId: "queue_job",
2174
+ execution_event_id: "execution_event",
2175
+ executionEventId: "execution_event",
2176
+ event_id: "execution_event",
2177
+ eventId: "execution_event",
2178
+ replay_run_id: "replay_run",
2179
+ replayRunId: "replay_run"
2180
+ };
2181
+ var PREFIX_KIND_MAP = {
2182
+ op: "op",
2183
+ routine: "routine",
2184
+ tick: "routine_tick",
2185
+ routine_tick: "routine_tick",
2186
+ trigger: "trigger_run",
2187
+ trigger_run: "trigger_run",
2188
+ run: "trigger_run",
2189
+ dataplane: "dataplane_run",
2190
+ dataplane_run: "dataplane_run",
2191
+ queue: "queue_job",
2192
+ queue_job: "queue_job",
2193
+ job: "queue_job",
2194
+ event: "execution_event",
2195
+ execution_event: "execution_event",
2196
+ replay: "replay_run",
2197
+ replay_run: "replay_run"
2198
+ };
2199
+ function normalizeExecutionReference(input) {
2200
+ const original = typeof input === "string" ? input : input.id;
2201
+ const trimmed = original.trim();
2202
+ const sourceField = typeof input === "string" ? void 0 : input.source_field;
2203
+ const explicitKind = typeof input === "string" ? void 0 : input.kind;
2204
+ const prefixed = trimmed.match(PREFIXED_RE);
2205
+ const kind = explicitKind ?? kindFromPrefix(prefixed?.[1]) ?? kindFromField(sourceField) ?? inferKind(trimmed);
2206
+ const id = prefixed?.[2]?.trim() || trimmed;
2207
+ return {
2208
+ kind,
2209
+ id,
2210
+ original,
2211
+ label: labelFor(kind),
2212
+ query_field: queryFieldFor(kind),
2213
+ status_command: statusCommandFor(kind, id),
2214
+ replay_command: replayCommandFor(kind, id)
2215
+ };
2216
+ }
2217
+ function collectExecutionReferences(payload) {
2218
+ const refs = [];
2219
+ const seen = /* @__PURE__ */ new Set();
2220
+ for (const [field, value] of Object.entries(payload)) {
2221
+ if (!Object.prototype.hasOwnProperty.call(FIELD_KIND_MAP, field)) continue;
2222
+ if (typeof value !== "string" || value.trim().length === 0) continue;
2223
+ const ref = normalizeExecutionReference({ id: value, source_field: field });
2224
+ const key = `${ref.kind}:${ref.id}`;
2225
+ if (seen.has(key)) continue;
2226
+ seen.add(key);
2227
+ refs.push(ref);
2228
+ }
2229
+ return refs;
2230
+ }
2231
+ function kindFromPrefix(prefix) {
2232
+ if (!prefix) return void 0;
2233
+ return PREFIX_KIND_MAP[prefix.toLowerCase()];
2234
+ }
2235
+ function kindFromField(field) {
2236
+ if (!field) return void 0;
2237
+ return FIELD_KIND_MAP[field];
2238
+ }
2239
+ function inferKind(value) {
2240
+ if (value.startsWith("run_")) return "trigger_run";
2241
+ if (UUID_RE.test(value)) return "dataplane_run";
2242
+ return "unknown";
2243
+ }
2244
+ function labelFor(kind) {
2245
+ switch (kind) {
2246
+ case "op":
2247
+ return "Op";
2248
+ case "routine":
2249
+ return "Routine";
2250
+ case "routine_tick":
2251
+ return "Routine tick";
2252
+ case "trigger_run":
2253
+ return "Trigger.dev run";
2254
+ case "dataplane_run":
2255
+ return "Dataplane run";
2256
+ case "queue_job":
2257
+ return "Queue job";
2258
+ case "execution_event":
2259
+ return "Execution event";
2260
+ case "replay_run":
2261
+ return "Replay run";
2262
+ case "unknown":
2263
+ default:
2264
+ return "Execution reference";
2265
+ }
2266
+ }
2267
+ function queryFieldFor(kind) {
2268
+ switch (kind) {
2269
+ case "op":
2270
+ return "op_id";
2271
+ case "routine":
2272
+ return "routine_id";
2273
+ case "routine_tick":
2274
+ return "tick_id";
2275
+ case "trigger_run":
2276
+ return "run_id";
2277
+ case "dataplane_run":
2278
+ return "run_id";
2279
+ case "queue_job":
2280
+ return "job_id";
2281
+ case "execution_event":
2282
+ return "execution_event_id";
2283
+ case "replay_run":
2284
+ return "replay_run_id";
2285
+ case "unknown":
2286
+ default:
2287
+ return "id";
2288
+ }
2289
+ }
2290
+ function statusCommandFor(kind, id) {
2291
+ switch (kind) {
2292
+ case "op":
2293
+ return `signaliz status ${id}`;
2294
+ case "trigger_run":
2295
+ case "dataplane_run":
2296
+ case "replay_run":
2297
+ return `signaliz watch ${id}`;
2298
+ case "queue_job":
2299
+ return `signaliz queue --job-id ${id}`;
2300
+ case "routine":
2301
+ return `signaliz routine ${id}`;
2302
+ default:
2303
+ return void 0;
2304
+ }
2305
+ }
2306
+ function replayCommandFor(kind, id) {
2307
+ if (kind !== "execution_event") return void 0;
2308
+ return `signaliz replay ${id}`;
2309
+ }
2310
+
2311
+ // src/resources/ops.ts
2312
+ function asRecord2(value) {
2313
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
2314
+ }
2315
+ function stringValue2(value, fallback = "") {
2316
+ return typeof value === "string" ? value : fallback;
2317
+ }
2318
+ function optionalString(value) {
2319
+ return typeof value === "string" && value.length > 0 ? value : void 0;
2320
+ }
2321
+ function numberValue(value) {
2322
+ const parsed = Number(value);
2323
+ return Number.isFinite(parsed) ? parsed : 0;
2324
+ }
2325
+ var Ops = class {
2326
+ constructor(client) {
2327
+ this.client = client;
2328
+ }
2329
+ async plan(params) {
2330
+ const body = typeof params === "string" ? { prompt: params } : buildOpsPlanBody(params);
2331
+ return normalizeOpsPlanResult(await this.call("ops_plan", body));
2332
+ }
2333
+ async autopilot(params = {}) {
2334
+ const data = await this.call("ops_autopilot", {
2335
+ window_hours: params.windowHours,
2336
+ output_format: "json"
2337
+ });
2338
+ return normalizeOpsAutopilotResult(data);
2339
+ }
2340
+ async create(params) {
2341
+ const body = typeof params === "string" ? { prompt: params } : buildOpsCreateBody(params);
2342
+ return normalizeOpsCreateResult(withExecutionRefs(await this.call("ops_create", body)));
2343
+ }
2344
+ async execute(params) {
2345
+ const body = typeof params === "string" ? { prompt: params } : buildOpsExecuteBody(params);
2346
+ return normalizeOpsExecuteResult(withExecutionRefs(await this.call("ops_execute", body)));
2347
+ }
2348
+ async run(params) {
2349
+ const body = typeof params === "string" ? { op_id: params } : buildOpsRunBody(params);
2350
+ return normalizeOpsRunResult(withExecutionRefs(await this.call("ops_run", body)));
2351
+ }
2352
+ async status(params) {
2353
+ const body = typeof params === "string" ? { op_id: params } : buildOpsStatusBody(params);
2354
+ return normalizeOpsStatusResult(withExecutionRefs(await this.call("ops_status", body)));
2355
+ }
2356
+ async results(params) {
2357
+ const body = typeof params === "string" ? { op_id: params } : buildOpsResultsBody(params);
2358
+ return normalizeOpsResultsResult(withExecutionRefs(await this.call("ops_results", body)));
2359
+ }
2360
+ async proof(params = {}) {
2361
+ const data = await this.call("ops_proof", {
2362
+ window_hours: params.windowHours,
2363
+ output_format: "json"
2364
+ });
2365
+ return normalizeOpsProofResult(data);
2366
+ }
2367
+ async debug(params) {
2368
+ const options = typeof params === "string" ? { op_id: params } : buildOpsDebugOptions(params);
2369
+ const diagnosticErrors = [];
2370
+ const status = await this.status(options.op_id);
2371
+ const refs = /* @__PURE__ */ new Map();
2372
+ const addRefs = (items) => {
2373
+ for (const ref of items ?? []) refs.set(`${ref.kind}:${ref.id}`, ref);
2374
+ };
2375
+ const recordError = (step, err) => {
2376
+ diagnosticErrors.push({
2377
+ step,
2378
+ message: err instanceof Error ? err.message : String(err)
2379
+ });
2380
+ };
2381
+ addRefs(status.execution_refs);
2382
+ if (status.latest_run && typeof status.latest_run === "object") {
2383
+ addRefs(collectExecutionReferences(status.latest_run));
2384
+ }
2385
+ const runRefs = Array.from(refs.values()).filter((ref) => ref.kind === "trigger_run" || ref.kind === "dataplane_run" || ref.kind === "replay_run");
2386
+ const runStatuses = [];
2387
+ for (const ref of runRefs) {
2388
+ try {
2389
+ const result = await this.getTriggerRunStatus(ref.id);
2390
+ const runs = "runs" in result ? result.runs : [result];
2391
+ runStatuses.push(...runs);
2392
+ for (const run of runs) addRefs(run.execution_refs);
2393
+ } catch (err) {
2394
+ recordError(`run-status:${ref.id}`, err);
2395
+ }
2396
+ }
2397
+ let queue;
2398
+ if (options.include_queue !== false) {
2399
+ try {
2400
+ queue = await this.getQueueStatus({ summary: true });
2401
+ addRefs(queue.execution_refs);
2402
+ } catch (err) {
2403
+ recordError("queue", err);
2404
+ }
2405
+ }
2406
+ let dashboardRecent;
2407
+ if (options.include_dashboard !== false) {
2408
+ try {
2409
+ dashboardRecent = await this.getDashboard({
2410
+ section: "recent",
2411
+ limit: options.dashboard_limit ?? 10,
2412
+ timeRangeDays: options.time_range_days
2413
+ });
2414
+ } catch (err) {
2415
+ recordError("dashboard:recent", err);
2416
+ }
2417
+ }
2418
+ let results;
2419
+ if (options.include_results) {
2420
+ try {
2421
+ results = await this.results({
2422
+ op_id: options.op_id,
2423
+ limit: options.results_limit ?? 25,
2424
+ include_failed_runs: true
2425
+ });
2426
+ addRefs(results.execution_refs);
2427
+ } catch (err) {
2428
+ recordError("results", err);
2429
+ }
2430
+ }
2431
+ const executionRefs = Array.from(refs.values());
2432
+ const replayCandidates = executionRefs.filter((ref) => ref.kind === "execution_event");
2433
+ const nextActions = buildDebugNextActions(status, executionRefs, diagnosticErrors);
2434
+ return normalizeOpsDebugResult({
2435
+ success: diagnosticErrors.length === 0,
2436
+ op_id: options.op_id,
2437
+ checked_at: (/* @__PURE__ */ new Date()).toISOString(),
2438
+ diagnosis: buildDebugDiagnosis(status, runStatuses, queue, diagnosticErrors),
2439
+ status,
2440
+ execution_refs: executionRefs,
2441
+ run_statuses: runStatuses,
2442
+ queue,
2443
+ dashboard_recent: dashboardRecent,
2444
+ results,
2445
+ replay_candidates: replayCandidates,
2446
+ next_actions: nextActions,
2447
+ diagnostic_errors: diagnosticErrors
2448
+ });
2449
+ }
2450
+ async quickstartWorkflow(workflowType = "email_verification") {
2451
+ const workflow = normalizeOpsQuickstartWorkflow(await this.call("quickstart_workflow", { workflow_type: workflowType }));
2452
+ assertQuickstartWorkflowCoherent(workflow, workflowType);
2453
+ return workflow;
2454
+ }
2455
+ async approve(params) {
2456
+ return normalizeOpsApproveResult(await this.call("ops_approve", buildApproveBody(params)));
2457
+ }
2458
+ async createRoutine(params) {
2459
+ return normalizeOpsRoutine(await this.call("create_routine", buildCreateRoutineBody(params)));
2460
+ }
2461
+ async listRoutines(params = {}) {
2462
+ const data = await this.call("list_routines", { ...params, format: "json" });
2463
+ const nextCursor = data.next_cursor ?? data.nextCursor ?? null;
2464
+ const hasMore = data.has_more ?? data.hasMore ?? false;
2465
+ return {
2466
+ routines: Array.isArray(data.routines ?? data) ? (data.routines ?? data).map(normalizeOpsRoutine) : [],
2467
+ total: data.total,
2468
+ next_cursor: nextCursor,
2469
+ nextCursor,
2470
+ has_more: hasMore,
2471
+ hasMore
2472
+ };
2473
+ }
2474
+ async getRoutine(routineId) {
2475
+ return normalizeOpsRoutine(await this.call("get_routine", { routine_id: routineId }));
2476
+ }
2477
+ async updateRoutine(params) {
2478
+ return normalizeOpsRoutine(await this.call("update_routine", buildRoutineBody(params)));
2479
+ }
2480
+ async runRoutineNow(params) {
2481
+ const body = typeof params === "string" ? { routine_id: params } : buildRoutineBody(params);
2482
+ return normalizeOpsRoutineRunResult(await this.call("run_routine_now", body));
2483
+ }
2484
+ async deleteRoutine(routineId, permanent = false) {
2485
+ return normalizeOpsRoutineDeleteResult(await this.call("delete_routine", { routine_id: routineId, confirm: true, permanent }));
2486
+ }
2487
+ async listOutputSinks(params = {}) {
2488
+ const data = await this.call("list_output_sinks", buildListOutputSinksBody(params));
2489
+ const sinks = data.sinks ?? data ?? [];
2490
+ return Array.isArray(sinks) ? sinks.map(normalizeOpsSink) : [];
2491
+ }
2492
+ async getReadiness(params = {}) {
2493
+ const data = await this.call("get_ops_readiness", {
2494
+ window_hours: params.windowHours,
2495
+ include_details: params.includeDetails,
2496
+ run_acquisition_probe: params.runAcquisitionProbe,
2497
+ output_format: "json"
2498
+ });
2499
+ const summary = asRecord2(data.summary);
2500
+ const checks = Array.isArray(data.checks) ? data.checks : [];
2501
+ const checkedAt = stringValue2(data.checked_at ?? data.checkedAt, (/* @__PURE__ */ new Date()).toISOString());
2502
+ const nextActions = Array.isArray(data.next_actions) ? data.next_actions.map(String) : Array.isArray(data.nextActions) ? data.nextActions.map(String) : [];
2503
+ return {
2504
+ status: data.status === "ready" || data.status === "blocked" ? data.status : "degraded",
2505
+ checked_at: checkedAt,
2506
+ checkedAt,
2507
+ credits_used: 0,
2508
+ creditsUsed: 0,
2509
+ credits_charged: 0,
2510
+ creditsCharged: 0,
2511
+ summary: {
2512
+ active_connections: numberValue(summary.active_connections ?? summary.activeConnections),
2513
+ activeConnections: numberValue(summary.active_connections ?? summary.activeConnections),
2514
+ failing_connections: numberValue(summary.failing_connections ?? summary.failingConnections),
2515
+ failingConnections: numberValue(summary.failing_connections ?? summary.failingConnections),
2516
+ active_routines: numberValue(summary.active_routines ?? summary.activeRoutines),
2517
+ activeRoutines: numberValue(summary.active_routines ?? summary.activeRoutines),
2518
+ recent_failed_ticks: numberValue(summary.recent_failed_ticks ?? summary.recentFailedTicks),
2519
+ recentFailedTicks: numberValue(summary.recent_failed_ticks ?? summary.recentFailedTicks),
2520
+ queued_deliveries: numberValue(summary.queued_deliveries ?? summary.queuedDeliveries),
2521
+ queuedDeliveries: numberValue(summary.queued_deliveries ?? summary.queuedDeliveries),
2522
+ pending_approvals: numberValue(summary.pending_approvals ?? summary.pendingApprovals),
2523
+ pendingApprovals: numberValue(summary.pending_approvals ?? summary.pendingApprovals),
2524
+ lead_records: numberValue(summary.lead_records ?? summary.leadRecords),
2525
+ leadRecords: numberValue(summary.lead_records ?? summary.leadRecords),
2526
+ recent_acquisition_failures: numberValue(summary.recent_acquisition_failures ?? summary.recentAcquisitionFailures),
2527
+ recentAcquisitionFailures: numberValue(summary.recent_acquisition_failures ?? summary.recentAcquisitionFailures),
2528
+ acquisition_probe_status: optionalString(summary.acquisition_probe_status ?? summary.acquisitionProbeStatus),
2529
+ acquisitionProbeStatus: optionalString(summary.acquisition_probe_status ?? summary.acquisitionProbeStatus)
2530
+ },
2531
+ checks: checks.map((rawCheck) => {
2532
+ const check = asRecord2(rawCheck);
2533
+ const nextAction = optionalString(check.next_action ?? check.nextAction);
2534
+ return {
2535
+ id: String(check.id ?? ""),
2536
+ label: String(check.label ?? check.id ?? ""),
2537
+ status: check.status === "fail" ? "fail" : check.status === "warn" ? "warn" : "pass",
2538
+ detail: String(check.detail ?? ""),
2539
+ next_action: nextAction,
2540
+ nextAction
2541
+ };
2542
+ }),
2543
+ next_actions: nextActions,
2544
+ nextActions,
2545
+ raw: data
2546
+ };
2547
+ }
2548
+ async doctor(params = {}) {
2549
+ return this.getReadiness(params);
2550
+ }
2551
+ async createOutputSink(params) {
2552
+ const data = await this.call("create_output_sink", buildCreateOutputSinkBody(params));
2553
+ return normalizeOpsSink(data.sink ?? data);
2554
+ }
2555
+ async attachSinkToRoutine(params) {
2556
+ return normalizeOpsRoutineSinkResult(await this.call("attach_sink_to_routine", buildRoutineSinkBody(params)));
2557
+ }
2558
+ async getRoutineTicks(params) {
2559
+ return normalizeOpsRoutineTicksResult(await this.call("get_routine_ticks", buildRoutineBody(params)));
2560
+ }
2561
+ async getLastTickItems(params) {
2562
+ return normalizeOpsRoutineTickItemsResult(await this.call("get_last_tick_items", buildRoutineBody(params)));
2563
+ }
2564
+ async getTriggerRunStatus(params) {
2565
+ const body = typeof params === "string" ? { run_id: params } : {
2566
+ run_id: params.run_id ?? params.runId,
2567
+ run_ids: params.run_ids ?? params.runIds
2568
+ };
2569
+ const result = await this.client.post("trigger-run-status", body);
2570
+ if ("runs" in result) {
2571
+ return {
2572
+ ...result,
2573
+ runs: result.runs.map((run) => normalizeOpsTriggerRunStatus(withExecutionRefs(run)))
2574
+ };
2575
+ }
2576
+ return normalizeOpsTriggerRunStatus(withExecutionRefs(result));
2577
+ }
2578
+ async getQueueStatus(params = {}) {
2579
+ return normalizeOpsQueueStatus(withExecutionRefs(await this.client.get("check-queue-status", {
2580
+ job_id: params.job_id ?? params.jobId,
2581
+ idempotency_key: params.idempotency_key ?? params.idempotencyKey,
2582
+ summary: params.summary
2583
+ })));
2584
+ }
2585
+ async replayFromCheckpoint(executionEventId) {
2586
+ const result = await this.client.post("replay-from-checkpoint", { execution_event_id: executionEventId });
2587
+ const normalized = normalizeOpsReplayResult(withExecutionRefs(result));
2588
+ return {
2589
+ ...normalized,
2590
+ execution_refs: [
2591
+ ...normalized.execution_refs ?? [],
2592
+ normalizeExecutionReference({ id: executionEventId, source_field: "execution_event_id" })
2593
+ ]
2594
+ };
2595
+ }
2596
+ normalizeExecutionReference(input) {
2597
+ return normalizeExecutionReference(input);
2598
+ }
2599
+ collectExecutionReferences(payload) {
2600
+ return collectExecutionReferences(payload);
2601
+ }
2602
+ async getDashboard(params = {}) {
2603
+ return normalizeOpsDashboardResult(await this.client.post("ops-dashboard", params));
2604
+ }
2605
+ async call(name, args) {
2606
+ return this.client.mcp("tools/call", {
2607
+ name,
2608
+ arguments: args
2609
+ });
2610
+ }
2611
+ };
2612
+ function withExecutionRefs(result) {
2613
+ return {
2614
+ ...result,
2615
+ execution_refs: mergeExecutionRefs(result)
2616
+ };
2617
+ }
2618
+ function mergeExecutionRefs(result) {
2619
+ const refs = /* @__PURE__ */ new Map();
2620
+ const add = (ref) => refs.set(`${ref.kind}:${ref.id}`, ref);
2621
+ if (Array.isArray(result.execution_refs)) {
2622
+ for (const raw of result.execution_refs) {
2623
+ if (raw && typeof raw === "object") {
2624
+ const ref = raw;
2625
+ if (typeof ref.id === "string" && typeof ref.kind === "string") add(ref);
2626
+ }
2627
+ }
2628
+ }
2629
+ for (const ref of collectExecutionReferences(result)) add(ref);
2630
+ return Array.from(refs.values());
2631
+ }
2632
+ function normalizeOpsPrimitiveRetryPolicy(policy = {}) {
2633
+ return {
2634
+ ...policy,
2635
+ max_retries: policy.max_retries ?? policy.maxRetries ?? 0,
2636
+ maxRetries: policy.maxRetries ?? policy.max_retries ?? 0,
2637
+ initial_delay_ms: policy.initial_delay_ms ?? policy.initialDelayMs ?? 0,
2638
+ initialDelayMs: policy.initialDelayMs ?? policy.initial_delay_ms ?? 0,
2639
+ max_delay_ms: policy.max_delay_ms ?? policy.maxDelayMs ?? 0,
2640
+ maxDelayMs: policy.maxDelayMs ?? policy.max_delay_ms ?? 0,
2641
+ backoff_multiplier: policy.backoff_multiplier ?? policy.backoffMultiplier ?? 0,
2642
+ backoffMultiplier: policy.backoffMultiplier ?? policy.backoff_multiplier ?? 0,
2643
+ jitter: policy.jitter ?? false,
2644
+ retryable_errors: policy.retryable_errors ?? policy.retryableErrors ?? [],
2645
+ retryableErrors: policy.retryableErrors ?? policy.retryable_errors ?? [],
2646
+ respect_retry_after: policy.respect_retry_after ?? policy.respectRetryAfter ?? false,
2647
+ respectRetryAfter: policy.respectRetryAfter ?? policy.respect_retry_after ?? false
2648
+ };
2649
+ }
2650
+ function normalizeOpsPrimitiveConcurrencyPolicy(policy = {}) {
2651
+ return {
2652
+ ...policy,
2653
+ workspace_key: policy.workspace_key ?? policy.workspaceKey ?? "",
2654
+ workspaceKey: policy.workspaceKey ?? policy.workspace_key ?? "",
2655
+ provider_key: policy.provider_key ?? policy.providerKey,
2656
+ providerKey: policy.providerKey ?? policy.provider_key,
2657
+ max_concurrency: policy.max_concurrency ?? policy.maxConcurrency ?? 0,
2658
+ maxConcurrency: policy.maxConcurrency ?? policy.max_concurrency ?? 0
2659
+ };
2660
+ }
2661
+ function normalizeOpsPrimitiveDeadLetterPolicy(policy = {}) {
2662
+ return {
2663
+ ...policy,
2664
+ enabled: policy.enabled ?? false,
2665
+ queue: policy.queue ?? "",
2666
+ include_input_hash: policy.include_input_hash ?? policy.includeInputHash ?? false,
2667
+ includeInputHash: policy.includeInputHash ?? policy.include_input_hash ?? false,
2668
+ include_execution_refs: policy.include_execution_refs ?? policy.includeExecutionRefs ?? false,
2669
+ includeExecutionRefs: policy.includeExecutionRefs ?? policy.include_execution_refs ?? false
2670
+ };
2671
+ }
2672
+ function normalizeOpsPrimitiveObservabilityPolicy(policy = {}) {
2673
+ return {
2674
+ ...policy,
2675
+ emits_execution_refs: policy.emits_execution_refs ?? policy.emitsExecutionRefs ?? false,
2676
+ emitsExecutionRefs: policy.emitsExecutionRefs ?? policy.emits_execution_refs ?? false,
2677
+ emits_progress_events: policy.emits_progress_events ?? policy.emitsProgressEvents ?? false,
2678
+ emitsProgressEvents: policy.emitsProgressEvents ?? policy.emits_progress_events ?? false,
2679
+ event_fields: policy.event_fields ?? policy.eventFields ?? [],
2680
+ eventFields: policy.eventFields ?? policy.event_fields ?? []
2681
+ };
2682
+ }
2683
+ function normalizeOpsPrimitive(primitive) {
2684
+ return {
2685
+ ...primitive,
2686
+ permission_level: primitive.permission_level ?? primitive.permissionLevel,
2687
+ permissionLevel: primitive.permissionLevel ?? primitive.permission_level,
2688
+ workspace_scope: primitive.workspace_scope ?? primitive.workspaceScope,
2689
+ workspaceScope: primitive.workspaceScope ?? primitive.workspace_scope,
2690
+ input_schema: primitive.input_schema ?? primitive.inputSchema,
2691
+ inputSchema: primitive.inputSchema ?? primitive.input_schema,
2692
+ output_schema: primitive.output_schema ?? primitive.outputSchema,
2693
+ outputSchema: primitive.outputSchema ?? primitive.output_schema,
2694
+ retry_policy: normalizeOpsPrimitiveRetryPolicy(primitive.retry_policy ?? primitive.retryPolicy),
2695
+ retryPolicy: normalizeOpsPrimitiveRetryPolicy(primitive.retryPolicy ?? primitive.retry_policy),
2696
+ concurrency_policy: normalizeOpsPrimitiveConcurrencyPolicy(primitive.concurrency_policy ?? primitive.concurrencyPolicy),
2697
+ concurrencyPolicy: normalizeOpsPrimitiveConcurrencyPolicy(primitive.concurrencyPolicy ?? primitive.concurrency_policy),
2698
+ rate_limit_key: primitive.rate_limit_key ?? primitive.rateLimitKey,
2699
+ rateLimitKey: primitive.rateLimitKey ?? primitive.rate_limit_key,
2700
+ idempotency_key_fields: primitive.idempotency_key_fields ?? primitive.idempotencyKeyFields ?? [],
2701
+ idempotencyKeyFields: primitive.idempotencyKeyFields ?? primitive.idempotency_key_fields ?? [],
2702
+ dead_letter_policy: normalizeOpsPrimitiveDeadLetterPolicy(primitive.dead_letter_policy ?? primitive.deadLetterPolicy),
2703
+ deadLetterPolicy: normalizeOpsPrimitiveDeadLetterPolicy(primitive.deadLetterPolicy ?? primitive.dead_letter_policy),
2704
+ observability: normalizeOpsPrimitiveObservabilityPolicy(primitive.observability)
2705
+ };
2706
+ }
2707
+ function normalizeOpsPlanResult(result) {
2708
+ const primitiveGraph = result.primitive_graph ?? result.primitiveGraph;
2709
+ return {
2710
+ ...result,
2711
+ plan_id: result.plan_id ?? result.planId,
2712
+ planId: result.planId ?? result.plan_id,
2713
+ target_count: result.target_count ?? result.targetCount,
2714
+ targetCount: result.targetCount ?? result.target_count,
2715
+ estimated_credits: result.estimated_credits ?? result.estimatedCredits,
2716
+ estimatedCredits: result.estimatedCredits ?? result.estimated_credits,
2717
+ approval_required: result.approval_required ?? result.approvalRequired,
2718
+ approvalRequired: result.approvalRequired ?? result.approval_required,
2719
+ expected_output: result.expected_output ?? result.expectedOutput,
2720
+ expectedOutput: result.expectedOutput ?? result.expected_output,
2721
+ next_action: result.next_action ?? result.nextAction,
2722
+ nextAction: result.nextAction ?? result.next_action,
2723
+ ui_summary: result.ui_summary ?? result.uiSummary,
2724
+ uiSummary: result.uiSummary ?? result.ui_summary,
2725
+ review_steps: result.review_steps ?? result.reviewSteps,
2726
+ reviewSteps: result.reviewSteps ?? result.review_steps,
2727
+ fix_actions: result.fix_actions ?? result.fixActions,
2728
+ fixActions: result.fixActions ?? result.fix_actions,
2729
+ destination_status: result.destination_status ?? result.destinationStatus,
2730
+ destinationStatus: result.destinationStatus ?? result.destination_status,
2731
+ primitive_graph: primitiveGraph?.map(normalizeOpsPrimitive),
2732
+ primitiveGraph: primitiveGraph?.map(normalizeOpsPrimitive)
2733
+ };
2734
+ }
2735
+ function normalizeOpsCreateResult(result) {
2736
+ return {
2737
+ ...result,
2738
+ op_id: result.op_id ?? result.opId,
2739
+ opId: result.opId ?? result.op_id,
2740
+ routine_id: result.routine_id ?? result.routineId,
2741
+ routineId: result.routineId ?? result.routine_id,
2742
+ run_id: result.run_id ?? result.runId,
2743
+ runId: result.runId ?? result.run_id,
2744
+ next_action: result.next_action ?? result.nextAction,
2745
+ nextAction: result.nextAction ?? result.next_action,
2746
+ results_count: result.results_count ?? result.resultsCount,
2747
+ resultsCount: result.resultsCount ?? result.results_count,
2748
+ results_url: result.results_url ?? result.resultsUrl,
2749
+ resultsUrl: result.resultsUrl ?? result.results_url,
2750
+ delivery_status: result.delivery_status ?? result.deliveryStatus,
2751
+ deliveryStatus: result.deliveryStatus ?? result.delivery_status,
2752
+ estimated_credits: result.estimated_credits ?? result.estimatedCredits,
2753
+ estimatedCredits: result.estimatedCredits ?? result.estimated_credits,
2754
+ plan: result.plan ? normalizeOpsPlanResult(result.plan) : result.plan
2755
+ };
2756
+ }
2757
+ function normalizeOpsExecuteResult(result) {
2758
+ const created = normalizeOpsCreateResult(result);
2759
+ return {
2760
+ ...created,
2761
+ error_code: result.error_code ?? result.errorCode,
2762
+ errorCode: result.errorCode ?? result.error_code,
2763
+ approval_required: result.approval_required ?? result.approvalRequired,
2764
+ approvalRequired: result.approvalRequired ?? result.approval_required,
2765
+ retry_arguments: result.retry_arguments ?? result.retryArguments,
2766
+ retryArguments: result.retryArguments ?? result.retry_arguments,
2767
+ next_step: result.next_step ?? result.nextStep,
2768
+ nextStep: result.nextStep ?? result.next_step,
2769
+ next_steps: result.next_steps ?? result.nextSteps,
2770
+ nextSteps: result.nextSteps ?? result.next_steps,
2771
+ blockers: result.blockers
2772
+ };
2773
+ }
2774
+ function normalizeOpsDebugDiagnosis(diagnosis) {
2775
+ return {
2776
+ ...diagnosis,
2777
+ queue_pending: diagnosis.queue_pending ?? diagnosis.queuePending,
2778
+ queuePending: diagnosis.queuePending ?? diagnosis.queue_pending,
2779
+ queue_processing: diagnosis.queue_processing ?? diagnosis.queueProcessing,
2780
+ queueProcessing: diagnosis.queueProcessing ?? diagnosis.queue_processing,
2781
+ queue_failed_last_hour: diagnosis.queue_failed_last_hour ?? diagnosis.queueFailedLastHour,
2782
+ queueFailedLastHour: diagnosis.queueFailedLastHour ?? diagnosis.queue_failed_last_hour,
2783
+ provider_pressure: diagnosis.provider_pressure ?? diagnosis.providerPressure,
2784
+ providerPressure: diagnosis.providerPressure ?? diagnosis.provider_pressure,
2785
+ failed_run_count: diagnosis.failed_run_count ?? diagnosis.failedRunCount,
2786
+ failedRunCount: diagnosis.failedRunCount ?? diagnosis.failed_run_count,
2787
+ primary_error: diagnosis.primary_error ?? diagnosis.primaryError,
2788
+ primaryError: diagnosis.primaryError ?? diagnosis.primary_error
2789
+ };
2790
+ }
2791
+ function normalizeOpsDebugResult(result) {
2792
+ return {
2793
+ ...result,
2794
+ op_id: result.op_id ?? result.opId,
2795
+ opId: result.opId ?? result.op_id,
2796
+ checked_at: result.checked_at ?? result.checkedAt,
2797
+ checkedAt: result.checkedAt ?? result.checked_at,
2798
+ diagnosis: normalizeOpsDebugDiagnosis(result.diagnosis),
2799
+ execution_refs: result.execution_refs ?? result.executionRefs ?? [],
2800
+ executionRefs: result.executionRefs ?? result.execution_refs ?? [],
2801
+ run_statuses: result.run_statuses ?? result.runStatuses ?? [],
2802
+ runStatuses: result.runStatuses ?? result.run_statuses ?? [],
2803
+ dashboard_recent: result.dashboard_recent ?? result.dashboardRecent,
2804
+ dashboardRecent: result.dashboardRecent ?? result.dashboard_recent,
2805
+ replay_candidates: result.replay_candidates ?? result.replayCandidates ?? [],
2806
+ replayCandidates: result.replayCandidates ?? result.replay_candidates ?? [],
2807
+ next_actions: result.next_actions ?? result.nextActions ?? [],
2808
+ nextActions: result.nextActions ?? result.next_actions ?? [],
2809
+ diagnostic_errors: result.diagnostic_errors ?? result.diagnosticErrors ?? [],
2810
+ diagnosticErrors: result.diagnosticErrors ?? result.diagnostic_errors ?? []
2811
+ };
2812
+ }
2813
+ function normalizeOpsQuickstartStep(step) {
2814
+ return {
2815
+ ...step,
2816
+ primitive_id: step.primitive_id ?? step.primitiveId,
2817
+ primitiveId: step.primitiveId ?? step.primitive_id,
2818
+ primitive_version: step.primitive_version ?? step.primitiveVersion,
2819
+ primitiveVersion: step.primitiveVersion ?? step.primitive_version
2820
+ };
2821
+ }
2822
+ function normalizeOpsQuickstartWorkflow(result) {
2823
+ const primitiveGraph = result.primitive_graph ?? result.primitiveGraph;
2824
+ return {
2825
+ ...result,
2826
+ workflow_type: result.workflow_type ?? result.workflowType,
2827
+ workflowType: result.workflowType ?? result.workflow_type,
2828
+ requested_workflow_type: result.requested_workflow_type ?? result.requestedWorkflowType,
2829
+ requestedWorkflowType: result.requestedWorkflowType ?? result.requested_workflow_type,
2830
+ credits_required: result.credits_required ?? result.creditsRequired,
2831
+ creditsRequired: result.creditsRequired ?? result.credits_required,
2832
+ steps: (result.steps ?? []).map(normalizeOpsQuickstartStep),
2833
+ primitive_graph: primitiveGraph?.map(normalizeOpsPrimitive),
2834
+ primitiveGraph: primitiveGraph?.map(normalizeOpsPrimitive),
2835
+ available_types: result.available_types ?? result.availableTypes ?? [],
2836
+ availableTypes: result.availableTypes ?? result.available_types ?? []
2837
+ };
2838
+ }
2839
+ function assertQuickstartWorkflowCoherent(workflow, requestedWorkflowType) {
2840
+ if (!workflow.available_types.length) return;
2841
+ if (workflow.available_types.includes(workflow.workflow_type)) return;
2842
+ throw new SignalizError({
2843
+ code: "QUICKSTART_TEMPLATE_DRIFT",
2844
+ errorType: "validation",
2845
+ message: `quickstart_workflow returned workflow_type "${workflow.workflow_type}" for requested type "${requestedWorkflowType}", but available_types did not include it`,
2846
+ details: {
2847
+ requested_workflow_type: requestedWorkflowType,
2848
+ workflow_type: workflow.workflow_type,
2849
+ available_types: workflow.available_types
2850
+ }
2851
+ });
2852
+ }
2853
+ function normalizeOpsRunResult(result) {
2854
+ return {
2855
+ ...result,
2856
+ op_id: result.op_id ?? result.opId,
2857
+ opId: result.opId ?? result.op_id,
2858
+ routine_id: result.routine_id ?? result.routineId,
2859
+ routineId: result.routineId ?? result.routine_id,
2860
+ run_id: result.run_id ?? result.runId,
2861
+ runId: result.runId ?? result.run_id,
2862
+ next_action: result.next_action ?? result.nextAction,
2863
+ nextAction: result.nextAction ?? result.next_action,
2864
+ results_count: result.results_count ?? result.resultsCount,
2865
+ resultsCount: result.resultsCount ?? result.results_count,
2866
+ results_url: result.results_url ?? result.resultsUrl,
2867
+ resultsUrl: result.resultsUrl ?? result.results_url,
2868
+ delivery_status: result.delivery_status ?? result.deliveryStatus,
2869
+ deliveryStatus: result.deliveryStatus ?? result.delivery_status
2870
+ };
2871
+ }
2872
+ function normalizeOpsStatusResult(result) {
2873
+ return {
2874
+ ...normalizeOpsRunResult(result),
2875
+ estimated_credits: result.estimated_credits ?? result.estimatedCredits,
2876
+ estimatedCredits: result.estimatedCredits ?? result.estimated_credits,
2877
+ latest_run: result.latest_run ?? result.latestRun,
2878
+ latestRun: result.latestRun ?? result.latest_run,
2879
+ diagnosis: result.diagnosis ? normalizeOpsDebugDiagnosis(result.diagnosis) : void 0
2880
+ };
2881
+ }
2882
+ function normalizeOpsResultsResult(result) {
2883
+ const nextCursor = result.next_cursor ?? result.nextCursor ?? null;
2884
+ const hasMore = result.has_more ?? result.hasMore ?? false;
2885
+ return {
2886
+ ...result,
2887
+ op_id: result.op_id ?? result.opId,
2888
+ opId: result.opId ?? result.op_id,
2889
+ routine_id: result.routine_id ?? result.routineId,
2890
+ routineId: result.routineId ?? result.routine_id,
2891
+ run_id: result.run_id ?? result.runId,
2892
+ runId: result.runId ?? result.run_id,
2893
+ results_count: result.results_count ?? result.resultsCount,
2894
+ resultsCount: result.resultsCount ?? result.results_count,
2895
+ results_total: result.results_total ?? result.resultsTotal,
2896
+ resultsTotal: result.resultsTotal ?? result.results_total,
2897
+ next_cursor: nextCursor,
2898
+ nextCursor,
2899
+ has_more: hasMore,
2900
+ hasMore,
2901
+ next_action: result.next_action ?? result.nextAction,
2902
+ nextAction: result.nextAction ?? result.next_action,
2903
+ results_url: result.results_url ?? result.resultsUrl,
2904
+ resultsUrl: result.resultsUrl ?? result.results_url,
2905
+ delivery_status: result.delivery_status ?? result.deliveryStatus,
2906
+ deliveryStatus: result.deliveryStatus ?? result.delivery_status
2907
+ };
2908
+ }
2909
+ function normalizeOpsProofResult(data) {
2910
+ const summary = asRecord2(data.summary);
2911
+ const destinations = Array.isArray(data.destinations) ? data.destinations.map((rawDestination) => {
2912
+ const destination = asRecord2(rawDestination);
2913
+ return {
2914
+ type: stringValue2(destination.type),
2915
+ label: stringValue2(destination.label, stringValue2(destination.type)),
2916
+ connected: Boolean(destination.connected),
2917
+ healthy: Boolean(destination.healthy),
2918
+ delivered: numberValue(destination.delivered),
2919
+ failed: numberValue(destination.failed),
2920
+ proof: stringValue2(destination.proof, "connected")
2921
+ };
2922
+ }) : [];
2923
+ const checkedAt = optionalString(data.checked_at ?? data.checkedAt);
2924
+ const nextActions = Array.isArray(data.next_actions) ? data.next_actions.map(String) : Array.isArray(data.nextActions) ? data.nextActions.map(String) : [];
2925
+ const blockers = Array.isArray(data.blockers) ? data.blockers.map(String) : [];
2926
+ const queryErrors = Array.isArray(data.query_errors) ? data.query_errors.map(String) : Array.isArray(data.queryErrors) ? data.queryErrors.map(String) : [];
2927
+ return {
2928
+ ...data,
2929
+ status: stringValue2(data.status, stringValue2(data.proof_state ?? data.proofState, "unproven")),
2930
+ proof_state: stringValue2(data.proof_state ?? data.proofState, stringValue2(data.status, "unproven")),
2931
+ proofState: stringValue2(data.proofState ?? data.proof_state, stringValue2(data.status, "unproven")),
2932
+ checked_at: checkedAt,
2933
+ checkedAt,
2934
+ window_hours: numberValue(data.window_hours ?? data.windowHours),
2935
+ windowHours: numberValue(data.window_hours ?? data.windowHours),
2936
+ label: stringValue2(data.label, "Ops proof"),
2937
+ ui_summary: optionalString(data.ui_summary ?? data.uiSummary),
2938
+ uiSummary: optionalString(data.ui_summary ?? data.uiSummary),
2939
+ founder_verdict: optionalString(data.founder_verdict ?? data.founderVerdict),
2940
+ founderVerdict: optionalString(data.founder_verdict ?? data.founderVerdict),
2941
+ summary: {
2942
+ connected_destinations: numberValue(summary.connected_destinations ?? summary.connectedDestinations),
2943
+ connectedDestinations: numberValue(summary.connected_destinations ?? summary.connectedDestinations),
2944
+ healthy_destinations: numberValue(summary.healthy_destinations ?? summary.healthyDestinations),
2945
+ healthyDestinations: numberValue(summary.healthy_destinations ?? summary.healthyDestinations),
2946
+ failing_destinations: numberValue(summary.failing_destinations ?? summary.failingDestinations),
2947
+ failingDestinations: numberValue(summary.failing_destinations ?? summary.failingDestinations),
2948
+ deliveries_30d: numberValue(summary.deliveries_30d ?? summary.deliveries30d),
2949
+ deliveries30d: numberValue(summary.deliveries_30d ?? summary.deliveries30d),
2950
+ delivered_30d: numberValue(summary.delivered_30d ?? summary.delivered30d),
2951
+ delivered30d: numberValue(summary.delivered_30d ?? summary.delivered30d),
2952
+ failed_30d: numberValue(summary.failed_30d ?? summary.failed30d),
2953
+ failed30d: numberValue(summary.failed_30d ?? summary.failed30d),
2954
+ external_delivered_30d: numberValue(summary.external_delivered_30d ?? summary.externalDelivered30d),
2955
+ externalDelivered30d: numberValue(summary.external_delivered_30d ?? summary.externalDelivered30d),
2956
+ nango_proofs_30d: numberValue(summary.nango_proofs_30d ?? summary.nangoProofs30d),
2957
+ nangoProofs30d: numberValue(summary.nango_proofs_30d ?? summary.nangoProofs30d),
2958
+ nango_failures_30d: numberValue(summary.nango_failures_30d ?? summary.nangoFailures30d),
2959
+ nangoFailures30d: numberValue(summary.nango_failures_30d ?? summary.nangoFailures30d),
2960
+ airbyte_configured: numberValue(summary.airbyte_configured ?? summary.airbyteConfigured),
2961
+ airbyteConfigured: numberValue(summary.airbyte_configured ?? summary.airbyteConfigured),
2962
+ airbyte_proofs_30d: numberValue(summary.airbyte_proofs_30d ?? summary.airbyteProofs30d),
2963
+ airbyteProofs30d: numberValue(summary.airbyte_proofs_30d ?? summary.airbyteProofs30d),
2964
+ airbyte_failures_30d: numberValue(summary.airbyte_failures_30d ?? summary.airbyteFailures30d),
2965
+ airbyteFailures30d: numberValue(summary.airbyte_failures_30d ?? summary.airbyteFailures30d)
2966
+ },
2967
+ destinations,
2968
+ blockers,
2969
+ next_action: optionalString(data.next_action ?? data.nextAction),
2970
+ nextAction: optionalString(data.next_action ?? data.nextAction),
2971
+ next_actions: nextActions,
2972
+ nextActions,
2973
+ estimated_credits: numberValue(data.estimated_credits ?? data.estimatedCredits),
2974
+ estimatedCredits: numberValue(data.estimated_credits ?? data.estimatedCredits),
2975
+ approval_required: Boolean(data.approval_required ?? data.approvalRequired),
2976
+ approvalRequired: Boolean(data.approval_required ?? data.approvalRequired),
2977
+ credits_charged: 0,
2978
+ creditsCharged: 0,
2979
+ proof_mode: data.proof_mode !== false,
2980
+ proofMode: data.proof_mode !== false,
2981
+ query_errors: queryErrors,
2982
+ queryErrors,
2983
+ raw: data
2984
+ };
2985
+ }
2986
+ function normalizeOpsAutopilotMotion(rawMotion) {
2987
+ const motion = asRecord2(rawMotion);
2988
+ const targetCount = numberValue(motion.target_count ?? motion.targetCount);
2989
+ const estimatedCredits = numberValue(motion.estimated_credits ?? motion.estimatedCredits);
2990
+ const mcpSequence = Array.isArray(motion.mcp_sequence) ? motion.mcp_sequence : Array.isArray(motion.mcpSequence) ? motion.mcpSequence : [];
2991
+ return {
2992
+ ...motion,
2993
+ id: stringValue2(motion.id),
2994
+ blueprint: stringValue2(motion.blueprint, "build_leads"),
2995
+ title: stringValue2(motion.title),
2996
+ outcome: stringValue2(motion.outcome),
2997
+ prompt: stringValue2(motion.prompt),
2998
+ target_count: targetCount,
2999
+ targetCount,
3000
+ cadence: stringValue2(motion.cadence, "manual"),
3001
+ destinations: Array.isArray(motion.destinations) ? motion.destinations.map(String) : [],
3002
+ estimated_credits: estimatedCredits,
3003
+ estimatedCredits,
3004
+ proof_gate: optionalString(motion.proof_gate ?? motion.proofGate),
3005
+ proofGate: optionalString(motion.proof_gate ?? motion.proofGate),
3006
+ why_now: optionalString(motion.why_now ?? motion.whyNow),
3007
+ whyNow: optionalString(motion.why_now ?? motion.whyNow),
3008
+ agent_prompt: optionalString(motion.agent_prompt ?? motion.agentPrompt),
3009
+ agentPrompt: optionalString(motion.agent_prompt ?? motion.agentPrompt),
3010
+ cli_command: optionalString(motion.cli_command ?? motion.cliCommand),
3011
+ cliCommand: optionalString(motion.cli_command ?? motion.cliCommand),
3012
+ mcp_sequence: mcpSequence,
3013
+ mcpSequence
3014
+ };
3015
+ }
3016
+ function normalizeOpsAutopilotResult(result) {
3017
+ const primary = normalizeOpsAutopilotMotion(result.primary_motion ?? result.primaryMotion);
3018
+ const motions = Array.isArray(result.motions) ? result.motions.map(normalizeOpsAutopilotMotion) : [];
3019
+ const queryErrors = Array.isArray(result.query_errors) ? result.query_errors.map(String) : Array.isArray(result.queryErrors) ? result.queryErrors.map(String) : [];
3020
+ return {
3021
+ ...result,
3022
+ stage: stringValue2(result.stage, "prove"),
3023
+ headline: stringValue2(result.headline, "Ops Autopilot"),
3024
+ verdict: stringValue2(result.verdict),
3025
+ next_action: stringValue2(result.next_action ?? result.nextAction),
3026
+ nextAction: stringValue2(result.next_action ?? result.nextAction),
3027
+ primary_motion: primary,
3028
+ primaryMotion: primary,
3029
+ motions,
3030
+ scale_rule: optionalString(result.scale_rule ?? result.scaleRule),
3031
+ scaleRule: optionalString(result.scale_rule ?? result.scaleRule),
3032
+ agent_handoff: optionalString(result.agent_handoff ?? result.agentHandoff),
3033
+ agentHandoff: optionalString(result.agent_handoff ?? result.agentHandoff),
3034
+ proof_state: optionalString(result.proof_state ?? result.proofState),
3035
+ proofState: optionalString(result.proof_state ?? result.proofState),
3036
+ proof_summary: result.proof_summary ?? result.proofSummary,
3037
+ proofSummary: result.proof_summary ?? result.proofSummary,
3038
+ next_step: result.next_step ?? result.nextStep,
3039
+ nextStep: result.next_step ?? result.nextStep,
3040
+ query_errors: queryErrors,
3041
+ queryErrors,
3042
+ credits_charged: 0,
3043
+ creditsCharged: 0
3044
+ };
3045
+ }
3046
+ function normalizeOpsTriggerRunStatus(result) {
3047
+ const runId = result.run_id ?? result.runId;
3048
+ return {
3049
+ ...result,
3050
+ run_id: runId,
3051
+ runId,
3052
+ diagnosis: result.diagnosis ? normalizeOpsDebugDiagnosis(result.diagnosis) : void 0
3053
+ };
3054
+ }
3055
+ function normalizeOpsQueueStatus(result) {
3056
+ const summary = result.summary;
3057
+ const producerEnvelope = normalizeOpsQueueProducerEnvelope(result.producer_envelope ?? result.producerEnvelope);
3058
+ const job = result.job ? {
3059
+ ...result.job,
3060
+ id: result.job.id ?? result.job.jobId,
3061
+ jobId: result.job.jobId ?? result.job.id,
3062
+ function_name: result.job.function_name ?? result.job.functionName,
3063
+ functionName: result.job.functionName ?? result.job.function_name,
3064
+ estimated_wait_ms: result.job.estimated_wait_ms ?? result.job.estimatedWaitMs,
3065
+ estimatedWaitMs: result.job.estimatedWaitMs ?? result.job.estimated_wait_ms,
3066
+ error_message: result.job.error_message ?? result.job.errorMessage,
3067
+ errorMessage: result.job.errorMessage ?? result.job.error_message
3068
+ } : void 0;
3069
+ if (!summary) {
3070
+ return {
3071
+ ...result,
3072
+ producer_envelope: producerEnvelope,
3073
+ producerEnvelope,
3074
+ job,
3075
+ diagnosis: result.diagnosis ? normalizeOpsDebugDiagnosis(result.diagnosis) : void 0
3076
+ };
3077
+ }
3078
+ const queue = summary.queue;
3079
+ const normalizedQueue = queue ? {
3080
+ ...queue,
3081
+ completed_last_hour: queue.completed_last_hour ?? queue.completedLastHour,
3082
+ completedLastHour: queue.completedLastHour ?? queue.completed_last_hour,
3083
+ failed_last_hour: queue.failed_last_hour ?? queue.failedLastHour,
3084
+ failedLastHour: queue.failedLastHour ?? queue.failed_last_hour,
3085
+ pending_by_function: queue.pending_by_function ?? queue.pendingByFunction,
3086
+ pendingByFunction: queue.pendingByFunction ?? queue.pending_by_function
3087
+ } : void 0;
3088
+ return {
3089
+ ...result,
3090
+ producer_envelope: producerEnvelope,
3091
+ producerEnvelope,
3092
+ job,
3093
+ diagnosis: result.diagnosis ? normalizeOpsDebugDiagnosis(result.diagnosis) : void 0,
3094
+ summary: {
3095
+ ...summary,
3096
+ queue: normalizedQueue,
3097
+ provider_stats: summary.provider_stats ?? summary.providerStats,
3098
+ providerStats: summary.providerStats ?? summary.provider_stats,
3099
+ redis_status: summary.redis_status ?? summary.redisStatus,
3100
+ redisStatus: summary.redisStatus ?? summary.redis_status,
3101
+ recent_events: summary.recent_events ?? summary.recentEvents,
3102
+ recentEvents: summary.recentEvents ?? summary.recent_events
3103
+ }
3104
+ };
3105
+ }
3106
+ function normalizeOpsQueueProducerEnvelope(envelope) {
3107
+ if (!envelope) return void 0;
3108
+ return {
3109
+ ...envelope,
3110
+ schema_version: envelope.schema_version ?? envelope.schemaVersion,
3111
+ schemaVersion: envelope.schemaVersion ?? envelope.schema_version,
3112
+ queue_name: envelope.queue_name ?? envelope.queueName,
3113
+ queueName: envelope.queueName ?? envelope.queue_name,
3114
+ status_source: envelope.status_source ?? envelope.statusSource,
3115
+ statusSource: envelope.statusSource ?? envelope.status_source,
3116
+ idempotency_key: envelope.idempotency_key ?? envelope.idempotencyKey ?? null,
3117
+ idempotencyKey: envelope.idempotencyKey ?? envelope.idempotency_key ?? null,
3118
+ job_id: envelope.job_id ?? envelope.jobId ?? null,
3119
+ jobId: envelope.jobId ?? envelope.job_id ?? null,
3120
+ summary_requested: envelope.summary_requested ?? envelope.summaryRequested,
3121
+ summaryRequested: envelope.summaryRequested ?? envelope.summary_requested,
3122
+ retry_after_ms: envelope.retry_after_ms ?? envelope.retryAfterMs,
3123
+ retryAfterMs: envelope.retryAfterMs ?? envelope.retry_after_ms,
3124
+ poll_after_seconds: envelope.poll_after_seconds ?? envelope.pollAfterSeconds,
3125
+ pollAfterSeconds: envelope.pollAfterSeconds ?? envelope.poll_after_seconds,
3126
+ emitted_at: envelope.emitted_at ?? envelope.emittedAt,
3127
+ emittedAt: envelope.emittedAt ?? envelope.emitted_at
3128
+ };
3129
+ }
3130
+ function normalizeOpsReplayResult(result) {
3131
+ const replayRunId = result.replay_run_id ?? result.replayRunId ?? "";
3132
+ const originalRunId = result.original_run_id ?? result.originalRunId ?? "";
3133
+ const startFromNode = result.start_from_node ?? result.startFromNode ?? 0;
3134
+ const totalNodes = result.total_nodes ?? result.totalNodes ?? 0;
3135
+ return {
3136
+ ...result,
3137
+ replay_run_id: replayRunId,
3138
+ replayRunId,
3139
+ original_run_id: originalRunId,
3140
+ originalRunId,
3141
+ start_from_node: startFromNode,
3142
+ startFromNode,
3143
+ total_nodes: totalNodes,
3144
+ totalNodes,
3145
+ diagnosis: result.diagnosis ? normalizeOpsDebugDiagnosis(result.diagnosis) : void 0
3146
+ };
3147
+ }
3148
+ function normalizeOpsApproveResult(result) {
3149
+ return {
3150
+ ...result,
3151
+ token_id: result.token_id ?? result.tokenId,
3152
+ tokenId: result.tokenId ?? result.token_id,
3153
+ token_ids: result.token_ids ?? result.tokenIds,
3154
+ tokenIds: result.tokenIds ?? result.token_ids,
3155
+ reviewer_notes: result.reviewer_notes ?? result.reviewerNotes,
3156
+ reviewerNotes: result.reviewerNotes ?? result.reviewer_notes
3157
+ };
3158
+ }
3159
+ function normalizeOpsDashboardResult(result) {
3160
+ return {
3161
+ ...result,
3162
+ today_executions: result.today_executions ?? result.todayExecutions,
3163
+ todayExecutions: result.todayExecutions ?? result.today_executions,
3164
+ today_credits: result.today_credits ?? result.todayCredits,
3165
+ todayCredits: result.todayCredits ?? result.today_credits,
3166
+ month_executions: result.month_executions ?? result.monthExecutions,
3167
+ monthExecutions: result.monthExecutions ?? result.month_executions,
3168
+ month_credits: result.month_credits ?? result.monthCredits,
3169
+ monthCredits: result.monthCredits ?? result.month_credits,
3170
+ avg_execution_time_ms: result.avg_execution_time_ms ?? result.avgExecutionTimeMs,
3171
+ avgExecutionTimeMs: result.avgExecutionTimeMs ?? result.avg_execution_time_ms
3172
+ };
3173
+ }
3174
+ function normalizeOpsSink(sink) {
3175
+ return {
3176
+ ...sink,
3177
+ id: sink.id ?? sink.sink_id ?? sink.sinkId,
3178
+ sink_id: sink.sink_id ?? sink.sinkId ?? sink.id,
3179
+ sinkId: sink.sinkId ?? sink.sink_id ?? sink.id,
3180
+ connection_id: sink.connection_id ?? sink.connectionId,
3181
+ connectionId: sink.connectionId ?? sink.connection_id,
3182
+ connector_id: sink.connector_id ?? sink.connectorId,
3183
+ connectorId: sink.connectorId ?? sink.connector_id,
3184
+ sync_status: sink.sync_status ?? sink.syncStatus,
3185
+ syncStatus: sink.syncStatus ?? sink.sync_status,
3186
+ last_synced_at: sink.last_synced_at ?? sink.lastSyncedAt,
3187
+ lastSyncedAt: sink.lastSyncedAt ?? sink.last_synced_at
3188
+ };
3189
+ }
3190
+ function normalizeOpsRoutine(routine) {
3191
+ const outputSinks = routine.output_sinks ?? routine.outputSinks;
3192
+ return withExecutionRefs({
3193
+ ...routine,
3194
+ id: routine.id ?? routine.routine_id ?? routine.routineId,
3195
+ routine_id: routine.routine_id ?? routine.routineId ?? routine.id,
3196
+ routineId: routine.routineId ?? routine.routine_id ?? routine.id,
3197
+ last_tick_at: routine.last_tick_at ?? routine.lastTickAt,
3198
+ lastTickAt: routine.lastTickAt ?? routine.last_tick_at,
3199
+ next_tick_at: routine.next_tick_at ?? routine.nextTickAt,
3200
+ nextTickAt: routine.nextTickAt ?? routine.next_tick_at,
3201
+ output_sinks: outputSinks?.map(normalizeOpsSink),
3202
+ outputSinks: outputSinks?.map(normalizeOpsSink)
3203
+ });
3204
+ }
3205
+ function normalizeOpsRoutineRunResult(result) {
3206
+ return withExecutionRefs({
3207
+ ...result,
3208
+ routine_id: result.routine_id ?? result.routineId,
3209
+ routineId: result.routineId ?? result.routine_id,
3210
+ tick_id: result.tick_id ?? result.tickId,
3211
+ tickId: result.tickId ?? result.tick_id,
3212
+ run_id: result.run_id ?? result.runId,
3213
+ runId: result.runId ?? result.run_id,
3214
+ next_action: result.next_action ?? result.nextAction,
3215
+ nextAction: result.nextAction ?? result.next_action
3216
+ });
3217
+ }
3218
+ function normalizeOpsRoutineDeleteResult(result) {
3219
+ return withExecutionRefs({
3220
+ ...result,
3221
+ routine_id: result.routine_id ?? result.routineId,
3222
+ routineId: result.routineId ?? result.routine_id,
3223
+ next_action: result.next_action ?? result.nextAction,
3224
+ nextAction: result.nextAction ?? result.next_action
3225
+ });
3226
+ }
3227
+ function normalizeOpsRoutineSinkResult(result) {
3228
+ return withExecutionRefs({
3229
+ ...result,
3230
+ routine_id: result.routine_id ?? result.routineId,
3231
+ routineId: result.routineId ?? result.routine_id,
3232
+ sink_id: result.sink_id ?? result.sinkId,
3233
+ sinkId: result.sinkId ?? result.sink_id,
3234
+ next_action: result.next_action ?? result.nextAction,
3235
+ nextAction: result.nextAction ?? result.next_action,
3236
+ routine: result.routine ? normalizeOpsRoutine(result.routine) : result.routine,
3237
+ sink: result.sink ? normalizeOpsSink(result.sink) : result.sink
3238
+ });
3239
+ }
3240
+ function normalizeOpsRoutineTick(tick) {
3241
+ return withExecutionRefs({
3242
+ ...tick,
3243
+ id: tick.id ?? tick.tick_id ?? tick.tickId,
3244
+ tick_id: tick.tick_id ?? tick.tickId ?? tick.id,
3245
+ tickId: tick.tickId ?? tick.tick_id ?? tick.id,
3246
+ routine_id: tick.routine_id ?? tick.routineId,
3247
+ routineId: tick.routineId ?? tick.routine_id,
3248
+ started_at: tick.started_at ?? tick.startedAt,
3249
+ startedAt: tick.startedAt ?? tick.started_at,
3250
+ completed_at: tick.completed_at ?? tick.completedAt,
3251
+ completedAt: tick.completedAt ?? tick.completed_at,
3252
+ error_message: tick.error_message ?? tick.errorMessage,
3253
+ errorMessage: tick.errorMessage ?? tick.error_message
3254
+ });
3255
+ }
3256
+ function normalizeOpsRoutineTicksResult(result) {
3257
+ const ticks = Array.isArray(result.ticks ?? result.items) ? (result.ticks ?? result.items ?? []).map(normalizeOpsRoutineTick) : [];
3258
+ const nextCursor = result.next_cursor ?? result.nextCursor ?? null;
3259
+ const hasMore = result.has_more ?? result.hasMore ?? false;
3260
+ return {
3261
+ ...result,
3262
+ ticks,
3263
+ items: result.items ? ticks : result.items,
3264
+ next_cursor: nextCursor,
3265
+ nextCursor,
3266
+ has_more: hasMore,
3267
+ hasMore
3268
+ };
3269
+ }
3270
+ function normalizeOpsRoutineTickItem(item) {
3271
+ return withExecutionRefs({
3272
+ ...item,
3273
+ id: item.id ?? item.item_id ?? item.itemId,
3274
+ item_id: item.item_id ?? item.itemId ?? item.id,
3275
+ itemId: item.itemId ?? item.item_id ?? item.id,
3276
+ tick_id: item.tick_id ?? item.tickId,
3277
+ tickId: item.tickId ?? item.tick_id,
3278
+ routine_id: item.routine_id ?? item.routineId,
3279
+ routineId: item.routineId ?? item.routine_id,
3280
+ error_message: item.error_message ?? item.errorMessage,
3281
+ errorMessage: item.errorMessage ?? item.error_message
3282
+ });
3283
+ }
3284
+ function normalizeOpsRoutineTickItemsResult(result) {
3285
+ const items = Array.isArray(result.items ?? result.rows) ? (result.items ?? result.rows ?? []).map(normalizeOpsRoutineTickItem) : [];
3286
+ const nextCursor = result.next_cursor ?? result.nextCursor ?? null;
3287
+ const hasMore = result.has_more ?? result.hasMore ?? false;
3288
+ return {
3289
+ ...result,
3290
+ items,
3291
+ rows: result.rows ? items : result.rows,
3292
+ next_cursor: nextCursor,
3293
+ nextCursor,
3294
+ has_more: hasMore,
3295
+ hasMore
3296
+ };
3297
+ }
3298
+ function buildOpsPlanBody(params) {
3299
+ const { targetCount, companyDomains, customAiPrompt, signalPrompt, outputPrompt, ...rest } = params;
3300
+ return {
3301
+ ...rest,
3302
+ target_count: rest.target_count ?? targetCount,
3303
+ company_domains: rest.company_domains ?? companyDomains,
3304
+ custom_ai_prompt: rest.custom_ai_prompt ?? customAiPrompt,
3305
+ signal_prompt: rest.signal_prompt ?? signalPrompt,
3306
+ output_prompt: rest.output_prompt ?? outputPrompt
3307
+ };
3308
+ }
3309
+ function buildOpsCreateBody(params) {
3310
+ const { confirmSpend, ...rest } = params;
3311
+ return {
3312
+ ...buildOpsPlanBody(rest),
3313
+ confirm_spend: rest.confirm_spend ?? confirmSpend
3314
+ };
3315
+ }
3316
+ function buildOpsExecuteBody(params) {
3317
+ const { autoRun, dryRun, outputFormat, ...rest } = params;
3318
+ return {
3319
+ ...buildOpsCreateBody(rest),
3320
+ auto_run: rest.auto_run ?? autoRun,
3321
+ dry_run: rest.dry_run ?? dryRun,
3322
+ output_format: rest.output_format ?? outputFormat
3323
+ };
3324
+ }
3325
+ function buildOpsRunBody(params) {
3326
+ const { opId, ...rest } = params;
3327
+ return {
3328
+ ...rest,
3329
+ op_id: rest.op_id ?? opId
3330
+ };
3331
+ }
3332
+ function buildOpsStatusBody(params) {
3333
+ const { opId, ...rest } = params;
3334
+ return {
3335
+ ...rest,
3336
+ op_id: rest.op_id ?? opId
3337
+ };
3338
+ }
3339
+ function buildOpsResultsBody(params) {
3340
+ const { opId, nextCursor, includeFailedRuns, ...rest } = params;
3341
+ return {
3342
+ ...rest,
3343
+ op_id: rest.op_id ?? opId,
3344
+ cursor: rest.cursor ?? nextCursor,
3345
+ include_failed_runs: rest.include_failed_runs ?? includeFailedRuns
3346
+ };
3347
+ }
3348
+ function buildOpsDebugOptions(params) {
3349
+ const {
3350
+ opId,
3351
+ includeResults,
3352
+ resultsLimit,
3353
+ includeQueue,
3354
+ includeDashboard,
3355
+ dashboardLimit,
3356
+ timeRangeDays,
3357
+ ...rest
3358
+ } = params;
3359
+ const op_id = rest.op_id ?? opId;
3360
+ if (!op_id) throw new Error("ops.debug requires op_id or opId");
3361
+ return {
3362
+ ...rest,
3363
+ op_id,
3364
+ include_results: rest.include_results ?? includeResults,
3365
+ results_limit: rest.results_limit ?? resultsLimit,
3366
+ include_queue: rest.include_queue ?? includeQueue,
3367
+ include_dashboard: rest.include_dashboard ?? includeDashboard,
3368
+ dashboard_limit: rest.dashboard_limit ?? dashboardLimit,
3369
+ time_range_days: rest.time_range_days ?? timeRangeDays
3370
+ };
3371
+ }
3372
+ function buildCreateRoutineBody(params) {
3373
+ const { outputSinks, wakeOnEvents, ...rest } = params;
3374
+ const sinks = rest.output_sinks ?? outputSinks;
3375
+ return {
3376
+ ...rest,
3377
+ output_sinks: Array.isArray(sinks) ? sinks.map(normalizeOpsSinkRequest) : sinks,
3378
+ wake_on_events: rest.wake_on_events ?? wakeOnEvents
3379
+ };
3380
+ }
3381
+ function buildRoutineBody(params) {
3382
+ const { routineId, ...rest } = params;
3383
+ return {
3384
+ ...rest,
3385
+ routine_id: rest.routine_id ?? routineId
3386
+ };
3387
+ }
3388
+ function buildRoutineSinkBody(params) {
3389
+ const { routineId, sinkId, ...rest } = params;
3390
+ return {
3391
+ ...rest,
3392
+ routine_id: rest.routine_id ?? routineId,
3393
+ sink_id: rest.sink_id ?? sinkId
3394
+ };
3395
+ }
3396
+ function buildListOutputSinksBody(params) {
3397
+ const { includeInactive, ...rest } = params;
3398
+ return {
3399
+ ...rest,
3400
+ include_inactive: rest.include_inactive ?? includeInactive
3401
+ };
3402
+ }
3403
+ function buildCreateOutputSinkBody(params) {
3404
+ const { connectionId, webhookUrl, ...rest } = params;
3405
+ return {
3406
+ ...rest,
3407
+ connection_id: rest.connection_id ?? connectionId,
3408
+ webhook_url: rest.webhook_url ?? webhookUrl
3409
+ };
3410
+ }
3411
+ function normalizeOpsSinkRequest(sink) {
3412
+ const {
3413
+ sinkId,
3414
+ connectionId,
3415
+ connectorId,
3416
+ connectorName,
3417
+ deliveryMode,
3418
+ providerConfigKey,
3419
+ integrationId,
3420
+ nangoConnectionId,
3421
+ actionName,
3422
+ nangoAction,
3423
+ proxyPath,
3424
+ nangoProxyPath,
3425
+ fieldMap,
3426
+ requiredFields,
3427
+ writeConfirmed,
3428
+ agentWriteConfirmed,
3429
+ config,
3430
+ ...rest
3431
+ } = sink;
3432
+ const normalizedConfig = normalizeOpsSinkConfigRequest(config);
3433
+ const connection_id = rest.connection_id ?? connectionId;
3434
+ const connector_id = rest.connector_id ?? connectorId;
3435
+ const delivery_mode = rest.delivery_mode ?? deliveryMode;
3436
+ const provider_config_key = rest.provider_config_key ?? providerConfigKey;
3437
+ const integration_id = rest.integration_id ?? integrationId;
3438
+ const nango_connection_id = rest.nango_connection_id ?? nangoConnectionId;
3439
+ const action_name = rest.action_name ?? actionName;
3440
+ const nango_action = rest.nango_action ?? nangoAction;
3441
+ const proxy_path = rest.proxy_path ?? proxyPath;
3442
+ const nango_proxy_path = rest.nango_proxy_path ?? nangoProxyPath;
3443
+ const field_map = rest.field_map ?? fieldMap;
3444
+ const required_fields = rest.required_fields ?? requiredFields;
3445
+ const write_confirmed = rest.write_confirmed ?? writeConfirmed;
3446
+ const agent_write_confirmed = rest.agent_write_confirmed ?? agentWriteConfirmed;
3447
+ if (connection_id !== void 0 && normalizedConfig.connection_id === void 0) normalizedConfig.connection_id = connection_id;
3448
+ if (connector_id !== void 0 && normalizedConfig.connector_id === void 0) normalizedConfig.connector_id = connector_id;
3449
+ if (delivery_mode !== void 0 && normalizedConfig.delivery_mode === void 0) normalizedConfig.delivery_mode = delivery_mode;
3450
+ if (provider_config_key !== void 0 && normalizedConfig.provider_config_key === void 0) normalizedConfig.provider_config_key = provider_config_key;
3451
+ if (integration_id !== void 0 && normalizedConfig.integration_id === void 0) normalizedConfig.integration_id = integration_id;
3452
+ if (nango_connection_id !== void 0 && normalizedConfig.nango_connection_id === void 0) normalizedConfig.nango_connection_id = nango_connection_id;
3453
+ if (action_name !== void 0 && normalizedConfig.action_name === void 0) normalizedConfig.action_name = action_name;
3454
+ if (nango_action !== void 0 && normalizedConfig.nango_action === void 0) normalizedConfig.nango_action = nango_action;
3455
+ if (proxy_path !== void 0 && normalizedConfig.proxy_path === void 0) normalizedConfig.proxy_path = proxy_path;
3456
+ if (nango_proxy_path !== void 0 && normalizedConfig.nango_proxy_path === void 0) normalizedConfig.nango_proxy_path = nango_proxy_path;
3457
+ if (field_map !== void 0 && normalizedConfig.field_map === void 0) normalizedConfig.field_map = field_map;
3458
+ if (required_fields !== void 0 && normalizedConfig.required_fields === void 0) normalizedConfig.required_fields = required_fields;
3459
+ if (write_confirmed !== void 0 && normalizedConfig.write_confirmed === void 0) normalizedConfig.write_confirmed = write_confirmed;
3460
+ if (agent_write_confirmed !== void 0 && normalizedConfig.agent_write_confirmed === void 0) normalizedConfig.agent_write_confirmed = agent_write_confirmed;
3461
+ if (sink.type === "nango" && normalizedConfig.integration_platform === void 0) normalizedConfig.integration_platform = "nango";
3462
+ return {
3463
+ ...rest,
3464
+ sink_id: rest.sink_id ?? sinkId,
3465
+ connection_id,
3466
+ connector_id,
3467
+ connector_name: rest.connector_name ?? connectorName,
3468
+ delivery_mode,
3469
+ provider_config_key,
3470
+ integration_id,
3471
+ nango_connection_id,
3472
+ action_name,
3473
+ nango_action,
3474
+ proxy_path,
3475
+ nango_proxy_path,
3476
+ field_map,
3477
+ required_fields,
3478
+ write_confirmed,
3479
+ agent_write_confirmed,
3480
+ config: normalizedConfig
3481
+ };
3482
+ }
3483
+ function normalizeOpsSinkConfigRequest(config) {
3484
+ const out = { ...config ?? {} };
3485
+ if (out.connection_id === void 0 && out.connectionId !== void 0) out.connection_id = out.connectionId;
3486
+ if (out.connector_id === void 0 && out.connectorId !== void 0) out.connector_id = out.connectorId;
3487
+ if (out.connector_name === void 0 && out.connectorName !== void 0) out.connector_name = out.connectorName;
3488
+ if (out.delivery_mode === void 0 && out.deliveryMode !== void 0) out.delivery_mode = out.deliveryMode;
3489
+ if (out.provider_config_key === void 0 && out.providerConfigKey !== void 0) out.provider_config_key = out.providerConfigKey;
3490
+ if (out.integration_id === void 0 && out.integrationId !== void 0) out.integration_id = out.integrationId;
3491
+ if (out.nango_connection_id === void 0 && out.nangoConnectionId !== void 0) out.nango_connection_id = out.nangoConnectionId;
3492
+ if (out.action_name === void 0 && out.actionName !== void 0) out.action_name = out.actionName;
3493
+ if (out.nango_action === void 0 && out.nangoAction !== void 0) out.nango_action = out.nangoAction;
3494
+ if (out.proxy_path === void 0 && out.proxyPath !== void 0) out.proxy_path = out.proxyPath;
3495
+ if (out.nango_proxy_path === void 0 && out.nangoProxyPath !== void 0) out.nango_proxy_path = out.nangoProxyPath;
3496
+ if (out.field_map === void 0 && out.fieldMap !== void 0) out.field_map = out.fieldMap;
3497
+ if (out.required_fields === void 0 && out.requiredFields !== void 0) out.required_fields = out.requiredFields;
3498
+ if (out.write_confirmed === void 0 && out.writeConfirmed !== void 0) out.write_confirmed = out.writeConfirmed;
3499
+ if (out.agent_write_confirmed === void 0 && out.agentWriteConfirmed !== void 0) out.agent_write_confirmed = out.agentWriteConfirmed;
3500
+ return out;
3501
+ }
3502
+ function buildApproveBody(params) {
3503
+ const { tokenId, tokenIds, reviewerNotes, ...rest } = params;
3504
+ return {
3505
+ ...rest,
3506
+ token_id: rest.token_id ?? tokenId,
3507
+ token_ids: rest.token_ids ?? tokenIds,
3508
+ reviewer_notes: rest.reviewer_notes ?? reviewerNotes
3509
+ };
3510
+ }
3511
+ function buildDebugNextActions(status, refs, errors) {
3512
+ const actions = /* @__PURE__ */ new Set();
3513
+ if (status.next_action) actions.add(status.next_action);
3514
+ for (const ref of refs) {
3515
+ if (ref.status_command) actions.add(ref.status_command);
3516
+ if (ref.replay_command) actions.add(ref.replay_command);
3517
+ }
3518
+ if (errors.length > 0) actions.add("Review diagnostic_errors before replaying or changing the Op prompt.");
3519
+ if (refs.some((ref) => ref.kind === "queue_job")) actions.add("Inspect queue pressure before retrying provider-backed work.");
3520
+ return Array.from(actions);
3521
+ }
3522
+ function buildDebugDiagnosis(status, runStatuses, queue, errors) {
3523
+ const backendDiagnosis = status.diagnosis ? normalizeOpsDebugDiagnosis(status.diagnosis) : void 0;
3524
+ const queueSummary = queue?.summary?.queue ?? queue?.queue;
3525
+ const queuePending = queueSummary?.pending ?? 0;
3526
+ const queueProcessing = queueSummary?.processing ?? 0;
3527
+ const queueFailedLastHour = queue?.summary?.queue?.failed_last_hour ?? queue?.summary?.queue?.failedLastHour ?? 0;
3528
+ const failedRuns = runStatuses.filter((run) => /fail|error|cancel/i.test(run.status || ""));
3529
+ const primaryRunError = failedRuns.map((run) => run.error).find((error) => error !== void 0);
3530
+ const primaryError = errors[0]?.message || stringifyDebugError(primaryRunError);
3531
+ const providerPressure = queuePending >= 100 ? "high" : queuePending >= 10 ? "medium" : queuePending > 0 || queueProcessing > 0 ? "low" : "none";
3532
+ const statusText = `${status.status || ""} ${status.phase || ""}`.toLowerCase();
3533
+ const state = errors.length > 0 ? "degraded" : failedRuns.length > 0 || statusText.includes("failed") || statusText.includes("error") ? "failed" : statusText.includes("running") || statusText.includes("pending") || statusText.includes("queued") || queueProcessing > 0 ? "running" : statusText.includes("complete") || statusText.includes("success") ? "healthy" : backendDiagnosis?.state ?? "unknown";
3534
+ const retryable = state === "failed" && (failedRuns.length > 0 || backendDiagnosis?.retryable === true || Boolean(status.execution_refs?.some((ref) => ref.replay_command)));
3535
+ const summary = [
3536
+ `State ${state}`,
3537
+ `retry ${retryable ? "available" : "not indicated"}`,
3538
+ `queue ${queuePending} pending/${queueProcessing} processing`,
3539
+ `provider pressure ${providerPressure}`
3540
+ ].join("; ");
3541
+ return {
3542
+ state,
3543
+ retryable,
3544
+ queue_pending: queuePending,
3545
+ queue_processing: queueProcessing,
3546
+ queue_failed_last_hour: queueFailedLastHour,
3547
+ provider_pressure: providerPressure,
3548
+ failed_run_count: failedRuns.length || backendDiagnosis?.failed_run_count || 0,
3549
+ primary_error: primaryError ?? backendDiagnosis?.primary_error,
3550
+ summary
3551
+ };
3552
+ }
3553
+ function stringifyDebugError(error) {
3554
+ if (error === void 0 || error === null) return void 0;
3555
+ if (typeof error === "string") return error;
3556
+ if (error instanceof Error) return error.message;
3557
+ try {
3558
+ return JSON.stringify(error);
3559
+ } catch {
3560
+ return String(error);
3561
+ }
3562
+ }
3563
+
3564
+ // src/resources/ai.ts
3565
+ function toSnakeConfig(params) {
3566
+ return {
3567
+ system_prompt: params.systemPrompt || params.system_prompt || "You are a senior business research analyst. Use multi-model evidence carefully and return concise structured enrichment.",
3568
+ user_template: params.userTemplate || params.user_template || params.prompt,
3569
+ model: params.model,
3570
+ temperature: params.temperature,
3571
+ max_concurrency: params.maxConcurrency || params.max_concurrency,
3572
+ max_tokens: params.maxTokens || params.max_tokens,
3573
+ output_fields: params.outputFields || params.output_fields || [{ name: "response", type: "text", description: "Structured enrichment result" }],
3574
+ attachments: params.attachments,
3575
+ attachment_fields: params.attachmentFields || params.attachment_fields,
3576
+ pdf_engine: params.pdfEngine || params.pdf_engine,
3577
+ fusion: params.fusion
3578
+ };
3579
+ }
3580
+ function recordsFromParams(params) {
3581
+ const records = params.records || params.inputs;
3582
+ if (records?.length) return { records };
3583
+ if (params.input) return { input: params.input };
3584
+ return { input: {} };
3585
+ }
3586
+ var Ai = class {
3587
+ constructor(client) {
3588
+ this.client = client;
3589
+ }
3590
+ /**
3591
+ * Run Custom AI Enrichment - Multi Model.
3592
+ *
3593
+ * Uses OpenRouter Fusion for multi-model analysis with web search/fetch enabled
3594
+ * inside Fusion, then synthesizes the requested structured output fields.
3595
+ */
3596
+ async multiModel(params) {
3597
+ if (!params.model) {
3598
+ throw new Error('model is required. Use an OpenRouter id such as "anthropic/claude-sonnet-4" or "google/gemini-2.5-flash".');
3599
+ }
3600
+ if (!params.prompt && !params.userTemplate && !params.user_template) {
3601
+ throw new Error("prompt or userTemplate is required.");
3602
+ }
3603
+ const data = await this.client.post("custom-ai-multi-model", {
3604
+ ...recordsFromParams(params),
3605
+ config: toSnakeConfig(params)
3606
+ });
3607
+ return {
3608
+ success: data.success ?? false,
3609
+ capability: data.capability ?? "custom_ai_multi_model",
3610
+ displayName: data.display_name ?? "Custom AI Enrichment - Multi Model",
3611
+ results: data.results ?? [],
3612
+ creditsUsed: data.total_credits_used ?? data.credits_used ?? 0,
3613
+ model: data.model,
3614
+ fusion: data.fusion,
3615
+ multimodalCount: data.multimodal_count ?? 0,
3616
+ tokensUsed: data.tokens_used ?? 0,
3617
+ costUsd: data.cost_usd ?? 0,
3618
+ billingMetadata: data.billing_metadata,
3619
+ raw: data
3620
+ };
3621
+ }
3622
+ };
3623
+
3624
+ // src/resources/gtm-kernel.ts
3625
+ var GtmKernel = class {
3626
+ constructor(client) {
3627
+ this.client = client;
3628
+ }
3629
+ /** Load workspace context for an agent session: campaigns, memory, Brain, connections, and Signaliz primitives. */
3630
+ async context(options = {}) {
3631
+ return this.callMcp("gtm_workspace_context", {
3632
+ include_campaigns: options.includeCampaigns,
3633
+ include_memory: options.includeMemory,
3634
+ include_brain: options.includeBrain,
3635
+ include_connections: options.includeConnections,
3636
+ limit: options.limit
3637
+ });
3638
+ }
3639
+ /** Inspect whether the workspace has the Kernel + Brain substrate pieces needed to build, run, and improve campaigns. */
3640
+ async bootstrapStatus(options = {}) {
3641
+ return this.callMcp("gtm_workspace_bootstrap_status", {
3642
+ campaign_id: options.campaignId,
3643
+ days: options.days,
3644
+ min_sample_size: options.minSampleSize,
3645
+ include_connections: options.includeConnections,
3646
+ include_samples: options.includeSamples,
3647
+ limit: options.limit
3648
+ });
3649
+ }
3650
+ /** Discover existing provider campaigns, starting with live/Kernel-linked Instantly campaigns, before audit or import preview. */
3651
+ async discoverExistingCampaigns(options = {}) {
3652
+ return this.callMcp("gtm_existing_campaign_discover", {
3653
+ provider: options.provider,
3654
+ integration_id: options.integrationId,
3655
+ search: options.search,
3656
+ limit: options.limit,
3657
+ include_kernel_linked: options.includeKernelLinked,
3658
+ include_provider_live: options.includeProviderLive
3659
+ });
3660
+ }
3661
+ /** Run a read-only existing campaign audit with completeness, recommendations, safe next MCP JSON, and approval boundaries. */
3662
+ async auditExistingCampaign(options) {
3663
+ return this.callMcp("gtm_existing_campaign_audit", {
3664
+ campaign_id: options.campaignId,
3665
+ provider: options.provider,
3666
+ provider_campaign_id: options.providerCampaignId,
3667
+ campaign_name: options.campaignName,
3668
+ days: options.days,
3669
+ include_route_preview: options.includeRoutePreview,
3670
+ include_memory: options.includeMemory,
3671
+ include_brain: options.includeBrain
3672
+ });
3673
+ }
3674
+ /** Discover the first matching existing provider campaign, then run the same read-only audit against that match. */
3675
+ async auditExistingCampaignBySearch(options) {
3676
+ const discovery = await this.discoverExistingCampaigns({
3677
+ provider: options.provider,
3678
+ integrationId: options.integrationId,
3679
+ search: options.search,
3680
+ limit: 1,
3681
+ includeKernelLinked: options.includeKernelLinked,
3682
+ includeProviderLive: options.includeProviderLive
3683
+ });
3684
+ const match = discovery.campaigns?.[0];
3685
+ const campaignId = match?.linked_kernel_campaign_id || void 0;
3686
+ const providerCampaignId = match?.provider_campaign_id || void 0;
3687
+ if (!campaignId && !providerCampaignId) {
3688
+ throw new Error(`No existing ${options.provider || discovery.provider || "provider"} campaign matched "${options.search}"`);
3689
+ }
3690
+ return this.auditExistingCampaign({
3691
+ provider: options.provider || discovery.provider || match?.provider,
3692
+ campaignId,
3693
+ providerCampaignId,
3694
+ campaignName: match?.name || match?.linked_kernel_campaign_name || void 0,
3695
+ days: options.days,
3696
+ includeRoutePreview: options.includeRoutePreview,
3697
+ includeMemory: options.includeMemory,
3698
+ includeBrain: options.includeBrain
3699
+ });
3700
+ }
3701
+ /** Create a first-class GTM campaign object in the current workspace. */
3702
+ async createCampaign(input) {
3703
+ return this.callMcp("gtm_campaign_create", campaignCreateArgs(input));
3704
+ }
3705
+ /** Backfill historical campaigns, provider links, feedback, and memory into the GTM Kernel substrate. */
3706
+ async importCampaignHistory(input) {
3707
+ return this.callMcp("gtm_campaign_history_import", {
3708
+ source: input.source,
3709
+ dry_run: input.dryRun,
3710
+ create_memory: input.createMemory,
3711
+ campaigns: input.campaigns.map(campaignHistoryImportCampaignArgs)
3712
+ });
3713
+ }
3714
+ /** Queue a Trigger-backed campaign history import for larger CMM/client backfills. */
3715
+ async importCampaignHistoryRun(input) {
3716
+ return this.callMcp("gtm_campaign_history_import_run", {
3717
+ source: input.source,
3718
+ dry_run: input.dryRun,
3719
+ create_memory: input.createMemory,
3720
+ campaigns: input.campaigns?.map(campaignHistoryImportCampaignArgs),
3721
+ batches: input.batches?.map((batch) => ({
3722
+ batch_id: batch.batchId,
3723
+ campaigns: batch.campaigns.map(campaignHistoryImportCampaignArgs)
3724
+ })),
3725
+ batch_size: input.batchSize,
3726
+ continue_on_error: input.continueOnError,
3727
+ run_brain_cycle: input.runBrainCycle,
3728
+ brain_cycle_write_mode: input.brainCycleWriteMode,
3729
+ brain_cycle_phases: input.brainCyclePhases,
3730
+ brain_cycle_days: input.brainCycleDays,
3731
+ brain_cycle_network_days: input.brainCycleNetworkDays,
3732
+ brain_cycle_min_sample_size: input.brainCycleMinSampleSize,
3733
+ brain_cycle_limit: input.brainCycleLimit
3734
+ });
3735
+ }
3736
+ /** Preview a provider-neutral history import payload derived from an existing campaign build. */
3737
+ async previewCampaignBuildBackfill(options) {
3738
+ return this.callMcp("gtm_campaign_build_backfill_preview", {
3739
+ campaign_build_id: options.campaignBuildId,
3740
+ include_sample_rows: options.includeSampleRows,
3741
+ include_copy_samples: options.includeCopySamples,
3742
+ sample_row_limit: options.sampleRowLimit,
3743
+ create_memory: options.createMemory,
3744
+ include_payload: options.includePayload
3745
+ });
3746
+ }
3747
+ /** Queue campaign-build history backfills through the Trigger-backed history import runner. */
3748
+ async runCampaignBuildBackfill(input) {
3749
+ return this.callMcp("gtm_campaign_build_backfill_run", {
3750
+ campaign_build_ids: input.campaignBuildIds,
3751
+ source: input.source,
3752
+ dry_run: input.dryRun,
3753
+ create_memory: input.createMemory,
3754
+ include_sample_rows: input.includeSampleRows,
3755
+ include_copy_samples: input.includeCopySamples,
3756
+ include_payload: input.includePayload,
3757
+ sample_row_limit: input.sampleRowLimit,
3758
+ batch_size: input.batchSize,
3759
+ continue_on_error: input.continueOnError,
3760
+ run_brain_cycle: input.runBrainCycle,
3761
+ brain_cycle_write_mode: input.brainCycleWriteMode,
3762
+ brain_cycle_phases: input.brainCyclePhases,
3763
+ brain_cycle_days: input.brainCycleDays,
3764
+ brain_cycle_network_days: input.brainCycleNetworkDays,
3765
+ brain_cycle_min_sample_size: input.brainCycleMinSampleSize,
3766
+ brain_cycle_limit: input.brainCycleLimit
3767
+ });
3768
+ }
3769
+ /** Inspect Campaign Builder to Kernel backfill status for one build. */
3770
+ async campaignBuildBackfillStatus(options) {
3771
+ return this.callMcp("gtm_campaign_build_backfill_status", {
3772
+ campaign_build_id: options.campaignBuildId,
3773
+ include_phases: options.includePhases,
3774
+ include_linked_campaign: options.includeLinkedCampaign
3775
+ });
3776
+ }
3777
+ /** List first-class GTM campaign objects in the current workspace. */
3778
+ async listCampaigns(options = {}) {
3779
+ return this.callMcp("gtm_campaign_list", {
3780
+ status: options.status,
3781
+ provider: options.provider,
3782
+ search: options.search,
3783
+ limit: options.limit,
3784
+ include_archived: options.includeArchived
3785
+ });
3786
+ }
3787
+ /** Get one campaign with provider links, logs, feedback summary, memory, and Brain patterns. */
3788
+ async getCampaign(campaignId, options = {}) {
3789
+ return this.callMcp("gtm_campaign_get", {
3790
+ campaign_id: campaignId,
3791
+ log_limit: options.logLimit,
3792
+ memory_limit: options.memoryLimit
3793
+ });
3794
+ }
3795
+ /** Inspect campaign execution state, linked build progress, provider readiness, feedback, memory, and next actions. */
3796
+ async campaignExecutionStatus(options) {
3797
+ return this.callMcp("gtm_campaign_execution_status", {
3798
+ campaign_id: options.campaignId,
3799
+ campaign_build_id: options.campaignBuildId,
3800
+ include_provider_readiness: options.includeProviderReadiness,
3801
+ include_feedback: options.includeFeedback,
3802
+ include_memory: options.includeMemory,
3803
+ include_recent_log: options.includeRecentLog,
3804
+ log_limit: options.logLimit,
3805
+ memory_limit: options.memoryLimit
3806
+ });
3807
+ }
3808
+ /** Inspect whether a campaign/build is ready for Brain learning and return exact learning-cycle args. */
3809
+ async campaignLearningStatus(options) {
3810
+ return this.callMcp("gtm_campaign_learning_status", {
3811
+ campaign_id: options.campaignId,
3812
+ campaign_build_id: options.campaignBuildId,
3813
+ days: options.days,
3814
+ network_days: options.networkDays,
3815
+ min_sample_size: options.minSampleSize,
3816
+ min_workspace_count: options.minWorkspaceCount,
3817
+ min_privacy_k: options.minPrivacyK,
3818
+ include_memory: options.includeMemory,
3819
+ include_network: options.includeNetwork,
3820
+ write_mode: options.writeMode,
3821
+ limit: options.limit
3822
+ });
3823
+ }
3824
+ /** Update a first-class GTM campaign and append the associated campaign log entry. */
3825
+ async updateCampaign(input) {
3826
+ return this.callMcp("gtm_campaign_update", campaignUpdateArgs(input));
3827
+ }
3828
+ /** Append an auditable campaign action with actor, rationale, payload, and optional idempotency key. */
3829
+ async logCampaign(campaignId, input) {
3830
+ return this.callMcp("gtm_campaign_log", campaignLogArgs({ ...input, campaignId }));
3831
+ }
3832
+ /** Ingest provider-neutral feedback from Instantly, Smartlead, HeyReach, webhook, or a custom MCP. */
3833
+ async ingestFeedback(input) {
3834
+ return this.callMcp("gtm_feedback_ingest", {
3835
+ source: input.source,
3836
+ campaign_id: input.campaignId,
3837
+ campaign_build_id: input.campaignBuildId,
3838
+ provider_campaign_id: input.providerCampaignId,
3839
+ events: input.events,
3840
+ provider_payload: input.providerPayload,
3841
+ create_memory: input.createMemory,
3842
+ write_routine_outcomes: input.writeRoutineOutcomes
3843
+ });
3844
+ }
3845
+ /** Normalize Instantly webhook/pull payloads and ingest row-level feedback through the GTM Kernel. */
3846
+ async syncInstantlyFeedback(input) {
3847
+ return this.callMcp("gtm_instantly_feedback_sync", {
3848
+ campaign_id: input.campaignId,
3849
+ campaign_build_id: input.campaignBuildId,
3850
+ provider_campaign_id: input.providerCampaignId,
3851
+ instantly_campaign_id: input.instantlyCampaignId,
3852
+ sync_mode: input.syncMode,
3853
+ events: input.events,
3854
+ provider_payload: input.providerPayload,
3855
+ cursor: input.cursor,
3856
+ since: input.since,
3857
+ until: input.until,
3858
+ aggregate_snapshot: input.aggregateSnapshot,
3859
+ create_memory: input.createMemory,
3860
+ write_routine_outcomes: input.writeRoutineOutcomes
3861
+ });
3862
+ }
3863
+ /** Start a background Instantly webhook-events pull and route results into the GTM feedback loop. */
3864
+ async pullInstantlyFeedback(input) {
3865
+ return this.callMcp("gtm_instantly_feedback_pull", {
3866
+ campaign_id: input.campaignId,
3867
+ campaign_build_id: input.campaignBuildId,
3868
+ provider_link_id: input.providerLinkId,
3869
+ provider_campaign_id: input.providerCampaignId,
3870
+ instantly_campaign_id: input.instantlyCampaignId,
3871
+ integration_id: input.integrationId,
3872
+ cursor: input.cursor,
3873
+ from: input.from,
3874
+ to: input.to,
3875
+ limit: input.limit,
3876
+ max_pages: input.maxPages,
3877
+ create_memory: input.createMemory,
3878
+ write_routine_outcomes: input.writeRoutineOutcomes,
3879
+ dry_run: input.dryRun,
3880
+ run_brain_cycle: input.runBrainCycle,
3881
+ brain_cycle_write_mode: input.brainCycleWriteMode,
3882
+ brain_cycle_phases: input.brainCyclePhases,
3883
+ brain_cycle_min_ingested: input.brainCycleMinIngested,
3884
+ brain_cycle_min_interval_minutes: input.brainCycleMinIntervalMinutes
3885
+ });
3886
+ }
3887
+ /** Prepare a secure Instantly feedback webhook URL for a campaign provider link. */
3888
+ async prepareInstantlyFeedbackWebhook(input) {
3889
+ return this.callMcp("gtm_instantly_feedback_webhook_prepare", {
3890
+ campaign_id: input.campaignId,
3891
+ campaign_build_id: input.campaignBuildId,
3892
+ provider_link_id: input.providerLinkId,
3893
+ provider_campaign_id: input.providerCampaignId,
3894
+ instantly_campaign_id: input.instantlyCampaignId,
3895
+ integration_id: input.integrationId,
3896
+ provider_workspace_id: input.providerWorkspaceId,
3897
+ provider_account_id: input.providerAccountId,
3898
+ rotate_secret: input.rotateSecret,
3899
+ run_brain_cycle: input.runBrainCycle,
3900
+ brain_cycle_write_mode: input.brainCycleWriteMode,
3901
+ brain_cycle_phases: input.brainCyclePhases,
3902
+ brain_cycle_min_ingested: input.brainCycleMinIngested,
3903
+ brain_cycle_min_interval_minutes: input.brainCycleMinIntervalMinutes
3904
+ });
3905
+ }
3906
+ /** Preview anonymized Instantly workspace sources registered for Kernel import. */
3907
+ async previewKernelImport(input = {}) {
3908
+ return this.callMcp("gtm_kernel_import_preview", {
3909
+ source_ids: input.sourceIds,
3910
+ include_leads: input.includeLeads,
3911
+ include_replies: input.includeReplies,
3912
+ include_private_copy: input.includePrivateCopy,
3913
+ max_pages: input.maxPages,
3914
+ limit: input.limit
3915
+ });
3916
+ }
3917
+ /** Queue the read-only Instantly-to-GTM Kernel import. Live writes require writeApproved. */
3918
+ async runKernelImport(input = {}) {
3919
+ return this.callMcp("gtm_kernel_import_run", {
3920
+ source_ids: input.sourceIds,
3921
+ dry_run: input.dryRun,
3922
+ write_approved: input.writeApproved,
3923
+ include_leads: input.includeLeads,
3924
+ include_replies: input.includeReplies,
3925
+ include_private_copy: input.includePrivateCopy,
3926
+ private_copy_approved: input.privateCopyApproved,
3927
+ promote_global_patterns: input.promoteGlobalPatterns,
3928
+ min_global_privacy_k: input.minGlobalPrivacyK,
3929
+ max_pages: input.maxPages,
3930
+ limit: input.limit
3931
+ });
3932
+ }
3933
+ /** Queue Brain distillation over imported Instantly memory with abstracted-only outputs. */
3934
+ async runBrainDistillation(input = {}) {
3935
+ return this.callMcp("gtm_brain_distill_run", {
3936
+ source_ids: input.sourceIds,
3937
+ write_mode: input.writeMode,
3938
+ write_approved: input.writeApproved,
3939
+ brain_cycle_phases: input.brainCyclePhases,
3940
+ days: input.days,
3941
+ network_days: input.networkDays,
3942
+ min_sample_size: input.minSampleSize,
3943
+ min_workspace_count: input.minWorkspaceCount,
3944
+ min_privacy_k: input.minPrivacyK
3945
+ });
3946
+ }
3947
+ /** Prepare a provider-agnostic feedback webhook URL for Smartlead, HeyReach, Airbyte, or custom sender events. */
3948
+ async prepareFeedbackWebhook(input) {
3949
+ return this.callMcp("gtm_feedback_webhook_prepare", {
3950
+ provider: input.provider,
3951
+ campaign_id: input.campaignId,
3952
+ campaign_build_id: input.campaignBuildId,
3953
+ provider_link_id: input.providerLinkId,
3954
+ provider_campaign_id: input.providerCampaignId,
3955
+ integration_id: input.integrationId,
3956
+ provider_workspace_id: input.providerWorkspaceId,
3957
+ provider_account_id: input.providerAccountId,
3958
+ rotate_secret: input.rotateSecret,
3959
+ run_brain_cycle: input.runBrainCycle,
3960
+ brain_cycle_write_mode: input.brainCycleWriteMode,
3961
+ brain_cycle_phases: input.brainCyclePhases,
3962
+ brain_cycle_min_ingested: input.brainCycleMinIngested,
3963
+ brain_cycle_min_interval_minutes: input.brainCycleMinIntervalMinutes
3964
+ });
3965
+ }
3966
+ /** Search ranked workspace campaign memory instead of dumping raw history. */
3967
+ async searchMemory(options = {}) {
3968
+ return this.callMcp("gtm_memory_search", {
3969
+ query: options.query,
3970
+ campaign_id: options.campaignId,
3971
+ memory_type: options.memoryType,
3972
+ keywords: options.keywords,
3973
+ outcome_type: options.outcomeType,
3974
+ target_icp: options.targetIcp,
3975
+ layers: options.layers,
3976
+ provider_chain: options.providerChain,
3977
+ dimension_filters: options.dimensionFilters,
3978
+ require_dimension_match: options.requireDimensionMatch,
3979
+ days: options.days,
3980
+ limit: options.limit
3981
+ });
3982
+ }
3983
+ /** Retrieve evidence-backed workspace and privacy-safe aggregate Brain patterns. */
3984
+ async brainPatterns(options = {}) {
3985
+ return this.callMcp("gtm_brain_patterns", {
3986
+ campaign_id: options.campaignId,
3987
+ pattern_type: options.patternType,
3988
+ segment_key: options.segmentKey,
3989
+ include_global: options.includeGlobal,
3990
+ min_confidence: options.minConfidence,
3991
+ limit: options.limit
3992
+ });
3993
+ }
3994
+ /** Plan the closed-loop Brain learning sequence without recursively executing Edge Functions. */
3995
+ async learningCyclePlan(input = {}) {
3996
+ return this.callMcp("gtm_brain_learning_cycle_plan", {
3997
+ campaign_id: input.campaignId,
3998
+ campaign_brief: input.campaignBrief,
3999
+ target_icp: input.targetIcp,
4000
+ layers: input.layers,
4001
+ provider_chain: input.providerChain,
4002
+ lead_source: input.leadSource,
4003
+ days: input.days,
4004
+ network_days: input.networkDays,
4005
+ min_sample_size: input.minSampleSize,
4006
+ min_workspace_count: input.minWorkspaceCount,
4007
+ min_privacy_k: input.minPrivacyK,
4008
+ include_memory: input.includeMemory,
4009
+ include_network: input.includeNetwork,
4010
+ write_mode: input.writeMode,
4011
+ limit: input.limit
4012
+ });
4013
+ }
4014
+ /** Queue the closed-loop Brain learning sequence in Trigger. */
4015
+ async learningCycleRun(input = {}) {
4016
+ return this.callMcp("gtm_brain_learning_cycle_run", {
4017
+ campaign_id: input.campaignId,
4018
+ campaign_brief: input.campaignBrief,
4019
+ target_icp: input.targetIcp,
4020
+ layers: input.layers,
4021
+ provider_chain: input.providerChain,
4022
+ lead_source: input.leadSource,
4023
+ days: input.days,
4024
+ network_days: input.networkDays,
4025
+ min_sample_size: input.minSampleSize,
4026
+ min_workspace_count: input.minWorkspaceCount,
4027
+ min_privacy_k: input.minPrivacyK,
4028
+ include_memory: input.includeMemory,
4029
+ include_network: input.includeNetwork,
4030
+ write_mode: input.writeMode,
4031
+ phases: input.phases,
4032
+ continue_on_error: input.continueOnError,
4033
+ limit: input.limit
4034
+ });
4035
+ }
4036
+ /** Seed campaign defaults from active Brain patterns and ranked workspace memory. */
4037
+ async seedBrainDefaults(input = {}) {
4038
+ return this.callMcp("gtm_brain_seed_defaults", {
4039
+ campaign_id: input.campaignId,
4040
+ campaign_brief: input.campaignBrief,
4041
+ target_icp: input.targetIcp,
4042
+ layers: input.layers,
4043
+ include_global: input.includeGlobal,
4044
+ include_memory: input.includeMemory,
4045
+ min_confidence: input.minConfidence,
4046
+ write_campaign: input.writeCampaign,
4047
+ limit: input.limit
4048
+ });
4049
+ }
4050
+ /** Extract within-workspace Brain V1 patterns from feedback, provider links, campaigns, and memory. */
4051
+ async extractBrainPatterns(input = {}) {
4052
+ return this.callMcp("gtm_brain_extract_patterns", {
4053
+ campaign_id: input.campaignId,
4054
+ days: input.days,
4055
+ pattern_types: input.patternTypes,
4056
+ min_sample_size: input.minSampleSize,
4057
+ include_memory: input.includeMemory,
4058
+ write_patterns: input.writePatterns,
4059
+ dry_run: input.dryRun,
4060
+ replace_existing: input.replaceExisting,
4061
+ limit: input.limit
4062
+ });
4063
+ }
4064
+ /** Aggregate opted-in workspace Brain patterns into privacy-safe global defaults. */
4065
+ async aggregateBrainPatterns(input = {}) {
4066
+ return this.callMcp("gtm_brain_aggregate_patterns", {
4067
+ days: input.days,
4068
+ pattern_types: input.patternTypes,
4069
+ min_workspace_count: input.minWorkspaceCount,
4070
+ min_privacy_k: input.minPrivacyK,
4071
+ min_confidence: input.minConfidence,
4072
+ include_low_confidence: input.includeLowConfidence,
4073
+ write_patterns: input.writePatterns,
4074
+ dry_run: input.dryRun,
4075
+ replace_existing: input.replaceExisting,
4076
+ limit: input.limit
4077
+ });
4078
+ }
4079
+ /** Aggregate opted-in workspace deliverability calibrations into privacy-safe global calibration rows. */
4080
+ async aggregateBrainCalibrations(input = {}) {
4081
+ return this.callMcp("gtm_brain_aggregate_calibrations", {
4082
+ days: input.days,
4083
+ dimension_types: input.dimensionTypes,
4084
+ min_workspace_count: input.minWorkspaceCount,
4085
+ min_privacy_k: input.minPrivacyK,
4086
+ min_confidence: input.minConfidence,
4087
+ include_low_confidence: input.includeLowConfidence,
4088
+ write_calibrations: input.writeCalibrations,
4089
+ dry_run: input.dryRun,
4090
+ replace_existing: input.replaceExisting,
4091
+ limit: input.limit
4092
+ });
4093
+ }
4094
+ /** Calibrate workspace deliverability predictions against actual bounce feedback. */
4095
+ async calibrateDeliverability(input = {}) {
4096
+ return this.callMcp("gtm_brain_calibrate_deliverability", {
4097
+ campaign_id: input.campaignId,
4098
+ days: input.days,
4099
+ dimension_types: input.dimensionTypes,
4100
+ min_sample_size: input.minSampleSize,
4101
+ dry_run: input.dryRun,
4102
+ write_calibrations: input.writeCalibrations,
4103
+ write_patterns: input.writePatterns,
4104
+ replace_existing: input.replaceExisting,
4105
+ limit: input.limit
4106
+ });
4107
+ }
4108
+ /** Estimate pre-send delivery risk from campaign context, lead samples, and Brain calibrations. */
4109
+ async deliveryRisk(input = {}) {
4110
+ return this.callMcp("gtm_brain_delivery_risk", {
4111
+ campaign_id: input.campaignId,
4112
+ provider_chain: input.providerChain,
4113
+ lead_source: input.leadSource,
4114
+ target_icp: input.targetIcp,
4115
+ lead_samples: input.leadSamples,
4116
+ include_global: input.includeGlobal,
4117
+ min_confidence: input.minConfidence,
4118
+ limit: input.limit
4119
+ });
4120
+ }
4121
+ /** Rank provider-chain, ICP, source, copy, and sequence failure patterns without writing raw lead data. */
4122
+ async failurePatterns(options = {}) {
4123
+ return this.callMcp("gtm_brain_failure_patterns", {
4124
+ campaign_id: options.campaignId,
4125
+ days: options.days,
4126
+ min_sample_size: options.minSampleSize,
4127
+ dimensions: options.dimensions,
4128
+ include_existing_patterns: options.includeExistingPatterns,
4129
+ include_global: options.includeGlobal,
4130
+ limit: options.limit
4131
+ });
4132
+ }
4133
+ /** List provider presets agents can wire into GTM campaign layers, including BYO and Signaliz fallback options. */
4134
+ async providerCatalog(options = {}) {
4135
+ return this.callMcp("gtm_provider_catalog", {
4136
+ provider_id: options.providerId,
4137
+ layer: options.layer,
4138
+ include_planned: options.includePlanned,
4139
+ include_layer_catalog: options.includeLayerCatalog
4140
+ });
4141
+ }
4142
+ /** Inspect GTM integration activation cards for UI and agent routing without writing state. */
4143
+ async integrationsActivationStatus(options = {}) {
4144
+ return this.callMcp("gtm_integrations_activation_status", {
4145
+ campaign_id: options.campaignId,
4146
+ layer: options.layer,
4147
+ include_planned: options.includePlanned,
4148
+ include_connections: options.includeConnections
4149
+ });
4150
+ }
4151
+ /** Compose Memory, Brain defaults, failure intelligence, and provider routes into a read-only campaign build plan. */
4152
+ async campaignBuildPlan(input = {}) {
4153
+ return this.callMcp("gtm_campaign_build_plan", {
4154
+ campaign_id: input.campaignId,
4155
+ campaign_build_id: input.campaignBuildId,
4156
+ campaign_brief: input.campaignBrief,
4157
+ target_icp: input.targetIcp,
4158
+ lead_count: input.leadCount,
4159
+ layers: input.layers,
4160
+ preferred_providers: input.preferredProviders,
4161
+ memory_dimension_filters: input.memoryDimensionFilters,
4162
+ require_memory_dimension_match: input.requireMemoryDimensionMatch,
4163
+ include_memory: input.includeMemory,
4164
+ include_brain: input.includeBrain,
4165
+ include_provider_routes: input.includeProviderRoutes,
4166
+ include_failure_patterns: input.includeFailurePatterns,
4167
+ include_planned_providers: input.includePlannedProviders,
4168
+ days: input.days,
4169
+ limit: input.limit
4170
+ });
4171
+ }
4172
+ /** Persist a reviewed campaign build plan into a campaign object and audit log. Dry-run first by default. */
4173
+ async commitCampaignBuildPlan(input = {}) {
4174
+ return this.callMcp("gtm_campaign_build_plan_commit", {
4175
+ campaign_id: input.campaignId,
4176
+ campaign_build_id: input.campaignBuildId,
4177
+ name: input.name,
4178
+ campaign_brief: input.campaignBrief,
4179
+ target_icp: input.targetIcp,
4180
+ lead_count: input.leadCount,
4181
+ layers: input.layers,
4182
+ preferred_providers: input.preferredProviders,
4183
+ plan_snapshot: input.planSnapshot,
4184
+ sequences: input.sequences,
4185
+ lead_list_refs: input.leadListRefs,
4186
+ send_config: input.sendConfig,
4187
+ brain_config: input.brainConfig,
4188
+ metadata: input.metadata,
4189
+ status: input.status,
4190
+ approval_required: input.approvalRequired,
4191
+ actor_type: input.actorType,
4192
+ actor_id: input.actorId,
4193
+ rationale: input.rationale,
4194
+ idempotency_key: input.idempotencyKey,
4195
+ dry_run: input.dryRun,
4196
+ confirm: input.confirm
4197
+ });
4198
+ }
4199
+ /** Derive exact build_campaign arguments from a committed campaign object without creating a build. */
4200
+ async prepareCampaignBuildExecution(input) {
4201
+ return this.callMcp("gtm_campaign_build_execution_prepare", {
4202
+ campaign_id: input.campaignId,
4203
+ target_count: input.targetCount,
4204
+ allow_downscale: input.allowDownscale,
4205
+ dry_run: input.dryRun,
4206
+ confirm_spend: input.confirmSpend,
4207
+ include_brain_context: input.includeBrainContext,
4208
+ require_delivery_risk_clearance: input.requireDeliveryRiskClearance,
4209
+ delivery_risk: input.deliveryRisk,
4210
+ dedup_keys: input.dedupKeys,
4211
+ policy: input.policy,
4212
+ signals: input.signals,
4213
+ qualification: input.qualification,
4214
+ copy: input.copy,
4215
+ delivery: input.delivery,
4216
+ enhancers: input.enhancers
4217
+ });
4218
+ }
4219
+ /** Prepare exact recipe, route, preview, and delivery arguments for a provider without writing state. */
4220
+ async prepareProviderRecipe(input) {
4221
+ return this.callMcp("gtm_provider_recipe_prepare", {
4222
+ provider_id: input.providerId,
4223
+ provider_name: input.providerName,
4224
+ description: input.description,
4225
+ layer_capabilities: input.layerCapabilities,
4226
+ invocation_type: input.invocationType,
4227
+ auth_strategy: input.authStrategy,
4228
+ endpoint_url: input.endpointUrl,
4229
+ http_method: input.httpMethod,
4230
+ secret_ref: input.secretRef,
4231
+ workspace_integration_id: input.workspaceIntegrationId,
4232
+ workspace_mcp_server_id: input.workspaceMcpServerId,
4233
+ workspace_connection_id: input.workspaceConnectionId,
4234
+ request_template: input.requestTemplate,
4235
+ response_mapping: input.responseMapping,
4236
+ input_schema: input.inputSchema,
4237
+ output_schema: input.outputSchema,
4238
+ readiness: input.readiness,
4239
+ metadata: input.metadata,
4240
+ layer: input.layer,
4241
+ campaign_id: input.campaignId,
4242
+ use_signaliz_fallback: input.useSignalizFallback,
4243
+ priority: input.priority,
4244
+ status: input.status,
4245
+ sample_records: input.sampleRecords,
4246
+ context: input.context
4247
+ });
4248
+ }
4249
+ /** Prepare exact Clay webhook recipe, route, preview, and delivery arguments without writing state. */
4250
+ async prepareClayWebhook(input = {}) {
4251
+ return this.callMcp("gtm_clay_webhook_prepare", {
4252
+ endpoint_url: input.endpointUrl,
4253
+ secret_ref: input.secretRef,
4254
+ layer: input.layer,
4255
+ campaign_id: input.campaignId,
4256
+ use_signaliz_fallback: input.useSignalizFallback,
4257
+ priority: input.priority,
4258
+ status: input.status,
4259
+ sample_records: input.sampleRecords,
4260
+ context: input.context
4261
+ });
4262
+ }
4263
+ /** Dry-run or confirm a one-call provider route activation across one or more GTM layers. */
4264
+ async activateProviderRoute(input) {
4265
+ return this.callMcp("gtm_provider_route_activate", {
4266
+ provider_id: input.providerId,
4267
+ provider_name: input.providerName,
4268
+ description: input.description,
4269
+ layer: input.layer,
4270
+ layers: input.layers,
4271
+ campaign_id: input.campaignId,
4272
+ invocation_type: input.invocationType,
4273
+ auth_strategy: input.authStrategy,
4274
+ endpoint_url: input.endpointUrl,
4275
+ http_method: input.httpMethod,
4276
+ secret_ref: input.secretRef,
4277
+ workspace_integration_id: input.workspaceIntegrationId,
4278
+ workspace_mcp_server_id: input.workspaceMcpServerId,
4279
+ workspace_connection_id: input.workspaceConnectionId,
4280
+ use_signaliz_fallback: input.useSignalizFallback,
4281
+ priority: input.priority,
4282
+ route_config: input.routeConfig,
4283
+ request_template: input.requestTemplate,
4284
+ response_mapping: input.responseMapping,
4285
+ input_schema: input.inputSchema,
4286
+ output_schema: input.outputSchema,
4287
+ readiness: input.readiness,
4288
+ metadata: input.metadata,
4289
+ status: input.status,
4290
+ route_status: input.routeStatus,
4291
+ replace_existing_routes: input.replaceExistingRoutes,
4292
+ dry_run: input.dryRun,
4293
+ confirm: input.confirm,
4294
+ sample_records: input.sampleRecords,
4295
+ context: input.context
4296
+ });
4297
+ }
4298
+ /** List Signaliz-managed integrations, external MCP servers, app connections, recipes, and layer routes. */
4299
+ async listConnections(options = {}) {
4300
+ return this.callMcp("gtm_connections_list", {
4301
+ kind: options.kind,
4302
+ include_disconnected: options.includeDisconnected
4303
+ });
4304
+ }
4305
+ /** Register a workspace connection for the Kernel connection layer. */
4306
+ async registerConnection(input) {
4307
+ return this.callMcp("gtm_connection_register", {
4308
+ connection_kind: input.connectionKind,
4309
+ name: input.name,
4310
+ server_url: input.serverUrl,
4311
+ auth_type: input.authType,
4312
+ auth_config: input.authConfig,
4313
+ enabled_tools: input.enabledTools,
4314
+ preset_id: input.presetId,
4315
+ vendor_id: input.vendorId,
4316
+ service_category: input.serviceCategory,
4317
+ connection_type: input.connectionType,
4318
+ status: input.status,
4319
+ metadata: input.metadata
4320
+ });
4321
+ }
4322
+ /** Create a reusable integration recipe for BYO providers such as Clay webhooks, Apollo, AI Ark, Octave, or Airbyte. */
4323
+ async createIntegrationRecipe(input) {
4324
+ return this.callMcp("gtm_integration_recipe_create", {
4325
+ provider_id: input.providerId,
4326
+ provider_name: input.providerName,
4327
+ description: input.description,
4328
+ layer_capabilities: input.layerCapabilities,
4329
+ invocation_type: input.invocationType,
4330
+ auth_strategy: input.authStrategy,
4331
+ workspace_integration_id: input.workspaceIntegrationId,
4332
+ workspace_mcp_server_id: input.workspaceMcpServerId,
4333
+ workspace_connection_id: input.workspaceConnectionId,
4334
+ endpoint_url: input.endpointUrl,
4335
+ http_method: input.httpMethod,
4336
+ request_template: input.requestTemplate,
4337
+ response_mapping: input.responseMapping,
4338
+ input_schema: input.inputSchema,
4339
+ output_schema: input.outputSchema,
4340
+ readiness: input.readiness,
4341
+ metadata: input.metadata,
4342
+ status: input.status
4343
+ });
4344
+ }
4345
+ /** Set a workspace or campaign provider route for one GTM layer. */
4346
+ async setLayerRoute(input) {
4347
+ return this.callMcp("gtm_layer_route_set", {
4348
+ layer: input.layer,
4349
+ provider_id: input.providerId,
4350
+ campaign_id: input.campaignId,
4351
+ recipe_id: input.recipeId,
4352
+ priority: input.priority,
4353
+ use_signaliz_fallback: input.useSignalizFallback,
4354
+ route_config: input.routeConfig,
4355
+ status: input.status
4356
+ });
4357
+ }
4358
+ /** Get effective layer routes, including Signaliz fallback availability. */
4359
+ async getLayerRoutes(options = {}) {
4360
+ return this.callMcp("gtm_layer_routes_get", {
4361
+ campaign_id: options.campaignId,
4362
+ layer: options.layer
4363
+ });
4364
+ }
4365
+ /** Preview one effective layer route before external delivery or provider execution. */
4366
+ async previewLayerRoute(input) {
4367
+ return this.callMcp("gtm_layer_route_preview", {
4368
+ layer: input.layer,
4369
+ campaign_id: input.campaignId,
4370
+ sample_records: input.sampleRecords,
4371
+ context: input.context
4372
+ });
4373
+ }
4374
+ /** List Nango-backed action tools for a workspace connection without executing them. */
4375
+ async listNangoTools(options = {}) {
4376
+ return this.callMcp("nango_mcp_tools_list", {
4377
+ workspace_connection_id: options.workspaceConnectionId,
4378
+ connection_id: options.connectionId,
4379
+ provider_config_key: options.providerConfigKey,
4380
+ integration_id: options.integrationId,
4381
+ nango_connection_id: options.nangoConnectionId,
4382
+ format: options.format,
4383
+ include_raw: options.includeRaw
4384
+ });
4385
+ }
4386
+ /** Dry-run or execute a Nango-backed action tool through the approval-aware MCP bridge. */
4387
+ async callNangoTool(input) {
4388
+ return this.callMcp("nango_mcp_tool_call", {
4389
+ workspace_connection_id: input.workspaceConnectionId,
4390
+ connection_id: input.connectionId,
4391
+ provider_config_key: input.providerConfigKey,
4392
+ integration_id: input.integrationId,
4393
+ nango_connection_id: input.nangoConnectionId,
4394
+ action_name: input.actionName,
4395
+ tool_name: input.toolName,
4396
+ input: input.input,
4397
+ async: input.async,
4398
+ max_retries: input.maxRetries,
4399
+ dry_run: input.dryRun,
4400
+ confirm: input.confirm,
4401
+ confirm_write: input.confirmWrite
4402
+ });
4403
+ }
4404
+ /** Poll an async Nango action result by action id or status URL. */
4405
+ async getNangoActionResult(input) {
4406
+ return this.callMcp("nango_mcp_action_result_get", {
4407
+ action_id: input.actionId,
4408
+ status_url: input.statusUrl
4409
+ });
4410
+ }
4411
+ /** Deliver approved campaign-layer records to a webhook recipe, starting with Clay-style webhooks. */
4412
+ async deliverWebhook(input) {
4413
+ return this.callMcp("gtm_webhook_deliver", {
4414
+ recipe_id: input.recipeId,
4415
+ campaign_id: input.campaignId,
4416
+ layer: input.layer,
4417
+ records: input.records,
4418
+ context: input.context,
4419
+ idempotency_key: input.idempotencyKey
4420
+ });
4421
+ }
4422
+ async callMcp(tool, args) {
4423
+ return this.client.mcp("tools/call", { name: tool, arguments: compact2(args) });
4424
+ }
4425
+ };
4426
+ function campaignCreateArgs(input) {
4427
+ return {
4428
+ name: input.name,
4429
+ description: input.description,
4430
+ source: input.source,
4431
+ status: input.status,
4432
+ campaign_build_id: input.campaignBuildId,
4433
+ campaign_builder_job_id: input.campaignBuilderJobId,
4434
+ routine_id: input.routineId,
4435
+ target_icp: input.targetIcp,
4436
+ sequences: input.sequences,
4437
+ lead_list_refs: input.leadListRefs,
4438
+ send_config: input.sendConfig,
4439
+ provider_links: input.providerLinks?.map(providerLinkArgs),
4440
+ brain_config: input.brainConfig,
4441
+ metadata: input.metadata,
4442
+ log: input.log ? campaignLogArgs(input.log) : void 0
4443
+ };
4444
+ }
4445
+ function campaignHistoryImportCampaignArgs(input) {
4446
+ return {
4447
+ campaign_id: input.campaignId,
4448
+ idempotency_key: input.idempotencyKey,
4449
+ name: input.name,
4450
+ description: input.description,
4451
+ source: input.source,
4452
+ status: input.status,
4453
+ campaign_build_id: input.campaignBuildId,
4454
+ campaign_builder_job_id: input.campaignBuilderJobId,
4455
+ routine_id: input.routineId,
4456
+ target_icp: input.targetIcp,
4457
+ sequences: input.sequences,
4458
+ lead_list_refs: input.leadListRefs,
4459
+ send_config: input.sendConfig,
4460
+ performance_metrics: input.performanceMetrics,
4461
+ brain_config: input.brainConfig,
4462
+ memory_summary: input.memorySummary,
4463
+ metadata: input.metadata,
4464
+ provider_links: input.providerLinks?.map(providerLinkArgs),
4465
+ feedback_events: input.feedbackEvents,
4466
+ memory_items: input.memoryItems?.map(campaignHistoryMemoryArgs),
4467
+ started_at: input.startedAt,
4468
+ completed_at: input.completedAt,
4469
+ summary: input.summary,
4470
+ memory_summary_text: input.memorySummaryText
4471
+ };
4472
+ }
4473
+ function campaignHistoryMemoryArgs(input) {
4474
+ return {
4475
+ idempotency_key: input.idempotencyKey,
4476
+ memory_type: input.memoryType,
4477
+ title: input.title,
4478
+ content: input.content,
4479
+ keywords: input.keywords,
4480
+ dimensions: input.dimensions,
4481
+ outcome_type: input.outcomeType,
4482
+ outcome_value: input.outcomeValue,
4483
+ sample_size: input.sampleSize,
4484
+ confidence: input.confidence,
4485
+ shareable: input.shareable,
4486
+ redaction_state: input.redactionState,
4487
+ metadata: input.metadata,
4488
+ recency_at: input.recencyAt
4489
+ };
4490
+ }
4491
+ function campaignUpdateArgs(input) {
4492
+ return {
4493
+ campaign_id: input.campaignId,
4494
+ name: input.name,
4495
+ description: input.description,
4496
+ status: input.status,
4497
+ target_icp: input.targetIcp,
4498
+ sequences: input.sequences,
4499
+ lead_list_refs: input.leadListRefs,
4500
+ send_config: input.sendConfig,
4501
+ performance_metrics: input.performanceMetrics,
4502
+ brain_config: input.brainConfig,
4503
+ memory_summary: input.memorySummary,
4504
+ metadata: input.metadata,
4505
+ provider_links: input.providerLinks?.map(providerLinkArgs),
4506
+ log: input.log ? campaignLogArgs(input.log) : void 0
4507
+ };
4508
+ }
4509
+ function campaignLogArgs(input) {
4510
+ return {
4511
+ campaign_id: input.campaignId,
4512
+ actor_type: input.actorType,
4513
+ actor_id: input.actorId,
4514
+ action: input.action,
4515
+ rationale: input.rationale,
4516
+ payload: input.payload,
4517
+ idempotency_key: input.idempotencyKey
4518
+ };
4519
+ }
4520
+ function providerLinkArgs(input) {
4521
+ return {
4522
+ provider: input.provider,
4523
+ provider_campaign_id: input.providerCampaignId,
4524
+ integration_id: input.integrationId,
4525
+ provider_workspace_id: input.providerWorkspaceId,
4526
+ provider_account_id: input.providerAccountId,
4527
+ status: input.status,
4528
+ metadata: input.metadata
4529
+ };
4530
+ }
4531
+ function compact2(value) {
4532
+ if (Array.isArray(value)) return value.map((item) => compact2(item)).filter((item) => item !== void 0);
4533
+ if (!value || typeof value !== "object") return value;
4534
+ const out = {};
4535
+ for (const [key, child] of Object.entries(value)) {
4536
+ if (child === void 0) continue;
4537
+ const compacted = compact2(child);
4538
+ if (compacted === void 0) continue;
4539
+ out[key] = compacted;
4540
+ }
4541
+ return out;
4542
+ }
4543
+
4544
+ // src/index.ts
4545
+ function inferMcpToolCategory(toolName) {
4546
+ if (typeof toolName !== "string" || !toolName) return void 0;
4547
+ if (toolName.startsWith("ops_") || toolName === "get_ops_readiness" || toolName === "get_gtm_ops_readiness" || toolName.startsWith("gtm_") || [
4548
+ "list_routines",
4549
+ "create_routine",
4550
+ "update_routine",
4551
+ "run_routine_now",
4552
+ "get_routine",
4553
+ "get_routine_ticks",
4554
+ "get_tick_items",
4555
+ "get_last_tick_items",
4556
+ "chain_routines",
4557
+ "get_chain_status",
4558
+ "launch_campaign",
4559
+ "quickstart_gtm_book",
4560
+ "list_campaigns",
4561
+ "campaign_performance",
4562
+ "tune_campaign",
4563
+ "emit_event",
4564
+ "approvals_list",
4565
+ "list_output_sinks",
4566
+ "create_output_sink",
4567
+ "update_output_sink",
4568
+ "delete_output_sink",
4569
+ "attach_sink_to_routine"
4570
+ ].includes(toolName)) {
4571
+ return "ops";
4572
+ }
4573
+ if ([
4574
+ "find_emails_with_verification",
4575
+ "verify_email",
4576
+ "enrich_company_signals",
4577
+ "company_intelligence",
4578
+ "find_contacts_with_email",
4579
+ "execute_primitive"
4580
+ ].includes(toolName)) {
4581
+ return "enrichment";
4582
+ }
4583
+ if (toolName.includes("icp")) return "icp";
4584
+ if (toolName.startsWith("ai_clean_")) return "data_cleaning";
4585
+ if (toolName.includes("system") || toolName.includes("workflow")) return "automation";
4586
+ if (toolName.includes("agent") || toolName.includes("platform_health") || toolName === "discover_capabilities") return "observability";
4587
+ return void 0;
4588
+ }
4589
+ function asRecord3(value) {
4590
+ return value && typeof value === "object" ? value : void 0;
4591
+ }
4592
+ function asStringArray(value) {
4593
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : void 0;
4594
+ }
4595
+ function asObjectSchema(value) {
4596
+ return asRecord3(value);
4597
+ }
4598
+ var Signaliz = class {
4599
+ constructor(config) {
4600
+ this.client = new HttpClient(config);
4601
+ this.emails = new Emails(this.client);
4602
+ this.signals = new Signals(this.client);
4603
+ this.systems = new Systems(this.client);
4604
+ this.runs = new Runs(this.client);
4605
+ this.http = new Http(this.client);
4606
+ this.campaigns = new Campaigns(this.client);
4607
+ this.campaignBuilderAgent = new CampaignBuilderAgent(this.client);
4608
+ this.icps = new Icps(this.client);
4609
+ this.leads = new Leads(this.client);
4610
+ this.ops = new Ops(this.client);
4611
+ this.ai = new Ai(this.client);
4612
+ this.gtm = new GtmKernel(this.client);
4613
+ }
4614
+ /** Get current workspace info including credits */
4615
+ async getWorkspace() {
4616
+ const data = await this.client.mcp("tools/call", {
4617
+ name: "get_workspace",
4618
+ arguments: {}
4619
+ });
4620
+ return {
4621
+ id: data.workspace_id ?? data.id,
4622
+ name: data.workspace_name ?? data.name ?? "Unknown",
4623
+ creditsRemaining: data.credits_remaining ?? data.credit_balance ?? data.credits ?? 0,
4624
+ plan: data.plan ?? data.plan_name ?? "unknown"
4625
+ };
4626
+ }
4627
+ /** Get MCP platform health and recent latency/error-rate signals */
4628
+ async getPlatformHealth() {
4629
+ const data = await this.client.mcp("tools/call", {
4630
+ name: "get_platform_health",
4631
+ arguments: {}
4632
+ });
4633
+ return {
4634
+ status: data.status ?? "unknown",
4635
+ period: data.period,
4636
+ totalRequests: data.total_requests ?? data.totalRequests ?? 0,
4637
+ errorRate: data.error_rate ?? data.errorRate ?? "0%",
4638
+ latency: {
4639
+ p50: data.latency?.p50 ?? 0,
4640
+ p95: data.latency?.p95 ?? 0,
4641
+ p99: data.latency?.p99 ?? 0,
4642
+ sampleCount: data.latency?.sample_count ?? data.latency?.sampleCount,
4643
+ source: data.latency?.source
4644
+ }
4645
+ };
4646
+ }
4647
+ /** Alias for getPlatformHealth, useful in health-check scripts */
4648
+ async health() {
4649
+ return this.getPlatformHealth();
4650
+ }
4651
+ /** List all available MCP tools */
4652
+ async listTools() {
4653
+ const data = await this.client.mcp("tools/list", {});
4654
+ const tools = data?.tools ?? data ?? [];
4655
+ return tools.map((t) => ({
4656
+ name: typeof t.name === "string" ? t.name : "",
4657
+ description: String(t.description ?? "").slice(0, 120),
4658
+ category: typeof t.annotations?.category === "string" ? t.annotations.category : inferMcpToolCategory(t.name),
4659
+ costCredits: typeof t.annotations?.cost_credits === "number" ? t.annotations.cost_credits : void 0,
4660
+ contractVersion: typeof (t.annotations?.contract_version ?? t.annotations?.contract?.contract_version) === "string" ? t.annotations?.contract_version ?? t.annotations?.contract?.contract_version : void 0,
4661
+ permissionLevel: typeof (t.annotations?.permission_level ?? t.annotations?.contract?.permission_level) === "string" ? t.annotations?.permission_level ?? t.annotations?.contract?.permission_level : void 0,
4662
+ authScopes: asStringArray(t.annotations?.auth_scopes ?? t.annotations?.contract?.auth_scopes),
4663
+ idempotent: typeof (t.annotations?.idempotentHint ?? t.annotations?.idempotent ?? t.annotations?.contract?.idempotent) === "boolean" ? t.annotations?.idempotentHint ?? t.annotations?.idempotent ?? t.annotations?.contract?.idempotent : void 0,
4664
+ destructive: typeof (t.annotations?.destructiveHint ?? t.annotations?.destructive ?? t.annotations?.contract?.destructive) === "boolean" ? t.annotations?.destructiveHint ?? t.annotations?.destructive ?? t.annotations?.contract?.destructive : void 0,
4665
+ retryable: typeof (t.annotations?.retryable ?? t.annotations?.contract?.retryable) === "boolean" ? t.annotations?.retryable ?? t.annotations?.contract?.retryable : void 0,
4666
+ rateLimitKey: typeof (t.annotations?.rate_limit_key ?? t.annotations?.contract?.rate_limit_key) === "string" ? t.annotations?.rate_limit_key ?? t.annotations?.contract?.rate_limit_key : void 0,
4667
+ observability: asRecord3(t.annotations?.observability ?? t.annotations?.contract?.observability),
4668
+ inputSchema: asObjectSchema(t.inputSchema ?? t.input_schema ?? t.annotations?.contract?.input_schema),
4669
+ outputSchema: asObjectSchema(t.outputSchema ?? t.output_schema ?? t.annotations?.contract?.output_schema),
4670
+ annotations: asRecord3(t.annotations)
4671
+ }));
4672
+ }
4673
+ /** Discover tools by natural language query */
4674
+ async discover(query, category) {
4675
+ const data = await this.client.mcp("tools/call", {
4676
+ name: "discover_capabilities",
4677
+ arguments: { query, category }
4678
+ });
4679
+ return (data.matches ?? []).map((m) => ({
4680
+ name: m.tool,
4681
+ description: m.description,
4682
+ category: m.category,
4683
+ costCredits: m.cost_credits,
4684
+ contractVersion: m.contract_version ?? m.contract?.contract_version,
4685
+ permissionLevel: m.permission_level ?? m.contract?.permission_level,
4686
+ authScopes: m.auth_scopes ?? m.contract?.auth_scopes,
4687
+ idempotent: m.idempotent ?? m.contract?.idempotent,
4688
+ destructive: m.destructive ?? m.contract?.destructive,
4689
+ retryable: m.retryable ?? m.contract?.retryable,
4690
+ rateLimitKey: m.rate_limit_key ?? m.contract?.rate_limit_key,
4691
+ observability: m.observability ?? m.contract?.observability,
4692
+ inputSchema: m.input_schema ?? m.inputSchema ?? m.contract?.input_schema,
4693
+ outputSchema: m.output_schema ?? m.outputSchema ?? m.contract?.output_schema,
4694
+ annotations: m.annotations
4695
+ }));
4696
+ }
4697
+ };
4698
+
4699
+ export {
4700
+ SignalizError,
4701
+ Campaigns,
4702
+ DEFAULT_SIGNALIZ_CAMPAIGN_BUILDER_DEFAULTS,
4703
+ CampaignBuilderAgent,
4704
+ createCampaignBuilderAgentPlan,
4705
+ getMissingCampaignBuilderApprovals,
4706
+ createCampaignBuilderApproval,
4707
+ Icps,
4708
+ normalizeExecutionReference,
4709
+ collectExecutionReferences,
4710
+ Ops,
4711
+ Ai,
4712
+ GtmKernel,
4713
+ Signaliz
4714
+ };