@apotech-os/support-kit 8.4.0 → 10.1.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.
package/dist/index.cjs CHANGED
@@ -10,12 +10,49 @@ var REASONING_MAX_LEN = 280;
10
10
  var DEFAULT_PROFILE_KEY = "customer";
11
11
  var WHATSAPP_MODES = ["escalate_only", "draft_only", "auto_reply"];
12
12
  var DEFAULT_WHATSAPP_MODE = "escalate_only";
13
+ var SUPPORT_CHANNELS = [
14
+ "email",
15
+ "whatsapp",
16
+ "phone",
17
+ "chat",
18
+ "sms",
19
+ "contact-form",
20
+ "instagram-direct-message",
21
+ "instagram-comment",
22
+ "instagram-mention",
23
+ "instagram-ad-comment",
24
+ "facebook",
25
+ "facebook-messenger"
26
+ ];
27
+ var DEFAULT_AUTO_SEND_CHANNELS = [
28
+ "email",
29
+ "whatsapp",
30
+ "phone",
31
+ "chat",
32
+ "sms",
33
+ "contact-form"
34
+ ];
13
35
  function whatsappModeFromLegacyBoolean(escalateOnly) {
14
36
  return escalateOnly ?? true ? "escalate_only" : "draft_only";
15
37
  }
16
38
  var DEFAULT_CHANNEL_PROMPT_EMAIL = "shared/style-email";
17
39
  var DEFAULT_CHANNEL_PROMPT_WHATSAPP = "shared/style-whatsapp";
18
40
 
41
+ // src/domain/publication.ts
42
+ function publicationMode(conversation) {
43
+ if (!conversation) return null;
44
+ const channel = conversation.sourceChannel;
45
+ if (channel === "whatsapp") return "whatsapp_note";
46
+ if (channel === "email") return conversation.customer.email ? "email" : null;
47
+ if (conversation.customer.email) return "email";
48
+ return canPublishOnOwnChannel(conversation) ? "channel" : null;
49
+ }
50
+ function canPublishOnOwnChannel(conversation) {
51
+ const { sourceChannel, answerableChannels: answerableChannels2, customerChannelAddress: customerChannelAddress2, accountChannelAddress: accountChannelAddress2 } = conversation;
52
+ if (!sourceChannel) return false;
53
+ return answerableChannels2.includes(sourceChannel) && customerChannelAddress2 !== null && accountChannelAddress2 !== null;
54
+ }
55
+
19
56
  // src/domain/evaluation-verdict.ts
20
57
  var EVALUATION_VERDICTS = ["send", "send_and_escalate", "hold"];
