@apotech-os/support-kit 7.0.0 → 8.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
@@ -28,6 +28,17 @@ function requiresFollowup(verdict) {
28
28
  return verdict === "send_and_escalate";
29
29
  }
30
30
 
31
+ // src/domain/origin.ts
32
+ var DECISION_ORIGINS = ["triage", "followup"];
33
+ var DEFAULT_DECISION_ORIGIN = "triage";
34
+ var ORIGIN_DESCRIPTION = "Which pass wrote this row: 'triage' (the cron's first pass) or 'followup' (a reply to a subsequent customer message, spec-gorgias-followup-webhook-v1 \xA77.2).";
35
+ function isDecisionOrigin(value) {
36
+ return typeof value === "string" && DECISION_ORIGINS.includes(value);
37
+ }
38
+ function toDecisionOrigin(value) {
39
+ return isDecisionOrigin(value) ? value : DEFAULT_DECISION_ORIGIN;
40
+ }
41
+
31
42
  // src/graph/state.ts
32
43
  var OUTCOMES = [
33
44
  "sent",
@@ -1346,6 +1357,8 @@ var CATEGORY_FIELD_DESCRIPTION_UID = "fa2aeb51-47b0-4c26-845a-0b9f543f0c89";
1346
1357
  var CATEGORY_FIELD_EXAMPLES_UID = "39e52ad6-34b1-4151-a70b-7f996648b9b0";
1347
1358
  var CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID = "4fa75e78-b826-4741-9612-b6cf28bde9f9";
1348
1359
  var CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID = "c6822551-821f-4255-b220-be40c9b56052";
1360
+ var CATEGORY_FIELD_FOLLOWUP_FAST_RESPONSE_ENABLED_UID = "6ea5d15b-166e-4c29-8555-844bd7f6193e";
1361
+ var CATEGORY_FIELD_FOLLOWUP_AUTO_REPLY_ENABLED_UID = "81804963-6ffb-486c-a663-6287353adff5";
1349
1362
  var CATEGORY_INDEX_TAG_NAME_UID = "5463dac5-715d-4545-ad75-905477d868eb";
1350
1363
  var CATEGORY_INDEX_NAME_UID = "2eda6e49-387a-4e08-94a8-06250652692d";
1351
1364
  var CATEGORY_INDEX_ORDER_UID = "bf4b1f9c-2dc8-4480-8fcb-dba789e8fe62";
@@ -1379,6 +1392,7 @@ var TRIAGE_DECISION_FIELD_ERROR_UID = "b271362b-a1b3-4110-a197-0b7a2ec6b152";
1379
1392
  var TRIAGE_DECISION_FIELD_RUN_ID_UID = "a1e244d6-8f4f-4cd5-8794-14f6e419b64e";
1380
1393
  var TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID = "449f1960-be88-4e42-96ee-43cd90f36f4c";
1381
1394
  var TRIAGE_DECISION_FIELD_TICKET_URL_UID = "727a775a-ea93-460f-9d08-16b05424c453";
1395
+ var TRIAGE_DECISION_FIELD_ORIGIN_UID = "8bde8d93-7d06-4cb5-8a88-2d6db562af05";
1382
1396
  var TRIAGE_DECISION_INDEX_TICKET_ID_UID = "20433066-e029-4faf-8033-c205cf5de0fb";
1383
1397
  var TRIAGE_DECISION_INDEX_DECIDED_AT_UID = "94040f6d-1d55-498f-8db8-abe5aed17c0a";
1384
1398
  var TRIAGE_DECISION_INDEX_ESCALATED_UID = "1c0ac4c3-9a48-4858-bbbf-0c689bbb5be5";
@@ -1411,6 +1425,7 @@ var GENERATED_RESPONSE_FIELD_GENERATED_MESSAGE_COUNT_UID = "33a282d3-7a1c-45a3-9
1411
1425
  var GENERATED_RESPONSE_FIELD_GENERATED_LAST_MESSAGE_AT_UID = "94c4594f-4ad0-4e3b-8a0b-76402b437434";
1412
1426
  var GENERATED_RESPONSE_FIELD_SENDING_AT_UID = "2ae9634b-79bb-42d2-a949-8b0f1ac9c763";
1413
1427
  var GENERATED_RESPONSE_FIELD_OUTCOME_UID = "8834b334-8f91-46f7-9bb9-96b69092d0ae";
1428
+ var GENERATED_RESPONSE_FIELD_ORIGIN_UID = "e75034d3-ee7f-40e7-b4fe-8be7b4322bdc";
1414
1429
  var GENERATED_RESPONSE_INDEX_TICKET_ID_UID = "a4534d26-8f43-4510-9c03-0b28c3d3f8e2";
1415
1430
  var GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID = "3d430166-07a2-43c2-911b-89ec25d13f64";
1416
1431
  var GENERATED_RESPONSE_INDEX_STATUS_UID = "f5c4e5d4-0810-424d-8a14-617e9555a7f3";
@@ -1559,6 +1574,24 @@ function buildCategoryRecord(slug) {
1559
1574
  label: "Auto-reply enabled",
1560
1575
  isNullable: false,
1561
1576
  defaultValue: false
1577
+ },
1578
+ {
1579
+ universalIdentifier: CATEGORY_FIELD_FOLLOWUP_FAST_RESPONSE_ENABLED_UID,
1580
+ name: "followupFastResponseEnabled",
1581
+ type: appKit.FieldType.BOOLEAN,
1582
+ label: "Follow-up fast response enabled",
1583
+ description: "Draft a reply to the FOLLOWING customer messages of an already-handled ticket (spec-gorgias-followup-webhook-v1 \xA77.1). Independent of `fastResponseEnabled`: a category may answer the first message without following the thread, and the reverse.",
1584
+ isNullable: false,
1585
+ defaultValue: false
1586
+ },
1587
+ {
1588
+ universalIdentifier: CATEGORY_FIELD_FOLLOWUP_AUTO_REPLY_ENABLED_UID,
1589
+ name: "followupAutoReplyEnabled",
1590
+ type: appKit.FieldType.BOOLEAN,
1591
+ label: "Follow-up auto-reply enabled",
1592
+ description: "Those follow-up drafts may be sent automatically (\xA77.1). Implies `followupFastResponseEnabled`, exactly as `autoReplyEnabled` implies `fastResponseEnabled`.",
1593
+ isNullable: false,
1594
+ defaultValue: false
1562
1595
  }
1563
1596
  ],
