@apotech-os/support-kit 7.0.1 → 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",
@@ -3438,21 +3460,21 @@ async function finalizeNonSent(ctx, id, ticketId, toStatus, extra) {
3438
3460
  throw err;
3439
3461
  }
3440
3462
  }
3441
- async function respondToPendingResponse(ctx, config, recordId) {
3463
+ 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) {
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;
@@ -3473,7 +3495,8 @@ async function respondToPendingResponse(ctx, config, recordId) {
3473
3495
  settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes)),
3474
3496
  origin
3475
3497
  );
3476
- const dryRun = settings.dryRun === true;
3498
+ const testRun = options.testRun === true;
3499
+ const dryRun = settings.dryRun === true || testRun;
3477
3500
  const trace = { sessionId: ticketId, tags: [`app:${config.slug}`] };
3478
3501
  const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx, trace), ctx.api) : buildTicketPorts(ctx, trace);
3479
3502
  const { clock } = ports;
@@ -3527,26 +3550,30 @@ async function respondToPendingResponse(ctx, config, recordId) {
3527
3550
  // sent reply and a held one are read by the same timeline.
3528
3551
  tracedInput: toTracedInput(result.draft?.messages ?? []),
3529
3552
  verdict: result.verdict ?? null,
3530
- generatedMessageCount: conversationSnapshot.messageCount,
3531
- generatedLastMessageAt: conversationSnapshot.lastMessageAt,
3553
+ // Omitted on a test run — see `RespondOptions.testRun`, consequence THREE.
3554
+ ...testRun ? {} : {
3555
+ generatedMessageCount: conversationSnapshot.messageCount,
3556
+ generatedLastMessageAt: conversationSnapshot.lastMessageAt
3557
+ },
3532
3558
  ...attributionFields(result.draft?.attribution)
3533
3559
  };
3560
+ const restingStatus = testRun ? "test_draft" : "ready";
3534
3561
  switch (result.outcome) {
3535
3562
  case "sent":
3536
3563
  if (dryRun) {
3537
- await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3538
- return;
3564
+ await finalizeNonSent(ctx, recordId, ticketId, restingStatus, draftExtra);
3565
+ return result.outcome;
3539
3566
  }
3540
- return;
3567
+ return result.outcome;
3541
3568
  case "ready":
3542
3569
  case "guardrail_hold":
3543
- await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3544
- return;
3570
+ await finalizeNonSent(ctx, recordId, ticketId, restingStatus, draftExtra);
3571
+ return result.outcome;
3545
3572
  case "needs_human":
3546
- await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3547
- return;
3573
+ await finalizeNonSent(ctx, recordId, ticketId, restingStatus, draftExtra);
3574
+ return result.outcome;
3548
3575
  case "awaiting_approval": {
3549
- const persisted = await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3576
+ const persisted = await finalizeNonSent(ctx, recordId, ticketId, restingStatus, draftExtra);
3550
3577
  if (persisted && !dryRun) {
3551
3578
  await ctx.api.approvals.request({
3552
3579
  key: buildApprovalKey(recordId),
@@ -3554,18 +3581,19 @@ async function respondToPendingResponse(ctx, config, recordId) {
3554
3581
  entityRef: { appSlug: config.slug, objectKey: "generated-response", id: recordId }
3555
3582
  });
3556
3583
  }
3557
- return;
3584
+ return result.outcome;
3558
3585
  }
3559
3586
  case "escalated":
3560
3587
  case "triaged_only":
3561
3588
  case "no_reply_needed":
3562
- await finalizeNonSent(ctx, recordId, ticketId, "no_reply_needed", draftExtra);
3563
- return;
3589
+ await finalizeNonSent(ctx, recordId, ticketId, testRun ? restingStatus : "no_reply_needed", draftExtra);
3590
+ return result.outcome;
3564
3591
  case "failed":
3565
3592
  await finalizeNonSent(ctx, recordId, ticketId, "failed", { ...draftExtra, error: "runTicket outcome: failed" });
3566
- return;
3593
+ return result.outcome;
3567
3594
  default:
3568
3595
  ctx.logger.error(`respond: generated-response ${recordId} resumed run ended with no outcome`);
3596
+ return null;
3569
3597
  }
3570
3598
  }
