@apotech-os/support-kit 8.0.0 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1128,20 +1128,33 @@ var GENERATED_RESPONSE_STATUSES = [
1128
1128
  "failed",
1129
1129
  "no_reply_needed",
1130
1130
  "invalidated",
1131
- "expired"
1131
+ "expired",
1132
+ // 24/09/2026 — where "générer sans envoyer" rests its draft. It used to
1133
+ // finalize as `invalidated`, which the ticket page and the dashboard both
1134
+ // read as "an agent had already answered": the test artefact was stored,
1135
+ // but disguised as a human intervention. Terminal on purpose — nothing may
1136
+ // serve, send or revive a test draft — and terminal is also what frees the
1137
+ // `openTicketKey` (see `openTicketKeyFor`), so an essay can never hold the
1138
+ // real webhook at G9.
1139
+ "test_draft"
1132
1140
  ];
1133
1141
  function isGeneratedResponseStatus(value) {
1134
1142
  return typeof value === "string" && GENERATED_RESPONSE_STATUSES.includes(value);
1135
1143
  }
1136
1144
  var ALLOWED_TRANSITIONS = {
1137
- pending: ["ready", "failed", "no_reply_needed", "sending", "invalidated"],
1145
+ // `pending -> test_draft` is the ONLY way in: the test pass finalizes the
1146
+ // very `pending` row it opened, and no other status can become a test
1147
+ // draft after the fact — an operator invalidating a real `ready` draft is
1148
+ // expressing "discard this", not "this was an essay".
1149
+ pending: ["ready", "failed", "no_reply_needed", "sending", "invalidated", "test_draft"],
1138
1150
  ready: ["sending", "invalidated", "expired"],
1139
1151
  sending: ["sent", "ready"],
1140
1152
  sent: [],
1141
1153
  failed: [],
1142
1154
  no_reply_needed: [],
1143
1155
  invalidated: [],
1144
- expired: []
1156
+ expired: [],
1157
+ test_draft: []
1145
1158
  };
1146
1159
  function canTransition(from, to) {
1147
1160
  if (!isGeneratedResponseStatus(from) || !isGeneratedResponseStatus(to)) return false;
@@ -1426,6 +1439,7 @@ var GENERATED_RESPONSE_FIELD_GENERATED_LAST_MESSAGE_AT_UID = "94c4594f-4ad0-4e3b
1426
1439
  var GENERATED_RESPONSE_FIELD_SENDING_AT_UID = "2ae9634b-79bb-42d2-a949-8b0f1ac9c763";
1427
1440
  var GENERATED_RESPONSE_FIELD_OUTCOME_UID = "8834b334-8f91-46f7-9bb9-96b69092d0ae";
1428
1441
  var GENERATED_RESPONSE_FIELD_ORIGIN_UID = "e75034d3-ee7f-40e7-b4fe-8be7b4322bdc";
1442
+ var GENERATED_RESPONSE_FIELD_RUN_ID_UID = "f3448bca-9c59-418f-9509-ce0e43eb8768";
1429
1443
  var GENERATED_RESPONSE_INDEX_TICKET_ID_UID = "a4534d26-8f43-4510-9c03-0b28c3d3f8e2";
1430
1444
  var GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID = "3d430166-07a2-43c2-911b-89ec25d13f64";
1431
1445
  var GENERATED_RESPONSE_INDEX_STATUS_UID = "f5c4e5d4-0810-424d-8a14-617e9555a7f3";
@@ -2117,6 +2131,14 @@ function buildGeneratedResponseRecord(slug) {
2117
2131
  description: "When status became 'sending' \u2014 the sweep's staleness clock (\xA73.5).",
2118
2132
  isNullable: true
2119
2133
  },
2134
+ {
2135
+ universalIdentifier: GENERATED_RESPONSE_FIELD_RUN_ID_UID,
2136
+ name: "runId",
2137
+ type: appKit.FieldType.TEXT,
2138
+ label: "Run id",
2139
+ description: "Applicative run this row was written under \u2014 `triage-decision.runId`'s twin, set by the follow-up pass (openFollowupResponse). Nullable: triage-tick's own creations predate their run linkage.",
2140
+ isNullable: true
2141
+ },
2120
2142
  {
2121
2143
  universalIdentifier: GENERATED_RESPONSE_FIELD_ORIGIN_UID,
2122
2144
  name: "origin",
@@ -3442,17 +3464,17 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
3442
3464
  const record = await getOptional(ctx, "generated-response", recordId);
3443
3465
  if (!record) {
3444
3466
  ctx.logger.info(`respond: generated-response ${recordId} no longer exists, skipping`);
3445
- return;
3467
+ return null;
3446
3468
  }
3447
3469
  const data = record.data;
3448
3470
  if (data.status !== "pending") {
3449
3471
  ctx.logger.info(`respond: generated-response ${recordId} is not pending (status="${String(data.status)}"), skipping \u2014 already handled by another worker`);
3450
- return;
3472
+ return null;
3451
3473
  }
3452
3474
  const settings = await ctx.api.settings.get();
3453
3475
  if (validateSettings(settings).length > 0) {
3454
3476
  ctx.logger.info("respond: settings invalid, skipping");
3455
- return;
3477
+ return null;
3456
3478
  }
3457
3479
  const ticketId = data.ticketId;
3458
3480
  const ref = { id: ticketId, channel: "gorgias" };
@@ -3460,7 +3482,7 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
3460
3482
  if (!decision) {
3461
3483
  ctx.logger.error(`respond: generated-response ${recordId} has no resolvable triage-decision, marking failed`);
3462
3484
  await finalizeNonSent(ctx, recordId, ticketId, "failed", { error: "triage-decision not found" });
3463
- return;
3485
+ return null;
3464
3486
  }
3465
3487
  const classification = classificationFromDecision(decision);
3466
3488
  const escalated = decision.data.escalated === true;
@@ -3535,21 +3557,21 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
3535
3557
  },
3536
3558
  ...attributionFields(result.draft?.attribution)
3537
3559
  };