1564
1597
  indexes: [
@@ -1745,7 +1778,8 @@ function buildTriageDecisionRecord(slug) {
1745
1778
  name: "confidence",
1746
1779
  type: appKit.FieldType.SELECT,
1747
1780
  label: "Confidence",
1748
- isNullable: false,
1781
+ description: "How confident the classifier was. NULL on a follow-up pass (spec-gorgias-followup-webhook-v1 \xA77.2): no classifier runs there \u2014 the category is inherited from the tag the first pass applied \u2014 so there is no confidence to state, and inventing one would be a stored lie. Readers that need a value derive 'low' (process-response.ts's classificationFromDecision).",
1782
+ isNullable: true,
1749
1783
  options: [...CONFIDENCE_OPTIONS]
1750
1784
  },
1751
1785
  {
@@ -1817,6 +1851,15 @@ function buildTriageDecisionRecord(slug) {
1817
1851
  label: "Subject renamed",
1818
1852
  isNullable: false,
1819
1853
  defaultValue: false
1854
+ },
1855
+ {
1856
+ universalIdentifier: TRIAGE_DECISION_FIELD_ORIGIN_UID,
1857
+ name: "origin",
1858
+ type: appKit.FieldType.TEXT,
1859
+ label: "Origin",
1860
+ description: ORIGIN_DESCRIPTION,
1861
+ isNullable: false,
1862
+ defaultValue: DEFAULT_DECISION_ORIGIN
1820
1863
  }
1821
1864
  ],
1822
1865
  indexes: [
@@ -2073,6 +2116,15 @@ function buildGeneratedResponseRecord(slug) {
2073
2116
  label: "Sending at",
2074
2117
  description: "When status became 'sending' \u2014 the sweep's staleness clock (\xA73.5).",
2075
2118
  isNullable: true
2119
+ },
2120
+ {
2121
+ universalIdentifier: GENERATED_RESPONSE_FIELD_ORIGIN_UID,
2122
+ name: "origin",
2123
+ type: appKit.FieldType.TEXT,
2124
+ label: "Origin",
2125
+ description: ORIGIN_DESCRIPTION,
2126
+ isNullable: false,
2127
+ defaultValue: DEFAULT_DECISION_ORIGIN
2076
2128
  }
2077
2129
  ],
2078
2130
  indexes: [
@@ -2504,6 +2556,17 @@ var SUPPORT_KIT_SETTINGS_FIELDS = [
2504
2556
  { key: "autoRepliedTag", type: "string", label: "Auto-replied tag", default: "wai/auto-replied" },
2505
2557
  { key: "needsReviewTag", type: "string", label: "Review-before-send tag", default: "wai/escalated" },
2506
2558
  { key: "followupTag", type: "string", label: "Followup tag", default: "wai/human-required" },
2559
+ // Follow-up webhook (spec-gorgias-followup-webhook-v1 D2)
2560
+ // The tag a ticket must ALREADY carry for this app to answer a SUBSEQUENT
2561
+ // customer message on it. Deliberately empty by default, twice over:
2562
+ // - two support apps installed on ONE Gorgias account each receive every
2563
+ // `ticket-message-created` event, so a shared default would make a
2564
+ // freshly-installed app answer the other audience's tickets. Two apps of
2565
+ // the same account MUST configure distinct values;
2566
+ // - empty therefore means "process no follow-up message at all", which is
2567
+ // both the fail-closed default and the feature's kill switch.
2568
+ // Not named `followupTag`: that key is taken (`wai/human-required`).
2569
+ { key: "webhookScopeTag", type: "string", label: "Webhook scope tag", default: "" },
2507
2570
  // Sending
2508
2571
  { key: "autoSendEnabled", type: "boolean", label: "Auto-send enabled", default: false },
2509
2572
  { key: "senderEmail", type: "string", label: "Sender email", default: "" },
@@ -3179,9 +3242,6 @@ function parseApprovalKey(key) {
3179
3242
  const id = key.slice(PREFIX.length);
3180
3243
  return id.length > 0 ? id : null;
3181
3244
  }
3182
- function buildInboxKey(generatedResponseId, suffix) {
3183
- return suffix ? `${PREFIX}${generatedResponseId}:${suffix}` : `${PREFIX}${generatedResponseId}`;
3184
- }
3185
3245
 
3186
3246
  // src/functions/traced-input.ts
3187
3247
  var TRACED_INPUT_MAX_CHARS = 4e3;
@@ -3222,7 +3282,9 @@ function toCategory(record) {
3222
3282
  description: data.description ?? null,
3223
3283
  examples: data.examples ?? null,
3224
3284
  autoReplyEnabled: data.autoReplyEnabled ?? false,
3225
- fastResponseEnabled: data.fastResponseEnabled ?? false
3285
+ fastResponseEnabled: data.fastResponseEnabled ?? false,
3286
+ followupFastResponseEnabled: data.followupFastResponseEnabled ?? false,
3287
+ followupAutoReplyEnabled: data.followupAutoReplyEnabled ?? false
3226
3288
  };
3227
3289
  }
3228
3290
  function toCategoryGroup(record) {
@@ -3271,7 +3333,8 @@ function toGeneratedResponse(record) {
3271
3333
  autoSendDecision: data.autoSendDecision ?? null,
3272
3334
  sentAt: data.sentAt ?? null,
3273
3335
  sentMessageId: data.sentMessageId ?? null,
3274
- error: data.error ?? null
3336
+ error: data.error ?? null,
3337
+ origin: toDecisionOrigin(data.origin)
3275
3338
  };
3276
3339
  }
3277
3340
  async function listCategories(api) {
@@ -3331,6 +3394,14 @@ function buildPromptsTable(config, draft2, nodes) {
3331
3394
  }
3332
3395
 
3333
3396
  // src/functions/process-response.ts
3397
+ function autoReplyEnabledFor(origin, category) {
3398
+ if (!category) return false;
3399
+ return origin === "followup" ? category.followupAutoReplyEnabled : category.autoReplyEnabled;
3400
+ }
3401
+ function applyFollowupSendPolicy(profile, origin) {
3402
+ if (origin !== "followup") return profile;
3403
+ return { ...profile, autoSend: { ...profile.autoSend, requireHighTriage: false } };
3404
+ }
3334
3405
  function classificationFromDecision(decision) {
3335
3406
  const data = decision.data;
3336
3407
  return {
@@ -3367,7 +3438,7 @@ async function finalizeNonSent(ctx, id, ticketId, toStatus, extra) {
3367
3438
  throw err;
3368
3439
  }
3369
3440
  }
3370
- async function respondToPendingResponse(ctx, config, recordId) {
3441
+ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
3371
3442
  const record = await getOptional(ctx, "generated-response", recordId);
3372
3443
  if (!record) {
3373
3444
  ctx.logger.info(`respond: generated-response ${recordId} no longer exists, skipping`);
@@ -3395,10 +3466,15 @@ async function respondToPendingResponse(ctx, config, recordId) {
3395
3466
  const escalated = decision.data.escalated === true;
3396
3467
  const categoryRecord = await getOptional(ctx, "category", data.categoryId ?? null);
3397
3468
  const category = categoryRecord ? toCategory(categoryRecord) : null;
3469
+ const origin = toDecisionOrigin(data.origin);
3398
3470
  const agentRecord2 = data.agentId ? await getOptional(ctx, "agent", data.agentId) : null;
3399
3471
  const agent = agentRecord2 ? toAgent(agentRecord2) : await resolveDraftAgent(ctx.api, null);
3400
- const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));
3401
- const dryRun = settings.dryRun === true;
3472
+ const profile = applyFollowupSendPolicy(
3473
+ settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes)),
3474
+ origin
3475
+ );
3476
+ const testRun = options.testRun === true;
3477
+ const dryRun = settings.dryRun === true || testRun;
3402
3478
  const trace = { sessionId: ticketId, tags: [`app:${config.slug}`] };
3403
3479
  const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx, trace), ctx.api) : buildTicketPorts(ctx, trace);
3404
3480
  const { clock } = ports;
@@ -3428,7 +3504,7 @@ async function respondToPendingResponse(ctx, config, recordId) {
3428
3504
  ports,
3429
3505
  toolContext: createNoToolContext(),
3430
3506
  budget,
3431
- category: { autoReplyEnabled: category?.autoReplyEnabled ?? false, minConfidence: null },
3507
+ category: { autoReplyEnabled: autoReplyEnabledFor(origin, category), minConfidence: null },
3432
3508
  categories: [],
3433
3509
  log: (msg) => ctx.logger.debug(msg),
3434
3510
  send: dryRun ? { mode: "none" } : { mode: "claimed", claim: seam.claim, commit: seam.commit },
@@ -3452,35 +3528,30 @@ async function respondToPendingResponse(ctx, config, recordId) {
3452
3528
  // sent reply and a held one are read by the same timeline.
3453
3529
  tracedInput: toTracedInput(result.draft?.messages ?? []),
3454
3530
  verdict: result.verdict ?? null,
3455
- generatedMessageCount: conversationSnapshot.messageCount,
3456
- generatedLastMessageAt: conversationSnapshot.lastMessageAt,
3531
+ // Omitted on a test run — see `RespondOptions.testRun`, consequence THREE.
3532
+ ...testRun ? {} : {
3533
+ generatedMessageCount: conversationSnapshot.messageCount,
3534
+ generatedLastMessageAt: conversationSnapshot.lastMessageAt
3535
+ },
3457
3536
  ...attributionFields(result.draft?.attribution)
3458
3537
  };
3538
+ const restingStatus = testRun ? "invalidated" : "ready";
3459
3539
  switch (result.outcome) {
3460
3540
  case "sent":
3461
3541
  if (dryRun) {
3462
- await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3542
+ await finalizeNonSent(ctx, recordId, ticketId, restingStatus, draftExtra);
3463
3543
  return;
3464
3544
  }
3465
3545
  return;
3466
3546
  case "ready":
3467
3547
  case "guardrail_hold":
3468
- await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3548
+ await finalizeNonSent(ctx, recordId, ticketId, restingStatus, draftExtra);
3469
3549
  return;
3470
- case "needs_human": {
3471
- const persisted = await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3472
- if (persisted) {
3473
- await ctx.api.inbox.raise({
3474
- key: buildInboxKey(recordId),
3475
- severity: "warning",
3476
- title: `R\xE9ponse g\xE9n\xE9r\xE9e \xE0 revoir \u2014 ticket ${ticketId}`,
3477
- entityRef: { appSlug: config.slug, objectKey: "generated-response", id: recordId }
3478
- });
3479
- }
3550
+ case "needs_human":
3551
+ await finalizeNonSent(ctx, recordId, ticketId, restingStatus, draftExtra);
3480
3552
  return;
3481
- }
3482
3553
  case "awaiting_approval": {
3483
- const persisted = await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3554
+ const persisted = await finalizeNonSent(ctx, recordId, ticketId, restingStatus, draftExtra);
3484
3555
  if (persisted && !dryRun) {
3485
3556
  await ctx.api.approvals.request({
3486
3557
  key: buildApprovalKey(recordId),
@@ -3680,13 +3751,15 @@ async function writeErrorDecision(ctx, ref, message, deps) {
3680
3751
  }
3681
3752
  }
3682
3753
  async function escalateTicket(ctx, ref, deps) {
3683
- const tag = deps.profile.audit.escalationTag;
3754
+ await flagEscalation(ctx, ref, deps.profile.audit.escalationTag, deps.ports);
3755
+ }
3756
+ async function flagEscalation(ctx, ref, tag, ports) {
3684
3757
  if (!tag) {
3685
- ctx.logger.warn(`triage-tick: ticket ${ref.id} failed but escalationTag is not configured \u2014 no tag applied`);
3758
+ ctx.logger.warn(`triage-tick: ticket ${ref.id} is escalated but escalationTag is not configured \u2014 no tag applied`);
3686
3759
  return;
3687
3760
  }
3688
3761
  try {
3689
- await deps.ports.state.flag(ref, tag);
3762
+ await ports.state.flag(ref, tag);
3690
3763
  } catch (flagErr) {
3691
3764
  ctx.logger.error(`triage-tick: failed to escalate ticket ${ref.id} \u2014 it is NOT tagged for a human`, {
3692
3765
  error: flagErr instanceof Error ? flagErr.message : String(flagErr)
@@ -3737,9 +3810,11 @@ async function processOneTicket(ctx, ref, deps) {
3737
3810
  escalated: state.escalated,
3738
3811
  status: "ok",
3739
3812
  runId,
3740
- subjectRenamed
3813
+ subjectRenamed,
3814
+ origin: "triage"
3741
3815
  });
3742
3816
  await ports.state.record(ref, classification, profile.audit);
3817
+ if (state.escalated) await flagEscalation(ctx, ref, profile.audit.escalationTag, ports);
3743
3818
  if (!isEligibleForGeneratedResponse(profile, classification, state.escalated, category)) return;
3744
3819
  const draftAgent = await resolveDraftAgent(ctx.api, category?.agentId ?? null);
3745
3820
  const conversation = state.conversation;
@@ -3763,7 +3838,8 @@ async function processOneTicket(ctx, ref, deps) {
3763
3838
  guardrailHits: [],
3764
3839
  servedTo: [],
3765
3840
  servedCount: 0,
3766
- followupRequired: false
3841
+ followupRequired: false,
3842
+ origin: "triage"
3767
3843
  });
3768
3844
  } catch (err) {
3769
3845
  if (err instanceof appKit.AppApiError && err.status === 409) {
@@ -3848,12 +3924,6 @@ async function sweepStalledSending(ctx, now, escalationTag, statePort) {
3848
3924
  if (!reclaimed) continue;
3849
3925
  const ref = { id: ticketId, channel: "gorgias" };
3850
3926
  await statePort.flag(ref, escalationTag);
3851
- await ctx.api.inbox.raise({
3852
- key: buildInboxKey(row.id, "stalled-send"),
3853
- severity: "warning",
3854
- title: `Envoi bloqu\xE9 d\xE9tect\xE9 \u2014 ticket ${ticketId}`,
3855
- body: 'La r\xE9ponse est rest\xE9e en statut "sending" plus de 30 minutes et a \xE9t\xE9 replac\xE9e en attente humaine.'
3856
- });
3857
3927
  }
3858
3928
  }
3859
3929
  async function sweepStalledPending(ctx, now) {
@@ -4049,6 +4119,8 @@ var CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID = "1039e196-cf6e-438e-8ec9-7ab42
4049
4119
  var CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID = "10ffe3e1-972e-43b4-bb45-343c4664464f";
4050
4120
  var SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID = "2f5d6cbb-1c69-4a76-9d8f-1a3f0a4e57c2";
4051
4121
  var INVALIDATE_RESPONSE_INPUT_GENERATED_RESPONSE_ID_UID = "9748baf5-97be-4a22-940d-46ef2f16a175";
4122
+ var TEST_GORGIAS_WEBHOOK_INPUT_TICKET_ID_UID = "2cfcbfc1-77f1-4081-8fba-5f3a51c29e62";
4123
+ var TEST_GORGIAS_WEBHOOK_INPUT_MODE_UID = "e75c5ec9-1205-492f-87df-a84ec12753f8";
4052
4124
 
4053
4125
  // src/functions/run-triage-now.ts
4054
4126
  var TRIAGE_RUN_REQUESTED_EVENT = "triage.run.requested";
@@ -5769,6 +5841,558 @@ function nonEmptyString(value) {
5769
5841
  return typeof value === "string" && value.length > 0 ? value : null;
5770
5842
  }
5771
5843
 
5844
+ // src/functions/followup-gates.ts
5845
+ var LABELS = {
5846
+ G1: "Identifiant de ticket",
5847
+ G2: "Tag de p\xE9rim\xE8tre configur\xE9",
5848
+ G5: "Tag de p\xE9rim\xE8tre pr\xE9sent sur le ticket",
5849
+ G6: "Aucune reprise humaine",
5850
+ G7: "Cat\xE9gorie r\xE9solue et opt\xE9e",
5851
+ G8: "Nouveau message client"
5852
+ };
5853
+ function humanTakeoverTags(settings) {
5854
+ const configured = [settings.escalationTag, settings.needsReviewTag, settings.followupTag].map((tag) => tag.trim()).filter((tag) => tag !== "");
5855
+ return [...new Set(configured)];
5856
+ }
5857
+ function evaluateTicketIdGate(ticketId) {
5858
+ return ticketId === null ? stopped("G1", "Aucun identifiant de ticket exploitable (il doit \xEAtre une suite de chiffres).") : passed("G1", `Ticket ${ticketId}.`);
5859
+ }
5860
+ function evaluateScopeGate(settings) {
5861
+ return settings.webhookScopeTag.trim() === "" ? stopped("G2", "Le r\xE9glage \xAB Tag de p\xE9rim\xE8tre webhook \xBB est vide : aucun message suivant n\u2019est trait\xE9.") : passed("G2", `P\xE9rim\xE8tre : \xAB ${settings.webhookScopeTag} \xBB.`);
5862
+ }
5863
+ function skippedFollowupGates(gates) {
5864
+ return gates.map((gate) => ({
5865
+ gate,
5866
+ label: LABELS[gate],
5867
+ status: "skipped",
5868
+ detail: "Non \xE9valu\xE9 : un gate pr\xE9c\xE9dent a arr\xEAt\xE9 le traitement."
5869
+ }));
5870
+ }
5871
+ var FRESH_READ_GATES = ["G5", "G6", "G7", "G8"];
5872
+ var ALL_FOLLOWUP_GATES = ["G1", "G2", ...FRESH_READ_GATES];
5873
+ function evaluateTicketGates(input) {
5874
+ const { settings, tags, categories, conversation, anchor, ignoreCategoryOptIn = false } = input;
5875
+ const trace = newTrace(FRESH_READ_GATES);
5876
+ trace.record(scopeTagOnTicket(settings, tags));
5877
+ trace.record(noHumanTakeover(settings, tags));
5878
+ const match = trace.record(categoryGate(categories, tags, ignoreCategoryOptIn));
5879
+ if (match) trace.category = match;
5880
+ trace.record(newCustomerMessage(conversation, anchor));
5881
+ return trace.done();
5882
+ }
5883
+ function evaluatePayloadGates(input) {
5884
+ const { settings, body, categories, anchor } = input;
5885
+ const trace = newTrace(FRESH_READ_GATES);
5886
+ const tags = body.tags;
5887
+ if (tags === null) {
5888
+ const detail = "Les tags du ticket n\u2019ont pas pu \xEAtre lus dans la charge utile \u2014 la lecture fra\xEEche tranchera.";
5889
+ trace.record(muted("G5", detail));
5890
+ trace.record(muted("G6", detail));
5891
+ trace.record(muted("G7", detail));
5892
+ } else {
5893
+ trace.record(scopeTagOnTicket(settings, tags));
5894
+ trace.record(noHumanTakeover(settings, tags));
5895
+ trace.record(anyCategoryMatch(categories, tags));
5896
+ }
5897
+ trace.record(payloadNewCustomerMessage(body, anchor));
5898
+ return trace.done();
5899
+ }
5900
+ function scopeTagOnTicket(settings, tags) {
5901
+ const scopeTag = settings.webhookScopeTag.trim();
5902
+ return tags.includes(scopeTag) ? passed("G5", `Le ticket porte \xAB ${scopeTag} \xBB.`) : stopped("G5", `Le ticket ne porte pas le tag de p\xE9rim\xE8tre \xAB ${scopeTag} \xBB : il n\u2019appartient pas \xE0 cette app.`);
5903
+ }
5904
+ function noHumanTakeover(settings, tags) {
5905
+ const present = humanTakeoverTags(settings).filter((tag) => tags.includes(tag));
5906
+ 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.`);
5907
+ }
5908
+ function categoryGate(categories, tags, ignoreOptIn) {
5909
+ const matches = matchingCategories(categories, tags);
5910
+ if (matches.length === 0) return noMatchingCategory();
5911
+ const eligible = matches.filter((category2) => (ignoreOptIn || category2.followupFastResponseEnabled) && category2.agentId).sort((a, b) => a.order - b.order || a.id.localeCompare(b.id));
5912
+ if (eligible.length === 0) return noEligibleCategory(matches, ignoreOptIn);
5913
+ const category = eligible[0];
5914
+ 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)}).`;
5915
+ return { ...passed("G7", detail), category };
5916
+ }
5917
+ function noEligibleCategory(matches, ignoreOptIn) {
5918
+ if (ignoreOptIn) {
5919
+ 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.`);
5920
+ }
5921
+ if (matches.length > 1) {
5922
+ return stopped(
5923
+ "G7",
5924
+ `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.`
5925
+ );
5926
+ }
5927
+ const category = matches[0];
5928
+ 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.`);
5929
+ }
5930
+ function tagList(categories) {
5931
+ return categories.map((category) => category.tagName).join(", ");
5932
+ }
5933
+ function anyCategoryMatch(categories, tags) {
5934
+ const matches = matchingCategories(categories, tags);
5935
+ return matches.length === 0 ? noMatchingCategory() : passed("G7", `Cat\xE9gorie \xAB ${matches[0].name} \xBB.`);
5936
+ }
5937
+ function noMatchingCategory() {
5938
+ return stopped("G7", "Aucune cat\xE9gorie ne correspond \xE0 un tag du ticket : la d\xE9cision de triage est illisible.");
5939
+ }
5940
+ function matchingCategories(categories, tags) {
5941
+ return categories.filter((category) => tags.includes(category.tagName));
5942
+ }
5943
+ function newCustomerMessage(conversation, anchor) {
5944
+ if (conversation.isClosed) return stopped("G8", "Le ticket est ferm\xE9.");
5945
+ const last = conversation.messages[conversation.messages.length - 1];
5946
+ if (!last) return stopped("G8", "La conversation extraite est vide.");
5947
+ if (!isCustomerTurnWithWords(last)) {
5948
+ 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).");
5949
+ }
5950
+ if (anchor === null) return passed("G8", "Le dernier message est du client ; aucune r\xE9ponse ant\xE9rieure, donc aucune ancre \xE0 battre.");
5951
+ const lastAt = conversation.lastMessageAt;
5952
+ 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.");
5953
+ 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.`);
5954
+ }
5955
+ function payloadNewCustomerMessage(body, anchor) {
5956
+ if (body.isClosed === true) return stopped("G8", "La charge utile annonce un ticket ferm\xE9.");
5957
+ if (body.lastMessageFromAgent === true) return stopped("G8", "La charge utile annonce un dernier message d\u2019agent.");
5958
+ if (body.lastMessagePublic === false) return stopped("G8", "La charge utile annonce une note interne en dernier message.");
5959
+ if (anchor !== null && body.lastMessageAt !== null && body.lastMessageAt.getTime() <= anchor.getTime()) {
5960
+ return stopped("G8", `La charge utile annonce un dernier message (${body.lastMessageAt.toISOString()}) ant\xE9rieur ou \xE9gal \xE0 la derni\xE8re r\xE9ponse : relivraison.`);
5961
+ }
5962
+ if (body.isClosed === null && body.lastMessageFromAgent === null && body.lastMessagePublic === null && body.lastMessageAt === null) {
5963
+ return muted("G8", "Aucun champ exploitable dans la charge utile \u2014 la lecture fra\xEEche tranchera.");
5964
+ }
5965
+ return passed("G8", "Rien dans la charge utile ne permet d\u2019\xE9carter le ticket.");
5966
+ }
5967
+ function passed(gate, detail) {
5968
+ return { gate, label: LABELS[gate], status: "passed", detail };
5969
+ }
5970
+ function stopped(gate, detail) {
5971
+ return { gate, label: LABELS[gate], status: "stopped", detail };
5972
+ }
5973
+ function muted(gate, detail) {
5974
+ return { gate, label: LABELS[gate], status: "muted", detail };
5975
+ }
5976
+ function newTrace(gates) {
5977
+ const results = [];
5978
+ let stop2 = null;
5979
+ return {
5980
+ category: null,
5981
+ /** Records `result` unless the run already stopped; returns the category it resolved, if any. */
5982
+ record(result) {
5983
+ if (stop2) return null;
5984
+ results.push({ gate: result.gate, label: result.label, status: result.status, detail: result.detail });
5985
+ if (result.status === "stopped") stop2 = result;
5986
+ return result.category ?? null;
5987
+ },
5988
+ done() {
5989
+ const evaluated = new Set(results.map((result) => result.gate));
5990
+ for (const gate of gates) {
5991
+ if (!evaluated.has(gate)) {
5992
+ results.push({ gate, label: LABELS[gate], status: "skipped", detail: "Non \xE9valu\xE9 : un gate pr\xE9c\xE9dent a arr\xEAt\xE9 le traitement." });
5993
+ }
5994
+ }
5995
+ return { results, stop: stop2, category: stop2 ? null : this.category };
5996
+ }
5997
+ };
5998
+ }
5999
+
6000
+ // src/functions/webhook-body.ts
6001
+ var EMPTY_BODY = {
6002
+ ticketId: null,
6003
+ channel: null,
6004
+ lastMessageAt: null,
6005
+ isClosed: null,
6006
+ tags: null,
6007
+ lastMessageFromAgent: null,
6008
+ lastMessagePublic: null
6009
+ };
6010
+ var NUMERIC = /^\d+$/;
6011
+ var TRUE_TOKENS = /* @__PURE__ */ new Set(["true", "1", "yes", "on"]);
6012
+ var FALSE_TOKENS = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
6013
+ function parseFollowupWebhookBody(raw) {
6014
+ const body = toRecord(raw);
6015
+ if (!body) return { ...EMPTY_BODY };
6016
+ return {
6017
+ ticketId: parseTicketId(body.ticket_id),
6018
+ channel: parseText(body.channel),
6019
+ lastMessageAt: parseDate(body.last_message_datetime),
6020
+ isClosed: parseClosed(body.status),
6021
+ tags: parseTags(body.tags),
6022
+ lastMessageFromAgent: parseLaxBoolean(body.last_message_from_agent),
6023
+ lastMessagePublic: parseLaxBoolean(body.last_message_public)
6024
+ };
6025
+ }
6026
+ function toRecord(raw) {
6027
+ if (isPlainObject(raw)) return raw;
6028
+ if (typeof raw !== "string" || raw.trim() === "") return null;
6029
+ const asJson = tryJson(raw);
6030
+ if (isPlainObject(asJson)) return asJson;
6031
+ return parseFormEncoded(raw);
6032
+ }
6033
+ function parseFormEncoded(raw) {
6034
+ if (!raw.includes("=")) return null;
6035
+ const params = new URLSearchParams(raw);
6036
+ const entries = [...params.entries()];
6037
+ return entries.length > 0 ? Object.fromEntries(entries) : null;
6038
+ }
6039
+ function tryJson(raw) {
6040
+ try {
6041
+ return JSON.parse(raw);
6042
+ } catch {
6043
+ return void 0;
6044
+ }
6045
+ }
6046
+ function isPlainObject(value) {
6047
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6048
+ }
6049
+ function parseTicketId(raw) {
6050
+ if (typeof raw === "number") return Number.isSafeInteger(raw) && raw >= 0 ? String(raw) : null;
6051
+ return typeof raw === "string" && NUMERIC.test(raw) ? raw : null;
6052
+ }
6053
+ function parseText(raw) {
6054
+ if (typeof raw !== "string") return null;
6055
+ const trimmed = raw.trim();
6056
+ return trimmed === "" ? null : trimmed;
6057
+ }
6058
+ function parseDate(raw) {
6059
+ if (typeof raw !== "string") return null;
6060
+ const at = new Date(raw.trim());
6061
+ return Number.isNaN(at.getTime()) ? null : at;
6062
+ }
6063
+ function parseClosed(raw) {
6064
+ const text = parseText(raw);
6065
+ if (text === null) return null;
6066
+ if (text.toLowerCase() === "closed") return true;
6067
+ return text.startsWith("{{") ? null : false;
6068
+ }
6069
+ function parseLaxBoolean(raw) {
6070
+ if (typeof raw === "boolean") return raw;
6071
+ if (typeof raw === "number") {
6072
+ if (raw === 1) return true;
6073
+ if (raw === 0) return false;
6074
+ return null;
6075
+ }
6076
+ const text = parseText(raw)?.toLowerCase();
6077
+ if (text === void 0 || text === null) return null;
6078
+ if (TRUE_TOKENS.has(text)) return true;
6079
+ if (FALSE_TOKENS.has(text)) return false;
6080
+ return null;
6081
+ }
6082
+ function parseTags(raw) {
6083
+ const list = Array.isArray(raw) ? raw : arrayFromJson(raw);
6084
+ if (list === null || list.length === 0) return null;
6085
+ const names = [];
6086
+ for (const entry of list) {
6087
+ const name = tagNameOf(entry);
6088
+ if (name === null) return null;
6089
+ names.push(name);
6090
+ }
6091
+ return names;
6092
+ }
6093
+ function arrayFromJson(raw) {
6094
+ if (typeof raw !== "string") return null;
6095
+ const parsed = tryJson(raw);
6096
+ return Array.isArray(parsed) ? parsed : null;
6097
+ }
6098
+ function tagNameOf(entry) {
6099
+ if (typeof entry === "string") return parseText(entry);
6100
+ if (isPlainObject(entry)) return parseText(entry.name);
6101
+ return null;
6102
+ }
6103
+
6104
+ // src/functions/gorgias-webhook.ts
6105
+ var FOLLOWUP_RUN_REQUESTED_EVENT = "followup.run.requested";
6106
+ var FOLLOWUP_RUN_KIND = "gorgias-webhook";
6107
+ function buildGorgiasWebhookFunctionDef(config) {
6108
+ return {
6109
+ universalIdentifier: identifierFor(config, "gorgias-webhook"),
6110
+ name: "gorgias-webhook",
6111
+ trigger: { type: "httpRoute", path: "/gorgias/webhook", method: "POST", auth: "apiKey" }
6112
+ };
6113
+ }
6114
+ function buildGorgiasFollowupRunFunctionDef(config) {
6115
+ return {
6116
+ universalIdentifier: identifierFor(config, "gorgias-followup-run"),
6117
+ name: "gorgias-followup-run",
6118
+ trigger: { type: "event", name: FOLLOWUP_RUN_REQUESTED_EVENT }
6119
+ };
6120
+ }
6121
+ function createGorgiasWebhookHandler(config) {
6122
+ return (ctx, payload) => executeFollowupRun(
6123
+ ctx,
6124
+ config,
6125
+ payload?.body,
6126
+ null
6127
+ );
6128
+ }
6129
+ function createGorgiasFollowupRunHandler(config) {
6130
+ return (ctx, payload) => {
6131
+ const event = payload ?? {};
6132
+ return executeFollowupRun(ctx, config, event.body, event.runId ?? null, {
6133
+ generateOnly: event.generateOnly === true
6134
+ });
6135
+ };
6136
+ }
6137
+ async function executeFollowupRun(ctx, config, rawBody, existingRunId, options = {}) {
6138
+ const run = { id: existingRunId };
6139
+ try {
6140
+ const result = await runFollowupPass(ctx, config, rawBody, run, options.generateOnly === true);
6141
+ if (run.id) await ctx.api.runs.succeed(run.id, { ...result });
6142
+ } catch (err) {
6143
+ if (run.id) await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });
6144
+ throw err;
6145
+ }
6146
+ }
6147
+ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
6148
+ const body = parseFollowupWebhookBody(rawBody);
6149
+ const ticketIdGate = evaluateTicketIdGate(body.ticketId);
6150
+ if (!body.ticketId) return stop(ctx, null, ticketIdGate.gate, ticketIdGate.detail);
6151
+ const ticketId = body.ticketId;
6152
+ const settings = await ctx.api.settings.get();
6153
+ const issues = validateSettings(settings);
6154
+ if (issues.length > 0) {
6155
+ return stop(ctx, ticketId, "settings", `r\xE9glages invalides : ${issues.map((issue) => issue.message).join(" ")}`);
6156
+ }
6157
+ const scope = evaluateScopeGate(settings);
6158
+ if (scope.status === "stopped") return stopAt(ctx, ticketId, scope);
6159
+ const { anchor, hasOpenResponse } = await readFollowupAnchor(ctx, ticketId);
6160
+ const categories = await listCategories(ctx.api);
6161
+ const preGates = evaluatePayloadGates({ settings, body, categories, anchor });
6162
+ if (preGates.stop) return stopAt(ctx, ticketId, preGates.stop, "pr\xE9-gate");
6163
+ const ref = { id: ticketId, channel: "gorgias" };
6164
+ const ticket = await ctx.api.integrations.run("gorgias", "getTicketWithContext", { ticketId });
6165
+ const raw = ticket?.ticket ?? {};
6166
+ const conversation = toConversation(ref, raw, ticket?.context ?? { messages: [], customerContext: null });
6167
+ const gates = evaluateTicketGates({
6168
+ settings,
6169
+ tags: ticketTagNames(raw),
6170
+ categories,
6171
+ conversation,
6172
+ anchor,
6173
+ ignoreCategoryOptIn: generateOnly
6174
+ });
6175
+ if (gates.stop || !gates.category) {
6176
+ return stopAt(ctx, ticketId, gates.stop ?? unresolvedCategory());
6177
+ }
6178
+ const category = gates.category;
6179
+ if (hasOpenResponse) return stop(ctx, ticketId, "G9", "une r\xE9ponse est d\xE9j\xE0 ouverte sur ce ticket");
6180
+ run.id ??= (await ctx.api.runs.start({
6181
+ kind: FOLLOWUP_RUN_KIND,
6182
+ message: `Message suivant \u2014 ticket ${ticketId}`,
6183
+ metadata: { ticketId, categoryTag: category.tagName, channel: body.channel, generateOnly }
6184
+ })).id;
6185
+ 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 });
6188
+ return {
6189
+ ticketId,
6190
+ 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)`
6192
+ };
6193
+ }
6194
+ async function readFollowupAnchor(ctx, ticketId) {
6195
+ const page = await ctx.api.list("generated-response", { filter: { ticketId }, limit: ANCHOR_LOOKUP_LIMIT });
6196
+ let anchor = null;
6197
+ let hasOpenResponse = false;
6198
+ for (const item of page.items) {
6199
+ const data = item.data;
6200
+ if (data.openTicketKey === ticketId) hasOpenResponse = true;
6201
+ for (const raw of [data.generatedLastMessageAt, data.sentAt]) {
6202
+ const at = toDate2(raw);
6203
+ if (at && (!anchor || at > anchor)) anchor = at;
6204
+ }
6205
+ }
6206
+ return { anchor, hasOpenResponse };
6207
+ }
6208
+ var ANCHOR_LOOKUP_LIMIT = 100;
6209
+ function toDate2(raw) {
6210
+ if (raw instanceof Date) return Number.isNaN(raw.getTime()) ? null : raw;
6211
+ if (typeof raw !== "string") return null;
6212
+ const at = new Date(raw);
6213
+ return Number.isNaN(at.getTime()) ? null : at;
6214
+ }
6215
+ function ticketTagNames(raw) {
6216
+ const tags = raw.tags;
6217
+ if (!Array.isArray(tags)) return [];
6218
+ const names = [];
6219
+ for (const entry of tags) {
6220
+ if (typeof entry === "string" && entry !== "") {
6221
+ names.push(entry);
6222
+ continue;
6223
+ }
6224
+ if (typeof entry === "object" && entry !== null) {
6225
+ const name = entry.name;
6226
+ if (typeof name === "string" && name !== "") names.push(name);
6227
+ }
6228
+ }
6229
+ return names;
6230
+ }
6231
+ async function openFollowupResponse(ctx, input) {
6232
+ const { ticketId, category, conversation, settings, runId } = input;
6233
+ const decision = await ctx.api.create("triage-decision", {
6234
+ ticketId,
6235
+ // Not resolved: `getTicketUrlBase` is a SECOND Gorgias call and this
6236
+ // function runs once per message of the whole account. The field is
6237
+ // documented nullable for exactly this kind of row.
6238
+ ticketUrl: null,
6239
+ decidedAt: /* @__PURE__ */ new Date(),
6240
+ categoryId: category.id,
6241
+ tag: category.tagName,
6242
+ // §7.2 — NULL, and it is the honest value: no classifier ran on this pass
6243
+ // (D3 — the category is inherited from the tag the first pass applied), so
6244
+ // there is no confidence to state. The column was widened to allow it
6245
+ // (`records/triage-decision.ts`); a reader that needs a value still derives
6246
+ // `'low'` (`process-response.ts`'s `classificationFromDecision`).
6247
+ //
6248
+ // That derived `'low'` no longer holds the reply back: a follow-up pass is
6249
+ // governed by the evaluation of its own draft, not by a triage confidence
6250
+ // that does not exist — see `applyFollowupSendPolicy` in
6251
+ // `process-response.ts` for the decision and what it replaces.
6252
+ confidence: null,
6253
+ reasoning: `Message suivant \u2014 cat\xE9gorie r\xE9solue par le tag ${category.tagName}`,
6254
+ // The customer has just written, so the thread is by definition not over;
6255
+ // and the escalation decision belongs to the first pass, which this one
6256
+ // deliberately does not replay (D5).
6257
+ conversationOver: false,
6258
+ escalated: false,
6259
+ status: "ok",
6260
+ runId,
6261
+ subjectRenamed: false,
6262
+ origin: "followup"
6263
+ });
6264
+ const agent = await resolveDraftAgent(ctx.api, category.agentId);
6265
+ const generatedAt = /* @__PURE__ */ new Date();
6266
+ try {
6267
+ return await ctx.api.create("generated-response", {
6268
+ ticketId,
6269
+ openTicketKey: openTicketKeyFor("pending", ticketId),
6270
+ status: "pending",
6271
+ triageDecisionId: decision.id,
6272
+ categoryId: category.id,
6273
+ agentId: agent?.id ?? null,
6274
+ channel: conversation.sourceChannel === "whatsapp" ? "whatsapp" : "email",
6275
+ generatedAt,
6276
+ expiresAt: new Date(generatedAt.getTime() + settings.responseTtlMinutes * 6e4),
6277
+ sources: [],
6278
+ tracedInput: [],
6279
+ guardrailHits: [],
6280
+ servedTo: [],
6281
+ servedCount: 0,
6282
+ followupRequired: false,
6283
+ origin: "followup"
6284
+ });
6285
+ } catch (err) {
6286
+ if (err instanceof appKit.AppApiError && err.status === 409) return null;
6287
+ throw err;
6288
+ }
6289
+ }
6290
+ function unresolvedCategory() {
6291
+ return {
6292
+ gate: "G7",
6293
+ label: "Cat\xE9gorie r\xE9solue et opt\xE9e",
6294
+ status: "stopped",
6295
+ detail: "Aucune cat\xE9gorie r\xE9solue."
6296
+ };
6297
+ }
6298
+ function stopAt(ctx, ticketId, result, kind = "gate") {
6299
+ return stop(ctx, ticketId, `${result.gate}${kind === "gate" ? "" : ` (${kind})`}`, result.detail);
6300
+ }
6301
+ function stop(ctx, ticketId, gate, reason) {
6302
+ ctx.logger.info(`gorgias-webhook: stop at ${gate} for ticket ${ticketId ?? "?"} \u2014 ${reason}`);
6303
+ return { ticketId, stoppedAt: gate, reason };
6304
+ }
6305
+ function buildTestGorgiasWebhookFunctionDef(config) {
6306
+ return {
6307
+ universalIdentifier: identifierFor(config, "test-gorgias-webhook"),
6308
+ name: "test-gorgias-webhook",
6309
+ trigger: { type: "uiInvoke", minRole: "ADMIN", timeoutMs: 2e4 },
6310
+ input: [
6311
+ {
6312
+ universalIdentifier: TEST_GORGIAS_WEBHOOK_INPUT_TICKET_ID_UID,
6313
+ name: "ticketId",
6314
+ type: appKit.FieldType.TEXT,
6315
+ label: "Ticket id",
6316
+ description: "Identifiant Gorgias du ticket \xE0 tester.",
6317
+ isNullable: true
6318
+ },
6319
+ {
6320
+ universalIdentifier: TEST_GORGIAS_WEBHOOK_INPUT_MODE_UID,
6321
+ name: "mode",
6322
+ type: appKit.FieldType.TEXT,
6323
+ label: "Mode",
6324
+ 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.",
6325
+ isNullable: true
6326
+ }
6327
+ ]
6328
+ };
6329
+ }
6330
+ function createTestGorgiasWebhookHandler(_config) {
6331
+ return (ctx, input) => testGorgiasWebhookHandler(ctx, input ?? {});
6332
+ }
6333
+ var NUMERIC2 = /^\d+$/;
6334
+ async function testGorgiasWebhookHandler(ctx, input) {
6335
+ const ticketId = typeof input.ticketId === "string" && NUMERIC2.test(input.ticketId.trim()) ? input.ticketId.trim() : null;
6336
+ const mode = input.mode === "run" ? "run" : input.mode === "generate" ? "generate" : "diagnostic";
6337
+ if (mode === "diagnostic") return diagnose(ctx, ticketId);
6338
+ if (!ticketId) throw new ctx.NonRetriableError("L'identifiant du ticket doit \xEAtre une suite de chiffres.");
6339
+ return triggerRun(ctx, ticketId, mode);
6340
+ }
6341
+ async function diagnose(ctx, ticketId) {
6342
+ const gates = [];
6343
+ const ticketIdGate = evaluateTicketIdGate(ticketId);
6344
+ gates.push(ticketIdGate);
6345
+ if (!ticketId) return finish3(gates, "");
6346
+ const settings = await ctx.api.settings.get();
6347
+ const issues = validateSettings(settings);
6348
+ if (issues.length > 0) {
6349
+ throw new ctx.NonRetriableError(`R\xE9glages invalides : ${issues.map((issue) => issue.message).join(" ")}`);
6350
+ }
6351
+ const scope = evaluateScopeGate(settings);
6352
+ gates.push(scope);
6353
+ if (scope.status === "stopped") return finish3(gates, ticketId);
6354
+ const { anchor } = await readFollowupAnchor(ctx, ticketId);
6355
+ const categories = await listCategories(ctx.api);
6356
+ const ref = { id: ticketId, channel: "gorgias" };
6357
+ const ticket = await ctx.api.integrations.run("gorgias", "getTicketWithContext", { ticketId });
6358
+ const raw = ticket?.ticket ?? {};
6359
+ const conversation = toConversation(ref, raw, ticket?.context ?? { messages: [], customerContext: null });
6360
+ const trace = evaluateTicketGates({ settings, tags: ticketTagNames(raw), categories, conversation, anchor });
6361
+ gates.push(...trace.results);
6362
+ return finish3(gates, ticketId);
6363
+ }
6364
+ 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)];
6368
+ return {
6369
+ mode: "diagnostic",
6370
+ ticketId,
6371
+ stoppedAt: full.find((gate) => gate.status === "stopped")?.gate ?? null,
6372
+ gates: full
6373
+ };
6374
+ }
6375
+ async function triggerRun(ctx, ticketId, mode) {
6376
+ const generateOnly = mode === "generate";
6377
+ const run = await ctx.api.runs.start({
6378
+ kind: FOLLOWUP_RUN_KIND,
6379
+ message: generateOnly ? `Test webhook sans envoi \u2014 ticket ${ticketId}` : `Test webhook \u2014 ticket ${ticketId}`,
6380
+ metadata: { ticketId, triggeredFrom: "test-gorgias-webhook", generateOnly }
6381
+ });
6382
+ try {
6383
+ await ctx.api.events.send(FOLLOWUP_RUN_REQUESTED_EVENT, {
6384
+ _key: run.id,
6385
+ runId: run.id,
6386
+ body: { ticket_id: ticketId },
6387
+ generateOnly
6388
+ });
6389
+ } catch (err) {
6390
+ await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });
6391
+ throw err;
6392
+ }
6393
+ return { mode, ticketId, runId: run.id };
6394
+ }
6395
+
5772
6396
  // src/pages/manifest.ts
5773
6397
  function pageIdentifierFor(config, key) {
5774
6398
  const id = config.identifiers[key];
@@ -5794,10 +6418,11 @@ var SUPPORT_KIT_GORGIAS_SCOPES = [
5794
6418
  "write_tags",
5795
6419
  "write_tickets"
5796
6420
  ];
6421
+ var SUPPORT_KIT_SERVER_VARIABLES = [];
5797
6422
  var SUPPORT_KIT_INTEGRATIONS = [
5798
6423
  { provider: "gorgias", scopes: [...SUPPORT_KIT_GORGIAS_SCOPES] }
5799
6424
  ];
5800
- var SUPPORT_KIT_EMITS = [TRIAGE_RUN_REQUESTED_EVENT];
6425
+ var SUPPORT_KIT_EMITS = [TRIAGE_RUN_REQUESTED_EVENT, FOLLOWUP_RUN_REQUESTED_EVENT];
5801
6426
  var FUNCTION_ASSEMBLY = [
5802
6427
  { key: "triage-tick", build: buildTriageTickFunctionDef, createHandler: createTriageTickHandler },
5803
6428
  { key: "sweep", build: buildSweepFunctionDef, createHandler: () => createSweepHandler() },
@@ -5892,6 +6517,22 @@ var FUNCTION_ASSEMBLY = [
5892
6517
  key: "ext-response-comparison",
5893
6518
  build: buildExtResponseComparisonFunctionDef,
5894
6519
  createHandler: () => createExtResponseComparisonHandler()
6520
+ },
6521
+ // spec-gorgias-followup-webhook-v1 §5 — the push half.
6522
+ {
6523
+ key: "gorgias-webhook",
6524
+ build: buildGorgiasWebhookFunctionDef,
6525
+ createHandler: createGorgiasWebhookHandler
6526
+ },
6527
+ {
6528
+ key: "gorgias-followup-run",
6529
+ build: buildGorgiasFollowupRunFunctionDef,
6530
+ createHandler: createGorgiasFollowupRunHandler
6531
+ },
6532
+ {
6533
+ key: "test-gorgias-webhook",
6534
+ build: buildTestGorgiasWebhookFunctionDef,
6535
+ createHandler: createTestGorgiasWebhookHandler
5895
6536
  }
5896
6537
  ];
5897
6538
  function buildPromptsAllowlist() {
@@ -6004,6 +6645,7 @@ function buildSupportPipeline(config) {
6004
6645
  navigation: buildNavigation(config),
6005
6646
  settingsPage: buildSettingsPage(config),
6006
6647
  integrations: SUPPORT_KIT_INTEGRATIONS,
6648
+ serverVariables: SUPPORT_KIT_SERVER_VARIABLES,
6007
6649
  emits: SUPPORT_KIT_EMITS,
6008
6650
  defaultRole: "NO_ACCESS",
6009
6651
  handlers,
@@ -6017,8 +6659,10 @@ exports.AGENT_STATUSES = AGENT_STATUSES;
6017
6659
  exports.AGENT_TOOLS = AGENT_TOOLS;
6018
6660
  exports.ATTACHMENT_MARKER_ONLY = ATTACHMENT_MARKER_ONLY;
6019
6661
  exports.CANDIDATE_MIN_LENGTH = CANDIDATE_MIN_LENGTH;
6662
+ exports.DECISION_ORIGINS = DECISION_ORIGINS;
6020
6663
  exports.DEFAULT_CHANNEL_PROMPT_EMAIL = DEFAULT_CHANNEL_PROMPT_EMAIL;
6021
6664
  exports.DEFAULT_CHANNEL_PROMPT_WHATSAPP = DEFAULT_CHANNEL_PROMPT_WHATSAPP;
6665
+ exports.DEFAULT_DECISION_ORIGIN = DEFAULT_DECISION_ORIGIN;
6022
6666
  exports.DEFAULT_LLM_PROVIDER = DEFAULT_LLM_PROVIDER;
6023
6667
  exports.DEFAULT_PROFILE_KEY = DEFAULT_PROFILE_KEY;
6024
6668
  exports.DEFAULT_WHATSAPP_MODE = DEFAULT_WHATSAPP_MODE;
@@ -6027,6 +6671,7 @@ exports.GENERATED_RESPONSE_STATUSES = GENERATED_RESPONSE_STATUSES;
6027
6671
  exports.InvalidStatusTransitionError = InvalidStatusTransitionError;
6028
6672
  exports.MissingPromptError = MissingPromptError;
6029
6673
  exports.NODE_NAMES = NODE_NAMES;
6674
+ exports.ORIGIN_DESCRIPTION = ORIGIN_DESCRIPTION;
6030
6675
  exports.OUTCOMES = OUTCOMES;
6031
6676
  exports.PROMPT_SLOTS = PROMPT_SLOTS;
6032
6677
  exports.REASONING_MAX_LEN = REASONING_MAX_LEN;
@@ -6059,6 +6704,8 @@ exports.initialState = initialState;
6059
6704
  exports.isAutoSendEligible = isAutoSendEligible;
6060
6705
  exports.isAutomatedSenderEmail = isAutomatedSenderEmail;
6061
6706
  exports.isAutomatedSenderTicket = isAutomatedSenderTicket;
6707
+ exports.isCustomerTurnWithWords = isCustomerTurnWithWords;
6708
+ exports.isDecisionOrigin = isDecisionOrigin;
6062
6709
  exports.isEvaluationVerdict = isEvaluationVerdict;
6063
6710
  exports.isGeneratedResponseStatus = isGeneratedResponseStatus;
6064
6711
  exports.isJudgemeConversation = isJudgemeConversation;
@@ -6084,6 +6731,7 @@ exports.runTicket = runTicket;
6084
6731
  exports.settingsToProfile = settingsToProfile;
6085
6732
  exports.stopOptOut = stopOptOut;
6086
6733
  exports.targetRefFor = targetRefFor;
6734
+ exports.toDecisionOrigin = toDecisionOrigin;
6087
6735
  exports.validateSettings = validateSettings;
6088
6736
  exports.verifyReply = verifyReply;
6089
6737
  exports.whatsappModeFromLegacyBoolean = whatsappModeFromLegacyBoolean;