@apotech-os/support-kit 8.4.0 → 10.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -12
- package/dist/{chunk-D3QGGJAI.js → chunk-KEPXRZ7R.js} +879 -107
- package/dist/chunk-KEPXRZ7R.js.map +1 -0
- package/dist/index.cjs +1850 -204
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +260 -21
- package/dist/index.d.ts +260 -21
- package/dist/index.js +918 -93
- package/dist/index.js.map +1 -1
- package/dist/ui/index.cjs +466 -178
- package/dist/ui/index.cjs.map +1 -1
- package/dist/ui/index.js +340 -531
- package/dist/ui/index.js.map +1 -1
- package/package.json +13 -13
- package/dist/chunk-D3QGGJAI.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_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,
|
|
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, settingsWarnings, stopOptOut, toDecisionOrigin, 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, OUTCOMES, 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_FIELD_LANGFUSE_TRACE_ID_UID, TRIAGE_DECISION_FIELD_LANGFUSE_OBSERVATION_IDS_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_INELIGIBLE_REASON_UID, GENERATED_RESPONSE_FIELD_SOURCE_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, GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_RECONSTRUCTED_AT_UID, 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_RUN_ID_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, listAgents, PROMPT_SLOTS, isGeneratedResponseStatus, isInvalidatableStatus, DEFAULT_LLM_PROVIDER, AGENT_PAGE_SIZE, CATEGORY_PAGE_SIZE, toCategoryGroup, toCategory, compareByGroupThenCategory, toGeneratedResponse, NODE_NAMES, toConversation, ToolInputError, DEFAULT_CHANNEL_PROMPT_EMAIL, DEFAULT_CHANNEL_PROMPT_WHATSAPP, reclaimStalledSend, applySignature, snapshotConversation, isEvaluationVerdict, requiresFollowup, computeWordDiff, findCategoryByTag, isTerminalStatus, canTransition, toDecisionOrigin, TRIAGE_LABEL, ESCALATION_LABEL, isConversationOver, isFallbackClassification, hasNoDraftNode, isCustomerTurnWithWords, dayRangeOf, assertOptionalBoolean, readCategoryNames, periodBoundsOf, WEEKLY_BUCKET_FROM_DAYS, CATEGORY_TOP_N, previousRangeOf, DEFAULT_STATS_TIMEZONE, OUTCOME_GROUP_BY, OUTCOME_METRICS, TRIAGE_HANDOFF_GROUP_BY, CATEGORY_TRIAGE_GROUP_BY, CATEGORY_OUTCOME_GROUP_BY, toTriageDecision, latestResponsesByTicket, newestPerTicket, NEWEST_DECISION_FIRST, isUnautomatedTriage, listTicketResponses, buildTimelineSteps, toDeliveryPolicy, toResponseComparison, foldOutcomes, foldDailyOutcomes, dashboardSignals, countFailed, fillMissingDays, foldCategoryOutcomes, foldHumanReasons, autonomyRate, sumCounts, isOutcome, promptRefFor, countOf } from './chunk-KEPXRZ7R.js';
|
|
2
|
+
export { AGENT_GUARDRAILS, AGENT_STATUSES, AGENT_TOOLS, ATTACHMENT_MARKER_ONLY, CANDIDATE_MIN_LENGTH, COLLISION_GUARDRAILS, DECISION_ORIGINS, DEFAULT_AUTO_SEND_CHANNELS, 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_CHANNELS, SUPPORT_KIT_SETTINGS_FIELDS, UNCERTAINTY_MARKERS, WHATSAPP_MODES, WHATSAPP_NOTE_CHEVRON, accountChannelAddress, agentRecord, answerableChannels, assertTransition, canTransition, channelPreGates, customerChannelAddress, firstCustomerMessage, guardrailBucket, hasCustomerAttachment, initialState, isAutoSendEligible, isAutomatedSenderEmail, isAutomatedSenderTicket, isCustomerTurnWithWords, isDecisionOrigin, isEvaluationVerdict, isGeneratedResponseStatus, isJudgemeConversation, isJudgemeTicket, isOutcome, isSendable, isSendableVerdict, isTerminalStatus, isTicketClosed, isWhatsappChevronNote, isWhatsappTicket, lastCustomerMessage, needsRevision, openTicketKeyFor, publicationMode, rawTicketFactsAt, reclaimStalledSend, reconstructGuardrailHits, requiresFollowup, resolvePromptName, runGuardrails, runTicket, settingsToProfile, settingsWarnings, stopOptOut, toDecisionOrigin, validateSettings, verifyReply, whatsappModeFromLegacyBoolean } from './chunk-KEPXRZ7R.js';
|
|
3
3
|
import { FieldType, APPROVAL_DECIDED_EVENT, AppApiError } from '@apotech-os/app-kit';
|
|
4
4
|
import { createHash } from 'node:crypto';
|
|
5
5
|
|
|
@@ -481,6 +481,22 @@ function buildTriageDecisionRecord(slug) {
|
|
|
481
481
|
description: ORIGIN_DESCRIPTION,
|
|
482
482
|
isNullable: false,
|
|
483
483
|
defaultValue: DEFAULT_DECISION_ORIGIN
|
|
484
|
+
},
|
|
485
|
+
{
|
|
486
|
+
universalIdentifier: TRIAGE_DECISION_FIELD_LANGFUSE_TRACE_ID_UID,
|
|
487
|
+
name: "langfuseTraceId",
|
|
488
|
+
type: FieldType.TEXT,
|
|
489
|
+
label: "Langfuse trace id",
|
|
490
|
+
description: "The Langfuse trace of the triage call. Null on a decision written before this field existed, on a follow-up pass (no classifier runs), or when the gateway traced nothing.",
|
|
491
|
+
isNullable: true
|
|
492
|
+
},
|
|
493
|
+
{
|
|
494
|
+
universalIdentifier: TRIAGE_DECISION_FIELD_LANGFUSE_OBSERVATION_IDS_UID,
|
|
495
|
+
name: "langfuseObservationIds",
|
|
496
|
+
type: FieldType.JSON,
|
|
497
|
+
label: "Langfuse observation ids",
|
|
498
|
+
description: "string[] \u2014 the triage observation, then the escalation one when that step ran. Not positional: the triage id may be absent. Null when nothing was traced.",
|
|
499
|
+
isNullable: true
|
|
484
500
|
}
|
|
485
501
|
],
|
|
486
502
|
indexes: [
|
|
@@ -563,9 +579,26 @@ function buildGeneratedResponseRecord(slug) {
|
|
|
563
579
|
name: "channel",
|
|
564
580
|
type: FieldType.SELECT,
|
|
565
581
|
label: "Channel",
|
|
582
|
+
description: "Publication MODE, not the channel: 'whatsapp' for a note, 'email' for everything else. See sourceChannel.",
|
|
566
583
|
isNullable: false,
|
|
567
584
|
options: ["email", "whatsapp"]
|
|
568
585
|
},
|
|
586
|
+
{
|
|
587
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_INELIGIBLE_REASON_UID,
|
|
588
|
+
name: "ineligibleReason",
|
|
589
|
+
type: FieldType.TEXT,
|
|
590
|
+
label: "Ineligible reason",
|
|
591
|
+
description: "Why auto-send was inapplicable, when the run knew a fact the settings cannot express. Today: 'no_publication_path'.",
|
|
592
|
+
isNullable: true
|
|
593
|
+
},
|
|
594
|
+
{
|
|
595
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_SOURCE_CHANNEL_UID,
|
|
596
|
+
name: "sourceChannel",
|
|
597
|
+
type: FieldType.TEXT,
|
|
598
|
+
label: "Source channel",
|
|
599
|
+
description: "The channel Gorgias reported (see SUPPORT_CHANNELS). Null on rows written before the field existed.",
|
|
600
|
+
isNullable: true
|
|
601
|
+
},
|
|
569
602
|
{
|
|
570
603
|
universalIdentifier: GENERATED_RESPONSE_FIELD_RESPONSE_TEXT_UID,
|
|
571
604
|
name: "responseText",
|
|
@@ -608,6 +641,14 @@ function buildGeneratedResponseRecord(slug) {
|
|
|
608
641
|
isNullable: false,
|
|
609
642
|
defaultValue: []
|
|
610
643
|
},
|
|
644
|
+
{
|
|
645
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_RECONSTRUCTED_AT_UID,
|
|
646
|
+
name: "guardrailHitsReconstructedAt",
|
|
647
|
+
type: FieldType.DATE_TIME,
|
|
648
|
+
label: "Guardrail hits reconstructed at",
|
|
649
|
+
description: "Set only by the backfill that rebuilt a pre-28/09/2026 hold\u2019s reason from Gorgias. Null \u2014 the normal case \u2014 means the run itself recorded the hits.",
|
|
650
|
+
isNullable: true
|
|
651
|
+
},
|
|
611
652
|
{
|
|
612
653
|
universalIdentifier: GENERATED_RESPONSE_FIELD_OUTCOME_UID,
|
|
613
654
|
name: "outcome",
|
|
@@ -1157,61 +1198,8 @@ function identifierFor(config, key) {
|
|
|
1157
1198
|
}
|
|
1158
1199
|
return id;
|
|
1159
1200
|
}
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
function isInternalNoteChannel(message) {
|
|
1163
|
-
return message.channel === "internal-note" || message.source?.type === "internal-note";
|
|
1164
|
-
}
|
|
1165
|
-
function countableMessages(messages, isWhatsapp) {
|
|
1166
|
-
return messages.filter((m) => {
|
|
1167
|
-
if (isInternalNoteChannel(m)) return isWhatsappChevronNote(m, isWhatsapp);
|
|
1168
|
-
const hasText = !!(m.body_text?.trim() || m.body_html?.trim() || m.stripped_text?.trim() || m.stripped_html?.trim());
|
|
1169
|
-
const hasAttachment = (m.attachments?.length ?? 0) > 0;
|
|
1170
|
-
return hasText || hasAttachment;
|
|
1171
|
-
});
|
|
1172
|
-
}
|
|
1173
|
-
function snapshotConversation(raw) {
|
|
1174
|
-
const isWhatsapp = isWhatsappTicket(raw);
|
|
1175
|
-
const messages = countableMessages(raw.messages ?? [], isWhatsapp);
|
|
1176
|
-
let lastAt = null;
|
|
1177
|
-
for (const m of messages) {
|
|
1178
|
-
if (!m.created_datetime) continue;
|
|
1179
|
-
const at = new Date(m.created_datetime);
|
|
1180
|
-
if (!lastAt || at > lastAt) lastAt = at;
|
|
1181
|
-
}
|
|
1182
|
-
return { count: messages.length, lastAt };
|
|
1183
|
-
}
|
|
1184
|
-
function lastAgentReplyAtOf(raw) {
|
|
1185
|
-
const isWhatsapp = isWhatsappTicket(raw);
|
|
1186
|
-
let latest = null;
|
|
1187
|
-
for (const m of raw.messages ?? []) {
|
|
1188
|
-
if (m.from_agent !== true) continue;
|
|
1189
|
-
if (isInternalNoteChannel(m) && !isWhatsappChevronNote(m, isWhatsapp)) continue;
|
|
1190
|
-
if (!m.created_datetime) continue;
|
|
1191
|
-
const at = new Date(m.created_datetime);
|
|
1192
|
-
if (!latest || at > latest) latest = at;
|
|
1193
|
-
}
|
|
1194
|
-
return latest;
|
|
1195
|
-
}
|
|
1196
|
-
function toConversation(ref, raw, context) {
|
|
1197
|
-
const snapshot = snapshotConversation(raw);
|
|
1198
|
-
const messages = context.messages.filter((m) => m.role === "user" || m.role === "assistant").map((m) => ({ role: m.role, content: m.content }));
|
|
1199
|
-
return {
|
|
1200
|
-
ref,
|
|
1201
|
-
subject: raw.subject ?? null,
|
|
1202
|
-
messages,
|
|
1203
|
-
customer: {
|
|
1204
|
-
name: context.customerName ?? null,
|
|
1205
|
-
email: context.customerEmail ?? null,
|
|
1206
|
-
orderContext: context.customerContext ?? null
|
|
1207
|
-
},
|
|
1208
|
-
isClosed: isTicketClosed(raw),
|
|
1209
|
-
lastMessageAt: snapshot.lastAt,
|
|
1210
|
-
messageCount: snapshot.count,
|
|
1211
|
-
lastAgentReplyAt: lastAgentReplyAtOf(raw),
|
|
1212
|
-
hasCustomerAttachment: hasCustomerAttachment(raw),
|
|
1213
|
-
sourceChannel: isWhatsappTicket(raw) ? "whatsapp" : raw.channel ?? null
|
|
1214
|
-
};
|
|
1201
|
+
function mcpToolIdentifierFor(config, key) {
|
|
1202
|
+
return config.identifiers[key] ?? deriveUid(`${config.slug}:function:${key}`);
|
|
1215
1203
|
}
|
|
1216
1204
|
|
|
1217
1205
|
// src/adapters/gorgias-tags.ts
|
|
@@ -1273,6 +1261,18 @@ function createGorgiasReplyPort(api) {
|
|
|
1273
1261
|
});
|
|
1274
1262
|
return { messageId: result2.messageId };
|
|
1275
1263
|
}
|
|
1264
|
+
if (reply.mode === "channel") {
|
|
1265
|
+
const result2 = await api.integrations.run("gorgias", "replyOnChannel", {
|
|
1266
|
+
ticketId: ref.id,
|
|
1267
|
+
channel: reply.channel,
|
|
1268
|
+
bodyHtml: reply.bodyHtml,
|
|
1269
|
+
bodyText: reply.bodyText,
|
|
1270
|
+
toAddress: reply.toAddress,
|
|
1271
|
+
fromAddress: reply.fromAddress,
|
|
1272
|
+
...reply.receiverName !== null ? { receiverName: reply.receiverName } : {}
|
|
1273
|
+
});
|
|
1274
|
+
return { messageId: result2.messageId };
|
|
1275
|
+
}
|
|
1276
1276
|
const result = await api.integrations.run("gorgias", "postWhatsappNote", {
|
|
1277
1277
|
ticketId: ref.id,
|
|
1278
1278
|
text: reply.bodyText
|
|
@@ -1336,6 +1336,7 @@ function createPlatformLlmPort(api, trace) {
|
|
|
1336
1336
|
// its own to carry the new field; it already carries whatever shape
|
|
1337
1337
|
// `CompletionRequest.promptRef` has.
|
|
1338
1338
|
...req.promptRef ? { promptRef: req.promptRef } : {},
|
|
1339
|
+
...req.promptVariables ? { promptVariables: req.promptVariables } : {},
|
|
1339
1340
|
...runTrace ? { trace: runTrace } : {}
|
|
1340
1341
|
});
|
|
1341
1342
|
return {
|
|
@@ -1479,15 +1480,23 @@ function createRecordingLlmPort(llm) {
|
|
|
1479
1480
|
};
|
|
1480
1481
|
}
|
|
1481
1482
|
var DEFAULT_MAX_TOOL_CALLS = 5;
|
|
1482
|
-
async function getOptional(
|
|
1483
|
+
async function getOptional(api, objectKey, id) {
|
|
1483
1484
|
if (!id) return null;
|
|
1484
1485
|
try {
|
|
1485
|
-
return await
|
|
1486
|
+
return await api.get(objectKey, id);
|
|
1486
1487
|
} catch (err) {
|
|
1487
1488
|
if (err instanceof AppApiError && err.status === 404) return null;
|
|
1488
1489
|
throw err;
|
|
1489
1490
|
}
|
|
1490
1491
|
}
|
|
1492
|
+
async function getSettingsOrNull(api) {
|
|
1493
|
+
try {
|
|
1494
|
+
return await api.settings.get();
|
|
1495
|
+
} catch (err) {
|
|
1496
|
+
if (err instanceof AppApiError) return null;
|
|
1497
|
+
throw err;
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1491
1500
|
function buildTicketPorts(ctx, trace) {
|
|
1492
1501
|
return {
|
|
1493
1502
|
conversation: createGorgiasConversationPort(ctx.api),
|
|
@@ -1668,7 +1677,7 @@ async function finalizeNonSent(ctx, id, ticketId, toStatus, extra) {
|
|
|
1668
1677
|
}
|
|
1669
1678
|
}
|
|
1670
1679
|
async function respondToPendingResponse(ctx, config, recordId, options = {}) {
|
|
1671
|
-
const record = await getOptional(ctx, "generated-response", recordId);
|
|
1680
|
+
const record = await getOptional(ctx.api, "generated-response", recordId);
|
|
1672
1681
|
if (!record) {
|
|
1673
1682
|
ctx.logger.info(`respond: generated-response ${recordId} no longer exists, skipping`);
|
|
1674
1683
|
return null;
|
|
@@ -1685,7 +1694,7 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
|
|
|
1685
1694
|
}
|
|
1686
1695
|
const ticketId = data.ticketId;
|
|
1687
1696
|
const ref = { id: ticketId, channel: "gorgias" };
|
|
1688
|
-
const decision = await getOptional(ctx, "triage-decision", data.triageDecisionId ?? null);
|
|
1697
|
+
const decision = await getOptional(ctx.api, "triage-decision", data.triageDecisionId ?? null);
|
|
1689
1698
|
if (!decision) {
|
|
1690
1699
|
ctx.logger.error(`respond: generated-response ${recordId} has no resolvable triage-decision, marking failed`);
|
|
1691
1700
|
await finalizeNonSent(ctx, recordId, ticketId, "failed", { error: "triage-decision not found" });
|
|
@@ -1693,10 +1702,10 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
|
|
|
1693
1702
|
}
|
|
1694
1703
|
const classification = classificationFromDecision(decision);
|
|
1695
1704
|
const escalated = decision.data.escalated === true;
|
|
1696
|
-
const categoryRecord = await getOptional(ctx, "category", data.categoryId ?? null);
|
|
1705
|
+
const categoryRecord = await getOptional(ctx.api, "category", data.categoryId ?? null);
|
|
1697
1706
|
const category = categoryRecord ? toCategory(categoryRecord) : null;
|
|
1698
1707
|
const origin = toDecisionOrigin(data.origin);
|
|
1699
|
-
const agentRecord2 = data.agentId ? await getOptional(ctx, "agent", data.agentId) : null;
|
|
1708
|
+
const agentRecord2 = data.agentId ? await getOptional(ctx.api, "agent", data.agentId) : null;
|
|
1700
1709
|
const agent = agentRecord2 ? toAgent(agentRecord2) : await resolveDraftAgent(ctx.api, null);
|
|
1701
1710
|
const profile = applyFollowupSendPolicy(
|
|
1702
1711
|
settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes)),
|
|
@@ -1760,6 +1769,14 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
|
|
|
1760
1769
|
// `outcome: 'sent'` on a `ready` row is exactly what "would have been
|
|
1761
1770
|
// sent, wasn't" looks like, and the timeline reads it that way.
|
|
1762
1771
|
outcome: result.outcome,
|
|
1772
|
+
// WHICH guardrail held the reply, not just that one did. Without this the
|
|
1773
|
+
// record keeps the `[]` its creation wrote and the timeline can only say
|
|
1774
|
+
// "un garde-fou a bloqué l'envoi" — the reason has to be reconstructed
|
|
1775
|
+
// from Gorgias by hand, which is exactly what it cost before this line.
|
|
1776
|
+
guardrailHits: result.guardrailHits,
|
|
1777
|
+
// The one "not sent" reason the timeline cannot re-derive from today's
|
|
1778
|
+
// settings: whether the contact had an address six weeks ago.
|
|
1779
|
+
ineligibleReason: result.ineligibleReason,
|
|
1763
1780
|
responseText: result.draft?.text ?? null,
|
|
1764
1781
|
sources: result.draft?.sources ?? [],
|
|
1765
1782
|
// The rendered system prompt and the customer's own turns, which nothing
|
|
@@ -1854,6 +1871,39 @@ function ticketUrlFor(base, ticketId) {
|
|
|
1854
1871
|
return base ? `${base}/${encodeURIComponent(ticketId)}` : null;
|
|
1855
1872
|
}
|
|
1856
1873
|
|
|
1874
|
+
// src/functions/ticket-trace.ts
|
|
1875
|
+
function buildTicketTrace({ slug, ticketId, ticketUrl }) {
|
|
1876
|
+
return {
|
|
1877
|
+
sessionId: ticketId,
|
|
1878
|
+
tags: [`app:${slug}`],
|
|
1879
|
+
metadata: {
|
|
1880
|
+
ticket_id: ticketId,
|
|
1881
|
+
...ticketUrl ? { conversation_url: ticketUrl } : {},
|
|
1882
|
+
origin: "triage"
|
|
1883
|
+
}
|
|
1884
|
+
};
|
|
1885
|
+
}
|
|
1886
|
+
function recordTriageTraces(llm) {
|
|
1887
|
+
const results = /* @__PURE__ */ new Map();
|
|
1888
|
+
return {
|
|
1889
|
+
llm: {
|
|
1890
|
+
async complete(req) {
|
|
1891
|
+
const result = await llm.complete(req);
|
|
1892
|
+
results.set(req.label, result);
|
|
1893
|
+
return result;
|
|
1894
|
+
}
|
|
1895
|
+
},
|
|
1896
|
+
fields() {
|
|
1897
|
+
const traceId = results.get(TRIAGE_LABEL)?.traceId;
|
|
1898
|
+
const observationIds = [TRIAGE_LABEL, ESCALATION_LABEL].map((label) => results.get(label)?.observationId).filter((id) => Boolean(id));
|
|
1899
|
+
return {
|
|
1900
|
+
...traceId ? { langfuseTraceId: traceId } : {},
|
|
1901
|
+
...observationIds.length > 0 ? { langfuseObservationIds: observationIds } : {}
|
|
1902
|
+
};
|
|
1903
|
+
}
|
|
1904
|
+
};
|
|
1905
|
+
}
|
|
1906
|
+
|
|
1857
1907
|
// src/functions/triage-tick.ts
|
|
1858
1908
|
function buildTriageTickFunctionDef(config) {
|
|
1859
1909
|
return {
|
|
@@ -2033,11 +2083,14 @@ async function processOneTicket(ctx, ref, deps) {
|
|
|
2033
2083
|
}
|
|
2034
2084
|
}
|
|
2035
2085
|
const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });
|
|
2086
|
+
const ticketUrl = ticketUrlFor(ticketUrlBase, ref.id);
|
|
2087
|
+
const ticketTrace = buildTicketTrace({ slug: config.slug, ticketId: ref.id, ticketUrl });
|
|
2088
|
+
const traces = recordTriageTraces(createPlatformLlmPort(ctx.api, ticketTrace));
|
|
2036
2089
|
const state = await runTicket(
|
|
2037
2090
|
{
|
|
2038
2091
|
ref,
|
|
2039
2092
|
profile,
|
|
2040
|
-
ports: { ...ports },
|
|
2093
|
+
ports: { ...ports, llm: traces.llm },
|
|
2041
2094
|
toolContext: createNoToolContext(),
|
|
2042
2095
|
budget,
|
|
2043
2096
|
// Unknown until triage runs — no node reached in the `until:'triage'`
|
|
@@ -2055,7 +2108,7 @@ async function processOneTicket(ctx, ref, deps) {
|
|
|
2055
2108
|
const category = findCategoryByTag(categories, classification.category);
|
|
2056
2109
|
const decision = await ctx.api.create("triage-decision", {
|
|
2057
2110
|
ticketId: ref.id,
|
|
2058
|
-
ticketUrl
|
|
2111
|
+
ticketUrl,
|
|
2059
2112
|
decidedAt: ports.clock.now(),
|
|
2060
2113
|
categoryId: category?.id ?? null,
|
|
2061
2114
|
tag: classification.category,
|
|
@@ -2066,7 +2119,8 @@ async function processOneTicket(ctx, ref, deps) {
|
|
|
2066
2119
|
status: "ok",
|
|
2067
2120
|
runId,
|
|
2068
2121
|
subjectRenamed,
|
|
2069
|
-
origin: "triage"
|
|
2122
|
+
origin: "triage",
|
|
2123
|
+
...traces.fields()
|
|
2070
2124
|
});
|
|
2071
2125
|
await ports.state.record(ref, classification, profile.audit);
|
|
2072
2126
|
if (state.escalated) await flagEscalation(ctx, ref, profile.audit.escalationTag, ports);
|
|
@@ -2074,6 +2128,7 @@ async function processOneTicket(ctx, ref, deps) {
|
|
|
2074
2128
|
const draftAgent = await resolveDraftAgent(ctx.api, category?.agentId ?? null);
|
|
2075
2129
|
const conversation = state.conversation;
|
|
2076
2130
|
const channel = conversation?.sourceChannel === "whatsapp" ? "whatsapp" : "email";
|
|
2131
|
+
const sourceChannel = conversation?.sourceChannel ?? null;
|
|
2077
2132
|
const generatedAt = ports.clock.now();
|
|
2078
2133
|
const expiresAt = new Date(generatedAt.getTime() + profile.schedule.fastResponseTtlMinutes * 6e4);
|
|
2079
2134
|
let created;
|
|
@@ -2086,6 +2141,7 @@ async function processOneTicket(ctx, ref, deps) {
|
|
|
2086
2141
|
categoryId: category?.id ?? null,
|
|
2087
2142
|
agentId: draftAgent?.id ?? null,
|
|
2088
2143
|
channel,
|
|
2144
|
+
sourceChannel,
|
|
2089
2145
|
generatedAt,
|
|
2090
2146
|
expiresAt,
|
|
2091
2147
|
sources: [],
|
|
@@ -2222,7 +2278,7 @@ async function handleApprovalHandler(ctx, config) {
|
|
|
2222
2278
|
ctx.logger.debug(`handle-approval: key "${payload.key}" is not a generated-response approval, ignoring`);
|
|
2223
2279
|
return;
|
|
2224
2280
|
}
|
|
2225
|
-
const record = await getOptional(ctx, "generated-response", id);
|
|
2281
|
+
const record = await getOptional(ctx.api, "generated-response", id);
|
|
2226
2282
|
if (!record) {
|
|
2227
2283
|
ctx.logger.info(`handle-approval: generated-response ${id} no longer exists, skipping`);
|
|
2228
2284
|
return;
|
|
@@ -2278,6 +2334,9 @@ async function handleApprovalHandler(ctx, config) {
|
|
|
2278
2334
|
lastMessageAt: data.generatedLastMessageAt ? new Date(data.generatedLastMessageAt) : null,
|
|
2279
2335
|
messageCount: data.generatedMessageCount ?? 0,
|
|
2280
2336
|
lastAgentReplyAt: null,
|
|
2337
|
+
answerableChannels: [],
|
|
2338
|
+
customerChannelAddress: null,
|
|
2339
|
+
accountChannelAddress: null,
|
|
2281
2340
|
hasCustomerAttachment: false,
|
|
2282
2341
|
sourceChannel: data.channel
|
|
2283
2342
|
};
|
|
@@ -2330,7 +2389,7 @@ async function handleApprovalHandler(ctx, config) {
|
|
|
2330
2389
|
return;
|
|
2331
2390
|
}
|
|
2332
2391
|
try {
|
|
2333
|
-
await ctx.api.update("generated-response", id, { autoSendDecision: "hold" }, { ifMatch: { status: "ready" } });
|
|
2392
|
+
await ctx.api.update("generated-response", id, { autoSendDecision: "hold", guardrailHits }, { ifMatch: { status: "ready" } });
|
|
2334
2393
|
} catch (err) {
|
|
2335
2394
|
if (!(err instanceof AppApiError && err.status === 409)) throw err;
|
|
2336
2395
|
}
|
|
@@ -2387,6 +2446,18 @@ var SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID = "2f5d6cbb-1c69-4a76-9d8f-
|
|
|
2387
2446
|
var INVALIDATE_RESPONSE_INPUT_GENERATED_RESPONSE_ID_UID = "9748baf5-97be-4a22-940d-46ef2f16a175";
|
|
2388
2447
|
var TEST_GORGIAS_WEBHOOK_INPUT_TICKET_ID_UID = "2cfcbfc1-77f1-4081-8fba-5f3a51c29e62";
|
|
2389
2448
|
var TEST_GORGIAS_WEBHOOK_INPUT_MODE_UID = "e75c5ec9-1205-492f-87df-a84ec12753f8";
|
|
2449
|
+
var TICKET_STATS_INPUT_FROM_UID = "15f48662-43f1-4a94-9e77-6aa34c2c8e41";
|
|
2450
|
+
var TICKET_STATS_INPUT_TO_UID = "2a50ec38-8d95-4a69-bc55-c21322088fe9";
|
|
2451
|
+
var TICKET_STATS_INPUT_COMPARE_TO_PREVIOUS_UID = "cb007f80-f00a-4f8f-a46c-61010a6c0609";
|
|
2452
|
+
var LIST_TICKETS_INPUT_FROM_UID = "dfbc9f3a-4ac9-4587-a9f1-47ea3fbb1d88";
|
|
2453
|
+
var LIST_TICKETS_INPUT_TO_UID = "c51c82ee-7d65-4b49-aef1-2a82983fa4eb";
|
|
2454
|
+
var LIST_TICKETS_INPUT_CATEGORY_ID_UID = "418e65f9-91e6-4d55-9dbd-03cb920207a6";
|
|
2455
|
+
var LIST_TICKETS_INPUT_OUTCOME_UID = "893cf56d-0f36-4701-9482-3de285c2108d";
|
|
2456
|
+
var LIST_TICKETS_INPUT_ESCALATED_UID = "eb154697-418d-4159-8050-503d214175b0";
|
|
2457
|
+
var LIST_TICKETS_INPUT_CHANNEL_UID = "a03a94ef-ccc6-48d9-a088-656406bb1585";
|
|
2458
|
+
var LIST_TICKETS_INPUT_STATUS_UID = "e2fdddae-0464-496d-9526-bb017c544f09";
|
|
2459
|
+
var LIST_TICKETS_INPUT_CURSOR_UID = "dfba83d4-8a6b-4e8b-bcfb-f3fc3cf663eb";
|
|
2460
|
+
var EXPLAIN_TICKET_INPUT_TICKET_ID_UID = "7b0e5d3a-42c1-4f6e-9a58-0d1c6f3e8b24";
|
|
2390
2461
|
|
|
2391
2462
|
// src/functions/run-triage-now.ts
|
|
2392
2463
|
var TRIAGE_RUN_REQUESTED_EVENT = "triage.run.requested";
|
|
@@ -2501,7 +2572,7 @@ var REFUSALS = {
|
|
|
2501
2572
|
async function invalidateResponseHandler(ctx, input) {
|
|
2502
2573
|
const id = input?.generatedResponseId?.trim();
|
|
2503
2574
|
if (!id) throw new ctx.NonRetriableError("generatedResponseId is required");
|
|
2504
|
-
const record = await getOptional(ctx, "generated-response", id);
|
|
2575
|
+
const record = await getOptional(ctx.api, "generated-response", id);
|
|
2505
2576
|
if (!record) throw new ctx.NonRetriableError(`R\xE9ponse g\xE9n\xE9r\xE9e introuvable (${id}).`);
|
|
2506
2577
|
const data = record.data;
|
|
2507
2578
|
const status = String(data.status ?? "");
|
|
@@ -2669,6 +2740,7 @@ async function runGraphDryRun({ base, api, resume, rebindDraft }) {
|
|
|
2669
2740
|
draft: result?.draft ?? null,
|
|
2670
2741
|
verdict: result?.verdict ?? null,
|
|
2671
2742
|
guardrailHits: result?.guardrailHits ?? [],
|
|
2743
|
+
ineligibleReason: result?.ineligibleReason ?? null,
|
|
2672
2744
|
...error ? { error } : {}
|
|
2673
2745
|
};
|
|
2674
2746
|
}
|
|
@@ -2731,6 +2803,9 @@ function createInlineConversationPort(ticket, now) {
|
|
|
2731
2803
|
// truth, and it is also what keeps `not_customer_turn` from holding the
|
|
2732
2804
|
// run before a single node has looked at the text.
|
|
2733
2805
|
lastAgentReplyAt: null,
|
|
2806
|
+
answerableChannels: [],
|
|
2807
|
+
customerChannelAddress: null,
|
|
2808
|
+
accountChannelAddress: null,
|
|
2734
2809
|
hasCustomerAttachment: false,
|
|
2735
2810
|
// `sourceChannel`, NOT `ref.channel`: the latter names the ADAPTER
|
|
2736
2811
|
// (gorgias) while every channel guardrail and the style prompt read this
|
|
@@ -3365,7 +3440,6 @@ async function syncAgentPromptSnapshotHandler(ctx, input) {
|
|
|
3365
3440
|
|
|
3366
3441
|
// src/functions/ext-models.ts
|
|
3367
3442
|
var TOKEN_APPROXIMATION_CHARS_PER_TOKEN = 4;
|
|
3368
|
-
var AGENT_PAGE_SIZE = 500;
|
|
3369
3443
|
function buildExtModelsFunctionDef(config) {
|
|
3370
3444
|
return {
|
|
3371
3445
|
universalIdentifier: identifierFor(config, "ext-models"),
|
|
@@ -3377,7 +3451,12 @@ function createExtModelsHandler() {
|
|
|
3377
3451
|
return (ctx) => extModelsHandler(ctx);
|
|
3378
3452
|
}
|
|
3379
3453
|
async function extModelsHandler(ctx) {
|
|
3380
|
-
const page = await
|
|
3454
|
+
const [page, settings] = await Promise.all([
|
|
3455
|
+
ctx.api.list("agent", { limit: AGENT_PAGE_SIZE }),
|
|
3456
|
+
ctx.api.settings.get()
|
|
3457
|
+
]);
|
|
3458
|
+
const appTag = trimmedSetting(settings.appScopeTag);
|
|
3459
|
+
const sourceViewId = trimmedSetting(settings.sourceViewId);
|
|
3381
3460
|
if (page.items.length >= AGENT_PAGE_SIZE) {
|
|
3382
3461
|
ctx.logger.warn(`ext-models: "agent" page came back full at ${page.items.length} rows \u2014 some may be silently missing from the response.`);
|
|
3383
3462
|
}
|
|
@@ -3390,17 +3469,20 @@ async function extModelsHandler(ctx) {
|
|
|
3390
3469
|
model_id: agent.modelId,
|
|
3391
3470
|
system_prompt: systemPrompt,
|
|
3392
3471
|
system_prompt_token_count: approximateTokenCount(systemPrompt),
|
|
3393
|
-
status: agent.status
|
|
3472
|
+
status: agent.status,
|
|
3473
|
+
app_tag: appTag,
|
|
3474
|
+
source_view_id: sourceViewId
|
|
3394
3475
|
};
|
|
3395
3476
|
});
|
|
3396
3477
|
}
|
|
3478
|
+
function trimmedSetting(value) {
|
|
3479
|
+
return typeof value === "string" ? value.trim() : "";
|
|
3480
|
+
}
|
|
3397
3481
|
function approximateTokenCount(text) {
|
|
3398
3482
|
return Math.ceil(text.length / TOKEN_APPROXIMATION_CHARS_PER_TOKEN);
|
|
3399
3483
|
}
|
|
3400
3484
|
|
|
3401
3485
|
// src/functions/ext-categories.ts
|
|
3402
|
-
var CATEGORY_PAGE_SIZE = 500;
|
|
3403
|
-
var AGENT_PAGE_SIZE2 = 500;
|
|
3404
3486
|
function buildExtCategoriesFunctionDef(config) {
|
|
3405
3487
|
return {
|
|
3406
3488
|
universalIdentifier: identifierFor(config, "ext-categories"),
|
|
@@ -3421,10 +3503,10 @@ async function extCategoriesHandler(ctx) {
|
|
|
3421
3503
|
// gateway's shared `FAN_OUT_BUDGET_MS`, so N+1 sequential round trips
|
|
3422
3504
|
// risk a slow tenant's whole categories response silently dropping out
|
|
3423
3505
|
// of the union on budget exhaustion.
|
|
3424
|
-
ctx.api.list("agent", { limit:
|
|
3506
|
+
ctx.api.list("agent", { limit: AGENT_PAGE_SIZE })
|
|
3425
3507
|
]);
|
|
3426
3508
|
warnIfTruncated(ctx, "category", categoriesPage.items.length, CATEGORY_PAGE_SIZE);
|
|
3427
|
-
warnIfTruncated(ctx, "agent", agentsPage.items.length,
|
|
3509
|
+
warnIfTruncated(ctx, "agent", agentsPage.items.length, AGENT_PAGE_SIZE);
|
|
3428
3510
|
const groupOrderById = new Map(groupsPage.items.map(toCategoryGroup).map((g) => [g.id, g.order]));
|
|
3429
3511
|
const agentById = new Map(agentsPage.items.map((record) => [record.id, toAgent(record)]));
|
|
3430
3512
|
const entries = [];
|
|
@@ -3436,11 +3518,7 @@ async function extCategoriesHandler(ctx) {
|
|
|
3436
3518
|
const groupOrder = category.groupId ? groupOrderById.get(category.groupId) ?? -Infinity : -Infinity;
|
|
3437
3519
|
entries.push({ category, agent, groupOrder });
|
|
3438
3520
|
}
|
|
3439
|
-
entries.sort(
|
|
3440
|
-
if (a.groupOrder !== b.groupOrder) return a.groupOrder - b.groupOrder;
|
|
3441
|
-
if (a.category.order !== b.category.order) return a.category.order - b.category.order;
|
|
3442
|
-
return a.category.name.localeCompare(b.category.name);
|
|
3443
|
-
});
|
|
3521
|
+
entries.sort(compareByGroupThenCategory);
|
|
3444
3522
|
return entries.map(({ category, agent }, index) => ({
|
|
3445
3523
|
_id: category.id,
|
|
3446
3524
|
name: category.name,
|
|
@@ -3460,7 +3538,7 @@ function warnIfTruncated(ctx, objectKey, itemCount, pageSize) {
|
|
|
3460
3538
|
// src/functions/ownership-probe.ts
|
|
3461
3539
|
async function ownsAgent(ctx, id) {
|
|
3462
3540
|
if (!id) return null;
|
|
3463
|
-
const record = await getOptional(ctx, "agent", id);
|
|
3541
|
+
const record = await getOptional(ctx.api, "agent", id);
|
|
3464
3542
|
return record ? { claimed: true } : null;
|
|
3465
3543
|
}
|
|
3466
3544
|
|
|
@@ -3623,7 +3701,7 @@ function toWireChatMessage(raw) {
|
|
|
3623
3701
|
}
|
|
3624
3702
|
async function resolveAgent(ctx, modelId) {
|
|
3625
3703
|
if (modelId) {
|
|
3626
|
-
const record2 = await getOptional(ctx, "agent", modelId);
|
|
3704
|
+
const record2 = await getOptional(ctx.api, "agent", modelId);
|
|
3627
3705
|
if (!record2) throw new ctx.NonRetriableError(`Model not found (id=${modelId})`);
|
|
3628
3706
|
return toAgent(record2);
|
|
3629
3707
|
}
|
|
@@ -3738,7 +3816,7 @@ async function serveHit(ctx, row, userId, now) {
|
|
|
3738
3816
|
);
|
|
3739
3817
|
} catch (err) {
|
|
3740
3818
|
if (!(err instanceof AppApiError) || err.status !== 409) throw err;
|
|
3741
|
-
const fresh = await getOptional(ctx, "generated-response", current.id);
|
|
3819
|
+
const fresh = await getOptional(ctx.api, "generated-response", current.id);
|
|
3742
3820
|
const freshStatus = fresh ? fresh.data.status : void 0;
|
|
3743
3821
|
if (!fresh || !isGeneratedResponseStatus(freshStatus) || freshStatus !== "ready") return null;
|
|
3744
3822
|
current = fresh;
|
|
@@ -3769,14 +3847,14 @@ async function buildAvailableResponse(ctx, generatedResponse) {
|
|
|
3769
3847
|
}
|
|
3770
3848
|
async function resolveCategoryRef(ctx, categoryId) {
|
|
3771
3849
|
if (!categoryId) return null;
|
|
3772
|
-
const record = await getOptional(ctx, "category", categoryId);
|
|
3850
|
+
const record = await getOptional(ctx.api, "category", categoryId);
|
|
3773
3851
|
if (!record) return null;
|
|
3774
3852
|
const category = toCategory(record);
|
|
3775
3853
|
return { _id: category.id, name: category.name };
|
|
3776
3854
|
}
|
|
3777
3855
|
async function resolveAgentRef(ctx, agentId) {
|
|
3778
3856
|
if (!agentId) return null;
|
|
3779
|
-
const record = await getOptional(ctx, "agent", agentId);
|
|
3857
|
+
const record = await getOptional(ctx.api, "agent", agentId);
|
|
3780
3858
|
if (!record) return null;
|
|
3781
3859
|
const agent = toAgent(record);
|
|
3782
3860
|
return { _id: agent.id, name: agent.name, model_id: agent.modelId };
|
|
@@ -3842,7 +3920,7 @@ async function executeEvaluation(ctx, userId, input) {
|
|
|
3842
3920
|
}
|
|
3843
3921
|
const modelId = input.modelId;
|
|
3844
3922
|
if (!modelId) throw new ctx.NonRetriableError("modelId is required");
|
|
3845
|
-
const agentRecord2 = await getOptional(ctx, "agent", modelId);
|
|
3923
|
+
const agentRecord2 = await getOptional(ctx.api, "agent", modelId);
|
|
3846
3924
|
if (!agentRecord2) throw new ctx.NonRetriableError(`Model not found (id=${modelId})`);
|
|
3847
3925
|
const agent = toAgent(agentRecord2);
|
|
3848
3926
|
const satisfied = input.satisfied;
|
|
@@ -4074,8 +4152,8 @@ function nonEmptyString(value) {
|
|
|
4074
4152
|
// src/functions/followup-gates.ts
|
|
4075
4153
|
var LABELS = {
|
|
4076
4154
|
G1: "Identifiant de ticket",
|
|
4077
|
-
G2: "Tag de
|
|
4078
|
-
G5: "Tag de
|
|
4155
|
+
G2: "Tag de l\u2019application configur\xE9",
|
|
4156
|
+
G5: "Tag de l\u2019application pr\xE9sent sur le ticket",
|
|
4079
4157
|
G6: "Aucune reprise humaine",
|
|
4080
4158
|
G7: "Cat\xE9gorie r\xE9solue et opt\xE9e",
|
|
4081
4159
|
G8: "Nouveau message client",
|
|
@@ -4089,7 +4167,7 @@ function evaluateTicketIdGate(ticketId) {
|
|
|
4089
4167
|
return ticketId === null ? stopped("G1", "Aucun identifiant de ticket exploitable (il doit \xEAtre une suite de chiffres).") : passed("G1", `Ticket ${ticketId}.`);
|
|
4090
4168
|
}
|
|
4091
4169
|
function evaluateScopeGate(settings) {
|
|
4092
|
-
return settings.
|
|
4170
|
+
return settings.appScopeTag.trim() === "" ? stopped("G2", "Le r\xE9glage \xAB Tag des tickets de l\u2019application \xBB est vide : aucun message suivant n\u2019est trait\xE9.") : passed("G2", `P\xE9rim\xE8tre : \xAB ${settings.appScopeTag} \xBB.`);
|
|
4093
4171
|
}
|
|
4094
4172
|
function skippedFollowupGates(gates) {
|
|
4095
4173
|
return gates.map((gate) => ({
|
|
@@ -4142,8 +4220,8 @@ function evaluatePayloadGates(input) {
|
|
|
4142
4220
|
return trace.done();
|
|
4143
4221
|
}
|
|
4144
4222
|
function scopeTagOnTicket(settings, tags) {
|
|
4145
|
-
const scopeTag = settings.
|
|
4146
|
-
return tags.includes(scopeTag) ? passed("G5", `Le ticket porte \xAB ${scopeTag} \xBB.`) : stopped("G5", `Le ticket ne porte pas le tag
|
|
4223
|
+
const scopeTag = settings.appScopeTag.trim();
|
|
4224
|
+
return tags.includes(scopeTag) ? passed("G5", `Le ticket porte \xAB ${scopeTag} \xBB.`) : stopped("G5", `Le ticket ne porte pas le tag \xAB ${scopeTag} \xBB : il n\u2019appartient pas \xE0 cette app.`);
|
|
4147
4225
|
}
|
|
4148
4226
|
function noHumanTakeover(settings, tags) {
|
|
4149
4227
|
const present = humanTakeoverTags(settings).filter((tag) => tags.includes(tag));
|
|
@@ -4530,7 +4608,7 @@ async function awaitSettledSend(ctx, id) {
|
|
|
4530
4608
|
return status;
|
|
4531
4609
|
}
|
|
4532
4610
|
async function readResponseStatus(ctx, id) {
|
|
4533
|
-
const row = await getOptional(ctx, "generated-response", id);
|
|
4611
|
+
const row = await getOptional(ctx.api, "generated-response", id);
|
|
4534
4612
|
if (!row) return "sent";
|
|
4535
4613
|
const raw = row.data.status;
|
|
4536
4614
|
return isGeneratedResponseStatus(raw) ? raw : null;
|
|
@@ -4603,6 +4681,7 @@ async function openFollowupResponse(ctx, input) {
|
|
|
4603
4681
|
categoryId: category.id,
|
|
4604
4682
|
agentId: agent?.id ?? null,
|
|
4605
4683
|
channel: conversation.sourceChannel === "whatsapp" ? "whatsapp" : "email",
|
|
4684
|
+
sourceChannel: conversation.sourceChannel ?? null,
|
|
4606
4685
|
generatedAt,
|
|
4607
4686
|
expiresAt: new Date(generatedAt.getTime() + settings.responseTtlMinutes * 6e4),
|
|
4608
4687
|
// Stamped HERE, not only when `process-response` finishes with the row:
|
|
@@ -4756,6 +4835,718 @@ async function triggerRun(ctx, ticketId, mode) {
|
|
|
4756
4835
|
return { mode, ticketId, runId: run.id };
|
|
4757
4836
|
}
|
|
4758
4837
|
|
|
4838
|
+
// src/domain/ticket-outcome.ts
|
|
4839
|
+
var REPORTED_OUTCOMES = [...OUTCOMES, "invalidated", "expired"];
|
|
4840
|
+
function emptyOutcomeCounts() {
|
|
4841
|
+
return Object.fromEntries(REPORTED_OUTCOMES.map((outcome) => [outcome, 0]));
|
|
4842
|
+
}
|
|
4843
|
+
var STATUS_EXITS = ["sent", "no_reply_needed", "failed", "invalidated", "expired"];
|
|
4844
|
+
function isStatusExit(status) {
|
|
4845
|
+
return STATUS_EXITS.includes(status);
|
|
4846
|
+
}
|
|
4847
|
+
function isReportedOutcome(value) {
|
|
4848
|
+
return REPORTED_OUTCOMES.includes(value);
|
|
4849
|
+
}
|
|
4850
|
+
function reportedOutcomeOf(status, outcome) {
|
|
4851
|
+
if (status === "test_draft" || status === "superseded") return null;
|
|
4852
|
+
if (isStatusExit(status)) return status;
|
|
4853
|
+
return isOutcome(outcome) ? outcome : null;
|
|
4854
|
+
}
|
|
4855
|
+
function foldOutcomeCounts(responseRows, triageRows) {
|
|
4856
|
+
const counts = emptyOutcomeCounts();
|
|
4857
|
+
for (const row of responseRows) {
|
|
4858
|
+
const outcome = reportedOutcomeOf(row["status"], row["outcome"]);
|
|
4859
|
+
if (outcome !== null) counts[outcome] += countOf(row);
|
|
4860
|
+
}
|
|
4861
|
+
for (const row of triageRows) {
|
|
4862
|
+
if (isUnautomatedTriage(row)) counts.escalated += countOf(row);
|
|
4863
|
+
}
|
|
4864
|
+
return counts;
|
|
4865
|
+
}
|
|
4866
|
+
|
|
4867
|
+
// src/domain/ticket-stats.ts
|
|
4868
|
+
function rateOrNull(rate) {
|
|
4869
|
+
return Number.isNaN(rate) ? null : rate;
|
|
4870
|
+
}
|
|
4871
|
+
function summarizeWindow({
|
|
4872
|
+
range,
|
|
4873
|
+
period,
|
|
4874
|
+
rows,
|
|
4875
|
+
categoryNames,
|
|
4876
|
+
compareRows
|
|
4877
|
+
}) {
|
|
4878
|
+
const totals = foldOutcomes(rows.responses, rows.triage);
|
|
4879
|
+
const compareTotals = compareRows === void 0 ? null : foldOutcomes(compareRows.responses, compareRows.triage);
|
|
4880
|
+
const daily = foldDailyOutcomes(rows.responses, rows.triage);
|
|
4881
|
+
return {
|
|
4882
|
+
period: range,
|
|
4883
|
+
interval: period.interval,
|
|
4884
|
+
// Every triage decision carries `escalated` and `status`, so this grouping partitions all of them.
|
|
4885
|
+
volume: sumCounts(rows.triage),
|
|
4886
|
+
autonomyRate: rateOrNull(autonomyRate(totals)),
|
|
4887
|
+
outcomes: foldOutcomeCounts(rows.responses, rows.triage),
|
|
4888
|
+
humanReasons: foldHumanReasons(rows.responses, rows.triage),
|
|
4889
|
+
byCategory: foldCategoryOutcomes(rows.categoryTriage, rows.categoryOutcomes, categoryNames),
|
|
4890
|
+
daily: period.interval === "day" ? fillMissingDays(daily, period.current.fromIso, period.current.toIso) : daily,
|
|
4891
|
+
signals: dashboardSignals(totals, compareTotals, countFailed(rows.responses))
|
|
4892
|
+
};
|
|
4893
|
+
}
|
|
4894
|
+
var STAT_DEFINITIONS = {
|
|
4895
|
+
volume: "Number of triage decisions over the period: every message the pipeline triaged, whether a draft followed or not.",
|
|
4896
|
+
autonomyRate: "autonomy rate = responses settled by the AI / (responses settled by the AI + requests taken over by a human); null when nothing is settled.",
|
|
4897
|
+
outcomes: {
|
|
4898
|
+
sent: "Response sent to the customer by the pipeline.",
|
|
4899
|
+
ready: "Draft ready to be served, with no tag (nominal path), still pending.",
|
|
4900
|
+
needs_human: "Verdict not sendable: draft ready, posted with the review tag, still pending.",
|
|
4901
|
+
guardrail_hold: "A guardrail held the draft, posted with the escalation tag, still pending.",
|
|
4902
|
+
awaiting_approval: "An action is waiting for a human\u2019s approval.",
|
|
4903
|
+
escalated: "Request escalated at triage, or triage error: no draft written.",
|
|
4904
|
+
triaged_only: "Triaged, with no drafting step to run.",
|
|
4905
|
+
no_reply_needed: "Conversation already closed: no reply needed, outside the autonomy rate.",
|
|
4906
|
+
failed: "Generation failed technically; the ticket went up to a human.",
|
|
4907
|
+
invalidated: "Draft invalidated (an agent replied before it was served): taken over by a human, whatever the outcome decided at generation.",
|
|
4908
|
+
expired: "Draft expired (the serving window closed without it being used): taken over by a human, whatever the outcome decided at generation."
|
|
4909
|
+
},
|
|
4910
|
+
humanReasons: {
|
|
4911
|
+
blocked: "Draft written but held (judge or guardrail), waiting for a human.",
|
|
4912
|
+
invalidated: "An agent replied before the draft was served.",
|
|
4913
|
+
expired: "The serving window closed on an unused draft.",
|
|
4914
|
+
escalatedNoDraft: "Handed over to a human at triage (escalation or triage error): no draft.",
|
|
4915
|
+
failed: "Generation failed technically and the ticket was escalated."
|
|
4916
|
+
},
|
|
4917
|
+
byCategory: `Per category: triaged volume (total) and who replied \u2014 AI (auto), human, no reply needed, no draft (undrafted); the top ${CATEGORY_TOP_N} categories, the rest under "Autres" (others).`,
|
|
4918
|
+
daily: `One entry per day (per week from ${WEEKLY_BUCKET_FROM_DAYS} days on): responses settled by the AI, requests taken over by a human, rate of the day (null with no settled request).`,
|
|
4919
|
+
signals: "What is worth reading out loud, like the dashboard\u2019s \xAB Signaux \xBB (signals) block; the sentences are in French."
|
|
4920
|
+
};
|
|
4921
|
+
|
|
4922
|
+
// src/functions/mcp-tool.ts
|
|
4923
|
+
function mcpToolTrigger(description, { exposed = true } = {}) {
|
|
4924
|
+
return {
|
|
4925
|
+
type: "mcpTool",
|
|
4926
|
+
description,
|
|
4927
|
+
readOnly: true,
|
|
4928
|
+
exposed
|
|
4929
|
+
};
|
|
4930
|
+
}
|
|
4931
|
+
function mcpToolHandler(run) {
|
|
4932
|
+
return (ctx, input) => {
|
|
4933
|
+
const { api } = ctx;
|
|
4934
|
+
return withToolInputErrors(ctx, () => run(api, input ?? {}));
|
|
4935
|
+
};
|
|
4936
|
+
}
|
|
4937
|
+
async function withToolInputErrors(ctx, run) {
|
|
4938
|
+
try {
|
|
4939
|
+
return await run();
|
|
4940
|
+
} catch (error) {
|
|
4941
|
+
if (error instanceof ToolInputError) throw new ctx.NonRetriableError(error.message);
|
|
4942
|
+
throw error;
|
|
4943
|
+
}
|
|
4944
|
+
}
|
|
4945
|
+
|
|
4946
|
+
// src/functions/ticket-stats.ts
|
|
4947
|
+
var TICKET_STATS_MAX_DAYS = 90;
|
|
4948
|
+
var DESCRIPTION = "Dashboard figures over a period of at most 90 days: volume, autonomy rate, outcomes, reasons for human takeovers, breakdown by category, daily series and signals. Same computation as the dashboard; each indicator is defined in `definitions`. With compareToPrevious, the same indicators over the previous period of the same length.";
|
|
4949
|
+
function buildTicketStatsFunctionDef(config) {
|
|
4950
|
+
return {
|
|
4951
|
+
universalIdentifier: mcpToolIdentifierFor(config, "ticket-stats"),
|
|
4952
|
+
name: "ticket-stats",
|
|
4953
|
+
trigger: mcpToolTrigger(DESCRIPTION),
|
|
4954
|
+
input: [
|
|
4955
|
+
{
|
|
4956
|
+
universalIdentifier: TICKET_STATS_INPUT_FROM_UID,
|
|
4957
|
+
name: "from",
|
|
4958
|
+
type: FieldType.TEXT,
|
|
4959
|
+
label: "From",
|
|
4960
|
+
description: "First day of the period, YYYY-MM-DD, included.",
|
|
4961
|
+
isNullable: false
|
|
4962
|
+
},
|
|
4963
|
+
{
|
|
4964
|
+
universalIdentifier: TICKET_STATS_INPUT_TO_UID,
|
|
4965
|
+
name: "to",
|
|
4966
|
+
type: FieldType.TEXT,
|
|
4967
|
+
label: "To",
|
|
4968
|
+
description: `Last day of the period, YYYY-MM-DD, included. At most ${TICKET_STATS_MAX_DAYS} days after "from".`,
|
|
4969
|
+
isNullable: false
|
|
4970
|
+
},
|
|
4971
|
+
{
|
|
4972
|
+
universalIdentifier: TICKET_STATS_INPUT_COMPARE_TO_PREVIOUS_UID,
|
|
4973
|
+
name: "compareToPrevious",
|
|
4974
|
+
type: FieldType.BOOLEAN,
|
|
4975
|
+
label: "Compare to previous period",
|
|
4976
|
+
description: 'Also compute the same indicators on the period of the same length that ends the day before "from".',
|
|
4977
|
+
isNullable: true
|
|
4978
|
+
}
|
|
4979
|
+
]
|
|
4980
|
+
};
|
|
4981
|
+
}
|
|
4982
|
+
function createTicketStatsHandler() {
|
|
4983
|
+
return mcpToolHandler(computeTicketStats);
|
|
4984
|
+
}
|
|
4985
|
+
async function computeTicketStats(api, input) {
|
|
4986
|
+
const range = dayRangeOf(input.from, input.to, TICKET_STATS_MAX_DAYS);
|
|
4987
|
+
assertOptionalBoolean("compareToPrevious", input.compareToPrevious);
|
|
4988
|
+
const [timezone, categoryNames] = await Promise.all([
|
|
4989
|
+
readStatsTimezone(api),
|
|
4990
|
+
readCategoryNames(api)
|
|
4991
|
+
]);
|
|
4992
|
+
const period = periodBoundsOf({ range });
|
|
4993
|
+
const previous = input.compareToPrevious === true ? previousWindowOf(range) : void 0;
|
|
4994
|
+
const [rows, previousRows] = await Promise.all([
|
|
4995
|
+
readWindowRows(api, period, timezone),
|
|
4996
|
+
previous && readWindowRows(api, previous.period, timezone)
|
|
4997
|
+
]);
|
|
4998
|
+
return {
|
|
4999
|
+
...summarizeWindow({ range, period, rows, categoryNames, compareRows: previousRows }),
|
|
5000
|
+
timezone,
|
|
5001
|
+
...previous && previousRows && {
|
|
5002
|
+
previous: summarizeWindow({ ...previous, rows: previousRows, categoryNames })
|
|
5003
|
+
},
|
|
5004
|
+
definitions: STAT_DEFINITIONS
|
|
5005
|
+
};
|
|
5006
|
+
}
|
|
5007
|
+
function previousWindowOf(range) {
|
|
5008
|
+
const previousRange = previousRangeOf(range);
|
|
5009
|
+
return { range: previousRange, period: periodBoundsOf({ range: previousRange }) };
|
|
5010
|
+
}
|
|
5011
|
+
async function readStatsTimezone(api) {
|
|
5012
|
+
const settings = await getSettingsOrNull(api);
|
|
5013
|
+
return settings?.statsTimezone || DEFAULT_STATS_TIMEZONE;
|
|
5014
|
+
}
|
|
5015
|
+
async function readWindowRows(api, period, timezone) {
|
|
5016
|
+
const { fromIso: gte, toIso: lte } = period.current;
|
|
5017
|
+
const generated = { filter: { generatedAt: { gte, lte } }, metrics: OUTCOME_METRICS };
|
|
5018
|
+
const decided = { filter: { decidedAt: { gte, lte } }, metrics: OUTCOME_METRICS };
|
|
5019
|
+
const bucketOn = (field) => ({ field, interval: period.interval, tz: timezone });
|
|
5020
|
+
const [responses, triage, categoryTriage, categoryOutcomes] = await Promise.all([
|
|
5021
|
+
api.aggregate("generated-response", {
|
|
5022
|
+
...generated,
|
|
5023
|
+
groupBy: OUTCOME_GROUP_BY,
|
|
5024
|
+
bucket: bucketOn("generatedAt")
|
|
5025
|
+
}),
|
|
5026
|
+
api.aggregate("triage-decision", {
|
|
5027
|
+
...decided,
|
|
5028
|
+
groupBy: TRIAGE_HANDOFF_GROUP_BY,
|
|
5029
|
+
bucket: bucketOn("decidedAt")
|
|
5030
|
+
}),
|
|
5031
|
+
api.aggregate("triage-decision", { ...decided, groupBy: CATEGORY_TRIAGE_GROUP_BY }),
|
|
5032
|
+
api.aggregate("generated-response", { ...generated, groupBy: CATEGORY_OUTCOME_GROUP_BY })
|
|
5033
|
+
]);
|
|
5034
|
+
return { responses, triage, categoryTriage, categoryOutcomes };
|
|
5035
|
+
}
|
|
5036
|
+
var LIST_TICKETS_MAX_DAYS = 31;
|
|
5037
|
+
var LIST_TICKETS_PAGE_SIZE = 50;
|
|
5038
|
+
var MAX_SCANNED_BATCHES = 8;
|
|
5039
|
+
var InvalidCursorError = class extends ToolInputError {
|
|
5040
|
+
constructor(reason = "The cursor is not one this tool issued") {
|
|
5041
|
+
super(`${reason}; start again without a cursor.`);
|
|
5042
|
+
this.name = "InvalidCursorError";
|
|
5043
|
+
}
|
|
5044
|
+
};
|
|
5045
|
+
var DESCRIPTION2 = "Lists the tickets the pipeline decided over a period of at most 31 days, newest first, 50 per page (nextCursor for the next one). One row per ticket (its most recent triage decision merged with its latest response): category, confidence, escalation, outcome, channel, sending, ineligibility reason, guardrails triggered, verdict. No customer text: use explain_ticket for the detail of a ticket. Filters: categoryId, outcome, escalated, channel, status. A page can be shorter than 50 rows while carrying a nextCursor: keep going as long as nextCursor is not null. The cursor is only valid with the same period and the same filters.";
|
|
5046
|
+
function buildListTicketsFunctionDef(config) {
|
|
5047
|
+
return {
|
|
5048
|
+
universalIdentifier: mcpToolIdentifierFor(config, "list-tickets"),
|
|
5049
|
+
name: "list-tickets",
|
|
5050
|
+
trigger: mcpToolTrigger(DESCRIPTION2),
|
|
5051
|
+
input: [
|
|
5052
|
+
{
|
|
5053
|
+
universalIdentifier: LIST_TICKETS_INPUT_FROM_UID,
|
|
5054
|
+
name: "from",
|
|
5055
|
+
type: FieldType.TEXT,
|
|
5056
|
+
label: "From",
|
|
5057
|
+
description: "First day of the period, YYYY-MM-DD, included.",
|
|
5058
|
+
isNullable: false
|
|
5059
|
+
},
|
|
5060
|
+
{
|
|
5061
|
+
universalIdentifier: LIST_TICKETS_INPUT_TO_UID,
|
|
5062
|
+
name: "to",
|
|
5063
|
+
type: FieldType.TEXT,
|
|
5064
|
+
label: "To",
|
|
5065
|
+
description: `Last day of the period, YYYY-MM-DD, included. At most ${LIST_TICKETS_MAX_DAYS} days after "from".`,
|
|
5066
|
+
isNullable: false
|
|
5067
|
+
},
|
|
5068
|
+
{
|
|
5069
|
+
universalIdentifier: LIST_TICKETS_INPUT_CATEGORY_ID_UID,
|
|
5070
|
+
name: "categoryId",
|
|
5071
|
+
type: FieldType.TEXT,
|
|
5072
|
+
label: "Category id",
|
|
5073
|
+
description: "Only the tickets triaged into this category (an id from list_categories).",
|
|
5074
|
+
isNullable: true
|
|
5075
|
+
},
|
|
5076
|
+
{
|
|
5077
|
+
universalIdentifier: LIST_TICKETS_INPUT_OUTCOME_UID,
|
|
5078
|
+
name: "outcome",
|
|
5079
|
+
type: FieldType.SELECT,
|
|
5080
|
+
label: "Outcome",
|
|
5081
|
+
description: 'Only the tickets that took this exit. "escalated" covers tickets handed over at triage, which have no response.',
|
|
5082
|
+
isNullable: true,
|
|
5083
|
+
options: [...REPORTED_OUTCOMES]
|
|
5084
|
+
},
|
|
5085
|
+
{
|
|
5086
|
+
universalIdentifier: LIST_TICKETS_INPUT_ESCALATED_UID,
|
|
5087
|
+
name: "escalated",
|
|
5088
|
+
type: FieldType.BOOLEAN,
|
|
5089
|
+
label: "Escalated",
|
|
5090
|
+
description: "Only the tickets the triage decision did (true) or did not (false) escalate.",
|
|
5091
|
+
isNullable: true
|
|
5092
|
+
},
|
|
5093
|
+
{
|
|
5094
|
+
universalIdentifier: LIST_TICKETS_INPUT_CHANNEL_UID,
|
|
5095
|
+
name: "channel",
|
|
5096
|
+
type: FieldType.TEXT,
|
|
5097
|
+
label: "Channel",
|
|
5098
|
+
description: "Only the tickets the customer wrote from this channel (e.g. email, whatsapp). The channel is recorded on the response only: a ticket with no response, such as one escalated at triage, never matches.",
|
|
5099
|
+
isNullable: true
|
|
5100
|
+
},
|
|
5101
|
+
{
|
|
5102
|
+
universalIdentifier: LIST_TICKETS_INPUT_STATUS_UID,
|
|
5103
|
+
name: "status",
|
|
5104
|
+
type: FieldType.SELECT,
|
|
5105
|
+
label: "Status",
|
|
5106
|
+
description: "Only the tickets whose response is in this status.",
|
|
5107
|
+
isNullable: true,
|
|
5108
|
+
options: [...GENERATED_RESPONSE_STATUSES]
|
|
5109
|
+
},
|
|
5110
|
+
{
|
|
5111
|
+
universalIdentifier: LIST_TICKETS_INPUT_CURSOR_UID,
|
|
5112
|
+
name: "cursor",
|
|
5113
|
+
type: FieldType.TEXT,
|
|
5114
|
+
label: "Cursor",
|
|
5115
|
+
description: "The nextCursor of the previous page. Leave empty for the first page.",
|
|
5116
|
+
isNullable: true
|
|
5117
|
+
}
|
|
5118
|
+
]
|
|
5119
|
+
};
|
|
5120
|
+
}
|
|
5121
|
+
function createListTicketsHandler() {
|
|
5122
|
+
return mcpToolHandler(listTickets);
|
|
5123
|
+
}
|
|
5124
|
+
function scopeOf(input) {
|
|
5125
|
+
const { from, to, categoryId, outcome, escalated, channel, status } = input;
|
|
5126
|
+
return JSON.stringify([
|
|
5127
|
+
from,
|
|
5128
|
+
to,
|
|
5129
|
+
categoryId || null,
|
|
5130
|
+
outcome || null,
|
|
5131
|
+
escalated ?? null,
|
|
5132
|
+
channel || null,
|
|
5133
|
+
status || null
|
|
5134
|
+
]);
|
|
5135
|
+
}
|
|
5136
|
+
function encodeCursor(position) {
|
|
5137
|
+
return Buffer.from(JSON.stringify(position)).toString("base64url");
|
|
5138
|
+
}
|
|
5139
|
+
function parseCursor(cursor) {
|
|
5140
|
+
let decoded;
|
|
5141
|
+
try {
|
|
5142
|
+
decoded = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
5143
|
+
} catch {
|
|
5144
|
+
throw new InvalidCursorError();
|
|
5145
|
+
}
|
|
5146
|
+
if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
|
|
5147
|
+
throw new InvalidCursorError();
|
|
5148
|
+
}
|
|
5149
|
+
return decoded;
|
|
5150
|
+
}
|
|
5151
|
+
function startOfScan(input) {
|
|
5152
|
+
const scope = scopeOf(input);
|
|
5153
|
+
if (!input.cursor) return { after: null, skip: 0, scope };
|
|
5154
|
+
const { after = null, skip, scope: issuedFor } = parseCursor(input.cursor);
|
|
5155
|
+
const wellFormed = (after === null || typeof after === "string") && typeof skip === "number" && Number.isInteger(skip) && skip >= 0 && typeof issuedFor === "string";
|
|
5156
|
+
if (!wellFormed) throw new InvalidCursorError();
|
|
5157
|
+
if (issuedFor !== scope)
|
|
5158
|
+
throw new InvalidCursorError("The cursor was issued for another period or other filters");
|
|
5159
|
+
return { after, skip, scope };
|
|
5160
|
+
}
|
|
5161
|
+
function assertValidFilters(input) {
|
|
5162
|
+
assertOptionalBoolean("escalated", input.escalated);
|
|
5163
|
+
if (input.outcome && !isReportedOutcome(input.outcome)) {
|
|
5164
|
+
throw new ToolInputError(
|
|
5165
|
+
`"outcome" must be one of ${REPORTED_OUTCOMES.join(", ")}; got ${JSON.stringify(input.outcome)}.`
|
|
5166
|
+
);
|
|
5167
|
+
}
|
|
5168
|
+
if (input.status && !isGeneratedResponseStatus(input.status)) {
|
|
5169
|
+
throw new ToolInputError(
|
|
5170
|
+
`"status" must be one of ${GENERATED_RESPONSE_STATUSES.join(", ")}; got ${JSON.stringify(input.status)}.`
|
|
5171
|
+
);
|
|
5172
|
+
}
|
|
5173
|
+
}
|
|
5174
|
+
async function listTickets(api, input) {
|
|
5175
|
+
const range = dayRangeOf(input.from, input.to, LIST_TICKETS_MAX_DAYS);
|
|
5176
|
+
assertValidFilters(input);
|
|
5177
|
+
let position = startOfScan(input);
|
|
5178
|
+
const window = periodBoundsOf({ range }).current;
|
|
5179
|
+
const filter = decisionFilter(window, input);
|
|
5180
|
+
const readBatch = (after) => api.list("triage-decision", {
|
|
5181
|
+
filter,
|
|
5182
|
+
sort: NEWEST_DECISION_FIRST,
|
|
5183
|
+
limit: LIST_TICKETS_PAGE_SIZE,
|
|
5184
|
+
...after === null ? {} : { cursor: after }
|
|
5185
|
+
});
|
|
5186
|
+
const [categoryNames, firstBatch] = await Promise.all([
|
|
5187
|
+
readCategoryNames(api),
|
|
5188
|
+
readBatch(position.after)
|
|
5189
|
+
]);
|
|
5190
|
+
let page = firstBatch;
|
|
5191
|
+
const rows = [];
|
|
5192
|
+
for (let scanned = 1; ; scanned++) {
|
|
5193
|
+
const batch = page.items.slice(position.skip).map(toTriageDecision);
|
|
5194
|
+
const candidates = await readTicketsOf(api, batch, window.toIso);
|
|
5195
|
+
for (const [index, candidate] of candidates.entries()) {
|
|
5196
|
+
if (candidate === null) continue;
|
|
5197
|
+
const row = toTicketRow(candidate.decision, candidate.response, categoryNames);
|
|
5198
|
+
if (!matchesResponseFilters(row, input)) continue;
|
|
5199
|
+
rows.push(row);
|
|
5200
|
+
if (rows.length === LIST_TICKETS_PAGE_SIZE) {
|
|
5201
|
+
return { rows, nextCursor: cursorAfter(page, position, position.skip + index + 1) };
|
|
5202
|
+
}
|
|
5203
|
+
}
|
|
5204
|
+
if (page.nextCursor === null) return { rows, nextCursor: null };
|
|
5205
|
+
position = { ...position, after: page.nextCursor, skip: 0 };
|
|
5206
|
+
if (scanned === MAX_SCANNED_BATCHES) return { rows, nextCursor: encodeCursor(position) };
|
|
5207
|
+
page = await readBatch(position.after);
|
|
5208
|
+
}
|
|
5209
|
+
}
|
|
5210
|
+
function cursorAfter(page, position, consumed) {
|
|
5211
|
+
if (consumed < page.items.length) return encodeCursor({ ...position, skip: consumed });
|
|
5212
|
+
return page.nextCursor === null ? null : encodeCursor({ ...position, after: page.nextCursor, skip: 0 });
|
|
5213
|
+
}
|
|
5214
|
+
function decisionFilter(window, input) {
|
|
5215
|
+
return {
|
|
5216
|
+
decidedAt: { gte: window.fromIso, lte: window.toIso },
|
|
5217
|
+
...input.categoryId ? { categoryId: input.categoryId } : {},
|
|
5218
|
+
...typeof input.escalated === "boolean" ? { escalated: input.escalated } : {}
|
|
5219
|
+
};
|
|
5220
|
+
}
|
|
5221
|
+
async function readTicketsOf(api, batch, windowEndIso) {
|
|
5222
|
+
const [newestDecidedAt, responses] = await Promise.all([
|
|
5223
|
+
readNewestDecisionTimes(api, batch, windowEndIso),
|
|
5224
|
+
latestResponsesByTicket(
|
|
5225
|
+
api,
|
|
5226
|
+
batch.map((decision) => decision.ticketId)
|
|
5227
|
+
)
|
|
5228
|
+
]);
|
|
5229
|
+
return batch.map(
|
|
5230
|
+
(decision) => isSuperseded(decision, newestDecidedAt) ? null : { decision, response: responses.get(decision.ticketId) ?? null }
|
|
5231
|
+
);
|
|
5232
|
+
}
|
|
5233
|
+
async function readNewestDecisionTimes(api, batch, windowEndIso) {
|
|
5234
|
+
const dated = batch.filter((decision) => decision.decidedAt !== null);
|
|
5235
|
+
if (dated.length === 0) return /* @__PURE__ */ new Map();
|
|
5236
|
+
const oldest = dated.reduce((a, b) => instantOf(b) < instantOf(a) ? b : a);
|
|
5237
|
+
const newest = await newestPerTicket(api, {
|
|
5238
|
+
objectKey: "triage-decision",
|
|
5239
|
+
ticketIds: dated.map((decision) => decision.ticketId),
|
|
5240
|
+
filter: { decidedAt: { gt: oldest.decidedAt, lte: windowEndIso } },
|
|
5241
|
+
sort: NEWEST_DECISION_FIRST
|
|
5242
|
+
});
|
|
5243
|
+
return new Map(
|
|
5244
|
+
[...newest].map(([ticketId, record]) => [ticketId, instantOf(toTriageDecision(record))])
|
|
5245
|
+
);
|
|
5246
|
+
}
|
|
5247
|
+
function isSuperseded(decision, newestDecidedAt) {
|
|
5248
|
+
return (newestDecidedAt.get(decision.ticketId) ?? -Infinity) > instantOf(decision);
|
|
5249
|
+
}
|
|
5250
|
+
function instantOf(decision) {
|
|
5251
|
+
return Date.parse(decision.decidedAt ?? "");
|
|
5252
|
+
}
|
|
5253
|
+
function toTicketRow(decision, response, categoryNames) {
|
|
5254
|
+
return {
|
|
5255
|
+
ticketId: decision.ticketId,
|
|
5256
|
+
ticketUrl: decision.ticketUrl,
|
|
5257
|
+
decidedAt: decision.decidedAt,
|
|
5258
|
+
categoryId: decision.categoryId,
|
|
5259
|
+
category: decision.categoryId === null ? null : categoryNames.get(decision.categoryId) ?? null,
|
|
5260
|
+
confidence: decision.confidence,
|
|
5261
|
+
escalated: decision.escalated,
|
|
5262
|
+
outcome: outcomeOf(decision, response),
|
|
5263
|
+
status: response?.status ?? null,
|
|
5264
|
+
channel: response === null ? null : response.sourceChannel ?? response.channel,
|
|
5265
|
+
sentAt: response?.sentAt ?? null,
|
|
5266
|
+
ineligibleReason: response?.ineligibleReason ?? null,
|
|
5267
|
+
guardrailHits: response?.guardrailHits ?? [],
|
|
5268
|
+
verdict: response?.verdict ? { verdict: response.verdict.verdict, confidence: response.verdict.confidence } : null,
|
|
5269
|
+
origin: decision.origin
|
|
5270
|
+
};
|
|
5271
|
+
}
|
|
5272
|
+
function outcomeOf(decision, response) {
|
|
5273
|
+
const answeredSince = response !== null && (response.generatedAt ?? "") >= (decision.decidedAt ?? "");
|
|
5274
|
+
if (isUnautomatedTriage(decision) && !answeredSince) return "escalated";
|
|
5275
|
+
return response === null ? null : reportedOutcomeOf(response.status, response.outcome);
|
|
5276
|
+
}
|
|
5277
|
+
function matchesResponseFilters(row, input) {
|
|
5278
|
+
return (!input.outcome || row.outcome === input.outcome) && (!input.channel || row.channel === input.channel) && (!input.status || row.status === input.status);
|
|
5279
|
+
}
|
|
5280
|
+
|
|
5281
|
+
// src/domain/trace-refs.ts
|
|
5282
|
+
function toTraceRefs(traceId, observationIds) {
|
|
5283
|
+
if (!traceId && observationIds.length === 0) return [];
|
|
5284
|
+
return [{ ...traceId ? { traceId } : {}, observationIds: [...observationIds] }];
|
|
5285
|
+
}
|
|
5286
|
+
|
|
5287
|
+
// src/functions/list-agents.ts
|
|
5288
|
+
var DESCRIPTION3 = "Lists the drafting agents: id, name, linked prompt (promptName, promptLabel), pinned version (promptVersion, null when the agent follows its label) and model. The prompt text is not returned: read it with get_prompt.";
|
|
5289
|
+
function buildListAgentsFunctionDef(config) {
|
|
5290
|
+
return {
|
|
5291
|
+
universalIdentifier: mcpToolIdentifierFor(config, "list-agents"),
|
|
5292
|
+
name: "list-agents",
|
|
5293
|
+
trigger: mcpToolTrigger(DESCRIPTION3)
|
|
5294
|
+
};
|
|
5295
|
+
}
|
|
5296
|
+
function createListAgentsHandler() {
|
|
5297
|
+
return (ctx) => describeAgents(ctx.api);
|
|
5298
|
+
}
|
|
5299
|
+
async function describeAgents(api) {
|
|
5300
|
+
return (await listAgents(api)).map(toAgentSummary);
|
|
5301
|
+
}
|
|
5302
|
+
function toAgentSummary(agent) {
|
|
5303
|
+
return {
|
|
5304
|
+
id: agent.id,
|
|
5305
|
+
name: agent.name,
|
|
5306
|
+
promptName: agent.promptName,
|
|
5307
|
+
promptLabel: agent.promptLabel,
|
|
5308
|
+
promptVersion: agent.promptVersion,
|
|
5309
|
+
modelId: agent.modelId
|
|
5310
|
+
};
|
|
5311
|
+
}
|
|
5312
|
+
|
|
5313
|
+
// src/functions/list-categories.ts
|
|
5314
|
+
var DESCRIPTION4 = "Lists the triage categories: id, name, tagName, description, examples, drafting agent (agentId), auto-reply and fast-reply flags (first message and follow-up) and group.";
|
|
5315
|
+
function buildListCategoriesFunctionDef(config) {
|
|
5316
|
+
return {
|
|
5317
|
+
universalIdentifier: mcpToolIdentifierFor(config, "list-categories"),
|
|
5318
|
+
name: "list-categories",
|
|
5319
|
+
trigger: mcpToolTrigger(DESCRIPTION4)
|
|
5320
|
+
};
|
|
5321
|
+
}
|
|
5322
|
+
function createListCategoriesHandler() {
|
|
5323
|
+
return (ctx) => describeCategories(ctx.api);
|
|
5324
|
+
}
|
|
5325
|
+
async function describeCategories(api) {
|
|
5326
|
+
const [categories, groupsPage] = await Promise.all([
|
|
5327
|
+
listCategories(api),
|
|
5328
|
+
api.list("category-group", { limit: CATEGORY_PAGE_SIZE })
|
|
5329
|
+
]);
|
|
5330
|
+
const groups = new Map(groupsPage.items.map(toCategoryGroup).map((group) => [group.id, group]));
|
|
5331
|
+
return categories.map((category) => {
|
|
5332
|
+
const group = groups.get(category.groupId ?? "") ?? null;
|
|
5333
|
+
return { category, group, groupOrder: group?.order ?? Number.NEGATIVE_INFINITY };
|
|
5334
|
+
}).sort(compareByGroupThenCategory).map(({ category, group }) => toCategorySummary(category, group));
|
|
5335
|
+
}
|
|
5336
|
+
function toCategorySummary(category, group) {
|
|
5337
|
+
return {
|
|
5338
|
+
...toCategoryFields(category),
|
|
5339
|
+
agentId: category.agentId,
|
|
5340
|
+
group: group === null ? null : { id: group.id, name: group.name }
|
|
5341
|
+
};
|
|
5342
|
+
}
|
|
5343
|
+
function toCategoryFields(category) {
|
|
5344
|
+
return {
|
|
5345
|
+
id: category.id,
|
|
5346
|
+
name: category.name,
|
|
5347
|
+
tagName: category.tagName,
|
|
5348
|
+
description: category.description,
|
|
5349
|
+
examples: category.examples,
|
|
5350
|
+
autoReplyEnabled: category.autoReplyEnabled,
|
|
5351
|
+
fastResponseEnabled: category.fastResponseEnabled,
|
|
5352
|
+
followupAutoReplyEnabled: category.followupAutoReplyEnabled,
|
|
5353
|
+
followupFastResponseEnabled: category.followupFastResponseEnabled
|
|
5354
|
+
};
|
|
5355
|
+
}
|
|
5356
|
+
|
|
5357
|
+
// src/functions/explain-ticket.ts
|
|
5358
|
+
var HISTORY_LIMIT = 20;
|
|
5359
|
+
var NEWEST_CORRECTION_FIRST = JSON.stringify([{ field: "capturedAt", direction: "desc" }]);
|
|
5360
|
+
var DESCRIPTION5 = "Explains a ticket: triage decision (category, confidence, reasoning, escalation and its reasoning), triage and escalation prompts as configured today in the settings (name, label; the version that ran is in the trace), generated responses (outcome, verdict, guardrails, send decision, drafting prompt version, sent text), human correction (generated text, sent text, diff), category, agent and timeline of the steps with the reason for the steps not reached. Also returns the Langfuse trace references (traceRefs) and traceAvailable: false on an old ticket or when the triage failed. { found: false } if the ticket is unknown.";
|
|
5361
|
+
function buildExplainTicketFunctionDef(config) {
|
|
5362
|
+
return {
|
|
5363
|
+
universalIdentifier: mcpToolIdentifierFor(config, "explain-ticket"),
|
|
5364
|
+
name: "explain-ticket",
|
|
5365
|
+
trigger: mcpToolTrigger(DESCRIPTION5),
|
|
5366
|
+
input: [
|
|
5367
|
+
{
|
|
5368
|
+
universalIdentifier: EXPLAIN_TICKET_INPUT_TICKET_ID_UID,
|
|
5369
|
+
name: "ticketId",
|
|
5370
|
+
type: FieldType.TEXT,
|
|
5371
|
+
label: "Ticket id",
|
|
5372
|
+
description: "The helpdesk ticket id, as listed by list_tickets.",
|
|
5373
|
+
isNullable: false
|
|
5374
|
+
}
|
|
5375
|
+
]
|
|
5376
|
+
};
|
|
5377
|
+
}
|
|
5378
|
+
function createExplainTicketHandler(config) {
|
|
5379
|
+
return mcpToolHandler((api, input) => explainTicket(api, config, input));
|
|
5380
|
+
}
|
|
5381
|
+
async function explainTicket(api, config, input) {
|
|
5382
|
+
const { ticketId } = input;
|
|
5383
|
+
if (typeof ticketId !== "string" || ticketId === "") {
|
|
5384
|
+
throw new ToolInputError('"ticketId" must be a non-empty string.');
|
|
5385
|
+
}
|
|
5386
|
+
const [decision, responses, comparisons, settings] = await Promise.all([
|
|
5387
|
+
readNewestDecision(api, ticketId),
|
|
5388
|
+
listTicketResponses(api, ticketId, HISTORY_LIMIT),
|
|
5389
|
+
readCorrections(api, ticketId),
|
|
5390
|
+
getSettingsOrNull(api)
|
|
5391
|
+
]);
|
|
5392
|
+
if (decision === null) return { found: false };
|
|
5393
|
+
const latest = responses[0];
|
|
5394
|
+
const categoryRead = readCategory(api, decision.categoryId);
|
|
5395
|
+
const agentId = latest?.agentId ?? (await categoryRead)?.agentId ?? null;
|
|
5396
|
+
const [category, agent] = await Promise.all([categoryRead, readAgent(api, agentId)]);
|
|
5397
|
+
return {
|
|
5398
|
+
found: true,
|
|
5399
|
+
ticketId,
|
|
5400
|
+
ticketUrl: decision.ticketUrl,
|
|
5401
|
+
triage: toTriageSection(decision, settings, config),
|
|
5402
|
+
responses: responses.map(toResponseSection),
|
|
5403
|
+
correction: comparisons[0] === void 0 ? null : toCorrectionSection(comparisons[0]),
|
|
5404
|
+
category: category === null ? null : toCategoryFields(category),
|
|
5405
|
+
agent,
|
|
5406
|
+
timeline: buildTimelineSteps({
|
|
5407
|
+
decision,
|
|
5408
|
+
job: latest,
|
|
5409
|
+
comparisons,
|
|
5410
|
+
conversation: persistedConversationOf(latest, comparisons[0]),
|
|
5411
|
+
policy: settings === null ? null : toDeliveryPolicy(settings),
|
|
5412
|
+
category
|
|
5413
|
+
})
|
|
5414
|
+
};
|
|
5415
|
+
}
|
|
5416
|
+
async function readNewestDecision(api, ticketId) {
|
|
5417
|
+
const page = await api.list("triage-decision", {
|
|
5418
|
+
filter: { ticketId },
|
|
5419
|
+
sort: NEWEST_DECISION_FIRST,
|
|
5420
|
+
limit: 1
|
|
5421
|
+
});
|
|
5422
|
+
return page.items[0] === void 0 ? null : toTriageDecision(page.items[0]);
|
|
5423
|
+
}
|
|
5424
|
+
async function readCorrections(api, ticketId) {
|
|
5425
|
+
const page = await api.list("response-comparison", {
|
|
5426
|
+
filter: { ticketId },
|
|
5427
|
+
sort: NEWEST_CORRECTION_FIRST,
|
|
5428
|
+
limit: HISTORY_LIMIT
|
|
5429
|
+
});
|
|
5430
|
+
return page.items.map(toResponseComparison);
|
|
5431
|
+
}
|
|
5432
|
+
async function readCategory(api, categoryId) {
|
|
5433
|
+
const record = await getOptional(api, "category", categoryId);
|
|
5434
|
+
return record === null ? null : toCategory(record);
|
|
5435
|
+
}
|
|
5436
|
+
async function readAgent(api, agentId) {
|
|
5437
|
+
const record = await getOptional(api, "agent", agentId);
|
|
5438
|
+
if (record === null) return null;
|
|
5439
|
+
const { modelId: _modelId, ...section } = toAgentSummary(toAgent(record));
|
|
5440
|
+
return section;
|
|
5441
|
+
}
|
|
5442
|
+
function persistedConversationOf(job, correction) {
|
|
5443
|
+
if (job !== void 0 && job.tracedInput.length > 0) {
|
|
5444
|
+
return { systemPrompt: job.tracedInput.find((m) => m.role === "system")?.content ?? null };
|
|
5445
|
+
}
|
|
5446
|
+
return correction !== void 0 && correction.conversationMessages.length > 0 ? { systemPrompt: null } : null;
|
|
5447
|
+
}
|
|
5448
|
+
function toTriageSection(decision, settings, config) {
|
|
5449
|
+
const traceRefs = toTraceRefs(decision.langfuseTraceId, decision.langfuseObservationIds);
|
|
5450
|
+
return {
|
|
5451
|
+
decidedAt: decision.decidedAt,
|
|
5452
|
+
origin: decision.origin,
|
|
5453
|
+
status: decision.status,
|
|
5454
|
+
error: decision.error,
|
|
5455
|
+
categoryId: decision.categoryId,
|
|
5456
|
+
tag: decision.tag,
|
|
5457
|
+
confidence: decision.confidence,
|
|
5458
|
+
reasoning: decision.reasoning,
|
|
5459
|
+
conversationOver: decision.conversationOver,
|
|
5460
|
+
escalated: decision.escalated,
|
|
5461
|
+
escalationConfidence: decision.escalationConfidence,
|
|
5462
|
+
escalationReasoning: decision.escalationReasoning,
|
|
5463
|
+
prompts: triagePromptsOf(decision.origin, settings, config),
|
|
5464
|
+
traceRefs,
|
|
5465
|
+
traceAvailable: traceRefs.length > 0
|
|
5466
|
+
};
|
|
5467
|
+
}
|
|
5468
|
+
function triagePromptsOf(origin, settings, config) {
|
|
5469
|
+
if (origin === "followup") return { triage: null, escalation: null };
|
|
5470
|
+
const nodes = settings?.nodes;
|
|
5471
|
+
const bindingOf = (node, derivedName) => node === null ? null : promptRefFor(node, derivedName);
|
|
5472
|
+
return {
|
|
5473
|
+
triage: bindingOf(nodes?.triage, resolvePromptName("triage", config)),
|
|
5474
|
+
escalation: bindingOf(nodes?.escalate, resolvePromptName("escalation", config))
|
|
5475
|
+
};
|
|
5476
|
+
}
|
|
5477
|
+
function toResponseSection(response) {
|
|
5478
|
+
return {
|
|
5479
|
+
id: response.id,
|
|
5480
|
+
status: response.status,
|
|
5481
|
+
outcome: response.outcome,
|
|
5482
|
+
generatedAt: response.generatedAt,
|
|
5483
|
+
sentAt: response.sentAt,
|
|
5484
|
+
verdict: response.verdict,
|
|
5485
|
+
guardrailHits: response.guardrailHits,
|
|
5486
|
+
autoSendDecision: response.autoSendDecision,
|
|
5487
|
+
ineligibleReason: response.ineligibleReason,
|
|
5488
|
+
promptName: response.promptName,
|
|
5489
|
+
promptVersion: response.promptVersion,
|
|
5490
|
+
traceRefs: [
|
|
5491
|
+
...toTraceRefs(
|
|
5492
|
+
response.langfuseTraceId,
|
|
5493
|
+
response.langfuseObservationId ? [response.langfuseObservationId] : []
|
|
5494
|
+
),
|
|
5495
|
+
...evaluationTraceRefs(response.evaluationObservationId)
|
|
5496
|
+
],
|
|
5497
|
+
sentText: response.status === "sent" ? response.responseText : null,
|
|
5498
|
+
tracedInput: response.tracedInput.filter((message) => message.role !== "system")
|
|
5499
|
+
};
|
|
5500
|
+
}
|
|
5501
|
+
function evaluationTraceRefs(observationId) {
|
|
5502
|
+
return observationId ? [{ observationIds: [observationId], withoutMessages: true }] : [];
|
|
5503
|
+
}
|
|
5504
|
+
function toCorrectionSection(correction) {
|
|
5505
|
+
return {
|
|
5506
|
+
capturedAt: correction.capturedAt,
|
|
5507
|
+
generatedText: correction.generatedText,
|
|
5508
|
+
sentText: correction.sentText,
|
|
5509
|
+
diff: correction.diff
|
|
5510
|
+
};
|
|
5511
|
+
}
|
|
5512
|
+
|
|
5513
|
+
// src/functions/prompt-scope.ts
|
|
5514
|
+
var DESCRIPTION6 = "Internal: exact names of the Langfuse prompts of this app (the seven kit slots, prefixed, the prompt of each agent and the prompts chosen in the settings). Never a wildcard.";
|
|
5515
|
+
function buildPromptScopeFunctionDef(config) {
|
|
5516
|
+
return {
|
|
5517
|
+
universalIdentifier: mcpToolIdentifierFor(config, "prompt-scope"),
|
|
5518
|
+
name: "prompt-scope",
|
|
5519
|
+
trigger: mcpToolTrigger(DESCRIPTION6, { exposed: false })
|
|
5520
|
+
};
|
|
5521
|
+
}
|
|
5522
|
+
function createPromptScopeHandler(config) {
|
|
5523
|
+
return (ctx) => promptScope(ctx.api, config);
|
|
5524
|
+
}
|
|
5525
|
+
async function promptScope(api, config) {
|
|
5526
|
+
const [agents, settings] = await Promise.all([
|
|
5527
|
+
listAgents(api),
|
|
5528
|
+
getSettingsOrNull(api)
|
|
5529
|
+
]);
|
|
5530
|
+
const candidates = [
|
|
5531
|
+
...PROMPT_SLOTS.map((slot) => resolvePromptName(slot, config)),
|
|
5532
|
+
...agents.map((agent) => agent.promptName),
|
|
5533
|
+
...settings === null ? [] : promptNamesChosenIn(settings)
|
|
5534
|
+
];
|
|
5535
|
+
return { names: [...new Set(candidates.filter(isExactName))] };
|
|
5536
|
+
}
|
|
5537
|
+
function promptNamesChosenIn(settings) {
|
|
5538
|
+
const nodes = Object.values(settings.nodes ?? {});
|
|
5539
|
+
const stepPrompts = nodes.map((node) => node?.prompt?.name);
|
|
5540
|
+
return [
|
|
5541
|
+
...stepPrompts,
|
|
5542
|
+
settings.channelPromptEmail || DEFAULT_CHANNEL_PROMPT_EMAIL,
|
|
5543
|
+
settings.channelPromptWhatsapp || DEFAULT_CHANNEL_PROMPT_WHATSAPP
|
|
5544
|
+
];
|
|
5545
|
+
}
|
|
5546
|
+
function isExactName(name) {
|
|
5547
|
+
return typeof name === "string" && name !== "" && !name.includes("*");
|
|
5548
|
+
}
|
|
5549
|
+
|
|
4759
5550
|
// src/pages/manifest.ts
|
|
4760
5551
|
function pageIdentifierFor(config, key) {
|
|
4761
5552
|
const id = config.identifiers[key];
|
|
@@ -4896,6 +5687,40 @@ var FUNCTION_ASSEMBLY = [
|
|
|
4896
5687
|
key: "test-gorgias-webhook",
|
|
4897
5688
|
build: buildTestGorgiasWebhookFunctionDef,
|
|
4898
5689
|
createHandler: createTestGorgiasWebhookHandler
|
|
5690
|
+
},
|
|
5691
|
+
// The read-only MCP tools (spec §5.3). Their identifiers are optional —
|
|
5692
|
+
// `mcpToolIdentifierFor` derives them — so they sit outside
|
|
5693
|
+
// FUNCTION_IDENTIFIER_KEYS and this assembly covers that list PLUS the MCP tools below.
|
|
5694
|
+
{
|
|
5695
|
+
key: "ticket-stats",
|
|
5696
|
+
build: buildTicketStatsFunctionDef,
|
|
5697
|
+
createHandler: () => createTicketStatsHandler()
|
|
5698
|
+
},
|
|
5699
|
+
{
|
|
5700
|
+
key: "list-tickets",
|
|
5701
|
+
build: buildListTicketsFunctionDef,
|
|
5702
|
+
createHandler: () => createListTicketsHandler()
|
|
5703
|
+
},
|
|
5704
|
+
{
|
|
5705
|
+
key: "explain-ticket",
|
|
5706
|
+
build: buildExplainTicketFunctionDef,
|
|
5707
|
+
createHandler: createExplainTicketHandler
|
|
5708
|
+
},
|
|
5709
|
+
{
|
|
5710
|
+
key: "list-categories",
|
|
5711
|
+
build: buildListCategoriesFunctionDef,
|
|
5712
|
+
createHandler: () => createListCategoriesHandler()
|
|
5713
|
+
},
|
|
5714
|
+
{
|
|
5715
|
+
key: "list-agents",
|
|
5716
|
+
build: buildListAgentsFunctionDef,
|
|
5717
|
+
createHandler: () => createListAgentsHandler()
|
|
5718
|
+
},
|
|
5719
|
+
// Internal (`exposed: false`): the OS asks it which prompt names belong to this app (D5).
|
|
5720
|
+
{
|
|
5721
|
+
key: "prompt-scope",
|
|
5722
|
+
build: buildPromptScopeFunctionDef,
|
|
5723
|
+
createHandler: createPromptScopeHandler
|
|
4899
5724
|
}
|
|
4900
5725
|
];
|
|
4901
5726
|
function buildPromptsAllowlist() {
|