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