3571
3599
  async function transitionGeneratedResponse(api, params) {
@@ -5863,14 +5891,19 @@ function skippedFollowupGates(gates) {
5863
5891
  detail: "Non \xE9valu\xE9 : un gate pr\xE9c\xE9dent a arr\xEAt\xE9 le traitement."
5864
5892
  }));
5865
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
+ }
5866
5899
  var FRESH_READ_GATES = ["G5", "G6", "G7", "G8"];
5867
5900
  var ALL_FOLLOWUP_GATES = ["G1", "G2", ...FRESH_READ_GATES];
5868
5901
  function evaluateTicketGates(input) {
5869
- const { settings, tags, categories, conversation, anchor } = input;
5902
+ const { settings, tags, categories, conversation, anchor, ignoreCategoryOptIn = false } = input;
5870
5903
  const trace = newTrace(FRESH_READ_GATES);
5871
5904
  trace.record(scopeTagOnTicket(settings, tags));
5872
5905
  trace.record(noHumanTakeover(settings, tags));
5873
- const match = trace.record(categoryGate(categories, tags));
5906
+ const match = trace.record(categoryGate(categories, tags, ignoreCategoryOptIn));
5874
5907
  if (match) trace.category = match;
5875
5908
  trace.record(newCustomerMessage(conversation, anchor));
5876
5909
  return trace.done();
@@ -5887,7 +5920,7 @@ function evaluatePayloadGates(input) {
5887
5920
  } else {
5888
5921
  trace.record(scopeTagOnTicket(settings, tags));
5889
5922
  trace.record(noHumanTakeover(settings, tags));
5890
- trace.record(singleCategoryMatch(categories, tags));
5923
+ trace.record(anyCategoryMatch(categories, tags));
5891
5924
  }
5892
5925
  trace.record(payloadNewCustomerMessage(body, anchor));
5893
5926
  return trace.done();
@@ -5900,25 +5933,37 @@ function noHumanTakeover(settings, tags) {
5900
5933
  const present = humanTakeoverTags(settings).filter((tag) => tags.includes(tag));
5901
5934
  return present.length === 0 ? passed("G6", "Aucun tag de reprise humaine sur le ticket.") : stopped("G6", `Un humain a repris le fil (tag ${present.join(", ")}) : aucune r\xE9ponse automatique.`);
5902
5935
  }
5903
- function categoryGate(categories, tags) {
5904
- const single = singleCategoryMatch(categories, tags);
5905
- if (single.status === "stopped") return single;
5906
- const category = matchingCategories(categories, tags)[0];
5907
- if (!category.followupFastResponseEnabled) {
5908
- return stopped("G7", `La cat\xE9gorie \xAB ${category.name} \xBB n\u2019a pas activ\xE9 les r\xE9ponses aux messages suivants.`);
5909
- }
5910
- if (!category.agentId) {
5911
- return stopped("G7", `La cat\xE9gorie \xAB ${category.name} \xBB n\u2019a aucun agent : personne pour r\xE9diger.`);
5936
+ function categoryGate(categories, tags, ignoreOptIn) {
5937
+ const matches = matchingCategories(categories, tags);
5938
+ if (matches.length === 0) return noMatchingCategory();
5939
+ const eligible = matches.filter((category2) => (ignoreOptIn || category2.followupFastResponseEnabled) && category2.agentId).sort((a, b) => a.order - b.order || a.id.localeCompare(b.id));
5940
+ if (eligible.length === 0) return noEligibleCategory(matches, ignoreOptIn);
5941
+ const category = eligible[0];
5942
+ const detail = matches.length === 1 ? `Cat\xE9gorie \xAB ${category.name} \xBB (tag \xAB ${category.tagName} \xBB).` : `Cat\xE9gorie \xAB ${category.name} \xBB (tag \xAB ${category.tagName} \xBB), retenue parmi ${matches.length} cat\xE9gories correspondantes (${tagList(matches)}).`;
5943
+ return { ...passed("G7", detail), category };
5944
+ }
5945
+ function noEligibleCategory(matches, ignoreOptIn) {
5946
+ if (ignoreOptIn) {
5947
+ return matches.length > 1 ? stopped("G7", `Aucune des ${matches.length} cat\xE9gories correspondantes (${tagList(matches)}) n\u2019a d\u2019agent : personne pour r\xE9diger.`) : stopped("G7", `La cat\xE9gorie \xAB ${matches[0].name} \xBB n\u2019a aucun agent : personne pour r\xE9diger.`);
5948
+ }
5949
+ if (matches.length > 1) {
5950
+ return stopped(
5951
+ "G7",
5952
+ `Aucune des ${matches.length} cat\xE9gories correspondantes (${tagList(matches)}) n\u2019a activ\xE9 les r\xE9ponses aux messages suivants avec un agent pour r\xE9diger.`
5953
+ );
5912
5954
  }
5913
- return { ...passed("G7", `Cat\xE9gorie \xAB ${category.name} \xBB (tag \xAB ${category.tagName} \xBB).`), category };
5955
+ const category = matches[0];
5956
+ return category.followupFastResponseEnabled ? stopped("G7", `La cat\xE9gorie \xAB ${category.name} \xBB n\u2019a aucun agent : personne pour r\xE9diger.`) : stopped("G7", `La cat\xE9gorie \xAB ${category.name} \xBB n\u2019a pas activ\xE9 les r\xE9ponses aux messages suivants.`);
5914
5957
  }
5915
- function singleCategoryMatch(categories, tags) {
5958
+ function tagList(categories) {
5959
+ return categories.map((category) => category.tagName).join(", ");
5960
+ }
5961
+ function anyCategoryMatch(categories, tags) {
5916
5962
  const matches = matchingCategories(categories, tags);
5917
- if (matches.length === 1) return passed("G7", `Cat\xE9gorie \xAB ${matches[0].name} \xBB.`);
5918
- return matches.length === 0 ? stopped("G7", "Aucune cat\xE9gorie ne correspond \xE0 un tag du ticket : la d\xE9cision de triage est illisible.") : stopped(
5919
- "G7",
5920
- `${matches.length} cat\xE9gories correspondent aux tags du ticket (${matches.map((c) => c.tagName).join(", ")}) : d\xE9cision ambigu\xEB.`
5921
- );
5963
+ return matches.length === 0 ? noMatchingCategory() : passed("G7", `Cat\xE9gorie \xAB ${matches[0].name} \xBB.`);
5964
+ }
5965
+ function noMatchingCategory() {
5966
+ return stopped("G7", "Aucune cat\xE9gorie ne correspond \xE0 un tag du ticket : la d\xE9cision de triage est illisible.");
5922
5967
  }
5923
5968
  function matchingCategories(categories, tags) {
5924
5969
  return categories.filter((category) => tags.includes(category.tagName));
@@ -6112,54 +6157,83 @@ function createGorgiasWebhookHandler(config) {
6112
6157
  function createGorgiasFollowupRunHandler(config) {
6113
6158
  return (ctx, payload) => {
6114
6159
  const event = payload ?? {};
6115
- return executeFollowupRun(ctx, config, event.body, event.runId ?? null);
6160
+ return executeFollowupRun(ctx, config, event.body, event.runId ?? null, {
6161
+ generateOnly: event.generateOnly === true
6162
+ });
6116
6163
  };
6117
6164
  }
6118
- async function executeFollowupRun(ctx, config, rawBody, existingRunId) {
6165
+ async function executeFollowupRun(ctx, config, rawBody, existingRunId, options = {}) {
6119
6166
  const run = { id: existingRunId };
6120
6167
  try {
6121
- const result = await runFollowupPass(ctx, config, rawBody, run);
6168
+ const result = await runFollowupPass(ctx, config, rawBody, run, options.generateOnly === true);
6122
6169
  if (run.id) await ctx.api.runs.succeed(run.id, { ...result });
6123
6170
  } catch (err) {
6124
6171
  if (run.id) await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });
6125
6172
  throw err;
6126
6173
  }
6127
6174
  }
6128
- async function runFollowupPass(ctx, config, rawBody, run) {
6175
+ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
6129
6176
  const body = parseFollowupWebhookBody(rawBody);
6177
+ const ladder = [];
6130
6178
  const ticketIdGate = evaluateTicketIdGate(body.ticketId);
6131
- 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);
6132
6181
  const ticketId = body.ticketId;
6133
6182
  const settings = await ctx.api.settings.get();
6134
6183
  const issues = validateSettings(settings);
6135
6184
  if (issues.length > 0) {
6136
- 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);
6137
6186
  }
6138
6187
  const scope = evaluateScopeGate(settings);
6139
- if (scope.status === "stopped") return stopAt(ctx, ticketId, scope);
6188
+ ladder.push(scope);
6189
+ if (scope.status === "stopped") return stopAt(ctx, ticketId, scope, ladder);
6140
6190
  const { anchor, hasOpenResponse } = await readFollowupAnchor(ctx, ticketId);
6141
6191
  const categories = await listCategories(ctx.api);
6142
6192
  const preGates = evaluatePayloadGates({ settings, body, categories, anchor });
6143
- 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
+ }
6144
6197
  const ref = { id: ticketId, channel: "gorgias" };
6145
6198
  const ticket = await ctx.api.integrations.run("gorgias", "getTicketWithContext", { ticketId });
6146
6199
  const raw = ticket?.ticket ?? {};
6147
6200
  const conversation = toConversation(ref, raw, ticket?.context ?? { messages: [], customerContext: null });
6148
- const gates = evaluateTicketGates({ settings, tags: ticketTagNames(raw), categories, conversation, anchor });
6201
+ const gates = evaluateTicketGates({
6202
+ settings,
6203
+ tags: ticketTagNames(raw),
6204
+ categories,
6205
+ conversation,
6206
+ anchor,
6207
+ ignoreCategoryOptIn: generateOnly
6208
+ });
6209
+ ladder.push(...gates.results);
6149
6210
  if (gates.stop || !gates.category) {
6150
- return stopAt(ctx, ticketId, gates.stop ?? unresolvedCategory());
6211
+ return stopAt(ctx, ticketId, gates.stop ?? unresolvedCategory(), ladder);
6151
6212
  }
6152
6213
  const category = gates.category;
6153
- 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);
6154
6215
  run.id ??= (await ctx.api.runs.start({
6155
6216
  kind: FOLLOWUP_RUN_KIND,
6156
6217
  message: `Message suivant \u2014 ticket ${ticketId}`,
6157
- metadata: { ticketId, categoryTag: category.tagName, channel: body.channel }
6218
+ metadata: { ticketId, categoryTag: category.tagName, channel: body.channel, generateOnly }
6158
6219
  })).id;
6159
6220
  const created = await openFollowupResponse(ctx, { ticketId, category, conversation, settings, runId: run.id });
6160
- if (!created) return stop(ctx, ticketId, "G9", "une autre ex\xE9cution a ouvert la r\xE9ponse en premier");
6161
- await respondToPendingResponse(ctx, config, created.id);
6162
- return { ticketId, stoppedAt: null, reason: `r\xE9ponse de suite g\xE9n\xE9r\xE9e (cat\xE9gorie \xAB ${category.name} \xBB)` };
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 });
6223
+ return {
6224
+ ticketId,
6225
+ stoppedAt: null,
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
6236
+ };
6163
6237
  }
