@apotech-os/support-kit 7.0.0 → 7.0.1

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.js CHANGED
@@ -1,5 +1,5 @@
1
- import { CATEGORY_GROUP_FIELD_NAME_UID, CATEGORY_GROUP_FIELD_ORDER_UID, PIPELINE_STATE_FIELD_SINGLETON_KEY_UID, PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID, PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID, PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID, PROMPT_CACHE_FIELD_PROMPT_KEY_UID, PROMPT_CACHE_FIELD_CONTENT_UID, PROMPT_CACHE_FIELD_VERSION_UID, PROMPT_CACHE_FIELD_LABEL_UID, PROMPT_CACHE_FIELD_CONFIG_UID, CATEGORY_GROUP_INDEX_NAME_UID, CATEGORY_GROUP_OBJECT_UID, PIPELINE_STATE_INDEX_SINGLETON_KEY_UID, PIPELINE_STATE_OBJECT_UID, PROMPT_CACHE_INDEX_PROMPT_KEY_UID, PROMPT_CACHE_OBJECT_UID, CATEGORY_INDEX_TAG_NAME_UID, CATEGORY_INDEX_NAME_UID, CATEGORY_INDEX_ORDER_UID, CATEGORY_FIELD_NAME_UID, CATEGORY_FIELD_TAG_NAME_UID, CATEGORY_FIELD_ORDER_UID, CATEGORY_FIELD_GROUP_ID_UID, CATEGORY_FIELD_AGENT_ID_UID, CATEGORY_FIELD_EXTRA_TAGS_UID, CATEGORY_FIELD_DESCRIPTION_UID, CATEGORY_FIELD_EXAMPLES_UID, CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID, CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID, CATEGORY_OBJECT_UID, TRIAGE_DECISION_INDEX_TICKET_ID_UID, TRIAGE_DECISION_INDEX_DECIDED_AT_UID, TRIAGE_DECISION_INDEX_ESCALATED_UID, TRIAGE_DECISION_FIELD_TICKET_ID_UID, TRIAGE_DECISION_FIELD_TICKET_URL_UID, TRIAGE_DECISION_FIELD_DECIDED_AT_UID, TRIAGE_DECISION_FIELD_CATEGORY_ID_UID, TRIAGE_DECISION_FIELD_TAG_UID, TRIAGE_DECISION_FIELD_CONFIDENCE_UID, TRIAGE_DECISION_FIELD_REASONING_UID, TRIAGE_DECISION_FIELD_CONVERSATION_OVER_UID, TRIAGE_DECISION_FIELD_ESCALATED_UID, TRIAGE_DECISION_FIELD_ESCALATION_CONFIDENCE_UID, TRIAGE_DECISION_FIELD_ESCALATION_REASONING_UID, TRIAGE_DECISION_FIELD_STATUS_UID, TRIAGE_DECISION_FIELD_ERROR_UID, TRIAGE_DECISION_FIELD_RUN_ID_UID, TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID, TRIAGE_DECISION_OBJECT_UID, GENERATED_RESPONSE_INDEX_TICKET_ID_UID, GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID, GENERATED_RESPONSE_INDEX_STATUS_UID, GENERATED_RESPONSE_INDEX_TRIAGE_DECISION_ID_UID, GENERATED_RESPONSE_INDEX_GENERATED_AT_UID, GENERATED_RESPONSE_INDEX_EXPIRES_AT_UID, GENERATED_RESPONSE_FIELD_TICKET_ID_UID, GENERATED_RESPONSE_FIELD_OPEN_TICKET_KEY_UID, GENERATED_RESPONSE_STATUSES, GENERATED_RESPONSE_FIELD_STATUS_UID, GENERATED_RESPONSE_FIELD_TRIAGE_DECISION_ID_UID, GENERATED_RESPONSE_FIELD_CATEGORY_ID_UID, GENERATED_RESPONSE_FIELD_AGENT_ID_UID, GENERATED_RESPONSE_FIELD_CHANNEL_UID, GENERATED_RESPONSE_FIELD_RESPONSE_TEXT_UID, GENERATED_RESPONSE_FIELD_SOURCES_UID, GENERATED_RESPONSE_FIELD_TRACED_INPUT_UID, GENERATED_RESPONSE_FIELD_VERDICT_UID, GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_UID, OUTCOMES, GENERATED_RESPONSE_FIELD_OUTCOME_UID, GENERATED_RESPONSE_FIELD_AUTO_SEND_DECISION_UID, GENERATED_RESPONSE_FIELD_FOLLOWUP_REQUIRED_UID, GENERATED_RESPONSE_FIELD_SERVED_COUNT_UID, GENERATED_RESPONSE_FIELD_SERVED_TO_UID, GENERATED_RESPONSE_FIELD_GENERATED_AT_UID, GENERATED_RESPONSE_FIELD_EXPIRES_AT_UID, GENERATED_RESPONSE_FIELD_SENT_AT_UID, GENERATED_RESPONSE_FIELD_SENT_MESSAGE_ID_UID, GENERATED_RESPONSE_FIELD_LANGFUSE_TRACE_ID_UID, GENERATED_RESPONSE_FIELD_LANGFUSE_OBSERVATION_ID_UID, GENERATED_RESPONSE_FIELD_PROMPT_NAME_UID, GENERATED_RESPONSE_FIELD_PROMPT_VERSION_UID, GENERATED_RESPONSE_FIELD_ERROR_UID, GENERATED_RESPONSE_FIELD_GENERATED_MESSAGE_COUNT_UID, GENERATED_RESPONSE_FIELD_GENERATED_LAST_MESSAGE_AT_UID, GENERATED_RESPONSE_FIELD_SENDING_AT_UID, GENERATED_RESPONSE_OBJECT_UID, RESPONSE_COMPARISON_INDEX_CAPTURED_AT_UID, RESPONSE_COMPARISON_INDEX_TICKET_ID_UID, RESPONSE_COMPARISON_FIELD_GENERATED_TEXT_UID, RESPONSE_COMPARISON_FIELD_SENT_TEXT_UID, RESPONSE_COMPARISON_FIELD_CAPTURED_AT_UID, RESPONSE_COMPARISON_FIELD_TICKET_ID_UID, RESPONSE_COMPARISON_FIELD_TICKET_URL_UID, RESPONSE_COMPARISON_FIELD_AGENT_ID_UID, RESPONSE_COMPARISON_FIELD_LANGFUSE_TRACE_ID_UID, RESPONSE_COMPARISON_FIELD_LANGFUSE_OBSERVATION_ID_UID, RESPONSE_COMPARISON_FIELD_PROMPT_NAME_UID, RESPONSE_COMPARISON_FIELD_PROMPT_VERSION_UID, RESPONSE_COMPARISON_FIELD_CONVERSATION_MESSAGES_UID, RESPONSE_COMPARISON_FIELD_DIFF_UID, RESPONSE_COMPARISON_OBJECT_UID, EVALUATION_FIELD_AGENT_ID_UID, EVALUATION_FIELD_SATISFIED_UID, EVALUATION_FIELD_MESSAGES_UID, EVALUATION_FIELD_TICKET_URL_UID, EVALUATION_FIELD_LANGFUSE_TRACE_ID_UID, EVALUATION_FIELD_LANGFUSE_OBSERVATION_ID_UID, EVALUATION_FIELD_SUPPORT_USER_KEY_ID_UID, EVALUATION_OBJECT_UID, DIFF_ANALYSIS_INDEX_UNIQUE_KEY_UID, DIFF_ANALYSIS_FIELD_AGENT_ID_UID, DIFF_ANALYSIS_FIELD_PROMPT_NAME_UID, DIFF_ANALYSIS_FIELD_PROMPT_VERSION_UID, DIFF_ANALYSIS_FIELD_POINTS_UID, DIFF_ANALYSIS_FIELD_UNIQUE_KEY_UID, DIFF_ANALYSIS_OBJECT_UID, agentRecord, SUPPORT_KIT_SETTINGS_FIELDS, MissingPromptError, validateSettings, settingsToProfile, buildPromptsTable, draftPromptRefFor, assertTransition, openTicketKeyFor, act, initialState, applyOutcomeTags, listCategories, resolveDraftAgent, runTicket, toCategoryReferential, toAgent, draftRebinder, resolvePromptName, isGeneratedResponseStatus, isInvalidatableStatus, DEFAULT_LLM_PROVIDER, toCategoryGroup, toCategory, toGeneratedResponse, NODE_NAMES, reclaimStalledSend, applySignature, isEvaluationVerdict, requiresFollowup, computeWordDiff, findCategoryByTag, isWhatsappTicket, isConversationOver, isFallbackClassification, hasNoDraftNode, hasCustomerAttachment, isTicketClosed, isWhatsappChevronNote } from './chunk-CQJJZA4F.js';
2
- export { AGENT_GUARDRAILS, AGENT_STATUSES, AGENT_TOOLS, ATTACHMENT_MARKER_ONLY, CANDIDATE_MIN_LENGTH, DEFAULT_CHANNEL_PROMPT_EMAIL, DEFAULT_CHANNEL_PROMPT_WHATSAPP, DEFAULT_LLM_PROVIDER, DEFAULT_PROFILE_KEY, DEFAULT_WHATSAPP_MODE, EVALUATION_VERDICTS, GENERATED_RESPONSE_STATUSES, InvalidStatusTransitionError, MissingPromptError, NODE_NAMES, OUTCOMES, PROMPT_SLOTS, REASONING_MAX_LEN, STOP_PHRASES, SUPPORT_KIT_SETTINGS_FIELDS, UNCERTAINTY_MARKERS, WHATSAPP_MODES, WHATSAPP_NOTE_CHEVRON, agentRecord, assertTransition, canTransition, channelPreGates, firstCustomerMessage, guardrailBucket, hasCustomerAttachment, initialState, isAutoSendEligible, isAutomatedSenderEmail, isAutomatedSenderTicket, isEvaluationVerdict, isGeneratedResponseStatus, isJudgemeConversation, isJudgemeTicket, isOutcome, isSendable, isSendableVerdict, isTerminalStatus, isTicketClosed, isWhatsappChevronNote, isWhatsappTicket, lastCustomerMessage, needsRevision, openTicketKeyFor, reclaimStalledSend, requiresFollowup, resolvePromptName, runGuardrails, runTicket, settingsToProfile, stopOptOut, validateSettings, verifyReply, whatsappModeFromLegacyBoolean } from './chunk-CQJJZA4F.js';
1
+ import { CATEGORY_GROUP_FIELD_NAME_UID, CATEGORY_GROUP_FIELD_ORDER_UID, PIPELINE_STATE_FIELD_SINGLETON_KEY_UID, PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID, PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID, PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID, PROMPT_CACHE_FIELD_PROMPT_KEY_UID, PROMPT_CACHE_FIELD_CONTENT_UID, PROMPT_CACHE_FIELD_VERSION_UID, PROMPT_CACHE_FIELD_LABEL_UID, PROMPT_CACHE_FIELD_CONFIG_UID, CATEGORY_GROUP_INDEX_NAME_UID, CATEGORY_GROUP_OBJECT_UID, PIPELINE_STATE_INDEX_SINGLETON_KEY_UID, PIPELINE_STATE_OBJECT_UID, PROMPT_CACHE_INDEX_PROMPT_KEY_UID, PROMPT_CACHE_OBJECT_UID, CATEGORY_INDEX_TAG_NAME_UID, CATEGORY_INDEX_NAME_UID, CATEGORY_INDEX_ORDER_UID, CATEGORY_FIELD_NAME_UID, CATEGORY_FIELD_TAG_NAME_UID, CATEGORY_FIELD_ORDER_UID, CATEGORY_FIELD_GROUP_ID_UID, CATEGORY_FIELD_AGENT_ID_UID, CATEGORY_FIELD_EXTRA_TAGS_UID, CATEGORY_FIELD_DESCRIPTION_UID, CATEGORY_FIELD_EXAMPLES_UID, CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID, CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID, CATEGORY_FIELD_FOLLOWUP_FAST_RESPONSE_ENABLED_UID, CATEGORY_FIELD_FOLLOWUP_AUTO_REPLY_ENABLED_UID, CATEGORY_OBJECT_UID, TRIAGE_DECISION_INDEX_TICKET_ID_UID, TRIAGE_DECISION_INDEX_DECIDED_AT_UID, TRIAGE_DECISION_INDEX_ESCALATED_UID, TRIAGE_DECISION_FIELD_TICKET_ID_UID, TRIAGE_DECISION_FIELD_TICKET_URL_UID, TRIAGE_DECISION_FIELD_DECIDED_AT_UID, TRIAGE_DECISION_FIELD_CATEGORY_ID_UID, TRIAGE_DECISION_FIELD_TAG_UID, TRIAGE_DECISION_FIELD_CONFIDENCE_UID, TRIAGE_DECISION_FIELD_REASONING_UID, TRIAGE_DECISION_FIELD_CONVERSATION_OVER_UID, TRIAGE_DECISION_FIELD_ESCALATED_UID, TRIAGE_DECISION_FIELD_ESCALATION_CONFIDENCE_UID, TRIAGE_DECISION_FIELD_ESCALATION_REASONING_UID, TRIAGE_DECISION_FIELD_STATUS_UID, TRIAGE_DECISION_FIELD_ERROR_UID, TRIAGE_DECISION_FIELD_RUN_ID_UID, TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID, DEFAULT_DECISION_ORIGIN, ORIGIN_DESCRIPTION, TRIAGE_DECISION_FIELD_ORIGIN_UID, TRIAGE_DECISION_OBJECT_UID, GENERATED_RESPONSE_INDEX_TICKET_ID_UID, GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID, GENERATED_RESPONSE_INDEX_STATUS_UID, GENERATED_RESPONSE_INDEX_TRIAGE_DECISION_ID_UID, GENERATED_RESPONSE_INDEX_GENERATED_AT_UID, GENERATED_RESPONSE_INDEX_EXPIRES_AT_UID, GENERATED_RESPONSE_FIELD_TICKET_ID_UID, GENERATED_RESPONSE_FIELD_OPEN_TICKET_KEY_UID, GENERATED_RESPONSE_STATUSES, GENERATED_RESPONSE_FIELD_STATUS_UID, GENERATED_RESPONSE_FIELD_TRIAGE_DECISION_ID_UID, GENERATED_RESPONSE_FIELD_CATEGORY_ID_UID, GENERATED_RESPONSE_FIELD_AGENT_ID_UID, GENERATED_RESPONSE_FIELD_CHANNEL_UID, GENERATED_RESPONSE_FIELD_RESPONSE_TEXT_UID, GENERATED_RESPONSE_FIELD_SOURCES_UID, GENERATED_RESPONSE_FIELD_TRACED_INPUT_UID, GENERATED_RESPONSE_FIELD_VERDICT_UID, GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_UID, OUTCOMES, GENERATED_RESPONSE_FIELD_OUTCOME_UID, GENERATED_RESPONSE_FIELD_AUTO_SEND_DECISION_UID, GENERATED_RESPONSE_FIELD_FOLLOWUP_REQUIRED_UID, GENERATED_RESPONSE_FIELD_SERVED_COUNT_UID, GENERATED_RESPONSE_FIELD_SERVED_TO_UID, GENERATED_RESPONSE_FIELD_GENERATED_AT_UID, GENERATED_RESPONSE_FIELD_EXPIRES_AT_UID, GENERATED_RESPONSE_FIELD_SENT_AT_UID, GENERATED_RESPONSE_FIELD_SENT_MESSAGE_ID_UID, GENERATED_RESPONSE_FIELD_LANGFUSE_TRACE_ID_UID, GENERATED_RESPONSE_FIELD_LANGFUSE_OBSERVATION_ID_UID, GENERATED_RESPONSE_FIELD_PROMPT_NAME_UID, GENERATED_RESPONSE_FIELD_PROMPT_VERSION_UID, GENERATED_RESPONSE_FIELD_ERROR_UID, GENERATED_RESPONSE_FIELD_GENERATED_MESSAGE_COUNT_UID, GENERATED_RESPONSE_FIELD_GENERATED_LAST_MESSAGE_AT_UID, GENERATED_RESPONSE_FIELD_SENDING_AT_UID, GENERATED_RESPONSE_FIELD_ORIGIN_UID, GENERATED_RESPONSE_OBJECT_UID, RESPONSE_COMPARISON_INDEX_CAPTURED_AT_UID, RESPONSE_COMPARISON_INDEX_TICKET_ID_UID, RESPONSE_COMPARISON_FIELD_GENERATED_TEXT_UID, RESPONSE_COMPARISON_FIELD_SENT_TEXT_UID, RESPONSE_COMPARISON_FIELD_CAPTURED_AT_UID, RESPONSE_COMPARISON_FIELD_TICKET_ID_UID, RESPONSE_COMPARISON_FIELD_TICKET_URL_UID, RESPONSE_COMPARISON_FIELD_AGENT_ID_UID, RESPONSE_COMPARISON_FIELD_LANGFUSE_TRACE_ID_UID, RESPONSE_COMPARISON_FIELD_LANGFUSE_OBSERVATION_ID_UID, RESPONSE_COMPARISON_FIELD_PROMPT_NAME_UID, RESPONSE_COMPARISON_FIELD_PROMPT_VERSION_UID, RESPONSE_COMPARISON_FIELD_CONVERSATION_MESSAGES_UID, RESPONSE_COMPARISON_FIELD_DIFF_UID, RESPONSE_COMPARISON_OBJECT_UID, EVALUATION_FIELD_AGENT_ID_UID, EVALUATION_FIELD_SATISFIED_UID, EVALUATION_FIELD_MESSAGES_UID, EVALUATION_FIELD_TICKET_URL_UID, EVALUATION_FIELD_LANGFUSE_TRACE_ID_UID, EVALUATION_FIELD_LANGFUSE_OBSERVATION_ID_UID, EVALUATION_FIELD_SUPPORT_USER_KEY_ID_UID, EVALUATION_OBJECT_UID, DIFF_ANALYSIS_INDEX_UNIQUE_KEY_UID, DIFF_ANALYSIS_FIELD_AGENT_ID_UID, DIFF_ANALYSIS_FIELD_PROMPT_NAME_UID, DIFF_ANALYSIS_FIELD_PROMPT_VERSION_UID, DIFF_ANALYSIS_FIELD_POINTS_UID, DIFF_ANALYSIS_FIELD_UNIQUE_KEY_UID, DIFF_ANALYSIS_OBJECT_UID, agentRecord, SUPPORT_KIT_SETTINGS_FIELDS, MissingPromptError, validateSettings, settingsToProfile, buildPromptsTable, draftPromptRefFor, assertTransition, openTicketKeyFor, act, initialState, applyOutcomeTags, listCategories, resolveDraftAgent, runTicket, toCategoryReferential, toAgent, draftRebinder, resolvePromptName, isGeneratedResponseStatus, isInvalidatableStatus, DEFAULT_LLM_PROVIDER, toCategoryGroup, toCategory, toGeneratedResponse, NODE_NAMES, reclaimStalledSend, applySignature, isEvaluationVerdict, requiresFollowup, computeWordDiff, findCategoryByTag, isWhatsappTicket, hasCustomerAttachment, isTicketClosed, toDecisionOrigin, isConversationOver, isFallbackClassification, hasNoDraftNode, isWhatsappChevronNote, isCustomerTurnWithWords } from './chunk-QCRCRNYE.js';
2
+ export { AGENT_GUARDRAILS, AGENT_STATUSES, AGENT_TOOLS, ATTACHMENT_MARKER_ONLY, CANDIDATE_MIN_LENGTH, DECISION_ORIGINS, DEFAULT_CHANNEL_PROMPT_EMAIL, DEFAULT_CHANNEL_PROMPT_WHATSAPP, DEFAULT_DECISION_ORIGIN, DEFAULT_LLM_PROVIDER, DEFAULT_PROFILE_KEY, DEFAULT_WHATSAPP_MODE, EVALUATION_VERDICTS, GENERATED_RESPONSE_STATUSES, InvalidStatusTransitionError, MissingPromptError, NODE_NAMES, ORIGIN_DESCRIPTION, OUTCOMES, PROMPT_SLOTS, REASONING_MAX_LEN, STOP_PHRASES, SUPPORT_KIT_SETTINGS_FIELDS, UNCERTAINTY_MARKERS, WHATSAPP_MODES, WHATSAPP_NOTE_CHEVRON, agentRecord, assertTransition, canTransition, channelPreGates, firstCustomerMessage, guardrailBucket, hasCustomerAttachment, initialState, isAutoSendEligible, isAutomatedSenderEmail, isAutomatedSenderTicket, isCustomerTurnWithWords, isDecisionOrigin, isEvaluationVerdict, isGeneratedResponseStatus, isJudgemeConversation, isJudgemeTicket, isOutcome, isSendable, isSendableVerdict, isTerminalStatus, isTicketClosed, isWhatsappChevronNote, isWhatsappTicket, lastCustomerMessage, needsRevision, openTicketKeyFor, reclaimStalledSend, requiresFollowup, resolvePromptName, runGuardrails, runTicket, settingsToProfile, stopOptOut, toDecisionOrigin, validateSettings, verifyReply, whatsappModeFromLegacyBoolean } from './chunk-QCRCRNYE.js';
3
3
  import { FieldType, APPROVAL_DECIDED_EVENT, AppApiError } from '@apotech-os/app-kit';