21
58
  function isEvaluationVerdict(value) {
@@ -71,6 +108,7 @@ function initialState() {
71
108
  verdict: null,
72
109
  reviseCount: 0,
73
110
  guardrailHits: [],
111
+ ineligibleReason: null,
74
112
  proposedActions: [],
75
113
  outcome: null
76
114
  };
@@ -179,6 +217,13 @@ var AGENT_GUARDRAILS = [
179
217
  "uncertainty_marker",
180
218
  "evaluation_missing"
181
219
  ];
220
+ var COLLISION_GUARDRAILS = [
221
+ "customer_email_missing",
222
+ "ticket_closed",
223
+ "agent_replied",
224
+ "diverged",
225
+ "run_deadline"
226
+ ];
182
227
 
183
228
  // src/guardrails/text.ts
184
229
  function normalise(s) {
@@ -235,6 +280,27 @@ function isAutomatedSenderEmail(email, senders) {
235
280
  }
236
281
 
237
282
  // src/guardrails/raw-ticket.ts
283
+ function answerableChannels(raw) {
284
+ const options = raw?.reply_options;
285
+ if (!options) return [];
286
+ return Object.entries(options).filter(([, value]) => value?.answerable === true).map(([channel]) => channel);
287
+ }
288
+ function customerChannelAddress(raw, channel) {
289
+ if (!channel) return null;
290
+ const matches = (raw?.customer?.channels ?? []).filter((entry) => entry.type === channel && !!entry.address);
291
+ const chosen = matches.find((entry) => entry.preferred) ?? matches[0];
292
+ return chosen?.address ?? null;
293
+ }
294
+ function accountChannelAddress(raw, channel) {
295
+ if (!channel) return null;
296
+ for (const message of raw?.messages ?? []) {
297
+ if (message.from_agent === true) continue;
298
+ if (message.channel !== channel) continue;
299
+ const address = message.source?.to?.[0]?.address;
300
+ if (address) return address;
301
+ }
302
+ return null;
303
+ }
238
304
  var WHATSAPP_NOTE_CHEVRON = ">";
239
305
  function isInternalNoteChannel(message) {
240
306
  return message.channel === "internal-note" || message.source?.type === "internal-note";
@@ -303,6 +369,129 @@ function guardrailBucket(hit) {
303
369
  return hit.split(":")[0] ?? hit;
304
370
  }
305
371
 
372
+ // src/graph/nodes/guardrails.ts
373
+ function collectGuardrailHits(conversation, draftText, classification, profile) {
374
+ const { params, active } = profile.guardrails;
375
+ const hits = [...channelPreGates(conversation)];
376
+ if (params.whatsappMode === "escalate_only" && conversation.sourceChannel === "whatsapp") hits.push("whatsapp");
377
+ if (params.judgemeEscalateOnly && isJudgemeConversation(conversation.subject, firstCustomerMessage(conversation))) {
378
+ hits.push("judgeme");
379
+ }
380
+ if (isAutomatedSenderEmail(conversation.customer.email, params.noreplySenders)) hits.push("noreply_sender");
381
+ if (profile.autoSend.requireHighTriage && classification?.confidence !== "high") hits.push("triage_not_high");
382
+ const contentHits = runGuardrails({
383
+ firstCustomerMessage: firstCustomerMessage(conversation) ?? "",
384
+ candidateAnswer: draftText,
385
+ hasAttachment: conversation.hasCustomerAttachment,
386
+ blocklist: params.blocklist
387
+ }).filter((hit) => active.includes(guardrailBucket(hit)));
388
+ return [...hits, ...contentHits];
389
+ }
390
+ var guardrails = async (state, deps) => {
391
+ const conversation = state.conversation;
392
+ if (!conversation || !state.draft) return { guardrailHits: [] };
393
+ return { guardrailHits: collectGuardrailHits(conversation, state.draft.text, state.classification, deps.profile) };
394
+ };
395
+
396
+ // src/adapters/conversation-mapping.ts
397
+ function isInternalNoteChannel2(message) {
398
+ return message.channel === "internal-note" || message.source?.type === "internal-note";
399
+ }
400
+ function countableMessages(messages, isWhatsapp) {
401
+ return messages.filter((m) => {
402
+ if (isInternalNoteChannel2(m)) return isWhatsappChevronNote(m, isWhatsapp);
403
+ const hasText = !!(m.body_text?.trim() || m.body_html?.trim() || m.stripped_text?.trim() || m.stripped_html?.trim());
404
+ const hasAttachment = (m.attachments?.length ?? 0) > 0;
405
+ return hasText || hasAttachment;
406
+ });
407
+ }
408
+ function snapshotConversation(raw) {
409
+ const isWhatsapp = isWhatsappTicket(raw);
410
+ const messages = countableMessages(raw.messages ?? [], isWhatsapp);
411
+ let lastAt = null;
412
+ for (const m of messages) {
413
+ if (!m.created_datetime) continue;
414
+ const at = new Date(m.created_datetime);
415
+ if (!lastAt || at > lastAt) lastAt = at;
416
+ }
417
+ return { count: messages.length, lastAt };
418
+ }
419
+ function lastAgentReplyAtOf(raw) {
420
+ const isWhatsapp = isWhatsappTicket(raw);
421
+ let latest = null;
422
+ for (const m of raw.messages ?? []) {
423
+ if (m.from_agent !== true) continue;
424
+ if (isInternalNoteChannel2(m) && !isWhatsappChevronNote(m, isWhatsapp)) continue;
425
+ if (!m.created_datetime) continue;
426
+ const at = new Date(m.created_datetime);
427
+ if (!latest || at > latest) latest = at;
428
+ }
429
+ return latest;
430
+ }
431
+ function toConversation(ref, raw, context) {
432
+ const snapshot = snapshotConversation(raw);
433
+ const messages = context.messages.filter((m) => m.role === "user" || m.role === "assistant").map((m) => ({ role: m.role, content: m.content }));
434
+ const sourceChannel = isWhatsappTicket(raw) ? "whatsapp" : raw.channel ?? null;
435
+ return {
436
+ ref,
437
+ subject: raw.subject ?? null,
438
+ messages,
439
+ customer: {
440
+ name: context.customerName ?? null,
441
+ email: context.customerEmail ?? null,
442
+ orderContext: context.customerContext ?? null
443
+ },
444
+ isClosed: isTicketClosed(raw),
445
+ lastMessageAt: snapshot.lastAt,
446
+ messageCount: snapshot.count,
447
+ lastAgentReplyAt: lastAgentReplyAtOf(raw),
448
+ answerableChannels: answerableChannels(raw),
449
+ customerChannelAddress: customerChannelAddress(raw, sourceChannel),
450
+ accountChannelAddress: accountChannelAddress(raw, sourceChannel),
451
+ hasCustomerAttachment: hasCustomerAttachment(raw),
452
+ sourceChannel
453
+ };
454
+ }
455
+
456
+ // src/guardrails/reconstruct-hold.ts
457
+ function reconstructGuardrailHits(input) {
458
+ const { generatedFrom, atSend, classification, draftText, profile, queuedAt } = input;
459
+ const stopHits = stopOptOut(generatedFrom);
460
+ if (stopHits.length > 0) return stopHits;
461
+ const preGateHits = channelPreGates(generatedFrom);
462
+ if (preGateHits.length > 0) return preGateHits;
463
+ const nodeHits = collectGuardrailHits(generatedFrom, draftText, classification, profile);
464
+ if (nodeHits.length > 0) return nodeHits;
465
+ return collisionHits(generatedFrom, atSend, queuedAt);
466
+ }
467
+ function collisionHits(generatedFrom, atSend, queuedAt) {
468
+ const mode = generatedFrom.sourceChannel === "whatsapp" ? "whatsapp_note" : "email";
469
+ if (mode === "email" && !atSend.customer.email) return ["customer_email_missing"];
470
+ if (atSend.isClosed) return ["ticket_closed"];
471
+ if (hasAgentRepliedSince(atSend.lastAgentReplyAt, queuedAt)) return ["agent_replied"];
472
+ if (hasDiverged(atSend, generatedFrom)) return ["diverged"];
473
+ return [];
474
+ }
475
+ function hasAgentRepliedSince(lastAgentReplyAt, queuedAt) {
476
+ if (!lastAgentReplyAt) return false;
477
+ if (!queuedAt) return true;
478
+ return lastAgentReplyAt.getTime() > queuedAt.getTime() - CLOCK_SKEW_MARGIN_MS;
479
+ }
480
+ function hasDiverged(atSend, generatedFrom) {
481
+ return atSend.messageCount !== generatedFrom.messageCount || (atSend.lastMessageAt?.getTime() ?? null) !== (generatedFrom.lastMessageAt?.getTime() ?? null);
482
+ }
483
+ function rawTicketFactsAt(raw, instant) {
484
+ const upTo = {
485
+ ...raw,
486
+ messages: (raw.messages ?? []).filter((message) => {
487
+ if (!message.created_datetime) return true;
488
+ return new Date(message.created_datetime).getTime() <= instant.getTime();
489
+ })
490
+ };
491
+ const { count, lastAt } = snapshotConversation(upTo);
492
+ return { messageCount: count, lastMessageAt: lastAt, lastAgentReplyAt: lastAgentReplyAtOf(upTo) };
493
+ }
494
+
306
495
  // src/guardrails/verify-reply.ts
307
496
  function verifyReply(input) {
308
497
  const { settings, triageConfidence, minConfidence, candidateAnswer } = input;
@@ -388,10 +577,18 @@ function isSendable(verdict, profile) {
388
577
  }
389
578
  function isAutoSendEligible(state, deps) {
390
579
  const isWhatsapp = state.conversation?.sourceChannel === "whatsapp";
391
- const whatsappMode = deps.profile.guardrails.params.whatsappMode;
392
- const whatsappDraftOnly = isWhatsapp && whatsappMode === "draft_only";
393
- const hasSenderForMode = isWhatsapp && whatsappMode === "auto_reply" || !!deps.profile.autoSend.senderEmail;
394
- return deps.profile.autoSend.enabled && deps.category.autoReplyEnabled && hasSenderForMode && !!state.verdict && !whatsappDraftOnly;
580
+ const whatsappDraftOnly = isWhatsapp && deps.profile.guardrails.params.whatsappMode === "draft_only";
581
+ const needsSenderEmail = publicationMode(state.conversation) === "email";
582
+ return deps.profile.autoSend.enabled && deps.category.autoReplyEnabled && (!needsSenderEmail || !!deps.profile.autoSend.senderEmail) && !!state.verdict && !whatsappDraftOnly;
583
+ }
584
+ function hasPublicationPath(state) {
585
+ return publicationMode(state.conversation) !== null;
586
+ }
587
+ function isAutoSendChannel(state, deps) {
588
+ const channel = state.conversation?.sourceChannel;
589
+ if (!channel) return false;
590
+ if (!SUPPORT_CHANNELS.includes(channel)) return true;
591
+ return deps.profile.autoSend.channels.includes(channel);
395
592
  }
396
593
  function needsRevision(verdict, profile, reviseCount) {
397
594
  if (!profile.nodes.revise) return false;
@@ -412,6 +609,7 @@ var fetchContext = async (_state, deps) => {
412
609
  };
413
610
 
414
611
  // src/graph/nodes/triage.ts
612
+ var TRIAGE_LABEL = "triage";
415
613
  var TRIAGE_SCHEMA = {
416
614
  type: "object",
417
615
  properties: {
@@ -462,12 +660,11 @@ ${message}`);
462
660
  const last = lastCustomerMessage(conversation);
463
661
  if (last && last !== message) userParts.push(`## Dernier message client
464
662
  ${last}`);
465
- const resolvedPrompt = await deps.ports.prompt.resolve(profile.prompts.triage, {
466
- categories: renderCategories(deps.categories)
467
- });
663
+ const promptVariables = { categories: renderCategories(deps.categories) };
664
+ const resolvedPrompt = await deps.ports.prompt.resolve(profile.prompts.triage, promptVariables);
468
665
  try {
469
666
  const result = await deps.ports.llm.complete({
470
- label: "triage",
667
+ label: TRIAGE_LABEL,
471
668
  // The resolved Langfuse prompt's own model config WINS over the
472
669
  // profile's fallback (I16) — see `PromptPort.resolve`'s doc.
473
670
  model: resolvedPrompt.config?.model ?? node.model,
@@ -478,7 +675,8 @@ ${last}`);
478
675
  ],
479
676
  responseSchema: TRIAGE_SCHEMA,
480
677
  signal: deps.budget.signal,
481
- promptRef: { name: resolvedPrompt.name, version: resolvedPrompt.version, resolve: false }
678
+ promptRef: { name: resolvedPrompt.name, version: resolvedPrompt.version, resolve: false },
679
+ promptVariables
482
680
  });
483
681
  deps.budget.charge("triage", result.usage, { usd: 0, pricingMissing: true });
484
682
  const parsed = JSON.parse(result.text ?? "");
@@ -500,6 +698,7 @@ ${last}`);
500
698
  };
501
699
 
502
700
  // src/graph/nodes/escalate.ts
701
+ var ESCALATION_LABEL = "escalation";
503
702
  var ESCALATION_SCHEMA = {
504
703
  type: "object",
505
704
  properties: {
@@ -525,7 +724,7 @@ ${conversation.customer.orderContext}`);
525
724
  userParts.push(`## Message \xE0 classifier
526
725
  ${message}`);
527
726
  const result = await deps.ports.llm.complete({
528
- label: "escalation",
727
+ label: ESCALATION_LABEL,
529
728
  model: resolvedPrompt.config?.model ?? node.model,
530
729
  reasoning: node.reasoning,
531
730
  messages: [
@@ -545,28 +744,6 @@ ${message}`);
545
744
  }
546
745
  };
547
746
 
548
- // src/graph/nodes/guardrails.ts
549
- var guardrails = async (state, deps) => {
550
- const { profile } = deps;
551
- const conversation = state.conversation;
552
- if (!conversation || !state.draft) return { guardrailHits: [] };
553
- const { params, active } = profile.guardrails;
554
- const hits = [...channelPreGates(conversation)];
555
- if (params.whatsappMode === "escalate_only" && conversation.sourceChannel === "whatsapp") hits.push("whatsapp");
556
- if (params.judgemeEscalateOnly && isJudgemeConversation(conversation.subject, firstCustomerMessage(conversation))) {
557
- hits.push("judgeme");
558
- }
559
- if (isAutomatedSenderEmail(conversation.customer.email, params.noreplySenders)) hits.push("noreply_sender");
560
- if (profile.autoSend.requireHighTriage && state.classification?.confidence !== "high") hits.push("triage_not_high");
561
- const contentHits = runGuardrails({
562
- firstCustomerMessage: firstCustomerMessage(conversation) ?? "",
563
- candidateAnswer: state.draft.text,
564
- hasAttachment: conversation.hasCustomerAttachment,
565
- blocklist: params.blocklist
566
- }).filter((hit) => active.includes(guardrailBucket(hit)));
567
- return { guardrailHits: [...hits, ...contentHits] };
568
- };
569
-
570
747
  // src/graph/nodes/authorize.ts
571
748
  var authorize = async (state, deps) => {
572
749
  const kind = "send_reply";
@@ -982,56 +1159,86 @@ function markdownToHtml(markdown) {
982
1159
  }
983
1160
 
984
1161
  // src/graph/nodes/act.ts
985
- function hasAgentRepliedSince(lastAgentReplyAt, queuedAt) {
1162
+ function hasAgentAnswered(fresh, queuedAt) {
1163
+ const { lastAgentReplyAt, lastMessageAt } = fresh;
986
1164
  if (!lastAgentReplyAt) return false;
1165
+ if (lastMessageAt && lastAgentReplyAt.getTime() < lastMessageAt.getTime()) return false;
987
1166
  if (!queuedAt) return true;
988
1167
  return lastAgentReplyAt.getTime() > queuedAt.getTime() - CLOCK_SKEW_MARGIN_MS;
989
1168
  }
990
- function hasDiverged(fresh, generatedFrom) {
1169
+ function hasDiverged2(fresh, generatedFrom) {
991
1170
  return fresh.messageCount !== generatedFrom.messageCount || (fresh.lastMessageAt?.getTime() ?? null) !== (generatedFrom.lastMessageAt?.getTime() ?? null);
992
1171
  }
1172
+ function refuse(hit) {
1173
+ return { guardrailHits: [hit] };
1174
+ }
993
1175
  var act = async (state, deps) => {
994
1176
  const generatedFrom = state.conversation;
995
1177
  const draft2 = state.draft;
996
1178
  const action = state.proposedActions[0];
997
1179
  if (!generatedFrom || !draft2 || !action) return {};
998
- const mode = generatedFrom.sourceChannel === "whatsapp" ? "whatsapp_note" : "email";
999
1180
  const fresh = await deps.ports.conversation.read(deps.ref);
1000
- if (mode === "email" && !fresh.customer.email) return { guardrailHits: ["customer_email_missing"] };
1001
- if (fresh.isClosed) return { guardrailHits: ["ticket_closed"] };
1002
- if (hasAgentRepliedSince(fresh.lastAgentReplyAt, deps.queuedAt ?? null)) {
1003
- return { guardrailHits: ["agent_replied"] };
1004
- }
1005
- if (hasDiverged(fresh, generatedFrom)) return { guardrailHits: ["diverged"] };
1006
- if (deps.budget.signal.aborted) return { guardrailHits: ["run_deadline"] };
1181
+ const mode = publicationMode(fresh);
1182
+ if (mode === null) return refuse("customer_email_missing");
1183
+ if (fresh.isClosed) return refuse("ticket_closed");
1184
+ if (hasAgentAnswered(fresh, deps.queuedAt ?? null)) return refuse("agent_replied");
1185
+ if (hasDiverged2(fresh, generatedFrom)) return refuse("diverged");
1186
+ if (deps.budget.signal.aborted) return refuse("run_deadline");
1007
1187
  const claimed = deps.send.mode === "claimed" ? await deps.send.claim({ draft: draft2, verdict: state.verdict }) : true;
1008
1188
  if (!claimed) return {};
1009
- const reply = mode === "email" ? {
1189
+ const reply = buildReply(mode, {
1190
+ draftText: draft2.text,
1191
+ idempotencyKey: action.idempotencyKey,
1192
+ fresh,
1193
+ senderEmail: deps.profile.autoSend.senderEmail ?? ""
1194
+ });
1195
+ const { messageId } = await deps.ports.reply.post(deps.ref, reply);
1196
+ if (deps.send.mode === "claimed") await deps.send.commit(messageId);
1197
+ return {};
1198
+ };
1199
+ function buildReply(mode, inputs) {
1200
+ const { draftText, idempotencyKey, fresh, senderEmail } = inputs;
1201
+ if (mode === "whatsapp_note") {
1202
+ return {
1203
+ mode: "whatsapp_note",
1204
+ // Raw draft text: no markdown-to-HTML rendering (§4.2/§6.4) — the note
1205
+ // carries the model's text as-is, the chevron prefix is the adapter's job.
1206
+ bodyText: draftText,
1207
+ idempotencyKey
1208
+ };
1209
+ }
1210
+ if (mode === "channel") {
1211
+ return {
1212
+ mode: "channel",
1213
+ channel: fresh.sourceChannel ?? "",
1214
+ bodyText: draftText,
1215
+ bodyHtml: markdownToHtml(draftText),
1216
+ // Guaranteed non-null by `publicationMode`, which read THIS snapshot
1217
+ // and only returns `'channel'` once both ends are known.
1218
+ toAddress: fresh.customerChannelAddress ?? "",
1219
+ fromAddress: fresh.accountChannelAddress ?? "",
1220
+ receiverName: fresh.customer.name,
1221
+ idempotencyKey
1222
+ };
1223
+ }
1224
+ return legacyEmailReply(draftText, idempotencyKey, fresh, senderEmail);
1225
+ }
1226
+ function legacyEmailReply(draftText, idempotencyKey, fresh, senderEmail) {
1227
+ return {
1010
1228
  mode: "email",
1011
- bodyText: draft2.text,
1012
- // The draft is markdown; the email channel's HTML body must be
1013
- // rendered, not the raw source.
1014
- bodyHtml: markdownToHtml(draft2.text),
1229
+ bodyText: draftText,
1230
+ // The draft is markdown; the email channel's HTML body must be rendered,
1231
+ // not the raw source.
1232
+ bodyHtml: markdownToHtml(draftText),
1015
1233
  subject: fresh.subject,
1016
- fromAddress: deps.profile.autoSend.senderEmail ?? "",
1234
+ fromAddress: senderEmail,
1017
1235
  receiverName: fresh.customer.name,
1018
- // Guaranteed non-null by the `customer_email_missing` gate above,
1019
- // in email mode — `?? ''` is belt-and-braces for the type, not a
1020
- // real fallback.
1236
+ // Guaranteed non-null by the `customer_email_missing` gate in `act` —
1237
+ // `?? ''` is belt-and-braces for the type, not a real fallback.
1021
1238
  receiverEmail: fresh.customer.email ?? "",
1022
- idempotencyKey: action.idempotencyKey
1023
- } : {
1024
- mode: "whatsapp_note",
1025
- // Raw draft text: no markdown-to-HTML rendering (§4.2/§6.4) — the
1026
- // note carries the model's text as-is, the chevron prefix is the
1027
- // adapter's job.
1028
- bodyText: draft2.text,
1029
- idempotencyKey: action.idempotencyKey
1239
+ idempotencyKey
1030
1240
  };
1031
- const { messageId } = await deps.ports.reply.post(deps.ref, reply);
1032
- if (deps.send.mode === "claimed") await deps.send.commit(messageId);
1033
- return {};
1034
- };
1241
+ }
1035
1242
 
1036
1243
  // src/graph/run-ticket.ts
1037
1244
  function merge(state, patch) {
@@ -1113,6 +1320,8 @@ async function runTicket(deps, options = {}) {
1113
1320
  if (!isAutoSendEligible(s, deps)) return finish2(s, deps, "ready");
1114
1321
  s = await step("guardrails", guardrails, s, deps);
1115
1322
  if (s.guardrailHits.length) return finish2(s, deps, "guardrail_hold");
1323
+ if (!isAutoSendChannel(s, deps)) return finish2(s, deps, "ready");
1324
+ if (!hasPublicationPath(s)) return finish2(merge(s, { ineligibleReason: "no_publication_path" }), deps, "ready");
1116
1325
  s = await step("authorize", authorize, s, deps);
1117
1326
  if (s.proposedActions.some((a) => a.decision !== "auto")) return finish2(s, deps, "awaiting_approval");
1118
1327
  s = await step("act", act, s, deps);
@@ -1424,6 +1633,8 @@ var TRIAGE_DECISION_FIELD_RUN_ID_UID = "a1e244d6-8f4f-4cd5-8794-14f6e419b64e";
1424
1633
  var TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID = "449f1960-be88-4e42-96ee-43cd90f36f4c";
1425
1634
  var TRIAGE_DECISION_FIELD_TICKET_URL_UID = "727a775a-ea93-460f-9d08-16b05424c453";
1426
1635
  var TRIAGE_DECISION_FIELD_ORIGIN_UID = "8bde8d93-7d06-4cb5-8a88-2d6db562af05";
1636
+ var TRIAGE_DECISION_FIELD_LANGFUSE_TRACE_ID_UID = "39fcbbd2-2d18-48db-b096-589f8072f854";
1637
+ var TRIAGE_DECISION_FIELD_LANGFUSE_OBSERVATION_IDS_UID = "15451c73-9f6d-4899-96ca-8fd3f5eb93db";
1427
1638
  var TRIAGE_DECISION_INDEX_TICKET_ID_UID = "20433066-e029-4faf-8033-c205cf5de0fb";
1428
1639
  var TRIAGE_DECISION_INDEX_DECIDED_AT_UID = "94040f6d-1d55-498f-8db8-abe5aed17c0a";
1429
1640
  var TRIAGE_DECISION_INDEX_ESCALATED_UID = "1c0ac4c3-9a48-4858-bbbf-0c689bbb5be5";
@@ -1458,6 +1669,9 @@ var GENERATED_RESPONSE_FIELD_SENDING_AT_UID = "2ae9634b-79bb-42d2-a949-8b0f1ac9c
1458
1669
  var GENERATED_RESPONSE_FIELD_OUTCOME_UID = "8834b334-8f91-46f7-9bb9-96b69092d0ae";
1459
1670
  var GENERATED_RESPONSE_FIELD_ORIGIN_UID = "e75034d3-ee7f-40e7-b4fe-8be7b4322bdc";
1460
1671
  var GENERATED_RESPONSE_FIELD_RUN_ID_UID = "f3448bca-9c59-418f-9509-ce0e43eb8768";
1672
+ var GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_RECONSTRUCTED_AT_UID = "b4db88de-b712-4713-9fe6-659a5563f4d2";
1673
+ var GENERATED_RESPONSE_FIELD_SOURCE_CHANNEL_UID = "0a05be96-0d3e-42f0-9153-4f2ee3cf7859";
1674
+ var GENERATED_RESPONSE_FIELD_INELIGIBLE_REASON_UID = "2fd5c90b-e8f4-480c-b040-189e4b1935fc";
1461
1675
  var GENERATED_RESPONSE_INDEX_TICKET_ID_UID = "a4534d26-8f43-4510-9c03-0b28c3d3f8e2";
1462
1676
  var GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID = "3d430166-07a2-43c2-911b-89ec25d13f64";
1463
1677
  var GENERATED_RESPONSE_INDEX_STATUS_UID = "f5c4e5d4-0810-424d-8a14-617e9555a7f3";
@@ -1892,6 +2106,22 @@ function buildTriageDecisionRecord(slug) {
1892
2106
  description: ORIGIN_DESCRIPTION,
1893
2107
  isNullable: false,
1894
2108
  defaultValue: DEFAULT_DECISION_ORIGIN
2109
+ },
2110
+ {
2111
+ universalIdentifier: TRIAGE_DECISION_FIELD_LANGFUSE_TRACE_ID_UID,
2112
+ name: "langfuseTraceId",
2113
+ type: appKit.FieldType.TEXT,
2114
+ label: "Langfuse trace id",
2115
+ description: "The Langfuse trace of the triage call. Null on a decision written before this field existed, on a follow-up pass (no classifier runs), or when the gateway traced nothing.",
2116
+ isNullable: true
2117
+ },
2118
+ {
2119
+ universalIdentifier: TRIAGE_DECISION_FIELD_LANGFUSE_OBSERVATION_IDS_UID,
2120
+ name: "langfuseObservationIds",
2121
+ type: appKit.FieldType.JSON,
2122
+ label: "Langfuse observation ids",
2123
+ description: "string[] \u2014 the triage observation, then the escalation one when that step ran. Not positional: the triage id may be absent. Null when nothing was traced.",
2124
+ isNullable: true
1895
2125
  }
1896
2126
  ],
1897
2127
  indexes: [
@@ -1974,9 +2204,26 @@ function buildGeneratedResponseRecord(slug) {
1974
2204
  name: "channel",
1975
2205
  type: appKit.FieldType.SELECT,
1976
2206
  label: "Channel",
2207
+ description: "Publication MODE, not the channel: 'whatsapp' for a note, 'email' for everything else. See sourceChannel.",
1977
2208
  isNullable: false,
1978
2209
  options: ["email", "whatsapp"]
1979
2210
  },
2211
+ {
2212
+ universalIdentifier: GENERATED_RESPONSE_FIELD_INELIGIBLE_REASON_UID,
2213
+ name: "ineligibleReason",
2214
+ type: appKit.FieldType.TEXT,
2215
+ label: "Ineligible reason",
2216
+ description: "Why auto-send was inapplicable, when the run knew a fact the settings cannot express. Today: 'no_publication_path'.",
2217
+ isNullable: true
2218
+ },
2219
+ {
2220
+ universalIdentifier: GENERATED_RESPONSE_FIELD_SOURCE_CHANNEL_UID,
2221
+ name: "sourceChannel",
2222
+ type: appKit.FieldType.TEXT,
2223
+ label: "Source channel",
2224
+ description: "The channel Gorgias reported (see SUPPORT_CHANNELS). Null on rows written before the field existed.",
2225
+ isNullable: true
2226
+ },
1980
2227
  {
1981
2228
  universalIdentifier: GENERATED_RESPONSE_FIELD_RESPONSE_TEXT_UID,
1982
2229
  name: "responseText",
@@ -2019,6 +2266,14 @@ function buildGeneratedResponseRecord(slug) {
2019
2266
  isNullable: false,
2020
2267
  defaultValue: []
2021
2268
  },
2269
+ {
2270
+ universalIdentifier: GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_RECONSTRUCTED_AT_UID,
2271
+ name: "guardrailHitsReconstructedAt",
2272
+ type: appKit.FieldType.DATE_TIME,
2273
+ label: "Guardrail hits reconstructed at",
2274
+ description: "Set only by the backfill that rebuilt a pre-28/09/2026 hold\u2019s reason from Gorgias. Null \u2014 the normal case \u2014 means the run itself recorded the hits.",
2275
+ isNullable: true
2276
+ },
2022
2277
  {
2023
2278
  universalIdentifier: GENERATED_RESPONSE_FIELD_OUTCOME_UID,
2024
2279
  name: "outcome",
@@ -2559,6 +2814,7 @@ function buildSupportKitRecords(slug) {
2559
2814
  }
2560
2815
 
2561
2816
  // src/settings/fields.ts
2817
+ var DEFAULT_STATS_TIMEZONE = "Europe/Paris";
2562
2818
  var SUPPORT_KIT_SETTINGS_FIELDS = [
2563
2819
  // Source
2564
2820
  // NO `gorgiasConnectionId`: every Gorgias call in this kit is
@@ -2596,26 +2852,20 @@ var SUPPORT_KIT_SETTINGS_FIELDS = [
2596
2852
  { key: "autoRepliedTag", type: "string", label: "Auto-replied tag", default: "wai/auto-replied" },
2597
2853
  { key: "needsReviewTag", type: "string", label: "Review-before-send tag", default: "wai/escalated" },
2598
2854
  { key: "followupTag", type: "string", label: "Followup tag", default: "wai/human-required" },
2599
- // The app's OWNERSHIP mark: applied to every ticket its triage sees, in the
2600
- // same call as the tags above (`adapters/gorgias-tags.ts`), so that a later
2601
- // pass can tell this app's tickets from a neighbouring app's on a SHARED
2602
- // Gorgias account. Every other audit tag here ships the same default in
2603
- // every app — `handledTag` is `wai/triaged` everywhere — so none of them can
2604
- // answer "whose ticket is this?". Empty by default for the same reason a
2605
- // shared default would be useless: an ownership mark two apps have in common
2606
- // marks nothing. Empty means "stamp nothing".
2607
- { key: "appScopeTag", type: "string", label: "App scope tag", default: "" },
2608
- // Follow-up webhook (spec-gorgias-followup-webhook-v1 D2)
2609
- // The tag a ticket must ALREADY carry for this app to answer a SUBSEQUENT
2610
- // customer message on it. Deliberately empty by default, twice over:
2611
- // - two support apps installed on ONE Gorgias account each receive every
2612
- // `ticket-message-created` event, so a shared default would make a
2613
- // freshly-installed app answer the other audience's tickets. Two apps of
2614
- // the same account MUST configure distinct values;
2615
- // - empty therefore means "process no follow-up message at all", which is
2616
- // both the fail-closed default and the feature's kill switch.
2617
- // Not named `followupTag`: that key is taken (`wai/human-required`).
2618
- { key: "webhookScopeTag", type: "string", label: "Webhook scope tag", default: "" },
2855
+ // The app's ticket tag — ONE tag, three readers:
2856
+ // - the triage stamps it on every ticket it sees, in the same call as the
2857
+ // tags above (`adapters/gorgias-tags.ts`);
2858
+ // - the follow-up webhook answers a SUBSEQUENT customer message only on a
2859
+ // ticket that carries it (`functions/followup-gates.ts`): two support apps
2860
+ // installed on ONE Gorgias account each receive every
2861
+ // `ticket-message-created` event, and this tag is what separates them;
2862
+ // - the Gorgias extension picks this app's default agent on a ticket that
2863
+ // carries it (`functions/ext-models.ts`).
2864
+ // Every other audit tag ships the same default in every app — `handledTag`
2865
+ // is `wai/triaged` everywhere — so none of them can answer "whose ticket is
2866
+ // this?". No usable default for the same reason: a mark two apps have in
2867
+ // common marks nothing. `validateSettings` refuses to run until it is set.
2868
+ { key: "appScopeTag", type: "string", label: "App ticket tag", default: "" },
2619
2869
  // Sending
2620
2870
  { key: "autoSendEnabled", type: "boolean", label: "Auto-send enabled", default: false },
2621
2871
  { key: "senderEmail", type: "string", label: "Sender email", default: "" },
@@ -2632,6 +2882,10 @@ var SUPPORT_KIT_SETTINGS_FIELDS = [
2632
2882
  options: [...WHATSAPP_MODES],
2633
2883
  default: DEFAULT_WHATSAPP_MODE
2634
2884
  },
2885
+ // An ALLOWLIST: a channel absent from it never auto-sends. Defaulted to the
2886
+ // two that had a publication path before the setting existed, so an app
2887
+ // that never touches it keeps behaving exactly as it did.
2888
+ { key: "autoSendChannels", type: "json", label: "Auto-send channels", default: [...DEFAULT_AUTO_SEND_CHANNELS] },
2635
2889
  // 14_400 minutes = 10 days, the legacy `fast_response_ttl_minutes` default
2636
2890
  // (`backoffice/src/models/AppSettings.ts`) — copied deliberately, not
2637
2891
  // chosen here. A pre-generated draft is only worth anything while the
@@ -2670,7 +2924,7 @@ var SUPPORT_KIT_SETTINGS_FIELDS = [
2670
2924
  // one-field deviation from §3.6, recorded for the spec owner.
2671
2925
  { key: "renameFrom", type: "string", label: "Rename \u2014 subject pattern to match", default: "" },
2672
2926
  { key: "renameTo", type: "string", label: "Rename \u2014 replacement subject", default: "" },
2673
- { key: "statsTimezone", type: "string", label: "Stats timezone (IANA)", default: "Europe/Paris" }
2927
+ { key: "statsTimezone", type: "string", label: "Stats timezone (IANA)", default: DEFAULT_STATS_TIMEZONE }
2674
2928
  ];
2675
2929
 
2676
2930
  // src/settings/validate.ts
@@ -2682,6 +2936,12 @@ function validateSettings(settings) {
2682
2936
  message: "sourceViewId is required \u2014 pick the Gorgias view this app owns."
2683
2937
  });
2684
2938
  }
2939
+ if (!isNonEmptyString(settings.appScopeTag) || settings.appScopeTag.trim() === "") {
2940
+ issues.push({
2941
+ key: "appScopeTag",
2942
+ message: "appScopeTag is required \u2014 set the tag that marks this app's tickets."
2943
+ });
2944
+ }
2685
2945
  if (!isConfiguredNode(settings.nodes)) {
2686
2946
  issues.push({
2687
2947
  key: "nodes",
@@ -2712,8 +2972,8 @@ var STEPS_REQUIRING_PROMPT = ["triage", "escalate", "evaluate"];
2712
2972
  function stepsMissingPrompt(nodes) {
2713
2973
  if (typeof nodes !== "object" || nodes === null) return [];
2714
2974
  const byStep = nodes;
2715
- return STEPS_REQUIRING_PROMPT.filter((step2) => {
2716
- const node = byStep[step2];
2975
+ return STEPS_REQUIRING_PROMPT.filter((step3) => {
2976
+ const node = byStep[step3];
2717
2977
  if (typeof node !== "object" || node === null) return false;
2718
2978
  return !isNonEmptyString(promptNameOf(node));
2719
2979
  });
@@ -2734,23 +2994,22 @@ var AUDIT_TAG_KEYS = ["unknownTag", "handledTag", "escalationTag", "autoRepliedT
2734
2994
  function settingsWarnings(settings) {
2735
2995
  const warnings = [];
2736
2996
  const appScopeTag = trimmed(settings.appScopeTag);
2737
- const webhookScopeTag = trimmed(settings.webhookScopeTag);
2738
2997
  const collidesWith = (keys) => appScopeTag ? keys.filter((key) => trimmed(settings[key]) === appScopeTag) : [];
2739
2998
  if (collidesWith(HUMAN_TAKEOVER_KEYS).length > 0) {
2740
2999
  warnings.push({
2741
3000
  key: "appScopeTagVetoesFollowups",
2742
- message: "Le tag d\u2019appartenance est l\u2019un des tags de reprise humaine (escalade, relecture, suivi) : le webhook de suivi consid\xE9rera que chaque ticket tri\xE9 a \xE9t\xE9 repris par un humain et ne r\xE9pondra plus \xE0 aucun message suivant."
3001
+ message: "Le tag des tickets de l\u2019application est l\u2019un des tags de reprise humaine (escalade, relecture, suivi) : le webhook de suivi consid\xE9rera que chaque ticket tri\xE9 a \xE9t\xE9 repris par un humain et ne r\xE9pondra plus \xE0 aucun message suivant."
2743
3002
  });
2744
3003
  } else if (collidesWith(AUDIT_TAG_KEYS).length > 0) {
2745
3004
  warnings.push({
2746
3005
  key: "appScopeTagCollision",
2747
- message: "Le tag d\u2019appartenance est l\u2019un des autres tags d\u2019audit, que toutes les apps posent avec la m\xEAme valeur par d\xE9faut : il ne distingue donc pas cette app d\u2019une autre install\xE9e sur le m\xEAme compte Gorgias."
3006
+ message: "Le tag des tickets de l\u2019application est l\u2019un des autres tags d\u2019audit, que toutes les apps posent avec la m\xEAme valeur par d\xE9faut : il ne distingue donc pas cette app d\u2019une autre install\xE9e sur le m\xEAme compte Gorgias."
2748
3007
  });
2749
3008
  }
2750
- if (appScopeTag && webhookScopeTag && appScopeTag !== webhookScopeTag) {
3009
+ if (settings.autoSendEnabled === true && Array.isArray(settings.autoSendChannels) && settings.autoSendChannels.length === 0) {
2751
3010
  warnings.push({
2752
- key: "scopeTagMismatch",
2753
- message: "Le tag de p\xE9rim\xE8tre du webhook de suivi n\u2019est pas celui que cette app pose sur ses tickets : le webhook ne r\xE9pondra sur aucun ticket tri\xE9 ici."
3011
+ key: "noAutoSendChannels",
3012
+ message: "L\u2019envoi automatique est actif mais aucun canal n\u2019est coch\xE9 : aucune r\xE9ponse ne peut partir. Cochez au moins un canal, ou coupez l\u2019envoi automatique."
2754
3013
  });
2755
3014
  }
2756
3015
  return warnings;
@@ -2838,7 +3097,11 @@ function settingsToProfile(settings, prompts) {
2838
3097
  // The auto-send floor is the evaluation floor: a second, independent
2839
3098
  // threshold would be a silent way to send below the one an operator set.
2840
3099
  minConfidence: evaluate2?.minConfidence ?? DEFAULT_MIN_CONFIDENCE,
2841
- requireHighTriage: settings.requireHighTriageConfidence
3100
+ requireHighTriage: settings.requireHighTriageConfidence,
3101
+ // Defaulted rather than required: `SupportKitSettings` describes what a
3102
+ // SettingsPage writes, and an app deployed before this field existed
3103
+ // has no value stored for it.
3104
+ channels: [...settings.autoSendChannels ?? DEFAULT_AUTO_SEND_CHANNELS]
2842
3105
  },
2843
3106
  rename: settings.renameEnabled ? { enabled: true, from: settings.renameFrom, to: settings.renameTo } : null,
2844
3107
  // Locks and run stamps are per-run state: they live in the
@@ -2878,61 +3141,8 @@ function identifierFor(config, key) {
2878
3141
  }
2879
3142
  return id;
2880
3143
  }
2881
-
2882
- // src/adapters/conversation-mapping.ts
2883
- function isInternalNoteChannel2(message) {
2884
- return message.channel === "internal-note" || message.source?.type === "internal-note";
2885
- }
2886
- function countableMessages(messages, isWhatsapp) {
2887
- return messages.filter((m) => {
2888
- if (isInternalNoteChannel2(m)) return isWhatsappChevronNote(m, isWhatsapp);
2889
- const hasText = !!(m.body_text?.trim() || m.body_html?.trim() || m.stripped_text?.trim() || m.stripped_html?.trim());
2890
- const hasAttachment = (m.attachments?.length ?? 0) > 0;
2891
- return hasText || hasAttachment;
2892
- });
2893
- }
2894
- function snapshotConversation(raw) {
2895
- const isWhatsapp = isWhatsappTicket(raw);
2896
- const messages = countableMessages(raw.messages ?? [], isWhatsapp);
2897
- let lastAt = null;
2898
- for (const m of messages) {
2899
- if (!m.created_datetime) continue;
2900
- const at = new Date(m.created_datetime);
2901
- if (!lastAt || at > lastAt) lastAt = at;
2902
- }
2903
- return { count: messages.length, lastAt };
2904
- }
2905
- function lastAgentReplyAtOf(raw) {
2906
- const isWhatsapp = isWhatsappTicket(raw);
2907
- let latest = null;
2908
- for (const m of raw.messages ?? []) {
2909
- if (m.from_agent !== true) continue;
2910
- if (isInternalNoteChannel2(m) && !isWhatsappChevronNote(m, isWhatsapp)) continue;
2911
- if (!m.created_datetime) continue;
2912
- const at = new Date(m.created_datetime);
2913
- if (!latest || at > latest) latest = at;
2914
- }
2915
- return latest;
2916
- }
2917
- function toConversation(ref, raw, context) {
2918
- const snapshot = snapshotConversation(raw);
2919
- const messages = context.messages.filter((m) => m.role === "user" || m.role === "assistant").map((m) => ({ role: m.role, content: m.content }));
2920
- return {
2921
- ref,
2922
- subject: raw.subject ?? null,
2923
- messages,
2924
- customer: {
2925
- name: context.customerName ?? null,
2926
- email: context.customerEmail ?? null,
2927
- orderContext: context.customerContext ?? null
2928
- },
2929
- isClosed: isTicketClosed(raw),
2930
- lastMessageAt: snapshot.lastAt,
2931
- messageCount: snapshot.count,
2932
- lastAgentReplyAt: lastAgentReplyAtOf(raw),
2933
- hasCustomerAttachment: hasCustomerAttachment(raw),
2934
- sourceChannel: isWhatsappTicket(raw) ? "whatsapp" : raw.channel ?? null
2935
- };
3144
+ function mcpToolIdentifierFor(config, key) {
3145
+ return config.identifiers[key] ?? deriveUid(`${config.slug}:function:${key}`);
2936
3146
  }
2937
3147
 
2938
3148
  // src/adapters/gorgias-tags.ts
@@ -2994,6 +3204,18 @@ function createGorgiasReplyPort(api) {
2994
3204
  });
2995
3205
  return { messageId: result2.messageId };
2996
3206
  }
3207
+ if (reply.mode === "channel") {
3208
+ const result2 = await api.integrations.run("gorgias", "replyOnChannel", {
3209
+ ticketId: ref.id,
3210
+ channel: reply.channel,
3211
+ bodyHtml: reply.bodyHtml,
3212
+ bodyText: reply.bodyText,
3213
+ toAddress: reply.toAddress,
3214
+ fromAddress: reply.fromAddress,
3215
+ ...reply.receiverName !== null ? { receiverName: reply.receiverName } : {}
3216
+ });
3217
+ return { messageId: result2.messageId };
3218
+ }
2997
3219
  const result = await api.integrations.run("gorgias", "postWhatsappNote", {
2998
3220
  ticketId: ref.id,
2999
3221
  text: reply.bodyText
@@ -3057,6 +3279,7 @@ function createPlatformLlmPort(api, trace) {
3057
3279
  // its own to carry the new field; it already carries whatever shape
3058
3280
  // `CompletionRequest.promptRef` has.
3059
3281
  ...req.promptRef ? { promptRef: req.promptRef } : {},
3282
+ ...req.promptVariables ? { promptVariables: req.promptVariables } : {},
3060
3283
  ...runTrace ? { trace: runTrace } : {}
3061
3284
  });
3062
3285
  return {
@@ -3200,15 +3423,23 @@ function createRecordingLlmPort(llm) {
3200
3423
  };
3201
3424
  }
3202
3425
  var DEFAULT_MAX_TOOL_CALLS2 = 5;
3203
- async function getOptional(ctx, objectKey, id) {
3426
+ async function getOptional(api, objectKey, id) {
3204
3427
  if (!id) return null;
3205
3428
  try {
3206
- return await ctx.api.get(objectKey, id);
3429
+ return await api.get(objectKey, id);
3207
3430
  } catch (err) {
3208
3431
  if (err instanceof appKit.AppApiError && err.status === 404) return null;
3209
3432
  throw err;
3210
3433
  }
3211
3434
  }
3435
+ async function getSettingsOrNull(api) {
3436
+ try {
3437
+ return await api.settings.get();
3438
+ } catch (err) {
3439
+ if (err instanceof appKit.AppApiError) return null;
3440
+ throw err;
3441
+ }
3442
+ }
3212
3443
  function buildTicketPorts(ctx, trace) {
3213
3444
  return {
3214
3445
  conversation: createGorgiasConversationPort(ctx.api),
@@ -3231,15 +3462,15 @@ function isEligibleForGeneratedResponse(profile, classification, escalated, cate
3231
3462
  }
3232
3463
 
3233
3464
  // src/functions/no-tool-context.ts
3234
- function refuse(name) {
3465
+ function refuse2(name) {
3235
3466
  throw new Error(`no-tool-context: "${name}" called, but this pipeline configures no tools (profile.tools is always []).`);
3236
3467
  }
3237
3468
  function createNoToolContext() {
3238
3469
  return {
3239
- getOrder: () => refuse("getOrder"),
3240
- getTracking: () => refuse("getTracking"),
3241
- searchKnowledge: () => refuse("searchKnowledge"),
3242
- findSimilarTickets: () => refuse("findSimilarTickets")
3470
+ getOrder: () => refuse2("getOrder"),
3471
+ getTracking: () => refuse2("getTracking"),
3472
+ searchKnowledge: () => refuse2("searchKnowledge"),
3473
+ findSimilarTickets: () => refuse2("findSimilarTickets")
3243
3474
  };
3244
3475
  }
3245
3476
 
@@ -3384,6 +3615,30 @@ function toCategoryGroup(record) {
3384
3615
  order: data.order ?? 0
3385
3616
  };
3386
3617
  }
3618
+ function toTriageDecision(record) {
3619
+ const data = record.data;
3620
+ return {
3621
+ id: record.id,
3622
+ ticketId: data.ticketId ?? "",
3623
+ ticketUrl: data.ticketUrl ?? null,
3624
+ decidedAt: data.decidedAt ?? null,
3625
+ categoryId: data.categoryId ?? null,
3626
+ tag: data.tag ?? null,
3627
+ confidence: data.confidence ?? null,
3628
+ reasoning: data.reasoning ?? null,
3629
+ conversationOver: data.conversationOver ?? false,
3630
+ escalated: data.escalated ?? false,
3631
+ escalationConfidence: data.escalationConfidence ?? null,
3632
+ escalationReasoning: data.escalationReasoning ?? null,
3633
+ status: data.status ?? null,
3634
+ error: data.error ?? null,
3635
+ runId: data.runId ?? null,
3636
+ subjectRenamed: data.subjectRenamed ?? false,
3637
+ origin: toDecisionOrigin(data.origin),
3638
+ langfuseTraceId: data.langfuseTraceId ?? null,
3639
+ langfuseObservationIds: Array.isArray(data.langfuseObservationIds) ? data.langfuseObservationIds.filter((id) => typeof id === "string" && id !== "") : []
3640
+ };
3641
+ }
3387
3642
  function toVerdict(raw) {
3388
3643
  if (raw === null || typeof raw !== "object") return null;
3389
3644
  const data = raw;
@@ -3393,6 +3648,11 @@ function toVerdict(raw) {
3393
3648
  const status = data.status === "success" || data.status === "error" ? data.status : "error";
3394
3649
  return { verdict, confidence, reason, status };
3395
3650
  }
3651
+ function toEvaluationObservationId(raw) {
3652
+ if (raw === null || typeof raw !== "object") return null;
3653
+ const observationId = raw.observationId;
3654
+ return typeof observationId === "string" && observationId !== "" ? observationId : null;
3655
+ }
3396
3656
  function toGeneratedResponse(record) {
3397
3657
  const data = record.data;
3398
3658
  return {
@@ -3415,10 +3675,14 @@ function toGeneratedResponse(record) {
3415
3675
  tracedInput: Array.isArray(data.tracedInput) ? data.tracedInput : [],
3416
3676
  sources: Array.isArray(data.sources) ? data.sources : [],
3417
3677
  verdict: toVerdict(data.verdict),
3678
+ evaluationObservationId: toEvaluationObservationId(data.verdict),
3418
3679
  guardrailHits: data.guardrailHits ?? [],
3680
+ guardrailHitsReconstructedAt: data.guardrailHitsReconstructedAt ?? null,
3419
3681
  outcome: isOutcome(data.outcome) ? data.outcome : null,
3420
3682
  triageDecisionId: data.triageDecisionId ?? null,
3421
3683
  channel: data.channel ?? null,
3684
+ sourceChannel: data.sourceChannel ?? null,
3685
+ ineligibleReason: data.ineligibleReason ?? null,
3422
3686
  autoSendDecision: data.autoSendDecision ?? null,
3423
3687
  sentAt: data.sentAt ?? null,
3424
3688
  sentMessageId: data.sentMessageId ?? null,
@@ -3426,12 +3690,81 @@ function toGeneratedResponse(record) {
3426
3690
  origin: toDecisionOrigin(data.origin)
3427
3691
  };
3428
3692
  }
3429
- async function listCategories(api) {
3430
- const page = await api.list("category", { limit: 500 });
3431
- return page.items.map(toCategory);
3693
+ function toResponseComparison(record) {
3694
+ const data = record.data;
3695
+ return {
3696
+ id: record.id,
3697
+ generatedText: data.generatedText ?? null,
3698
+ sentText: data.sentText ?? "",
3699
+ capturedAt: data.capturedAt ?? "",
3700
+ ticketId: data.ticketId ?? null,
3701
+ ticketUrl: data.ticketUrl ?? "",
3702
+ agentId: data.agentId ?? null,
3703
+ langfuseTraceId: data.langfuseTraceId ?? null,
3704
+ langfuseObservationId: data.langfuseObservationId ?? null,
3705
+ promptName: data.promptName ?? null,
3706
+ promptVersion: data.promptVersion ?? null,
3707
+ conversationMessages: data.conversationMessages ?? [],
3708
+ diff: data.diff ?? null
3709
+ };
3432
3710
  }
3433
- function findCategoryByTag(categories, tag) {
3434
- return categories.find((c) => c.tagName === tag) ?? null;
3711
+ var CATEGORY_PAGE_SIZE = 500;
3712
+ var AGENT_PAGE_SIZE = 500;
3713
+ function compareByGroupThenCategory(a, b) {
3714
+ if (a.groupOrder !== b.groupOrder) return a.groupOrder < b.groupOrder ? -1 : 1;
3715
+ return a.category.order - b.category.order || a.category.name.localeCompare(b.category.name);
3716
+ }
3717
+ async function listAgents(api) {
3718
+ const page = await api.list("agent", { limit: AGENT_PAGE_SIZE });
3719
+ return page.items.map(toAgent);
3720
+ }
3721
+ async function listCategories(api) {
3722
+ const page = await api.list("category", { limit: CATEGORY_PAGE_SIZE });
3723
+ return page.items.map(toCategory);
3724
+ }
3725
+ var NEWEST_DECISION_FIRST = JSON.stringify([{ field: "decidedAt", direction: "desc" }]);
3726
+ var NEWEST_RESPONSE_FIRST = JSON.stringify([{ field: "generatedAt", direction: "desc" }]);
3727
+ var ANSWERS_ONLY = { status: { neq: "test_draft" } };
3728
+ async function listTicketResponses(api, ticketId, limit) {
3729
+ const page = await api.list("generated-response", {
3730
+ filter: { ticketId, ...ANSWERS_ONLY },
3731
+ sort: NEWEST_RESPONSE_FIRST,
3732
+ limit
3733
+ });
3734
+ return page.items.map(toGeneratedResponse);
3735
+ }
3736
+ async function latestResponsesByTicket(api, ticketIds) {
3737
+ const newest = await newestPerTicket(api, {
3738
+ objectKey: "generated-response",
3739
+ ticketIds,
3740
+ filter: ANSWERS_ONLY,
3741
+ sort: NEWEST_RESPONSE_FIRST
3742
+ });
3743
+ return new Map([...newest].map(([ticketId, record]) => [ticketId, toGeneratedResponse(record)]));
3744
+ }
3745
+ var NEWEST_PER_TICKET_READ_SIZE = 200;
3746
+ async function newestPerTicket(api, { objectKey, ticketIds, filter, sort }) {
3747
+ const wanted = [...new Set(ticketIds)];
3748
+ const newest = /* @__PURE__ */ new Map();
3749
+ if (wanted.length === 0) return newest;
3750
+ let cursor = null;
3751
+ do {
3752
+ const page = await api.list(objectKey, {
3753
+ filter: { ...filter, ticketId: { in: wanted } },
3754
+ sort,
3755
+ limit: NEWEST_PER_TICKET_READ_SIZE,
3756
+ ...cursor === null ? {} : { cursor }
3757
+ });
3758
+ for (const record of page.items) {
3759
+ const ticketId = String(record.data["ticketId"]);
3760
+ if (!newest.has(ticketId)) newest.set(ticketId, record);
3761
+ }
3762
+ cursor = page.nextCursor;
3763
+ } while (cursor !== null && newest.size < wanted.length);
3764
+ return newest;
3765
+ }
3766
+ function findCategoryByTag(categories, tag) {
3767
+ return categories.find((c) => c.tagName === tag) ?? null;
3435
3768
  }
3436
3769
  function toCategoryReferential(categories) {
3437
3770
  return categories.map((c) => ({
@@ -3467,20 +3800,33 @@ function draftRebinder(api, categories, config) {
3467
3800
  };
3468
3801
  }
3469
3802
  function buildPromptsTable(config, draft2, nodes) {
3470
- const DEFAULT_LABEL = "production";
3471
- const refFor = (node, derivedName, fallback2) => ({
3472
- name: node?.prompt?.name ?? derivedName,
3473
- label: node?.prompt?.label ?? DEFAULT_LABEL,
3474
- ...fallback2 ? { fallback: fallback2 } : {}
3475
- });
3476
3803
  const prompts = config.defaults?.prompts;
3477
3804
  return {
3478
- triage: refFor(nodes.triage, resolvePromptName("triage", config), prompts?.triage),
3479
- escalate: refFor(nodes.escalate, resolvePromptName("escalation", config), prompts?.escalation),
3480
- evaluate: refFor(nodes.evaluate, resolvePromptName("evaluation", config), prompts?.evaluation),
3805
+ triage: promptRefFor(nodes.triage, resolvePromptName("triage", config), prompts?.triage),
3806
+ escalate: promptRefFor(
3807
+ nodes.escalate,
3808
+ resolvePromptName("escalation", config),
3809
+ prompts?.escalation
3810
+ ),
3811
+ evaluate: promptRefFor(
3812
+ nodes.evaluate,
3813
+ resolvePromptName("evaluation", config),
3814
+ prompts?.evaluation
3815
+ ),
3481
3816
  draft: draft2
3482
3817
  };
3483
3818
  }
3819
+ function promptRefFor(node, derivedName, fallback2) {
3820
+ return {
3821
+ name: node?.prompt?.name ?? derivedName,
3822
+ label: node?.prompt?.label ?? "production",
3823
+ ...fallback2 ? { fallback: fallback2 } : {}
3824
+ };
3825
+ }
3826
+ async function readCategoryNames(api) {
3827
+ const categories = await listCategories(api);
3828
+ return new Map(categories.map((category) => [category.id, category.name]));
3829
+ }
3484
3830
 
3485
3831
  // src/functions/process-response.ts
3486
3832
  function autoReplyEnabledFor(origin, category) {
@@ -3528,7 +3874,7 @@ async function finalizeNonSent(ctx, id, ticketId, toStatus, extra) {
3528
3874
  }
3529
3875
  }
3530
3876
  async function respondToPendingResponse(ctx, config, recordId, options = {}) {
3531
- const record = await getOptional(ctx, "generated-response", recordId);
3877
+ const record = await getOptional(ctx.api, "generated-response", recordId);
3532
3878
  if (!record) {
3533
3879
  ctx.logger.info(`respond: generated-response ${recordId} no longer exists, skipping`);
3534
3880
  return null;
@@ -3545,7 +3891,7 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
3545
3891
  }
3546
3892
  const ticketId = data.ticketId;
3547
3893
  const ref = { id: ticketId, channel: "gorgias" };
3548
- const decision = await getOptional(ctx, "triage-decision", data.triageDecisionId ?? null);
3894
+ const decision = await getOptional(ctx.api, "triage-decision", data.triageDecisionId ?? null);
3549
3895
  if (!decision) {
3550
3896
  ctx.logger.error(`respond: generated-response ${recordId} has no resolvable triage-decision, marking failed`);
3551
3897
  await finalizeNonSent(ctx, recordId, ticketId, "failed", { error: "triage-decision not found" });
@@ -3553,10 +3899,10 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
3553
3899
  }
3554
3900
  const classification = classificationFromDecision(decision);
3555
3901
  const escalated = decision.data.escalated === true;
3556
- const categoryRecord = await getOptional(ctx, "category", data.categoryId ?? null);
3902
+ const categoryRecord = await getOptional(ctx.api, "category", data.categoryId ?? null);
3557
3903
  const category = categoryRecord ? toCategory(categoryRecord) : null;
3558
3904
  const origin = toDecisionOrigin(data.origin);
3559
- const agentRecord2 = data.agentId ? await getOptional(ctx, "agent", data.agentId) : null;
3905
+ const agentRecord2 = data.agentId ? await getOptional(ctx.api, "agent", data.agentId) : null;
3560
3906
  const agent = agentRecord2 ? toAgent(agentRecord2) : await resolveDraftAgent(ctx.api, null);
3561
3907
  const profile = applyFollowupSendPolicy(
3562
3908
  settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes)),
@@ -3620,6 +3966,14 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
3620
3966
  // `outcome: 'sent'` on a `ready` row is exactly what "would have been
3621
3967
  // sent, wasn't" looks like, and the timeline reads it that way.
3622
3968
  outcome: result.outcome,
3969
+ // WHICH guardrail held the reply, not just that one did. Without this the
3970
+ // record keeps the `[]` its creation wrote and the timeline can only say
3971
+ // "un garde-fou a bloqué l'envoi" — the reason has to be reconstructed
3972
+ // from Gorgias by hand, which is exactly what it cost before this line.
3973
+ guardrailHits: result.guardrailHits,
3974
+ // The one "not sent" reason the timeline cannot re-derive from today's
3975
+ // settings: whether the contact had an address six weeks ago.
3976
+ ineligibleReason: result.ineligibleReason,
3623
3977
  responseText: result.draft?.text ?? null,
3624
3978
  sources: result.draft?.sources ?? [],
3625
3979
  // The rendered system prompt and the customer's own turns, which nothing
@@ -3714,6 +4068,39 @@ function ticketUrlFor(base, ticketId) {
3714
4068
  return base ? `${base}/${encodeURIComponent(ticketId)}` : null;
3715
4069
  }
3716
4070
 
4071
+ // src/functions/ticket-trace.ts
4072
+ function buildTicketTrace({ slug, ticketId, ticketUrl }) {
4073
+ return {
4074
+ sessionId: ticketId,
4075
+ tags: [`app:${slug}`],
4076
+ metadata: {
4077
+ ticket_id: ticketId,
4078
+ ...ticketUrl ? { conversation_url: ticketUrl } : {},
4079
+ origin: "triage"
4080
+ }
4081
+ };
4082
+ }
4083
+ function recordTriageTraces(llm) {
4084
+ const results = /* @__PURE__ */ new Map();
4085
+ return {
4086
+ llm: {
4087
+ async complete(req) {
4088
+ const result = await llm.complete(req);
4089
+ results.set(req.label, result);
4090
+ return result;
4091
+ }
4092
+ },
4093
+ fields() {
4094
+ const traceId = results.get(TRIAGE_LABEL)?.traceId;
4095
+ const observationIds = [TRIAGE_LABEL, ESCALATION_LABEL].map((label) => results.get(label)?.observationId).filter((id) => Boolean(id));
4096
+ return {
4097
+ ...traceId ? { langfuseTraceId: traceId } : {},
4098
+ ...observationIds.length > 0 ? { langfuseObservationIds: observationIds } : {}
4099
+ };
4100
+ }
4101
+ };
4102
+ }
4103
+
3717
4104
  // src/functions/triage-tick.ts
3718
4105
  function buildTriageTickFunctionDef(config) {
3719
4106
  return {
@@ -3893,11 +4280,14 @@ async function processOneTicket(ctx, ref, deps) {
3893
4280
  }
3894
4281
  }
3895
4282
  const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS2 });
4283
+ const ticketUrl = ticketUrlFor(ticketUrlBase, ref.id);
4284
+ const ticketTrace = buildTicketTrace({ slug: config.slug, ticketId: ref.id, ticketUrl });
4285
+ const traces = recordTriageTraces(createPlatformLlmPort(ctx.api, ticketTrace));
3896
4286
  const state = await runTicket(
3897
4287
  {
3898
4288
  ref,
3899
4289
  profile,
3900
- ports: { ...ports },
4290
+ ports: { ...ports, llm: traces.llm },
3901
4291
  toolContext: createNoToolContext(),
3902
4292
  budget,
3903
4293
  // Unknown until triage runs — no node reached in the `until:'triage'`
@@ -3915,7 +4305,7 @@ async function processOneTicket(ctx, ref, deps) {
3915
4305
  const category = findCategoryByTag(categories, classification.category);
3916
4306
  const decision = await ctx.api.create("triage-decision", {
3917
4307
  ticketId: ref.id,
3918
- ticketUrl: ticketUrlFor(ticketUrlBase, ref.id),
4308
+ ticketUrl,
3919
4309
  decidedAt: ports.clock.now(),
3920
4310
  categoryId: category?.id ?? null,
3921
4311
  tag: classification.category,
@@ -3926,7 +4316,8 @@ async function processOneTicket(ctx, ref, deps) {
3926
4316
  status: "ok",
3927
4317
  runId,
3928
4318
  subjectRenamed,
3929
- origin: "triage"
4319
+ origin: "triage",
4320
+ ...traces.fields()
3930
4321
  });
3931
4322
  await ports.state.record(ref, classification, profile.audit);
3932
4323
  if (state.escalated) await flagEscalation(ctx, ref, profile.audit.escalationTag, ports);
@@ -3934,6 +4325,7 @@ async function processOneTicket(ctx, ref, deps) {
3934
4325
  const draftAgent = await resolveDraftAgent(ctx.api, category?.agentId ?? null);
3935
4326
  const conversation = state.conversation;
3936
4327
  const channel = conversation?.sourceChannel === "whatsapp" ? "whatsapp" : "email";
4328
+ const sourceChannel = conversation?.sourceChannel ?? null;
3937
4329
  const generatedAt = ports.clock.now();
3938
4330
  const expiresAt = new Date(generatedAt.getTime() + profile.schedule.fastResponseTtlMinutes * 6e4);
3939
4331
  let created;
@@ -3946,6 +4338,7 @@ async function processOneTicket(ctx, ref, deps) {
3946
4338
  categoryId: category?.id ?? null,
3947
4339
  agentId: draftAgent?.id ?? null,
3948
4340
  channel,
4341
+ sourceChannel,
3949
4342
  generatedAt,
3950
4343
  expiresAt,
3951
4344
  sources: [],
@@ -4082,7 +4475,7 @@ async function handleApprovalHandler(ctx, config) {
4082
4475
  ctx.logger.debug(`handle-approval: key "${payload.key}" is not a generated-response approval, ignoring`);
4083
4476
  return;
4084
4477
  }
4085
- const record = await getOptional(ctx, "generated-response", id);
4478
+ const record = await getOptional(ctx.api, "generated-response", id);
4086
4479
  if (!record) {
4087
4480
  ctx.logger.info(`handle-approval: generated-response ${id} no longer exists, skipping`);
4088
4481
  return;
@@ -4138,6 +4531,9 @@ async function handleApprovalHandler(ctx, config) {
4138
4531
  lastMessageAt: data.generatedLastMessageAt ? new Date(data.generatedLastMessageAt) : null,
4139
4532
  messageCount: data.generatedMessageCount ?? 0,
4140
4533
  lastAgentReplyAt: null,
4534
+ answerableChannels: [],
4535
+ customerChannelAddress: null,
4536
+ accountChannelAddress: null,
4141
4537
  hasCustomerAttachment: false,
4142
4538
  sourceChannel: data.channel
4143
4539
  };
@@ -4186,7 +4582,7 @@ async function handleApprovalHandler(ctx, config) {
4186
4582
  return;
4187
4583
  }
4188
4584
  try {
4189
- await ctx.api.update("generated-response", id, { autoSendDecision: "hold" }, { ifMatch: { status: "ready" } });
4585
+ await ctx.api.update("generated-response", id, { autoSendDecision: "hold", guardrailHits }, { ifMatch: { status: "ready" } });
4190
4586
  } catch (err) {
4191
4587
  if (!(err instanceof appKit.AppApiError && err.status === 409)) throw err;
4192
4588
  }
@@ -4243,6 +4639,18 @@ var SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID = "2f5d6cbb-1c69-4a76-9d8f-
4243
4639
  var INVALIDATE_RESPONSE_INPUT_GENERATED_RESPONSE_ID_UID = "9748baf5-97be-4a22-940d-46ef2f16a175";
4244
4640
  var TEST_GORGIAS_WEBHOOK_INPUT_TICKET_ID_UID = "2cfcbfc1-77f1-4081-8fba-5f3a51c29e62";
4245
4641
  var TEST_GORGIAS_WEBHOOK_INPUT_MODE_UID = "e75c5ec9-1205-492f-87df-a84ec12753f8";
4642
+ var TICKET_STATS_INPUT_FROM_UID = "15f48662-43f1-4a94-9e77-6aa34c2c8e41";
4643
+ var TICKET_STATS_INPUT_TO_UID = "2a50ec38-8d95-4a69-bc55-c21322088fe9";
4644
+ var TICKET_STATS_INPUT_COMPARE_TO_PREVIOUS_UID = "cb007f80-f00a-4f8f-a46c-61010a6c0609";
4645
+ var LIST_TICKETS_INPUT_FROM_UID = "dfbc9f3a-4ac9-4587-a9f1-47ea3fbb1d88";
4646
+ var LIST_TICKETS_INPUT_TO_UID = "c51c82ee-7d65-4b49-aef1-2a82983fa4eb";
4647
+ var LIST_TICKETS_INPUT_CATEGORY_ID_UID = "418e65f9-91e6-4d55-9dbd-03cb920207a6";
4648
+ var LIST_TICKETS_INPUT_OUTCOME_UID = "893cf56d-0f36-4701-9482-3de285c2108d";
4649
+ var LIST_TICKETS_INPUT_ESCALATED_UID = "eb154697-418d-4159-8050-503d214175b0";
4650
+ var LIST_TICKETS_INPUT_CHANNEL_UID = "a03a94ef-ccc6-48d9-a088-656406bb1585";
4651
+ var LIST_TICKETS_INPUT_STATUS_UID = "e2fdddae-0464-496d-9526-bb017c544f09";
4652
+ var LIST_TICKETS_INPUT_CURSOR_UID = "dfba83d4-8a6b-4e8b-bcfb-f3fc3cf663eb";
4653
+ var EXPLAIN_TICKET_INPUT_TICKET_ID_UID = "7b0e5d3a-42c1-4f6e-9a58-0d1c6f3e8b24";
4246
4654
 
4247
4655
  // src/functions/run-triage-now.ts
4248
4656
  var TRIAGE_RUN_REQUESTED_EVENT = "triage.run.requested";
@@ -4357,7 +4765,7 @@ var REFUSALS = {
4357
4765
  async function invalidateResponseHandler(ctx, input) {
4358
4766
  const id = input?.generatedResponseId?.trim();
4359
4767
  if (!id) throw new ctx.NonRetriableError("generatedResponseId is required");
4360
- const record = await getOptional(ctx, "generated-response", id);
4768
+ const record = await getOptional(ctx.api, "generated-response", id);
4361
4769
  if (!record) throw new ctx.NonRetriableError(`R\xE9ponse g\xE9n\xE9r\xE9e introuvable (${id}).`);
4362
4770
  const data = record.data;
4363
4771
  const status = String(data.status ?? "");
@@ -4502,7 +4910,7 @@ async function runGraphDryRun({ base, api, resume, rebindDraft }) {
4502
4910
  ...recordingEvaluator ? { evaluator: recordingEvaluator.port } : {}
4503
4911
  },
4504
4912
  send: recordingSend.send,
4505
- trace: (step2) => steps.push(step2)
4913
+ trace: (step3) => steps.push(step3)
4506
4914
  };
4507
4915
  let result = null;
4508
4916
  let error;
@@ -4525,6 +4933,7 @@ async function runGraphDryRun({ base, api, resume, rebindDraft }) {
4525
4933
  draft: result?.draft ?? null,
4526
4934
  verdict: result?.verdict ?? null,
4527
4935
  guardrailHits: result?.guardrailHits ?? [],
4936
+ ineligibleReason: result?.ineligibleReason ?? null,
4528
4937
  ...error ? { error } : {}
4529
4938
  };
4530
4939
  }
@@ -4587,6 +4996,9 @@ function createInlineConversationPort(ticket, now) {
4587
4996
  // truth, and it is also what keeps `not_customer_turn` from holding the
4588
4997
  // run before a single node has looked at the text.
4589
4998
  lastAgentReplyAt: null,
4999
+ answerableChannels: [],
5000
+ customerChannelAddress: null,
5001
+ accountChannelAddress: null,
4590
5002
  hasCustomerAttachment: false,
4591
5003
  // `sourceChannel`, NOT `ref.channel`: the latter names the ADAPTER
4592
5004
  // (gorgias) while every channel guardrail and the style prompt read this
@@ -5221,7 +5633,6 @@ async function syncAgentPromptSnapshotHandler(ctx, input) {
5221
5633
 
5222
5634
  // src/functions/ext-models.ts
5223
5635
  var TOKEN_APPROXIMATION_CHARS_PER_TOKEN = 4;
5224
- var AGENT_PAGE_SIZE = 500;
5225
5636
  function buildExtModelsFunctionDef(config) {
5226
5637
  return {
5227
5638
  universalIdentifier: identifierFor(config, "ext-models"),
@@ -5233,7 +5644,12 @@ function createExtModelsHandler() {
5233
5644
  return (ctx) => extModelsHandler(ctx);
5234
5645
  }
5235
5646
  async function extModelsHandler(ctx) {
5236
- const page = await ctx.api.list("agent", { limit: AGENT_PAGE_SIZE });
5647
+ const [page, settings] = await Promise.all([
5648
+ ctx.api.list("agent", { limit: AGENT_PAGE_SIZE }),
5649
+ ctx.api.settings.get()
5650
+ ]);
5651
+ const appTag = trimmedSetting(settings.appScopeTag);
5652
+ const sourceViewId = trimmedSetting(settings.sourceViewId);
5237
5653
  if (page.items.length >= AGENT_PAGE_SIZE) {
5238
5654
  ctx.logger.warn(`ext-models: "agent" page came back full at ${page.items.length} rows \u2014 some may be silently missing from the response.`);
5239
5655
  }
@@ -5246,17 +5662,20 @@ async function extModelsHandler(ctx) {
5246
5662
  model_id: agent.modelId,
5247
5663
  system_prompt: systemPrompt,
5248
5664
  system_prompt_token_count: approximateTokenCount(systemPrompt),
5249
- status: agent.status
5665
+ status: agent.status,
5666
+ app_tag: appTag,
5667
+ source_view_id: sourceViewId
5250
5668
  };
5251
5669
  });
5252
5670
  }
5671
+ function trimmedSetting(value) {
5672
+ return typeof value === "string" ? value.trim() : "";
5673
+ }
5253
5674
  function approximateTokenCount(text) {
5254
5675
  return Math.ceil(text.length / TOKEN_APPROXIMATION_CHARS_PER_TOKEN);
5255
5676
  }
5256
5677
 
5257
5678
  // src/functions/ext-categories.ts
5258
- var CATEGORY_PAGE_SIZE = 500;
5259
- var AGENT_PAGE_SIZE2 = 500;
5260
5679
  function buildExtCategoriesFunctionDef(config) {
5261
5680
  return {
5262
5681
  universalIdentifier: identifierFor(config, "ext-categories"),
@@ -5277,10 +5696,10 @@ async function extCategoriesHandler(ctx) {
5277
5696
  // gateway's shared `FAN_OUT_BUDGET_MS`, so N+1 sequential round trips
5278
5697
  // risk a slow tenant's whole categories response silently dropping out
5279
5698
  // of the union on budget exhaustion.
5280
- ctx.api.list("agent", { limit: AGENT_PAGE_SIZE2 })
5699
+ ctx.api.list("agent", { limit: AGENT_PAGE_SIZE })
5281
5700
  ]);
5282
5701
  warnIfTruncated(ctx, "category", categoriesPage.items.length, CATEGORY_PAGE_SIZE);
5283
- warnIfTruncated(ctx, "agent", agentsPage.items.length, AGENT_PAGE_SIZE2);
5702
+ warnIfTruncated(ctx, "agent", agentsPage.items.length, AGENT_PAGE_SIZE);
5284
5703
  const groupOrderById = new Map(groupsPage.items.map(toCategoryGroup).map((g) => [g.id, g.order]));
5285
5704
  const agentById = new Map(agentsPage.items.map((record) => [record.id, toAgent(record)]));
5286
5705
  const entries = [];
@@ -5292,11 +5711,7 @@ async function extCategoriesHandler(ctx) {
5292
5711
  const groupOrder = category.groupId ? groupOrderById.get(category.groupId) ?? -Infinity : -Infinity;
5293
5712
  entries.push({ category, agent, groupOrder });
5294
5713
  }
5295
- entries.sort((a, b) => {
5296
- if (a.groupOrder !== b.groupOrder) return a.groupOrder - b.groupOrder;
5297
- if (a.category.order !== b.category.order) return a.category.order - b.category.order;
5298
- return a.category.name.localeCompare(b.category.name);
5299
- });
5714
+ entries.sort(compareByGroupThenCategory);
5300
5715
  return entries.map(({ category, agent }, index) => ({
5301
5716
  _id: category.id,
5302
5717
  name: category.name,
@@ -5316,7 +5731,7 @@ function warnIfTruncated(ctx, objectKey, itemCount, pageSize) {
5316
5731
  // src/functions/ownership-probe.ts
5317
5732
  async function ownsAgent(ctx, id) {
5318
5733
  if (!id) return null;
5319
- const record = await getOptional(ctx, "agent", id);
5734
+ const record = await getOptional(ctx.api, "agent", id);
5320
5735
  return record ? { claimed: true } : null;
5321
5736
  }
5322
5737
 
@@ -5479,7 +5894,7 @@ function toWireChatMessage(raw) {
5479
5894
  }
5480
5895
  async function resolveAgent(ctx, modelId) {
5481
5896
  if (modelId) {
5482
- const record2 = await getOptional(ctx, "agent", modelId);
5897
+ const record2 = await getOptional(ctx.api, "agent", modelId);
5483
5898
  if (!record2) throw new ctx.NonRetriableError(`Model not found (id=${modelId})`);
5484
5899
  return toAgent(record2);
5485
5900
  }
@@ -5594,7 +6009,7 @@ async function serveHit(ctx, row, userId, now) {
5594
6009
  );
5595
6010
  } catch (err) {
5596
6011
  if (!(err instanceof appKit.AppApiError) || err.status !== 409) throw err;
5597
- const fresh = await getOptional(ctx, "generated-response", current.id);
6012
+ const fresh = await getOptional(ctx.api, "generated-response", current.id);
5598
6013
  const freshStatus = fresh ? fresh.data.status : void 0;
5599
6014
  if (!fresh || !isGeneratedResponseStatus(freshStatus) || freshStatus !== "ready") return null;
5600
6015
  current = fresh;
@@ -5625,14 +6040,14 @@ async function buildAvailableResponse(ctx, generatedResponse) {
5625
6040
  }
5626
6041
  async function resolveCategoryRef(ctx, categoryId) {
5627
6042
  if (!categoryId) return null;
5628
- const record = await getOptional(ctx, "category", categoryId);
6043
+ const record = await getOptional(ctx.api, "category", categoryId);
5629
6044
  if (!record) return null;
5630
6045
  const category = toCategory(record);
5631
6046
  return { _id: category.id, name: category.name };
5632
6047
  }
5633
6048
  async function resolveAgentRef(ctx, agentId) {
5634
6049
  if (!agentId) return null;
5635
- const record = await getOptional(ctx, "agent", agentId);
6050
+ const record = await getOptional(ctx.api, "agent", agentId);
5636
6051
  if (!record) return null;
5637
6052
  const agent = toAgent(record);
5638
6053
  return { _id: agent.id, name: agent.name, model_id: agent.modelId };
@@ -5698,7 +6113,7 @@ async function executeEvaluation(ctx, userId, input) {
5698
6113
  }
5699
6114
  const modelId = input.modelId;
5700
6115
  if (!modelId) throw new ctx.NonRetriableError("modelId is required");
5701
- const agentRecord2 = await getOptional(ctx, "agent", modelId);
6116
+ const agentRecord2 = await getOptional(ctx.api, "agent", modelId);
5702
6117
  if (!agentRecord2) throw new ctx.NonRetriableError(`Model not found (id=${modelId})`);
5703
6118
  const agent = toAgent(agentRecord2);
5704
6119
  const satisfied = input.satisfied;
@@ -5966,8 +6381,8 @@ function nonEmptyString(value) {
5966
6381
  // src/functions/followup-gates.ts
5967
6382
  var LABELS = {
5968
6383
  G1: "Identifiant de ticket",
5969
- G2: "Tag de p\xE9rim\xE8tre configur\xE9",
5970
- G5: "Tag de p\xE9rim\xE8tre pr\xE9sent sur le ticket",
6384
+ G2: "Tag de l\u2019application configur\xE9",
6385
+ G5: "Tag de l\u2019application pr\xE9sent sur le ticket",
5971
6386
  G6: "Aucune reprise humaine",
5972
6387
  G7: "Cat\xE9gorie r\xE9solue et opt\xE9e",
5973
6388
  G8: "Nouveau message client",
@@ -5981,7 +6396,7 @@ function evaluateTicketIdGate(ticketId) {
5981
6396
  return ticketId === null ? stopped("G1", "Aucun identifiant de ticket exploitable (il doit \xEAtre une suite de chiffres).") : passed("G1", `Ticket ${ticketId}.`);
5982
6397
  }
5983
6398
  function evaluateScopeGate(settings) {
5984
- return settings.webhookScopeTag.trim() === "" ? stopped("G2", "Le r\xE9glage \xAB Tag de p\xE9rim\xE8tre webhook \xBB est vide : aucun message suivant n\u2019est trait\xE9.") : passed("G2", `P\xE9rim\xE8tre : \xAB ${settings.webhookScopeTag} \xBB.`);
6399
+ return settings.appScopeTag.trim() === "" ? stopped("G2", "Le r\xE9glage \xAB Tag des tickets de l\u2019application \xBB est vide : aucun message suivant n\u2019est trait\xE9.") : passed("G2", `P\xE9rim\xE8tre : \xAB ${settings.appScopeTag} \xBB.`);
5985
6400
  }
5986
6401
  function skippedFollowupGates(gates) {
5987
6402
  return gates.map((gate) => ({
@@ -6034,8 +6449,8 @@ function evaluatePayloadGates(input) {
6034
6449
  return trace.done();
6035
6450
  }
6036
6451
  function scopeTagOnTicket(settings, tags) {
6037
- const scopeTag = settings.webhookScopeTag.trim();
6038
- return tags.includes(scopeTag) ? passed("G5", `Le ticket porte \xAB ${scopeTag} \xBB.`) : stopped("G5", `Le ticket ne porte pas le tag de p\xE9rim\xE8tre \xAB ${scopeTag} \xBB : il n\u2019appartient pas \xE0 cette app.`);
6452
+ const scopeTag = settings.appScopeTag.trim();
6453
+ return tags.includes(scopeTag) ? passed("G5", `Le ticket porte \xAB ${scopeTag} \xBB.`) : stopped("G5", `Le ticket ne porte pas le tag \xAB ${scopeTag} \xBB : il n\u2019appartient pas \xE0 cette app.`);
6039
6454
  }
6040
6455
  function noHumanTakeover(settings, tags) {
6041
6456
  const present = humanTakeoverTags(settings).filter((tag) => tags.includes(tag));
@@ -6422,7 +6837,7 @@ async function awaitSettledSend(ctx, id) {
6422
6837
  return status;
6423
6838
  }
6424
6839
  async function readResponseStatus(ctx, id) {
6425
- const row = await getOptional(ctx, "generated-response", id);
6840
+ const row = await getOptional(ctx.api, "generated-response", id);
6426
6841
  if (!row) return "sent";
6427
6842
  const raw = row.data.status;
6428
6843
  return isGeneratedResponseStatus(raw) ? raw : null;
@@ -6495,6 +6910,7 @@ async function openFollowupResponse(ctx, input) {
6495
6910
  categoryId: category.id,
6496
6911
  agentId: agent?.id ?? null,
6497
6912
  channel: conversation.sourceChannel === "whatsapp" ? "whatsapp" : "email",
6913
+ sourceChannel: conversation.sourceChannel ?? null,
6498
6914
  generatedAt,
6499
6915
  expiresAt: new Date(generatedAt.getTime() + settings.responseTtlMinutes * 6e4),
6500
6916
  // Stamped HERE, not only when `process-response` finishes with the row:
@@ -6648,6 +7064,1193 @@ async function triggerRun(ctx, ticketId, mode) {
6648
7064
  return { mode, ticketId, runId: run.id };
6649
7065
  }
6650
7066
 
7067
+ // src/domain/dashboard-queries.ts
7068
+ var OUTCOME_METRICS = [{ op: "count", as: "count" }];
7069
+ var OUTCOME_GROUP_BY = ["status", "autoSendDecision", "outcome"];
7070
+ var CATEGORY_OUTCOME_GROUP_BY = ["categoryId", "status", "autoSendDecision", "outcome"];
7071
+ var TRIAGE_HANDOFF_GROUP_BY = ["escalated", "status"];
7072
+ var CATEGORY_TRIAGE_GROUP_BY = ["categoryId", "escalated", "status"];
7073
+
7074
+ // src/domain/tool-input-error.ts
7075
+ var ToolInputError = class extends Error {
7076
+ constructor(message) {
7077
+ super(message);
7078
+ this.name = "ToolInputError";
7079
+ }
7080
+ };
7081
+ function assertOptionalBoolean(name, value) {
7082
+ if (value !== void 0 && value !== null && typeof value !== "boolean") {
7083
+ throw new ToolInputError(`"${name}" must be a boolean, got ${JSON.stringify(value)}.`);
7084
+ }
7085
+ }
7086
+
7087
+ // src/domain/period.ts
7088
+ var WEEKLY_BUCKET_FROM_DAYS = 46;
7089
+ var DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
7090
+ var MS_PER_DAY = 864e5;
7091
+ var EPOCH_ISO = "1970-01-01T00:00:00.000Z";
7092
+ function startOfDayIso(day) {
7093
+ return day !== void 0 && DAY_PATTERN.test(day) ? `${day}T00:00:00.000Z` : EPOCH_ISO;
7094
+ }
7095
+ function endOfDayIso(day) {
7096
+ return DAY_PATTERN.test(day) ? `${day}T23:59:59.999Z` : (/* @__PURE__ */ new Date()).toISOString();
7097
+ }
7098
+ function dayCount(bounds) {
7099
+ const from = Date.parse(bounds.fromIso);
7100
+ const to = Date.parse(bounds.toIso);
7101
+ if (Number.isNaN(from) || Number.isNaN(to)) return 0;
7102
+ return Math.max(1, Math.round((to - from) / MS_PER_DAY));
7103
+ }
7104
+ function boundsOf(range) {
7105
+ return { fromIso: startOfDayIso(range.from), toIso: endOfDayIso(range.to) };
7106
+ }
7107
+ function periodBoundsOf({ range, compareRange }) {
7108
+ const current = boundsOf(range);
7109
+ const days = dayCount(current);
7110
+ return {
7111
+ current,
7112
+ previous: compareRange === void 0 ? null : boundsOf(compareRange),
7113
+ days,
7114
+ interval: days >= WEEKLY_BUCKET_FROM_DAYS ? "week" : "day"
7115
+ };
7116
+ }
7117
+ function dayToMs(day) {
7118
+ return Date.parse(`${day}T00:00:00.000Z`);
7119
+ }
7120
+ function msToDay(ms) {
7121
+ return new Date(ms).toISOString().slice(0, 10);
7122
+ }
7123
+ function isCalendarDay(value) {
7124
+ if (typeof value !== "string" || !DAY_PATTERN.test(value)) return false;
7125
+ const ms = dayToMs(value);
7126
+ return !Number.isNaN(ms) && msToDay(ms) === value;
7127
+ }
7128
+ function requireCalendarDay(name, value) {
7129
+ if (!isCalendarDay(value)) {
7130
+ throw new ToolInputError(
7131
+ `"${name}" must be a calendar day written YYYY-MM-DD, got ${JSON.stringify(value)}.`
7132
+ );
7133
+ }
7134
+ return value;
7135
+ }
7136
+ function dayRangeOf(from, to, maxDays) {
7137
+ const range = { from: requireCalendarDay("from", from), to: requireCalendarDay("to", to) };
7138
+ const length = lengthInDays(range);
7139
+ if (length < 1) throw new ToolInputError('"to" must not be before "from".');
7140
+ if (length > maxDays) {
7141
+ throw new ToolInputError(`The window is ${length} days long; the maximum is ${maxDays} days.`);
7142
+ }
7143
+ return range;
7144
+ }
7145
+ function previousRangeOf(range) {
7146
+ const from = dayToMs(range.from);
7147
+ const length = lengthInDays(range);
7148
+ return { from: msToDay(from - length * MS_PER_DAY), to: msToDay(from - MS_PER_DAY) };
7149
+ }
7150
+ function lengthInDays(range) {
7151
+ return (dayToMs(range.to) - dayToMs(range.from)) / MS_PER_DAY + 1;
7152
+ }
7153
+
7154
+ // src/domain/dashboard-stats.ts
7155
+ function sumCounts(rows, countField = "count") {
7156
+ return rows.reduce((sum, row) => sum + (Number(row[countField]) || 0), 0);
7157
+ }
7158
+ function bucketDay(row) {
7159
+ return String(row["bucket"]).slice(0, 10);
7160
+ }
7161
+ var EMPTY_TOTALS = {
7162
+ auto: 0,
7163
+ human: 0,
7164
+ inProgress: 0,
7165
+ noReplyNeeded: 0
7166
+ };
7167
+ function countFailed(rows) {
7168
+ return sumCounts(rows.filter((row) => row["status"] === "failed"));
7169
+ }
7170
+ var HUMAN_OUTCOMES = /* @__PURE__ */ new Set(["needs_human", "guardrail_hold", "escalated", "awaiting_approval"]);
7171
+ function isUnautomatedTriage(decision) {
7172
+ return decision.escalated === "true" || decision.escalated === true || decision.status === "error";
7173
+ }
7174
+ function countOf(row) {
7175
+ return Number(row["count"]) || 0;
7176
+ }
7177
+ function outcomeOf(row) {
7178
+ const status = row["status"];
7179
+ const autoSendDecision = row["autoSendDecision"];
7180
+ if (status === "test_draft" || status === "superseded") return null;
7181
+ if (status === "sent") return "auto";
7182
+ if (status === "no_reply_needed") return "noReplyNeeded";
7183
+ if (status === "failed") return "human";
7184
+ if (status === "invalidated" || status === "expired") return "human";
7185
+ const outcome2 = row["outcome"];
7186
+ if (typeof outcome2 === "string" && HUMAN_OUTCOMES.has(outcome2)) return "human";
7187
+ if (outcome2 === "no_reply_needed") return "noReplyNeeded";
7188
+ if (outcome2 === "triaged_only") return null;
7189
+ return autoSendDecision === "hold" ? "human" : "inProgress";
7190
+ }
7191
+ function foldOutcomes(rows, triageRows = []) {
7192
+ const totals = { ...EMPTY_TOTALS };
7193
+ for (const row of rows) {
7194
+ const outcome2 = outcomeOf(row);
7195
+ if (outcome2 !== null) totals[outcome2] += countOf(row);
7196
+ }
7197
+ for (const row of triageRows) {
7198
+ if (isUnautomatedTriage(row)) totals.human += countOf(row);
7199
+ }
7200
+ return totals;
7201
+ }
7202
+ function settledCount(totals) {
7203
+ return totals.auto + totals.human;
7204
+ }
7205
+ function autonomyRate(totals) {
7206
+ const settled = settledCount(totals);
7207
+ return settled > 0 ? totals.auto / settled : Number.NaN;
7208
+ }
7209
+ function foldDailyOutcomes(rows, triageRows = []) {
7210
+ const byDay = /* @__PURE__ */ new Map();
7211
+ const totalsFor = (day) => {
7212
+ const existing = byDay.get(day);
7213
+ if (existing !== void 0) return existing;
7214
+ const fresh = { ...EMPTY_TOTALS };
7215
+ byDay.set(day, fresh);
7216
+ return fresh;
7217
+ };
7218
+ for (const row of rows) {
7219
+ const outcome2 = outcomeOf(row);
7220
+ if (outcome2 === null) continue;
7221
+ totalsFor(bucketDay(row))[outcome2] += countOf(row);
7222
+ }
7223
+ for (const row of triageRows) {
7224
+ if (isUnautomatedTriage(row)) totalsFor(bucketDay(row)).human += countOf(row);
7225
+ }
7226
+ return [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, totals]) => ({
7227
+ day,
7228
+ auto: totals.auto,
7229
+ human: totals.human,
7230
+ rate: settledCount(totals) > 0 ? autonomyRate(totals) : null
7231
+ }));
7232
+ }
7233
+ function fillMissingDays(series, fromIso, toIso) {
7234
+ const from = Date.parse(fromIso.slice(0, 10));
7235
+ const to = Date.parse(toIso.slice(0, 10));
7236
+ if (Number.isNaN(from) || Number.isNaN(to) || to < from) return series;
7237
+ const measured = new Map(series.map((point) => [point.day, point]));
7238
+ const filled = [];
7239
+ for (let t = from; t <= to; t += 864e5) {
7240
+ const day = new Date(t).toISOString().slice(0, 10);
7241
+ filled.push(measured.get(day) ?? { day, auto: 0, human: 0, rate: null });
7242
+ }
7243
+ return filled;
7244
+ }
7245
+ function ratePoints(rate, compareRate) {
7246
+ return Number.isNaN(rate) || Number.isNaN(compareRate) ? null : (rate - compareRate) * 100;
7247
+ }
7248
+ var SIGNAL_MIN_VOLUME = 20;
7249
+ var SIGNAL_MIN_POINTS = 3;
7250
+ function dashboardSignals(totals, compare, failed2 = 0) {
7251
+ const signals = [];
7252
+ const settled = settledCount(totals);
7253
+ const rate = autonomyRate(totals);
7254
+ if (compare !== null && settled >= SIGNAL_MIN_VOLUME && settledCount(compare) >= SIGNAL_MIN_VOLUME) {
7255
+ const points = ratePoints(rate, autonomyRate(compare));
7256
+ if (points !== null && Math.abs(points) >= SIGNAL_MIN_POINTS) {
7257
+ const move = points < 0 ? "recule" : "progresse";
7258
+ signals.push({
7259
+ level: points < 0 ? "creuser" : "info",
7260
+ text: `Le taux d\u2019autonomie ${move} de ${Math.abs(Math.round(points))} points par rapport \xE0 la p\xE9riode pr\xE9c\xE9dente.`
7261
+ });
7262
+ }
7263
+ }
7264
+ if (failed2 > 0) {
7265
+ signals.push({
7266
+ level: "creuser",
7267
+ text: `${failed2} g\xE9n\xE9ration${failed2 > 1 ? "s ont" : " a"} \xE9chou\xE9 techniquement : ${failed2 > 1 ? "ces demandes n\u2019ont" : "cette demande n\u2019a"} jamais eu de brouillon et ${failed2 > 1 ? "sont retomb\xE9es" : "est retomb\xE9e"} sur un humain.`
7268
+ });
7269
+ }
7270
+ if (totals.inProgress > 0) {
7271
+ signals.push({
7272
+ level: "info",
7273
+ text: `${totals.inProgress} r\xE9ponse${totals.inProgress > 1 ? "s sont" : " est"} encore en cours : ${totals.inProgress > 1 ? "elles ne comptent" : "elle ne compte"} dans aucun des deux camps.`
7274
+ });
7275
+ }
7276
+ if (totals.noReplyNeeded > 0) {
7277
+ signals.push({
7278
+ level: "info",
7279
+ text: `${totals.noReplyNeeded} demande${totals.noReplyNeeded > 1 ? "s" : ""} ne n\xE9cessitai${totals.noReplyNeeded > 1 ? "ent" : "t"} aucune r\xE9ponse : hors du taux d\u2019autonomie.`
7280
+ });
7281
+ }
7282
+ if (compare !== null && settled > 0 && settledCount(compare) < SIGNAL_MIN_VOLUME) {
7283
+ signals.push({
7284
+ level: "info",
7285
+ text: "La p\xE9riode pr\xE9c\xE9dente compte trop peu de demandes r\xE9gl\xE9es pour que la comparaison veuille dire quelque chose."
7286
+ });
7287
+ }
7288
+ return signals;
7289
+ }
7290
+ function foldHumanReasons(rows, triageRows = []) {
7291
+ const reasons = { blocked: 0, invalidated: 0, expired: 0, escalatedNoDraft: 0, failed: 0 };
7292
+ for (const row of rows) {
7293
+ if (outcomeOf(row) !== "human") continue;
7294
+ const count = countOf(row);
7295
+ if (row["status"] === "invalidated") reasons.invalidated += count;
7296
+ else if (row["status"] === "expired") reasons.expired += count;
7297
+ else if (row["status"] === "failed") reasons.failed += count;
7298
+ else reasons.blocked += count;
7299
+ }
7300
+ for (const row of triageRows) {
7301
+ if (isUnautomatedTriage(row)) reasons.escalatedNoDraft += countOf(row);
7302
+ }
7303
+ return reasons;
7304
+ }
7305
+ var CATEGORY_TOP_N = 10;
7306
+ function foldCategoryOutcomes(triageRows, responseRows, categoryNames, topN = CATEGORY_TOP_N) {
7307
+ const byId = /* @__PURE__ */ new Map();
7308
+ const barFor = (id) => {
7309
+ const name = typeof id === "string" ? categoryNames.get(id) : void 0;
7310
+ if (name === void 0) return null;
7311
+ const existing = byId.get(id);
7312
+ if (existing !== void 0) return existing;
7313
+ const bar = {
7314
+ label: name,
7315
+ total: 0,
7316
+ auto: 0,
7317
+ human: 0,
7318
+ noReply: 0,
7319
+ undrafted: 0
7320
+ };
7321
+ byId.set(id, bar);
7322
+ return bar;
7323
+ };
7324
+ for (const row of triageRows) {
7325
+ const bar = barFor(row["categoryId"]);
7326
+ if (bar === null) continue;
7327
+ const count = countOf(row);
7328
+ bar.total += count;
7329
+ if (isUnautomatedTriage(row)) bar.human += count;
7330
+ }
7331
+ for (const row of responseRows) {
7332
+ const bar = barFor(row["categoryId"]);
7333
+ if (bar === null) continue;
7334
+ const outcome2 = outcomeOf(row);
7335
+ const count = countOf(row);
7336
+ if (outcome2 === "auto") bar.auto += count;
7337
+ else if (outcome2 === "human") bar.human += count;
7338
+ else if (outcome2 === "noReplyNeeded") bar.noReply += count;
7339
+ }
7340
+ const bars = [...byId.values()].map((bar) => {
7341
+ const accounted = bar.auto + bar.human + bar.noReply;
7342
+ return {
7343
+ ...bar,
7344
+ total: Math.max(bar.total, accounted),
7345
+ undrafted: Math.max(0, bar.total - accounted)
7346
+ };
7347
+ }).filter((bar) => bar.total > 0).sort((a, b) => b.total - a.total);
7348
+ if (bars.length <= topN + 1) return bars;
7349
+ const tail = bars.slice(topN).reduce(
7350
+ (sum, bar) => ({
7351
+ label: "Autres",
7352
+ total: sum.total + bar.total,
7353
+ auto: sum.auto + bar.auto,
7354
+ human: sum.human + bar.human,
7355
+ noReply: sum.noReply + bar.noReply,
7356
+ undrafted: sum.undrafted + bar.undrafted
7357
+ }),
7358
+ { label: "Autres", total: 0, auto: 0, human: 0, noReply: 0, undrafted: 0 }
7359
+ );
7360
+ return [...bars.slice(0, topN), tail];
7361
+ }
7362
+
7363
+ // src/domain/ticket-outcome.ts
7364
+ var REPORTED_OUTCOMES = [...OUTCOMES, "invalidated", "expired"];
7365
+ function emptyOutcomeCounts() {
7366
+ return Object.fromEntries(REPORTED_OUTCOMES.map((outcome2) => [outcome2, 0]));
7367
+ }
7368
+ var STATUS_EXITS = ["sent", "no_reply_needed", "failed", "invalidated", "expired"];
7369
+ function isStatusExit(status) {
7370
+ return STATUS_EXITS.includes(status);
7371
+ }
7372
+ function isReportedOutcome(value) {
7373
+ return REPORTED_OUTCOMES.includes(value);
7374
+ }
7375
+ function reportedOutcomeOf(status, outcome2) {
7376
+ if (status === "test_draft" || status === "superseded") return null;
7377
+ if (isStatusExit(status)) return status;
7378
+ return isOutcome(outcome2) ? outcome2 : null;
7379
+ }
7380
+ function foldOutcomeCounts(responseRows, triageRows) {
7381
+ const counts = emptyOutcomeCounts();
7382
+ for (const row of responseRows) {
7383
+ const outcome2 = reportedOutcomeOf(row["status"], row["outcome"]);
7384
+ if (outcome2 !== null) counts[outcome2] += countOf(row);
7385
+ }
7386
+ for (const row of triageRows) {
7387
+ if (isUnautomatedTriage(row)) counts.escalated += countOf(row);
7388
+ }
7389
+ return counts;
7390
+ }
7391
+
7392
+ // src/domain/ticket-stats.ts
7393
+ function rateOrNull(rate) {
7394
+ return Number.isNaN(rate) ? null : rate;
7395
+ }
7396
+ function summarizeWindow({
7397
+ range,
7398
+ period,
7399
+ rows,
7400
+ categoryNames,
7401
+ compareRows
7402
+ }) {
7403
+ const totals = foldOutcomes(rows.responses, rows.triage);
7404
+ const compareTotals = compareRows === void 0 ? null : foldOutcomes(compareRows.responses, compareRows.triage);
7405
+ const daily = foldDailyOutcomes(rows.responses, rows.triage);
7406
+ return {
7407
+ period: range,
7408
+ interval: period.interval,
7409
+ // Every triage decision carries `escalated` and `status`, so this grouping partitions all of them.
7410
+ volume: sumCounts(rows.triage),
7411
+ autonomyRate: rateOrNull(autonomyRate(totals)),
7412
+ outcomes: foldOutcomeCounts(rows.responses, rows.triage),
7413
+ humanReasons: foldHumanReasons(rows.responses, rows.triage),
7414
+ byCategory: foldCategoryOutcomes(rows.categoryTriage, rows.categoryOutcomes, categoryNames),
7415
+ daily: period.interval === "day" ? fillMissingDays(daily, period.current.fromIso, period.current.toIso) : daily,
7416
+ signals: dashboardSignals(totals, compareTotals, countFailed(rows.responses))
7417
+ };
7418
+ }
7419
+ var STAT_DEFINITIONS = {
7420
+ volume: "Number of triage decisions over the period: every message the pipeline triaged, whether a draft followed or not.",
7421
+ autonomyRate: "autonomy rate = responses settled by the AI / (responses settled by the AI + requests taken over by a human); null when nothing is settled.",
7422
+ outcomes: {
7423
+ sent: "Response sent to the customer by the pipeline.",
7424
+ ready: "Draft ready to be served, with no tag (nominal path), still pending.",
7425
+ needs_human: "Verdict not sendable: draft ready, posted with the review tag, still pending.",
7426
+ guardrail_hold: "A guardrail held the draft, posted with the escalation tag, still pending.",
7427
+ awaiting_approval: "An action is waiting for a human\u2019s approval.",
7428
+ escalated: "Request escalated at triage, or triage error: no draft written.",
7429
+ triaged_only: "Triaged, with no drafting step to run.",
7430
+ no_reply_needed: "Conversation already closed: no reply needed, outside the autonomy rate.",
7431
+ failed: "Generation failed technically; the ticket went up to a human.",
7432
+ invalidated: "Draft invalidated (an agent replied before it was served): taken over by a human, whatever the outcome decided at generation.",
7433
+ expired: "Draft expired (the serving window closed without it being used): taken over by a human, whatever the outcome decided at generation."
7434
+ },
7435
+ humanReasons: {
7436
+ blocked: "Draft written but held (judge or guardrail), waiting for a human.",
7437
+ invalidated: "An agent replied before the draft was served.",
7438
+ expired: "The serving window closed on an unused draft.",
7439
+ escalatedNoDraft: "Handed over to a human at triage (escalation or triage error): no draft.",
7440
+ failed: "Generation failed technically and the ticket was escalated."
7441
+ },
7442
+ byCategory: `Per category: triaged volume (total) and who replied \u2014 AI (auto), human, no reply needed, no draft (undrafted); the top ${CATEGORY_TOP_N} categories, the rest under "Autres" (others).`,
7443
+ daily: `One entry per day (per week from ${WEEKLY_BUCKET_FROM_DAYS} days on): responses settled by the AI, requests taken over by a human, rate of the day (null with no settled request).`,
7444
+ signals: "What is worth reading out loud, like the dashboard\u2019s \xAB Signaux \xBB (signals) block; the sentences are in French."
7445
+ };
7446
+
7447
+ // src/functions/mcp-tool.ts
7448
+ function mcpToolTrigger(description, { exposed = true } = {}) {
7449
+ return {
7450
+ type: "mcpTool",
7451
+ description,
7452
+ readOnly: true,
7453
+ exposed
7454
+ };
7455
+ }
7456
+ function mcpToolHandler(run) {
7457
+ return (ctx, input) => {
7458
+ const { api } = ctx;
7459
+ return withToolInputErrors(ctx, () => run(api, input ?? {}));
7460
+ };
7461
+ }
7462
+ async function withToolInputErrors(ctx, run) {
7463
+ try {
7464
+ return await run();
7465
+ } catch (error) {
7466
+ if (error instanceof ToolInputError) throw new ctx.NonRetriableError(error.message);
7467
+ throw error;
7468
+ }
7469
+ }
7470
+
7471
+ // src/functions/ticket-stats.ts
7472
+ var TICKET_STATS_MAX_DAYS = 90;
7473
+ var DESCRIPTION = "Dashboard figures over a period of at most 90 days: volume, autonomy rate, outcomes, reasons for human takeovers, breakdown by category, daily series and signals. Same computation as the dashboard; each indicator is defined in `definitions`. With compareToPrevious, the same indicators over the previous period of the same length.";
7474
+ function buildTicketStatsFunctionDef(config) {
7475
+ return {
7476
+ universalIdentifier: mcpToolIdentifierFor(config, "ticket-stats"),
7477
+ name: "ticket-stats",
7478
+ trigger: mcpToolTrigger(DESCRIPTION),
7479
+ input: [
7480
+ {
7481
+ universalIdentifier: TICKET_STATS_INPUT_FROM_UID,
7482
+ name: "from",
7483
+ type: appKit.FieldType.TEXT,
7484
+ label: "From",
7485
+ description: "First day of the period, YYYY-MM-DD, included.",
7486
+ isNullable: false
7487
+ },
7488
+ {
7489
+ universalIdentifier: TICKET_STATS_INPUT_TO_UID,
7490
+ name: "to",
7491
+ type: appKit.FieldType.TEXT,
7492
+ label: "To",
7493
+ description: `Last day of the period, YYYY-MM-DD, included. At most ${TICKET_STATS_MAX_DAYS} days after "from".`,
7494
+ isNullable: false
7495
+ },
7496
+ {
7497
+ universalIdentifier: TICKET_STATS_INPUT_COMPARE_TO_PREVIOUS_UID,
7498
+ name: "compareToPrevious",
7499
+ type: appKit.FieldType.BOOLEAN,
7500
+ label: "Compare to previous period",
7501
+ description: 'Also compute the same indicators on the period of the same length that ends the day before "from".',
7502
+ isNullable: true
7503
+ }
7504
+ ]
7505
+ };
7506
+ }
7507
+ function createTicketStatsHandler() {
7508
+ return mcpToolHandler(computeTicketStats);
7509
+ }
7510
+ async function computeTicketStats(api, input) {
7511
+ const range = dayRangeOf(input.from, input.to, TICKET_STATS_MAX_DAYS);
7512
+ assertOptionalBoolean("compareToPrevious", input.compareToPrevious);
7513
+ const [timezone, categoryNames] = await Promise.all([
7514
+ readStatsTimezone(api),
7515
+ readCategoryNames(api)
7516
+ ]);
7517
+ const period = periodBoundsOf({ range });
7518
+ const previous = input.compareToPrevious === true ? previousWindowOf(range) : void 0;
7519
+ const [rows, previousRows] = await Promise.all([
7520
+ readWindowRows(api, period, timezone),
7521
+ previous && readWindowRows(api, previous.period, timezone)
7522
+ ]);
7523
+ return {
7524
+ ...summarizeWindow({ range, period, rows, categoryNames, compareRows: previousRows }),
7525
+ timezone,
7526
+ ...previous && previousRows && {
7527
+ previous: summarizeWindow({ ...previous, rows: previousRows, categoryNames })
7528
+ },
7529
+ definitions: STAT_DEFINITIONS
7530
+ };
7531
+ }
7532
+ function previousWindowOf(range) {
7533
+ const previousRange = previousRangeOf(range);
7534
+ return { range: previousRange, period: periodBoundsOf({ range: previousRange }) };
7535
+ }
7536
+ async function readStatsTimezone(api) {
7537
+ const settings = await getSettingsOrNull(api);
7538
+ return settings?.statsTimezone || DEFAULT_STATS_TIMEZONE;
7539
+ }
7540
+ async function readWindowRows(api, period, timezone) {
7541
+ const { fromIso: gte, toIso: lte } = period.current;
7542
+ const generated = { filter: { generatedAt: { gte, lte } }, metrics: OUTCOME_METRICS };
7543
+ const decided = { filter: { decidedAt: { gte, lte } }, metrics: OUTCOME_METRICS };
7544
+ const bucketOn = (field) => ({ field, interval: period.interval, tz: timezone });
7545
+ const [responses, triage2, categoryTriage, categoryOutcomes] = await Promise.all([
7546
+ api.aggregate("generated-response", {
7547
+ ...generated,
7548
+ groupBy: OUTCOME_GROUP_BY,
7549
+ bucket: bucketOn("generatedAt")
7550
+ }),
7551
+ api.aggregate("triage-decision", {
7552
+ ...decided,
7553
+ groupBy: TRIAGE_HANDOFF_GROUP_BY,
7554
+ bucket: bucketOn("decidedAt")
7555
+ }),
7556
+ api.aggregate("triage-decision", { ...decided, groupBy: CATEGORY_TRIAGE_GROUP_BY }),
7557
+ api.aggregate("generated-response", { ...generated, groupBy: CATEGORY_OUTCOME_GROUP_BY })
7558
+ ]);
7559
+ return { responses, triage: triage2, categoryTriage, categoryOutcomes };
7560
+ }
7561
+ var LIST_TICKETS_MAX_DAYS = 31;
7562
+ var LIST_TICKETS_PAGE_SIZE = 50;
7563
+ var MAX_SCANNED_BATCHES = 8;
7564
+ var InvalidCursorError = class extends ToolInputError {
7565
+ constructor(reason = "The cursor is not one this tool issued") {
7566
+ super(`${reason}; start again without a cursor.`);
7567
+ this.name = "InvalidCursorError";
7568
+ }
7569
+ };
7570
+ var DESCRIPTION2 = "Lists the tickets the pipeline decided over a period of at most 31 days, newest first, 50 per page (nextCursor for the next one). One row per ticket (its most recent triage decision merged with its latest response): category, confidence, escalation, outcome, channel, sending, ineligibility reason, guardrails triggered, verdict. No customer text: use explain_ticket for the detail of a ticket. Filters: categoryId, outcome, escalated, channel, status. A page can be shorter than 50 rows while carrying a nextCursor: keep going as long as nextCursor is not null. The cursor is only valid with the same period and the same filters.";
7571
+ function buildListTicketsFunctionDef(config) {
7572
+ return {
7573
+ universalIdentifier: mcpToolIdentifierFor(config, "list-tickets"),
7574
+ name: "list-tickets",
7575
+ trigger: mcpToolTrigger(DESCRIPTION2),
7576
+ input: [
7577
+ {
7578
+ universalIdentifier: LIST_TICKETS_INPUT_FROM_UID,
7579
+ name: "from",
7580
+ type: appKit.FieldType.TEXT,
7581
+ label: "From",
7582
+ description: "First day of the period, YYYY-MM-DD, included.",
7583
+ isNullable: false
7584
+ },
7585
+ {
7586
+ universalIdentifier: LIST_TICKETS_INPUT_TO_UID,
7587
+ name: "to",
7588
+ type: appKit.FieldType.TEXT,
7589
+ label: "To",
7590
+ description: `Last day of the period, YYYY-MM-DD, included. At most ${LIST_TICKETS_MAX_DAYS} days after "from".`,
7591
+ isNullable: false
7592
+ },
7593
+ {
7594
+ universalIdentifier: LIST_TICKETS_INPUT_CATEGORY_ID_UID,
7595
+ name: "categoryId",
7596
+ type: appKit.FieldType.TEXT,
7597
+ label: "Category id",
7598
+ description: "Only the tickets triaged into this category (an id from list_categories).",
7599
+ isNullable: true
7600
+ },
7601
+ {
7602
+ universalIdentifier: LIST_TICKETS_INPUT_OUTCOME_UID,
7603
+ name: "outcome",
7604
+ type: appKit.FieldType.SELECT,
7605
+ label: "Outcome",
7606
+ description: 'Only the tickets that took this exit. "escalated" covers tickets handed over at triage, which have no response.',
7607
+ isNullable: true,
7608
+ options: [...REPORTED_OUTCOMES]
7609
+ },
7610
+ {
7611
+ universalIdentifier: LIST_TICKETS_INPUT_ESCALATED_UID,
7612
+ name: "escalated",
7613
+ type: appKit.FieldType.BOOLEAN,
7614
+ label: "Escalated",
7615
+ description: "Only the tickets the triage decision did (true) or did not (false) escalate.",
7616
+ isNullable: true
7617
+ },
7618
+ {
7619
+ universalIdentifier: LIST_TICKETS_INPUT_CHANNEL_UID,
7620
+ name: "channel",
7621
+ type: appKit.FieldType.TEXT,
7622
+ label: "Channel",
7623
+ description: "Only the tickets the customer wrote from this channel (e.g. email, whatsapp). The channel is recorded on the response only: a ticket with no response, such as one escalated at triage, never matches.",
7624
+ isNullable: true
7625
+ },
7626
+ {
7627
+ universalIdentifier: LIST_TICKETS_INPUT_STATUS_UID,
7628
+ name: "status",
7629
+ type: appKit.FieldType.SELECT,
7630
+ label: "Status",
7631
+ description: "Only the tickets whose response is in this status.",
7632
+ isNullable: true,
7633
+ options: [...GENERATED_RESPONSE_STATUSES]
7634
+ },
7635
+ {
7636
+ universalIdentifier: LIST_TICKETS_INPUT_CURSOR_UID,
7637
+ name: "cursor",
7638
+ type: appKit.FieldType.TEXT,
7639
+ label: "Cursor",
7640
+ description: "The nextCursor of the previous page. Leave empty for the first page.",
7641
+ isNullable: true
7642
+ }
7643
+ ]
7644
+ };
7645
+ }
7646
+ function createListTicketsHandler() {
7647
+ return mcpToolHandler(listTickets);
7648
+ }
7649
+ function scopeOf(input) {
7650
+ const { from, to, categoryId, outcome: outcome2, escalated, channel, status } = input;
7651
+ return JSON.stringify([
7652
+ from,
7653
+ to,
7654
+ categoryId || null,
7655
+ outcome2 || null,
7656
+ escalated ?? null,
7657
+ channel || null,
7658
+ status || null
7659
+ ]);
7660
+ }
7661
+ function encodeCursor(position) {
7662
+ return Buffer.from(JSON.stringify(position)).toString("base64url");
7663
+ }
7664
+ function parseCursor(cursor) {
7665
+ let decoded;
7666
+ try {
7667
+ decoded = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
7668
+ } catch {
7669
+ throw new InvalidCursorError();
7670
+ }
7671
+ if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
7672
+ throw new InvalidCursorError();
7673
+ }
7674
+ return decoded;
7675
+ }
7676
+ function startOfScan(input) {
7677
+ const scope = scopeOf(input);
7678
+ if (!input.cursor) return { after: null, skip: 0, scope };
7679
+ const { after = null, skip, scope: issuedFor } = parseCursor(input.cursor);
7680
+ const wellFormed = (after === null || typeof after === "string") && typeof skip === "number" && Number.isInteger(skip) && skip >= 0 && typeof issuedFor === "string";
7681
+ if (!wellFormed) throw new InvalidCursorError();
7682
+ if (issuedFor !== scope)
7683
+ throw new InvalidCursorError("The cursor was issued for another period or other filters");
7684
+ return { after, skip, scope };
7685
+ }
7686
+ function assertValidFilters(input) {
7687
+ assertOptionalBoolean("escalated", input.escalated);
7688
+ if (input.outcome && !isReportedOutcome(input.outcome)) {
7689
+ throw new ToolInputError(
7690
+ `"outcome" must be one of ${REPORTED_OUTCOMES.join(", ")}; got ${JSON.stringify(input.outcome)}.`
7691
+ );
7692
+ }
7693
+ if (input.status && !isGeneratedResponseStatus(input.status)) {
7694
+ throw new ToolInputError(
7695
+ `"status" must be one of ${GENERATED_RESPONSE_STATUSES.join(", ")}; got ${JSON.stringify(input.status)}.`
7696
+ );
7697
+ }
7698
+ }
7699
+ async function listTickets(api, input) {
7700
+ const range = dayRangeOf(input.from, input.to, LIST_TICKETS_MAX_DAYS);
7701
+ assertValidFilters(input);
7702
+ let position = startOfScan(input);
7703
+ const window = periodBoundsOf({ range }).current;
7704
+ const filter = decisionFilter(window, input);
7705
+ const readBatch = (after) => api.list("triage-decision", {
7706
+ filter,
7707
+ sort: NEWEST_DECISION_FIRST,
7708
+ limit: LIST_TICKETS_PAGE_SIZE,
7709
+ ...after === null ? {} : { cursor: after }
7710
+ });
7711
+ const [categoryNames, firstBatch] = await Promise.all([
7712
+ readCategoryNames(api),
7713
+ readBatch(position.after)
7714
+ ]);
7715
+ let page = firstBatch;
7716
+ const rows = [];
7717
+ for (let scanned = 1; ; scanned++) {
7718
+ const batch = page.items.slice(position.skip).map(toTriageDecision);
7719
+ const candidates = await readTicketsOf(api, batch, window.toIso);
7720
+ for (const [index, candidate] of candidates.entries()) {
7721
+ if (candidate === null) continue;
7722
+ const row = toTicketRow(candidate.decision, candidate.response, categoryNames);
7723
+ if (!matchesResponseFilters(row, input)) continue;
7724
+ rows.push(row);
7725
+ if (rows.length === LIST_TICKETS_PAGE_SIZE) {
7726
+ return { rows, nextCursor: cursorAfter(page, position, position.skip + index + 1) };
7727
+ }
7728
+ }
7729
+ if (page.nextCursor === null) return { rows, nextCursor: null };
7730
+ position = { ...position, after: page.nextCursor, skip: 0 };
7731
+ if (scanned === MAX_SCANNED_BATCHES) return { rows, nextCursor: encodeCursor(position) };
7732
+ page = await readBatch(position.after);
7733
+ }
7734
+ }
7735
+ function cursorAfter(page, position, consumed) {
7736
+ if (consumed < page.items.length) return encodeCursor({ ...position, skip: consumed });
7737
+ return page.nextCursor === null ? null : encodeCursor({ ...position, after: page.nextCursor, skip: 0 });
7738
+ }
7739
+ function decisionFilter(window, input) {
7740
+ return {
7741
+ decidedAt: { gte: window.fromIso, lte: window.toIso },
7742
+ ...input.categoryId ? { categoryId: input.categoryId } : {},
7743
+ ...typeof input.escalated === "boolean" ? { escalated: input.escalated } : {}
7744
+ };
7745
+ }
7746
+ async function readTicketsOf(api, batch, windowEndIso) {
7747
+ const [newestDecidedAt, responses] = await Promise.all([
7748
+ readNewestDecisionTimes(api, batch, windowEndIso),
7749
+ latestResponsesByTicket(
7750
+ api,
7751
+ batch.map((decision) => decision.ticketId)
7752
+ )
7753
+ ]);
7754
+ return batch.map(
7755
+ (decision) => isSuperseded(decision, newestDecidedAt) ? null : { decision, response: responses.get(decision.ticketId) ?? null }
7756
+ );
7757
+ }
7758
+ async function readNewestDecisionTimes(api, batch, windowEndIso) {
7759
+ const dated = batch.filter((decision) => decision.decidedAt !== null);
7760
+ if (dated.length === 0) return /* @__PURE__ */ new Map();
7761
+ const oldest = dated.reduce((a, b) => instantOf(b) < instantOf(a) ? b : a);
7762
+ const newest = await newestPerTicket(api, {
7763
+ objectKey: "triage-decision",
7764
+ ticketIds: dated.map((decision) => decision.ticketId),
7765
+ filter: { decidedAt: { gt: oldest.decidedAt, lte: windowEndIso } },
7766
+ sort: NEWEST_DECISION_FIRST
7767
+ });
7768
+ return new Map(
7769
+ [...newest].map(([ticketId, record]) => [ticketId, instantOf(toTriageDecision(record))])
7770
+ );
7771
+ }
7772
+ function isSuperseded(decision, newestDecidedAt) {
7773
+ return (newestDecidedAt.get(decision.ticketId) ?? -Infinity) > instantOf(decision);
7774
+ }
7775
+ function instantOf(decision) {
7776
+ return Date.parse(decision.decidedAt ?? "");
7777
+ }
7778
+ function toTicketRow(decision, response, categoryNames) {
7779
+ return {
7780
+ ticketId: decision.ticketId,
7781
+ ticketUrl: decision.ticketUrl,
7782
+ decidedAt: decision.decidedAt,
7783
+ categoryId: decision.categoryId,
7784
+ category: decision.categoryId === null ? null : categoryNames.get(decision.categoryId) ?? null,
7785
+ confidence: decision.confidence,
7786
+ escalated: decision.escalated,
7787
+ outcome: outcomeOf2(decision, response),
7788
+ status: response?.status ?? null,
7789
+ channel: response === null ? null : response.sourceChannel ?? response.channel,
7790
+ sentAt: response?.sentAt ?? null,
7791
+ ineligibleReason: response?.ineligibleReason ?? null,
7792
+ guardrailHits: response?.guardrailHits ?? [],
7793
+ verdict: response?.verdict ? { verdict: response.verdict.verdict, confidence: response.verdict.confidence } : null,
7794
+ origin: decision.origin
7795
+ };
7796
+ }
7797
+ function outcomeOf2(decision, response) {
7798
+ const answeredSince = response !== null && (response.generatedAt ?? "") >= (decision.decidedAt ?? "");
7799
+ if (isUnautomatedTriage(decision) && !answeredSince) return "escalated";
7800
+ return response === null ? null : reportedOutcomeOf(response.status, response.outcome);
7801
+ }
7802
+ function matchesResponseFilters(row, input) {
7803
+ return (!input.outcome || row.outcome === input.outcome) && (!input.channel || row.channel === input.channel) && (!input.status || row.status === input.status);
7804
+ }
7805
+
7806
+ // src/domain/timeline.ts
7807
+ var GENERIC_NOT_SENT = { code: "generic_not_sent" };
7808
+ function buildTimelineSteps(facts) {
7809
+ return [
7810
+ step2("received", receivedReason(facts)),
7811
+ step2("prompt", promptReason(facts)),
7812
+ step2("triage", triageReason(facts)),
7813
+ step2("draft", draftReason(facts)),
7814
+ step2("evaluation", evaluationReason(facts)),
7815
+ step2("delivery", deliveryReason(facts)),
7816
+ step2("correction", correctionReason(facts))
7817
+ ];
7818
+ }
7819
+ function step2(key, reason) {
7820
+ return reason === null ? { key, reached: true } : { key, reached: false, reason };
7821
+ }
7822
+ function receivedReason({
7823
+ conversation,
7824
+ conversationLoading
7825
+ }) {
7826
+ if (conversation) return null;
7827
+ return conversationLoading ? { code: "conversation_loading" } : { code: "conversation_unavailable" };
7828
+ }
7829
+ function promptReason({ conversation, job, decision }) {
7830
+ if (!job) return noResponseReason(decision);
7831
+ if (conversation?.systemPrompt) return null;
7832
+ return { code: "prompt_not_captured" };
7833
+ }
7834
+ function triageReason({ decision }) {
7835
+ if (decision.status === "error" && !decision.tag)
7836
+ return { code: "triage_failed", error: decision.error ?? null };
7837
+ return null;
7838
+ }
7839
+ function draftReason({ job, decision }) {
7840
+ if (!job) return noResponseReason(decision);
7841
+ if (job.responseText) return null;
7842
+ if (job.status === "pending") return { code: "draft_pending" };
7843
+ return { code: "draft_empty", error: job.error ?? null };
7844
+ }
7845
+ function evaluationReason({ job, decision }) {
7846
+ if (!job) return noResponseReason(decision);
7847
+ if (job.verdict) return null;
7848
+ return job.status === "pending" ? { code: "evaluation_pending" } : { code: "evaluation_missing" };
7849
+ }
7850
+ function deliveryReason(facts) {
7851
+ const { job, decision } = facts;
7852
+ if (!job) return noResponseReason(decision);
7853
+ switch (job.status) {
7854
+ case "sent":
7855
+ return null;
7856
+ case "pending":
7857
+ return { code: "reply_queued" };
7858
+ case "ready":
7859
+ return notSentReason(facts, job);
7860
+ case "expired": {
7861
+ const why = notSentReason(facts, job);
7862
+ return { code: "expired", detail: why.code === "generic_not_sent" ? null : why };
7863
+ }
7864
+ case "failed":
7865
+ return { code: "delivery_failed", error: job.error ?? null };
7866
+ case "superseded":
7867
+ return { code: "superseded" };
7868
+ case "test_draft":
7869
+ return { code: "test_draft" };
7870
+ default:
7871
+ return { code: "unexpected_status", status: job.status };
7872
+ }
7873
+ }
7874
+ function notSentReason({ policy, category }, job) {
7875
+ if (job.autoSendDecision === "hold" && job.guardrailHits.length === 0)
7876
+ return { code: "held_permanently" };
7877
+ if (job.autoSendDecision === "hold") return guardrailReason(job);
7878
+ switch (job.outcome) {
7879
+ case "needs_human":
7880
+ return notSendableReason(job, policy);
7881
+ case "guardrail_hold":
7882
+ return guardrailReason(job);
7883
+ case "awaiting_approval":
7884
+ return { code: "awaiting_approval" };
7885
+ case "ready":
7886
+ return notEligibleReason(job, policy, category);
7887
+ case "sent":
7888
+ return { code: "trial_mode" };
7889
+ case null:
7890
+ return legacyNotSentReason(job, policy, category);
7891
+ default:
7892
+ return GENERIC_NOT_SENT;
7893
+ }
7894
+ }
7895
+ function notSendableReason(job, policy) {
7896
+ const verdict = job.verdict;
7897
+ if (!verdict) return { code: "no_verdict" };
7898
+ if (verdict.status === "error") return { code: "evaluation_failed" };
7899
+ if (verdict.verdict === "hold") return { code: "judge_held" };
7900
+ if (!policy) return { code: "judge_not_authorized" };
7901
+ if ((verdict.confidence ?? 0) < policy.minConfidence) {
7902
+ return {
7903
+ code: "below_confidence",
7904
+ confidence: verdict.confidence ?? 0,
7905
+ minConfidence: policy.minConfidence
7906
+ };
7907
+ }
7908
+ if (requiresFollowup(verdict.verdict) && !policy.followupSendable)
7909
+ return { code: "followup_not_sendable" };
7910
+ return { code: "judge_not_authorized" };
7911
+ }
7912
+ function notEligibleReason(job, policy, category) {
7913
+ if (!policy) return GENERIC_NOT_SENT;
7914
+ if (!policy.evaluateConfigured) return { code: "evaluation_disabled" };
7915
+ if (!policy.autoSendEnabled) return { code: "auto_send_disabled" };
7916
+ if (category && !category.autoReplyEnabled)
7917
+ return { code: "category_auto_reply_off", categoryName: category.name };
7918
+ const isWhatsapp = job.channel === "whatsapp";
7919
+ if (isWhatsapp && policy.whatsappMode === "draft_only") return { code: "whatsapp_draft_only" };
7920
+ if (job.ineligibleReason === "no_publication_path") {
7921
+ return { code: "no_publication_path", channel: job.sourceChannel || null };
7922
+ }
7923
+ if (isRestrictedChannel(job.sourceChannel, policy.autoSendChannels)) {
7924
+ return { code: "channel_not_enabled", channel: job.sourceChannel };
7925
+ }
7926
+ if (!policy.senderEmail && !isWhatsapp) return { code: "no_sender_address" };
7927
+ return GENERIC_NOT_SENT;
7928
+ }
7929
+ function isRestrictedChannel(sourceChannel, allowed) {
7930
+ if (!sourceChannel) return false;
7931
+ if (!SUPPORT_CHANNELS.includes(sourceChannel)) return false;
7932
+ return !allowed.includes(sourceChannel);
7933
+ }
7934
+ function guardrailReason(job) {
7935
+ if (job.guardrailHits.length === 0) return { code: "guardrail_unrecorded" };
7936
+ return {
7937
+ code: "guardrail",
7938
+ hits: [...job.guardrailHits],
7939
+ reconstructed: Boolean(job.guardrailHitsReconstructedAt)
7940
+ };
7941
+ }
7942
+ function legacyNotSentReason(job, policy, category) {
7943
+ if (job.guardrailHits.length > 0) return guardrailReason(job);
7944
+ const verdict = job.verdict;
7945
+ if (policy && verdict && verdict.status === "success" && requiresFollowup(verdict.verdict) && !policy.followupSendable) {
7946
+ return { code: "legacy_followup_probable" };
7947
+ }
7948
+ if (verdict && (verdict.status === "error" || verdict.verdict === "hold"))
7949
+ return notSendableReason(job, policy);
7950
+ return notEligibleReason(job, policy, category);
7951
+ }
7952
+ function correctionReason({ comparisons }) {
7953
+ return comparisons.length > 0 ? null : { code: "no_correction" };
7954
+ }
7955
+ function noResponseReason(decision) {
7956
+ if (decision.escalated) return { code: "ticket_escalated" };
7957
+ if (decision.conversationOver) return { code: "conversation_over" };
7958
+ if (decision.status === "error") return { code: "triage_error", error: decision.error ?? null };
7959
+ return { code: "category_not_drafting" };
7960
+ }
7961
+
7962
+ // src/domain/trace-refs.ts
7963
+ function toTraceRefs(traceId, observationIds) {
7964
+ if (!traceId && observationIds.length === 0) return [];
7965
+ return [{ ...traceId ? { traceId } : {}, observationIds: [...observationIds] }];
7966
+ }
7967
+
7968
+ // src/settings/delivery-policy.ts
7969
+ function evaluateNode(settings) {
7970
+ const node = settings.nodes?.evaluate;
7971
+ return node && typeof node === "object" ? node : null;
7972
+ }
7973
+ function toDeliveryPolicy(raw) {
7974
+ if (!raw || typeof raw !== "object") return null;
7975
+ const settings = raw;
7976
+ const evaluate2 = evaluateNode(settings);
7977
+ const senderEmail = typeof settings.senderEmail === "string" ? settings.senderEmail : "";
7978
+ return {
7979
+ followupSendable: typeof evaluate2?.escalationEnabled === "boolean" ? evaluate2.escalationEnabled : DEFAULT_ESCALATION_ENABLED,
7980
+ minConfidence: typeof evaluate2?.minConfidence === "number" ? evaluate2.minConfidence : DEFAULT_MIN_CONFIDENCE,
7981
+ evaluateConfigured: evaluate2 !== null,
7982
+ autoSendEnabled: settings.autoSendEnabled === true,
7983
+ senderEmail: senderEmail === "" ? null : senderEmail,
7984
+ whatsappMode: typeof settings.whatsappMode === "string" ? settings.whatsappMode : null,
7985
+ autoSendChannels: Array.isArray(settings.autoSendChannels) ? settings.autoSendChannels : [...DEFAULT_AUTO_SEND_CHANNELS],
7986
+ dryRun: settings.dryRun === true,
7987
+ audit: toAuditTags(settings)
7988
+ };
7989
+ }
7990
+
7991
+ // src/functions/list-agents.ts
7992
+ var DESCRIPTION3 = "Lists the drafting agents: id, name, linked prompt (promptName, promptLabel), pinned version (promptVersion, null when the agent follows its label) and model. The prompt text is not returned: read it with get_prompt.";
7993
+ function buildListAgentsFunctionDef(config) {
7994
+ return {
7995
+ universalIdentifier: mcpToolIdentifierFor(config, "list-agents"),
7996
+ name: "list-agents",
7997
+ trigger: mcpToolTrigger(DESCRIPTION3)
7998
+ };
7999
+ }
8000
+ function createListAgentsHandler() {
8001
+ return (ctx) => describeAgents(ctx.api);
8002
+ }
8003
+ async function describeAgents(api) {
8004
+ return (await listAgents(api)).map(toAgentSummary);
8005
+ }
8006
+ function toAgentSummary(agent) {
8007
+ return {
8008
+ id: agent.id,
8009
+ name: agent.name,
8010
+ promptName: agent.promptName,
8011
+ promptLabel: agent.promptLabel,
8012
+ promptVersion: agent.promptVersion,
8013
+ modelId: agent.modelId
8014
+ };
8015
+ }
8016
+
8017
+ // src/functions/list-categories.ts
8018
+ var DESCRIPTION4 = "Lists the triage categories: id, name, tagName, description, examples, drafting agent (agentId), auto-reply and fast-reply flags (first message and follow-up) and group.";
8019
+ function buildListCategoriesFunctionDef(config) {
8020
+ return {
8021
+ universalIdentifier: mcpToolIdentifierFor(config, "list-categories"),
8022
+ name: "list-categories",
8023
+ trigger: mcpToolTrigger(DESCRIPTION4)
8024
+ };
8025
+ }
8026
+ function createListCategoriesHandler() {
8027
+ return (ctx) => describeCategories(ctx.api);
8028
+ }
8029
+ async function describeCategories(api) {
8030
+ const [categories, groupsPage] = await Promise.all([
8031
+ listCategories(api),
8032
+ api.list("category-group", { limit: CATEGORY_PAGE_SIZE })
8033
+ ]);
8034
+ const groups = new Map(groupsPage.items.map(toCategoryGroup).map((group) => [group.id, group]));
8035
+ return categories.map((category) => {
8036
+ const group = groups.get(category.groupId ?? "") ?? null;
8037
+ return { category, group, groupOrder: group?.order ?? Number.NEGATIVE_INFINITY };
8038
+ }).sort(compareByGroupThenCategory).map(({ category, group }) => toCategorySummary(category, group));
8039
+ }
8040
+ function toCategorySummary(category, group) {
8041
+ return {
8042
+ ...toCategoryFields(category),
8043
+ agentId: category.agentId,
8044
+ group: group === null ? null : { id: group.id, name: group.name }
8045
+ };
8046
+ }
8047
+ function toCategoryFields(category) {
8048
+ return {
8049
+ id: category.id,
8050
+ name: category.name,
8051
+ tagName: category.tagName,
8052
+ description: category.description,
8053
+ examples: category.examples,
8054
+ autoReplyEnabled: category.autoReplyEnabled,
8055
+ fastResponseEnabled: category.fastResponseEnabled,
8056
+ followupAutoReplyEnabled: category.followupAutoReplyEnabled,
8057
+ followupFastResponseEnabled: category.followupFastResponseEnabled
8058
+ };
8059
+ }
8060
+
8061
+ // src/functions/explain-ticket.ts
8062
+ var HISTORY_LIMIT = 20;
8063
+ var NEWEST_CORRECTION_FIRST = JSON.stringify([{ field: "capturedAt", direction: "desc" }]);
8064
+ var DESCRIPTION5 = "Explains a ticket: triage decision (category, confidence, reasoning, escalation and its reasoning), triage and escalation prompts as configured today in the settings (name, label; the version that ran is in the trace), generated responses (outcome, verdict, guardrails, send decision, drafting prompt version, sent text), human correction (generated text, sent text, diff), category, agent and timeline of the steps with the reason for the steps not reached. Also returns the Langfuse trace references (traceRefs) and traceAvailable: false on an old ticket or when the triage failed. { found: false } if the ticket is unknown.";
8065
+ function buildExplainTicketFunctionDef(config) {
8066
+ return {
8067
+ universalIdentifier: mcpToolIdentifierFor(config, "explain-ticket"),
8068
+ name: "explain-ticket",
8069
+ trigger: mcpToolTrigger(DESCRIPTION5),
8070
+ input: [
8071
+ {
8072
+ universalIdentifier: EXPLAIN_TICKET_INPUT_TICKET_ID_UID,
8073
+ name: "ticketId",
8074
+ type: appKit.FieldType.TEXT,
8075
+ label: "Ticket id",
8076
+ description: "The helpdesk ticket id, as listed by list_tickets.",
8077
+ isNullable: false
8078
+ }
8079
+ ]
8080
+ };
8081
+ }
8082
+ function createExplainTicketHandler(config) {
8083
+ return mcpToolHandler((api, input) => explainTicket(api, config, input));
8084
+ }
8085
+ async function explainTicket(api, config, input) {
8086
+ const { ticketId } = input;
8087
+ if (typeof ticketId !== "string" || ticketId === "") {
8088
+ throw new ToolInputError('"ticketId" must be a non-empty string.');
8089
+ }
8090
+ const [decision, responses, comparisons, settings] = await Promise.all([
8091
+ readNewestDecision(api, ticketId),
8092
+ listTicketResponses(api, ticketId, HISTORY_LIMIT),
8093
+ readCorrections(api, ticketId),
8094
+ getSettingsOrNull(api)
8095
+ ]);
8096
+ if (decision === null) return { found: false };
8097
+ const latest = responses[0];
8098
+ const categoryRead = readCategory(api, decision.categoryId);
8099
+ const agentId = latest?.agentId ?? (await categoryRead)?.agentId ?? null;
8100
+ const [category, agent] = await Promise.all([categoryRead, readAgent(api, agentId)]);
8101
+ return {
8102
+ found: true,
8103
+ ticketId,
8104
+ ticketUrl: decision.ticketUrl,
8105
+ triage: toTriageSection(decision, settings, config),
8106
+ responses: responses.map(toResponseSection),
8107
+ correction: comparisons[0] === void 0 ? null : toCorrectionSection(comparisons[0]),
8108
+ category: category === null ? null : toCategoryFields(category),
8109
+ agent,
8110
+ timeline: buildTimelineSteps({
8111
+ decision,
8112
+ job: latest,
8113
+ comparisons,
8114
+ conversation: persistedConversationOf(latest, comparisons[0]),
8115
+ policy: settings === null ? null : toDeliveryPolicy(settings),
8116
+ category
8117
+ })
8118
+ };
8119
+ }
8120
+ async function readNewestDecision(api, ticketId) {
8121
+ const page = await api.list("triage-decision", {
8122
+ filter: { ticketId },
8123
+ sort: NEWEST_DECISION_FIRST,
8124
+ limit: 1
8125
+ });
8126
+ return page.items[0] === void 0 ? null : toTriageDecision(page.items[0]);
8127
+ }
8128
+ async function readCorrections(api, ticketId) {
8129
+ const page = await api.list("response-comparison", {
8130
+ filter: { ticketId },
8131
+ sort: NEWEST_CORRECTION_FIRST,
8132
+ limit: HISTORY_LIMIT
8133
+ });
8134
+ return page.items.map(toResponseComparison);
8135
+ }
8136
+ async function readCategory(api, categoryId) {
8137
+ const record = await getOptional(api, "category", categoryId);
8138
+ return record === null ? null : toCategory(record);
8139
+ }
8140
+ async function readAgent(api, agentId) {
8141
+ const record = await getOptional(api, "agent", agentId);
8142
+ if (record === null) return null;
8143
+ const { modelId: _modelId, ...section2 } = toAgentSummary(toAgent(record));
8144
+ return section2;
8145
+ }
8146
+ function persistedConversationOf(job, correction) {
8147
+ if (job !== void 0 && job.tracedInput.length > 0) {
8148
+ return { systemPrompt: job.tracedInput.find((m) => m.role === "system")?.content ?? null };
8149
+ }
8150
+ return correction !== void 0 && correction.conversationMessages.length > 0 ? { systemPrompt: null } : null;
8151
+ }
8152
+ function toTriageSection(decision, settings, config) {
8153
+ const traceRefs = toTraceRefs(decision.langfuseTraceId, decision.langfuseObservationIds);
8154
+ return {
8155
+ decidedAt: decision.decidedAt,
8156
+ origin: decision.origin,
8157
+ status: decision.status,
8158
+ error: decision.error,
8159
+ categoryId: decision.categoryId,
8160
+ tag: decision.tag,
8161
+ confidence: decision.confidence,
8162
+ reasoning: decision.reasoning,
8163
+ conversationOver: decision.conversationOver,
8164
+ escalated: decision.escalated,
8165
+ escalationConfidence: decision.escalationConfidence,
8166
+ escalationReasoning: decision.escalationReasoning,
8167
+ prompts: triagePromptsOf(decision.origin, settings, config),
8168
+ traceRefs,
8169
+ traceAvailable: traceRefs.length > 0
8170
+ };
8171
+ }
8172
+ function triagePromptsOf(origin, settings, config) {
8173
+ if (origin === "followup") return { triage: null, escalation: null };
8174
+ const nodes = settings?.nodes;
8175
+ const bindingOf = (node, derivedName) => node === null ? null : promptRefFor(node, derivedName);
8176
+ return {
8177
+ triage: bindingOf(nodes?.triage, resolvePromptName("triage", config)),
8178
+ escalation: bindingOf(nodes?.escalate, resolvePromptName("escalation", config))
8179
+ };
8180
+ }
8181
+ function toResponseSection(response) {
8182
+ return {
8183
+ id: response.id,
8184
+ status: response.status,
8185
+ outcome: response.outcome,
8186
+ generatedAt: response.generatedAt,
8187
+ sentAt: response.sentAt,
8188
+ verdict: response.verdict,
8189
+ guardrailHits: response.guardrailHits,
8190
+ autoSendDecision: response.autoSendDecision,
8191
+ ineligibleReason: response.ineligibleReason,
8192
+ promptName: response.promptName,
8193
+ promptVersion: response.promptVersion,
8194
+ traceRefs: [
8195
+ ...toTraceRefs(
8196
+ response.langfuseTraceId,
8197
+ response.langfuseObservationId ? [response.langfuseObservationId] : []
8198
+ ),
8199
+ ...evaluationTraceRefs(response.evaluationObservationId)
8200
+ ],
8201
+ sentText: response.status === "sent" ? response.responseText : null,
8202
+ tracedInput: response.tracedInput.filter((message) => message.role !== "system")
8203
+ };
8204
+ }
8205
+ function evaluationTraceRefs(observationId) {
8206
+ return observationId ? [{ observationIds: [observationId], withoutMessages: true }] : [];
8207
+ }
8208
+ function toCorrectionSection(correction) {
8209
+ return {
8210
+ capturedAt: correction.capturedAt,
8211
+ generatedText: correction.generatedText,
8212
+ sentText: correction.sentText,
8213
+ diff: correction.diff
8214
+ };
8215
+ }
8216
+
8217
+ // src/functions/prompt-scope.ts
8218
+ var DESCRIPTION6 = "Internal: exact names of the Langfuse prompts of this app (the seven kit slots, prefixed, the prompt of each agent and the prompts chosen in the settings). Never a wildcard.";
8219
+ function buildPromptScopeFunctionDef(config) {
8220
+ return {
8221
+ universalIdentifier: mcpToolIdentifierFor(config, "prompt-scope"),
8222
+ name: "prompt-scope",
8223
+ trigger: mcpToolTrigger(DESCRIPTION6, { exposed: false })
8224
+ };
8225
+ }
8226
+ function createPromptScopeHandler(config) {
8227
+ return (ctx) => promptScope(ctx.api, config);
8228
+ }
8229
+ async function promptScope(api, config) {
8230
+ const [agents, settings] = await Promise.all([
8231
+ listAgents(api),
8232
+ getSettingsOrNull(api)
8233
+ ]);
8234
+ const candidates = [
8235
+ ...PROMPT_SLOTS.map((slot) => resolvePromptName(slot, config)),
8236
+ ...agents.map((agent) => agent.promptName),
8237
+ ...settings === null ? [] : promptNamesChosenIn(settings)
8238
+ ];
8239
+ return { names: [...new Set(candidates.filter(isExactName))] };
8240
+ }
8241
+ function promptNamesChosenIn(settings) {
8242
+ const nodes = Object.values(settings.nodes ?? {});
8243
+ const stepPrompts = nodes.map((node) => node?.prompt?.name);
8244
+ return [
8245
+ ...stepPrompts,
8246
+ settings.channelPromptEmail || DEFAULT_CHANNEL_PROMPT_EMAIL,
8247
+ settings.channelPromptWhatsapp || DEFAULT_CHANNEL_PROMPT_WHATSAPP
8248
+ ];
8249
+ }
8250
+ function isExactName(name) {
8251
+ return typeof name === "string" && name !== "" && !name.includes("*");
8252
+ }
8253
+
6651
8254
  // src/pages/manifest.ts
6652
8255
  function pageIdentifierFor(config, key) {
6653
8256
  const id = config.identifiers[key];
@@ -6788,6 +8391,40 @@ var FUNCTION_ASSEMBLY = [
6788
8391
  key: "test-gorgias-webhook",
6789
8392
  build: buildTestGorgiasWebhookFunctionDef,
6790
8393
  createHandler: createTestGorgiasWebhookHandler
8394
+ },
8395
+ // The read-only MCP tools (spec §5.3). Their identifiers are optional —
8396
+ // `mcpToolIdentifierFor` derives them — so they sit outside
8397
+ // FUNCTION_IDENTIFIER_KEYS and this assembly covers that list PLUS the MCP tools below.
8398
+ {
8399
+ key: "ticket-stats",
8400
+ build: buildTicketStatsFunctionDef,
8401
+ createHandler: () => createTicketStatsHandler()
8402
+ },
8403
+ {
8404
+ key: "list-tickets",
8405
+ build: buildListTicketsFunctionDef,
8406
+ createHandler: () => createListTicketsHandler()
8407
+ },
8408
+ {
8409
+ key: "explain-ticket",
8410
+ build: buildExplainTicketFunctionDef,
8411
+ createHandler: createExplainTicketHandler
8412
+ },
8413
+ {
8414
+ key: "list-categories",
8415
+ build: buildListCategoriesFunctionDef,
8416
+ createHandler: () => createListCategoriesHandler()
8417
+ },
8418
+ {
8419
+ key: "list-agents",
8420
+ build: buildListAgentsFunctionDef,
8421
+ createHandler: () => createListAgentsHandler()
8422
+ },
8423
+ // Internal (`exposed: false`): the OS asks it which prompt names belong to this app (D5).
8424
+ {
8425
+ key: "prompt-scope",
8426
+ build: buildPromptScopeFunctionDef,
8427
+ createHandler: createPromptScopeHandler
6791
8428
  }
6792
8429
  ];
6793
8430
  function buildPromptsAllowlist() {
@@ -6914,7 +8551,9 @@ exports.AGENT_STATUSES = AGENT_STATUSES;
6914
8551
  exports.AGENT_TOOLS = AGENT_TOOLS;
6915
8552
  exports.ATTACHMENT_MARKER_ONLY = ATTACHMENT_MARKER_ONLY;
6916
8553
  exports.CANDIDATE_MIN_LENGTH = CANDIDATE_MIN_LENGTH;
8554
+ exports.COLLISION_GUARDRAILS = COLLISION_GUARDRAILS;
6917
8555
  exports.DECISION_ORIGINS = DECISION_ORIGINS;
8556
+ exports.DEFAULT_AUTO_SEND_CHANNELS = DEFAULT_AUTO_SEND_CHANNELS;
6918
8557
  exports.DEFAULT_CHANNEL_PROMPT_EMAIL = DEFAULT_CHANNEL_PROMPT_EMAIL;
6919
8558
  exports.DEFAULT_CHANNEL_PROMPT_WHATSAPP = DEFAULT_CHANNEL_PROMPT_WHATSAPP;
6920
8559
  exports.DEFAULT_DECISION_ORIGIN = DEFAULT_DECISION_ORIGIN;
@@ -6931,11 +8570,14 @@ exports.OUTCOMES = OUTCOMES;
6931
8570
  exports.PROMPT_SLOTS = PROMPT_SLOTS;
6932
8571
  exports.REASONING_MAX_LEN = REASONING_MAX_LEN;
6933
8572
  exports.STOP_PHRASES = STOP_PHRASES;
8573
+ exports.SUPPORT_CHANNELS = SUPPORT_CHANNELS;
6934
8574
  exports.SUPPORT_KIT_SETTINGS_FIELDS = SUPPORT_KIT_SETTINGS_FIELDS;
6935
8575
  exports.UNCERTAINTY_MARKERS = UNCERTAINTY_MARKERS;
6936
8576
  exports.WHATSAPP_MODES = WHATSAPP_MODES;
6937
8577
  exports.WHATSAPP_NOTE_CHEVRON = WHATSAPP_NOTE_CHEVRON;
8578
+ exports.accountChannelAddress = accountChannelAddress;
6938
8579
  exports.agentRecord = agentRecord;
8580
+ exports.answerableChannels = answerableChannels;
6939
8581
  exports.assertTransition = assertTransition;
6940
8582
  exports.buildCategoryRecord = buildCategoryRecord;
6941
8583
  exports.buildDiffAnalysisRecord = buildDiffAnalysisRecord;
@@ -6950,6 +8592,7 @@ exports.categoryGroupRecord = categoryGroupRecord;
6950
8592
  exports.channelPreGates = channelPreGates;
6951
8593
  exports.createBudget = createBudget;
6952
8594
  exports.createPromptResolver = createPromptResolver;
8595
+ exports.customerChannelAddress = customerChannelAddress;
6953
8596
  exports.diffAnalysisUniqueKey = diffAnalysisUniqueKey;
6954
8597
  exports.firstCustomerMessage = firstCustomerMessage;
6955
8598
  exports.guardrailBucket = guardrailBucket;
@@ -6978,7 +8621,10 @@ exports.openTicketKeyFor = openTicketKeyFor;
6978
8621
  exports.parseReferences = parseReferences;
6979
8622
  exports.pipelineStateRecord = pipelineStateRecord;
6980
8623
  exports.promptCacheRecord = promptCacheRecord;
8624
+ exports.publicationMode = publicationMode;
8625
+ exports.rawTicketFactsAt = rawTicketFactsAt;
6981
8626
  exports.reclaimStalledSend = reclaimStalledSend;
8627
+ exports.reconstructGuardrailHits = reconstructGuardrailHits;
6982
8628
  exports.requiresFollowup = requiresFollowup;
6983
8629
  exports.resolvePromptName = resolvePromptName;
6984
8630
  exports.runGuardrails = runGuardrails;