@apotech-os/support-kit 8.3.0 → 8.4.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
@@ -1136,7 +1136,19 @@ var GENERATED_RESPONSE_STATUSES = [
1136
1136
  // serve, send or revive a test draft — and terminal is also what frees the
1137
1137
  // `openTicketKey` (see `openTicketKeyFor`), so an essay can never hold the
1138
1138
  // real webhook at G9.
1139
- "test_draft"
1139
+ "test_draft",
1140
+ // 24/09/2026 — where a draft goes when a newer customer message arrives
1141
+ // before it was sent. The follow-up webhook used to refuse the new message
1142
+ // instead (G9 stopped on "une réponse est déjà ouverte"), which lost it
1143
+ // outright: Gorgias never replays a webhook it acked. The row is closed and
1144
+ // the pass drafts again, so the customer's latest message always wins.
1145
+ //
1146
+ // NOT `invalidated`, for the reason `test_draft` was split off it: the ticket
1147
+ // page and the dashboard read `invalidated` as "a human intervened", and a
1148
+ // draft replaced by a fresher one is nobody's intervention. Terminal, which
1149
+ // is also what releases `openTicketKey` (see `openTicketKeyFor`) — without
1150
+ // that release the replacement draft could not be created at all.
1151
+ "superseded"
1140
1152
  ];