4
4
  import { createHash } from 'node:crypto';
5
5
 
@@ -294,6 +294,24 @@ function buildCategoryRecord(slug) {
294
294
  label: "Auto-reply enabled",
295
295
  isNullable: false,
296
296
  defaultValue: false
297
+ },
298
+ {
299
+ universalIdentifier: CATEGORY_FIELD_FOLLOWUP_FAST_RESPONSE_ENABLED_UID,
300
+ name: "followupFastResponseEnabled",
301
+ type: FieldType.BOOLEAN,
302
+ label: "Follow-up fast response enabled",
303
+ 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.",
304
+ isNullable: false,
305
+ defaultValue: false
306
+ },
307
+ {
308
+ universalIdentifier: CATEGORY_FIELD_FOLLOWUP_AUTO_REPLY_ENABLED_UID,
309
+ name: "followupAutoReplyEnabled",
310
+ type: FieldType.BOOLEAN,
311
+ label: "Follow-up auto-reply enabled",
312
+ description: "Those follow-up drafts may be sent automatically (\xA77.1). Implies `followupFastResponseEnabled`, exactly as `autoReplyEnabled` implies `fastResponseEnabled`.",
313
+ isNullable: false,
314
+ defaultValue: false
297
315
  }
298
316
  ],
299
317
  indexes: [
@@ -381,7 +399,8 @@ function buildTriageDecisionRecord(slug) {
381
399
  name: "confidence",
382
400
  type: FieldType.SELECT,
383
401
  label: "Confidence",
384
- isNullable: false,
402
+ 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).",
403
+ isNullable: true,
385
404
  options: [...CONFIDENCE_OPTIONS]
386
405
  },
