@apotech-os/support-kit 8.4.0 → 9.0.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;
@@ -545,28 +742,6 @@ ${message}`);
545
742
  }
546
743
  };
547
744
 
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
745
  // src/graph/nodes/authorize.ts
571
746
  var authorize = async (state, deps) => {
572
747
  const kind = "send_reply";
@@ -982,56 +1157,86 @@ function markdownToHtml(markdown) {
982
1157
  }
983
1158
 
984
1159
  // src/graph/nodes/act.ts
985
- function hasAgentRepliedSince(lastAgentReplyAt, queuedAt) {
1160
+ function hasAgentAnswered(fresh, queuedAt) {
1161
+ const { lastAgentReplyAt, lastMessageAt } = fresh;
986
1162
  if (!lastAgentReplyAt) return false;
1163
+ if (lastMessageAt && lastAgentReplyAt.getTime() < lastMessageAt.getTime()) return false;
987
1164
  if (!queuedAt) return true;
988
1165
  return lastAgentReplyAt.getTime() > queuedAt.getTime() - CLOCK_SKEW_MARGIN_MS;
989
1166
  }
990
- function hasDiverged(fresh, generatedFrom) {
1167
+ function hasDiverged2(fresh, generatedFrom) {
991
1168
  return fresh.messageCount !== generatedFrom.messageCount || (fresh.lastMessageAt?.getTime() ?? null) !== (generatedFrom.lastMessageAt?.getTime() ?? null);
992
1169
  }
1170
+ function refuse(hit) {
1171
+ return { guardrailHits: [hit] };
1172
+ }
993
1173
  var act = async (state, deps) => {
994
1174
  const generatedFrom = state.conversation;
995
1175
  const draft2 = state.draft;
996
1176
  const action = state.proposedActions[0];
997
1177
  if (!generatedFrom || !draft2 || !action) return {};
998
- const mode = generatedFrom.sourceChannel === "whatsapp" ? "whatsapp_note" : "email";
999
1178
  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"] };
1179
+ const mode = publicationMode(fresh);
1180
+ if (mode === null) return refuse("customer_email_missing");
1181
+ if (fresh.isClosed) return refuse("ticket_closed");
1182
+ if (hasAgentAnswered(fresh, deps.queuedAt ?? null)) return refuse("agent_replied");
1183
+ if (hasDiverged2(fresh, generatedFrom)) return refuse("diverged");
1184
+ if (deps.budget.signal.aborted) return refuse("run_deadline");
1007
1185
  const claimed = deps.send.mode === "claimed" ? await deps.send.claim({ draft: draft2, verdict: state.verdict }) : true;
1008
1186
  if (!claimed) return {};
1009
- const reply = mode === "email" ? {
1187
+ const reply = buildReply(mode, {
1188
+ draftText: draft2.text,
1189
+ idempotencyKey: action.idempotencyKey,
1190
+ fresh,
1191
+ senderEmail: deps.profile.autoSend.senderEmail ?? ""
1192
+ });
1193
+ const { messageId } = await deps.ports.reply.post(deps.ref, reply);
1194
+ if (deps.send.mode === "claimed") await deps.send.commit(messageId);
1195
+ return {};
1196
+ };
1197
+ function buildReply(mode, inputs) {
1198
+ const { draftText, idempotencyKey, fresh, senderEmail } = inputs;
1199
+ if (mode === "whatsapp_note") {
1200
+ return {
1201
+ mode: "whatsapp_note",
1202
+ // Raw draft text: no markdown-to-HTML rendering (§4.2/§6.4) — the note
1203
+ // carries the model's text as-is, the chevron prefix is the adapter's job.
1204
+ bodyText: draftText,
1205
+ idempotencyKey
1206
+ };
1207
+ }
1208
+ if (mode === "channel") {
1209
+ return {
1210
+ mode: "channel",
1211
+ channel: fresh.sourceChannel ?? "",
1212
+ bodyText: draftText,
1213
+ bodyHtml: markdownToHtml(draftText),
1214
+ // Guaranteed non-null by `publicationMode`, which read THIS snapshot
1215
+ // and only returns `'channel'` once both ends are known.
1216
+ toAddress: fresh.customerChannelAddress ?? "",
1217
+ fromAddress: fresh.accountChannelAddress ?? "",
1218
+ receiverName: fresh.customer.name,
1219
+ idempotencyKey
1220
+ };
1221
+ }
1222
+ return legacyEmailReply(draftText, idempotencyKey, fresh, senderEmail);
1223
+ }
1224
+ function legacyEmailReply(draftText, idempotencyKey, fresh, senderEmail) {
1225
+ return {
1010
1226
  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),
1227
+ bodyText: draftText,
1228
+ // The draft is markdown; the email channel's HTML body must be rendered,
1229
+ // not the raw source.
1230
+ bodyHtml: markdownToHtml(draftText),
1015
1231
  subject: fresh.subject,
1016
- fromAddress: deps.profile.autoSend.senderEmail ?? "",
1232
+ fromAddress: senderEmail,
1017
1233
  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.
1234
+ // Guaranteed non-null by the `customer_email_missing` gate in `act` —
1235
+ // `?? ''` is belt-and-braces for the type, not a real fallback.
1021
1236
  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
1237
+ idempotencyKey
1030
1238
  };
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
- };
1239
+ }
1035
1240
 
1036
1241
  // src/graph/run-ticket.ts
1037
1242
  function merge(state, patch) {
@@ -1113,6 +1318,8 @@ async function runTicket(deps, options = {}) {
1113
1318
  if (!isAutoSendEligible(s, deps)) return finish2(s, deps, "ready");
1114
1319
  s = await step("guardrails", guardrails, s, deps);
1115
1320
  if (s.guardrailHits.length) return finish2(s, deps, "guardrail_hold");
1321
+ if (!isAutoSendChannel(s, deps)) return finish2(s, deps, "ready");
1322
+ if (!hasPublicationPath(s)) return finish2(merge(s, { ineligibleReason: "no_publication_path" }), deps, "ready");
1116
1323
  s = await step("authorize", authorize, s, deps);
1117
1324
  if (s.proposedActions.some((a) => a.decision !== "auto")) return finish2(s, deps, "awaiting_approval");
1118
1325
  s = await step("act", act, s, deps);
@@ -1458,6 +1665,9 @@ var GENERATED_RESPONSE_FIELD_SENDING_AT_UID = "2ae9634b-79bb-42d2-a949-8b0f1ac9c
1458
1665
  var GENERATED_RESPONSE_FIELD_OUTCOME_UID = "8834b334-8f91-46f7-9bb9-96b69092d0ae";
1459
1666
  var GENERATED_RESPONSE_FIELD_ORIGIN_UID = "e75034d3-ee7f-40e7-b4fe-8be7b4322bdc";
1460
1667
  var GENERATED_RESPONSE_FIELD_RUN_ID_UID = "f3448bca-9c59-418f-9509-ce0e43eb8768";
1668
+ var GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_RECONSTRUCTED_AT_UID = "b4db88de-b712-4713-9fe6-659a5563f4d2";
1669
+ var GENERATED_RESPONSE_FIELD_SOURCE_CHANNEL_UID = "0a05be96-0d3e-42f0-9153-4f2ee3cf7859";
1670
+ var GENERATED_RESPONSE_FIELD_INELIGIBLE_REASON_UID = "2fd5c90b-e8f4-480c-b040-189e4b1935fc";
1461
1671
  var GENERATED_RESPONSE_INDEX_TICKET_ID_UID = "a4534d26-8f43-4510-9c03-0b28c3d3f8e2";
1462
1672
  var GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID = "3d430166-07a2-43c2-911b-89ec25d13f64";
1463
1673
  var GENERATED_RESPONSE_INDEX_STATUS_UID = "f5c4e5d4-0810-424d-8a14-617e9555a7f3";
@@ -1974,9 +2184,26 @@ function buildGeneratedResponseRecord(slug) {
1974
2184
  name: "channel",
1975
2185
  type: appKit.FieldType.SELECT,
1976
2186
  label: "Channel",
2187
+ description: "Publication MODE, not the channel: 'whatsapp' for a note, 'email' for everything else. See sourceChannel.",
1977
2188
  isNullable: false,
1978
2189
  options: ["email", "whatsapp"]
1979
2190
  },
2191
+ {
2192
+ universalIdentifier: GENERATED_RESPONSE_FIELD_INELIGIBLE_REASON_UID,
2193
+ name: "ineligibleReason",
2194
+ type: appKit.FieldType.TEXT,
2195
+ label: "Ineligible reason",
2196
+ description: "Why auto-send was inapplicable, when the run knew a fact the settings cannot express. Today: 'no_publication_path'.",
2197
+ isNullable: true
2198
+ },
2199
+ {
2200
+ universalIdentifier: GENERATED_RESPONSE_FIELD_SOURCE_CHANNEL_UID,
2201
+ name: "sourceChannel",
2202
+ type: appKit.FieldType.TEXT,
2203
+ label: "Source channel",
2204
+ description: "The channel Gorgias reported (see SUPPORT_CHANNELS). Null on rows written before the field existed.",
2205
+ isNullable: true
2206
+ },
1980
2207
  {
1981
2208
  universalIdentifier: GENERATED_RESPONSE_FIELD_RESPONSE_TEXT_UID,
1982
2209
  name: "responseText",
@@ -2019,6 +2246,14 @@ function buildGeneratedResponseRecord(slug) {
2019
2246
  isNullable: false,
2020
2247
  defaultValue: []
2021
2248
  },
2249
+ {
2250
+ universalIdentifier: GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_RECONSTRUCTED_AT_UID,
2251
+ name: "guardrailHitsReconstructedAt",
2252
+ type: appKit.FieldType.DATE_TIME,
2253
+ label: "Guardrail hits reconstructed at",
2254
+ 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.",
2255
+ isNullable: true
2256
+ },
2022
2257
  {
2023
2258
  universalIdentifier: GENERATED_RESPONSE_FIELD_OUTCOME_UID,
2024
2259
  name: "outcome",
@@ -2632,6 +2867,10 @@ var SUPPORT_KIT_SETTINGS_FIELDS = [
2632
2867
  options: [...WHATSAPP_MODES],
2633
2868
  default: DEFAULT_WHATSAPP_MODE
2634
2869
  },
2870
+ // An ALLOWLIST: a channel absent from it never auto-sends. Defaulted to the
2871
+ // two that had a publication path before the setting existed, so an app
2872
+ // that never touches it keeps behaving exactly as it did.
2873
+ { key: "autoSendChannels", type: "json", label: "Auto-send channels", default: [...DEFAULT_AUTO_SEND_CHANNELS] },
2635
2874
  // 14_400 minutes = 10 days, the legacy `fast_response_ttl_minutes` default
2636
2875
  // (`backoffice/src/models/AppSettings.ts`) — copied deliberately, not
2637
2876
  // chosen here. A pre-generated draft is only worth anything while the
@@ -2747,6 +2986,12 @@ function settingsWarnings(settings) {
2747
2986
  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."
2748
2987
  });
2749
2988
  }
2989
+ if (settings.autoSendEnabled === true && Array.isArray(settings.autoSendChannels) && settings.autoSendChannels.length === 0) {
2990
+ warnings.push({
2991
+ key: "noAutoSendChannels",
2992
+ 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."
2993
+ });
2994
+ }
2750
2995
  if (appScopeTag && webhookScopeTag && appScopeTag !== webhookScopeTag) {
2751
2996
  warnings.push({
2752
2997
  key: "scopeTagMismatch",
@@ -2838,7 +3083,11 @@ function settingsToProfile(settings, prompts) {
2838
3083
  // The auto-send floor is the evaluation floor: a second, independent
2839
3084
  // threshold would be a silent way to send below the one an operator set.
2840
3085
  minConfidence: evaluate2?.minConfidence ?? DEFAULT_MIN_CONFIDENCE,
2841
- requireHighTriage: settings.requireHighTriageConfidence
3086
+ requireHighTriage: settings.requireHighTriageConfidence,
3087
+ // Defaulted rather than required: `SupportKitSettings` describes what a
3088
+ // SettingsPage writes, and an app deployed before this field existed
3089
+ // has no value stored for it.
3090
+ channels: [...settings.autoSendChannels ?? DEFAULT_AUTO_SEND_CHANNELS]
2842
3091
  },
2843
3092
  rename: settings.renameEnabled ? { enabled: true, from: settings.renameFrom, to: settings.renameTo } : null,
2844
3093
  // Locks and run stamps are per-run state: they live in the
@@ -2879,62 +3128,6 @@ function identifierFor(config, key) {
2879
3128
  return id;
2880
3129
  }
2881
3130
 
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
- };
2936
- }
2937
-
2938
3131
  // src/adapters/gorgias-tags.ts
2939
3132
  function dedupeTagNames(tags) {
2940
3133
  const seen = /* @__PURE__ */ new Set();
@@ -2994,6 +3187,18 @@ function createGorgiasReplyPort(api) {
2994
3187
  });
2995
3188
  return { messageId: result2.messageId };
2996
3189
  }
3190
+ if (reply.mode === "channel") {
3191
+ const result2 = await api.integrations.run("gorgias", "replyOnChannel", {
3192
+ ticketId: ref.id,
3193
+ channel: reply.channel,
3194
+ bodyHtml: reply.bodyHtml,
3195
+ bodyText: reply.bodyText,
3196
+ toAddress: reply.toAddress,
3197
+ fromAddress: reply.fromAddress,
3198
+ ...reply.receiverName !== null ? { receiverName: reply.receiverName } : {}
3199
+ });
3200
+ return { messageId: result2.messageId };
3201
+ }
2997
3202
  const result = await api.integrations.run("gorgias", "postWhatsappNote", {
2998
3203
  ticketId: ref.id,
2999
3204
  text: reply.bodyText
@@ -3231,15 +3436,15 @@ function isEligibleForGeneratedResponse(profile, classification, escalated, cate
3231
3436
  }
3232
3437
 
3233
3438
  // src/functions/no-tool-context.ts
3234
- function refuse(name) {
3439
+ function refuse2(name) {
3235
3440
  throw new Error(`no-tool-context: "${name}" called, but this pipeline configures no tools (profile.tools is always []).`);
3236
3441
  }
3237
3442
  function createNoToolContext() {
3238
3443
  return {
3239
- getOrder: () => refuse("getOrder"),
3240
- getTracking: () => refuse("getTracking"),
3241
- searchKnowledge: () => refuse("searchKnowledge"),
3242
- findSimilarTickets: () => refuse("findSimilarTickets")
3444
+ getOrder: () => refuse2("getOrder"),
3445
+ getTracking: () => refuse2("getTracking"),
3446
+ searchKnowledge: () => refuse2("searchKnowledge"),
3447
+ findSimilarTickets: () => refuse2("findSimilarTickets")
3243
3448
  };
3244
3449
  }
3245
3450
 
@@ -3416,9 +3621,12 @@ function toGeneratedResponse(record) {
3416
3621
  sources: Array.isArray(data.sources) ? data.sources : [],
3417
3622
  verdict: toVerdict(data.verdict),
3418
3623
  guardrailHits: data.guardrailHits ?? [],
3624
+ guardrailHitsReconstructedAt: data.guardrailHitsReconstructedAt ?? null,
3419
3625
  outcome: isOutcome(data.outcome) ? data.outcome : null,
3420
3626
  triageDecisionId: data.triageDecisionId ?? null,
3421
3627
  channel: data.channel ?? null,
3628
+ sourceChannel: data.sourceChannel ?? null,
3629
+ ineligibleReason: data.ineligibleReason ?? null,
3422
3630
  autoSendDecision: data.autoSendDecision ?? null,
3423
3631
  sentAt: data.sentAt ?? null,
3424
3632
  sentMessageId: data.sentMessageId ?? null,
@@ -3620,6 +3828,14 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
3620
3828
  // `outcome: 'sent'` on a `ready` row is exactly what "would have been
3621
3829
  // sent, wasn't" looks like, and the timeline reads it that way.
3622
3830
  outcome: result.outcome,
3831
+ // WHICH guardrail held the reply, not just that one did. Without this the
3832
+ // record keeps the `[]` its creation wrote and the timeline can only say
3833
+ // "un garde-fou a bloqué l'envoi" — the reason has to be reconstructed
3834
+ // from Gorgias by hand, which is exactly what it cost before this line.
3835
+ guardrailHits: result.guardrailHits,
3836
+ // The one "not sent" reason the timeline cannot re-derive from today's
3837
+ // settings: whether the contact had an address six weeks ago.
3838
+ ineligibleReason: result.ineligibleReason,
3623
3839
  responseText: result.draft?.text ?? null,
3624
3840
  sources: result.draft?.sources ?? [],
3625
3841
  // The rendered system prompt and the customer's own turns, which nothing
@@ -3934,6 +4150,7 @@ async function processOneTicket(ctx, ref, deps) {
3934
4150
  const draftAgent = await resolveDraftAgent(ctx.api, category?.agentId ?? null);
3935
4151
  const conversation = state.conversation;
3936
4152
  const channel = conversation?.sourceChannel === "whatsapp" ? "whatsapp" : "email";
4153
+ const sourceChannel = conversation?.sourceChannel ?? null;
3937
4154
  const generatedAt = ports.clock.now();
3938
4155
  const expiresAt = new Date(generatedAt.getTime() + profile.schedule.fastResponseTtlMinutes * 6e4);
3939
4156
  let created;
@@ -3946,6 +4163,7 @@ async function processOneTicket(ctx, ref, deps) {
3946
4163
  categoryId: category?.id ?? null,
3947
4164
  agentId: draftAgent?.id ?? null,
3948
4165
  channel,
4166
+ sourceChannel,
3949
4167
  generatedAt,
3950
4168
  expiresAt,
3951
4169
  sources: [],
@@ -4138,6 +4356,9 @@ async function handleApprovalHandler(ctx, config) {
4138
4356
  lastMessageAt: data.generatedLastMessageAt ? new Date(data.generatedLastMessageAt) : null,
4139
4357
  messageCount: data.generatedMessageCount ?? 0,
4140
4358
  lastAgentReplyAt: null,
4359
+ answerableChannels: [],
4360
+ customerChannelAddress: null,
4361
+ accountChannelAddress: null,
4141
4362
  hasCustomerAttachment: false,
4142
4363
  sourceChannel: data.channel
4143
4364
  };
@@ -4186,7 +4407,7 @@ async function handleApprovalHandler(ctx, config) {
4186
4407
  return;
4187
4408
  }
4188
4409
  try {
4189
- await ctx.api.update("generated-response", id, { autoSendDecision: "hold" }, { ifMatch: { status: "ready" } });
4410
+ await ctx.api.update("generated-response", id, { autoSendDecision: "hold", guardrailHits }, { ifMatch: { status: "ready" } });
4190
4411
  } catch (err) {
4191
4412
  if (!(err instanceof appKit.AppApiError && err.status === 409)) throw err;
4192
4413
  }
@@ -4525,6 +4746,7 @@ async function runGraphDryRun({ base, api, resume, rebindDraft }) {
4525
4746
  draft: result?.draft ?? null,
4526
4747
  verdict: result?.verdict ?? null,
4527
4748
  guardrailHits: result?.guardrailHits ?? [],
4749
+ ineligibleReason: result?.ineligibleReason ?? null,
4528
4750
  ...error ? { error } : {}
4529
4751
  };
4530
4752
  }
@@ -4587,6 +4809,9 @@ function createInlineConversationPort(ticket, now) {
4587
4809
  // truth, and it is also what keeps `not_customer_turn` from holding the
4588
4810
  // run before a single node has looked at the text.
4589
4811
  lastAgentReplyAt: null,
4812
+ answerableChannels: [],
4813
+ customerChannelAddress: null,
4814
+ accountChannelAddress: null,
4590
4815
  hasCustomerAttachment: false,
4591
4816
  // `sourceChannel`, NOT `ref.channel`: the latter names the ADAPTER
4592
4817
  // (gorgias) while every channel guardrail and the style prompt read this
@@ -6495,6 +6720,7 @@ async function openFollowupResponse(ctx, input) {
6495
6720
  categoryId: category.id,
6496
6721
  agentId: agent?.id ?? null,
6497
6722
  channel: conversation.sourceChannel === "whatsapp" ? "whatsapp" : "email",
6723
+ sourceChannel: conversation.sourceChannel ?? null,
6498
6724
  generatedAt,
6499
6725
  expiresAt: new Date(generatedAt.getTime() + settings.responseTtlMinutes * 6e4),
6500
6726
  // Stamped HERE, not only when `process-response` finishes with the row:
@@ -6914,7 +7140,9 @@ exports.AGENT_STATUSES = AGENT_STATUSES;
6914
7140
  exports.AGENT_TOOLS = AGENT_TOOLS;
6915
7141
  exports.ATTACHMENT_MARKER_ONLY = ATTACHMENT_MARKER_ONLY;
6916
7142
  exports.CANDIDATE_MIN_LENGTH = CANDIDATE_MIN_LENGTH;
7143
+ exports.COLLISION_GUARDRAILS = COLLISION_GUARDRAILS;
6917
7144
  exports.DECISION_ORIGINS = DECISION_ORIGINS;
7145
+ exports.DEFAULT_AUTO_SEND_CHANNELS = DEFAULT_AUTO_SEND_CHANNELS;
6918
7146
  exports.DEFAULT_CHANNEL_PROMPT_EMAIL = DEFAULT_CHANNEL_PROMPT_EMAIL;
6919
7147
  exports.DEFAULT_CHANNEL_PROMPT_WHATSAPP = DEFAULT_CHANNEL_PROMPT_WHATSAPP;
6920
7148
  exports.DEFAULT_DECISION_ORIGIN = DEFAULT_DECISION_ORIGIN;
@@ -6931,11 +7159,14 @@ exports.OUTCOMES = OUTCOMES;
6931
7159
  exports.PROMPT_SLOTS = PROMPT_SLOTS;
6932
7160
  exports.REASONING_MAX_LEN = REASONING_MAX_LEN;
6933
7161
  exports.STOP_PHRASES = STOP_PHRASES;
7162
+ exports.SUPPORT_CHANNELS = SUPPORT_CHANNELS;
6934
7163
  exports.SUPPORT_KIT_SETTINGS_FIELDS = SUPPORT_KIT_SETTINGS_FIELDS;
6935
7164
  exports.UNCERTAINTY_MARKERS = UNCERTAINTY_MARKERS;
6936
7165
  exports.WHATSAPP_MODES = WHATSAPP_MODES;
6937
7166
  exports.WHATSAPP_NOTE_CHEVRON = WHATSAPP_NOTE_CHEVRON;
7167
+ exports.accountChannelAddress = accountChannelAddress;
6938
7168
  exports.agentRecord = agentRecord;
7169
+ exports.answerableChannels = answerableChannels;
6939
7170
  exports.assertTransition = assertTransition;
6940
7171
  exports.buildCategoryRecord = buildCategoryRecord;
6941
7172
  exports.buildDiffAnalysisRecord = buildDiffAnalysisRecord;
@@ -6950,6 +7181,7 @@ exports.categoryGroupRecord = categoryGroupRecord;
6950
7181
  exports.channelPreGates = channelPreGates;
6951
7182
  exports.createBudget = createBudget;
6952
7183
  exports.createPromptResolver = createPromptResolver;
7184
+ exports.customerChannelAddress = customerChannelAddress;
6953
7185
  exports.diffAnalysisUniqueKey = diffAnalysisUniqueKey;
6954
7186
  exports.firstCustomerMessage = firstCustomerMessage;
6955
7187
  exports.guardrailBucket = guardrailBucket;
@@ -6978,7 +7210,10 @@ exports.openTicketKeyFor = openTicketKeyFor;
6978
7210
  exports.parseReferences = parseReferences;
6979
7211
  exports.pipelineStateRecord = pipelineStateRecord;
6980
7212
  exports.promptCacheRecord = promptCacheRecord;
7213
+ exports.publicationMode = publicationMode;
7214
+ exports.rawTicketFactsAt = rawTicketFactsAt;
6981
7215
  exports.reclaimStalledSend = reclaimStalledSend;
7216
+ exports.reconstructGuardrailHits = reconstructGuardrailHits;
6982
7217
  exports.requiresFollowup = requiresFollowup;
6983
7218
  exports.resolvePromptName = resolvePromptName;
6984
7219
  exports.runGuardrails = runGuardrails;