1141
1153
  function isGeneratedResponseStatus(value) {
1142
1154
  return typeof value === "string" && GENERATED_RESPONSE_STATUSES.includes(value);
@@ -1146,15 +1158,21 @@ var ALLOWED_TRANSITIONS = {
1146
1158
  // very `pending` row it opened, and no other status can become a test
1147
1159
  // draft after the fact — an operator invalidating a real `ready` draft is
1148
1160
  // expressing "discard this", not "this was an essay".
1149
- pending: ["ready", "failed", "no_reply_needed", "sending", "invalidated", "test_draft"],
1150
- ready: ["sending", "invalidated", "expired"],
1161
+ pending: ["ready", "failed", "no_reply_needed", "sending", "invalidated", "test_draft", "superseded"],
1162
+ ready: ["sending", "invalidated", "expired", "superseded"],
1163
+ // `sending` reaches neither `invalidated` nor `superseded`, and for the same
1164
+ // reason: a worker holds the send lock, so nobody yet knows whether the
1165
+ // customer received anything. Closing that row would strand the send — the
1166
+ // sweep could no longer reclaim it, and `sentMessageId` would never be
1167
+ // written. A follow-up pass that meets one waits for it instead.
1151
1168
  sending: ["sent", "ready"],
1152
1169
  sent: [],
1153
1170
  failed: [],
1154
1171
  no_reply_needed: [],
1155
1172
  invalidated: [],
1156
1173
  expired: [],
1157
- test_draft: []
1174
+ test_draft: [],
1175
+ superseded: []
1158
1176
  };
1159
1177
  function canTransition(from, to) {
1160
1178
  if (!isGeneratedResponseStatus(from) || !isGeneratedResponseStatus(to)) return false;
@@ -3973,11 +3991,11 @@ async function sweepHandler(ctx) {
3973
3991
  const statePort = createGorgiasStatePort(ctx.api);
3974
3992
  const escalationTag = typeof settings?.escalationTag === "string" ? settings.escalationTag : "";
3975
3993
  if (!escalationTag) {
3976
- ctx.logger.warn("sweep: escalationTag is not configured \u2014 a stalled-send reclaim will proceed without an escalation tag");
3994
+ 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
3995
  }
3978
3996
  await sweepExpiredReady(ctx, now);
3979
3997
  await sweepStalledSending(ctx, now, escalationTag, statePort);
3980
- await sweepStalledPending(ctx, now);
3998
+ await sweepStalledPending(ctx, now, escalationTag, statePort);
3981
3999
  await upsertPipelineState(ctx.api, { lastSweepAt: now });
3982
4000
  }
3983
4001
  async function sweepExpiredReady(ctx, now) {
@@ -4023,23 +4041,26 @@ async function sweepStalledSending(ctx, now, escalationTag, statePort) {
4023
4041
  await statePort.flag(ref, escalationTag);
4024
4042
  }
4025
4043
  }
4026
- async function sweepStalledPending(ctx, now) {
4044
+ async function sweepStalledPending(ctx, now, escalationTag, statePort) {
4027
4045
  const page = await ctx.api.list("generated-response", { filter: { status: "pending" }, limit: SWEEP_PAGE_SIZE });
4028
4046
  for (const row of page.items) {
4029
4047
  const expiresAt = toDate(row.data.expiresAt);
4030
4048
  if (!expiresAt || expiresAt.getTime() > now.getTime()) continue;
4049
+ const ticketId = row.data.ticketId;
4031
4050
  assertTransition("pending", "failed");
4032
4051
  try {
4033
4052
  await ctx.api.update(
4034
4053
  "generated-response",
4035
4054
  row.id,
4036
- { status: "failed", openTicketKey: openTicketKeyFor("failed", row.data.ticketId), error: "orphaned pending row past its TTL (sweep)" },
4055
+ { status: "failed", openTicketKey: openTicketKeyFor("failed", ticketId), error: "orphaned pending row past its TTL (sweep)" },
4037
4056
  { ifMatch: { status: "pending" } }
4038
4057
  );
4039
4058
  } catch (err) {
4040
4059
  if (err instanceof appKit.AppApiError && err.status === 409) continue;
4041
4060
  throw err;
4042
4061
  }
4062
+ const ref = { id: ticketId, channel: "gorgias" };
4063
+ await statePort.flag(ref, escalationTag);
4043
4064
  }
4044
4065
  }
4045
4066
  function buildHandleApprovalFunctionDef(config) {
@@ -5949,7 +5970,8 @@ var LABELS = {
5949
5970
  G5: "Tag de p\xE9rim\xE8tre pr\xE9sent sur le ticket",
5950
5971
  G6: "Aucune reprise humaine",
5951
5972
  G7: "Cat\xE9gorie r\xE9solue et opt\xE9e",
5952
- G8: "Nouveau message client"
5973
+ G8: "Nouveau message client",
5974
+ G9: "R\xE9ponse ouverte pr\xE9empt\xE9e"
5953
5975
  };
5954
5976
  function humanTakeoverTags(settings) {
5955
5977
  const configured = [settings.escalationTag, settings.needsReviewTag, settings.followupTag].map((tag) => tag.trim()).filter((tag) => tag !== "");
@@ -5975,15 +5997,23 @@ function completeFollowupLadder(results) {
5975
5997
  return missing.length === 0 ? results : [...results, ...skippedFollowupGates(missing)];
5976
5998
  }
5977
5999
  var FRESH_READ_GATES = ["G5", "G6", "G7", "G8"];
5978
- var ALL_FOLLOWUP_GATES = ["G1", "G2", ...FRESH_READ_GATES];
6000
+ var ALL_FOLLOWUP_GATES = ["G1", "G2", ...FRESH_READ_GATES, "G9"];
5979
6001
  function evaluateTicketGates(input) {
5980
- const { settings, tags, categories, conversation, anchor, ignoreCategoryOptIn = false } = input;
6002
+ const {
6003
+ settings,
6004
+ tags,
6005
+ categories,
6006
+ conversation,
6007
+ anchor,
6008
+ openResponse = null,
6009
+ ignoreCategoryOptIn = false
6010
+ } = input;
5981
6011
  const trace = newTrace(FRESH_READ_GATES);
5982
6012
  trace.record(scopeTagOnTicket(settings, tags));
5983
6013
  trace.record(noHumanTakeover(settings, tags));
5984
6014
  const match = trace.record(categoryGate(categories, tags, ignoreCategoryOptIn));
5985
6015
  if (match) trace.category = match;
5986
- trace.record(newCustomerMessage(conversation, anchor));
6016
+ trace.record(newCustomerMessage(conversation, anchor, openResponse));
5987
6017
  return trace.done();
5988
6018
  }
5989
6019
  function evaluatePayloadGates(input) {
@@ -6046,15 +6076,20 @@ function noMatchingCategory() {
6046
6076
  function matchingCategories(categories, tags) {
6047
6077
  return categories.filter((category) => tags.includes(category.tagName));
6048
6078
  }
6049
- function newCustomerMessage(conversation, anchor) {
6079
+ function newCustomerMessage(conversation, anchor, openResponse) {
6050
6080
  if (conversation.isClosed) return stopped("G8", "Le ticket est ferm\xE9.");
6051
6081
  const last = conversation.messages[conversation.messages.length - 1];
6052
6082
  if (!last) return stopped("G8", "La conversation extraite est vide.");
6053
6083
  if (!isCustomerTurnWithWords(last)) {
6054
6084
  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
6085
  }
6056
- if (anchor === null) return passed("G8", "Le dernier message est du client ; aucune r\xE9ponse ant\xE9rieure, donc aucune ancre \xE0 battre.");
6057
6086
  const lastAt = conversation.lastMessageAt;
6087
+ if (openResponse?.status === "pending" && lastAt && openResponse.ownAnchor?.getTime() === lastAt.getTime()) {
6088
+ 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.");
6089
+ }
6090
+ if (anchor === null) {
6091
+ 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.");
6092
+ }
6058
6093
  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
6094
  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
6095
  }
@@ -6265,7 +6300,7 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
6265
6300
  const scope = evaluateScopeGate(settings);
6266
6301
  ladder.push(scope);
6267
6302
  if (scope.status === "stopped") return stopAt(ctx, ticketId, scope, ladder);
6268
- const { anchor, hasOpenResponse } = await readFollowupAnchor(ctx, ticketId);
6303
+ const { anchor, openResponse } = await readFollowupAnchor(ctx, ticketId);
6269
6304
  const categories = await listCategories(ctx.api);
6270
6305
  const preGates = evaluatePayloadGates({ settings, body, categories, anchor });
6271
6306
  if (preGates.stop) {
@@ -6282,6 +6317,7 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
6282
6317
  categories,
6283
6318
  conversation,
6284
6319
  anchor,
6320
+ openResponse,
6285
6321
  ignoreCategoryOptIn: generateOnly
6286
6322
  });
6287
6323
  ladder.push(...gates.results);
@@ -6289,15 +6325,27 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
6289
6325
  return stopAt(ctx, ticketId, gates.stop ?? unresolvedCategory(), ladder);
6290
6326
  }
6291
6327
  const category = gates.category;
6292
- if (hasOpenResponse) return stop(ctx, ticketId, "G9", "une r\xE9ponse est d\xE9j\xE0 ouverte sur ce ticket", ladder);
6328
+ 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.");
6329
+ if (preemption.status === "stopped") {
6330
+ ladder.push(preemption);
6331
+ return stopAt(ctx, ticketId, preemption, ladder);
6332
+ }
6293
6333
  run.id ??= (await ctx.api.runs.start({
6294
6334
  kind: FOLLOWUP_RUN_KIND,
6295
6335
  message: `Message suivant \u2014 ticket ${ticketId}`,
6296
6336
  metadata: { ticketId, categoryTag: category.tagName, channel: body.channel, generateOnly }
6297
6337
  })).id;
6298
6338
  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);
6339
+ const created = await openFollowupResponse(ctx, { ticketId, category, conversation, settings, runId: run.id, ticketUrl, generateOnly });
6340
+ if (!created) {
6341
+ const lost = stopped(
6342
+ "G9",
6343
+ `Une autre ex\xE9cution a ouvert la r\xE9ponse en premier. ${preemption.detail}`.trim()
6344
+ );
6345
+ ladder.push(lost);
6346
+ return stopAt(ctx, ticketId, lost, ladder);
6347
+ }
6348
+ ladder.push(preemption);
6301
6349
  const outcome2 = await respondToPendingResponse(ctx, config, created.id, { testRun: generateOnly });
6302
6350
  return {
6303
6351
  ticketId,
@@ -6318,16 +6366,66 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
6318
6366
  async function readFollowupAnchor(ctx, ticketId) {
6319
6367
  const page = await ctx.api.list("generated-response", { filter: { ticketId }, limit: ANCHOR_LOOKUP_LIMIT });
6320
6368
  let anchor = null;
6321
- let hasOpenResponse = false;
6369
+ let openResponse = null;
6322
6370
  for (const item of page.items) {
6323
6371
  const data = item.data;
6324
- if (data.openTicketKey === ticketId) hasOpenResponse = true;
6372
+ let ownAnchor = null;
6325
6373
  for (const raw of [data.generatedLastMessageAt, data.sentAt]) {
6326
6374
  const at = toDate2(raw);
6375
+ if (at && (!ownAnchor || at > ownAnchor)) ownAnchor = at;
6327
6376
  if (at && (!anchor || at > anchor)) anchor = at;
6328
6377
  }
6378
+ if (data.openTicketKey === ticketId) {
6379
+ openResponse = { id: item.id, status: isGeneratedResponseStatus(data.status) ? data.status : null, ownAnchor };
6380
+ }
6381
+ }
6382
+ return { anchor, openResponse };
6383
+ }
6384
+ var SEND_SETTLE_POLL_MS = 2e3;
6385
+ var SEND_SETTLE_ATTEMPTS = 4;
6386
+ var PREEMPT_ATTEMPTS = 3;
6387
+ async function preemptOpenResponse(ctx, ticketId, open) {
6388
+ let status = open.status;
6389
+ for (let attempt = 1; attempt <= PREEMPT_ATTEMPTS; attempt += 1) {
6390
+ if (status === null) {
6391
+ return stopped("G9", "Une r\xE9ponse ouverte porte un statut illisible : elle doit \xEAtre d\xE9bloqu\xE9e \xE0 la main.");
6392
+ }
6393
+ if (isTerminalStatus(status)) {
6394
+ return passed("G9", "La r\xE9ponse ouverte s'est termin\xE9e d'elle-m\xEAme : le ticket est libre.");
6395
+ }
6396
+ if (status === "sending") {
6397
+ status = await awaitSettledSend(ctx, open.id);
6398
+ if (status === "sending") {
6399
+ ctx.logger.warn(
6400
+ `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`
6401
+ );
6402
+ return stopped("G9", "Une r\xE9ponse est en cours d'envoi et ne se termine pas : au sweep de la r\xE9clamer.");
6403
+ }
6404
+ continue;
6405
+ }
6406
+ if (!canTransition(status, "superseded")) {
6407
+ return stopped("G9", `Une r\xE9ponse au statut \xAB ${status} \xBB tient le ticket et ne peut pas \xEAtre remplac\xE9e.`);
6408
+ }
6409
+ if (await transitionGeneratedResponse(ctx.api, { id: open.id, ticketId, from: status, to: "superseded" })) {
6410
+ return passed("G9", `La r\xE9ponse ouverte (${status}) r\xE9pondait \xE0 un message ant\xE9rieur : remplac\xE9e.`);
6411
+ }
6412
+ status = await readResponseStatus(ctx, open.id);
6413
+ }
6414
+ return stopped("G9", "La r\xE9ponse ouverte change de statut plus vite que ce passage ne peut la remplacer.");
6415
+ }
6416
+ async function awaitSettledSend(ctx, id) {
6417
+ let status = "sending";
6418
+ for (let attempt = 1; attempt <= SEND_SETTLE_ATTEMPTS && status === "sending"; attempt += 1) {
6419
+ await new Promise((resolve) => setTimeout(resolve, SEND_SETTLE_POLL_MS));
6420
+ status = await readResponseStatus(ctx, id);
6329
6421
  }
6330
- return { anchor, hasOpenResponse };
6422
+ return status;
6423
+ }
6424
+ async function readResponseStatus(ctx, id) {
6425
+ const row = await getOptional(ctx, "generated-response", id);
6426
+ if (!row) return "sent";
6427
+ const raw = row.data.status;
6428
+ return isGeneratedResponseStatus(raw) ? raw : null;
6331
6429
  }
6332
6430
  var ANCHOR_LOOKUP_LIMIT = 100;
6333
6431
  function toDate2(raw) {
@@ -6399,6 +6497,15 @@ async function openFollowupResponse(ctx, input) {
6399
6497
  channel: conversation.sourceChannel === "whatsapp" ? "whatsapp" : "email",
6400
6498
  generatedAt,
6401
6499
  expiresAt: new Date(generatedAt.getTime() + settings.responseTtlMinutes * 6e4),
6500
+ // Stamped HERE, not only when `process-response` finishes with the row:
6501
+ // until it exists the draft contributes nothing to §6's anchor, so a
6502
+ // webhook redelivered while it is still `pending` would read "no anchor
6503
+ // to beat" at G8 and draft the very same message all over again.
6504
+ //
6505
+ // Withheld from the operator's essay for the reason §8 keeps it out of
6506
+ // the lifecycle entirely: raising the anchor there would make the REAL
6507
+ // reply to that same message impossible ever after.
6508
+ ...input.generateOnly ? {} : { generatedMessageCount: conversation.messageCount, generatedLastMessageAt: conversation.lastMessageAt },
6402
6509
  sources: [],
6403
6510
  tracedInput: [],
6404
6511
  guardrailHits: [],
@@ -6414,12 +6521,7 @@ async function openFollowupResponse(ctx, input) {
6414
6521
  }
6415
6522
  }
6416
6523
  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
- };
6524
+ return stopped("G7", "Aucune cat\xE9gorie r\xE9solue.");
6423
6525
  }
6424
6526
  function stopAt(ctx, ticketId, result, ladder, kind = "gate") {
6425
6527
  return stop(ctx, ticketId, `${result.gate}${kind === "gate" ? "" : ` (${kind})`}`, result.detail, ladder);
@@ -6488,7 +6590,7 @@ async function diagnose(ctx, ticketId) {
6488
6590
  const scope = evaluateScopeGate(settings);
6489
6591
  gates.push(scope);
6490
6592
  if (scope.status === "stopped") return finish3(gates, ticketId);
6491
- const { anchor } = await readFollowupAnchor(ctx, ticketId);
6593
+ const { anchor, openResponse } = await readFollowupAnchor(ctx, ticketId);
6492
6594
  const categories = await listCategories(ctx.api);
6493
6595
  const ref = { id: ticketId, channel: "gorgias" };
6494
6596
  const ticket = await ctx.api.integrations.run("gorgias", "getTicketWithContext", { ticketId });
@@ -6496,8 +6598,26 @@ async function diagnose(ctx, ticketId) {
6496
6598
  const conversation = toConversation(ref, raw, ticket?.context ?? { messages: [], customerContext: null });
6497
6599
  const trace = evaluateTicketGates({ settings, tags: ticketTagNames(raw), categories, conversation, anchor });
6498
6600
  gates.push(...trace.results);
6601
+ if (!trace.stop) gates.push(predictPreemption(openResponse));
6499
6602
  return finish3(gates, ticketId);
6500
6603
  }
6604
+ function predictPreemption(openResponse) {
6605
+ if (!openResponse) return passed("G9", "Aucune r\xE9ponse ouverte sur ce ticket.");
6606
+ const { status } = openResponse;
6607
+ if (status === null) {
6608
+ return stopped("G9", "Une r\xE9ponse ouverte porte un statut illisible : elle doit \xEAtre d\xE9bloqu\xE9e \xE0 la main.");
6609
+ }
6610
+ if (status === "sending") {
6611
+ return passed("G9", "Une r\xE9ponse est en cours d'envoi : le passage attendrait qu'elle se termine.");
6612
+ }
6613
+ if (isTerminalStatus(status)) {
6614
+ return passed("G9", "La r\xE9ponse ouverte est d\xE9j\xE0 termin\xE9e : le ticket est libre.");
6615
+ }
6616
+ if (!canTransition(status, "superseded")) {
6617
+ return stopped("G9", `Une r\xE9ponse au statut \xAB ${status} \xBB tient le ticket et ne peut pas \xEAtre remplac\xE9e.`);
6618
+ }
6619
+ return passed("G9", `Une r\xE9ponse ouverte (${status}) serait remplac\xE9e.`);
6620
+ }
6501
6621
  function finish3(gates, ticketId) {
6502
6622
  const full = completeFollowupLadder(gates);
6503
6623
  return {