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