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