@apotech-os/support-kit 8.2.0 → 8.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -4
- package/dist/{chunk-LXHPPWPM.js → chunk-D3QGGJAI.js} +73 -14
- package/dist/chunk-D3QGGJAI.js.map +1 -0
- package/dist/index.cjs +220 -47
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +32 -2
- package/dist/index.d.ts +32 -2
- package/dist/index.js +140 -27
- package/dist/index.js.map +1 -1
- package/dist/ui/index.cjs +228 -55
- package/dist/ui/index.cjs.map +1 -1
- package/dist/ui/index.js +166 -43
- package/dist/ui/index.js.map +1 -1
- package/package.json +11 -11
- package/dist/chunk-LXHPPWPM.js.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -747,9 +747,9 @@ async function draftWithTools(params) {
|
|
|
747
747
|
return finish(null, sources, messages, null);
|
|
748
748
|
}
|
|
749
749
|
function finish(text, sources, messages, attribution) {
|
|
750
|
-
const
|
|
751
|
-
if (!
|
|
752
|
-
return { text:
|
|
750
|
+
const trimmed2 = (text ?? "").trim();
|
|
751
|
+
if (!trimmed2) throw new Error("Provider returned empty response");
|
|
752
|
+
return { text: trimmed2, sources, messages, revised: false, ...attribution ? { attribution } : {} };
|
|
753
753
|
}
|
|
754
754
|
function attributionOf(result, promptRef) {
|
|
755
755
|
return {
|
|
@@ -896,9 +896,9 @@ function buildMessages(input) {
|
|
|
896
896
|
];
|
|
897
897
|
}
|
|
898
898
|
function section(title, body) {
|
|
899
|
-
const
|
|
900
|
-
return
|
|
901
|
-
${
|
|
899
|
+
const trimmed2 = body?.trim();
|
|
900
|
+
return trimmed2 ? `## ${title}
|
|
901
|
+
${trimmed2}` : null;
|
|
902
902
|
}
|
|
903
903
|
|
|
904
904
|
// src/graph/revise.ts
|
|
@@ -1136,7 +1136,19 @@ var GENERATED_RESPONSE_STATUSES = [
|
|
|
1136
1136
|
// serve, send or revive a test draft — and terminal is also what frees the
|
|
1137
1137
|
// `openTicketKey` (see `openTicketKeyFor`), so an essay can never hold the
|
|
1138
1138
|
// real webhook at G9.
|
|
1139
|
-
"test_draft"
|
|
1139
|
+
"test_draft",
|
|
1140
|
+
// 24/09/2026 — where a draft goes when a newer customer message arrives
|
|
1141
|
+
// before it was sent. The follow-up webhook used to refuse the new message
|
|
1142
|
+
// instead (G9 stopped on "une réponse est déjà ouverte"), which lost it
|
|
1143
|
+
// outright: Gorgias never replays a webhook it acked. The row is closed and
|
|
1144
|
+
// the pass drafts again, so the customer's latest message always wins.
|
|
1145
|
+
//
|
|
1146
|
+
// NOT `invalidated`, for the reason `test_draft` was split off it: the ticket
|
|
1147
|
+
// page and the dashboard read `invalidated` as "a human intervened", and a
|
|
1148
|
+
// draft replaced by a fresher one is nobody's intervention. Terminal, which
|
|
1149
|
+
// is also what releases `openTicketKey` (see `openTicketKeyFor`) — without
|
|
1150
|
+
// that release the replacement draft could not be created at all.
|
|
1151
|
+
"superseded"
|
|
1140
1152
|
];
|
|
1141
1153
|
function isGeneratedResponseStatus(value) {
|
|
1142
1154
|
return typeof value === "string" && GENERATED_RESPONSE_STATUSES.includes(value);
|
|
@@ -1146,15 +1158,21 @@ var ALLOWED_TRANSITIONS = {
|
|
|
1146
1158
|
// very `pending` row it opened, and no other status can become a test
|
|
1147
1159
|
// draft after the fact — an operator invalidating a real `ready` draft is
|
|
1148
1160
|
// expressing "discard this", not "this was an essay".
|
|
1149
|
-
pending: ["ready", "failed", "no_reply_needed", "sending", "invalidated", "test_draft"],
|
|
1150
|
-
ready: ["sending", "invalidated", "expired"],
|
|
1161
|
+
pending: ["ready", "failed", "no_reply_needed", "sending", "invalidated", "test_draft", "superseded"],
|
|
1162
|
+
ready: ["sending", "invalidated", "expired", "superseded"],
|
|
1163
|
+
// `sending` reaches neither `invalidated` nor `superseded`, and for the same
|
|
1164
|
+
// reason: a worker holds the send lock, so nobody yet knows whether the
|
|
1165
|
+
// customer received anything. Closing that row would strand the send — the
|
|
1166
|
+
// sweep could no longer reclaim it, and `sentMessageId` would never be
|
|
1167
|
+
// written. A follow-up pass that meets one waits for it instead.
|
|
1151
1168
|
sending: ["sent", "ready"],
|
|
1152
1169
|
sent: [],
|
|
1153
1170
|
failed: [],
|
|
1154
1171
|
no_reply_needed: [],
|
|
1155
1172
|
invalidated: [],
|
|
1156
1173
|
expired: [],
|
|
1157
|
-
test_draft: []
|
|
1174
|
+
test_draft: [],
|
|
1175
|
+
superseded: []
|
|
1158
1176
|
};
|
|
1159
1177
|
function canTransition(from, to) {
|
|
1160
1178
|
if (!isGeneratedResponseStatus(from) || !isGeneratedResponseStatus(to)) return false;
|
|
@@ -2578,6 +2596,15 @@ var SUPPORT_KIT_SETTINGS_FIELDS = [
|
|
|
2578
2596
|
{ key: "autoRepliedTag", type: "string", label: "Auto-replied tag", default: "wai/auto-replied" },
|
|
2579
2597
|
{ key: "needsReviewTag", type: "string", label: "Review-before-send tag", default: "wai/escalated" },
|
|
2580
2598
|
{ key: "followupTag", type: "string", label: "Followup tag", default: "wai/human-required" },
|
|
2599
|
+
// The app's OWNERSHIP mark: applied to every ticket its triage sees, in the
|
|
2600
|
+
// same call as the tags above (`adapters/gorgias-tags.ts`), so that a later
|
|
2601
|
+
// pass can tell this app's tickets from a neighbouring app's on a SHARED
|
|
2602
|
+
// Gorgias account. Every other audit tag here ships the same default in
|
|
2603
|
+
// every app — `handledTag` is `wai/triaged` everywhere — so none of them can
|
|
2604
|
+
// answer "whose ticket is this?". Empty by default for the same reason a
|
|
2605
|
+
// shared default would be useless: an ownership mark two apps have in common
|
|
2606
|
+
// marks nothing. Empty means "stamp nothing".
|
|
2607
|
+
{ key: "appScopeTag", type: "string", label: "App scope tag", default: "" },
|
|
2581
2608
|
// Follow-up webhook (spec-gorgias-followup-webhook-v1 D2)
|
|
2582
2609
|
// The tag a ticket must ALREADY carry for this app to answer a SUBSEQUENT
|
|
2583
2610
|
// customer message on it. Deliberately empty by default, twice over:
|
|
@@ -2701,6 +2728,37 @@ function isConfiguredNode(nodes) {
|
|
|
2701
2728
|
return typeof triage2 === "object" && triage2 !== null;
|
|
2702
2729
|
}
|
|
2703
2730
|
|
|
2731
|
+
// src/settings/warnings.ts
|
|
2732
|
+
var HUMAN_TAKEOVER_KEYS = ["escalationTag", "needsReviewTag", "followupTag"];
|
|
2733
|
+
var AUDIT_TAG_KEYS = ["unknownTag", "handledTag", "escalationTag", "autoRepliedTag", "needsReviewTag", "followupTag"];
|
|
2734
|
+
function settingsWarnings(settings) {
|
|
2735
|
+
const warnings = [];
|
|
2736
|
+
const appScopeTag = trimmed(settings.appScopeTag);
|
|
2737
|
+
const webhookScopeTag = trimmed(settings.webhookScopeTag);
|
|
2738
|
+
const collidesWith = (keys) => appScopeTag ? keys.filter((key) => trimmed(settings[key]) === appScopeTag) : [];
|
|
2739
|
+
if (collidesWith(HUMAN_TAKEOVER_KEYS).length > 0) {
|
|
2740
|
+
warnings.push({
|
|
2741
|
+
key: "appScopeTagVetoesFollowups",
|
|
2742
|
+
message: "Le tag d\u2019appartenance 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."
|
|
2743
|
+
});
|
|
2744
|
+
} else if (collidesWith(AUDIT_TAG_KEYS).length > 0) {
|
|
2745
|
+
warnings.push({
|
|
2746
|
+
key: "appScopeTagCollision",
|
|
2747
|
+
message: "Le tag d\u2019appartenance 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."
|
|
2748
|
+
});
|
|
2749
|
+
}
|
|
2750
|
+
if (appScopeTag && webhookScopeTag && appScopeTag !== webhookScopeTag) {
|
|
2751
|
+
warnings.push({
|
|
2752
|
+
key: "scopeTagMismatch",
|
|
2753
|
+
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."
|
|
2754
|
+
});
|
|
2755
|
+
}
|
|
2756
|
+
return warnings;
|
|
2757
|
+
}
|
|
2758
|
+
function trimmed(value) {
|
|
2759
|
+
return typeof value === "string" ? value.trim() : "";
|
|
2760
|
+
}
|
|
2761
|
+
|
|
2704
2762
|
// src/settings/to-profile.ts
|
|
2705
2763
|
var DEFAULT_REASONING = "off";
|
|
2706
2764
|
var DEFAULT_MAX_TOOL_CALLS = 5;
|
|
@@ -2711,7 +2769,8 @@ function toAuditTags(settings) {
|
|
|
2711
2769
|
escalationTag: settings.escalationTag,
|
|
2712
2770
|
sentTag: settings.autoRepliedTag,
|
|
2713
2771
|
needsHumanTag: settings.needsReviewTag,
|
|
2714
|
-
followupTag: settings.followupTag
|
|
2772
|
+
followupTag: settings.followupTag,
|
|
2773
|
+
appScopeTag: settings.appScopeTag
|
|
2715
2774
|
};
|
|
2716
2775
|
}
|
|
2717
2776
|
var DEFAULT_MIN_CONFIDENCE = 0.8;
|
|
@@ -2881,10 +2940,10 @@ function dedupeTagNames(tags) {
|
|
|
2881
2940
|
const seen = /* @__PURE__ */ new Set();
|
|
2882
2941
|
const out = [];
|
|
2883
2942
|
for (const tag of tags) {
|
|
2884
|
-
const
|
|
2885
|
-
if (
|
|
2886
|
-
seen.add(
|
|
2887
|
-
out.push(
|
|
2943
|
+
const trimmed2 = (tag ?? "").trim();
|
|
2944
|
+
if (trimmed2 && !seen.has(trimmed2)) {
|
|
2945
|
+
seen.add(trimmed2);
|
|
2946
|
+
out.push(trimmed2);
|
|
2888
2947
|
}
|
|
2889
2948
|
}
|
|
2890
2949
|
return out;
|
|
@@ -2896,7 +2955,7 @@ async function extraTagsFor(api, tagName) {
|
|
|
2896
2955
|
}
|
|
2897
2956
|
async function resolveHandledTags(api, classification, audit) {
|
|
2898
2957
|
const extraTags = await extraTagsFor(api, classification.category);
|
|
2899
|
-
return dedupeTagNames([classification.category, ...extraTags, audit.handledTag]);
|
|
2958
|
+
return dedupeTagNames([classification.category, ...extraTags, audit.handledTag, audit.appScopeTag]);
|
|
2900
2959
|
}
|
|
2901
2960
|
|
|
2902
2961
|
// src/adapters/ctx-ports.ts
|
|
@@ -2954,9 +3013,9 @@ function createGorgiasStatePort(api) {
|
|
|
2954
3013
|
await api.integrations.run("gorgias", "renameTicket", { ticketId: ref.id, subject });
|
|
2955
3014
|
},
|
|
2956
3015
|
async flag(ref, tag) {
|
|
2957
|
-
const
|
|
2958
|
-
if (!
|
|
2959
|
-
await api.integrations.run("gorgias", "applyTags", { ticketId: ref.id, names: [
|
|
3016
|
+
const trimmed2 = tag.trim();
|
|
3017
|
+
if (!trimmed2) return;
|
|
3018
|
+
await api.integrations.run("gorgias", "applyTags", { ticketId: ref.id, names: [trimmed2] });
|
|
2960
3019
|
}
|
|
2961
3020
|
};
|
|
2962
3021
|
}
|
|
@@ -3063,8 +3122,8 @@ function createRecordingReplyPort() {
|
|
|
3063
3122
|
function createRecordingStatePort(api) {
|
|
3064
3123
|
const tagged = [];
|
|
3065
3124
|
const push = (tag) => {
|
|
3066
|
-
const
|
|
3067
|
-
if (
|
|
3125
|
+
const trimmed2 = tag.trim();
|
|
3126
|
+
if (trimmed2 && !tagged.includes(trimmed2)) tagged.push(trimmed2);
|
|
3068
3127
|
};
|
|
3069
3128
|
return {
|
|
3070
3129
|
port: {
|
|
@@ -3759,6 +3818,7 @@ async function handleTicketFailure(ctx, ref, err, deps) {
|
|
|
3759
3818
|
await finalizeFailedResponse(ctx, ref, err.generatedResponseId, message);
|
|
3760
3819
|
} else {
|
|
3761
3820
|
await writeErrorDecision(ctx, ref, message, deps);
|
|
3821
|
+
await stampAppScope(ctx, ref, deps.profile.audit.appScopeTag, deps.ports);
|
|
3762
3822
|
}
|
|
3763
3823
|
await escalateTicket(ctx, ref, deps);
|
|
3764
3824
|
}
|
|
@@ -3798,6 +3858,16 @@ async function writeErrorDecision(ctx, ref, message, deps) {
|
|
|
3798
3858
|
async function escalateTicket(ctx, ref, deps) {
|
|
3799
3859
|
await flagEscalation(ctx, ref, deps.profile.audit.escalationTag, deps.ports);
|
|
3800
3860
|
}
|
|
3861
|
+
async function stampAppScope(ctx, ref, tag, ports) {
|
|
3862
|
+
if (!tag) return;
|
|
3863
|
+
try {
|
|
3864
|
+
await ports.state.flag(ref, tag);
|
|
3865
|
+
} catch (err) {
|
|
3866
|
+
ctx.logger.error(`triage-tick: failed to stamp the app scope tag on ticket ${ref.id}`, {
|
|
3867
|
+
error: err instanceof Error ? err.message : String(err)
|
|
3868
|
+
});
|
|
3869
|
+
}
|
|
3870
|
+
}
|
|
3801
3871
|
async function flagEscalation(ctx, ref, tag, ports) {
|
|
3802
3872
|
if (!tag) {
|
|
3803
3873
|
ctx.logger.warn(`triage-tick: ticket ${ref.id} is escalated but escalationTag is not configured \u2014 no tag applied`);
|
|
@@ -3921,11 +3991,11 @@ async function sweepHandler(ctx) {
|
|
|
3921
3991
|
const statePort = createGorgiasStatePort(ctx.api);
|
|
3922
3992
|
const escalationTag = typeof settings?.escalationTag === "string" ? settings.escalationTag : "";
|
|
3923
3993
|
if (!escalationTag) {
|
|
3924
|
-
ctx.logger.warn("sweep: escalationTag is not configured \u2014 a stalled-send reclaim will proceed without an escalation tag");
|
|
3994
|
+
ctx.logger.warn("sweep: escalationTag is not configured \u2014 a stalled-send reclaim or an orphaned-pending hand-off will proceed without an escalation tag");
|
|
3925
3995
|
}
|
|
3926
3996
|
await sweepExpiredReady(ctx, now);
|
|
3927
3997
|
await sweepStalledSending(ctx, now, escalationTag, statePort);
|
|
3928
|
-
await sweepStalledPending(ctx, now);
|
|
3998
|
+
await sweepStalledPending(ctx, now, escalationTag, statePort);
|
|
3929
3999
|
await upsertPipelineState(ctx.api, { lastSweepAt: now });
|
|
3930
4000
|
}
|
|
3931
4001
|
async function sweepExpiredReady(ctx, now) {
|
|
@@ -3971,23 +4041,26 @@ async function sweepStalledSending(ctx, now, escalationTag, statePort) {
|
|
|
3971
4041
|
await statePort.flag(ref, escalationTag);
|
|
3972
4042
|
}
|
|
3973
4043
|
}
|
|
3974
|
-
async function sweepStalledPending(ctx, now) {
|
|
4044
|
+
async function sweepStalledPending(ctx, now, escalationTag, statePort) {
|
|
3975
4045
|
const page = await ctx.api.list("generated-response", { filter: { status: "pending" }, limit: SWEEP_PAGE_SIZE });
|
|
3976
4046
|
for (const row of page.items) {
|
|
3977
4047
|
const expiresAt = toDate(row.data.expiresAt);
|
|
3978
4048
|
if (!expiresAt || expiresAt.getTime() > now.getTime()) continue;
|
|
4049
|
+
const ticketId = row.data.ticketId;
|
|
3979
4050
|
assertTransition("pending", "failed");
|
|
3980
4051
|
try {
|
|
3981
4052
|
await ctx.api.update(
|
|
3982
4053
|
"generated-response",
|
|
3983
4054
|
row.id,
|
|
3984
|
-
{ status: "failed", openTicketKey: openTicketKeyFor("failed",
|
|
4055
|
+
{ status: "failed", openTicketKey: openTicketKeyFor("failed", ticketId), error: "orphaned pending row past its TTL (sweep)" },
|
|
3985
4056
|
{ ifMatch: { status: "pending" } }
|
|
3986
4057
|
);
|
|
3987
4058
|
} catch (err) {
|
|
3988
4059
|
if (err instanceof appKit.AppApiError && err.status === 409) continue;
|
|
3989
4060
|
throw err;
|
|
3990
4061
|
}
|
|
4062
|
+
const ref = { id: ticketId, channel: "gorgias" };
|
|
4063
|
+
await statePort.flag(ref, escalationTag);
|
|
3991
4064
|
}
|
|
3992
4065
|
}
|
|
3993
4066
|
function buildHandleApprovalFunctionDef(config) {
|
|
@@ -5897,7 +5970,8 @@ var LABELS = {
|
|
|
5897
5970
|
G5: "Tag de p\xE9rim\xE8tre pr\xE9sent sur le ticket",
|
|
5898
5971
|
G6: "Aucune reprise humaine",
|
|
5899
5972
|
G7: "Cat\xE9gorie r\xE9solue et opt\xE9e",
|
|
5900
|
-
G8: "Nouveau message client"
|
|
5973
|
+
G8: "Nouveau message client",
|
|
5974
|
+
G9: "R\xE9ponse ouverte pr\xE9empt\xE9e"
|
|
5901
5975
|
};
|
|
5902
5976
|
function humanTakeoverTags(settings) {
|
|
5903
5977
|
const configured = [settings.escalationTag, settings.needsReviewTag, settings.followupTag].map((tag) => tag.trim()).filter((tag) => tag !== "");
|
|
@@ -5923,15 +5997,23 @@ function completeFollowupLadder(results) {
|
|
|
5923
5997
|
return missing.length === 0 ? results : [...results, ...skippedFollowupGates(missing)];
|
|
5924
5998
|
}
|
|
5925
5999
|
var FRESH_READ_GATES = ["G5", "G6", "G7", "G8"];
|
|
5926
|
-
var ALL_FOLLOWUP_GATES = ["G1", "G2", ...FRESH_READ_GATES];
|
|
6000
|
+
var ALL_FOLLOWUP_GATES = ["G1", "G2", ...FRESH_READ_GATES, "G9"];
|
|
5927
6001
|
function evaluateTicketGates(input) {
|
|
5928
|
-
const {
|
|
6002
|
+
const {
|
|
6003
|
+
settings,
|
|
6004
|
+
tags,
|
|
6005
|
+
categories,
|
|
6006
|
+
conversation,
|
|
6007
|
+
anchor,
|
|
6008
|
+
openResponse = null,
|
|
6009
|
+
ignoreCategoryOptIn = false
|
|
6010
|
+
} = input;
|
|
5929
6011
|
const trace = newTrace(FRESH_READ_GATES);
|
|
5930
6012
|
trace.record(scopeTagOnTicket(settings, tags));
|
|
5931
6013
|
trace.record(noHumanTakeover(settings, tags));
|
|
5932
6014
|
const match = trace.record(categoryGate(categories, tags, ignoreCategoryOptIn));
|
|
5933
6015
|
if (match) trace.category = match;
|
|
5934
|
-
trace.record(newCustomerMessage(conversation, anchor));
|
|
6016
|
+
trace.record(newCustomerMessage(conversation, anchor, openResponse));
|
|
5935
6017
|
return trace.done();
|
|
5936
6018
|
}
|
|
5937
6019
|
function evaluatePayloadGates(input) {
|
|
@@ -5994,15 +6076,20 @@ function noMatchingCategory() {
|
|
|
5994
6076
|
function matchingCategories(categories, tags) {
|
|
5995
6077
|
return categories.filter((category) => tags.includes(category.tagName));
|
|
5996
6078
|
}
|
|
5997
|
-
function newCustomerMessage(conversation, anchor) {
|
|
6079
|
+
function newCustomerMessage(conversation, anchor, openResponse) {
|
|
5998
6080
|
if (conversation.isClosed) return stopped("G8", "Le ticket est ferm\xE9.");
|
|
5999
6081
|
const last = conversation.messages[conversation.messages.length - 1];
|
|
6000
6082
|
if (!last) return stopped("G8", "La conversation extraite est vide.");
|
|
6001
6083
|
if (!isCustomerTurnWithWords(last)) {
|
|
6002
6084
|
return stopped("G8", "Le dernier message du fil n\u2019est pas un message client porteur de mots (agent, note interne, ou pi\xE8ce jointe seule).");
|
|
6003
6085
|
}
|
|
6004
|
-
if (anchor === null) return passed("G8", "Le dernier message est du client ; aucune r\xE9ponse ant\xE9rieure, donc aucune ancre \xE0 battre.");
|
|
6005
6086
|
const lastAt = conversation.lastMessageAt;
|
|
6087
|
+
if (openResponse?.status === "pending" && lastAt && openResponse.ownAnchor?.getTime() === lastAt.getTime()) {
|
|
6088
|
+
return passed("G8", "Une tentative pr\xE9c\xE9dente de ce passage a laiss\xE9 une r\xE9ponse en attente sur ce m\xEAme message : reprise.");
|
|
6089
|
+
}
|
|
6090
|
+
if (anchor === null) {
|
|
6091
|
+
return openResponse === null ? passed("G8", "Le dernier message est du client ; aucune r\xE9ponse ant\xE9rieure, donc aucune ancre \xE0 battre.") : stopped("G8", "Une r\xE9ponse est d\xE9j\xE0 en cours de r\xE9daction sur ce ticket et ne porte aucune ancre : impossible de prouver que ce message est nouveau.");
|
|
6092
|
+
}
|
|
6006
6093
|
if (!lastAt) return stopped("G8", "Le dernier message ne porte aucun horodatage : impossible de prouver qu\u2019il est post\xE9rieur \xE0 la derni\xE8re r\xE9ponse.");
|
|
6007
6094
|
return lastAt.getTime() > anchor.getTime() ? passed("G8", `Message client du ${lastAt.toISOString()}, post\xE9rieur \xE0 la derni\xE8re r\xE9ponse.`) : stopped("G8", `Le dernier message (${lastAt.toISOString()}) n\u2019est pas post\xE9rieur \xE0 la derni\xE8re r\xE9ponse (${anchor.toISOString()}) : relivraison ou \xE9v\xE9nement en retard.`);
|
|
6008
6095
|
}
|
|
@@ -6106,8 +6193,8 @@ function parseTicketId(raw) {
|
|
|
6106
6193
|
}
|
|
6107
6194
|
function parseText(raw) {
|
|
6108
6195
|
if (typeof raw !== "string") return null;
|
|
6109
|
-
const
|
|
6110
|
-
return
|
|
6196
|
+
const trimmed2 = raw.trim();
|
|
6197
|
+
return trimmed2 === "" ? null : trimmed2;
|
|
6111
6198
|
}
|
|
6112
6199
|
function parseDate(raw) {
|
|
6113
6200
|
if (typeof raw !== "string") return null;
|
|
@@ -6213,7 +6300,7 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
|
|
|
6213
6300
|
const scope = evaluateScopeGate(settings);
|
|
6214
6301
|
ladder.push(scope);
|
|
6215
6302
|
if (scope.status === "stopped") return stopAt(ctx, ticketId, scope, ladder);
|
|
6216
|
-
const { anchor,
|
|
6303
|
+
const { anchor, openResponse } = await readFollowupAnchor(ctx, ticketId);
|
|
6217
6304
|
const categories = await listCategories(ctx.api);
|
|
6218
6305
|
const preGates = evaluatePayloadGates({ settings, body, categories, anchor });
|
|
6219
6306
|
if (preGates.stop) {
|
|
@@ -6230,6 +6317,7 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
|
|
|
6230
6317
|
categories,
|
|
6231
6318
|
conversation,
|
|
6232
6319
|
anchor,
|
|
6320
|
+
openResponse,
|
|
6233
6321
|
ignoreCategoryOptIn: generateOnly
|
|
6234
6322
|
});
|
|
6235
6323
|
ladder.push(...gates.results);
|
|
@@ -6237,15 +6325,27 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
|
|
|
6237
6325
|
return stopAt(ctx, ticketId, gates.stop ?? unresolvedCategory(), ladder);
|
|
6238
6326
|
}
|
|
6239
6327
|
const category = gates.category;
|
|
6240
|
-
|
|
6328
|
+
const preemption = openResponse ? generateOnly ? stopped("G9", "Une r\xE9ponse est d\xE9j\xE0 ouverte sur ce ticket : l'essai ne la remplace pas, contrairement \xE0 un passage r\xE9el.") : await preemptOpenResponse(ctx, ticketId, openResponse) : passed("G9", "Aucune r\xE9ponse ouverte sur ce ticket.");
|
|
6329
|
+
if (preemption.status === "stopped") {
|
|
6330
|
+
ladder.push(preemption);
|
|
6331
|
+
return stopAt(ctx, ticketId, preemption, ladder);
|
|
6332
|
+
}
|
|
6241
6333
|
run.id ??= (await ctx.api.runs.start({
|
|
6242
6334
|
kind: FOLLOWUP_RUN_KIND,
|
|
6243
6335
|
message: `Message suivant \u2014 ticket ${ticketId}`,
|
|
6244
6336
|
metadata: { ticketId, categoryTag: category.tagName, channel: body.channel, generateOnly }
|
|
6245
6337
|
})).id;
|
|
6246
6338
|
const ticketUrl = ticketUrlFor(await resolveTicketUrlBase(ctx), ticketId);
|
|
6247
|
-
const created = await openFollowupResponse(ctx, { ticketId, category, conversation, settings, runId: run.id, ticketUrl });
|
|
6248
|
-
if (!created)
|
|
6339
|
+
const created = await openFollowupResponse(ctx, { ticketId, category, conversation, settings, runId: run.id, ticketUrl, generateOnly });
|
|
6340
|
+
if (!created) {
|
|
6341
|
+
const lost = stopped(
|
|
6342
|
+
"G9",
|
|
6343
|
+
`Une autre ex\xE9cution a ouvert la r\xE9ponse en premier. ${preemption.detail}`.trim()
|
|
6344
|
+
);
|
|
6345
|
+
ladder.push(lost);
|
|
6346
|
+
return stopAt(ctx, ticketId, lost, ladder);
|
|
6347
|
+
}
|
|
6348
|
+
ladder.push(preemption);
|
|
6249
6349
|
const outcome2 = await respondToPendingResponse(ctx, config, created.id, { testRun: generateOnly });
|
|
6250
6350
|
return {
|
|
6251
6351
|
ticketId,
|
|
@@ -6266,16 +6366,66 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
|
|
|
6266
6366
|
async function readFollowupAnchor(ctx, ticketId) {
|
|
6267
6367
|
const page = await ctx.api.list("generated-response", { filter: { ticketId }, limit: ANCHOR_LOOKUP_LIMIT });
|
|
6268
6368
|
let anchor = null;
|
|
6269
|
-
let
|
|
6369
|
+
let openResponse = null;
|
|
6270
6370
|
for (const item of page.items) {
|
|
6271
6371
|
const data = item.data;
|
|
6272
|
-
|
|
6372
|
+
let ownAnchor = null;
|
|
6273
6373
|
for (const raw of [data.generatedLastMessageAt, data.sentAt]) {
|
|
6274
6374
|
const at = toDate2(raw);
|
|
6375
|
+
if (at && (!ownAnchor || at > ownAnchor)) ownAnchor = at;
|
|
6275
6376
|
if (at && (!anchor || at > anchor)) anchor = at;
|
|
6276
6377
|
}
|
|
6378
|
+
if (data.openTicketKey === ticketId) {
|
|
6379
|
+
openResponse = { id: item.id, status: isGeneratedResponseStatus(data.status) ? data.status : null, ownAnchor };
|
|
6380
|
+
}
|
|
6381
|
+
}
|
|
6382
|
+
return { anchor, openResponse };
|
|
6383
|
+
}
|
|
6384
|
+
var SEND_SETTLE_POLL_MS = 2e3;
|
|
6385
|
+
var SEND_SETTLE_ATTEMPTS = 4;
|
|
6386
|
+
var PREEMPT_ATTEMPTS = 3;
|
|
6387
|
+
async function preemptOpenResponse(ctx, ticketId, open) {
|
|
6388
|
+
let status = open.status;
|
|
6389
|
+
for (let attempt = 1; attempt <= PREEMPT_ATTEMPTS; attempt += 1) {
|
|
6390
|
+
if (status === null) {
|
|
6391
|
+
return stopped("G9", "Une r\xE9ponse ouverte porte un statut illisible : elle doit \xEAtre d\xE9bloqu\xE9e \xE0 la main.");
|
|
6392
|
+
}
|
|
6393
|
+
if (isTerminalStatus(status)) {
|
|
6394
|
+
return passed("G9", "La r\xE9ponse ouverte s'est termin\xE9e d'elle-m\xEAme : le ticket est libre.");
|
|
6395
|
+
}
|
|
6396
|
+
if (status === "sending") {
|
|
6397
|
+
status = await awaitSettledSend(ctx, open.id);
|
|
6398
|
+
if (status === "sending") {
|
|
6399
|
+
ctx.logger.warn(
|
|
6400
|
+
`gorgias-webhook: stop at G9 for ticket ${ticketId} \u2014 envoi bloqu\xE9 depuis plus de ${SEND_SETTLE_POLL_MS * SEND_SETTLE_ATTEMPTS / 1e3} s, message suivant non trait\xE9`
|
|
6401
|
+
);
|
|
6402
|
+
return stopped("G9", "Une r\xE9ponse est en cours d'envoi et ne se termine pas : au sweep de la r\xE9clamer.");
|
|
6403
|
+
}
|
|
6404
|
+
continue;
|
|
6405
|
+
}
|
|
6406
|
+
if (!canTransition(status, "superseded")) {
|
|
6407
|
+
return stopped("G9", `Une r\xE9ponse au statut \xAB ${status} \xBB tient le ticket et ne peut pas \xEAtre remplac\xE9e.`);
|
|
6408
|
+
}
|
|
6409
|
+
if (await transitionGeneratedResponse(ctx.api, { id: open.id, ticketId, from: status, to: "superseded" })) {
|
|
6410
|
+
return passed("G9", `La r\xE9ponse ouverte (${status}) r\xE9pondait \xE0 un message ant\xE9rieur : remplac\xE9e.`);
|
|
6411
|
+
}
|
|
6412
|
+
status = await readResponseStatus(ctx, open.id);
|
|
6413
|
+
}
|
|
6414
|
+
return stopped("G9", "La r\xE9ponse ouverte change de statut plus vite que ce passage ne peut la remplacer.");
|
|
6415
|
+
}
|
|
6416
|
+
async function awaitSettledSend(ctx, id) {
|
|
6417
|
+
let status = "sending";
|
|
6418
|
+
for (let attempt = 1; attempt <= SEND_SETTLE_ATTEMPTS && status === "sending"; attempt += 1) {
|
|
6419
|
+
await new Promise((resolve) => setTimeout(resolve, SEND_SETTLE_POLL_MS));
|
|
6420
|
+
status = await readResponseStatus(ctx, id);
|
|
6277
6421
|
}
|
|
6278
|
-
return
|
|
6422
|
+
return status;
|
|
6423
|
+
}
|
|
6424
|
+
async function readResponseStatus(ctx, id) {
|
|
6425
|
+
const row = await getOptional(ctx, "generated-response", id);
|
|
6426
|
+
if (!row) return "sent";
|
|
6427
|
+
const raw = row.data.status;
|
|
6428
|
+
return isGeneratedResponseStatus(raw) ? raw : null;
|
|
6279
6429
|
}
|
|
6280
6430
|
var ANCHOR_LOOKUP_LIMIT = 100;
|
|
6281
6431
|
function toDate2(raw) {
|
|
@@ -6347,6 +6497,15 @@ async function openFollowupResponse(ctx, input) {
|
|
|
6347
6497
|
channel: conversation.sourceChannel === "whatsapp" ? "whatsapp" : "email",
|
|
6348
6498
|
generatedAt,
|
|
6349
6499
|
expiresAt: new Date(generatedAt.getTime() + settings.responseTtlMinutes * 6e4),
|
|
6500
|
+
// Stamped HERE, not only when `process-response` finishes with the row:
|
|
6501
|
+
// until it exists the draft contributes nothing to §6's anchor, so a
|
|
6502
|
+
// webhook redelivered while it is still `pending` would read "no anchor
|
|
6503
|
+
// to beat" at G8 and draft the very same message all over again.
|
|
6504
|
+
//
|
|
6505
|
+
// Withheld from the operator's essay for the reason §8 keeps it out of
|
|
6506
|
+
// the lifecycle entirely: raising the anchor there would make the REAL
|
|
6507
|
+
// reply to that same message impossible ever after.
|
|
6508
|
+
...input.generateOnly ? {} : { generatedMessageCount: conversation.messageCount, generatedLastMessageAt: conversation.lastMessageAt },
|
|
6350
6509
|
sources: [],
|
|
6351
6510
|
tracedInput: [],
|
|
6352
6511
|
guardrailHits: [],
|
|
@@ -6362,12 +6521,7 @@ async function openFollowupResponse(ctx, input) {
|
|
|
6362
6521
|
}
|
|
6363
6522
|
}
|
|
6364
6523
|
function unresolvedCategory() {
|
|
6365
|
-
return
|
|
6366
|
-
gate: "G7",
|
|
6367
|
-
label: "Cat\xE9gorie r\xE9solue et opt\xE9e",
|
|
6368
|
-
status: "stopped",
|
|
6369
|
-
detail: "Aucune cat\xE9gorie r\xE9solue."
|
|
6370
|
-
};
|
|
6524
|
+
return stopped("G7", "Aucune cat\xE9gorie r\xE9solue.");
|
|
6371
6525
|
}
|
|
6372
6526
|
function stopAt(ctx, ticketId, result, ladder, kind = "gate") {
|
|
6373
6527
|
return stop(ctx, ticketId, `${result.gate}${kind === "gate" ? "" : ` (${kind})`}`, result.detail, ladder);
|
|
@@ -6436,7 +6590,7 @@ async function diagnose(ctx, ticketId) {
|
|
|
6436
6590
|
const scope = evaluateScopeGate(settings);
|
|
6437
6591
|
gates.push(scope);
|
|
6438
6592
|
if (scope.status === "stopped") return finish3(gates, ticketId);
|
|
6439
|
-
const { anchor } = await readFollowupAnchor(ctx, ticketId);
|
|
6593
|
+
const { anchor, openResponse } = await readFollowupAnchor(ctx, ticketId);
|
|
6440
6594
|
const categories = await listCategories(ctx.api);
|
|
6441
6595
|
const ref = { id: ticketId, channel: "gorgias" };
|
|
6442
6596
|
const ticket = await ctx.api.integrations.run("gorgias", "getTicketWithContext", { ticketId });
|
|
@@ -6444,8 +6598,26 @@ async function diagnose(ctx, ticketId) {
|
|
|
6444
6598
|
const conversation = toConversation(ref, raw, ticket?.context ?? { messages: [], customerContext: null });
|
|
6445
6599
|
const trace = evaluateTicketGates({ settings, tags: ticketTagNames(raw), categories, conversation, anchor });
|
|
6446
6600
|
gates.push(...trace.results);
|
|
6601
|
+
if (!trace.stop) gates.push(predictPreemption(openResponse));
|
|
6447
6602
|
return finish3(gates, ticketId);
|
|
6448
6603
|
}
|
|
6604
|
+
function predictPreemption(openResponse) {
|
|
6605
|
+
if (!openResponse) return passed("G9", "Aucune r\xE9ponse ouverte sur ce ticket.");
|
|
6606
|
+
const { status } = openResponse;
|
|
6607
|
+
if (status === null) {
|
|
6608
|
+
return stopped("G9", "Une r\xE9ponse ouverte porte un statut illisible : elle doit \xEAtre d\xE9bloqu\xE9e \xE0 la main.");
|
|
6609
|
+
}
|
|
6610
|
+
if (status === "sending") {
|
|
6611
|
+
return passed("G9", "Une r\xE9ponse est en cours d'envoi : le passage attendrait qu'elle se termine.");
|
|
6612
|
+
}
|
|
6613
|
+
if (isTerminalStatus(status)) {
|
|
6614
|
+
return passed("G9", "La r\xE9ponse ouverte est d\xE9j\xE0 termin\xE9e : le ticket est libre.");
|
|
6615
|
+
}
|
|
6616
|
+
if (!canTransition(status, "superseded")) {
|
|
6617
|
+
return stopped("G9", `Une r\xE9ponse au statut \xAB ${status} \xBB tient le ticket et ne peut pas \xEAtre remplac\xE9e.`);
|
|
6618
|
+
}
|
|
6619
|
+
return passed("G9", `Une r\xE9ponse ouverte (${status}) serait remplac\xE9e.`);
|
|
6620
|
+
}
|
|
6449
6621
|
function finish3(gates, ticketId) {
|
|
6450
6622
|
const full = completeFollowupLadder(gates);
|
|
6451
6623
|
return {
|
|
@@ -6812,6 +6984,7 @@ exports.resolvePromptName = resolvePromptName;
|
|
|
6812
6984
|
exports.runGuardrails = runGuardrails;
|
|
6813
6985
|
exports.runTicket = runTicket;
|
|
6814
6986
|
exports.settingsToProfile = settingsToProfile;
|
|
6987
|
+
exports.settingsWarnings = settingsWarnings;
|
|
6815
6988
|
exports.stopOptOut = stopOptOut;
|
|
6816
6989
|
exports.targetRefFor = targetRefFor;
|
|
6817
6990
|
exports.toDecisionOrigin = toDecisionOrigin;
|