@speakai/mcp-server 1.24.3 → 1.27.0

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.
Files changed (3) hide show
  1. package/README.md +89 -3
  2. package/dist/index.js +2549 -173
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -283,7 +283,7 @@ var init_auth = __esm({
283
283
  });
284
284
 
285
285
  // node_modules/@speakai/shared/dist/enums/automation.js
286
- var AutomationTrigger, AutomationAction, AutomationRunType, AutomationScheduleTimePeriod, AssistantType;
286
+ var AutomationTrigger, AutomationAction, AutomationStepType, AutomationRunStatus, AutomationIOType, AutomationRunType, AutomationScheduleTimePeriod, AssistantType;
287
287
  var init_automation = __esm({
288
288
  "node_modules/@speakai/shared/dist/enums/automation.js"() {
289
289
  "use strict";
@@ -291,11 +291,38 @@ var init_automation = __esm({
291
291
  AutomationTrigger2["FOLDERS"] = "folders";
292
292
  AutomationTrigger2["TAGS"] = "tags";
293
293
  AutomationTrigger2["KEYWORDS"] = "keywords";
294
+ AutomationTrigger2["COMPOSIO"] = "composio";
295
+ AutomationTrigger2["WEBHOOK"] = "webhook";
294
296
  })(AutomationTrigger || (AutomationTrigger = {}));
295
297
  (function(AutomationAction2) {
296
298
  AutomationAction2["MAGIC_PROMPT"] = "magic-prompt";
297
299
  AutomationAction2["TRANSLATION"] = "translation";
298
300
  })(AutomationAction || (AutomationAction = {}));
301
+ (function(AutomationStepType2) {
302
+ AutomationStepType2["TRIGGER"] = "trigger";
303
+ AutomationStepType2["MAGIC_PROMPT"] = "magic-prompt";
304
+ AutomationStepType2["TRANSLATION"] = "translation";
305
+ AutomationStepType2["COMPOSIO_ACTION"] = "composio-action";
306
+ AutomationStepType2["FILTER"] = "filter";
307
+ AutomationStepType2["SPEAK_UPLOAD"] = "speak-upload";
308
+ AutomationStepType2["NOTIFY"] = "notify";
309
+ AutomationStepType2["OUTBOUND_WEBHOOK"] = "outbound-webhook";
310
+ AutomationStepType2["CONDITION"] = "condition";
311
+ })(AutomationStepType || (AutomationStepType = {}));
312
+ (function(AutomationRunStatus2) {
313
+ AutomationRunStatus2["PENDING"] = "pending";
314
+ AutomationRunStatus2["RUNNING"] = "running";
315
+ AutomationRunStatus2["COMPLETED"] = "completed";
316
+ AutomationRunStatus2["FAILED"] = "failed";
317
+ AutomationRunStatus2["KILLED"] = "killed";
318
+ })(AutomationRunStatus || (AutomationRunStatus = {}));
319
+ (function(AutomationIOType2) {
320
+ AutomationIOType2["FILE"] = "file";
321
+ AutomationIOType2["MEDIA"] = "media";
322
+ AutomationIOType2["INSIGHT"] = "insight";
323
+ AutomationIOType2["NOTIFY"] = "notify";
324
+ AutomationIOType2["DATA"] = "data";
325
+ })(AutomationIOType || (AutomationIOType = {}));
299
326
  (function(AutomationRunType2) {
300
327
  AutomationRunType2["INSTANT"] = "instant";
301
328
  AutomationRunType2["SCHEDULE"] = "schedule";
@@ -387,6 +414,7 @@ var init_embed = __esm({
387
414
  (function(EmbedType2) {
388
415
  EmbedType2["MEDIA_PLAYER"] = "mediaPlayer";
389
416
  EmbedType2["REPOSITORY"] = "repository";
417
+ EmbedType2["DASHBOARD"] = "dashboard";
390
418
  })(EmbedType || (EmbedType = {}));
391
419
  (function(ImageSelectionType2) {
392
420
  ImageSelectionType2["LOGO"] = "logo";
@@ -486,6 +514,18 @@ var init_filter = __esm({
486
514
  }
487
515
  });
488
516
 
517
+ // node_modules/@speakai/shared/dist/enums/integration.js
518
+ var IntegrationAuthType;
519
+ var init_integration = __esm({
520
+ "node_modules/@speakai/shared/dist/enums/integration.js"() {
521
+ "use strict";
522
+ (function(IntegrationAuthType2) {
523
+ IntegrationAuthType2["OAUTH"] = "oauth";
524
+ IntegrationAuthType2["API_KEY"] = "api_key";
525
+ })(IntegrationAuthType || (IntegrationAuthType = {}));
526
+ }
527
+ });
528
+
489
529
  // node_modules/@speakai/shared/dist/enums/media.js
490
530
  var MediaType, MediaState, MediaPrivacyMode, MediaInsightType, MediaInsightStatus, MediaProcessType;
491
531
  var init_media = __esm({
@@ -963,10 +1003,72 @@ var init_webhook = __esm({
963
1003
  (function(WebhookEventSource2) {
964
1004
  WebhookEventSource2["SPEAK"] = "speak";
965
1005
  WebhookEventSource2["ZAPIER"] = "zapier";
1006
+ WebhookEventSource2["N8N"] = "n8n";
1007
+ WebhookEventSource2["PIPEDREAM"] = "pipedream";
1008
+ WebhookEventSource2["MAKE"] = "make";
966
1009
  })(WebhookEventSource || (WebhookEventSource = {}));
967
1010
  }
968
1011
  });
969
1012
 
1013
+ // node_modules/@speakai/shared/dist/enums/llm.js
1014
+ var LLMProvider, LLMModels;
1015
+ var init_llm = __esm({
1016
+ "node_modules/@speakai/shared/dist/enums/llm.js"() {
1017
+ "use strict";
1018
+ (function(LLMProvider2) {
1019
+ LLMProvider2["OPENAI"] = "openai";
1020
+ LLMProvider2["GOOGLE"] = "google";
1021
+ LLMProvider2["ANTHROPIC"] = "anthropic";
1022
+ LLMProvider2["OPENROUTER"] = "openrouter";
1023
+ })(LLMProvider || (LLMProvider = {}));
1024
+ (function(LLMModels2) {
1025
+ LLMModels2["GPT_3_5"] = "gpt-3.5";
1026
+ LLMModels2["GPT_3_5_TURBO_16K"] = "gpt-3.5-turbo-16k";
1027
+ LLMModels2["GPT_3_5_TURBO_0125"] = "gpt-3.5-turbo-0125";
1028
+ LLMModels2["GPT_4"] = "gpt-4";
1029
+ LLMModels2["GPT_4_1106_PREVIEW"] = "gpt-4-1106-preview";
1030
+ LLMModels2["GPT_4_TURBO"] = "gpt-4-turbo";
1031
+ LLMModels2["GPT_4_O_2024_05_13"] = "gpt-4o-2024-05-13";
1032
+ LLMModels2["GPT_4O"] = "gpt-4o";
1033
+ LLMModels2["GPT_4O_MINI"] = "gpt-4o-mini";
1034
+ LLMModels2["GPT_4_O_2024_08_06"] = "gpt-4o-2024-08-06";
1035
+ LLMModels2["GPT_4_MINI_2024_07_18"] = "gpt-4o-mini-2024-07-18";
1036
+ LLMModels2["GPT_4_1_2025_04_14"] = "gpt-4.1-2025-04-14";
1037
+ LLMModels2["GPT_5_1_2025_11_13"] = "gpt-5.1-2025-11-13";
1038
+ LLMModels2["GPT_5_2"] = "gpt-5.2";
1039
+ LLMModels2["GPT_5_4"] = "gpt-5.4";
1040
+ LLMModels2["GPT_5_4_MINI"] = "gpt-5.4-mini";
1041
+ LLMModels2["GPT_5_4_MINI_2026_03_17"] = "gpt-5.4-mini-2026-03-17";
1042
+ LLMModels2["GPT_5_4_NANO"] = "gpt-5.4-nano";
1043
+ LLMModels2["GPT_5_5"] = "gpt-5.5";
1044
+ LLMModels2["GPT_5_5_THINKING"] = "gpt-5.5-thinking";
1045
+ LLMModels2["GPT_5_6_SOL"] = "gpt-5.6-sol";
1046
+ LLMModels2["GPT_5_6_TERRA"] = "gpt-5.6-terra";
1047
+ LLMModels2["GPT_5_6_LUNA"] = "gpt-5.6-luna";
1048
+ LLMModels2["CLAUDE_2"] = "claude-2";
1049
+ LLMModels2["CLAUDE_3_5_SONNET"] = "claude-3-5-sonnet";
1050
+ LLMModels2["CLAUDE_3_5_SONNET_20241022"] = "claude-3-5-sonnet-20241022";
1051
+ LLMModels2["CLAUDE_3_7_SONNET_LATEST"] = "claude-3-7-sonnet-latest";
1052
+ LLMModels2["CLAUDE_HAIKU_4_5"] = "claude-haiku-4-5";
1053
+ LLMModels2["CLAUDE_SONNET_4_6"] = "claude-sonnet-4-6";
1054
+ LLMModels2["CLAUDE_SONNET_5"] = "claude-sonnet-5";
1055
+ LLMModels2["CLAUDE_OPUS_4_8"] = "claude-opus-4-8";
1056
+ LLMModels2["GEMINI_1_5_PRO"] = "gemini-1.5-pro";
1057
+ LLMModels2["GEMINI_1_5_FLASH"] = "gemini-1.5-flash";
1058
+ LLMModels2["GEMINI_2_0_FLASH"] = "gemini-2.0-flash";
1059
+ LLMModels2["GEMINI_2_5_PRO"] = "gemini-2.5-pro";
1060
+ LLMModels2["GEMINI_2_5_FLASH"] = "gemini-2.5-flash";
1061
+ LLMModels2["GEMINI_2_5_FLASH_LITE"] = "gemini-2.5-flash-lite";
1062
+ LLMModels2["GEMINI_3_FLASH_PREVIEW"] = "gemini-3-flash-preview";
1063
+ LLMModels2["GEMINI_3_1_FLASH_LITE"] = "gemini-3.1-flash-lite";
1064
+ LLMModels2["GEMINI_3_1_PRO_PREVIEW"] = "gemini-3.1-pro-preview";
1065
+ LLMModels2["GEMINI_3_5_FLASH"] = "gemini-3.5-flash";
1066
+ LLMModels2["GROK_4_5"] = "x-ai/grok-4.5";
1067
+ LLMModels2["GLM_5_2"] = "z-ai/glm-5.2";
1068
+ })(LLMModels || (LLMModels = {}));
1069
+ }
1070
+ });
1071
+
970
1072
  // node_modules/@speakai/shared/dist/enums/index.js
971
1073
  var init_enums = __esm({
972
1074
  "node_modules/@speakai/shared/dist/enums/index.js"() {
@@ -981,6 +1083,7 @@ var init_enums = __esm({
981
1083
  init_export();
982
1084
  init_fields();
983
1085
  init_filter();
1086
+ init_integration();
984
1087
  init_media();
985
1088
  init_meeting();
986
1089
  init_notification();
@@ -993,6 +1096,7 @@ var init_enums = __esm({
993
1096
  init_translation();
994
1097
  init_user();
995
1098
  init_webhook();
1099
+ init_llm();
996
1100
  }
997
1101
  });
998
1102
 
@@ -1031,6 +1135,13 @@ var init_folder = __esm({
1031
1135
  }
1032
1136
  });
1033
1137
 
1138
+ // node_modules/@speakai/shared/dist/interfaces/integration.js
1139
+ var init_integration2 = __esm({
1140
+ "node_modules/@speakai/shared/dist/interfaces/integration.js"() {
1141
+ "use strict";
1142
+ }
1143
+ });
1144
+
1034
1145
  // node_modules/@speakai/shared/dist/interfaces/recorder.js
1035
1146
  var init_recorder2 = __esm({
1036
1147
  "node_modules/@speakai/shared/dist/interfaces/recorder.js"() {
@@ -1122,6 +1233,21 @@ var init_clip2 = __esm({
1122
1233
  }
1123
1234
  });
1124
1235
 
1236
+ // node_modules/@speakai/shared/dist/utils/dashboard-spec.js
1237
+ var init_dashboard_spec = __esm({
1238
+ "node_modules/@speakai/shared/dist/utils/dashboard-spec.js"() {
1239
+ "use strict";
1240
+ }
1241
+ });
1242
+
1243
+ // node_modules/@speakai/shared/dist/interfaces/dashboard.js
1244
+ var init_dashboard = __esm({
1245
+ "node_modules/@speakai/shared/dist/interfaces/dashboard.js"() {
1246
+ "use strict";
1247
+ init_dashboard_spec();
1248
+ }
1249
+ });
1250
+
1125
1251
  // node_modules/@speakai/shared/dist/interfaces/index.js
1126
1252
  var init_interfaces = __esm({
1127
1253
  "node_modules/@speakai/shared/dist/interfaces/index.js"() {
@@ -1131,6 +1257,7 @@ var init_interfaces = __esm({
1131
1257
  init_transcript();
1132
1258
  init_text();
1133
1259
  init_folder();
1260
+ init_integration2();
1134
1261
  init_recorder2();
1135
1262
  init_embed2();
1136
1263
  init_automation2();
@@ -1144,6 +1271,7 @@ var init_interfaces = __esm({
1144
1271
  init_calendar2();
1145
1272
  init_category();
1146
1273
  init_clip2();
1274
+ init_dashboard();
1147
1275
  }
1148
1276
  });
1149
1277
 
@@ -1154,6 +1282,70 @@ var init_transcript2 = __esm({
1154
1282
  }
1155
1283
  });
1156
1284
 
1285
+ // node_modules/@speakai/shared/dist/pricing/modelPricing.js
1286
+ var MODEL_PRICING;
1287
+ var init_modelPricing = __esm({
1288
+ "node_modules/@speakai/shared/dist/pricing/modelPricing.js"() {
1289
+ "use strict";
1290
+ init_llm();
1291
+ MODEL_PRICING = {
1292
+ // ═══════════════ OpenAI ═══════════════
1293
+ // Deprecated
1294
+ [LLMModels.GPT_3_5]: { inputPerMillion: 0.5, outputPerMillion: 1.5, provider: LLMProvider.OPENAI },
1295
+ [LLMModels.GPT_3_5_TURBO_16K]: { inputPerMillion: 3, outputPerMillion: 4, provider: LLMProvider.OPENAI },
1296
+ [LLMModels.GPT_3_5_TURBO_0125]: { inputPerMillion: 0.5, outputPerMillion: 1.5, provider: LLMProvider.OPENAI },
1297
+ [LLMModels.GPT_4]: { inputPerMillion: 30, outputPerMillion: 60, provider: LLMProvider.OPENAI },
1298
+ [LLMModels.GPT_4_1106_PREVIEW]: { inputPerMillion: 10, outputPerMillion: 30, provider: LLMProvider.OPENAI },
1299
+ [LLMModels.GPT_4_TURBO]: { inputPerMillion: 10, outputPerMillion: 30, provider: LLMProvider.OPENAI },
1300
+ [LLMModels.GPT_4_O_2024_05_13]: { inputPerMillion: 5, outputPerMillion: 15, provider: LLMProvider.OPENAI },
1301
+ // Live
1302
+ [LLMModels.GPT_4O]: { inputPerMillion: 2.5, outputPerMillion: 10, cachedInputPerMillion: 1.25, provider: LLMProvider.OPENAI },
1303
+ [LLMModels.GPT_4O_MINI]: { inputPerMillion: 0.15, outputPerMillion: 0.6, cachedInputPerMillion: 0.075, provider: LLMProvider.OPENAI },
1304
+ [LLMModels.GPT_4_O_2024_08_06]: { inputPerMillion: 2.5, outputPerMillion: 10, cachedInputPerMillion: 1.25, provider: LLMProvider.OPENAI },
1305
+ [LLMModels.GPT_4_MINI_2024_07_18]: { inputPerMillion: 0.15, outputPerMillion: 0.6, cachedInputPerMillion: 0.075, provider: LLMProvider.OPENAI },
1306
+ [LLMModels.GPT_4_1_2025_04_14]: { inputPerMillion: 2, outputPerMillion: 8, cachedInputPerMillion: 0.5, provider: LLMProvider.OPENAI },
1307
+ [LLMModels.GPT_5_1_2025_11_13]: { inputPerMillion: 1.25, outputPerMillion: 10, cachedInputPerMillion: 0.125, provider: LLMProvider.OPENAI },
1308
+ [LLMModels.GPT_5_2]: { inputPerMillion: 1.75, outputPerMillion: 14, cachedInputPerMillion: 0.175, provider: LLMProvider.OPENAI },
1309
+ [LLMModels.GPT_5_4]: { inputPerMillion: 2.5, outputPerMillion: 15, cachedInputPerMillion: 0.25, longContextThresholdTokens: 272e3, inputPerMillionLong: 5, outputPerMillionLong: 22.5, cachedInputPerMillionLong: 0.5, provider: LLMProvider.OPENAI },
1310
+ [LLMModels.GPT_5_4_MINI]: { inputPerMillion: 0.75, outputPerMillion: 4.5, cachedInputPerMillion: 0.075, provider: LLMProvider.OPENAI },
1311
+ [LLMModels.GPT_5_4_MINI_2026_03_17]: { inputPerMillion: 0.75, outputPerMillion: 4.5, cachedInputPerMillion: 0.075, provider: LLMProvider.OPENAI },
1312
+ [LLMModels.GPT_5_4_NANO]: { inputPerMillion: 0.2, outputPerMillion: 1.25, cachedInputPerMillion: 0.02, provider: LLMProvider.OPENAI },
1313
+ [LLMModels.GPT_5_5]: { inputPerMillion: 5, outputPerMillion: 30, cachedInputPerMillion: 0.5, longContextThresholdTokens: 272e3, inputPerMillionLong: 10, outputPerMillionLong: 45, cachedInputPerMillionLong: 1, provider: LLMProvider.OPENAI },
1314
+ [LLMModels.GPT_5_5_THINKING]: { inputPerMillion: 5, outputPerMillion: 30, cachedInputPerMillion: 0.5, longContextThresholdTokens: 272e3, inputPerMillionLong: 10, outputPerMillionLong: 45, cachedInputPerMillionLong: 1, provider: LLMProvider.OPENAI },
1315
+ // gpt-5.5 reasoning mode (same rate)
1316
+ [LLMModels.GPT_5_6_SOL]: { inputPerMillion: 5, outputPerMillion: 30, cachedInputPerMillion: 0.5, provider: LLMProvider.OPENAI },
1317
+ [LLMModels.GPT_5_6_TERRA]: { inputPerMillion: 2.5, outputPerMillion: 15, cachedInputPerMillion: 0.25, provider: LLMProvider.OPENAI },
1318
+ [LLMModels.GPT_5_6_LUNA]: { inputPerMillion: 1, outputPerMillion: 6, cachedInputPerMillion: 0.1, provider: LLMProvider.OPENAI },
1319
+ // ═══════════════ Anthropic (cache read = 0.1x input) ═══════════════
1320
+ // Deprecated
1321
+ [LLMModels.CLAUDE_2]: { inputPerMillion: 8, outputPerMillion: 24, provider: LLMProvider.ANTHROPIC },
1322
+ [LLMModels.CLAUDE_3_5_SONNET]: { inputPerMillion: 3, outputPerMillion: 15, cachedInputPerMillion: 0.3, provider: LLMProvider.ANTHROPIC },
1323
+ [LLMModels.CLAUDE_3_5_SONNET_20241022]: { inputPerMillion: 3, outputPerMillion: 15, cachedInputPerMillion: 0.3, provider: LLMProvider.ANTHROPIC },
1324
+ [LLMModels.CLAUDE_3_7_SONNET_LATEST]: { inputPerMillion: 3, outputPerMillion: 15, cachedInputPerMillion: 0.3, provider: LLMProvider.ANTHROPIC },
1325
+ // Live
1326
+ [LLMModels.CLAUDE_HAIKU_4_5]: { inputPerMillion: 1, outputPerMillion: 5, cachedInputPerMillion: 0.1, provider: LLMProvider.ANTHROPIC },
1327
+ [LLMModels.CLAUDE_SONNET_4_6]: { inputPerMillion: 3, outputPerMillion: 15, cachedInputPerMillion: 0.3, provider: LLMProvider.ANTHROPIC },
1328
+ [LLMModels.CLAUDE_SONNET_5]: { inputPerMillion: 3, outputPerMillion: 15, cachedInputPerMillion: 0.3, provider: LLMProvider.ANTHROPIC },
1329
+ [LLMModels.CLAUDE_OPUS_4_8]: { inputPerMillion: 5, outputPerMillion: 25, cachedInputPerMillion: 0.5, provider: LLMProvider.ANTHROPIC },
1330
+ // ═══════════════ Google Gemini ═══════════════
1331
+ // Deprecated
1332
+ [LLMModels.GEMINI_1_5_PRO]: { inputPerMillion: 1.25, outputPerMillion: 5, provider: LLMProvider.GOOGLE },
1333
+ [LLMModels.GEMINI_1_5_FLASH]: { inputPerMillion: 0.075, outputPerMillion: 0.3, cachedInputPerMillion: 0.01875, provider: LLMProvider.GOOGLE },
1334
+ [LLMModels.GEMINI_2_0_FLASH]: { inputPerMillion: 0.1, outputPerMillion: 0.4, cachedInputPerMillion: 0.025, provider: LLMProvider.GOOGLE },
1335
+ // Live
1336
+ [LLMModels.GEMINI_2_5_PRO]: { inputPerMillion: 1.25, outputPerMillion: 10, longContextThresholdTokens: 2e5, inputPerMillionLong: 2.5, outputPerMillionLong: 15, provider: LLMProvider.GOOGLE },
1337
+ [LLMModels.GEMINI_2_5_FLASH]: { inputPerMillion: 0.3, outputPerMillion: 2.5, cachedInputPerMillion: 0.03, provider: LLMProvider.GOOGLE },
1338
+ [LLMModels.GEMINI_2_5_FLASH_LITE]: { inputPerMillion: 0.1, outputPerMillion: 0.4, cachedInputPerMillion: 0.01, provider: LLMProvider.GOOGLE },
1339
+ [LLMModels.GEMINI_3_FLASH_PREVIEW]: { inputPerMillion: 0.5, outputPerMillion: 3, cachedInputPerMillion: 0.05, provider: LLMProvider.GOOGLE },
1340
+ [LLMModels.GEMINI_3_1_FLASH_LITE]: { inputPerMillion: 0.25, outputPerMillion: 1.5, provider: LLMProvider.GOOGLE },
1341
+ [LLMModels.GEMINI_3_1_PRO_PREVIEW]: { inputPerMillion: 2, outputPerMillion: 12, longContextThresholdTokens: 2e5, inputPerMillionLong: 4, outputPerMillionLong: 18, provider: LLMProvider.GOOGLE },
1342
+ [LLMModels.GEMINI_3_5_FLASH]: { inputPerMillion: 1.5, outputPerMillion: 9, cachedInputPerMillion: 0.15, provider: LLMProvider.GOOGLE },
1343
+ [LLMModels.GROK_4_5]: { inputPerMillion: 2.2, outputPerMillion: 6.6, cachedInputPerMillion: 0.22, provider: LLMProvider.OPENROUTER },
1344
+ [LLMModels.GLM_5_2]: { inputPerMillion: 1.023, outputPerMillion: 3.3, cachedInputPerMillion: 0.1023, provider: LLMProvider.OPENROUTER }
1345
+ };
1346
+ }
1347
+ });
1348
+
1157
1349
  // node_modules/@speakai/shared/dist/index.js
1158
1350
  var init_dist = __esm({
1159
1351
  "node_modules/@speakai/shared/dist/index.js"() {
@@ -1161,6 +1353,8 @@ var init_dist = __esm({
1161
1353
  init_enums();
1162
1354
  init_interfaces();
1163
1355
  init_transcript2();
1356
+ init_dashboard_spec();
1357
+ init_modelPricing();
1164
1358
  }
1165
1359
  });
1166
1360
 
@@ -3912,6 +4106,555 @@ var init_capabilities = __esm({
3912
4106
  }
3913
4107
  });
3914
4108
 
4109
+ // src/tools/automation-graph.ts
4110
+ function containsCondition(nodes) {
4111
+ return nodes.some(
4112
+ (node) => isConditionNode(node) || LEG_BRANCHES.some((br) => containsCondition(legOf(node, br)))
4113
+ );
4114
+ }
4115
+ function legTails(leg, enclosingConditionId) {
4116
+ if (!leg.length) return [enclosingConditionId];
4117
+ const last = leg[leg.length - 1];
4118
+ if (!isConditionNode(last)) return [last.step.stepId];
4119
+ const rejoining = LEG_BRANCHES.filter((br) => exitOf(last, br) === "rejoin");
4120
+ if (!rejoining.length) return [];
4121
+ return uniq(rejoining.flatMap((br) => legTails(legOf(last, br), last.step.stepId)));
4122
+ }
4123
+ function flatten(nodes, parentIds = [], branch) {
4124
+ const out = [];
4125
+ let incoming = parentIds;
4126
+ let incomingBranch = branch;
4127
+ for (const node of nodes) {
4128
+ out.push({
4129
+ node,
4130
+ dependsOn: uniq(incoming),
4131
+ ...incomingBranch ? { branch: incomingBranch } : {}
4132
+ });
4133
+ if (!isConditionNode(node)) {
4134
+ incoming = [node.step.stepId];
4135
+ incomingBranch = branch;
4136
+ continue;
4137
+ }
4138
+ for (const br of LEG_BRANCHES) {
4139
+ out.push(...flatten(legOf(node, br), [node.step.stepId], br));
4140
+ }
4141
+ const rejoining = LEG_BRANCHES.filter((br) => exitOf(node, br) === "rejoin");
4142
+ incoming = uniq(rejoining.flatMap((br) => legTails(legOf(node, br), node.step.stepId)));
4143
+ incomingBranch = rejoining.length === 1 && !legOf(node, rejoining[0]).length ? rejoining[0] : branch;
4144
+ }
4145
+ return out;
4146
+ }
4147
+ function compileGraph(nodes) {
4148
+ const branched = containsCondition(nodes);
4149
+ return flatten(nodes).map(({ node, dependsOn, branch }) => ({
4150
+ ...node.step,
4151
+ ...branched ? { dependsOn } : {},
4152
+ ...branch ? { branch } : {}
4153
+ }));
4154
+ }
4155
+ function hydrateLegs(steps) {
4156
+ const byParent = /* @__PURE__ */ new Map();
4157
+ for (const step of steps) {
4158
+ for (const parent of step.dependsOn ?? []) {
4159
+ const list = byParent.get(parent) ?? [];
4160
+ list.push(step);
4161
+ byParent.set(parent, list);
4162
+ }
4163
+ }
4164
+ const referenced = new Set(steps.flatMap((step) => step.dependsOn ?? []));
4165
+ const claimed = /* @__PURE__ */ new Set();
4166
+ function legReaches(leg, conditionId, legMemberIds) {
4167
+ if (!leg.length) {
4168
+ return steps.some(
4169
+ (step) => step.stepId !== conditionId && !legMemberIds.has(step.stepId) && (step.dependsOn ?? []).includes(conditionId)
4170
+ );
4171
+ }
4172
+ const tails = legTails(leg, conditionId);
4173
+ if (!tails.length) return true;
4174
+ return tails.some((id) => referenced.has(id));
4175
+ }
4176
+ function buildLeg(conditionId, branch) {
4177
+ const leg = [];
4178
+ let cursor = conditionId;
4179
+ for (; ; ) {
4180
+ const next = (byParent.get(cursor) ?? []).find(
4181
+ (step) => step.branch === branch && !claimed.has(step.stepId)
4182
+ );
4183
+ if (!next) break;
4184
+ claimed.add(next.stepId);
4185
+ leg.push(next.stepType === CONDITION_STEP_TYPE ? withLegs(next) : { step: next });
4186
+ cursor = next.stepId;
4187
+ }
4188
+ return leg;
4189
+ }
4190
+ function withLegs(condition) {
4191
+ const legs = {
4192
+ true: buildLeg(condition.stepId, "true"),
4193
+ false: buildLeg(condition.stepId, "false")
4194
+ };
4195
+ const legMemberIds = new Set(
4196
+ [...legs.true, ...legs.false].map((node) => node.step.stepId)
4197
+ );
4198
+ return {
4199
+ step: condition,
4200
+ legs,
4201
+ legExit: {
4202
+ true: legReaches(legs.true, condition.stepId, legMemberIds) ? "rejoin" : "end",
4203
+ false: legReaches(legs.false, condition.stepId, legMemberIds) ? "rejoin" : "end"
4204
+ }
4205
+ };
4206
+ }
4207
+ const nested = /* @__PURE__ */ new Map();
4208
+ for (const step of steps) {
4209
+ if (claimed.has(step.stepId)) continue;
4210
+ if (step.stepType === CONDITION_STEP_TYPE) nested.set(step.stepId, withLegs(step));
4211
+ }
4212
+ return steps.filter((step) => !claimed.has(step.stepId)).map((step) => nested.get(step.stepId) ?? { step });
4213
+ }
4214
+ function resolveIncomingTypes(steps, rootType) {
4215
+ const byId = new Map(steps.map((step) => [step.stepId, step]));
4216
+ const incoming = /* @__PURE__ */ new Map();
4217
+ const resolving = /* @__PURE__ */ new Set();
4218
+ const outputsOf = (step, into2) => {
4219
+ const io = ACTION_IO[step.stepType];
4220
+ if (!io) return into2;
4221
+ if (io.passthrough) return into2;
4222
+ return /* @__PURE__ */ new Set([io.out]);
4223
+ };
4224
+ const into = (step) => {
4225
+ const cached2 = incoming.get(step.stepId);
4226
+ if (cached2) return cached2;
4227
+ if (resolving.has(step.stepId)) return /* @__PURE__ */ new Set([rootType]);
4228
+ resolving.add(step.stepId);
4229
+ const parents = (step.dependsOn ?? []).map((id) => byId.get(id)).filter((parent) => parent !== void 0);
4230
+ const types = parents.length ? new Set(parents.flatMap((parent) => [...outputsOf(parent, into(parent))])) : /* @__PURE__ */ new Set([rootType]);
4231
+ resolving.delete(step.stepId);
4232
+ incoming.set(step.stepId, types);
4233
+ return types;
4234
+ };
4235
+ steps.forEach(into);
4236
+ return incoming;
4237
+ }
4238
+ function incomingTypesByStep(steps, rootType) {
4239
+ const hasDependencies = steps.some((step) => (step.dependsOn ?? []).length > 0);
4240
+ if (hasDependencies) return resolveIncomingTypes(steps, rootType);
4241
+ const byStep = /* @__PURE__ */ new Map();
4242
+ let cursor = rootType;
4243
+ for (const step of steps) {
4244
+ byStep.set(step.stepId, /* @__PURE__ */ new Set([cursor]));
4245
+ const io = ACTION_IO[step.stepType];
4246
+ if (io && !io.passthrough) cursor = io.out;
4247
+ }
4248
+ return byStep;
4249
+ }
4250
+ function mediaAvailabilityByStep(steps, rootType) {
4251
+ const available = /* @__PURE__ */ new Map();
4252
+ const rootHasMedia = rootType === "media";
4253
+ const byId = new Map(steps.map((step) => [step.stepId, step]));
4254
+ const hasDependencies = steps.some((step) => (step.dependsOn ?? []).length > 0);
4255
+ if (!hasDependencies) {
4256
+ let seen = rootHasMedia;
4257
+ for (const step of steps) {
4258
+ available.set(step.stepId, seen);
4259
+ if (step.stepType === "speak-upload") seen = true;
4260
+ }
4261
+ return available;
4262
+ }
4263
+ const resolving = /* @__PURE__ */ new Set();
4264
+ const at = (stepId) => {
4265
+ const cached2 = available.get(stepId);
4266
+ if (cached2 !== void 0) return cached2;
4267
+ if (resolving.has(stepId)) return rootHasMedia;
4268
+ resolving.add(stepId);
4269
+ const parents = (byId.get(stepId)?.dependsOn ?? []).filter((id) => byId.has(id));
4270
+ const result = parents.length ? parents.every((id) => byId.get(id).stepType === "speak-upload" || at(id)) : rootHasMedia;
4271
+ resolving.delete(stepId);
4272
+ available.set(stepId, result);
4273
+ return result;
4274
+ };
4275
+ for (const step of steps) at(step.stepId);
4276
+ return available;
4277
+ }
4278
+ function validateGraph(steps, opts = {}) {
4279
+ const errors = [];
4280
+ const warnings = [];
4281
+ if (!Array.isArray(steps) || steps.length === 0) {
4282
+ return { errors: ["The automation needs at least one step."], warnings };
4283
+ }
4284
+ if (steps.length > MAX_STEPS) {
4285
+ errors.push(
4286
+ `An automation can hold ${MAX_STEPS} steps; this one has ${steps.length}. A branch spends steps quickly \u2014 a condition plus two two-step legs plus a merge is six.`
4287
+ );
4288
+ }
4289
+ const byId = /* @__PURE__ */ new Map();
4290
+ for (const step of steps) {
4291
+ if (!step.stepId) {
4292
+ errors.push("Every step needs a stepId.");
4293
+ continue;
4294
+ }
4295
+ if (byId.has(step.stepId)) errors.push(`Two steps share the id "${step.stepId}".`);
4296
+ byId.set(step.stepId, step);
4297
+ }
4298
+ for (const step of steps) {
4299
+ if (step.stepId && !/^[A-Za-z_]/.test(step.stepId)) {
4300
+ warnings.push(
4301
+ `Step id "${step.stepId}" does not start with a letter, so a whole-value {{step.${step.stepId}.\u2026}} token inside a Composio argsTemplate arrives as text instead of keeping its type.`
4302
+ );
4303
+ }
4304
+ }
4305
+ for (const step of steps) {
4306
+ for (const parentId of step.dependsOn ?? []) {
4307
+ if (!byId.has(parentId)) {
4308
+ errors.push(`Step "${step.stepId}" depends on "${parentId}", which is not in this automation.`);
4309
+ }
4310
+ }
4311
+ }
4312
+ const hasDependencies = steps.some((step) => (step.dependsOn ?? []).length > 0);
4313
+ if (hasDependencies) {
4314
+ const state = /* @__PURE__ */ new Map();
4315
+ const walk = (id) => {
4316
+ const status = state.get(id);
4317
+ if (status === 1) return false;
4318
+ if (status === 0) return true;
4319
+ state.set(id, 0);
4320
+ for (const parent of byId.get(id)?.dependsOn ?? []) {
4321
+ if (byId.has(parent) && walk(parent)) return true;
4322
+ }
4323
+ state.set(id, 1);
4324
+ return false;
4325
+ };
4326
+ for (const step of steps) {
4327
+ if (step.stepId && walk(step.stepId)) {
4328
+ errors.push(`The steps form a loop through "${step.stepId}" \u2014 a step cannot depend on itself, directly or indirectly.`);
4329
+ break;
4330
+ }
4331
+ }
4332
+ }
4333
+ const branchedSteps = steps.filter((step) => step.branch === "true" || step.branch === "false");
4334
+ const conditionSteps = steps.filter((step) => step.stepType === CONDITION_STEP_TYPE);
4335
+ const isBranched = branchedSteps.length > 0 || conditionSteps.length > 0;
4336
+ for (const step of steps) {
4337
+ if (step.stepType !== CONDITION_STEP_TYPE && step.stepType !== FILTER_STEP_TYPE) continue;
4338
+ const block = ruleBlockOf(step);
4339
+ const rules = block?.rules ?? [];
4340
+ if (!rules.length) {
4341
+ errors.push(
4342
+ step.stepType === CONDITION_STEP_TYPE ? `Condition "${step.stepId}" has no rules. An empty rule set counts as a match, so every run would take the "true" branch.` : `Filter "${step.stepId}" has no rules.`
4343
+ );
4344
+ }
4345
+ if (rules.length > 20) {
4346
+ errors.push(`Step "${step.stepId}" has ${rules.length} rules; the limit is 20.`);
4347
+ }
4348
+ }
4349
+ if (isBranched) {
4350
+ const anchorsOf = (stepId, seen = /* @__PURE__ */ new Set()) => {
4351
+ const found = /* @__PURE__ */ new Set();
4352
+ if (seen.has(stepId)) return found;
4353
+ seen.add(stepId);
4354
+ const self = byId.get(stepId);
4355
+ for (const parentId of self?.dependsOn ?? []) {
4356
+ const parent = byId.get(parentId);
4357
+ if (!parent) continue;
4358
+ if (parent.stepType === CONDITION_STEP_TYPE) found.add(parent.stepId);
4359
+ else if (parent.branch && parent.branch === self?.branch) {
4360
+ for (const id of anchorsOf(parent.stepId, seen)) found.add(id);
4361
+ }
4362
+ }
4363
+ return found;
4364
+ };
4365
+ const ancestorsOf = (stepId) => {
4366
+ const out = /* @__PURE__ */ new Set();
4367
+ const stack = [...byId.get(stepId)?.dependsOn ?? []];
4368
+ while (stack.length) {
4369
+ const id = stack.pop();
4370
+ if (out.has(id) || !byId.has(id)) continue;
4371
+ out.add(id);
4372
+ stack.push(...byId.get(id)?.dependsOn ?? []);
4373
+ }
4374
+ return out;
4375
+ };
4376
+ const anchored = /* @__PURE__ */ new Set();
4377
+ for (const step of branchedSteps) {
4378
+ const anchors = anchorsOf(step.stepId);
4379
+ if (!anchors.size) {
4380
+ errors.push(
4381
+ `Step "${step.stepId}" is marked as the "${step.branch}" branch but nothing connects it to a condition, so it would run on every path.`
4382
+ );
4383
+ continue;
4384
+ }
4385
+ for (const id of anchors) anchored.add(id);
4386
+ const opposite = [...ancestorsOf(step.stepId)].map((id) => byId.get(id)).find(
4387
+ (ancestor) => (ancestor?.branch === "true" || ancestor?.branch === "false") && ancestor.branch !== step.branch && [...anchorsOf(ancestor.stepId)].some((id) => anchors.has(id))
4388
+ );
4389
+ if (opposite) {
4390
+ errors.push(
4391
+ `Step "${step.stepId}" (on the "${step.branch}" branch) waits on "${opposite.stepId}", which is on the other branch of the same condition \u2014 so it can never run.`
4392
+ );
4393
+ }
4394
+ }
4395
+ for (const condition of conditionSteps) {
4396
+ if (!anchored.has(condition.stepId)) {
4397
+ errors.push(
4398
+ `Condition "${condition.stepId}" has no steps on either side, so both paths do the same thing. Put a step on one of its branches, or use a filter to stop the run instead.`
4399
+ );
4400
+ }
4401
+ }
4402
+ const roots = steps.filter((step) => !(step.dependsOn ?? []).length);
4403
+ if (branchedSteps.length && roots.length > 1) {
4404
+ errors.push(
4405
+ `A branched automation must have a single entry step, but ${roots.length} steps declare no dependsOn (${roots.map((step) => `"${step.stepId}"`).join(", ")}) \u2014 each of those would run on every branch. Give every step after the first a dependsOn.`
4406
+ );
4407
+ }
4408
+ }
4409
+ if (opts.runType === "schedule" && conditionSteps.length) {
4410
+ errors.push(
4411
+ 'A scheduled automation cannot branch. A schedule runs over a batch of media and a condition resolves once for the whole batch \u2014 it answers "true" when any one media matches and narrows nothing, so the branch would run against media that did not match. Use a filter, which narrows the batch.'
4412
+ );
4413
+ }
4414
+ if (isBranched) {
4415
+ const tree = hydrateLegs(steps);
4416
+ errors.push(...branchingReloadErrors(tree, 1));
4417
+ const rebuilt = new Map(compileGraph(tree).map((step) => [step.stepId, step]));
4418
+ const structurallyMoved = [];
4419
+ const reordered = [];
4420
+ for (const step of steps) {
4421
+ const after = rebuilt.get(step.stepId);
4422
+ if (!after) {
4423
+ structurallyMoved.push(step.stepId);
4424
+ continue;
4425
+ }
4426
+ const before = step.dependsOn ?? [];
4427
+ const now = after.dependsOn ?? [];
4428
+ if (step.branch !== after.branch || before.length !== now.length || now.some((id) => !before.includes(id))) {
4429
+ structurallyMoved.push(step.stepId);
4430
+ } else if (before.some((id, i) => now[i] !== id)) {
4431
+ reordered.push(step.stepId);
4432
+ }
4433
+ }
4434
+ if (structurallyMoved.length) {
4435
+ errors.push(
4436
+ `The Speak web editor would not reload this automation the way it is written: ${structurallyMoved.slice(0, 4).map((id) => `"${id}"`).join(", ")} would come back on a different branch or with different parents. The usual cause is a step placed after a nested condition \u2014 a branch inside a branch has to be the last step of the branch it sits on, because the leg marker cannot say which of the two branches it belongs to.`
4437
+ );
4438
+ }
4439
+ if (reordered.length) {
4440
+ warnings.push(
4441
+ `Reopening this automation in the Speak web editor would reorder the dependsOn of ${reordered.slice(0, 4).map((id) => `"${id}"`).join(", ")}. The steps are the same; only the order the branches are listed in changes, which can affect which branch's fields a merge is validated against.`
4442
+ );
4443
+ }
4444
+ }
4445
+ const rootType = opts.triggerSlug ? TRIGGER_OUT[opts.triggerSlug] : void 0;
4446
+ if (rootType) {
4447
+ const incomingByStep = incomingTypesByStep(steps, rootType);
4448
+ const hasMedia = mediaAvailabilityByStep(steps, rootType);
4449
+ for (const step of steps) {
4450
+ const incomingTypes = incomingByStep.get(step.stepId) ?? /* @__PURE__ */ new Set([rootType]);
4451
+ const io = ACTION_IO[step.stepType];
4452
+ if (!io) continue;
4453
+ const unacceptable = [...incomingTypes].filter((type) => !io.in.includes(type));
4454
+ if (unacceptable.length && step.stepType !== "composio-action") {
4455
+ errors.push(
4456
+ `Step "${step.stepId}" (${step.stepType}) cannot accept "${unacceptable.join('", "')}" from the step before it \u2014 it expects one of: ${io.in.join(", ")}.`
4457
+ );
4458
+ }
4459
+ if (step.stepType !== CONDITION_STEP_TYPE && step.stepType !== FILTER_STEP_TYPE) continue;
4460
+ if (incomingTypes.size > 1) {
4461
+ warnings.push(
4462
+ `Step "${step.stepId}" merges branches carrying different kinds of data (${[...incomingTypes].join(", ")}). The server checks its rule fields against "${[...incomingTypes][0]}" only, so a rule valid on the other branch may be refused.`
4463
+ );
4464
+ }
4465
+ const flowing = [...incomingTypes][0] ?? rootType;
4466
+ for (const rule of ruleBlockOf(step)?.rules ?? []) {
4467
+ const field = String(rule.field ?? "");
4468
+ if (!field) {
4469
+ errors.push(`Step "${step.stepId}" has a rule with no field.`);
4470
+ continue;
4471
+ }
4472
+ const payloadAdvice = `Upload the payload first and use fieldsMap (create_automation) or mapFields (build_automation) to write "${field}" onto the media as a custom field, then test that field id here.`;
4473
+ if (!hasMedia.get(step.stepId)) {
4474
+ errors.push(
4475
+ `Step "${step.stepId}" tests "${field}", but at this point in the automation nothing has produced a media item yet \u2014 and a ${step.stepType} can only read a media item and earlier step answers, never the trigger payload. As written the run would stop here with "Media not found". ${payloadAdvice}`
4476
+ );
4477
+ continue;
4478
+ }
4479
+ if (looksLikePayloadPath(field)) {
4480
+ errors.push(
4481
+ `Step "${step.stepId}" tests "${field}", which reads the trigger payload \u2014 and a ${step.stepType} cannot read the payload. It would silently find nothing and take the same branch on every run. ${payloadAdvice}`
4482
+ );
4483
+ continue;
4484
+ }
4485
+ if (isCanonicalFilterField(field)) {
4486
+ const strictFlow = flowing === "media" || flowing === "insight" || flowing === "file";
4487
+ const allowed = FILTER_FIELDS_BY_IOTYPE[flowing] ?? [];
4488
+ if (strictFlow && !allowed.includes(canonicalFilterField(field))) {
4489
+ errors.push(
4490
+ `Step "${step.stepId}" tests "${field}", which is not available here: what reaches this step is "${flowing}"` + (flowing === "insight" ? `, so only "answer" can be tested. Move the ${step.stepType} before the AI step to test media fields.` : `, which offers: ${allowed.join(", ") || "no built-in fields"}.`)
4491
+ );
4492
+ }
4493
+ continue;
4494
+ }
4495
+ if (flowing === "insight" || flowing === "file") {
4496
+ errors.push(
4497
+ `Step "${step.stepId}" tests the custom field "${field}", but straight after an AI step only "answer" can be tested. Move the ${step.stepType} before the AI step.`
4498
+ );
4499
+ continue;
4500
+ }
4501
+ if (!looksLikeCustomFieldId(field)) {
4502
+ errors.push(`Step "${step.stepId}": "${field}" is not a valid field name or id.`);
4503
+ continue;
4504
+ }
4505
+ if (opts.knownFieldIds && !opts.knownFieldIds.has(field)) {
4506
+ errors.push(
4507
+ `Step "${step.stepId}" tests custom field "${field}", which does not exist in this workspace. A condition naming an unknown field is not rejected by the server and silently takes the same branch every time \u2014 use list_fields to get a real field id.`
4508
+ );
4509
+ }
4510
+ }
4511
+ }
4512
+ }
4513
+ if (isBranched) {
4514
+ const positional = /* @__PURE__ */ new Set();
4515
+ for (const step of steps) {
4516
+ for (const match of JSON.stringify(step).matchAll(/\{\{\s*step\.(\d+)\.[^}\s]+\s*\}\}/g)) {
4517
+ positional.add(match[0].replace(/\\"/g, '"'));
4518
+ }
4519
+ }
4520
+ if (positional.size) {
4521
+ errors.push(
4522
+ `This automation branches, so a numbered step token cannot be trusted: ${[...positional].slice(0, 3).join(", ")}. The number indexes the stored order ([condition, true leg, false leg, merge]), not the order steps run, and a step on the branch that was not taken produces nothing. Address the step by its id instead: {{step.<stepId>.answer}}.`
4523
+ );
4524
+ }
4525
+ }
4526
+ return { errors, warnings };
4527
+ }
4528
+ function branchingReloadErrors(nodes, depth) {
4529
+ const errors = [];
4530
+ for (const [index, node] of nodes.entries()) {
4531
+ if (!isConditionNode(node)) continue;
4532
+ if (depth > MAX_BRANCH_DEPTH) {
4533
+ errors.push(
4534
+ `Condition "${node.step.stepId}" is nested ${depth} branches deep; the editor supports ${MAX_BRANCH_DEPTH}. Deeper than that cannot be opened on the canvas.`
4535
+ );
4536
+ continue;
4537
+ }
4538
+ const yesExit = exitOf(node, "true");
4539
+ const noExit = exitOf(node, "false");
4540
+ if (yesExit === "end" && noExit === "end" && index < nodes.length - 1) {
4541
+ errors.push(
4542
+ `Both branches of condition "${node.step.stepId}" end the run, but "${nodes[index + 1].step.stepId}" comes after it \u2014 nothing would reach that step.`
4543
+ );
4544
+ }
4545
+ const reaches = LEG_BRANCHES.some(
4546
+ (branch) => exitOf(node, branch) === "rejoin" && legReachesOnward(legOf(node, branch))
4547
+ );
4548
+ if (!reaches && index < nodes.length - 1) {
4549
+ errors.push(
4550
+ `Every path through condition "${node.step.stepId}" ends inside it, so "${nodes[index + 1].step.stepId}" would be left with nothing to run after.`
4551
+ );
4552
+ }
4553
+ for (const branch of LEG_BRANCHES) {
4554
+ errors.push(...branchingReloadErrors(legOf(node, branch), depth + 1));
4555
+ }
4556
+ }
4557
+ return errors;
4558
+ }
4559
+ function legReachesOnward(leg) {
4560
+ if (!leg.length) return true;
4561
+ const last = leg[leg.length - 1];
4562
+ if (!isConditionNode(last)) return true;
4563
+ return LEG_BRANCHES.some(
4564
+ (branch) => exitOf(last, branch) === "rejoin" && legReachesOnward(legOf(last, branch))
4565
+ );
4566
+ }
4567
+ function describeGraph(steps) {
4568
+ const lines = [];
4569
+ const summarise = (step) => {
4570
+ const block = ruleBlockOf(step);
4571
+ if (block?.rules?.length) {
4572
+ const logic = block.logic ?? "AND";
4573
+ const rules = block.rules.map((rule) => `${rule.field} ${rule.op}${"value" in rule ? ` ${JSON.stringify(rule.value)}` : ""}`).join(` ${logic} `);
4574
+ return `${step.stepType} [${rules}]`;
4575
+ }
4576
+ return step.stepType;
4577
+ };
4578
+ const walk = (nodes, indent) => {
4579
+ for (const node of nodes) {
4580
+ lines.push(`${indent}${node.step.stepId} ${summarise(node.step)}`);
4581
+ if (!isConditionNode(node)) continue;
4582
+ for (const branch of LEG_BRANCHES) {
4583
+ const leg = legOf(node, branch);
4584
+ const exit = exitOf(node, branch);
4585
+ const label = branch === "true" ? "yes" : "no";
4586
+ const tail = exit === "end" ? " (ends the run)" : "";
4587
+ lines.push(`${indent} \u251C\u2500 ${label}:${leg.length ? tail : ` (no steps)${tail}`}`);
4588
+ walk(leg, `${indent} \u2502 `);
4589
+ }
4590
+ }
4591
+ };
4592
+ walk(hydrateLegs(steps), "");
4593
+ return lines.join("\n");
4594
+ }
4595
+ var LEG_BRANCHES, MAX_BRANCH_DEPTH, MAX_STEPS, CONDITION_STEP_TYPE, FILTER_STEP_TYPE, ACTION_IO, TRIGGER_OUT, FILTER_FIELDS_BY_IOTYPE, FILTER_FIELD_ALIASES, canonicalFilterField, ALL_CANONICAL_FILTER_FIELDS, isCanonicalFilterField, CUSTOM_FIELD_ID_PATTERN, PAYLOAD_PATH_PATTERN, looksLikePayloadPath, looksLikeCustomFieldId, isConditionNode, legOf, exitOf, uniq, ruleBlockOf;
4596
+ var init_automation_graph = __esm({
4597
+ "src/tools/automation-graph.ts"() {
4598
+ "use strict";
4599
+ LEG_BRANCHES = ["true", "false"];
4600
+ MAX_BRANCH_DEPTH = 3;
4601
+ MAX_STEPS = 20;
4602
+ CONDITION_STEP_TYPE = "condition";
4603
+ FILTER_STEP_TYPE = "filter";
4604
+ ACTION_IO = {
4605
+ "speak-upload": { in: ["data"], out: "media" },
4606
+ "magic-prompt": { in: ["media", "insight"], out: "insight" },
4607
+ translation: { in: ["media"], out: "media" },
4608
+ filter: { in: ["file", "media", "insight"], out: "media", passthrough: true },
4609
+ condition: { in: ["media", "insight", "data"], out: "media", passthrough: true },
4610
+ notify: { in: ["media", "insight", "data"], out: "data" },
4611
+ "outbound-webhook": { in: ["media", "insight", "data"], out: "data" },
4612
+ // Composio actions carry per-action overrides on the server; the generic entry is the
4613
+ // safe default and unknown actions are not type-checked locally.
4614
+ "composio-action": { in: ["media", "insight"], out: "notify" }
4615
+ };
4616
+ TRIGGER_OUT = {
4617
+ media_analyzed: "media",
4618
+ field_updated: "media",
4619
+ schedule: "media",
4620
+ inbound_webhook: "data",
4621
+ ai_chat_completed: "media",
4622
+ recording_received: "media",
4623
+ clip_created: "data"
4624
+ };
4625
+ FILTER_FIELDS_BY_IOTYPE = {
4626
+ media: ["name", "duration", "sourceLanguage", "tags", "transcript", "speakers"],
4627
+ file: ["name"],
4628
+ insight: ["answer"],
4629
+ notify: [],
4630
+ data: []
4631
+ };
4632
+ FILTER_FIELD_ALIASES = {
4633
+ title: "name",
4634
+ language: "sourceLanguage",
4635
+ speakersCount: "speakers"
4636
+ };
4637
+ canonicalFilterField = (field) => FILTER_FIELD_ALIASES[field] ?? field;
4638
+ ALL_CANONICAL_FILTER_FIELDS = /* @__PURE__ */ new Set([
4639
+ ...Object.values(FILTER_FIELDS_BY_IOTYPE).flat(),
4640
+ ...Object.keys(FILTER_FIELD_ALIASES)
4641
+ ]);
4642
+ isCanonicalFilterField = (field) => ALL_CANONICAL_FILTER_FIELDS.has(canonicalFilterField(field));
4643
+ CUSTOM_FIELD_ID_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
4644
+ PAYLOAD_PATH_PATTERN = /^[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
4645
+ looksLikePayloadPath = (field) => typeof field === "string" && PAYLOAD_PATH_PATTERN.test(field);
4646
+ looksLikeCustomFieldId = (field) => typeof field === "string" && !isCanonicalFilterField(field) && CUSTOM_FIELD_ID_PATTERN.test(field);
4647
+ isConditionNode = (node) => node.step.stepType === CONDITION_STEP_TYPE;
4648
+ legOf = (node, branch) => node.legs?.[branch] ?? [];
4649
+ exitOf = (node, branch) => node.legExit?.[branch] ?? "rejoin";
4650
+ uniq = (ids) => ids.filter((id, i) => ids.indexOf(id) === i);
4651
+ ruleBlockOf = (step) => {
4652
+ const block = step.stepType === CONDITION_STEP_TYPE ? step.condition : step.filter;
4653
+ return block && typeof block === "object" ? block : void 0;
4654
+ };
4655
+ }
4656
+ });
4657
+
3915
4658
  // src/tools/automations.ts
3916
4659
  var automations_exports = {};
3917
4660
  __export(automations_exports, {
@@ -3933,6 +4676,56 @@ async function refuseUngatedAnalysis(api, steps) {
3933
4676
  isError: true
3934
4677
  };
3935
4678
  }
4679
+ function refuseInvalidGraph(steps, trigger, runType) {
4680
+ if (!Array.isArray(steps)) return null;
4681
+ const triggerSlug = trigger?.triggerSlug;
4682
+ const { errors } = validateGraph(steps, {
4683
+ triggerSlug: typeof triggerSlug === "string" ? triggerSlug : void 0,
4684
+ runType: typeof runType === "string" ? runType : void 0
4685
+ });
4686
+ if (!errors.length) return null;
4687
+ return {
4688
+ content: [
4689
+ {
4690
+ type: "text",
4691
+ text: `Error: this automation cannot be saved as described.
4692
+
4693
+ ` + errors.map((e) => `- ${e}`).join("\n")
4694
+ }
4695
+ ],
4696
+ isError: true
4697
+ };
4698
+ }
4699
+ function graphWarnings(steps, trigger, runType) {
4700
+ if (!Array.isArray(steps)) return [];
4701
+ const triggerSlug = trigger?.triggerSlug;
4702
+ return validateGraph(steps, {
4703
+ triggerSlug: typeof triggerSlug === "string" ? triggerSlug : void 0,
4704
+ runType: typeof runType === "string" ? runType : void 0
4705
+ }).warnings;
4706
+ }
4707
+ function summariseBranching(data) {
4708
+ const run = data;
4709
+ const steps = Array.isArray(run?.steps) ? run.steps : [];
4710
+ if (!steps.length) return void 0;
4711
+ const conditions = steps.filter((step) => step.stepType === "condition").map((step) => ({
4712
+ stepId: step.stepId,
4713
+ took: step.outputs?.branch ?? "not reached"
4714
+ }));
4715
+ if (!conditions.length && !steps.some((step) => step.branchSkipped)) return void 0;
4716
+ const notTaken = steps.filter((step) => step.branchSkipped).map((step) => step.stepId);
4717
+ const ran = steps.filter((step) => !step.branchSkipped && step.status === "completed").map((step) => step.stepId);
4718
+ const summary = {
4719
+ conditions,
4720
+ stepsThatRan: ran,
4721
+ stepsSkippedBecauseTheirBranchWasNotTaken: notTaken
4722
+ };
4723
+ if (run.stoppedAt?.stepId) summary.stoppedAt = run.stoppedAt;
4724
+ if (run.status === "killed" && ran.length) {
4725
+ summary.note = `The run is marked "killed" because a filter stopped one path, but ${ran.length} step(s) ran to completion first \u2014 a stopped leg ends the whole run's status, not its work.`;
4726
+ }
4727
+ return summary;
4728
+ }
3936
4729
  async function withInboundWebhookInfo(api, responseData, automationId) {
3937
4730
  try {
3938
4731
  if (!automationId) return responseData;
@@ -4080,6 +4873,8 @@ function register10(server, client) {
4080
4873
  },
4081
4874
  async (body) => {
4082
4875
  try {
4876
+ const graphRefusal = refuseInvalidGraph(body.steps, body.trigger, body.runType);
4877
+ if (graphRefusal) return graphRefusal;
4083
4878
  const refusal = await refuseUngatedAnalysis(api, body.steps);
4084
4879
  if (refusal) return refusal;
4085
4880
  const result = await api.post("/v1/automations/", body);
@@ -4088,6 +4883,10 @@ function register10(server, client) {
4088
4883
  const automationId = unwrapData(result.data)?.automationId;
4089
4884
  data = await withInboundWebhookInfo(api, data, automationId);
4090
4885
  }
4886
+ const warnings = graphWarnings(body.steps, body.trigger, body.runType);
4887
+ if (warnings.length && data && typeof data === "object") {
4888
+ data = { ...data, warnings };
4889
+ }
4091
4890
  return {
4092
4891
  content: [{ type: "text", text: JSON.stringify(data, null, 2) }]
4093
4892
  };
@@ -4116,6 +4915,8 @@ function register10(server, client) {
4116
4915
  },
4117
4916
  async ({ automationId, ...body }) => {
4118
4917
  try {
4918
+ const graphRefusal = refuseInvalidGraph(body.steps, body.trigger, body.runType);
4919
+ if (graphRefusal) return graphRefusal;
4119
4920
  const refusal = await refuseUngatedAnalysis(api, body.steps);
4120
4921
  if (refusal) return refusal;
4121
4922
  const result = await api.put(`/v1/automations/${automationId}`, body);
@@ -4123,6 +4924,10 @@ function register10(server, client) {
4123
4924
  if (isInboundWebhookTrigger(body.trigger)) {
4124
4925
  data = await withInboundWebhookInfo(api, data, automationId);
4125
4926
  }
4927
+ const warnings = graphWarnings(body.steps, body.trigger, body.runType);
4928
+ if (warnings.length && data && typeof data === "object") {
4929
+ data = { ...data, warnings };
4930
+ }
4126
4931
  return {
4127
4932
  content: [{ type: "text", text: JSON.stringify(data, null, 2) }]
4128
4933
  };
@@ -4279,21 +5084,27 @@ function register10(server, client) {
4279
5084
  );
4280
5085
  registerSpeakTool(
4281
5086
  server,
4282
- "list_automation_apps",
4283
- "List the apps available in the automation catalog (e.g. Speak native + connected integrations). Use to discover what triggers/actions exist before building an automation.",
4284
- {},
5087
+ "get_automation_run",
5088
+ `Get one automation run in full: every step, in dependency order, with what it produced and why it stopped. Use this after test_automation or to explain a run that went the wrong way. On a branched automation the run's overall status is not the whole story \u2014 a filter that stops one leg marks the entire run "killed" even when the other leg finished its work \u2014 so read the per-step summary this returns, not just the status.`,
4285
5089
  {
4286
- title: "List Automation Apps",
5090
+ automationId: import_zod11.z.string().min(1).describe("Unique identifier of the automation"),
5091
+ runId: import_zod11.z.string().min(1).describe("Run id, from get_automation_runs or test_automation")
5092
+ },
5093
+ {
5094
+ title: "Get Automation Run",
4287
5095
  readOnlyHint: true,
4288
5096
  destructiveHint: false,
4289
5097
  idempotentHint: true,
4290
5098
  openWorldHint: false
4291
5099
  },
4292
- async () => {
5100
+ async ({ automationId, runId }) => {
4293
5101
  try {
4294
- const result = await api.get("/v1/automations/catalog/apps");
5102
+ const result = await api.get(`/v1/automations/${automationId}/runs/${runId}`);
5103
+ const data = unwrapData(result.data) ?? result.data;
4295
5104
  return {
4296
- content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }]
5105
+ content: [
5106
+ { type: "text", text: JSON.stringify({ ...data, branchSummary: summariseBranching(data) }, null, 2) }
5107
+ ]
4297
5108
  };
4298
5109
  } catch (err) {
4299
5110
  return {
@@ -4305,21 +5116,24 @@ function register10(server, client) {
4305
5116
  );
4306
5117
  registerSpeakTool(
4307
5118
  server,
4308
- "list_automation_triggers",
4309
- "List the trigger types available in the automation catalog. Optionally filter by app.",
5119
+ "get_automation_run_stats",
5120
+ "Aggregate run counts for an automation over a period \u2014 how many completed, failed, or were stopped.",
4310
5121
  {
4311
- app: import_zod11.z.string().min(1).max(100).optional().describe("Filter triggers to a specific app slug")
5122
+ automationId: import_zod11.z.string().min(1).describe("Unique identifier of the automation"),
5123
+ days: import_zod11.z.number().int().min(1).max(90).optional().describe(
5124
+ "How many days back to count, 1-90. The run ledger is kept for 90 days, so that is the whole window."
5125
+ )
4312
5126
  },
4313
5127
  {
4314
- title: "List Automation Triggers",
5128
+ title: "Get Automation Run Stats",
4315
5129
  readOnlyHint: true,
4316
5130
  destructiveHint: false,
4317
5131
  idempotentHint: true,
4318
5132
  openWorldHint: false
4319
5133
  },
4320
- async (params) => {
5134
+ async ({ automationId, ...params }) => {
4321
5135
  try {
4322
- const result = await api.get("/v1/automations/catalog/triggers", { params });
5136
+ const result = await api.get(`/v1/automations/${automationId}/runs/stats`, { params });
4323
5137
  return {
4324
5138
  content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }]
4325
5139
  };
@@ -4333,21 +5147,24 @@ function register10(server, client) {
4333
5147
  );
4334
5148
  registerSpeakTool(
4335
5149
  server,
4336
- "list_automation_actions",
4337
- "List the action/step types available in the automation catalog. Optionally filter by app.",
5150
+ "test_automation",
5151
+ "Run an automation once against one media item to see which way it branches. THIS HAS REAL SIDE EFFECTS: only Speak's own run notifications are suppressed \u2014 outbound webhooks fire, Composio actions run against the connected third party, and AI steps are billed. Ask the user before calling it on an automation that posts anywhere outside Speak. It also needs a mediaId and sends no webhook payload, so an inbound-webhook automation cannot be meaningfully tested this way \u2014 its payload tokens will resolve to empty. Returns a runId; read the result with get_automation_run.",
4338
5152
  {
4339
- app: import_zod11.z.string().min(1).max(100).optional().describe("Filter actions to a specific app slug")
5153
+ automationId: import_zod11.z.string().min(1).describe("Unique identifier of the automation to test"),
5154
+ mediaId: import_zod11.z.string().min(1).describe("Media item to run the automation against")
4340
5155
  },
4341
5156
  {
4342
- title: "List Automation Actions",
4343
- readOnlyHint: true,
4344
- destructiveHint: false,
4345
- idempotentHint: true,
4346
- openWorldHint: false
5157
+ title: "Test Automation",
5158
+ readOnlyHint: false,
5159
+ destructiveHint: true,
5160
+ idempotentHint: false,
5161
+ openWorldHint: true
4347
5162
  },
4348
- async (params) => {
5163
+ async (body) => {
4349
5164
  try {
4350
- const result = await api.get("/v1/automations/catalog/actions", { params });
5165
+ const result = await api.post(`/v1/automations/${body.automationId}/test-run`, {
5166
+ mediaId: body.mediaId
5167
+ });
4351
5168
  return {
4352
5169
  content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }]
4353
5170
  };
@@ -4359,63 +5176,263 @@ function register10(server, client) {
4359
5176
  }
4360
5177
  }
4361
5178
  );
4362
- }
4363
- var import_zod11, TOKEN_SYNTAX_NOTE, STEPS_DESCRIPTION, TRIGGER_DESCRIPTION, OR_TRIGGERS_DESCRIPTION, writeSchema;
4364
- var init_automations = __esm({
4365
- "src/tools/automations.ts"() {
4366
- "use strict";
4367
- import_zod11 = require("zod");
4368
- init_helpers();
4369
- init_client();
4370
- init_inbound_webhook_utils();
4371
- init_capabilities();
4372
- TOKEN_SYNTAX_NOTE = "Token syntax (usable in fields marked 'tokens allowed'): {{trigger.payload.<path>}} reads the inbound webhook payload (dot paths and [n] array indices; paths are relative to trigger.childKey when set \u2014 discover valid paths with get_inbound_webhook after sending a test payload); {{step.<index>.<path>}} or {{step.<stepId>.<path>}} reads a previous step's output (speak-upload -> mediaId, magic-prompt -> answer, outbound-webhook -> status/response).";
4373
- STEPS_DESCRIPTION = `Ordered array of graph steps (1-20). Each step is an object: { stepId: string (unique within the array), stepType: one of "speak-upload" | "magic-prompt" | "translation" | "filter" | "condition" | "notify" | "outbound-webhook" | "composio-action", dependsOn?: string[] (stepIds this step runs after), branch?: "true"|"false" (which outcome of an upstream condition step this step belongs to) } plus ONE config key matching stepType:
4374
- - speak-upload -> speakUpload: { sourceMode: "url"|"file", sourceUrl (required when sourceMode="url"; tokens allowed \u2014 if the token resolves to an object, the first http(s) URL inside it is used), folderId (required, unless folderRouting.mode="dynamic" where it becomes the optional fallback), name? (tokens allowed, mixable with static text), language? (language code or token), fieldsMap?: { <customFieldId>: "<value>" } (writes payload values into Speak custom fields on the uploaded media; values are usually {{trigger.payload.<path>}} tokens \u2014 get field ids from list_fields), folderRouting?: { mode: "static"|"dynamic", sourceKey (payload key holding the destination folder name, required when dynamic), onNoMatch: "create"|"default" (create a folder named after the value, or fall back to folderId) } }
4375
- - magic-prompt -> magicPrompt: { prompt (required unless fieldIds given, max 20000), title?, assistantType? ("general"|"researcher"|"marketer"|"sales"|"recruiter"|"custom", default "general"), assistantTemplateId? (required if assistantType="custom"), fieldIds?: string[] (max 10 \u2014 extract answers into these custom fields), analysisInput? ("transcript" (default) | "audio" | "video") \u2014 what the model receives. "audio" lets it hear tone and delivery, "video" also lets it see what is on screen; on a video file "audio" extracts the audio track first. Premium: requires the account's audio/video analysis opt-in, and costs credits per hour of media }
4376
- - translation -> translation: { targetLanguage: region-qualified locale code, e.g. "es-ES", "fr-FR" (bare codes like "es" are rejected) }
4377
- - filter -> filter: { logic: "AND"|"OR" (default "AND"), rules: [{ field, op, value? }] (1-20) } \u2014 the run continues only when the rules match, otherwise it stops silently
4378
- - condition -> condition: same { logic, rules } shape as filter, but instead of stopping it routes: downstream steps marked branch:"true"/"false" run according to the outcome
4379
- - notify -> notify: { channel: "in_app"|"email"|"slack", target?, message (required, tokens allowed) }
4380
- - outbound-webhook -> outboundWebhook: { url (required, tokens allowed), method? ("GET"|"POST"|"PUT"|"PATCH"|"DELETE", default "POST"), headers?: { <name>: <value> }, bodyTemplate?: string | object (tokens allowed) }
4381
- - composio-action -> composio: { app, action, connectedAccountId?, argsTemplate? } (Composio is currently behind a server flag and may be unavailable)
4382
- Filter/condition rule fields depend on what flows into the step: MEDIA -> name|duration|sourceLanguage|tags|transcript|speakers or a custom field id; INSIGHT -> answer; inbound-webhook DATA -> any payload path (e.g. "contact.status"). Ops by field type \u2014 text: eq|neq|contains|ncontains|startsWith|exists; number: eq|neq|gt|lt|exists; array: contains|ncontains|exists ("exists" takes no value; gt/lt values are numbers).
4383
- ` + TOKEN_SYNTAX_NOTE;
4384
- TRIGGER_DESCRIPTION = `Trigger object (the automation's root). Always include triggerSlug. Supported shapes:
4385
- - Media analyzed in folder(s): { type: "folders", triggerSlug: "media_analyzed", folderIds: string[] (min 1) }
4386
- - Inbound webhook (receive external payloads): { type: "folders", triggerSlug: "inbound_webhook", webhookId? (from provision_inbound_webhook; omit to auto-provision a new one on create), childKey? (dot-path narrowing which part of the payload feeds the automation, e.g. "data") }. The create/update response includes inboundWebhook.inboundUrl \u2014 the public URL to POST payloads to.
4387
- - Custom field updated: { type: "folders", triggerSlug: "field_updated", values: string[] (watched custom field ids, min 1), fieldValueMatches?: [{ fieldId, values: string[] }] (fire only when the field changes TO one of these values; empty values = any change), fieldMatchLogic?: "AND"|"OR" (how multiple fieldValueMatches combine, default "OR") }
4388
- - Composio app event: { type: "composio", provider: "composio", app, triggerSlug, connectedAccountId } (requires a connected account; may be behind a server flag)
4389
- Notes: "tags"/"keywords" trigger types are rejected for graph automations. The server stores inbound-webhook triggers with type "webhook" internally \u2014 send type "folders" plus the slug as shown above.`;
4390
- OR_TRIGGERS_DESCRIPTION = 'Optional additional "Or" triggers (max 10): the automation runs when ANY of them fires, sharing the same steps. Each entry mirrors the trigger shapes above but cannot be an inbound webhook and carries no webhookId/childKey. Example: [{ type: "folders", triggerSlug: "field_updated", values: ["<fieldId>"] }]';
4391
- writeSchema = {
4392
- name: import_zod11.z.string().min(1).max(150).describe("Display name for the automation"),
4393
- trigger: import_zod11.z.record(import_zod11.z.unknown()).describe(TRIGGER_DESCRIPTION),
4394
- triggers: import_zod11.z.array(import_zod11.z.record(import_zod11.z.unknown())).max(10).optional().describe(OR_TRIGGERS_DESCRIPTION),
4395
- steps: import_zod11.z.array(import_zod11.z.record(import_zod11.z.unknown())).min(1).max(20).describe(STEPS_DESCRIPTION),
4396
- description: import_zod11.z.string().max(1e3).optional().describe("Optional description"),
4397
- isActive: import_zod11.z.boolean().optional().describe("Whether the automation is active (defaults to true)"),
4398
- runType: import_zod11.z.enum(["instant", "schedule"]).optional().describe('Run type: "instant" (default, runs on trigger) or "schedule" (cron)'),
4399
- schedule: import_zod11.z.record(import_zod11.z.unknown()).optional().describe(
4400
- 'Required when runType="schedule": { timePeriod: "today"|"yesterday"|"last7days"|"last14days"|"thisWeek", repeatAt: string }'
4401
- )
4402
- };
4403
- }
4404
- });
4405
-
4406
- // src/tools/webhooks.ts
4407
- var webhooks_exports = {};
4408
- __export(webhooks_exports, {
4409
- register: () => register11
4410
- });
4411
- function register11(server, client) {
4412
- const api = client ?? speakClient;
4413
5179
  registerSpeakTool(
4414
5180
  server,
4415
- "create_webhook",
4416
- "Create a new webhook to receive real-time notifications when events occur in Speak AI.",
5181
+ "validate_automation_graph",
5182
+ "Check a step graph without saving anything. Reports the same problems create_automation and update_automation would refuse \u2014 branch wiring, rules a condition cannot actually read, shapes the Speak web editor could not reopen \u2014 plus non-blocking warnings. Use it to iterate on a branched automation instead of discovering the problems one failed save at a time.",
4417
5183
  {
4418
- callbackUrl: import_zod12.z.string().url().describe("HTTPS endpoint URL to receive webhook payloads"),
5184
+ steps: import_zod11.z.array(import_zod11.z.record(import_zod11.z.unknown())).min(1).describe(STEPS_DESCRIPTION),
5185
+ trigger: import_zod11.z.record(import_zod11.z.unknown()).optional().describe(TRIGGER_DESCRIPTION),
5186
+ runType: import_zod11.z.enum(["instant", "schedule"]).optional().describe("Run type the graph would be saved with. A schedule refuses any branch.")
5187
+ },
5188
+ {
5189
+ title: "Validate Automation Graph",
5190
+ readOnlyHint: true,
5191
+ destructiveHint: false,
5192
+ idempotentHint: true,
5193
+ openWorldHint: false
5194
+ },
5195
+ async ({ steps, trigger, runType }) => {
5196
+ const triggerSlug = trigger?.triggerSlug;
5197
+ const { errors, warnings } = validateGraph(steps, {
5198
+ triggerSlug: typeof triggerSlug === "string" ? triggerSlug : void 0,
5199
+ runType
5200
+ });
5201
+ return {
5202
+ content: [
5203
+ {
5204
+ type: "text",
5205
+ text: JSON.stringify(
5206
+ {
5207
+ valid: errors.length === 0,
5208
+ errors,
5209
+ warnings,
5210
+ shape: describeGraph(steps)
5211
+ },
5212
+ null,
5213
+ 2
5214
+ )
5215
+ }
5216
+ ]
5217
+ };
5218
+ }
5219
+ );
5220
+ registerSpeakTool(
5221
+ server,
5222
+ "describe_automation_graph",
5223
+ "Show a saved automation's steps as an indented branch tree instead of a flat list. Worth calling before update_automation, which replaces the whole automation: editing one leg means re-sending every step with its dependsOn intact, and this shows what the shape currently is.",
5224
+ {
5225
+ automationId: import_zod11.z.string().min(1).describe("Unique identifier of the automation")
5226
+ },
5227
+ {
5228
+ title: "Describe Automation Graph",
5229
+ readOnlyHint: true,
5230
+ destructiveHint: false,
5231
+ idempotentHint: true,
5232
+ openWorldHint: false
5233
+ },
5234
+ async ({ automationId }) => {
5235
+ try {
5236
+ const result = await api.get(`/v1/automations/${automationId}`);
5237
+ const data = unwrapData(result.data) ?? result.data;
5238
+ const steps = data?.steps;
5239
+ if (!Array.isArray(steps) || !steps.length) {
5240
+ return {
5241
+ content: [
5242
+ {
5243
+ type: "text",
5244
+ text: JSON.stringify(
5245
+ { automationId, shape: null, note: "This automation has no graph steps (it may be a legacy single-action rule)." },
5246
+ null,
5247
+ 2
5248
+ )
5249
+ }
5250
+ ]
5251
+ };
5252
+ }
5253
+ const triggerSlug = data?.trigger?.triggerSlug;
5254
+ const { errors, warnings } = validateGraph(steps, {
5255
+ triggerSlug: typeof triggerSlug === "string" ? triggerSlug : void 0,
5256
+ runType: data?.runType
5257
+ });
5258
+ return {
5259
+ content: [
5260
+ {
5261
+ type: "text",
5262
+ text: JSON.stringify(
5263
+ {
5264
+ automationId,
5265
+ name: data?.name,
5266
+ runType: data?.runType,
5267
+ shape: describeGraph(steps),
5268
+ steps,
5269
+ // A stored automation can predate a rule, or have been written through the
5270
+ // raw API. Saying so here is cheaper than a failed round-trip on re-save.
5271
+ problemsIfResaved: errors,
5272
+ warnings
5273
+ },
5274
+ null,
5275
+ 2
5276
+ )
5277
+ }
5278
+ ]
5279
+ };
5280
+ } catch (err) {
5281
+ return {
5282
+ content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }],
5283
+ isError: true
5284
+ };
5285
+ }
5286
+ }
5287
+ );
5288
+ registerSpeakTool(
5289
+ server,
5290
+ "list_automation_apps",
5291
+ "List the apps available in the automation catalog (e.g. Speak native + connected integrations). Use to discover what triggers/actions exist before building an automation.",
5292
+ {},
5293
+ {
5294
+ title: "List Automation Apps",
5295
+ readOnlyHint: true,
5296
+ destructiveHint: false,
5297
+ idempotentHint: true,
5298
+ openWorldHint: false
5299
+ },
5300
+ async () => {
5301
+ try {
5302
+ const result = await api.get("/v1/automations/catalog/apps");
5303
+ return {
5304
+ content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }]
5305
+ };
5306
+ } catch (err) {
5307
+ return {
5308
+ content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }],
5309
+ isError: true
5310
+ };
5311
+ }
5312
+ }
5313
+ );
5314
+ registerSpeakTool(
5315
+ server,
5316
+ "list_automation_triggers",
5317
+ "List the trigger types available in the automation catalog. Optionally filter by app.",
5318
+ {
5319
+ app: import_zod11.z.string().min(1).max(100).optional().describe("Filter triggers to a specific app slug")
5320
+ },
5321
+ {
5322
+ title: "List Automation Triggers",
5323
+ readOnlyHint: true,
5324
+ destructiveHint: false,
5325
+ idempotentHint: true,
5326
+ openWorldHint: false
5327
+ },
5328
+ async (params) => {
5329
+ try {
5330
+ const result = await api.get("/v1/automations/catalog/triggers", { params });
5331
+ return {
5332
+ content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }]
5333
+ };
5334
+ } catch (err) {
5335
+ return {
5336
+ content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }],
5337
+ isError: true
5338
+ };
5339
+ }
5340
+ }
5341
+ );
5342
+ registerSpeakTool(
5343
+ server,
5344
+ "list_automation_actions",
5345
+ "List the action/step types available in the automation catalog. Optionally filter by app.",
5346
+ {
5347
+ app: import_zod11.z.string().min(1).max(100).optional().describe("Filter actions to a specific app slug")
5348
+ },
5349
+ {
5350
+ title: "List Automation Actions",
5351
+ readOnlyHint: true,
5352
+ destructiveHint: false,
5353
+ idempotentHint: true,
5354
+ openWorldHint: false
5355
+ },
5356
+ async (params) => {
5357
+ try {
5358
+ const result = await api.get("/v1/automations/catalog/actions", { params });
5359
+ return {
5360
+ content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }]
5361
+ };
5362
+ } catch (err) {
5363
+ return {
5364
+ content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }],
5365
+ isError: true
5366
+ };
5367
+ }
5368
+ }
5369
+ );
5370
+ }
5371
+ var import_zod11, TOKEN_SYNTAX_NOTE, STEPS_DESCRIPTION, TRIGGER_DESCRIPTION, OR_TRIGGERS_DESCRIPTION, writeSchema;
5372
+ var init_automations = __esm({
5373
+ "src/tools/automations.ts"() {
5374
+ "use strict";
5375
+ import_zod11 = require("zod");
5376
+ init_helpers();
5377
+ init_client();
5378
+ init_inbound_webhook_utils();
5379
+ init_capabilities();
5380
+ init_automation_graph();
5381
+ TOKEN_SYNTAX_NOTE = "Token syntax (usable in fields marked 'tokens allowed'): {{trigger.payload.<path>}} reads the inbound webhook payload (dot paths and [n] array indices; paths are relative to trigger.childKey when set \u2014 discover valid paths with get_inbound_webhook after sending a test payload); {{step.<stepId>.<path>}} reads a previous step's output (speak-upload -> mediaId, magic-prompt -> answer, outbound-webhook -> status/response). A positional {{step.<index>.<path>}} form also exists but is REFUSED on a branched automation: the index counts stored order ([condition, true leg, false leg, merge]), not run order, and a step on the branch that was not taken produces nothing \u2014 the token would resolve to an empty string inside whatever the step sends.";
5382
+ STEPS_DESCRIPTION = `Ordered array of graph steps (1-20). Each step is an object: { stepId: string (unique within the array), stepType: one of "speak-upload" | "magic-prompt" | "translation" | "filter" | "condition" | "notify" | "outbound-webhook" | "composio-action", dependsOn?: string[] (stepIds this step runs after), branch?: "true"|"false" (which outcome of an upstream condition step this step belongs to) } plus ONE config key matching stepType:
5383
+ - speak-upload -> speakUpload: { sourceMode: "url"|"file", sourceUrl (required when sourceMode="url"; tokens allowed \u2014 if the token resolves to an object, the first http(s) URL inside it is used), folderId (required, unless folderRouting.mode="dynamic" where it becomes the optional fallback), name? (tokens allowed, mixable with static text), language? (language code or token), fieldsMap?: { <customFieldId>: "<value>" } (writes payload values into Speak custom fields on the uploaded media; values are usually {{trigger.payload.<path>}} tokens \u2014 get field ids from list_fields), folderRouting?: { mode: "static"|"dynamic", sourceKey (payload key holding the destination folder name, required when dynamic), onNoMatch: "create"|"default" (create a folder named after the value, or fall back to folderId) } }
5384
+ - magic-prompt -> magicPrompt: { prompt (required unless fieldIds given, max 20000), title?, assistantType? ("general"|"researcher"|"marketer"|"sales"|"recruiter"|"custom", default "general"), assistantTemplateId? (required if assistantType="custom"), fieldIds?: string[] (max 10 \u2014 extract answers into these custom fields), analysisInput? ("transcript" (default) | "audio" | "video") \u2014 what the model receives. "audio" lets it hear tone and delivery, "video" also lets it see what is on screen; on a video file "audio" extracts the audio track first. Premium: requires the account's audio/video analysis opt-in, and costs credits per hour of media }
5385
+ - translation -> translation: { targetLanguage: region-qualified locale code, e.g. "es-ES", "fr-FR" (bare codes like "es" are rejected) }
5386
+ - filter -> filter: { logic: "AND"|"OR" (default "AND"), rules: [{ field, op, value? }] (1-20) } \u2014 the run continues only when the rules match, otherwise it stops silently
5387
+ - condition -> condition: same { logic, rules } shape as filter, but instead of stopping it routes: downstream steps marked branch:"true"/"false" run according to the outcome.
5388
+ Branch wiring rules, all enforced before the request is sent:
5389
+ * A leg is a CHAIN: the first step of a leg depends on the condition, the rest depend on the step before them in the same leg, and every step on the leg carries the same branch marker.
5390
+ * A step that runs after the branch (a merge) depends on the LAST step of every leg that carries on. When a leg is empty its last step IS the condition, and the merge then carries that leg's marker.
5391
+ * A leg ends the run simply by having nothing depend on its last step.
5392
+ * Once anything carries a branch marker, EVERY other step needs a dependsOn \u2014 a step with no parents is an entry point and runs on both branches, and a second entry point is rejected.
5393
+ * A condition with no steps on either side is rejected: both paths would do the same thing.
5394
+ * Branches nest at most three deep, and a nested condition must be the last step of the leg it sits on, or the automation cannot be reopened in the Speak web editor.
5395
+ * A scheduled automation cannot branch: a schedule runs over a batch and a condition resolves once for the whole batch, so the leg would run against media that did not match. Use a filter, which narrows the batch.
5396
+ - notify -> notify: { channel: "in_app"|"email"|"slack", target?, message (required, tokens allowed) }
5397
+ - outbound-webhook -> outboundWebhook: { url (required, tokens allowed), method? ("GET"|"POST"|"PUT"|"PATCH"|"DELETE", default "POST"), headers?: { <name>: <value> }, bodyTemplate?: string | object (tokens allowed) }
5398
+ - composio-action -> composio: { app, action, connectedAccountId?, argsTemplate? } (Composio is currently behind a server flag and may be unavailable)
5399
+ Filter/condition rule fields depend on what flows into the step: MEDIA -> name|duration|sourceLanguage|tags|transcript|speakers or a custom field id; INSIGHT (straight after a magic-prompt step) -> answer only, so put a branch on a media field BEFORE the AI step. Neither a filter nor a condition can read the inbound webhook payload \u2014 they see the media and earlier step answers only \u2014 so a payload path such as "contact.status" is refused: upload first with speakUpload.fieldsMap to write that value into a custom field, then test the field id instead. Ops by field type \u2014 text: eq|neq|contains|ncontains|startsWith|exists; number: eq|neq|gt|lt|exists; array: contains|ncontains|exists ("exists" takes no value; gt/lt values are numbers).
5400
+ ` + TOKEN_SYNTAX_NOTE;
5401
+ TRIGGER_DESCRIPTION = `Trigger object (the automation's root). Always include triggerSlug. Supported shapes:
5402
+ - Media analyzed in folder(s): { type: "folders", triggerSlug: "media_analyzed", folderIds: string[] (min 1) }
5403
+ - Inbound webhook (receive external payloads): { type: "folders", triggerSlug: "inbound_webhook", webhookId? (from provision_inbound_webhook; omit to auto-provision a new one on create), childKey? (dot-path narrowing which part of the payload feeds the automation, e.g. "data") }. The create/update response includes inboundWebhook.inboundUrl \u2014 the public URL to POST payloads to.
5404
+ - Custom field updated: { type: "folders", triggerSlug: "field_updated", values: string[] (watched custom field ids, min 1), fieldValueMatches?: [{ fieldId, values: string[] }] (fire only when the field changes TO one of these values; empty values = any change), fieldMatchLogic?: "AND"|"OR" (how multiple fieldValueMatches combine, default "OR") }
5405
+ - Composio app event: { type: "composio", provider: "composio", app, triggerSlug, connectedAccountId } (requires a connected account; may be behind a server flag)
5406
+ Notes: "tags"/"keywords" trigger types are rejected for graph automations. The server stores inbound-webhook triggers with type "webhook" internally \u2014 send type "folders" plus the slug as shown above.`;
5407
+ OR_TRIGGERS_DESCRIPTION = 'Optional additional "Or" triggers (max 10): the automation runs when ANY of them fires, sharing the same steps. Each entry mirrors the trigger shapes above but cannot be an inbound webhook and carries no webhookId/childKey. Example: [{ type: "folders", triggerSlug: "field_updated", values: ["<fieldId>"] }]';
5408
+ writeSchema = {
5409
+ name: import_zod11.z.string().min(1).max(150).describe("Display name for the automation"),
5410
+ trigger: import_zod11.z.record(import_zod11.z.unknown()).describe(TRIGGER_DESCRIPTION),
5411
+ triggers: import_zod11.z.array(import_zod11.z.record(import_zod11.z.unknown())).max(10).optional().describe(OR_TRIGGERS_DESCRIPTION),
5412
+ steps: import_zod11.z.array(import_zod11.z.record(import_zod11.z.unknown())).min(1).max(20).describe(STEPS_DESCRIPTION),
5413
+ description: import_zod11.z.string().max(1e3).optional().describe("Optional description"),
5414
+ isActive: import_zod11.z.boolean().optional().describe("Whether the automation is active (defaults to true)"),
5415
+ runType: import_zod11.z.enum(["instant", "schedule"]).optional().describe('Run type: "instant" (default, runs on trigger) or "schedule" (cron)'),
5416
+ schedule: import_zod11.z.record(import_zod11.z.unknown()).optional().describe(
5417
+ 'Required when runType="schedule": { timePeriod: "today"|"yesterday"|"last7days"|"last14days"|"thisWeek", repeatAt: string }'
5418
+ )
5419
+ };
5420
+ }
5421
+ });
5422
+
5423
+ // src/tools/webhooks.ts
5424
+ var webhooks_exports = {};
5425
+ __export(webhooks_exports, {
5426
+ register: () => register11
5427
+ });
5428
+ function register11(server, client) {
5429
+ const api = client ?? speakClient;
5430
+ registerSpeakTool(
5431
+ server,
5432
+ "create_webhook",
5433
+ "Create a new webhook to receive real-time notifications when events occur in Speak AI.",
5434
+ {
5435
+ callbackUrl: import_zod12.z.string().url().describe("HTTPS endpoint URL to receive webhook payloads"),
4419
5436
  events: import_zod12.z.array(import_zod12.z.string()).optional().describe("Array of event types to subscribe to"),
4420
5437
  description: import_zod12.z.string().optional().describe("Optional description for the webhook")
4421
5438
  },
@@ -4992,13 +6009,13 @@ function register14(server, client) {
4992
6009
  throw new Error(`Unknown trigger \`on\`: "${on}". Use media_analyzed, inbound_webhook, or field_updated.`);
4993
6010
  };
4994
6011
  const isWebhookAutomation = trigger.on === "inbound_webhook";
4995
- const buildRules = async (rules, flowing2, isFilterStep) => {
6012
+ const buildRules = async (rules, flowing, isFilterStep) => {
4996
6013
  const out = [];
4997
6014
  for (const r of rules) {
4998
6015
  let field = String(r.field ?? "");
4999
- if (flowing2 === "media" && !CANONICAL_FILTER_FIELDS.has(field) && !field.includes(".")) {
6016
+ if (flowing === "media" && !CANONICAL_FILTER_FIELDS.has(field) && !field.includes(".")) {
5000
6017
  field = resolveField(field, await getFields());
5001
- } else if (isFilterStep && flowing2 === "data" && !CANONICAL_FILTER_FIELDS.has(field)) {
6018
+ } else if (isFilterStep && flowing === "data" && !CANONICAL_FILTER_FIELDS.has(field)) {
5002
6019
  dataFlowFilterFields.push(field);
5003
6020
  }
5004
6021
  const op = String(r.op ?? "eq");
@@ -5010,29 +6027,43 @@ function register14(server, client) {
5010
6027
  }
5011
6028
  return out;
5012
6029
  };
5013
- const wireSteps = [];
5014
- let lastBranchStepId = null;
5015
- let flowing = isWebhookAutomation ? "data" : "media";
5016
- for (let i = 0; i < steps.length; i++) {
5017
- const spec = steps[i];
5018
- const stepId = `s${i + 1}`;
6030
+ let idSeq = 0;
6031
+ const nextStepId = () => `s${++idSeq}`;
6032
+ const foldLegacyRunWhen = (specs) => {
6033
+ const out = [];
6034
+ for (let i = 0; i < specs.length; i++) {
6035
+ const spec = { ...specs[i] };
6036
+ out.push(spec);
6037
+ if (String(spec.do ?? "") !== "branch") continue;
6038
+ if (spec.then !== void 0 || spec.otherwise !== void 0) continue;
6039
+ const thenLeg = [];
6040
+ const elseLeg = [];
6041
+ let j = i + 1;
6042
+ for (; j < specs.length; j++) {
6043
+ const runWhen = specs[j].runWhen;
6044
+ if (runWhen !== "true" && runWhen !== "false") break;
6045
+ const { runWhen: _drop, ...rest } = specs[j];
6046
+ (runWhen === "true" ? thenLeg : elseLeg).push(rest);
6047
+ }
6048
+ if (thenLeg.length || elseLeg.length) {
6049
+ spec.then = thenLeg;
6050
+ spec.otherwise = elseLeg;
6051
+ i = j - 1;
6052
+ }
6053
+ }
6054
+ return out;
6055
+ };
6056
+ const buildStepBody = async (stepId, spec, where) => {
5019
6057
  const doType = String(spec.do ?? "");
5020
6058
  const step = { stepId };
5021
- if (spec.runWhen === "true" || spec.runWhen === "false") {
5022
- if (!lastBranchStepId) throw new Error(`Step ${i + 1}: runWhen requires an earlier branch step`);
5023
- step.branch = spec.runWhen;
5024
- step.dependsOn = [lastBranchStepId];
5025
- }
5026
6059
  if (doType === "filter" || doType === "branch") {
5027
6060
  step.stepType = doType === "filter" ? "filter" : "condition";
5028
- const block = {
6061
+ step[doType === "filter" ? "filter" : "condition"] = {
5029
6062
  logic: spec.logic === "OR" ? "OR" : "AND",
5030
- rules: await buildRules(spec.rules ?? [], flowing, doType === "filter")
6063
+ rules: (spec.rules ?? []).map((rule) => ({ ...rule }))
5031
6064
  };
5032
- step[doType === "filter" ? "filter" : "condition"] = block;
5033
- if (doType === "branch") lastBranchStepId = stepId;
5034
6065
  } else if (doType === "upload") {
5035
- if (!spec.source) throw new Error(`Step ${i + 1} (upload): \`source\` is required (URL or payload.<path>)`);
6066
+ if (!spec.source) throw new Error(`${where} (upload): \`source\` is required (URL or payload.<path>)`);
5036
6067
  const upload = {
5037
6068
  sourceMode: "url",
5038
6069
  sourceUrl: tokenize(spec.source),
@@ -5053,7 +6084,7 @@ function register14(server, client) {
5053
6084
  };
5054
6085
  if (spec.folder) upload.folderId = await resolveFolder(api, String(spec.folder), await getFolders(), createdFolders);
5055
6086
  } else {
5056
- if (!spec.folder) throw new Error(`Step ${i + 1} (upload): provide \`folder\` (name or id) or \`folderFromPayload\``);
6087
+ if (!spec.folder) throw new Error(`${where} (upload): provide \`folder\` (name or id) or \`folderFromPayload\``);
5057
6088
  upload.folderId = await resolveFolder(api, String(spec.folder), await getFolders(), createdFolders);
5058
6089
  }
5059
6090
  if (spec.mapFields && typeof spec.mapFields === "object") {
@@ -5061,7 +6092,7 @@ function register14(server, client) {
5061
6092
  const fieldsMap = {};
5062
6093
  for (const [ref, value] of Object.entries(spec.mapFields)) {
5063
6094
  if (value !== null && typeof value === "object") {
5064
- throw new Error(`Step ${i + 1} (upload): mapFields["${ref}"] must be a string or number, not an object`);
6095
+ throw new Error(`${where} (upload): mapFields["${ref}"] must be a string or number, not an object`);
5065
6096
  }
5066
6097
  fieldsMap[resolveField(ref, fieldList)] = tokenize(String(value));
5067
6098
  }
@@ -5069,11 +6100,10 @@ function register14(server, client) {
5069
6100
  }
5070
6101
  step.stepType = "speak-upload";
5071
6102
  step.speakUpload = upload;
5072
- flowing = "media";
5073
6103
  } else if (doType === "ai_chat") {
5074
6104
  const hasSaveToFields = Array.isArray(spec.saveToFields) && spec.saveToFields.length > 0;
5075
6105
  if (!spec.prompt && !hasSaveToFields) {
5076
- throw new Error(`Step ${i + 1} (ai_chat): provide \`prompt\`, \`saveToFields\`, or both`);
6106
+ throw new Error(`${where} (ai_chat): provide \`prompt\`, \`saveToFields\`, or both`);
5077
6107
  }
5078
6108
  const magicPrompt = { prompt: spec.prompt ?? "", assistantType: "general" };
5079
6109
  if (spec.title) magicPrompt.title = spec.title;
@@ -5082,60 +6112,119 @@ function register14(server, client) {
5082
6112
  const analysis = String(spec.analyse ?? spec.analyze);
5083
6113
  if (!["transcript", "audio", "video"].includes(analysis)) {
5084
6114
  throw new Error(
5085
- `Step ${i + 1} (ai_chat): analyse must be "transcript", "audio" or "video", got "${analysis}"`
6115
+ `${where} (ai_chat): analyse must be "transcript", "audio" or "video", got "${analysis}"`
5086
6116
  );
5087
6117
  }
5088
6118
  if (analysis !== "transcript") magicPrompt.analysisInput = analysis;
5089
6119
  }
5090
6120
  if (Array.isArray(spec.saveToFields) && spec.saveToFields.length) {
5091
6121
  if (spec.saveToFields.length > 10) {
5092
- throw new Error(`Step ${i + 1} (ai_chat): saveToFields supports at most 10 fields`);
6122
+ throw new Error(`${where} (ai_chat): saveToFields supports at most 10 fields`);
5093
6123
  }
5094
6124
  const fieldList = await getFields();
5095
6125
  magicPrompt.fieldIds = spec.saveToFields.map((ref) => resolveField(String(ref), fieldList));
5096
6126
  }
5097
6127
  step.stepType = "magic-prompt";
5098
6128
  step.magicPrompt = magicPrompt;
5099
- flowing = "insight";
5100
6129
  } else if (doType === "translate") {
5101
- if (!spec.language) throw new Error(`Step ${i + 1} (translate): \`language\` is required (e.g. "es-ES")`);
6130
+ if (!spec.language) throw new Error(`${where} (translate): \`language\` is required (e.g. "es-ES")`);
5102
6131
  step.stepType = "translation";
5103
6132
  step.translation = { targetLanguage: spec.language };
5104
- flowing = "media";
5105
6133
  } else if (doType === "notify") {
5106
- if (!spec.message) throw new Error(`Step ${i + 1} (notify): \`message\` is required`);
6134
+ if (!spec.message) throw new Error(`${where} (notify): \`message\` is required`);
5107
6135
  const channel = spec.channel === void 0 ? "in_app" : String(spec.channel);
5108
6136
  if (!["in_app", "email", "slack"].includes(channel)) {
5109
- throw new Error(`Step ${i + 1} (notify): channel must be "in_app", "email", or "slack" (got "${channel}")`);
6137
+ throw new Error(`${where} (notify): channel must be "in_app", "email", or "slack" (got "${channel}")`);
5110
6138
  }
5111
6139
  const notify = { channel, message: tokenize(spec.message) };
5112
6140
  if (spec.target) notify.target = String(spec.target);
5113
6141
  step.stepType = "notify";
5114
6142
  step.notify = notify;
5115
- flowing = "data";
5116
6143
  } else if (doType === "call_webhook") {
5117
- if (!spec.url) throw new Error(`Step ${i + 1} (call_webhook): \`url\` is required`);
6144
+ if (!spec.url) throw new Error(`${where} (call_webhook): \`url\` is required`);
5118
6145
  const method = spec.method === void 0 ? "POST" : String(spec.method).toUpperCase();
5119
6146
  if (!["GET", "POST", "PUT", "PATCH", "DELETE"].includes(method)) {
5120
- throw new Error(`Step ${i + 1} (call_webhook): method must be GET, POST, PUT, PATCH, or DELETE (got "${spec.method}")`);
6147
+ throw new Error(`${where} (call_webhook): method must be GET, POST, PUT, PATCH, or DELETE (got "${spec.method}")`);
5121
6148
  }
5122
- const outbound = {
5123
- url: tokenize(spec.url),
5124
- method
5125
- };
6149
+ const outbound = { url: tokenize(spec.url), method };
5126
6150
  if (spec.headers && typeof spec.headers === "object") outbound.headers = spec.headers;
5127
6151
  if (spec.body !== void 0) {
5128
6152
  outbound.bodyTemplate = typeof spec.body === "string" ? tokenize(spec.body) : spec.body;
5129
6153
  }
5130
6154
  step.stepType = "outbound-webhook";
5131
6155
  step.outboundWebhook = outbound;
5132
- flowing = "data";
5133
6156
  } else {
5134
6157
  throw new Error(
5135
- `Step ${i + 1}: unknown \`do\`: "${doType}". Use filter, branch, upload, ai_chat, translate, notify, or call_webhook.`
6158
+ `${where}: unknown \`do\`: "${doType}". Use filter, branch, upload, ai_chat, translate, notify, or call_webhook.`
5136
6159
  );
5137
6160
  }
5138
- wireSteps.push(step);
6161
+ return step;
6162
+ };
6163
+ const buildNodes = async (specs, path4) => {
6164
+ const nodes2 = [];
6165
+ const folded = foldLegacyRunWhen(specs);
6166
+ for (const [index, spec] of folded.entries()) {
6167
+ const where = `${path4}[${index}]`;
6168
+ const stepId = nextStepId();
6169
+ const body2 = await buildStepBody(stepId, spec, where);
6170
+ if (String(spec.do ?? "") !== "branch") {
6171
+ nodes2.push({ step: body2 });
6172
+ continue;
6173
+ }
6174
+ nodes2.push({
6175
+ step: body2,
6176
+ legs: {
6177
+ true: await buildNodes(spec.then ?? [], `${where}.then`),
6178
+ false: await buildNodes(spec.otherwise ?? [], `${where}.otherwise`)
6179
+ },
6180
+ legExit: {
6181
+ true: spec.thenEnds === true ? "end" : "rejoin",
6182
+ false: spec.otherwiseEnds === true ? "end" : "rejoin"
6183
+ }
6184
+ });
6185
+ }
6186
+ return nodes2;
6187
+ };
6188
+ const nodes = await buildNodes(steps, "steps");
6189
+ const wireSteps = compileGraph(nodes);
6190
+ const triggerSlug = String(trigger.on ?? "");
6191
+ const rootType = TRIGGER_OUT[triggerSlug] ?? (isWebhookAutomation ? "data" : "media");
6192
+ const incomingByStep = incomingTypesByStep(wireSteps, rootType);
6193
+ for (const step of wireSteps) {
6194
+ const stepType = String(step.stepType);
6195
+ if (stepType !== "filter" && stepType !== "condition") continue;
6196
+ const incoming = incomingByStep.get(String(step.stepId)) ?? /* @__PURE__ */ new Set([rootType]);
6197
+ const flowing = [...incoming][0] ?? rootType;
6198
+ const key = stepType === "filter" ? "filter" : "condition";
6199
+ const block = step[key];
6200
+ block.rules = await buildRules(block.rules ?? [], flowing, stepType === "filter");
6201
+ }
6202
+ const rulesReferenceFieldIds = wireSteps.some((step) => {
6203
+ const key = step.stepType === "condition" ? "condition" : step.stepType === "filter" ? "filter" : null;
6204
+ if (!key) return false;
6205
+ const rules = step[key]?.rules ?? [];
6206
+ return rules.some((rule) => looksLikeCustomFieldId(String(rule.field ?? "")));
6207
+ });
6208
+ const knownFieldIds = rulesReferenceFieldIds ? new Set((await getFields()).map((entry) => entry.id)) : null;
6209
+ const graphCheck = validateGraph(wireSteps, {
6210
+ triggerSlug,
6211
+ // build_automation only writes instant automations; a schedule comes through
6212
+ // create_automation, which runs the same validator with its own runType.
6213
+ runType: "instant",
6214
+ knownFieldIds
6215
+ });
6216
+ if (graphCheck.errors.length) {
6217
+ return {
6218
+ content: [
6219
+ {
6220
+ type: "text",
6221
+ text: `Error: this automation cannot be saved as described.
6222
+
6223
+ ` + graphCheck.errors.map((e) => `- ${e}`).join("\n")
6224
+ }
6225
+ ],
6226
+ isError: true
6227
+ };
5139
6228
  }
5140
6229
  const body = {
5141
6230
  name,
@@ -5164,6 +6253,7 @@ function register14(server, client) {
5164
6253
  ...typeof result.data === "object" ? result.data : { data: result.data }
5165
6254
  };
5166
6255
  if (createdFolders.length) response.createdFolders = createdFolders;
6256
+ if (graphCheck.warnings.length) response.warnings = graphCheck.warnings;
5167
6257
  if (isWebhookAutomation && resolvedId) {
5168
6258
  try {
5169
6259
  const resolved = await resolveAutomationInboundWebhook(api, resolvedId);
@@ -5436,6 +6526,7 @@ var init_workflows = __esm({
5436
6526
  init_media_utils();
5437
6527
  init_capabilities();
5438
6528
  init_inbound_webhook_utils();
6529
+ init_automation_graph();
5439
6530
  MAX_BATCH_URLS = 25;
5440
6531
  MAX_BATCH_CONCURRENCY = 5;
5441
6532
  RATE_LIMIT_RETRY_DELAY_MS = 5e3;
@@ -5455,7 +6546,7 @@ var init_workflows = __esm({
5455
6546
  ]);
5456
6547
  ID_PATTERN = /^[0-9a-f]{12}$/;
5457
6548
  TRIGGER_SPEC_DESCRIPTION = 'What starts the automation. Object with:\n- on (required): "media_analyzed" | "inbound_webhook" | "field_updated"\n- folders: array of folder names or ids (required for media_analyzed; missing folders are created)\n- childKey: dot-path narrowing the webhook payload root, e.g. "data" (inbound_webhook only)\n- webhookId: reuse a webhook from provision_inbound_webhook (inbound_webhook only; omit to auto-provision)\n- watchFields: array of { field: name-or-id, values?: string[] } (required for field_updated \u2014 fires when the field changes; values restricts to specific new values)\n- matchLogic: "AND"|"OR" for combining multiple watchFields value matches (default OR)';
5458
- STEP_SPEC_DESCRIPTION = 'Ordered actions. Each step is an object with a `do` key plus its options. String values may be literals, "payload.<path>" shorthand (converted to {{trigger.payload.<path>}} only when it is the ENTIRE value), or raw {{...}} tokens \u2014 inside longer text, write the full {{trigger.payload.<path>}} form.\n- { do: "filter", rules: [{ field, op, value? }], logic?: "AND"|"OR" } \u2014 continue only if rules match. Fields: media flows use name|duration|sourceLanguage|tags|transcript|speakers or a custom field name; webhook payloads use payload paths like "contact.status". Ops: eq|neq|contains|ncontains|startsWith|gt|lt|exists\n- { do: "branch", rules, logic? } \u2014 like filter but routes instead of stopping; later steps with runWhen: "true"|"false" only run on that outcome. NOTE: branch routing requires the server\'s DAG runner (feature-flagged); when it is off, steps run in order and runWhen markers are ignored \u2014 prefer filter for guaranteed gating\n- { do: "upload", source (URL or payload.<path>, required), name?, language? (e.g. "en-US"), folder? (name or id; created if missing), folderFromPayload? (payload key holding the destination folder name \u2014 dynamic routing), onNoFolderMatch?: "create"|"default", mapFields?: { <field name or id>: <value or payload.<path>> } (writes payload values into custom fields on the uploaded media) }\n- { do: "ai_chat", prompt? (required unless saveToFields given), title?, saveToFields?: [field names or ids] (max 10 \u2014 values are extracted into these custom fields; prompt may be omitted for extraction-only steps), model? (a Speak-supported LLM id, e.g. "gemini-2.5-flash", "claude-sonnet-4-6"; omit for the workspace default), analyse?: "transcript" (default) | "audio" | "video" \u2014 what the model receives. "audio" lets it hear tone and delivery, "video" also lets it see the screen; on a video file "audio" extracts the audio track first. Premium: requires the account\'s audio/video analysis opt-in and costs credits per hour of media }\n- { do: "translate", language: region-qualified code like "es-ES", "fr-FR" }\n- { do: "notify", message (required, tokens allowed), channel?: "in_app"|"email"|"slack" (default in_app; email currently falls back to an in-app notification), target? (reserved \u2014 not yet used for delivery) }\n- { do: "call_webhook", url (required), method?, headers?, body? (string or object template, tokens allowed) }\nSteps may also set runWhen (after a branch step). Composio app actions (Google Drive, Slack apps, \u2026) are not supported by this builder yet \u2014 use create_automation directly for those.';
6549
+ STEP_SPEC_DESCRIPTION = 'Ordered actions. Each step is an object with a `do` key plus its options. String values may be literals, "payload.<path>" shorthand (converted to {{trigger.payload.<path>}} only when it is the ENTIRE value), or raw {{...}} tokens \u2014 inside longer text, write the full {{trigger.payload.<path>}} form.\n- { do: "filter", rules: [{ field, op, value? }], logic?: "AND"|"OR" } \u2014 continue only if rules match, otherwise the run stops here. Ops: eq|neq|contains|ncontains|startsWith|gt|lt|exists\n- { do: "branch", rules, logic?, then: [steps], otherwise: [steps], thenEnds?, otherwiseEnds? } \u2014 routes instead of stopping. `then` runs when the rules match, `otherwise` when they do not, and whatever follows the branch runs on both paths. Set thenEnds/otherwiseEnds to true to finish the run on that side instead of carrying on. One side may be empty ("if it matches do this, otherwise just carry on"), but not both. Branches may nest three deep, and a nested branch must be the LAST step of the side it sits on.\n Rule fields for BOTH filter and branch depend on what reaches the step: while media is flowing use name|duration|sourceLanguage|tags|transcript|speakers or a custom field name; straight after an ai_chat step only "answer" is available, so put the branch BEFORE the ai_chat step if you need a media field. A filter and a branch CANNOT read the webhook payload \u2014 they only see the media and earlier answers. To branch on payload data, upload first with mapFields to write the value into a custom field, then branch on that field.\n- { do: "upload", source (URL or payload.<path>, required), name?, language? (e.g. "en-US"), folder? (name or id; created if missing), folderFromPayload? (payload key holding the destination folder name \u2014 dynamic routing), onNoFolderMatch?: "create"|"default", mapFields?: { <field name or id>: <value or payload.<path>> } (writes payload values into custom fields on the uploaded media) }\n- { do: "ai_chat", prompt? (required unless saveToFields given), title?, saveToFields?: [field names or ids] (max 10 \u2014 values are extracted into these custom fields; prompt may be omitted for extraction-only steps), model? (a Speak-supported LLM id, e.g. "gemini-2.5-flash", "claude-sonnet-4-6"; omit for the workspace default), analyse?: "transcript" (default) | "audio" | "video" \u2014 what the model receives. "audio" lets it hear tone and delivery, "video" also lets it see the screen; on a video file "audio" extracts the audio track first. Premium: requires the account\'s audio/video analysis opt-in and costs credits per hour of media }\n- { do: "translate", language: region-qualified code like "es-ES", "fr-FR" }\n- { do: "notify", message (required, tokens allowed), channel?: "in_app"|"email"|"slack" (default in_app; email currently falls back to an in-app notification), target? (reserved \u2014 not yet used for delivery) }\n- { do: "call_webhook", url (required), method?, headers?, body? (string or object template, tokens allowed) }\nLegacy: a flat list where steps after a branch carry runWhen: "true"|"false" is still accepted and folded into then/otherwise, but it cannot express nesting or an ending side \u2014 prefer then/otherwise. Composio app actions (Google Drive, Slack apps, \u2026) are not supported by this builder yet \u2014 use create_automation directly for those.';
5459
6550
  buildAutomationSchema = {
5460
6551
  name: import_zod15.z.string().min(1).max(150).describe("Display name for the automation"),
5461
6552
  trigger: import_zod15.z.record(import_zod15.z.unknown()).describe(TRIGGER_SPEC_DESCRIPTION),
@@ -5685,6 +6776,8 @@ function defaultWidgetConfig(type) {
5685
6776
  return { metrics: ["uploads", "minutes", "lastActive"] };
5686
6777
  case "notes":
5687
6778
  return { content: "Add notes or context for this dashboard." };
6779
+ case "chat-history":
6780
+ return { limit: 25 };
5688
6781
  }
5689
6782
  }
5690
6783
  function buildDashboardWidgets(items, sections = []) {
@@ -5786,7 +6879,8 @@ var init_dashboard_widgets = __esm({
5786
6879
  "themes",
5787
6880
  "people",
5788
6881
  "team-activity",
5789
- "notes"
6882
+ "notes",
6883
+ "chat-history"
5790
6884
  ];
5791
6885
  DATE_RANGE_PRESETS = [
5792
6886
  "last7days",
@@ -5806,7 +6900,8 @@ var init_dashboard_widgets = __esm({
5806
6900
  themes: { w: 6, h: 4, titleDefault: "Themes" },
5807
6901
  people: { w: 6, h: 4, titleDefault: "People" },
5808
6902
  "team-activity": { w: 6, h: 4, titleDefault: "Team activity" },
5809
- notes: { w: GRID_COLS, h: 2, titleDefault: "Note" }
6903
+ notes: { w: GRID_COLS, h: 2, titleDefault: "Note" },
6904
+ "chat-history": { w: GRID_COLS, h: 6, titleDefault: "AI Chat History" }
5810
6905
  };
5811
6906
  KEBAB_ID = /^[a-z0-9]+(-[a-z0-9]+)*$/;
5812
6907
  AUTO_LAYOUT = { x: 0, y: 0, w: 0, h: 0 };
@@ -5865,6 +6960,11 @@ var init_dashboard_widgets = __esm({
5865
6960
  type: "notes",
5866
6961
  purpose: "Free-text note/context block (full width).",
5867
6962
  config: "content: string (1-4000 chars, required)"
6963
+ },
6964
+ {
6965
+ type: "chat-history",
6966
+ purpose: "Past AI chat conversations held on this dashboard (full width) \u2014 messages, feedback, and the thinking/tool-call trail when the viewer's embed allows it. Not a Media-aggregation widget.",
6967
+ config: "limit?: number (1-100, optional, default 25) \u2014 conversations per page."
5868
6968
  }
5869
6969
  ];
5870
6970
  SPEC_VOCABULARY = {
@@ -6016,6 +7116,7 @@ function pickMetadata(body) {
6016
7116
  if (body.assignTo !== void 0) out.assignTo = body.assignTo;
6017
7117
  if (body.filters !== void 0) out.filters = body.filters;
6018
7118
  if (body.isDefault !== void 0) out.isDefault = body.isDefault;
7119
+ if (body.settings !== void 0) out.settings = body.settings;
6019
7120
  return out;
6020
7121
  }
6021
7122
  function register16(server, client) {
@@ -6111,7 +7212,7 @@ function register16(server, client) {
6111
7212
  registerSpeakTool(
6112
7213
  server,
6113
7214
  "create_dashboard",
6114
- `Create an analytics dashboard. Only \`title\` is required \u2014 source defaults to the whole workspace and dateRange to last30days. Add widgets by listing their types (the MCP assigns ids and lays them out automatically), scope with source ({type:"folders",folderIds} | {type:"team"} | {type:"workspace"}) and dateRange ({preset}), and optionally group widgets into sections. Design guidance: lead with a narrative widget as the first widget; group sections by the QUESTION they answer, not by widget type; don't pad \u2014 every widget earns its place (aim for 4-16 widgets on a full build); if something can't be expressed by the widget catalog, put it in a narrative widget's focus instead of faking it. Call list_dashboard_widgets first for the widget catalog, config vocabulary, design rules, and full examples.`,
7215
+ `Create an analytics dashboard. Only \`title\` is required \u2014 source defaults to the whole workspace and dateRange to last30days. Add widgets by listing their types (the MCP assigns ids and lays them out automatically), scope with source ({type:"folders",folderIds} | {type:"team"} | {type:"workspace"}) and dateRange ({preset}), and optionally group widgets into sections. Design guidance: lead with a narrative widget as the first widget; group sections by the QUESTION they answer, not by widget type; don't pad \u2014 every widget earns its place (aim for 4-16 widgets on a full build); if something can't be expressed by the widget catalog, put it in a narrative widget's focus instead of faking it. Call list_dashboard_widgets first for the widget catalog, config vocabulary, design rules, and full examples. Viewer settings (the settings input): ` + SETTINGS_RULES,
6115
7216
  {
6116
7217
  title: import_zod17.z.string().min(1).max(60).describe("Dashboard name, max 60 chars (the only required field)"),
6117
7218
  ...specFields,
@@ -6152,7 +7253,7 @@ function register16(server, client) {
6152
7253
  registerSpeakTool(
6153
7254
  server,
6154
7255
  "update_dashboard",
6155
- "Update a dashboard. Two modes. (1) Metadata-only: pass just icon/assignTo/filters/isDefault \u2014 no spec fields, no revision needed. (2) Spec update: pass the FULL spec \u2014 title, source, dateRange, sections, widgets \u2014 plus `revision`. Widgets and sections are REPLACED, not merged, so call get_dashboard first and resend everything you want to keep. `revision` is the optimistic-concurrency token from get_dashboard/list_dashboards: the server accepts the write only if it still matches, then increments it. A 409 conflict means another writer saved first \u2014 re-fetch with get_dashboard, rebuild your changes on the fresh spec, and retry with the new revision.",
7256
+ "Update a dashboard. Two modes. (1) Metadata-only: pass just icon/assignTo/filters/isDefault/settings, with no spec fields and no revision. (2) Spec update: pass the FULL spec \u2014 title, source, dateRange, sections, widgets \u2014 plus `revision`. Widgets and sections are REPLACED, not merged, so call get_dashboard first and resend everything you want to keep. `revision` is the optimistic-concurrency token from get_dashboard/list_dashboards: the server accepts the write only if it still matches, then increments it. A 409 conflict means another writer saved first \u2014 re-fetch with get_dashboard, rebuild your changes on the fresh spec, and retry with the new revision. Viewer settings (the settings input): " + SETTINGS_RULES,
6156
7257
  {
6157
7258
  dashboardId: import_zod17.z.string().min(1).describe("Dashboard business id"),
6158
7259
  title: import_zod17.z.string().min(1).max(60).optional().describe("Dashboard name \u2014 required (with revision) when updating the spec"),
@@ -6317,7 +7418,7 @@ function register16(server, client) {
6317
7418
  }
6318
7419
  );
6319
7420
  }
6320
- var import_zod17, FILTER_LIST_DESCRIPTION, widgetInputSchema, sectionInputSchema, sourceInputSchema, dateRangeInputSchema, metadataFields, specFields, SPEAKERS_FILTER_SCHEMA;
7421
+ var import_zod17, FILTER_LIST_DESCRIPTION, widgetInputSchema, sectionInputSchema, sourceInputSchema, dateRangeInputSchema, settingsFieldIds, SETTINGS_RULES, dashboardSettingsSchema, metadataFields, specFields, SPEAKERS_FILTER_SCHEMA;
6321
7422
  var init_dashboards = __esm({
6322
7423
  "src/tools/dashboards.ts"() {
6323
7424
  "use strict";
@@ -6328,14 +7429,14 @@ var init_dashboards = __esm({
6328
7429
  FILTER_LIST_DESCRIPTION = "Field filters. filters.filterList is an array of { fieldName, fieldOperator?, fieldValue?: string[], fieldCondition? }. Other keys pass through but only filterList is enforced.";
6329
7430
  widgetInputSchema = import_zod17.z.object({
6330
7431
  type: import_zod17.z.enum(WIDGET_TYPES).describe(
6331
- "Widget type: narrative | stat-cards | metric-chart | table | comparison | field-distribution | sentiment-trend | themes | people | team-activity | notes"
7432
+ "Widget type: narrative | stat-cards | metric-chart | table | comparison | field-distribution | sentiment-trend | themes | people | team-activity | notes | chat-history"
6332
7433
  ),
6333
7434
  id: import_zod17.z.string().max(64).optional().describe(
6334
7435
  "Optional explicit widget id (kebab-case). Required if you reference the widget from sections[].widgetIds; auto-generated otherwise."
6335
7436
  ),
6336
7437
  title: import_zod17.z.string().min(1).max(40).optional().describe("Widget title, max 40 chars (defaults to a per-type label)"),
6337
7438
  config: import_zod17.z.record(import_zod17.z.unknown()).optional().describe(
6338
- "Per-type config (STRICT \u2014 unknown keys are rejected). metric-chart: mark (line|bar|area|donut|stacked-bar) + metric + groupBy/series + thresholds; table: rowsAre + columns [{header, field|metric}]; stat-cards: tiles; field-distribution: fieldName+measure+chartType (required); narrative: focus; notes: content. Call list_dashboard_widgets for the full per-type vocabulary + metric/filter grammar. Omit for a sensible valid default (except field-distribution, which needs fieldName)."
7439
+ "Per-type config (STRICT \u2014 unknown keys are rejected). metric-chart: mark (line|bar|area|donut|stacked-bar) + metric + groupBy/series + thresholds; table: rowsAre + columns [{header, field|metric}]; stat-cards: tiles; field-distribution: fieldName+measure+chartType (required); narrative: focus; notes: content; chat-history: limit (optional, past conversations to list, 1-100, default 25). Call list_dashboard_widgets for the full per-type vocabulary + metric/filter grammar. Omit for a sensible valid default (except field-distribution, which needs fieldName)."
6339
7440
  ),
6340
7441
  binding: import_zod17.z.record(import_zod17.z.unknown()).optional().describe(
6341
7442
  "Per-widget scope override: { source?, dateRange?: {preset}, filter? }. Omit any key to inherit the dashboard's value."
@@ -6366,11 +7467,67 @@ var init_dashboards = __esm({
6366
7467
  dateRangeInputSchema = import_zod17.z.object({
6367
7468
  preset: import_zod17.z.enum(DATE_RANGE_PRESETS).describe("One of: last7days | last30days | last3months | yearToDate | allTime")
6368
7469
  }).describe("Date range \u2014 strict preset only, no free-form start/end dates");
7470
+ settingsFieldIds = import_zod17.z.array(import_zod17.z.string());
7471
+ SETTINGS_RULES = "Do not pass settings unless the user explicitly asks to change this dashboard's viewer settings. Never pass settings for a Foxtons dashboard unless explicitly asked; Foxtons moves by a server script. Saving any settings section moves that dashboard onto the settings flow immediately: its media pages use these groups and this Feedback setup from then on. Each section (fields, feedback) replaces that whole section when sent. Call get_dashboard first and resend every key of the section you change; a key left out resets to its default. Get field ids from list_fields. Ids that are not the company's fields are dropped when saving. When feedback.isEnabled is true, pass a non-empty feedback.fieldIds (score fields) rather than leaving it empty. Only set feedback.sheetWebhookUrl when the user gives the Apps Script URL.";
7472
+ dashboardSettingsSchema = import_zod17.z.object({
7473
+ fields: import_zod17.z.object({
7474
+ includeIds: settingsFieldIds.describe(
7475
+ "Field ids a viewer sees on each media page opened from this shared dashboard, in this order. Private fields are shown when listed. Empty shows only the company's public fields."
7476
+ ),
7477
+ groups: import_zod17.z.array(
7478
+ import_zod17.z.object({
7479
+ key: import_zod17.z.string().min(1),
7480
+ label: import_zod17.z.string().min(1),
7481
+ fieldIds: settingsFieldIds.min(1)
7482
+ })
7483
+ ).describe("Pills on the media page Fields tab, each listing the field ids it shows. Empty means no pills."),
7484
+ orderIds: settingsFieldIds.optional().describe(
7485
+ "Used only when includeIds is empty: these fields show first, in this order, then every other public field. Does not change which fields are visible."
7486
+ )
7487
+ }).optional(),
7488
+ feedback: import_zod17.z.object({
7489
+ isEnabled: import_zod17.z.boolean().describe("Show the Feedback button on media pages opened from this shared dashboard"),
7490
+ fieldIds: settingsFieldIds.describe(
7491
+ "Fields a reviewer gives feedback on. Empty means every field the media page shows."
7492
+ ),
7493
+ submitters: import_zod17.z.array(import_zod17.z.string().min(1)).describe("Names a reviewer picks from. Empty lets them type their own name."),
7494
+ removeReasons: import_zod17.z.array(import_zod17.z.string().min(1)).describe("Reasons for removing a call from scoring. Empty hides that option."),
7495
+ reviewScope: import_zod17.z.enum(["dashboard", "company"]).optional().describe(
7496
+ "'dashboard' (default) lists and reviews only this dashboard's feedback; 'company' lists every dashboard's feedback in the company. Use 'company' only on a manager dashboard, never on a personal one."
7497
+ ),
7498
+ allowOtherSubmitter: import_zod17.z.boolean().optional().describe("Lets a reviewer type a name that is not in submitters."),
7499
+ groups: import_zod17.z.array(
7500
+ import_zod17.z.object({
7501
+ key: import_zod17.z.string().min(1),
7502
+ label: import_zod17.z.string().min(1),
7503
+ fieldIds: settingsFieldIds.min(1)
7504
+ })
7505
+ ).optional().describe(
7506
+ "Pills in the Feedback dialog, each listing feedback field ids in order. Leave out to reuse fields.groups."
7507
+ ),
7508
+ fieldRules: import_zod17.z.record(
7509
+ import_zod17.z.string(),
7510
+ import_zod17.z.object({
7511
+ label: import_zod17.z.string().optional(),
7512
+ min: import_zod17.z.number().optional(),
7513
+ max: import_zod17.z.number().optional()
7514
+ })
7515
+ ).optional().describe(
7516
+ "Per feedback field: a short row label and the allowed score range, used for both the reviewer's score and the approver's score."
7517
+ ),
7518
+ sheetWebhookUrl: import_zod17.z.string().optional().describe(
7519
+ "Google Apps Script web app URL that receives one row per submission. Only script.google.com addresses are posted to. Never shown to viewers."
7520
+ )
7521
+ }).optional()
7522
+ }).describe(
7523
+ "Viewer settings for media pages opened from this dashboard's share link: which fields show, how the Fields tab groups them, and the Feedback button. " + SETTINGS_RULES
7524
+ );
6369
7525
  metadataFields = {
6370
7526
  icon: import_zod17.z.string().max(200).optional().describe("Icon identifier"),
6371
7527
  assignTo: import_zod17.z.array(import_zod17.z.string()).max(100).optional().describe('User ids, or group ids in the "<groupId> (G)" convention, to share view access with'),
6372
7528
  filters: import_zod17.z.record(import_zod17.z.unknown()).optional().describe(FILTER_LIST_DESCRIPTION),
6373
- isDefault: import_zod17.z.boolean().optional().describe("Make this the company default dashboard")
7529
+ isDefault: import_zod17.z.boolean().optional().describe("Make this the company default dashboard"),
7530
+ settings: dashboardSettingsSchema.optional()
6374
7531
  };
6375
7532
  specFields = {
6376
7533
  description: import_zod17.z.string().max(280).optional().describe("Dashboard description, max 280 chars"),
@@ -6399,43 +7556,1199 @@ var init_dashboards = __esm({
6399
7556
  }
6400
7557
  });
6401
7558
 
6402
- // src/tools/index.ts
6403
- var tools_exports = {};
6404
- __export(tools_exports, {
6405
- registerAllTools: () => registerAllTools
7559
+ // src/tools/voice.ts
7560
+ var voice_exports = {};
7561
+ __export(voice_exports, {
7562
+ register: () => register17
6406
7563
  });
6407
- function registerAllTools(server, client) {
6408
- for (const mod of modules) {
6409
- mod.register(server, client);
6410
- }
6411
- }
6412
- var modules;
6413
- var init_tools = __esm({
6414
- "src/tools/index.ts"() {
6415
- "use strict";
6416
- init_media3();
6417
- init_text2();
6418
- init_exports();
6419
- init_folders();
6420
- init_recorder3();
6421
- init_embed3();
6422
- init_prompt3();
6423
- init_meeting3();
6424
- init_fields2();
6425
- init_automations();
6426
- init_webhooks();
6427
- init_analytics();
6428
- init_clips();
6429
- init_workflows();
6430
- init_users();
6431
- init_dashboards();
6432
- modules = [
6433
- media_exports,
6434
- text_exports,
6435
- exports_exports,
6436
- folders_exports,
6437
- recorder_exports,
6438
- embed_exports,
7564
+ function register17(server, client) {
7565
+ const api = client ?? speakClient;
7566
+ registerSpeakTool(
7567
+ server,
7568
+ "list_voice_agents",
7569
+ "List the voice agents in the company (newest first). Each agent includes its agentId, name, personality/instructions, and voice/stt/llm/avatar configuration. Use the returned agentId with get_voice_agent or to filter list_voice_conversations.",
7570
+ {},
7571
+ {
7572
+ title: "List Voice Agents",
7573
+ readOnlyHint: true,
7574
+ destructiveHint: false,
7575
+ idempotentHint: true,
7576
+ openWorldHint: false
7577
+ },
7578
+ async () => {
7579
+ try {
7580
+ const result = await api.get("/v1/voice/agents");
7581
+ return {
7582
+ content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }]
7583
+ };
7584
+ } catch (err) {
7585
+ return {
7586
+ content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }],
7587
+ isError: true
7588
+ };
7589
+ }
7590
+ }
7591
+ );
7592
+ registerSpeakTool(
7593
+ server,
7594
+ "get_voice_agent",
7595
+ "Fetch a single voice agent by its agentId. Returns the full agent configuration. A cross-company agentId returns 404.",
7596
+ {
7597
+ agentId: import_zod18.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)")
7598
+ },
7599
+ {
7600
+ title: "Get Voice Agent",
7601
+ readOnlyHint: true,
7602
+ destructiveHint: false,
7603
+ idempotentHint: true,
7604
+ openWorldHint: false
7605
+ },
7606
+ async ({ agentId }) => {
7607
+ try {
7608
+ const result = await api.get(`/v1/voice/agents/${agentId}`);
7609
+ return {
7610
+ content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }]
7611
+ };
7612
+ } catch (err) {
7613
+ return {
7614
+ content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }],
7615
+ isError: true
7616
+ };
7617
+ }
7618
+ }
7619
+ );
7620
+ registerSpeakTool(
7621
+ server,
7622
+ "list_voice_conversations",
7623
+ "List the company's voice conversations (newest first). Optionally filter to a single agent. Each conversation includes its conversationId, agentId, status, duration, transcript summary, and usage/costs. Use conversationId with get_voice_conversation for the full record.",
7624
+ {
7625
+ agentId: import_zod18.z.string().optional().describe("Filter conversations to a single agent (from list_voice_agents)"),
7626
+ page: import_zod18.z.number().int().min(1).optional().describe("1-based page index (default 1)"),
7627
+ limit: import_zod18.z.number().int().min(1).max(200).optional().describe("Results per page (default 50, max 200)")
7628
+ },
7629
+ {
7630
+ title: "List Voice Conversations",
7631
+ readOnlyHint: true,
7632
+ destructiveHint: false,
7633
+ idempotentHint: true,
7634
+ openWorldHint: false
7635
+ },
7636
+ async (params) => {
7637
+ try {
7638
+ const result = await api.get("/v1/voice/conversations", { params });
7639
+ return {
7640
+ content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }]
7641
+ };
7642
+ } catch (err) {
7643
+ return {
7644
+ content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }],
7645
+ isError: true
7646
+ };
7647
+ }
7648
+ }
7649
+ );
7650
+ registerSpeakTool(
7651
+ server,
7652
+ "get_voice_conversation",
7653
+ "Fetch a single voice conversation by its conversationId, including transcript, usage, costs, and analysis. A cross-company conversationId returns 404.",
7654
+ {
7655
+ conversationId: import_zod18.z.string().min(1).describe("ID of the conversation (from list_voice_conversations)")
7656
+ },
7657
+ {
7658
+ title: "Get Voice Conversation",
7659
+ readOnlyHint: true,
7660
+ destructiveHint: false,
7661
+ idempotentHint: true,
7662
+ openWorldHint: false
7663
+ },
7664
+ async ({ conversationId }) => {
7665
+ try {
7666
+ const result = await api.get(`/v1/voice/conversations/${conversationId}`);
7667
+ return {
7668
+ content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }]
7669
+ };
7670
+ } catch (err) {
7671
+ return {
7672
+ content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }],
7673
+ isError: true
7674
+ };
7675
+ }
7676
+ }
7677
+ );
7678
+ registerSpeakTool(
7679
+ server,
7680
+ "create_voice_agent",
7681
+ "Create a voice agent. Requires the OWNER or ADMIN role. name, personality, instructions, and voice (provider + voiceId) are required; everything else can be set now or later with update_voice_agent. Call list_voice_avatars or list_voices first to get valid ids.",
7682
+ voiceInputSchema,
7683
+ {
7684
+ title: "Create Voice Agent",
7685
+ readOnlyHint: false,
7686
+ destructiveHint: false,
7687
+ idempotentHint: false,
7688
+ openWorldHint: false
7689
+ },
7690
+ async (body) => {
7691
+ try {
7692
+ const result = await api.post("/v1/voice/agents", body);
7693
+ return {
7694
+ content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }]
7695
+ };
7696
+ } catch (err) {
7697
+ return {
7698
+ content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }],
7699
+ isError: true
7700
+ };
7701
+ }
7702
+ }
7703
+ );
7704
+ registerSpeakTool(
7705
+ server,
7706
+ "update_voice_agent",
7707
+ "Update a voice agent. Requires the OWNER or ADMIN role. Send only the fields you want to change; agentId, companyId, and userId are immutable and silently dropped if sent.",
7708
+ {
7709
+ agentId: import_zod18.z.string().min(1).describe("ID of the voice agent to update (from list_voice_agents)"),
7710
+ ...Object.fromEntries(
7711
+ Object.entries(voiceInputSchema).map(([key, schema]) => [key, schema.optional()])
7712
+ )
7713
+ },
7714
+ {
7715
+ title: "Update Voice Agent",
7716
+ readOnlyHint: false,
7717
+ destructiveHint: false,
7718
+ idempotentHint: false,
7719
+ openWorldHint: false
7720
+ },
7721
+ async ({ agentId, ...body }) => {
7722
+ try {
7723
+ const result = await api.put(`/v1/voice/agents/${agentId}`, body);
7724
+ return {
7725
+ content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }]
7726
+ };
7727
+ } catch (err) {
7728
+ return {
7729
+ content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }],
7730
+ isError: true
7731
+ };
7732
+ }
7733
+ }
7734
+ );
7735
+ registerSpeakTool(
7736
+ server,
7737
+ "list_voice_avatars",
7738
+ "List the video avatars available to attach to a voice agent (your company's own uploads plus the shared system catalog). Use the returned avatarId with create_voice_agent or update_voice_agent.",
7739
+ {},
7740
+ {
7741
+ title: "List Voice Avatars",
7742
+ readOnlyHint: true,
7743
+ destructiveHint: false,
7744
+ idempotentHint: true,
7745
+ openWorldHint: false
7746
+ },
7747
+ async () => {
7748
+ try {
7749
+ const result = await api.get("/v1/voice/avatars");
7750
+ return {
7751
+ content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }]
7752
+ };
7753
+ } catch (err) {
7754
+ return {
7755
+ content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }],
7756
+ isError: true
7757
+ };
7758
+ }
7759
+ }
7760
+ );
7761
+ registerSpeakTool(
7762
+ server,
7763
+ "list_voices",
7764
+ "List the text-to-speech voices available to a voice agent. Use the returned provider/voiceId with create_voice_agent or update_voice_agent's voice field. When an agent's llm.model is a Live (speech-to-speech) model, its usable voices are a fixed, smaller set scoped to that model instead of this full catalog.",
7765
+ {},
7766
+ {
7767
+ title: "List Voices",
7768
+ readOnlyHint: true,
7769
+ destructiveHint: false,
7770
+ idempotentHint: true,
7771
+ openWorldHint: false
7772
+ },
7773
+ async () => {
7774
+ try {
7775
+ const result = await api.get("/v1/voice/voices");
7776
+ return {
7777
+ content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }]
7778
+ };
7779
+ } catch (err) {
7780
+ return {
7781
+ content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }],
7782
+ isError: true
7783
+ };
7784
+ }
7785
+ }
7786
+ );
7787
+ registerSpeakTool(
7788
+ server,
7789
+ "delete_voice_agent",
7790
+ "Permanently delete a voice agent. Requires the OWNER or ADMIN role. Irreversible: also removes its questions, test suite, and share link; past conversations are kept for record-keeping but are no longer reachable from this agent.",
7791
+ { agentId: import_zod18.z.string().min(1).describe("ID of the voice agent to delete (from list_voice_agents)") },
7792
+ { title: "Delete Voice Agent", readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
7793
+ async ({ agentId }) => {
7794
+ try {
7795
+ const result = await api.delete(`/v1/voice/agents/${agentId}`);
7796
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
7797
+ } catch (err) {
7798
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
7799
+ }
7800
+ }
7801
+ );
7802
+ registerSpeakTool(
7803
+ server,
7804
+ "create_voice_agent_from_prompt",
7805
+ "Create a new voice agent by describing it in plain English instead of filling in name/personality/instructions/voice yourself. Requires the OWNER or ADMIN role. Response always includes the new agentId, plus either the generated agent config, or needsFollowUp: true with a follow-up question if the prompt was too thin to act on \u2014 call generate_voice_agent_config again on that agentId with more detail (or manualInstructions) when that happens.",
7806
+ {
7807
+ prompt: import_zod18.z.string().min(1).describe('Plain-English description of the agent to build, e.g. "a friendly dental clinic receptionist that books appointments and answers insurance questions".'),
7808
+ name: import_zod18.z.string().optional().describe("Agent name. Defaults to one derived from the prompt if omitted."),
7809
+ manualInstructions: import_zod18.z.string().optional().describe("Skip generation and use this as the agent's instructions verbatim.")
7810
+ },
7811
+ { title: "Create Voice Agent From Prompt", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
7812
+ async (body) => {
7813
+ try {
7814
+ const result = await api.post("/v1/voice/agents/generation", body);
7815
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
7816
+ } catch (err) {
7817
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
7818
+ }
7819
+ }
7820
+ );
7821
+ registerSpeakTool(
7822
+ server,
7823
+ "generate_voice_agent_config",
7824
+ "Run the same prompt-to-config generation as create_voice_agent_from_prompt, but against an existing agent instead of creating a new one. Requires the OWNER or ADMIN role. On success the generated config is persisted onto the agent immediately. If the prompt is too thin and manualInstructions was not sent, the response has needsFollowUp: true with a follow-up question instead \u2014 call this again with more detail.",
7825
+ {
7826
+ agentId: import_zod18.z.string().min(1).describe("ID of the existing voice agent to generate config for (from list_voice_agents)"),
7827
+ prompt: import_zod18.z.string().min(1).describe("Plain-English description of what the agent should do."),
7828
+ manualInstructions: import_zod18.z.string().optional().describe("Skip generation and set the agent's instructions to this verbatim.")
7829
+ },
7830
+ { title: "Generate Voice Agent Config", readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
7831
+ async ({ agentId, ...body }) => {
7832
+ try {
7833
+ const result = await api.post(`/v1/voice/agents/${agentId}/generation/generate`, body);
7834
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
7835
+ } catch (err) {
7836
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
7837
+ }
7838
+ }
7839
+ );
7840
+ registerSpeakTool(
7841
+ server,
7842
+ "get_voice_agent_setup_guide",
7843
+ "Discovery + how-to helper for building and operating a Speak AI voice agent end to end. Returns the four configuration pieces every agent is built from, which tool covers each one, the recommended build order, and how testing/questions/knowledge-base/intelligence tools chain together after the agent exists. Call this before create_voice_agent or create_voice_agent_from_prompt if you are not already familiar with this tool surface.",
7844
+ {},
7845
+ { title: "Get Voice Agent Setup Guide", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
7846
+ async () => {
7847
+ const data = {
7848
+ overview: "A voice agent is a standalone resource: create it once, then it holds live spoken conversations, asking configured questions and answering from a knowledge base. It is built from four independent pieces, plus optional testing, sharing, and self-improvement layers.",
7849
+ buildOrder: [
7850
+ {
7851
+ step: 1,
7852
+ piece: "The agent record itself",
7853
+ tools: ["create_voice_agent", "create_voice_agent_from_prompt"],
7854
+ notes: "name, personality, instructions, and voice (provider+voiceId) are the only required fields. Call list_voices and list_voice_avatars first to get valid ids."
7855
+ },
7856
+ {
7857
+ step: 2,
7858
+ piece: "Voice & avatar",
7859
+ tools: ["list_voices", "list_voice_avatars", "update_voice_agent"],
7860
+ notes: "Every agent needs a voice. It only needs an avatar if conversationMode is video_avatar."
7861
+ },
7862
+ {
7863
+ step: 3,
7864
+ piece: "Instructions & behavior",
7865
+ tools: ["update_voice_agent", "generate_voice_agent_config"],
7866
+ notes: "personality/instructions are plain fields on the agent record; generate_voice_agent_config can (re)write them from a prompt instead of hand-authoring."
7867
+ },
7868
+ {
7869
+ step: 4,
7870
+ piece: "Questions",
7871
+ tools: ["list_voice_question_templates", "create_voice_question", "reorder_voice_questions"],
7872
+ notes: "Optional. Attaches a question template to the agent so it collects structured data mid-call. See the Questions tool group."
7873
+ },
7874
+ {
7875
+ step: 5,
7876
+ piece: "Knowledge base",
7877
+ tools: ["Knowledge Base tool group (separate from voice agents)"],
7878
+ notes: "Optional. A knowledge base collection is attached to the agent from the Knowledge Base API, not a voice-agent tool -- an agent has no documents of its own until one is attached."
7879
+ }
7880
+ ],
7881
+ afterTheAgentExists: [
7882
+ {
7883
+ area: "Testing",
7884
+ tools: ["get_voice_test_suite", "update_voice_test_suite", "generate_voice_test_suite", "start_voice_test_run"],
7885
+ notes: "Scripted scenarios and a run history. The run lifecycle is live; the engine that drives a simulated conversation is not wired up yet, so a run stays queued."
7886
+ },
7887
+ {
7888
+ area: "Feedback / self-improvement (Intelligence)",
7889
+ tools: [
7890
+ "list_voice_kb_gaps",
7891
+ "list_voice_faq_suggestions",
7892
+ "analyze_voice_instruction_gaps",
7893
+ "list_voice_agent_resources"
7894
+ ],
7895
+ notes: "What the agent surfaces from real calls: knowledge it lacked, questions callers repeat, and gaps in its own instructions. Nothing is written automatically -- every suggestion needs an explicit add/apply/dismiss call."
7896
+ },
7897
+ {
7898
+ area: "Conversations & analytics",
7899
+ tools: ["list_voice_conversations", "get_voice_conversation"],
7900
+ notes: "Read call history and transcripts once the agent has taken calls."
7901
+ }
7902
+ ],
7903
+ commonMistakes: [
7904
+ "Calling create_voice_agent with a made-up voiceId instead of one from list_voices -- the create call fails validation.",
7905
+ "Expecting start_voice_test_run to return real scores -- the execution engine isn't wired up yet, see the Testing tools' own descriptions.",
7906
+ "Looking for a knowledge-base tool in this group -- collections are managed by the separate Knowledge Base tool group and only attached here."
7907
+ ]
7908
+ };
7909
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
7910
+ }
7911
+ );
7912
+ }
7913
+ var import_zod18, voiceInputSchema;
7914
+ var init_voice = __esm({
7915
+ "src/tools/voice.ts"() {
7916
+ "use strict";
7917
+ import_zod18 = require("zod");
7918
+ init_helpers();
7919
+ init_client();
7920
+ voiceInputSchema = {
7921
+ name: import_zod18.z.string().min(1).describe("Required on create. Trimmed, non-empty."),
7922
+ personality: import_zod18.z.string().describe("Required on create. Free text describing the agent's tone."),
7923
+ instructions: import_zod18.z.string().describe("Required on create. The agent's system instructions."),
7924
+ voice: import_zod18.z.object({
7925
+ provider: import_zod18.z.string().describe("TTS provider, e.g. elevenlabs or openai."),
7926
+ voiceId: import_zod18.z.string(),
7927
+ model: import_zod18.z.string().optional()
7928
+ }).describe("Required on create."),
7929
+ llm: import_zod18.z.object({
7930
+ provider: import_zod18.z.string().optional().describe("Must be one of the voice-agent LLM providers if sent."),
7931
+ model: import_zod18.z.string().optional().describe("Must be one of the voice-agent model ids if sent.")
7932
+ }).optional(),
7933
+ avatar: import_zod18.z.object({
7934
+ avatarId: import_zod18.z.string().describe("Must match a row in your company's avatar catalog (list_voice_avatars) or the shared system catalog.")
7935
+ }).optional().describe("Set to attach a video avatar; avatarUrl/provider are derived server-side from the catalog row."),
7936
+ conversationMode: import_zod18.z.enum(["voice_only", "video_avatar"]).optional(),
7937
+ folderId: import_zod18.z.string().optional().describe("Folder to file this agent's conversations under."),
7938
+ enableWebSearch: import_zod18.z.boolean().optional().describe("Let the agent search the web mid-call, separate from any attached knowledge base.")
7939
+ };
7940
+ }
7941
+ });
7942
+
7943
+ // src/tools/voice-testing.ts
7944
+ var voice_testing_exports = {};
7945
+ __export(voice_testing_exports, {
7946
+ register: () => register18
7947
+ });
7948
+ function register18(server, client) {
7949
+ const api = client ?? speakClient;
7950
+ registerSpeakTool(
7951
+ server,
7952
+ "get_voice_test_suite",
7953
+ "Get a voice agent's test suite (its scenarios and run settings). Returns null in data.suite if none has been created yet \u2014 not a 404.",
7954
+ { agentId: import_zod19.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)") },
7955
+ { title: "Get Voice Test Suite", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
7956
+ async ({ agentId }) => {
7957
+ try {
7958
+ const result = await api.get(`/v1/voice/testing/${agentId}/suite`);
7959
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
7960
+ } catch (err) {
7961
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
7962
+ }
7963
+ }
7964
+ );
7965
+ registerSpeakTool(
7966
+ server,
7967
+ "update_voice_test_suite",
7968
+ "Create or update a voice agent's test suite. Requires the OWNER or ADMIN role. Upserts. Send the full scenarios array you want to keep \u2014 it replaces the stored one, it is not merged.",
7969
+ {
7970
+ agentId: import_zod19.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)"),
7971
+ scenarios: import_zod19.z.array(scenarioSchema).optional(),
7972
+ maxCostPerRun: import_zod19.z.number().min(0).optional(),
7973
+ autoRunOnKbUpdate: import_zod19.z.boolean().optional(),
7974
+ autoRunOnInstructionSave: import_zod19.z.boolean().optional(),
7975
+ scheduledCron: import_zod19.z.string().optional().nullable()
7976
+ },
7977
+ { title: "Update Voice Test Suite", readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
7978
+ async ({ agentId, ...body }) => {
7979
+ try {
7980
+ const result = await api.put(`/v1/voice/testing/${agentId}/suite`, body);
7981
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
7982
+ } catch (err) {
7983
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
7984
+ }
7985
+ }
7986
+ );
7987
+ registerSpeakTool(
7988
+ server,
7989
+ "generate_voice_test_suite",
7990
+ "Auto-generate a default test suite for a voice agent from its own instructions and knowledge base, via an LLM call. Requires the OWNER or ADMIN role. Overwrites the suite's existing scenarios.",
7991
+ { agentId: import_zod19.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)") },
7992
+ { title: "Generate Voice Test Suite", readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
7993
+ async ({ agentId }) => {
7994
+ try {
7995
+ const result = await api.post(`/v1/voice/testing/${agentId}/suite/generate`);
7996
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
7997
+ } catch (err) {
7998
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
7999
+ }
8000
+ }
8001
+ );
8002
+ registerSpeakTool(
8003
+ server,
8004
+ "start_voice_test_run",
8005
+ "Start a test run against a voice agent's suite. Requires the OWNER or ADMIN role. Rejects with 409 if the agent has no test suite." + NOT_WIRED_NOTE,
8006
+ { agentId: import_zod19.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)") },
8007
+ { title: "Start Voice Test Run", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
8008
+ async ({ agentId }) => {
8009
+ try {
8010
+ const result = await api.post(`/v1/voice/testing/${agentId}/run`);
8011
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8012
+ } catch (err) {
8013
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8014
+ }
8015
+ }
8016
+ );
8017
+ registerSpeakTool(
8018
+ server,
8019
+ "get_active_voice_test_run",
8020
+ "Get a voice agent's currently active test run (queued, running, or paused). Returns null in data.run if none is active \u2014 not a 404.",
8021
+ { agentId: import_zod19.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)") },
8022
+ { title: "Get Active Voice Test Run", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
8023
+ async ({ agentId }) => {
8024
+ try {
8025
+ const result = await api.get(`/v1/voice/testing/${agentId}/run/active`);
8026
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8027
+ } catch (err) {
8028
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8029
+ }
8030
+ }
8031
+ );
8032
+ registerSpeakTool(
8033
+ server,
8034
+ "pause_voice_test_run",
8035
+ "Pause a voice agent's test run. Requires the OWNER or ADMIN role. Valid only from queued or running." + NOT_WIRED_NOTE,
8036
+ {
8037
+ agentId: import_zod19.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)"),
8038
+ runId: import_zod19.z.string().min(1).describe("ID of the run (from get_active_voice_test_run or list_voice_test_runs)")
8039
+ },
8040
+ { title: "Pause Voice Test Run", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
8041
+ async ({ agentId, runId }) => {
8042
+ try {
8043
+ const result = await api.post(`/v1/voice/testing/${agentId}/run/${runId}/pause`);
8044
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8045
+ } catch (err) {
8046
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8047
+ }
8048
+ }
8049
+ );
8050
+ registerSpeakTool(
8051
+ server,
8052
+ "resume_voice_test_run",
8053
+ "Resume a paused voice agent test run, transitioning it back to running. Requires the OWNER or ADMIN role. Valid only from paused.",
8054
+ {
8055
+ agentId: import_zod19.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)"),
8056
+ runId: import_zod19.z.string().min(1).describe("ID of the run (from get_active_voice_test_run or list_voice_test_runs)")
8057
+ },
8058
+ { title: "Resume Voice Test Run", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
8059
+ async ({ agentId, runId }) => {
8060
+ try {
8061
+ const result = await api.post(`/v1/voice/testing/${agentId}/run/${runId}/resume`);
8062
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8063
+ } catch (err) {
8064
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8065
+ }
8066
+ }
8067
+ );
8068
+ registerSpeakTool(
8069
+ server,
8070
+ "cancel_voice_test_run",
8071
+ "Cancel a voice agent test run. Requires the OWNER or ADMIN role. Valid from queued, running, or paused. Terminal \u2014 a cancelled run can never be resumed.",
8072
+ {
8073
+ agentId: import_zod19.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)"),
8074
+ runId: import_zod19.z.string().min(1).describe("ID of the run (from get_active_voice_test_run or list_voice_test_runs)")
8075
+ },
8076
+ { title: "Cancel Voice Test Run", readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
8077
+ async ({ agentId, runId }) => {
8078
+ try {
8079
+ const result = await api.post(`/v1/voice/testing/${agentId}/run/${runId}/cancel`);
8080
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8081
+ } catch (err) {
8082
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8083
+ }
8084
+ }
8085
+ );
8086
+ registerSpeakTool(
8087
+ server,
8088
+ "list_voice_test_runs",
8089
+ "List a voice agent's test runs, most recent first. Capped at 100 regardless of limit.",
8090
+ {
8091
+ agentId: import_zod19.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)"),
8092
+ limit: import_zod19.z.number().int().min(1).optional()
8093
+ },
8094
+ { title: "List Voice Test Runs", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
8095
+ async ({ agentId, ...params }) => {
8096
+ try {
8097
+ const result = await api.get(`/v1/voice/testing/${agentId}/runs`, { params });
8098
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8099
+ } catch (err) {
8100
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8101
+ }
8102
+ }
8103
+ );
8104
+ registerSpeakTool(
8105
+ server,
8106
+ "get_voice_test_run",
8107
+ "Get a test run's full detail, including scenarioResults and recommendations. Scoped to your company; agentId is not used to filter this lookup, only runId.",
8108
+ {
8109
+ agentId: import_zod19.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)"),
8110
+ runId: import_zod19.z.string().min(1).describe("ID of the run (from list_voice_test_runs)")
8111
+ },
8112
+ { title: "Get Voice Test Run", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
8113
+ async ({ agentId, runId }) => {
8114
+ try {
8115
+ const result = await api.get(`/v1/voice/testing/${agentId}/runs/${runId}`);
8116
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8117
+ } catch (err) {
8118
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8119
+ }
8120
+ }
8121
+ );
8122
+ registerSpeakTool(
8123
+ server,
8124
+ "apply_voice_test_recommendation",
8125
+ "Apply a test run recommendation's quick action to the agent (e.g. patch_instructions appends the suggested fix to the agent's instructions). Requires the OWNER or ADMIN role.",
8126
+ {
8127
+ agentId: import_zod19.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)"),
8128
+ runId: import_zod19.z.string().min(1).describe("ID of the run (from get_voice_test_run)"),
8129
+ recId: import_zod19.z.string().min(1).describe("ID of the recommendation within that run's recommendations list")
8130
+ },
8131
+ { title: "Apply Voice Test Recommendation", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
8132
+ async ({ agentId, runId, recId }) => {
8133
+ try {
8134
+ const result = await api.post(`/v1/voice/testing/${agentId}/runs/${runId}/recommendations/${recId}/apply`);
8135
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8136
+ } catch (err) {
8137
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8138
+ }
8139
+ }
8140
+ );
8141
+ registerSpeakTool(
8142
+ server,
8143
+ "get_voice_test_baseline",
8144
+ "Get a voice agent's best-scoring completed test run, used to detect regressions on later runs. Returns null in data.baseline if no run has completed yet.",
8145
+ { agentId: import_zod19.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)") },
8146
+ { title: "Get Voice Test Baseline", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
8147
+ async ({ agentId }) => {
8148
+ try {
8149
+ const result = await api.get(`/v1/voice/testing/${agentId}/baseline`);
8150
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8151
+ } catch (err) {
8152
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8153
+ }
8154
+ }
8155
+ );
8156
+ registerSpeakTool(
8157
+ server,
8158
+ "get_voice_test_score_history",
8159
+ "Get completed-run score points for a voice agent, most recent first, for charting. Capped at 100 regardless of limit. Only status=completed runs are included.",
8160
+ {
8161
+ agentId: import_zod19.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)"),
8162
+ limit: import_zod19.z.number().int().min(1).optional()
8163
+ },
8164
+ { title: "Get Voice Test Score History", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
8165
+ async ({ agentId, ...params }) => {
8166
+ try {
8167
+ const result = await api.get(`/v1/voice/testing/${agentId}/score-history`, { params });
8168
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8169
+ } catch (err) {
8170
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8171
+ }
8172
+ }
8173
+ );
8174
+ }
8175
+ var import_zod19, NOT_WIRED_NOTE, criterionSchema, scenarioSchema;
8176
+ var init_voice_testing = __esm({
8177
+ "src/tools/voice-testing.ts"() {
8178
+ "use strict";
8179
+ import_zod19 = require("zod");
8180
+ init_helpers();
8181
+ init_client();
8182
+ NOT_WIRED_NOTE = " The live execution engine is not wired up yet: a run created here stays queued, scenarioResults stays empty, and overallScore stays 0.";
8183
+ criterionSchema = import_zod19.z.object({
8184
+ criterionId: import_zod19.z.string().optional(),
8185
+ name: import_zod19.z.string(),
8186
+ evaluationPrompt: import_zod19.z.string().describe("What the LLM judge is asked to evaluate."),
8187
+ weight: import_zod19.z.number().min(1).max(10).optional(),
8188
+ isCritical: import_zod19.z.boolean().optional(),
8189
+ type: import_zod19.z.enum(["llm_judged", "response_length", "regex_match", "tool_called"]).optional().describe("Defaults to llm_judged. The other three route through a deterministic code check before the LLM judge runs."),
8190
+ maxWords: import_zod19.z.number().int().optional().describe("For type=response_length: fails if any agent response exceeds this word count."),
8191
+ regexPattern: import_zod19.z.string().optional().describe("For type=regex_match: JS regex source, no slashes."),
8192
+ mustMatch: import_zod19.z.boolean().optional().describe("For type=regex_match: true (default) requires a match, false requires none."),
8193
+ expectedToolName: import_zod19.z.string().optional().describe("For type=tool_called: the tool name to look for in the transcript's tool calls.")
8194
+ });
8195
+ scenarioSchema = import_zod19.z.object({
8196
+ scenarioId: import_zod19.z.string().optional(),
8197
+ name: import_zod19.z.string(),
8198
+ description: import_zod19.z.string().optional(),
8199
+ userMessages: import_zod19.z.array(import_zod19.z.string()).min(1).describe("The scripted turns sent to the agent."),
8200
+ criteria: import_zod19.z.array(criterionSchema).optional().describe("Defaults to an empty array."),
8201
+ category: import_zod19.z.enum(["greeting", "kb_retrieval", "off_topic", "edge_case", "custom"]).optional(),
8202
+ isEnabled: import_zod19.z.boolean().optional()
8203
+ });
8204
+ }
8205
+ });
8206
+
8207
+ // src/tools/voice-questions.ts
8208
+ var voice_questions_exports = {};
8209
+ __export(voice_questions_exports, {
8210
+ register: () => register19
8211
+ });
8212
+ function register19(server, client) {
8213
+ const api = client ?? speakClient;
8214
+ registerSpeakTool(
8215
+ server,
8216
+ "list_voice_questions",
8217
+ "List the questions configured on a voice agent, in the order it asks them. Each is an agent-level instance of a question template with its own required/attempts/no-response settings and optional field mapping.",
8218
+ {
8219
+ agentId: import_zod20.z.string().min(1).describe("Required. Returns 404 if the agent does not exist or does not belong to your company."),
8220
+ enabledOnly: import_zod20.z.boolean().optional()
8221
+ },
8222
+ { title: "List Voice Questions", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
8223
+ async (params) => {
8224
+ try {
8225
+ const result = await api.get("/v1/voice/questions", { params });
8226
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8227
+ } catch (err) {
8228
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8229
+ }
8230
+ }
8231
+ );
8232
+ registerSpeakTool(
8233
+ server,
8234
+ "get_voice_question",
8235
+ "Fetch a single voice agent question by its fieldId, scoped to your company.",
8236
+ { fieldId: import_zod20.z.string().min(1).describe("ID of the question (from list_voice_questions)") },
8237
+ { title: "Get Voice Question", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
8238
+ async ({ fieldId }) => {
8239
+ try {
8240
+ const result = await api.get(`/v1/voice/questions/${fieldId}`);
8241
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8242
+ } catch (err) {
8243
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8244
+ }
8245
+ }
8246
+ );
8247
+ registerSpeakTool(
8248
+ server,
8249
+ "create_voice_question",
8250
+ "Attach a question template to a voice agent. Requires the OWNER or ADMIN role. agentId and templateId are both required and must belong to your company (or, for templateId, be a public system template) \u2014 404 if either isn't found.",
8251
+ {
8252
+ agentId: import_zod20.z.string().min(1),
8253
+ templateId: import_zod20.z.string().min(1).describe("From list_voice_question_templates."),
8254
+ customConfig: customConfigSchema.optional().describe("Agent-level override of the template's defaultConfig; only the keys you send are overridden."),
8255
+ required: import_zod20.z.boolean().optional(),
8256
+ maxPromptAttempts: import_zod20.z.number().min(1).max(3).optional(),
8257
+ noResponseBehavior: import_zod20.z.enum(["move_to_next_question", "end_conversation"]).optional(),
8258
+ triggerCondition: import_zod20.z.string().optional(),
8259
+ order: import_zod20.z.number().optional(),
8260
+ enabled: import_zod20.z.boolean().optional(),
8261
+ mappedFieldId: import_zod20.z.string().optional().nullable().describe("ID of an existing company Field to write this question's collected answer onto after each call.")
8262
+ },
8263
+ { title: "Create Voice Question", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
8264
+ async (body) => {
8265
+ try {
8266
+ const result = await api.post("/v1/voice/questions", body);
8267
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8268
+ } catch (err) {
8269
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8270
+ }
8271
+ }
8272
+ );
8273
+ registerSpeakTool(
8274
+ server,
8275
+ "update_voice_question",
8276
+ "Partially update a voice agent question \u2014 only the fields you send are changed. Requires the OWNER or ADMIN role. agentId and templateId are fixed after create; sending them is silently dropped.",
8277
+ {
8278
+ fieldId: import_zod20.z.string().min(1).describe("ID of the question to update (from list_voice_questions)"),
8279
+ customConfig: customConfigSchema.optional(),
8280
+ required: import_zod20.z.boolean().optional(),
8281
+ maxPromptAttempts: import_zod20.z.number().min(1).max(3).optional(),
8282
+ noResponseBehavior: import_zod20.z.enum(["move_to_next_question", "end_conversation"]).optional(),
8283
+ triggerCondition: import_zod20.z.string().optional(),
8284
+ order: import_zod20.z.number().optional(),
8285
+ enabled: import_zod20.z.boolean().optional(),
8286
+ mappedFieldId: import_zod20.z.string().optional().nullable()
8287
+ },
8288
+ { title: "Update Voice Question", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
8289
+ async ({ fieldId, ...body }) => {
8290
+ try {
8291
+ const result = await api.put(`/v1/voice/questions/${fieldId}`, body);
8292
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8293
+ } catch (err) {
8294
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8295
+ }
8296
+ }
8297
+ );
8298
+ registerSpeakTool(
8299
+ server,
8300
+ "delete_voice_question",
8301
+ "Permanently remove a question from a voice agent and decrement the underlying template's usageCount. Requires the OWNER or ADMIN role. The template itself is not deleted and can be attached to another agent later.",
8302
+ { fieldId: import_zod20.z.string().min(1).describe("ID of the question to remove (from list_voice_questions)") },
8303
+ { title: "Delete Voice Question", readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
8304
+ async ({ fieldId }) => {
8305
+ try {
8306
+ const result = await api.delete(`/v1/voice/questions/${fieldId}`);
8307
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8308
+ } catch (err) {
8309
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8310
+ }
8311
+ }
8312
+ );
8313
+ registerSpeakTool(
8314
+ server,
8315
+ "reorder_voice_questions",
8316
+ "Set the order a voice agent asks its questions in. Requires the OWNER or ADMIN role. Bulk-writes the order value on each listed question (written directly, not resequenced), then returns the agent's full question list in its new order. Entries whose fieldId doesn't belong to agentId are silently skipped.",
8317
+ {
8318
+ agentId: import_zod20.z.string().min(1),
8319
+ fieldOrders: import_zod20.z.array(import_zod20.z.object({ fieldId: import_zod20.z.string().min(1), order: import_zod20.z.number() })).min(1).describe("The new order for some or all of the agent's questions.")
8320
+ },
8321
+ { title: "Reorder Voice Questions", readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
8322
+ async (body) => {
8323
+ try {
8324
+ const result = await api.put("/v1/voice/questions/reorder", body);
8325
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8326
+ } catch (err) {
8327
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8328
+ }
8329
+ }
8330
+ );
8331
+ registerSpeakTool(
8332
+ server,
8333
+ "list_voice_question_templates",
8334
+ "List the question templates visible to your company: Speak's shared system templates, plus your own company's templates. Use the returned templateId with create_voice_question.",
8335
+ { category: import_zod20.z.enum(["contact", "booking", "qualification", "payment", "custom"]).optional() },
8336
+ { title: "List Voice Question Templates", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
8337
+ async (params) => {
8338
+ try {
8339
+ const result = await api.get("/v1/voice/question-templates", { params });
8340
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8341
+ } catch (err) {
8342
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8343
+ }
8344
+ }
8345
+ );
8346
+ registerSpeakTool(
8347
+ server,
8348
+ "create_voice_question_template",
8349
+ `Create a company-scoped question template \u2014 the "custom question" a user names themselves rather than picking from Speak's shared library. Requires the OWNER or ADMIN role. The server stamps companyId and forces isSystemTemplate to false, so this template is only ever visible to your company.`,
8350
+ {
8351
+ name: import_zod20.z.string().min(1),
8352
+ description: import_zod20.z.string().min(1),
8353
+ category: import_zod20.z.enum(["contact", "booking", "qualification", "payment", "custom"]),
8354
+ fieldType: import_zod20.z.enum(["email", "phone", "date", "time", "datetime", "text", "number", "boolean", "choice", "url"]),
8355
+ defaultConfig: import_zod20.z.object({
8356
+ displayLabel: import_zod20.z.string(),
8357
+ question: import_zod20.z.string().describe("The prompt text the agent speaks to ask this."),
8358
+ confirmationText: import_zod20.z.string().optional(),
8359
+ validationPrompt: import_zod20.z.string().optional(),
8360
+ validation: validationSchema.optional()
8361
+ }).describe("displayLabel and question are both required within this object."),
8362
+ isPublic: import_zod20.z.boolean().optional(),
8363
+ tags: import_zod20.z.array(import_zod20.z.string()).optional()
8364
+ },
8365
+ { title: "Create Voice Question Template", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
8366
+ async (body) => {
8367
+ try {
8368
+ const result = await api.post("/v1/voice/question-templates", body);
8369
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8370
+ } catch (err) {
8371
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8372
+ }
8373
+ }
8374
+ );
8375
+ }
8376
+ var import_zod20, validationSchema, customConfigSchema;
8377
+ var init_voice_questions = __esm({
8378
+ "src/tools/voice-questions.ts"() {
8379
+ "use strict";
8380
+ import_zod20 = require("zod");
8381
+ init_helpers();
8382
+ init_client();
8383
+ validationSchema = import_zod20.z.object({
8384
+ pattern: import_zod20.z.string().optional(),
8385
+ minLength: import_zod20.z.number().optional(),
8386
+ maxLength: import_zod20.z.number().optional(),
8387
+ min: import_zod20.z.number().optional(),
8388
+ max: import_zod20.z.number().optional(),
8389
+ allowedValues: import_zod20.z.array(import_zod20.z.string()).optional()
8390
+ });
8391
+ customConfigSchema = import_zod20.z.object({
8392
+ displayLabel: import_zod20.z.string().optional(),
8393
+ question: import_zod20.z.string().optional().describe("The prompt text the agent speaks to ask this question."),
8394
+ confirmationText: import_zod20.z.string().optional(),
8395
+ validationPrompt: import_zod20.z.string().optional(),
8396
+ validation: validationSchema.optional()
8397
+ });
8398
+ }
8399
+ });
8400
+
8401
+ // src/tools/voice-intelligence.ts
8402
+ var voice_intelligence_exports = {};
8403
+ __export(voice_intelligence_exports, {
8404
+ register: () => register20
8405
+ });
8406
+ function register20(server, client) {
8407
+ const api = client ?? speakClient;
8408
+ registerSpeakTool(
8409
+ server,
8410
+ "list_voice_kb_gaps",
8411
+ `List a voice agent's pending knowledge-base gaps \u2014 questions callers asked that the agent answered with low confidence or an explicit "I don't know," surfaced automatically after calls. Up to the 50 most recent pending gaps, newest first.`,
8412
+ { agentId: import_zod21.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)") },
8413
+ { title: "List Voice KB Gaps", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
8414
+ async ({ agentId }) => {
8415
+ try {
8416
+ const result = await api.get(`/v1/voice/knowledge-base/${agentId}/gaps`);
8417
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8418
+ } catch (err) {
8419
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8420
+ }
8421
+ }
8422
+ );
8423
+ registerSpeakTool(
8424
+ server,
8425
+ "analyze_voice_kb_gaps",
8426
+ "Trigger knowledge-base gap analysis over a voice agent's recent calls. Requires the OWNER or ADMIN role. Runs in the background and returns immediately \u2014 new gaps appear in list_voice_kb_gaps once analysis finishes, not synchronously with this response.",
8427
+ { agentId: import_zod21.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)") },
8428
+ { title: "Analyze Voice KB Gaps", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
8429
+ async ({ agentId }) => {
8430
+ try {
8431
+ const result = await api.post(`/v1/voice/knowledge-base/${agentId}/gaps/analyze`);
8432
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8433
+ } catch (err) {
8434
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8435
+ }
8436
+ }
8437
+ );
8438
+ registerSpeakTool(
8439
+ server,
8440
+ "add_voice_kb_gap",
8441
+ "Write a knowledge-base gap's answer into the voice agent's attached knowledge base as a new document, and mark the gap added. Requires the OWNER or ADMIN role. Fails with 409 if the gap was already added or dismissed, or if the agent has no knowledge base collection to write into.",
8442
+ {
8443
+ agentId: import_zod21.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)"),
8444
+ gapId: import_zod21.z.string().min(1).describe("ID of the gap (from list_voice_kb_gaps)"),
8445
+ answer: import_zod21.z.string().optional().describe("Overrides the gap's suggested answer."),
8446
+ title: import_zod21.z.string().optional().describe("Overrides the gap's suggested title.")
8447
+ },
8448
+ { title: "Add Voice KB Gap", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
8449
+ async ({ agentId, gapId, ...body }) => {
8450
+ try {
8451
+ const result = await api.post(`/v1/voice/knowledge-base/${agentId}/gaps/${gapId}/add`, body);
8452
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8453
+ } catch (err) {
8454
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8455
+ }
8456
+ }
8457
+ );
8458
+ registerSpeakTool(
8459
+ server,
8460
+ "dismiss_voice_kb_gap",
8461
+ "Mark a voice agent's knowledge-base gap dismissed without writing anything to the knowledge base. Requires the OWNER or ADMIN role.",
8462
+ {
8463
+ agentId: import_zod21.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)"),
8464
+ gapId: import_zod21.z.string().min(1).describe("ID of the gap (from list_voice_kb_gaps)")
8465
+ },
8466
+ { title: "Dismiss Voice KB Gap", readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
8467
+ async ({ agentId, gapId }) => {
8468
+ try {
8469
+ const result = await api.delete(`/v1/voice/knowledge-base/${agentId}/gaps/${gapId}`);
8470
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8471
+ } catch (err) {
8472
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8473
+ }
8474
+ }
8475
+ );
8476
+ registerSpeakTool(
8477
+ server,
8478
+ "list_voice_faq_suggestions",
8479
+ "List a voice agent's pending FAQ suggestions \u2014 questions multiple callers asked in similar form, clustered and drafted into a reusable question/answer pair. Up to the 20 largest clusters, largest first.",
8480
+ { agentId: import_zod21.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)") },
8481
+ { title: "List Voice FAQ Suggestions", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
8482
+ async ({ agentId }) => {
8483
+ try {
8484
+ const result = await api.get(`/v1/voice/knowledge-base/${agentId}/faqs`);
8485
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8486
+ } catch (err) {
8487
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8488
+ }
8489
+ }
8490
+ );
8491
+ registerSpeakTool(
8492
+ server,
8493
+ "generate_voice_faq_suggestions",
8494
+ "Trigger FAQ clustering over a voice agent's recent calls. Requires the OWNER or ADMIN role. Runs in the background and returns immediately \u2014 new suggestions appear in list_voice_faq_suggestions once generation finishes, not synchronously with this response.",
8495
+ { agentId: import_zod21.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)") },
8496
+ { title: "Generate Voice FAQ Suggestions", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
8497
+ async ({ agentId }) => {
8498
+ try {
8499
+ const result = await api.post(`/v1/voice/knowledge-base/${agentId}/faqs/generate`);
8500
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8501
+ } catch (err) {
8502
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8503
+ }
8504
+ }
8505
+ );
8506
+ registerSpeakTool(
8507
+ server,
8508
+ "add_voice_faq_suggestion",
8509
+ "Write an FAQ suggestion's question/answer into the voice agent's attached knowledge base as a new document, and mark the suggestion added. Requires the OWNER or ADMIN role. Fails with 409 if the suggestion was already added or dismissed, or if the agent has no knowledge base collection to write into.",
8510
+ {
8511
+ agentId: import_zod21.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)"),
8512
+ suggestionId: import_zod21.z.string().min(1).describe("ID of the suggestion (from list_voice_faq_suggestions)"),
8513
+ question: import_zod21.z.string().optional().describe("Overrides the suggested question."),
8514
+ answer: import_zod21.z.string().optional().describe("Overrides the suggested answer.")
8515
+ },
8516
+ { title: "Add Voice FAQ Suggestion", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
8517
+ async ({ agentId, suggestionId, ...body }) => {
8518
+ try {
8519
+ const result = await api.post(`/v1/voice/knowledge-base/${agentId}/faqs/${suggestionId}/add`, body);
8520
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8521
+ } catch (err) {
8522
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8523
+ }
8524
+ }
8525
+ );
8526
+ registerSpeakTool(
8527
+ server,
8528
+ "update_voice_faq_suggestion",
8529
+ "Edit a still-pending FAQ suggestion's question and/or answer before adding it. Requires the OWNER or ADMIN role. Fails with 400 if the suggestion was already added or dismissed.",
8530
+ {
8531
+ agentId: import_zod21.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)"),
8532
+ suggestionId: import_zod21.z.string().min(1).describe("ID of the suggestion (from list_voice_faq_suggestions)"),
8533
+ question: import_zod21.z.string().optional(),
8534
+ answer: import_zod21.z.string().optional()
8535
+ },
8536
+ { title: "Update Voice FAQ Suggestion", readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
8537
+ async ({ agentId, suggestionId, ...body }) => {
8538
+ try {
8539
+ const result = await api.put(`/v1/voice/knowledge-base/${agentId}/faqs/${suggestionId}`, body);
8540
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8541
+ } catch (err) {
8542
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8543
+ }
8544
+ }
8545
+ );
8546
+ registerSpeakTool(
8547
+ server,
8548
+ "dismiss_voice_faq_suggestion",
8549
+ "Mark a voice agent's FAQ suggestion dismissed without writing anything to the knowledge base. Requires the OWNER or ADMIN role.",
8550
+ {
8551
+ agentId: import_zod21.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)"),
8552
+ suggestionId: import_zod21.z.string().min(1).describe("ID of the suggestion (from list_voice_faq_suggestions)")
8553
+ },
8554
+ { title: "Dismiss Voice FAQ Suggestion", readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
8555
+ async ({ agentId, suggestionId }) => {
8556
+ try {
8557
+ const result = await api.delete(`/v1/voice/knowledge-base/${agentId}/faqs/${suggestionId}`);
8558
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8559
+ } catch (err) {
8560
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8561
+ }
8562
+ }
8563
+ );
8564
+ registerSpeakTool(
8565
+ server,
8566
+ "list_voice_agent_resources",
8567
+ "List the knowledge documents/links a voice agent searches during calls \u2014 separate from KB gaps and FAQ suggestions, which are the self-improvement layer that surfaces what an agent is missing, not the content itself.",
8568
+ {
8569
+ agentId: import_zod21.z.string().optional(),
8570
+ page: import_zod21.z.number().int().min(1).optional(),
8571
+ limit: import_zod21.z.number().int().min(1).optional(),
8572
+ search: import_zod21.z.string().optional().describe("Search by title/description.")
8573
+ },
8574
+ { title: "List Voice Agent Resources", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
8575
+ async (params) => {
8576
+ try {
8577
+ const result = await api.get("/v1/voice/agent-resources", { params });
8578
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8579
+ } catch (err) {
8580
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8581
+ }
8582
+ }
8583
+ );
8584
+ registerSpeakTool(
8585
+ server,
8586
+ "create_voice_agent_resource",
8587
+ "Add one document/link to a voice agent's knowledge base. Requires the OWNER or ADMIN role. The server fetches and embeds the content in the background (status moves from pending to completed).",
8588
+ { agentId: import_zod21.z.string().min(1), ...resourceBodySchema },
8589
+ { title: "Create Voice Agent Resource", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
8590
+ async (body) => {
8591
+ try {
8592
+ const result = await api.post("/v1/voice/agent-resources", body);
8593
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8594
+ } catch (err) {
8595
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8596
+ }
8597
+ }
8598
+ );
8599
+ registerSpeakTool(
8600
+ server,
8601
+ "bulk_create_voice_agent_resources",
8602
+ "Add up to 100 documents/links to a voice agent's knowledge base in one call. Requires the OWNER or ADMIN role. Each is fetched and embedded independently in the background. Use this instead of calling create_voice_agent_resource in a loop.",
8603
+ {
8604
+ agentId: import_zod21.z.string().min(1),
8605
+ resources: import_zod21.z.array(import_zod21.z.object(resourceBodySchema)).min(1).max(100).describe("1 to 100 entries, each shaped like create_voice_agent_resource's body minus agentId.")
8606
+ },
8607
+ { title: "Bulk Create Voice Agent Resources", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
8608
+ async (body) => {
8609
+ try {
8610
+ const result = await api.post("/v1/voice/agent-resources/bulk", body);
8611
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8612
+ } catch (err) {
8613
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8614
+ }
8615
+ }
8616
+ );
8617
+ registerSpeakTool(
8618
+ server,
8619
+ "update_voice_agent_resource",
8620
+ "Partially update a voice agent resource \u2014 send at least one field. Requires the OWNER or ADMIN role. agentId cannot be changed. Changing url, title, or description re-triggers embedding.",
8621
+ {
8622
+ resourceId: import_zod21.z.string().min(1).describe("ID of the resource to update (from list_voice_agent_resources)"),
8623
+ url: import_zod21.z.string().url().optional(),
8624
+ title: import_zod21.z.string().max(200).optional(),
8625
+ description: import_zod21.z.string().max(1e3).optional(),
8626
+ action: import_zod21.z.enum(["link", "presentation"]).optional(),
8627
+ contentType: import_zod21.z.enum(["video", "pdf", "image"]).optional()
8628
+ },
8629
+ { title: "Update Voice Agent Resource", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
8630
+ async ({ resourceId, ...body }) => {
8631
+ try {
8632
+ const result = await api.put(`/v1/voice/agent-resources/${resourceId}`, body);
8633
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8634
+ } catch (err) {
8635
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8636
+ }
8637
+ }
8638
+ );
8639
+ registerSpeakTool(
8640
+ server,
8641
+ "delete_voice_agent_resource",
8642
+ "Soft-delete a voice agent resource \u2014 it stops appearing in lists and the agent stops searching it, but the document is not physically removed. Requires the OWNER or ADMIN role.",
8643
+ { resourceId: import_zod21.z.string().min(1).describe("ID of the resource to delete (from list_voice_agent_resources)") },
8644
+ { title: "Delete Voice Agent Resource", readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
8645
+ async ({ resourceId }) => {
8646
+ try {
8647
+ const result = await api.delete(`/v1/voice/agent-resources/${resourceId}`);
8648
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8649
+ } catch (err) {
8650
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8651
+ }
8652
+ }
8653
+ );
8654
+ registerSpeakTool(
8655
+ server,
8656
+ "analyze_voice_instruction_gaps",
8657
+ "Advisory only \u2014 compares a voice agent's current instructions against anchors/original intent/recent call summaries you supply and suggests up to 3 patches. Requires the OWNER or ADMIN role. Nothing is written; pass a suggestion's suggestedPatch to apply_voice_instruction_gap to actually apply it.",
8658
+ {
8659
+ agentId: import_zod21.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)"),
8660
+ anchors: import_zod21.z.array(import_zod21.z.string()).optional().describe("Specific requirements the instructions must cover. Defaults to empty."),
8661
+ originalPrompt: import_zod21.z.string().optional().describe("The original generation prompt, for context."),
8662
+ conversationSummaries: import_zod21.z.array(import_zod21.z.string()).optional().describe("Recent call summaries, to ground suggestions in what actually came up. Defaults to empty.")
8663
+ },
8664
+ { title: "Analyze Voice Instruction Gaps", readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: false },
8665
+ async ({ agentId, ...body }) => {
8666
+ try {
8667
+ const result = await api.post(`/v1/voice/agents/${agentId}/generation/gaps/analyze`, body);
8668
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8669
+ } catch (err) {
8670
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8671
+ }
8672
+ }
8673
+ );
8674
+ registerSpeakTool(
8675
+ server,
8676
+ "apply_voice_instruction_gap",
8677
+ "Insert a suggested instruction patch into a voice agent's instructions and persist the result. Requires the OWNER or ADMIN role. suggestedPatch is typically taken directly from analyze_voice_instruction_gaps.",
8678
+ {
8679
+ agentId: import_zod21.z.string().min(1).describe("ID of the voice agent (from list_voice_agents)"),
8680
+ suggestedPatch: import_zod21.z.string().min(1),
8681
+ insertAfterSection: import_zod21.z.string().optional().nullable().describe("Insert after this named section heading; omit or null to append at the end.")
8682
+ },
8683
+ { title: "Apply Voice Instruction Gap", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
8684
+ async ({ agentId, ...body }) => {
8685
+ try {
8686
+ const result = await api.post(`/v1/voice/agents/${agentId}/generation/gaps/apply`, body);
8687
+ return { content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }] };
8688
+ } catch (err) {
8689
+ return { content: [{ type: "text", text: `Error: ${formatAxiosError(err)}` }], isError: true };
8690
+ }
8691
+ }
8692
+ );
8693
+ }
8694
+ var import_zod21, resourceBodySchema;
8695
+ var init_voice_intelligence = __esm({
8696
+ "src/tools/voice-intelligence.ts"() {
8697
+ "use strict";
8698
+ import_zod21 = require("zod");
8699
+ init_helpers();
8700
+ init_client();
8701
+ resourceBodySchema = {
8702
+ url: import_zod21.z.string().url(),
8703
+ title: import_zod21.z.string().max(200),
8704
+ description: import_zod21.z.string().max(1e3),
8705
+ action: import_zod21.z.enum(["link", "presentation"]),
8706
+ contentType: import_zod21.z.enum(["video", "pdf", "image"]).optional()
8707
+ };
8708
+ }
8709
+ });
8710
+
8711
+ // src/tools/index.ts
8712
+ var tools_exports = {};
8713
+ __export(tools_exports, {
8714
+ registerAllTools: () => registerAllTools
8715
+ });
8716
+ function registerAllTools(server, client) {
8717
+ for (const mod of modules) {
8718
+ mod.register(server, client);
8719
+ }
8720
+ }
8721
+ var modules;
8722
+ var init_tools = __esm({
8723
+ "src/tools/index.ts"() {
8724
+ "use strict";
8725
+ init_media3();
8726
+ init_text2();
8727
+ init_exports();
8728
+ init_folders();
8729
+ init_recorder3();
8730
+ init_embed3();
8731
+ init_prompt3();
8732
+ init_meeting3();
8733
+ init_fields2();
8734
+ init_automations();
8735
+ init_webhooks();
8736
+ init_analytics();
8737
+ init_clips();
8738
+ init_workflows();
8739
+ init_users();
8740
+ init_dashboards();
8741
+ init_voice();
8742
+ init_voice_testing();
8743
+ init_voice_questions();
8744
+ init_voice_intelligence();
8745
+ modules = [
8746
+ media_exports,
8747
+ text_exports,
8748
+ exports_exports,
8749
+ folders_exports,
8750
+ recorder_exports,
8751
+ embed_exports,
6439
8752
  prompt_exports,
6440
8753
  meeting_exports,
6441
8754
  fields_exports,
@@ -6445,7 +8758,11 @@ var init_tools = __esm({
6445
8758
  clips_exports,
6446
8759
  workflows_exports,
6447
8760
  users_exports,
6448
- dashboards_exports
8761
+ dashboards_exports,
8762
+ voice_exports,
8763
+ voice_testing_exports,
8764
+ voice_questions_exports,
8765
+ voice_intelligence_exports
6449
8766
  ];
6450
8767
  }
6451
8768
  });
@@ -6562,8 +8879,8 @@ function registerPrompts(server) {
6562
8879
  "analyze-meeting",
6563
8880
  "Upload a meeting recording and get a full analysis \u2014 transcript, insights, action items, and key takeaways.",
6564
8881
  {
6565
- url: import_zod18.z.string().describe(`URL of the meeting recording \u2014 a direct file link, or a shareable page link from ${SUPPORTED_URL_SOURCES} (resolved to the underlying media automatically)`),
6566
- name: import_zod18.z.string().optional().describe("Meeting name (optional)")
8882
+ url: import_zod22.z.string().describe(`URL of the meeting recording \u2014 a direct file link, or a shareable page link from ${SUPPORTED_URL_SOURCES} (resolved to the underlying media automatically)`),
8883
+ name: import_zod22.z.string().optional().describe("Meeting name (optional)")
6567
8884
  },
6568
8885
  async ({ url, name }) => ({
6569
8886
  messages: [
@@ -6598,8 +8915,8 @@ function registerPrompts(server) {
6598
8915
  "research-across-media",
6599
8916
  "Search for themes, patterns, or topics across multiple recordings or your entire media library.",
6600
8917
  {
6601
- topic: import_zod18.z.string().describe("The topic, theme, or question to research"),
6602
- folder: import_zod18.z.string().optional().describe("Folder ID to scope the research (optional)")
8918
+ topic: import_zod22.z.string().describe("The topic, theme, or question to research"),
8919
+ folder: import_zod22.z.string().optional().describe("Folder ID to scope the research (optional)")
6603
8920
  },
6604
8921
  async ({ topic, folder }) => ({
6605
8922
  messages: [
@@ -6632,8 +8949,8 @@ function registerPrompts(server) {
6632
8949
  "meeting-brief",
6633
8950
  "Prepare a brief from recent meetings \u2014 pull transcripts, extract decisions, and summarize open items.",
6634
8951
  {
6635
- days: import_zod18.z.string().optional().describe("Number of days to look back (default: 7)"),
6636
- folder: import_zod18.z.string().optional().describe("Folder ID to scope to (optional)")
8952
+ days: import_zod22.z.string().optional().describe("Number of days to look back (default: 7)"),
8953
+ folder: import_zod22.z.string().optional().describe("Folder ID to scope to (optional)")
6637
8954
  },
6638
8955
  async ({ days, folder }) => {
6639
8956
  const lookback = parseInt(days ?? "7");
@@ -6670,11 +8987,11 @@ function registerPrompts(server) {
6670
8987
  }
6671
8988
  );
6672
8989
  }
6673
- var import_zod18;
8990
+ var import_zod22;
6674
8991
  var init_prompts = __esm({
6675
8992
  "src/prompts.ts"() {
6676
8993
  "use strict";
6677
- import_zod18 = require("zod");
8994
+ import_zod22 = require("zod");
6678
8995
  init_media_utils();
6679
8996
  }
6680
8997
  });
@@ -6696,6 +9013,11 @@ var init_tool_names = __esm({
6696
9013
  "list_automation_names",
6697
9014
  "get_automation",
6698
9015
  "get_automation_runs",
9016
+ "get_automation_run",
9017
+ "get_automation_run_stats",
9018
+ "test_automation",
9019
+ "validate_automation_graph",
9020
+ "describe_automation_graph",
6699
9021
  "create_automation",
6700
9022
  "update_automation",
6701
9023
  "toggle_automation_status",
@@ -6818,7 +9140,61 @@ var init_tool_names = __esm({
6818
9140
  "delete_dashboard",
6819
9141
  "duplicate_dashboard",
6820
9142
  "share_dashboard",
6821
- "get_dashboard_speakers_insight"
9143
+ "get_dashboard_speakers_insight",
9144
+ // voice: agents + conversations
9145
+ "list_voice_agents",
9146
+ "get_voice_agent",
9147
+ "create_voice_agent",
9148
+ "update_voice_agent",
9149
+ "list_voice_avatars",
9150
+ "list_voices",
9151
+ "list_voice_conversations",
9152
+ "get_voice_conversation",
9153
+ // voice: testing
9154
+ "get_voice_test_suite",
9155
+ "update_voice_test_suite",
9156
+ "generate_voice_test_suite",
9157
+ "start_voice_test_run",
9158
+ "get_active_voice_test_run",
9159
+ "pause_voice_test_run",
9160
+ "resume_voice_test_run",
9161
+ "cancel_voice_test_run",
9162
+ "list_voice_test_runs",
9163
+ "get_voice_test_run",
9164
+ "apply_voice_test_recommendation",
9165
+ "get_voice_test_baseline",
9166
+ "get_voice_test_score_history",
9167
+ // voice: agents round-out + discovery
9168
+ "delete_voice_agent",
9169
+ "create_voice_agent_from_prompt",
9170
+ "generate_voice_agent_config",
9171
+ "get_voice_agent_setup_guide",
9172
+ // voice: questions
9173
+ "list_voice_questions",
9174
+ "get_voice_question",
9175
+ "create_voice_question",
9176
+ "update_voice_question",
9177
+ "delete_voice_question",
9178
+ "reorder_voice_questions",
9179
+ "list_voice_question_templates",
9180
+ "create_voice_question_template",
9181
+ // voice: intelligence (kb gaps, faq suggestions, agent resources, instruction gaps)
9182
+ "list_voice_kb_gaps",
9183
+ "analyze_voice_kb_gaps",
9184
+ "add_voice_kb_gap",
9185
+ "dismiss_voice_kb_gap",
9186
+ "list_voice_faq_suggestions",
9187
+ "generate_voice_faq_suggestions",
9188
+ "add_voice_faq_suggestion",
9189
+ "update_voice_faq_suggestion",
9190
+ "dismiss_voice_faq_suggestion",
9191
+ "list_voice_agent_resources",
9192
+ "create_voice_agent_resource",
9193
+ "bulk_create_voice_agent_resources",
9194
+ "update_voice_agent_resource",
9195
+ "delete_voice_agent_resource",
9196
+ "analyze_voice_instruction_gaps",
9197
+ "apply_voice_instruction_gap"
6822
9198
  ];
6823
9199
  }
6824
9200
  });