@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/README.md +66 -0
- package/dist/{chunk-CQJJZA4F.js → chunk-2UHFKGMI.js} +55 -6
- package/dist/chunk-2UHFKGMI.js.map +1 -0
- package/dist/index.cjs +686 -38
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +51 -5
- package/dist/index.d.ts +51 -5
- package/dist/index.js +651 -38
- package/dist/index.js.map +1 -1
- package/dist/ui/index.cjs +284 -8
- package/dist/ui/index.cjs.map +1 -1
- package/dist/ui/index.js +249 -6
- package/dist/ui/index.js.map +1 -1
- package/package.json +11 -11
- package/dist/chunk-CQJJZA4F.js.map +0 -1
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,
|
|
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-
|
|
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-2UHFKGMI.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-2UHFKGMI.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
|
-
|
|
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 {
|
|
@@ -1609,7 +1651,7 @@ async function finalizeNonSent(ctx, id, ticketId, toStatus, extra) {
|
|
|
1609
1651
|
throw err;
|
|
1610
1652
|
}
|
|
1611
1653
|
}
|
|
1612
|
-
async function respondToPendingResponse(ctx, config, recordId) {
|
|
1654
|
+
async function respondToPendingResponse(ctx, config, recordId, options = {}) {
|
|
1613
1655
|
const record = await getOptional(ctx, "generated-response", recordId);
|
|
1614
1656
|
if (!record) {
|
|
1615
1657
|
ctx.logger.info(`respond: generated-response ${recordId} no longer exists, skipping`);
|
|
@@ -1637,10 +1679,15 @@ 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 =
|
|
1643
|
-
|
|
1685
|
+
const profile = applyFollowupSendPolicy(
|
|
1686
|
+
settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes)),
|
|
1687
|
+
origin
|
|
1688
|
+
);
|
|
1689
|
+
const testRun = options.testRun === true;
|
|
1690
|
+
const dryRun = settings.dryRun === true || testRun;
|
|
1644
1691
|
const trace = { sessionId: ticketId, tags: [`app:${config.slug}`] };
|
|
1645
1692
|
const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx, trace), ctx.api) : buildTicketPorts(ctx, trace);
|
|
1646
1693
|
const { clock } = ports;
|
|
@@ -1670,7 +1717,7 @@ async function respondToPendingResponse(ctx, config, recordId) {
|
|
|
1670
1717
|
ports,
|
|
1671
1718
|
toolContext: createNoToolContext(),
|
|
1672
1719
|
budget,
|
|
1673
|
-
category: { autoReplyEnabled: category
|
|
1720
|
+
category: { autoReplyEnabled: autoReplyEnabledFor(origin, category), minConfidence: null },
|
|
1674
1721
|
categories: [],
|
|
1675
1722
|
log: (msg) => ctx.logger.debug(msg),
|
|
1676
1723
|
send: dryRun ? { mode: "none" } : { mode: "claimed", claim: seam.claim, commit: seam.commit },
|
|
@@ -1694,35 +1741,30 @@ async function respondToPendingResponse(ctx, config, recordId) {
|
|
|
1694
1741
|
// sent reply and a held one are read by the same timeline.
|
|
1695
1742
|
tracedInput: toTracedInput(result.draft?.messages ?? []),
|
|
1696
1743
|
verdict: result.verdict ?? null,
|
|
1697
|
-
|
|
1698
|
-
|
|
1744
|
+
// Omitted on a test run — see `RespondOptions.testRun`, consequence THREE.
|
|
1745
|
+
...testRun ? {} : {
|
|
1746
|
+
generatedMessageCount: conversationSnapshot.messageCount,
|
|
1747
|
+
generatedLastMessageAt: conversationSnapshot.lastMessageAt
|
|
1748
|
+
},
|
|
1699
1749
|
...attributionFields(result.draft?.attribution)
|
|
1700
1750
|
};
|
|
1751
|
+
const restingStatus = testRun ? "invalidated" : "ready";
|
|
1701
1752
|
switch (result.outcome) {
|
|
1702
1753
|
case "sent":
|
|
1703
1754
|
if (dryRun) {
|
|
1704
|
-
await finalizeNonSent(ctx, recordId, ticketId,
|
|
1755
|
+
await finalizeNonSent(ctx, recordId, ticketId, restingStatus, draftExtra);
|
|
1705
1756
|
return;
|
|
1706
1757
|
}
|
|
1707
1758
|
return;
|
|
1708
1759
|
case "ready":
|
|
1709
1760
|
case "guardrail_hold":
|
|
1710
|
-
await finalizeNonSent(ctx, recordId, ticketId,
|
|
1761
|
+
await finalizeNonSent(ctx, recordId, ticketId, restingStatus, draftExtra);
|
|
1711
1762
|
return;
|
|
1712
|
-
case "needs_human":
|
|
1713
|
-
|
|
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
|
-
}
|
|
1763
|
+
case "needs_human":
|
|
1764
|
+
await finalizeNonSent(ctx, recordId, ticketId, restingStatus, draftExtra);
|
|
1722
1765
|
return;
|
|
1723
|
-
}
|
|
1724
1766
|
case "awaiting_approval": {
|
|
1725
|
-
const persisted = await finalizeNonSent(ctx, recordId, ticketId,
|
|
1767
|
+
const persisted = await finalizeNonSent(ctx, recordId, ticketId, restingStatus, draftExtra);
|
|
1726
1768
|
if (persisted && !dryRun) {
|
|
1727
1769
|
await ctx.api.approvals.request({
|
|
1728
1770
|
key: buildApprovalKey(recordId),
|
|
@@ -1922,13 +1964,15 @@ async function writeErrorDecision(ctx, ref, message, deps) {
|
|
|
1922
1964
|
}
|
|
1923
1965
|
}
|
|
1924
1966
|
async function escalateTicket(ctx, ref, deps) {
|
|
1925
|
-
|
|
1967
|
+
await flagEscalation(ctx, ref, deps.profile.audit.escalationTag, deps.ports);
|
|
1968
|
+
}
|
|
1969
|
+
async function flagEscalation(ctx, ref, tag, ports) {
|
|
1926
1970
|
if (!tag) {
|
|
1927
|
-
ctx.logger.warn(`triage-tick: ticket ${ref.id}
|
|
1971
|
+
ctx.logger.warn(`triage-tick: ticket ${ref.id} is escalated but escalationTag is not configured \u2014 no tag applied`);
|
|
1928
1972
|
return;
|
|
1929
1973
|
}
|
|
1930
1974
|
try {
|
|
1931
|
-
await
|
|
1975
|
+
await ports.state.flag(ref, tag);
|
|
1932
1976
|
} catch (flagErr) {
|
|
1933
1977
|
ctx.logger.error(`triage-tick: failed to escalate ticket ${ref.id} \u2014 it is NOT tagged for a human`, {
|
|
1934
1978
|
error: flagErr instanceof Error ? flagErr.message : String(flagErr)
|
|
@@ -1979,9 +2023,11 @@ async function processOneTicket(ctx, ref, deps) {
|
|
|
1979
2023
|
escalated: state.escalated,
|
|
1980
2024
|
status: "ok",
|
|
1981
2025
|
runId,
|
|
1982
|
-
subjectRenamed
|
|
2026
|
+
subjectRenamed,
|
|
2027
|
+
origin: "triage"
|
|
1983
2028
|
});
|
|
1984
2029
|
await ports.state.record(ref, classification, profile.audit);
|
|
2030
|
+
if (state.escalated) await flagEscalation(ctx, ref, profile.audit.escalationTag, ports);
|
|
1985
2031
|
if (!isEligibleForGeneratedResponse(profile, classification, state.escalated, category)) return;
|
|
1986
2032
|
const draftAgent = await resolveDraftAgent(ctx.api, category?.agentId ?? null);
|
|
1987
2033
|
const conversation = state.conversation;
|
|
@@ -2005,7 +2051,8 @@ async function processOneTicket(ctx, ref, deps) {
|
|
|
2005
2051
|
guardrailHits: [],
|
|
2006
2052
|
servedTo: [],
|
|
2007
2053
|
servedCount: 0,
|
|
2008
|
-
followupRequired: false
|
|
2054
|
+
followupRequired: false,
|
|
2055
|
+
origin: "triage"
|
|
2009
2056
|
});
|
|
2010
2057
|
} catch (err) {
|
|
2011
2058
|
if (err instanceof AppApiError && err.status === 409) {
|
|
@@ -2090,12 +2137,6 @@ async function sweepStalledSending(ctx, now, escalationTag, statePort) {
|
|
|
2090
2137
|
if (!reclaimed) continue;
|
|
2091
2138
|
const ref = { id: ticketId, channel: "gorgias" };
|
|
2092
2139
|
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
2140
|
}
|
|
2100
2141
|
}
|
|
2101
2142
|
async function sweepStalledPending(ctx, now) {
|
|
@@ -2295,6 +2336,8 @@ var CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID = "1039e196-cf6e-438e-8ec9-7ab42
|
|
|
2295
2336
|
var CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID = "10ffe3e1-972e-43b4-bb45-343c4664464f";
|
|
2296
2337
|
var SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID = "2f5d6cbb-1c69-4a76-9d8f-1a3f0a4e57c2";
|
|
2297
2338
|
var INVALIDATE_RESPONSE_INPUT_GENERATED_RESPONSE_ID_UID = "9748baf5-97be-4a22-940d-46ef2f16a175";
|
|
2339
|
+
var TEST_GORGIAS_WEBHOOK_INPUT_TICKET_ID_UID = "2cfcbfc1-77f1-4081-8fba-5f3a51c29e62";
|
|
2340
|
+
var TEST_GORGIAS_WEBHOOK_INPUT_MODE_UID = "e75c5ec9-1205-492f-87df-a84ec12753f8";
|
|
2298
2341
|
|
|
2299
2342
|
// src/functions/run-triage-now.ts
|
|
2300
2343
|
var TRIAGE_RUN_REQUESTED_EVENT = "triage.run.requested";
|
|
@@ -3979,6 +4022,558 @@ function nonEmptyString(value) {
|
|
|
3979
4022
|
return typeof value === "string" && value.length > 0 ? value : null;
|
|
3980
4023
|
}
|
|
3981
4024
|
|
|
4025
|
+
// src/functions/followup-gates.ts
|
|
4026
|
+
var LABELS = {
|
|
4027
|
+
G1: "Identifiant de ticket",
|
|
4028
|
+
G2: "Tag de p\xE9rim\xE8tre configur\xE9",
|
|
4029
|
+
G5: "Tag de p\xE9rim\xE8tre pr\xE9sent sur le ticket",
|
|
4030
|
+
G6: "Aucune reprise humaine",
|
|
4031
|
+
G7: "Cat\xE9gorie r\xE9solue et opt\xE9e",
|
|
4032
|
+
G8: "Nouveau message client"
|
|
4033
|
+
};
|
|
4034
|
+
function humanTakeoverTags(settings) {
|
|
4035
|
+
const configured = [settings.escalationTag, settings.needsReviewTag, settings.followupTag].map((tag) => tag.trim()).filter((tag) => tag !== "");
|
|
4036
|
+
return [...new Set(configured)];
|
|
4037
|
+
}
|
|
4038
|
+
function evaluateTicketIdGate(ticketId) {
|
|
4039
|
+
return ticketId === null ? stopped("G1", "Aucun identifiant de ticket exploitable (il doit \xEAtre une suite de chiffres).") : passed("G1", `Ticket ${ticketId}.`);
|
|
4040
|
+
}
|
|
4041
|
+
function evaluateScopeGate(settings) {
|
|
4042
|
+
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.`);
|
|
4043
|
+
}
|
|
4044
|
+
function skippedFollowupGates(gates) {
|
|
4045
|
+
return gates.map((gate) => ({
|
|
4046
|
+
gate,
|
|
4047
|
+
label: LABELS[gate],
|
|
4048
|
+
status: "skipped",
|
|
4049
|
+
detail: "Non \xE9valu\xE9 : un gate pr\xE9c\xE9dent a arr\xEAt\xE9 le traitement."
|
|
4050
|
+
}));
|
|
4051
|
+
}
|
|
4052
|
+
var FRESH_READ_GATES = ["G5", "G6", "G7", "G8"];
|
|
4053
|
+
var ALL_FOLLOWUP_GATES = ["G1", "G2", ...FRESH_READ_GATES];
|
|
4054
|
+
function evaluateTicketGates(input) {
|
|
4055
|
+
const { settings, tags, categories, conversation, anchor, ignoreCategoryOptIn = false } = input;
|
|
4056
|
+
const trace = newTrace(FRESH_READ_GATES);
|
|
4057
|
+
trace.record(scopeTagOnTicket(settings, tags));
|
|
4058
|
+
trace.record(noHumanTakeover(settings, tags));
|
|
4059
|
+
const match = trace.record(categoryGate(categories, tags, ignoreCategoryOptIn));
|
|
4060
|
+
if (match) trace.category = match;
|
|
4061
|
+
trace.record(newCustomerMessage(conversation, anchor));
|
|
4062
|
+
return trace.done();
|
|
4063
|
+
}
|
|
4064
|
+
function evaluatePayloadGates(input) {
|
|
4065
|
+
const { settings, body, categories, anchor } = input;
|
|
4066
|
+
const trace = newTrace(FRESH_READ_GATES);
|
|
4067
|
+
const tags = body.tags;
|
|
4068
|
+
if (tags === null) {
|
|
4069
|
+
const detail = "Les tags du ticket n\u2019ont pas pu \xEAtre lus dans la charge utile \u2014 la lecture fra\xEEche tranchera.";
|
|
4070
|
+
trace.record(muted("G5", detail));
|
|
4071
|
+
trace.record(muted("G6", detail));
|
|
4072
|
+
trace.record(muted("G7", detail));
|
|
4073
|
+
} else {
|
|
4074
|
+
trace.record(scopeTagOnTicket(settings, tags));
|
|
4075
|
+
trace.record(noHumanTakeover(settings, tags));
|
|
4076
|
+
trace.record(anyCategoryMatch(categories, tags));
|
|
4077
|
+
}
|
|
4078
|
+
trace.record(payloadNewCustomerMessage(body, anchor));
|
|
4079
|
+
return trace.done();
|
|
4080
|
+
}
|
|
4081
|
+
function scopeTagOnTicket(settings, tags) {
|
|
4082
|
+
const scopeTag = settings.webhookScopeTag.trim();
|
|
4083
|
+
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.`);
|
|
4084
|
+
}
|
|
4085
|
+
function noHumanTakeover(settings, tags) {
|
|
4086
|
+
const present = humanTakeoverTags(settings).filter((tag) => tags.includes(tag));
|
|
4087
|
+
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.`);
|
|
4088
|
+
}
|
|
4089
|
+
function categoryGate(categories, tags, ignoreOptIn) {
|
|
4090
|
+
const matches = matchingCategories(categories, tags);
|
|
4091
|
+
if (matches.length === 0) return noMatchingCategory();
|
|
4092
|
+
const eligible = matches.filter((category2) => (ignoreOptIn || category2.followupFastResponseEnabled) && category2.agentId).sort((a, b) => a.order - b.order || a.id.localeCompare(b.id));
|
|
4093
|
+
if (eligible.length === 0) return noEligibleCategory(matches, ignoreOptIn);
|
|
4094
|
+
const category = eligible[0];
|
|
4095
|
+
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)}).`;
|
|
4096
|
+
return { ...passed("G7", detail), category };
|
|
4097
|
+
}
|
|
4098
|
+
function noEligibleCategory(matches, ignoreOptIn) {
|
|
4099
|
+
if (ignoreOptIn) {
|
|
4100
|
+
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.`);
|
|
4101
|
+
}
|
|
4102
|
+
if (matches.length > 1) {
|
|
4103
|
+
return stopped(
|
|
4104
|
+
"G7",
|
|
4105
|
+
`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.`
|
|
4106
|
+
);
|
|
4107
|
+
}
|
|
4108
|
+
const category = matches[0];
|
|
4109
|
+
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.`);
|
|
4110
|
+
}
|
|
4111
|
+
function tagList(categories) {
|
|
4112
|
+
return categories.map((category) => category.tagName).join(", ");
|
|
4113
|
+
}
|
|
4114
|
+
function anyCategoryMatch(categories, tags) {
|
|
4115
|
+
const matches = matchingCategories(categories, tags);
|
|
4116
|
+
return matches.length === 0 ? noMatchingCategory() : passed("G7", `Cat\xE9gorie \xAB ${matches[0].name} \xBB.`);
|
|
4117
|
+
}
|
|
4118
|
+
function noMatchingCategory() {
|
|
4119
|
+
return stopped("G7", "Aucune cat\xE9gorie ne correspond \xE0 un tag du ticket : la d\xE9cision de triage est illisible.");
|
|
4120
|
+
}
|
|
4121
|
+
function matchingCategories(categories, tags) {
|
|
4122
|
+
return categories.filter((category) => tags.includes(category.tagName));
|
|
4123
|
+
}
|
|
4124
|
+
function newCustomerMessage(conversation, anchor) {
|
|
4125
|
+
if (conversation.isClosed) return stopped("G8", "Le ticket est ferm\xE9.");
|
|
4126
|
+
const last = conversation.messages[conversation.messages.length - 1];
|
|
4127
|
+
if (!last) return stopped("G8", "La conversation extraite est vide.");
|
|
4128
|
+
if (!isCustomerTurnWithWords(last)) {
|
|
4129
|
+
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).");
|
|
4130
|
+
}
|
|
4131
|
+
if (anchor === null) return passed("G8", "Le dernier message est du client ; aucune r\xE9ponse ant\xE9rieure, donc aucune ancre \xE0 battre.");
|
|
4132
|
+
const lastAt = conversation.lastMessageAt;
|
|
4133
|
+
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.");
|
|
4134
|
+
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.`);
|
|
4135
|
+
}
|
|
4136
|
+
function payloadNewCustomerMessage(body, anchor) {
|
|
4137
|
+
if (body.isClosed === true) return stopped("G8", "La charge utile annonce un ticket ferm\xE9.");
|
|
4138
|
+
if (body.lastMessageFromAgent === true) return stopped("G8", "La charge utile annonce un dernier message d\u2019agent.");
|
|
4139
|
+
if (body.lastMessagePublic === false) return stopped("G8", "La charge utile annonce une note interne en dernier message.");
|
|
4140
|
+
if (anchor !== null && body.lastMessageAt !== null && body.lastMessageAt.getTime() <= anchor.getTime()) {
|
|
4141
|
+
return stopped("G8", `La charge utile annonce un dernier message (${body.lastMessageAt.toISOString()}) ant\xE9rieur ou \xE9gal \xE0 la derni\xE8re r\xE9ponse : relivraison.`);
|
|
4142
|
+
}
|
|
4143
|
+
if (body.isClosed === null && body.lastMessageFromAgent === null && body.lastMessagePublic === null && body.lastMessageAt === null) {
|
|
4144
|
+
return muted("G8", "Aucun champ exploitable dans la charge utile \u2014 la lecture fra\xEEche tranchera.");
|
|
4145
|
+
}
|
|
4146
|
+
return passed("G8", "Rien dans la charge utile ne permet d\u2019\xE9carter le ticket.");
|
|
4147
|
+
}
|
|
4148
|
+
function passed(gate, detail) {
|
|
4149
|
+
return { gate, label: LABELS[gate], status: "passed", detail };
|
|
4150
|
+
}
|
|
4151
|
+
function stopped(gate, detail) {
|
|
4152
|
+
return { gate, label: LABELS[gate], status: "stopped", detail };
|
|
4153
|
+
}
|
|
4154
|
+
function muted(gate, detail) {
|
|
4155
|
+
return { gate, label: LABELS[gate], status: "muted", detail };
|
|
4156
|
+
}
|
|
4157
|
+
function newTrace(gates) {
|
|
4158
|
+
const results = [];
|
|
4159
|
+
let stop2 = null;
|
|
4160
|
+
return {
|
|
4161
|
+
category: null,
|
|
4162
|
+
/** Records `result` unless the run already stopped; returns the category it resolved, if any. */
|
|
4163
|
+
record(result) {
|
|
4164
|
+
if (stop2) return null;
|
|
4165
|
+
results.push({ gate: result.gate, label: result.label, status: result.status, detail: result.detail });
|
|
4166
|
+
if (result.status === "stopped") stop2 = result;
|
|
4167
|
+
return result.category ?? null;
|
|
4168
|
+
},
|
|
4169
|
+
done() {
|
|
4170
|
+
const evaluated = new Set(results.map((result) => result.gate));
|
|
4171
|
+
for (const gate of gates) {
|
|
4172
|
+
if (!evaluated.has(gate)) {
|
|
4173
|
+
results.push({ gate, label: LABELS[gate], status: "skipped", detail: "Non \xE9valu\xE9 : un gate pr\xE9c\xE9dent a arr\xEAt\xE9 le traitement." });
|
|
4174
|
+
}
|
|
4175
|
+
}
|
|
4176
|
+
return { results, stop: stop2, category: stop2 ? null : this.category };
|
|
4177
|
+
}
|
|
4178
|
+
};
|
|
4179
|
+
}
|
|
4180
|
+
|
|
4181
|
+
// src/functions/webhook-body.ts
|
|
4182
|
+
var EMPTY_BODY = {
|
|
4183
|
+
ticketId: null,
|
|
4184
|
+
channel: null,
|
|
4185
|
+
lastMessageAt: null,
|
|
4186
|
+
isClosed: null,
|
|
4187
|
+
tags: null,
|
|
4188
|
+
lastMessageFromAgent: null,
|
|
4189
|
+
lastMessagePublic: null
|
|
4190
|
+
};
|
|
4191
|
+
var NUMERIC = /^\d+$/;
|
|
4192
|
+
var TRUE_TOKENS = /* @__PURE__ */ new Set(["true", "1", "yes", "on"]);
|
|
4193
|
+
var FALSE_TOKENS = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
|
|
4194
|
+
function parseFollowupWebhookBody(raw) {
|
|
4195
|
+
const body = toRecord(raw);
|
|
4196
|
+
if (!body) return { ...EMPTY_BODY };
|
|
4197
|
+
return {
|
|
4198
|
+
ticketId: parseTicketId(body.ticket_id),
|
|
4199
|
+
channel: parseText(body.channel),
|
|
4200
|
+
lastMessageAt: parseDate(body.last_message_datetime),
|
|
4201
|
+
isClosed: parseClosed(body.status),
|
|
4202
|
+
tags: parseTags(body.tags),
|
|
4203
|
+
lastMessageFromAgent: parseLaxBoolean(body.last_message_from_agent),
|
|
4204
|
+
lastMessagePublic: parseLaxBoolean(body.last_message_public)
|
|
4205
|
+
};
|
|
4206
|
+
}
|
|
4207
|
+
function toRecord(raw) {
|
|
4208
|
+
if (isPlainObject(raw)) return raw;
|
|
4209
|
+
if (typeof raw !== "string" || raw.trim() === "") return null;
|
|
4210
|
+
const asJson = tryJson(raw);
|
|
4211
|
+
if (isPlainObject(asJson)) return asJson;
|
|
4212
|
+
return parseFormEncoded(raw);
|
|
4213
|
+
}
|
|
4214
|
+
function parseFormEncoded(raw) {
|
|
4215
|
+
if (!raw.includes("=")) return null;
|
|
4216
|
+
const params = new URLSearchParams(raw);
|
|
4217
|
+
const entries = [...params.entries()];
|
|
4218
|
+
return entries.length > 0 ? Object.fromEntries(entries) : null;
|
|
4219
|
+
}
|
|
4220
|
+
function tryJson(raw) {
|
|
4221
|
+
try {
|
|
4222
|
+
return JSON.parse(raw);
|
|
4223
|
+
} catch {
|
|
4224
|
+
return void 0;
|
|
4225
|
+
}
|
|
4226
|
+
}
|
|
4227
|
+
function isPlainObject(value) {
|
|
4228
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4229
|
+
}
|
|
4230
|
+
function parseTicketId(raw) {
|
|
4231
|
+
if (typeof raw === "number") return Number.isSafeInteger(raw) && raw >= 0 ? String(raw) : null;
|
|
4232
|
+
return typeof raw === "string" && NUMERIC.test(raw) ? raw : null;
|
|
4233
|
+
}
|
|
4234
|
+
function parseText(raw) {
|
|
4235
|
+
if (typeof raw !== "string") return null;
|
|
4236
|
+
const trimmed = raw.trim();
|
|
4237
|
+
return trimmed === "" ? null : trimmed;
|
|
4238
|
+
}
|
|
4239
|
+
function parseDate(raw) {
|
|
4240
|
+
if (typeof raw !== "string") return null;
|
|
4241
|
+
const at = new Date(raw.trim());
|
|
4242
|
+
return Number.isNaN(at.getTime()) ? null : at;
|
|
4243
|
+
}
|
|
4244
|
+
function parseClosed(raw) {
|
|
4245
|
+
const text = parseText(raw);
|
|
4246
|
+
if (text === null) return null;
|
|
4247
|
+
if (text.toLowerCase() === "closed") return true;
|
|
4248
|
+
return text.startsWith("{{") ? null : false;
|
|
4249
|
+
}
|
|
4250
|
+
function parseLaxBoolean(raw) {
|
|
4251
|
+
if (typeof raw === "boolean") return raw;
|
|
4252
|
+
if (typeof raw === "number") {
|
|
4253
|
+
if (raw === 1) return true;
|
|
4254
|
+
if (raw === 0) return false;
|
|
4255
|
+
return null;
|
|
4256
|
+
}
|
|
4257
|
+
const text = parseText(raw)?.toLowerCase();
|
|
4258
|
+
if (text === void 0 || text === null) return null;
|
|
4259
|
+
if (TRUE_TOKENS.has(text)) return true;
|
|
4260
|
+
if (FALSE_TOKENS.has(text)) return false;
|
|
4261
|
+
return null;
|
|
4262
|
+
}
|
|
4263
|
+
function parseTags(raw) {
|
|
4264
|
+
const list = Array.isArray(raw) ? raw : arrayFromJson(raw);
|
|
4265
|
+
if (list === null || list.length === 0) return null;
|
|
4266
|
+
const names = [];
|
|
4267
|
+
for (const entry of list) {
|
|
4268
|
+
const name = tagNameOf(entry);
|
|
4269
|
+
if (name === null) return null;
|
|
4270
|
+
names.push(name);
|
|
4271
|
+
}
|
|
4272
|
+
return names;
|
|
4273
|
+
}
|
|
4274
|
+
function arrayFromJson(raw) {
|
|
4275
|
+
if (typeof raw !== "string") return null;
|
|
4276
|
+
const parsed = tryJson(raw);
|
|
4277
|
+
return Array.isArray(parsed) ? parsed : null;
|
|
4278
|
+
}
|
|
4279
|
+
function tagNameOf(entry) {
|
|
4280
|
+
if (typeof entry === "string") return parseText(entry);
|
|
4281
|
+
if (isPlainObject(entry)) return parseText(entry.name);
|
|
4282
|
+
return null;
|
|
4283
|
+
}
|
|
4284
|
+
|
|
4285
|
+
// src/functions/gorgias-webhook.ts
|
|
4286
|
+
var FOLLOWUP_RUN_REQUESTED_EVENT = "followup.run.requested";
|
|
4287
|
+
var FOLLOWUP_RUN_KIND = "gorgias-webhook";
|
|
4288
|
+
function buildGorgiasWebhookFunctionDef(config) {
|
|
4289
|
+
return {
|
|
4290
|
+
universalIdentifier: identifierFor(config, "gorgias-webhook"),
|
|
4291
|
+
name: "gorgias-webhook",
|
|
4292
|
+
trigger: { type: "httpRoute", path: "/gorgias/webhook", method: "POST", auth: "apiKey" }
|
|
4293
|
+
};
|
|
4294
|
+
}
|
|
4295
|
+
function buildGorgiasFollowupRunFunctionDef(config) {
|
|
4296
|
+
return {
|
|
4297
|
+
universalIdentifier: identifierFor(config, "gorgias-followup-run"),
|
|
4298
|
+
name: "gorgias-followup-run",
|
|
4299
|
+
trigger: { type: "event", name: FOLLOWUP_RUN_REQUESTED_EVENT }
|
|
4300
|
+
};
|
|
4301
|
+
}
|
|
4302
|
+
function createGorgiasWebhookHandler(config) {
|
|
4303
|
+
return (ctx, payload) => executeFollowupRun(
|
|
4304
|
+
ctx,
|
|
4305
|
+
config,
|
|
4306
|
+
payload?.body,
|
|
4307
|
+
null
|
|
4308
|
+
);
|
|
4309
|
+
}
|
|
4310
|
+
function createGorgiasFollowupRunHandler(config) {
|
|
4311
|
+
return (ctx, payload) => {
|
|
4312
|
+
const event = payload ?? {};
|
|
4313
|
+
return executeFollowupRun(ctx, config, event.body, event.runId ?? null, {
|
|
4314
|
+
generateOnly: event.generateOnly === true
|
|
4315
|
+
});
|
|
4316
|
+
};
|
|
4317
|
+
}
|
|
4318
|
+
async function executeFollowupRun(ctx, config, rawBody, existingRunId, options = {}) {
|
|
4319
|
+
const run = { id: existingRunId };
|
|
4320
|
+
try {
|
|
4321
|
+
const result = await runFollowupPass(ctx, config, rawBody, run, options.generateOnly === true);
|
|
4322
|
+
if (run.id) await ctx.api.runs.succeed(run.id, { ...result });
|
|
4323
|
+
} catch (err) {
|
|
4324
|
+
if (run.id) await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });
|
|
4325
|
+
throw err;
|
|
4326
|
+
}
|
|
4327
|
+
}
|
|
4328
|
+
async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
|
|
4329
|
+
const body = parseFollowupWebhookBody(rawBody);
|
|
4330
|
+
const ticketIdGate = evaluateTicketIdGate(body.ticketId);
|
|
4331
|
+
if (!body.ticketId) return stop(ctx, null, ticketIdGate.gate, ticketIdGate.detail);
|
|
4332
|
+
const ticketId = body.ticketId;
|
|
4333
|
+
const settings = await ctx.api.settings.get();
|
|
4334
|
+
const issues = validateSettings(settings);
|
|
4335
|
+
if (issues.length > 0) {
|
|
4336
|
+
return stop(ctx, ticketId, "settings", `r\xE9glages invalides : ${issues.map((issue) => issue.message).join(" ")}`);
|
|
4337
|
+
}
|
|
4338
|
+
const scope = evaluateScopeGate(settings);
|
|
4339
|
+
if (scope.status === "stopped") return stopAt(ctx, ticketId, scope);
|
|
4340
|
+
const { anchor, hasOpenResponse } = await readFollowupAnchor(ctx, ticketId);
|
|
4341
|
+
const categories = await listCategories(ctx.api);
|
|
4342
|
+
const preGates = evaluatePayloadGates({ settings, body, categories, anchor });
|
|
4343
|
+
if (preGates.stop) return stopAt(ctx, ticketId, preGates.stop, "pr\xE9-gate");
|
|
4344
|
+
const ref = { id: ticketId, channel: "gorgias" };
|
|
4345
|
+
const ticket = await ctx.api.integrations.run("gorgias", "getTicketWithContext", { ticketId });
|
|
4346
|
+
const raw = ticket?.ticket ?? {};
|
|
4347
|
+
const conversation = toConversation(ref, raw, ticket?.context ?? { messages: [], customerContext: null });
|
|
4348
|
+
const gates = evaluateTicketGates({
|
|
4349
|
+
settings,
|
|
4350
|
+
tags: ticketTagNames(raw),
|
|
4351
|
+
categories,
|
|
4352
|
+
conversation,
|
|
4353
|
+
anchor,
|
|
4354
|
+
ignoreCategoryOptIn: generateOnly
|
|
4355
|
+
});
|
|
4356
|
+
if (gates.stop || !gates.category) {
|
|
4357
|
+
return stopAt(ctx, ticketId, gates.stop ?? unresolvedCategory());
|
|
4358
|
+
}
|
|
4359
|
+
const category = gates.category;
|
|
4360
|
+
if (hasOpenResponse) return stop(ctx, ticketId, "G9", "une r\xE9ponse est d\xE9j\xE0 ouverte sur ce ticket");
|
|
4361
|
+
run.id ??= (await ctx.api.runs.start({
|
|
4362
|
+
kind: FOLLOWUP_RUN_KIND,
|
|
4363
|
+
message: `Message suivant \u2014 ticket ${ticketId}`,
|
|
4364
|
+
metadata: { ticketId, categoryTag: category.tagName, channel: body.channel, generateOnly }
|
|
4365
|
+
})).id;
|
|
4366
|
+
const created = await openFollowupResponse(ctx, { ticketId, category, conversation, settings, runId: run.id });
|
|
4367
|
+
if (!created) return stop(ctx, ticketId, "G9", "une autre ex\xE9cution a ouvert la r\xE9ponse en premier");
|
|
4368
|
+
await respondToPendingResponse(ctx, config, created.id, { testRun: generateOnly });
|
|
4369
|
+
return {
|
|
4370
|
+
ticketId,
|
|
4371
|
+
stoppedAt: null,
|
|
4372
|
+
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)`
|
|
4373
|
+
};
|
|
4374
|
+
}
|
|
4375
|
+
async function readFollowupAnchor(ctx, ticketId) {
|
|
4376
|
+
const page = await ctx.api.list("generated-response", { filter: { ticketId }, limit: ANCHOR_LOOKUP_LIMIT });
|
|
4377
|
+
let anchor = null;
|
|
4378
|
+
let hasOpenResponse = false;
|
|
4379
|
+
for (const item of page.items) {
|
|
4380
|
+
const data = item.data;
|
|
4381
|
+
if (data.openTicketKey === ticketId) hasOpenResponse = true;
|
|
4382
|
+
for (const raw of [data.generatedLastMessageAt, data.sentAt]) {
|
|
4383
|
+
const at = toDate2(raw);
|
|
4384
|
+
if (at && (!anchor || at > anchor)) anchor = at;
|
|
4385
|
+
}
|
|
4386
|
+
}
|
|
4387
|
+
return { anchor, hasOpenResponse };
|
|
4388
|
+
}
|
|
4389
|
+
var ANCHOR_LOOKUP_LIMIT = 100;
|
|
4390
|
+
function toDate2(raw) {
|
|
4391
|
+
if (raw instanceof Date) return Number.isNaN(raw.getTime()) ? null : raw;
|
|
4392
|
+
if (typeof raw !== "string") return null;
|
|
4393
|
+
const at = new Date(raw);
|
|
4394
|
+
return Number.isNaN(at.getTime()) ? null : at;
|
|
4395
|
+
}
|
|
4396
|
+
function ticketTagNames(raw) {
|
|
4397
|
+
const tags = raw.tags;
|
|
4398
|
+
if (!Array.isArray(tags)) return [];
|
|
4399
|
+
const names = [];
|
|
4400
|
+
for (const entry of tags) {
|
|
4401
|
+
if (typeof entry === "string" && entry !== "") {
|
|
4402
|
+
names.push(entry);
|
|
4403
|
+
continue;
|
|
4404
|
+
}
|
|
4405
|
+
if (typeof entry === "object" && entry !== null) {
|
|
4406
|
+
const name = entry.name;
|
|
4407
|
+
if (typeof name === "string" && name !== "") names.push(name);
|
|
4408
|
+
}
|
|
4409
|
+
}
|
|
4410
|
+
return names;
|
|
4411
|
+
}
|
|
4412
|
+
async function openFollowupResponse(ctx, input) {
|
|
4413
|
+
const { ticketId, category, conversation, settings, runId } = input;
|
|
4414
|
+
const decision = await ctx.api.create("triage-decision", {
|
|
4415
|
+
ticketId,
|
|
4416
|
+
// Not resolved: `getTicketUrlBase` is a SECOND Gorgias call and this
|
|
4417
|
+
// function runs once per message of the whole account. The field is
|
|
4418
|
+
// documented nullable for exactly this kind of row.
|
|
4419
|
+
ticketUrl: null,
|
|
4420
|
+
decidedAt: /* @__PURE__ */ new Date(),
|
|
4421
|
+
categoryId: category.id,
|
|
4422
|
+
tag: category.tagName,
|
|
4423
|
+
// §7.2 — NULL, and it is the honest value: no classifier ran on this pass
|
|
4424
|
+
// (D3 — the category is inherited from the tag the first pass applied), so
|
|
4425
|
+
// there is no confidence to state. The column was widened to allow it
|
|
4426
|
+
// (`records/triage-decision.ts`); a reader that needs a value still derives
|
|
4427
|
+
// `'low'` (`process-response.ts`'s `classificationFromDecision`).
|
|
4428
|
+
//
|
|
4429
|
+
// That derived `'low'` no longer holds the reply back: a follow-up pass is
|
|
4430
|
+
// governed by the evaluation of its own draft, not by a triage confidence
|
|
4431
|
+
// that does not exist — see `applyFollowupSendPolicy` in
|
|
4432
|
+
// `process-response.ts` for the decision and what it replaces.
|
|
4433
|
+
confidence: null,
|
|
4434
|
+
reasoning: `Message suivant \u2014 cat\xE9gorie r\xE9solue par le tag ${category.tagName}`,
|
|
4435
|
+
// The customer has just written, so the thread is by definition not over;
|
|
4436
|
+
// and the escalation decision belongs to the first pass, which this one
|
|
4437
|
+
// deliberately does not replay (D5).
|
|
4438
|
+
conversationOver: false,
|
|
4439
|
+
escalated: false,
|
|
4440
|
+
status: "ok",
|
|
4441
|
+
runId,
|
|
4442
|
+
subjectRenamed: false,
|
|
4443
|
+
origin: "followup"
|
|
4444
|
+
});
|
|
4445
|
+
const agent = await resolveDraftAgent(ctx.api, category.agentId);
|
|
4446
|
+
const generatedAt = /* @__PURE__ */ new Date();
|
|
4447
|
+
try {
|
|
4448
|
+
return await ctx.api.create("generated-response", {
|
|
4449
|
+
ticketId,
|
|
4450
|
+
openTicketKey: openTicketKeyFor("pending", ticketId),
|
|
4451
|
+
status: "pending",
|
|
4452
|
+
triageDecisionId: decision.id,
|
|
4453
|
+
categoryId: category.id,
|
|
4454
|
+
agentId: agent?.id ?? null,
|
|
4455
|
+
channel: conversation.sourceChannel === "whatsapp" ? "whatsapp" : "email",
|
|
4456
|
+
generatedAt,
|
|
4457
|
+
expiresAt: new Date(generatedAt.getTime() + settings.responseTtlMinutes * 6e4),
|
|
4458
|
+
sources: [],
|
|
4459
|
+
tracedInput: [],
|
|
4460
|
+
guardrailHits: [],
|
|
4461
|
+
servedTo: [],
|
|
4462
|
+
servedCount: 0,
|
|
4463
|
+
followupRequired: false,
|
|
4464
|
+
origin: "followup"
|
|
4465
|
+
});
|
|
4466
|
+
} catch (err) {
|
|
4467
|
+
if (err instanceof AppApiError && err.status === 409) return null;
|
|
4468
|
+
throw err;
|
|
4469
|
+
}
|
|
4470
|
+
}
|
|
4471
|
+
function unresolvedCategory() {
|
|
4472
|
+
return {
|
|
4473
|
+
gate: "G7",
|
|
4474
|
+
label: "Cat\xE9gorie r\xE9solue et opt\xE9e",
|
|
4475
|
+
status: "stopped",
|
|
4476
|
+
detail: "Aucune cat\xE9gorie r\xE9solue."
|
|
4477
|
+
};
|
|
4478
|
+
}
|
|
4479
|
+
function stopAt(ctx, ticketId, result, kind = "gate") {
|
|
4480
|
+
return stop(ctx, ticketId, `${result.gate}${kind === "gate" ? "" : ` (${kind})`}`, result.detail);
|
|
4481
|
+
}
|
|
4482
|
+
function stop(ctx, ticketId, gate, reason) {
|
|
4483
|
+
ctx.logger.info(`gorgias-webhook: stop at ${gate} for ticket ${ticketId ?? "?"} \u2014 ${reason}`);
|
|
4484
|
+
return { ticketId, stoppedAt: gate, reason };
|
|
4485
|
+
}
|
|
4486
|
+
function buildTestGorgiasWebhookFunctionDef(config) {
|
|
4487
|
+
return {
|
|
4488
|
+
universalIdentifier: identifierFor(config, "test-gorgias-webhook"),
|
|
4489
|
+
name: "test-gorgias-webhook",
|
|
4490
|
+
trigger: { type: "uiInvoke", minRole: "ADMIN", timeoutMs: 2e4 },
|
|
4491
|
+
input: [
|
|
4492
|
+
{
|
|
4493
|
+
universalIdentifier: TEST_GORGIAS_WEBHOOK_INPUT_TICKET_ID_UID,
|
|
4494
|
+
name: "ticketId",
|
|
4495
|
+
type: FieldType.TEXT,
|
|
4496
|
+
label: "Ticket id",
|
|
4497
|
+
description: "Identifiant Gorgias du ticket \xE0 tester.",
|
|
4498
|
+
isNullable: true
|
|
4499
|
+
},
|
|
4500
|
+
{
|
|
4501
|
+
universalIdentifier: TEST_GORGIAS_WEBHOOK_INPUT_MODE_UID,
|
|
4502
|
+
name: "mode",
|
|
4503
|
+
type: FieldType.TEXT,
|
|
4504
|
+
label: "Mode",
|
|
4505
|
+
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.",
|
|
4506
|
+
isNullable: true
|
|
4507
|
+
}
|
|
4508
|
+
]
|
|
4509
|
+
};
|
|
4510
|
+
}
|
|
4511
|
+
function createTestGorgiasWebhookHandler(_config) {
|
|
4512
|
+
return (ctx, input) => testGorgiasWebhookHandler(ctx, input ?? {});
|
|
4513
|
+
}
|
|
4514
|
+
var NUMERIC2 = /^\d+$/;
|
|
4515
|
+
async function testGorgiasWebhookHandler(ctx, input) {
|
|
4516
|
+
const ticketId = typeof input.ticketId === "string" && NUMERIC2.test(input.ticketId.trim()) ? input.ticketId.trim() : null;
|
|
4517
|
+
const mode = input.mode === "run" ? "run" : input.mode === "generate" ? "generate" : "diagnostic";
|
|
4518
|
+
if (mode === "diagnostic") return diagnose(ctx, ticketId);
|
|
4519
|
+
if (!ticketId) throw new ctx.NonRetriableError("L'identifiant du ticket doit \xEAtre une suite de chiffres.");
|
|
4520
|
+
return triggerRun(ctx, ticketId, mode);
|
|
4521
|
+
}
|
|
4522
|
+
async function diagnose(ctx, ticketId) {
|
|
4523
|
+
const gates = [];
|
|
4524
|
+
const ticketIdGate = evaluateTicketIdGate(ticketId);
|
|
4525
|
+
gates.push(ticketIdGate);
|
|
4526
|
+
if (!ticketId) return finish(gates, "");
|
|
4527
|
+
const settings = await ctx.api.settings.get();
|
|
4528
|
+
const issues = validateSettings(settings);
|
|
4529
|
+
if (issues.length > 0) {
|
|
4530
|
+
throw new ctx.NonRetriableError(`R\xE9glages invalides : ${issues.map((issue) => issue.message).join(" ")}`);
|
|
4531
|
+
}
|
|
4532
|
+
const scope = evaluateScopeGate(settings);
|
|
4533
|
+
gates.push(scope);
|
|
4534
|
+
if (scope.status === "stopped") return finish(gates, ticketId);
|
|
4535
|
+
const { anchor } = await readFollowupAnchor(ctx, ticketId);
|
|
4536
|
+
const categories = await listCategories(ctx.api);
|
|
4537
|
+
const ref = { id: ticketId, channel: "gorgias" };
|
|
4538
|
+
const ticket = await ctx.api.integrations.run("gorgias", "getTicketWithContext", { ticketId });
|
|
4539
|
+
const raw = ticket?.ticket ?? {};
|
|
4540
|
+
const conversation = toConversation(ref, raw, ticket?.context ?? { messages: [], customerContext: null });
|
|
4541
|
+
const trace = evaluateTicketGates({ settings, tags: ticketTagNames(raw), categories, conversation, anchor });
|
|
4542
|
+
gates.push(...trace.results);
|
|
4543
|
+
return finish(gates, ticketId);
|
|
4544
|
+
}
|
|
4545
|
+
function finish(gates, ticketId) {
|
|
4546
|
+
const evaluated = new Set(gates.map((gate) => gate.gate));
|
|
4547
|
+
const missing = ALL_FOLLOWUP_GATES.filter((gate) => !evaluated.has(gate));
|
|
4548
|
+
const full = [...gates, ...skippedFollowupGates(missing)];
|
|
4549
|
+
return {
|
|
4550
|
+
mode: "diagnostic",
|
|
4551
|
+
ticketId,
|
|
4552
|
+
stoppedAt: full.find((gate) => gate.status === "stopped")?.gate ?? null,
|
|
4553
|
+
gates: full
|
|
4554
|
+
};
|
|
4555
|
+
}
|
|
4556
|
+
async function triggerRun(ctx, ticketId, mode) {
|
|
4557
|
+
const generateOnly = mode === "generate";
|
|
4558
|
+
const run = await ctx.api.runs.start({
|
|
4559
|
+
kind: FOLLOWUP_RUN_KIND,
|
|
4560
|
+
message: generateOnly ? `Test webhook sans envoi \u2014 ticket ${ticketId}` : `Test webhook \u2014 ticket ${ticketId}`,
|
|
4561
|
+
metadata: { ticketId, triggeredFrom: "test-gorgias-webhook", generateOnly }
|
|
4562
|
+
});
|
|
4563
|
+
try {
|
|
4564
|
+
await ctx.api.events.send(FOLLOWUP_RUN_REQUESTED_EVENT, {
|
|
4565
|
+
_key: run.id,
|
|
4566
|
+
runId: run.id,
|
|
4567
|
+
body: { ticket_id: ticketId },
|
|
4568
|
+
generateOnly
|
|
4569
|
+
});
|
|
4570
|
+
} catch (err) {
|
|
4571
|
+
await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });
|
|
4572
|
+
throw err;
|
|
4573
|
+
}
|
|
4574
|
+
return { mode, ticketId, runId: run.id };
|
|
4575
|
+
}
|
|
4576
|
+
|
|
3982
4577
|
// src/pages/manifest.ts
|
|
3983
4578
|
function pageIdentifierFor(config, key) {
|
|
3984
4579
|
const id = config.identifiers[key];
|
|
@@ -4004,10 +4599,11 @@ var SUPPORT_KIT_GORGIAS_SCOPES = [
|
|
|
4004
4599
|
"write_tags",
|
|
4005
4600
|
"write_tickets"
|
|
4006
4601
|
];
|
|
4602
|
+
var SUPPORT_KIT_SERVER_VARIABLES = [];
|
|
4007
4603
|
var SUPPORT_KIT_INTEGRATIONS = [
|
|
4008
4604
|
{ provider: "gorgias", scopes: [...SUPPORT_KIT_GORGIAS_SCOPES] }
|
|
4009
4605
|
];
|
|
4010
|
-
var SUPPORT_KIT_EMITS = [TRIAGE_RUN_REQUESTED_EVENT];
|
|
4606
|
+
var SUPPORT_KIT_EMITS = [TRIAGE_RUN_REQUESTED_EVENT, FOLLOWUP_RUN_REQUESTED_EVENT];
|
|
4011
4607
|
var FUNCTION_ASSEMBLY = [
|
|
4012
4608
|
{ key: "triage-tick", build: buildTriageTickFunctionDef, createHandler: createTriageTickHandler },
|
|
4013
4609
|
{ key: "sweep", build: buildSweepFunctionDef, createHandler: () => createSweepHandler() },
|
|
@@ -4102,6 +4698,22 @@ var FUNCTION_ASSEMBLY = [
|
|
|
4102
4698
|
key: "ext-response-comparison",
|
|
4103
4699
|
build: buildExtResponseComparisonFunctionDef,
|
|
4104
4700
|
createHandler: () => createExtResponseComparisonHandler()
|
|
4701
|
+
},
|
|
4702
|
+
// spec-gorgias-followup-webhook-v1 §5 — the push half.
|
|
4703
|
+
{
|
|
4704
|
+
key: "gorgias-webhook",
|
|
4705
|
+
build: buildGorgiasWebhookFunctionDef,
|
|
4706
|
+
createHandler: createGorgiasWebhookHandler
|
|
4707
|
+
},
|
|
4708
|
+
{
|
|
4709
|
+
key: "gorgias-followup-run",
|
|
4710
|
+
build: buildGorgiasFollowupRunFunctionDef,
|
|
4711
|
+
createHandler: createGorgiasFollowupRunHandler
|
|
4712
|
+
},
|
|
4713
|
+
{
|
|
4714
|
+
key: "test-gorgias-webhook",
|
|
4715
|
+
build: buildTestGorgiasWebhookFunctionDef,
|
|
4716
|
+
createHandler: createTestGorgiasWebhookHandler
|
|
4105
4717
|
}
|
|
4106
4718
|
];
|
|
4107
4719
|
function buildPromptsAllowlist() {
|
|
@@ -4214,6 +4826,7 @@ function buildSupportPipeline(config) {
|
|
|
4214
4826
|
navigation: buildNavigation(config),
|
|
4215
4827
|
settingsPage: buildSettingsPage(config),
|
|
4216
4828
|
integrations: SUPPORT_KIT_INTEGRATIONS,
|
|
4829
|
+
serverVariables: SUPPORT_KIT_SERVER_VARIABLES,
|
|
4217
4830
|
emits: SUPPORT_KIT_EMITS,
|
|
4218
4831
|
defaultRole: "NO_ACCESS",
|
|
4219
4832
|
handlers,
|