3538
- const restingStatus = testRun ? "invalidated" : "ready";
3560
+ const restingStatus = testRun ? "test_draft" : "ready";
3539
3561
  switch (result.outcome) {
3540
3562
  case "sent":
3541
3563
  if (dryRun) {
3542
3564
  await finalizeNonSent(ctx, recordId, ticketId, restingStatus, draftExtra);
3543
- return;
3565
+ return result.outcome;
3544
3566
  }
3545
- return;
3567
+ return result.outcome;
3546
3568
  case "ready":
3547
3569
  case "guardrail_hold":
3548
3570
  await finalizeNonSent(ctx, recordId, ticketId, restingStatus, draftExtra);
3549
- return;
3571
+ return result.outcome;
3550
3572
  case "needs_human":
3551
3573
  await finalizeNonSent(ctx, recordId, ticketId, restingStatus, draftExtra);
3552
- return;
3574
+ return result.outcome;
3553
3575
  case "awaiting_approval": {
3554
3576
  const persisted = await finalizeNonSent(ctx, recordId, ticketId, restingStatus, draftExtra);
3555
3577
  if (persisted && !dryRun) {
@@ -3559,18 +3581,19 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
3559
3581
  entityRef: { appSlug: config.slug, objectKey: "generated-response", id: recordId }
3560
3582
  });
3561
3583
  }
3562
- return;
3584
+ return result.outcome;
3563
3585
  }
3564
3586
  case "escalated":
3565
3587
  case "triaged_only":
3566
3588
  case "no_reply_needed":
3567
- await finalizeNonSent(ctx, recordId, ticketId, "no_reply_needed", draftExtra);
3568
- return;
3589
+ await finalizeNonSent(ctx, recordId, ticketId, testRun ? restingStatus : "no_reply_needed", draftExtra);
3590
+ return result.outcome;
3569
3591
  case "failed":
3570
3592
  await finalizeNonSent(ctx, recordId, ticketId, "failed", { ...draftExtra, error: "runTicket outcome: failed" });
3571
- return;
3593
+ return result.outcome;
3572
3594
  default:
3573
3595
  ctx.logger.error(`respond: generated-response ${recordId} resumed run ended with no outcome`);
3596
+ return null;
3574
3597
  }
3575
3598
  }
3576
3599
  async function transitionGeneratedResponse(api, params) {
@@ -5868,6 +5891,11 @@ function skippedFollowupGates(gates) {
5868
5891
  detail: "Non \xE9valu\xE9 : un gate pr\xE9c\xE9dent a arr\xEAt\xE9 le traitement."
5869
5892
  }));
5870
5893
  }