387
406
  {
@@ -453,6 +472,15 @@ function buildTriageDecisionRecord(slug) {
453
472
  label: "Subject renamed",
454
473
  isNullable: false,
455
474
  defaultValue: false
475
+ },
476
+ {
477
+ universalIdentifier: TRIAGE_DECISION_FIELD_ORIGIN_UID,
478
+ name: "origin",
479
+ type: FieldType.TEXT,
480
+ label: "Origin",
481
+ description: ORIGIN_DESCRIPTION,
482
+ isNullable: false,
483
+ defaultValue: DEFAULT_DECISION_ORIGIN
456
484
  }
457
485
  ],
458
486
  indexes: [
@@ -709,6 +737,15 @@ function buildGeneratedResponseRecord(slug) {
709
737
  label: "Sending at",
710
738
  description: "When status became 'sending' \u2014 the sweep's staleness clock (\xA73.5).",
711
739
  isNullable: true
740
+ },
741
+ {
742
+ universalIdentifier: GENERATED_RESPONSE_FIELD_ORIGIN_UID,
743
+ name: "origin",
744
+ type: FieldType.TEXT,
745
+ label: "Origin",
746
+ description: ORIGIN_DESCRIPTION,
747
+ isNullable: false,
748
+ defaultValue: DEFAULT_DECISION_ORIGIN
712
749
  }
713
750
  ],
714
751
  indexes: [
@@ -1557,9 +1594,6 @@ function parseApprovalKey(key) {
1557
1594
  const id = key.slice(PREFIX.length);
1558
1595
  return id.length > 0 ? id : null;
1559
1596
  }
1560
- function buildInboxKey(generatedResponseId, suffix) {
1561
- return suffix ? `${PREFIX}${generatedResponseId}:${suffix}` : `${PREFIX}${generatedResponseId}`;
1562
- }
1563
1597
 
1564
1598
  // src/functions/traced-input.ts
1565
1599
  var TRACED_INPUT_MAX_CHARS = 4e3;
@@ -1573,6 +1607,14 @@ function cap(content) {
1573
1607
  }
1574
1608
 
1575
1609
  // src/functions/process-response.ts
1610
+ function autoReplyEnabledFor(origin, category) {
1611
+ if (!category) return false;
1612
+ return origin === "followup" ? category.followupAutoReplyEnabled : category.autoReplyEnabled;
1613
+ }
1614
+ function applyFollowupSendPolicy(profile, origin) {
1615
+ if (origin !== "followup") return profile;
1616
+ return { ...profile, autoSend: { ...profile.autoSend, requireHighTriage: false } };
1617
+ }
1576
1618
  function classificationFromDecision(decision) {
1577
1619
  const data = decision.data;
1578
1620
  return {
@@ -1637,9 +1679,13 @@ async function respondToPendingResponse(ctx, config, recordId) {
1637
1679
  const escalated = decision.data.escalated === true;
1638
1680
  const categoryRecord = await getOptional(ctx, "category", data.categoryId ?? null);
1639
1681
  const category = categoryRecord ? toCategory(categoryRecord) : null;
1682
+ const origin = toDecisionOrigin(data.origin);
1640
1683
  const agentRecord2 = data.agentId ? await getOptional(ctx, "agent", data.agentId) : null;
1641
1684
  const agent = agentRecord2 ? toAgent(agentRecord2) : await resolveDraftAgent(ctx.api, null);
1642
- const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));
1685
+ const profile = applyFollowupSendPolicy(
1686
+ settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes)),
1687
+ origin
1688
+ );
1643
1689
  const dryRun = settings.dryRun === true;
