@signaliz/sdk 1.0.1 → 1.0.3

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