@signaliz/sdk 1.0.1 → 1.0.4

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