@signaliz/sdk 1.0.6 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,6 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
3
 
4
+ // src/cli.ts
5
+ var import_node_fs = require("fs");
6
+
4
7
  // src/errors.ts
5
8
  var SignalizError = class extends Error {
6
9
  constructor(data) {
@@ -754,7 +757,7 @@ var Campaigns = class {
754
757
  async build(request, options) {
755
758
  return this.buildCampaign(request, options);
756
759
  }
757
- /** Scope an agency/client campaign into a markdown brief plus build_campaign dry-run args. */
760
+ /** Scope an agency/customer campaign into a markdown brief plus build_campaign dry-run args. */
758
761
  async scope(request) {
759
762
  return this.scopeCampaign(request);
760
763
  }
@@ -936,6 +939,10 @@ function mapStatus(data) {
936
939
  errors: diagnosticMessages(data.errors),
937
940
  artifactCount: data.artifact_count ?? 0,
938
941
  providerRoute: mapProviderRoute(data),
942
+ triggerRunId: typeof data.trigger_run_id === "string" ? data.trigger_run_id : null,
943
+ staleRunningPhase: data.stale_running_phase === true,
944
+ phaseAgeSeconds: numberOrNull(data.phase_age_seconds),
945
+ diagnostics: recordOrNull(data.diagnostics) ?? {},
939
946
  nextAction: formatNextAction(data.next_action),
940
947
  createdAt: data.created_at,
941
948
  updatedAt: data.updated_at,
@@ -1029,7 +1036,7 @@ function mapArtifact(a) {
1029
1036
  function mapScope(data) {
1030
1037
  return {
1031
1038
  campaignScopeId: data.campaign_scope_id,
1032
- clientName: data.client_name,
1039
+ accountLabel: data.account_label,
1033
1040
  campaignName: data.campaign_name,
1034
1041
  approach: data.approach,
1035
1042
  approachLabel: data.approach_label,
@@ -1055,8 +1062,8 @@ function scopeArgs(request) {
1055
1062
  const args = {
1056
1063
  prompt: request.prompt
1057
1064
  };
1058
- if (request.clientName) args.client_name = request.clientName;
1059
- if (request.clientContext) args.client_context = request.clientContext;
1065
+ if (request.accountLabel) args.account_label = request.accountLabel;
1066
+ if (request.accountContext) args.account_context = request.accountContext;
1060
1067
  if (request.campaignGoal) args.campaign_goal = request.campaignGoal;
1061
1068
  if (request.targetCount) args.target_count = request.targetCount;
1062
1069
  if (request.destinations) args.destinations = request.destinations;
@@ -1184,22 +1191,565 @@ var DEFAULT_SIGNALIZ_CAMPAIGN_BUILDER_DEFAULTS = {
1184
1191
  approvalRequired: true
1185
1192
  }
1186
1193
  };
1194
+ var DEFAULT_CAMPAIGN_BUILDER_BUILT_INS = [
1195
+ "lead_generation",
1196
+ "email_finding",
1197
+ "email_verification",
1198
+ "signals"
1199
+ ];
1200
+ var DEFAULT_CAMPAIGN_BUILDER_APPROVAL_TYPES = [
1201
+ "memory_retrieval",
1202
+ "spend",
1203
+ "customer_tool",
1204
+ "external_write",
1205
+ "delivery",
1206
+ "launch"
1207
+ ];
1208
+ var CAMPAIGN_BUILDER_OPERATING_PLAYBOOKS = [
1209
+ {
1210
+ slug: "cache-first-large-list",
1211
+ label: "Cache-First Large List",
1212
+ whenToUse: [
1213
+ "The target count is high and reusable workspace lead or cache coverage may exist.",
1214
+ "The deliverable is a verified list or top-up rather than a deeply custom one-off workflow."
1215
+ ],
1216
+ sequence: [
1217
+ "Inventory reusable cache before paid sourcing.",
1218
+ "Report unique emails, role buckets, exclusions, and missing-field counts.",
1219
+ "Use fresh sourcing only for the approved gap.",
1220
+ "Write newly approved source metadata back to memory or cache after review."
1221
+ ],
1222
+ requiredFields: {
1223
+ inventory: ["matching_cached_rows", "unique_cached_emails", "persona_bucket_counts", "exclusions_applied", "missing_field_counts"],
1224
+ finalRows: ["first_name", "last_name", "company_name", "company_domain", "work_email", "email_status", "source_type"]
1225
+ },
1226
+ qualityGates: [
1227
+ "Deduplicate by normalized email before counting final rows.",
1228
+ "Separate cache reuse from fresh sourcing in the build receipt.",
1229
+ "Block export when required identity, company, or email fields are missing."
1230
+ ],
1231
+ activationBoundary: "Cache inventory is read-only. Fresh sourcing, cache writes, export, and sender loading require explicit approval.",
1232
+ memoryKeywords: ["cache inventory", "large list", "unique emails", "top-up sourcing", "source metadata"]
1233
+ },
1234
+ {
1235
+ slug: "net-new-suppressed-list",
1236
+ label: "Net-New Suppressed List",
1237
+ whenToUse: [
1238
+ "A prior campaign, seed list, or exclusion list must be suppressed.",
1239
+ "The operator needs both outreach-facing rows and provenance-rich QA evidence."
1240
+ ],
1241
+ sequence: [
1242
+ "Load suppression baselines before source selection.",
1243
+ "Apply email suppression as a hard gate and domain suppression as required by the brief.",
1244
+ "Keep provenance, source, and validation fields outside the outreach-facing export when needed.",
1245
+ "Run final overlap checks before any delivery action."
1246
+ ],
1247
+ requiredFields: {
1248
+ suppression: ["suppression_source", "prior_email_overlap", "prior_domain_match", "suppression_decision"],
1249
+ finalRows: ["first_name", "last_name", "company_name", "company_domain", "work_email", "email_status", "provenance_id"]
1250
+ },
1251
+ qualityGates: [
1252
+ "Prior email overlap must be zero for rows marked export ready.",
1253
+ "Prior-domain matches must be flagged or blocked according to the approved campaign promise.",
1254
+ "Do not describe rows as fully qualified when the approved path only proves net-new email status."
1255
+ ],
1256
+ activationBoundary: "Suppression review must pass before export, upload, CRM sync, sender load, or sequence launch.",
1257
+ memoryKeywords: ["suppression", "net-new", "prior email overlap", "domain review", "provenance-rich QA"]
1258
+ },
1259
+ {
1260
+ slug: "proof-first-vertical-gate",
1261
+ label: "Proof-First Vertical Gate",
1262
+ whenToUse: [
1263
+ "Wrong-account risk is high or the target category has close lookalike exclusions.",
1264
+ "Account proof is more important than raw lead volume."
1265
+ ],
1266
+ sequence: [
1267
+ "Define positive and negative proof fields before sourcing at scale.",
1268
+ "Qualify companies before contact discovery.",
1269
+ "Qualify contacts before email finding.",
1270
+ "Keep pass, review, and fail rows distinct through delivery review."
1271
+ ],
1272
+ requiredFields: {
1273
+ account: ["company_name", "company_domain", "source_url", "positive_proof", "negative_proof", "fit_score", "account_qualified"],
1274
+ contact: ["person_name", "person_title", "persona_match", "contact_fit_score", "contact_qualified"]
1275
+ },
1276
+ qualityGates: [
1277
+ "Do not spend on contact or email enrichment until the account passes the proof gate.",
1278
+ "Adjacent excluded categories must stay exclusions, not synonyms.",
1279
+ "Contact fit should meet the configured threshold before email finding or copy generation."
1280
+ ],
1281
+ activationBoundary: "Proof gates are required before contact spend, copy, export, or external writes.",
1282
+ memoryKeywords: ["proof gate", "vertical exclusion", "company before contact", "pass review fail", "fit threshold"]
1283
+ },
1284
+ {
1285
+ slug: "signal-led-copy-approval",
1286
+ label: "Signal-Led Copy With Approval",
1287
+ whenToUse: [
1288
+ "Outbound copy should be grounded in company signals, proof fields, or row context.",
1289
+ "Delivery destinations must remain locked after copy generation until review."
1290
+ ],
1291
+ sequence: [
1292
+ "Validate list quality before copy.",
1293
+ "Attach the strongest supported signal and source evidence.",
1294
+ "Generate copy only for fit-qualified and contactable rows.",
1295
+ "Hold every destination behind explicit approval."
1296
+ ],
1297
+ requiredFields: {
1298
+ evidence: ["strongest_signal", "signal_source_url", "why_now", "personalization_basis"],
1299
+ copy: ["subject_line", "opening_line", "email_copy", "copy_ready", "copy_blocker"]
1300
+ },
1301
+ qualityGates: [
1302
+ "Copy cannot invent unsupported pain, claims, numbers, or recent events.",
1303
+ "Weak evidence should route the row to review instead of send-ready copy.",
1304
+ "Destination fields must remain blocked until approval metadata is present."
1305
+ ],
1306
+ activationBoundary: "Copy readiness is not delivery approval. Export, sync, sender load, and launch require a separate human-approved gate.",
1307
+ memoryKeywords: ["company signals", "evidence-fed copy", "why now", "copy blocker", "approval gate"]
1308
+ },
1309
+ {
1310
+ slug: "domain-first-recovery",
1311
+ label: "Domain-First Recovery",
1312
+ whenToUse: [
1313
+ "Strict yield is low and broad people sourcing creates noisy, duplicated, or off-fit rows.",
1314
+ "The account universe should be recovered or expanded before more contact spend."
1315
+ ],
1316
+ sequence: [
1317
+ "Model attrition after an initial sample.",
1318
+ "Source or recover account domains in tight slices.",
1319
+ "Filter domains locally before contact discovery.",
1320
+ "Use accepted domains as the seed for person and email work."
1321
+ ],
1322
+ requiredFields: {
1323
+ domainReview: ["company_domain", "source_slice", "domain_fit_score", "domain_rejection_reason", "accepted_domain"],
1324
+ recovery: ["target_gap", "expected_yield", "accepted_domain_count", "contact_pull_limit"]
1325
+ },
1326
+ qualityGates: [
1327
+ "Do not repeat broad people-with-email sourcing after strict yield proves low.",
1328
+ "Rejected domains should stay suppressed unless the operator changes the ICP.",
1329
+ "Target count means final held rows, not raw sourced rows."
1330
+ ],
1331
+ activationBoundary: "Domain recovery informs sourcing. Contact enrichment, paid qualification, and export still require approved gates.",
1332
+ memoryKeywords: ["domain-first", "yield modeling", "attrition", "accepted domains", "gap fill"]
1333
+ },
1334
+ {
1335
+ slug: "table-workflow-handoff",
1336
+ label: "Table Workflow Handoff",
1337
+ whenToUse: [
1338
+ "The campaign needs connected source, account, people, enrichment, copy, and destination tables.",
1339
+ "A workspace or partner tool owns part of the workflow through MCP, webhook, API, or managed integration."
1340
+ ],
1341
+ sequence: [
1342
+ "Create source/account context before child people rows.",
1343
+ "Carry source context into enrichment, copy, and destination mapping.",
1344
+ "Expose request-ready, result, error, blocker, and export-ready fields for every action.",
1345
+ "Dry-run provider routes and destination writes before activation."
1346
+ ],
1347
+ requiredFields: {
1348
+ workflow: ["source_record_id", "company_context", "request_ready", "provider_status", "error", "export_ready", "export_blocker"],
1349
+ destination: ["destination_type", "destination_status", "approval_status", "approved_by", "approved_at"]
1350
+ },
1351
+ qualityGates: [
1352
+ "Every paid/API action needs visible request readiness and parsed output fields.",
1353
+ "Child people rows must preserve the account context that justified the search.",
1354
+ "Provider route activation must dry-run before any external write."
1355
+ ],
1356
+ activationBoundary: "MCP, webhook, managed integration, and destination routes remain dry-run until the reviewed route and campaign are approved.",
1357
+ memoryKeywords: ["table workflow", "request ready", "provider status", "export blocker", "BYO integration"]
1358
+ }
1359
+ ];
1360
+ var CAMPAIGN_BUILDER_STRATEGY_TEMPLATES = [
1361
+ {
1362
+ slug: "industrial-ot-resilience",
1363
+ label: "Industrial OT Resilience",
1364
+ aliases: ["industrial ot", "ot resilience", "industrial continuity", "industrial-ot-resilience"],
1365
+ defaultTargetCount: 3e3,
1366
+ campaignName: "Industrial OT Resilience Net-New",
1367
+ accountContext: [
1368
+ "Strategy template: Signaliz-only OT, industrial, manufacturing, embedded systems, field service, cyber resilience, and business continuity sourcing.",
1369
+ "Use prior approved campaign output as the email suppression baseline; final files must have zero prior-used email overlap.",
1370
+ "Keep external qualification providers disabled unless the operator explicitly changes the requirement."
1371
+ ].join(" "),
1372
+ icp: {
1373
+ personas: [
1374
+ "OT leader",
1375
+ "Industrial automation leader",
1376
+ "Engineering leader",
1377
+ "IT infrastructure leader",
1378
+ "Reliability or maintenance leader",
1379
+ "Operations leader"
1380
+ ],
1381
+ industries: [
1382
+ "Machinery",
1383
+ "Electrical and electronic manufacturing",
1384
+ "Mechanical or industrial engineering",
1385
+ "Industrial automation",
1386
+ "Semiconductors",
1387
+ "Medical devices",
1388
+ "Oil and energy",
1389
+ "Automotive"
1390
+ ],
1391
+ geographies: ["United States", "United Kingdom", "Canada", "Nordics", "Netherlands"],
1392
+ keywords: [
1393
+ "OT",
1394
+ "ICS",
1395
+ "SCADA",
1396
+ "control systems",
1397
+ "industrial automation",
1398
+ "manufacturing",
1399
+ "plant operations",
1400
+ "reliability",
1401
+ "maintenance",
1402
+ "PLC",
1403
+ "business continuity"
1404
+ ],
1405
+ exclusions: [
1406
+ "sales",
1407
+ "marketing",
1408
+ "recruiting",
1409
+ "HR",
1410
+ "finance",
1411
+ "legal",
1412
+ "customer success",
1413
+ "retail",
1414
+ "restaurants",
1415
+ "staffing",
1416
+ "real estate"
1417
+ ],
1418
+ requireVerifiedEmail: true
1419
+ },
1420
+ builtIns: ["lead_generation", "email_finding", "email_verification", "signals"],
1421
+ preferredProviders: ["signaliz_native"],
1422
+ memoryQueries: [{
1423
+ query: "industrial OT net-new prior email suppression verified manufacturing embedded systems field service cyber resilience business continuity",
1424
+ scopes: ["workspace", "operator_notes"],
1425
+ topK: 10,
1426
+ required: true,
1427
+ rationale: "Load OT sourcing, dedupe, cache metadata, and approval gates before planning net-new work."
1428
+ }],
1429
+ constraints: {
1430
+ deliverabilityNotes: [
1431
+ "Require verified email, valid syntax, first name, last name, company name, and normalized company domain.",
1432
+ "Keep export, upload, sync, send, and replacement actions blocked until explicit approval.",
1433
+ "Treat prior-domain matches as flagged review evidence unless strict domain suppression is explicitly requested."
1434
+ ]
1435
+ },
1436
+ signalizDefaults: {
1437
+ copy: {
1438
+ offerContext: "Do not invent product claims. Anchor messaging only in row-supported OT, industrial, cyber resilience, backup/recovery, or business-continuity context."
1439
+ }
1440
+ },
1441
+ agencyContext: {
1442
+ partnerEcosystem: ["signaliz", "instantly", "nango"]
1443
+ },
1444
+ operatingPlaybookSlugs: ["net-new-suppressed-list", "proof-first-vertical-gate", "signal-led-copy-approval"]
1445
+ },
1446
+ {
1447
+ slug: "non-medical-home-care",
1448
+ label: "Non-Medical Home Care Operations",
1449
+ aliases: ["home care", "non-medical home care", "home-care-operations", "non-medical-home-care"],
1450
+ defaultTargetCount: 3e3,
1451
+ campaignName: "Mature Home Care Agency Operators",
1452
+ accountContext: [
1453
+ "Strategy template: mature US non-medical home care agencies with scale signals, proof fields, strict home-care vs home-health separation, and approval-gated export.",
1454
+ "Use proof before paid enrichment or copy. Preserve pass vs review ICP status because healthcare language often blurs home care and home health."
1455
+ ].join(" "),
1456
+ icp: {
1457
+ personas: [
1458
+ "Owner",
1459
+ "CEO",
1460
+ "COO",
1461
+ "Administrator",
1462
+ "Operations Director",
1463
+ "Scheduler",
1464
+ "Care coordinator leader"
1465
+ ],
1466
+ industries: ["Non-medical home care", "Senior care", "Private duty care", "Home services"],
1467
+ companySizes: ["20+ employees", "600+ billable care hours/week", "1000+ billable care hours/week ideal"],
1468
+ geographies: ["United States"],
1469
+ keywords: [
1470
+ "non-medical home care",
1471
+ "private duty",
1472
+ "caregiver recruiting",
1473
+ "multi-location",
1474
+ "franchise",
1475
+ "scheduler",
1476
+ "billing",
1477
+ "payroll",
1478
+ "EVV",
1479
+ "WellSky",
1480
+ "AxisCare",
1481
+ "CareSmartz360"
1482
+ ],
1483
+ exclusions: [
1484
+ "home health",
1485
+ "skilled nursing",
1486
+ "hospice",
1487
+ "hospital",
1488
+ "clinic",
1489
+ "therapy practice",
1490
+ "very small owner-only shop"
1491
+ ],
1492
+ requireVerifiedEmail: true
1493
+ },
1494
+ builtIns: ["lead_generation", "local_leads", "email_finding", "email_verification", "signals"],
1495
+ preferredProviders: ["signaliz_native", "octave", "clay_webhook", "apify"],
1496
+ memoryQueries: [{
1497
+ query: "mature non-medical home care agencies billable hours franchise caregiver recruiting proof gate qualification export approval",
1498
+ scopes: ["workspace", "operator_notes"],
1499
+ topK: 10,
1500
+ required: true,
1501
+ rationale: "Load home-care ICP gates, source lanes, qualification thresholds, and home-care exclusion logic."
1502
+ }],
1503
+ constraints: {
1504
+ deliverabilityNotes: [
1505
+ "Company proof and strict ICP gate must pass before contact search, email finding, Signaliz signals, or export.",
1506
+ "Home health is an exclusion signal, not a synonym for home care."
1507
+ ]
1508
+ },
1509
+ signalizDefaults: {
1510
+ copy: {
1511
+ offerContext: "Use angles around after-hours shift recovery, billing/payroll exceptions, multi-location consistency, and caregiver retention only when supported by evidence."
1512
+ }
1513
+ },
1514
+ agencyContext: {
1515
+ partnerEcosystem: ["clay", "octave", "signaliz", "instantly", "nango"]
1516
+ },
1517
+ operatingPlaybookSlugs: ["proof-first-vertical-gate", "domain-first-recovery", "table-workflow-handoff"]
1518
+ },
1519
+ {
1520
+ slug: "agency-founder-led",
1521
+ label: "Founder-Led Agency Services",
1522
+ aliases: ["agency founder", "founder-led agency", "agency-founder-led"],
1523
+ defaultTargetCount: 3e3,
1524
+ campaignName: "Founder-Led Agency Executive Campaign",
1525
+ accountContext: [
1526
+ "Strategy template: agency founder, owner, CEO, and executive sourcing across marketing services, creative, web, PR, ecommerce, paid media, SEO, content, and specialist digital agencies.",
1527
+ "Use suppression files, company-domain pool review, people/email verification queues, and final approval gates before any delivery action."
1528
+ ].join(" "),
1529
+ icp: {
1530
+ personas: ["Founder", "Owner", "CEO", "Managing Partner", "President", "Agency Executive"],
1531
+ industries: [
1532
+ "Marketing services",
1533
+ "Advertising services",
1534
+ "Digital marketing agency",
1535
+ "Creative agency",
1536
+ "PR and communications",
1537
+ "Ecommerce agency",
1538
+ "Paid media agency",
1539
+ "SEO agency",
1540
+ "Content agency"
1541
+ ],
1542
+ companySizes: ["11-50", "25-150", "51-200"],
1543
+ geographies: ["United States"],
1544
+ keywords: [
1545
+ "agency founder",
1546
+ "performance marketing",
1547
+ "paid media",
1548
+ "SEO",
1549
+ "content",
1550
+ "creative",
1551
+ "web design",
1552
+ "brand agency",
1553
+ "PR communications",
1554
+ "Shopify",
1555
+ "Klaviyo"
1556
+ ],
1557
+ exclusions: ["enterprise holding company", "staffing", "recruiting", "software-only vendor", "freelancer-only profile"],
1558
+ requireVerifiedEmail: true
1559
+ },
1560
+ builtIns: ["lead_generation", "email_finding", "email_verification", "signals"],
1561
+ preferredProviders: ["signaliz_native", "octave"],
1562
+ memoryQueries: [{
1563
+ query: "agency founder owner CEO marketing services suppression domain pool email verification final approval gate",
1564
+ scopes: ["workspace", "operator_notes"],
1565
+ topK: 10,
1566
+ required: true,
1567
+ rationale: "Load agency-segment sourcing lanes, suppression rules, and verification workflow lessons."
1568
+ }],
1569
+ constraints: {
1570
+ deliverabilityNotes: [
1571
+ "Keep email and domain suppression visible in the plan.",
1572
+ "Do not export or send until the final verified file and suppression checks are approved."
1573
+ ]
1574
+ },
1575
+ agencyContext: {
1576
+ partnerEcosystem: ["signaliz", "octave", "instantly", "nango"]
1577
+ },
1578
+ operatingPlaybookSlugs: ["net-new-suppressed-list", "signal-led-copy-approval", "table-workflow-handoff"]
1579
+ },
1580
+ {
1581
+ slug: "cloud-infrastructure-displacement",
1582
+ label: "Cloud Infrastructure Displacement",
1583
+ aliases: ["cloud displacement", "private cloud displacement", "cloud infrastructure", "cloud-infrastructure-displacement"],
1584
+ defaultTargetCount: 3e3,
1585
+ campaignName: "Cloud Infrastructure Displacement Campaign",
1586
+ accountContext: [
1587
+ "Strategy template: managed infrastructure, private cloud, disaster recovery, colocation, and VMware/Broadcom displacement motions.",
1588
+ "The spend-efficient ladder is Signaliz company search, Octave company qualification, Signaliz people search, Octave person qualification, then Signaliz email finding and verification."
1589
+ ].join(" "),
1590
+ icp: {
1591
+ personas: [
1592
+ "CTO",
1593
+ "CIO",
1594
+ "CISO",
1595
+ "CFO tied to cloud spend",
1596
+ "VP Engineering",
1597
+ "VP Infrastructure",
1598
+ "VP Cloud",
1599
+ "Head of Platform",
1600
+ "Director IT",
1601
+ "Cloud Architect",
1602
+ "Infrastructure Architect"
1603
+ ],
1604
+ industries: [
1605
+ "SaaS",
1606
+ "Software",
1607
+ "Cybersecurity",
1608
+ "Fintech",
1609
+ "Healthcare technology",
1610
+ "Compliance and GRC",
1611
+ "DevOps",
1612
+ "Infrastructure",
1613
+ "Observability"
1614
+ ],
1615
+ companySizes: ["$10M-$500M revenue", "50-1500 employees"],
1616
+ geographies: ["United States"],
1617
+ keywords: [
1618
+ "VMware Broadcom",
1619
+ "VxRail",
1620
+ "cloud cost pressure",
1621
+ "private cloud",
1622
+ "Proxmox",
1623
+ "Hyper-V",
1624
+ "managed infrastructure",
1625
+ "DRaaS",
1626
+ "colocation",
1627
+ "uptime",
1628
+ "reliability"
1629
+ ],
1630
+ exclusions: [
1631
+ "MSP competitor",
1632
+ "hosting provider",
1633
+ "data center competitor",
1634
+ "staffing",
1635
+ "recruiting",
1636
+ "international-only",
1637
+ "procurement-only",
1638
+ "AI GPU-heavy infrastructure"
1639
+ ],
1640
+ requireVerifiedEmail: true
1641
+ },
1642
+ builtIns: ["lead_generation", "email_finding", "email_verification", "signals"],
1643
+ preferredProviders: ["signaliz_native", "octave"],
1644
+ memoryQueries: [{
1645
+ query: "cloud hosting infrastructure VMware Broadcom qualification verified email persona trigger SKU mapping",
1646
+ scopes: ["workspace", "operator_notes"],
1647
+ topK: 10,
1648
+ required: true,
1649
+ rationale: "Load cloud-infrastructure qualification order, persona clusters, trigger/SKU mapping, and verified-list QA rules."
1650
+ }],
1651
+ constraints: {
1652
+ deliverabilityNotes: [
1653
+ "Qualify accounts and people before email verification.",
1654
+ "If signal enrichment is deferred or unavailable, state it plainly instead of inventing evidence."
1655
+ ]
1656
+ },
1657
+ signalizDefaults: {
1658
+ copy: {
1659
+ offerContext: "Map pain to routes such as VMware/Broadcom exit, cloud cost reduction, infrastructure modernization, compliance gap, managed infrastructure, private cloud, Proxmox/Hyper-V, colocation, or DRaaS."
1660
+ }
1661
+ },
1662
+ agencyContext: {
1663
+ partnerEcosystem: ["signaliz", "octave", "instantly", "nango"]
1664
+ },
1665
+ operatingPlaybookSlugs: ["proof-first-vertical-gate", "domain-first-recovery", "signal-led-copy-approval"]
1666
+ }
1667
+ ];
1187
1668
  var CampaignBuilderAgent = class {
1188
1669
  constructor(client) {
1189
1670
  this.client = client;
1190
1671
  }
1191
1672
  async createPlan(request, options = {}) {
1673
+ const resolvedRequest = applyCampaignBuilderStrategyTemplate(request);
1192
1674
  const warnings = [];
1193
- const workspaceContext = request.workspaceContext ?? await this.getWorkspaceContext(warnings);
1194
- const scopeResult = options.scopeCampaign === false ? void 0 : await this.scopeCampaign(request, warnings);
1675
+ const workspaceContext = resolvedRequest.workspaceContext ?? await this.getWorkspaceContext(warnings);
1676
+ const scopeResult = options.scopeCampaign === false ? void 0 : await this.scopeCampaign(resolvedRequest, warnings);
1195
1677
  if (options.discoverCapabilities !== false) {
1196
- await this.discoverPlannedRoutes(request, warnings);
1678
+ await this.discoverPlannedRoutes(resolvedRequest, warnings);
1197
1679
  }
1198
- return createCampaignBuilderAgentPlan(request, {
1680
+ const plan = createCampaignBuilderAgentPlan(resolvedRequest, {
1199
1681
  workspaceContext,
1200
1682
  scopeBuildArgs: asRecord(scopeResult?.build_campaign_args ?? scopeResult?.buildCampaignArgs),
1201
1683
  warnings
1202
1684
  });
1685
+ if (options.includeStrategyMemoryStatus !== false) {
1686
+ await this.attachStrategyMemoryStatus(plan, warnings);
1687
+ }
1688
+ if (options.includeKernelPlan !== false) {
1689
+ await this.attachKernelCampaignBuildPlan(plan, warnings);
1690
+ }
1691
+ if (options.includeDeliveryRisk !== false) {
1692
+ await this.attachDeliveryRiskPreflight(plan, warnings);
1693
+ }
1694
+ return plan;
1695
+ }
1696
+ async commitPlan(plan, options = {}) {
1697
+ const writeMode = options.confirm === true && options.dryRun === false;
1698
+ if (writeMode && !options.approvedBy) {
1699
+ throw new Error("Campaign builder plan commit requires approvedBy before writing state");
1700
+ }
1701
+ const plannerStep = plan.mcpFlow.find((step) => step.id === "agency-campaign-build-plan");
1702
+ const plannerArgs = asRecord(plannerStep?.arguments);
1703
+ const commitArgs = compact({
1704
+ campaign_id: plan.buildRequest.gtmCampaignId,
1705
+ name: plan.campaignName,
1706
+ campaign_brief: plan.buildRequest.prompt || plan.goal,
1707
+ target_icp: plan.buildRequest.icp ? buildGtmTargetIcpContext(plan.buildRequest.icp) : void 0,
1708
+ lead_count: plan.targetCount,
1709
+ layers: plannerArgs.layers,
1710
+ preferred_providers: plannerArgs.preferred_providers,
1711
+ plan_snapshot: Object.keys(asRecord(plan.kernelPlan)).length > 0 ? plan.kernelPlan : buildFallbackPlanSnapshot(plan),
1712
+ send_config: plan.buildRequest.delivery ? {
1713
+ delivery: plan.buildRequest.delivery,
1714
+ approval_required: true
1715
+ } : void 0,
1716
+ brain_config: compact({
1717
+ campaign_builder_agent_v1: {
1718
+ plan_id: plan.planId,
1719
+ kernel_plan_attached: Object.keys(asRecord(plan.kernelPlan)).length > 0,
1720
+ approval_ids: plan.approvals.map((approval) => approval.id)
1721
+ },
1722
+ brain_defaults: plan.buildRequest.brainDefaults,
1723
+ brain_preflight: plan.buildRequest.brainPreflight,
1724
+ delivery_risk_preflight: plan.buildRequest.deliveryRisk,
1725
+ delivery_risk: plan.buildRequest.deliveryRisk
1726
+ }),
1727
+ metadata: {
1728
+ campaign_builder_agent_v1: {
1729
+ plan_id: plan.planId,
1730
+ source: "campaign-builder-agent",
1731
+ approval_required: plan.approvals.some((approval) => approval.blocking),
1732
+ approval_ids: plan.approvals.map((approval) => approval.id),
1733
+ estimated_credits: plan.estimatedCredits
1734
+ },
1735
+ brain_delivery_risk_preflight: plan.buildRequest.deliveryRisk,
1736
+ delivery_risk: plan.buildRequest.deliveryRisk
1737
+ },
1738
+ approval_required: plan.approvals.some((approval) => approval.blocking),
1739
+ actor_type: "agent",
1740
+ actor_id: options.approvedBy,
1741
+ rationale: options.rationale || "Committed a reviewed strategy-template campaign-builder plan before execution.",
1742
+ idempotency_key: options.idempotencyKey,
1743
+ dry_run: !writeMode,
1744
+ confirm: writeMode
1745
+ });
1746
+ const data = asRecord(await this.callMcp("gtm_campaign_build_plan_commit", commitArgs));
1747
+ const result = mapPlanCommitResult(data);
1748
+ if (result.wroteState && result.campaignId) {
1749
+ plan.buildRequest.gtmCampaignId = result.campaignId;
1750
+ refreshBuildStepArguments(plan);
1751
+ }
1752
+ return result;
1203
1753
  }
1204
1754
  async dryRunPlan(plan, options) {
1205
1755
  let args = buildCampaignArgs({
@@ -1234,6 +1784,15 @@ var CampaignBuilderAgent = class {
1234
1784
  if (missing.length > 0) {
1235
1785
  throw new Error(`Campaign builder approval is incomplete: ${missing.map((a) => a.label).join(", ")}`);
1236
1786
  }
1787
+ if (options?.commitBeforeLaunch && !plan.buildRequest.gtmCampaignId) {
1788
+ await this.commitPlan(plan, {
1789
+ confirm: true,
1790
+ dryRun: false,
1791
+ approvedBy: approval.approvedBy,
1792
+ idempotencyKey: options.idempotencyKey ? `${options.idempotencyKey}:plan-commit` : void 0,
1793
+ rationale: "Committed reviewed campaign-builder plan immediately before approved launch."
1794
+ });
1795
+ }
1237
1796
  let args = buildCampaignArgs({
1238
1797
  ...plan.buildRequest,
1239
1798
  dryRun: false,
@@ -1280,8 +1839,8 @@ var CampaignBuilderAgent = class {
1280
1839
  try {
1281
1840
  return await this.callMcp("scope_campaign", {
1282
1841
  prompt: request.goal,
1283
- client_name: request.clientName,
1284
- client_context: request.clientContext,
1842
+ account_label: campaignBuilderAccountLabel(request),
1843
+ account_context: campaignBuilderAccountContext(request),
1285
1844
  campaign_goal: request.goal,
1286
1845
  target_count: request.targetCount,
1287
1846
  approval_policy: request.approvalPolicy?.requireHumanApproval ? "human_required" : "standard"
@@ -1306,25 +1865,70 @@ var CampaignBuilderAgent = class {
1306
1865
  }
1307
1866
  }
1308
1867
  }
1868
+ async attachStrategyMemoryStatus(plan, warnings) {
1869
+ const statusStep = plan.mcpFlow.find((step) => step.id === "strategy-memory-status");
1870
+ if (!statusStep) return;
1871
+ try {
1872
+ const status = asRecord(await this.callMcp("gtm_campaign_strategy_memory_status", asRecord(statusStep.arguments)));
1873
+ plan.strategyMemoryStatus = status;
1874
+ const blockers = arrayOfStrings(status.blockers) ?? [];
1875
+ if (status.ready === false || blockers.length > 0) {
1876
+ warnings.push(`Strategy memory readiness is incomplete: ${blockers.join("; ") || "missing required strategy or workflow memory"}`);
1877
+ }
1878
+ } catch (error) {
1879
+ warnings.push(`Strategy memory readiness check failed: ${errorMessage(error)}`);
1880
+ }
1881
+ }
1882
+ async attachKernelCampaignBuildPlan(plan, warnings) {
1883
+ const plannerStep = plan.mcpFlow.find((step) => step.id === "agency-campaign-build-plan");
1884
+ if (!plannerStep) return;
1885
+ try {
1886
+ const kernelPlan = await this.callMcp("gtm_campaign_build_plan", asRecord(plannerStep.arguments));
1887
+ plan.kernelPlan = asRecord(kernelPlan);
1888
+ const brainDefaults = asRecord(plan.kernelPlan.brain_defaults ?? plan.kernelPlan.brainDefaults);
1889
+ if (Object.keys(brainDefaults).length > 0 && Object.keys(asRecord(plan.buildRequest.brainDefaults)).length === 0) {
1890
+ plan.buildRequest.brainDefaults = brainDefaults;
1891
+ refreshBuildStepArguments(plan);
1892
+ }
1893
+ } catch (error) {
1894
+ warnings.push(`GTM Kernel campaign build plan failed: ${errorMessage(error)}`);
1895
+ }
1896
+ }
1897
+ async attachDeliveryRiskPreflight(plan, warnings) {
1898
+ if (Object.keys(asRecord(plan.buildRequest.deliveryRisk)).length > 0) return;
1899
+ const riskStep = plan.mcpFlow.find((step) => step.tool === "gtm_brain_delivery_risk");
1900
+ if (!riskStep) return;
1901
+ try {
1902
+ const deliveryRisk = asRecord(await this.callMcp("gtm_brain_delivery_risk", asRecord(riskStep.arguments)));
1903
+ if (Object.keys(deliveryRisk).length > 0) {
1904
+ plan.buildRequest.deliveryRisk = deliveryRisk;
1905
+ refreshBuildStepArguments(plan);
1906
+ }
1907
+ } catch (error) {
1908
+ warnings.push(`GTM Brain delivery risk preflight failed: ${errorMessage(error)}`);
1909
+ }
1910
+ }
1309
1911
  async callMcp(tool, args) {
1310
1912
  return this.client.mcp("tools/call", { name: tool, arguments: compact(args) });
1311
1913
  }
1312
1914
  };
1313
1915
  function createCampaignBuilderAgentPlan(request, context = {}) {
1314
- const defaults = mergeDefaults(request.signalizDefaults);
1315
- const targetCount = request.targetCount ?? numberOrUndefined2(context.scopeBuildArgs?.target_count) ?? 100;
1316
- const campaignName = request.campaignName ?? stringValue(context.scopeBuildArgs?.name) ?? titleFromGoal(request.goal);
1317
- const workspaceContext = context.workspaceContext ?? request.workspaceContext ?? {};
1318
- const memory = normalizeMemory(request);
1319
- const routes = normalizeRoutes(request);
1320
- const estimatedCredits = estimateCredits(request, defaults, targetCount);
1321
- const buildRequest = createBuildRequest(request, defaults, targetCount, campaignName, context.scopeBuildArgs, routes, memory, context.scopeBrainPreflight);
1916
+ const resolvedRequest = applyCampaignBuilderStrategyTemplate(request);
1917
+ const defaults = mergeDefaults(resolvedRequest.signalizDefaults);
1918
+ const targetCount = resolvedRequest.targetCount ?? numberOrUndefined2(context.scopeBuildArgs?.target_count) ?? 100;
1919
+ const campaignName = resolvedRequest.campaignName ?? stringValue(context.scopeBuildArgs?.name) ?? titleFromGoal(resolvedRequest.goal);
1920
+ const workspaceContext = context.workspaceContext ?? resolvedRequest.workspaceContext ?? {};
1921
+ const memory = normalizeMemory(resolvedRequest);
1922
+ const routes = normalizeRoutes(resolvedRequest);
1923
+ const operatingPlaybooks = getCampaignBuilderOperatingPlaybooksForRequest(resolvedRequest);
1924
+ const estimatedCredits = estimateCredits(resolvedRequest, defaults, targetCount);
1925
+ const buildRequest = createBuildRequest(resolvedRequest, defaults, targetCount, campaignName, context.scopeBuildArgs, routes, memory, context.scopeBrainPreflight);
1322
1926
  const brainPreflight = asRecord(buildRequest.brainPreflight);
1323
- const approvals = deriveApprovals(request, routes, memory, estimatedCredits, defaults.delivery?.approvalRequired !== false);
1927
+ const approvals = deriveApprovals(resolvedRequest, routes, memory, estimatedCredits, defaults.delivery?.approvalRequired !== false);
1324
1928
  return {
1325
- planId: `cbp_${hashString(JSON.stringify({ goal: request.goal, campaignName, targetCount, routes }))}`,
1929
+ planId: `cbp_${hashString(JSON.stringify({ goal: resolvedRequest.goal, campaignName, targetCount, routes }))}`,
1326
1930
  campaignName,
1327
- goal: request.goal,
1931
+ goal: resolvedRequest.goal,
1328
1932
  targetCount,
1329
1933
  workspaceContext,
1330
1934
  memory,
@@ -1337,7 +1941,8 @@ function createCampaignBuilderAgentPlan(request, context = {}) {
1337
1941
  approvals,
1338
1942
  buildRequest,
1339
1943
  brainPreflight,
1340
- mcpFlow: createMcpFlow(request, buildRequest, routes, memory, approvals),
1944
+ operatingPlaybooks,
1945
+ mcpFlow: createMcpFlow(resolvedRequest, buildRequest, routes, memory, approvals),
1341
1946
  estimatedCredits,
1342
1947
  warnings: context.warnings ?? []
1343
1948
  };
@@ -1358,6 +1963,256 @@ function getMissingCampaignBuilderApprovals(plan, approval) {
1358
1963
  return false;
1359
1964
  });
1360
1965
  }
1966
+ function createCampaignBuilderApproval(plan, input) {
1967
+ return {
1968
+ ...input,
1969
+ planId: plan.planId,
1970
+ approvedAt: (/* @__PURE__ */ new Date()).toISOString()
1971
+ };
1972
+ }
1973
+ function getCampaignBuilderStrategyTemplate(value) {
1974
+ const normalized = normalizeTemplateKey(value);
1975
+ if (!normalized) return void 0;
1976
+ return CAMPAIGN_BUILDER_STRATEGY_TEMPLATES.find(
1977
+ (template) => template.slug === normalized || template.aliases.some((alias) => normalizeTemplateKey(alias) === normalized)
1978
+ );
1979
+ }
1980
+ function getCampaignBuilderOperatingPlaybook(value) {
1981
+ const normalized = normalizeTemplateKey(value);
1982
+ if (!normalized) return void 0;
1983
+ return CAMPAIGN_BUILDER_OPERATING_PLAYBOOKS.find((playbook) => playbook.slug === normalized);
1984
+ }
1985
+ function getCampaignBuilderOperatingPlaybooksForRequest(request) {
1986
+ const template = getCampaignBuilderStrategyTemplate(request.strategyTemplate);
1987
+ const slugs = uniqueStrings([
1988
+ ...template?.operatingPlaybookSlugs ?? [],
1989
+ ...request.operatingPlaybooks ?? []
1990
+ ]);
1991
+ return slugs.map(getCampaignBuilderOperatingPlaybook).filter((playbook) => Boolean(playbook));
1992
+ }
1993
+ function applyCampaignBuilderStrategyTemplate(request) {
1994
+ const template = getCampaignBuilderStrategyTemplate(request.strategyTemplate);
1995
+ if (!template) return request;
1996
+ return {
1997
+ ...request,
1998
+ strategyTemplate: template.slug,
1999
+ campaignName: request.campaignName ?? template.campaignName,
2000
+ accountContext: mergeText(template.accountContext, campaignBuilderAccountContext(request)),
2001
+ targetCount: request.targetCount ?? template.defaultTargetCount,
2002
+ icp: mergeIcp(template.icp, request.icp),
2003
+ builtIns: request.builtIns ?? template.builtIns,
2004
+ operatingPlaybooks: uniqueStrings([
2005
+ ...template.operatingPlaybookSlugs,
2006
+ ...request.operatingPlaybooks ?? []
2007
+ ]),
2008
+ preferredProviders: uniqueStrings([
2009
+ ...template.preferredProviders,
2010
+ ...request.preferredProviders ?? []
2011
+ ]),
2012
+ memory: mergeMemoryPlan({
2013
+ enabled: true,
2014
+ useWorkspaceHistory: true,
2015
+ useNetworkPatterns: request.memory?.useNetworkPatterns,
2016
+ privacyMode: request.memory?.privacyMode,
2017
+ queries: template.memoryQueries
2018
+ }, request.memory),
2019
+ constraints: mergeConstraints(template.constraints, request.constraints),
2020
+ signalizDefaults: mergeSignalizDefaultOverrides(template.signalizDefaults, request.signalizDefaults),
2021
+ agencyContext: mergeAgencyContext(template.agencyContext, request.agencyContext)
2022
+ };
2023
+ }
2024
+ function createCampaignBuilderAgentRequestTemplate(input = {}) {
2025
+ const builtIns = new Set(input.builtIns ?? DEFAULT_CAMPAIGN_BUILDER_BUILT_INS);
2026
+ if (input.includeLocalLeads) builtIns.add("local_leads");
2027
+ const integrations = input.integrations ?? (input.includeCustomToolPlaceholder ? [createCampaignBuilderToolRoute({
2028
+ provider: "custom_mcp",
2029
+ layer: "enrichment",
2030
+ gtmLayers: ["company_enrichment"],
2031
+ toolName: "workspace_enrich",
2032
+ mcpServerName: "workspace-mcp",
2033
+ label: "Workspace enrichment MCP",
2034
+ mode: "if_available",
2035
+ approvalRequired: true
2036
+ })] : void 0);
2037
+ const preferredProviders = uniqueStrings([
2038
+ ...input.preferredProviders ?? [],
2039
+ ...input.includeNango === false ? [] : ["nango"]
2040
+ ]);
2041
+ const templated = applyCampaignBuilderStrategyTemplate({
2042
+ goal: input.goal || "Build a strategy-template campaign for mature operators in the target ICP.",
2043
+ strategyTemplate: input.strategyTemplate || "non-medical-home-care",
2044
+ campaignName: input.campaignName,
2045
+ accountLabel: input.accountLabel || "Workspace Campaign",
2046
+ accountContext: input.accountContext || "Use private workspace memory, current suppression rules, verified-email quality gates, and approval-gated provider routes.",
2047
+ targetCount: input.targetCount,
2048
+ icp: input.icp ?? {
2049
+ personas: ["Operations leader", "Founder", "Revenue leader"],
2050
+ industries: ["B2B services", "Vertical software", "Local operators"],
2051
+ geographies: ["United States"],
2052
+ keywords: ["growth", "operations", "customer acquisition"],
2053
+ requireVerifiedEmail: true
2054
+ },
2055
+ builtIns: [...builtIns],
2056
+ integrations,
2057
+ customerTools: input.customerTools,
2058
+ preferredProviders,
2059
+ constraints: input.constraints,
2060
+ workspaceContext: input.workspaceContext,
2061
+ brainDefaults: input.brainDefaults,
2062
+ deliveryRisk: input.deliveryRisk,
2063
+ gtmCampaignId: input.gtmCampaignId
2064
+ });
2065
+ return compact({
2066
+ ...templated,
2067
+ memory: mergeMemoryPlan({
2068
+ enabled: true,
2069
+ useWorkspaceHistory: true,
2070
+ useNetworkPatterns: false,
2071
+ privacyMode: "anonymized_patterns",
2072
+ queries: [{
2073
+ query: `${templated.strategyTemplate || "strategy-template"} campaign reply patterns, objections, qualification gates, and verified-email QA`,
2074
+ scopes: ["workspace", "operator_notes"],
2075
+ topK: 10,
2076
+ required: true,
2077
+ rationale: "Load approved private strategy and workflow patterns before campaign planning."
2078
+ }]
2079
+ }, input.memory),
2080
+ agencyContext: mergeAgencyContext({
2081
+ strategyModel: "strategy_template",
2082
+ includeStrategyPatterns: true,
2083
+ includeWorkflowPatterns: true,
2084
+ includeNangoCatalog: true,
2085
+ partnerEcosystem: input.includeNango === false ? ["signaliz"] : ["signaliz", "nango"]
2086
+ }, input.agencyContext),
2087
+ signalizDefaults: mergeSignalizDefaultOverrides({
2088
+ maxCredits: input.signalizDefaults?.maxCredits,
2089
+ delivery: {
2090
+ enabled: true,
2091
+ destinationType: input.signalizDefaults?.delivery?.destinationType ?? "json",
2092
+ approvalRequired: true
2093
+ }
2094
+ }, input.signalizDefaults),
2095
+ approvalPolicy: {
2096
+ requireHumanApproval: true,
2097
+ maxCreditsWithoutApproval: 0,
2098
+ requireApprovalFor: DEFAULT_CAMPAIGN_BUILDER_APPROVAL_TYPES,
2099
+ ...input.approvalPolicy
2100
+ }
2101
+ });
2102
+ }
2103
+ function createCampaignBuilderToolRoute(input) {
2104
+ return {
2105
+ provider: input.provider ?? "custom_mcp",
2106
+ layer: input.layer,
2107
+ toolName: input.toolName,
2108
+ mcpServerName: input.mcpServerName,
2109
+ label: input.label,
2110
+ mode: input.mode ?? "if_available",
2111
+ gtmLayer: input.gtmLayer,
2112
+ gtmLayers: input.gtmLayers,
2113
+ approvalRequired: input.approvalRequired ?? input.mode === "required",
2114
+ config: input.config,
2115
+ rationale: `${input.label ?? input.provider ?? "Custom tool"} is a user-provided campaign-builder route for ${input.layer}.`
2116
+ };
2117
+ }
2118
+ function normalizeTemplateKey(value) {
2119
+ return String(value || "").trim().toLowerCase().replace(/[_\s]+/g, "-");
2120
+ }
2121
+ function mergeText(base, override) {
2122
+ if (base && override && !base.includes(override)) return `${base}
2123
+ ${override}`;
2124
+ return override ?? base;
2125
+ }
2126
+ function mergeIcp(base, override) {
2127
+ if (!base) return override;
2128
+ if (!override) return base;
2129
+ return {
2130
+ ...base,
2131
+ ...override,
2132
+ personas: uniqueStrings([...base.personas ?? [], ...override.personas ?? []]),
2133
+ industries: uniqueStrings([...base.industries ?? [], ...override.industries ?? []]),
2134
+ companySizes: uniqueStrings([...base.companySizes ?? [], ...override.companySizes ?? []]),
2135
+ geographies: uniqueStrings([...base.geographies ?? [], ...override.geographies ?? []]),
2136
+ keywords: uniqueStrings([...base.keywords ?? [], ...override.keywords ?? []]),
2137
+ exclusions: uniqueStrings([...base.exclusions ?? [], ...override.exclusions ?? []]),
2138
+ requireVerifiedEmail: override.requireVerifiedEmail ?? base.requireVerifiedEmail
2139
+ };
2140
+ }
2141
+ function mergeMemoryPlan(base, override) {
2142
+ const queries = dedupeMemoryQueries([...base.queries ?? [], ...override?.queries ?? []]);
2143
+ return {
2144
+ ...base,
2145
+ ...override,
2146
+ queries: queries.length > 0 ? queries : void 0,
2147
+ enabled: override?.enabled ?? base.enabled,
2148
+ useWorkspaceHistory: override?.useWorkspaceHistory ?? base.useWorkspaceHistory,
2149
+ useNetworkPatterns: override?.useNetworkPatterns ?? base.useNetworkPatterns,
2150
+ privacyMode: override?.privacyMode ?? base.privacyMode
2151
+ };
2152
+ }
2153
+ function dedupeMemoryQueries(queries) {
2154
+ const seen = /* @__PURE__ */ new Set();
2155
+ return queries.filter((query) => {
2156
+ const key = query.query.trim().toLowerCase();
2157
+ if (!key || seen.has(key)) return false;
2158
+ seen.add(key);
2159
+ return true;
2160
+ });
2161
+ }
2162
+ function mergeConstraints(base, override) {
2163
+ if (!base) return override;
2164
+ if (!override) return base;
2165
+ return {
2166
+ ...base,
2167
+ ...override,
2168
+ geographies: uniqueStrings([...base.geographies ?? [], ...override.geographies ?? []]),
2169
+ exclusions: uniqueStrings([...base.exclusions ?? [], ...override.exclusions ?? []]),
2170
+ deliverabilityNotes: uniqueStrings([...base.deliverabilityNotes ?? [], ...override.deliverabilityNotes ?? []]),
2171
+ maxDailySends: override.maxDailySends ?? base.maxDailySends
2172
+ };
2173
+ }
2174
+ function mergeSignalizDefaultOverrides(base, override) {
2175
+ if (!base) return override;
2176
+ if (!override) return base;
2177
+ return {
2178
+ ...base,
2179
+ ...override,
2180
+ signals: { ...base.signals, ...override.signals },
2181
+ qualification: { ...base.qualification, ...override.qualification },
2182
+ copy: { ...base.copy, ...override.copy },
2183
+ delivery: { ...base.delivery, ...override.delivery }
2184
+ };
2185
+ }
2186
+ function mergeAgencyContext(base, override) {
2187
+ if (!base) return override;
2188
+ if (!override) return base;
2189
+ return {
2190
+ ...base,
2191
+ ...override,
2192
+ partnerEcosystem: uniqueStrings([...base.partnerEcosystem ?? [], ...override.partnerEcosystem ?? []]),
2193
+ strategyModel: override.strategyModel ?? base.strategyModel,
2194
+ includeStrategyPatterns: override.includeStrategyPatterns ?? base.includeStrategyPatterns,
2195
+ includeWorkflowPatterns: override.includeWorkflowPatterns ?? base.includeWorkflowPatterns,
2196
+ includeClayPatterns: override.includeClayPatterns ?? base.includeClayPatterns,
2197
+ includeNangoCatalog: override.includeNangoCatalog ?? base.includeNangoCatalog,
2198
+ revenueMotion: override.revenueMotion ?? base.revenueMotion
2199
+ };
2200
+ }
2201
+ function campaignBuilderStrategyModel(agencyContext) {
2202
+ return agencyContext?.strategyModel ?? "strategy_template";
2203
+ }
2204
+ function campaignBuilderStrategyPatternsEnabled(agencyContext) {
2205
+ return agencyContext?.includeStrategyPatterns ?? true;
2206
+ }
2207
+ function campaignBuilderWorkflowPatternsEnabled(agencyContext) {
2208
+ return agencyContext?.includeWorkflowPatterns ?? agencyContext?.includeClayPatterns ?? true;
2209
+ }
2210
+ function campaignBuilderAccountLabel(request) {
2211
+ return request.accountLabel;
2212
+ }
2213
+ function campaignBuilderAccountContext(request) {
2214
+ return request.accountContext;
2215
+ }
1361
2216
  function mergeDefaults(overrides) {
1362
2217
  return {
1363
2218
  ...DEFAULT_SIGNALIZ_CAMPAIGN_BUILDER_DEFAULTS,
@@ -1370,12 +2225,9 @@ function mergeDefaults(overrides) {
1370
2225
  }
1371
2226
  function normalizeMemory(request) {
1372
2227
  const configured = request.memory ?? {};
1373
- const queries = configured.queries && configured.queries.length > 0 ? configured.queries : [{
1374
- query: request.goal,
1375
- scopes: ["workspace", configured.useNetworkPatterns ? "network_patterns" : "operator_notes"],
1376
- topK: 8,
1377
- rationale: "Seed the campaign plan with prior ICP, angle, source, and reply-performance patterns."
1378
- }];
2228
+ const defaultQueries = defaultAgencyMemoryQueries(request, configured);
2229
+ const configuredQueries = configured.queries ?? [];
2230
+ const queries = configuredQueries.length > 0 ? request.strategyTemplate ? dedupeMemoryQueries([...configuredQueries, ...defaultQueries]) : configuredQueries : defaultQueries;
1379
2231
  return {
1380
2232
  enabled: configured.enabled !== false,
1381
2233
  queries,
@@ -1384,40 +2236,130 @@ function normalizeMemory(request) {
1384
2236
  privacyMode: configured.privacyMode ?? (configured.useNetworkPatterns ? "anonymized_patterns" : "workspace_only")
1385
2237
  };
1386
2238
  }
2239
+ function defaultAgencyMemoryQueries(request, configured) {
2240
+ const operatingPlaybookTerms = getCampaignBuilderOperatingPlaybooksForRequest(request).flatMap((playbook) => [playbook.label, ...playbook.memoryKeywords]).join(" ");
2241
+ const queries = [{
2242
+ query: request.goal,
2243
+ scopes: ["workspace", configured.useNetworkPatterns ? "network_patterns" : "operator_notes"],
2244
+ topK: 8,
2245
+ rationale: "Seed the campaign plan with prior ICP, angle, source, and reply-performance patterns."
2246
+ }];
2247
+ if (campaignBuilderStrategyModel(request.agencyContext) !== "custom" && campaignBuilderStrategyPatternsEnabled(request.agencyContext)) {
2248
+ queries.push({
2249
+ query: [
2250
+ "Private campaign strategy pattern library prior campaign casebook",
2251
+ campaignBuilderAccountLabel(request),
2252
+ operatingPlaybookTerms,
2253
+ request.goal
2254
+ ].filter(Boolean).join(" "),
2255
+ scopes: ["workspace", "operator_notes"],
2256
+ topK: 8,
2257
+ required: true,
2258
+ rationale: "Anchor the plan in private strategy learnings from prior industrial, healthcare, agency-services, infrastructure, recruiting, media, and integration builds."
2259
+ });
2260
+ }
2261
+ if (campaignBuilderWorkflowPatternsEnabled(request.agencyContext)) {
2262
+ queries.push({
2263
+ query: [
2264
+ "Workflow table architecture enrichment qualification copy export gates",
2265
+ request.goal
2266
+ ].filter(Boolean).join(" "),
2267
+ scopes: ["workspace", "operator_notes"],
2268
+ topK: 6,
2269
+ rationale: "Pull workflow patterns for source tables, enrichment order, qualification gates, and handoff controls."
2270
+ });
2271
+ }
2272
+ return queries;
2273
+ }
1387
2274
  function normalizeRoutes(request) {
1388
- const routes = [
1389
- {
1390
- id: "signaliz-source",
2275
+ const routes = builtInRoutesFor(request);
2276
+ routes.push(...routesFromCustomerTools(request.customerTools ?? []));
2277
+ routes.push(...request.integrations ?? []);
2278
+ return routes.map((route, index) => ({
2279
+ ...route,
2280
+ id: route.id ?? `${route.provider}-${route.layer}-${index + 1}`,
2281
+ mode: route.mode ?? "if_available"
2282
+ }));
2283
+ }
2284
+ function builtInRoutesFor(request) {
2285
+ const builtIns = new Set(normalizeBuiltIns(request));
2286
+ const routes = [];
2287
+ if (builtIns.has("lead_generation")) {
2288
+ routes.push({
2289
+ id: "signaliz-lead-generation",
1391
2290
  layer: "source",
2291
+ gtmLayers: ["find_company", "find_people", "lead_generation"],
1392
2292
  provider: "signaliz",
1393
2293
  mode: "required",
1394
2294
  toolName: "generate_leads",
1395
2295
  rationale: "Use Signaliz fresh workspace acquisition as the default source of truth."
1396
- },
1397
- {
1398
- id: "signaliz-verify",
1399
- layer: "qualification",
2296
+ });
2297
+ }
2298
+ if (builtIns.has("local_leads")) {
2299
+ routes.push({
2300
+ id: "signaliz-local-leads",
2301
+ layer: "source",
2302
+ gtmLayer: "local_leads",
2303
+ provider: "signaliz",
2304
+ mode: "if_available",
2305
+ toolName: "generate_local_leads",
2306
+ rationale: "Use Signaliz local-leads sourcing for geography-bound local business campaigns."
2307
+ });
2308
+ }
2309
+ if (builtIns.has("email_finding")) {
2310
+ routes.push({
2311
+ id: "signaliz-email-finding",
2312
+ layer: "enrichment",
2313
+ gtmLayer: "email_finding",
1400
2314
  provider: "signaliz",
1401
2315
  mode: "required",
1402
2316
  toolName: "find_and_verify_emails",
2317
+ rationale: "Find contact emails before verification and campaign handoff."
2318
+ });
2319
+ }
2320
+ if (builtIns.has("email_verification")) {
2321
+ routes.push({
2322
+ id: "signaliz-email-verification",
2323
+ layer: "qualification",
2324
+ gtmLayer: "email_verification",
2325
+ provider: "signaliz",
2326
+ mode: "required",
2327
+ toolName: "verify_emails",
1403
2328
  rationale: "Require verified contactability before sequence delivery."
1404
- },
1405
- {
2329
+ });
2330
+ }
2331
+ if (builtIns.has("signals")) {
2332
+ routes.push({
1406
2333
  id: "signaliz-signals",
1407
2334
  layer: "enrichment",
2335
+ gtmLayer: "company_enrichment",
1408
2336
  provider: "signaliz",
1409
2337
  mode: "if_available",
1410
2338
  toolName: "enrich_company_signals",
1411
2339
  rationale: "Attach current buying signals and evidence for qualification and copy."
1412
- }
1413
- ];
1414
- routes.push(...routesFromCustomerTools(request.customerTools ?? []));
1415
- routes.push(...request.integrations ?? []);
1416
- return routes.map((route, index) => ({
1417
- ...route,
1418
- id: route.id ?? `${route.provider}-${route.layer}-${index + 1}`,
1419
- mode: route.mode ?? "if_available"
1420
- }));
2340
+ });
2341
+ }
2342
+ return routes;
2343
+ }
2344
+ function normalizeBuiltIns(request) {
2345
+ const configured = request.builtIns !== void 0 ? request.builtIns : DEFAULT_CAMPAIGN_BUILDER_BUILT_INS;
2346
+ const builtIns = new Set(configured);
2347
+ if (request.builtIns === void 0 && looksLikeLocalLeadCampaign(request)) {
2348
+ builtIns.add("local_leads");
2349
+ }
2350
+ return [...builtIns].filter(isCampaignBuilderBuiltInTool);
2351
+ }
2352
+ function isCampaignBuilderBuiltInTool(value) {
2353
+ return ["lead_generation", "local_leads", "email_finding", "email_verification", "signals"].includes(String(value));
2354
+ }
2355
+ function looksLikeLocalLeadCampaign(request) {
2356
+ const text = [
2357
+ request.goal,
2358
+ campaignBuilderAccountContext(request),
2359
+ ...request.icp?.industries ?? [],
2360
+ ...request.icp?.keywords ?? []
2361
+ ].filter(Boolean).join(" ").toLowerCase();
2362
+ return /\b(local|google maps|near me|nearby|city|cities|location|locations|home services?|clinics?|restaurants?|contractors?)\b/.test(text);
1421
2363
  }
1422
2364
  function routesFromCustomerTools(tools) {
1423
2365
  return tools.flatMap(
@@ -1435,7 +2377,7 @@ function routesFromCustomerTools(tools) {
1435
2377
  ...tool.config,
1436
2378
  available_tools: tool.availableTools
1437
2379
  },
1438
- rationale: `${tool.label ?? tool.provider} is customer-provided for ${layer}.`
2380
+ rationale: `${tool.label ?? tool.provider} is operator-provided for ${layer}.`
1439
2381
  }))
1440
2382
  );
1441
2383
  }
@@ -1480,6 +2422,7 @@ function createBuildRequest(request, defaults, targetCount, campaignName, scopeB
1480
2422
  return buildRequest;
1481
2423
  }
1482
2424
  function createBrainPreflight(request, buildRequest, routes, memory) {
2425
+ const operatingPlaybooks = getCampaignBuilderOperatingPlaybooksForRequest(request);
1483
2426
  const layers = uniqueStrings([
1484
2427
  "icp",
1485
2428
  "email_finding",
@@ -1489,7 +2432,7 @@ function createBrainPreflight(request, buildRequest, routes, memory) {
1489
2432
  ["instantly", "smartlead", "heyreach"].some((provider) => routes.some((route) => route.provider === provider)) ? "sender" : void 0,
1490
2433
  memory.enabled ? "feedback" : void 0
1491
2434
  ]);
1492
- const providerChain = uniqueStrings(["signaliz", ...routes.map((route) => route.provider)]);
2435
+ const providerChain = uniqueStrings(["signaliz", ...request.preferredProviders ?? [], ...routes.map((route) => route.provider)]);
1493
2436
  const targetIcp = compact({
1494
2437
  personas: buildRequest.icp?.personas,
1495
2438
  industries: buildRequest.icp?.industries,
@@ -1530,6 +2473,13 @@ function createBrainPreflight(request, buildRequest, routes, memory) {
1530
2473
  required: true,
1531
2474
  policy: "Run read-only GTM Brain preflight before build_campaign so learned defaults, memory, and deliverability risk stay attached to the build.",
1532
2475
  layers,
2476
+ operating_playbooks: operatingPlaybooks.map((playbook) => ({
2477
+ slug: playbook.slug,
2478
+ label: playbook.label,
2479
+ quality_gates: playbook.qualityGates,
2480
+ required_fields: playbook.requiredFields,
2481
+ activation_boundary: playbook.activationBoundary
2482
+ })),
1533
2483
  target_icp: targetIcp,
1534
2484
  provider_chain: providerChain,
1535
2485
  lead_source: providerChain[0] ?? "signaliz",
@@ -1662,6 +2612,47 @@ function createMcpFlow(request, buildRequest, routes, memory, approvals) {
1662
2612
  approvalRequired: false
1663
2613
  }
1664
2614
  ];
2615
+ steps.push({
2616
+ id: "gtm-provider-catalog",
2617
+ phase: "plan",
2618
+ tool: "gtm_provider_catalog",
2619
+ arguments: {
2620
+ include_layer_catalog: true,
2621
+ include_planned: true
2622
+ },
2623
+ readOnly: true,
2624
+ approvalRequired: false
2625
+ });
2626
+ if (request.agencyContext?.includeNangoCatalog !== false) {
2627
+ steps.push({
2628
+ id: "nango-tool-catalog",
2629
+ phase: "plan",
2630
+ tool: "nango_mcp_tools_list",
2631
+ arguments: {
2632
+ format: "mcp"
2633
+ },
2634
+ readOnly: true,
2635
+ approvalRequired: false
2636
+ });
2637
+ }
2638
+ if (memory.enabled) {
2639
+ steps.push({
2640
+ id: "strategy-memory-status",
2641
+ phase: "memory",
2642
+ tool: "gtm_campaign_strategy_memory_status",
2643
+ arguments: buildGtmCampaignStrategyMemoryStatusArgs(request, buildRequest),
2644
+ readOnly: true,
2645
+ approvalRequired: false
2646
+ });
2647
+ }
2648
+ steps.push({
2649
+ id: "agency-campaign-build-plan",
2650
+ phase: "plan",
2651
+ tool: "gtm_campaign_build_plan",
2652
+ arguments: buildGtmCampaignBuildPlanArgs(request, buildRequest, routes, memory),
2653
+ readOnly: true,
2654
+ approvalRequired: memory.useNetworkPatterns === true
2655
+ });
1665
2656
  if (memory.enabled) {
1666
2657
  for (const [index, query] of memory.queries.entries()) {
1667
2658
  steps.push({
@@ -1675,6 +2666,25 @@ function createMcpFlow(request, buildRequest, routes, memory, approvals) {
1675
2666
  }
1676
2667
  }
1677
2668
  for (const route of routes) {
2669
+ if (shouldPrepareProviderRoute(route)) {
2670
+ steps.push({
2671
+ id: `prepare-${route.id}`,
2672
+ phase: "plan",
2673
+ tool: "gtm_provider_recipe_prepare",
2674
+ arguments: buildProviderRecipePrepareArgs(route, buildRequest),
2675
+ readOnly: true,
2676
+ approvalRequired: false
2677
+ });
2678
+ steps.push({
2679
+ id: `activate-${route.id}-dry-run`,
2680
+ phase: "plan",
2681
+ tool: "gtm_provider_route_activate",
2682
+ arguments: buildProviderRouteActivateArgs(route, buildRequest),
2683
+ readOnly: true,
2684
+ approvalRequired: false
2685
+ });
2686
+ }
2687
+ const routeApprovalRequired = route.approvalRequired === true || route.provider !== "signaliz" && route.approvalRequired !== false && route.mode === "required" || route.layer === "delivery" || route.layer === "feedback";
1678
2688
  steps.push({
1679
2689
  id: `route-${route.id}`,
1680
2690
  phase: route.layer,
@@ -1686,7 +2696,7 @@ function createMcpFlow(request, buildRequest, routes, memory, approvals) {
1686
2696
  config: route.config
1687
2697
  },
1688
2698
  readOnly: !["delivery", "feedback"].includes(route.layer),
1689
- approvalRequired: route.approvalRequired === true || route.layer === "delivery" || route.layer === "feedback"
2699
+ approvalRequired: routeApprovalRequired
1690
2700
  });
1691
2701
  }
1692
2702
  steps.push({
@@ -1695,8 +2705,8 @@ function createMcpFlow(request, buildRequest, routes, memory, approvals) {
1695
2705
  tool: "scope_campaign",
1696
2706
  arguments: {
1697
2707
  prompt: request.goal,
1698
- client_name: request.clientName,
1699
- client_context: request.clientContext,
2708
+ account_label: campaignBuilderAccountLabel(request),
2709
+ account_context: campaignBuilderAccountContext(request),
1700
2710
  target_count: request.targetCount
1701
2711
  },
1702
2712
  readOnly: true,
@@ -1756,11 +2766,212 @@ function createMcpFlow(request, buildRequest, routes, memory, approvals) {
1756
2766
  readOnly: false,
1757
2767
  approvalRequired: approvals.some((approval) => approval.blocking)
1758
2768
  });
2769
+ const deliveryApprovalArgs = buildDeliveryApprovalArgs(buildRequest);
2770
+ if (deliveryApprovalArgs) {
2771
+ steps.push({
2772
+ id: "delivery-approval",
2773
+ phase: "delivery",
2774
+ tool: "approve_campaign_delivery",
2775
+ arguments: deliveryApprovalArgs,
2776
+ readOnly: false,
2777
+ approvalRequired: true
2778
+ });
2779
+ }
1759
2780
  return steps.map((step) => ({ ...step, arguments: compact(step.arguments) }));
1760
2781
  }
2782
+ function shouldPrepareProviderRoute(route) {
2783
+ return !["signaliz", "csv"].includes(route.provider);
2784
+ }
2785
+ function buildProviderRecipePrepareArgs(route, buildRequest) {
2786
+ const layerCapabilities = uniqueStrings(gtmLayersForRoute(route));
2787
+ const layer = layerCapabilities[0] ?? mapCampaignBuilderLayerToGtmLayer(route.layer) ?? "custom";
2788
+ const config = asRecord(route.config);
2789
+ return compact({
2790
+ provider_id: route.provider,
2791
+ provider_name: route.label,
2792
+ layer,
2793
+ layer_capabilities: layerCapabilities.length > 0 ? layerCapabilities : void 0,
2794
+ invocation_type: route.providerCapability?.invocationType ?? inferProviderInvocationType(route),
2795
+ auth_strategy: inferProviderAuthStrategy(route),
2796
+ workspace_mcp_server_id: stringValue(config.workspace_mcp_server_id ?? config.workspaceMcpServerId ?? route.mcpServerName),
2797
+ workspace_integration_id: stringValue(config.workspace_integration_id ?? config.workspaceIntegrationId),
2798
+ workspace_connection_id: stringValue(config.workspace_connection_id ?? config.workspaceConnectionId),
2799
+ endpoint_url: stringValue(config.endpoint_url ?? config.endpointUrl ?? config.webhook_url ?? config.webhookUrl),
2800
+ request_template: asOptionalRecord(config.request_template ?? config.requestTemplate),
2801
+ response_mapping: asOptionalRecord(config.response_mapping ?? config.responseMapping),
2802
+ input_schema: asOptionalRecord(config.input_schema ?? config.inputSchema ?? route.providerCapability?.exampleInputSchema),
2803
+ output_schema: asOptionalRecord(config.output_schema ?? config.outputSchema ?? route.providerCapability?.exampleOutputSchema),
2804
+ readiness: asOptionalRecord(config.readiness),
2805
+ metadata: compact({
2806
+ source: "campaign-builder-agent",
2807
+ route_id: route.id,
2808
+ campaign_name: buildRequest.name,
2809
+ tool_name: route.toolName,
2810
+ mcp_server_name: route.mcpServerName,
2811
+ dry_run_only: true
2812
+ }),
2813
+ context: compact({
2814
+ source: "campaign-builder-agent",
2815
+ route_id: route.id,
2816
+ gtm_campaign_id: buildRequest.gtmCampaignId
2817
+ }),
2818
+ use_signaliz_fallback: route.routingPolicy?.useSignalizFallback ?? true,
2819
+ priority: numberOrUndefined2(config.priority),
2820
+ status: stringValue(config.status) ?? "needs_setup"
2821
+ });
2822
+ }
2823
+ function buildProviderRouteActivateArgs(route, buildRequest) {
2824
+ const layerCapabilities = uniqueStrings(gtmLayersForRoute(route));
2825
+ const config = asRecord(route.config);
2826
+ return compact({
2827
+ provider_id: route.provider,
2828
+ provider_name: route.label,
2829
+ campaign_id: buildRequest.gtmCampaignId,
2830
+ layer: layerCapabilities[0] ?? mapCampaignBuilderLayerToGtmLayer(route.layer) ?? "custom",
2831
+ layers: layerCapabilities.length > 0 ? layerCapabilities : void 0,
2832
+ invocation_type: route.providerCapability?.invocationType ?? inferProviderInvocationType(route),
2833
+ auth_strategy: inferProviderAuthStrategy(route),
2834
+ workspace_mcp_server_id: stringValue(config.workspace_mcp_server_id ?? config.workspaceMcpServerId ?? route.mcpServerName),
2835
+ workspace_integration_id: stringValue(config.workspace_integration_id ?? config.workspaceIntegrationId),
2836
+ workspace_connection_id: stringValue(config.workspace_connection_id ?? config.workspaceConnectionId),
2837
+ endpoint_url: stringValue(config.endpoint_url ?? config.endpointUrl ?? config.webhook_url ?? config.webhookUrl),
2838
+ route_config: compact({
2839
+ ...asRecord(config.route_config ?? config.routeConfig),
2840
+ source: "campaign-builder-agent",
2841
+ route_id: route.id,
2842
+ tool_name: route.toolName,
2843
+ mcp_server_name: route.mcpServerName
2844
+ }),
2845
+ use_signaliz_fallback: route.routingPolicy?.useSignalizFallback ?? true,
2846
+ priority: numberOrUndefined2(config.priority),
2847
+ dry_run: true,
2848
+ confirm: false
2849
+ });
2850
+ }
2851
+ function inferProviderInvocationType(route) {
2852
+ if (route.provider === "airbyte") return "airbyte";
2853
+ if (route.provider === "nango") return "managed_integration";
2854
+ if (["custom_webhook", "webhook", "clay_webhook"].includes(route.provider)) return "webhook";
2855
+ if (["custom_api", "apollo", "ai_ark", "apify"].includes(route.provider)) return "api";
2856
+ if (route.mcpServerName || route.toolName || ["custom_mcp", "octave"].includes(route.provider)) return "mcp_tool";
2857
+ return "manual";
2858
+ }
2859
+ function inferProviderAuthStrategy(route) {
2860
+ const config = asRecord(route.config);
2861
+ const configured = stringValue(config.auth_strategy ?? config.authStrategy);
2862
+ if (configured) return configured;
2863
+ const invocationType = route.providerCapability?.invocationType ?? inferProviderInvocationType(route);
2864
+ if (invocationType === "webhook") return "webhook_secret";
2865
+ if (invocationType === "mcp_tool") return "mcp_auth";
2866
+ if (invocationType === "managed_integration") return "byo_runtime";
2867
+ if (invocationType === "api" || invocationType === "airbyte") return "integration_key";
2868
+ return void 0;
2869
+ }
2870
+ function refreshBuildStepArguments(plan) {
2871
+ for (const step of plan.mcpFlow) {
2872
+ if (step.id === "dry-run-build") {
2873
+ step.arguments = compact({
2874
+ ...buildCampaignArgs({ ...plan.buildRequest, dryRun: true, confirmSpend: false }),
2875
+ dry_run: true
2876
+ });
2877
+ }
2878
+ if (step.id === "approved-build") {
2879
+ step.arguments = compact({
2880
+ ...buildCampaignArgs({ ...plan.buildRequest, dryRun: false, confirmSpend: true }),
2881
+ required_approvals: plan.approvals.map((approval) => approval.id)
2882
+ });
2883
+ }
2884
+ }
2885
+ }
2886
+ function buildFallbackPlanSnapshot(plan) {
2887
+ const plannerStep = plan.mcpFlow.find((step) => step.id === "agency-campaign-build-plan");
2888
+ return compact({
2889
+ source_tool: "campaign-builder-agent",
2890
+ plan_id: plan.planId,
2891
+ query: asRecord(plannerStep?.arguments),
2892
+ campaign_name: plan.campaignName,
2893
+ goal: plan.goal,
2894
+ target_count: plan.targetCount,
2895
+ approvals: plan.approvals,
2896
+ brain_preflight: plan.brainPreflight,
2897
+ operating_playbooks: plan.operatingPlaybooks
2898
+ });
2899
+ }
2900
+ function mapPlanCommitResult(data) {
2901
+ const campaign = asRecord(data.campaign);
2902
+ const campaignBuild = asRecord(data.campaign_build ?? data.campaignBuild);
2903
+ const committedPlan = asRecord(data.committed_plan ?? data.committedPlan);
2904
+ const commitPlan = asRecord(data.commit_plan ?? data.commitPlan);
2905
+ const campaignArgs = asRecord(commitPlan.campaign_arguments ?? commitPlan.campaignArguments);
2906
+ return {
2907
+ dryRun: data.dry_run === true || data.dryRun === true,
2908
+ wroteState: data.wrote_state === true || data.wroteState === true,
2909
+ campaignId: stringValue(campaign.id ?? committedPlan.campaign_id ?? committedPlan.campaignId ?? commitPlan.campaign_id ?? commitPlan.campaignId ?? campaignArgs.id),
2910
+ campaignBuildId: stringValue(campaignBuild.id ?? committedPlan.campaign_build_id ?? committedPlan.campaignBuildId ?? campaignArgs.campaign_build_id ?? campaignArgs.campaignBuildId),
2911
+ raw: data
2912
+ };
2913
+ }
2914
+ function buildGtmCampaignBuildPlanArgs(request, buildRequest, routes, memory) {
2915
+ const agencyContext = request.agencyContext ?? {};
2916
+ const strategyModel = campaignBuilderStrategyModel(agencyContext);
2917
+ const partnerEcosystem = agencyContext.partnerEcosystem ?? (strategyModel === "custom" ? void 0 : ["clay", "instantly", "nango"]);
2918
+ const layers = uniqueStrings([
2919
+ "icp",
2920
+ buildRequest.icp?.requireVerifiedEmail !== false ? "email_finding" : void 0,
2921
+ buildRequest.icp?.requireVerifiedEmail !== false ? "email_verification" : void 0,
2922
+ ...routes.flatMap(gtmLayersForRoute),
2923
+ buildRequest.delivery?.destinationType === "webhook" ? "destination_export" : void 0,
2924
+ memory.enabled ? "feedback" : void 0
2925
+ ]);
2926
+ const preferredProviders = uniqueStrings([
2927
+ ...request.preferredProviders ?? [],
2928
+ ...routes.map((route) => route.provider).filter((provider) => provider !== "signaliz")
2929
+ ]);
2930
+ const operatingPlaybooks = getCampaignBuilderOperatingPlaybooksForRequest(request);
2931
+ return compact({
2932
+ campaign_id: buildRequest.gtmCampaignId,
2933
+ campaign_brief: buildRequest.prompt || request.goal,
2934
+ strategy_template: request.strategyTemplate,
2935
+ target_icp: buildRequest.icp ? buildGtmTargetIcpContext(buildRequest.icp) : void 0,
2936
+ lead_count: buildRequest.targetCount,
2937
+ layers: layers.length > 0 ? layers : void 0,
2938
+ preferred_providers: preferredProviders.length > 0 ? preferredProviders : void 0,
2939
+ strategy_model: strategyModel,
2940
+ include_strategy_patterns: campaignBuilderStrategyPatternsEnabled(agencyContext),
2941
+ include_workflow_patterns: campaignBuilderWorkflowPatternsEnabled(agencyContext),
2942
+ include_nango_catalog: agencyContext.includeNangoCatalog !== false,
2943
+ partner_ecosystem: partnerEcosystem,
2944
+ operating_playbooks: operatingPlaybooks.map((playbook) => ({
2945
+ slug: playbook.slug,
2946
+ label: playbook.label,
2947
+ quality_gates: playbook.qualityGates,
2948
+ activation_boundary: playbook.activationBoundary
2949
+ })),
2950
+ include_memory: memory.enabled,
2951
+ include_brain: true,
2952
+ include_provider_routes: true,
2953
+ include_failure_patterns: true,
2954
+ include_planned_providers: true,
2955
+ limit: 25
2956
+ });
2957
+ }
2958
+ function buildGtmCampaignStrategyMemoryStatusArgs(request, buildRequest) {
2959
+ return compact({
2960
+ query: request.goal,
2961
+ campaign_brief: buildRequest.prompt || request.goal,
2962
+ strategy_template: request.strategyTemplate,
2963
+ target_icp: buildRequest.icp ? buildGtmTargetIcpContext(buildRequest.icp) : void 0,
2964
+ memory_dimension_filters: request.strategyTemplate ? { strategy_template: request.strategyTemplate } : void 0,
2965
+ require_memory_dimension_match: false,
2966
+ include_samples: false,
2967
+ include_sources: true,
2968
+ days: 3650,
2969
+ limit: 25
2970
+ });
2971
+ }
1761
2972
  function buildGtmMemorySearchArgs(request, routes, query) {
1762
2973
  const layers = uniqueStrings(routes.flatMap(gtmLayersForRoute));
1763
- const providerChain = uniqueStrings(routes.map((route) => route.provider));
2974
+ const providerChain = uniqueStrings([...request.preferredProviders ?? [], ...routes.map((route) => route.provider)]);
1764
2975
  return compact({
1765
2976
  query: query.query,
1766
2977
  limit: query.topK,
@@ -1782,6 +2993,26 @@ function buildGtmTargetIcpContext(icp) {
1782
2993
  require_verified_email: icp.requireVerifiedEmail
1783
2994
  });
1784
2995
  }
2996
+ function mapCampaignBuilderLayerToGtmLayer(layer) {
2997
+ switch (layer) {
2998
+ case "source":
2999
+ return "lead_generation";
3000
+ case "enrichment":
3001
+ return "company_enrichment";
3002
+ case "qualification":
3003
+ return "qualification";
3004
+ case "copy":
3005
+ return "copy_enrichment";
3006
+ case "delivery":
3007
+ return "destination_export";
3008
+ case "feedback":
3009
+ return "feedback";
3010
+ case "approval":
3011
+ return "approval";
3012
+ default:
3013
+ return void 0;
3014
+ }
3015
+ }
1785
3016
  function buildCampaignArgs(request) {
1786
3017
  const args = {
1787
3018
  name: request.name,
@@ -1888,6 +3119,14 @@ function buildExecutionPrepareArgs(request, dryRun, confirmSpend) {
1888
3119
  enhancers: buildArgs2.enhancers
1889
3120
  });
1890
3121
  }
3122
+ function buildDeliveryApprovalArgs(request) {
3123
+ if (request.delivery?.enabled === false || request.delivery?.approvalRequired === false) return void 0;
3124
+ return compact({
3125
+ campaign_build_id: "<campaign_build_id_from_approved_build>",
3126
+ destination_type: request.delivery?.destinationType ?? "json",
3127
+ destination_config: request.delivery?.destinationConfig
3128
+ });
3129
+ }
1891
3130
  function mapBuildResult(data, dryRun) {
1892
3131
  return {
1893
3132
  campaignBuildId: data.campaign_build_id ?? null,
@@ -1962,8 +3201,8 @@ function estimateCredits(request, defaults, targetCount) {
1962
3201
  }
1963
3202
  function buildDescription(request) {
1964
3203
  const parts = [
1965
- request.clientName ? `Client: ${request.clientName}` : void 0,
1966
- request.clientContext ? `Context: ${request.clientContext}` : void 0,
3204
+ campaignBuilderAccountLabel(request) ? `Account label: ${campaignBuilderAccountLabel(request)}` : void 0,
3205
+ campaignBuilderAccountContext(request) ? `Context: ${campaignBuilderAccountContext(request)}` : void 0,
1967
3206
  request.constraints?.deliverabilityNotes?.length ? `Deliverability: ${request.constraints.deliverabilityNotes.join("; ")}` : void 0,
1968
3207
  "Agent-built campaign plan layered on Signaliz kernel and existing MCP tools."
1969
3208
  ];
@@ -1986,6 +3225,10 @@ function compact(record) {
1986
3225
  function asRecord(value) {
1987
3226
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
1988
3227
  }
3228
+ function asOptionalRecord(value) {
3229
+ const record = asRecord(value);
3230
+ return Object.keys(record).length > 0 ? record : void 0;
3231
+ }
1989
3232
  function stringValue(value) {
1990
3233
  return typeof value === "string" && value.length > 0 ? value : void 0;
1991
3234
  }
@@ -3730,7 +4973,7 @@ var GtmKernel = class {
3730
4973
  campaigns: input.campaigns.map(campaignHistoryImportCampaignArgs)
3731
4974
  });
3732
4975
  }
3733
- /** Queue a Trigger-backed campaign history import for larger CMM/client backfills. */
4976
+ /** Queue a Trigger-backed campaign history import for larger private campaign backfills. */
3734
4977
  async importCampaignHistoryRun(input) {
3735
4978
  return this.callMcp("gtm_campaign_history_import_run", {
3736
4979
  source: input.source,
@@ -4177,6 +5420,40 @@ var GtmKernel = class {
4177
5420
  include_layer_catalog: options.includeLayerCatalog
4178
5421
  });
4179
5422
  }
5423
+ /** List private-safe campaign strategy templates agents can merge into campaign build plans. */
5424
+ async campaignStrategyTemplates(options = {}) {
5425
+ return this.callMcp("gtm_campaign_strategy_templates", {
5426
+ strategy_template: options.strategyTemplate,
5427
+ query: options.query,
5428
+ include_details: options.includeDetails
5429
+ });
5430
+ }
5431
+ /** Build the read-only Memory, Brain, risk, and provider-route runbook needed before planning a campaign. */
5432
+ async campaignStartContext(input = {}) {
5433
+ return this.callMcp("gtm_campaign_start_context", {
5434
+ campaign_id: input.campaignId,
5435
+ campaign_build_id: input.campaignBuildId,
5436
+ campaign_brief: input.campaignBrief,
5437
+ strategy_template: input.strategyTemplate,
5438
+ target_icp: input.targetIcp,
5439
+ lead_count: input.leadCount,
5440
+ layers: input.layers,
5441
+ preferred_providers: input.preferredProviders,
5442
+ memory_dimension_filters: input.memoryDimensionFilters,
5443
+ require_memory_dimension_match: input.requireMemoryDimensionMatch,
5444
+ include_memory: input.includeMemory,
5445
+ include_brain: input.includeBrain,
5446
+ include_provider_routes: input.includeProviderRoutes,
5447
+ include_failure_patterns: input.includeFailurePatterns,
5448
+ include_delivery_risk: input.includeDeliveryRisk,
5449
+ include_global_brain: input.includeGlobalBrain,
5450
+ include_planned_providers: input.includePlannedProviders,
5451
+ days: input.days,
5452
+ min_confidence: input.minConfidence,
5453
+ min_sample_size: input.minSampleSize,
5454
+ limit: input.limit
5455
+ });
5456
+ }
4180
5457
  /** Inspect GTM integration activation cards for UI and agent routing without writing state. */
4181
5458
  async integrationsActivationStatus(options = {}) {
4182
5459
  return this.callMcp("gtm_integrations_activation_status", {
@@ -4192,10 +5469,16 @@ var GtmKernel = class {
4192
5469
  campaign_id: input.campaignId,
4193
5470
  campaign_build_id: input.campaignBuildId,
4194
5471
  campaign_brief: input.campaignBrief,
5472
+ strategy_template: input.strategyTemplate,
4195
5473
  target_icp: input.targetIcp,
4196
5474
  lead_count: input.leadCount,
4197
5475
  layers: input.layers,
4198
5476
  preferred_providers: input.preferredProviders,
5477
+ strategy_model: input.strategyModel,
5478
+ include_strategy_patterns: input.includeStrategyPatterns,
5479
+ include_workflow_patterns: input.includeWorkflowPatterns ?? input.includeClayPatterns,
5480
+ include_nango_catalog: input.includeNangoCatalog,
5481
+ partner_ecosystem: input.partnerEcosystem,
4199
5482
  memory_dimension_filters: input.memoryDimensionFilters,
4200
5483
  require_memory_dimension_match: input.requireMemoryDimensionMatch,
4201
5484
  include_memory: input.includeMemory,
@@ -4207,6 +5490,79 @@ var GtmKernel = class {
4207
5490
  limit: input.limit
4208
5491
  });
4209
5492
  }
5493
+ /** Emit reusable CampaignBuilderAgentRequest JSON from hosted MCP strategy-template defaults without spending credits. */
5494
+ async campaignAgentRequestTemplate(input = {}) {
5495
+ return this.callMcp("gtm_campaign_agent_request_template", {
5496
+ goal: input.goal,
5497
+ campaign_brief: input.campaignBrief,
5498
+ campaign_name: input.campaignName,
5499
+ account_label: input.accountLabel,
5500
+ account_context: input.accountContext,
5501
+ strategy_template: input.strategyTemplate,
5502
+ operating_playbooks: input.operatingPlaybooks,
5503
+ target_icp: input.targetIcp,
5504
+ target_count: input.targetCount,
5505
+ builtins: input.builtIns,
5506
+ include_local_leads: input.includeLocalLeads,
5507
+ include_byo_placeholder: input.includeByoPlaceholder,
5508
+ include_nango_catalog: input.includeNangoCatalog,
5509
+ preferred_providers: input.preferredProviders,
5510
+ privacy_mode: input.privacyMode,
5511
+ destination_type: input.destinationType
5512
+ });
5513
+ }
5514
+ /** Compose a one-call read-only strategy-template campaign-agent runbook across built-ins, Memory, Brain, Nango, and BYO routes. */
5515
+ async campaignAgentPlan(input = {}) {
5516
+ return this.callMcp("gtm_campaign_agent_plan", {
5517
+ goal: input.goal,
5518
+ campaign_brief: input.campaignBrief,
5519
+ campaign_name: input.campaignName,
5520
+ campaign_id: input.campaignId,
5521
+ campaign_build_id: input.campaignBuildId,
5522
+ strategy_template: input.strategyTemplate,
5523
+ operating_playbooks: input.operatingPlaybooks,
5524
+ account_context: input.accountContext,
5525
+ target_icp: input.targetIcp,
5526
+ target_count: input.targetCount,
5527
+ lead_count: input.leadCount,
5528
+ builtins: input.builtIns,
5529
+ use_local_leads: input.useLocalLeads,
5530
+ layers: input.layers,
5531
+ preferred_providers: input.preferredProviders,
5532
+ custom_tools: input.customTools,
5533
+ integrations: input.integrations,
5534
+ strategy_model: input.strategyModel,
5535
+ include_strategy_patterns: input.includeStrategyPatterns,
5536
+ include_workflow_patterns: input.includeWorkflowPatterns,
5537
+ include_nango_catalog: input.includeNangoCatalog,
5538
+ partner_ecosystem: input.partnerEcosystem,
5539
+ memory_dimension_filters: input.memoryDimensionFilters,
5540
+ require_memory_dimension_match: input.requireMemoryDimensionMatch,
5541
+ include_memory: input.includeMemory,
5542
+ include_brain: input.includeBrain,
5543
+ include_provider_routes: input.includeProviderRoutes,
5544
+ include_failure_patterns: input.includeFailurePatterns,
5545
+ include_delivery_risk: input.includeDeliveryRisk,
5546
+ include_planned_providers: input.includePlannedProviders,
5547
+ days: input.days,
5548
+ limit: input.limit
5549
+ });
5550
+ }
5551
+ /** Inspect private-safe strategy-template/workflow memory readiness before campaign planning. */
5552
+ async campaignStrategyMemoryStatus(input = {}) {
5553
+ return this.callMcp("gtm_campaign_strategy_memory_status", {
5554
+ strategy_template: input.strategyTemplate,
5555
+ query: input.query,
5556
+ campaign_brief: input.campaignBrief,
5557
+ target_icp: input.targetIcp,
5558
+ memory_dimension_filters: input.memoryDimensionFilters,
5559
+ require_memory_dimension_match: input.requireMemoryDimensionMatch,
5560
+ include_samples: input.includeSamples,
5561
+ include_sources: input.includeSources,
5562
+ days: input.days,
5563
+ limit: input.limit
5564
+ });
5565
+ }
4210
5566
  /** Persist a reviewed campaign build plan into a campaign object and audit log. Dry-run first by default. */
4211
5567
  async commitCampaignBuildPlan(input = {}) {
4212
5568
  return this.callMcp("gtm_campaign_build_plan_commit", {
@@ -4353,6 +5709,13 @@ var GtmKernel = class {
4353
5709
  vendor_id: input.vendorId,
4354
5710
  service_category: input.serviceCategory,
4355
5711
  connection_type: input.connectionType,
5712
+ integration_id: input.integrationId,
5713
+ provider_config_key: input.providerConfigKey,
5714
+ allowed_integrations: input.allowedIntegrations,
5715
+ surface: input.surface,
5716
+ source: input.source,
5717
+ user_email: input.userEmail,
5718
+ user_display_name: input.userDisplayName,
4356
5719
  status: input.status,
4357
5720
  metadata: input.metadata
4358
5721
  });
@@ -4409,6 +5772,20 @@ var GtmKernel = class {
4409
5772
  context: input.context
4410
5773
  });
4411
5774
  }
5775
+ /** Create a short-lived Nango Connect session so a user can authorize a vendor API. */
5776
+ async createNangoConnectSession(input) {
5777
+ return this.callMcp("nango_connect_session_create", {
5778
+ provider_id: input.providerId,
5779
+ integration_id: input.integrationId,
5780
+ provider_display_name: input.providerDisplayName,
5781
+ integration_display_name: input.integrationDisplayName,
5782
+ allowed_integrations: input.allowedIntegrations,
5783
+ surface: input.surface,
5784
+ source: input.source,
5785
+ user_email: input.userEmail,
5786
+ user_display_name: input.userDisplayName
5787
+ });
5788
+ }
4412
5789
  /** List Nango-backed action tools for a workspace connection without executing them. */
4413
5790
  async listNangoTools(options = {}) {
4414
5791
  return this.callMcp("nango_mcp_tools_list", {
@@ -4752,14 +6129,20 @@ var Signaliz = class {
4752
6129
 
4753
6130
  // src/cli.ts
4754
6131
  var apiKey = process.env.SIGNALIZ_API_KEY;
6132
+ var baseUrl = process.env.SIGNALIZ_BASE_URL || process.env.SIGNALIZ_API_URL;
4755
6133
  async function main() {
4756
6134
  const command = process.argv[2];
4757
- if (!apiKey) {
6135
+ if (!command || command === "help" || command === "--help" || command === "-h") {
6136
+ printHelp();
6137
+ return;
6138
+ }
6139
+ const offlineCampaignAgentTemplate = (command === "campaign-agent" || command === "campaign-builder") && ["init", "template", "request-template", "new"].includes(String(process.argv[3] || ""));
6140
+ if (!apiKey && !offlineCampaignAgentTemplate) {
4758
6141
  console.error("\u274C SIGNALIZ_API_KEY environment variable is required.");
4759
6142
  console.error(" Set it with: export SIGNALIZ_API_KEY=sk_...");
4760
6143
  process.exit(1);
4761
6144
  }
4762
- const signaliz = new Signaliz({ apiKey });
6145
+ const signaliz = new Signaliz({ apiKey: apiKey || "offline", baseUrl });
4763
6146
  switch (command) {
4764
6147
  case "test": {
4765
6148
  try {
@@ -4790,18 +6173,963 @@ async function main() {
4790
6173
  }
4791
6174
  break;
4792
6175
  }
6176
+ case "gtm": {
6177
+ await handleGtmCommand(signaliz, process.argv.slice(3));
6178
+ break;
6179
+ }
6180
+ case "campaign-agent":
6181
+ case "campaign-builder": {
6182
+ await handleCampaignAgentCommand(signaliz, process.argv.slice(3));
6183
+ break;
6184
+ }
4793
6185
  default:
4794
- console.log(`
6186
+ printHelp();
6187
+ }
6188
+ }
6189
+ async function handleGtmCommand(signaliz, argv) {
6190
+ const subcommand = argv[0];
6191
+ if (!subcommand || subcommand === "help" || subcommand === "--help" || subcommand === "-h") {
6192
+ printGtmHelp();
6193
+ return;
6194
+ }
6195
+ if (subcommand === "context") {
6196
+ const flags = parseFlags(argv.slice(1));
6197
+ const result = await signaliz.gtm.context({
6198
+ includeCampaigns: booleanFlag(flags, "include-campaigns"),
6199
+ includeMemory: booleanFlag(flags, "include-memory"),
6200
+ includeBrain: booleanFlag(flags, "include-brain"),
6201
+ includeConnections: booleanFlag(flags, "include-connections"),
6202
+ limit: numberFlag(flags, "limit")
6203
+ });
6204
+ printResult(result, flags);
6205
+ return;
6206
+ }
6207
+ if (subcommand === "bootstrap") {
6208
+ const flags = parseFlags(argv.slice(1));
6209
+ const result = await signaliz.gtm.bootstrapStatus({
6210
+ campaignId: stringFlag(flags, "campaign-id"),
6211
+ days: numberFlag(flags, "days"),
6212
+ minSampleSize: numberFlag(flags, "min-sample-size"),
6213
+ includeConnections: booleanFlag(flags, "include-connections"),
6214
+ includeSamples: booleanFlag(flags, "include-samples"),
6215
+ limit: numberFlag(flags, "limit")
6216
+ });
6217
+ printResult(result, flags);
6218
+ return;
6219
+ }
6220
+ if (subcommand === "memory" && argv[1] === "search") {
6221
+ const flags = parseFlags(argv.slice(2));
6222
+ const query = stringFlag(flags, "query", "q");
6223
+ if (!query) throw new Error("gtm memory search requires --query");
6224
+ const options = {
6225
+ query,
6226
+ campaignId: stringFlag(flags, "campaign-id"),
6227
+ memoryType: stringFlag(flags, "memory-type"),
6228
+ keywords: csvFlag(flags, "keywords"),
6229
+ outcomeType: stringFlag(flags, "outcome-type"),
6230
+ layers: csvFlag(flags, "layers"),
6231
+ providerChain: csvFlag(flags, "provider-chain", "providers"),
6232
+ days: numberFlag(flags, "days"),
6233
+ limit: numberFlag(flags, "limit")
6234
+ };
6235
+ const result = await signaliz.gtm.searchMemory(options);
6236
+ printResult(result, flags);
6237
+ return;
6238
+ }
6239
+ if (subcommand === "templates" || subcommand === "strategy-templates") {
6240
+ const flags = parseFlags(argv.slice(1));
6241
+ const result = await signaliz.gtm.campaignStrategyTemplates({
6242
+ strategyTemplate: stringFlag(flags, "strategy-template", "template"),
6243
+ query: stringFlag(flags, "query", "q"),
6244
+ includeDetails: !booleanFlag(flags, "summary")
6245
+ });
6246
+ printResult(result, flags);
6247
+ return;
6248
+ }
6249
+ if (subcommand === "start-context" || subcommand === "start") {
6250
+ const flags = parseFlags(argv.slice(1));
6251
+ const campaignBrief = stringFlag(flags, "brief", "campaign-brief", "goal");
6252
+ const strategyTemplate = stringFlag(flags, "strategy-template", "template");
6253
+ const targetIcp = jsonObjectFlag(flags, "target-icp", "icp");
6254
+ if (!campaignBrief && !stringFlag(flags, "campaign-id") && !stringFlag(flags, "campaign-build-id") && !strategyTemplate && !targetIcp) {
6255
+ throw new Error("gtm start-context requires --brief, --campaign-id, --campaign-build-id, --strategy-template, or --target-icp");
6256
+ }
6257
+ const input = {
6258
+ campaignId: stringFlag(flags, "campaign-id"),
6259
+ campaignBuildId: stringFlag(flags, "campaign-build-id"),
6260
+ campaignBrief,
6261
+ strategyTemplate,
6262
+ targetIcp,
6263
+ leadCount: numberFlag(flags, "lead-count", "target-count"),
6264
+ layers: csvFlag(flags, "layers"),
6265
+ preferredProviders: csvFlag(flags, "preferred-providers", "providers"),
6266
+ memoryDimensionFilters: jsonObjectFlag(flags, "memory-dimension-filters"),
6267
+ requireMemoryDimensionMatch: booleanFlag(flags, "require-memory-dimension-match"),
6268
+ includeMemory: booleanFlag(flags, "include-memory", true),
6269
+ includeBrain: booleanFlag(flags, "include-brain", true),
6270
+ includeProviderRoutes: booleanFlag(flags, "include-provider-routes", true),
6271
+ includeFailurePatterns: booleanFlag(flags, "include-failure-patterns", true),
6272
+ includeDeliveryRisk: booleanFlag(flags, "include-delivery-risk", true),
6273
+ includeGlobalBrain: booleanFlag(flags, "include-global-brain", true),
6274
+ includePlannedProviders: booleanFlag(flags, "include-planned-providers", true),
6275
+ days: numberFlag(flags, "days"),
6276
+ minConfidence: numberFlag(flags, "min-confidence"),
6277
+ minSampleSize: numberFlag(flags, "min-sample-size"),
6278
+ limit: numberFlag(flags, "limit")
6279
+ };
6280
+ const result = await signaliz.gtm.campaignStartContext(input);
6281
+ printResult(result, flags);
6282
+ return;
6283
+ }
6284
+ if (subcommand === "strategy-memory" || subcommand === "memory-status" || subcommand === "strategy-memory-status") {
6285
+ const flags = parseFlags(argv.slice(1));
6286
+ const input = {
6287
+ strategyTemplate: stringFlag(flags, "strategy-template", "template"),
6288
+ query: stringFlag(flags, "query", "goal", "q"),
6289
+ campaignBrief: stringFlag(flags, "brief", "campaign-brief"),
6290
+ targetIcp: jsonObjectFlag(flags, "target-icp", "icp"),
6291
+ memoryDimensionFilters: jsonObjectFlag(flags, "memory-dimension-filters"),
6292
+ requireMemoryDimensionMatch: booleanFlag(flags, "require-memory-dimension-match"),
6293
+ includeSamples: booleanFlag(flags, "include-samples"),
6294
+ includeSources: !booleanFlag(flags, "no-sources"),
6295
+ days: numberFlag(flags, "days"),
6296
+ limit: numberFlag(flags, "limit")
6297
+ };
6298
+ const result = await signaliz.gtm.campaignStrategyMemoryStatus(input);
6299
+ printResult(result, flags);
6300
+ return;
6301
+ }
6302
+ if (subcommand === "plan") {
6303
+ const flags = parseFlags(argv.slice(1));
6304
+ const campaignBrief = stringFlag(flags, "brief", "campaign-brief", "goal");
6305
+ if (!campaignBrief && !stringFlag(flags, "campaign-id") && !stringFlag(flags, "campaign-build-id")) {
6306
+ throw new Error("gtm plan requires --brief, --campaign-id, or --campaign-build-id");
6307
+ }
6308
+ const input = {
6309
+ campaignId: stringFlag(flags, "campaign-id"),
6310
+ campaignBuildId: stringFlag(flags, "campaign-build-id"),
6311
+ campaignBrief,
6312
+ strategyTemplate: stringFlag(flags, "strategy-template", "template"),
6313
+ targetIcp: jsonObjectFlag(flags, "target-icp", "icp"),
6314
+ leadCount: numberFlag(flags, "lead-count", "target-count"),
6315
+ layers: csvFlag(flags, "layers"),
6316
+ preferredProviders: csvFlag(flags, "preferred-providers", "providers"),
6317
+ strategyModel: stringFlag(flags, "strategy-model"),
6318
+ includeStrategyPatterns: !booleanFlag(flags, "no-strategy-patterns") && !booleanFlag(flags, "no-agency-patterns"),
6319
+ includeWorkflowPatterns: !booleanFlag(flags, "no-workflow-patterns") && !booleanFlag(flags, "no-clay-patterns"),
6320
+ includeNangoCatalog: !booleanFlag(flags, "no-nango-catalog"),
6321
+ partnerEcosystem: csvFlag(flags, "partner-ecosystem", "partners"),
6322
+ includeMemory: booleanFlag(flags, "include-memory", true),
6323
+ includeBrain: booleanFlag(flags, "include-brain", true),
6324
+ includeProviderRoutes: booleanFlag(flags, "include-provider-routes", true),
6325
+ includeFailurePatterns: booleanFlag(flags, "include-failure-patterns", true),
6326
+ includePlannedProviders: booleanFlag(flags, "include-planned-providers", true),
6327
+ days: numberFlag(flags, "days"),
6328
+ limit: numberFlag(flags, "limit")
6329
+ };
6330
+ const result = await signaliz.gtm.campaignBuildPlan(input);
6331
+ printResult(result, flags);
6332
+ return;
6333
+ }
6334
+ if (subcommand === "agent-plan" || subcommand === "campaign-agent-plan") {
6335
+ const flags = parseFlags(argv.slice(1));
6336
+ const goal = stringFlag(flags, "goal", "brief", "campaign-brief");
6337
+ if (!goal && !stringFlag(flags, "campaign-id") && !stringFlag(flags, "campaign-build-id") && !stringFlag(flags, "strategy-template", "template")) {
6338
+ throw new Error("gtm agent-plan requires --goal, --campaign-id, --campaign-build-id, or --strategy-template");
6339
+ }
6340
+ const input = {
6341
+ goal,
6342
+ campaignName: stringFlag(flags, "campaign-name", "name"),
6343
+ campaignId: stringFlag(flags, "campaign-id"),
6344
+ campaignBuildId: stringFlag(flags, "campaign-build-id", "build-id"),
6345
+ strategyTemplate: stringFlag(flags, "strategy-template", "template"),
6346
+ operatingPlaybooks: csvFlag(flags, "operating-playbooks", "playbooks"),
6347
+ accountContext: stringFlag(flags, "account-context", "workspace-context"),
6348
+ targetIcp: jsonObjectFlag(flags, "target-icp", "icp"),
6349
+ targetCount: numberFlag(flags, "target-count", "lead-count"),
6350
+ builtIns: campaignAgentBuiltInsFromFlags(flags),
6351
+ useLocalLeads: booleanFlag(flags, "use-local-leads") || void 0,
6352
+ layers: csvFlag(flags, "layers"),
6353
+ preferredProviders: csvFlag(flags, "preferred-providers", "providers"),
6354
+ customTools: campaignAgentCustomToolRoutesFromFlags(flags),
6355
+ strategyModel: stringFlag(flags, "strategy-model"),
6356
+ includeStrategyPatterns: !booleanFlag(flags, "no-strategy-patterns"),
6357
+ includeWorkflowPatterns: !booleanFlag(flags, "no-workflow-patterns"),
6358
+ includeNangoCatalog: !booleanFlag(flags, "no-nango-catalog"),
6359
+ partnerEcosystem: csvFlag(flags, "partner-ecosystem", "partners"),
6360
+ includeMemory: !booleanFlag(flags, "no-memory"),
6361
+ includeBrain: !booleanFlag(flags, "no-brain"),
6362
+ includeProviderRoutes: !booleanFlag(flags, "no-provider-routes"),
6363
+ includeFailurePatterns: !booleanFlag(flags, "no-failure-patterns"),
6364
+ includeDeliveryRisk: !booleanFlag(flags, "no-delivery-risk"),
6365
+ includePlannedProviders: !booleanFlag(flags, "no-planned-providers"),
6366
+ days: numberFlag(flags, "days"),
6367
+ limit: numberFlag(flags, "limit")
6368
+ };
6369
+ const result = await signaliz.gtm.campaignAgentPlan(input);
6370
+ printResult(result, flags);
6371
+ return;
6372
+ }
6373
+ if (subcommand === "agent-template" || subcommand === "campaign-agent-template" || subcommand === "request-template") {
6374
+ const flags = parseFlags(argv.slice(1));
6375
+ const input = {
6376
+ goal: stringFlag(flags, "goal", "brief", "campaign-brief"),
6377
+ campaignName: stringFlag(flags, "campaign-name", "name"),
6378
+ accountLabel: stringFlag(flags, "workspace-label", "account-label"),
6379
+ accountContext: stringFlag(flags, "account-context", "workspace-context"),
6380
+ strategyTemplate: stringFlag(flags, "strategy-template", "template"),
6381
+ operatingPlaybooks: csvFlag(flags, "operating-playbooks", "playbooks"),
6382
+ targetIcp: jsonObjectFlag(flags, "target-icp", "icp"),
6383
+ targetCount: numberFlag(flags, "target-count", "lead-count"),
6384
+ builtIns: campaignAgentBuiltInsFromFlags(flags),
6385
+ includeLocalLeads: booleanFlag(flags, "use-local-leads") || booleanFlag(flags, "include-local-leads") || void 0,
6386
+ includeByoPlaceholder: booleanFlag(flags, "with-byo-placeholder") || booleanFlag(flags, "include-byo-placeholder") || void 0,
6387
+ includeNangoCatalog: !booleanFlag(flags, "no-nango-catalog"),
6388
+ preferredProviders: csvFlag(flags, "preferred-providers", "providers"),
6389
+ privacyMode: stringFlag(flags, "privacy-mode"),
6390
+ destinationType: stringFlag(flags, "destination", "destination-type")
6391
+ };
6392
+ const result = await signaliz.gtm.campaignAgentRequestTemplate(input);
6393
+ printResult(result, flags);
6394
+ return;
6395
+ }
6396
+ if (subcommand === "provider-prepare" || subcommand === "prepare-provider" || subcommand === "recipe-prepare" || subcommand === "prepare-recipe") {
6397
+ const flags = parseFlags(argv.slice(1));
6398
+ const providerId = stringFlag(flags, "provider-id", "provider") || argv[1];
6399
+ if (!providerId) {
6400
+ throw new Error("gtm provider-prepare requires --provider-id or provider id");
6401
+ }
6402
+ const input = {
6403
+ providerId,
6404
+ providerName: stringFlag(flags, "provider-name", "name"),
6405
+ description: stringFlag(flags, "description"),
6406
+ layerCapabilities: csvFlag(flags, "layer-capabilities", "layers"),
6407
+ invocationType: stringFlag(flags, "invocation-type"),
6408
+ authStrategy: stringFlag(flags, "auth-strategy"),
6409
+ endpointUrl: stringFlag(flags, "endpoint-url"),
6410
+ httpMethod: stringFlag(flags, "http-method") || void 0,
6411
+ secretRef: stringFlag(flags, "secret-ref"),
6412
+ workspaceIntegrationId: stringFlag(flags, "workspace-integration-id"),
6413
+ workspaceMcpServerId: stringFlag(flags, "workspace-mcp-server-id"),
6414
+ workspaceConnectionId: stringFlag(flags, "workspace-connection-id"),
6415
+ requestTemplate: jsonObjectFlag(flags, "request-template"),
6416
+ responseMapping: jsonObjectFlag(flags, "response-mapping"),
6417
+ inputSchema: jsonObjectFlag(flags, "input-schema"),
6418
+ outputSchema: jsonObjectFlag(flags, "output-schema"),
6419
+ readiness: jsonObjectFlag(flags, "readiness"),
6420
+ metadata: jsonObjectFlag(flags, "metadata"),
6421
+ layer: stringFlag(flags, "layer"),
6422
+ campaignId: stringFlag(flags, "campaign-id"),
6423
+ useSignalizFallback: !booleanFlag(flags, "no-signaliz-fallback"),
6424
+ priority: numberFlag(flags, "priority"),
6425
+ status: stringFlag(flags, "status"),
6426
+ context: jsonObjectFlag(flags, "context")
6427
+ };
6428
+ const result = await signaliz.gtm.prepareProviderRecipe(input);
6429
+ printResult(result, flags);
6430
+ return;
6431
+ }
6432
+ if (subcommand === "activate-route" || subcommand === "route-activate") {
6433
+ const flags = parseFlags(argv.slice(1));
6434
+ const providerId = stringFlag(flags, "provider-id", "provider") || argv[1];
6435
+ if (!providerId) {
6436
+ throw new Error("gtm activate-route requires --provider-id or provider id");
6437
+ }
6438
+ const layers = csvFlag(flags, "layers");
6439
+ const layer = stringFlag(flags, "layer");
6440
+ if (!layer && !layers?.length) {
6441
+ throw new Error("gtm activate-route requires --layer or --layers");
6442
+ }
6443
+ const confirm = booleanFlag(flags, "confirm");
6444
+ const input = {
6445
+ providerId,
6446
+ providerName: stringFlag(flags, "provider-name", "name"),
6447
+ description: stringFlag(flags, "description"),
6448
+ campaignId: stringFlag(flags, "campaign-id"),
6449
+ layer,
6450
+ layers,
6451
+ invocationType: stringFlag(flags, "invocation-type"),
6452
+ authStrategy: stringFlag(flags, "auth-strategy"),
6453
+ endpointUrl: stringFlag(flags, "endpoint-url"),
6454
+ httpMethod: stringFlag(flags, "http-method") || void 0,
6455
+ secretRef: stringFlag(flags, "secret-ref"),
6456
+ workspaceIntegrationId: stringFlag(flags, "workspace-integration-id"),
6457
+ workspaceMcpServerId: stringFlag(flags, "workspace-mcp-server-id"),
6458
+ workspaceConnectionId: stringFlag(flags, "workspace-connection-id"),
6459
+ useSignalizFallback: !booleanFlag(flags, "no-signaliz-fallback"),
6460
+ priority: numberFlag(flags, "priority"),
6461
+ routeConfig: jsonObjectFlag(flags, "route-config"),
6462
+ requestTemplate: jsonObjectFlag(flags, "request-template"),
6463
+ responseMapping: jsonObjectFlag(flags, "response-mapping"),
6464
+ inputSchema: jsonObjectFlag(flags, "input-schema"),
6465
+ outputSchema: jsonObjectFlag(flags, "output-schema"),
6466
+ readiness: jsonObjectFlag(flags, "readiness"),
6467
+ metadata: jsonObjectFlag(flags, "metadata"),
6468
+ status: stringFlag(flags, "status"),
6469
+ routeStatus: stringFlag(flags, "route-status"),
6470
+ replaceExistingRoutes: !booleanFlag(flags, "keep-existing-routes"),
6471
+ dryRun: !confirm,
6472
+ confirm,
6473
+ context: jsonObjectFlag(flags, "context")
6474
+ };
6475
+ const result = await signaliz.gtm.activateProviderRoute(input);
6476
+ printResult(result, flags);
6477
+ return;
6478
+ }
6479
+ printGtmHelp();
6480
+ }
6481
+ async function handleCampaignAgentCommand(signaliz, argv) {
6482
+ const subcommand = argv[0];
6483
+ if (!subcommand || subcommand === "help" || subcommand === "--help" || subcommand === "-h") {
6484
+ printCampaignAgentHelp();
6485
+ return;
6486
+ }
6487
+ if (["init", "template", "request-template", "new"].includes(subcommand)) {
6488
+ const flags2 = parseFlags(argv.slice(1));
6489
+ const request2 = campaignAgentRequestTemplateFromFlags(flags2);
6490
+ const outputFile = stringFlag(flags2, "output-file", "out");
6491
+ if (outputFile) {
6492
+ (0, import_node_fs.writeFileSync)(outputFile, `${JSON.stringify(request2, null, 2)}
6493
+ `, "utf8");
6494
+ }
6495
+ if (booleanFlag(flags2, "json") || !outputFile) {
6496
+ printJson(request2);
6497
+ } else {
6498
+ console.log(`Campaign request template written: ${outputFile}`);
6499
+ console.log(`Next: signaliz campaign-agent plan --request-file ${outputFile} --json`);
6500
+ }
6501
+ return;
6502
+ }
6503
+ if (!["plan", "proof", "smoke", "commit-plan", "dry-run", "build-approved", "launch-approved"].includes(subcommand)) {
6504
+ printCampaignAgentHelp();
6505
+ return;
6506
+ }
6507
+ const flags = parseFlags(argv.slice(1));
6508
+ const requestFromFile = campaignAgentRequestFileFromFlags(flags);
6509
+ const goal = stringFlag(flags, "goal", "brief") ?? stringOrUndefined(requestFromFile?.goal);
6510
+ if (!goal) throw new Error(`campaign-agent ${subcommand} requires --goal or a request file with goal`);
6511
+ const isApprovedBuild = subcommand === "build-approved" || subcommand === "launch-approved";
6512
+ const isCommitPlan = subcommand === "commit-plan";
6513
+ const isConfirmedCommit = isCommitPlan && booleanFlag(flags, "confirm-write");
6514
+ const approvedBy = stringFlag(flags, "approved-by");
6515
+ if (isApprovedBuild) {
6516
+ if (!booleanFlag(flags, "confirm-launch")) {
6517
+ throw new Error(`campaign-agent ${subcommand} requires --confirm-launch`);
6518
+ }
6519
+ if (!approvedBy) throw new Error(`campaign-agent ${subcommand} requires --approved-by`);
6520
+ }
6521
+ if (isConfirmedCommit && !approvedBy) {
6522
+ throw new Error("campaign-agent commit-plan --confirm-write requires --approved-by");
6523
+ }
6524
+ const request = mergeCampaignAgentRequests(
6525
+ requestFromFile,
6526
+ campaignAgentRequestFromFlags(goal, flags, { includeDefaults: !requestFromFile })
6527
+ );
6528
+ const plan = await signaliz.campaignBuilderAgent.createPlan(request, {
6529
+ discoverCapabilities: !booleanFlag(flags, "skip-discovery"),
6530
+ scopeCampaign: !booleanFlag(flags, "skip-scope"),
6531
+ includeStrategyMemoryStatus: !booleanFlag(flags, "no-strategy-memory"),
6532
+ includeKernelPlan: !booleanFlag(flags, "no-kernel-plan"),
6533
+ includeDeliveryRisk: !booleanFlag(flags, "no-delivery-risk")
6534
+ });
6535
+ if (subcommand === "proof" || subcommand === "smoke") {
6536
+ const result = await signaliz.campaignBuilderAgent.dryRunPlan(plan, {
6537
+ idempotencyKey: stringFlag(flags, "idempotency-key")
6538
+ });
6539
+ const proof = createCampaignAgentProofReceipt(plan, result);
6540
+ if (booleanFlag(flags, "json")) {
6541
+ printJson(proof);
6542
+ } else {
6543
+ printCampaignAgentProof(proof);
6544
+ }
6545
+ if (!proof.success) process.exitCode = 1;
6546
+ return;
6547
+ }
6548
+ if (isCommitPlan) {
6549
+ const result = await signaliz.campaignBuilderAgent.commitPlan(plan, {
6550
+ confirm: isConfirmedCommit,
6551
+ dryRun: !isConfirmedCommit,
6552
+ approvedBy,
6553
+ idempotencyKey: stringFlag(flags, "idempotency-key"),
6554
+ rationale: stringFlag(flags, "rationale")
6555
+ });
6556
+ printCampaignAgentExecution({ plan, result }, flags);
6557
+ return;
6558
+ }
6559
+ if (subcommand === "dry-run") {
6560
+ const result = await signaliz.campaignBuilderAgent.dryRunPlan(plan, {
6561
+ idempotencyKey: stringFlag(flags, "idempotency-key")
6562
+ });
6563
+ printCampaignAgentExecution({ plan, result }, flags);
6564
+ return;
6565
+ }
6566
+ if (isApprovedBuild) {
6567
+ const approvedTypes = approvedTypesFromFlags(plan, flags);
6568
+ const approval = createCampaignBuilderApproval(plan, {
6569
+ approvedBy,
6570
+ approvedTypes,
6571
+ spendLimitCredits: numberFlag(flags, "spend-limit", "spend-limit-credits", "max-credits"),
6572
+ approvedRouteIds: approvedRouteIdsFromFlags(plan, flags),
6573
+ notes: stringFlag(flags, "approval-notes", "notes")
6574
+ });
6575
+ const result = await signaliz.campaignBuilderAgent.buildApprovedPlan(plan, approval, {
6576
+ idempotencyKey: stringFlag(flags, "idempotency-key"),
6577
+ commitBeforeLaunch: booleanFlag(flags, "commit-before-launch")
6578
+ });
6579
+ printCampaignAgentExecution({ plan, approval, result }, flags);
6580
+ return;
6581
+ }
6582
+ if (booleanFlag(flags, "json")) {
6583
+ printJson(plan);
6584
+ } else {
6585
+ printCampaignAgentPlan(plan);
6586
+ }
6587
+ }
6588
+ function campaignAgentRequestTemplateFromFlags(flags) {
6589
+ const goal = stringFlag(flags, "goal", "brief") || "Build a strategy-template campaign for mature operators in the target ICP.";
6590
+ const request = campaignAgentRequestFromFlags(goal, flags, { includeDefaults: true });
6591
+ const options = {
6592
+ ...request,
6593
+ includeLocalLeads: booleanFlag(flags, "use-local-leads"),
6594
+ includeCustomToolPlaceholder: booleanFlag(flags, "with-byo-placeholder") || booleanFlag(flags, "include-custom-tool-placeholder") || booleanFlag(flags, "include-byo-placeholder"),
6595
+ includeNango: !booleanFlag(flags, "no-nango-catalog")
6596
+ };
6597
+ return createCampaignBuilderAgentRequestTemplate(options);
6598
+ }
6599
+ function campaignAgentRequestFileFromFlags(flags) {
6600
+ const file = stringFlag(flags, "request-file", "input-file", "campaign-file");
6601
+ if (!file) return void 0;
6602
+ const parsed = JSON.parse((0, import_node_fs.readFileSync)(file, "utf8"));
6603
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
6604
+ throw new Error(`Expected JSON object for --request-file`);
6605
+ }
6606
+ return parsed;
6607
+ }
6608
+ function campaignAgentRequestFromFlags(goal, flags, options = {}) {
6609
+ const builtIns = campaignAgentBuiltInsFromFlags(flags);
6610
+ const integrations = campaignAgentCustomToolRoutesFromFlags(flags);
6611
+ const includeDefaults = options.includeDefaults !== false;
6612
+ const request = {
6613
+ goal,
6614
+ campaignName: stringFlag(flags, "campaign-name", "name"),
6615
+ accountLabel: stringFlag(flags, "workspace-label", "account-label"),
6616
+ strategyTemplate: stringFlag(flags, "strategy-template", "template"),
6617
+ accountContext: stringFlag(flags, "account-context", "workspace-context"),
6618
+ targetCount: numberFlag(flags, "target-count", "lead-count"),
6619
+ gtmCampaignId: stringFlag(flags, "gtm-campaign-id", "campaign-id"),
6620
+ icp: jsonObjectFlag(flags, "icp", "target-icp"),
6621
+ brainDefaults: jsonObjectFlag(flags, "brain-defaults"),
6622
+ deliveryRisk: jsonObjectFlag(flags, "delivery-risk"),
6623
+ builtIns,
6624
+ operatingPlaybooks: csvFlag(flags, "operating-playbooks", "playbooks"),
6625
+ integrations,
6626
+ preferredProviders: csvFlag(flags, "preferred-providers", "providers")
6627
+ };
6628
+ if (includeDefaults || flagValue(flags, "strategy-model", "no-strategy-patterns", "no-agency-patterns", "no-workflow-patterns", "no-clay-patterns", "no-nango-catalog", "partners", "revenue-motion") !== void 0) {
6629
+ request.agencyContext = {
6630
+ strategyModel: stringFlag(flags, "strategy-model"),
6631
+ includeStrategyPatterns: !booleanFlag(flags, "no-strategy-patterns") && !booleanFlag(flags, "no-agency-patterns"),
6632
+ includeWorkflowPatterns: !booleanFlag(flags, "no-workflow-patterns") && !booleanFlag(flags, "no-clay-patterns"),
6633
+ includeNangoCatalog: !booleanFlag(flags, "no-nango-catalog"),
6634
+ partnerEcosystem: csvFlag(flags, "partners"),
6635
+ revenueMotion: stringFlag(flags, "revenue-motion")
6636
+ };
6637
+ }
6638
+ if (includeDefaults || flagValue(flags, "no-memory", "no-workspace-history", "use-network-patterns", "privacy-mode") !== void 0) {
6639
+ request.memory = {
6640
+ enabled: !booleanFlag(flags, "no-memory"),
6641
+ useWorkspaceHistory: !booleanFlag(flags, "no-workspace-history"),
6642
+ useNetworkPatterns: booleanFlag(flags, "use-network-patterns"),
6643
+ privacyMode: stringFlag(flags, "privacy-mode")
6644
+ };
6645
+ }
6646
+ if (includeDefaults || flagValue(flags, "max-credits", "no-delivery", "destination") !== void 0) {
6647
+ request.signalizDefaults = {
6648
+ maxCredits: numberFlag(flags, "max-credits"),
6649
+ delivery: {
6650
+ enabled: !booleanFlag(flags, "no-delivery"),
6651
+ destinationType: stringFlag(flags, "destination"),
6652
+ approvalRequired: true
6653
+ }
6654
+ };
6655
+ }
6656
+ if (includeDefaults || flagValue(flags, "no-human-approval", "max-credits-without-approval") !== void 0) {
6657
+ request.approvalPolicy = {
6658
+ requireHumanApproval: !booleanFlag(flags, "no-human-approval"),
6659
+ maxCreditsWithoutApproval: numberFlag(flags, "max-credits-without-approval"),
6660
+ requireApprovalFor: ["memory_retrieval", "spend", "customer_tool", "external_write", "delivery", "launch"]
6661
+ };
6662
+ }
6663
+ return compactRequest(request);
6664
+ }
6665
+ function mergeCampaignAgentRequests(base, override) {
6666
+ if (!base) return override;
6667
+ return compactRequest({
6668
+ ...base,
6669
+ ...override,
6670
+ icp: mergeRecords(base.icp, override.icp),
6671
+ memory: mergeRecords(base.memory, override.memory),
6672
+ agencyContext: mergeRecords(base.agencyContext, override.agencyContext),
6673
+ signalizDefaults: mergeRecords(base.signalizDefaults, override.signalizDefaults),
6674
+ approvalPolicy: mergeRecords(base.approvalPolicy, override.approvalPolicy),
6675
+ constraints: mergeRecords(base.constraints, override.constraints),
6676
+ workspaceContext: mergeRecords(base.workspaceContext, override.workspaceContext),
6677
+ builtIns: override.builtIns ?? base.builtIns,
6678
+ operatingPlaybooks: override.operatingPlaybooks ?? base.operatingPlaybooks,
6679
+ integrations: override.integrations ?? base.integrations,
6680
+ customerTools: override.customerTools ?? base.customerTools,
6681
+ preferredProviders: override.preferredProviders ?? base.preferredProviders
6682
+ });
6683
+ }
6684
+ function mergeRecords(base, override) {
6685
+ if (!base) return override;
6686
+ if (!override) return base;
6687
+ if (typeof base === "object" && typeof override === "object" && !Array.isArray(base) && !Array.isArray(override)) {
6688
+ return { ...base, ...override };
6689
+ }
6690
+ return override;
6691
+ }
6692
+ function compactRequest(record) {
6693
+ return Object.fromEntries(
6694
+ Object.entries(record).filter(([, value]) => value !== void 0)
6695
+ );
6696
+ }
6697
+ function campaignAgentBuiltInsFromFlags(flags) {
6698
+ const explicit = csvFlag(flags, "builtins", "builtin-tools", "signaliz-tools");
6699
+ const hasBuiltinFlag = Boolean(
6700
+ explicit?.length || flagValue(flags, "use-local-leads") !== void 0 || flagValue(flags, "no-lead-generation") !== void 0 || flagValue(flags, "no-email-finding") !== void 0 || flagValue(flags, "no-verification") !== void 0 || flagValue(flags, "no-signals") !== void 0
6701
+ );
6702
+ if (!hasBuiltinFlag) return void 0;
6703
+ const builtIns = new Set(
6704
+ explicit?.length ? explicit : ["lead_generation", "email_finding", "email_verification", "signals"]
6705
+ );
6706
+ if (booleanFlag(flags, "use-local-leads")) builtIns.add("local_leads");
6707
+ if (booleanFlag(flags, "no-lead-generation")) builtIns.delete("lead_generation");
6708
+ if (booleanFlag(flags, "no-email-finding")) builtIns.delete("email_finding");
6709
+ if (booleanFlag(flags, "no-verification")) builtIns.delete("email_verification");
6710
+ if (booleanFlag(flags, "no-signals")) builtIns.delete("signals");
6711
+ return [...builtIns];
6712
+ }
6713
+ function campaignAgentCustomToolRoutesFromFlags(flags) {
6714
+ const values = repeatedStringFlag(flags, "custom-tool", "customer-tool", "byo-tool", "integration-route");
6715
+ const routes = values.map(parseCampaignAgentCustomToolRoute);
6716
+ return routes.length > 0 ? routes : void 0;
6717
+ }
6718
+ function parseCampaignAgentCustomToolRoute(raw) {
6719
+ const record = raw.trim().startsWith("{") ? jsonObjectFromString(raw, "--custom-tool") : raw.includes("=") ? keyValueObject(raw) : colonRouteObject(raw);
6720
+ const layer = normalizeCampaignBuilderLayer(String(record.layer ?? record.use_for_layer ?? record.useForLayer ?? "enrichment"));
6721
+ const gtmLayers = stringArrayValue(record.gtm_layers ?? record.gtmLayers ?? record.capabilities);
6722
+ const provider = String(record.provider ?? record.provider_id ?? record.providerId ?? "custom_mcp");
6723
+ const toolName = stringOrUndefined(record.tool ?? record.tool_name ?? record.toolName);
6724
+ const label = stringOrUndefined(record.label ?? record.name) ?? provider;
6725
+ const mcpServerName = stringOrUndefined(record.mcp ?? record.server ?? record.mcp_server_name ?? record.mcpServerName);
6726
+ const mode = normalizeRouteMode(String(record.mode ?? "required"));
6727
+ return {
6728
+ provider,
6729
+ layer,
6730
+ gtmLayers,
6731
+ mode,
6732
+ toolName,
6733
+ mcpServerName,
6734
+ label,
6735
+ approvalRequired: optionalBoolean(record.approval_required ?? record.approvalRequired, true),
6736
+ config: {
6737
+ provider_id: record.provider_id ?? record.providerId,
6738
+ available_tools: stringArrayValue(record.available_tools ?? record.availableTools ?? record.tools),
6739
+ raw: raw.trim()
6740
+ },
6741
+ rationale: `${label} is a user-provided campaign-builder route declared from the CLI.`
6742
+ };
6743
+ }
6744
+ function colonRouteObject(raw) {
6745
+ const [provider, layer, tool, mcp] = raw.split(":").map((part) => part.trim()).filter(Boolean);
6746
+ if (!provider || !layer) {
6747
+ throw new Error("Expected --custom-tool provider:layer:tool[:mcp] or key=value pairs");
6748
+ }
6749
+ return { provider, layer, tool, mcp };
6750
+ }
6751
+ function keyValueObject(raw) {
6752
+ const record = {};
6753
+ for (const segment of raw.split(",")) {
6754
+ const eq = segment.indexOf("=");
6755
+ if (eq < 0) continue;
6756
+ const key = segment.slice(0, eq).trim().replace(/-/g, "_");
6757
+ const value = segment.slice(eq + 1).trim();
6758
+ record[key] = value;
6759
+ }
6760
+ return record;
6761
+ }
6762
+ function normalizeCampaignBuilderLayer(value) {
6763
+ const normalized = normalizeEnumValue(value);
6764
+ const allowed = ["workspace_context", "memory", "source", "enrichment", "qualification", "copy", "delivery", "feedback", "approval"];
6765
+ if (!allowed.includes(normalized)) {
6766
+ throw new Error(`Unknown campaign-builder layer "${value}". Use source, enrichment, qualification, copy, delivery, feedback, or approval.`);
6767
+ }
6768
+ return normalized;
6769
+ }
6770
+ function normalizeRouteMode(value) {
6771
+ const normalized = normalizeEnumValue(value);
6772
+ return ["required", "if_available", "fallback", "disabled"].includes(normalized) ? normalized : "required";
6773
+ }
6774
+ function normalizeEnumValue(value) {
6775
+ return value.trim().toLowerCase().replace(/-/g, "_");
6776
+ }
6777
+ function stringArrayValue(value) {
6778
+ const values = Array.isArray(value) ? value : value === void 0 ? [] : [value];
6779
+ const parsed = values.flatMap((item) => String(item).split(/[|,]/).map((part) => part.trim()).filter(Boolean));
6780
+ return parsed.length > 0 ? parsed : void 0;
6781
+ }
6782
+ function stringOrUndefined(value) {
6783
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
6784
+ }
6785
+ function optionalBoolean(value, defaultValue) {
6786
+ if (value === void 0) return defaultValue;
6787
+ if (typeof value === "boolean") return value;
6788
+ return parseBoolean(String(value), defaultValue);
6789
+ }
6790
+ function approvedTypesFromFlags(plan, flags) {
6791
+ const requested = csvFlag(flags, "approved-types", "approve-types");
6792
+ if (requested?.length) return requested;
6793
+ if (!booleanFlag(flags, "approve-all")) {
6794
+ throw new Error("campaign-agent build-approved requires --approve-all or --approved-types");
6795
+ }
6796
+ return [...new Set(plan.approvals.map((item) => item.type))];
6797
+ }
6798
+ function approvedRouteIdsFromFlags(plan, flags) {
6799
+ const requested = csvFlag(flags, "approved-route-ids", "route-ids");
6800
+ if (requested?.length) return requested;
6801
+ if (!booleanFlag(flags, "approve-all")) return void 0;
6802
+ const routeIds = plan.approvals.map((item) => item.routeId).filter((id) => Boolean(id));
6803
+ return routeIds.length > 0 ? routeIds : void 0;
6804
+ }
6805
+ function parseFlags(argv) {
6806
+ const flags = {};
6807
+ for (let i = 0; i < argv.length; i += 1) {
6808
+ const token = argv[i];
6809
+ if (!token.startsWith("--")) continue;
6810
+ const eq = token.indexOf("=");
6811
+ const key = normalizeFlagName(eq >= 0 ? token.slice(2, eq) : token.slice(2));
6812
+ const value = eq >= 0 ? token.slice(eq + 1) : argv[i + 1] && !argv[i + 1].startsWith("--") ? argv[++i] : true;
6813
+ const existing = flags[key];
6814
+ if (existing === void 0) {
6815
+ flags[key] = value;
6816
+ } else if (Array.isArray(existing)) {
6817
+ existing.push(String(value));
6818
+ } else {
6819
+ flags[key] = [String(existing), String(value)];
6820
+ }
6821
+ }
6822
+ return flags;
6823
+ }
6824
+ function normalizeFlagName(name) {
6825
+ return name.replace(/_/g, "-");
6826
+ }
6827
+ function flagValue(flags, ...names) {
6828
+ for (const name of names.map(normalizeFlagName)) {
6829
+ if (flags[name] !== void 0) return flags[name];
6830
+ }
6831
+ return void 0;
6832
+ }
6833
+ function stringFlag(flags, ...names) {
6834
+ const value = flagValue(flags, ...names);
6835
+ if (Array.isArray(value)) return value.at(-1);
6836
+ if (value === void 0 || value === true || value === false) return void 0;
6837
+ const trimmed = String(value).trim();
6838
+ return trimmed || void 0;
6839
+ }
6840
+ function numberFlag(flags, ...names) {
6841
+ const value = stringFlag(flags, ...names);
6842
+ if (!value) return void 0;
6843
+ const parsed = Number(value);
6844
+ if (!Number.isFinite(parsed)) throw new Error(`Expected numeric value for --${names[0]}`);
6845
+ return parsed;
6846
+ }
6847
+ function booleanFlag(flags, name, defaultValue = false) {
6848
+ const value = flagValue(flags, name);
6849
+ if (value === void 0) return defaultValue;
6850
+ if (Array.isArray(value)) return value.length > 0 ? parseBoolean(value.at(-1), defaultValue) : defaultValue;
6851
+ return parseBoolean(value, defaultValue);
6852
+ }
6853
+ function parseBoolean(value, defaultValue) {
6854
+ if (value === void 0) return defaultValue;
6855
+ if (typeof value === "boolean") return value;
6856
+ return !["0", "false", "no", "off"].includes(value.toLowerCase());
6857
+ }
6858
+ function csvFlag(flags, ...names) {
6859
+ const value = flagValue(flags, ...names);
6860
+ const values = Array.isArray(value) ? value : value === void 0 || typeof value === "boolean" ? [] : [value];
6861
+ const parsed = values.flatMap((item) => String(item).split(",").map((part) => part.trim()).filter(Boolean));
6862
+ return parsed.length > 0 ? parsed : void 0;
6863
+ }
6864
+ function repeatedStringFlag(flags, ...names) {
6865
+ const value = flagValue(flags, ...names);
6866
+ if (Array.isArray(value)) return value.map(String).map((item) => item.trim()).filter(Boolean);
6867
+ if (value === void 0 || typeof value === "boolean") return [];
6868
+ const trimmed = String(value).trim();
6869
+ return trimmed ? [trimmed] : [];
6870
+ }
6871
+ function jsonObjectFlag(flags, ...names) {
6872
+ const value = stringFlag(flags, ...names);
6873
+ if (!value) return void 0;
6874
+ return jsonObjectFromString(value, `--${names[0]}`);
6875
+ }
6876
+ function jsonObjectFromString(value, label) {
6877
+ const parsed = JSON.parse(value);
6878
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
6879
+ throw new Error(`Expected JSON object for ${label}`);
6880
+ }
6881
+ return parsed;
6882
+ }
6883
+ function printResult(result, flags) {
6884
+ if (booleanFlag(flags, "json")) {
6885
+ printJson(result);
6886
+ return;
6887
+ }
6888
+ if (result && typeof result === "object") {
6889
+ const record = result;
6890
+ const title = record.summary || record.message || record.next_action || record.status;
6891
+ if (title) console.log(String(title));
6892
+ printJson(result);
6893
+ return;
6894
+ }
6895
+ console.log(String(result ?? ""));
6896
+ }
6897
+ function printCampaignAgentPlan(plan) {
6898
+ console.log(`Plan: ${plan.campaignName}`);
6899
+ console.log(`Plan ID: ${plan.planId}`);
6900
+ console.log(`Target: ${plan.targetCount}`);
6901
+ console.log(`Estimated credits: ${plan.estimatedCredits}`);
6902
+ console.log(`Memory: ${plan.memory.enabled ? plan.memory.privacyMode : "disabled"}`);
6903
+ console.log(`Playbooks: ${plan.operatingPlaybooks.map((item) => item.slug).join(", ") || "none"}`);
6904
+ console.log(`Strategy memory: ${plan.strategyMemoryStatus ? plan.strategyMemoryStatus.ready === false ? "needs seeding" : "ready" : "not loaded"}`);
6905
+ console.log(`Kernel plan: ${plan.kernelPlan ? "loaded" : "not loaded"}`);
6906
+ console.log(`Approvals: ${plan.approvals.map((item) => item.type).join(", ") || "none"}`);
6907
+ if (plan.warnings.length > 0) {
6908
+ console.log(`Warnings: ${plan.warnings.join("; ")}`);
6909
+ }
6910
+ console.log("\nMCP flow:");
6911
+ for (const step of plan.mcpFlow) {
6912
+ console.log(`- ${step.id}: ${step.tool}${step.approvalRequired ? " (approval required)" : ""}`);
6913
+ }
6914
+ }
6915
+ function printCampaignAgentExecution(payload, flags) {
6916
+ if (booleanFlag(flags, "json")) {
6917
+ printJson(payload);
6918
+ return;
6919
+ }
6920
+ printCampaignAgentPlan(payload.plan);
6921
+ console.log("\nResult:");
6922
+ printJson(payload.result);
6923
+ }
6924
+ function asRecord4(value) {
6925
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
6926
+ }
6927
+ function createCampaignAgentProofReceipt(plan, result) {
6928
+ const strategyMemory = asRecord4(plan.strategyMemoryStatus);
6929
+ const dryRunResult = asRecord4(result);
6930
+ const memoryReady = plan.strategyMemoryStatus ? strategyMemory.ready !== false : false;
6931
+ const dryRunCompleted = dryRunResult.dryRun === true || dryRunResult.dry_run === true || dryRunResult.status === "dry_run";
6932
+ const noLaunch = dryRunCompleted && !dryRunResult.campaignBuildId && !dryRunResult.campaign_build_id;
6933
+ const gates = [
6934
+ {
6935
+ id: "strategy_memory_ready",
6936
+ passed: memoryReady,
6937
+ ready: strategyMemory.ready ?? null,
6938
+ blocker_count: Array.isArray(strategyMemory.blockers) ? strategyMemory.blockers.length : 0
6939
+ },
6940
+ {
6941
+ id: "campaign_plan_ready",
6942
+ passed: Boolean(plan.planId && plan.mcpFlow.length > 0),
6943
+ plan_id: plan.planId,
6944
+ flow_steps: plan.mcpFlow.length
6945
+ },
6946
+ {
6947
+ id: "approval_gates_present",
6948
+ passed: plan.approvals.length > 0,
6949
+ approval_types: plan.approvals.map((approval) => approval.type)
6950
+ },
6951
+ {
6952
+ id: "dry_run_completed",
6953
+ passed: dryRunCompleted,
6954
+ status: dryRunResult.status ?? null,
6955
+ current_phase: dryRunResult.currentPhase ?? dryRunResult.current_phase ?? null
6956
+ },
6957
+ {
6958
+ id: "no_spendful_launch",
6959
+ passed: noLaunch,
6960
+ campaign_build_id: dryRunResult.campaignBuildId ?? dryRunResult.campaign_build_id ?? null
6961
+ }
6962
+ ];
6963
+ return {
6964
+ receipt_version: "campaign-agent-proof.v1",
6965
+ source: "signaliz campaign-agent proof",
6966
+ success: gates.every((gate) => gate.passed),
6967
+ safety: {
6968
+ spendful_tools_called: false,
6969
+ external_writes_called: false,
6970
+ sender_loads_called: false,
6971
+ email_sends_called: false,
6972
+ dry_run_only: true
6973
+ },
6974
+ campaign: {
6975
+ plan_id: plan.planId,
6976
+ campaign_name: plan.campaignName,
6977
+ strategy_template: campaignAgentStrategyTemplate(plan),
6978
+ target_count: plan.targetCount,
6979
+ estimated_credits: plan.estimatedCredits,
6980
+ operating_playbooks: plan.operatingPlaybooks.map((playbook) => playbook.slug)
6981
+ },
6982
+ gates,
6983
+ strategy_memory_status: summarizeCampaignAgentStrategyMemory(strategyMemory),
6984
+ dry_run_result: summarizeCampaignAgentDryRun(dryRunResult),
6985
+ recommended_next_actions: [
6986
+ "Review the plan, approvals, and dry-run result.",
6987
+ "Use campaign-agent commit-plan --confirm-write only after review.",
6988
+ "Use campaign-agent build-approved only with --confirm-launch, approval identity, approval types, and spend limit.",
6989
+ "When an approved build reaches pending_approval, review rows and approve delivery through the Campaigns SDK."
6990
+ ]
6991
+ };
6992
+ }
6993
+ function campaignAgentString(...values) {
6994
+ for (const value of values) {
6995
+ if (typeof value === "string" && value.trim()) return value;
6996
+ }
6997
+ return null;
6998
+ }
6999
+ function campaignAgentStrategyTemplate(plan) {
7000
+ const buildRequest = asRecord4(plan.buildRequest);
7001
+ const strategyMemory = asRecord4(plan.strategyMemoryStatus);
7002
+ const statusTemplate = strategyMemory.strategy_template ?? strategyMemory.strategyTemplate;
7003
+ const statusTemplateRecord = asRecord4(statusTemplate);
7004
+ const flowTemplate = plan.mcpFlow.map((step) => asRecord4(step.arguments).strategy_template ?? asRecord4(step.arguments).strategyTemplate).find((value) => typeof value === "string" && value.trim());
7005
+ return campaignAgentString(
7006
+ buildRequest.strategyTemplate,
7007
+ buildRequest.strategy_template,
7008
+ statusTemplate,
7009
+ statusTemplateRecord.slug,
7010
+ statusTemplateRecord.id,
7011
+ flowTemplate
7012
+ );
7013
+ }
7014
+ function summarizeCampaignAgentStrategyMemory(strategyMemory) {
7015
+ if (Object.keys(strategyMemory).length === 0) return { ready: false };
7016
+ const template = strategyMemory.strategy_template ?? strategyMemory.strategyTemplate;
7017
+ const templateRecord = asRecord4(template);
7018
+ const coverage = asRecord4(strategyMemory.coverage);
7019
+ const rawSourceGroups = Array.isArray(strategyMemory.source_groups) ? strategyMemory.source_groups : Array.isArray(strategyMemory.sourceGroups) ? strategyMemory.sourceGroups : [];
7020
+ const sourceGroups = rawSourceGroups.map((group) => {
7021
+ const sourceGroup = asRecord4(group);
7022
+ return {
7023
+ id: sourceGroup.id ?? null,
7024
+ required: sourceGroup.required ?? null,
7025
+ ready: sourceGroup.ready ?? null,
7026
+ counts: asRecord4(sourceGroup.counts)
7027
+ };
7028
+ });
7029
+ return {
7030
+ ready: strategyMemory.ready ?? null,
7031
+ read_only: strategyMemory.read_only ?? strategyMemory.readOnly ?? null,
7032
+ source_tool: campaignAgentString(strategyMemory.source_tool, strategyMemory.sourceTool),
7033
+ strategy_template: {
7034
+ slug: campaignAgentString(template, templateRecord.slug, templateRecord.id),
7035
+ label: campaignAgentString(templateRecord.label)
7036
+ },
7037
+ coverage: {
7038
+ required_groups_ready: coverage.required_groups_ready ?? coverage.requiredGroupsReady ?? null,
7039
+ required_groups_total: coverage.required_groups_total ?? coverage.requiredGroupsTotal ?? null,
7040
+ source_groups_ready: coverage.source_groups_ready ?? coverage.sourceGroupsReady ?? null,
7041
+ source_groups_total: coverage.source_groups_total ?? coverage.sourceGroupsTotal ?? null,
7042
+ knowledge_docs: coverage.knowledge_docs ?? coverage.knowledgeDocs ?? null,
7043
+ memories: coverage.memories ?? null
7044
+ },
7045
+ source_groups: sourceGroups,
7046
+ blocker_count: Array.isArray(strategyMemory.blockers) ? strategyMemory.blockers.length : 0,
7047
+ warning_count: Array.isArray(strategyMemory.warnings) ? strategyMemory.warnings.length : 0
7048
+ };
7049
+ }
7050
+ function summarizeCampaignAgentDryRun(dryRunResult) {
7051
+ return {
7052
+ dryRun: dryRunResult.dryRun ?? dryRunResult.dry_run ?? null,
7053
+ status: dryRunResult.status ?? null,
7054
+ currentPhase: dryRunResult.currentPhase ?? dryRunResult.current_phase ?? null,
7055
+ campaignBuildId: dryRunResult.campaignBuildId ?? dryRunResult.campaign_build_id ?? null,
7056
+ plannedTargetCount: dryRunResult.plannedTargetCount ?? dryRunResult.planned_target_count ?? null
7057
+ };
7058
+ }
7059
+ function printCampaignAgentProof(proof) {
7060
+ console.log(`Campaign-agent proof: ${proof.success ? "passed" : "failed"}`);
7061
+ const campaign = asRecord4(proof.campaign);
7062
+ if (campaign.plan_id) console.log(`Plan ID: ${campaign.plan_id}`);
7063
+ if (campaign.strategy_template) console.log(`Strategy template: ${campaign.strategy_template}`);
7064
+ if (campaign.target_count !== void 0) console.log(`Target: ${campaign.target_count}`);
7065
+ console.log("\nGates:");
7066
+ const gates = Array.isArray(proof.gates) ? proof.gates : [];
7067
+ for (const gate of gates) {
7068
+ const gateRecord = asRecord4(gate);
7069
+ console.log(`- ${gateRecord.id}: ${gateRecord.passed ? "passed" : "failed"}`);
7070
+ }
7071
+ console.log("\nSafety: dry-run only; no spendful launch, external write, sender load, or email send.");
7072
+ }
7073
+ function printJson(value) {
7074
+ console.log(JSON.stringify(value, null, 2));
7075
+ }
7076
+ function printHelp() {
7077
+ console.log(`
4795
7078
  Signaliz CLI v1.0.0
4796
7079
 
4797
7080
  Usage:
4798
- signaliz test Verify API connectivity
4799
- signaliz tools List all available MCP tools
7081
+ signaliz test Verify API connectivity
7082
+ signaliz tools List all available MCP tools
7083
+ signaliz gtm context --json Load GTM Kernel workspace context
7084
+ signaliz gtm bootstrap --json Inspect GTM Kernel readiness
7085
+ signaliz gtm templates --json List private-safe campaign strategy templates
7086
+ signaliz gtm start-context --strategy-template non-medical-home-care --json
7087
+ signaliz gtm strategy-memory --strategy-template non-medical-home-care --include-samples --json
7088
+ signaliz gtm agent-plan --goal "Build a strategy-template campaign" --strategy-template non-medical-home-care --target-count 500 --json
7089
+ signaliz gtm provider-prepare --provider-id customer_mcp --layer company_enrichment --invocation-type mcp_tool --json
7090
+ signaliz gtm memory search --query "proof-first vertical gate" --json
7091
+ signaliz gtm plan --brief "Build 500 verified leads for..." --strategy-template non-medical-home-care --lead-count 500 --json
7092
+ signaliz campaign-agent init --strategy-template non-medical-home-care --target-count 250 --use-local-leads --json > campaign-request.json
7093
+ signaliz campaign-agent plan --goal "Build a strategy-template campaign..." --strategy-template industrial-ot-resilience --target-count 500 --builtins lead_generation,email_finding,email_verification,signals
7094
+ signaliz campaign-agent proof --goal "Build a strategy-template campaign..." --strategy-template non-medical-home-care --target-count 100 --json
7095
+ signaliz campaign-agent plan --request-file examples/campaign-builder-agent-request.json --target-count 250 --json
7096
+ signaliz campaign-agent commit-plan --goal "Build a strategy-template campaign..." --json
7097
+ signaliz campaign-agent dry-run --goal "Build a strategy-template campaign..." --target-count 500 --use-local-leads --json
7098
+ signaliz campaign-agent build-approved --goal "Build a strategy-template campaign..." --confirm-launch --approve-all --approved-by you@example.com --spend-limit 500
4800
7099
 
4801
7100
  Environment:
4802
- SIGNALIZ_API_KEY Your API key (required)
7101
+ SIGNALIZ_API_KEY Your API key (not required for campaign-agent init)
7102
+ SIGNALIZ_BASE_URL Optional API base URL override
7103
+ `);
7104
+ }
7105
+ function printGtmHelp() {
7106
+ console.log(`
7107
+ Signaliz GTM commands:
7108
+
7109
+ signaliz gtm context [--include-campaigns] [--include-memory] [--include-brain] [--include-connections] [--limit N] [--json]
7110
+ signaliz gtm bootstrap [--campaign-id ID] [--days N] [--include-connections] [--include-samples] [--json]
7111
+ signaliz gtm templates [--query TEXT] [--strategy-template ID] [--summary] [--json]
7112
+ signaliz gtm start-context [--brief TEXT] [--strategy-template ID] [--target-count N] [--layers a,b] [--providers a,b] [--json]
7113
+ signaliz gtm strategy-memory [--query TEXT] [--strategy-template ID] [--include-samples] [--json]
7114
+ signaliz gtm provider-prepare --provider-id ID [--layer NAME] [--invocation-type webhook|mcp_tool|api] [--json]
7115
+ signaliz gtm activate-route --provider-id ID --layer NAME [--confirm] [--json]
7116
+ signaliz gtm memory search --query TEXT [--layers a,b] [--provider-chain a,b] [--limit N] [--json]
7117
+ signaliz gtm plan --brief TEXT [--strategy-template industrial-ot-resilience|non-medical-home-care|agency-founder-led|cloud-infrastructure-displacement] [--lead-count N] [--layers a,b] [--providers a,b] [--partners clay,instantly,nango] [--target-icp JSON] [--json]
7118
+ `);
7119
+ }
7120
+ function printCampaignAgentHelp() {
7121
+ console.log(`
7122
+ Signaliz campaign-agent commands:
7123
+
7124
+ signaliz campaign-agent init [--goal TEXT] [--strategy-template ID] [--target-count N] [--use-local-leads] [--with-byo-placeholder] [--output-file FILE] [--json]
7125
+ signaliz campaign-agent plan (--goal TEXT | --request-file FILE) [--campaign-name NAME] [--workspace-label NAME] [--strategy-template industrial-ot-resilience|non-medical-home-care|agency-founder-led|cloud-infrastructure-displacement] [--operating-playbooks proof-first-vertical-gate,signal-led-copy-approval] [--target-count N] [--icp JSON] [--builtins lead_generation,email_finding,email_verification,signals,local_leads] [--use-local-leads] [--custom-tool provider:layer:tool[:mcp]] [--preferred-providers signaliz_native,octave] [--partners clay,instantly,nango] [--no-strategy-memory] [--no-kernel-plan] [--no-delivery-risk] [--json]
7126
+ signaliz campaign-agent proof (--goal TEXT | --request-file FILE) [--strategy-template ID] [--target-count N] [--use-local-leads] [--custom-tool provider:layer:tool[:mcp]] [--idempotency-key KEY] [--json]
7127
+ signaliz campaign-agent commit-plan (--goal TEXT | --request-file FILE) [--confirm-write --approved-by EMAIL] [--idempotency-key KEY] [--json]
7128
+ signaliz campaign-agent dry-run (--goal TEXT | --request-file FILE) [--gtm-campaign-id ID] [--delivery-risk JSON] [--idempotency-key KEY] [--json]
7129
+ signaliz campaign-agent build-approved (--goal TEXT | --request-file FILE) --confirm-launch --approved-by EMAIL (--approve-all | --approved-types a,b) [--commit-before-launch] [--spend-limit N] [--approved-route-ids a,b] [--idempotency-key KEY] [--json]
7130
+
7131
+ The init command emits a reusable JSON CampaignBuilderAgentRequest. The plan command composes an approval-gated strategy-template MCP flow. Proof runs the same plan path plus build_campaign dry_run=true and returns a no-spend receipt. Use --request-file to load a reusable request, then override fields such as --target-count or --strategy-template from the command line. Use --strategy-template to merge a private-safe strategy pattern into the plan without exposing private account labels, and --operating-playbooks to add reusable build-loop gates such as proof-first vertical qualification, net-new suppression, cache-first inventory, and signal-led copy approval. Built-ins map to Signaliz-native tools: lead_generation -> generate_leads, local_leads -> generate_local_leads, email_finding -> find_and_verify_emails, email_verification -> verify_emails, signals -> enrich_company_signals. Add BYO tools with --custom-tool provider:layer:tool[:mcp] or key=value pairs such as provider=apollo,layer=source,tool=apollo_search,mcp=apollo. Use --no-strategy-patterns or --no-workflow-patterns to disable default private strategy memory hints. Commit-plan dry-runs by default and writes only with --confirm-write plus approval identity. Dry-run executes build_campaign with dry_run=true. Approved build requires explicit launch confirmation and approval metadata; add --commit-before-launch to persist the reviewed plan as a GTM campaign before launch.
4803
7132
  `);
4804
- }
4805
7133
  }
4806
7134
  main().catch((e) => {
4807
7135
  console.error(e);