5894
+ function completeFollowupLadder(results) {
5895
+ const evaluated = new Set(results.map((result) => result.gate));
5896
+ const missing = ALL_FOLLOWUP_GATES.filter((gate) => !evaluated.has(gate));
5897
+ return missing.length === 0 ? results : [...results, ...skippedFollowupGates(missing)];
5898
+ }
5871
5899
  var FRESH_READ_GATES = ["G5", "G6", "G7", "G8"];
5872
5900
  var ALL_FOLLOWUP_GATES = ["G1", "G2", ...FRESH_READ_GATES];
5873
5901
  function evaluateTicketGates(input) {
@@ -6146,20 +6174,26 @@ async function executeFollowupRun(ctx, config, rawBody, existingRunId, options =
6146
6174
  }
6147
6175
  async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
6148
6176
  const body = parseFollowupWebhookBody(rawBody);
6177
+ const ladder = [];
6149
6178
  const ticketIdGate = evaluateTicketIdGate(body.ticketId);
6150
- if (!body.ticketId) return stop(ctx, null, ticketIdGate.gate, ticketIdGate.detail);
6179
+ ladder.push(ticketIdGate);
6180
+ if (!body.ticketId) return stop(ctx, null, ticketIdGate.gate, ticketIdGate.detail, ladder);
6151
6181
  const ticketId = body.ticketId;
6152
6182
  const settings = await ctx.api.settings.get();
6153
6183
  const issues = validateSettings(settings);
6154
6184
  if (issues.length > 0) {
6155
- return stop(ctx, ticketId, "settings", `r\xE9glages invalides : ${issues.map((issue) => issue.message).join(" ")}`);
6185
+ return stop(ctx, ticketId, "settings", `r\xE9glages invalides : ${issues.map((issue) => issue.message).join(" ")}`, ladder);
6156
6186
  }
6157
6187
  const scope = evaluateScopeGate(settings);
6158
- if (scope.status === "stopped") return stopAt(ctx, ticketId, scope);
6188
+ ladder.push(scope);
6189
+ if (scope.status === "stopped") return stopAt(ctx, ticketId, scope, ladder);
6159
6190
  const { anchor, hasOpenResponse } = await readFollowupAnchor(ctx, ticketId);
6160
6191
  const categories = await listCategories(ctx.api);
6161
6192
  const preGates = evaluatePayloadGates({ settings, body, categories, anchor });
6162
- if (preGates.stop) return stopAt(ctx, ticketId, preGates.stop, "pr\xE9-gate");
6193
+ if (preGates.stop) {
6194
+ ladder.push(...preGates.results);
6195
+ return stopAt(ctx, ticketId, preGates.stop, ladder, "pr\xE9-gate");
6196
+ }
6163
6197
  const ref = { id: ticketId, channel: "gorgias" };
6164
6198
  const ticket = await ctx.api.integrations.run("gorgias", "getTicketWithContext", { ticketId });
6165
6199
  const raw = ticket?.ticket ?? {};
@@ -6172,23 +6206,33 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
6172
6206
  anchor,
6173
6207
  ignoreCategoryOptIn: generateOnly
6174
6208
  });
6209
+ ladder.push(...gates.results);
6175
6210
  if (gates.stop || !gates.category) {
6176
- return stopAt(ctx, ticketId, gates.stop ?? unresolvedCategory());
6211
+ return stopAt(ctx, ticketId, gates.stop ?? unresolvedCategory(), ladder);
6177
6212
  }
6178
6213
  const category = gates.category;
6179
- if (hasOpenResponse) return stop(ctx, ticketId, "G9", "une r\xE9ponse est d\xE9j\xE0 ouverte sur ce ticket");
6214
+ if (hasOpenResponse) return stop(ctx, ticketId, "G9", "une r\xE9ponse est d\xE9j\xE0 ouverte sur ce ticket", ladder);
6180
6215
  run.id ??= (await ctx.api.runs.start({
6181
6216
  kind: FOLLOWUP_RUN_KIND,
6182
6217
  message: `Message suivant \u2014 ticket ${ticketId}`,
6183
6218
  metadata: { ticketId, categoryTag: category.tagName, channel: body.channel, generateOnly }
6184
6219
  })).id;
6185
6220
  const created = await openFollowupResponse(ctx, { ticketId, category, conversation, settings, runId: run.id });
