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