@apotech-os/support-kit 8.3.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);
@@ -1136,7 +1343,19 @@ var GENERATED_RESPONSE_STATUSES = [
1136
1343
  // serve, send or revive a test draft — and terminal is also what frees the
1137
1344
  // `openTicketKey` (see `openTicketKeyFor`), so an essay can never hold the
1138
1345
  // real webhook at G9.
1139
- "test_draft"
1346
+ "test_draft",
1347
+ // 24/09/2026 — where a draft goes when a newer customer message arrives
1348
+ // before it was sent. The follow-up webhook used to refuse the new message
1349
+ // instead (G9 stopped on "une réponse est déjà ouverte"), which lost it
1350
+ // outright: Gorgias never replays a webhook it acked. The row is closed and
1351
+ // the pass drafts again, so the customer's latest message always wins.
1352
+ //
1353
+ // NOT `invalidated`, for the reason `test_draft` was split off it: the ticket
1354
+ // page and the dashboard read `invalidated` as "a human intervened", and a
1355
+ // draft replaced by a fresher one is nobody's intervention. Terminal, which
1356
+ // is also what releases `openTicketKey` (see `openTicketKeyFor`) — without
1357
+ // that release the replacement draft could not be created at all.
1358
+ "superseded"
1140
1359
  ];