6164
6238
  async function readFollowupAnchor(ctx, ticketId) {
6165
6239
  const page = await ctx.api.list("generated-response", { filter: { ticketId }, limit: ANCHOR_LOOKUP_LIMIT });
@@ -6250,7 +6324,8 @@ async function openFollowupResponse(ctx, input) {
6250
6324
  servedTo: [],
6251
6325
  servedCount: 0,
6252
6326
  followupRequired: false,
6253
- origin: "followup"
6327
+ origin: "followup",
6328
+ runId
6254
6329
  });
6255
6330
  } catch (err) {
6256
6331
  if (err instanceof appKit.AppApiError && err.status === 409) return null;
@@ -6265,85 +6340,23 @@ function unresolvedCategory() {
6265
6340
  detail: "Aucune cat\xE9gorie r\xE9solue."
6266
6341
  };
6267
6342
  }
6268
- function stopAt(ctx, ticketId, result, kind = "gate") {
6269
- 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);
6270
6345
  }
6271
- function stop(ctx, ticketId, gate, reason) {
6346
+ function stop(ctx, ticketId, gate, reason, ladder) {
6272
6347
  ctx.logger.info(`gorgias-webhook: stop at ${gate} for ticket ${ticketId ?? "?"} \u2014 ${reason}`);
6273
- return { ticketId, stoppedAt: gate, reason };
6274
- }
6275
-
6276
- // src/functions/setup-gorgias-webhook.ts
6277
- var GORGIAS_CALLBACK_APP_KEY_VARIABLE = "GORGIAS_CALLBACK_APP_KEY";
6278
- var APP_API_KEY_PREFIX = "wopilo_app_";
6279
- var FOLLOWUP_WEBHOOK_FORM = {
6280
- ticket_id: "{{ticket.id}}",
6281
- channel: "{{ticket.channel}}",
6282
- last_message_datetime: "{{ticket.last_message_datetime}}",
6283
- status: "{{ticket.status}}",
6284
- tags: "{{ticket.tags}}",
6285
- last_message_from_agent: "{{ticket.messages[-1].from_agent}}",
6286
- last_message_public: "{{ticket.messages[-1].public}}"
6287
- };
6288
- var FOLLOWUP_WEBHOOK_TRIGGERS = { "ticket-message-created": true };
6289
- function followupIntegrationName(slug) {
6290
- return `Wopilo \u2014 R\xE9ponses aux messages suivants (${slug})`;
6291
- }
6292
- function buildSetupGorgiasWebhookFunctionDef(config) {
6293
6348
  return {
6294
- universalIdentifier: identifierFor(config, "setup-gorgias-webhook"),
6295
- name: "setup-gorgias-webhook",
6296
- trigger: { type: "uiInvoke", minRole: "ADMIN", timeoutMs: 2e4 }
6297
- };
6298
- }
6299
- function createSetupGorgiasWebhookHandler(config) {
6300
- return (ctx) => setupGorgiasWebhookHandler(ctx, config);
6301
- }
6302
- async function setupGorgiasWebhookHandler(ctx, config) {
6303
- const key = readCallbackKey(ctx);
6304
- const name = followupIntegrationName(config.slug);
6305
- const url = `${publicOrigin(ctx)}/api/s/${config.slug}/gorgias/webhook`;
6306
- const result = await ctx.api.integrations.run("gorgias", "upsertHttpIntegration", {
6307
- name,
6308
- description: "Rappelle Wopilo \xE0 chaque nouveau message de ticket, pour r\xE9pondre aux messages suivants.",
6309
- url,
6310
- method: "POST",
6311
- headers: { Authorization: `Bearer ${key}` },
6312
- form: FOLLOWUP_WEBHOOK_FORM,
6313
- triggers: FOLLOWUP_WEBHOOK_TRIGGERS
6314
- });
6315
- ctx.logger.info(`setup-gorgias-webhook: int\xE9gration \xAB ${name} \xBB pos\xE9e sur ${url}`);
6316
- return {
6317
- integrationId: String(result?.id ?? ""),
6318
- created: result?.created === true,
6319
- name,
6320
- url
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
6321
6358
  };
6322
6359
  }
6323
- function readCallbackKey(ctx) {
6324
- const raw = ctx.variables[GORGIAS_CALLBACK_APP_KEY_VARIABLE];
6325
- const key = typeof raw === "string" ? raw.trim() : "";
6326
- if (!key) {
6327
- throw new ctx.NonRetriableError(
6328
- `La variable serveur ${GORGIAS_CALLBACK_APP_KEY_VARIABLE} n'est pas renseign\xE9e : Gorgias n'aurait aucun moyen de s'authentifier aupr\xE8s de cette app.`
6329
- );
6330
- }
6331
- if (!key.startsWith(APP_API_KEY_PREFIX)) {
6332
- throw new ctx.NonRetriableError(
6333
- `La variable serveur ${GORGIAS_CALLBACK_APP_KEY_VARIABLE} ne contient pas une cl\xE9 d'application : elle doit commencer par \xAB ${APP_API_KEY_PREFIX} \xBB.`
6334
- );
6335
- }
6336
- return key;
6337
- }
6338
- function publicOrigin(ctx) {
6339
- const base = process.env.PUBLIC_BASE_URL?.trim().replace(/\/+$/, "");
6340
- if (!base) {
6341
- throw new ctx.NonRetriableError(
6342
- "La variable d'instance PUBLIC_BASE_URL n'est pas d\xE9finie : impossible de construire une URL de rappel que Gorgias puisse joindre."
6343
- );
6344
- }
6345
- return base;
6346
- }
6347
6360
  function buildTestGorgiasWebhookFunctionDef(config) {
6348
6361
  return {
6349
6362
  universalIdentifier: identifierFor(config, "test-gorgias-webhook"),
@@ -6363,7 +6376,7 @@ function buildTestGorgiasWebhookFunctionDef(config) {
6363
6376
  name: "mode",
6364
6377
  type: appKit.FieldType.TEXT,
6365
6378
  label: "Mode",
6366
- description: "'diagnostic' (d\xE9faut) \xE9value les gates sans aucun effet de bord ; 'run' d\xE9clenche le vrai traitement, envoi compris si la cat\xE9gorie est en auto.",
6379
+ description: "'diagnostic' (d\xE9faut) \xE9value les gates sans aucun effet de bord ; 'generate' g\xE9n\xE8re la r\xE9ponse sans jamais l'envoyer, m\xEAme si la cat\xE9gorie n'a pas opt\xE9 ; 'run' d\xE9clenche le vrai traitement, envoi compris si la cat\xE9gorie est en auto.",
6367
6380
  isNullable: true
6368
6381
  }
6369
6382
  ]
@@ -6375,12 +6388,10 @@ function createTestGorgiasWebhookHandler(_config) {
6375
6388
  var NUMERIC2 = /^\d+$/;
6376
6389
  async function testGorgiasWebhookHandler(ctx, input) {
6377
6390
  const ticketId = typeof input.ticketId === "string" && NUMERIC2.test(input.ticketId.trim()) ? input.ticketId.trim() : null;
6378
- const mode = input.mode === "run" ? "run" : "diagnostic";
6379
- if (mode === "run") {
6380
- if (!ticketId) throw new ctx.NonRetriableError("L'identifiant du ticket doit \xEAtre une suite de chiffres.");
6381
- return triggerRealRun(ctx, ticketId);
6382
- }
6383
- return diagnose(ctx, ticketId);
6391
+ const mode = input.mode === "run" ? "run" : input.mode === "generate" ? "generate" : "diagnostic";
6392
+ if (mode === "diagnostic") return diagnose(ctx, ticketId);
6393
+ if (!ticketId) throw new ctx.NonRetriableError("L'identifiant du ticket doit \xEAtre une suite de chiffres.");
6394
+ return triggerRun(ctx, ticketId, mode);
6384
6395
  }
6385
6396
  async function diagnose(ctx, ticketId) {
6386
6397
  const gates = [];
@@ -6406,9 +6417,7 @@ async function diagnose(ctx, ticketId) {
6406
6417
  return finish3(gates, ticketId);
6407
6418
  }
6408
6419
  function finish3(gates, ticketId) {
6409
- const evaluated = new Set(gates.map((gate) => gate.gate));
6410
- const missing = ALL_FOLLOWUP_GATES.filter((gate) => !evaluated.has(gate));
6411
- const full = [...gates, ...skippedFollowupGates(missing)];
6420
+ const full = completeFollowupLadder(gates);
6412
6421
  return {
6413
6422
  mode: "diagnostic",
6414
6423
  ticketId,
@@ -6416,23 +6425,25 @@ function finish3(gates, ticketId) {
6416
6425
  gates: full
6417
6426
  };
6418
6427
  }
6419
- async function triggerRealRun(ctx, ticketId) {
6428
+ async function triggerRun(ctx, ticketId, mode) {
6429
+ const generateOnly = mode === "generate";
6420
6430
  const run = await ctx.api.runs.start({
6421
6431
  kind: FOLLOWUP_RUN_KIND,
6422
- message: `Test webhook \u2014 ticket ${ticketId}`,
6423
- metadata: { ticketId, triggeredFrom: "test-gorgias-webhook" }
6432
+ message: generateOnly ? `Test webhook sans envoi \u2014 ticket ${ticketId}` : `Test webhook \u2014 ticket ${ticketId}`,
6433
+ metadata: { ticketId, triggeredFrom: "test-gorgias-webhook", generateOnly }
6424
6434
  });
6425
6435
  try {
6426
6436
  await ctx.api.events.send(FOLLOWUP_RUN_REQUESTED_EVENT, {
6427
6437
  _key: run.id,
6428
6438
  runId: run.id,
6429
- body: { ticket_id: ticketId }
6439
+ body: { ticket_id: ticketId },
6440
+ generateOnly
6430
6441
  });
6431
6442
  } catch (err) {
6432
6443
  await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });
6433
6444
  throw err;
6434
6445
  }
6435
- return { mode: "run", ticketId, runId: run.id };
6446
+ return { mode, ticketId, runId: run.id };
6436
6447
  }
6437
6448
 
6438
6449
  // src/pages/manifest.ts
@@ -6458,24 +6469,9 @@ var SUPPORT_KIT_GORGIAS_SCOPES = [
6458
6469
  "read_tickets",
6459
6470
  "read_views",
6460
6471
  "write_tags",
6461
- "write_tickets",
6462
- // What `upsertHttpIntegration` demands (its own `scopes`, in
6463
- // `packages/gorgias-client/src/sidebar-widget.ts`). The name says "widgets"
6464
- // because that action's sibling posts one; this kit posts no widget, only
6465
- // the HTTP integration the same scope governs. Requesting it makes the
6466
- // consent modal state, honestly, that the app may write an integration on
6467
- // the account.
6468
- "write_widgets"
6469
- ];
6470
- var SUPPORT_KIT_SERVER_VARIABLES = [
6471
- {
6472
- universalIdentifier: "4dd02108-ba4c-441e-9ea3-ec86f8bf3a1f",
6473
- name: GORGIAS_CALLBACK_APP_KEY_VARIABLE,
6474
- description: "Cl\xE9 d'application (wopilo_app_\u2026) que Gorgias pr\xE9sente en rappelant la route des messages suivants. Saisie par app ; elle porte le r\xF4le manifeste complet de l'app (voir docs/app-platform/gorgias-callback-authentication.md \xA75).",
6475
- type: "STRING",
6476
- isRequired: false
6477
- }
6472
+ "write_tickets"
6478
6473
  ];
6474
+ var SUPPORT_KIT_SERVER_VARIABLES = [];
6479
6475
  var SUPPORT_KIT_INTEGRATIONS = [
6480
6476
  { provider: "gorgias", scopes: [...SUPPORT_KIT_GORGIAS_SCOPES] }
6481
6477
  ];
@@ -6586,11 +6582,6 @@ var FUNCTION_ASSEMBLY = [
6586
6582
  build: buildGorgiasFollowupRunFunctionDef,
6587
6583
  createHandler: createGorgiasFollowupRunHandler
6588
6584
  },
6589
- {
6590
- key: "setup-gorgias-webhook",
6591
- build: buildSetupGorgiasWebhookFunctionDef,
6592
- createHandler: createSetupGorgiasWebhookHandler
6593
- },
6594
6585
  {
6595
6586
  key: "test-gorgias-webhook",
6596
6587
  build: buildTestGorgiasWebhookFunctionDef,