@signaliz/sdk 1.0.1 → 1.0.3

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