6186
- if (!created) return stop(ctx, ticketId, "G9", "une autre ex\xE9cution a ouvert la r\xE9ponse en premier");
6187
- await respondToPendingResponse(ctx, config, created.id, { testRun: generateOnly });
6221
+ if (!created) return stop(ctx, ticketId, "G9", "une autre ex\xE9cution a ouvert la r\xE9ponse en premier", ladder);
6222
+ const outcome2 = await respondToPendingResponse(ctx, config, created.id, { testRun: generateOnly });
6188
6223
  return {
6189
6224
  ticketId,
6190
6225
  stoppedAt: null,
6191
- reason: generateOnly ? `r\xE9ponse de suite g\xE9n\xE9r\xE9e sans envoi (cat\xE9gorie \xAB ${category.name} \xBB)` : `r\xE9ponse de suite g\xE9n\xE9r\xE9e (cat\xE9gorie \xAB ${category.name} \xBB)`
6226
+ reason: generateOnly ? `r\xE9ponse de suite g\xE9n\xE9r\xE9e sans envoi (cat\xE9gorie \xAB ${category.name} \xBB)` : `r\xE9ponse de suite g\xE9n\xE9r\xE9e (cat\xE9gorie \xAB ${category.name} \xBB)`,
6227
+ gates: completeFollowupLadder(ladder),
6228
+ categoryId: category.id,
6229
+ categoryName: category.name,
6230
+ // Off the ROW, not off the category: `openFollowupResponse` resolves a
6231
+ // default agent when the category names none, and the row records who
6232
+ // actually wrote.
6233
+ agentId: created.data.agentId ?? null,
6234
+ outcome: outcome2,
6235
+ responseId: created.id
6192
6236
  };
6193
6237
  }
6194
6238
  async function readFollowupAnchor(ctx, ticketId) {
@@ -6280,7 +6324,8 @@ async function openFollowupResponse(ctx, input) {
6280
6324
  servedTo: [],
6281
6325
  servedCount: 0,
6282
6326
  followupRequired: false,
6283
- origin: "followup"
6327
+ origin: "followup",
6328
+ runId
6284
6329
  });
6285
6330
  } catch (err) {
6286
6331
  if (err instanceof appKit.AppApiError && err.status === 409) return null;
@@ -6295,12 +6340,22 @@ function unresolvedCategory() {
6295
6340
  detail: "Aucune cat\xE9gorie r\xE9solue."
6296
6341
  };
6297
6342
  }
6298
- function stopAt(ctx, ticketId, result, kind = "gate") {
6299
- return stop(ctx, ticketId, `${result.gate}${kind === "gate" ? "" : ` (${kind})`}`, result.detail);
6343
+ function stopAt(ctx, ticketId, result, ladder, kind = "gate") {
6344
+ return stop(ctx, ticketId, `${result.gate}${kind === "gate" ? "" : ` (${kind})`}`, result.detail, ladder);
6300
6345
  }
6301
- function stop(ctx, ticketId, gate, reason) {
6346
+ function stop(ctx, ticketId, gate, reason, ladder) {
6302
6347
  ctx.logger.info(`gorgias-webhook: stop at ${gate} for ticket ${ticketId ?? "?"} \u2014 ${reason}`);
6303
- return { ticketId, stoppedAt: gate, reason };
6348
+ return {
6349
+ ticketId,
6350
+ stoppedAt: gate,
6351
+ reason,
6352
+ gates: completeFollowupLadder(ladder),
6353
+ categoryId: null,
6354
+ categoryName: null,
6355
+ agentId: null,
6356
+ outcome: null,
6357
+ responseId: null
6358
+ };
6304
6359
  }
6305
6360
  function buildTestGorgiasWebhookFunctionDef(config) {
6306
6361
  return {
@@ -6362,9 +6417,7 @@ async function diagnose(ctx, ticketId) {
6362
6417
  return finish3(gates, ticketId);
6363
6418
  }
6364
6419
  function finish3(gates, ticketId) {
6365
- const evaluated = new Set(gates.map((gate) => gate.gate));
6366
- const missing = ALL_FOLLOWUP_GATES.filter((gate) => !evaluated.has(gate));
6367
- const full = [...gates, ...skippedFollowupGates(missing)];
6420
+ const full = completeFollowupLadder(gates);
6368
6421
  return {
6369
6422
  mode: "diagnostic",
6370
6423
  ticketId,