@apotech-os/support-kit 9.0.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-MHRKUDEZ.js → chunk-KEPXRZ7R.js} +597 -52
- package/dist/chunk-KEPXRZ7R.js.map +1 -0
- package/dist/index.cjs +1495 -84
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +15 -13
- package/dist/index.d.ts +15 -13
- package/dist/index.js +863 -37
- package/dist/index.js.map +1 -1
- package/dist/ui/index.cjs +267 -171
- package/dist/ui/index.cjs.map +1 -1
- package/dist/ui/index.js +186 -527
- package/dist/ui/index.js.map +1 -1
- package/package.json +5 -5
- package/dist/chunk-MHRKUDEZ.js.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -609,6 +609,7 @@ var fetchContext = async (_state, deps) => {
|
|
|
609
609
|
};
|
|
610
610
|
|
|
611
611
|
// src/graph/nodes/triage.ts
|
|
612
|
+
var TRIAGE_LABEL = "triage";
|
|
612
613
|
var TRIAGE_SCHEMA = {
|
|
613
614
|
type: "object",
|
|
614
615
|
properties: {
|
|
@@ -659,12 +660,11 @@ ${message}`);
|
|
|
659
660
|
const last = lastCustomerMessage(conversation);
|
|
660
661
|
if (last && last !== message) userParts.push(`## Dernier message client
|
|
661
662
|
${last}`);
|
|
662
|
-
const
|
|
663
|
-
|
|
664
|
-
});
|
|
663
|
+
const promptVariables = { categories: renderCategories(deps.categories) };
|
|
664
|
+
const resolvedPrompt = await deps.ports.prompt.resolve(profile.prompts.triage, promptVariables);
|
|
665
665
|
try {
|
|
666
666
|
const result = await deps.ports.llm.complete({
|
|
667
|
-
label:
|
|
667
|
+
label: TRIAGE_LABEL,
|
|
668
668
|
// The resolved Langfuse prompt's own model config WINS over the
|
|
669
669
|
// profile's fallback (I16) — see `PromptPort.resolve`'s doc.
|
|
670
670
|
model: resolvedPrompt.config?.model ?? node.model,
|
|
@@ -675,7 +675,8 @@ ${last}`);
|
|
|
675
675
|
],
|
|
676
676
|
responseSchema: TRIAGE_SCHEMA,
|
|
677
677
|
signal: deps.budget.signal,
|
|
678
|
-
promptRef: { name: resolvedPrompt.name, version: resolvedPrompt.version, resolve: false }
|
|
678
|
+
promptRef: { name: resolvedPrompt.name, version: resolvedPrompt.version, resolve: false },
|
|
679
|
+
promptVariables
|
|
679
680
|
});
|
|
680
681
|
deps.budget.charge("triage", result.usage, { usd: 0, pricingMissing: true });
|
|
681
682
|
const parsed = JSON.parse(result.text ?? "");
|
|
@@ -697,6 +698,7 @@ ${last}`);
|
|
|
697
698
|
};
|
|
698
699
|
|
|
699
700
|
// src/graph/nodes/escalate.ts
|
|
701
|
+
var ESCALATION_LABEL = "escalation";
|
|
700
702
|
var ESCALATION_SCHEMA = {
|
|
701
703
|
type: "object",
|
|
702
704
|
properties: {
|
|
@@ -722,7 +724,7 @@ ${conversation.customer.orderContext}`);
|
|
|
722
724
|
userParts.push(`## Message \xE0 classifier
|
|
723
725
|
${message}`);
|
|
724
726
|
const result = await deps.ports.llm.complete({
|
|
725
|
-
label:
|
|
727
|
+
label: ESCALATION_LABEL,
|
|
726
728
|
model: resolvedPrompt.config?.model ?? node.model,
|
|
727
729
|
reasoning: node.reasoning,
|
|
728
730
|
messages: [
|
|
@@ -1631,6 +1633,8 @@ var TRIAGE_DECISION_FIELD_RUN_ID_UID = "a1e244d6-8f4f-4cd5-8794-14f6e419b64e";
|
|
|
1631
1633
|
var TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID = "449f1960-be88-4e42-96ee-43cd90f36f4c";
|
|
1632
1634
|
var TRIAGE_DECISION_FIELD_TICKET_URL_UID = "727a775a-ea93-460f-9d08-16b05424c453";
|
|
1633
1635
|
var TRIAGE_DECISION_FIELD_ORIGIN_UID = "8bde8d93-7d06-4cb5-8a88-2d6db562af05";
|
|
1636
|
+
var TRIAGE_DECISION_FIELD_LANGFUSE_TRACE_ID_UID = "39fcbbd2-2d18-48db-b096-589f8072f854";
|
|
1637
|
+
var TRIAGE_DECISION_FIELD_LANGFUSE_OBSERVATION_IDS_UID = "15451c73-9f6d-4899-96ca-8fd3f5eb93db";
|
|
1634
1638
|
var TRIAGE_DECISION_INDEX_TICKET_ID_UID = "20433066-e029-4faf-8033-c205cf5de0fb";
|
|
1635
1639
|
var TRIAGE_DECISION_INDEX_DECIDED_AT_UID = "94040f6d-1d55-498f-8db8-abe5aed17c0a";
|
|
1636
1640
|
var TRIAGE_DECISION_INDEX_ESCALATED_UID = "1c0ac4c3-9a48-4858-bbbf-0c689bbb5be5";
|
|
@@ -2102,6 +2106,22 @@ function buildTriageDecisionRecord(slug) {
|
|
|
2102
2106
|
description: ORIGIN_DESCRIPTION,
|
|
2103
2107
|
isNullable: false,
|
|
2104
2108
|
defaultValue: DEFAULT_DECISION_ORIGIN
|
|
2109
|
+
},
|
|
2110
|
+
{
|
|
2111
|
+
universalIdentifier: TRIAGE_DECISION_FIELD_LANGFUSE_TRACE_ID_UID,
|
|
2112
|
+
name: "langfuseTraceId",
|
|
2113
|
+
type: appKit.FieldType.TEXT,
|
|
2114
|
+
label: "Langfuse trace id",
|
|
2115
|
+
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.",
|
|
2116
|
+
isNullable: true
|
|
2117
|
+
},
|
|
2118
|
+
{
|
|
2119
|
+
universalIdentifier: TRIAGE_DECISION_FIELD_LANGFUSE_OBSERVATION_IDS_UID,
|
|
2120
|
+
name: "langfuseObservationIds",
|
|
2121
|
+
type: appKit.FieldType.JSON,
|
|
2122
|
+
label: "Langfuse observation ids",
|
|
2123
|
+
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.",
|
|
2124
|
+
isNullable: true
|
|
2105
2125
|
}
|
|
2106
2126
|
],
|
|
2107
2127
|
indexes: [
|
|
@@ -2794,6 +2814,7 @@ function buildSupportKitRecords(slug) {
|
|
|
2794
2814
|
}
|
|
2795
2815
|
|
|
2796
2816
|
// src/settings/fields.ts
|
|
2817
|
+
var DEFAULT_STATS_TIMEZONE = "Europe/Paris";
|
|
2797
2818
|
var SUPPORT_KIT_SETTINGS_FIELDS = [
|
|
2798
2819
|
// Source
|
|
2799
2820
|
// NO `gorgiasConnectionId`: every Gorgias call in this kit is
|
|
@@ -2831,26 +2852,20 @@ var SUPPORT_KIT_SETTINGS_FIELDS = [
|
|
|
2831
2852
|
{ key: "autoRepliedTag", type: "string", label: "Auto-replied tag", default: "wai/auto-replied" },
|
|
2832
2853
|
{ key: "needsReviewTag", type: "string", label: "Review-before-send tag", default: "wai/escalated" },
|
|
2833
2854
|
{ key: "followupTag", type: "string", label: "Followup tag", default: "wai/human-required" },
|
|
2834
|
-
// The app's
|
|
2835
|
-
//
|
|
2836
|
-
//
|
|
2837
|
-
//
|
|
2838
|
-
//
|
|
2839
|
-
//
|
|
2840
|
-
//
|
|
2841
|
-
//
|
|
2842
|
-
|
|
2843
|
-
//
|
|
2844
|
-
//
|
|
2845
|
-
//
|
|
2846
|
-
//
|
|
2847
|
-
|
|
2848
|
-
// freshly-installed app answer the other audience's tickets. Two apps of
|
|
2849
|
-
// the same account MUST configure distinct values;
|
|
2850
|
-
// - empty therefore means "process no follow-up message at all", which is
|
|
2851
|
-
// both the fail-closed default and the feature's kill switch.
|
|
2852
|
-
// Not named `followupTag`: that key is taken (`wai/human-required`).
|
|
2853
|
-
{ key: "webhookScopeTag", type: "string", label: "Webhook scope tag", default: "" },
|
|
2855
|
+
// The app's ticket tag — ONE tag, three readers:
|
|
2856
|
+
// - the triage stamps it on every ticket it sees, in the same call as the
|
|
2857
|
+
// tags above (`adapters/gorgias-tags.ts`);
|
|
2858
|
+
// - the follow-up webhook answers a SUBSEQUENT customer message only on a
|
|
2859
|
+
// ticket that carries it (`functions/followup-gates.ts`): two support apps
|
|
2860
|
+
// installed on ONE Gorgias account each receive every
|
|
2861
|
+
// `ticket-message-created` event, and this tag is what separates them;
|
|
2862
|
+
// - the Gorgias extension picks this app's default agent on a ticket that
|
|
2863
|
+
// carries it (`functions/ext-models.ts`).
|
|
2864
|
+
// Every other audit tag ships the same default in every app — `handledTag`
|
|
2865
|
+
// is `wai/triaged` everywhere — so none of them can answer "whose ticket is
|
|
2866
|
+
// this?". No usable default for the same reason: a mark two apps have in
|
|
2867
|
+
// common marks nothing. `validateSettings` refuses to run until it is set.
|
|
2868
|
+
{ key: "appScopeTag", type: "string", label: "App ticket tag", default: "" },
|
|
2854
2869
|
// Sending
|
|
2855
2870
|
{ key: "autoSendEnabled", type: "boolean", label: "Auto-send enabled", default: false },
|
|
2856
2871
|
{ key: "senderEmail", type: "string", label: "Sender email", default: "" },
|
|
@@ -2909,7 +2924,7 @@ var SUPPORT_KIT_SETTINGS_FIELDS = [
|
|
|
2909
2924
|
// one-field deviation from §3.6, recorded for the spec owner.
|
|
2910
2925
|
{ key: "renameFrom", type: "string", label: "Rename \u2014 subject pattern to match", default: "" },
|
|
2911
2926
|
{ key: "renameTo", type: "string", label: "Rename \u2014 replacement subject", default: "" },
|
|
2912
|
-
{ key: "statsTimezone", type: "string", label: "Stats timezone (IANA)", default:
|
|
2927
|
+
{ key: "statsTimezone", type: "string", label: "Stats timezone (IANA)", default: DEFAULT_STATS_TIMEZONE }
|
|
2913
2928
|
];
|
|
2914
2929
|
|
|
2915
2930
|
// src/settings/validate.ts
|
|
@@ -2921,6 +2936,12 @@ function validateSettings(settings) {
|
|
|
2921
2936
|
message: "sourceViewId is required \u2014 pick the Gorgias view this app owns."
|
|
2922
2937
|
});
|
|
2923
2938
|
}
|
|
2939
|
+
if (!isNonEmptyString(settings.appScopeTag) || settings.appScopeTag.trim() === "") {
|
|
2940
|
+
issues.push({
|
|
2941
|
+
key: "appScopeTag",
|
|
2942
|
+
message: "appScopeTag is required \u2014 set the tag that marks this app's tickets."
|
|
2943
|
+
});
|
|
2944
|
+
}
|
|
2924
2945
|
if (!isConfiguredNode(settings.nodes)) {
|
|
2925
2946
|
issues.push({
|
|
2926
2947
|
key: "nodes",
|
|
@@ -2951,8 +2972,8 @@ var STEPS_REQUIRING_PROMPT = ["triage", "escalate", "evaluate"];
|
|
|
2951
2972
|
function stepsMissingPrompt(nodes) {
|
|
2952
2973
|
if (typeof nodes !== "object" || nodes === null) return [];
|
|
2953
2974
|
const byStep = nodes;
|
|
2954
|
-
return STEPS_REQUIRING_PROMPT.filter((
|
|
2955
|
-
const node = byStep[
|
|
2975
|
+
return STEPS_REQUIRING_PROMPT.filter((step3) => {
|
|
2976
|
+
const node = byStep[step3];
|
|
2956
2977
|
if (typeof node !== "object" || node === null) return false;
|
|
2957
2978
|
return !isNonEmptyString(promptNameOf(node));
|
|
2958
2979
|
});
|
|
@@ -2973,17 +2994,16 @@ var AUDIT_TAG_KEYS = ["unknownTag", "handledTag", "escalationTag", "autoRepliedT
|
|
|
2973
2994
|
function settingsWarnings(settings) {
|
|
2974
2995
|
const warnings = [];
|
|
2975
2996
|
const appScopeTag = trimmed(settings.appScopeTag);
|
|
2976
|
-
const webhookScopeTag = trimmed(settings.webhookScopeTag);
|
|
2977
2997
|
const collidesWith = (keys) => appScopeTag ? keys.filter((key) => trimmed(settings[key]) === appScopeTag) : [];
|
|
2978
2998
|
if (collidesWith(HUMAN_TAKEOVER_KEYS).length > 0) {
|
|
2979
2999
|
warnings.push({
|
|
2980
3000
|
key: "appScopeTagVetoesFollowups",
|
|
2981
|
-
message: "Le tag
|
|
3001
|
+
message: "Le tag des tickets de l\u2019application est l\u2019un des tags de reprise humaine (escalade, relecture, suivi) : le webhook de suivi consid\xE9rera que chaque ticket tri\xE9 a \xE9t\xE9 repris par un humain et ne r\xE9pondra plus \xE0 aucun message suivant."
|
|
2982
3002
|
});
|
|
2983
3003
|
} else if (collidesWith(AUDIT_TAG_KEYS).length > 0) {
|
|
2984
3004
|
warnings.push({
|
|
2985
3005
|
key: "appScopeTagCollision",
|
|
2986
|
-
message: "Le tag
|
|
3006
|
+
message: "Le tag des tickets de l\u2019application est l\u2019un des autres tags d\u2019audit, que toutes les apps posent avec la m\xEAme valeur par d\xE9faut : il ne distingue donc pas cette app d\u2019une autre install\xE9e sur le m\xEAme compte Gorgias."
|
|
2987
3007
|
});
|
|
2988
3008
|
}
|
|
2989
3009
|
if (settings.autoSendEnabled === true && Array.isArray(settings.autoSendChannels) && settings.autoSendChannels.length === 0) {
|
|
@@ -2992,12 +3012,6 @@ function settingsWarnings(settings) {
|
|
|
2992
3012
|
message: "L\u2019envoi automatique est actif mais aucun canal n\u2019est coch\xE9 : aucune r\xE9ponse ne peut partir. Cochez au moins un canal, ou coupez l\u2019envoi automatique."
|
|
2993
3013
|
});
|
|
2994
3014
|
}
|
|
2995
|
-
if (appScopeTag && webhookScopeTag && appScopeTag !== webhookScopeTag) {
|
|
2996
|
-
warnings.push({
|
|
2997
|
-
key: "scopeTagMismatch",
|
|
2998
|
-
message: "Le tag de p\xE9rim\xE8tre du webhook de suivi n\u2019est pas celui que cette app pose sur ses tickets : le webhook ne r\xE9pondra sur aucun ticket tri\xE9 ici."
|
|
2999
|
-
});
|
|
3000
|
-
}
|
|
3001
3015
|
return warnings;
|
|
3002
3016
|
}
|
|
3003
3017
|
function trimmed(value) {
|
|
@@ -3127,6 +3141,9 @@ function identifierFor(config, key) {
|
|
|
3127
3141
|
}
|
|
3128
3142
|
return id;
|
|
3129
3143
|
}
|
|
3144
|
+
function mcpToolIdentifierFor(config, key) {
|
|
3145
|
+
return config.identifiers[key] ?? deriveUid(`${config.slug}:function:${key}`);
|
|
3146
|
+
}
|
|
3130
3147
|
|
|
3131
3148
|
// src/adapters/gorgias-tags.ts
|
|
3132
3149
|
function dedupeTagNames(tags) {
|
|
@@ -3262,6 +3279,7 @@ function createPlatformLlmPort(api, trace) {
|
|
|
3262
3279
|
// its own to carry the new field; it already carries whatever shape
|
|
3263
3280
|
// `CompletionRequest.promptRef` has.
|
|
3264
3281
|
...req.promptRef ? { promptRef: req.promptRef } : {},
|
|
3282
|
+
...req.promptVariables ? { promptVariables: req.promptVariables } : {},
|
|
3265
3283
|
...runTrace ? { trace: runTrace } : {}
|
|
3266
3284
|
});
|
|
3267
3285
|
return {
|
|
@@ -3405,15 +3423,23 @@ function createRecordingLlmPort(llm) {
|
|
|
3405
3423
|
};
|
|
3406
3424
|
}
|
|
3407
3425
|
var DEFAULT_MAX_TOOL_CALLS2 = 5;
|
|
3408
|
-
async function getOptional(
|
|
3426
|
+
async function getOptional(api, objectKey, id) {
|
|
3409
3427
|
if (!id) return null;
|
|
3410
3428
|
try {
|
|
3411
|
-
return await
|
|
3429
|
+
return await api.get(objectKey, id);
|
|
3412
3430
|
} catch (err) {
|
|
3413
3431
|
if (err instanceof appKit.AppApiError && err.status === 404) return null;
|
|
3414
3432
|
throw err;
|
|
3415
3433
|
}
|
|
3416
3434
|
}
|
|
3435
|
+
async function getSettingsOrNull(api) {
|
|
3436
|
+
try {
|
|
3437
|
+
return await api.settings.get();
|
|
3438
|
+
} catch (err) {
|
|
3439
|
+
if (err instanceof appKit.AppApiError) return null;
|
|
3440
|
+
throw err;
|
|
3441
|
+
}
|
|
3442
|
+
}
|
|
3417
3443
|
function buildTicketPorts(ctx, trace) {
|
|
3418
3444
|
return {
|
|
3419
3445
|
conversation: createGorgiasConversationPort(ctx.api),
|
|
@@ -3589,6 +3615,30 @@ function toCategoryGroup(record) {
|
|
|
3589
3615
|
order: data.order ?? 0
|
|
3590
3616
|
};
|
|
3591
3617
|
}
|
|
3618
|
+
function toTriageDecision(record) {
|
|
3619
|
+
const data = record.data;
|
|
3620
|
+
return {
|
|
3621
|
+
id: record.id,
|
|
3622
|
+
ticketId: data.ticketId ?? "",
|
|
3623
|
+
ticketUrl: data.ticketUrl ?? null,
|
|
3624
|
+
decidedAt: data.decidedAt ?? null,
|
|
3625
|
+
categoryId: data.categoryId ?? null,
|
|
3626
|
+
tag: data.tag ?? null,
|
|
3627
|
+
confidence: data.confidence ?? null,
|
|
3628
|
+
reasoning: data.reasoning ?? null,
|
|
3629
|
+
conversationOver: data.conversationOver ?? false,
|
|
3630
|
+
escalated: data.escalated ?? false,
|
|
3631
|
+
escalationConfidence: data.escalationConfidence ?? null,
|
|
3632
|
+
escalationReasoning: data.escalationReasoning ?? null,
|
|
3633
|
+
status: data.status ?? null,
|
|
3634
|
+
error: data.error ?? null,
|
|
3635
|
+
runId: data.runId ?? null,
|
|
3636
|
+
subjectRenamed: data.subjectRenamed ?? false,
|
|
3637
|
+
origin: toDecisionOrigin(data.origin),
|
|
3638
|
+
langfuseTraceId: data.langfuseTraceId ?? null,
|
|
3639
|
+
langfuseObservationIds: Array.isArray(data.langfuseObservationIds) ? data.langfuseObservationIds.filter((id) => typeof id === "string" && id !== "") : []
|
|
3640
|
+
};
|
|
3641
|
+
}
|
|
3592
3642
|
function toVerdict(raw) {
|
|
3593
3643
|
if (raw === null || typeof raw !== "object") return null;
|
|
3594
3644
|
const data = raw;
|
|
@@ -3598,6 +3648,11 @@ function toVerdict(raw) {
|
|
|
3598
3648
|
const status = data.status === "success" || data.status === "error" ? data.status : "error";
|
|
3599
3649
|
return { verdict, confidence, reason, status };
|
|
3600
3650
|
}
|
|
3651
|
+
function toEvaluationObservationId(raw) {
|
|
3652
|
+
if (raw === null || typeof raw !== "object") return null;
|
|
3653
|
+
const observationId = raw.observationId;
|
|
3654
|
+
return typeof observationId === "string" && observationId !== "" ? observationId : null;
|
|
3655
|
+
}
|
|
3601
3656
|
function toGeneratedResponse(record) {
|
|
3602
3657
|
const data = record.data;
|
|
3603
3658
|
return {
|
|
@@ -3620,6 +3675,7 @@ function toGeneratedResponse(record) {
|
|
|
3620
3675
|
tracedInput: Array.isArray(data.tracedInput) ? data.tracedInput : [],
|
|
3621
3676
|
sources: Array.isArray(data.sources) ? data.sources : [],
|
|
3622
3677
|
verdict: toVerdict(data.verdict),
|
|
3678
|
+
evaluationObservationId: toEvaluationObservationId(data.verdict),
|
|
3623
3679
|
guardrailHits: data.guardrailHits ?? [],
|
|
3624
3680
|
guardrailHitsReconstructedAt: data.guardrailHitsReconstructedAt ?? null,
|
|
3625
3681
|
outcome: isOutcome(data.outcome) ? data.outcome : null,
|
|
@@ -3634,10 +3690,79 @@ function toGeneratedResponse(record) {
|
|
|
3634
3690
|
origin: toDecisionOrigin(data.origin)
|
|
3635
3691
|
};
|
|
3636
3692
|
}
|
|
3693
|
+
function toResponseComparison(record) {
|
|
3694
|
+
const data = record.data;
|
|
3695
|
+
return {
|
|
3696
|
+
id: record.id,
|
|
3697
|
+
generatedText: data.generatedText ?? null,
|
|
3698
|
+
sentText: data.sentText ?? "",
|
|
3699
|
+
capturedAt: data.capturedAt ?? "",
|
|
3700
|
+
ticketId: data.ticketId ?? null,
|
|
3701
|
+
ticketUrl: data.ticketUrl ?? "",
|
|
3702
|
+
agentId: data.agentId ?? null,
|
|
3703
|
+
langfuseTraceId: data.langfuseTraceId ?? null,
|
|
3704
|
+
langfuseObservationId: data.langfuseObservationId ?? null,
|
|
3705
|
+
promptName: data.promptName ?? null,
|
|
3706
|
+
promptVersion: data.promptVersion ?? null,
|
|
3707
|
+
conversationMessages: data.conversationMessages ?? [],
|
|
3708
|
+
diff: data.diff ?? null
|
|
3709
|
+
};
|
|
3710
|
+
}
|
|
3711
|
+
var CATEGORY_PAGE_SIZE = 500;
|
|
3712
|
+
var AGENT_PAGE_SIZE = 500;
|
|
3713
|
+
function compareByGroupThenCategory(a, b) {
|
|
3714
|
+
if (a.groupOrder !== b.groupOrder) return a.groupOrder < b.groupOrder ? -1 : 1;
|
|
3715
|
+
return a.category.order - b.category.order || a.category.name.localeCompare(b.category.name);
|
|
3716
|
+
}
|
|
3717
|
+
async function listAgents(api) {
|
|
3718
|
+
const page = await api.list("agent", { limit: AGENT_PAGE_SIZE });
|
|
3719
|
+
return page.items.map(toAgent);
|
|
3720
|
+
}
|
|
3637
3721
|
async function listCategories(api) {
|
|
3638
|
-
const page = await api.list("category", { limit:
|
|
3722
|
+
const page = await api.list("category", { limit: CATEGORY_PAGE_SIZE });
|
|
3639
3723
|
return page.items.map(toCategory);
|
|
3640
3724
|
}
|
|
3725
|
+
var NEWEST_DECISION_FIRST = JSON.stringify([{ field: "decidedAt", direction: "desc" }]);
|
|
3726
|
+
var NEWEST_RESPONSE_FIRST = JSON.stringify([{ field: "generatedAt", direction: "desc" }]);
|
|
3727
|
+
var ANSWERS_ONLY = { status: { neq: "test_draft" } };
|
|
3728
|
+
async function listTicketResponses(api, ticketId, limit) {
|
|
3729
|
+
const page = await api.list("generated-response", {
|
|
3730
|
+
filter: { ticketId, ...ANSWERS_ONLY },
|
|
3731
|
+
sort: NEWEST_RESPONSE_FIRST,
|
|
3732
|
+
limit
|
|
3733
|
+
});
|
|
3734
|
+
return page.items.map(toGeneratedResponse);
|
|
3735
|
+
}
|
|
3736
|
+
async function latestResponsesByTicket(api, ticketIds) {
|
|
3737
|
+
const newest = await newestPerTicket(api, {
|
|
3738
|
+
objectKey: "generated-response",
|
|
3739
|
+
ticketIds,
|
|
3740
|
+
filter: ANSWERS_ONLY,
|
|
3741
|
+
sort: NEWEST_RESPONSE_FIRST
|
|
3742
|
+
});
|
|
3743
|
+
return new Map([...newest].map(([ticketId, record]) => [ticketId, toGeneratedResponse(record)]));
|
|
3744
|
+
}
|
|
3745
|
+
var NEWEST_PER_TICKET_READ_SIZE = 200;
|
|
3746
|
+
async function newestPerTicket(api, { objectKey, ticketIds, filter, sort }) {
|
|
3747
|
+
const wanted = [...new Set(ticketIds)];
|
|
3748
|
+
const newest = /* @__PURE__ */ new Map();
|
|
3749
|
+
if (wanted.length === 0) return newest;
|
|
3750
|
+
let cursor = null;
|
|
3751
|
+
do {
|
|
3752
|
+
const page = await api.list(objectKey, {
|
|
3753
|
+
filter: { ...filter, ticketId: { in: wanted } },
|
|
3754
|
+
sort,
|
|
3755
|
+
limit: NEWEST_PER_TICKET_READ_SIZE,
|
|
3756
|
+
...cursor === null ? {} : { cursor }
|
|
3757
|
+
});
|
|
3758
|
+
for (const record of page.items) {
|
|
3759
|
+
const ticketId = String(record.data["ticketId"]);
|
|
3760
|
+
if (!newest.has(ticketId)) newest.set(ticketId, record);
|
|
3761
|
+
}
|
|
3762
|
+
cursor = page.nextCursor;
|
|
3763
|
+
} while (cursor !== null && newest.size < wanted.length);
|
|
3764
|
+
return newest;
|
|
3765
|
+
}
|
|
3641
3766
|
function findCategoryByTag(categories, tag) {
|
|
3642
3767
|
return categories.find((c) => c.tagName === tag) ?? null;
|
|
3643
3768
|
}
|
|
@@ -3675,20 +3800,33 @@ function draftRebinder(api, categories, config) {
|
|
|
3675
3800
|
};
|
|
3676
3801
|
}
|
|
3677
3802
|
function buildPromptsTable(config, draft2, nodes) {
|
|
3678
|
-
const DEFAULT_LABEL = "production";
|
|
3679
|
-
const refFor = (node, derivedName, fallback2) => ({
|
|
3680
|
-
name: node?.prompt?.name ?? derivedName,
|
|
3681
|
-
label: node?.prompt?.label ?? DEFAULT_LABEL,
|
|
3682
|
-
...fallback2 ? { fallback: fallback2 } : {}
|
|
3683
|
-
});
|
|
3684
3803
|
const prompts = config.defaults?.prompts;
|
|
3685
3804
|
return {
|
|
3686
|
-
triage:
|
|
3687
|
-
escalate:
|
|
3688
|
-
|
|
3805
|
+
triage: promptRefFor(nodes.triage, resolvePromptName("triage", config), prompts?.triage),
|
|
3806
|
+
escalate: promptRefFor(
|
|
3807
|
+
nodes.escalate,
|
|
3808
|
+
resolvePromptName("escalation", config),
|
|
3809
|
+
prompts?.escalation
|
|
3810
|
+
),
|
|
3811
|
+
evaluate: promptRefFor(
|
|
3812
|
+
nodes.evaluate,
|
|
3813
|
+
resolvePromptName("evaluation", config),
|
|
3814
|
+
prompts?.evaluation
|
|
3815
|
+
),
|
|
3689
3816
|
draft: draft2
|
|
3690
3817
|
};
|
|
3691
3818
|
}
|
|
3819
|
+
function promptRefFor(node, derivedName, fallback2) {
|
|
3820
|
+
return {
|
|
3821
|
+
name: node?.prompt?.name ?? derivedName,
|
|
3822
|
+
label: node?.prompt?.label ?? "production",
|
|
3823
|
+
...fallback2 ? { fallback: fallback2 } : {}
|
|
3824
|
+
};
|
|
3825
|
+
}
|
|
3826
|
+
async function readCategoryNames(api) {
|
|
3827
|
+
const categories = await listCategories(api);
|
|
3828
|
+
return new Map(categories.map((category) => [category.id, category.name]));
|
|
3829
|
+
}
|
|
3692
3830
|
|
|
3693
3831
|
// src/functions/process-response.ts
|
|
3694
3832
|
function autoReplyEnabledFor(origin, category) {
|
|
@@ -3736,7 +3874,7 @@ async function finalizeNonSent(ctx, id, ticketId, toStatus, extra) {
|
|
|
3736
3874
|
}
|
|
3737
3875
|
}
|
|
3738
3876
|
async function respondToPendingResponse(ctx, config, recordId, options = {}) {
|
|
3739
|
-
const record = await getOptional(ctx, "generated-response", recordId);
|
|
3877
|
+
const record = await getOptional(ctx.api, "generated-response", recordId);
|
|
3740
3878
|
if (!record) {
|
|
3741
3879
|
ctx.logger.info(`respond: generated-response ${recordId} no longer exists, skipping`);
|
|
3742
3880
|
return null;
|
|
@@ -3753,7 +3891,7 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
|
|
|
3753
3891
|
}
|
|
3754
3892
|
const ticketId = data.ticketId;
|
|
3755
3893
|
const ref = { id: ticketId, channel: "gorgias" };
|
|
3756
|
-
const decision = await getOptional(ctx, "triage-decision", data.triageDecisionId ?? null);
|
|
3894
|
+
const decision = await getOptional(ctx.api, "triage-decision", data.triageDecisionId ?? null);
|
|
3757
3895
|
if (!decision) {
|
|
3758
3896
|
ctx.logger.error(`respond: generated-response ${recordId} has no resolvable triage-decision, marking failed`);
|
|
3759
3897
|
await finalizeNonSent(ctx, recordId, ticketId, "failed", { error: "triage-decision not found" });
|
|
@@ -3761,10 +3899,10 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
|
|
|
3761
3899
|
}
|
|
3762
3900
|
const classification = classificationFromDecision(decision);
|
|
3763
3901
|
const escalated = decision.data.escalated === true;
|
|
3764
|
-
const categoryRecord = await getOptional(ctx, "category", data.categoryId ?? null);
|
|
3902
|
+
const categoryRecord = await getOptional(ctx.api, "category", data.categoryId ?? null);
|
|
3765
3903
|
const category = categoryRecord ? toCategory(categoryRecord) : null;
|
|
3766
3904
|
const origin = toDecisionOrigin(data.origin);
|
|
3767
|
-
const agentRecord2 = data.agentId ? await getOptional(ctx, "agent", data.agentId) : null;
|
|
3905
|
+
const agentRecord2 = data.agentId ? await getOptional(ctx.api, "agent", data.agentId) : null;
|
|
3768
3906
|
const agent = agentRecord2 ? toAgent(agentRecord2) : await resolveDraftAgent(ctx.api, null);
|
|
3769
3907
|
const profile = applyFollowupSendPolicy(
|
|
3770
3908
|
settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes)),
|
|
@@ -3930,6 +4068,39 @@ function ticketUrlFor(base, ticketId) {
|
|
|
3930
4068
|
return base ? `${base}/${encodeURIComponent(ticketId)}` : null;
|
|
3931
4069
|
}
|
|
3932
4070
|
|
|
4071
|
+
// src/functions/ticket-trace.ts
|
|
4072
|
+
function buildTicketTrace({ slug, ticketId, ticketUrl }) {
|
|
4073
|
+
return {
|
|
4074
|
+
sessionId: ticketId,
|
|
4075
|
+
tags: [`app:${slug}`],
|
|
4076
|
+
metadata: {
|
|
4077
|
+
ticket_id: ticketId,
|
|
4078
|
+
...ticketUrl ? { conversation_url: ticketUrl } : {},
|
|
4079
|
+
origin: "triage"
|
|
4080
|
+
}
|
|
4081
|
+
};
|
|
4082
|
+
}
|
|
4083
|
+
function recordTriageTraces(llm) {
|
|
4084
|
+
const results = /* @__PURE__ */ new Map();
|
|
4085
|
+
return {
|
|
4086
|
+
llm: {
|
|
4087
|
+
async complete(req) {
|
|
4088
|
+
const result = await llm.complete(req);
|
|
4089
|
+
results.set(req.label, result);
|
|
4090
|
+
return result;
|
|
4091
|
+
}
|
|
4092
|
+
},
|
|
4093
|
+
fields() {
|
|
4094
|
+
const traceId = results.get(TRIAGE_LABEL)?.traceId;
|
|
4095
|
+
const observationIds = [TRIAGE_LABEL, ESCALATION_LABEL].map((label) => results.get(label)?.observationId).filter((id) => Boolean(id));
|
|
4096
|
+
return {
|
|
4097
|
+
...traceId ? { langfuseTraceId: traceId } : {},
|
|
4098
|
+
...observationIds.length > 0 ? { langfuseObservationIds: observationIds } : {}
|
|
4099
|
+
};
|
|
4100
|
+
}
|
|
4101
|
+
};
|
|
4102
|
+
}
|
|
4103
|
+
|
|
3933
4104
|
// src/functions/triage-tick.ts
|
|
3934
4105
|
function buildTriageTickFunctionDef(config) {
|
|
3935
4106
|
return {
|
|
@@ -4109,11 +4280,14 @@ async function processOneTicket(ctx, ref, deps) {
|
|
|
4109
4280
|
}
|
|
4110
4281
|
}
|
|
4111
4282
|
const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS2 });
|
|
4283
|
+
const ticketUrl = ticketUrlFor(ticketUrlBase, ref.id);
|
|
4284
|
+
const ticketTrace = buildTicketTrace({ slug: config.slug, ticketId: ref.id, ticketUrl });
|
|
4285
|
+
const traces = recordTriageTraces(createPlatformLlmPort(ctx.api, ticketTrace));
|
|
4112
4286
|
const state = await runTicket(
|
|
4113
4287
|
{
|
|
4114
4288
|
ref,
|
|
4115
4289
|
profile,
|
|
4116
|
-
ports: { ...ports },
|
|
4290
|
+
ports: { ...ports, llm: traces.llm },
|
|
4117
4291
|
toolContext: createNoToolContext(),
|
|
4118
4292
|
budget,
|
|
4119
4293
|
// Unknown until triage runs — no node reached in the `until:'triage'`
|
|
@@ -4131,7 +4305,7 @@ async function processOneTicket(ctx, ref, deps) {
|
|
|
4131
4305
|
const category = findCategoryByTag(categories, classification.category);
|
|
4132
4306
|
const decision = await ctx.api.create("triage-decision", {
|
|
4133
4307
|
ticketId: ref.id,
|
|
4134
|
-
ticketUrl
|
|
4308
|
+
ticketUrl,
|
|
4135
4309
|
decidedAt: ports.clock.now(),
|
|
4136
4310
|
categoryId: category?.id ?? null,
|
|
4137
4311
|
tag: classification.category,
|
|
@@ -4142,7 +4316,8 @@ async function processOneTicket(ctx, ref, deps) {
|
|
|
4142
4316
|
status: "ok",
|
|
4143
4317
|
runId,
|
|
4144
4318
|
subjectRenamed,
|
|
4145
|
-
origin: "triage"
|
|
4319
|
+
origin: "triage",
|
|
4320
|
+
...traces.fields()
|
|
4146
4321
|
});
|
|
4147
4322
|
await ports.state.record(ref, classification, profile.audit);
|
|
4148
4323
|
if (state.escalated) await flagEscalation(ctx, ref, profile.audit.escalationTag, ports);
|
|
@@ -4300,7 +4475,7 @@ async function handleApprovalHandler(ctx, config) {
|
|
|
4300
4475
|
ctx.logger.debug(`handle-approval: key "${payload.key}" is not a generated-response approval, ignoring`);
|
|
4301
4476
|
return;
|
|
4302
4477
|
}
|
|
4303
|
-
const record = await getOptional(ctx, "generated-response", id);
|
|
4478
|
+
const record = await getOptional(ctx.api, "generated-response", id);
|
|
4304
4479
|
if (!record) {
|
|
4305
4480
|
ctx.logger.info(`handle-approval: generated-response ${id} no longer exists, skipping`);
|
|
4306
4481
|
return;
|
|
@@ -4464,6 +4639,18 @@ var SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID = "2f5d6cbb-1c69-4a76-9d8f-
|
|
|
4464
4639
|
var INVALIDATE_RESPONSE_INPUT_GENERATED_RESPONSE_ID_UID = "9748baf5-97be-4a22-940d-46ef2f16a175";
|
|
4465
4640
|
var TEST_GORGIAS_WEBHOOK_INPUT_TICKET_ID_UID = "2cfcbfc1-77f1-4081-8fba-5f3a51c29e62";
|
|
4466
4641
|
var TEST_GORGIAS_WEBHOOK_INPUT_MODE_UID = "e75c5ec9-1205-492f-87df-a84ec12753f8";
|
|
4642
|
+
var TICKET_STATS_INPUT_FROM_UID = "15f48662-43f1-4a94-9e77-6aa34c2c8e41";
|
|
4643
|
+
var TICKET_STATS_INPUT_TO_UID = "2a50ec38-8d95-4a69-bc55-c21322088fe9";
|
|
4644
|
+
var TICKET_STATS_INPUT_COMPARE_TO_PREVIOUS_UID = "cb007f80-f00a-4f8f-a46c-61010a6c0609";
|
|
4645
|
+
var LIST_TICKETS_INPUT_FROM_UID = "dfbc9f3a-4ac9-4587-a9f1-47ea3fbb1d88";
|
|
4646
|
+
var LIST_TICKETS_INPUT_TO_UID = "c51c82ee-7d65-4b49-aef1-2a82983fa4eb";
|
|
4647
|
+
var LIST_TICKETS_INPUT_CATEGORY_ID_UID = "418e65f9-91e6-4d55-9dbd-03cb920207a6";
|
|
4648
|
+
var LIST_TICKETS_INPUT_OUTCOME_UID = "893cf56d-0f36-4701-9482-3de285c2108d";
|
|
4649
|
+
var LIST_TICKETS_INPUT_ESCALATED_UID = "eb154697-418d-4159-8050-503d214175b0";
|
|
4650
|
+
var LIST_TICKETS_INPUT_CHANNEL_UID = "a03a94ef-ccc6-48d9-a088-656406bb1585";
|
|
4651
|
+
var LIST_TICKETS_INPUT_STATUS_UID = "e2fdddae-0464-496d-9526-bb017c544f09";
|
|
4652
|
+
var LIST_TICKETS_INPUT_CURSOR_UID = "dfba83d4-8a6b-4e8b-bcfb-f3fc3cf663eb";
|
|
4653
|
+
var EXPLAIN_TICKET_INPUT_TICKET_ID_UID = "7b0e5d3a-42c1-4f6e-9a58-0d1c6f3e8b24";
|
|
4467
4654
|
|
|
4468
4655
|
// src/functions/run-triage-now.ts
|
|
4469
4656
|
var TRIAGE_RUN_REQUESTED_EVENT = "triage.run.requested";
|
|
@@ -4578,7 +4765,7 @@ var REFUSALS = {
|
|
|
4578
4765
|
async function invalidateResponseHandler(ctx, input) {
|
|
4579
4766
|
const id = input?.generatedResponseId?.trim();
|
|
4580
4767
|
if (!id) throw new ctx.NonRetriableError("generatedResponseId is required");
|
|
4581
|
-
const record = await getOptional(ctx, "generated-response", id);
|
|
4768
|
+
const record = await getOptional(ctx.api, "generated-response", id);
|
|
4582
4769
|
if (!record) throw new ctx.NonRetriableError(`R\xE9ponse g\xE9n\xE9r\xE9e introuvable (${id}).`);
|
|
4583
4770
|
const data = record.data;
|
|
4584
4771
|
const status = String(data.status ?? "");
|
|
@@ -4723,7 +4910,7 @@ async function runGraphDryRun({ base, api, resume, rebindDraft }) {
|
|
|
4723
4910
|
...recordingEvaluator ? { evaluator: recordingEvaluator.port } : {}
|
|
4724
4911
|
},
|
|
4725
4912
|
send: recordingSend.send,
|
|
4726
|
-
trace: (
|
|
4913
|
+
trace: (step3) => steps.push(step3)
|
|
4727
4914
|
};
|
|
4728
4915
|
let result = null;
|
|
4729
4916
|
let error;
|
|
@@ -5446,7 +5633,6 @@ async function syncAgentPromptSnapshotHandler(ctx, input) {
|
|
|
5446
5633
|
|
|
5447
5634
|
// src/functions/ext-models.ts
|
|
5448
5635
|
var TOKEN_APPROXIMATION_CHARS_PER_TOKEN = 4;
|
|
5449
|
-
var AGENT_PAGE_SIZE = 500;
|
|
5450
5636
|
function buildExtModelsFunctionDef(config) {
|
|
5451
5637
|
return {
|
|
5452
5638
|
universalIdentifier: identifierFor(config, "ext-models"),
|
|
@@ -5458,7 +5644,12 @@ function createExtModelsHandler() {
|
|
|
5458
5644
|
return (ctx) => extModelsHandler(ctx);
|
|
5459
5645
|
}
|
|
5460
5646
|
async function extModelsHandler(ctx) {
|
|
5461
|
-
const page = await
|
|
5647
|
+
const [page, settings] = await Promise.all([
|
|
5648
|
+
ctx.api.list("agent", { limit: AGENT_PAGE_SIZE }),
|
|
5649
|
+
ctx.api.settings.get()
|
|
5650
|
+
]);
|
|
5651
|
+
const appTag = trimmedSetting(settings.appScopeTag);
|
|
5652
|
+
const sourceViewId = trimmedSetting(settings.sourceViewId);
|
|
5462
5653
|
if (page.items.length >= AGENT_PAGE_SIZE) {
|
|
5463
5654
|
ctx.logger.warn(`ext-models: "agent" page came back full at ${page.items.length} rows \u2014 some may be silently missing from the response.`);
|
|
5464
5655
|
}
|
|
@@ -5471,17 +5662,20 @@ async function extModelsHandler(ctx) {
|
|
|
5471
5662
|
model_id: agent.modelId,
|
|
5472
5663
|
system_prompt: systemPrompt,
|
|
5473
5664
|
system_prompt_token_count: approximateTokenCount(systemPrompt),
|
|
5474
|
-
status: agent.status
|
|
5665
|
+
status: agent.status,
|
|
5666
|
+
app_tag: appTag,
|
|
5667
|
+
source_view_id: sourceViewId
|
|
5475
5668
|
};
|
|
5476
5669
|
});
|
|
5477
5670
|
}
|
|
5671
|
+
function trimmedSetting(value) {
|
|
5672
|
+
return typeof value === "string" ? value.trim() : "";
|
|
5673
|
+
}
|
|
5478
5674
|
function approximateTokenCount(text) {
|
|
5479
5675
|
return Math.ceil(text.length / TOKEN_APPROXIMATION_CHARS_PER_TOKEN);
|
|
5480
5676
|
}
|
|
5481
5677
|
|
|
5482
5678
|
// src/functions/ext-categories.ts
|
|
5483
|
-
var CATEGORY_PAGE_SIZE = 500;
|
|
5484
|
-
var AGENT_PAGE_SIZE2 = 500;
|
|
5485
5679
|
function buildExtCategoriesFunctionDef(config) {
|
|
5486
5680
|
return {
|
|
5487
5681
|
universalIdentifier: identifierFor(config, "ext-categories"),
|
|
@@ -5502,10 +5696,10 @@ async function extCategoriesHandler(ctx) {
|
|
|
5502
5696
|
// gateway's shared `FAN_OUT_BUDGET_MS`, so N+1 sequential round trips
|
|
5503
5697
|
// risk a slow tenant's whole categories response silently dropping out
|
|
5504
5698
|
// of the union on budget exhaustion.
|
|
5505
|
-
ctx.api.list("agent", { limit:
|
|
5699
|
+
ctx.api.list("agent", { limit: AGENT_PAGE_SIZE })
|
|
5506
5700
|
]);
|
|
5507
5701
|
warnIfTruncated(ctx, "category", categoriesPage.items.length, CATEGORY_PAGE_SIZE);
|
|
5508
|
-
warnIfTruncated(ctx, "agent", agentsPage.items.length,
|
|
5702
|
+
warnIfTruncated(ctx, "agent", agentsPage.items.length, AGENT_PAGE_SIZE);
|
|
5509
5703
|
const groupOrderById = new Map(groupsPage.items.map(toCategoryGroup).map((g) => [g.id, g.order]));
|
|
5510
5704
|
const agentById = new Map(agentsPage.items.map((record) => [record.id, toAgent(record)]));
|
|
5511
5705
|
const entries = [];
|
|
@@ -5517,11 +5711,7 @@ async function extCategoriesHandler(ctx) {
|
|
|
5517
5711
|
const groupOrder = category.groupId ? groupOrderById.get(category.groupId) ?? -Infinity : -Infinity;
|
|
5518
5712
|
entries.push({ category, agent, groupOrder });
|
|
5519
5713
|
}
|
|
5520
|
-
entries.sort(
|
|
5521
|
-
if (a.groupOrder !== b.groupOrder) return a.groupOrder - b.groupOrder;
|
|
5522
|
-
if (a.category.order !== b.category.order) return a.category.order - b.category.order;
|
|
5523
|
-
return a.category.name.localeCompare(b.category.name);
|
|
5524
|
-
});
|
|
5714
|
+
entries.sort(compareByGroupThenCategory);
|
|
5525
5715
|
return entries.map(({ category, agent }, index) => ({
|
|
5526
5716
|
_id: category.id,
|
|
5527
5717
|
name: category.name,
|
|
@@ -5541,7 +5731,7 @@ function warnIfTruncated(ctx, objectKey, itemCount, pageSize) {
|
|
|
5541
5731
|
// src/functions/ownership-probe.ts
|
|
5542
5732
|
async function ownsAgent(ctx, id) {
|
|
5543
5733
|
if (!id) return null;
|
|
5544
|
-
const record = await getOptional(ctx, "agent", id);
|
|
5734
|
+
const record = await getOptional(ctx.api, "agent", id);
|
|
5545
5735
|
return record ? { claimed: true } : null;
|
|
5546
5736
|
}
|
|
5547
5737
|
|
|
@@ -5704,7 +5894,7 @@ function toWireChatMessage(raw) {
|
|
|
5704
5894
|
}
|
|
5705
5895
|
async function resolveAgent(ctx, modelId) {
|
|
5706
5896
|
if (modelId) {
|
|
5707
|
-
const record2 = await getOptional(ctx, "agent", modelId);
|
|
5897
|
+
const record2 = await getOptional(ctx.api, "agent", modelId);
|
|
5708
5898
|
if (!record2) throw new ctx.NonRetriableError(`Model not found (id=${modelId})`);
|
|
5709
5899
|
return toAgent(record2);
|
|
5710
5900
|
}
|
|
@@ -5819,7 +6009,7 @@ async function serveHit(ctx, row, userId, now) {
|
|
|
5819
6009
|
);
|
|
5820
6010
|
} catch (err) {
|
|
5821
6011
|
if (!(err instanceof appKit.AppApiError) || err.status !== 409) throw err;
|
|
5822
|
-
const fresh = await getOptional(ctx, "generated-response", current.id);
|
|
6012
|
+
const fresh = await getOptional(ctx.api, "generated-response", current.id);
|
|
5823
6013
|
const freshStatus = fresh ? fresh.data.status : void 0;
|
|
5824
6014
|
if (!fresh || !isGeneratedResponseStatus(freshStatus) || freshStatus !== "ready") return null;
|
|
5825
6015
|
current = fresh;
|
|
@@ -5850,14 +6040,14 @@ async function buildAvailableResponse(ctx, generatedResponse) {
|
|
|
5850
6040
|
}
|
|
5851
6041
|
async function resolveCategoryRef(ctx, categoryId) {
|
|
5852
6042
|
if (!categoryId) return null;
|
|
5853
|
-
const record = await getOptional(ctx, "category", categoryId);
|
|
6043
|
+
const record = await getOptional(ctx.api, "category", categoryId);
|
|
5854
6044
|
if (!record) return null;
|
|
5855
6045
|
const category = toCategory(record);
|
|
5856
6046
|
return { _id: category.id, name: category.name };
|
|
5857
6047
|
}
|
|
5858
6048
|
async function resolveAgentRef(ctx, agentId) {
|
|
5859
6049
|
if (!agentId) return null;
|
|
5860
|
-
const record = await getOptional(ctx, "agent", agentId);
|
|
6050
|
+
const record = await getOptional(ctx.api, "agent", agentId);
|
|
5861
6051
|
if (!record) return null;
|
|
5862
6052
|
const agent = toAgent(record);
|
|
5863
6053
|
return { _id: agent.id, name: agent.name, model_id: agent.modelId };
|
|
@@ -5923,7 +6113,7 @@ async function executeEvaluation(ctx, userId, input) {
|
|
|
5923
6113
|
}
|
|
5924
6114
|
const modelId = input.modelId;
|
|
5925
6115
|
if (!modelId) throw new ctx.NonRetriableError("modelId is required");
|
|
5926
|
-
const agentRecord2 = await getOptional(ctx, "agent", modelId);
|
|
6116
|
+
const agentRecord2 = await getOptional(ctx.api, "agent", modelId);
|
|
5927
6117
|
if (!agentRecord2) throw new ctx.NonRetriableError(`Model not found (id=${modelId})`);
|
|
5928
6118
|
const agent = toAgent(agentRecord2);
|
|
5929
6119
|
const satisfied = input.satisfied;
|
|
@@ -6191,8 +6381,8 @@ function nonEmptyString(value) {
|
|
|
6191
6381
|
// src/functions/followup-gates.ts
|
|
6192
6382
|
var LABELS = {
|
|
6193
6383
|
G1: "Identifiant de ticket",
|
|
6194
|
-
G2: "Tag de
|
|
6195
|
-
G5: "Tag de
|
|
6384
|
+
G2: "Tag de l\u2019application configur\xE9",
|
|
6385
|
+
G5: "Tag de l\u2019application pr\xE9sent sur le ticket",
|
|
6196
6386
|
G6: "Aucune reprise humaine",
|
|
6197
6387
|
G7: "Cat\xE9gorie r\xE9solue et opt\xE9e",
|
|
6198
6388
|
G8: "Nouveau message client",
|
|
@@ -6206,7 +6396,7 @@ function evaluateTicketIdGate(ticketId) {
|
|
|
6206
6396
|
return ticketId === null ? stopped("G1", "Aucun identifiant de ticket exploitable (il doit \xEAtre une suite de chiffres).") : passed("G1", `Ticket ${ticketId}.`);
|
|
6207
6397
|
}
|
|
6208
6398
|
function evaluateScopeGate(settings) {
|
|
6209
|
-
return settings.
|
|
6399
|
+
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.`);
|
|
6210
6400
|
}
|
|
6211
6401
|
function skippedFollowupGates(gates) {
|
|
6212
6402
|
return gates.map((gate) => ({
|
|
@@ -6259,8 +6449,8 @@ function evaluatePayloadGates(input) {
|
|
|
6259
6449
|
return trace.done();
|
|
6260
6450
|
}
|
|
6261
6451
|
function scopeTagOnTicket(settings, tags) {
|
|
6262
|
-
const scopeTag = settings.
|
|
6263
|
-
return tags.includes(scopeTag) ? passed("G5", `Le ticket porte \xAB ${scopeTag} \xBB.`) : stopped("G5", `Le ticket ne porte pas le tag
|
|
6452
|
+
const scopeTag = settings.appScopeTag.trim();
|
|
6453
|
+
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.`);
|
|
6264
6454
|
}
|
|
6265
6455
|
function noHumanTakeover(settings, tags) {
|
|
6266
6456
|
const present = humanTakeoverTags(settings).filter((tag) => tags.includes(tag));
|
|
@@ -6647,7 +6837,7 @@ async function awaitSettledSend(ctx, id) {
|
|
|
6647
6837
|
return status;
|
|
6648
6838
|
}
|
|
6649
6839
|
async function readResponseStatus(ctx, id) {
|
|
6650
|
-
const row = await getOptional(ctx, "generated-response", id);
|
|
6840
|
+
const row = await getOptional(ctx.api, "generated-response", id);
|
|
6651
6841
|
if (!row) return "sent";
|
|
6652
6842
|
const raw = row.data.status;
|
|
6653
6843
|
return isGeneratedResponseStatus(raw) ? raw : null;
|
|
@@ -6874,6 +7064,1193 @@ async function triggerRun(ctx, ticketId, mode) {
|
|
|
6874
7064
|
return { mode, ticketId, runId: run.id };
|
|
6875
7065
|
}
|
|
6876
7066
|
|
|
7067
|
+
// src/domain/dashboard-queries.ts
|
|
7068
|
+
var OUTCOME_METRICS = [{ op: "count", as: "count" }];
|
|
7069
|
+
var OUTCOME_GROUP_BY = ["status", "autoSendDecision", "outcome"];
|
|
7070
|
+
var CATEGORY_OUTCOME_GROUP_BY = ["categoryId", "status", "autoSendDecision", "outcome"];
|
|
7071
|
+
var TRIAGE_HANDOFF_GROUP_BY = ["escalated", "status"];
|
|
7072
|
+
var CATEGORY_TRIAGE_GROUP_BY = ["categoryId", "escalated", "status"];
|
|
7073
|
+
|
|
7074
|
+
// src/domain/tool-input-error.ts
|
|
7075
|
+
var ToolInputError = class extends Error {
|
|
7076
|
+
constructor(message) {
|
|
7077
|
+
super(message);
|
|
7078
|
+
this.name = "ToolInputError";
|
|
7079
|
+
}
|
|
7080
|
+
};
|
|
7081
|
+
function assertOptionalBoolean(name, value) {
|
|
7082
|
+
if (value !== void 0 && value !== null && typeof value !== "boolean") {
|
|
7083
|
+
throw new ToolInputError(`"${name}" must be a boolean, got ${JSON.stringify(value)}.`);
|
|
7084
|
+
}
|
|
7085
|
+
}
|
|
7086
|
+
|
|
7087
|
+
// src/domain/period.ts
|
|
7088
|
+
var WEEKLY_BUCKET_FROM_DAYS = 46;
|
|
7089
|
+
var DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
|
7090
|
+
var MS_PER_DAY = 864e5;
|
|
7091
|
+
var EPOCH_ISO = "1970-01-01T00:00:00.000Z";
|
|
7092
|
+
function startOfDayIso(day) {
|
|
7093
|
+
return day !== void 0 && DAY_PATTERN.test(day) ? `${day}T00:00:00.000Z` : EPOCH_ISO;
|
|
7094
|
+
}
|
|
7095
|
+
function endOfDayIso(day) {
|
|
7096
|
+
return DAY_PATTERN.test(day) ? `${day}T23:59:59.999Z` : (/* @__PURE__ */ new Date()).toISOString();
|
|
7097
|
+
}
|
|
7098
|
+
function dayCount(bounds) {
|
|
7099
|
+
const from = Date.parse(bounds.fromIso);
|
|
7100
|
+
const to = Date.parse(bounds.toIso);
|
|
7101
|
+
if (Number.isNaN(from) || Number.isNaN(to)) return 0;
|
|
7102
|
+
return Math.max(1, Math.round((to - from) / MS_PER_DAY));
|
|
7103
|
+
}
|
|
7104
|
+
function boundsOf(range) {
|
|
7105
|
+
return { fromIso: startOfDayIso(range.from), toIso: endOfDayIso(range.to) };
|
|
7106
|
+
}
|
|
7107
|
+
function periodBoundsOf({ range, compareRange }) {
|
|
7108
|
+
const current = boundsOf(range);
|
|
7109
|
+
const days = dayCount(current);
|
|
7110
|
+
return {
|
|
7111
|
+
current,
|
|
7112
|
+
previous: compareRange === void 0 ? null : boundsOf(compareRange),
|
|
7113
|
+
days,
|
|
7114
|
+
interval: days >= WEEKLY_BUCKET_FROM_DAYS ? "week" : "day"
|
|
7115
|
+
};
|
|
7116
|
+
}
|
|
7117
|
+
function dayToMs(day) {
|
|
7118
|
+
return Date.parse(`${day}T00:00:00.000Z`);
|
|
7119
|
+
}
|
|
7120
|
+
function msToDay(ms) {
|
|
7121
|
+
return new Date(ms).toISOString().slice(0, 10);
|
|
7122
|
+
}
|
|
7123
|
+
function isCalendarDay(value) {
|
|
7124
|
+
if (typeof value !== "string" || !DAY_PATTERN.test(value)) return false;
|
|
7125
|
+
const ms = dayToMs(value);
|
|
7126
|
+
return !Number.isNaN(ms) && msToDay(ms) === value;
|
|
7127
|
+
}
|
|
7128
|
+
function requireCalendarDay(name, value) {
|
|
7129
|
+
if (!isCalendarDay(value)) {
|
|
7130
|
+
throw new ToolInputError(
|
|
7131
|
+
`"${name}" must be a calendar day written YYYY-MM-DD, got ${JSON.stringify(value)}.`
|
|
7132
|
+
);
|
|
7133
|
+
}
|
|
7134
|
+
return value;
|
|
7135
|
+
}
|
|
7136
|
+
function dayRangeOf(from, to, maxDays) {
|
|
7137
|
+
const range = { from: requireCalendarDay("from", from), to: requireCalendarDay("to", to) };
|
|
7138
|
+
const length = lengthInDays(range);
|
|
7139
|
+
if (length < 1) throw new ToolInputError('"to" must not be before "from".');
|
|
7140
|
+
if (length > maxDays) {
|
|
7141
|
+
throw new ToolInputError(`The window is ${length} days long; the maximum is ${maxDays} days.`);
|
|
7142
|
+
}
|
|
7143
|
+
return range;
|
|
7144
|
+
}
|
|
7145
|
+
function previousRangeOf(range) {
|
|
7146
|
+
const from = dayToMs(range.from);
|
|
7147
|
+
const length = lengthInDays(range);
|
|
7148
|
+
return { from: msToDay(from - length * MS_PER_DAY), to: msToDay(from - MS_PER_DAY) };
|
|
7149
|
+
}
|
|
7150
|
+
function lengthInDays(range) {
|
|
7151
|
+
return (dayToMs(range.to) - dayToMs(range.from)) / MS_PER_DAY + 1;
|
|
7152
|
+
}
|
|
7153
|
+
|
|
7154
|
+
// src/domain/dashboard-stats.ts
|
|
7155
|
+
function sumCounts(rows, countField = "count") {
|
|
7156
|
+
return rows.reduce((sum, row) => sum + (Number(row[countField]) || 0), 0);
|
|
7157
|
+
}
|
|
7158
|
+
function bucketDay(row) {
|
|
7159
|
+
return String(row["bucket"]).slice(0, 10);
|
|
7160
|
+
}
|
|
7161
|
+
var EMPTY_TOTALS = {
|
|
7162
|
+
auto: 0,
|
|
7163
|
+
human: 0,
|
|
7164
|
+
inProgress: 0,
|
|
7165
|
+
noReplyNeeded: 0
|
|
7166
|
+
};
|
|
7167
|
+
function countFailed(rows) {
|
|
7168
|
+
return sumCounts(rows.filter((row) => row["status"] === "failed"));
|
|
7169
|
+
}
|
|
7170
|
+
var HUMAN_OUTCOMES = /* @__PURE__ */ new Set(["needs_human", "guardrail_hold", "escalated", "awaiting_approval"]);
|
|
7171
|
+
function isUnautomatedTriage(decision) {
|
|
7172
|
+
return decision.escalated === "true" || decision.escalated === true || decision.status === "error";
|
|
7173
|
+
}
|
|
7174
|
+
function countOf(row) {
|
|
7175
|
+
return Number(row["count"]) || 0;
|
|
7176
|
+
}
|
|
7177
|
+
function outcomeOf(row) {
|
|
7178
|
+
const status = row["status"];
|
|
7179
|
+
const autoSendDecision = row["autoSendDecision"];
|
|
7180
|
+
if (status === "test_draft" || status === "superseded") return null;
|
|
7181
|
+
if (status === "sent") return "auto";
|
|
7182
|
+
if (status === "no_reply_needed") return "noReplyNeeded";
|
|
7183
|
+
if (status === "failed") return "human";
|
|
7184
|
+
if (status === "invalidated" || status === "expired") return "human";
|
|
7185
|
+
const outcome2 = row["outcome"];
|
|
7186
|
+
if (typeof outcome2 === "string" && HUMAN_OUTCOMES.has(outcome2)) return "human";
|
|
7187
|
+
if (outcome2 === "no_reply_needed") return "noReplyNeeded";
|
|
7188
|
+
if (outcome2 === "triaged_only") return null;
|
|
7189
|
+
return autoSendDecision === "hold" ? "human" : "inProgress";
|
|
7190
|
+
}
|
|
7191
|
+
function foldOutcomes(rows, triageRows = []) {
|
|
7192
|
+
const totals = { ...EMPTY_TOTALS };
|
|
7193
|
+
for (const row of rows) {
|
|
7194
|
+
const outcome2 = outcomeOf(row);
|
|
7195
|
+
if (outcome2 !== null) totals[outcome2] += countOf(row);
|
|
7196
|
+
}
|
|
7197
|
+
for (const row of triageRows) {
|
|
7198
|
+
if (isUnautomatedTriage(row)) totals.human += countOf(row);
|
|
7199
|
+
}
|
|
7200
|
+
return totals;
|
|
7201
|
+
}
|
|
7202
|
+
function settledCount(totals) {
|
|
7203
|
+
return totals.auto + totals.human;
|
|
7204
|
+
}
|
|
7205
|
+
function autonomyRate(totals) {
|
|
7206
|
+
const settled = settledCount(totals);
|
|
7207
|
+
return settled > 0 ? totals.auto / settled : Number.NaN;
|
|
7208
|
+
}
|
|
7209
|
+
function foldDailyOutcomes(rows, triageRows = []) {
|
|
7210
|
+
const byDay = /* @__PURE__ */ new Map();
|
|
7211
|
+
const totalsFor = (day) => {
|
|
7212
|
+
const existing = byDay.get(day);
|
|
7213
|
+
if (existing !== void 0) return existing;
|
|
7214
|
+
const fresh = { ...EMPTY_TOTALS };
|
|
7215
|
+
byDay.set(day, fresh);
|
|
7216
|
+
return fresh;
|
|
7217
|
+
};
|
|
7218
|
+
for (const row of rows) {
|
|
7219
|
+
const outcome2 = outcomeOf(row);
|
|
7220
|
+
if (outcome2 === null) continue;
|
|
7221
|
+
totalsFor(bucketDay(row))[outcome2] += countOf(row);
|
|
7222
|
+
}
|
|
7223
|
+
for (const row of triageRows) {
|
|
7224
|
+
if (isUnautomatedTriage(row)) totalsFor(bucketDay(row)).human += countOf(row);
|
|
7225
|
+
}
|
|
7226
|
+
return [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, totals]) => ({
|
|
7227
|
+
day,
|
|
7228
|
+
auto: totals.auto,
|
|
7229
|
+
human: totals.human,
|
|
7230
|
+
rate: settledCount(totals) > 0 ? autonomyRate(totals) : null
|
|
7231
|
+
}));
|
|
7232
|
+
}
|
|
7233
|
+
function fillMissingDays(series, fromIso, toIso) {
|
|
7234
|
+
const from = Date.parse(fromIso.slice(0, 10));
|
|
7235
|
+
const to = Date.parse(toIso.slice(0, 10));
|
|
7236
|
+
if (Number.isNaN(from) || Number.isNaN(to) || to < from) return series;
|
|
7237
|
+
const measured = new Map(series.map((point) => [point.day, point]));
|
|
7238
|
+
const filled = [];
|
|
7239
|
+
for (let t = from; t <= to; t += 864e5) {
|
|
7240
|
+
const day = new Date(t).toISOString().slice(0, 10);
|
|
7241
|
+
filled.push(measured.get(day) ?? { day, auto: 0, human: 0, rate: null });
|
|
7242
|
+
}
|
|
7243
|
+
return filled;
|
|
7244
|
+
}
|
|
7245
|
+
function ratePoints(rate, compareRate) {
|
|
7246
|
+
return Number.isNaN(rate) || Number.isNaN(compareRate) ? null : (rate - compareRate) * 100;
|
|
7247
|
+
}
|
|
7248
|
+
var SIGNAL_MIN_VOLUME = 20;
|
|
7249
|
+
var SIGNAL_MIN_POINTS = 3;
|
|
7250
|
+
function dashboardSignals(totals, compare, failed2 = 0) {
|
|
7251
|
+
const signals = [];
|
|
7252
|
+
const settled = settledCount(totals);
|
|
7253
|
+
const rate = autonomyRate(totals);
|
|
7254
|
+
if (compare !== null && settled >= SIGNAL_MIN_VOLUME && settledCount(compare) >= SIGNAL_MIN_VOLUME) {
|
|
7255
|
+
const points = ratePoints(rate, autonomyRate(compare));
|
|
7256
|
+
if (points !== null && Math.abs(points) >= SIGNAL_MIN_POINTS) {
|
|
7257
|
+
const move = points < 0 ? "recule" : "progresse";
|
|
7258
|
+
signals.push({
|
|
7259
|
+
level: points < 0 ? "creuser" : "info",
|
|
7260
|
+
text: `Le taux d\u2019autonomie ${move} de ${Math.abs(Math.round(points))} points par rapport \xE0 la p\xE9riode pr\xE9c\xE9dente.`
|
|
7261
|
+
});
|
|
7262
|
+
}
|
|
7263
|
+
}
|
|
7264
|
+
if (failed2 > 0) {
|
|
7265
|
+
signals.push({
|
|
7266
|
+
level: "creuser",
|
|
7267
|
+
text: `${failed2} g\xE9n\xE9ration${failed2 > 1 ? "s ont" : " a"} \xE9chou\xE9 techniquement : ${failed2 > 1 ? "ces demandes n\u2019ont" : "cette demande n\u2019a"} jamais eu de brouillon et ${failed2 > 1 ? "sont retomb\xE9es" : "est retomb\xE9e"} sur un humain.`
|
|
7268
|
+
});
|
|
7269
|
+
}
|
|
7270
|
+
if (totals.inProgress > 0) {
|
|
7271
|
+
signals.push({
|
|
7272
|
+
level: "info",
|
|
7273
|
+
text: `${totals.inProgress} r\xE9ponse${totals.inProgress > 1 ? "s sont" : " est"} encore en cours : ${totals.inProgress > 1 ? "elles ne comptent" : "elle ne compte"} dans aucun des deux camps.`
|
|
7274
|
+
});
|
|
7275
|
+
}
|
|
7276
|
+
if (totals.noReplyNeeded > 0) {
|
|
7277
|
+
signals.push({
|
|
7278
|
+
level: "info",
|
|
7279
|
+
text: `${totals.noReplyNeeded} demande${totals.noReplyNeeded > 1 ? "s" : ""} ne n\xE9cessitai${totals.noReplyNeeded > 1 ? "ent" : "t"} aucune r\xE9ponse : hors du taux d\u2019autonomie.`
|
|
7280
|
+
});
|
|
7281
|
+
}
|
|
7282
|
+
if (compare !== null && settled > 0 && settledCount(compare) < SIGNAL_MIN_VOLUME) {
|
|
7283
|
+
signals.push({
|
|
7284
|
+
level: "info",
|
|
7285
|
+
text: "La p\xE9riode pr\xE9c\xE9dente compte trop peu de demandes r\xE9gl\xE9es pour que la comparaison veuille dire quelque chose."
|
|
7286
|
+
});
|
|
7287
|
+
}
|
|
7288
|
+
return signals;
|
|
7289
|
+
}
|
|
7290
|
+
function foldHumanReasons(rows, triageRows = []) {
|
|
7291
|
+
const reasons = { blocked: 0, invalidated: 0, expired: 0, escalatedNoDraft: 0, failed: 0 };
|
|
7292
|
+
for (const row of rows) {
|
|
7293
|
+
if (outcomeOf(row) !== "human") continue;
|
|
7294
|
+
const count = countOf(row);
|
|
7295
|
+
if (row["status"] === "invalidated") reasons.invalidated += count;
|
|
7296
|
+
else if (row["status"] === "expired") reasons.expired += count;
|
|
7297
|
+
else if (row["status"] === "failed") reasons.failed += count;
|
|
7298
|
+
else reasons.blocked += count;
|
|
7299
|
+
}
|
|
7300
|
+
for (const row of triageRows) {
|
|
7301
|
+
if (isUnautomatedTriage(row)) reasons.escalatedNoDraft += countOf(row);
|
|
7302
|
+
}
|
|
7303
|
+
return reasons;
|
|
7304
|
+
}
|
|
7305
|
+
var CATEGORY_TOP_N = 10;
|
|
7306
|
+
function foldCategoryOutcomes(triageRows, responseRows, categoryNames, topN = CATEGORY_TOP_N) {
|
|
7307
|
+
const byId = /* @__PURE__ */ new Map();
|
|
7308
|
+
const barFor = (id) => {
|
|
7309
|
+
const name = typeof id === "string" ? categoryNames.get(id) : void 0;
|
|
7310
|
+
if (name === void 0) return null;
|
|
7311
|
+
const existing = byId.get(id);
|
|
7312
|
+
if (existing !== void 0) return existing;
|
|
7313
|
+
const bar = {
|
|
7314
|
+
label: name,
|
|
7315
|
+
total: 0,
|
|
7316
|
+
auto: 0,
|
|
7317
|
+
human: 0,
|
|
7318
|
+
noReply: 0,
|
|
7319
|
+
undrafted: 0
|
|
7320
|
+
};
|
|
7321
|
+
byId.set(id, bar);
|
|
7322
|
+
return bar;
|
|
7323
|
+
};
|
|
7324
|
+
for (const row of triageRows) {
|
|
7325
|
+
const bar = barFor(row["categoryId"]);
|
|
7326
|
+
if (bar === null) continue;
|
|
7327
|
+
const count = countOf(row);
|
|
7328
|
+
bar.total += count;
|
|
7329
|
+
if (isUnautomatedTriage(row)) bar.human += count;
|
|
7330
|
+
}
|
|
7331
|
+
for (const row of responseRows) {
|
|
7332
|
+
const bar = barFor(row["categoryId"]);
|
|
7333
|
+
if (bar === null) continue;
|
|
7334
|
+
const outcome2 = outcomeOf(row);
|
|
7335
|
+
const count = countOf(row);
|
|
7336
|
+
if (outcome2 === "auto") bar.auto += count;
|
|
7337
|
+
else if (outcome2 === "human") bar.human += count;
|
|
7338
|
+
else if (outcome2 === "noReplyNeeded") bar.noReply += count;
|
|
7339
|
+
}
|
|
7340
|
+
const bars = [...byId.values()].map((bar) => {
|
|
7341
|
+
const accounted = bar.auto + bar.human + bar.noReply;
|
|
7342
|
+
return {
|
|
7343
|
+
...bar,
|
|
7344
|
+
total: Math.max(bar.total, accounted),
|
|
7345
|
+
undrafted: Math.max(0, bar.total - accounted)
|
|
7346
|
+
};
|
|
7347
|
+
}).filter((bar) => bar.total > 0).sort((a, b) => b.total - a.total);
|
|
7348
|
+
if (bars.length <= topN + 1) return bars;
|
|
7349
|
+
const tail = bars.slice(topN).reduce(
|
|
7350
|
+
(sum, bar) => ({
|
|
7351
|
+
label: "Autres",
|
|
7352
|
+
total: sum.total + bar.total,
|
|
7353
|
+
auto: sum.auto + bar.auto,
|
|
7354
|
+
human: sum.human + bar.human,
|
|
7355
|
+
noReply: sum.noReply + bar.noReply,
|
|
7356
|
+
undrafted: sum.undrafted + bar.undrafted
|
|
7357
|
+
}),
|
|
7358
|
+
{ label: "Autres", total: 0, auto: 0, human: 0, noReply: 0, undrafted: 0 }
|
|
7359
|
+
);
|
|
7360
|
+
return [...bars.slice(0, topN), tail];
|
|
7361
|
+
}
|
|
7362
|
+
|
|
7363
|
+
// src/domain/ticket-outcome.ts
|
|
7364
|
+
var REPORTED_OUTCOMES = [...OUTCOMES, "invalidated", "expired"];
|
|
7365
|
+
function emptyOutcomeCounts() {
|
|
7366
|
+
return Object.fromEntries(REPORTED_OUTCOMES.map((outcome2) => [outcome2, 0]));
|
|
7367
|
+
}
|
|
7368
|
+
var STATUS_EXITS = ["sent", "no_reply_needed", "failed", "invalidated", "expired"];
|
|
7369
|
+
function isStatusExit(status) {
|
|
7370
|
+
return STATUS_EXITS.includes(status);
|
|
7371
|
+
}
|
|
7372
|
+
function isReportedOutcome(value) {
|
|
7373
|
+
return REPORTED_OUTCOMES.includes(value);
|
|
7374
|
+
}
|
|
7375
|
+
function reportedOutcomeOf(status, outcome2) {
|
|
7376
|
+
if (status === "test_draft" || status === "superseded") return null;
|
|
7377
|
+
if (isStatusExit(status)) return status;
|
|
7378
|
+
return isOutcome(outcome2) ? outcome2 : null;
|
|
7379
|
+
}
|
|
7380
|
+
function foldOutcomeCounts(responseRows, triageRows) {
|
|
7381
|
+
const counts = emptyOutcomeCounts();
|
|
7382
|
+
for (const row of responseRows) {
|
|
7383
|
+
const outcome2 = reportedOutcomeOf(row["status"], row["outcome"]);
|
|
7384
|
+
if (outcome2 !== null) counts[outcome2] += countOf(row);
|
|
7385
|
+
}
|
|
7386
|
+
for (const row of triageRows) {
|
|
7387
|
+
if (isUnautomatedTriage(row)) counts.escalated += countOf(row);
|
|
7388
|
+
}
|
|
7389
|
+
return counts;
|
|
7390
|
+
}
|
|
7391
|
+
|
|
7392
|
+
// src/domain/ticket-stats.ts
|
|
7393
|
+
function rateOrNull(rate) {
|
|
7394
|
+
return Number.isNaN(rate) ? null : rate;
|
|
7395
|
+
}
|
|
7396
|
+
function summarizeWindow({
|
|
7397
|
+
range,
|
|
7398
|
+
period,
|
|
7399
|
+
rows,
|
|
7400
|
+
categoryNames,
|
|
7401
|
+
compareRows
|
|
7402
|
+
}) {
|
|
7403
|
+
const totals = foldOutcomes(rows.responses, rows.triage);
|
|
7404
|
+
const compareTotals = compareRows === void 0 ? null : foldOutcomes(compareRows.responses, compareRows.triage);
|
|
7405
|
+
const daily = foldDailyOutcomes(rows.responses, rows.triage);
|
|
7406
|
+
return {
|
|
7407
|
+
period: range,
|
|
7408
|
+
interval: period.interval,
|
|
7409
|
+
// Every triage decision carries `escalated` and `status`, so this grouping partitions all of them.
|
|
7410
|
+
volume: sumCounts(rows.triage),
|
|
7411
|
+
autonomyRate: rateOrNull(autonomyRate(totals)),
|
|
7412
|
+
outcomes: foldOutcomeCounts(rows.responses, rows.triage),
|
|
7413
|
+
humanReasons: foldHumanReasons(rows.responses, rows.triage),
|
|
7414
|
+
byCategory: foldCategoryOutcomes(rows.categoryTriage, rows.categoryOutcomes, categoryNames),
|
|
7415
|
+
daily: period.interval === "day" ? fillMissingDays(daily, period.current.fromIso, period.current.toIso) : daily,
|
|
7416
|
+
signals: dashboardSignals(totals, compareTotals, countFailed(rows.responses))
|
|
7417
|
+
};
|
|
7418
|
+
}
|
|
7419
|
+
var STAT_DEFINITIONS = {
|
|
7420
|
+
volume: "Number of triage decisions over the period: every message the pipeline triaged, whether a draft followed or not.",
|
|
7421
|
+
autonomyRate: "autonomy rate = responses settled by the AI / (responses settled by the AI + requests taken over by a human); null when nothing is settled.",
|
|
7422
|
+
outcomes: {
|
|
7423
|
+
sent: "Response sent to the customer by the pipeline.",
|
|
7424
|
+
ready: "Draft ready to be served, with no tag (nominal path), still pending.",
|
|
7425
|
+
needs_human: "Verdict not sendable: draft ready, posted with the review tag, still pending.",
|
|
7426
|
+
guardrail_hold: "A guardrail held the draft, posted with the escalation tag, still pending.",
|
|
7427
|
+
awaiting_approval: "An action is waiting for a human\u2019s approval.",
|
|
7428
|
+
escalated: "Request escalated at triage, or triage error: no draft written.",
|
|
7429
|
+
triaged_only: "Triaged, with no drafting step to run.",
|
|
7430
|
+
no_reply_needed: "Conversation already closed: no reply needed, outside the autonomy rate.",
|
|
7431
|
+
failed: "Generation failed technically; the ticket went up to a human.",
|
|
7432
|
+
invalidated: "Draft invalidated (an agent replied before it was served): taken over by a human, whatever the outcome decided at generation.",
|
|
7433
|
+
expired: "Draft expired (the serving window closed without it being used): taken over by a human, whatever the outcome decided at generation."
|
|
7434
|
+
},
|
|
7435
|
+
humanReasons: {
|
|
7436
|
+
blocked: "Draft written but held (judge or guardrail), waiting for a human.",
|
|
7437
|
+
invalidated: "An agent replied before the draft was served.",
|
|
7438
|
+
expired: "The serving window closed on an unused draft.",
|
|
7439
|
+
escalatedNoDraft: "Handed over to a human at triage (escalation or triage error): no draft.",
|
|
7440
|
+
failed: "Generation failed technically and the ticket was escalated."
|
|
7441
|
+
},
|
|
7442
|
+
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).`,
|
|
7443
|
+
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).`,
|
|
7444
|
+
signals: "What is worth reading out loud, like the dashboard\u2019s \xAB Signaux \xBB (signals) block; the sentences are in French."
|
|
7445
|
+
};
|
|
7446
|
+
|
|
7447
|
+
// src/functions/mcp-tool.ts
|
|
7448
|
+
function mcpToolTrigger(description, { exposed = true } = {}) {
|
|
7449
|
+
return {
|
|
7450
|
+
type: "mcpTool",
|
|
7451
|
+
description,
|
|
7452
|
+
readOnly: true,
|
|
7453
|
+
exposed
|
|
7454
|
+
};
|
|
7455
|
+
}
|
|
7456
|
+
function mcpToolHandler(run) {
|
|
7457
|
+
return (ctx, input) => {
|
|
7458
|
+
const { api } = ctx;
|
|
7459
|
+
return withToolInputErrors(ctx, () => run(api, input ?? {}));
|
|
7460
|
+
};
|
|
7461
|
+
}
|
|
7462
|
+
async function withToolInputErrors(ctx, run) {
|
|
7463
|
+
try {
|
|
7464
|
+
return await run();
|
|
7465
|
+
} catch (error) {
|
|
7466
|
+
if (error instanceof ToolInputError) throw new ctx.NonRetriableError(error.message);
|
|
7467
|
+
throw error;
|
|
7468
|
+
}
|
|
7469
|
+
}
|
|
7470
|
+
|
|
7471
|
+
// src/functions/ticket-stats.ts
|
|
7472
|
+
var TICKET_STATS_MAX_DAYS = 90;
|
|
7473
|
+
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.";
|
|
7474
|
+
function buildTicketStatsFunctionDef(config) {
|
|
7475
|
+
return {
|
|
7476
|
+
universalIdentifier: mcpToolIdentifierFor(config, "ticket-stats"),
|
|
7477
|
+
name: "ticket-stats",
|
|
7478
|
+
trigger: mcpToolTrigger(DESCRIPTION),
|
|
7479
|
+
input: [
|
|
7480
|
+
{
|
|
7481
|
+
universalIdentifier: TICKET_STATS_INPUT_FROM_UID,
|
|
7482
|
+
name: "from",
|
|
7483
|
+
type: appKit.FieldType.TEXT,
|
|
7484
|
+
label: "From",
|
|
7485
|
+
description: "First day of the period, YYYY-MM-DD, included.",
|
|
7486
|
+
isNullable: false
|
|
7487
|
+
},
|
|
7488
|
+
{
|
|
7489
|
+
universalIdentifier: TICKET_STATS_INPUT_TO_UID,
|
|
7490
|
+
name: "to",
|
|
7491
|
+
type: appKit.FieldType.TEXT,
|
|
7492
|
+
label: "To",
|
|
7493
|
+
description: `Last day of the period, YYYY-MM-DD, included. At most ${TICKET_STATS_MAX_DAYS} days after "from".`,
|
|
7494
|
+
isNullable: false
|
|
7495
|
+
},
|
|
7496
|
+
{
|
|
7497
|
+
universalIdentifier: TICKET_STATS_INPUT_COMPARE_TO_PREVIOUS_UID,
|
|
7498
|
+
name: "compareToPrevious",
|
|
7499
|
+
type: appKit.FieldType.BOOLEAN,
|
|
7500
|
+
label: "Compare to previous period",
|
|
7501
|
+
description: 'Also compute the same indicators on the period of the same length that ends the day before "from".',
|
|
7502
|
+
isNullable: true
|
|
7503
|
+
}
|
|
7504
|
+
]
|
|
7505
|
+
};
|
|
7506
|
+
}
|
|
7507
|
+
function createTicketStatsHandler() {
|
|
7508
|
+
return mcpToolHandler(computeTicketStats);
|
|
7509
|
+
}
|
|
7510
|
+
async function computeTicketStats(api, input) {
|
|
7511
|
+
const range = dayRangeOf(input.from, input.to, TICKET_STATS_MAX_DAYS);
|
|
7512
|
+
assertOptionalBoolean("compareToPrevious", input.compareToPrevious);
|
|
7513
|
+
const [timezone, categoryNames] = await Promise.all([
|
|
7514
|
+
readStatsTimezone(api),
|
|
7515
|
+
readCategoryNames(api)
|
|
7516
|
+
]);
|
|
7517
|
+
const period = periodBoundsOf({ range });
|
|
7518
|
+
const previous = input.compareToPrevious === true ? previousWindowOf(range) : void 0;
|
|
7519
|
+
const [rows, previousRows] = await Promise.all([
|
|
7520
|
+
readWindowRows(api, period, timezone),
|
|
7521
|
+
previous && readWindowRows(api, previous.period, timezone)
|
|
7522
|
+
]);
|
|
7523
|
+
return {
|
|
7524
|
+
...summarizeWindow({ range, period, rows, categoryNames, compareRows: previousRows }),
|
|
7525
|
+
timezone,
|
|
7526
|
+
...previous && previousRows && {
|
|
7527
|
+
previous: summarizeWindow({ ...previous, rows: previousRows, categoryNames })
|
|
7528
|
+
},
|
|
7529
|
+
definitions: STAT_DEFINITIONS
|
|
7530
|
+
};
|
|
7531
|
+
}
|
|
7532
|
+
function previousWindowOf(range) {
|
|
7533
|
+
const previousRange = previousRangeOf(range);
|
|
7534
|
+
return { range: previousRange, period: periodBoundsOf({ range: previousRange }) };
|
|
7535
|
+
}
|
|
7536
|
+
async function readStatsTimezone(api) {
|
|
7537
|
+
const settings = await getSettingsOrNull(api);
|
|
7538
|
+
return settings?.statsTimezone || DEFAULT_STATS_TIMEZONE;
|
|
7539
|
+
}
|
|
7540
|
+
async function readWindowRows(api, period, timezone) {
|
|
7541
|
+
const { fromIso: gte, toIso: lte } = period.current;
|
|
7542
|
+
const generated = { filter: { generatedAt: { gte, lte } }, metrics: OUTCOME_METRICS };
|
|
7543
|
+
const decided = { filter: { decidedAt: { gte, lte } }, metrics: OUTCOME_METRICS };
|
|
7544
|
+
const bucketOn = (field) => ({ field, interval: period.interval, tz: timezone });
|
|
7545
|
+
const [responses, triage2, categoryTriage, categoryOutcomes] = await Promise.all([
|
|
7546
|
+
api.aggregate("generated-response", {
|
|
7547
|
+
...generated,
|
|
7548
|
+
groupBy: OUTCOME_GROUP_BY,
|
|
7549
|
+
bucket: bucketOn("generatedAt")
|
|
7550
|
+
}),
|
|
7551
|
+
api.aggregate("triage-decision", {
|
|
7552
|
+
...decided,
|
|
7553
|
+
groupBy: TRIAGE_HANDOFF_GROUP_BY,
|
|
7554
|
+
bucket: bucketOn("decidedAt")
|
|
7555
|
+
}),
|
|
7556
|
+
api.aggregate("triage-decision", { ...decided, groupBy: CATEGORY_TRIAGE_GROUP_BY }),
|
|
7557
|
+
api.aggregate("generated-response", { ...generated, groupBy: CATEGORY_OUTCOME_GROUP_BY })
|
|
7558
|
+
]);
|
|
7559
|
+
return { responses, triage: triage2, categoryTriage, categoryOutcomes };
|
|
7560
|
+
}
|
|
7561
|
+
var LIST_TICKETS_MAX_DAYS = 31;
|
|
7562
|
+
var LIST_TICKETS_PAGE_SIZE = 50;
|
|
7563
|
+
var MAX_SCANNED_BATCHES = 8;
|
|
7564
|
+
var InvalidCursorError = class extends ToolInputError {
|
|
7565
|
+
constructor(reason = "The cursor is not one this tool issued") {
|
|
7566
|
+
super(`${reason}; start again without a cursor.`);
|
|
7567
|
+
this.name = "InvalidCursorError";
|
|
7568
|
+
}
|
|
7569
|
+
};
|
|
7570
|
+
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.";
|
|
7571
|
+
function buildListTicketsFunctionDef(config) {
|
|
7572
|
+
return {
|
|
7573
|
+
universalIdentifier: mcpToolIdentifierFor(config, "list-tickets"),
|
|
7574
|
+
name: "list-tickets",
|
|
7575
|
+
trigger: mcpToolTrigger(DESCRIPTION2),
|
|
7576
|
+
input: [
|
|
7577
|
+
{
|
|
7578
|
+
universalIdentifier: LIST_TICKETS_INPUT_FROM_UID,
|
|
7579
|
+
name: "from",
|
|
7580
|
+
type: appKit.FieldType.TEXT,
|
|
7581
|
+
label: "From",
|
|
7582
|
+
description: "First day of the period, YYYY-MM-DD, included.",
|
|
7583
|
+
isNullable: false
|
|
7584
|
+
},
|
|
7585
|
+
{
|
|
7586
|
+
universalIdentifier: LIST_TICKETS_INPUT_TO_UID,
|
|
7587
|
+
name: "to",
|
|
7588
|
+
type: appKit.FieldType.TEXT,
|
|
7589
|
+
label: "To",
|
|
7590
|
+
description: `Last day of the period, YYYY-MM-DD, included. At most ${LIST_TICKETS_MAX_DAYS} days after "from".`,
|
|
7591
|
+
isNullable: false
|
|
7592
|
+
},
|
|
7593
|
+
{
|
|
7594
|
+
universalIdentifier: LIST_TICKETS_INPUT_CATEGORY_ID_UID,
|
|
7595
|
+
name: "categoryId",
|
|
7596
|
+
type: appKit.FieldType.TEXT,
|
|
7597
|
+
label: "Category id",
|
|
7598
|
+
description: "Only the tickets triaged into this category (an id from list_categories).",
|
|
7599
|
+
isNullable: true
|
|
7600
|
+
},
|
|
7601
|
+
{
|
|
7602
|
+
universalIdentifier: LIST_TICKETS_INPUT_OUTCOME_UID,
|
|
7603
|
+
name: "outcome",
|
|
7604
|
+
type: appKit.FieldType.SELECT,
|
|
7605
|
+
label: "Outcome",
|
|
7606
|
+
description: 'Only the tickets that took this exit. "escalated" covers tickets handed over at triage, which have no response.',
|
|
7607
|
+
isNullable: true,
|
|
7608
|
+
options: [...REPORTED_OUTCOMES]
|
|
7609
|
+
},
|
|
7610
|
+
{
|
|
7611
|
+
universalIdentifier: LIST_TICKETS_INPUT_ESCALATED_UID,
|
|
7612
|
+
name: "escalated",
|
|
7613
|
+
type: appKit.FieldType.BOOLEAN,
|
|
7614
|
+
label: "Escalated",
|
|
7615
|
+
description: "Only the tickets the triage decision did (true) or did not (false) escalate.",
|
|
7616
|
+
isNullable: true
|
|
7617
|
+
},
|
|
7618
|
+
{
|
|
7619
|
+
universalIdentifier: LIST_TICKETS_INPUT_CHANNEL_UID,
|
|
7620
|
+
name: "channel",
|
|
7621
|
+
type: appKit.FieldType.TEXT,
|
|
7622
|
+
label: "Channel",
|
|
7623
|
+
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.",
|
|
7624
|
+
isNullable: true
|
|
7625
|
+
},
|
|
7626
|
+
{
|
|
7627
|
+
universalIdentifier: LIST_TICKETS_INPUT_STATUS_UID,
|
|
7628
|
+
name: "status",
|
|
7629
|
+
type: appKit.FieldType.SELECT,
|
|
7630
|
+
label: "Status",
|
|
7631
|
+
description: "Only the tickets whose response is in this status.",
|
|
7632
|
+
isNullable: true,
|
|
7633
|
+
options: [...GENERATED_RESPONSE_STATUSES]
|
|
7634
|
+
},
|
|
7635
|
+
{
|
|
7636
|
+
universalIdentifier: LIST_TICKETS_INPUT_CURSOR_UID,
|
|
7637
|
+
name: "cursor",
|
|
7638
|
+
type: appKit.FieldType.TEXT,
|
|
7639
|
+
label: "Cursor",
|
|
7640
|
+
description: "The nextCursor of the previous page. Leave empty for the first page.",
|
|
7641
|
+
isNullable: true
|
|
7642
|
+
}
|
|
7643
|
+
]
|
|
7644
|
+
};
|
|
7645
|
+
}
|
|
7646
|
+
function createListTicketsHandler() {
|
|
7647
|
+
return mcpToolHandler(listTickets);
|
|
7648
|
+
}
|
|
7649
|
+
function scopeOf(input) {
|
|
7650
|
+
const { from, to, categoryId, outcome: outcome2, escalated, channel, status } = input;
|
|
7651
|
+
return JSON.stringify([
|
|
7652
|
+
from,
|
|
7653
|
+
to,
|
|
7654
|
+
categoryId || null,
|
|
7655
|
+
outcome2 || null,
|
|
7656
|
+
escalated ?? null,
|
|
7657
|
+
channel || null,
|
|
7658
|
+
status || null
|
|
7659
|
+
]);
|
|
7660
|
+
}
|
|
7661
|
+
function encodeCursor(position) {
|
|
7662
|
+
return Buffer.from(JSON.stringify(position)).toString("base64url");
|
|
7663
|
+
}
|
|
7664
|
+
function parseCursor(cursor) {
|
|
7665
|
+
let decoded;
|
|
7666
|
+
try {
|
|
7667
|
+
decoded = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
7668
|
+
} catch {
|
|
7669
|
+
throw new InvalidCursorError();
|
|
7670
|
+
}
|
|
7671
|
+
if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
|
|
7672
|
+
throw new InvalidCursorError();
|
|
7673
|
+
}
|
|
7674
|
+
return decoded;
|
|
7675
|
+
}
|
|
7676
|
+
function startOfScan(input) {
|
|
7677
|
+
const scope = scopeOf(input);
|
|
7678
|
+
if (!input.cursor) return { after: null, skip: 0, scope };
|
|
7679
|
+
const { after = null, skip, scope: issuedFor } = parseCursor(input.cursor);
|
|
7680
|
+
const wellFormed = (after === null || typeof after === "string") && typeof skip === "number" && Number.isInteger(skip) && skip >= 0 && typeof issuedFor === "string";
|
|
7681
|
+
if (!wellFormed) throw new InvalidCursorError();
|
|
7682
|
+
if (issuedFor !== scope)
|
|
7683
|
+
throw new InvalidCursorError("The cursor was issued for another period or other filters");
|
|
7684
|
+
return { after, skip, scope };
|
|
7685
|
+
}
|
|
7686
|
+
function assertValidFilters(input) {
|
|
7687
|
+
assertOptionalBoolean("escalated", input.escalated);
|
|
7688
|
+
if (input.outcome && !isReportedOutcome(input.outcome)) {
|
|
7689
|
+
throw new ToolInputError(
|
|
7690
|
+
`"outcome" must be one of ${REPORTED_OUTCOMES.join(", ")}; got ${JSON.stringify(input.outcome)}.`
|
|
7691
|
+
);
|
|
7692
|
+
}
|
|
7693
|
+
if (input.status && !isGeneratedResponseStatus(input.status)) {
|
|
7694
|
+
throw new ToolInputError(
|
|
7695
|
+
`"status" must be one of ${GENERATED_RESPONSE_STATUSES.join(", ")}; got ${JSON.stringify(input.status)}.`
|
|
7696
|
+
);
|
|
7697
|
+
}
|
|
7698
|
+
}
|
|
7699
|
+
async function listTickets(api, input) {
|
|
7700
|
+
const range = dayRangeOf(input.from, input.to, LIST_TICKETS_MAX_DAYS);
|
|
7701
|
+
assertValidFilters(input);
|
|
7702
|
+
let position = startOfScan(input);
|
|
7703
|
+
const window = periodBoundsOf({ range }).current;
|
|
7704
|
+
const filter = decisionFilter(window, input);
|
|
7705
|
+
const readBatch = (after) => api.list("triage-decision", {
|
|
7706
|
+
filter,
|
|
7707
|
+
sort: NEWEST_DECISION_FIRST,
|
|
7708
|
+
limit: LIST_TICKETS_PAGE_SIZE,
|
|
7709
|
+
...after === null ? {} : { cursor: after }
|
|
7710
|
+
});
|
|
7711
|
+
const [categoryNames, firstBatch] = await Promise.all([
|
|
7712
|
+
readCategoryNames(api),
|
|
7713
|
+
readBatch(position.after)
|
|
7714
|
+
]);
|
|
7715
|
+
let page = firstBatch;
|
|
7716
|
+
const rows = [];
|
|
7717
|
+
for (let scanned = 1; ; scanned++) {
|
|
7718
|
+
const batch = page.items.slice(position.skip).map(toTriageDecision);
|
|
7719
|
+
const candidates = await readTicketsOf(api, batch, window.toIso);
|
|
7720
|
+
for (const [index, candidate] of candidates.entries()) {
|
|
7721
|
+
if (candidate === null) continue;
|
|
7722
|
+
const row = toTicketRow(candidate.decision, candidate.response, categoryNames);
|
|
7723
|
+
if (!matchesResponseFilters(row, input)) continue;
|
|
7724
|
+
rows.push(row);
|
|
7725
|
+
if (rows.length === LIST_TICKETS_PAGE_SIZE) {
|
|
7726
|
+
return { rows, nextCursor: cursorAfter(page, position, position.skip + index + 1) };
|
|
7727
|
+
}
|
|
7728
|
+
}
|
|
7729
|
+
if (page.nextCursor === null) return { rows, nextCursor: null };
|
|
7730
|
+
position = { ...position, after: page.nextCursor, skip: 0 };
|
|
7731
|
+
if (scanned === MAX_SCANNED_BATCHES) return { rows, nextCursor: encodeCursor(position) };
|
|
7732
|
+
page = await readBatch(position.after);
|
|
7733
|
+
}
|
|
7734
|
+
}
|
|
7735
|
+
function cursorAfter(page, position, consumed) {
|
|
7736
|
+
if (consumed < page.items.length) return encodeCursor({ ...position, skip: consumed });
|
|
7737
|
+
return page.nextCursor === null ? null : encodeCursor({ ...position, after: page.nextCursor, skip: 0 });
|
|
7738
|
+
}
|
|
7739
|
+
function decisionFilter(window, input) {
|
|
7740
|
+
return {
|
|
7741
|
+
decidedAt: { gte: window.fromIso, lte: window.toIso },
|
|
7742
|
+
...input.categoryId ? { categoryId: input.categoryId } : {},
|
|
7743
|
+
...typeof input.escalated === "boolean" ? { escalated: input.escalated } : {}
|
|
7744
|
+
};
|
|
7745
|
+
}
|
|
7746
|
+
async function readTicketsOf(api, batch, windowEndIso) {
|
|
7747
|
+
const [newestDecidedAt, responses] = await Promise.all([
|
|
7748
|
+
readNewestDecisionTimes(api, batch, windowEndIso),
|
|
7749
|
+
latestResponsesByTicket(
|
|
7750
|
+
api,
|
|
7751
|
+
batch.map((decision) => decision.ticketId)
|
|
7752
|
+
)
|
|
7753
|
+
]);
|
|
7754
|
+
return batch.map(
|
|
7755
|
+
(decision) => isSuperseded(decision, newestDecidedAt) ? null : { decision, response: responses.get(decision.ticketId) ?? null }
|
|
7756
|
+
);
|
|
7757
|
+
}
|
|
7758
|
+
async function readNewestDecisionTimes(api, batch, windowEndIso) {
|
|
7759
|
+
const dated = batch.filter((decision) => decision.decidedAt !== null);
|
|
7760
|
+
if (dated.length === 0) return /* @__PURE__ */ new Map();
|
|
7761
|
+
const oldest = dated.reduce((a, b) => instantOf(b) < instantOf(a) ? b : a);
|
|
7762
|
+
const newest = await newestPerTicket(api, {
|
|
7763
|
+
objectKey: "triage-decision",
|
|
7764
|
+
ticketIds: dated.map((decision) => decision.ticketId),
|
|
7765
|
+
filter: { decidedAt: { gt: oldest.decidedAt, lte: windowEndIso } },
|
|
7766
|
+
sort: NEWEST_DECISION_FIRST
|
|
7767
|
+
});
|
|
7768
|
+
return new Map(
|
|
7769
|
+
[...newest].map(([ticketId, record]) => [ticketId, instantOf(toTriageDecision(record))])
|
|
7770
|
+
);
|
|
7771
|
+
}
|
|
7772
|
+
function isSuperseded(decision, newestDecidedAt) {
|
|
7773
|
+
return (newestDecidedAt.get(decision.ticketId) ?? -Infinity) > instantOf(decision);
|
|
7774
|
+
}
|
|
7775
|
+
function instantOf(decision) {
|
|
7776
|
+
return Date.parse(decision.decidedAt ?? "");
|
|
7777
|
+
}
|
|
7778
|
+
function toTicketRow(decision, response, categoryNames) {
|
|
7779
|
+
return {
|
|
7780
|
+
ticketId: decision.ticketId,
|
|
7781
|
+
ticketUrl: decision.ticketUrl,
|
|
7782
|
+
decidedAt: decision.decidedAt,
|
|
7783
|
+
categoryId: decision.categoryId,
|
|
7784
|
+
category: decision.categoryId === null ? null : categoryNames.get(decision.categoryId) ?? null,
|
|
7785
|
+
confidence: decision.confidence,
|
|
7786
|
+
escalated: decision.escalated,
|
|
7787
|
+
outcome: outcomeOf2(decision, response),
|
|
7788
|
+
status: response?.status ?? null,
|
|
7789
|
+
channel: response === null ? null : response.sourceChannel ?? response.channel,
|
|
7790
|
+
sentAt: response?.sentAt ?? null,
|
|
7791
|
+
ineligibleReason: response?.ineligibleReason ?? null,
|
|
7792
|
+
guardrailHits: response?.guardrailHits ?? [],
|
|
7793
|
+
verdict: response?.verdict ? { verdict: response.verdict.verdict, confidence: response.verdict.confidence } : null,
|
|
7794
|
+
origin: decision.origin
|
|
7795
|
+
};
|
|
7796
|
+
}
|
|
7797
|
+
function outcomeOf2(decision, response) {
|
|
7798
|
+
const answeredSince = response !== null && (response.generatedAt ?? "") >= (decision.decidedAt ?? "");
|
|
7799
|
+
if (isUnautomatedTriage(decision) && !answeredSince) return "escalated";
|
|
7800
|
+
return response === null ? null : reportedOutcomeOf(response.status, response.outcome);
|
|
7801
|
+
}
|
|
7802
|
+
function matchesResponseFilters(row, input) {
|
|
7803
|
+
return (!input.outcome || row.outcome === input.outcome) && (!input.channel || row.channel === input.channel) && (!input.status || row.status === input.status);
|
|
7804
|
+
}
|
|
7805
|
+
|
|
7806
|
+
// src/domain/timeline.ts
|
|
7807
|
+
var GENERIC_NOT_SENT = { code: "generic_not_sent" };
|
|
7808
|
+
function buildTimelineSteps(facts) {
|
|
7809
|
+
return [
|
|
7810
|
+
step2("received", receivedReason(facts)),
|
|
7811
|
+
step2("prompt", promptReason(facts)),
|
|
7812
|
+
step2("triage", triageReason(facts)),
|
|
7813
|
+
step2("draft", draftReason(facts)),
|
|
7814
|
+
step2("evaluation", evaluationReason(facts)),
|
|
7815
|
+
step2("delivery", deliveryReason(facts)),
|
|
7816
|
+
step2("correction", correctionReason(facts))
|
|
7817
|
+
];
|
|
7818
|
+
}
|
|
7819
|
+
function step2(key, reason) {
|
|
7820
|
+
return reason === null ? { key, reached: true } : { key, reached: false, reason };
|
|
7821
|
+
}
|
|
7822
|
+
function receivedReason({
|
|
7823
|
+
conversation,
|
|
7824
|
+
conversationLoading
|
|
7825
|
+
}) {
|
|
7826
|
+
if (conversation) return null;
|
|
7827
|
+
return conversationLoading ? { code: "conversation_loading" } : { code: "conversation_unavailable" };
|
|
7828
|
+
}
|
|
7829
|
+
function promptReason({ conversation, job, decision }) {
|
|
7830
|
+
if (!job) return noResponseReason(decision);
|
|
7831
|
+
if (conversation?.systemPrompt) return null;
|
|
7832
|
+
return { code: "prompt_not_captured" };
|
|
7833
|
+
}
|
|
7834
|
+
function triageReason({ decision }) {
|
|
7835
|
+
if (decision.status === "error" && !decision.tag)
|
|
7836
|
+
return { code: "triage_failed", error: decision.error ?? null };
|
|
7837
|
+
return null;
|
|
7838
|
+
}
|
|
7839
|
+
function draftReason({ job, decision }) {
|
|
7840
|
+
if (!job) return noResponseReason(decision);
|
|
7841
|
+
if (job.responseText) return null;
|
|
7842
|
+
if (job.status === "pending") return { code: "draft_pending" };
|
|
7843
|
+
return { code: "draft_empty", error: job.error ?? null };
|
|
7844
|
+
}
|
|
7845
|
+
function evaluationReason({ job, decision }) {
|
|
7846
|
+
if (!job) return noResponseReason(decision);
|
|
7847
|
+
if (job.verdict) return null;
|
|
7848
|
+
return job.status === "pending" ? { code: "evaluation_pending" } : { code: "evaluation_missing" };
|
|
7849
|
+
}
|
|
7850
|
+
function deliveryReason(facts) {
|
|
7851
|
+
const { job, decision } = facts;
|
|
7852
|
+
if (!job) return noResponseReason(decision);
|
|
7853
|
+
switch (job.status) {
|
|
7854
|
+
case "sent":
|
|
7855
|
+
return null;
|
|
7856
|
+
case "pending":
|
|
7857
|
+
return { code: "reply_queued" };
|
|
7858
|
+
case "ready":
|
|
7859
|
+
return notSentReason(facts, job);
|
|
7860
|
+
case "expired": {
|
|
7861
|
+
const why = notSentReason(facts, job);
|
|
7862
|
+
return { code: "expired", detail: why.code === "generic_not_sent" ? null : why };
|
|
7863
|
+
}
|
|
7864
|
+
case "failed":
|
|
7865
|
+
return { code: "delivery_failed", error: job.error ?? null };
|
|
7866
|
+
case "superseded":
|
|
7867
|
+
return { code: "superseded" };
|
|
7868
|
+
case "test_draft":
|
|
7869
|
+
return { code: "test_draft" };
|
|
7870
|
+
default:
|
|
7871
|
+
return { code: "unexpected_status", status: job.status };
|
|
7872
|
+
}
|
|
7873
|
+
}
|
|
7874
|
+
function notSentReason({ policy, category }, job) {
|
|
7875
|
+
if (job.autoSendDecision === "hold" && job.guardrailHits.length === 0)
|
|
7876
|
+
return { code: "held_permanently" };
|
|
7877
|
+
if (job.autoSendDecision === "hold") return guardrailReason(job);
|
|
7878
|
+
switch (job.outcome) {
|
|
7879
|
+
case "needs_human":
|
|
7880
|
+
return notSendableReason(job, policy);
|
|
7881
|
+
case "guardrail_hold":
|
|
7882
|
+
return guardrailReason(job);
|
|
7883
|
+
case "awaiting_approval":
|
|
7884
|
+
return { code: "awaiting_approval" };
|
|
7885
|
+
case "ready":
|
|
7886
|
+
return notEligibleReason(job, policy, category);
|
|
7887
|
+
case "sent":
|
|
7888
|
+
return { code: "trial_mode" };
|
|
7889
|
+
case null:
|
|
7890
|
+
return legacyNotSentReason(job, policy, category);
|
|
7891
|
+
default:
|
|
7892
|
+
return GENERIC_NOT_SENT;
|
|
7893
|
+
}
|
|
7894
|
+
}
|
|
7895
|
+
function notSendableReason(job, policy) {
|
|
7896
|
+
const verdict = job.verdict;
|
|
7897
|
+
if (!verdict) return { code: "no_verdict" };
|
|
7898
|
+
if (verdict.status === "error") return { code: "evaluation_failed" };
|
|
7899
|
+
if (verdict.verdict === "hold") return { code: "judge_held" };
|
|
7900
|
+
if (!policy) return { code: "judge_not_authorized" };
|
|
7901
|
+
if ((verdict.confidence ?? 0) < policy.minConfidence) {
|
|
7902
|
+
return {
|
|
7903
|
+
code: "below_confidence",
|
|
7904
|
+
confidence: verdict.confidence ?? 0,
|
|
7905
|
+
minConfidence: policy.minConfidence
|
|
7906
|
+
};
|
|
7907
|
+
}
|
|
7908
|
+
if (requiresFollowup(verdict.verdict) && !policy.followupSendable)
|
|
7909
|
+
return { code: "followup_not_sendable" };
|
|
7910
|
+
return { code: "judge_not_authorized" };
|
|
7911
|
+
}
|
|
7912
|
+
function notEligibleReason(job, policy, category) {
|
|
7913
|
+
if (!policy) return GENERIC_NOT_SENT;
|
|
7914
|
+
if (!policy.evaluateConfigured) return { code: "evaluation_disabled" };
|
|
7915
|
+
if (!policy.autoSendEnabled) return { code: "auto_send_disabled" };
|
|
7916
|
+
if (category && !category.autoReplyEnabled)
|
|
7917
|
+
return { code: "category_auto_reply_off", categoryName: category.name };
|
|
7918
|
+
const isWhatsapp = job.channel === "whatsapp";
|
|
7919
|
+
if (isWhatsapp && policy.whatsappMode === "draft_only") return { code: "whatsapp_draft_only" };
|
|
7920
|
+
if (job.ineligibleReason === "no_publication_path") {
|
|
7921
|
+
return { code: "no_publication_path", channel: job.sourceChannel || null };
|
|
7922
|
+
}
|
|
7923
|
+
if (isRestrictedChannel(job.sourceChannel, policy.autoSendChannels)) {
|
|
7924
|
+
return { code: "channel_not_enabled", channel: job.sourceChannel };
|
|
7925
|
+
}
|
|
7926
|
+
if (!policy.senderEmail && !isWhatsapp) return { code: "no_sender_address" };
|
|
7927
|
+
return GENERIC_NOT_SENT;
|
|
7928
|
+
}
|
|
7929
|
+
function isRestrictedChannel(sourceChannel, allowed) {
|
|
7930
|
+
if (!sourceChannel) return false;
|
|
7931
|
+
if (!SUPPORT_CHANNELS.includes(sourceChannel)) return false;
|
|
7932
|
+
return !allowed.includes(sourceChannel);
|
|
7933
|
+
}
|
|
7934
|
+
function guardrailReason(job) {
|
|
7935
|
+
if (job.guardrailHits.length === 0) return { code: "guardrail_unrecorded" };
|
|
7936
|
+
return {
|
|
7937
|
+
code: "guardrail",
|
|
7938
|
+
hits: [...job.guardrailHits],
|
|
7939
|
+
reconstructed: Boolean(job.guardrailHitsReconstructedAt)
|
|
7940
|
+
};
|
|
7941
|
+
}
|
|
7942
|
+
function legacyNotSentReason(job, policy, category) {
|
|
7943
|
+
if (job.guardrailHits.length > 0) return guardrailReason(job);
|
|
7944
|
+
const verdict = job.verdict;
|
|
7945
|
+
if (policy && verdict && verdict.status === "success" && requiresFollowup(verdict.verdict) && !policy.followupSendable) {
|
|
7946
|
+
return { code: "legacy_followup_probable" };
|
|
7947
|
+
}
|
|
7948
|
+
if (verdict && (verdict.status === "error" || verdict.verdict === "hold"))
|
|
7949
|
+
return notSendableReason(job, policy);
|
|
7950
|
+
return notEligibleReason(job, policy, category);
|
|
7951
|
+
}
|
|
7952
|
+
function correctionReason({ comparisons }) {
|
|
7953
|
+
return comparisons.length > 0 ? null : { code: "no_correction" };
|
|
7954
|
+
}
|
|
7955
|
+
function noResponseReason(decision) {
|
|
7956
|
+
if (decision.escalated) return { code: "ticket_escalated" };
|
|
7957
|
+
if (decision.conversationOver) return { code: "conversation_over" };
|
|
7958
|
+
if (decision.status === "error") return { code: "triage_error", error: decision.error ?? null };
|
|
7959
|
+
return { code: "category_not_drafting" };
|
|
7960
|
+
}
|
|
7961
|
+
|
|
7962
|
+
// src/domain/trace-refs.ts
|
|
7963
|
+
function toTraceRefs(traceId, observationIds) {
|
|
7964
|
+
if (!traceId && observationIds.length === 0) return [];
|
|
7965
|
+
return [{ ...traceId ? { traceId } : {}, observationIds: [...observationIds] }];
|
|
7966
|
+
}
|
|
7967
|
+
|
|
7968
|
+
// src/settings/delivery-policy.ts
|
|
7969
|
+
function evaluateNode(settings) {
|
|
7970
|
+
const node = settings.nodes?.evaluate;
|
|
7971
|
+
return node && typeof node === "object" ? node : null;
|
|
7972
|
+
}
|
|
7973
|
+
function toDeliveryPolicy(raw) {
|
|
7974
|
+
if (!raw || typeof raw !== "object") return null;
|
|
7975
|
+
const settings = raw;
|
|
7976
|
+
const evaluate2 = evaluateNode(settings);
|
|
7977
|
+
const senderEmail = typeof settings.senderEmail === "string" ? settings.senderEmail : "";
|
|
7978
|
+
return {
|
|
7979
|
+
followupSendable: typeof evaluate2?.escalationEnabled === "boolean" ? evaluate2.escalationEnabled : DEFAULT_ESCALATION_ENABLED,
|
|
7980
|
+
minConfidence: typeof evaluate2?.minConfidence === "number" ? evaluate2.minConfidence : DEFAULT_MIN_CONFIDENCE,
|
|
7981
|
+
evaluateConfigured: evaluate2 !== null,
|
|
7982
|
+
autoSendEnabled: settings.autoSendEnabled === true,
|
|
7983
|
+
senderEmail: senderEmail === "" ? null : senderEmail,
|
|
7984
|
+
whatsappMode: typeof settings.whatsappMode === "string" ? settings.whatsappMode : null,
|
|
7985
|
+
autoSendChannels: Array.isArray(settings.autoSendChannels) ? settings.autoSendChannels : [...DEFAULT_AUTO_SEND_CHANNELS],
|
|
7986
|
+
dryRun: settings.dryRun === true,
|
|
7987
|
+
audit: toAuditTags(settings)
|
|
7988
|
+
};
|
|
7989
|
+
}
|
|
7990
|
+
|
|
7991
|
+
// src/functions/list-agents.ts
|
|
7992
|
+
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.";
|
|
7993
|
+
function buildListAgentsFunctionDef(config) {
|
|
7994
|
+
return {
|
|
7995
|
+
universalIdentifier: mcpToolIdentifierFor(config, "list-agents"),
|
|
7996
|
+
name: "list-agents",
|
|
7997
|
+
trigger: mcpToolTrigger(DESCRIPTION3)
|
|
7998
|
+
};
|
|
7999
|
+
}
|
|
8000
|
+
function createListAgentsHandler() {
|
|
8001
|
+
return (ctx) => describeAgents(ctx.api);
|
|
8002
|
+
}
|
|
8003
|
+
async function describeAgents(api) {
|
|
8004
|
+
return (await listAgents(api)).map(toAgentSummary);
|
|
8005
|
+
}
|
|
8006
|
+
function toAgentSummary(agent) {
|
|
8007
|
+
return {
|
|
8008
|
+
id: agent.id,
|
|
8009
|
+
name: agent.name,
|
|
8010
|
+
promptName: agent.promptName,
|
|
8011
|
+
promptLabel: agent.promptLabel,
|
|
8012
|
+
promptVersion: agent.promptVersion,
|
|
8013
|
+
modelId: agent.modelId
|
|
8014
|
+
};
|
|
8015
|
+
}
|
|
8016
|
+
|
|
8017
|
+
// src/functions/list-categories.ts
|
|
8018
|
+
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.";
|
|
8019
|
+
function buildListCategoriesFunctionDef(config) {
|
|
8020
|
+
return {
|
|
8021
|
+
universalIdentifier: mcpToolIdentifierFor(config, "list-categories"),
|
|
8022
|
+
name: "list-categories",
|
|
8023
|
+
trigger: mcpToolTrigger(DESCRIPTION4)
|
|
8024
|
+
};
|
|
8025
|
+
}
|
|
8026
|
+
function createListCategoriesHandler() {
|
|
8027
|
+
return (ctx) => describeCategories(ctx.api);
|
|
8028
|
+
}
|
|
8029
|
+
async function describeCategories(api) {
|
|
8030
|
+
const [categories, groupsPage] = await Promise.all([
|
|
8031
|
+
listCategories(api),
|
|
8032
|
+
api.list("category-group", { limit: CATEGORY_PAGE_SIZE })
|
|
8033
|
+
]);
|
|
8034
|
+
const groups = new Map(groupsPage.items.map(toCategoryGroup).map((group) => [group.id, group]));
|
|
8035
|
+
return categories.map((category) => {
|
|
8036
|
+
const group = groups.get(category.groupId ?? "") ?? null;
|
|
8037
|
+
return { category, group, groupOrder: group?.order ?? Number.NEGATIVE_INFINITY };
|
|
8038
|
+
}).sort(compareByGroupThenCategory).map(({ category, group }) => toCategorySummary(category, group));
|
|
8039
|
+
}
|
|
8040
|
+
function toCategorySummary(category, group) {
|
|
8041
|
+
return {
|
|
8042
|
+
...toCategoryFields(category),
|
|
8043
|
+
agentId: category.agentId,
|
|
8044
|
+
group: group === null ? null : { id: group.id, name: group.name }
|
|
8045
|
+
};
|
|
8046
|
+
}
|
|
8047
|
+
function toCategoryFields(category) {
|
|
8048
|
+
return {
|
|
8049
|
+
id: category.id,
|
|
8050
|
+
name: category.name,
|
|
8051
|
+
tagName: category.tagName,
|
|
8052
|
+
description: category.description,
|
|
8053
|
+
examples: category.examples,
|
|
8054
|
+
autoReplyEnabled: category.autoReplyEnabled,
|
|
8055
|
+
fastResponseEnabled: category.fastResponseEnabled,
|
|
8056
|
+
followupAutoReplyEnabled: category.followupAutoReplyEnabled,
|
|
8057
|
+
followupFastResponseEnabled: category.followupFastResponseEnabled
|
|
8058
|
+
};
|
|
8059
|
+
}
|
|
8060
|
+
|
|
8061
|
+
// src/functions/explain-ticket.ts
|
|
8062
|
+
var HISTORY_LIMIT = 20;
|
|
8063
|
+
var NEWEST_CORRECTION_FIRST = JSON.stringify([{ field: "capturedAt", direction: "desc" }]);
|
|
8064
|
+
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.";
|
|
8065
|
+
function buildExplainTicketFunctionDef(config) {
|
|
8066
|
+
return {
|
|
8067
|
+
universalIdentifier: mcpToolIdentifierFor(config, "explain-ticket"),
|
|
8068
|
+
name: "explain-ticket",
|
|
8069
|
+
trigger: mcpToolTrigger(DESCRIPTION5),
|
|
8070
|
+
input: [
|
|
8071
|
+
{
|
|
8072
|
+
universalIdentifier: EXPLAIN_TICKET_INPUT_TICKET_ID_UID,
|
|
8073
|
+
name: "ticketId",
|
|
8074
|
+
type: appKit.FieldType.TEXT,
|
|
8075
|
+
label: "Ticket id",
|
|
8076
|
+
description: "The helpdesk ticket id, as listed by list_tickets.",
|
|
8077
|
+
isNullable: false
|
|
8078
|
+
}
|
|
8079
|
+
]
|
|
8080
|
+
};
|
|
8081
|
+
}
|
|
8082
|
+
function createExplainTicketHandler(config) {
|
|
8083
|
+
return mcpToolHandler((api, input) => explainTicket(api, config, input));
|
|
8084
|
+
}
|
|
8085
|
+
async function explainTicket(api, config, input) {
|
|
8086
|
+
const { ticketId } = input;
|
|
8087
|
+
if (typeof ticketId !== "string" || ticketId === "") {
|
|
8088
|
+
throw new ToolInputError('"ticketId" must be a non-empty string.');
|
|
8089
|
+
}
|
|
8090
|
+
const [decision, responses, comparisons, settings] = await Promise.all([
|
|
8091
|
+
readNewestDecision(api, ticketId),
|
|
8092
|
+
listTicketResponses(api, ticketId, HISTORY_LIMIT),
|
|
8093
|
+
readCorrections(api, ticketId),
|
|
8094
|
+
getSettingsOrNull(api)
|
|
8095
|
+
]);
|
|
8096
|
+
if (decision === null) return { found: false };
|
|
8097
|
+
const latest = responses[0];
|
|
8098
|
+
const categoryRead = readCategory(api, decision.categoryId);
|
|
8099
|
+
const agentId = latest?.agentId ?? (await categoryRead)?.agentId ?? null;
|
|
8100
|
+
const [category, agent] = await Promise.all([categoryRead, readAgent(api, agentId)]);
|
|
8101
|
+
return {
|
|
8102
|
+
found: true,
|
|
8103
|
+
ticketId,
|
|
8104
|
+
ticketUrl: decision.ticketUrl,
|
|
8105
|
+
triage: toTriageSection(decision, settings, config),
|
|
8106
|
+
responses: responses.map(toResponseSection),
|
|
8107
|
+
correction: comparisons[0] === void 0 ? null : toCorrectionSection(comparisons[0]),
|
|
8108
|
+
category: category === null ? null : toCategoryFields(category),
|
|
8109
|
+
agent,
|
|
8110
|
+
timeline: buildTimelineSteps({
|
|
8111
|
+
decision,
|
|
8112
|
+
job: latest,
|
|
8113
|
+
comparisons,
|
|
8114
|
+
conversation: persistedConversationOf(latest, comparisons[0]),
|
|
8115
|
+
policy: settings === null ? null : toDeliveryPolicy(settings),
|
|
8116
|
+
category
|
|
8117
|
+
})
|
|
8118
|
+
};
|
|
8119
|
+
}
|
|
8120
|
+
async function readNewestDecision(api, ticketId) {
|
|
8121
|
+
const page = await api.list("triage-decision", {
|
|
8122
|
+
filter: { ticketId },
|
|
8123
|
+
sort: NEWEST_DECISION_FIRST,
|
|
8124
|
+
limit: 1
|
|
8125
|
+
});
|
|
8126
|
+
return page.items[0] === void 0 ? null : toTriageDecision(page.items[0]);
|
|
8127
|
+
}
|
|
8128
|
+
async function readCorrections(api, ticketId) {
|
|
8129
|
+
const page = await api.list("response-comparison", {
|
|
8130
|
+
filter: { ticketId },
|
|
8131
|
+
sort: NEWEST_CORRECTION_FIRST,
|
|
8132
|
+
limit: HISTORY_LIMIT
|
|
8133
|
+
});
|
|
8134
|
+
return page.items.map(toResponseComparison);
|
|
8135
|
+
}
|
|
8136
|
+
async function readCategory(api, categoryId) {
|
|
8137
|
+
const record = await getOptional(api, "category", categoryId);
|
|
8138
|
+
return record === null ? null : toCategory(record);
|
|
8139
|
+
}
|
|
8140
|
+
async function readAgent(api, agentId) {
|
|
8141
|
+
const record = await getOptional(api, "agent", agentId);
|
|
8142
|
+
if (record === null) return null;
|
|
8143
|
+
const { modelId: _modelId, ...section2 } = toAgentSummary(toAgent(record));
|
|
8144
|
+
return section2;
|
|
8145
|
+
}
|
|
8146
|
+
function persistedConversationOf(job, correction) {
|
|
8147
|
+
if (job !== void 0 && job.tracedInput.length > 0) {
|
|
8148
|
+
return { systemPrompt: job.tracedInput.find((m) => m.role === "system")?.content ?? null };
|
|
8149
|
+
}
|
|
8150
|
+
return correction !== void 0 && correction.conversationMessages.length > 0 ? { systemPrompt: null } : null;
|
|
8151
|
+
}
|
|
8152
|
+
function toTriageSection(decision, settings, config) {
|
|
8153
|
+
const traceRefs = toTraceRefs(decision.langfuseTraceId, decision.langfuseObservationIds);
|
|
8154
|
+
return {
|
|
8155
|
+
decidedAt: decision.decidedAt,
|
|
8156
|
+
origin: decision.origin,
|
|
8157
|
+
status: decision.status,
|
|
8158
|
+
error: decision.error,
|
|
8159
|
+
categoryId: decision.categoryId,
|
|
8160
|
+
tag: decision.tag,
|
|
8161
|
+
confidence: decision.confidence,
|
|
8162
|
+
reasoning: decision.reasoning,
|
|
8163
|
+
conversationOver: decision.conversationOver,
|
|
8164
|
+
escalated: decision.escalated,
|
|
8165
|
+
escalationConfidence: decision.escalationConfidence,
|
|
8166
|
+
escalationReasoning: decision.escalationReasoning,
|
|
8167
|
+
prompts: triagePromptsOf(decision.origin, settings, config),
|
|
8168
|
+
traceRefs,
|
|
8169
|
+
traceAvailable: traceRefs.length > 0
|
|
8170
|
+
};
|
|
8171
|
+
}
|
|
8172
|
+
function triagePromptsOf(origin, settings, config) {
|
|
8173
|
+
if (origin === "followup") return { triage: null, escalation: null };
|
|
8174
|
+
const nodes = settings?.nodes;
|
|
8175
|
+
const bindingOf = (node, derivedName) => node === null ? null : promptRefFor(node, derivedName);
|
|
8176
|
+
return {
|
|
8177
|
+
triage: bindingOf(nodes?.triage, resolvePromptName("triage", config)),
|
|
8178
|
+
escalation: bindingOf(nodes?.escalate, resolvePromptName("escalation", config))
|
|
8179
|
+
};
|
|
8180
|
+
}
|
|
8181
|
+
function toResponseSection(response) {
|
|
8182
|
+
return {
|
|
8183
|
+
id: response.id,
|
|
8184
|
+
status: response.status,
|
|
8185
|
+
outcome: response.outcome,
|
|
8186
|
+
generatedAt: response.generatedAt,
|
|
8187
|
+
sentAt: response.sentAt,
|
|
8188
|
+
verdict: response.verdict,
|
|
8189
|
+
guardrailHits: response.guardrailHits,
|
|
8190
|
+
autoSendDecision: response.autoSendDecision,
|
|
8191
|
+
ineligibleReason: response.ineligibleReason,
|
|
8192
|
+
promptName: response.promptName,
|
|
8193
|
+
promptVersion: response.promptVersion,
|
|
8194
|
+
traceRefs: [
|
|
8195
|
+
...toTraceRefs(
|
|
8196
|
+
response.langfuseTraceId,
|
|
8197
|
+
response.langfuseObservationId ? [response.langfuseObservationId] : []
|
|
8198
|
+
),
|
|
8199
|
+
...evaluationTraceRefs(response.evaluationObservationId)
|
|
8200
|
+
],
|
|
8201
|
+
sentText: response.status === "sent" ? response.responseText : null,
|
|
8202
|
+
tracedInput: response.tracedInput.filter((message) => message.role !== "system")
|
|
8203
|
+
};
|
|
8204
|
+
}
|
|
8205
|
+
function evaluationTraceRefs(observationId) {
|
|
8206
|
+
return observationId ? [{ observationIds: [observationId], withoutMessages: true }] : [];
|
|
8207
|
+
}
|
|
8208
|
+
function toCorrectionSection(correction) {
|
|
8209
|
+
return {
|
|
8210
|
+
capturedAt: correction.capturedAt,
|
|
8211
|
+
generatedText: correction.generatedText,
|
|
8212
|
+
sentText: correction.sentText,
|
|
8213
|
+
diff: correction.diff
|
|
8214
|
+
};
|
|
8215
|
+
}
|
|
8216
|
+
|
|
8217
|
+
// src/functions/prompt-scope.ts
|
|
8218
|
+
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.";
|
|
8219
|
+
function buildPromptScopeFunctionDef(config) {
|
|
8220
|
+
return {
|
|
8221
|
+
universalIdentifier: mcpToolIdentifierFor(config, "prompt-scope"),
|
|
8222
|
+
name: "prompt-scope",
|
|
8223
|
+
trigger: mcpToolTrigger(DESCRIPTION6, { exposed: false })
|
|
8224
|
+
};
|
|
8225
|
+
}
|
|
8226
|
+
function createPromptScopeHandler(config) {
|
|
8227
|
+
return (ctx) => promptScope(ctx.api, config);
|
|
8228
|
+
}
|
|
8229
|
+
async function promptScope(api, config) {
|
|
8230
|
+
const [agents, settings] = await Promise.all([
|
|
8231
|
+
listAgents(api),
|
|
8232
|
+
getSettingsOrNull(api)
|
|
8233
|
+
]);
|
|
8234
|
+
const candidates = [
|
|
8235
|
+
...PROMPT_SLOTS.map((slot) => resolvePromptName(slot, config)),
|
|
8236
|
+
...agents.map((agent) => agent.promptName),
|
|
8237
|
+
...settings === null ? [] : promptNamesChosenIn(settings)
|
|
8238
|
+
];
|
|
8239
|
+
return { names: [...new Set(candidates.filter(isExactName))] };
|
|
8240
|
+
}
|
|
8241
|
+
function promptNamesChosenIn(settings) {
|
|
8242
|
+
const nodes = Object.values(settings.nodes ?? {});
|
|
8243
|
+
const stepPrompts = nodes.map((node) => node?.prompt?.name);
|
|
8244
|
+
return [
|
|
8245
|
+
...stepPrompts,
|
|
8246
|
+
settings.channelPromptEmail || DEFAULT_CHANNEL_PROMPT_EMAIL,
|
|
8247
|
+
settings.channelPromptWhatsapp || DEFAULT_CHANNEL_PROMPT_WHATSAPP
|
|
8248
|
+
];
|
|
8249
|
+
}
|
|
8250
|
+
function isExactName(name) {
|
|
8251
|
+
return typeof name === "string" && name !== "" && !name.includes("*");
|
|
8252
|
+
}
|
|
8253
|
+
|
|
6877
8254
|
// src/pages/manifest.ts
|
|
6878
8255
|
function pageIdentifierFor(config, key) {
|
|
6879
8256
|
const id = config.identifiers[key];
|
|
@@ -7014,6 +8391,40 @@ var FUNCTION_ASSEMBLY = [
|
|
|
7014
8391
|
key: "test-gorgias-webhook",
|
|
7015
8392
|
build: buildTestGorgiasWebhookFunctionDef,
|
|
7016
8393
|
createHandler: createTestGorgiasWebhookHandler
|
|
8394
|
+
},
|
|
8395
|
+
// The read-only MCP tools (spec §5.3). Their identifiers are optional —
|
|
8396
|
+
// `mcpToolIdentifierFor` derives them — so they sit outside
|
|
8397
|
+
// FUNCTION_IDENTIFIER_KEYS and this assembly covers that list PLUS the MCP tools below.
|
|
8398
|
+
{
|
|
8399
|
+
key: "ticket-stats",
|
|
8400
|
+
build: buildTicketStatsFunctionDef,
|
|
8401
|
+
createHandler: () => createTicketStatsHandler()
|
|
8402
|
+
},
|
|
8403
|
+
{
|
|
8404
|
+
key: "list-tickets",
|
|
8405
|
+
build: buildListTicketsFunctionDef,
|
|
8406
|
+
createHandler: () => createListTicketsHandler()
|
|
8407
|
+
},
|
|
8408
|
+
{
|
|
8409
|
+
key: "explain-ticket",
|
|
8410
|
+
build: buildExplainTicketFunctionDef,
|
|
8411
|
+
createHandler: createExplainTicketHandler
|
|
8412
|
+
},
|
|
8413
|
+
{
|
|
8414
|
+
key: "list-categories",
|
|
8415
|
+
build: buildListCategoriesFunctionDef,
|
|
8416
|
+
createHandler: () => createListCategoriesHandler()
|
|
8417
|
+
},
|
|
8418
|
+
{
|
|
8419
|
+
key: "list-agents",
|
|
8420
|
+
build: buildListAgentsFunctionDef,
|
|
8421
|
+
createHandler: () => createListAgentsHandler()
|
|
8422
|
+
},
|
|
8423
|
+
// Internal (`exposed: false`): the OS asks it which prompt names belong to this app (D5).
|
|
8424
|
+
{
|
|
8425
|
+
key: "prompt-scope",
|
|
8426
|
+
build: buildPromptScopeFunctionDef,
|
|
8427
|
+
createHandler: createPromptScopeHandler
|
|
7017
8428
|
}
|
|
7018
8429
|
];
|
|
7019
8430
|
function buildPromptsAllowlist() {
|