@apotech-os/support-kit 9.0.0 → 10.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { CATEGORY_GROUP_FIELD_NAME_UID, CATEGORY_GROUP_FIELD_ORDER_UID, PIPELINE_STATE_FIELD_SINGLETON_KEY_UID, PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID, PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID, PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID, PROMPT_CACHE_FIELD_PROMPT_KEY_UID, PROMPT_CACHE_FIELD_CONTENT_UID, PROMPT_CACHE_FIELD_VERSION_UID, PROMPT_CACHE_FIELD_LABEL_UID, PROMPT_CACHE_FIELD_CONFIG_UID, CATEGORY_GROUP_INDEX_NAME_UID, CATEGORY_GROUP_OBJECT_UID, PIPELINE_STATE_INDEX_SINGLETON_KEY_UID, PIPELINE_STATE_OBJECT_UID, PROMPT_CACHE_INDEX_PROMPT_KEY_UID, PROMPT_CACHE_OBJECT_UID, CATEGORY_INDEX_TAG_NAME_UID, CATEGORY_INDEX_NAME_UID, CATEGORY_INDEX_ORDER_UID, CATEGORY_FIELD_NAME_UID, CATEGORY_FIELD_TAG_NAME_UID, CATEGORY_FIELD_ORDER_UID, CATEGORY_FIELD_GROUP_ID_UID, CATEGORY_FIELD_AGENT_ID_UID, CATEGORY_FIELD_EXTRA_TAGS_UID, CATEGORY_FIELD_DESCRIPTION_UID, CATEGORY_FIELD_EXAMPLES_UID, CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID, CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID, CATEGORY_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_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, 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_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, isGeneratedResponseStatus, isInvalidatableStatus, DEFAULT_LLM_PROVIDER, toCategoryGroup, toCategory, toGeneratedResponse, NODE_NAMES, toConversation, reclaimStalledSend, applySignature, snapshotConversation, isEvaluationVerdict, requiresFollowup, computeWordDiff, findCategoryByTag, isTerminalStatus, canTransition, toDecisionOrigin, isConversationOver, isFallbackClassification, hasNoDraftNode, isCustomerTurnWithWords } from './chunk-MHRKUDEZ.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-MHRKUDEZ.js';
1
+ import { CATEGORY_GROUP_FIELD_NAME_UID, CATEGORY_GROUP_FIELD_ORDER_UID, PIPELINE_STATE_FIELD_SINGLETON_KEY_UID, PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID, PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID, PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID, PROMPT_CACHE_FIELD_PROMPT_KEY_UID, PROMPT_CACHE_FIELD_CONTENT_UID, PROMPT_CACHE_FIELD_VERSION_UID, PROMPT_CACHE_FIELD_LABEL_UID, PROMPT_CACHE_FIELD_CONFIG_UID, 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-G3Q4P4OA.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-G3Q4P4OA.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: [
@@ -1182,6 +1198,9 @@ function identifierFor(config, key) {
1182
1198
  }
1183
1199
  return id;
1184
1200
  }
1201
+ function mcpToolIdentifierFor(config, key) {
1202
+ return config.identifiers[key] ?? deriveUid(`${config.slug}:function:${key}`);
1203
+ }
1185
1204
 
1186
1205
  // src/adapters/gorgias-tags.ts
1187
1206
  function dedupeTagNames(tags) {
@@ -1317,6 +1336,7 @@ function createPlatformLlmPort(api, trace) {
1317
1336
  // its own to carry the new field; it already carries whatever shape
1318
1337
  // `CompletionRequest.promptRef` has.
1319
1338
  ...req.promptRef ? { promptRef: req.promptRef } : {},
1339
+ ...req.promptVariables ? { promptVariables: req.promptVariables } : {},
1320
1340
  ...runTrace ? { trace: runTrace } : {}
1321
1341
  });
1322
1342
  return {
@@ -1460,15 +1480,23 @@ function createRecordingLlmPort(llm) {
1460
1480
  };
1461
1481
  }
1462
1482
  var DEFAULT_MAX_TOOL_CALLS = 5;
1463
- async function getOptional(ctx, objectKey, id) {
1483
+ async function getOptional(api, objectKey, id) {
1464
1484
  if (!id) return null;
1465
1485
  try {
1466
- return await ctx.api.get(objectKey, id);
1486
+ return await api.get(objectKey, id);
1467
1487
  } catch (err) {
1468
1488
  if (err instanceof AppApiError && err.status === 404) return null;
1469
1489
  throw err;
1470
1490
  }
1471
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
+ }
1472
1500
  function buildTicketPorts(ctx, trace) {
1473
1501
  return {
1474
1502
  conversation: createGorgiasConversationPort(ctx.api),
@@ -1649,7 +1677,7 @@ async function finalizeNonSent(ctx, id, ticketId, toStatus, extra) {
1649
1677
  }
1650
1678
  }
1651
1679
  async function respondToPendingResponse(ctx, config, recordId, options = {}) {
1652
- const record = await getOptional(ctx, "generated-response", recordId);
1680
+ const record = await getOptional(ctx.api, "generated-response", recordId);
1653
1681
  if (!record) {
1654
1682
  ctx.logger.info(`respond: generated-response ${recordId} no longer exists, skipping`);
1655
1683
  return null;
@@ -1666,7 +1694,7 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
1666
1694
  }
1667
1695
  const ticketId = data.ticketId;
1668
1696
  const ref = { id: ticketId, channel: "gorgias" };
1669
- const decision = await getOptional(ctx, "triage-decision", data.triageDecisionId ?? null);
1697
+ const decision = await getOptional(ctx.api, "triage-decision", data.triageDecisionId ?? null);
1670
1698
  if (!decision) {
1671
1699
  ctx.logger.error(`respond: generated-response ${recordId} has no resolvable triage-decision, marking failed`);
1672
1700
  await finalizeNonSent(ctx, recordId, ticketId, "failed", { error: "triage-decision not found" });
@@ -1674,10 +1702,10 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
1674
1702
  }
1675
1703
  const classification = classificationFromDecision(decision);
1676
1704
  const escalated = decision.data.escalated === true;
1677
- const categoryRecord = await getOptional(ctx, "category", data.categoryId ?? null);
1705
+ const categoryRecord = await getOptional(ctx.api, "category", data.categoryId ?? null);
1678
1706
  const category = categoryRecord ? toCategory(categoryRecord) : null;
1679
1707
  const origin = toDecisionOrigin(data.origin);
1680
- const agentRecord2 = data.agentId ? await getOptional(ctx, "agent", data.agentId) : null;
1708
+ const agentRecord2 = data.agentId ? await getOptional(ctx.api, "agent", data.agentId) : null;
1681
1709
  const agent = agentRecord2 ? toAgent(agentRecord2) : await resolveDraftAgent(ctx.api, null);
1682
1710
  const profile = applyFollowupSendPolicy(
1683
1711
  settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes)),
@@ -1843,6 +1871,39 @@ function ticketUrlFor(base, ticketId) {
1843
1871
  return base ? `${base}/${encodeURIComponent(ticketId)}` : null;
1844
1872
  }
1845
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
+
1846
1907
  // src/functions/triage-tick.ts
1847
1908
  function buildTriageTickFunctionDef(config) {
1848
1909
  return {
@@ -2022,11 +2083,14 @@ async function processOneTicket(ctx, ref, deps) {
2022
2083
  }
2023
2084
  }
2024
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));
2025
2089
  const state = await runTicket(
2026
2090
  {
2027
2091
  ref,
2028
2092
  profile,
2029
- ports: { ...ports },
2093
+ ports: { ...ports, llm: traces.llm },
2030
2094
  toolContext: createNoToolContext(),
2031
2095
  budget,
2032
2096
  // Unknown until triage runs — no node reached in the `until:'triage'`
@@ -2044,7 +2108,7 @@ async function processOneTicket(ctx, ref, deps) {
2044
2108
  const category = findCategoryByTag(categories, classification.category);
2045
2109
  const decision = await ctx.api.create("triage-decision", {
2046
2110
  ticketId: ref.id,
2047
- ticketUrl: ticketUrlFor(ticketUrlBase, ref.id),
2111
+ ticketUrl,
2048
2112
  decidedAt: ports.clock.now(),
2049
2113
  categoryId: category?.id ?? null,
2050
2114
  tag: classification.category,
@@ -2055,7 +2119,8 @@ async function processOneTicket(ctx, ref, deps) {
2055
2119
  status: "ok",
2056
2120
  runId,
2057
2121
  subjectRenamed,
2058
- origin: "triage"
2122
+ origin: "triage",
2123
+ ...traces.fields()
2059
2124
  });
2060
2125
  await ports.state.record(ref, classification, profile.audit);
2061
2126
  if (state.escalated) await flagEscalation(ctx, ref, profile.audit.escalationTag, ports);
@@ -2213,7 +2278,7 @@ async function handleApprovalHandler(ctx, config) {
2213
2278
  ctx.logger.debug(`handle-approval: key "${payload.key}" is not a generated-response approval, ignoring`);
2214
2279
  return;
2215
2280
  }
2216
- const record = await getOptional(ctx, "generated-response", id);
2281
+ const record = await getOptional(ctx.api, "generated-response", id);
2217
2282
  if (!record) {
2218
2283
  ctx.logger.info(`handle-approval: generated-response ${id} no longer exists, skipping`);
2219
2284
  return;
@@ -2381,6 +2446,18 @@ var SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID = "2f5d6cbb-1c69-4a76-9d8f-
2381
2446
  var INVALIDATE_RESPONSE_INPUT_GENERATED_RESPONSE_ID_UID = "9748baf5-97be-4a22-940d-46ef2f16a175";
2382
2447
  var TEST_GORGIAS_WEBHOOK_INPUT_TICKET_ID_UID = "2cfcbfc1-77f1-4081-8fba-5f3a51c29e62";
2383
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";
2384
2461
 
2385
2462
  // src/functions/run-triage-now.ts
2386
2463
  var TRIAGE_RUN_REQUESTED_EVENT = "triage.run.requested";
@@ -2495,7 +2572,7 @@ var REFUSALS = {
2495
2572
  async function invalidateResponseHandler(ctx, input) {
2496
2573
  const id = input?.generatedResponseId?.trim();
2497
2574
  if (!id) throw new ctx.NonRetriableError("generatedResponseId is required");
2498
- const record = await getOptional(ctx, "generated-response", id);
2575
+ const record = await getOptional(ctx.api, "generated-response", id);
2499
2576
  if (!record) throw new ctx.NonRetriableError(`R\xE9ponse g\xE9n\xE9r\xE9e introuvable (${id}).`);
2500
2577
  const data = record.data;
2501
2578
  const status = String(data.status ?? "");
@@ -3363,7 +3440,6 @@ async function syncAgentPromptSnapshotHandler(ctx, input) {
3363
3440
 
3364
3441
  // src/functions/ext-models.ts
3365
3442
  var TOKEN_APPROXIMATION_CHARS_PER_TOKEN = 4;
3366
- var AGENT_PAGE_SIZE = 500;
3367
3443
  function buildExtModelsFunctionDef(config) {
3368
3444
  return {
3369
3445
  universalIdentifier: identifierFor(config, "ext-models"),
@@ -3375,7 +3451,12 @@ function createExtModelsHandler() {
3375
3451
  return (ctx) => extModelsHandler(ctx);
3376
3452
  }
3377
3453
  async function extModelsHandler(ctx) {
3378
- const page = await ctx.api.list("agent", { limit: AGENT_PAGE_SIZE });
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);
3379
3460
  if (page.items.length >= AGENT_PAGE_SIZE) {
3380
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.`);
3381
3462
  }
@@ -3388,17 +3469,20 @@ async function extModelsHandler(ctx) {
3388
3469
  model_id: agent.modelId,
3389
3470
  system_prompt: systemPrompt,
3390
3471
  system_prompt_token_count: approximateTokenCount(systemPrompt),
3391
- status: agent.status
3472
+ status: agent.status,
3473
+ app_tag: appTag,
3474
+ source_view_id: sourceViewId
3392
3475
  };
3393
3476
  });
3394
3477
  }
3478
+ function trimmedSetting(value) {
3479
+ return typeof value === "string" ? value.trim() : "";
3480
+ }
3395
3481
  function approximateTokenCount(text) {
3396
3482
  return Math.ceil(text.length / TOKEN_APPROXIMATION_CHARS_PER_TOKEN);
3397
3483
  }
3398
3484
 
3399
3485
  // src/functions/ext-categories.ts
3400
- var CATEGORY_PAGE_SIZE = 500;
3401
- var AGENT_PAGE_SIZE2 = 500;
3402
3486
  function buildExtCategoriesFunctionDef(config) {
3403
3487
  return {
3404
3488
  universalIdentifier: identifierFor(config, "ext-categories"),
@@ -3419,10 +3503,10 @@ async function extCategoriesHandler(ctx) {
3419
3503
  // gateway's shared `FAN_OUT_BUDGET_MS`, so N+1 sequential round trips
3420
3504
  // risk a slow tenant's whole categories response silently dropping out
3421
3505
  // of the union on budget exhaustion.
3422
- ctx.api.list("agent", { limit: AGENT_PAGE_SIZE2 })
3506
+ ctx.api.list("agent", { limit: AGENT_PAGE_SIZE })
3423
3507
  ]);
3424
3508
  warnIfTruncated(ctx, "category", categoriesPage.items.length, CATEGORY_PAGE_SIZE);
3425
- warnIfTruncated(ctx, "agent", agentsPage.items.length, AGENT_PAGE_SIZE2);
3509
+ warnIfTruncated(ctx, "agent", agentsPage.items.length, AGENT_PAGE_SIZE);
3426
3510
  const groupOrderById = new Map(groupsPage.items.map(toCategoryGroup).map((g) => [g.id, g.order]));
3427
3511
  const agentById = new Map(agentsPage.items.map((record) => [record.id, toAgent(record)]));
3428
3512
  const entries = [];
@@ -3434,11 +3518,7 @@ async function extCategoriesHandler(ctx) {
3434
3518
  const groupOrder = category.groupId ? groupOrderById.get(category.groupId) ?? -Infinity : -Infinity;
3435
3519
  entries.push({ category, agent, groupOrder });
3436
3520
  }
3437
- entries.sort((a, b) => {
3438
- if (a.groupOrder !== b.groupOrder) return a.groupOrder - b.groupOrder;
3439
- if (a.category.order !== b.category.order) return a.category.order - b.category.order;
3440
- return a.category.name.localeCompare(b.category.name);
3441
- });
3521
+ entries.sort(compareByGroupThenCategory);
3442
3522
  return entries.map(({ category, agent }, index) => ({
3443
3523
  _id: category.id,
3444
3524
  name: category.name,
@@ -3458,7 +3538,7 @@ function warnIfTruncated(ctx, objectKey, itemCount, pageSize) {
3458
3538
  // src/functions/ownership-probe.ts
3459
3539
  async function ownsAgent(ctx, id) {
3460
3540
  if (!id) return null;
3461
- const record = await getOptional(ctx, "agent", id);
3541
+ const record = await getOptional(ctx.api, "agent", id);
3462
3542
  return record ? { claimed: true } : null;
3463
3543
  }
3464
3544
 
@@ -3539,11 +3619,9 @@ async function executeChat(ctx, userId, input) {
3539
3619
  const chatMessages = systemContent ? [{ role: "system", content: systemContent }, ...contextMessages] : contextMessages;
3540
3620
  const result = await ctx.api.llm.complete({
3541
3621
  messages: chatMessages,
3542
- // H3/I16: the resolved Langfuse prompt's own model config WINS over the
3543
- // agent's fallback modelId — every ported graph node applies this same
3544
- // rule (`draft.ts`, `triage.ts`, …); this was the one `PromptPort
3545
- // .resolve` consumer in the repo that dropped it.
3546
- options: { model: resolvedPrompt.config?.model ?? agent.modelId },
3622
+ // The agent's modelId stored in the OS wins; the prompt's Langfuse
3623
+ // config is ignored, like every graph node (`draft.ts`, `triage.ts`, …).
3624
+ options: { model: agent.modelId },
3547
3625
  // Link-only (D-LF follow-up, option (b)): this function already resolved
3548
3626
  // its own prompt two lines above via `PromptPort` — `resolve: false`
3549
3627
  // links the completion to it in Langfuse WITHOUT re-triggering the
@@ -3621,7 +3699,7 @@ function toWireChatMessage(raw) {
3621
3699
  }
3622
3700
  async function resolveAgent(ctx, modelId) {
3623
3701
  if (modelId) {
3624
- const record2 = await getOptional(ctx, "agent", modelId);
3702
+ const record2 = await getOptional(ctx.api, "agent", modelId);
3625
3703
  if (!record2) throw new ctx.NonRetriableError(`Model not found (id=${modelId})`);
3626
3704
  return toAgent(record2);
3627
3705
  }
@@ -3736,7 +3814,7 @@ async function serveHit(ctx, row, userId, now) {
3736
3814
  );
3737
3815
  } catch (err) {
3738
3816
  if (!(err instanceof AppApiError) || err.status !== 409) throw err;
3739
- const fresh = await getOptional(ctx, "generated-response", current.id);
3817
+ const fresh = await getOptional(ctx.api, "generated-response", current.id);
3740
3818
  const freshStatus = fresh ? fresh.data.status : void 0;
3741
3819
  if (!fresh || !isGeneratedResponseStatus(freshStatus) || freshStatus !== "ready") return null;
3742
3820
  current = fresh;
@@ -3767,14 +3845,14 @@ async function buildAvailableResponse(ctx, generatedResponse) {
3767
3845
  }
3768
3846
  async function resolveCategoryRef(ctx, categoryId) {
3769
3847
  if (!categoryId) return null;
3770
- const record = await getOptional(ctx, "category", categoryId);
3848
+ const record = await getOptional(ctx.api, "category", categoryId);
3771
3849
  if (!record) return null;
3772
3850
  const category = toCategory(record);
3773
3851
  return { _id: category.id, name: category.name };
3774
3852
  }
3775
3853
  async function resolveAgentRef(ctx, agentId) {
3776
3854
  if (!agentId) return null;
3777
- const record = await getOptional(ctx, "agent", agentId);
3855
+ const record = await getOptional(ctx.api, "agent", agentId);
3778
3856
  if (!record) return null;
3779
3857
  const agent = toAgent(record);
3780
3858
  return { _id: agent.id, name: agent.name, model_id: agent.modelId };
@@ -3840,7 +3918,7 @@ async function executeEvaluation(ctx, userId, input) {
3840
3918
  }
3841
3919
  const modelId = input.modelId;
3842
3920
  if (!modelId) throw new ctx.NonRetriableError("modelId is required");
3843
- const agentRecord2 = await getOptional(ctx, "agent", modelId);
3921
+ const agentRecord2 = await getOptional(ctx.api, "agent", modelId);
3844
3922
  if (!agentRecord2) throw new ctx.NonRetriableError(`Model not found (id=${modelId})`);
3845
3923
  const agent = toAgent(agentRecord2);
3846
3924
  const satisfied = input.satisfied;
@@ -4072,8 +4150,8 @@ function nonEmptyString(value) {
4072
4150
  // src/functions/followup-gates.ts
4073
4151
  var LABELS = {
4074
4152
  G1: "Identifiant de ticket",
4075
- G2: "Tag de p\xE9rim\xE8tre configur\xE9",
4076
- G5: "Tag de p\xE9rim\xE8tre pr\xE9sent sur le ticket",
4153
+ G2: "Tag de l\u2019application configur\xE9",
4154
+ G5: "Tag de l\u2019application pr\xE9sent sur le ticket",
4077
4155
  G6: "Aucune reprise humaine",
4078
4156
  G7: "Cat\xE9gorie r\xE9solue et opt\xE9e",
4079
4157
  G8: "Nouveau message client",
@@ -4087,7 +4165,7 @@ function evaluateTicketIdGate(ticketId) {
4087
4165
  return ticketId === null ? stopped("G1", "Aucun identifiant de ticket exploitable (il doit \xEAtre une suite de chiffres).") : passed("G1", `Ticket ${ticketId}.`);
4088
4166
  }
4089
4167
  function evaluateScopeGate(settings) {
4090
- 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.`);
4168
+ 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.`);
4091
4169
  }
4092
4170
  function skippedFollowupGates(gates) {
4093
4171
  return gates.map((gate) => ({
@@ -4140,8 +4218,8 @@ function evaluatePayloadGates(input) {
4140
4218
  return trace.done();
4141
4219
  }
4142
4220
  function scopeTagOnTicket(settings, tags) {
4143
- const scopeTag = settings.webhookScopeTag.trim();
4144
- 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.`);
4221
+ const scopeTag = settings.appScopeTag.trim();
4222
+ 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.`);
4145
4223
  }
4146
4224
  function noHumanTakeover(settings, tags) {
4147
4225
  const present = humanTakeoverTags(settings).filter((tag) => tags.includes(tag));
@@ -4528,7 +4606,7 @@ async function awaitSettledSend(ctx, id) {
4528
4606
  return status;
4529
4607
  }
4530
4608
  async function readResponseStatus(ctx, id) {
4531
- const row = await getOptional(ctx, "generated-response", id);
4609
+ const row = await getOptional(ctx.api, "generated-response", id);
4532
4610
  if (!row) return "sent";
4533
4611
  const raw = row.data.status;
4534
4612
  return isGeneratedResponseStatus(raw) ? raw : null;
@@ -4755,6 +4833,718 @@ async function triggerRun(ctx, ticketId, mode) {
4755
4833
  return { mode, ticketId, runId: run.id };
4756
4834
  }
4757
4835
 
4836
+ // src/domain/ticket-outcome.ts
4837
+ var REPORTED_OUTCOMES = [...OUTCOMES, "invalidated", "expired"];
4838
+ function emptyOutcomeCounts() {
4839
+ return Object.fromEntries(REPORTED_OUTCOMES.map((outcome) => [outcome, 0]));
4840
+ }
4841
+ var STATUS_EXITS = ["sent", "no_reply_needed", "failed", "invalidated", "expired"];
4842
+ function isStatusExit(status) {
4843
+ return STATUS_EXITS.includes(status);
4844
+ }
4845
+ function isReportedOutcome(value) {
4846
+ return REPORTED_OUTCOMES.includes(value);
4847
+ }
4848
+ function reportedOutcomeOf(status, outcome) {
4849
+ if (status === "test_draft" || status === "superseded") return null;
4850
+ if (isStatusExit(status)) return status;
4851
+ return isOutcome(outcome) ? outcome : null;
4852
+ }
4853
+ function foldOutcomeCounts(responseRows, triageRows) {
4854
+ const counts = emptyOutcomeCounts();
4855
+ for (const row of responseRows) {
4856
+ const outcome = reportedOutcomeOf(row["status"], row["outcome"]);
4857
+ if (outcome !== null) counts[outcome] += countOf(row);
4858
+ }
4859
+ for (const row of triageRows) {
4860
+ if (isUnautomatedTriage(row)) counts.escalated += countOf(row);
4861
+ }
4862
+ return counts;
4863
+ }
4864
+
4865
+ // src/domain/ticket-stats.ts
4866
+ function rateOrNull(rate) {
4867
+ return Number.isNaN(rate) ? null : rate;
4868
+ }
4869
+ function summarizeWindow({
4870
+ range,
4871
+ period,
4872
+ rows,
4873
+ categoryNames,
4874
+ compareRows
4875
+ }) {
4876
+ const totals = foldOutcomes(rows.responses, rows.triage);
4877
+ const compareTotals = compareRows === void 0 ? null : foldOutcomes(compareRows.responses, compareRows.triage);
4878
+ const daily = foldDailyOutcomes(rows.responses, rows.triage);
4879
+ return {
4880
+ period: range,
4881
+ interval: period.interval,
4882
+ // Every triage decision carries `escalated` and `status`, so this grouping partitions all of them.
4883
+ volume: sumCounts(rows.triage),
4884
+ autonomyRate: rateOrNull(autonomyRate(totals)),
4885
+ outcomes: foldOutcomeCounts(rows.responses, rows.triage),
4886
+ humanReasons: foldHumanReasons(rows.responses, rows.triage),
4887
+ byCategory: foldCategoryOutcomes(rows.categoryTriage, rows.categoryOutcomes, categoryNames),
4888
+ daily: period.interval === "day" ? fillMissingDays(daily, period.current.fromIso, period.current.toIso) : daily,
4889
+ signals: dashboardSignals(totals, compareTotals, countFailed(rows.responses))
4890
+ };
4891
+ }
4892
+ var STAT_DEFINITIONS = {
4893
+ volume: "Number of triage decisions over the period: every message the pipeline triaged, whether a draft followed or not.",
4894
+ autonomyRate: "autonomy rate = responses settled by the AI / (responses settled by the AI + requests taken over by a human); null when nothing is settled.",
4895
+ outcomes: {
4896
+ sent: "Response sent to the customer by the pipeline.",
4897
+ ready: "Draft ready to be served, with no tag (nominal path), still pending.",
4898
+ needs_human: "Verdict not sendable: draft ready, posted with the review tag, still pending.",
4899
+ guardrail_hold: "A guardrail held the draft, posted with the escalation tag, still pending.",
4900
+ awaiting_approval: "An action is waiting for a human\u2019s approval.",
4901
+ escalated: "Request escalated at triage, or triage error: no draft written.",
4902
+ triaged_only: "Triaged, with no drafting step to run.",
4903
+ no_reply_needed: "Conversation already closed: no reply needed, outside the autonomy rate.",
4904
+ failed: "Generation failed technically; the ticket went up to a human.",
4905
+ invalidated: "Draft invalidated (an agent replied before it was served): taken over by a human, whatever the outcome decided at generation.",
4906
+ expired: "Draft expired (the serving window closed without it being used): taken over by a human, whatever the outcome decided at generation."
4907
+ },
4908
+ humanReasons: {
4909
+ blocked: "Draft written but held (judge or guardrail), waiting for a human.",
4910
+ invalidated: "An agent replied before the draft was served.",
4911
+ expired: "The serving window closed on an unused draft.",
4912
+ escalatedNoDraft: "Handed over to a human at triage (escalation or triage error): no draft.",
4913
+ failed: "Generation failed technically and the ticket was escalated."
4914
+ },
4915
+ 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).`,
4916
+ 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).`,
4917
+ signals: "What is worth reading out loud, like the dashboard\u2019s \xAB Signaux \xBB (signals) block; the sentences are in French."
4918
+ };
4919
+
4920
+ // src/functions/mcp-tool.ts
4921
+ function mcpToolTrigger(description, { exposed = true } = {}) {
4922
+ return {
4923
+ type: "mcpTool",
4924
+ description,
4925
+ readOnly: true,
4926
+ exposed
4927
+ };
4928
+ }
4929
+ function mcpToolHandler(run) {
4930
+ return (ctx, input) => {
4931
+ const { api } = ctx;
4932
+ return withToolInputErrors(ctx, () => run(api, input ?? {}));
4933
+ };
4934
+ }
4935
+ async function withToolInputErrors(ctx, run) {
4936
+ try {
4937
+ return await run();
4938
+ } catch (error) {
4939
+ if (error instanceof ToolInputError) throw new ctx.NonRetriableError(error.message);
4940
+ throw error;
4941
+ }
4942
+ }
4943
+
4944
+ // src/functions/ticket-stats.ts
4945
+ var TICKET_STATS_MAX_DAYS = 90;
4946
+ 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.";
4947
+ function buildTicketStatsFunctionDef(config) {
4948
+ return {
4949
+ universalIdentifier: mcpToolIdentifierFor(config, "ticket-stats"),
4950
+ name: "ticket-stats",
4951
+ trigger: mcpToolTrigger(DESCRIPTION),
4952
+ input: [
4953
+ {
4954
+ universalIdentifier: TICKET_STATS_INPUT_FROM_UID,
4955
+ name: "from",
4956
+ type: FieldType.TEXT,
4957
+ label: "From",
4958
+ description: "First day of the period, YYYY-MM-DD, included.",
4959
+ isNullable: false
4960
+ },
4961
+ {
4962
+ universalIdentifier: TICKET_STATS_INPUT_TO_UID,
4963
+ name: "to",
4964
+ type: FieldType.TEXT,
4965
+ label: "To",
4966
+ description: `Last day of the period, YYYY-MM-DD, included. At most ${TICKET_STATS_MAX_DAYS} days after "from".`,
4967
+ isNullable: false
4968
+ },
4969
+ {
4970
+ universalIdentifier: TICKET_STATS_INPUT_COMPARE_TO_PREVIOUS_UID,
4971
+ name: "compareToPrevious",
4972
+ type: FieldType.BOOLEAN,
4973
+ label: "Compare to previous period",
4974
+ description: 'Also compute the same indicators on the period of the same length that ends the day before "from".',
4975
+ isNullable: true
4976
+ }
4977
+ ]
4978
+ };
4979
+ }
4980
+ function createTicketStatsHandler() {
4981
+ return mcpToolHandler(computeTicketStats);
4982
+ }
4983
+ async function computeTicketStats(api, input) {
4984
+ const range = dayRangeOf(input.from, input.to, TICKET_STATS_MAX_DAYS);
4985
+ assertOptionalBoolean("compareToPrevious", input.compareToPrevious);
4986
+ const [timezone, categoryNames] = await Promise.all([
4987
+ readStatsTimezone(api),
4988
+ readCategoryNames(api)
4989
+ ]);
4990
+ const period = periodBoundsOf({ range });
4991
+ const previous = input.compareToPrevious === true ? previousWindowOf(range) : void 0;
4992
+ const [rows, previousRows] = await Promise.all([
4993
+ readWindowRows(api, period, timezone),
4994
+ previous && readWindowRows(api, previous.period, timezone)
4995
+ ]);
4996
+ return {
4997
+ ...summarizeWindow({ range, period, rows, categoryNames, compareRows: previousRows }),
4998
+ timezone,
4999
+ ...previous && previousRows && {
5000
+ previous: summarizeWindow({ ...previous, rows: previousRows, categoryNames })
5001
+ },
5002
+ definitions: STAT_DEFINITIONS
5003
+ };
5004
+ }
5005
+ function previousWindowOf(range) {
5006
+ const previousRange = previousRangeOf(range);
5007
+ return { range: previousRange, period: periodBoundsOf({ range: previousRange }) };
5008
+ }
5009
+ async function readStatsTimezone(api) {
5010
+ const settings = await getSettingsOrNull(api);
5011
+ return settings?.statsTimezone || DEFAULT_STATS_TIMEZONE;
5012
+ }
5013
+ async function readWindowRows(api, period, timezone) {
5014
+ const { fromIso: gte, toIso: lte } = period.current;
5015
+ const generated = { filter: { generatedAt: { gte, lte } }, metrics: OUTCOME_METRICS };
5016
+ const decided = { filter: { decidedAt: { gte, lte } }, metrics: OUTCOME_METRICS };
5017
+ const bucketOn = (field) => ({ field, interval: period.interval, tz: timezone });
5018
+ const [responses, triage, categoryTriage, categoryOutcomes] = await Promise.all([
5019
+ api.aggregate("generated-response", {
5020
+ ...generated,
5021
+ groupBy: OUTCOME_GROUP_BY,
5022
+ bucket: bucketOn("generatedAt")
5023
+ }),
5024
+ api.aggregate("triage-decision", {
5025
+ ...decided,
5026
+ groupBy: TRIAGE_HANDOFF_GROUP_BY,
5027
+ bucket: bucketOn("decidedAt")
5028
+ }),
5029
+ api.aggregate("triage-decision", { ...decided, groupBy: CATEGORY_TRIAGE_GROUP_BY }),
5030
+ api.aggregate("generated-response", { ...generated, groupBy: CATEGORY_OUTCOME_GROUP_BY })
5031
+ ]);
5032
+ return { responses, triage, categoryTriage, categoryOutcomes };
5033
+ }
5034
+ var LIST_TICKETS_MAX_DAYS = 31;
5035
+ var LIST_TICKETS_PAGE_SIZE = 50;
5036
+ var MAX_SCANNED_BATCHES = 8;
5037
+ var InvalidCursorError = class extends ToolInputError {
5038
+ constructor(reason = "The cursor is not one this tool issued") {
5039
+ super(`${reason}; start again without a cursor.`);
5040
+ this.name = "InvalidCursorError";
5041
+ }
5042
+ };
5043
+ 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.";
5044
+ function buildListTicketsFunctionDef(config) {
5045
+ return {
5046
+ universalIdentifier: mcpToolIdentifierFor(config, "list-tickets"),
5047
+ name: "list-tickets",
5048
+ trigger: mcpToolTrigger(DESCRIPTION2),
5049
+ input: [
5050
+ {
5051
+ universalIdentifier: LIST_TICKETS_INPUT_FROM_UID,
5052
+ name: "from",
5053
+ type: FieldType.TEXT,
5054
+ label: "From",
5055
+ description: "First day of the period, YYYY-MM-DD, included.",
5056
+ isNullable: false
5057
+ },
5058
+ {
5059
+ universalIdentifier: LIST_TICKETS_INPUT_TO_UID,
5060
+ name: "to",
5061
+ type: FieldType.TEXT,
5062
+ label: "To",
5063
+ description: `Last day of the period, YYYY-MM-DD, included. At most ${LIST_TICKETS_MAX_DAYS} days after "from".`,
5064
+ isNullable: false
5065
+ },
5066
+ {
5067
+ universalIdentifier: LIST_TICKETS_INPUT_CATEGORY_ID_UID,
5068
+ name: "categoryId",
5069
+ type: FieldType.TEXT,
5070
+ label: "Category id",
5071
+ description: "Only the tickets triaged into this category (an id from list_categories).",
5072
+ isNullable: true
5073
+ },
5074
+ {
5075
+ universalIdentifier: LIST_TICKETS_INPUT_OUTCOME_UID,
5076
+ name: "outcome",
5077
+ type: FieldType.SELECT,
5078
+ label: "Outcome",
5079
+ description: 'Only the tickets that took this exit. "escalated" covers tickets handed over at triage, which have no response.',
5080
+ isNullable: true,
5081
+ options: [...REPORTED_OUTCOMES]
5082
+ },
5083
+ {
5084
+ universalIdentifier: LIST_TICKETS_INPUT_ESCALATED_UID,
5085
+ name: "escalated",
5086
+ type: FieldType.BOOLEAN,
5087
+ label: "Escalated",
5088
+ description: "Only the tickets the triage decision did (true) or did not (false) escalate.",
5089
+ isNullable: true
5090
+ },
5091
+ {
5092
+ universalIdentifier: LIST_TICKETS_INPUT_CHANNEL_UID,
5093
+ name: "channel",
5094
+ type: FieldType.TEXT,
5095
+ label: "Channel",
5096
+ 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.",
5097
+ isNullable: true
5098
+ },
5099
+ {
5100
+ universalIdentifier: LIST_TICKETS_INPUT_STATUS_UID,
5101
+ name: "status",
5102
+ type: FieldType.SELECT,
5103
+ label: "Status",
5104
+ description: "Only the tickets whose response is in this status.",
5105
+ isNullable: true,
5106
+ options: [...GENERATED_RESPONSE_STATUSES]
5107
+ },
5108
+ {
5109
+ universalIdentifier: LIST_TICKETS_INPUT_CURSOR_UID,
5110
+ name: "cursor",
5111
+ type: FieldType.TEXT,
5112
+ label: "Cursor",
5113
+ description: "The nextCursor of the previous page. Leave empty for the first page.",
5114
+ isNullable: true
5115
+ }
5116
+ ]
5117
+ };
5118
+ }
5119
+ function createListTicketsHandler() {
5120
+ return mcpToolHandler(listTickets);
5121
+ }
5122
+ function scopeOf(input) {
5123
+ const { from, to, categoryId, outcome, escalated, channel, status } = input;
5124
+ return JSON.stringify([
5125
+ from,
5126
+ to,
5127
+ categoryId || null,
5128
+ outcome || null,
5129
+ escalated ?? null,
5130
+ channel || null,
5131
+ status || null
5132
+ ]);
5133
+ }
5134
+ function encodeCursor(position) {
5135
+ return Buffer.from(JSON.stringify(position)).toString("base64url");
5136
+ }
5137
+ function parseCursor(cursor) {
5138
+ let decoded;
5139
+ try {
5140
+ decoded = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
5141
+ } catch {
5142
+ throw new InvalidCursorError();
5143
+ }
5144
+ if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
5145
+ throw new InvalidCursorError();
5146
+ }
5147
+ return decoded;
5148
+ }
5149
+ function startOfScan(input) {
5150
+ const scope = scopeOf(input);
5151
+ if (!input.cursor) return { after: null, skip: 0, scope };
5152
+ const { after = null, skip, scope: issuedFor } = parseCursor(input.cursor);
5153
+ const wellFormed = (after === null || typeof after === "string") && typeof skip === "number" && Number.isInteger(skip) && skip >= 0 && typeof issuedFor === "string";
5154
+ if (!wellFormed) throw new InvalidCursorError();
5155
+ if (issuedFor !== scope)
5156
+ throw new InvalidCursorError("The cursor was issued for another period or other filters");
5157
+ return { after, skip, scope };
5158
+ }
5159
+ function assertValidFilters(input) {
5160
+ assertOptionalBoolean("escalated", input.escalated);
5161
+ if (input.outcome && !isReportedOutcome(input.outcome)) {
5162
+ throw new ToolInputError(
5163
+ `"outcome" must be one of ${REPORTED_OUTCOMES.join(", ")}; got ${JSON.stringify(input.outcome)}.`
5164
+ );
5165
+ }
5166
+ if (input.status && !isGeneratedResponseStatus(input.status)) {
5167
+ throw new ToolInputError(
5168
+ `"status" must be one of ${GENERATED_RESPONSE_STATUSES.join(", ")}; got ${JSON.stringify(input.status)}.`
5169
+ );
5170
+ }
5171
+ }
5172
+ async function listTickets(api, input) {
5173
+ const range = dayRangeOf(input.from, input.to, LIST_TICKETS_MAX_DAYS);
5174
+ assertValidFilters(input);
5175
+ let position = startOfScan(input);
5176
+ const window = periodBoundsOf({ range }).current;
5177
+ const filter = decisionFilter(window, input);
5178
+ const readBatch = (after) => api.list("triage-decision", {
5179
+ filter,
5180
+ sort: NEWEST_DECISION_FIRST,
5181
+ limit: LIST_TICKETS_PAGE_SIZE,
5182
+ ...after === null ? {} : { cursor: after }
5183
+ });
5184
+ const [categoryNames, firstBatch] = await Promise.all([
5185
+ readCategoryNames(api),
5186
+ readBatch(position.after)
5187
+ ]);
5188
+ let page = firstBatch;
5189
+ const rows = [];
5190
+ for (let scanned = 1; ; scanned++) {
5191
+ const batch = page.items.slice(position.skip).map(toTriageDecision);
5192
+ const candidates = await readTicketsOf(api, batch, window.toIso);
5193
+ for (const [index, candidate] of candidates.entries()) {
5194
+ if (candidate === null) continue;
5195
+ const row = toTicketRow(candidate.decision, candidate.response, categoryNames);
5196
+ if (!matchesResponseFilters(row, input)) continue;
5197
+ rows.push(row);
5198
+ if (rows.length === LIST_TICKETS_PAGE_SIZE) {
5199
+ return { rows, nextCursor: cursorAfter(page, position, position.skip + index + 1) };
5200
+ }
5201
+ }
5202
+ if (page.nextCursor === null) return { rows, nextCursor: null };
5203
+ position = { ...position, after: page.nextCursor, skip: 0 };
5204
+ if (scanned === MAX_SCANNED_BATCHES) return { rows, nextCursor: encodeCursor(position) };
5205
+ page = await readBatch(position.after);
5206
+ }
5207
+ }
5208
+ function cursorAfter(page, position, consumed) {
5209
+ if (consumed < page.items.length) return encodeCursor({ ...position, skip: consumed });
5210
+ return page.nextCursor === null ? null : encodeCursor({ ...position, after: page.nextCursor, skip: 0 });
5211
+ }
5212
+ function decisionFilter(window, input) {
5213
+ return {
5214
+ decidedAt: { gte: window.fromIso, lte: window.toIso },
5215
+ ...input.categoryId ? { categoryId: input.categoryId } : {},
5216
+ ...typeof input.escalated === "boolean" ? { escalated: input.escalated } : {}
5217
+ };
5218
+ }
5219
+ async function readTicketsOf(api, batch, windowEndIso) {
5220
+ const [newestDecidedAt, responses] = await Promise.all([
5221
+ readNewestDecisionTimes(api, batch, windowEndIso),
5222
+ latestResponsesByTicket(
5223
+ api,
5224
+ batch.map((decision) => decision.ticketId)
5225
+ )
5226
+ ]);
5227
+ return batch.map(
5228
+ (decision) => isSuperseded(decision, newestDecidedAt) ? null : { decision, response: responses.get(decision.ticketId) ?? null }
5229
+ );
5230
+ }
5231
+ async function readNewestDecisionTimes(api, batch, windowEndIso) {
5232
+ const dated = batch.filter((decision) => decision.decidedAt !== null);
5233
+ if (dated.length === 0) return /* @__PURE__ */ new Map();
5234
+ const oldest = dated.reduce((a, b) => instantOf(b) < instantOf(a) ? b : a);
5235
+ const newest = await newestPerTicket(api, {
5236
+ objectKey: "triage-decision",
5237
+ ticketIds: dated.map((decision) => decision.ticketId),
5238
+ filter: { decidedAt: { gt: oldest.decidedAt, lte: windowEndIso } },
5239
+ sort: NEWEST_DECISION_FIRST
5240
+ });
5241
+ return new Map(
5242
+ [...newest].map(([ticketId, record]) => [ticketId, instantOf(toTriageDecision(record))])
5243
+ );
5244
+ }
5245
+ function isSuperseded(decision, newestDecidedAt) {
5246
+ return (newestDecidedAt.get(decision.ticketId) ?? -Infinity) > instantOf(decision);
5247
+ }
5248
+ function instantOf(decision) {
5249
+ return Date.parse(decision.decidedAt ?? "");
5250
+ }
5251
+ function toTicketRow(decision, response, categoryNames) {
5252
+ return {
5253
+ ticketId: decision.ticketId,
5254
+ ticketUrl: decision.ticketUrl,
5255
+ decidedAt: decision.decidedAt,
5256
+ categoryId: decision.categoryId,
5257
+ category: decision.categoryId === null ? null : categoryNames.get(decision.categoryId) ?? null,
5258
+ confidence: decision.confidence,
5259
+ escalated: decision.escalated,
5260
+ outcome: outcomeOf(decision, response),
5261
+ status: response?.status ?? null,
5262
+ channel: response === null ? null : response.sourceChannel ?? response.channel,
5263
+ sentAt: response?.sentAt ?? null,
5264
+ ineligibleReason: response?.ineligibleReason ?? null,
5265
+ guardrailHits: response?.guardrailHits ?? [],
5266
+ verdict: response?.verdict ? { verdict: response.verdict.verdict, confidence: response.verdict.confidence } : null,
5267
+ origin: decision.origin
5268
+ };
5269
+ }
5270
+ function outcomeOf(decision, response) {
5271
+ const answeredSince = response !== null && (response.generatedAt ?? "") >= (decision.decidedAt ?? "");
5272
+ if (isUnautomatedTriage(decision) && !answeredSince) return "escalated";
5273
+ return response === null ? null : reportedOutcomeOf(response.status, response.outcome);
5274
+ }
5275
+ function matchesResponseFilters(row, input) {
5276
+ return (!input.outcome || row.outcome === input.outcome) && (!input.channel || row.channel === input.channel) && (!input.status || row.status === input.status);
5277
+ }
5278
+
5279
+ // src/domain/trace-refs.ts
5280
+ function toTraceRefs(traceId, observationIds) {
5281
+ if (!traceId && observationIds.length === 0) return [];
5282
+ return [{ ...traceId ? { traceId } : {}, observationIds: [...observationIds] }];
5283
+ }
5284
+
5285
+ // src/functions/list-agents.ts
5286
+ 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.";
5287
+ function buildListAgentsFunctionDef(config) {
5288
+ return {
5289
+ universalIdentifier: mcpToolIdentifierFor(config, "list-agents"),
5290
+ name: "list-agents",
5291
+ trigger: mcpToolTrigger(DESCRIPTION3)
5292
+ };
5293
+ }
5294
+ function createListAgentsHandler() {
5295
+ return (ctx) => describeAgents(ctx.api);
5296
+ }
5297
+ async function describeAgents(api) {
5298
+ return (await listAgents(api)).map(toAgentSummary);
5299
+ }
5300
+ function toAgentSummary(agent) {
5301
+ return {
5302
+ id: agent.id,
5303
+ name: agent.name,
5304
+ promptName: agent.promptName,
5305
+ promptLabel: agent.promptLabel,
5306
+ promptVersion: agent.promptVersion,
5307
+ modelId: agent.modelId
5308
+ };
5309
+ }
5310
+
5311
+ // src/functions/list-categories.ts
5312
+ 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.";
5313
+ function buildListCategoriesFunctionDef(config) {
5314
+ return {
5315
+ universalIdentifier: mcpToolIdentifierFor(config, "list-categories"),
5316
+ name: "list-categories",
5317
+ trigger: mcpToolTrigger(DESCRIPTION4)
5318
+ };
5319
+ }
5320
+ function createListCategoriesHandler() {
5321
+ return (ctx) => describeCategories(ctx.api);
5322
+ }
5323
+ async function describeCategories(api) {
5324
+ const [categories, groupsPage] = await Promise.all([
5325
+ listCategories(api),
5326
+ api.list("category-group", { limit: CATEGORY_PAGE_SIZE })
5327
+ ]);
5328
+ const groups = new Map(groupsPage.items.map(toCategoryGroup).map((group) => [group.id, group]));
5329
+ return categories.map((category) => {
5330
+ const group = groups.get(category.groupId ?? "") ?? null;
5331
+ return { category, group, groupOrder: group?.order ?? Number.NEGATIVE_INFINITY };
5332
+ }).sort(compareByGroupThenCategory).map(({ category, group }) => toCategorySummary(category, group));
5333
+ }
5334
+ function toCategorySummary(category, group) {
5335
+ return {
5336
+ ...toCategoryFields(category),
5337
+ agentId: category.agentId,
5338
+ group: group === null ? null : { id: group.id, name: group.name }
5339
+ };
5340
+ }
5341
+ function toCategoryFields(category) {
5342
+ return {
5343
+ id: category.id,
5344
+ name: category.name,
5345
+ tagName: category.tagName,
5346
+ description: category.description,
5347
+ examples: category.examples,
5348
+ autoReplyEnabled: category.autoReplyEnabled,
5349
+ fastResponseEnabled: category.fastResponseEnabled,
5350
+ followupAutoReplyEnabled: category.followupAutoReplyEnabled,
5351
+ followupFastResponseEnabled: category.followupFastResponseEnabled
5352
+ };
5353
+ }
5354
+
5355
+ // src/functions/explain-ticket.ts
5356
+ var HISTORY_LIMIT = 20;
5357
+ var NEWEST_CORRECTION_FIRST = JSON.stringify([{ field: "capturedAt", direction: "desc" }]);
5358
+ 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.";
5359
+ function buildExplainTicketFunctionDef(config) {
5360
+ return {
5361
+ universalIdentifier: mcpToolIdentifierFor(config, "explain-ticket"),
5362
+ name: "explain-ticket",
5363
+ trigger: mcpToolTrigger(DESCRIPTION5),
5364
+ input: [
5365
+ {
5366
+ universalIdentifier: EXPLAIN_TICKET_INPUT_TICKET_ID_UID,
5367
+ name: "ticketId",
5368
+ type: FieldType.TEXT,
5369
+ label: "Ticket id",
5370
+ description: "The helpdesk ticket id, as listed by list_tickets.",
5371
+ isNullable: false
5372
+ }
5373
+ ]
5374
+ };
5375
+ }
5376
+ function createExplainTicketHandler(config) {
5377
+ return mcpToolHandler((api, input) => explainTicket(api, config, input));
5378
+ }
5379
+ async function explainTicket(api, config, input) {
5380
+ const { ticketId } = input;
5381
+ if (typeof ticketId !== "string" || ticketId === "") {
5382
+ throw new ToolInputError('"ticketId" must be a non-empty string.');
5383
+ }
5384
+ const [decision, responses, comparisons, settings] = await Promise.all([
5385
+ readNewestDecision(api, ticketId),
5386
+ listTicketResponses(api, ticketId, HISTORY_LIMIT),
5387
+ readCorrections(api, ticketId),
5388
+ getSettingsOrNull(api)
5389
+ ]);
5390
+ if (decision === null) return { found: false };
5391
+ const latest = responses[0];
5392
+ const categoryRead = readCategory(api, decision.categoryId);
5393
+ const agentId = latest?.agentId ?? (await categoryRead)?.agentId ?? null;
5394
+ const [category, agent] = await Promise.all([categoryRead, readAgent(api, agentId)]);
5395
+ return {
5396
+ found: true,
5397
+ ticketId,
5398
+ ticketUrl: decision.ticketUrl,
5399
+ triage: toTriageSection(decision, settings, config),
5400
+ responses: responses.map(toResponseSection),
5401
+ correction: comparisons[0] === void 0 ? null : toCorrectionSection(comparisons[0]),
5402
+ category: category === null ? null : toCategoryFields(category),
5403
+ agent,
5404
+ timeline: buildTimelineSteps({
5405
+ decision,
5406
+ job: latest,
5407
+ comparisons,
5408
+ conversation: persistedConversationOf(latest, comparisons[0]),
5409
+ policy: settings === null ? null : toDeliveryPolicy(settings),
5410
+ category
5411
+ })
5412
+ };
5413
+ }
5414
+ async function readNewestDecision(api, ticketId) {
5415
+ const page = await api.list("triage-decision", {
5416
+ filter: { ticketId },
5417
+ sort: NEWEST_DECISION_FIRST,
5418
+ limit: 1
5419
+ });
5420
+ return page.items[0] === void 0 ? null : toTriageDecision(page.items[0]);
5421
+ }
5422
+ async function readCorrections(api, ticketId) {
5423
+ const page = await api.list("response-comparison", {
5424
+ filter: { ticketId },
5425
+ sort: NEWEST_CORRECTION_FIRST,
5426
+ limit: HISTORY_LIMIT
5427
+ });
5428
+ return page.items.map(toResponseComparison);
5429
+ }
5430
+ async function readCategory(api, categoryId) {
5431
+ const record = await getOptional(api, "category", categoryId);
5432
+ return record === null ? null : toCategory(record);
5433
+ }
5434
+ async function readAgent(api, agentId) {
5435
+ const record = await getOptional(api, "agent", agentId);
5436
+ if (record === null) return null;
5437
+ const { modelId: _modelId, ...section } = toAgentSummary(toAgent(record));
5438
+ return section;
5439
+ }
5440
+ function persistedConversationOf(job, correction) {
5441
+ if (job !== void 0 && job.tracedInput.length > 0) {
5442
+ return { systemPrompt: job.tracedInput.find((m) => m.role === "system")?.content ?? null };
5443
+ }
5444
+ return correction !== void 0 && correction.conversationMessages.length > 0 ? { systemPrompt: null } : null;
5445
+ }
5446
+ function toTriageSection(decision, settings, config) {
5447
+ const traceRefs = toTraceRefs(decision.langfuseTraceId, decision.langfuseObservationIds);
5448
+ return {
5449
+ decidedAt: decision.decidedAt,
5450
+ origin: decision.origin,
5451
+ status: decision.status,
5452
+ error: decision.error,
5453
+ categoryId: decision.categoryId,
5454
+ tag: decision.tag,
5455
+ confidence: decision.confidence,
5456
+ reasoning: decision.reasoning,
5457
+ conversationOver: decision.conversationOver,
5458
+ escalated: decision.escalated,
5459
+ escalationConfidence: decision.escalationConfidence,
5460
+ escalationReasoning: decision.escalationReasoning,
5461
+ prompts: triagePromptsOf(decision.origin, settings, config),
5462
+ traceRefs,
5463
+ traceAvailable: traceRefs.length > 0
5464
+ };
5465
+ }
5466
+ function triagePromptsOf(origin, settings, config) {
5467
+ if (origin === "followup") return { triage: null, escalation: null };
5468
+ const nodes = settings?.nodes;
5469
+ const bindingOf = (node, derivedName) => node === null ? null : promptRefFor(node, derivedName);
5470
+ return {
5471
+ triage: bindingOf(nodes?.triage, resolvePromptName("triage", config)),
5472
+ escalation: bindingOf(nodes?.escalate, resolvePromptName("escalation", config))
5473
+ };
5474
+ }
5475
+ function toResponseSection(response) {
5476
+ return {
5477
+ id: response.id,
5478
+ status: response.status,
5479
+ outcome: response.outcome,
5480
+ generatedAt: response.generatedAt,
5481
+ sentAt: response.sentAt,
5482
+ verdict: response.verdict,
5483
+ guardrailHits: response.guardrailHits,
5484
+ autoSendDecision: response.autoSendDecision,
5485
+ ineligibleReason: response.ineligibleReason,
5486
+ promptName: response.promptName,
5487
+ promptVersion: response.promptVersion,
5488
+ traceRefs: [
5489
+ ...toTraceRefs(
5490
+ response.langfuseTraceId,
5491
+ response.langfuseObservationId ? [response.langfuseObservationId] : []
5492
+ ),
5493
+ ...evaluationTraceRefs(response.evaluationObservationId)
5494
+ ],
5495
+ sentText: response.status === "sent" ? response.responseText : null,
5496
+ tracedInput: response.tracedInput.filter((message) => message.role !== "system")
5497
+ };
5498
+ }
5499
+ function evaluationTraceRefs(observationId) {
5500
+ return observationId ? [{ observationIds: [observationId], withoutMessages: true }] : [];
5501
+ }
5502
+ function toCorrectionSection(correction) {
5503
+ return {
5504
+ capturedAt: correction.capturedAt,
5505
+ generatedText: correction.generatedText,
5506
+ sentText: correction.sentText,
5507
+ diff: correction.diff
5508
+ };
5509
+ }
5510
+
5511
+ // src/functions/prompt-scope.ts
5512
+ 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.";
5513
+ function buildPromptScopeFunctionDef(config) {
5514
+ return {
5515
+ universalIdentifier: mcpToolIdentifierFor(config, "prompt-scope"),
5516
+ name: "prompt-scope",
5517
+ trigger: mcpToolTrigger(DESCRIPTION6, { exposed: false })
5518
+ };
5519
+ }
5520
+ function createPromptScopeHandler(config) {
5521
+ return (ctx) => promptScope(ctx.api, config);
5522
+ }
5523
+ async function promptScope(api, config) {
5524
+ const [agents, settings] = await Promise.all([
5525
+ listAgents(api),
5526
+ getSettingsOrNull(api)
5527
+ ]);
5528
+ const candidates = [
5529
+ ...PROMPT_SLOTS.map((slot) => resolvePromptName(slot, config)),
5530
+ ...agents.map((agent) => agent.promptName),
5531
+ ...settings === null ? [] : promptNamesChosenIn(settings)
5532
+ ];
5533
+ return { names: [...new Set(candidates.filter(isExactName))] };
5534
+ }
5535
+ function promptNamesChosenIn(settings) {
5536
+ const nodes = Object.values(settings.nodes ?? {});
5537
+ const stepPrompts = nodes.map((node) => node?.prompt?.name);
5538
+ return [
5539
+ ...stepPrompts,
5540
+ settings.channelPromptEmail || DEFAULT_CHANNEL_PROMPT_EMAIL,
5541
+ settings.channelPromptWhatsapp || DEFAULT_CHANNEL_PROMPT_WHATSAPP
5542
+ ];
5543
+ }
5544
+ function isExactName(name) {
5545
+ return typeof name === "string" && name !== "" && !name.includes("*");
5546
+ }
5547
+
4758
5548
  // src/pages/manifest.ts
4759
5549
  function pageIdentifierFor(config, key) {
4760
5550
  const id = config.identifiers[key];
@@ -4895,6 +5685,40 @@ var FUNCTION_ASSEMBLY = [
4895
5685
  key: "test-gorgias-webhook",
4896
5686
  build: buildTestGorgiasWebhookFunctionDef,
4897
5687
  createHandler: createTestGorgiasWebhookHandler
5688
+ },
5689
+ // The read-only MCP tools (spec §5.3). Their identifiers are optional —
5690
+ // `mcpToolIdentifierFor` derives them — so they sit outside
5691
+ // FUNCTION_IDENTIFIER_KEYS and this assembly covers that list PLUS the MCP tools below.
5692
+ {
5693
+ key: "ticket-stats",
5694
+ build: buildTicketStatsFunctionDef,
5695
+ createHandler: () => createTicketStatsHandler()
5696
+ },
5697
+ {
5698
+ key: "list-tickets",
5699
+ build: buildListTicketsFunctionDef,
5700
+ createHandler: () => createListTicketsHandler()
5701
+ },
5702
+ {
5703
+ key: "explain-ticket",
5704
+ build: buildExplainTicketFunctionDef,
5705
+ createHandler: createExplainTicketHandler
5706
+ },
5707
+ {
5708
+ key: "list-categories",
5709
+ build: buildListCategoriesFunctionDef,
5710
+ createHandler: () => createListCategoriesHandler()
5711
+ },
5712
+ {
5713
+ key: "list-agents",
5714
+ build: buildListAgentsFunctionDef,
5715
+ createHandler: () => createListAgentsHandler()
5716
+ },
5717
+ // Internal (`exposed: false`): the OS asks it which prompt names belong to this app (D5).
5718
+ {
5719
+ key: "prompt-scope",
5720
+ build: buildPromptScopeFunctionDef,
5721
+ createHandler: createPromptScopeHandler
4898
5722
  }
4899
5723
  ];
4900
5724
  function buildPromptsAllowlist() {