1644
1690
  const trace = { sessionId: ticketId, tags: [`app:${config.slug}`] };
1645
1691
  const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx, trace), ctx.api) : buildTicketPorts(ctx, trace);
@@ -1670,7 +1716,7 @@ async function respondToPendingResponse(ctx, config, recordId) {
1670
1716
  ports,
1671
1717
  toolContext: createNoToolContext(),
1672
1718
  budget,
1673
- category: { autoReplyEnabled: category?.autoReplyEnabled ?? false, minConfidence: null },
1719
+ category: { autoReplyEnabled: autoReplyEnabledFor(origin, category), minConfidence: null },
1674
1720
  categories: [],
1675
1721
  log: (msg) => ctx.logger.debug(msg),
1676
1722
  send: dryRun ? { mode: "none" } : { mode: "claimed", claim: seam.claim, commit: seam.commit },
@@ -1709,18 +1755,9 @@ async function respondToPendingResponse(ctx, config, recordId) {
1709
1755
  case "guardrail_hold":
1710
1756
  await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
1711
1757
  return;
1712
- case "needs_human": {
1713
- const persisted = await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
1714
- if (persisted) {
1715
- await ctx.api.inbox.raise({
1716
- key: buildInboxKey(recordId),
1717
- severity: "warning",
1718
- title: `R\xE9ponse g\xE9n\xE9r\xE9e \xE0 revoir \u2014 ticket ${ticketId}`,
1719
- entityRef: { appSlug: config.slug, objectKey: "generated-response", id: recordId }
1720
- });
1721
- }
1758
+ case "needs_human":
1759
+ await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
1722
1760
  return;
1723
- }
1724
1761
  case "awaiting_approval": {
1725
1762
  const persisted = await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
1726
1763
  if (persisted && !dryRun) {
@@ -1922,13 +1959,15 @@ async function writeErrorDecision(ctx, ref, message, deps) {
1922
1959
  }
1923
1960
  }
1924
1961
  async function escalateTicket(ctx, ref, deps) {
1925
- const tag = deps.profile.audit.escalationTag;
1962
+ await flagEscalation(ctx, ref, deps.profile.audit.escalationTag, deps.ports);
1963
+ }
1964
+ async function flagEscalation(ctx, ref, tag, ports) {
1926
1965
  if (!tag) {
1927
- ctx.logger.warn(`triage-tick: ticket ${ref.id} failed but escalationTag is not configured \u2014 no tag applied`);
1966
+ ctx.logger.warn(`triage-tick: ticket ${ref.id} is escalated but escalationTag is not configured \u2014 no tag applied`);
1928
1967
  return;
1929
1968
  }
1930
1969
  try {
1931
- await deps.ports.state.flag(ref, tag);
1970
+ await ports.state.flag(ref, tag);
1932
1971
  } catch (flagErr) {
1933
1972
  ctx.logger.error(`triage-tick: failed to escalate ticket ${ref.id} \u2014 it is NOT tagged for a human`, {
1934
1973
  error: flagErr instanceof Error ? flagErr.message : String(flagErr)
@@ -1979,9 +2018,11 @@ async function processOneTicket(ctx, ref, deps) {
1979
2018
  escalated: state.escalated,
1980
2019
  status: "ok",
1981
2020
  runId,
1982
- subjectRenamed
2021
+ subjectRenamed,
2022
+ origin: "triage"
1983
2023
  });
1984
2024
  await ports.state.record(ref, classification, profile.audit);
2025
+ if (state.escalated) await flagEscalation(ctx, ref, profile.audit.escalationTag, ports);
1985
2026
  if (!isEligibleForGeneratedResponse(profile, classification, state.escalated, category)) return;
1986
2027
  const draftAgent = await resolveDraftAgent(ctx.api, category?.agentId ?? null);
1987
2028
  const conversation = state.conversation;
@@ -2005,7 +2046,8 @@ async function processOneTicket(ctx, ref, deps) {
2005
2046
  guardrailHits: [],
2006
2047
  servedTo: [],
2007
2048
  servedCount: 0,
2008
- followupRequired: false
2049
+ followupRequired: false,
2050
+ origin: "triage"
2009
2051
  });
2010
2052
  } catch (err) {
2011
2053
  if (err instanceof AppApiError && err.status === 409) {
@@ -2090,12 +2132,6 @@ async function sweepStalledSending(ctx, now, escalationTag, statePort) {
2090
2132
  if (!reclaimed) continue;
2091
2133
  const ref = { id: ticketId, channel: "gorgias" };
2092
2134
  await statePort.flag(ref, escalationTag);
2093
- await ctx.api.inbox.raise({
2094
- key: buildInboxKey(row.id, "stalled-send"),
2095
- severity: "warning",
2096
- title: `Envoi bloqu\xE9 d\xE9tect\xE9 \u2014 ticket ${ticketId}`,
2097
- body: 'La r\xE9ponse est rest\xE9e en statut "sending" plus de 30 minutes et a \xE9t\xE9 replac\xE9e en attente humaine.'
2098
- });
2099
2135
  }
2100
2136
  }
2101
2137
  async function sweepStalledPending(ctx, now) {
@@ -2295,6 +2331,8 @@ var CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID = "1039e196-cf6e-438e-8ec9-7ab42
2295
2331
  var CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID = "10ffe3e1-972e-43b4-bb45-343c4664464f";
2296
2332
  var SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID = "2f5d6cbb-1c69-4a76-9d8f-1a3f0a4e57c2";
2297
2333
  var INVALIDATE_RESPONSE_INPUT_GENERATED_RESPONSE_ID_UID = "9748baf5-97be-4a22-940d-46ef2f16a175";
2334
+ var TEST_GORGIAS_WEBHOOK_INPUT_TICKET_ID_UID = "2cfcbfc1-77f1-4081-8fba-5f3a51c29e62";
2335
+ var TEST_GORGIAS_WEBHOOK_INPUT_MODE_UID = "e75c5ec9-1205-492f-87df-a84ec12753f8";
2298
2336
 
2299
2337
  // src/functions/run-triage-now.ts
2300
2338
  var TRIAGE_RUN_REQUESTED_EVENT = "triage.run.requested";
@@ -3979,6 +4017,605 @@ function nonEmptyString(value) {
3979
4017
  return typeof value === "string" && value.length > 0 ? value : null;
3980
4018
  }
3981
4019
 
4020
+ // src/functions/followup-gates.ts
4021
+ var LABELS = {
4022
+ G1: "Identifiant de ticket",
4023
+ G2: "Tag de p\xE9rim\xE8tre configur\xE9",
4024
+ G5: "Tag de p\xE9rim\xE8tre pr\xE9sent sur le ticket",
4025
+ G6: "Aucune reprise humaine",
4026
+ G7: "Cat\xE9gorie r\xE9solue et opt\xE9e",
4027
+ G8: "Nouveau message client"
4028
+ };
4029
+ function humanTakeoverTags(settings) {
4030
+ const configured = [settings.escalationTag, settings.needsReviewTag, settings.followupTag].map((tag) => tag.trim()).filter((tag) => tag !== "");
4031
+ return [...new Set(configured)];
4032
+ }
4033
+ function evaluateTicketIdGate(ticketId) {
4034
+ return ticketId === null ? stopped("G1", "Aucun identifiant de ticket exploitable (il doit \xEAtre une suite de chiffres).") : passed("G1", `Ticket ${ticketId}.`);
4035
+ }
4036
+ function evaluateScopeGate(settings) {
4037
+ 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.`);
4038
+ }
4039
+ function skippedFollowupGates(gates) {
4040
+ return gates.map((gate) => ({
4041
+ gate,
4042
+ label: LABELS[gate],
4043
+ status: "skipped",
4044
+ detail: "Non \xE9valu\xE9 : un gate pr\xE9c\xE9dent a arr\xEAt\xE9 le traitement."
4045
+ }));
4046
+ }
4047
+ var FRESH_READ_GATES = ["G5", "G6", "G7", "G8"];
4048
+ var ALL_FOLLOWUP_GATES = ["G1", "G2", ...FRESH_READ_GATES];
4049
+ function evaluateTicketGates(input) {
4050
+ const { settings, tags, categories, conversation, anchor } = input;
4051
+ const trace = newTrace(FRESH_READ_GATES);
4052
+ trace.record(scopeTagOnTicket(settings, tags));
4053
+ trace.record(noHumanTakeover(settings, tags));
4054
+ const match = trace.record(categoryGate(categories, tags));
4055
+ if (match) trace.category = match;
4056
+ trace.record(newCustomerMessage(conversation, anchor));
4057
+ return trace.done();
4058
+ }
4059
+ function evaluatePayloadGates(input) {
4060
+ const { settings, body, categories, anchor } = input;
4061
+ const trace = newTrace(FRESH_READ_GATES);
4062
+ const tags = body.tags;
4063
+ if (tags === null) {
4064
+ const detail = "Les tags du ticket n\u2019ont pas pu \xEAtre lus dans la charge utile \u2014 la lecture fra\xEEche tranchera.";
4065
+ trace.record(muted("G5", detail));
4066
+ trace.record(muted("G6", detail));
4067
+ trace.record(muted("G7", detail));
4068
+ } else {
4069
+ trace.record(scopeTagOnTicket(settings, tags));
4070
+ trace.record(noHumanTakeover(settings, tags));
4071
+ trace.record(singleCategoryMatch(categories, tags));
4072
+ }
4073
+ trace.record(payloadNewCustomerMessage(body, anchor));
4074
+ return trace.done();
4075
+ }
4076
+ function scopeTagOnTicket(settings, tags) {
4077
+ const scopeTag = settings.webhookScopeTag.trim();
4078
+ 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.`);
4079
+ }
4080
+ function noHumanTakeover(settings, tags) {
4081
+ const present = humanTakeoverTags(settings).filter((tag) => tags.includes(tag));
4082
+ 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.`);
4083
+ }
4084
+ function categoryGate(categories, tags) {
4085
+ const single = singleCategoryMatch(categories, tags);
4086
+ if (single.status === "stopped") return single;
4087
+ const category = matchingCategories(categories, tags)[0];
4088
+ if (!category.followupFastResponseEnabled) {
4089
+ return stopped("G7", `La cat\xE9gorie \xAB ${category.name} \xBB n\u2019a pas activ\xE9 les r\xE9ponses aux messages suivants.`);
4090
+ }
4091
+ if (!category.agentId) {
4092
+ return stopped("G7", `La cat\xE9gorie \xAB ${category.name} \xBB n\u2019a aucun agent : personne pour r\xE9diger.`);
4093
+ }
4094
+ return { ...passed("G7", `Cat\xE9gorie \xAB ${category.name} \xBB (tag \xAB ${category.tagName} \xBB).`), category };
4095
+ }
4096
+ function singleCategoryMatch(categories, tags) {
4097
+ const matches = matchingCategories(categories, tags);
4098
+ if (matches.length === 1) return passed("G7", `Cat\xE9gorie \xAB ${matches[0].name} \xBB.`);
4099
+ return matches.length === 0 ? stopped("G7", "Aucune cat\xE9gorie ne correspond \xE0 un tag du ticket : la d\xE9cision de triage est illisible.") : stopped(
4100
+ "G7",
4101
+ `${matches.length} cat\xE9gories correspondent aux tags du ticket (${matches.map((c) => c.tagName).join(", ")}) : d\xE9cision ambigu\xEB.`
4102
+ );
4103
+ }
4104
+ function matchingCategories(categories, tags) {
4105
+ return categories.filter((category) => tags.includes(category.tagName));
4106
+ }
4107
+ function newCustomerMessage(conversation, anchor) {
4108
+ if (conversation.isClosed) return stopped("G8", "Le ticket est ferm\xE9.");
4109
+ const last = conversation.messages[conversation.messages.length - 1];
4110
+ if (!last) return stopped("G8", "La conversation extraite est vide.");
4111
+ if (!isCustomerTurnWithWords(last)) {
4112
+ 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).");
4113
+ }
4114
+ if (anchor === null) return passed("G8", "Le dernier message est du client ; aucune r\xE9ponse ant\xE9rieure, donc aucune ancre \xE0 battre.");
4115
+ const lastAt = conversation.lastMessageAt;
4116
+ 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.");
4117
+ 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.`);
4118
+ }
4119
+ function payloadNewCustomerMessage(body, anchor) {
4120
+ if (body.isClosed === true) return stopped("G8", "La charge utile annonce un ticket ferm\xE9.");
4121
+ if (body.lastMessageFromAgent === true) return stopped("G8", "La charge utile annonce un dernier message d\u2019agent.");
4122
+ if (body.lastMessagePublic === false) return stopped("G8", "La charge utile annonce une note interne en dernier message.");
4123
+ if (anchor !== null && body.lastMessageAt !== null && body.lastMessageAt.getTime() <= anchor.getTime()) {
4124
+ return stopped("G8", `La charge utile annonce un dernier message (${body.lastMessageAt.toISOString()}) ant\xE9rieur ou \xE9gal \xE0 la derni\xE8re r\xE9ponse : relivraison.`);
4125
+ }
4126
+ if (body.isClosed === null && body.lastMessageFromAgent === null && body.lastMessagePublic === null && body.lastMessageAt === null) {
4127
+ return muted("G8", "Aucun champ exploitable dans la charge utile \u2014 la lecture fra\xEEche tranchera.");
4128
+ }
4129
+ return passed("G8", "Rien dans la charge utile ne permet d\u2019\xE9carter le ticket.");
4130
+ }
4131
+ function passed(gate, detail) {
4132
+ return { gate, label: LABELS[gate], status: "passed", detail };
4133
+ }
4134
+ function stopped(gate, detail) {
4135
+ return { gate, label: LABELS[gate], status: "stopped", detail };
4136
+ }
4137
+ function muted(gate, detail) {
4138
+ return { gate, label: LABELS[gate], status: "muted", detail };
4139
+ }
4140
+ function newTrace(gates) {
4141
+ const results = [];
4142
+ let stop2 = null;
4143
+ return {
4144
+ category: null,
4145
+ /** Records `result` unless the run already stopped; returns the category it resolved, if any. */
4146
+ record(result) {
4147
+ if (stop2) return null;
4148
+ results.push({ gate: result.gate, label: result.label, status: result.status, detail: result.detail });
4149
+ if (result.status === "stopped") stop2 = result;
4150
+ return result.category ?? null;
4151
+ },
4152
+ done() {
4153
+ const evaluated = new Set(results.map((result) => result.gate));
4154
+ for (const gate of gates) {
4155
+ if (!evaluated.has(gate)) {
4156
+ results.push({ gate, label: LABELS[gate], status: "skipped", detail: "Non \xE9valu\xE9 : un gate pr\xE9c\xE9dent a arr\xEAt\xE9 le traitement." });
4157
+ }
4158
+ }
4159
+ return { results, stop: stop2, category: stop2 ? null : this.category };
4160
+ }
4161
+ };
4162
+ }
4163
+
4164
+ // src/functions/webhook-body.ts
4165
+ var EMPTY_BODY = {
4166
+ ticketId: null,
4167
+ channel: null,
4168
+ lastMessageAt: null,
4169
+ isClosed: null,
4170
+ tags: null,
4171
+ lastMessageFromAgent: null,
4172
+ lastMessagePublic: null
4173
+ };
4174
+ var NUMERIC = /^\d+$/;
4175
+ var TRUE_TOKENS = /* @__PURE__ */ new Set(["true", "1", "yes", "on"]);
4176
+ var FALSE_TOKENS = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
4177
+ function parseFollowupWebhookBody(raw) {
4178
+ const body = toRecord(raw);
4179
+ if (!body) return { ...EMPTY_BODY };
4180
+ return {
4181
+ ticketId: parseTicketId(body.ticket_id),
4182
+ channel: parseText(body.channel),
4183
+ lastMessageAt: parseDate(body.last_message_datetime),
4184
+ isClosed: parseClosed(body.status),
4185
+ tags: parseTags(body.tags),
4186
+ lastMessageFromAgent: parseLaxBoolean(body.last_message_from_agent),
4187
+ lastMessagePublic: parseLaxBoolean(body.last_message_public)
4188
+ };
4189
+ }
4190
+ function toRecord(raw) {
4191
+ if (isPlainObject(raw)) return raw;
4192
+ if (typeof raw !== "string" || raw.trim() === "") return null;
4193
+ const asJson = tryJson(raw);
4194
+ if (isPlainObject(asJson)) return asJson;
4195
+ return parseFormEncoded(raw);
4196
+ }
4197
+ function parseFormEncoded(raw) {
4198
+ if (!raw.includes("=")) return null;
4199
+ const params = new URLSearchParams(raw);
4200
+ const entries = [...params.entries()];
4201
+ return entries.length > 0 ? Object.fromEntries(entries) : null;
4202
+ }
4203
+ function tryJson(raw) {
4204
+ try {
4205
+ return JSON.parse(raw);
4206
+ } catch {
4207
+ return void 0;
4208
+ }
4209
+ }
4210
+ function isPlainObject(value) {
4211
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4212
+ }
4213
+ function parseTicketId(raw) {
4214
+ if (typeof raw === "number") return Number.isSafeInteger(raw) && raw >= 0 ? String(raw) : null;
4215
+ return typeof raw === "string" && NUMERIC.test(raw) ? raw : null;
4216
+ }
4217
+ function parseText(raw) {
4218
+ if (typeof raw !== "string") return null;
4219
+ const trimmed = raw.trim();
4220
+ return trimmed === "" ? null : trimmed;
4221
+ }
4222
+ function parseDate(raw) {
4223
+ if (typeof raw !== "string") return null;
4224
+ const at = new Date(raw.trim());
4225
+ return Number.isNaN(at.getTime()) ? null : at;
4226
+ }
4227
+ function parseClosed(raw) {
4228
+ const text = parseText(raw);
4229
+ if (text === null) return null;
4230
+ if (text.toLowerCase() === "closed") return true;
4231
+ return text.startsWith("{{") ? null : false;
4232
+ }
4233
+ function parseLaxBoolean(raw) {
4234
+ if (typeof raw === "boolean") return raw;
4235
+ if (typeof raw === "number") {
4236
+ if (raw === 1) return true;
4237
+ if (raw === 0) return false;
4238
+ return null;
4239
+ }
4240
+ const text = parseText(raw)?.toLowerCase();
4241
+ if (text === void 0 || text === null) return null;
4242
+ if (TRUE_TOKENS.has(text)) return true;
4243
+ if (FALSE_TOKENS.has(text)) return false;
4244
+ return null;
4245
+ }
4246
+ function parseTags(raw) {
4247
+ const list = Array.isArray(raw) ? raw : arrayFromJson(raw);
4248
+ if (list === null || list.length === 0) return null;
4249
+ const names = [];
4250
+ for (const entry of list) {
4251
+ const name = tagNameOf(entry);
4252
+ if (name === null) return null;
4253
+ names.push(name);
4254
+ }
4255
+ return names;
4256
+ }
4257
+ function arrayFromJson(raw) {
4258
+ if (typeof raw !== "string") return null;
4259
+ const parsed = tryJson(raw);
4260
+ return Array.isArray(parsed) ? parsed : null;
4261
+ }
4262
+ function tagNameOf(entry) {
4263
+ if (typeof entry === "string") return parseText(entry);
4264
+ if (isPlainObject(entry)) return parseText(entry.name);
4265
+ return null;
4266
+ }
4267
+
4268
+ // src/functions/gorgias-webhook.ts
4269
+ var FOLLOWUP_RUN_REQUESTED_EVENT = "followup.run.requested";
4270
+ var FOLLOWUP_RUN_KIND = "gorgias-webhook";
4271
+ function buildGorgiasWebhookFunctionDef(config) {
4272
+ return {
4273
+ universalIdentifier: identifierFor(config, "gorgias-webhook"),
4274
+ name: "gorgias-webhook",
4275
+ trigger: { type: "httpRoute", path: "/gorgias/webhook", method: "POST", auth: "apiKey" }
4276
+ };
4277
+ }
4278
+ function buildGorgiasFollowupRunFunctionDef(config) {
4279
+ return {
4280
+ universalIdentifier: identifierFor(config, "gorgias-followup-run"),
4281
+ name: "gorgias-followup-run",
4282
+ trigger: { type: "event", name: FOLLOWUP_RUN_REQUESTED_EVENT }
4283
+ };
4284
+ }
4285
+ function createGorgiasWebhookHandler(config) {
4286
+ return (ctx, payload) => executeFollowupRun(
4287
+ ctx,
4288
+ config,
4289
+ payload?.body,
4290
+ null
4291
+ );
4292
+ }
4293
+ function createGorgiasFollowupRunHandler(config) {
4294
+ return (ctx, payload) => {
4295
+ const event = payload ?? {};
4296
+ return executeFollowupRun(ctx, config, event.body, event.runId ?? null);
4297
+ };
4298
+ }
4299
+ async function executeFollowupRun(ctx, config, rawBody, existingRunId) {
4300
+ const run = { id: existingRunId };
4301
+ try {
4302
+ const result = await runFollowupPass(ctx, config, rawBody, run);
4303
+ if (run.id) await ctx.api.runs.succeed(run.id, { ...result });
4304
+ } catch (err) {
4305
+ if (run.id) await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });
4306
+ throw err;
4307
+ }
4308
+ }
4309
+ async function runFollowupPass(ctx, config, rawBody, run) {
4310
+ const body = parseFollowupWebhookBody(rawBody);
4311
+ const ticketIdGate = evaluateTicketIdGate(body.ticketId);
4312
+ if (!body.ticketId) return stop(ctx, null, ticketIdGate.gate, ticketIdGate.detail);
4313
+ const ticketId = body.ticketId;
4314
+ const settings = await ctx.api.settings.get();
4315
+ const issues = validateSettings(settings);
4316
+ if (issues.length > 0) {
4317
+ return stop(ctx, ticketId, "settings", `r\xE9glages invalides : ${issues.map((issue) => issue.message).join(" ")}`);
4318
+ }
4319
+ const scope = evaluateScopeGate(settings);
4320
+ if (scope.status === "stopped") return stopAt(ctx, ticketId, scope);
4321
+ const { anchor, hasOpenResponse } = await readFollowupAnchor(ctx, ticketId);
4322
+ const categories = await listCategories(ctx.api);
4323
+ const preGates = evaluatePayloadGates({ settings, body, categories, anchor });
4324
+ if (preGates.stop) return stopAt(ctx, ticketId, preGates.stop, "pr\xE9-gate");
4325
+ const ref = { id: ticketId, channel: "gorgias" };
4326
+ const ticket = await ctx.api.integrations.run("gorgias", "getTicketWithContext", { ticketId });
4327
+ const raw = ticket?.ticket ?? {};
4328
+ const conversation = toConversation(ref, raw, ticket?.context ?? { messages: [], customerContext: null });
4329
+ const gates = evaluateTicketGates({ settings, tags: ticketTagNames(raw), categories, conversation, anchor });
4330
+ if (gates.stop || !gates.category) {
4331
+ return stopAt(ctx, ticketId, gates.stop ?? unresolvedCategory());
4332
+ }
4333
+ const category = gates.category;
4334
+ if (hasOpenResponse) return stop(ctx, ticketId, "G9", "une r\xE9ponse est d\xE9j\xE0 ouverte sur ce ticket");
4335
+ run.id ??= (await ctx.api.runs.start({
4336
+ kind: FOLLOWUP_RUN_KIND,
4337
+ message: `Message suivant \u2014 ticket ${ticketId}`,
4338
+ metadata: { ticketId, categoryTag: category.tagName, channel: body.channel }
4339
+ })).id;
4340
+ const created = await openFollowupResponse(ctx, { ticketId, category, conversation, settings, runId: run.id });
4341
+ if (!created) return stop(ctx, ticketId, "G9", "une autre ex\xE9cution a ouvert la r\xE9ponse en premier");
4342
+ await respondToPendingResponse(ctx, config, created.id);
4343
+ return { ticketId, stoppedAt: null, reason: `r\xE9ponse de suite g\xE9n\xE9r\xE9e (cat\xE9gorie \xAB ${category.name} \xBB)` };
4344
+ }
4345
+ async function readFollowupAnchor(ctx, ticketId) {
4346
+ const page = await ctx.api.list("generated-response", { filter: { ticketId }, limit: ANCHOR_LOOKUP_LIMIT });
4347
+ let anchor = null;
4348
+ let hasOpenResponse = false;
4349
+ for (const item of page.items) {
4350
+ const data = item.data;
4351
+ if (data.openTicketKey === ticketId) hasOpenResponse = true;
4352
+ for (const raw of [data.generatedLastMessageAt, data.sentAt]) {
4353
+ const at = toDate2(raw);
4354
+ if (at && (!anchor || at > anchor)) anchor = at;
4355
+ }
4356
+ }
4357
+ return { anchor, hasOpenResponse };
4358
+ }
4359
+ var ANCHOR_LOOKUP_LIMIT = 100;
4360
+ function toDate2(raw) {
4361
+ if (raw instanceof Date) return Number.isNaN(raw.getTime()) ? null : raw;
4362
+ if (typeof raw !== "string") return null;
4363
+ const at = new Date(raw);
4364
+ return Number.isNaN(at.getTime()) ? null : at;
4365
+ }
4366
+ function ticketTagNames(raw) {
4367
+ const tags = raw.tags;
4368
+ if (!Array.isArray(tags)) return [];
4369
+ const names = [];
4370
+ for (const entry of tags) {
4371
+ if (typeof entry === "string" && entry !== "") {
4372
+ names.push(entry);
4373
+ continue;
4374
+ }
4375
+ if (typeof entry === "object" && entry !== null) {
4376
+ const name = entry.name;
4377
+ if (typeof name === "string" && name !== "") names.push(name);
4378
+ }
4379
+ }
4380
+ return names;
4381
+ }
4382
+ async function openFollowupResponse(ctx, input) {
4383
+ const { ticketId, category, conversation, settings, runId } = input;
4384
+ const decision = await ctx.api.create("triage-decision", {
4385
+ ticketId,
4386
+ // Not resolved: `getTicketUrlBase` is a SECOND Gorgias call and this
4387
+ // function runs once per message of the whole account. The field is
4388
+ // documented nullable for exactly this kind of row.
4389
+ ticketUrl: null,
4390
+ decidedAt: /* @__PURE__ */ new Date(),
4391
+ categoryId: category.id,
4392
+ tag: category.tagName,
4393
+ // §7.2 — NULL, and it is the honest value: no classifier ran on this pass
4394
+ // (D3 — the category is inherited from the tag the first pass applied), so
4395
+ // there is no confidence to state. The column was widened to allow it
4396
+ // (`records/triage-decision.ts`); a reader that needs a value still derives
4397
+ // `'low'` (`process-response.ts`'s `classificationFromDecision`).
4398
+ //
4399
+ // That derived `'low'` no longer holds the reply back: a follow-up pass is
4400
+ // governed by the evaluation of its own draft, not by a triage confidence
4401
+ // that does not exist — see `applyFollowupSendPolicy` in
4402
+ // `process-response.ts` for the decision and what it replaces.
4403
+ confidence: null,
4404
+ reasoning: `Message suivant \u2014 cat\xE9gorie r\xE9solue par le tag ${category.tagName}`,
4405
+ // The customer has just written, so the thread is by definition not over;
4406
+ // and the escalation decision belongs to the first pass, which this one
4407
+ // deliberately does not replay (D5).
4408
+ conversationOver: false,
4409
+ escalated: false,
4410
+ status: "ok",
4411
+ runId,
4412
+ subjectRenamed: false,
4413
+ origin: "followup"
4414
+ });
4415
+ const agent = await resolveDraftAgent(ctx.api, category.agentId);
4416
+ const generatedAt = /* @__PURE__ */ new Date();
4417
+ try {
4418
+ return await ctx.api.create("generated-response", {
4419
+ ticketId,
4420
+ openTicketKey: openTicketKeyFor("pending", ticketId),
4421
+ status: "pending",
4422
+ triageDecisionId: decision.id,
4423
+ categoryId: category.id,
4424
+ agentId: agent?.id ?? null,
4425
+ channel: conversation.sourceChannel === "whatsapp" ? "whatsapp" : "email",
4426
+ generatedAt,
4427
+ expiresAt: new Date(generatedAt.getTime() + settings.responseTtlMinutes * 6e4),
4428
+ sources: [],
4429
+ tracedInput: [],
4430
+ guardrailHits: [],
4431
+ servedTo: [],
4432
+ servedCount: 0,
4433
+ followupRequired: false,
4434
+ origin: "followup"
4435
+ });
4436
+ } catch (err) {
4437
+ if (err instanceof AppApiError && err.status === 409) return null;
4438
+ throw err;
4439
+ }
4440
+ }
4441
+ function unresolvedCategory() {
4442
+ return {
4443
+ gate: "G7",
4444
+ label: "Cat\xE9gorie r\xE9solue et opt\xE9e",
4445
+ status: "stopped",
4446
+ detail: "Aucune cat\xE9gorie r\xE9solue."
4447
+ };
4448
+ }
4449
+ function stopAt(ctx, ticketId, result, kind = "gate") {
4450
+ return stop(ctx, ticketId, `${result.gate}${kind === "gate" ? "" : ` (${kind})`}`, result.detail);
4451
+ }
4452
+ function stop(ctx, ticketId, gate, reason) {
4453
+ ctx.logger.info(`gorgias-webhook: stop at ${gate} for ticket ${ticketId ?? "?"} \u2014 ${reason}`);
4454
+ return { ticketId, stoppedAt: gate, reason };
4455
+ }
4456
+
4457
+ // src/functions/setup-gorgias-webhook.ts
4458
+ var GORGIAS_CALLBACK_APP_KEY_VARIABLE = "GORGIAS_CALLBACK_APP_KEY";
4459
+ var APP_API_KEY_PREFIX = "wopilo_app_";
4460
+ var FOLLOWUP_WEBHOOK_FORM = {
4461
+ ticket_id: "{{ticket.id}}",
4462
+ channel: "{{ticket.channel}}",
4463
+ last_message_datetime: "{{ticket.last_message_datetime}}",
4464
+ status: "{{ticket.status}}",
4465
+ tags: "{{ticket.tags}}",
4466
+ last_message_from_agent: "{{ticket.messages[-1].from_agent}}",
4467
+ last_message_public: "{{ticket.messages[-1].public}}"
4468
+ };
4469
+ var FOLLOWUP_WEBHOOK_TRIGGERS = { "ticket-message-created": true };
4470
+ function followupIntegrationName(slug) {
4471
+ return `Wopilo \u2014 R\xE9ponses aux messages suivants (${slug})`;
4472
+ }
4473
+ function buildSetupGorgiasWebhookFunctionDef(config) {
4474
+ return {
4475
+ universalIdentifier: identifierFor(config, "setup-gorgias-webhook"),
4476
+ name: "setup-gorgias-webhook",
4477
+ trigger: { type: "uiInvoke", minRole: "ADMIN", timeoutMs: 2e4 }
4478
+ };
4479
+ }
4480
+ function createSetupGorgiasWebhookHandler(config) {
4481
+ return (ctx) => setupGorgiasWebhookHandler(ctx, config);
4482
+ }
4483
+ async function setupGorgiasWebhookHandler(ctx, config) {
4484
+ const key = readCallbackKey(ctx);
4485
+ const name = followupIntegrationName(config.slug);
4486
+ const url = `${publicOrigin(ctx)}/api/s/${config.slug}/gorgias/webhook`;
4487
+ const result = await ctx.api.integrations.run("gorgias", "upsertHttpIntegration", {
4488
+ name,
4489
+ description: "Rappelle Wopilo \xE0 chaque nouveau message de ticket, pour r\xE9pondre aux messages suivants.",
4490
+ url,
4491
+ method: "POST",
4492
+ headers: { Authorization: `Bearer ${key}` },
4493
+ form: FOLLOWUP_WEBHOOK_FORM,
4494
+ triggers: FOLLOWUP_WEBHOOK_TRIGGERS
4495
+ });
4496
+ ctx.logger.info(`setup-gorgias-webhook: int\xE9gration \xAB ${name} \xBB pos\xE9e sur ${url}`);
4497
+ return {
4498
+ integrationId: String(result?.id ?? ""),
4499
+ created: result?.created === true,
4500
+ name,
4501
+ url
4502
+ };
4503
+ }
4504
+ function readCallbackKey(ctx) {
4505
+ const raw = ctx.variables[GORGIAS_CALLBACK_APP_KEY_VARIABLE];
4506
+ const key = typeof raw === "string" ? raw.trim() : "";
4507
+ if (!key) {
4508
+ throw new ctx.NonRetriableError(
4509
+ `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.`
4510
+ );
4511
+ }
4512
+ if (!key.startsWith(APP_API_KEY_PREFIX)) {
4513
+ throw new ctx.NonRetriableError(
4514
+ `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.`
4515
+ );
4516
+ }
4517
+ return key;
4518
+ }
4519
+ function publicOrigin(ctx) {
4520
+ const base = process.env.PUBLIC_BASE_URL?.trim().replace(/\/+$/, "");
4521
+ if (!base) {
4522
+ throw new ctx.NonRetriableError(
4523
+ "La variable d'instance PUBLIC_BASE_URL n'est pas d\xE9finie : impossible de construire une URL de rappel que Gorgias puisse joindre."
4524
+ );
4525
+ }
4526
+ return base;
4527
+ }
4528
+ function buildTestGorgiasWebhookFunctionDef(config) {
4529
+ return {
4530
+ universalIdentifier: identifierFor(config, "test-gorgias-webhook"),
4531
+ name: "test-gorgias-webhook",
4532
+ trigger: { type: "uiInvoke", minRole: "ADMIN", timeoutMs: 2e4 },
4533
+ input: [
4534
+ {
4535
+ universalIdentifier: TEST_GORGIAS_WEBHOOK_INPUT_TICKET_ID_UID,
4536
+ name: "ticketId",
4537
+ type: FieldType.TEXT,
4538
+ label: "Ticket id",
4539
+ description: "Identifiant Gorgias du ticket \xE0 tester.",
4540
+ isNullable: true
4541
+ },
4542
+ {
4543
+ universalIdentifier: TEST_GORGIAS_WEBHOOK_INPUT_MODE_UID,
4544
+ name: "mode",
4545
+ type: FieldType.TEXT,
4546
+ label: "Mode",
4547
+ 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.",
4548
+ isNullable: true
4549
+ }
4550
+ ]
4551
+ };
4552
+ }
4553
+ function createTestGorgiasWebhookHandler(_config) {
4554
+ return (ctx, input) => testGorgiasWebhookHandler(ctx, input ?? {});
4555
+ }
4556
+ var NUMERIC2 = /^\d+$/;
4557
+ async function testGorgiasWebhookHandler(ctx, input) {
4558
+ const ticketId = typeof input.ticketId === "string" && NUMERIC2.test(input.ticketId.trim()) ? input.ticketId.trim() : null;
4559
+ const mode = input.mode === "run" ? "run" : "diagnostic";
4560
+ if (mode === "run") {
4561
+ if (!ticketId) throw new ctx.NonRetriableError("L'identifiant du ticket doit \xEAtre une suite de chiffres.");
4562
+ return triggerRealRun(ctx, ticketId);
4563
+ }
4564
+ return diagnose(ctx, ticketId);
4565
+ }
4566
+ async function diagnose(ctx, ticketId) {
4567
+ const gates = [];
4568
+ const ticketIdGate = evaluateTicketIdGate(ticketId);
4569
+ gates.push(ticketIdGate);
4570
+ if (!ticketId) return finish(gates, "");
4571
+ const settings = await ctx.api.settings.get();
4572
+ const issues = validateSettings(settings);
4573
+ if (issues.length > 0) {
4574
+ throw new ctx.NonRetriableError(`R\xE9glages invalides : ${issues.map((issue) => issue.message).join(" ")}`);
4575
+ }
4576
+ const scope = evaluateScopeGate(settings);
4577
+ gates.push(scope);
4578
+ if (scope.status === "stopped") return finish(gates, ticketId);
4579
+ const { anchor } = await readFollowupAnchor(ctx, ticketId);
4580
+ const categories = await listCategories(ctx.api);
4581
+ const ref = { id: ticketId, channel: "gorgias" };
4582
+ const ticket = await ctx.api.integrations.run("gorgias", "getTicketWithContext", { ticketId });
4583
+ const raw = ticket?.ticket ?? {};
4584
+ const conversation = toConversation(ref, raw, ticket?.context ?? { messages: [], customerContext: null });
4585
+ const trace = evaluateTicketGates({ settings, tags: ticketTagNames(raw), categories, conversation, anchor });
4586
+ gates.push(...trace.results);
4587
+ return finish(gates, ticketId);
4588
+ }
4589
+ function finish(gates, ticketId) {
4590
+ const evaluated = new Set(gates.map((gate) => gate.gate));
4591
+ const missing = ALL_FOLLOWUP_GATES.filter((gate) => !evaluated.has(gate));
4592
+ const full = [...gates, ...skippedFollowupGates(missing)];
4593
+ return {
4594
+ mode: "diagnostic",
4595
+ ticketId,
4596
+ stoppedAt: full.find((gate) => gate.status === "stopped")?.gate ?? null,
4597
+ gates: full
4598
+ };
4599
+ }
4600
+ async function triggerRealRun(ctx, ticketId) {
4601
+ const run = await ctx.api.runs.start({
4602
+ kind: FOLLOWUP_RUN_KIND,
4603
+ message: `Test webhook \u2014 ticket ${ticketId}`,
4604
+ metadata: { ticketId, triggeredFrom: "test-gorgias-webhook" }
4605
+ });
4606
+ try {
4607
+ await ctx.api.events.send(FOLLOWUP_RUN_REQUESTED_EVENT, {
4608
+ _key: run.id,
4609
+ runId: run.id,
4610
+ body: { ticket_id: ticketId }
4611
+ });
4612
+ } catch (err) {
4613
+ await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });
4614
+ throw err;
4615
+ }
4616
+ return { mode: "run", ticketId, runId: run.id };
4617
+ }
4618
+
3982
4619
  // src/pages/manifest.ts