1141
1360
  function isGeneratedResponseStatus(value) {
1142
1361
  return typeof value === "string" && GENERATED_RESPONSE_STATUSES.includes(value);
@@ -1146,15 +1365,21 @@ var ALLOWED_TRANSITIONS = {
1146
1365
  // very `pending` row it opened, and no other status can become a test
1147
1366
  // draft after the fact — an operator invalidating a real `ready` draft is
1148
1367
  // expressing "discard this", not "this was an essay".
1149
- pending: ["ready", "failed", "no_reply_needed", "sending", "invalidated", "test_draft"],
1150
- ready: ["sending", "invalidated", "expired"],
1368
+ pending: ["ready", "failed", "no_reply_needed", "sending", "invalidated", "test_draft", "superseded"],
1369
+ ready: ["sending", "invalidated", "expired", "superseded"],
1370
+ // `sending` reaches neither `invalidated` nor `superseded`, and for the same
1371
+ // reason: a worker holds the send lock, so nobody yet knows whether the
1372
+ // customer received anything. Closing that row would strand the send — the
1373
+ // sweep could no longer reclaim it, and `sentMessageId` would never be
1374
+ // written. A follow-up pass that meets one waits for it instead.
1151
1375
  sending: ["sent", "ready"],
1152
1376
  sent: [],
1153
1377
  failed: [],
1154
1378
  no_reply_needed: [],
1155
1379
  invalidated: [],
1156
1380
  expired: [],
1157
- test_draft: []
1381
+ test_draft: [],
1382
+ superseded: []
1158
1383
  };
1159
1384
  function canTransition(from, to) {
1160
1385
  if (!isGeneratedResponseStatus(from) || !isGeneratedResponseStatus(to)) return false;
@@ -1440,6 +1665,9 @@ var GENERATED_RESPONSE_FIELD_SENDING_AT_UID = "2ae9634b-79bb-42d2-a949-8b0f1ac9c
1440
1665
  var GENERATED_RESPONSE_FIELD_OUTCOME_UID = "8834b334-8f91-46f7-9bb9-96b69092d0ae";
1441
1666
  var GENERATED_RESPONSE_FIELD_ORIGIN_UID = "e75034d3-ee7f-40e7-b4fe-8be7b4322bdc";
1442
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";
1443
1671
  var GENERATED_RESPONSE_INDEX_TICKET_ID_UID = "a4534d26-8f43-4510-9c03-0b28c3d3f8e2";
1444
1672
  var GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID = "3d430166-07a2-43c2-911b-89ec25d13f64";
1445
1673
  var GENERATED_RESPONSE_INDEX_STATUS_UID = "f5c4e5d4-0810-424d-8a14-617e9555a7f3";
@@ -1956,9 +2184,26 @@ function buildGeneratedResponseRecord(slug) {
1956
2184
  name: "channel",
1957
2185
  type: appKit.FieldType.SELECT,
1958
2186
  label: "Channel",
2187
+ description: "Publication MODE, not the channel: 'whatsapp' for a note, 'email' for everything else. See sourceChannel.",
1959
2188
  isNullable: false,
1960
2189
  options: ["email", "whatsapp"]
1961
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
+ },
1962
2207
  {
1963
2208
  universalIdentifier: GENERATED_RESPONSE_FIELD_RESPONSE_TEXT_UID,
1964
2209
  name: "responseText",
@@ -2001,6 +2246,14 @@ function buildGeneratedResponseRecord(slug) {
2001
2246
  isNullable: false,
2002
2247
  defaultValue: []
2003
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
+ },
2004
2257
  {
2005
2258
  universalIdentifier: GENERATED_RESPONSE_FIELD_OUTCOME_UID,
2006
2259
  name: "outcome",
@@ -2614,6 +2867,10 @@ var SUPPORT_KIT_SETTINGS_FIELDS = [
2614
2867
  options: [...WHATSAPP_MODES],
2615
2868
  default: DEFAULT_WHATSAPP_MODE
2616
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] },
2617
2874
  // 14_400 minutes = 10 days, the legacy `fast_response_ttl_minutes` default
2618
2875
  // (`backoffice/src/models/AppSettings.ts`) — copied deliberately, not
2619
2876
  // chosen here. A pre-generated draft is only worth anything while the
@@ -2729,6 +2986,12 @@ function settingsWarnings(settings) {
2729
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."
2730
2987
  });
2731
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
+ }
2732
2995
  if (appScopeTag && webhookScopeTag && appScopeTag !== webhookScopeTag) {
2733
2996
  warnings.push({
2734
2997
  key: "scopeTagMismatch",
@@ -2820,7 +3083,11 @@ function settingsToProfile(settings, prompts) {
2820
3083
  // The auto-send floor is the evaluation floor: a second, independent
2821
3084
  // threshold would be a silent way to send below the one an operator set.
2822
3085
  minConfidence: evaluate2?.minConfidence ?? DEFAULT_MIN_CONFIDENCE,
2823
- 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]
2824
3091
  },
2825
3092
  rename: settings.renameEnabled ? { enabled: true, from: settings.renameFrom, to: settings.renameTo } : null,
2826
3093
  // Locks and run stamps are per-run state: they live in the
@@ -2861,62 +3128,6 @@ function identifierFor(config, key) {
2861
3128
  return id;
2862
3129
  }
2863
3130
 
2864
- // src/adapters/conversation-mapping.ts
2865
- function isInternalNoteChannel2(message) {
2866
- return message.channel === "internal-note" || message.source?.type === "internal-note";
2867
- }
2868
- function countableMessages(messages, isWhatsapp) {
2869
- return messages.filter((m) => {
2870
- if (isInternalNoteChannel2(m)) return isWhatsappChevronNote(m, isWhatsapp);
2871
- const hasText = !!(m.body_text?.trim() || m.body_html?.trim() || m.stripped_text?.trim() || m.stripped_html?.trim());
2872
- const hasAttachment = (m.attachments?.length ?? 0) > 0;
2873
- return hasText || hasAttachment;
2874
- });
2875
- }
2876
- function snapshotConversation(raw) {
2877
- const isWhatsapp = isWhatsappTicket(raw);
2878
- const messages = countableMessages(raw.messages ?? [], isWhatsapp);
2879
- let lastAt = null;
2880
- for (const m of messages) {
2881
- if (!m.created_datetime) continue;
2882
- const at = new Date(m.created_datetime);
2883
- if (!lastAt || at > lastAt) lastAt = at;
2884
- }
2885
- return { count: messages.length, lastAt };
2886
- }
2887
- function lastAgentReplyAtOf(raw) {
2888
- const isWhatsapp = isWhatsappTicket(raw);
2889
- let latest = null;
2890
- for (const m of raw.messages ?? []) {
2891
- if (m.from_agent !== true) continue;
2892
- if (isInternalNoteChannel2(m) && !isWhatsappChevronNote(m, isWhatsapp)) continue;
2893
- if (!m.created_datetime) continue;
2894
- const at = new Date(m.created_datetime);
2895
- if (!latest || at > latest) latest = at;
2896
- }
2897
- return latest;
2898
- }
2899
- function toConversation(ref, raw, context) {
2900
- const snapshot = snapshotConversation(raw);
2901
- const messages = context.messages.filter((m) => m.role === "user" || m.role === "assistant").map((m) => ({ role: m.role, content: m.content }));
2902
- return {
2903
- ref,
2904
- subject: raw.subject ?? null,
2905
- messages,
2906
- customer: {
2907
- name: context.customerName ?? null,
2908
- email: context.customerEmail ?? null,
2909
- orderContext: context.customerContext ?? null
2910
- },
2911
- isClosed: isTicketClosed(raw),
2912
- lastMessageAt: snapshot.lastAt,
2913
- messageCount: snapshot.count,
2914
- lastAgentReplyAt: lastAgentReplyAtOf(raw),
2915
- hasCustomerAttachment: hasCustomerAttachment(raw),
2916
- sourceChannel: isWhatsappTicket(raw) ? "whatsapp" : raw.channel ?? null
2917
- };
2918
- }
2919
-
2920
3131
  // src/adapters/gorgias-tags.ts
2921
3132
  function dedupeTagNames(tags) {
2922
3133
  const seen = /* @__PURE__ */ new Set();
@@ -2976,6 +3187,18 @@ function createGorgiasReplyPort(api) {
2976
3187
  });
2977
3188
  return { messageId: result2.messageId };
2978
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
+ }
2979
3202
  const result = await api.integrations.run("gorgias", "postWhatsappNote", {
2980
3203
  ticketId: ref.id,
2981
3204
  text: reply.bodyText
@@ -3213,15 +3436,15 @@ function isEligibleForGeneratedResponse(profile, classification, escalated, cate
3213
3436
  }
3214
3437
 
3215
3438
  // src/functions/no-tool-context.ts
3216
- function refuse(name) {
3439
+ function refuse2(name) {
3217
3440
  throw new Error(`no-tool-context: "${name}" called, but this pipeline configures no tools (profile.tools is always []).`);
3218
3441
  }
3219
3442
  function createNoToolContext() {
3220
3443
  return {
3221
- getOrder: () => refuse("getOrder"),
3222
- getTracking: () => refuse("getTracking"),
3223
- searchKnowledge: () => refuse("searchKnowledge"),
3224
- findSimilarTickets: () => refuse("findSimilarTickets")
3444
+ getOrder: () => refuse2("getOrder"),
3445
+ getTracking: () => refuse2("getTracking"),
3446
+ searchKnowledge: () => refuse2("searchKnowledge"),
3447
+ findSimilarTickets: () => refuse2("findSimilarTickets")
3225
3448
  };
3226
3449
  }
3227
3450
 
@@ -3398,9 +3621,12 @@ function toGeneratedResponse(record) {
3398
3621
  sources: Array.isArray(data.sources) ? data.sources : [],
3399
3622
  verdict: toVerdict(data.verdict),
3400
3623
  guardrailHits: data.guardrailHits ?? [],
3624
+ guardrailHitsReconstructedAt: data.guardrailHitsReconstructedAt ?? null,
3401
3625
  outcome: isOutcome(data.outcome) ? data.outcome : null,
3402
3626
  triageDecisionId: data.triageDecisionId ?? null,
3403
3627
  channel: data.channel ?? null,
3628
+ sourceChannel: data.sourceChannel ?? null,
3629
+ ineligibleReason: data.ineligibleReason ?? null,
3404
3630
  autoSendDecision: data.autoSendDecision ?? null,
3405
3631
  sentAt: data.sentAt ?? null,
3406
3632
  sentMessageId: data.sentMessageId ?? null,
@@ -3602,6 +3828,14 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
3602
3828
  // `outcome: 'sent'` on a `ready` row is exactly what "would have been
3603
3829
  // sent, wasn't" looks like, and the timeline reads it that way.
3604
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,
3605
3839
  responseText: result.draft?.text ?? null,
3606
3840
  sources: result.draft?.sources ?? [],
3607
3841
  // The rendered system prompt and the customer's own turns, which nothing
@@ -3916,6 +4150,7 @@ async function processOneTicket(ctx, ref, deps) {
3916
4150
  const draftAgent = await resolveDraftAgent(ctx.api, category?.agentId ?? null);
3917
4151
  const conversation = state.conversation;
3918
4152
  const channel = conversation?.sourceChannel === "whatsapp" ? "whatsapp" : "email";
4153
+ const sourceChannel = conversation?.sourceChannel ?? null;
3919
4154
  const generatedAt = ports.clock.now();
3920
4155
  const expiresAt = new Date(generatedAt.getTime() + profile.schedule.fastResponseTtlMinutes * 6e4);
3921
4156
  let created;
@@ -3928,6 +4163,7 @@ async function processOneTicket(ctx, ref, deps) {
3928
4163
  categoryId: category?.id ?? null,
3929
4164
  agentId: draftAgent?.id ?? null,
3930
4165
  channel,
4166
+ sourceChannel,
3931
4167
  generatedAt,
3932
4168
  expiresAt,
3933
4169
  sources: [],
@@ -3973,11 +4209,11 @@ async function sweepHandler(ctx) {
3973
4209
  const statePort = createGorgiasStatePort(ctx.api);
3974
4210
  const escalationTag = typeof settings?.escalationTag === "string" ? settings.escalationTag : "";
3975
4211
  if (!escalationTag) {
3976
- ctx.logger.warn("sweep: escalationTag is not configured \u2014 a stalled-send reclaim will proceed without an escalation tag");
4212
+ ctx.logger.warn("sweep: escalationTag is not configured \u2014 a stalled-send reclaim or an orphaned-pending hand-off will proceed without an escalation tag");
3977
4213
  }
3978
4214
  await sweepExpiredReady(ctx, now);
3979
4215
  await sweepStalledSending(ctx, now, escalationTag, statePort);
3980
- await sweepStalledPending(ctx, now);
4216
+ await sweepStalledPending(ctx, now, escalationTag, statePort);
3981
4217
  await upsertPipelineState(ctx.api, { lastSweepAt: now });
3982
4218
  }
3983
4219
  async function sweepExpiredReady(ctx, now) {
@@ -4023,23 +4259,26 @@ async function sweepStalledSending(ctx, now, escalationTag, statePort) {
4023
4259
  await statePort.flag(ref, escalationTag);
4024
4260
  }
4025
4261
  }
4026
- async function sweepStalledPending(ctx, now) {
4262
+ async function sweepStalledPending(ctx, now, escalationTag, statePort) {
4027
4263
  const page = await ctx.api.list("generated-response", { filter: { status: "pending" }, limit: SWEEP_PAGE_SIZE });
4028
4264
  for (const row of page.items) {
4029
4265
  const expiresAt = toDate(row.data.expiresAt);
4030
4266
  if (!expiresAt || expiresAt.getTime() > now.getTime()) continue;
4267
+ const ticketId = row.data.ticketId;
4031
4268
  assertTransition("pending", "failed");
4032
4269
  try {
4033
4270
  await ctx.api.update(
4034
4271
  "generated-response",
4035
4272
  row.id,
4036
- { status: "failed", openTicketKey: openTicketKeyFor("failed", row.data.ticketId), error: "orphaned pending row past its TTL (sweep)" },
4273
+ { status: "failed", openTicketKey: openTicketKeyFor("failed", ticketId), error: "orphaned pending row past its TTL (sweep)" },
4037
4274
  { ifMatch: { status: "pending" } }
4038
4275
  );
4039
4276
  } catch (err) {
4040
4277
  if (err instanceof appKit.AppApiError && err.status === 409) continue;
4041
4278
  throw err;
4042
4279
  }
4280
+ const ref = { id: ticketId, channel: "gorgias" };
4281
+ await statePort.flag(ref, escalationTag);
4043
4282
  }
4044
4283
  }
4045
4284
  function buildHandleApprovalFunctionDef(config) {
@@ -4117,6 +4356,9 @@ async function handleApprovalHandler(ctx, config) {
4117
4356
  lastMessageAt: data.generatedLastMessageAt ? new Date(data.generatedLastMessageAt) : null,
4118
4357
  messageCount: data.generatedMessageCount ?? 0,
4119
4358
  lastAgentReplyAt: null,
4359
+ answerableChannels: [],
4360
+ customerChannelAddress: null,
4361
+ accountChannelAddress: null,
4120
4362
  hasCustomerAttachment: false,
4121
4363
  sourceChannel: data.channel
4122
4364
  };
@@ -4165,7 +4407,7 @@ async function handleApprovalHandler(ctx, config) {
4165
4407
  return;
4166
4408
  }
4167
4409
  try {
4168
- 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" } });
4169
4411
  } catch (err) {
4170
4412
  if (!(err instanceof appKit.AppApiError && err.status === 409)) throw err;
4171
4413
  }
@@ -4504,6 +4746,7 @@ async function runGraphDryRun({ base, api, resume, rebindDraft }) {
4504
4746
  draft: result?.draft ?? null,
4505
4747
  verdict: result?.verdict ?? null,
4506
4748
  guardrailHits: result?.guardrailHits ?? [],
4749
+ ineligibleReason: result?.ineligibleReason ?? null,
4507
4750
  ...error ? { error } : {}
4508
4751
  };
4509
4752
  }
@@ -4566,6 +4809,9 @@ function createInlineConversationPort(ticket, now) {
4566
4809
  // truth, and it is also what keeps `not_customer_turn` from holding the
4567
4810
  // run before a single node has looked at the text.
4568
4811
  lastAgentReplyAt: null,
4812
+ answerableChannels: [],
4813
+ customerChannelAddress: null,
4814
+ accountChannelAddress: null,
4569
4815
  hasCustomerAttachment: false,
4570
4816
  // `sourceChannel`, NOT `ref.channel`: the latter names the ADAPTER
4571
4817
  // (gorgias) while every channel guardrail and the style prompt read this
@@ -5949,7 +6195,8 @@ var LABELS = {
5949
6195
  G5: "Tag de p\xE9rim\xE8tre pr\xE9sent sur le ticket",
5950
6196
  G6: "Aucune reprise humaine",
5951
6197
  G7: "Cat\xE9gorie r\xE9solue et opt\xE9e",
5952
- G8: "Nouveau message client"
6198
+ G8: "Nouveau message client",
6199
+ G9: "R\xE9ponse ouverte pr\xE9empt\xE9e"
5953
6200
  };
5954
6201
  function humanTakeoverTags(settings) {
5955
6202
  const configured = [settings.escalationTag, settings.needsReviewTag, settings.followupTag].map((tag) => tag.trim()).filter((tag) => tag !== "");
@@ -5975,15 +6222,23 @@ function completeFollowupLadder(results) {
5975
6222
  return missing.length === 0 ? results : [...results, ...skippedFollowupGates(missing)];
5976
6223
  }
5977
6224
  var FRESH_READ_GATES = ["G5", "G6", "G7", "G8"];
5978
- var ALL_FOLLOWUP_GATES = ["G1", "G2", ...FRESH_READ_GATES];
6225
+ var ALL_FOLLOWUP_GATES = ["G1", "G2", ...FRESH_READ_GATES, "G9"];
5979
6226
  function evaluateTicketGates(input) {
5980
- const { settings, tags, categories, conversation, anchor, ignoreCategoryOptIn = false } = input;
6227
+ const {
6228
+ settings,
6229
+ tags,
6230
+ categories,
6231
+ conversation,
6232
+ anchor,
6233
+ openResponse = null,
6234
+ ignoreCategoryOptIn = false
6235
+ } = input;
5981
6236
  const trace = newTrace(FRESH_READ_GATES);
5982
6237
  trace.record(scopeTagOnTicket(settings, tags));
5983
6238
  trace.record(noHumanTakeover(settings, tags));
5984
6239
  const match = trace.record(categoryGate(categories, tags, ignoreCategoryOptIn));
5985
6240
  if (match) trace.category = match;
5986
- trace.record(newCustomerMessage(conversation, anchor));
6241
+ trace.record(newCustomerMessage(conversation, anchor, openResponse));
5987
6242
  return trace.done();
5988
6243
  }
5989
6244
  function evaluatePayloadGates(input) {
@@ -6046,15 +6301,20 @@ function noMatchingCategory() {
6046
6301
  function matchingCategories(categories, tags) {
6047
6302
  return categories.filter((category) => tags.includes(category.tagName));
6048
6303
  }
6049
- function newCustomerMessage(conversation, anchor) {
6304
+ function newCustomerMessage(conversation, anchor, openResponse) {
6050
6305
  if (conversation.isClosed) return stopped("G8", "Le ticket est ferm\xE9.");
6051
6306
  const last = conversation.messages[conversation.messages.length - 1];
6052
6307
  if (!last) return stopped("G8", "La conversation extraite est vide.");
6053
6308
  if (!isCustomerTurnWithWords(last)) {
6054
6309
  return stopped("G8", "Le dernier message du fil n\u2019est pas un message client porteur de mots (agent, note interne, ou pi\xE8ce jointe seule).");
6055
6310
  }
6056
- if (anchor === null) return passed("G8", "Le dernier message est du client ; aucune r\xE9ponse ant\xE9rieure, donc aucune ancre \xE0 battre.");
6057
6311
  const lastAt = conversation.lastMessageAt;
6312
+ if (openResponse?.status === "pending" && lastAt && openResponse.ownAnchor?.getTime() === lastAt.getTime()) {
6313
+ return passed("G8", "Une tentative pr\xE9c\xE9dente de ce passage a laiss\xE9 une r\xE9ponse en attente sur ce m\xEAme message : reprise.");
6314
+ }
6315
+ if (anchor === null) {
6316
+ return openResponse === null ? passed("G8", "Le dernier message est du client ; aucune r\xE9ponse ant\xE9rieure, donc aucune ancre \xE0 battre.") : stopped("G8", "Une r\xE9ponse est d\xE9j\xE0 en cours de r\xE9daction sur ce ticket et ne porte aucune ancre : impossible de prouver que ce message est nouveau.");
6317
+ }
6058
6318
  if (!lastAt) return stopped("G8", "Le dernier message ne porte aucun horodatage : impossible de prouver qu\u2019il est post\xE9rieur \xE0 la derni\xE8re r\xE9ponse.");
6059
6319
  return lastAt.getTime() > anchor.getTime() ? passed("G8", `Message client du ${lastAt.toISOString()}, post\xE9rieur \xE0 la derni\xE8re r\xE9ponse.`) : stopped("G8", `Le dernier message (${lastAt.toISOString()}) n\u2019est pas post\xE9rieur \xE0 la derni\xE8re r\xE9ponse (${anchor.toISOString()}) : relivraison ou \xE9v\xE9nement en retard.`);
6060
6320
  }
@@ -6265,7 +6525,7 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
6265
6525
  const scope = evaluateScopeGate(settings);
6266
6526
  ladder.push(scope);
6267
6527
  if (scope.status === "stopped") return stopAt(ctx, ticketId, scope, ladder);
6268
- const { anchor, hasOpenResponse } = await readFollowupAnchor(ctx, ticketId);
6528
+ const { anchor, openResponse } = await readFollowupAnchor(ctx, ticketId);
6269
6529
  const categories = await listCategories(ctx.api);
6270
6530
  const preGates = evaluatePayloadGates({ settings, body, categories, anchor });
6271
6531
  if (preGates.stop) {
@@ -6282,6 +6542,7 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
6282
6542
  categories,
6283
6543
  conversation,
6284
6544
  anchor,
6545
+ openResponse,
6285
6546
  ignoreCategoryOptIn: generateOnly
6286
6547
  });
6287
6548
  ladder.push(...gates.results);
@@ -6289,15 +6550,27 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
6289
6550
  return stopAt(ctx, ticketId, gates.stop ?? unresolvedCategory(), ladder);
6290
6551
  }
6291
6552
  const category = gates.category;
6292
- if (hasOpenResponse) return stop(ctx, ticketId, "G9", "une r\xE9ponse est d\xE9j\xE0 ouverte sur ce ticket", ladder);
6553
+ const preemption = openResponse ? generateOnly ? stopped("G9", "Une r\xE9ponse est d\xE9j\xE0 ouverte sur ce ticket : l'essai ne la remplace pas, contrairement \xE0 un passage r\xE9el.") : await preemptOpenResponse(ctx, ticketId, openResponse) : passed("G9", "Aucune r\xE9ponse ouverte sur ce ticket.");
6554
+ if (preemption.status === "stopped") {
6555
+ ladder.push(preemption);
6556
+ return stopAt(ctx, ticketId, preemption, ladder);
6557
+ }
6293
6558
  run.id ??= (await ctx.api.runs.start({
6294
6559
  kind: FOLLOWUP_RUN_KIND,
6295
6560
  message: `Message suivant \u2014 ticket ${ticketId}`,
6296
6561
  metadata: { ticketId, categoryTag: category.tagName, channel: body.channel, generateOnly }
6297
6562
  })).id;
6298
6563
  const ticketUrl = ticketUrlFor(await resolveTicketUrlBase(ctx), ticketId);
6299
- const created = await openFollowupResponse(ctx, { ticketId, category, conversation, settings, runId: run.id, ticketUrl });
6300
- if (!created) return stop(ctx, ticketId, "G9", "une autre ex\xE9cution a ouvert la r\xE9ponse en premier", ladder);
6564
+ const created = await openFollowupResponse(ctx, { ticketId, category, conversation, settings, runId: run.id, ticketUrl, generateOnly });
6565
+ if (!created) {
6566
+ const lost = stopped(
6567
+ "G9",
6568
+ `Une autre ex\xE9cution a ouvert la r\xE9ponse en premier. ${preemption.detail}`.trim()
6569
+ );
6570
+ ladder.push(lost);
6571
+ return stopAt(ctx, ticketId, lost, ladder);
6572
+ }
6573
+ ladder.push(preemption);
6301
6574
  const outcome2 = await respondToPendingResponse(ctx, config, created.id, { testRun: generateOnly });
6302
6575
  return {
6303
6576
  ticketId,
@@ -6318,16 +6591,66 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
6318
6591
  async function readFollowupAnchor(ctx, ticketId) {
6319
6592
  const page = await ctx.api.list("generated-response", { filter: { ticketId }, limit: ANCHOR_LOOKUP_LIMIT });
6320
6593
  let anchor = null;
6321
- let hasOpenResponse = false;
6594
+ let openResponse = null;
6322
6595
  for (const item of page.items) {
6323
6596
  const data = item.data;
6324
- if (data.openTicketKey === ticketId) hasOpenResponse = true;
6597
+ let ownAnchor = null;
6325
6598
  for (const raw of [data.generatedLastMessageAt, data.sentAt]) {
6326
6599
  const at = toDate2(raw);
6600
+ if (at && (!ownAnchor || at > ownAnchor)) ownAnchor = at;
6327
6601
  if (at && (!anchor || at > anchor)) anchor = at;
6328
6602
  }
6603
+ if (data.openTicketKey === ticketId) {
6604
+ openResponse = { id: item.id, status: isGeneratedResponseStatus(data.status) ? data.status : null, ownAnchor };
6605
+ }
6329
6606
  }
6330
- return { anchor, hasOpenResponse };
6607
+ return { anchor, openResponse };
6608
+ }
6609
+ var SEND_SETTLE_POLL_MS = 2e3;
6610
+ var SEND_SETTLE_ATTEMPTS = 4;
6611
+ var PREEMPT_ATTEMPTS = 3;
6612
+ async function preemptOpenResponse(ctx, ticketId, open) {
6613
+ let status = open.status;
6614
+ for (let attempt = 1; attempt <= PREEMPT_ATTEMPTS; attempt += 1) {
6615
+ if (status === null) {
6616
+ return stopped("G9", "Une r\xE9ponse ouverte porte un statut illisible : elle doit \xEAtre d\xE9bloqu\xE9e \xE0 la main.");
6617
+ }
6618
+ if (isTerminalStatus(status)) {
6619
+ return passed("G9", "La r\xE9ponse ouverte s'est termin\xE9e d'elle-m\xEAme : le ticket est libre.");
6620
+ }
6621
+ if (status === "sending") {
6622
+ status = await awaitSettledSend(ctx, open.id);
6623
+ if (status === "sending") {
6624
+ ctx.logger.warn(
6625
+ `gorgias-webhook: stop at G9 for ticket ${ticketId} \u2014 envoi bloqu\xE9 depuis plus de ${SEND_SETTLE_POLL_MS * SEND_SETTLE_ATTEMPTS / 1e3} s, message suivant non trait\xE9`
6626
+ );
6627
+ return stopped("G9", "Une r\xE9ponse est en cours d'envoi et ne se termine pas : au sweep de la r\xE9clamer.");
6628
+ }
6629
+ continue;
6630
+ }
6631
+ if (!canTransition(status, "superseded")) {
6632
+ return stopped("G9", `Une r\xE9ponse au statut \xAB ${status} \xBB tient le ticket et ne peut pas \xEAtre remplac\xE9e.`);
6633
+ }
6634
+ if (await transitionGeneratedResponse(ctx.api, { id: open.id, ticketId, from: status, to: "superseded" })) {
6635
+ return passed("G9", `La r\xE9ponse ouverte (${status}) r\xE9pondait \xE0 un message ant\xE9rieur : remplac\xE9e.`);
6636
+ }
6637
+ status = await readResponseStatus(ctx, open.id);
6638
+ }
6639
+ return stopped("G9", "La r\xE9ponse ouverte change de statut plus vite que ce passage ne peut la remplacer.");
6640
+ }
6641
+ async function awaitSettledSend(ctx, id) {
6642
+ let status = "sending";
6643
+ for (let attempt = 1; attempt <= SEND_SETTLE_ATTEMPTS && status === "sending"; attempt += 1) {
6644
+ await new Promise((resolve) => setTimeout(resolve, SEND_SETTLE_POLL_MS));
6645
+ status = await readResponseStatus(ctx, id);
6646
+ }
6647
+ return status;
6648
+ }
6649
+ async function readResponseStatus(ctx, id) {
6650
+ const row = await getOptional(ctx, "generated-response", id);
6651
+ if (!row) return "sent";
6652
+ const raw = row.data.status;
6653
+ return isGeneratedResponseStatus(raw) ? raw : null;
6331
6654
  }
6332
6655
  var ANCHOR_LOOKUP_LIMIT = 100;
6333
6656
  function toDate2(raw) {
@@ -6397,8 +6720,18 @@ async function openFollowupResponse(ctx, input) {
6397
6720
  categoryId: category.id,
6398
6721
  agentId: agent?.id ?? null,
6399
6722
  channel: conversation.sourceChannel === "whatsapp" ? "whatsapp" : "email",
6723
+ sourceChannel: conversation.sourceChannel ?? null,
6400
6724
  generatedAt,
6401
6725
  expiresAt: new Date(generatedAt.getTime() + settings.responseTtlMinutes * 6e4),
6726
+ // Stamped HERE, not only when `process-response` finishes with the row:
6727
+ // until it exists the draft contributes nothing to §6's anchor, so a
6728
+ // webhook redelivered while it is still `pending` would read "no anchor
6729
+ // to beat" at G8 and draft the very same message all over again.
6730
+ //
6731
+ // Withheld from the operator's essay for the reason §8 keeps it out of
6732
+ // the lifecycle entirely: raising the anchor there would make the REAL
6733
+ // reply to that same message impossible ever after.
6734
+ ...input.generateOnly ? {} : { generatedMessageCount: conversation.messageCount, generatedLastMessageAt: conversation.lastMessageAt },
6402
6735
  sources: [],
6403
6736
  tracedInput: [],
6404
6737
  guardrailHits: [],
@@ -6414,12 +6747,7 @@ async function openFollowupResponse(ctx, input) {
6414
6747
  }
6415
6748
  }
6416
6749
  function unresolvedCategory() {
6417
- return {
6418
- gate: "G7",
6419
- label: "Cat\xE9gorie r\xE9solue et opt\xE9e",
6420
- status: "stopped",
6421
- detail: "Aucune cat\xE9gorie r\xE9solue."
6422
- };
6750
+ return stopped("G7", "Aucune cat\xE9gorie r\xE9solue.");
6423
6751
  }
6424
6752
  function stopAt(ctx, ticketId, result, ladder, kind = "gate") {
6425
6753
  return stop(ctx, ticketId, `${result.gate}${kind === "gate" ? "" : ` (${kind})`}`, result.detail, ladder);
@@ -6488,7 +6816,7 @@ async function diagnose(ctx, ticketId) {
6488
6816
  const scope = evaluateScopeGate(settings);
6489
6817
  gates.push(scope);
6490
6818
  if (scope.status === "stopped") return finish3(gates, ticketId);
6491
- const { anchor } = await readFollowupAnchor(ctx, ticketId);
6819
+ const { anchor, openResponse } = await readFollowupAnchor(ctx, ticketId);
6492
6820
  const categories = await listCategories(ctx.api);
6493
6821
  const ref = { id: ticketId, channel: "gorgias" };
6494
6822
  const ticket = await ctx.api.integrations.run("gorgias", "getTicketWithContext", { ticketId });
@@ -6496,8 +6824,26 @@ async function diagnose(ctx, ticketId) {
6496
6824
  const conversation = toConversation(ref, raw, ticket?.context ?? { messages: [], customerContext: null });
6497
6825
  const trace = evaluateTicketGates({ settings, tags: ticketTagNames(raw), categories, conversation, anchor });
6498
6826
  gates.push(...trace.results);
6827
+ if (!trace.stop) gates.push(predictPreemption(openResponse));
6499
6828
  return finish3(gates, ticketId);
6500
6829
  }
6830
+ function predictPreemption(openResponse) {
6831
+ if (!openResponse) return passed("G9", "Aucune r\xE9ponse ouverte sur ce ticket.");
6832
+ const { status } = openResponse;
6833
+ if (status === null) {
6834
+ return stopped("G9", "Une r\xE9ponse ouverte porte un statut illisible : elle doit \xEAtre d\xE9bloqu\xE9e \xE0 la main.");
6835
+ }
6836
+ if (status === "sending") {
6837
+ return passed("G9", "Une r\xE9ponse est en cours d'envoi : le passage attendrait qu'elle se termine.");
6838
+ }
6839
+ if (isTerminalStatus(status)) {
6840
+ return passed("G9", "La r\xE9ponse ouverte est d\xE9j\xE0 termin\xE9e : le ticket est libre.");
6841
+ }
6842
+ if (!canTransition(status, "superseded")) {
6843
+ return stopped("G9", `Une r\xE9ponse au statut \xAB ${status} \xBB tient le ticket et ne peut pas \xEAtre remplac\xE9e.`);
6844
+ }
6845
+ return passed("G9", `Une r\xE9ponse ouverte (${status}) serait remplac\xE9e.`);
6846
+ }
6501
6847
  function finish3(gates, ticketId) {
6502
6848
  const full = completeFollowupLadder(gates);
6503
6849
  return {
@@ -6794,7 +7140,9 @@ exports.AGENT_STATUSES = AGENT_STATUSES;
6794
7140
  exports.AGENT_TOOLS = AGENT_TOOLS;
6795
7141
  exports.ATTACHMENT_MARKER_ONLY = ATTACHMENT_MARKER_ONLY;
6796
7142
  exports.CANDIDATE_MIN_LENGTH = CANDIDATE_MIN_LENGTH;
7143
+ exports.COLLISION_GUARDRAILS = COLLISION_GUARDRAILS;
6797
7144
  exports.DECISION_ORIGINS = DECISION_ORIGINS;
7145
+ exports.DEFAULT_AUTO_SEND_CHANNELS = DEFAULT_AUTO_SEND_CHANNELS;
6798
7146
  exports.DEFAULT_CHANNEL_PROMPT_EMAIL = DEFAULT_CHANNEL_PROMPT_EMAIL;
6799
7147
  exports.DEFAULT_CHANNEL_PROMPT_WHATSAPP = DEFAULT_CHANNEL_PROMPT_WHATSAPP;
6800
7148
  exports.DEFAULT_DECISION_ORIGIN = DEFAULT_DECISION_ORIGIN;
@@ -6811,11 +7159,14 @@ exports.OUTCOMES = OUTCOMES;
6811
7159
  exports.PROMPT_SLOTS = PROMPT_SLOTS;
6812
7160
  exports.REASONING_MAX_LEN = REASONING_MAX_LEN;
6813
7161
  exports.STOP_PHRASES = STOP_PHRASES;
7162
+ exports.SUPPORT_CHANNELS = SUPPORT_CHANNELS;
6814
7163
  exports.SUPPORT_KIT_SETTINGS_FIELDS = SUPPORT_KIT_SETTINGS_FIELDS;
6815
7164
  exports.UNCERTAINTY_MARKERS = UNCERTAINTY_MARKERS;
6816
7165
  exports.WHATSAPP_MODES = WHATSAPP_MODES;
6817
7166
  exports.WHATSAPP_NOTE_CHEVRON = WHATSAPP_NOTE_CHEVRON;
7167
+ exports.accountChannelAddress = accountChannelAddress;
6818
7168
  exports.agentRecord = agentRecord;
7169
+ exports.answerableChannels = answerableChannels;
6819
7170
  exports.assertTransition = assertTransition;
6820
7171
  exports.buildCategoryRecord = buildCategoryRecord;
6821
7172
  exports.buildDiffAnalysisRecord = buildDiffAnalysisRecord;
@@ -6830,6 +7181,7 @@ exports.categoryGroupRecord = categoryGroupRecord;
6830
7181
  exports.channelPreGates = channelPreGates;
6831
7182
  exports.createBudget = createBudget;
6832
7183
  exports.createPromptResolver = createPromptResolver;
7184
+ exports.customerChannelAddress = customerChannelAddress;
6833
7185
  exports.diffAnalysisUniqueKey = diffAnalysisUniqueKey;
6834
7186
  exports.firstCustomerMessage = firstCustomerMessage;
6835
7187
  exports.guardrailBucket = guardrailBucket;
@@ -6858,7 +7210,10 @@ exports.openTicketKeyFor = openTicketKeyFor;
6858
7210
  exports.parseReferences = parseReferences;
6859
7211
  exports.pipelineStateRecord = pipelineStateRecord;
6860
7212
  exports.promptCacheRecord = promptCacheRecord;
7213
+ exports.publicationMode = publicationMode;
7214
+ exports.rawTicketFactsAt = rawTicketFactsAt;
6861
7215
  exports.reclaimStalledSend = reclaimStalledSend;
7216
+ exports.reconstructGuardrailHits = reconstructGuardrailHits;
6862
7217
  exports.requiresFollowup = requiresFollowup;
6863
7218
  exports.resolvePromptName = resolvePromptName;
6864
7219
  exports.runGuardrails = runGuardrails;