3983
4620
  function pageIdentifierFor(config, key) {
3984
4621
  const id = config.identifiers[key];
@@ -4002,12 +4639,28 @@ var SUPPORT_KIT_GORGIAS_SCOPES = [
4002
4639
  "read_tickets",
4003
4640
  "read_views",
4004
4641
  "write_tags",
4005
- "write_tickets"
4642
+ "write_tickets",
4643
+ // What `upsertHttpIntegration` demands (its own `scopes`, in
4644
+ // `packages/gorgias-client/src/sidebar-widget.ts`). The name says "widgets"
4645
+ // because that action's sibling posts one; this kit posts no widget, only
4646
+ // the HTTP integration the same scope governs. Requesting it makes the
4647
+ // consent modal state, honestly, that the app may write an integration on
4648
+ // the account.
4649
+ "write_widgets"
4650
+ ];
4651
+ var SUPPORT_KIT_SERVER_VARIABLES = [
4652
+ {
4653
+ universalIdentifier: "4dd02108-ba4c-441e-9ea3-ec86f8bf3a1f",
4654
+ name: GORGIAS_CALLBACK_APP_KEY_VARIABLE,
4655
+ 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).",
4656
+ type: "STRING",
4657
+ isRequired: false
4658
+ }
4006
4659
  ];
4007
4660
  var SUPPORT_KIT_INTEGRATIONS = [
4008
4661
  { provider: "gorgias", scopes: [...SUPPORT_KIT_GORGIAS_SCOPES] }
4009
4662
  ];
4010
- var SUPPORT_KIT_EMITS = [TRIAGE_RUN_REQUESTED_EVENT];
4663
+ var SUPPORT_KIT_EMITS = [TRIAGE_RUN_REQUESTED_EVENT, FOLLOWUP_RUN_REQUESTED_EVENT];
4011
4664
  var FUNCTION_ASSEMBLY = [
4012
4665
  { key: "triage-tick", build: buildTriageTickFunctionDef, createHandler: createTriageTickHandler },
4013
4666
  { key: "sweep", build: buildSweepFunctionDef, createHandler: () => createSweepHandler() },
@@ -4102,6 +4755,27 @@ var FUNCTION_ASSEMBLY = [
4102
4755
  key: "ext-response-comparison",
4103
4756
  build: buildExtResponseComparisonFunctionDef,
4104
4757
  createHandler: () => createExtResponseComparisonHandler()
4758
+ },
4759
+ // spec-gorgias-followup-webhook-v1 §5 — the push half.
4760
+ {
4761
+ key: "gorgias-webhook",
4762
+ build: buildGorgiasWebhookFunctionDef,
4763
+ createHandler: createGorgiasWebhookHandler
4764
+ },
4765
+ {
4766
+ key: "gorgias-followup-run",
4767
+ build: buildGorgiasFollowupRunFunctionDef,
4768
+ createHandler: createGorgiasFollowupRunHandler
4769
+ },
4770
+ {
4771
+ key: "setup-gorgias-webhook",
4772
+ build: buildSetupGorgiasWebhookFunctionDef,
4773
+ createHandler: createSetupGorgiasWebhookHandler
4774
+ },
4775
+ {
4776
+ key: "test-gorgias-webhook",
4777
+ build: buildTestGorgiasWebhookFunctionDef,
4778
+ createHandler: createTestGorgiasWebhookHandler
4105
4779
  }
4106
4780
  ];
4107
4781
  function buildPromptsAllowlist() {
@@ -4214,6 +4888,7 @@ function buildSupportPipeline(config) {
4214
4888
  navigation: buildNavigation(config),
4215
4889
  settingsPage: buildSettingsPage(config),
4216
4890
  integrations: SUPPORT_KIT_INTEGRATIONS,
4891
+ serverVariables: SUPPORT_KIT_SERVER_VARIABLES,
4217
4892
  emits: SUPPORT_KIT_EMITS,
4218
4893
  defaultRole: "NO_ACCESS",
4219
4894
  handlers,