@apotech-os/support-kit 2.6.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 +67 -0
- package/dist/chunk-KDOL3MLH.js +1766 -0
- package/dist/chunk-KDOL3MLH.js.map +1 -0
- package/dist/index.cjs +5744 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +2010 -0
- package/dist/index.d.ts +2010 -0
- package/dist/index.js +3965 -0
- package/dist/index.js.map +1 -0
- package/dist/ui/index.cjs +4946 -0
- package/dist/ui/index.cjs.map +1 -0
- package/dist/ui/index.d.cts +25 -0
- package/dist/ui/index.d.ts +25 -0
- package/dist/ui/index.js +4464 -0
- package/dist/ui/index.js.map +1 -0
- package/package.json +68 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,3965 @@
|
|
|
1
|
+
import { CATEGORY_GROUP_FIELD_NAME_UID, CATEGORY_GROUP_FIELD_ORDER_UID, PIPELINE_STATE_FIELD_SINGLETON_KEY_UID, PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID, PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID, PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID, PROMPT_CACHE_FIELD_PROMPT_KEY_UID, PROMPT_CACHE_FIELD_CONTENT_UID, PROMPT_CACHE_FIELD_VERSION_UID, PROMPT_CACHE_FIELD_LABEL_UID, PROMPT_CACHE_FIELD_CONFIG_UID, CATEGORY_GROUP_INDEX_NAME_UID, CATEGORY_GROUP_OBJECT_UID, PIPELINE_STATE_INDEX_SINGLETON_KEY_UID, PIPELINE_STATE_OBJECT_UID, PROMPT_CACHE_INDEX_PROMPT_KEY_UID, PROMPT_CACHE_OBJECT_UID, CATEGORY_INDEX_TAG_NAME_UID, CATEGORY_INDEX_NAME_UID, CATEGORY_INDEX_ORDER_UID, CATEGORY_FIELD_NAME_UID, CATEGORY_FIELD_TAG_NAME_UID, CATEGORY_FIELD_ORDER_UID, CATEGORY_FIELD_GROUP_ID_UID, CATEGORY_FIELD_AGENT_ID_UID, CATEGORY_FIELD_EXTRA_TAGS_UID, CATEGORY_FIELD_EXAMPLES_UID, CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID, CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID, CATEGORY_OBJECT_UID, TRIAGE_DECISION_INDEX_TICKET_ID_UID, TRIAGE_DECISION_INDEX_DECIDED_AT_UID, TRIAGE_DECISION_INDEX_ESCALATED_UID, TRIAGE_DECISION_FIELD_TICKET_ID_UID, TRIAGE_DECISION_FIELD_DECIDED_AT_UID, TRIAGE_DECISION_FIELD_CATEGORY_ID_UID, TRIAGE_DECISION_FIELD_TAG_UID, TRIAGE_DECISION_FIELD_CONFIDENCE_UID, TRIAGE_DECISION_FIELD_REASONING_UID, TRIAGE_DECISION_FIELD_CONVERSATION_OVER_UID, TRIAGE_DECISION_FIELD_ESCALATED_UID, TRIAGE_DECISION_FIELD_ESCALATION_CONFIDENCE_UID, TRIAGE_DECISION_FIELD_ESCALATION_REASONING_UID, TRIAGE_DECISION_FIELD_STATUS_UID, TRIAGE_DECISION_FIELD_ERROR_UID, TRIAGE_DECISION_FIELD_RUN_ID_UID, TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID, TRIAGE_DECISION_OBJECT_UID, GENERATED_RESPONSE_INDEX_TICKET_ID_UID, GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID, GENERATED_RESPONSE_INDEX_STATUS_UID, GENERATED_RESPONSE_INDEX_TRIAGE_DECISION_ID_UID, GENERATED_RESPONSE_INDEX_GENERATED_AT_UID, GENERATED_RESPONSE_INDEX_EXPIRES_AT_UID, GENERATED_RESPONSE_FIELD_TICKET_ID_UID, GENERATED_RESPONSE_FIELD_OPEN_TICKET_KEY_UID, GENERATED_RESPONSE_STATUSES, GENERATED_RESPONSE_FIELD_STATUS_UID, GENERATED_RESPONSE_FIELD_TRIAGE_DECISION_ID_UID, GENERATED_RESPONSE_FIELD_CATEGORY_ID_UID, GENERATED_RESPONSE_FIELD_AGENT_ID_UID, GENERATED_RESPONSE_FIELD_CHANNEL_UID, GENERATED_RESPONSE_FIELD_RESPONSE_TEXT_UID, GENERATED_RESPONSE_FIELD_SOURCES_UID, GENERATED_RESPONSE_FIELD_TRACED_INPUT_UID, GENERATED_RESPONSE_FIELD_VERDICT_UID, GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_UID, GENERATED_RESPONSE_FIELD_AUTO_SEND_DECISION_UID, GENERATED_RESPONSE_FIELD_FOLLOWUP_REQUIRED_UID, GENERATED_RESPONSE_FIELD_SERVED_COUNT_UID, GENERATED_RESPONSE_FIELD_SERVED_TO_UID, GENERATED_RESPONSE_FIELD_GENERATED_AT_UID, GENERATED_RESPONSE_FIELD_EXPIRES_AT_UID, GENERATED_RESPONSE_FIELD_SENT_AT_UID, GENERATED_RESPONSE_FIELD_SENT_MESSAGE_ID_UID, GENERATED_RESPONSE_FIELD_LANGFUSE_TRACE_ID_UID, GENERATED_RESPONSE_FIELD_LANGFUSE_OBSERVATION_ID_UID, GENERATED_RESPONSE_FIELD_PROMPT_NAME_UID, GENERATED_RESPONSE_FIELD_PROMPT_VERSION_UID, GENERATED_RESPONSE_FIELD_ERROR_UID, GENERATED_RESPONSE_FIELD_GENERATED_MESSAGE_COUNT_UID, GENERATED_RESPONSE_FIELD_GENERATED_LAST_MESSAGE_AT_UID, GENERATED_RESPONSE_FIELD_SENDING_AT_UID, GENERATED_RESPONSE_OBJECT_UID, RESPONSE_COMPARISON_INDEX_CAPTURED_AT_UID, RESPONSE_COMPARISON_INDEX_TICKET_ID_UID, RESPONSE_COMPARISON_FIELD_GENERATED_TEXT_UID, RESPONSE_COMPARISON_FIELD_SENT_TEXT_UID, RESPONSE_COMPARISON_FIELD_CAPTURED_AT_UID, RESPONSE_COMPARISON_FIELD_TICKET_ID_UID, RESPONSE_COMPARISON_FIELD_TICKET_URL_UID, RESPONSE_COMPARISON_FIELD_AGENT_ID_UID, RESPONSE_COMPARISON_FIELD_LANGFUSE_TRACE_ID_UID, RESPONSE_COMPARISON_FIELD_LANGFUSE_OBSERVATION_ID_UID, RESPONSE_COMPARISON_FIELD_PROMPT_NAME_UID, RESPONSE_COMPARISON_FIELD_PROMPT_VERSION_UID, RESPONSE_COMPARISON_FIELD_CONVERSATION_MESSAGES_UID, RESPONSE_COMPARISON_FIELD_DIFF_UID, RESPONSE_COMPARISON_OBJECT_UID, EVALUATION_FIELD_AGENT_ID_UID, EVALUATION_FIELD_SATISFIED_UID, EVALUATION_FIELD_MESSAGES_UID, EVALUATION_FIELD_TICKET_URL_UID, EVALUATION_FIELD_LANGFUSE_TRACE_ID_UID, EVALUATION_FIELD_LANGFUSE_OBSERVATION_ID_UID, EVALUATION_FIELD_SUPPORT_USER_KEY_ID_UID, EVALUATION_OBJECT_UID, DIFF_ANALYSIS_INDEX_UNIQUE_KEY_UID, DIFF_ANALYSIS_FIELD_AGENT_ID_UID, DIFF_ANALYSIS_FIELD_PROMPT_NAME_UID, DIFF_ANALYSIS_FIELD_PROMPT_VERSION_UID, DIFF_ANALYSIS_FIELD_POINTS_UID, DIFF_ANALYSIS_FIELD_UNIQUE_KEY_UID, DIFF_ANALYSIS_OBJECT_UID, agentRecord, SUPPORT_KIT_SETTINGS_FIELDS, validateSettings, toCategory, toAgent, resolveDraftAgent, settingsToProfile, buildPromptsTable, draftPromptRefFor, runTicket, assertTransition, openTicketKeyFor, act, initialState, applyOutcomeTags, listCategories, toCategoryReferential, resolvePromptName, PROMPT_SLOTS, resolveReviseName, DEFAULT_LLM_PROVIDER, toCategoryGroup, toGeneratedResponse, NODE_NAMES, reclaimStalledSend, applySignature, isGeneratedResponseStatus, isEvaluationVerdict, requiresFollowup, computeWordDiff, findCategoryByTag, isWhatsappTicket, isConversationOver, isFallbackClassification, hasNoDraftNode, hasCustomerAttachment, isTicketClosed, isWhatsappChevronNote } from './chunk-KDOL3MLH.js';
|
|
2
|
+
export { AGENT_GUARDRAILS, AGENT_STATUSES, AGENT_TOOLS, CANDIDATE_MIN_LENGTH, DEFAULT_CHANNEL_PROMPT_EMAIL, DEFAULT_CHANNEL_PROMPT_WHATSAPP, DEFAULT_LLM_PROVIDER, DEFAULT_PROFILE_KEY, DEFAULT_WHATSAPP_MODE, EVALUATION_VERDICTS, GENERATED_RESPONSE_STATUSES, InvalidStatusTransitionError, NODE_NAMES, PROMPT_SLOTS, REASONING_MAX_LEN, STOP_PHRASES, SUPPORT_KIT_SETTINGS_FIELDS, UNCERTAINTY_MARKERS, WHATSAPP_MODES, WHATSAPP_NOTE_CHEVRON, agentRecord, assertTransition, canTransition, channelPreGates, firstCustomerMessage, guardrailBucket, hasCustomerAttachment, initialState, isAutoSendEligible, isAutomatedSenderEmail, isAutomatedSenderTicket, isEvaluationVerdict, isGeneratedResponseStatus, isJudgemeConversation, isJudgemeTicket, isSendable, isSendableVerdict, isTerminalStatus, isTicketClosed, isWhatsappChevronNote, isWhatsappTicket, lastCustomerMessage, needsRevision, openTicketKeyFor, reclaimStalledSend, requiresFollowup, resolvePromptName, resolveReviseName, runGuardrails, runTicket, settingsToProfile, stopOptOut, validateSettings, verifyReply, whatsappModeFromLegacyBoolean } from './chunk-KDOL3MLH.js';
|
|
3
|
+
import { FieldType, APPROVAL_DECIDED_EVENT, AppApiError } from '@apotech-os/app-kit';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
|
|
6
|
+
// src/graph/budget.ts
|
|
7
|
+
var ZERO_COST = { input: 0, output: 0, reasoning: 0, usd: 0, pricingMissing: false };
|
|
8
|
+
function addCost(existing, usage, cost) {
|
|
9
|
+
const base = existing ?? ZERO_COST;
|
|
10
|
+
return {
|
|
11
|
+
input: base.input + usage.input,
|
|
12
|
+
output: base.output + usage.output,
|
|
13
|
+
reasoning: base.reasoning + usage.reasoning,
|
|
14
|
+
usd: base.usd + cost.usd,
|
|
15
|
+
// Sticky: one unpriced charge is enough to mark the whole node unpriced,
|
|
16
|
+
// so a later zero-cost charge never makes it read as "this was free".
|
|
17
|
+
pricingMissing: base.pricingMissing || cost.pricingMissing
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
function createBudget({ signal, maxToolCalls }) {
|
|
21
|
+
let toolCallsUsed = 0;
|
|
22
|
+
const costs = {};
|
|
23
|
+
return {
|
|
24
|
+
signal,
|
|
25
|
+
consumeToolCall() {
|
|
26
|
+
toolCallsUsed += 1;
|
|
27
|
+
},
|
|
28
|
+
exhausted() {
|
|
29
|
+
return toolCallsUsed >= maxToolCalls || signal.aborted;
|
|
30
|
+
},
|
|
31
|
+
charge(node, usage, cost) {
|
|
32
|
+
costs[node] = addCost(costs[node], usage, cost);
|
|
33
|
+
},
|
|
34
|
+
ledger() {
|
|
35
|
+
return { ...costs };
|
|
36
|
+
},
|
|
37
|
+
total() {
|
|
38
|
+
return Object.values(costs).reduce(
|
|
39
|
+
(acc, entry) => addCost(acc, entry, { usd: entry.usd, pricingMissing: entry.pricingMissing }),
|
|
40
|
+
ZERO_COST
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// src/prompts/references.ts
|
|
47
|
+
var REF_RE = /@@@langfusePrompt:name=([^|@]+)\|(?:version=(\d+)|label=([^@]+))@@@/g;
|
|
48
|
+
var REFERENCE_TAG_SOURCE = REF_RE.source;
|
|
49
|
+
function parseReferences(content) {
|
|
50
|
+
const refs = [];
|
|
51
|
+
for (const [raw, name, version, label] of content.matchAll(REF_RE)) {
|
|
52
|
+
refs.push(version !== void 0 ? { name, version: Number(version), raw } : { name, label, raw });
|
|
53
|
+
}
|
|
54
|
+
return refs;
|
|
55
|
+
}
|
|
56
|
+
function hasReferences(content) {
|
|
57
|
+
return new RegExp(REF_RE.source).test(content);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// src/prompts/resolver.ts
|
|
61
|
+
var PRODUCTION_LABEL = "production";
|
|
62
|
+
var DEFAULT_TTL_MS = 6e4;
|
|
63
|
+
var MAX_COMPOSITION_DEPTH = 5;
|
|
64
|
+
function cacheKey(name, label) {
|
|
65
|
+
return label === PRODUCTION_LABEL ? name : `${name}::${label}`;
|
|
66
|
+
}
|
|
67
|
+
function memoryKey(name, opts) {
|
|
68
|
+
if (opts.version !== void 0) return `${name}::v${opts.version}`;
|
|
69
|
+
return cacheKey(name, opts.label ?? PRODUCTION_LABEL);
|
|
70
|
+
}
|
|
71
|
+
function substituteVars(text, vars) {
|
|
72
|
+
if (!vars) return text;
|
|
73
|
+
return Object.entries(vars).reduce((out, [key, value]) => out.replaceAll(`{{${key}}}`, () => value), text);
|
|
74
|
+
}
|
|
75
|
+
function reasonOf(err) {
|
|
76
|
+
return err instanceof Error ? err.message : String(err);
|
|
77
|
+
}
|
|
78
|
+
function dedupeByRaw(refs) {
|
|
79
|
+
const seen = /* @__PURE__ */ new Set();
|
|
80
|
+
return refs.filter((ref) => {
|
|
81
|
+
if (seen.has(ref.raw)) return false;
|
|
82
|
+
seen.add(ref.raw);
|
|
83
|
+
return true;
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
function stripReferences(content, refs) {
|
|
87
|
+
let out = content;
|
|
88
|
+
for (const ref of dedupeByRaw(refs)) out = out.replaceAll(ref.raw, () => "");
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
async function readComposed(name, opts, ctx, visited, depth) {
|
|
92
|
+
const key = memoryKey(name, opts);
|
|
93
|
+
const cached = ctx.memory.get(key);
|
|
94
|
+
if (cached && cached.expiresAt > ctx.now()) return cached;
|
|
95
|
+
const raw = await ctx.platform.get(name, opts);
|
|
96
|
+
const content = await composeReferences(raw.content, ctx, visited, depth);
|
|
97
|
+
const entry = { content, version: raw.version, config: raw.config, expiresAt: ctx.now() + ctx.ttlMs };
|
|
98
|
+
ctx.memory.set(key, entry);
|
|
99
|
+
return entry;
|
|
100
|
+
}
|
|
101
|
+
async function resolveOneReference(ref, ctx, visited, depth) {
|
|
102
|
+
if (visited.has(ref.name)) {
|
|
103
|
+
ctx.onDegraded?.({ stage: "composition-cycle", name: ref.name, reason: "cyclic composition reference" });
|
|
104
|
+
return "";
|
|
105
|
+
}
|
|
106
|
+
const targetOpts = ref.version !== void 0 ? { version: ref.version } : { label: ref.label };
|
|
107
|
+
try {
|
|
108
|
+
const target = await readComposed(ref.name, targetOpts, ctx, /* @__PURE__ */ new Set([...visited, ref.name]), depth + 1);
|
|
109
|
+
return target.content;
|
|
110
|
+
} catch (err) {
|
|
111
|
+
const forbidden = err instanceof AppApiError && err.status === 403;
|
|
112
|
+
ctx.onDegraded?.({
|
|
113
|
+
stage: forbidden ? "composition-target-forbidden" : "composition-target-missing",
|
|
114
|
+
name: ref.name,
|
|
115
|
+
reason: reasonOf(err)
|
|
116
|
+
});
|
|
117
|
+
return "";
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
async function composeReferences(content, ctx, visited, depth) {
|
|
121
|
+
if (!hasReferences(content)) return content;
|
|
122
|
+
const refs = parseReferences(content);
|
|
123
|
+
if (depth >= MAX_COMPOSITION_DEPTH) {
|
|
124
|
+
for (const ref of dedupeByRaw(refs)) {
|
|
125
|
+
ctx.onDegraded?.({
|
|
126
|
+
stage: "composition-depth-exceeded",
|
|
127
|
+
name: ref.name,
|
|
128
|
+
reason: `composition chain exceeded ${MAX_COMPOSITION_DEPTH} levels`
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
return stripReferences(content, refs);
|
|
132
|
+
}
|
|
133
|
+
let resolved = content;
|
|
134
|
+
for (const ref of dedupeByRaw(refs)) {
|
|
135
|
+
const replacement = await resolveOneReference(ref, ctx, visited, depth);
|
|
136
|
+
resolved = resolved.replaceAll(ref.raw, () => replacement);
|
|
137
|
+
}
|
|
138
|
+
return resolved;
|
|
139
|
+
}
|
|
140
|
+
function toResolvedConfig(config) {
|
|
141
|
+
if (!config || typeof config.model !== "string" || config.model.length === 0) return null;
|
|
142
|
+
return config.temperature !== void 0 ? { model: config.model, temperature: config.temperature } : { model: config.model };
|
|
143
|
+
}
|
|
144
|
+
function createPromptResolver(deps) {
|
|
145
|
+
const ttlMs = deps.ttlMs ?? DEFAULT_TTL_MS;
|
|
146
|
+
const now = deps.now ?? Date.now;
|
|
147
|
+
const memory = /* @__PURE__ */ new Map();
|
|
148
|
+
const composeCtx = { platform: deps.platform, memory, ttlMs, now, onDegraded: deps.onDegraded };
|
|
149
|
+
async function resolveFromCacheOrFallback(name, label, ref, vars) {
|
|
150
|
+
const cached = await deps.cache.read(cacheKey(name, label)).catch((err) => {
|
|
151
|
+
deps.onDegraded?.({ stage: "cache-unavailable", name, reason: reasonOf(err) });
|
|
152
|
+
return null;
|
|
153
|
+
});
|
|
154
|
+
if (cached) {
|
|
155
|
+
return { name, text: substituteVars(cached.content, vars), version: cached.version, config: null };
|
|
156
|
+
}
|
|
157
|
+
const rawFallback = ref.fallback ?? "";
|
|
158
|
+
const text = hasReferences(rawFallback) ? await composeReferences(rawFallback, composeCtx, /* @__PURE__ */ new Set([name]), 0) : rawFallback;
|
|
159
|
+
return { name, text: substituteVars(text, vars), version: 0, config: null };
|
|
160
|
+
}
|
|
161
|
+
return {
|
|
162
|
+
async resolve(ref, vars) {
|
|
163
|
+
const label = ref.label?.trim() || PRODUCTION_LABEL;
|
|
164
|
+
const persistKey = cacheKey(ref.name, label);
|
|
165
|
+
let resolved;
|
|
166
|
+
try {
|
|
167
|
+
resolved = await readComposed(ref.name, { label }, composeCtx, /* @__PURE__ */ new Set([ref.name]), 0);
|
|
168
|
+
} catch (err) {
|
|
169
|
+
deps.onDegraded?.({ stage: "platform-unavailable", name: ref.name, reason: reasonOf(err) });
|
|
170
|
+
return resolveFromCacheOrFallback(ref.name, label, ref, vars);
|
|
171
|
+
}
|
|
172
|
+
if (!hasReferences(resolved.content)) {
|
|
173
|
+
await deps.cache.write(persistKey, { content: resolved.content, version: resolved.version }).catch(() => void 0);
|
|
174
|
+
}
|
|
175
|
+
return {
|
|
176
|
+
name: ref.name,
|
|
177
|
+
text: substituteVars(resolved.content, vars),
|
|
178
|
+
version: resolved.version,
|
|
179
|
+
config: toResolvedConfig(resolved.config)
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// src/records/target-ref.ts
|
|
186
|
+
function targetRefFor(slug, objectKey) {
|
|
187
|
+
return `app:${slug}/${objectKey}`;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// src/records/category.ts
|
|
191
|
+
function buildCategoryRecord(slug) {
|
|
192
|
+
return {
|
|
193
|
+
universalIdentifier: CATEGORY_OBJECT_UID,
|
|
194
|
+
objectKey: "category",
|
|
195
|
+
labelSingular: "Category",
|
|
196
|
+
labelPlural: "Categories",
|
|
197
|
+
description: "A triage category, matched against a Gorgias tag.",
|
|
198
|
+
fields: [
|
|
199
|
+
{
|
|
200
|
+
universalIdentifier: CATEGORY_FIELD_NAME_UID,
|
|
201
|
+
name: "name",
|
|
202
|
+
type: FieldType.TEXT,
|
|
203
|
+
label: "Name",
|
|
204
|
+
isNullable: false
|
|
205
|
+
},
|
|
206
|
+
{
|
|
207
|
+
universalIdentifier: CATEGORY_FIELD_TAG_NAME_UID,
|
|
208
|
+
name: "tagName",
|
|
209
|
+
type: FieldType.TEXT,
|
|
210
|
+
label: "Gorgias tag",
|
|
211
|
+
description: "Matched exactly, case-sensitively, against Gorgias tags.",
|
|
212
|
+
isNullable: false
|
|
213
|
+
},
|
|
214
|
+
{
|
|
215
|
+
universalIdentifier: CATEGORY_FIELD_ORDER_UID,
|
|
216
|
+
name: "order",
|
|
217
|
+
type: FieldType.NUMBER,
|
|
218
|
+
label: "Order",
|
|
219
|
+
isNullable: false
|
|
220
|
+
},
|
|
221
|
+
{
|
|
222
|
+
universalIdentifier: CATEGORY_FIELD_GROUP_ID_UID,
|
|
223
|
+
name: "groupId",
|
|
224
|
+
type: FieldType.RELATION,
|
|
225
|
+
label: "Category group",
|
|
226
|
+
isNullable: true,
|
|
227
|
+
relation: {
|
|
228
|
+
targetRef: targetRefFor(slug, "category-group"),
|
|
229
|
+
relationType: "MANY_TO_ONE",
|
|
230
|
+
onDelete: "SET_NULL"
|
|
231
|
+
}
|
|
232
|
+
},
|
|
233
|
+
{
|
|
234
|
+
universalIdentifier: CATEGORY_FIELD_AGENT_ID_UID,
|
|
235
|
+
name: "agentId",
|
|
236
|
+
type: FieldType.RELATION,
|
|
237
|
+
label: "Agent",
|
|
238
|
+
isNullable: true,
|
|
239
|
+
relation: {
|
|
240
|
+
targetRef: targetRefFor(slug, "agent"),
|
|
241
|
+
relationType: "MANY_TO_ONE",
|
|
242
|
+
onDelete: "SET_NULL"
|
|
243
|
+
}
|
|
244
|
+
},
|
|
245
|
+
{
|
|
246
|
+
universalIdentifier: CATEGORY_FIELD_EXTRA_TAGS_UID,
|
|
247
|
+
name: "extraTags",
|
|
248
|
+
type: FieldType.JSON,
|
|
249
|
+
label: "Extra tags",
|
|
250
|
+
description: "string[], at most 10 entries of at most 50 characters each.",
|
|
251
|
+
isNullable: false,
|
|
252
|
+
defaultValue: []
|
|
253
|
+
},
|
|
254
|
+
{
|
|
255
|
+
universalIdentifier: CATEGORY_FIELD_EXAMPLES_UID,
|
|
256
|
+
name: "examples",
|
|
257
|
+
type: FieldType.TEXT,
|
|
258
|
+
label: "Examples",
|
|
259
|
+
description: "At most 4000 characters.",
|
|
260
|
+
isNullable: true
|
|
261
|
+
},
|
|
262
|
+
{
|
|
263
|
+
universalIdentifier: CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID,
|
|
264
|
+
name: "fastResponseEnabled",
|
|
265
|
+
type: FieldType.BOOLEAN,
|
|
266
|
+
label: "Fast response enabled",
|
|
267
|
+
isNullable: false,
|
|
268
|
+
defaultValue: false
|
|
269
|
+
},
|
|
270
|
+
{
|
|
271
|
+
universalIdentifier: CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID,
|
|
272
|
+
name: "autoReplyEnabled",
|
|
273
|
+
type: FieldType.BOOLEAN,
|
|
274
|
+
label: "Auto-reply enabled",
|
|
275
|
+
isNullable: false,
|
|
276
|
+
defaultValue: false
|
|
277
|
+
}
|
|
278
|
+
],
|
|
279
|
+
indexes: [
|
|
280
|
+
{ universalIdentifier: CATEGORY_INDEX_TAG_NAME_UID, fields: ["tagName"], isUnique: true },
|
|
281
|
+
{ universalIdentifier: CATEGORY_INDEX_NAME_UID, fields: ["name"], isUnique: true },
|
|
282
|
+
{ universalIdentifier: CATEGORY_INDEX_ORDER_UID, fields: ["order"] }
|
|
283
|
+
]
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
var categoryGroupRecord = {
|
|
287
|
+
universalIdentifier: CATEGORY_GROUP_OBJECT_UID,
|
|
288
|
+
objectKey: "category-group",
|
|
289
|
+
labelSingular: "Category group",
|
|
290
|
+
labelPlural: "Category groups",
|
|
291
|
+
fields: [
|
|
292
|
+
{
|
|
293
|
+
universalIdentifier: CATEGORY_GROUP_FIELD_NAME_UID,
|
|
294
|
+
name: "name",
|
|
295
|
+
type: FieldType.TEXT,
|
|
296
|
+
label: "Name",
|
|
297
|
+
isNullable: false
|
|
298
|
+
},
|
|
299
|
+
{
|
|
300
|
+
universalIdentifier: CATEGORY_GROUP_FIELD_ORDER_UID,
|
|
301
|
+
name: "order",
|
|
302
|
+
type: FieldType.NUMBER,
|
|
303
|
+
label: "Order",
|
|
304
|
+
isNullable: false
|
|
305
|
+
}
|
|
306
|
+
],
|
|
307
|
+
indexes: [{ universalIdentifier: CATEGORY_GROUP_INDEX_NAME_UID, fields: ["name"], isUnique: true }]
|
|
308
|
+
};
|
|
309
|
+
var CONFIDENCE_OPTIONS = ["high", "low"];
|
|
310
|
+
function buildTriageDecisionRecord(slug) {
|
|
311
|
+
return {
|
|
312
|
+
universalIdentifier: TRIAGE_DECISION_OBJECT_UID,
|
|
313
|
+
objectKey: "triage-decision",
|
|
314
|
+
labelSingular: "Triage decision",
|
|
315
|
+
labelPlural: "Triage decisions",
|
|
316
|
+
fields: [
|
|
317
|
+
{
|
|
318
|
+
universalIdentifier: TRIAGE_DECISION_FIELD_TICKET_ID_UID,
|
|
319
|
+
name: "ticketId",
|
|
320
|
+
type: FieldType.TEXT,
|
|
321
|
+
label: "Ticket id",
|
|
322
|
+
isNullable: false
|
|
323
|
+
},
|
|
324
|
+
{
|
|
325
|
+
universalIdentifier: TRIAGE_DECISION_FIELD_DECIDED_AT_UID,
|
|
326
|
+
name: "decidedAt",
|
|
327
|
+
type: FieldType.DATE_TIME,
|
|
328
|
+
label: "Decided at",
|
|
329
|
+
description: "Backs the 24h/7d stat windows \u2014 not the system createdAt.",
|
|
330
|
+
isNullable: false
|
|
331
|
+
},
|
|
332
|
+
{
|
|
333
|
+
universalIdentifier: TRIAGE_DECISION_FIELD_CATEGORY_ID_UID,
|
|
334
|
+
name: "categoryId",
|
|
335
|
+
type: FieldType.RELATION,
|
|
336
|
+
label: "Category",
|
|
337
|
+
isNullable: true,
|
|
338
|
+
relation: {
|
|
339
|
+
targetRef: targetRefFor(slug, "category"),
|
|
340
|
+
relationType: "MANY_TO_ONE",
|
|
341
|
+
onDelete: "SET_NULL"
|
|
342
|
+
}
|
|
343
|
+
},
|
|
344
|
+
{
|
|
345
|
+
universalIdentifier: TRIAGE_DECISION_FIELD_TAG_UID,
|
|
346
|
+
name: "tag",
|
|
347
|
+
type: FieldType.TEXT,
|
|
348
|
+
label: "Tag",
|
|
349
|
+
isNullable: true
|
|
350
|
+
},
|
|
351
|
+
{
|
|
352
|
+
universalIdentifier: TRIAGE_DECISION_FIELD_CONFIDENCE_UID,
|
|
353
|
+
name: "confidence",
|
|
354
|
+
type: FieldType.SELECT,
|
|
355
|
+
label: "Confidence",
|
|
356
|
+
isNullable: false,
|
|
357
|
+
options: [...CONFIDENCE_OPTIONS]
|
|
358
|
+
},
|
|
359
|
+
{
|
|
360
|
+
universalIdentifier: TRIAGE_DECISION_FIELD_REASONING_UID,
|
|
361
|
+
name: "reasoning",
|
|
362
|
+
type: FieldType.TEXT,
|
|
363
|
+
label: "Reasoning",
|
|
364
|
+
description: "At most 280 characters.",
|
|
365
|
+
isNullable: true
|
|
366
|
+
},
|
|
367
|
+
{
|
|
368
|
+
universalIdentifier: TRIAGE_DECISION_FIELD_CONVERSATION_OVER_UID,
|
|
369
|
+
name: "conversationOver",
|
|
370
|
+
type: FieldType.BOOLEAN,
|
|
371
|
+
label: "Conversation over",
|
|
372
|
+
isNullable: false,
|
|
373
|
+
defaultValue: false
|
|
374
|
+
},
|
|
375
|
+
{
|
|
376
|
+
universalIdentifier: TRIAGE_DECISION_FIELD_ESCALATED_UID,
|
|
377
|
+
name: "escalated",
|
|
378
|
+
type: FieldType.BOOLEAN,
|
|
379
|
+
label: "Escalated",
|
|
380
|
+
isNullable: false,
|
|
381
|
+
defaultValue: false
|
|
382
|
+
},
|
|
383
|
+
{
|
|
384
|
+
universalIdentifier: TRIAGE_DECISION_FIELD_ESCALATION_CONFIDENCE_UID,
|
|
385
|
+
name: "escalationConfidence",
|
|
386
|
+
type: FieldType.SELECT,
|
|
387
|
+
label: "Escalation confidence",
|
|
388
|
+
isNullable: true,
|
|
389
|
+
options: [...CONFIDENCE_OPTIONS]
|
|
390
|
+
},
|
|
391
|
+
{
|
|
392
|
+
universalIdentifier: TRIAGE_DECISION_FIELD_ESCALATION_REASONING_UID,
|
|
393
|
+
name: "escalationReasoning",
|
|
394
|
+
type: FieldType.TEXT,
|
|
395
|
+
label: "Escalation reasoning",
|
|
396
|
+
isNullable: true
|
|
397
|
+
},
|
|
398
|
+
{
|
|
399
|
+
universalIdentifier: TRIAGE_DECISION_FIELD_STATUS_UID,
|
|
400
|
+
name: "status",
|
|
401
|
+
type: FieldType.SELECT,
|
|
402
|
+
label: "Status",
|
|
403
|
+
isNullable: false,
|
|
404
|
+
options: ["ok", "error"]
|
|
405
|
+
},
|
|
406
|
+
{
|
|
407
|
+
universalIdentifier: TRIAGE_DECISION_FIELD_ERROR_UID,
|
|
408
|
+
name: "error",
|
|
409
|
+
type: FieldType.TEXT,
|
|
410
|
+
label: "Error",
|
|
411
|
+
isNullable: true
|
|
412
|
+
},
|
|
413
|
+
{
|
|
414
|
+
universalIdentifier: TRIAGE_DECISION_FIELD_RUN_ID_UID,
|
|
415
|
+
name: "runId",
|
|
416
|
+
type: FieldType.TEXT,
|
|
417
|
+
label: "Run id",
|
|
418
|
+
description: "The application run this decision was made under.",
|
|
419
|
+
isNullable: false
|
|
420
|
+
},
|
|
421
|
+
{
|
|
422
|
+
universalIdentifier: TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID,
|
|
423
|
+
name: "subjectRenamed",
|
|
424
|
+
type: FieldType.BOOLEAN,
|
|
425
|
+
label: "Subject renamed",
|
|
426
|
+
isNullable: false,
|
|
427
|
+
defaultValue: false
|
|
428
|
+
}
|
|
429
|
+
],
|
|
430
|
+
indexes: [
|
|
431
|
+
{ universalIdentifier: TRIAGE_DECISION_INDEX_TICKET_ID_UID, fields: ["ticketId"] },
|
|
432
|
+
{ universalIdentifier: TRIAGE_DECISION_INDEX_DECIDED_AT_UID, fields: ["decidedAt"] },
|
|
433
|
+
{ universalIdentifier: TRIAGE_DECISION_INDEX_ESCALATED_UID, fields: ["escalated"] }
|
|
434
|
+
]
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
function buildGeneratedResponseRecord(slug) {
|
|
438
|
+
return {
|
|
439
|
+
universalIdentifier: GENERATED_RESPONSE_OBJECT_UID,
|
|
440
|
+
objectKey: "generated-response",
|
|
441
|
+
labelSingular: "Generated response",
|
|
442
|
+
labelPlural: "Generated responses",
|
|
443
|
+
description: "A drafted reply, from pending draft through its send outcome.",
|
|
444
|
+
fields: [
|
|
445
|
+
{
|
|
446
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_TICKET_ID_UID,
|
|
447
|
+
name: "ticketId",
|
|
448
|
+
type: FieldType.TEXT,
|
|
449
|
+
label: "Ticket id",
|
|
450
|
+
isNullable: false
|
|
451
|
+
},
|
|
452
|
+
{
|
|
453
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_OPEN_TICKET_KEY_UID,
|
|
454
|
+
name: "openTicketKey",
|
|
455
|
+
type: FieldType.TEXT,
|
|
456
|
+
label: "Open ticket key",
|
|
457
|
+
description: "= ticketId while status is open, cleared on a terminal status. Unique \u2014 see openTicketKeyFor().",
|
|
458
|
+
isNullable: true
|
|
459
|
+
},
|
|
460
|
+
{
|
|
461
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_STATUS_UID,
|
|
462
|
+
name: "status",
|
|
463
|
+
type: FieldType.SELECT,
|
|
464
|
+
label: "Status",
|
|
465
|
+
isNullable: false,
|
|
466
|
+
options: [...GENERATED_RESPONSE_STATUSES],
|
|
467
|
+
defaultValue: "pending"
|
|
468
|
+
},
|
|
469
|
+
{
|
|
470
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_TRIAGE_DECISION_ID_UID,
|
|
471
|
+
name: "triageDecisionId",
|
|
472
|
+
type: FieldType.RELATION,
|
|
473
|
+
label: "Triage decision",
|
|
474
|
+
isNullable: false,
|
|
475
|
+
relation: {
|
|
476
|
+
targetRef: targetRefFor(slug, "triage-decision"),
|
|
477
|
+
relationType: "MANY_TO_ONE",
|
|
478
|
+
onDelete: "CASCADE"
|
|
479
|
+
}
|
|
480
|
+
},
|
|
481
|
+
{
|
|
482
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_CATEGORY_ID_UID,
|
|
483
|
+
name: "categoryId",
|
|
484
|
+
type: FieldType.RELATION,
|
|
485
|
+
label: "Category",
|
|
486
|
+
isNullable: true,
|
|
487
|
+
relation: {
|
|
488
|
+
targetRef: targetRefFor(slug, "category"),
|
|
489
|
+
relationType: "MANY_TO_ONE",
|
|
490
|
+
onDelete: "SET_NULL"
|
|
491
|
+
}
|
|
492
|
+
},
|
|
493
|
+
{
|
|
494
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_AGENT_ID_UID,
|
|
495
|
+
name: "agentId",
|
|
496
|
+
type: FieldType.RELATION,
|
|
497
|
+
label: "Agent",
|
|
498
|
+
isNullable: true,
|
|
499
|
+
relation: {
|
|
500
|
+
targetRef: targetRefFor(slug, "agent"),
|
|
501
|
+
relationType: "MANY_TO_ONE",
|
|
502
|
+
onDelete: "SET_NULL"
|
|
503
|
+
}
|
|
504
|
+
},
|
|
505
|
+
{
|
|
506
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_CHANNEL_UID,
|
|
507
|
+
name: "channel",
|
|
508
|
+
type: FieldType.SELECT,
|
|
509
|
+
label: "Channel",
|
|
510
|
+
isNullable: false,
|
|
511
|
+
options: ["email", "whatsapp"]
|
|
512
|
+
},
|
|
513
|
+
{
|
|
514
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_RESPONSE_TEXT_UID,
|
|
515
|
+
name: "responseText",
|
|
516
|
+
type: FieldType.TEXT,
|
|
517
|
+
label: "Response text",
|
|
518
|
+
isNullable: true
|
|
519
|
+
},
|
|
520
|
+
{
|
|
521
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_SOURCES_UID,
|
|
522
|
+
name: "sources",
|
|
523
|
+
type: FieldType.JSON,
|
|
524
|
+
label: "Sources",
|
|
525
|
+
description: "[{name, arguments, observation}]",
|
|
526
|
+
isNullable: false,
|
|
527
|
+
defaultValue: []
|
|
528
|
+
},
|
|
529
|
+
{
|
|
530
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_TRACED_INPUT_UID,
|
|
531
|
+
name: "tracedInput",
|
|
532
|
+
type: FieldType.JSON,
|
|
533
|
+
label: "Traced input",
|
|
534
|
+
description: "[{role, content}]",
|
|
535
|
+
isNullable: false,
|
|
536
|
+
defaultValue: []
|
|
537
|
+
},
|
|
538
|
+
{
|
|
539
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_VERDICT_UID,
|
|
540
|
+
name: "verdict",
|
|
541
|
+
type: FieldType.JSON,
|
|
542
|
+
label: "Verdict",
|
|
543
|
+
description: "{verdict, confidence, reason, status}",
|
|
544
|
+
isNullable: true
|
|
545
|
+
},
|
|
546
|
+
{
|
|
547
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_UID,
|
|
548
|
+
name: "guardrailHits",
|
|
549
|
+
type: FieldType.JSON,
|
|
550
|
+
label: "Guardrail hits",
|
|
551
|
+
description: "string[]",
|
|
552
|
+
isNullable: false,
|
|
553
|
+
defaultValue: []
|
|
554
|
+
},
|
|
555
|
+
{
|
|
556
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_AUTO_SEND_DECISION_UID,
|
|
557
|
+
name: "autoSendDecision",
|
|
558
|
+
type: FieldType.SELECT,
|
|
559
|
+
label: "Auto-send decision",
|
|
560
|
+
isNullable: true,
|
|
561
|
+
options: ["auto", "hold"]
|
|
562
|
+
},
|
|
563
|
+
{
|
|
564
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_FOLLOWUP_REQUIRED_UID,
|
|
565
|
+
name: "followupRequired",
|
|
566
|
+
type: FieldType.BOOLEAN,
|
|
567
|
+
label: "Followup required",
|
|
568
|
+
isNullable: false,
|
|
569
|
+
defaultValue: false
|
|
570
|
+
},
|
|
571
|
+
{
|
|
572
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_SERVED_COUNT_UID,
|
|
573
|
+
name: "servedCount",
|
|
574
|
+
type: FieldType.NUMBER,
|
|
575
|
+
label: "Served count",
|
|
576
|
+
isNullable: false,
|
|
577
|
+
defaultValue: 0
|
|
578
|
+
},
|
|
579
|
+
{
|
|
580
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_SERVED_TO_UID,
|
|
581
|
+
name: "servedTo",
|
|
582
|
+
type: FieldType.JSON,
|
|
583
|
+
label: "Served to",
|
|
584
|
+
description: "[{user, at}], capped at 500 entries. Updated via S5 ifMatch + retry.",
|
|
585
|
+
isNullable: false,
|
|
586
|
+
defaultValue: []
|
|
587
|
+
},
|
|
588
|
+
{
|
|
589
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_GENERATED_AT_UID,
|
|
590
|
+
name: "generatedAt",
|
|
591
|
+
type: FieldType.DATE_TIME,
|
|
592
|
+
label: "Generated at",
|
|
593
|
+
description: "Backs the daily series stat.",
|
|
594
|
+
isNullable: false
|
|
595
|
+
},
|
|
596
|
+
{
|
|
597
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_EXPIRES_AT_UID,
|
|
598
|
+
name: "expiresAt",
|
|
599
|
+
type: FieldType.DATE_TIME,
|
|
600
|
+
label: "Expires at",
|
|
601
|
+
isNullable: false
|
|
602
|
+
},
|
|
603
|
+
{
|
|
604
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_SENT_AT_UID,
|
|
605
|
+
name: "sentAt",
|
|
606
|
+
type: FieldType.DATE_TIME,
|
|
607
|
+
label: "Sent at",
|
|
608
|
+
isNullable: true
|
|
609
|
+
},
|
|
610
|
+
{
|
|
611
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_SENT_MESSAGE_ID_UID,
|
|
612
|
+
name: "sentMessageId",
|
|
613
|
+
type: FieldType.TEXT,
|
|
614
|
+
label: "Sent message id",
|
|
615
|
+
isNullable: true
|
|
616
|
+
},
|
|
617
|
+
{
|
|
618
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_LANGFUSE_TRACE_ID_UID,
|
|
619
|
+
name: "langfuseTraceId",
|
|
620
|
+
type: FieldType.TEXT,
|
|
621
|
+
label: "Langfuse trace id",
|
|
622
|
+
isNullable: true
|
|
623
|
+
},
|
|
624
|
+
{
|
|
625
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_LANGFUSE_OBSERVATION_ID_UID,
|
|
626
|
+
name: "langfuseObservationId",
|
|
627
|
+
type: FieldType.TEXT,
|
|
628
|
+
label: "Langfuse observation id",
|
|
629
|
+
isNullable: true
|
|
630
|
+
},
|
|
631
|
+
{
|
|
632
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_PROMPT_NAME_UID,
|
|
633
|
+
name: "promptName",
|
|
634
|
+
type: FieldType.TEXT,
|
|
635
|
+
label: "Prompt name",
|
|
636
|
+
isNullable: true
|
|
637
|
+
},
|
|
638
|
+
{
|
|
639
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_PROMPT_VERSION_UID,
|
|
640
|
+
name: "promptVersion",
|
|
641
|
+
type: FieldType.NUMBER,
|
|
642
|
+
label: "Prompt version",
|
|
643
|
+
isNullable: true
|
|
644
|
+
},
|
|
645
|
+
{
|
|
646
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_ERROR_UID,
|
|
647
|
+
name: "error",
|
|
648
|
+
type: FieldType.TEXT,
|
|
649
|
+
label: "Error",
|
|
650
|
+
isNullable: true
|
|
651
|
+
},
|
|
652
|
+
{
|
|
653
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_GENERATED_MESSAGE_COUNT_UID,
|
|
654
|
+
name: "generatedMessageCount",
|
|
655
|
+
type: FieldType.NUMBER,
|
|
656
|
+
label: "Generated message count",
|
|
657
|
+
description: "Conversation.messageCount snapshot at generation time \u2014 act()'s divergence baseline when replayed via handle-approval.",
|
|
658
|
+
isNullable: true
|
|
659
|
+
},
|
|
660
|
+
{
|
|
661
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_GENERATED_LAST_MESSAGE_AT_UID,
|
|
662
|
+
name: "generatedLastMessageAt",
|
|
663
|
+
type: FieldType.DATE_TIME,
|
|
664
|
+
label: "Generated last message at",
|
|
665
|
+
description: "Conversation.lastMessageAt snapshot at generation time \u2014 act()'s divergence baseline when replayed via handle-approval.",
|
|
666
|
+
isNullable: true
|
|
667
|
+
},
|
|
668
|
+
{
|
|
669
|
+
universalIdentifier: GENERATED_RESPONSE_FIELD_SENDING_AT_UID,
|
|
670
|
+
name: "sendingAt",
|
|
671
|
+
type: FieldType.DATE_TIME,
|
|
672
|
+
label: "Sending at",
|
|
673
|
+
description: "When status became 'sending' \u2014 the sweep's staleness clock (\xA73.5).",
|
|
674
|
+
isNullable: true
|
|
675
|
+
}
|
|
676
|
+
],
|
|
677
|
+
indexes: [
|
|
678
|
+
{ universalIdentifier: GENERATED_RESPONSE_INDEX_TICKET_ID_UID, fields: ["ticketId"] },
|
|
679
|
+
{
|
|
680
|
+
universalIdentifier: GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID,
|
|
681
|
+
fields: ["openTicketKey"],
|
|
682
|
+
isUnique: true
|
|
683
|
+
},
|
|
684
|
+
{ universalIdentifier: GENERATED_RESPONSE_INDEX_STATUS_UID, fields: ["status"] },
|
|
685
|
+
{
|
|
686
|
+
universalIdentifier: GENERATED_RESPONSE_INDEX_TRIAGE_DECISION_ID_UID,
|
|
687
|
+
fields: ["triageDecisionId"],
|
|
688
|
+
isUnique: true
|
|
689
|
+
},
|
|
690
|
+
{ universalIdentifier: GENERATED_RESPONSE_INDEX_GENERATED_AT_UID, fields: ["generatedAt"] },
|
|
691
|
+
{ universalIdentifier: GENERATED_RESPONSE_INDEX_EXPIRES_AT_UID, fields: ["expiresAt"] }
|
|
692
|
+
]
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
function buildResponseComparisonRecord(slug) {
|
|
696
|
+
return {
|
|
697
|
+
universalIdentifier: RESPONSE_COMPARISON_OBJECT_UID,
|
|
698
|
+
objectKey: "response-comparison",
|
|
699
|
+
labelSingular: "Response comparison",
|
|
700
|
+
labelPlural: "Response comparisons",
|
|
701
|
+
description: "Compares the agent's draft against what the human actually sent.",
|
|
702
|
+
fields: [
|
|
703
|
+
{
|
|
704
|
+
universalIdentifier: RESPONSE_COMPARISON_FIELD_GENERATED_TEXT_UID,
|
|
705
|
+
name: "generatedText",
|
|
706
|
+
type: FieldType.TEXT,
|
|
707
|
+
label: "Generated text",
|
|
708
|
+
isNullable: true
|
|
709
|
+
},
|
|
710
|
+
{
|
|
711
|
+
universalIdentifier: RESPONSE_COMPARISON_FIELD_SENT_TEXT_UID,
|
|
712
|
+
name: "sentText",
|
|
713
|
+
type: FieldType.TEXT,
|
|
714
|
+
label: "Sent text",
|
|
715
|
+
isNullable: false
|
|
716
|
+
},
|
|
717
|
+
{
|
|
718
|
+
universalIdentifier: RESPONSE_COMPARISON_FIELD_CAPTURED_AT_UID,
|
|
719
|
+
name: "capturedAt",
|
|
720
|
+
type: FieldType.DATE_TIME,
|
|
721
|
+
label: "Captured at",
|
|
722
|
+
description: "Backs the rewrite-rate trend.",
|
|
723
|
+
isNullable: false
|
|
724
|
+
},
|
|
725
|
+
{
|
|
726
|
+
universalIdentifier: RESPONSE_COMPARISON_FIELD_TICKET_ID_UID,
|
|
727
|
+
name: "ticketId",
|
|
728
|
+
type: FieldType.TEXT,
|
|
729
|
+
label: "Ticket id",
|
|
730
|
+
isNullable: true
|
|
731
|
+
},
|
|
732
|
+
{
|
|
733
|
+
universalIdentifier: RESPONSE_COMPARISON_FIELD_TICKET_URL_UID,
|
|
734
|
+
name: "ticketUrl",
|
|
735
|
+
type: FieldType.TEXT,
|
|
736
|
+
label: "Ticket URL",
|
|
737
|
+
isNullable: false
|
|
738
|
+
},
|
|
739
|
+
{
|
|
740
|
+
universalIdentifier: RESPONSE_COMPARISON_FIELD_AGENT_ID_UID,
|
|
741
|
+
name: "agentId",
|
|
742
|
+
type: FieldType.RELATION,
|
|
743
|
+
label: "Agent",
|
|
744
|
+
isNullable: true,
|
|
745
|
+
relation: {
|
|
746
|
+
targetRef: targetRefFor(slug, "agent"),
|
|
747
|
+
relationType: "MANY_TO_ONE",
|
|
748
|
+
onDelete: "SET_NULL"
|
|
749
|
+
}
|
|
750
|
+
},
|
|
751
|
+
{
|
|
752
|
+
universalIdentifier: RESPONSE_COMPARISON_FIELD_LANGFUSE_TRACE_ID_UID,
|
|
753
|
+
name: "langfuseTraceId",
|
|
754
|
+
type: FieldType.TEXT,
|
|
755
|
+
label: "Langfuse trace id",
|
|
756
|
+
isNullable: true
|
|
757
|
+
},
|
|
758
|
+
{
|
|
759
|
+
universalIdentifier: RESPONSE_COMPARISON_FIELD_LANGFUSE_OBSERVATION_ID_UID,
|
|
760
|
+
name: "langfuseObservationId",
|
|
761
|
+
type: FieldType.TEXT,
|
|
762
|
+
label: "Langfuse observation id",
|
|
763
|
+
isNullable: true
|
|
764
|
+
},
|
|
765
|
+
{
|
|
766
|
+
universalIdentifier: RESPONSE_COMPARISON_FIELD_PROMPT_NAME_UID,
|
|
767
|
+
name: "promptName",
|
|
768
|
+
type: FieldType.TEXT,
|
|
769
|
+
label: "Prompt name",
|
|
770
|
+
isNullable: true
|
|
771
|
+
},
|
|
772
|
+
{
|
|
773
|
+
universalIdentifier: RESPONSE_COMPARISON_FIELD_PROMPT_VERSION_UID,
|
|
774
|
+
name: "promptVersion",
|
|
775
|
+
type: FieldType.NUMBER,
|
|
776
|
+
label: "Prompt version",
|
|
777
|
+
isNullable: true
|
|
778
|
+
},
|
|
779
|
+
{
|
|
780
|
+
universalIdentifier: RESPONSE_COMPARISON_FIELD_CONVERSATION_MESSAGES_UID,
|
|
781
|
+
name: "conversationMessages",
|
|
782
|
+
type: FieldType.JSON,
|
|
783
|
+
label: "Conversation messages",
|
|
784
|
+
description: "[{role, content}]",
|
|
785
|
+
isNullable: false,
|
|
786
|
+
defaultValue: []
|
|
787
|
+
},
|
|
788
|
+
{
|
|
789
|
+
universalIdentifier: RESPONSE_COMPARISON_FIELD_DIFF_UID,
|
|
790
|
+
name: "diff",
|
|
791
|
+
type: FieldType.JSON,
|
|
792
|
+
label: "Diff",
|
|
793
|
+
description: "Word-by-word diff, computed at write time.",
|
|
794
|
+
isNullable: true
|
|
795
|
+
}
|
|
796
|
+
],
|
|
797
|
+
indexes: [
|
|
798
|
+
{ universalIdentifier: RESPONSE_COMPARISON_INDEX_CAPTURED_AT_UID, fields: ["capturedAt"] },
|
|
799
|
+
{ universalIdentifier: RESPONSE_COMPARISON_INDEX_TICKET_ID_UID, fields: ["ticketId"] }
|
|
800
|
+
]
|
|
801
|
+
};
|
|
802
|
+
}
|
|
803
|
+
function buildEvaluationRecord(slug) {
|
|
804
|
+
return {
|
|
805
|
+
universalIdentifier: EVALUATION_OBJECT_UID,
|
|
806
|
+
objectKey: "evaluation",
|
|
807
|
+
labelSingular: "Evaluation",
|
|
808
|
+
labelPlural: "Evaluations",
|
|
809
|
+
description: "A human satisfaction verdict on an agent conversation.",
|
|
810
|
+
fields: [
|
|
811
|
+
{
|
|
812
|
+
universalIdentifier: EVALUATION_FIELD_AGENT_ID_UID,
|
|
813
|
+
name: "agentId",
|
|
814
|
+
type: FieldType.RELATION,
|
|
815
|
+
label: "Agent",
|
|
816
|
+
isNullable: false,
|
|
817
|
+
relation: {
|
|
818
|
+
targetRef: targetRefFor(slug, "agent"),
|
|
819
|
+
relationType: "MANY_TO_ONE",
|
|
820
|
+
onDelete: "CASCADE"
|
|
821
|
+
}
|
|
822
|
+
},
|
|
823
|
+
{
|
|
824
|
+
universalIdentifier: EVALUATION_FIELD_SATISFIED_UID,
|
|
825
|
+
name: "satisfied",
|
|
826
|
+
type: FieldType.BOOLEAN,
|
|
827
|
+
label: "Satisfied",
|
|
828
|
+
isNullable: false
|
|
829
|
+
},
|
|
830
|
+
{
|
|
831
|
+
universalIdentifier: EVALUATION_FIELD_MESSAGES_UID,
|
|
832
|
+
name: "messages",
|
|
833
|
+
type: FieldType.JSON,
|
|
834
|
+
label: "Messages",
|
|
835
|
+
description: "[{role, content}] \u2014 the conversation the verdict is about.",
|
|
836
|
+
isNullable: false,
|
|
837
|
+
defaultValue: []
|
|
838
|
+
},
|
|
839
|
+
{
|
|
840
|
+
universalIdentifier: EVALUATION_FIELD_TICKET_URL_UID,
|
|
841
|
+
name: "ticketUrl",
|
|
842
|
+
type: FieldType.TEXT,
|
|
843
|
+
label: "Ticket URL",
|
|
844
|
+
isNullable: false
|
|
845
|
+
},
|
|
846
|
+
{
|
|
847
|
+
universalIdentifier: EVALUATION_FIELD_LANGFUSE_TRACE_ID_UID,
|
|
848
|
+
name: "langfuseTraceId",
|
|
849
|
+
type: FieldType.TEXT,
|
|
850
|
+
label: "Langfuse trace id",
|
|
851
|
+
isNullable: true
|
|
852
|
+
},
|
|
853
|
+
{
|
|
854
|
+
universalIdentifier: EVALUATION_FIELD_LANGFUSE_OBSERVATION_ID_UID,
|
|
855
|
+
name: "langfuseObservationId",
|
|
856
|
+
type: FieldType.TEXT,
|
|
857
|
+
label: "Langfuse observation id",
|
|
858
|
+
isNullable: true
|
|
859
|
+
},
|
|
860
|
+
{
|
|
861
|
+
universalIdentifier: EVALUATION_FIELD_SUPPORT_USER_KEY_ID_UID,
|
|
862
|
+
name: "supportUserKeyId",
|
|
863
|
+
type: FieldType.TEXT,
|
|
864
|
+
label: "Support user key id",
|
|
865
|
+
isNullable: true
|
|
866
|
+
}
|
|
867
|
+
]
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
function diffAnalysisUniqueKey(agentId, promptName, promptVersion) {
|
|
871
|
+
return `${agentId}::${promptName}::${promptVersion}`;
|
|
872
|
+
}
|
|
873
|
+
function buildDiffAnalysisRecord(slug) {
|
|
874
|
+
return {
|
|
875
|
+
universalIdentifier: DIFF_ANALYSIS_OBJECT_UID,
|
|
876
|
+
objectKey: "diff-analysis",
|
|
877
|
+
labelSingular: "Diff analysis",
|
|
878
|
+
labelPlural: "Diff analyses",
|
|
879
|
+
description: "Correction patterns aggregated for one (agent, prompt, version).",
|
|
880
|
+
fields: [
|
|
881
|
+
{
|
|
882
|
+
universalIdentifier: DIFF_ANALYSIS_FIELD_AGENT_ID_UID,
|
|
883
|
+
name: "agentId",
|
|
884
|
+
type: FieldType.RELATION,
|
|
885
|
+
label: "Agent",
|
|
886
|
+
isNullable: false,
|
|
887
|
+
relation: {
|
|
888
|
+
targetRef: targetRefFor(slug, "agent"),
|
|
889
|
+
relationType: "MANY_TO_ONE",
|
|
890
|
+
onDelete: "CASCADE"
|
|
891
|
+
}
|
|
892
|
+
},
|
|
893
|
+
{
|
|
894
|
+
universalIdentifier: DIFF_ANALYSIS_FIELD_PROMPT_NAME_UID,
|
|
895
|
+
name: "promptName",
|
|
896
|
+
type: FieldType.TEXT,
|
|
897
|
+
label: "Prompt name",
|
|
898
|
+
isNullable: false
|
|
899
|
+
},
|
|
900
|
+
{
|
|
901
|
+
universalIdentifier: DIFF_ANALYSIS_FIELD_PROMPT_VERSION_UID,
|
|
902
|
+
name: "promptVersion",
|
|
903
|
+
type: FieldType.NUMBER,
|
|
904
|
+
label: "Prompt version",
|
|
905
|
+
isNullable: false
|
|
906
|
+
},
|
|
907
|
+
{
|
|
908
|
+
universalIdentifier: DIFF_ANALYSIS_FIELD_POINTS_UID,
|
|
909
|
+
name: "points",
|
|
910
|
+
type: FieldType.JSON,
|
|
911
|
+
label: "Points",
|
|
912
|
+
description: "string[]",
|
|
913
|
+
isNullable: false,
|
|
914
|
+
defaultValue: []
|
|
915
|
+
},
|
|
916
|
+
{
|
|
917
|
+
universalIdentifier: DIFF_ANALYSIS_FIELD_UNIQUE_KEY_UID,
|
|
918
|
+
name: "uniqueKey",
|
|
919
|
+
type: FieldType.TEXT,
|
|
920
|
+
label: "Unique key",
|
|
921
|
+
description: "<agentId>::<promptName>::<promptVersion>",
|
|
922
|
+
isNullable: false
|
|
923
|
+
}
|
|
924
|
+
],
|
|
925
|
+
indexes: [
|
|
926
|
+
{ universalIdentifier: DIFF_ANALYSIS_INDEX_UNIQUE_KEY_UID, fields: ["uniqueKey"], isUnique: true }
|
|
927
|
+
]
|
|
928
|
+
};
|
|
929
|
+
}
|
|
930
|
+
var pipelineStateRecord = {
|
|
931
|
+
universalIdentifier: PIPELINE_STATE_OBJECT_UID,
|
|
932
|
+
objectKey: "pipeline-state",
|
|
933
|
+
labelSingular: "Pipeline state",
|
|
934
|
+
labelPlural: "Pipeline state",
|
|
935
|
+
description: "Singleton run-cadence and view-claim state, readable by every installed app.",
|
|
936
|
+
fields: [
|
|
937
|
+
{
|
|
938
|
+
universalIdentifier: PIPELINE_STATE_FIELD_SINGLETON_KEY_UID,
|
|
939
|
+
name: "singletonKey",
|
|
940
|
+
type: FieldType.TEXT,
|
|
941
|
+
label: "Singleton key",
|
|
942
|
+
description: "Always the same constant value \u2014 the unique index below is what makes this record a true singleton, not just a convention.",
|
|
943
|
+
isNullable: false
|
|
944
|
+
},
|
|
945
|
+
{
|
|
946
|
+
universalIdentifier: PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID,
|
|
947
|
+
name: "sourceViewId",
|
|
948
|
+
type: FieldType.TEXT,
|
|
949
|
+
label: "Source view id",
|
|
950
|
+
description: "The claimed Gorgias view \u2014 supports the cross-app overlap warning (\xA74).",
|
|
951
|
+
isNullable: true
|
|
952
|
+
},
|
|
953
|
+
{
|
|
954
|
+
universalIdentifier: PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID,
|
|
955
|
+
name: "lastTriageAt",
|
|
956
|
+
type: FieldType.DATE_TIME,
|
|
957
|
+
label: "Last triage at",
|
|
958
|
+
description: "Gates triage-tick's cadence.",
|
|
959
|
+
isNullable: true
|
|
960
|
+
},
|
|
961
|
+
{
|
|
962
|
+
universalIdentifier: PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID,
|
|
963
|
+
name: "lastSweepAt",
|
|
964
|
+
type: FieldType.DATE_TIME,
|
|
965
|
+
label: "Last sweep at",
|
|
966
|
+
isNullable: true
|
|
967
|
+
}
|
|
968
|
+
],
|
|
969
|
+
indexes: [{ universalIdentifier: PIPELINE_STATE_INDEX_SINGLETON_KEY_UID, fields: ["singletonKey"], isUnique: true }],
|
|
970
|
+
exposedToApps: ["*"]
|
|
971
|
+
};
|
|
972
|
+
var promptCacheRecord = {
|
|
973
|
+
universalIdentifier: PROMPT_CACHE_OBJECT_UID,
|
|
974
|
+
objectKey: "prompt-cache",
|
|
975
|
+
labelSingular: "Prompt cache entry",
|
|
976
|
+
labelPlural: "Prompt cache entries",
|
|
977
|
+
description: "Last-known-good snapshot of a Langfuse prompt, for the resolver fallback ladder.",
|
|
978
|
+
fields: [
|
|
979
|
+
{
|
|
980
|
+
universalIdentifier: PROMPT_CACHE_FIELD_PROMPT_KEY_UID,
|
|
981
|
+
name: "promptKey",
|
|
982
|
+
type: FieldType.TEXT,
|
|
983
|
+
label: "Prompt key",
|
|
984
|
+
description: "'name' or 'name::label'.",
|
|
985
|
+
isNullable: false
|
|
986
|
+
},
|
|
987
|
+
{
|
|
988
|
+
universalIdentifier: PROMPT_CACHE_FIELD_CONTENT_UID,
|
|
989
|
+
name: "content",
|
|
990
|
+
type: FieldType.TEXT,
|
|
991
|
+
label: "Content",
|
|
992
|
+
description: "Raw, uncompiled template.",
|
|
993
|
+
isNullable: false
|
|
994
|
+
},
|
|
995
|
+
{
|
|
996
|
+
universalIdentifier: PROMPT_CACHE_FIELD_VERSION_UID,
|
|
997
|
+
name: "version",
|
|
998
|
+
type: FieldType.NUMBER,
|
|
999
|
+
label: "Version",
|
|
1000
|
+
isNullable: false
|
|
1001
|
+
},
|
|
1002
|
+
{
|
|
1003
|
+
universalIdentifier: PROMPT_CACHE_FIELD_LABEL_UID,
|
|
1004
|
+
name: "label",
|
|
1005
|
+
type: FieldType.TEXT,
|
|
1006
|
+
label: "Label",
|
|
1007
|
+
isNullable: true
|
|
1008
|
+
},
|
|
1009
|
+
{
|
|
1010
|
+
universalIdentifier: PROMPT_CACHE_FIELD_CONFIG_UID,
|
|
1011
|
+
name: "config",
|
|
1012
|
+
type: FieldType.JSON,
|
|
1013
|
+
label: "Config",
|
|
1014
|
+
description: "Model config snapshot, for I16. Not yet written or read \u2014 see module doc.",
|
|
1015
|
+
isNullable: true
|
|
1016
|
+
}
|
|
1017
|
+
],
|
|
1018
|
+
indexes: [{ universalIdentifier: PROMPT_CACHE_INDEX_PROMPT_KEY_UID, fields: ["promptKey"], isUnique: true }]
|
|
1019
|
+
};
|
|
1020
|
+
var SUPPORT_KIT_UID_NAMESPACE = "2b6a9c0e-6c1e-4c1a-8b0e-2a2f4b8c9d3f";
|
|
1021
|
+
function uuidToBytes(uuid) {
|
|
1022
|
+
return Buffer.from(uuid.replace(/-/g, ""), "hex");
|
|
1023
|
+
}
|
|
1024
|
+
function bytesToUuid(bytes) {
|
|
1025
|
+
const hex = bytes.toString("hex");
|
|
1026
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
1027
|
+
}
|
|
1028
|
+
function deriveUid(seed) {
|
|
1029
|
+
const hash = createHash("sha1").update(uuidToBytes(SUPPORT_KIT_UID_NAMESPACE)).update(seed, "utf8").digest();
|
|
1030
|
+
const bytes = hash.subarray(0, 16);
|
|
1031
|
+
bytes[6] = bytes[6] & 15 | 80;
|
|
1032
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
1033
|
+
return bytesToUuid(bytes);
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
// src/records/scope-to-app.ts
|
|
1037
|
+
function scopeRecordToApp(slug, record) {
|
|
1038
|
+
return {
|
|
1039
|
+
...record,
|
|
1040
|
+
universalIdentifier: deriveUid(`${slug}:${record.universalIdentifier}`),
|
|
1041
|
+
fields: record.fields.map((field) => ({
|
|
1042
|
+
...field,
|
|
1043
|
+
universalIdentifier: deriveUid(`${slug}:${field.universalIdentifier}`)
|
|
1044
|
+
})),
|
|
1045
|
+
indexes: record.indexes?.map((index) => ({
|
|
1046
|
+
...index,
|
|
1047
|
+
universalIdentifier: deriveUid(`${slug}:${index.universalIdentifier}`)
|
|
1048
|
+
}))
|
|
1049
|
+
};
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
// src/records/index.ts
|
|
1053
|
+
function buildSupportKitRecords(slug) {
|
|
1054
|
+
return [
|
|
1055
|
+
buildCategoryRecord(slug),
|
|
1056
|
+
categoryGroupRecord,
|
|
1057
|
+
agentRecord,
|
|
1058
|
+
buildTriageDecisionRecord(slug),
|
|
1059
|
+
buildGeneratedResponseRecord(slug),
|
|
1060
|
+
buildResponseComparisonRecord(slug),
|
|
1061
|
+
buildEvaluationRecord(slug),
|
|
1062
|
+
buildDiffAnalysisRecord(slug),
|
|
1063
|
+
pipelineStateRecord,
|
|
1064
|
+
promptCacheRecord
|
|
1065
|
+
].map((record) => scopeRecordToApp(slug, record));
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
// src/functions/config.ts
|
|
1069
|
+
function identifierFor(config, key) {
|
|
1070
|
+
const id = config.identifiers[key];
|
|
1071
|
+
if (!id) {
|
|
1072
|
+
throw new Error(
|
|
1073
|
+
`SupportKitFunctionConfig.identifiers is missing a universalIdentifier for "${key}" \u2014 every support-kit function needs a stable id.`
|
|
1074
|
+
);
|
|
1075
|
+
}
|
|
1076
|
+
return id;
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
// src/adapters/conversation-mapping.ts
|
|
1080
|
+
function isInternalNoteChannel(message) {
|
|
1081
|
+
return message.channel === "internal-note" || message.source?.type === "internal-note";
|
|
1082
|
+
}
|
|
1083
|
+
function countableMessages(messages, isWhatsapp) {
|
|
1084
|
+
return messages.filter((m) => {
|
|
1085
|
+
if (isInternalNoteChannel(m)) return isWhatsappChevronNote(m, isWhatsapp);
|
|
1086
|
+
const hasText = !!(m.body_text?.trim() || m.body_html?.trim() || m.stripped_text?.trim() || m.stripped_html?.trim());
|
|
1087
|
+
const hasAttachment = (m.attachments?.length ?? 0) > 0;
|
|
1088
|
+
return hasText || hasAttachment;
|
|
1089
|
+
});
|
|
1090
|
+
}
|
|
1091
|
+
function snapshotConversation(raw) {
|
|
1092
|
+
const isWhatsapp = isWhatsappTicket(raw);
|
|
1093
|
+
const messages = countableMessages(raw.messages ?? [], isWhatsapp);
|
|
1094
|
+
let lastAt = null;
|
|
1095
|
+
for (const m of messages) {
|
|
1096
|
+
if (!m.created_datetime) continue;
|
|
1097
|
+
const at = new Date(m.created_datetime);
|
|
1098
|
+
if (!lastAt || at > lastAt) lastAt = at;
|
|
1099
|
+
}
|
|
1100
|
+
return { count: messages.length, lastAt };
|
|
1101
|
+
}
|
|
1102
|
+
function lastAgentReplyAtOf(raw) {
|
|
1103
|
+
const isWhatsapp = isWhatsappTicket(raw);
|
|
1104
|
+
let latest = null;
|
|
1105
|
+
for (const m of raw.messages ?? []) {
|
|
1106
|
+
if (m.from_agent !== true) continue;
|
|
1107
|
+
if (isInternalNoteChannel(m) && !isWhatsappChevronNote(m, isWhatsapp)) continue;
|
|
1108
|
+
if (!m.created_datetime) continue;
|
|
1109
|
+
const at = new Date(m.created_datetime);
|
|
1110
|
+
if (!latest || at > latest) latest = at;
|
|
1111
|
+
}
|
|
1112
|
+
return latest;
|
|
1113
|
+
}
|
|
1114
|
+
function toConversation(ref, raw, context) {
|
|
1115
|
+
const snapshot = snapshotConversation(raw);
|
|
1116
|
+
const messages = context.messages.filter((m) => m.role === "user" || m.role === "assistant").map((m) => ({ role: m.role, content: m.content }));
|
|
1117
|
+
return {
|
|
1118
|
+
ref,
|
|
1119
|
+
subject: raw.subject ?? null,
|
|
1120
|
+
messages,
|
|
1121
|
+
customer: {
|
|
1122
|
+
name: context.customerName ?? null,
|
|
1123
|
+
email: context.customerEmail ?? null,
|
|
1124
|
+
orderContext: context.customerContext ?? null
|
|
1125
|
+
},
|
|
1126
|
+
isClosed: isTicketClosed(raw),
|
|
1127
|
+
lastMessageAt: snapshot.lastAt,
|
|
1128
|
+
messageCount: snapshot.count,
|
|
1129
|
+
lastAgentReplyAt: lastAgentReplyAtOf(raw),
|
|
1130
|
+
hasCustomerAttachment: hasCustomerAttachment(raw),
|
|
1131
|
+
sourceChannel: isWhatsappTicket(raw) ? "whatsapp" : raw.channel ?? null
|
|
1132
|
+
};
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
// src/adapters/gorgias-tags.ts
|
|
1136
|
+
function dedupeTagNames(tags) {
|
|
1137
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1138
|
+
const out = [];
|
|
1139
|
+
for (const tag of tags) {
|
|
1140
|
+
const trimmed = (tag ?? "").trim();
|
|
1141
|
+
if (trimmed && !seen.has(trimmed)) {
|
|
1142
|
+
seen.add(trimmed);
|
|
1143
|
+
out.push(trimmed);
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
return out;
|
|
1147
|
+
}
|
|
1148
|
+
async function extraTagsFor(api, tagName) {
|
|
1149
|
+
const page = await api.list("category", { filter: { tagName }, limit: 1 });
|
|
1150
|
+
const data = page.items[0]?.data;
|
|
1151
|
+
return data?.extraTags ?? [];
|
|
1152
|
+
}
|
|
1153
|
+
async function resolveHandledTags(api, classification, audit) {
|
|
1154
|
+
const extraTags = await extraTagsFor(api, classification.category);
|
|
1155
|
+
return dedupeTagNames([classification.category, ...extraTags, audit.handledTag]);
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
// src/adapters/ctx-ports.ts
|
|
1159
|
+
function asRawTicket(value) {
|
|
1160
|
+
return value ?? {};
|
|
1161
|
+
}
|
|
1162
|
+
function createGorgiasConversationPort(api) {
|
|
1163
|
+
return {
|
|
1164
|
+
async listPending(source, limit) {
|
|
1165
|
+
const tickets = await api.integrations.run("gorgias", "fetchTicketsFromView", {
|
|
1166
|
+
viewId: source.viewOrTag,
|
|
1167
|
+
limit
|
|
1168
|
+
});
|
|
1169
|
+
return tickets.map((t) => ({ id: String(t.id), channel: "gorgias" }));
|
|
1170
|
+
},
|
|
1171
|
+
async read(ref) {
|
|
1172
|
+
const result = await api.integrations.run("gorgias", "getTicketWithContext", {
|
|
1173
|
+
ticketId: ref.id
|
|
1174
|
+
});
|
|
1175
|
+
return toConversation(ref, asRawTicket(result?.ticket), result?.context ?? { messages: [], customerContext: null });
|
|
1176
|
+
}
|
|
1177
|
+
};
|
|
1178
|
+
}
|
|
1179
|
+
function createGorgiasReplyPort(api) {
|
|
1180
|
+
return {
|
|
1181
|
+
async post(ref, reply) {
|
|
1182
|
+
if (reply.mode === "email") {
|
|
1183
|
+
const result2 = await api.integrations.run("gorgias", "replyEmail", {
|
|
1184
|
+
ticketId: ref.id,
|
|
1185
|
+
bodyHtml: reply.bodyHtml,
|
|
1186
|
+
bodyText: reply.bodyText,
|
|
1187
|
+
senderEmail: reply.fromAddress,
|
|
1188
|
+
toAddress: reply.receiverEmail,
|
|
1189
|
+
...reply.subject !== null ? { subject: reply.subject } : {},
|
|
1190
|
+
...reply.receiverName !== null ? { receiverName: reply.receiverName } : {}
|
|
1191
|
+
});
|
|
1192
|
+
return { messageId: result2.messageId };
|
|
1193
|
+
}
|
|
1194
|
+
const result = await api.integrations.run("gorgias", "postWhatsappNote", {
|
|
1195
|
+
ticketId: ref.id,
|
|
1196
|
+
text: reply.bodyText
|
|
1197
|
+
});
|
|
1198
|
+
return { messageId: result.messageId };
|
|
1199
|
+
}
|
|
1200
|
+
};
|
|
1201
|
+
}
|
|
1202
|
+
function createGorgiasStatePort(api) {
|
|
1203
|
+
return {
|
|
1204
|
+
async record(ref, classification, audit) {
|
|
1205
|
+
const names = await resolveHandledTags(api, classification, audit);
|
|
1206
|
+
if (names.length === 0) return;
|
|
1207
|
+
await api.integrations.run("gorgias", "applyTags", { ticketId: ref.id, names });
|
|
1208
|
+
},
|
|
1209
|
+
async rename(ref, subject) {
|
|
1210
|
+
await api.integrations.run("gorgias", "renameTicket", { ticketId: ref.id, subject });
|
|
1211
|
+
},
|
|
1212
|
+
async flag(ref, tag) {
|
|
1213
|
+
const trimmed = tag.trim();
|
|
1214
|
+
if (!trimmed) return;
|
|
1215
|
+
await api.integrations.run("gorgias", "applyTags", { ticketId: ref.id, names: [trimmed] });
|
|
1216
|
+
}
|
|
1217
|
+
};
|
|
1218
|
+
}
|
|
1219
|
+
function toPlatformMessage(msg) {
|
|
1220
|
+
if (msg.role === "tool") return { role: "user", content: msg.content };
|
|
1221
|
+
if (msg.role === "assistant") return { role: "assistant", content: msg.content ?? "" };
|
|
1222
|
+
return { role: msg.role, content: msg.content };
|
|
1223
|
+
}
|
|
1224
|
+
function createPlatformLlmPort(api, trace) {
|
|
1225
|
+
return {
|
|
1226
|
+
async complete(req) {
|
|
1227
|
+
if (req.signal?.aborted) {
|
|
1228
|
+
throw Object.assign(new Error("Request was aborted."), { name: "AbortError" });
|
|
1229
|
+
}
|
|
1230
|
+
if (req.tools?.length) {
|
|
1231
|
+
throw new Error(
|
|
1232
|
+
"createPlatformLlmPort: ctx.api.llm.complete v2 has no tool-calling surface (no `tools` parameter, no `role: 'tool'` message) \u2014 cannot honour CompletionRequest.tools."
|
|
1233
|
+
);
|
|
1234
|
+
}
|
|
1235
|
+
const runTrace = req.trace ?? trace;
|
|
1236
|
+
const result = await api.llm.complete({
|
|
1237
|
+
messages: req.messages.map(toPlatformMessage),
|
|
1238
|
+
options: {
|
|
1239
|
+
model: req.model,
|
|
1240
|
+
reasoningEffort: req.reasoning,
|
|
1241
|
+
...req.responseSchema !== void 0 ? { responseSchema: { name: req.label, schema: req.responseSchema } } : {}
|
|
1242
|
+
},
|
|
1243
|
+
// `req.promptRef` (including `resolve`, see `CompletionRequest.promptRef`'s
|
|
1244
|
+
// own doc) is forwarded WHOLESALE — every caller in this package now
|
|
1245
|
+
// sets `resolve: false`, so this pass-through needs no code change of
|
|
1246
|
+
// its own to carry the new field; it already carries whatever shape
|
|
1247
|
+
// `CompletionRequest.promptRef` has.
|
|
1248
|
+
...req.promptRef ? { promptRef: req.promptRef } : {},
|
|
1249
|
+
...runTrace ? { trace: runTrace } : {}
|
|
1250
|
+
});
|
|
1251
|
+
return {
|
|
1252
|
+
text: result.text ?? null,
|
|
1253
|
+
// No tool-calling support on this surface today — see the module
|
|
1254
|
+
// doc above.
|
|
1255
|
+
toolCalls: [],
|
|
1256
|
+
usage: { input: result.usage.inputTokens, output: result.usage.outputTokens, reasoning: 0 },
|
|
1257
|
+
...result.traceId ? { traceId: result.traceId } : {},
|
|
1258
|
+
...result.observationId ? { observationId: result.observationId } : {}
|
|
1259
|
+
};
|
|
1260
|
+
}
|
|
1261
|
+
};
|
|
1262
|
+
}
|
|
1263
|
+
function createPlatformPromptReader(api) {
|
|
1264
|
+
return {
|
|
1265
|
+
async get(name, ref) {
|
|
1266
|
+
const detail = await api.prompts.get(name, { ...ref, resolve: false });
|
|
1267
|
+
return { version: detail.version, content: detail.content, config: detail.config ?? null };
|
|
1268
|
+
}
|
|
1269
|
+
};
|
|
1270
|
+
}
|
|
1271
|
+
function createRecordPromptCachePort(api) {
|
|
1272
|
+
return {
|
|
1273
|
+
async read(key) {
|
|
1274
|
+
const page = await api.list("prompt-cache", { filter: { promptKey: key }, limit: 1 });
|
|
1275
|
+
const data = page.items[0]?.data;
|
|
1276
|
+
return data ? { content: data.content, version: data.version } : null;
|
|
1277
|
+
},
|
|
1278
|
+
async write(key, entry) {
|
|
1279
|
+
await api.upsert(
|
|
1280
|
+
"prompt-cache",
|
|
1281
|
+
[{ data: { promptKey: key, content: entry.content, version: entry.version } }],
|
|
1282
|
+
{ uniqueBy: ["promptKey"] }
|
|
1283
|
+
);
|
|
1284
|
+
}
|
|
1285
|
+
};
|
|
1286
|
+
}
|
|
1287
|
+
function createPlatformPromptPort(api, log) {
|
|
1288
|
+
return createPromptResolver({
|
|
1289
|
+
platform: createPlatformPromptReader(api),
|
|
1290
|
+
cache: createRecordPromptCachePort(api),
|
|
1291
|
+
onDegraded: (event) => log(`prompt resolution degraded [${event.stage}] ${event.name}: ${event.reason}`)
|
|
1292
|
+
});
|
|
1293
|
+
}
|
|
1294
|
+
function createRealClock() {
|
|
1295
|
+
return { now: () => /* @__PURE__ */ new Date() };
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
// src/adapters/recording-ports.ts
|
|
1299
|
+
function createRecordingReplyPort() {
|
|
1300
|
+
let wouldHaveReplied = null;
|
|
1301
|
+
return {
|
|
1302
|
+
port: {
|
|
1303
|
+
async post(_ref, reply) {
|
|
1304
|
+
wouldHaveReplied = { subject: reply.mode === "email" ? reply.subject : null, body: reply.bodyText };
|
|
1305
|
+
return { messageId: "dry-run" };
|
|
1306
|
+
}
|
|
1307
|
+
},
|
|
1308
|
+
wouldHaveReplied: () => wouldHaveReplied
|
|
1309
|
+
};
|
|
1310
|
+
}
|
|
1311
|
+
function createRecordingStatePort(api) {
|
|
1312
|
+
const tagged = [];
|
|
1313
|
+
const push = (tag) => {
|
|
1314
|
+
const trimmed = tag.trim();
|
|
1315
|
+
if (trimmed && !tagged.includes(trimmed)) tagged.push(trimmed);
|
|
1316
|
+
};
|
|
1317
|
+
return {
|
|
1318
|
+
port: {
|
|
1319
|
+
async record(_ref, classification, audit) {
|
|
1320
|
+
const names = await resolveHandledTags(api, classification, audit);
|
|
1321
|
+
names.forEach(push);
|
|
1322
|
+
},
|
|
1323
|
+
async rename() {
|
|
1324
|
+
},
|
|
1325
|
+
async flag(_ref, tag) {
|
|
1326
|
+
push(tag);
|
|
1327
|
+
}
|
|
1328
|
+
},
|
|
1329
|
+
wouldHaveTagged: () => [...tagged]
|
|
1330
|
+
};
|
|
1331
|
+
}
|
|
1332
|
+
function createRecordingSendPort() {
|
|
1333
|
+
const calls = [];
|
|
1334
|
+
return {
|
|
1335
|
+
calls,
|
|
1336
|
+
send: {
|
|
1337
|
+
mode: "claimed",
|
|
1338
|
+
async claim(run) {
|
|
1339
|
+
calls.push({ surface: "send.claim", args: [run] });
|
|
1340
|
+
return true;
|
|
1341
|
+
},
|
|
1342
|
+
async commit(messageId) {
|
|
1343
|
+
calls.push({ surface: "send.commit", args: [messageId] });
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
};
|
|
1347
|
+
}
|
|
1348
|
+
function withRecordingWritePorts(ports, api) {
|
|
1349
|
+
return { ...ports, reply: createRecordingReplyPort().port, state: createRecordingStatePort(api).port };
|
|
1350
|
+
}
|
|
1351
|
+
function toRecordedToolCalls(calls) {
|
|
1352
|
+
return calls.map((c) => ({ name: c.name, arguments: c.arguments }));
|
|
1353
|
+
}
|
|
1354
|
+
function createRecordingLlmPort(llm) {
|
|
1355
|
+
const completions = [];
|
|
1356
|
+
return {
|
|
1357
|
+
completions,
|
|
1358
|
+
port: {
|
|
1359
|
+
async complete(req) {
|
|
1360
|
+
const startedAt = Date.now();
|
|
1361
|
+
const entry = {
|
|
1362
|
+
label: req.label,
|
|
1363
|
+
model: req.model,
|
|
1364
|
+
reasoning: req.reasoning,
|
|
1365
|
+
messages: req.messages,
|
|
1366
|
+
toolsOffered: (req.tools ?? []).map((t) => t.name),
|
|
1367
|
+
text: null,
|
|
1368
|
+
toolCalls: [],
|
|
1369
|
+
usage: { input: 0, output: 0, reasoning: 0 },
|
|
1370
|
+
traceId: null,
|
|
1371
|
+
durationMs: 0
|
|
1372
|
+
};
|
|
1373
|
+
completions.push(entry);
|
|
1374
|
+
try {
|
|
1375
|
+
const result = await llm.complete(req);
|
|
1376
|
+
entry.text = result.text;
|
|
1377
|
+
entry.toolCalls = toRecordedToolCalls(result.toolCalls);
|
|
1378
|
+
entry.usage = result.usage;
|
|
1379
|
+
entry.traceId = result.traceId ?? null;
|
|
1380
|
+
return result;
|
|
1381
|
+
} catch (err) {
|
|
1382
|
+
entry.error = err instanceof Error ? err.message : String(err);
|
|
1383
|
+
throw err;
|
|
1384
|
+
} finally {
|
|
1385
|
+
entry.durationMs = Date.now() - startedAt;
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
};
|
|
1390
|
+
}
|
|
1391
|
+
var DEFAULT_MAX_TOOL_CALLS = 5;
|
|
1392
|
+
async function getOptional(ctx, objectKey, id) {
|
|
1393
|
+
if (!id) return null;
|
|
1394
|
+
try {
|
|
1395
|
+
return await ctx.api.get(objectKey, id);
|
|
1396
|
+
} catch (err) {
|
|
1397
|
+
if (err instanceof AppApiError && err.status === 404) return null;
|
|
1398
|
+
throw err;
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
function buildTicketPorts(ctx, trace) {
|
|
1402
|
+
return {
|
|
1403
|
+
conversation: createGorgiasConversationPort(ctx.api),
|
|
1404
|
+
reply: createGorgiasReplyPort(ctx.api),
|
|
1405
|
+
llm: createPlatformLlmPort(ctx.api, trace),
|
|
1406
|
+
prompt: createPlatformPromptPort(ctx.api, (message) => ctx.logger.warn(message)),
|
|
1407
|
+
state: createGorgiasStatePort(ctx.api),
|
|
1408
|
+
clock: createRealClock()
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
// src/functions/eligibility.ts
|
|
1413
|
+
function isEligibleForGeneratedResponse(profile, classification, escalated, category) {
|
|
1414
|
+
if (!category || !category.fastResponseEnabled || !category.agentId) return false;
|
|
1415
|
+
if (escalated) return false;
|
|
1416
|
+
if (isConversationOver(classification)) return false;
|
|
1417
|
+
if (isFallbackClassification(classification)) return false;
|
|
1418
|
+
if (hasNoDraftNode(profile)) return false;
|
|
1419
|
+
return true;
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
// src/functions/no-tool-context.ts
|
|
1423
|
+
function refuse(name) {
|
|
1424
|
+
throw new Error(`no-tool-context: "${name}" called, but this pipeline configures no tools (profile.tools is always []).`);
|
|
1425
|
+
}
|
|
1426
|
+
function createNoToolContext() {
|
|
1427
|
+
return {
|
|
1428
|
+
getOrder: () => refuse("getOrder"),
|
|
1429
|
+
getTracking: () => refuse("getTracking"),
|
|
1430
|
+
searchKnowledge: () => refuse("searchKnowledge"),
|
|
1431
|
+
findSimilarTickets: () => refuse("findSimilarTickets")
|
|
1432
|
+
};
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
// src/functions/pipeline-state.ts
|
|
1436
|
+
var PIPELINE_STATE_SINGLETON_KEY = "default";
|
|
1437
|
+
function toDate(value) {
|
|
1438
|
+
if (!value) return null;
|
|
1439
|
+
const date = value instanceof Date ? value : new Date(value);
|
|
1440
|
+
return Number.isNaN(date.getTime()) ? null : date;
|
|
1441
|
+
}
|
|
1442
|
+
async function readPipelineState(api) {
|
|
1443
|
+
const page = await api.list("pipeline-state", { filter: { singletonKey: PIPELINE_STATE_SINGLETON_KEY }, limit: 1 });
|
|
1444
|
+
return page.items[0] ?? null;
|
|
1445
|
+
}
|
|
1446
|
+
async function upsertPipelineState(api, patch) {
|
|
1447
|
+
await api.upsert("pipeline-state", [{ data: { singletonKey: PIPELINE_STATE_SINGLETON_KEY, ...patch } }], {
|
|
1448
|
+
uniqueBy: ["singletonKey"]
|
|
1449
|
+
});
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
// src/functions/triage-tick.ts
|
|
1453
|
+
function buildTriageTickFunctionDef(config) {
|
|
1454
|
+
return {
|
|
1455
|
+
universalIdentifier: identifierFor(config, "triage-tick"),
|
|
1456
|
+
name: "triage-tick",
|
|
1457
|
+
trigger: { type: "cron", pattern: "*/5 * * * *" },
|
|
1458
|
+
retries: 0,
|
|
1459
|
+
concurrency: 1,
|
|
1460
|
+
notify: { onFailure: true, severity: "warning" }
|
|
1461
|
+
};
|
|
1462
|
+
}
|
|
1463
|
+
function createTriageTickHandler(config) {
|
|
1464
|
+
return (ctx) => triageTickHandler(ctx, config);
|
|
1465
|
+
}
|
|
1466
|
+
async function triageTickHandler(ctx, config) {
|
|
1467
|
+
const settings = await ctx.api.settings.get();
|
|
1468
|
+
const issues = validateSettings(settings);
|
|
1469
|
+
if (issues.length > 0) {
|
|
1470
|
+
ctx.logger.info("triage-tick: settings invalid, skipping", { issues });
|
|
1471
|
+
return;
|
|
1472
|
+
}
|
|
1473
|
+
if (!settings.triageEnabled) {
|
|
1474
|
+
ctx.logger.info("triage-tick: triageEnabled is off, skipping");
|
|
1475
|
+
return;
|
|
1476
|
+
}
|
|
1477
|
+
if (!settings.sourceViewId) {
|
|
1478
|
+
ctx.logger.info("triage-tick: no sourceViewId configured, skipping");
|
|
1479
|
+
return;
|
|
1480
|
+
}
|
|
1481
|
+
const clock = createRealClock();
|
|
1482
|
+
const now = clock.now();
|
|
1483
|
+
const pipelineState = await readPipelineState(ctx.api);
|
|
1484
|
+
const lastTriageAt = toDate(pipelineState?.data.lastTriageAt);
|
|
1485
|
+
if (lastTriageAt) {
|
|
1486
|
+
const dueAt = lastTriageAt.getTime() + settings.triageIntervalMinutes * 6e4;
|
|
1487
|
+
if (now.getTime() < dueAt) {
|
|
1488
|
+
ctx.logger.info("triage-tick: not due yet, skipping");
|
|
1489
|
+
return;
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
await runTriageBatch(ctx, config, settings);
|
|
1493
|
+
}
|
|
1494
|
+
async function runTriageBatch(ctx, config, settings) {
|
|
1495
|
+
const dryRun = settings.dryRun === true;
|
|
1496
|
+
const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx), ctx.api) : buildTicketPorts(ctx);
|
|
1497
|
+
const categories = await listCategories(ctx.api);
|
|
1498
|
+
const batchDefaultAgent = await resolveDraftAgent(ctx.api, null);
|
|
1499
|
+
const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(batchDefaultAgent, config)));
|
|
1500
|
+
const refs = await ports.conversation.listPending({ viewOrTag: settings.sourceViewId }, settings.batchLimit);
|
|
1501
|
+
const run = await ctx.api.runs.start({
|
|
1502
|
+
kind: "triage-tick",
|
|
1503
|
+
message: `${dryRun ? "Dry-run triage tick" : "Triage tick"} over ${refs.length} ticket(s)`,
|
|
1504
|
+
metadata: { sourceViewId: settings.sourceViewId, ticketCount: refs.length, dryRun }
|
|
1505
|
+
});
|
|
1506
|
+
let failureCount = 0;
|
|
1507
|
+
try {
|
|
1508
|
+
for (const ref of refs) {
|
|
1509
|
+
try {
|
|
1510
|
+
await processOneTicket(ctx, ref, {
|
|
1511
|
+
profile,
|
|
1512
|
+
categories,
|
|
1513
|
+
ports,
|
|
1514
|
+
runId: run.id
|
|
1515
|
+
});
|
|
1516
|
+
} catch (err) {
|
|
1517
|
+
failureCount += 1;
|
|
1518
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1519
|
+
ctx.logger.error(`triage-tick: ticket ${ref.id} failed, continuing with the rest of the batch`, { error: message });
|
|
1520
|
+
try {
|
|
1521
|
+
await ctx.api.create("triage-decision", {
|
|
1522
|
+
ticketId: ref.id,
|
|
1523
|
+
decidedAt: ports.clock.now(),
|
|
1524
|
+
status: "error",
|
|
1525
|
+
error: message,
|
|
1526
|
+
confidence: "low",
|
|
1527
|
+
runId: run.id,
|
|
1528
|
+
subjectRenamed: false
|
|
1529
|
+
});
|
|
1530
|
+
} catch (writeErr) {
|
|
1531
|
+
ctx.logger.error(`triage-tick: failed to record the error decision for ticket ${ref.id}`, {
|
|
1532
|
+
error: writeErr instanceof Error ? writeErr.message : String(writeErr)
|
|
1533
|
+
});
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
await ctx.api.runs.succeed(run.id, { ticketCount: refs.length, failureCount });
|
|
1538
|
+
} catch (err) {
|
|
1539
|
+
await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });
|
|
1540
|
+
throw err;
|
|
1541
|
+
} finally {
|
|
1542
|
+
await upsertPipelineState(ctx.api, { sourceViewId: settings.sourceViewId, lastTriageAt: ports.clock.now() });
|
|
1543
|
+
}
|
|
1544
|
+
return { ticketCount: refs.length, failureCount };
|
|
1545
|
+
}
|
|
1546
|
+
async function processOneTicket(ctx, ref, deps) {
|
|
1547
|
+
const { profile, categories, ports, runId } = deps;
|
|
1548
|
+
let subjectRenamed = false;
|
|
1549
|
+
if (profile.rename) {
|
|
1550
|
+
const conversation2 = await ports.conversation.read(ref);
|
|
1551
|
+
const subject = conversation2.subject ?? "";
|
|
1552
|
+
if (subject.includes(profile.rename.from)) {
|
|
1553
|
+
await ports.state.rename(ref, subject.replace(profile.rename.from, profile.rename.to));
|
|
1554
|
+
subjectRenamed = true;
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });
|
|
1558
|
+
const state = await runTicket(
|
|
1559
|
+
{
|
|
1560
|
+
ref,
|
|
1561
|
+
profile,
|
|
1562
|
+
ports: { ...ports },
|
|
1563
|
+
toolContext: createNoToolContext(),
|
|
1564
|
+
budget,
|
|
1565
|
+
// Unknown until triage runs — no node reached in the `until:'triage'`
|
|
1566
|
+
// phase reads `deps.category` (`run-ticket.ts`'s early return happens
|
|
1567
|
+
// before any node touches it).
|
|
1568
|
+
category: { autoReplyEnabled: true, minConfidence: null },
|
|
1569
|
+
categories: toCategoryReferential(categories),
|
|
1570
|
+
log: (msg) => ctx.logger.debug(msg),
|
|
1571
|
+
send: { mode: "none" }
|
|
1572
|
+
},
|
|
1573
|
+
{ until: "triage" }
|
|
1574
|
+
);
|
|
1575
|
+
if (!state.classification) {
|
|
1576
|
+
await ctx.api.create("triage-decision", {
|
|
1577
|
+
ticketId: ref.id,
|
|
1578
|
+
decidedAt: ports.clock.now(),
|
|
1579
|
+
status: "error",
|
|
1580
|
+
error: "triage produced no classification",
|
|
1581
|
+
confidence: "low",
|
|
1582
|
+
runId,
|
|
1583
|
+
subjectRenamed
|
|
1584
|
+
});
|
|
1585
|
+
return;
|
|
1586
|
+
}
|
|
1587
|
+
const { classification } = state;
|
|
1588
|
+
const category = findCategoryByTag(categories, classification.category);
|
|
1589
|
+
const decision = await ctx.api.create("triage-decision", {
|
|
1590
|
+
ticketId: ref.id,
|
|
1591
|
+
decidedAt: ports.clock.now(),
|
|
1592
|
+
categoryId: category?.id ?? null,
|
|
1593
|
+
tag: classification.category,
|
|
1594
|
+
confidence: classification.confidence,
|
|
1595
|
+
reasoning: classification.reasoning,
|
|
1596
|
+
conversationOver: classification.conversationOver ?? false,
|
|
1597
|
+
escalated: state.escalated,
|
|
1598
|
+
status: "ok",
|
|
1599
|
+
runId,
|
|
1600
|
+
subjectRenamed
|
|
1601
|
+
});
|
|
1602
|
+
await ports.state.record(ref, classification, profile.audit);
|
|
1603
|
+
if (!isEligibleForGeneratedResponse(profile, classification, state.escalated, category)) return;
|
|
1604
|
+
const draftAgent = await resolveDraftAgent(ctx.api, category?.agentId ?? null);
|
|
1605
|
+
const conversation = state.conversation;
|
|
1606
|
+
const channel = conversation?.sourceChannel === "whatsapp" ? "whatsapp" : "email";
|
|
1607
|
+
const generatedAt = ports.clock.now();
|
|
1608
|
+
const expiresAt = new Date(generatedAt.getTime() + profile.schedule.fastResponseTtlMinutes * 6e4);
|
|
1609
|
+
try {
|
|
1610
|
+
await ctx.api.create("generated-response", {
|
|
1611
|
+
ticketId: ref.id,
|
|
1612
|
+
openTicketKey: openTicketKeyFor("pending", ref.id),
|
|
1613
|
+
status: "pending",
|
|
1614
|
+
triageDecisionId: decision.id,
|
|
1615
|
+
categoryId: category?.id ?? null,
|
|
1616
|
+
agentId: draftAgent?.id ?? null,
|
|
1617
|
+
channel,
|
|
1618
|
+
generatedAt,
|
|
1619
|
+
expiresAt,
|
|
1620
|
+
sources: [],
|
|
1621
|
+
tracedInput: [],
|
|
1622
|
+
guardrailHits: [],
|
|
1623
|
+
servedTo: [],
|
|
1624
|
+
servedCount: 0,
|
|
1625
|
+
followupRequired: false
|
|
1626
|
+
});
|
|
1627
|
+
} catch (err) {
|
|
1628
|
+
if (err instanceof AppApiError && err.status === 409) {
|
|
1629
|
+
ctx.logger.debug(`triage-tick: generated-response already pending for ticket ${ref.id}, skipping`);
|
|
1630
|
+
return;
|
|
1631
|
+
}
|
|
1632
|
+
throw err;
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
function buildSendSeam(params) {
|
|
1636
|
+
const { api, clock, id, ticketId, fromStatus, extraClaimData } = params;
|
|
1637
|
+
return {
|
|
1638
|
+
async claim(run) {
|
|
1639
|
+
assertTransition(fromStatus, "sending");
|
|
1640
|
+
try {
|
|
1641
|
+
await api.update(
|
|
1642
|
+
"generated-response",
|
|
1643
|
+
id,
|
|
1644
|
+
{
|
|
1645
|
+
status: "sending",
|
|
1646
|
+
sendingAt: clock.now(),
|
|
1647
|
+
openTicketKey: openTicketKeyFor("sending", ticketId),
|
|
1648
|
+
...extraClaimData ? extraClaimData(run) : {}
|
|
1649
|
+
},
|
|
1650
|
+
{ ifMatch: { status: fromStatus } }
|
|
1651
|
+
);
|
|
1652
|
+
return true;
|
|
1653
|
+
} catch (err) {
|
|
1654
|
+
if (err instanceof AppApiError && err.status === 409) return false;
|
|
1655
|
+
throw err;
|
|
1656
|
+
}
|
|
1657
|
+
},
|
|
1658
|
+
async commit(messageId) {
|
|
1659
|
+
assertTransition("sending", "sent");
|
|
1660
|
+
await api.update(
|
|
1661
|
+
"generated-response",
|
|
1662
|
+
id,
|
|
1663
|
+
{
|
|
1664
|
+
status: "sent",
|
|
1665
|
+
sentAt: clock.now(),
|
|
1666
|
+
sentMessageId: messageId,
|
|
1667
|
+
openTicketKey: openTicketKeyFor("sent", ticketId)
|
|
1668
|
+
},
|
|
1669
|
+
{ ifMatch: { status: "sending" } }
|
|
1670
|
+
);
|
|
1671
|
+
}
|
|
1672
|
+
};
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1675
|
+
// src/functions/approval-key.ts
|
|
1676
|
+
var PREFIX = "generated-response:";
|
|
1677
|
+
function buildApprovalKey(generatedResponseId) {
|
|
1678
|
+
return `${PREFIX}${generatedResponseId}`;
|
|
1679
|
+
}
|
|
1680
|
+
function parseApprovalKey(key) {
|
|
1681
|
+
if (!key.startsWith(PREFIX)) return null;
|
|
1682
|
+
const id = key.slice(PREFIX.length);
|
|
1683
|
+
return id.length > 0 ? id : null;
|
|
1684
|
+
}
|
|
1685
|
+
function buildInboxKey(generatedResponseId, suffix) {
|
|
1686
|
+
return suffix ? `${PREFIX}${generatedResponseId}:${suffix}` : `${PREFIX}${generatedResponseId}`;
|
|
1687
|
+
}
|
|
1688
|
+
|
|
1689
|
+
// src/functions/process-response.ts
|
|
1690
|
+
function classificationFromDecision(decision) {
|
|
1691
|
+
const data = decision.data;
|
|
1692
|
+
return {
|
|
1693
|
+
category: data.tag ?? "",
|
|
1694
|
+
confidence: data.confidence ?? "low",
|
|
1695
|
+
reasoning: data.reasoning ?? "",
|
|
1696
|
+
isFallback: false,
|
|
1697
|
+
conversationOver: data.conversationOver ?? false
|
|
1698
|
+
};
|
|
1699
|
+
}
|
|
1700
|
+
function attributionFields(attribution) {
|
|
1701
|
+
return {
|
|
1702
|
+
langfuseTraceId: attribution?.traceId ?? null,
|
|
1703
|
+
langfuseObservationId: attribution?.observationId ?? null,
|
|
1704
|
+
promptName: attribution?.promptName ?? null,
|
|
1705
|
+
promptVersion: attribution?.promptVersion ?? null
|
|
1706
|
+
};
|
|
1707
|
+
}
|
|
1708
|
+
async function finalizeNonSent(ctx, id, ticketId, toStatus, extra) {
|
|
1709
|
+
assertTransition("pending", toStatus);
|
|
1710
|
+
try {
|
|
1711
|
+
await ctx.api.update(
|
|
1712
|
+
"generated-response",
|
|
1713
|
+
id,
|
|
1714
|
+
{ status: toStatus, openTicketKey: openTicketKeyFor(toStatus, ticketId), ...extra },
|
|
1715
|
+
{ ifMatch: { status: "pending" } }
|
|
1716
|
+
);
|
|
1717
|
+
return true;
|
|
1718
|
+
} catch (err) {
|
|
1719
|
+
if (err instanceof AppApiError && err.status === 409) {
|
|
1720
|
+
ctx.logger.info(`process-response: generated-response ${id} was already moved off "pending" by another worker, abandoning`);
|
|
1721
|
+
return false;
|
|
1722
|
+
}
|
|
1723
|
+
throw err;
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
function buildProcessResponseFunctionDef(config) {
|
|
1727
|
+
return {
|
|
1728
|
+
universalIdentifier: identifierFor(config, "process-response"),
|
|
1729
|
+
name: "process-response",
|
|
1730
|
+
trigger: { type: "dbEvent", objectRef: `app:${config.slug}/generated-response`, operation: "created" },
|
|
1731
|
+
retries: 3,
|
|
1732
|
+
concurrency: 3,
|
|
1733
|
+
notify: { onFailure: true, severity: "warning" }
|
|
1734
|
+
};
|
|
1735
|
+
}
|
|
1736
|
+
function createProcessResponseHandler(config) {
|
|
1737
|
+
return (ctx) => processResponseHandler(ctx, config);
|
|
1738
|
+
}
|
|
1739
|
+
async function processResponseHandler(ctx, config) {
|
|
1740
|
+
const recordId = ctx.event.recordId;
|
|
1741
|
+
if (!recordId) {
|
|
1742
|
+
ctx.logger.warn("process-response: event carried no recordId, skipping");
|
|
1743
|
+
return;
|
|
1744
|
+
}
|
|
1745
|
+
const record = await getOptional(ctx, "generated-response", recordId);
|
|
1746
|
+
if (!record) {
|
|
1747
|
+
ctx.logger.info(`process-response: generated-response ${recordId} no longer exists, skipping`);
|
|
1748
|
+
return;
|
|
1749
|
+
}
|
|
1750
|
+
const data = record.data;
|
|
1751
|
+
if (data.status !== "pending") {
|
|
1752
|
+
ctx.logger.info(`process-response: generated-response ${recordId} is not pending (status="${String(data.status)}"), skipping \u2014 already handled or a dbEvent redelivery`);
|
|
1753
|
+
return;
|
|
1754
|
+
}
|
|
1755
|
+
const settings = await ctx.api.settings.get();
|
|
1756
|
+
if (validateSettings(settings).length > 0) {
|
|
1757
|
+
ctx.logger.info("process-response: settings invalid, skipping");
|
|
1758
|
+
return;
|
|
1759
|
+
}
|
|
1760
|
+
const ticketId = data.ticketId;
|
|
1761
|
+
const ref = { id: ticketId, channel: "gorgias" };
|
|
1762
|
+
const decision = await getOptional(ctx, "triage-decision", data.triageDecisionId ?? null);
|
|
1763
|
+
if (!decision) {
|
|
1764
|
+
ctx.logger.error(`process-response: generated-response ${recordId} has no resolvable triage-decision, marking failed`);
|
|
1765
|
+
await finalizeNonSent(ctx, recordId, ticketId, "failed", { error: "triage-decision not found" });
|
|
1766
|
+
return;
|
|
1767
|
+
}
|
|
1768
|
+
const classification = classificationFromDecision(decision);
|
|
1769
|
+
const escalated = decision.data.escalated === true;
|
|
1770
|
+
const categoryRecord = await getOptional(ctx, "category", data.categoryId ?? null);
|
|
1771
|
+
const category = categoryRecord ? toCategory(categoryRecord) : null;
|
|
1772
|
+
const agentRecord2 = data.agentId ? await getOptional(ctx, "agent", data.agentId) : null;
|
|
1773
|
+
const agent = agentRecord2 ? toAgent(agentRecord2) : await resolveDraftAgent(ctx.api, null);
|
|
1774
|
+
const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config)));
|
|
1775
|
+
const dryRun = settings.dryRun === true;
|
|
1776
|
+
const trace = { sessionId: ticketId, tags: [`app:${config.slug}`] };
|
|
1777
|
+
const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx, trace), ctx.api) : buildTicketPorts(ctx, trace);
|
|
1778
|
+
const { clock } = ports;
|
|
1779
|
+
const conversationSnapshot = await ports.conversation.read(ref);
|
|
1780
|
+
const generatedAt = data.generatedAt instanceof Date ? data.generatedAt : new Date(data.generatedAt);
|
|
1781
|
+
const seam = buildSendSeam({
|
|
1782
|
+
api: ctx.api,
|
|
1783
|
+
clock,
|
|
1784
|
+
id: recordId,
|
|
1785
|
+
ticketId,
|
|
1786
|
+
fromStatus: "pending",
|
|
1787
|
+
extraClaimData: (run) => ({
|
|
1788
|
+
responseText: run.draft.text,
|
|
1789
|
+
sources: run.draft.sources,
|
|
1790
|
+
verdict: run.verdict,
|
|
1791
|
+
generatedMessageCount: conversationSnapshot.messageCount,
|
|
1792
|
+
generatedLastMessageAt: conversationSnapshot.lastMessageAt,
|
|
1793
|
+
...attributionFields(run.draft.attribution)
|
|
1794
|
+
})
|
|
1795
|
+
});
|
|
1796
|
+
const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });
|
|
1797
|
+
const result = await runTicket(
|
|
1798
|
+
{
|
|
1799
|
+
ref,
|
|
1800
|
+
profile,
|
|
1801
|
+
ports,
|
|
1802
|
+
toolContext: createNoToolContext(),
|
|
1803
|
+
budget,
|
|
1804
|
+
category: { autoReplyEnabled: category?.autoReplyEnabled ?? false, minConfidence: null },
|
|
1805
|
+
categories: [],
|
|
1806
|
+
log: (msg) => ctx.logger.debug(msg),
|
|
1807
|
+
send: dryRun ? { mode: "none" } : { mode: "claimed", claim: seam.claim, commit: seam.commit },
|
|
1808
|
+
queuedAt: generatedAt
|
|
1809
|
+
},
|
|
1810
|
+
{ resume: { classification, escalated } }
|
|
1811
|
+
);
|
|
1812
|
+
const draftExtra = {
|
|
1813
|
+
responseText: result.draft?.text ?? null,
|
|
1814
|
+
sources: result.draft?.sources ?? [],
|
|
1815
|
+
verdict: result.verdict ?? null,
|
|
1816
|
+
generatedMessageCount: conversationSnapshot.messageCount,
|
|
1817
|
+
generatedLastMessageAt: conversationSnapshot.lastMessageAt,
|
|
1818
|
+
...attributionFields(result.draft?.attribution)
|
|
1819
|
+
};
|
|
1820
|
+
switch (result.outcome) {
|
|
1821
|
+
case "sent":
|
|
1822
|
+
if (dryRun) {
|
|
1823
|
+
await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
|
|
1824
|
+
return;
|
|
1825
|
+
}
|
|
1826
|
+
return;
|
|
1827
|
+
case "ready":
|
|
1828
|
+
case "guardrail_hold":
|
|
1829
|
+
await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
|
|
1830
|
+
return;
|
|
1831
|
+
case "needs_human": {
|
|
1832
|
+
const persisted = await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
|
|
1833
|
+
if (persisted) {
|
|
1834
|
+
await ctx.api.inbox.raise({
|
|
1835
|
+
key: buildInboxKey(recordId),
|
|
1836
|
+
severity: "warning",
|
|
1837
|
+
title: `R\xE9ponse g\xE9n\xE9r\xE9e \xE0 revoir \u2014 ticket ${ticketId}`,
|
|
1838
|
+
entityRef: { appSlug: config.slug, objectKey: "generated-response", id: recordId }
|
|
1839
|
+
});
|
|
1840
|
+
}
|
|
1841
|
+
return;
|
|
1842
|
+
}
|
|
1843
|
+
case "awaiting_approval": {
|
|
1844
|
+
const persisted = await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
|
|
1845
|
+
if (persisted && !dryRun) {
|
|
1846
|
+
await ctx.api.approvals.request({
|
|
1847
|
+
key: buildApprovalKey(recordId),
|
|
1848
|
+
title: `Approuver l'envoi automatique \u2014 ticket ${ticketId}`,
|
|
1849
|
+
entityRef: { appSlug: config.slug, objectKey: "generated-response", id: recordId }
|
|
1850
|
+
});
|
|
1851
|
+
}
|
|
1852
|
+
return;
|
|
1853
|
+
}
|
|
1854
|
+
case "escalated":
|
|
1855
|
+
case "triaged_only":
|
|
1856
|
+
case "no_reply_needed":
|
|
1857
|
+
await finalizeNonSent(ctx, recordId, ticketId, "no_reply_needed", draftExtra);
|
|
1858
|
+
return;
|
|
1859
|
+
case "failed":
|
|
1860
|
+
await finalizeNonSent(ctx, recordId, ticketId, "failed", { ...draftExtra, error: "runTicket outcome: failed" });
|
|
1861
|
+
return;
|
|
1862
|
+
default:
|
|
1863
|
+
ctx.logger.error(`process-response: generated-response ${recordId} resumed run ended with no outcome`);
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
async function transitionGeneratedResponse(api, params) {
|
|
1867
|
+
const { id, ticketId, from, to, extra } = params;
|
|
1868
|
+
assertTransition(from, to);
|
|
1869
|
+
try {
|
|
1870
|
+
await api.update(
|
|
1871
|
+
"generated-response",
|
|
1872
|
+
id,
|
|
1873
|
+
{ status: to, openTicketKey: openTicketKeyFor(to, ticketId), ...extra ?? {} },
|
|
1874
|
+
{ ifMatch: { status: from } }
|
|
1875
|
+
);
|
|
1876
|
+
return true;
|
|
1877
|
+
} catch (err) {
|
|
1878
|
+
if (err instanceof AppApiError && err.status === 409) return false;
|
|
1879
|
+
throw err;
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
// src/functions/sweep.ts
|
|
1884
|
+
var STALE_SENDING_THRESHOLD_MS = 30 * 6e4;
|
|
1885
|
+
var SWEEP_PAGE_SIZE = 500;
|
|
1886
|
+
function buildSweepFunctionDef(config) {
|
|
1887
|
+
return {
|
|
1888
|
+
universalIdentifier: identifierFor(config, "sweep"),
|
|
1889
|
+
name: "sweep",
|
|
1890
|
+
trigger: { type: "cron", pattern: "*/5 * * * *" },
|
|
1891
|
+
retries: 0,
|
|
1892
|
+
concurrency: 1,
|
|
1893
|
+
notify: { onFailure: true, severity: "warning" }
|
|
1894
|
+
};
|
|
1895
|
+
}
|
|
1896
|
+
function createSweepHandler() {
|
|
1897
|
+
return (ctx) => sweepHandler(ctx);
|
|
1898
|
+
}
|
|
1899
|
+
async function sweepHandler(ctx) {
|
|
1900
|
+
const clock = createRealClock();
|
|
1901
|
+
const now = clock.now();
|
|
1902
|
+
const settings = await ctx.api.settings.get();
|
|
1903
|
+
const statePort = createGorgiasStatePort(ctx.api);
|
|
1904
|
+
const escalationTag = typeof settings?.escalationTag === "string" ? settings.escalationTag : "";
|
|
1905
|
+
if (!escalationTag) {
|
|
1906
|
+
ctx.logger.warn("sweep: escalationTag is not configured \u2014 a stalled-send reclaim will proceed without an escalation tag");
|
|
1907
|
+
}
|
|
1908
|
+
await sweepExpiredReady(ctx, now);
|
|
1909
|
+
await sweepStalledSending(ctx, now, escalationTag, statePort);
|
|
1910
|
+
await sweepStalledPending(ctx, now);
|
|
1911
|
+
await upsertPipelineState(ctx.api, { lastSweepAt: now });
|
|
1912
|
+
}
|
|
1913
|
+
async function sweepExpiredReady(ctx, now) {
|
|
1914
|
+
const page = await ctx.api.list("generated-response", { filter: { status: "ready" }, limit: SWEEP_PAGE_SIZE });
|
|
1915
|
+
for (const row of page.items) {
|
|
1916
|
+
const expiresAt = toDate(row.data.expiresAt);
|
|
1917
|
+
if (!expiresAt || expiresAt.getTime() > now.getTime()) continue;
|
|
1918
|
+
await transitionGeneratedResponse(ctx.api, { id: row.id, ticketId: row.data.ticketId, from: "ready", to: "expired" });
|
|
1919
|
+
}
|
|
1920
|
+
}
|
|
1921
|
+
async function sweepStalledSending(ctx, now, escalationTag, statePort) {
|
|
1922
|
+
const page = await ctx.api.list("generated-response", { filter: { status: "sending" }, limit: SWEEP_PAGE_SIZE });
|
|
1923
|
+
for (const row of page.items) {
|
|
1924
|
+
const sendingAt = toDate(row.data.sendingAt);
|
|
1925
|
+
if (!sendingAt || now.getTime() - sendingAt.getTime() < STALE_SENDING_THRESHOLD_MS) continue;
|
|
1926
|
+
assertTransition("sending", "ready");
|
|
1927
|
+
const ticketId = row.data.ticketId;
|
|
1928
|
+
let reclaimed;
|
|
1929
|
+
try {
|
|
1930
|
+
await ctx.api.update(
|
|
1931
|
+
"generated-response",
|
|
1932
|
+
row.id,
|
|
1933
|
+
{
|
|
1934
|
+
// Status AND the hold together, in the SAME write — see the
|
|
1935
|
+
// module doc and `reclaimStalledSend`'s own doc for why splitting
|
|
1936
|
+
// this into two writes (or dropping the hold) would re-open the
|
|
1937
|
+
// record as a sendable `ready` row.
|
|
1938
|
+
...reclaimStalledSend(),
|
|
1939
|
+
openTicketKey: openTicketKeyFor("ready", ticketId)
|
|
1940
|
+
},
|
|
1941
|
+
{ ifMatch: { status: "sending" } }
|
|
1942
|
+
);
|
|
1943
|
+
reclaimed = true;
|
|
1944
|
+
} catch (err) {
|
|
1945
|
+
if (err instanceof AppApiError && err.status === 409) {
|
|
1946
|
+
reclaimed = false;
|
|
1947
|
+
} else {
|
|
1948
|
+
throw err;
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
if (!reclaimed) continue;
|
|
1952
|
+
const ref = { id: ticketId, channel: "gorgias" };
|
|
1953
|
+
await statePort.flag(ref, escalationTag);
|
|
1954
|
+
await ctx.api.inbox.raise({
|
|
1955
|
+
key: buildInboxKey(row.id, "stalled-send"),
|
|
1956
|
+
severity: "warning",
|
|
1957
|
+
title: `Envoi bloqu\xE9 d\xE9tect\xE9 \u2014 ticket ${ticketId}`,
|
|
1958
|
+
body: 'La r\xE9ponse est rest\xE9e en statut "sending" plus de 30 minutes et a \xE9t\xE9 replac\xE9e en attente humaine.'
|
|
1959
|
+
});
|
|
1960
|
+
}
|
|
1961
|
+
}
|
|
1962
|
+
async function sweepStalledPending(ctx, now) {
|
|
1963
|
+
const page = await ctx.api.list("generated-response", { filter: { status: "pending" }, limit: SWEEP_PAGE_SIZE });
|
|
1964
|
+
for (const row of page.items) {
|
|
1965
|
+
const expiresAt = toDate(row.data.expiresAt);
|
|
1966
|
+
if (!expiresAt || expiresAt.getTime() > now.getTime()) continue;
|
|
1967
|
+
assertTransition("pending", "failed");
|
|
1968
|
+
try {
|
|
1969
|
+
await ctx.api.update(
|
|
1970
|
+
"generated-response",
|
|
1971
|
+
row.id,
|
|
1972
|
+
{ status: "failed", openTicketKey: openTicketKeyFor("failed", row.data.ticketId), error: "orphaned pending row past its TTL (sweep)" },
|
|
1973
|
+
{ ifMatch: { status: "pending" } }
|
|
1974
|
+
);
|
|
1975
|
+
} catch (err) {
|
|
1976
|
+
if (err instanceof AppApiError && err.status === 409) continue;
|
|
1977
|
+
throw err;
|
|
1978
|
+
}
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
function buildHandleApprovalFunctionDef(config) {
|
|
1982
|
+
return {
|
|
1983
|
+
universalIdentifier: identifierFor(config, "handle-approval"),
|
|
1984
|
+
name: "handle-approval",
|
|
1985
|
+
trigger: { type: "event", name: APPROVAL_DECIDED_EVENT },
|
|
1986
|
+
retries: 3
|
|
1987
|
+
// No `notify` — §3.5's table gives only the first three functions one.
|
|
1988
|
+
};
|
|
1989
|
+
}
|
|
1990
|
+
function createHandleApprovalHandler(config) {
|
|
1991
|
+
return (ctx) => handleApprovalHandler(ctx, config);
|
|
1992
|
+
}
|
|
1993
|
+
async function handleApprovalHandler(ctx, config) {
|
|
1994
|
+
const payload = ctx.event;
|
|
1995
|
+
const id = parseApprovalKey(payload.key);
|
|
1996
|
+
if (!id) {
|
|
1997
|
+
ctx.logger.debug(`handle-approval: key "${payload.key}" is not a generated-response approval, ignoring`);
|
|
1998
|
+
return;
|
|
1999
|
+
}
|
|
2000
|
+
const record = await getOptional(ctx, "generated-response", id);
|
|
2001
|
+
if (!record) {
|
|
2002
|
+
ctx.logger.info(`handle-approval: generated-response ${id} no longer exists, skipping`);
|
|
2003
|
+
return;
|
|
2004
|
+
}
|
|
2005
|
+
const data = record.data;
|
|
2006
|
+
if (data.status !== "ready") {
|
|
2007
|
+
ctx.logger.info(`handle-approval: generated-response ${id} is not ready (status="${String(data.status)}"), skipping \u2014 already handled or reclaimed`);
|
|
2008
|
+
return;
|
|
2009
|
+
}
|
|
2010
|
+
const ticketId = data.ticketId;
|
|
2011
|
+
if (payload.status === "rejected") {
|
|
2012
|
+
try {
|
|
2013
|
+
await ctx.api.update("generated-response", id, { autoSendDecision: "hold" }, { ifMatch: { status: "ready" } });
|
|
2014
|
+
} catch (err) {
|
|
2015
|
+
if (!(err instanceof AppApiError && err.status === 409)) throw err;
|
|
2016
|
+
}
|
|
2017
|
+
return;
|
|
2018
|
+
}
|
|
2019
|
+
if (data.autoSendDecision === "hold") {
|
|
2020
|
+
ctx.logger.warn(`handle-approval: generated-response ${id} is on hold (autoSendDecision), refusing to send despite the approval`);
|
|
2021
|
+
return;
|
|
2022
|
+
}
|
|
2023
|
+
const settings = await ctx.api.settings.get();
|
|
2024
|
+
const issues = validateSettings(settings);
|
|
2025
|
+
if (issues.length > 0) {
|
|
2026
|
+
ctx.logger.info("handle-approval: settings invalid, skipping", { issues });
|
|
2027
|
+
return;
|
|
2028
|
+
}
|
|
2029
|
+
const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(null, config)));
|
|
2030
|
+
const responseText = data.responseText ?? "";
|
|
2031
|
+
if (responseText.trim().length === 0) {
|
|
2032
|
+
ctx.logger.error(`handle-approval: generated-response ${id} has no responseText, refusing to send an empty reply`);
|
|
2033
|
+
assertTransition("ready", "invalidated");
|
|
2034
|
+
try {
|
|
2035
|
+
await ctx.api.update("generated-response", id, { status: "invalidated", openTicketKey: openTicketKeyFor("invalidated", ticketId) }, { ifMatch: { status: "ready" } });
|
|
2036
|
+
} catch (err) {
|
|
2037
|
+
if (!(err instanceof AppApiError && err.status === 409)) throw err;
|
|
2038
|
+
}
|
|
2039
|
+
return;
|
|
2040
|
+
}
|
|
2041
|
+
const ports = buildTicketPorts(ctx);
|
|
2042
|
+
const { clock, state: statePort } = ports;
|
|
2043
|
+
const conversation = {
|
|
2044
|
+
ref: { id: ticketId, channel: "gorgias" },
|
|
2045
|
+
subject: null,
|
|
2046
|
+
messages: [],
|
|
2047
|
+
customer: { name: null, email: null, orderContext: null },
|
|
2048
|
+
isClosed: false,
|
|
2049
|
+
lastMessageAt: data.generatedLastMessageAt ? new Date(data.generatedLastMessageAt) : null,
|
|
2050
|
+
messageCount: data.generatedMessageCount ?? 0,
|
|
2051
|
+
lastAgentReplyAt: null,
|
|
2052
|
+
hasCustomerAttachment: false,
|
|
2053
|
+
sourceChannel: data.channel
|
|
2054
|
+
};
|
|
2055
|
+
const draft = { text: responseText, sources: data.sources ?? [], revised: false };
|
|
2056
|
+
const proposedActions = [{ kind: "send_reply", args: {}, idempotencyKey: id, decision: "auto" }];
|
|
2057
|
+
const seam = buildSendSeam({ api: ctx.api, clock, id, ticketId, fromStatus: "ready" });
|
|
2058
|
+
let claimed = true;
|
|
2059
|
+
const trackedSeam = {
|
|
2060
|
+
claim: async (run) => {
|
|
2061
|
+
claimed = await seam.claim(run);
|
|
2062
|
+
return claimed;
|
|
2063
|
+
},
|
|
2064
|
+
commit: seam.commit
|
|
2065
|
+
};
|
|
2066
|
+
const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: 1 });
|
|
2067
|
+
const ref = { id: ticketId, channel: "gorgias" };
|
|
2068
|
+
const verdict = data.verdict ?? null;
|
|
2069
|
+
const patch = await act(
|
|
2070
|
+
{ ...initialState(), conversation, draft, verdict, proposedActions },
|
|
2071
|
+
{
|
|
2072
|
+
ref,
|
|
2073
|
+
profile,
|
|
2074
|
+
ports,
|
|
2075
|
+
toolContext: createNoToolContext(),
|
|
2076
|
+
budget,
|
|
2077
|
+
category: { autoReplyEnabled: true, minConfidence: null },
|
|
2078
|
+
categories: [],
|
|
2079
|
+
log: (msg) => ctx.logger.debug(msg),
|
|
2080
|
+
send: { mode: "claimed", claim: trackedSeam.claim, commit: trackedSeam.commit },
|
|
2081
|
+
queuedAt: data.generatedAt ? new Date(data.generatedAt) : null
|
|
2082
|
+
}
|
|
2083
|
+
);
|
|
2084
|
+
const guardrailHits = patch.guardrailHits ?? [];
|
|
2085
|
+
if (guardrailHits.length === 0) {
|
|
2086
|
+
if (!claimed) {
|
|
2087
|
+
ctx.logger.warn(
|
|
2088
|
+
`handle-approval: generated-response ${id} claim was lost \u2014 a concurrent worker already advanced this record, nothing to persist here`
|
|
2089
|
+
);
|
|
2090
|
+
return;
|
|
2091
|
+
}
|
|
2092
|
+
await applyOutcomeTags("sent", verdict, { ports: { state: statePort }, ref, audit: profile.audit });
|
|
2093
|
+
return;
|
|
2094
|
+
}
|
|
2095
|
+
try {
|
|
2096
|
+
await ctx.api.update("generated-response", id, { autoSendDecision: "hold" }, { ifMatch: { status: "ready" } });
|
|
2097
|
+
} catch (err) {
|
|
2098
|
+
if (!(err instanceof AppApiError && err.status === 409)) throw err;
|
|
2099
|
+
}
|
|
2100
|
+
await applyOutcomeTags("guardrail_hold", verdict, { ports: { state: statePort }, ref, audit: profile.audit });
|
|
2101
|
+
}
|
|
2102
|
+
|
|
2103
|
+
// src/functions/ids.ts
|
|
2104
|
+
var RUN_TRIAGE_NOW_INPUT_IGNORE_TRIAGE_DISABLED_UID = "dd175229-feee-4306-a429-b25ea5dd89e4";
|
|
2105
|
+
var PREVIEW_TRIAGE_INPUT_TICKET_ID_UID = "b9d5da91-ce08-4aac-ae52-5ffef730fab0";
|
|
2106
|
+
var GRAPH_DRY_RUN_INPUT_TICKET_ID_UID = "5861e7be-3a28-4852-874c-1c14e82d4b35";
|
|
2107
|
+
var GRAPH_DRY_RUN_INPUT_CATEGORY_ID_UID = "c47b8b57-6f7a-47d7-a9d1-a18fbf71a0f0";
|
|
2108
|
+
var GRAPH_DRY_RUN_INPUT_AGENT_ID_UID = "95d38506-bc22-4f91-ad43-797ff7b54f48";
|
|
2109
|
+
var GRAPH_DRY_RUN_INPUT_OVERRIDES_UID = "306a4f7d-db5d-4144-a6bd-865889e152e2";
|
|
2110
|
+
var TEST_AGENTS_INPUT_VIEW_ID_UID = "20227a8f-95d8-4c20-a9cd-eccb0ce39e3e";
|
|
2111
|
+
var TEST_AGENTS_INPUT_TICKET_IDS_UID = "7d27acff-b558-4783-a3ac-722f676b71a7";
|
|
2112
|
+
var TEST_AGENTS_INPUT_AGENT_ID_UID = "ea12d731-708b-4fcc-9ebb-6c4e0d04a60e";
|
|
2113
|
+
var TEST_AGENTS_INPUT_LIMIT_UID = "95151bdf-2966-41cd-8b6f-c5b0b10c427e";
|
|
2114
|
+
var SUGGEST_PROMPT_INPUT_AGENT_ID_UID = "40509afa-5931-419d-8467-a52cbac5c17e";
|
|
2115
|
+
var SUGGEST_PROMPT_INPUT_MAX_COMPARISONS_UID = "0c2e2f58-ffd3-4aee-a1b4-cb81d1762eb6";
|
|
2116
|
+
var RUN_DIFF_ANALYSIS_INPUT_AGENT_ID_UID = "bfe1e895-1608-40d8-99e9-230ab9c41473";
|
|
2117
|
+
var RUN_DIFF_ANALYSIS_INPUT_LIMIT_UID = "b1936472-a9dc-4b0b-8ef6-ab84733a2bfa";
|
|
2118
|
+
var LIST_GORGIAS_VIEWS_INPUT_CHECK_APP_SLUGS_UID = "1ac5eb02-32da-4fd4-9462-dac4ff23b208";
|
|
2119
|
+
var CREATE_AGENT_INPUT_NAME_UID = "0cb57453-7b02-49ce-875b-7ff079a5810d";
|
|
2120
|
+
var CREATE_AGENT_INPUT_MODEL_ID_UID = "f19f1c10-3145-482b-8c1d-6fd3576596ff";
|
|
2121
|
+
var CREATE_AGENT_INPUT_PROVIDER_UID = "0dd94db4-f31a-4cd2-b030-1b1a4da5b43e";
|
|
2122
|
+
var CREATE_AGENT_INPUT_SYSTEM_PROMPT_SNAPSHOT_UID = "d50f3810-b6fe-4c90-b69b-3e36ba502cdb";
|
|
2123
|
+
var SET_DEFAULT_AGENT_INPUT_AGENT_ID_UID = "0686c615-63f8-49a1-b3c7-3542bac76cd6";
|
|
2124
|
+
var EXT_CHAT_INPUT_MESSAGES_UID = "874e4408-74c0-4188-b923-a0791da4d096";
|
|
2125
|
+
var EXT_CHAT_INPUT_MODEL_ID_UID = "d63f05b1-165d-45e0-9300-cabe5e22fa42";
|
|
2126
|
+
var EXT_CHAT_INPUT_AGENT_NAME_UID = "928f03e6-2d48-487e-85ee-15999b9cbbbb";
|
|
2127
|
+
var EXT_CHAT_INPUT_GORGIAS_TICKET_ID_UID = "86fcc5df-8545-4d77-b3d7-d741c6b1d5a5";
|
|
2128
|
+
var EXT_FAST_RESPONSE_CHECK_INPUT_TICKET_ID_UID = "4a597dbf-ba6f-4628-b526-759448e7ed17";
|
|
2129
|
+
var EXT_EVALUATION_INPUT_SATISFIED_UID = "b1af323a-d1e0-40c7-b975-66a1e3cd4b21";
|
|
2130
|
+
var EXT_EVALUATION_INPUT_MESSAGES_UID = "ea5d9df8-c7d5-459c-b25d-2cfe0b45ad45";
|
|
2131
|
+
var EXT_EVALUATION_INPUT_TICKET_URL_UID = "6648f361-e16b-46b2-a411-3d9cdf35e87a";
|
|
2132
|
+
var EXT_EVALUATION_INPUT_LANGFUSE_TRACE_ID_UID = "0d8d5556-2ffe-4d5e-aaca-55e0eab63066";
|
|
2133
|
+
var EXT_EVALUATION_INPUT_LANGFUSE_OBSERVATION_ID_UID = "8285ab1d-e20d-4088-b9b0-176236339d1c";
|
|
2134
|
+
var EXT_EVALUATION_INPUT_MODEL_ID_UID = "1646f686-57d9-4204-b901-9d7a8e1a8078";
|
|
2135
|
+
var EXT_RESPONSE_COMPARISON_INPUT_LAST_MESSAGE_GENERATED_UID = "f2ad97ac-0abf-449a-9cc3-72efff6723c6";
|
|
2136
|
+
var EXT_RESPONSE_COMPARISON_INPUT_MESSAGE_ACTUAL_SENT_UID = "2dfe91f9-7177-4c44-8bcb-f841ff399ce0";
|
|
2137
|
+
var EXT_RESPONSE_COMPARISON_INPUT_TICKET_ID_UID = "63afd37e-4f0f-411b-aa62-6f480ef6cd3c";
|
|
2138
|
+
var EXT_RESPONSE_COMPARISON_INPUT_TICKET_URL_UID = "295c10ef-cb7c-4409-876a-1e384cfe6f45";
|
|
2139
|
+
var EXT_RESPONSE_COMPARISON_INPUT_MODEL_CONFIG_ID_UID = "c48778a5-a8f5-4ee7-92b7-66de1bb543be";
|
|
2140
|
+
var EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_TRACE_ID_UID = "5113fc86-3865-4110-b65f-c91748816f02";
|
|
2141
|
+
var EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_OBSERVATION_ID_UID = "e5310144-8004-4c20-9ce4-9c0c820e3577";
|
|
2142
|
+
var EXT_RESPONSE_COMPARISON_INPUT_PROMPT_NAME_UID = "4813f09d-88ac-4574-8f38-be5f87a6c9ac";
|
|
2143
|
+
var EXT_RESPONSE_COMPARISON_INPUT_PROMPT_VERSION_UID = "e87e65e8-e078-47e3-92b7-104368952a56";
|
|
2144
|
+
var EXT_RESPONSE_COMPARISON_INPUT_CONVERSATION_MESSAGES_UID = "0a985d59-fd20-4672-91bb-4824b8dfb026";
|
|
2145
|
+
var CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID = "1039e196-cf6e-438e-8ec9-7ab422feaf4d";
|
|
2146
|
+
var CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID = "10ffe3e1-972e-43b4-bb45-343c4664464f";
|
|
2147
|
+
var SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID = "2f5d6cbb-1c69-4a76-9d8f-1a3f0a4e57c2";
|
|
2148
|
+
|
|
2149
|
+
// src/functions/run-triage-now.ts
|
|
2150
|
+
var TRIAGE_RUN_REQUESTED_EVENT = "triage.run.requested";
|
|
2151
|
+
var MANUAL_TRIAGE_RUN_KIND = "run-triage-now";
|
|
2152
|
+
var MANUAL_TRIAGE_RUN_KEY = "manual";
|
|
2153
|
+
function buildRunTriageNowFunctionDef(config) {
|
|
2154
|
+
return {
|
|
2155
|
+
universalIdentifier: identifierFor(config, "run-triage-now"),
|
|
2156
|
+
name: "run-triage-now",
|
|
2157
|
+
// The handler is two API calls now, not a batch: a budget well under the
|
|
2158
|
+
// platform's 15 s default states that, and turns a hung platform call
|
|
2159
|
+
// into a fast error instead of a slow one.
|
|
2160
|
+
trigger: { type: "uiInvoke", minRole: "EDITOR", timeoutMs: 1e4 },
|
|
2161
|
+
input: [
|
|
2162
|
+
{
|
|
2163
|
+
universalIdentifier: RUN_TRIAGE_NOW_INPUT_IGNORE_TRIAGE_DISABLED_UID,
|
|
2164
|
+
name: "ignoreTriageDisabled",
|
|
2165
|
+
type: FieldType.BOOLEAN,
|
|
2166
|
+
label: "Ignore triageEnabled",
|
|
2167
|
+
description: "Bypass the triageEnabled kill switch and run the real batch anyway. This is NOT a dry run \u2014 tickets are classified and tagged for real.",
|
|
2168
|
+
isNullable: true
|
|
2169
|
+
}
|
|
2170
|
+
]
|
|
2171
|
+
};
|
|
2172
|
+
}
|
|
2173
|
+
function buildRunTriageBatchFunctionDef(config) {
|
|
2174
|
+
return {
|
|
2175
|
+
universalIdentifier: identifierFor(config, "run-triage-batch"),
|
|
2176
|
+
name: "run-triage-batch",
|
|
2177
|
+
trigger: { type: "event", name: TRIAGE_RUN_REQUESTED_EVENT },
|
|
2178
|
+
retries: 0,
|
|
2179
|
+
concurrency: 1,
|
|
2180
|
+
notify: { onFailure: true, severity: "warning" }
|
|
2181
|
+
};
|
|
2182
|
+
}
|
|
2183
|
+
function createRunTriageNowHandler(config) {
|
|
2184
|
+
return (ctx, input) => runTriageNowHandler(ctx, config, input ?? {});
|
|
2185
|
+
}
|
|
2186
|
+
function createRunTriageBatchHandler(config) {
|
|
2187
|
+
return (ctx, input) => runTriageBatchEventHandler(ctx, config, input ?? {});
|
|
2188
|
+
}
|
|
2189
|
+
async function runTriageNowHandler(ctx, config, input) {
|
|
2190
|
+
const ignoreTriageDisabled = input.ignoreTriageDisabled ?? false;
|
|
2191
|
+
const settings = await ctx.api.settings.get();
|
|
2192
|
+
assertRunnable(ctx, settings, ignoreTriageDisabled);
|
|
2193
|
+
const run = await ctx.api.runs.start({
|
|
2194
|
+
kind: MANUAL_TRIAGE_RUN_KIND,
|
|
2195
|
+
key: MANUAL_TRIAGE_RUN_KEY,
|
|
2196
|
+
message: "Triage manuel demand\xE9",
|
|
2197
|
+
metadata: { ignoreTriageDisabled }
|
|
2198
|
+
});
|
|
2199
|
+
if (run.reused) {
|
|
2200
|
+
ctx.logger.info("run-triage-now: a manual batch is already running, not queueing a second one", { runId: run.id });
|
|
2201
|
+
return { runId: run.id, status: "already-running" };
|
|
2202
|
+
}
|
|
2203
|
+
try {
|
|
2204
|
+
await ctx.api.events.send(TRIAGE_RUN_REQUESTED_EVENT, {
|
|
2205
|
+
_key: run.id,
|
|
2206
|
+
runId: run.id,
|
|
2207
|
+
ignoreTriageDisabled
|
|
2208
|
+
});
|
|
2209
|
+
} catch (err) {
|
|
2210
|
+
await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });
|
|
2211
|
+
throw err;
|
|
2212
|
+
}
|
|
2213
|
+
return { runId: run.id, status: "queued" };
|
|
2214
|
+
}
|
|
2215
|
+
async function runTriageBatchEventHandler(ctx, config, payload) {
|
|
2216
|
+
const { runId } = payload;
|
|
2217
|
+
const settings = await ctx.api.settings.get();
|
|
2218
|
+
try {
|
|
2219
|
+
assertRunnable(ctx, settings, payload.ignoreTriageDisabled ?? false);
|
|
2220
|
+
const result = await runTriageBatch(ctx, config, settings);
|
|
2221
|
+
if (runId) await ctx.api.runs.succeed(runId, result);
|
|
2222
|
+
} catch (err) {
|
|
2223
|
+
if (runId) await ctx.api.runs.fail(runId, { message: err instanceof Error ? err.message : String(err) });
|
|
2224
|
+
throw err;
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
function assertRunnable(ctx, settings, ignoreTriageDisabled) {
|
|
2228
|
+
const issues = validateSettings(settings);
|
|
2229
|
+
if (issues.length > 0) {
|
|
2230
|
+
throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(" ")}`);
|
|
2231
|
+
}
|
|
2232
|
+
if (!ignoreTriageDisabled && !settings.triageEnabled) {
|
|
2233
|
+
throw new ctx.NonRetriableError("Triage is disabled (triageEnabled is off) \u2014 pass ignoreTriageDisabled to override.");
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
function buildPreviewTriageFunctionDef(config) {
|
|
2237
|
+
return {
|
|
2238
|
+
universalIdentifier: identifierFor(config, "preview-triage"),
|
|
2239
|
+
name: "preview-triage",
|
|
2240
|
+
trigger: { type: "uiInvoke", minRole: "VIEWER" },
|
|
2241
|
+
input: [
|
|
2242
|
+
{
|
|
2243
|
+
universalIdentifier: PREVIEW_TRIAGE_INPUT_TICKET_ID_UID,
|
|
2244
|
+
name: "ticketId",
|
|
2245
|
+
type: FieldType.TEXT,
|
|
2246
|
+
label: "Ticket id",
|
|
2247
|
+
isNullable: false
|
|
2248
|
+
}
|
|
2249
|
+
]
|
|
2250
|
+
};
|
|
2251
|
+
}
|
|
2252
|
+
function createPreviewTriageHandler(config) {
|
|
2253
|
+
return (ctx, input) => previewTriageHandler(ctx, config, input);
|
|
2254
|
+
}
|
|
2255
|
+
async function previewTriageHandler(ctx, config, input) {
|
|
2256
|
+
const ticketId = input?.ticketId?.trim();
|
|
2257
|
+
if (!ticketId) throw new ctx.NonRetriableError("ticketId is required");
|
|
2258
|
+
const settings = await ctx.api.settings.get();
|
|
2259
|
+
const issues = validateSettings(settings);
|
|
2260
|
+
if (issues.length > 0) {
|
|
2261
|
+
throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(" ")}`);
|
|
2262
|
+
}
|
|
2263
|
+
const categories = await listCategories(ctx.api);
|
|
2264
|
+
const agent = await resolveDraftAgent(ctx.api, null);
|
|
2265
|
+
const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config)));
|
|
2266
|
+
const realPorts = buildTicketPorts(ctx);
|
|
2267
|
+
const recordingState = createRecordingStatePort(ctx.api);
|
|
2268
|
+
const recordingReply = createRecordingReplyPort();
|
|
2269
|
+
const ref = { id: ticketId, channel: "gorgias" };
|
|
2270
|
+
const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });
|
|
2271
|
+
const state = await runTicket(
|
|
2272
|
+
{
|
|
2273
|
+
ref,
|
|
2274
|
+
profile,
|
|
2275
|
+
ports: {
|
|
2276
|
+
conversation: realPorts.conversation,
|
|
2277
|
+
reply: recordingReply.port,
|
|
2278
|
+
llm: realPorts.llm,
|
|
2279
|
+
prompt: realPorts.prompt,
|
|
2280
|
+
state: recordingState.port,
|
|
2281
|
+
clock: realPorts.clock
|
|
2282
|
+
},
|
|
2283
|
+
toolContext: createNoToolContext(),
|
|
2284
|
+
budget,
|
|
2285
|
+
category: { autoReplyEnabled: true, minConfidence: null },
|
|
2286
|
+
categories: toCategoryReferential(categories),
|
|
2287
|
+
log: (msg) => ctx.logger.debug(msg),
|
|
2288
|
+
send: { mode: "none" }
|
|
2289
|
+
},
|
|
2290
|
+
{ until: "triage" }
|
|
2291
|
+
);
|
|
2292
|
+
const wouldHaveTagged = state.classification ? await resolveHandledTags(ctx.api, state.classification, profile.audit) : [];
|
|
2293
|
+
return {
|
|
2294
|
+
ticketId,
|
|
2295
|
+
classification: state.classification,
|
|
2296
|
+
escalated: state.escalated,
|
|
2297
|
+
wouldHaveTagged
|
|
2298
|
+
};
|
|
2299
|
+
}
|
|
2300
|
+
|
|
2301
|
+
// src/functions/graph-dry-run-core.ts
|
|
2302
|
+
var DRY_RUN_DEADLINE_MS = 3 * 60 * 1e3;
|
|
2303
|
+
async function runGraphDryRun({ base, api, resume }) {
|
|
2304
|
+
const recordingReply = createRecordingReplyPort();
|
|
2305
|
+
const recordingState = createRecordingStatePort(api);
|
|
2306
|
+
const recordingSend = createRecordingSendPort();
|
|
2307
|
+
const recordingLlm = createRecordingLlmPort(base.ports.llm);
|
|
2308
|
+
const recordingEvaluator = base.ports.evaluator ? createRecordingLlmPort(base.ports.evaluator) : null;
|
|
2309
|
+
const steps = [];
|
|
2310
|
+
const deps = {
|
|
2311
|
+
...base,
|
|
2312
|
+
ports: {
|
|
2313
|
+
...base.ports,
|
|
2314
|
+
reply: recordingReply.port,
|
|
2315
|
+
state: recordingState.port,
|
|
2316
|
+
llm: recordingLlm.port,
|
|
2317
|
+
...recordingEvaluator ? { evaluator: recordingEvaluator.port } : {}
|
|
2318
|
+
},
|
|
2319
|
+
send: recordingSend.send,
|
|
2320
|
+
trace: (step) => steps.push(step)
|
|
2321
|
+
};
|
|
2322
|
+
let result = null;
|
|
2323
|
+
let error;
|
|
2324
|
+
try {
|
|
2325
|
+
result = await runTicket(deps, resume ? { resume } : void 0);
|
|
2326
|
+
} catch (err) {
|
|
2327
|
+
error = err instanceof Error ? err.message : String(err);
|
|
2328
|
+
}
|
|
2329
|
+
const seen = new Set(steps.map((s) => s.node));
|
|
2330
|
+
const completions = [...recordingLlm.completions, ...recordingEvaluator?.completions ?? []];
|
|
2331
|
+
return {
|
|
2332
|
+
ticketId: base.ref.id,
|
|
2333
|
+
outcome: result?.outcome ?? null,
|
|
2334
|
+
steps,
|
|
2335
|
+
skipped: NODE_NAMES.filter((name) => !seen.has(name)),
|
|
2336
|
+
completions,
|
|
2337
|
+
wouldHaveTagged: recordingState.wouldHaveTagged(),
|
|
2338
|
+
wouldHaveReplied: recordingReply.wouldHaveReplied(),
|
|
2339
|
+
sendSeamExercised: recordingSend.calls.length > 0,
|
|
2340
|
+
draft: result?.draft ?? null,
|
|
2341
|
+
verdict: result?.verdict ?? null,
|
|
2342
|
+
guardrailHits: result?.guardrailHits ?? [],
|
|
2343
|
+
...error ? { error } : {}
|
|
2344
|
+
};
|
|
2345
|
+
}
|
|
2346
|
+
|
|
2347
|
+
// src/functions/graph-dry-run.ts
|
|
2348
|
+
function resolveReviseNode(profile, override) {
|
|
2349
|
+
if (override === false) return null;
|
|
2350
|
+
if (profile.nodes.revise) return profile.nodes.revise;
|
|
2351
|
+
if (override !== true) return null;
|
|
2352
|
+
const writer = profile.nodes.draft;
|
|
2353
|
+
return writer ? { model: writer.model, provider: writer.provider, reasoning: "off" } : null;
|
|
2354
|
+
}
|
|
2355
|
+
function withTrialJudge(profile, override) {
|
|
2356
|
+
if (override !== true || profile.nodes.evaluate) return profile;
|
|
2357
|
+
const trial = {
|
|
2358
|
+
model: profile.nodes.draft?.model ?? "",
|
|
2359
|
+
provider: "openai",
|
|
2360
|
+
reasoning: "off",
|
|
2361
|
+
minConfidence: profile.autoSend.minConfidence,
|
|
2362
|
+
escalationEnabled: false
|
|
2363
|
+
};
|
|
2364
|
+
return { ...profile, nodes: { ...profile.nodes, evaluate: trial } };
|
|
2365
|
+
}
|
|
2366
|
+
function applyOverrides(profile, overrides) {
|
|
2367
|
+
const withEvaluate = overrides.evaluate === false ? { ...profile, nodes: { ...profile.nodes, evaluate: null } } : withTrialJudge(profile, overrides.evaluate);
|
|
2368
|
+
return {
|
|
2369
|
+
...withEvaluate,
|
|
2370
|
+
nodes: { ...withEvaluate.nodes, revise: resolveReviseNode(withEvaluate, overrides.revise) },
|
|
2371
|
+
// `auto_reply`, not `draft_only`: `draft_only` blocks `isAutoSendEligible`
|
|
2372
|
+
// outright for a WhatsApp ticket, which would stop the run at `ready`
|
|
2373
|
+
// and defeat the whole point of this override — reaching `act` with
|
|
2374
|
+
// nothing standing in the way. The category opt-in is bypassed the same
|
|
2375
|
+
// way triage-tick's own dry-run-adjacent callers do it (see below,
|
|
2376
|
+
// `category: {autoReplyEnabled: true, …}`).
|
|
2377
|
+
//
|
|
2378
|
+
// `judgemeEscalateOnly: false` (T23 post-review C1): that rule is NOT
|
|
2379
|
+
// filtered through `active` (`graph/nodes/guardrails.ts` checks it
|
|
2380
|
+
// unconditionally) and `settingsToProfile` hardcodes it to `true` with
|
|
2381
|
+
// no settings surface to turn it off — so without this, an operator
|
|
2382
|
+
// dry-running a Judge.me ticket with guardrails off still gets held by
|
|
2383
|
+
// a guardrail this override exists specifically to bypass.
|
|
2384
|
+
guardrails: overrides.guardrails === false ? { active: [], params: { ...withEvaluate.guardrails.params, whatsappMode: "auto_reply", judgemeEscalateOnly: false } } : withEvaluate.guardrails,
|
|
2385
|
+
autoSend: { ...withEvaluate.autoSend, enabled: overrides.autoSend === true && !!withEvaluate.autoSend.senderEmail }
|
|
2386
|
+
};
|
|
2387
|
+
}
|
|
2388
|
+
function forcedClassification(tagName) {
|
|
2389
|
+
return { category: tagName, confidence: "high", reasoning: "operator: cat\xE9gorie forc\xE9e", isFallback: false, conversationOver: false };
|
|
2390
|
+
}
|
|
2391
|
+
function buildGraphDryRunFunctionDef(config) {
|
|
2392
|
+
return {
|
|
2393
|
+
universalIdentifier: identifierFor(config, "graph-dry-run"),
|
|
2394
|
+
name: "graph-dry-run",
|
|
2395
|
+
trigger: { type: "uiInvoke", minRole: "EDITOR" },
|
|
2396
|
+
input: [
|
|
2397
|
+
{ universalIdentifier: GRAPH_DRY_RUN_INPUT_TICKET_ID_UID, name: "ticketId", type: FieldType.TEXT, label: "Ticket id", isNullable: false },
|
|
2398
|
+
{ universalIdentifier: GRAPH_DRY_RUN_INPUT_AGENT_ID_UID, name: "agentId", type: FieldType.TEXT, label: "Agent id", isNullable: true },
|
|
2399
|
+
{ universalIdentifier: GRAPH_DRY_RUN_INPUT_CATEGORY_ID_UID, name: "categoryId", type: FieldType.TEXT, label: "Category id", isNullable: true },
|
|
2400
|
+
{
|
|
2401
|
+
universalIdentifier: GRAPH_DRY_RUN_INPUT_OVERRIDES_UID,
|
|
2402
|
+
name: "overrides",
|
|
2403
|
+
type: FieldType.JSON,
|
|
2404
|
+
label: "Overrides",
|
|
2405
|
+
description: "{evaluate?, revise?, guardrails?, autoSend?}",
|
|
2406
|
+
isNullable: true
|
|
2407
|
+
}
|
|
2408
|
+
]
|
|
2409
|
+
};
|
|
2410
|
+
}
|
|
2411
|
+
function createGraphDryRunHandler(config) {
|
|
2412
|
+
return (ctx, input) => graphDryRunHandler(ctx, config, input);
|
|
2413
|
+
}
|
|
2414
|
+
async function graphDryRunHandler(ctx, config, input) {
|
|
2415
|
+
const ticketId = input?.ticketId?.trim();
|
|
2416
|
+
if (!ticketId) throw new ctx.NonRetriableError("ticketId is required");
|
|
2417
|
+
const settings = await ctx.api.settings.get();
|
|
2418
|
+
const issues = validateSettings(settings);
|
|
2419
|
+
if (issues.length > 0) {
|
|
2420
|
+
throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(" ")}`);
|
|
2421
|
+
}
|
|
2422
|
+
const categories = await listCategories(ctx.api);
|
|
2423
|
+
const forcedCategory = input.categoryId ? categories.find((c) => c.id === input.categoryId) ?? null : null;
|
|
2424
|
+
if (input.categoryId && !forcedCategory) throw new ctx.NonRetriableError(`Category "${input.categoryId}" not found`);
|
|
2425
|
+
const agent = input.agentId ? toAgent(await ctx.api.get("agent", input.agentId)) : await resolveDraftAgent(ctx.api, forcedCategory?.agentId ?? null);
|
|
2426
|
+
const baseProfile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config)));
|
|
2427
|
+
const profile = applyOverrides(baseProfile, input.overrides ?? {});
|
|
2428
|
+
const realPorts = buildTicketPorts(ctx);
|
|
2429
|
+
const ref = { id: ticketId, channel: "gorgias" };
|
|
2430
|
+
const budget = createBudget({ signal: AbortSignal.timeout(DRY_RUN_DEADLINE_MS), maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });
|
|
2431
|
+
const base = {
|
|
2432
|
+
ref,
|
|
2433
|
+
profile,
|
|
2434
|
+
ports: {
|
|
2435
|
+
conversation: realPorts.conversation,
|
|
2436
|
+
reply: realPorts.reply,
|
|
2437
|
+
llm: realPorts.llm,
|
|
2438
|
+
prompt: realPorts.prompt,
|
|
2439
|
+
state: realPorts.state,
|
|
2440
|
+
clock: realPorts.clock
|
|
2441
|
+
},
|
|
2442
|
+
toolContext: createNoToolContext(),
|
|
2443
|
+
budget,
|
|
2444
|
+
// Bypassed the same way `triage-tick`'s dry-run-adjacent batch is:
|
|
2445
|
+
// reaching `act` is what the `autoSend` override is for, and requiring
|
|
2446
|
+
// the category to ALSO have opted in would make the override inert on
|
|
2447
|
+
// every category that has auto-reply off — which is all of them today.
|
|
2448
|
+
category: { autoReplyEnabled: true, minConfidence: null },
|
|
2449
|
+
categories: toCategoryReferential(categories),
|
|
2450
|
+
log: (msg) => ctx.logger.debug(msg),
|
|
2451
|
+
send: { mode: "none" }
|
|
2452
|
+
// overridden unconditionally by `runGraphDryRun`
|
|
2453
|
+
};
|
|
2454
|
+
const resume = forcedCategory ? { classification: forcedClassification(forcedCategory.tagName), escalated: false } : void 0;
|
|
2455
|
+
return runGraphDryRun({ base, api: ctx.api, resume });
|
|
2456
|
+
}
|
|
2457
|
+
var DEFAULT_LIMIT = 20;
|
|
2458
|
+
var MAX_LIMIT = 100;
|
|
2459
|
+
function buildTestAgentsFunctionDef(config) {
|
|
2460
|
+
return {
|
|
2461
|
+
universalIdentifier: identifierFor(config, "test-agents"),
|
|
2462
|
+
name: "test-agents",
|
|
2463
|
+
trigger: { type: "uiInvoke", minRole: "EDITOR" },
|
|
2464
|
+
input: [
|
|
2465
|
+
{ universalIdentifier: TEST_AGENTS_INPUT_VIEW_ID_UID, name: "viewId", type: FieldType.TEXT, label: "View id", isNullable: true },
|
|
2466
|
+
{ universalIdentifier: TEST_AGENTS_INPUT_TICKET_IDS_UID, name: "ticketIds", type: FieldType.JSON, label: "Ticket ids", description: "string[]", isNullable: true },
|
|
2467
|
+
{ universalIdentifier: TEST_AGENTS_INPUT_AGENT_ID_UID, name: "agentId", type: FieldType.TEXT, label: "Agent id", isNullable: true },
|
|
2468
|
+
{ universalIdentifier: TEST_AGENTS_INPUT_LIMIT_UID, name: "limit", type: FieldType.NUMBER, label: "Limit", isNullable: true }
|
|
2469
|
+
]
|
|
2470
|
+
};
|
|
2471
|
+
}
|
|
2472
|
+
function createTestAgentsHandler(config) {
|
|
2473
|
+
return (ctx, input) => testAgentsHandler(ctx, config, input);
|
|
2474
|
+
}
|
|
2475
|
+
async function testAgentsHandler(ctx, config, input) {
|
|
2476
|
+
const explicitIds = (input?.ticketIds ?? []).map((id) => id.trim()).filter(Boolean);
|
|
2477
|
+
const viewId = input?.viewId?.trim();
|
|
2478
|
+
if (!viewId && explicitIds.length === 0) {
|
|
2479
|
+
throw new ctx.NonRetriableError("Either viewId or ticketIds is required");
|
|
2480
|
+
}
|
|
2481
|
+
const settings = await ctx.api.settings.get();
|
|
2482
|
+
const issues = validateSettings(settings);
|
|
2483
|
+
if (issues.length > 0) {
|
|
2484
|
+
throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(" ")}`);
|
|
2485
|
+
}
|
|
2486
|
+
const limit = Math.min(input?.limit ?? DEFAULT_LIMIT, MAX_LIMIT);
|
|
2487
|
+
const categories = await listCategories(ctx.api);
|
|
2488
|
+
const agent = input.agentId ? toAgent(await ctx.api.get("agent", input.agentId)) : await resolveDraftAgent(ctx.api, null);
|
|
2489
|
+
const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config)));
|
|
2490
|
+
const realPorts = buildTicketPorts(ctx);
|
|
2491
|
+
const refs = explicitIds.length ? explicitIds.slice(0, limit).map((id) => ({ id, channel: "gorgias" })) : await realPorts.conversation.listPending({ viewOrTag: viewId }, limit);
|
|
2492
|
+
const deadline = AbortSignal.timeout(DRY_RUN_DEADLINE_MS);
|
|
2493
|
+
const results = [];
|
|
2494
|
+
for (const ref of refs) {
|
|
2495
|
+
if (deadline.aborted) break;
|
|
2496
|
+
const budget = createBudget({ signal: deadline, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });
|
|
2497
|
+
const base = {
|
|
2498
|
+
ref,
|
|
2499
|
+
profile,
|
|
2500
|
+
ports: {
|
|
2501
|
+
conversation: realPorts.conversation,
|
|
2502
|
+
reply: realPorts.reply,
|
|
2503
|
+
llm: realPorts.llm,
|
|
2504
|
+
prompt: realPorts.prompt,
|
|
2505
|
+
state: realPorts.state,
|
|
2506
|
+
clock: realPorts.clock
|
|
2507
|
+
},
|
|
2508
|
+
toolContext: createNoToolContext(),
|
|
2509
|
+
budget,
|
|
2510
|
+
category: { autoReplyEnabled: true, minConfidence: null },
|
|
2511
|
+
categories: toCategoryReferential(categories),
|
|
2512
|
+
log: (msg) => ctx.logger.debug(msg),
|
|
2513
|
+
send: { mode: "none" }
|
|
2514
|
+
// overridden unconditionally by `runGraphDryRun`
|
|
2515
|
+
};
|
|
2516
|
+
results.push(await runGraphDryRun({ base, api: ctx.api }));
|
|
2517
|
+
}
|
|
2518
|
+
return { results, autoReplyForced: true };
|
|
2519
|
+
}
|
|
2520
|
+
var LITERAL_PREFIX = "@@@langfusePrompt:";
|
|
2521
|
+
var MALFORMED_SNIPPET_MAX_LEN = 60;
|
|
2522
|
+
var MAX_CYCLE_DEPTH = 10;
|
|
2523
|
+
var REF_RE2 = new RegExp(REFERENCE_TAG_SOURCE, "g");
|
|
2524
|
+
function snippetAt(content, index) {
|
|
2525
|
+
const rest = content.slice(index);
|
|
2526
|
+
const closingIdx = rest.indexOf("@@@", LITERAL_PREFIX.length);
|
|
2527
|
+
const snippet = closingIdx === -1 ? rest.slice(0, MALFORMED_SNIPPET_MAX_LEN) : rest.slice(0, closingIdx + 3);
|
|
2528
|
+
return snippet.length > MALFORMED_SNIPPET_MAX_LEN ? `${snippet.slice(0, MALFORMED_SNIPPET_MAX_LEN)}\u2026` : snippet;
|
|
2529
|
+
}
|
|
2530
|
+
function findMalformedTags(content) {
|
|
2531
|
+
if (!content.includes(LITERAL_PREFIX)) return [];
|
|
2532
|
+
const validStarts = new Set([...content.matchAll(REF_RE2)].map((m) => m.index ?? -1));
|
|
2533
|
+
const malformed = [];
|
|
2534
|
+
for (const m of content.matchAll(new RegExp(LITERAL_PREFIX, "g"))) {
|
|
2535
|
+
const index = m.index ?? -1;
|
|
2536
|
+
if (!validStarts.has(index)) malformed.push(snippetAt(content, index));
|
|
2537
|
+
}
|
|
2538
|
+
return malformed;
|
|
2539
|
+
}
|
|
2540
|
+
function locatorFor(ref) {
|
|
2541
|
+
return ref.version !== void 0 ? `version ${ref.version}` : `label "${ref.label}"`;
|
|
2542
|
+
}
|
|
2543
|
+
function isFetchFailure(result) {
|
|
2544
|
+
return !("content" in result);
|
|
2545
|
+
}
|
|
2546
|
+
function targetKey(ref) {
|
|
2547
|
+
return ref.version !== void 0 ? `${ref.name}::v${ref.version}` : `${ref.name}::${ref.label}`;
|
|
2548
|
+
}
|
|
2549
|
+
async function fetchTarget(api, ref) {
|
|
2550
|
+
try {
|
|
2551
|
+
const detail = await api.prompts.get(ref.name, {
|
|
2552
|
+
resolve: false,
|
|
2553
|
+
...ref.version !== void 0 ? { version: ref.version } : { label: ref.label }
|
|
2554
|
+
});
|
|
2555
|
+
return { content: detail.content };
|
|
2556
|
+
} catch (err) {
|
|
2557
|
+
return { forbidden: err instanceof AppApiError && err.status === 403 };
|
|
2558
|
+
}
|
|
2559
|
+
}
|
|
2560
|
+
async function fetchTargetCached(api, ref, cache) {
|
|
2561
|
+
const key = targetKey(ref);
|
|
2562
|
+
const cached = cache.get(key);
|
|
2563
|
+
if (cached) return cached;
|
|
2564
|
+
const target = await fetchTarget(api, ref);
|
|
2565
|
+
cache.set(key, target);
|
|
2566
|
+
return target;
|
|
2567
|
+
}
|
|
2568
|
+
async function hasPathToOrigin(api, content, origin, depth, cache, visited) {
|
|
2569
|
+
if (depth > MAX_CYCLE_DEPTH) return false;
|
|
2570
|
+
for (const ref of parseReferences(content)) {
|
|
2571
|
+
if (ref.name === origin) return true;
|
|
2572
|
+
const key = targetKey(ref);
|
|
2573
|
+
if (visited.has(key)) continue;
|
|
2574
|
+
visited.add(key);
|
|
2575
|
+
const target = await fetchTargetCached(api, ref, cache);
|
|
2576
|
+
if (isFetchFailure(target)) continue;
|
|
2577
|
+
if (await hasPathToOrigin(api, target.content, origin, depth + 1, cache, visited)) return true;
|
|
2578
|
+
}
|
|
2579
|
+
return false;
|
|
2580
|
+
}
|
|
2581
|
+
async function exceedsCompositionDepth(api, content, depth, cache, visited) {
|
|
2582
|
+
const refs = parseReferences(content);
|
|
2583
|
+
if (refs.length === 0) return false;
|
|
2584
|
+
if (depth >= MAX_COMPOSITION_DEPTH) return true;
|
|
2585
|
+
for (const ref of refs) {
|
|
2586
|
+
if (visited.has(ref.name)) continue;
|
|
2587
|
+
const target = await fetchTargetCached(api, ref, cache);
|
|
2588
|
+
if (isFetchFailure(target)) continue;
|
|
2589
|
+
if (await exceedsCompositionDepth(api, target.content, depth + 1, cache, /* @__PURE__ */ new Set([...visited, ref.name]))) return true;
|
|
2590
|
+
}
|
|
2591
|
+
return false;
|
|
2592
|
+
}
|
|
2593
|
+
async function validateReferences(api, content, selfName) {
|
|
2594
|
+
const errors = [];
|
|
2595
|
+
const cache = /* @__PURE__ */ new Map();
|
|
2596
|
+
for (const snippet of findMalformedTags(content)) {
|
|
2597
|
+
errors.push(`Malformed reference tag near "${snippet}": it will be saved as literal text instead of being resolved.`);
|
|
2598
|
+
}
|
|
2599
|
+
for (const ref of parseReferences(content)) {
|
|
2600
|
+
if (ref.name === selfName) {
|
|
2601
|
+
errors.push(`Reference "${ref.raw}" points to this same prompt ("${selfName}") \u2014 a prompt cannot reference itself.`);
|
|
2602
|
+
continue;
|
|
2603
|
+
}
|
|
2604
|
+
const target = await fetchTargetCached(api, ref, cache);
|
|
2605
|
+
if (isFetchFailure(target)) {
|
|
2606
|
+
errors.push(
|
|
2607
|
+
target.forbidden ? `Reference "${ref.raw}" points to prompt "${ref.name}", which exists but is outside this app's prompts allowlist (role.prompts) \u2014 it cannot be composed here even though it can be read elsewhere.` : `Reference "${ref.raw}" could not be resolved: prompt "${ref.name}" with ${locatorFor(ref)} was not found, or the prompt store could not be reached to verify it.`
|
|
2608
|
+
);
|
|
2609
|
+
continue;
|
|
2610
|
+
}
|
|
2611
|
+
if (await hasPathToOrigin(api, target.content, selfName, 1, cache, /* @__PURE__ */ new Set([targetKey(ref)]))) {
|
|
2612
|
+
errors.push(`Reference "${ref.raw}" creates a cycle: prompt "${ref.name}" (transitively) references this prompt ("${selfName}").`);
|
|
2613
|
+
}
|
|
2614
|
+
}
|
|
2615
|
+
if (errors.length === 0 && await exceedsCompositionDepth(api, content, 0, cache, /* @__PURE__ */ new Set([selfName]))) {
|
|
2616
|
+
errors.push(
|
|
2617
|
+
`Reference chain exceeds the runtime composition cap (${MAX_COMPOSITION_DEPTH} levels): the segment past that depth would be silently stripped when this prompt is resolved.`
|
|
2618
|
+
);
|
|
2619
|
+
}
|
|
2620
|
+
return errors;
|
|
2621
|
+
}
|
|
2622
|
+
|
|
2623
|
+
// src/functions/suggest-prompt.ts
|
|
2624
|
+
var DEFAULT_MAX_COMPARISONS = 50;
|
|
2625
|
+
var MIN_COMPARISONS_REQUIRED = 3;
|
|
2626
|
+
var DEFAULT_SUGGEST_META_PROMPT = [
|
|
2627
|
+
"Tu es un expert en r\xE9daction de prompts syst\xE8me pour des assistants IA de support client.",
|
|
2628
|
+
"Analyse les diff\xE9rences entre les r\xE9ponses de l'IA et celles des agents humains dans les exemples fournis.",
|
|
2629
|
+
"Identifie les patterns r\xE9currents (ton, structure, longueur, formulations) puis r\xE9\xE9cris le prompt syst\xE8me actuel pour en corriger les \xE9carts.",
|
|
2630
|
+
"Retourne UNIQUEMENT le texte du prompt syst\xE8me am\xE9lior\xE9, sans explication ni mise en forme markdown.",
|
|
2631
|
+
"Toute balise de r\xE9f\xE9rence de la forme @@@langfusePrompt:...@@@ pr\xE9sente dans le prompt actuel doit \xEAtre reproduite telle quelle, sans modification."
|
|
2632
|
+
].join("\n");
|
|
2633
|
+
function buildSuggestPromptFunctionDef(config) {
|
|
2634
|
+
return {
|
|
2635
|
+
universalIdentifier: identifierFor(config, "suggest-prompt"),
|
|
2636
|
+
name: "suggest-prompt",
|
|
2637
|
+
trigger: { type: "uiInvoke", minRole: "EDITOR" },
|
|
2638
|
+
input: [
|
|
2639
|
+
{ universalIdentifier: SUGGEST_PROMPT_INPUT_AGENT_ID_UID, name: "agentId", type: FieldType.TEXT, label: "Agent id", isNullable: false },
|
|
2640
|
+
{ universalIdentifier: SUGGEST_PROMPT_INPUT_MAX_COMPARISONS_UID, name: "maxComparisons", type: FieldType.NUMBER, label: "Max comparisons", isNullable: true }
|
|
2641
|
+
]
|
|
2642
|
+
};
|
|
2643
|
+
}
|
|
2644
|
+
function createSuggestPromptHandler(config) {
|
|
2645
|
+
return (ctx, input) => suggestPromptHandler(ctx, config, input);
|
|
2646
|
+
}
|
|
2647
|
+
function comparisonBlock(index, generatedText, sentText) {
|
|
2648
|
+
const ai = generatedText?.trim() || "(aucune r\xE9ponse g\xE9n\xE9r\xE9e)";
|
|
2649
|
+
return `### Exemple ${index + 1}
|
|
2650
|
+
IA a g\xE9n\xE9r\xE9 :
|
|
2651
|
+
${ai}
|
|
2652
|
+
|
|
2653
|
+
Agent a r\xE9ellement envoy\xE9 :
|
|
2654
|
+
${sentText.trim()}`;
|
|
2655
|
+
}
|
|
2656
|
+
async function suggestPromptHandler(ctx, config, input) {
|
|
2657
|
+
const agentId = input?.agentId?.trim();
|
|
2658
|
+
if (!agentId) throw new ctx.NonRetriableError("agentId is required");
|
|
2659
|
+
const agent = toAgent(await ctx.api.get("agent", agentId));
|
|
2660
|
+
const promptName = agent.promptName;
|
|
2661
|
+
if (!promptName) throw new ctx.NonRetriableError(`Agent "${agentId}" has no promptName configured`);
|
|
2662
|
+
let currentContent;
|
|
2663
|
+
let promptVersion;
|
|
2664
|
+
try {
|
|
2665
|
+
const detail = await ctx.api.prompts.get(promptName, { label: "production", resolve: false });
|
|
2666
|
+
currentContent = detail.content;
|
|
2667
|
+
promptVersion = detail.version;
|
|
2668
|
+
} catch (err) {
|
|
2669
|
+
if (err instanceof AppApiError && err.status === 403) {
|
|
2670
|
+
throw new ctx.NonRetriableError(
|
|
2671
|
+
`Agent "${agentId}"'s prompt "${promptName}" is outside this app's prompts allowlist (role.prompts) \u2014 suggest-prompt cannot read it. ${err.message}`
|
|
2672
|
+
);
|
|
2673
|
+
}
|
|
2674
|
+
currentContent = agent.systemPromptSnapshot ?? "";
|
|
2675
|
+
promptVersion = agent.promptVersion;
|
|
2676
|
+
}
|
|
2677
|
+
const limit = Math.min(input?.maxComparisons ?? DEFAULT_MAX_COMPARISONS, DEFAULT_MAX_COMPARISONS);
|
|
2678
|
+
const page = await ctx.api.list("response-comparison", { filter: { agentId, promptName, promptVersion }, limit });
|
|
2679
|
+
const comparisons = page.items.map((r) => r.data);
|
|
2680
|
+
if (comparisons.length < MIN_COMPARISONS_REQUIRED) {
|
|
2681
|
+
throw new ctx.NonRetriableError(
|
|
2682
|
+
`Not enough comparison data (${comparisons.length} record(s), minimum ${MIN_COMPARISONS_REQUIRED} required)`
|
|
2683
|
+
);
|
|
2684
|
+
}
|
|
2685
|
+
const metaPromptName = resolvePromptName("suggest", config);
|
|
2686
|
+
const configuredFallback = config.defaults?.prompts?.suggest ?? DEFAULT_SUGGEST_META_PROMPT;
|
|
2687
|
+
let metaPromptContent = configuredFallback;
|
|
2688
|
+
try {
|
|
2689
|
+
metaPromptContent = (await ctx.api.prompts.get(metaPromptName, { label: "production" })).content || configuredFallback;
|
|
2690
|
+
} catch {
|
|
2691
|
+
}
|
|
2692
|
+
const userMessage = [
|
|
2693
|
+
"--- PROMPT SYST\xC8ME ACTUEL ---",
|
|
2694
|
+
currentContent,
|
|
2695
|
+
"--- FIN DU PROMPT SYST\xC8ME ---",
|
|
2696
|
+
"",
|
|
2697
|
+
`Voici ${comparisons.length} exemples comparant ce que l'IA a g\xE9n\xE9r\xE9 avec ce que l'agent a r\xE9ellement envoy\xE9 :`,
|
|
2698
|
+
"",
|
|
2699
|
+
comparisons.map((c, i) => comparisonBlock(i, c.generatedText, c.sentText)).join("\n\n---\n\n")
|
|
2700
|
+
].join("\n");
|
|
2701
|
+
const result = await ctx.api.llm.complete({
|
|
2702
|
+
messages: [
|
|
2703
|
+
{ role: "system", content: metaPromptContent },
|
|
2704
|
+
{ role: "user", content: userMessage }
|
|
2705
|
+
],
|
|
2706
|
+
options: { model: agent.modelId },
|
|
2707
|
+
promptRef: { name: metaPromptName, label: "production", resolve: false }
|
|
2708
|
+
});
|
|
2709
|
+
const suggestedContent = result.text.trim();
|
|
2710
|
+
if (!suggestedContent) throw new ctx.NonRetriableError("The model returned an empty suggestion");
|
|
2711
|
+
const referenceErrors = await validateReferences(ctx.api, suggestedContent, promptName);
|
|
2712
|
+
if (referenceErrors.length > 0) {
|
|
2713
|
+
throw new ctx.NonRetriableError(
|
|
2714
|
+
[
|
|
2715
|
+
`Suggested content has invalid reference tags: ${referenceErrors.join(" ")}`,
|
|
2716
|
+
"--- REJECTED CONTENT ---",
|
|
2717
|
+
suggestedContent
|
|
2718
|
+
].join("\n\n")
|
|
2719
|
+
);
|
|
2720
|
+
}
|
|
2721
|
+
let version;
|
|
2722
|
+
try {
|
|
2723
|
+
({ version } = await ctx.api.prompts.createVersion(promptName, {
|
|
2724
|
+
content: suggestedContent,
|
|
2725
|
+
tags: ["ai_suggested"]
|
|
2726
|
+
}));
|
|
2727
|
+
} catch (err) {
|
|
2728
|
+
if (err instanceof AppApiError && err.status === 403) {
|
|
2729
|
+
throw new ctx.NonRetriableError(
|
|
2730
|
+
[
|
|
2731
|
+
`Cannot save this suggestion: prompt "${promptName}" is outside this app's prompts allowlist (role.prompts). ${err.message}`,
|
|
2732
|
+
"--- REJECTED CONTENT ---",
|
|
2733
|
+
suggestedContent
|
|
2734
|
+
].join("\n\n")
|
|
2735
|
+
);
|
|
2736
|
+
}
|
|
2737
|
+
throw err;
|
|
2738
|
+
}
|
|
2739
|
+
return { promptName, version, comparisonCount: comparisons.length };
|
|
2740
|
+
}
|
|
2741
|
+
var DEFAULT_LIMIT2 = 50;
|
|
2742
|
+
var MAX_IMPROVEMENTS = 3;
|
|
2743
|
+
var DEFAULT_DIFF_ANALYSIS_META_PROMPT = [
|
|
2744
|
+
"Tu analyses des paires (r\xE9ponse g\xE9n\xE9r\xE9e par l'IA, r\xE9ponse r\xE9ellement envoy\xE9e par un agent humain) pour un assistant de support client.",
|
|
2745
|
+
"Identifie au maximum 3 patterns r\xE9currents de correction (ton, structure, longueur, formulations, niveau de d\xE9tail).",
|
|
2746
|
+
'R\xE9ponds uniquement avec un objet JSON {"improvements": string[]}, sans autre texte.'
|
|
2747
|
+
].join("\n");
|
|
2748
|
+
var RESPONSE_SCHEMA = {
|
|
2749
|
+
name: "diff_analysis",
|
|
2750
|
+
schema: {
|
|
2751
|
+
type: "object",
|
|
2752
|
+
properties: { improvements: { type: "array", items: { type: "string" } } },
|
|
2753
|
+
required: ["improvements"],
|
|
2754
|
+
additionalProperties: false
|
|
2755
|
+
}
|
|
2756
|
+
};
|
|
2757
|
+
function buildRunDiffAnalysisFunctionDef(config) {
|
|
2758
|
+
return {
|
|
2759
|
+
universalIdentifier: identifierFor(config, "run-diff-analysis"),
|
|
2760
|
+
name: "run-diff-analysis",
|
|
2761
|
+
trigger: { type: "uiInvoke", minRole: "EDITOR" },
|
|
2762
|
+
input: [
|
|
2763
|
+
{ universalIdentifier: RUN_DIFF_ANALYSIS_INPUT_AGENT_ID_UID, name: "agentId", type: FieldType.TEXT, label: "Agent id", isNullable: false },
|
|
2764
|
+
{ universalIdentifier: RUN_DIFF_ANALYSIS_INPUT_LIMIT_UID, name: "limit", type: FieldType.NUMBER, label: "Limit", isNullable: true }
|
|
2765
|
+
]
|
|
2766
|
+
};
|
|
2767
|
+
}
|
|
2768
|
+
function createRunDiffAnalysisHandler(config) {
|
|
2769
|
+
return (ctx, input) => runDiffAnalysisHandler(ctx, config, input);
|
|
2770
|
+
}
|
|
2771
|
+
async function runDiffAnalysisHandler(ctx, config, input) {
|
|
2772
|
+
const agentId = input?.agentId?.trim();
|
|
2773
|
+
if (!agentId) throw new ctx.NonRetriableError("agentId is required");
|
|
2774
|
+
const agent = toAgent(await ctx.api.get("agent", agentId));
|
|
2775
|
+
const promptName = agent.promptName;
|
|
2776
|
+
if (!promptName) throw new ctx.NonRetriableError(`Agent "${agentId}" has no promptName configured`);
|
|
2777
|
+
let promptVersion = agent.promptVersion ?? 0;
|
|
2778
|
+
try {
|
|
2779
|
+
promptVersion = (await ctx.api.prompts.get(promptName, { label: "production" })).version;
|
|
2780
|
+
} catch {
|
|
2781
|
+
}
|
|
2782
|
+
const limit = Math.min(input?.limit ?? DEFAULT_LIMIT2, DEFAULT_LIMIT2);
|
|
2783
|
+
const page = await ctx.api.list("response-comparison", { filter: { agentId, promptName, promptVersion }, limit });
|
|
2784
|
+
const pairs = page.items.map((r) => r.data).filter((c) => c.generatedText && c.generatedText.trim() !== c.sentText.trim());
|
|
2785
|
+
if (pairs.length === 0) {
|
|
2786
|
+
throw new ctx.NonRetriableError("No non-identical comparison found for this agent");
|
|
2787
|
+
}
|
|
2788
|
+
const metaPromptName = resolvePromptName("diff-analysis", config);
|
|
2789
|
+
const configuredFallback = config.defaults?.prompts?.["diff-analysis"] ?? DEFAULT_DIFF_ANALYSIS_META_PROMPT;
|
|
2790
|
+
let metaPromptContent = configuredFallback;
|
|
2791
|
+
try {
|
|
2792
|
+
metaPromptContent = (await ctx.api.prompts.get(metaPromptName, { label: "production" })).content || configuredFallback;
|
|
2793
|
+
} catch {
|
|
2794
|
+
}
|
|
2795
|
+
const userMessage = pairs.map((c, i) => `### Exemple ${i + 1}
|
|
2796
|
+
IA a g\xE9n\xE9r\xE9 :
|
|
2797
|
+
${(c.generatedText ?? "").trim()}
|
|
2798
|
+
|
|
2799
|
+
Agent a r\xE9ellement envoy\xE9 :
|
|
2800
|
+
${c.sentText.trim()}`).join("\n\n---\n\n");
|
|
2801
|
+
const result = await ctx.api.llm.complete({
|
|
2802
|
+
messages: [
|
|
2803
|
+
{ role: "system", content: metaPromptContent },
|
|
2804
|
+
{ role: "user", content: userMessage }
|
|
2805
|
+
],
|
|
2806
|
+
options: { model: agent.modelId, responseSchema: RESPONSE_SCHEMA },
|
|
2807
|
+
promptRef: { name: metaPromptName, label: "production", resolve: false }
|
|
2808
|
+
});
|
|
2809
|
+
let points;
|
|
2810
|
+
try {
|
|
2811
|
+
const parsed = JSON.parse(result.text);
|
|
2812
|
+
points = Array.isArray(parsed.improvements) ? parsed.improvements.filter((p) => typeof p === "string").slice(0, MAX_IMPROVEMENTS) : [];
|
|
2813
|
+
} catch {
|
|
2814
|
+
throw new ctx.NonRetriableError("The model returned an invalid JSON response");
|
|
2815
|
+
}
|
|
2816
|
+
await ctx.api.upsert(
|
|
2817
|
+
"diff-analysis",
|
|
2818
|
+
[
|
|
2819
|
+
{
|
|
2820
|
+
data: {
|
|
2821
|
+
agentId,
|
|
2822
|
+
promptName,
|
|
2823
|
+
promptVersion,
|
|
2824
|
+
points,
|
|
2825
|
+
uniqueKey: diffAnalysisUniqueKey(agentId, promptName, promptVersion)
|
|
2826
|
+
}
|
|
2827
|
+
}
|
|
2828
|
+
],
|
|
2829
|
+
{ uniqueBy: ["uniqueKey"] }
|
|
2830
|
+
);
|
|
2831
|
+
return { agentId, promptName, promptVersion, points, comparisonCount: pairs.length };
|
|
2832
|
+
}
|
|
2833
|
+
function buildListGorgiasViewsFunctionDef(config) {
|
|
2834
|
+
return {
|
|
2835
|
+
universalIdentifier: identifierFor(config, "list-gorgias-views"),
|
|
2836
|
+
name: "list-gorgias-views",
|
|
2837
|
+
trigger: { type: "uiInvoke", minRole: "VIEWER" },
|
|
2838
|
+
input: [
|
|
2839
|
+
{
|
|
2840
|
+
universalIdentifier: LIST_GORGIAS_VIEWS_INPUT_CHECK_APP_SLUGS_UID,
|
|
2841
|
+
name: "checkAppSlugs",
|
|
2842
|
+
type: FieldType.JSON,
|
|
2843
|
+
label: "Check app slugs",
|
|
2844
|
+
description: "string[] \u2014 other support-kit app slugs to check for a sourceViewId overlap.",
|
|
2845
|
+
isNullable: true
|
|
2846
|
+
}
|
|
2847
|
+
]
|
|
2848
|
+
};
|
|
2849
|
+
}
|
|
2850
|
+
function createListGorgiasViewsHandler(config) {
|
|
2851
|
+
return (ctx, input) => listGorgiasViewsHandler(ctx, config, input ?? {});
|
|
2852
|
+
}
|
|
2853
|
+
var PIPELINE_STATE_SINGLETON_KEY2 = "default";
|
|
2854
|
+
async function readClaimedView(ctx, appSlug) {
|
|
2855
|
+
try {
|
|
2856
|
+
const page = await ctx.api.crossApp.list(appSlug, "pipeline-state", { filter: { singletonKey: PIPELINE_STATE_SINGLETON_KEY2 }, limit: 1 });
|
|
2857
|
+
const sourceViewId = page.items[0]?.data.sourceViewId;
|
|
2858
|
+
return { ok: true, claimedViewId: typeof sourceViewId === "string" && sourceViewId.length > 0 ? sourceViewId : null };
|
|
2859
|
+
} catch {
|
|
2860
|
+
return { ok: false };
|
|
2861
|
+
}
|
|
2862
|
+
}
|
|
2863
|
+
async function listGorgiasViewsHandler(ctx, config, input) {
|
|
2864
|
+
const rawViews = await ctx.api.integrations.run("gorgias", "listViews", {});
|
|
2865
|
+
const views = rawViews.views.map((v) => ({ id: String(v.id), name: v.name }));
|
|
2866
|
+
const candidateSlugs = (input.checkAppSlugs ?? []).filter((slug) => slug && slug !== config.slug);
|
|
2867
|
+
const claimedByViewId = /* @__PURE__ */ new Map();
|
|
2868
|
+
const uncheckedAppSlugs = [];
|
|
2869
|
+
for (const slug of candidateSlugs) {
|
|
2870
|
+
const read = await readClaimedView(ctx, slug);
|
|
2871
|
+
if (!read.ok) {
|
|
2872
|
+
uncheckedAppSlugs.push(slug);
|
|
2873
|
+
continue;
|
|
2874
|
+
}
|
|
2875
|
+
if (read.claimedViewId === null) continue;
|
|
2876
|
+
const claimants = claimedByViewId.get(read.claimedViewId) ?? [];
|
|
2877
|
+
claimants.push(slug);
|
|
2878
|
+
claimedByViewId.set(read.claimedViewId, claimants);
|
|
2879
|
+
}
|
|
2880
|
+
return {
|
|
2881
|
+
views: views.map((v) => ({ id: v.id, name: v.name, claimedByAppSlugs: claimedByViewId.get(v.id) ?? [] })),
|
|
2882
|
+
uncheckedAppSlugs
|
|
2883
|
+
};
|
|
2884
|
+
}
|
|
2885
|
+
var PENDING_PROMPT_NAME = "agent/pending";
|
|
2886
|
+
function buildCreateAgentFunctionDef(config) {
|
|
2887
|
+
return {
|
|
2888
|
+
universalIdentifier: identifierFor(config, "create-agent"),
|
|
2889
|
+
name: "create-agent",
|
|
2890
|
+
trigger: { type: "uiInvoke", minRole: "EDITOR" },
|
|
2891
|
+
input: [
|
|
2892
|
+
{ universalIdentifier: CREATE_AGENT_INPUT_NAME_UID, name: "name", type: FieldType.TEXT, label: "Name", isNullable: false },
|
|
2893
|
+
{ universalIdentifier: CREATE_AGENT_INPUT_MODEL_ID_UID, name: "modelId", type: FieldType.TEXT, label: "Model id", isNullable: false },
|
|
2894
|
+
{ universalIdentifier: CREATE_AGENT_INPUT_PROVIDER_UID, name: "provider", type: FieldType.TEXT, label: "Provider", isNullable: true },
|
|
2895
|
+
{
|
|
2896
|
+
universalIdentifier: CREATE_AGENT_INPUT_SYSTEM_PROMPT_SNAPSHOT_UID,
|
|
2897
|
+
name: "systemPromptSnapshot",
|
|
2898
|
+
type: FieldType.TEXT,
|
|
2899
|
+
label: "System prompt snapshot",
|
|
2900
|
+
isNullable: true
|
|
2901
|
+
}
|
|
2902
|
+
]
|
|
2903
|
+
};
|
|
2904
|
+
}
|
|
2905
|
+
function createCreateAgentHandler() {
|
|
2906
|
+
return (ctx, input) => createAgentHandler(ctx, input ?? {});
|
|
2907
|
+
}
|
|
2908
|
+
async function createAgentHandler(ctx, input) {
|
|
2909
|
+
const name = input?.name?.trim();
|
|
2910
|
+
if (!name) throw new ctx.NonRetriableError("name is required");
|
|
2911
|
+
const modelId = input?.modelId?.trim();
|
|
2912
|
+
if (!modelId) throw new ctx.NonRetriableError("modelId is required");
|
|
2913
|
+
const created = await ctx.api.create("agent", {
|
|
2914
|
+
name,
|
|
2915
|
+
modelId,
|
|
2916
|
+
provider: input.provider?.trim() || DEFAULT_LLM_PROVIDER,
|
|
2917
|
+
status: "available",
|
|
2918
|
+
promptName: PENDING_PROMPT_NAME,
|
|
2919
|
+
...input.systemPromptSnapshot?.trim() ? { systemPromptSnapshot: input.systemPromptSnapshot.trim() } : {}
|
|
2920
|
+
});
|
|
2921
|
+
const withPromptName = await ctx.api.update("agent", created.id, { promptName: `agent/${created.id}` });
|
|
2922
|
+
return toAgent(withPromptName);
|
|
2923
|
+
}
|
|
2924
|
+
var DEFAULT_KEY_VALUE = "default";
|
|
2925
|
+
function buildSetDefaultAgentFunctionDef(config) {
|
|
2926
|
+
return {
|
|
2927
|
+
universalIdentifier: identifierFor(config, "set-default-agent"),
|
|
2928
|
+
name: "set-default-agent",
|
|
2929
|
+
trigger: { type: "uiInvoke", minRole: "EDITOR" },
|
|
2930
|
+
input: [
|
|
2931
|
+
{
|
|
2932
|
+
universalIdentifier: SET_DEFAULT_AGENT_INPUT_AGENT_ID_UID,
|
|
2933
|
+
name: "agentId",
|
|
2934
|
+
type: FieldType.TEXT,
|
|
2935
|
+
label: "Agent id",
|
|
2936
|
+
isNullable: false
|
|
2937
|
+
}
|
|
2938
|
+
]
|
|
2939
|
+
};
|
|
2940
|
+
}
|
|
2941
|
+
function createSetDefaultAgentHandler() {
|
|
2942
|
+
return (ctx, input) => setDefaultAgentHandler(ctx, input ?? {});
|
|
2943
|
+
}
|
|
2944
|
+
async function setDefaultAgentHandler(ctx, input) {
|
|
2945
|
+
const agentId = input?.agentId?.trim();
|
|
2946
|
+
if (!agentId) throw new ctx.NonRetriableError("agentId is required");
|
|
2947
|
+
const target = toAgent(await ctx.api.get("agent", agentId));
|
|
2948
|
+
if (target.status === "default") return target;
|
|
2949
|
+
const incumbentPage = await ctx.api.list("agent", { filter: { status: "default" }, limit: 1 });
|
|
2950
|
+
const incumbent = incumbentPage.items[0];
|
|
2951
|
+
if (incumbent && incumbent.id !== agentId) {
|
|
2952
|
+
await ctx.api.update("agent", incumbent.id, { status: "available", defaultKey: null });
|
|
2953
|
+
}
|
|
2954
|
+
const promoted = await ctx.api.update("agent", agentId, {
|
|
2955
|
+
status: "default",
|
|
2956
|
+
defaultKey: DEFAULT_KEY_VALUE
|
|
2957
|
+
});
|
|
2958
|
+
return toAgent(promoted);
|
|
2959
|
+
}
|
|
2960
|
+
var SHARED_PREFIX = "shared/";
|
|
2961
|
+
function buildCreateSharedPromptVersionFunctionDef(config) {
|
|
2962
|
+
return {
|
|
2963
|
+
universalIdentifier: identifierFor(config, "create-shared-prompt-version"),
|
|
2964
|
+
name: "create-shared-prompt-version",
|
|
2965
|
+
trigger: { type: "uiInvoke", minRole: "EDITOR" },
|
|
2966
|
+
input: [
|
|
2967
|
+
{
|
|
2968
|
+
universalIdentifier: CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID,
|
|
2969
|
+
name: "name",
|
|
2970
|
+
type: FieldType.TEXT,
|
|
2971
|
+
label: "Prompt name",
|
|
2972
|
+
isNullable: false
|
|
2973
|
+
},
|
|
2974
|
+
{
|
|
2975
|
+
universalIdentifier: CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID,
|
|
2976
|
+
name: "content",
|
|
2977
|
+
type: FieldType.TEXT,
|
|
2978
|
+
label: "Content",
|
|
2979
|
+
isNullable: false
|
|
2980
|
+
}
|
|
2981
|
+
]
|
|
2982
|
+
};
|
|
2983
|
+
}
|
|
2984
|
+
function createCreateSharedPromptVersionHandler() {
|
|
2985
|
+
return (ctx, input) => createSharedPromptVersionHandler(
|
|
2986
|
+
ctx,
|
|
2987
|
+
input ?? { name: "", content: "" }
|
|
2988
|
+
);
|
|
2989
|
+
}
|
|
2990
|
+
async function createSharedPromptVersionHandler(ctx, input) {
|
|
2991
|
+
const name = input?.name?.trim();
|
|
2992
|
+
if (!name) throw new ctx.NonRetriableError("name is required");
|
|
2993
|
+
if (!name.startsWith(SHARED_PREFIX)) {
|
|
2994
|
+
throw new ctx.NonRetriableError(
|
|
2995
|
+
`"${name}" is not a shared/* prompt \u2014 create-shared-prompt-version only writes the shared/* library.`
|
|
2996
|
+
);
|
|
2997
|
+
}
|
|
2998
|
+
const content = input?.content ?? "";
|
|
2999
|
+
if (!content.trim()) throw new ctx.NonRetriableError("content is required");
|
|
3000
|
+
const referenceErrors = await validateReferences(ctx.api, content, name);
|
|
3001
|
+
if (referenceErrors.length > 0) {
|
|
3002
|
+
throw new ctx.NonRetriableError(`Invalid reference tags: ${referenceErrors.join(" ")}`);
|
|
3003
|
+
}
|
|
3004
|
+
return ctx.api.prompts.createVersion(name, { content });
|
|
3005
|
+
}
|
|
3006
|
+
function buildSyncAgentPromptSnapshotFunctionDef(config) {
|
|
3007
|
+
return {
|
|
3008
|
+
universalIdentifier: identifierFor(config, "sync-agent-prompt-snapshot"),
|
|
3009
|
+
name: "sync-agent-prompt-snapshot",
|
|
3010
|
+
trigger: { type: "uiInvoke", minRole: "EDITOR" },
|
|
3011
|
+
input: [
|
|
3012
|
+
{
|
|
3013
|
+
universalIdentifier: SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID,
|
|
3014
|
+
name: "promptName",
|
|
3015
|
+
type: FieldType.TEXT,
|
|
3016
|
+
label: "Prompt name",
|
|
3017
|
+
isNullable: false
|
|
3018
|
+
}
|
|
3019
|
+
]
|
|
3020
|
+
};
|
|
3021
|
+
}
|
|
3022
|
+
function createSyncAgentPromptSnapshotHandler() {
|
|
3023
|
+
return (ctx, input) => syncAgentPromptSnapshotHandler(
|
|
3024
|
+
ctx,
|
|
3025
|
+
input ?? { promptName: "" }
|
|
3026
|
+
);
|
|
3027
|
+
}
|
|
3028
|
+
async function syncAgentPromptSnapshotHandler(ctx, input) {
|
|
3029
|
+
const promptName = input?.promptName?.trim();
|
|
3030
|
+
if (!promptName) throw new ctx.NonRetriableError("promptName is required");
|
|
3031
|
+
const page = await ctx.api.list("agent", { filter: { promptName }, limit: 1 });
|
|
3032
|
+
const record = page.items[0];
|
|
3033
|
+
if (!record) return { updated: false };
|
|
3034
|
+
const agent = toAgent(record);
|
|
3035
|
+
try {
|
|
3036
|
+
const ref = agent.promptVersion !== null ? { version: agent.promptVersion } : { label: agent.promptLabel ?? "production" };
|
|
3037
|
+
const detail = await ctx.api.prompts.get(promptName, { ...ref, resolve: false });
|
|
3038
|
+
if (detail.content === agent.systemPromptSnapshot) return { updated: false };
|
|
3039
|
+
await ctx.api.update("agent", agent.id, { systemPromptSnapshot: detail.content });
|
|
3040
|
+
return { updated: true };
|
|
3041
|
+
} catch (error) {
|
|
3042
|
+
ctx.logger.warn(
|
|
3043
|
+
`sync-agent-prompt-snapshot: could not refresh "${promptName}" \u2014 GET /models keeps serving the previous snapshot (${String(error)})`
|
|
3044
|
+
);
|
|
3045
|
+
return { updated: false };
|
|
3046
|
+
}
|
|
3047
|
+
}
|
|
3048
|
+
|
|
3049
|
+
// src/functions/ext-models.ts
|
|
3050
|
+
var TOKEN_APPROXIMATION_CHARS_PER_TOKEN = 4;
|
|
3051
|
+
var AGENT_PAGE_SIZE = 500;
|
|
3052
|
+
function buildExtModelsFunctionDef(config) {
|
|
3053
|
+
return {
|
|
3054
|
+
universalIdentifier: identifierFor(config, "ext-models"),
|
|
3055
|
+
name: "ext-models",
|
|
3056
|
+
trigger: { type: "uiInvoke", minRole: "VIEWER" }
|
|
3057
|
+
};
|
|
3058
|
+
}
|
|
3059
|
+
function createExtModelsHandler() {
|
|
3060
|
+
return (ctx) => extModelsHandler(ctx);
|
|
3061
|
+
}
|
|
3062
|
+
async function extModelsHandler(ctx) {
|
|
3063
|
+
const page = await ctx.api.list("agent", { limit: AGENT_PAGE_SIZE });
|
|
3064
|
+
if (page.items.length >= AGENT_PAGE_SIZE) {
|
|
3065
|
+
ctx.logger.warn(`ext-models: "agent" page came back full at ${page.items.length} rows \u2014 some may be silently missing from the response.`);
|
|
3066
|
+
}
|
|
3067
|
+
return page.items.map(toAgent).filter((agent) => agent.status !== "archived").sort((a, b) => a.status === b.status ? a.name.localeCompare(b.name) : a.status.localeCompare(b.status)).map((agent) => {
|
|
3068
|
+
const systemPrompt = agent.systemPromptSnapshot ?? "";
|
|
3069
|
+
return {
|
|
3070
|
+
_id: agent.id,
|
|
3071
|
+
name: agent.name,
|
|
3072
|
+
provider: agent.provider,
|
|
3073
|
+
model_id: agent.modelId,
|
|
3074
|
+
system_prompt: systemPrompt,
|
|
3075
|
+
system_prompt_token_count: approximateTokenCount(systemPrompt),
|
|
3076
|
+
status: agent.status
|
|
3077
|
+
};
|
|
3078
|
+
});
|
|
3079
|
+
}
|
|
3080
|
+
function approximateTokenCount(text) {
|
|
3081
|
+
return Math.ceil(text.length / TOKEN_APPROXIMATION_CHARS_PER_TOKEN);
|
|
3082
|
+
}
|
|
3083
|
+
|
|
3084
|
+
// src/functions/ext-categories.ts
|
|
3085
|
+
var CATEGORY_PAGE_SIZE = 500;
|
|
3086
|
+
var AGENT_PAGE_SIZE2 = 500;
|
|
3087
|
+
function buildExtCategoriesFunctionDef(config) {
|
|
3088
|
+
return {
|
|
3089
|
+
universalIdentifier: identifierFor(config, "ext-categories"),
|
|
3090
|
+
name: "ext-categories",
|
|
3091
|
+
trigger: { type: "uiInvoke", minRole: "VIEWER" }
|
|
3092
|
+
};
|
|
3093
|
+
}
|
|
3094
|
+
function createExtCategoriesHandler() {
|
|
3095
|
+
return (ctx) => extCategoriesHandler(ctx);
|
|
3096
|
+
}
|
|
3097
|
+
async function extCategoriesHandler(ctx) {
|
|
3098
|
+
const [categoriesPage, groupsPage, agentsPage] = await Promise.all([
|
|
3099
|
+
ctx.api.list("category", { limit: CATEGORY_PAGE_SIZE }),
|
|
3100
|
+
ctx.api.list("category-group", { limit: CATEGORY_PAGE_SIZE }),
|
|
3101
|
+
// M7: ONE bulk read, not one `ctx.api.get` per category — this endpoint
|
|
3102
|
+
// runs on the same "every ticket change, every agent" cadence §5.2
|
|
3103
|
+
// documents for `/models` (which already does this), inside the
|
|
3104
|
+
// gateway's shared `FAN_OUT_BUDGET_MS`, so N+1 sequential round trips
|
|
3105
|
+
// risk a slow tenant's whole categories response silently dropping out
|
|
3106
|
+
// of the union on budget exhaustion.
|
|
3107
|
+
ctx.api.list("agent", { limit: AGENT_PAGE_SIZE2 })
|
|
3108
|
+
]);
|
|
3109
|
+
warnIfTruncated(ctx, "category", categoriesPage.items.length, CATEGORY_PAGE_SIZE);
|
|
3110
|
+
warnIfTruncated(ctx, "agent", agentsPage.items.length, AGENT_PAGE_SIZE2);
|
|
3111
|
+
const groupOrderById = new Map(groupsPage.items.map(toCategoryGroup).map((g) => [g.id, g.order]));
|
|
3112
|
+
const agentById = new Map(agentsPage.items.map((record) => [record.id, toAgent(record)]));
|
|
3113
|
+
const entries = [];
|
|
3114
|
+
for (const category of categoriesPage.items.map(toCategory)) {
|
|
3115
|
+
if (!category.agentId) continue;
|
|
3116
|
+
const agent = agentById.get(category.agentId);
|
|
3117
|
+
if (!agent) continue;
|
|
3118
|
+
if (agent.status === "archived") continue;
|
|
3119
|
+
const groupOrder = category.groupId ? groupOrderById.get(category.groupId) ?? -Infinity : -Infinity;
|
|
3120
|
+
entries.push({ category, agent, groupOrder });
|
|
3121
|
+
}
|
|
3122
|
+
entries.sort((a, b) => {
|
|
3123
|
+
if (a.groupOrder !== b.groupOrder) return a.groupOrder - b.groupOrder;
|
|
3124
|
+
if (a.category.order !== b.category.order) return a.category.order - b.category.order;
|
|
3125
|
+
return a.category.name.localeCompare(b.category.name);
|
|
3126
|
+
});
|
|
3127
|
+
return entries.map(({ category, agent }, index) => ({
|
|
3128
|
+
_id: category.id,
|
|
3129
|
+
name: category.name,
|
|
3130
|
+
tag_name: category.tagName,
|
|
3131
|
+
// M4: this category's own POSITION in the fully sorted sequence, not
|
|
3132
|
+
// `category.order` verbatim — see this module's own doc.
|
|
3133
|
+
order: index,
|
|
3134
|
+
agent: { _id: agent.id, name: agent.name, model_id: agent.modelId, provider: agent.provider }
|
|
3135
|
+
}));
|
|
3136
|
+
}
|
|
3137
|
+
function warnIfTruncated(ctx, objectKey, itemCount, pageSize) {
|
|
3138
|
+
if (itemCount >= pageSize) {
|
|
3139
|
+
ctx.logger.warn(`ext-categories: "${objectKey}" page came back full at ${itemCount} rows \u2014 some may be silently missing from the response.`);
|
|
3140
|
+
}
|
|
3141
|
+
}
|
|
3142
|
+
|
|
3143
|
+
// src/functions/ownership-probe.ts
|
|
3144
|
+
async function ownsAgent(ctx, id) {
|
|
3145
|
+
if (!id) return null;
|
|
3146
|
+
const record = await getOptional(ctx, "agent", id);
|
|
3147
|
+
return record ? { claimed: true } : null;
|
|
3148
|
+
}
|
|
3149
|
+
|
|
3150
|
+
// src/functions/support-extension-envelope.ts
|
|
3151
|
+
function readSupportExtensionEnvelope(ctx) {
|
|
3152
|
+
const raw = ctx.event?.supportExtension;
|
|
3153
|
+
return {
|
|
3154
|
+
userId: typeof raw?.userId === "string" ? raw.userId : "",
|
|
3155
|
+
phase: raw?.phase === "probe" ? "probe" : "execute"
|
|
3156
|
+
};
|
|
3157
|
+
}
|
|
3158
|
+
|
|
3159
|
+
// src/functions/ext-chat.ts
|
|
3160
|
+
var DEFAULT_AGENT_FILTER = { status: "default" };
|
|
3161
|
+
function buildExtChatFunctionDef(config) {
|
|
3162
|
+
return {
|
|
3163
|
+
universalIdentifier: identifierFor(config, "ext-chat"),
|
|
3164
|
+
name: "ext-chat",
|
|
3165
|
+
trigger: { type: "uiInvoke", minRole: "VIEWER" },
|
|
3166
|
+
input: [
|
|
3167
|
+
{
|
|
3168
|
+
universalIdentifier: EXT_CHAT_INPUT_MESSAGES_UID,
|
|
3169
|
+
name: "messages",
|
|
3170
|
+
type: FieldType.JSON,
|
|
3171
|
+
label: "Messages",
|
|
3172
|
+
description: "[{role, content}] \u2014 required unless gorgiasTicketId is given.",
|
|
3173
|
+
isNullable: true,
|
|
3174
|
+
defaultValue: null
|
|
3175
|
+
},
|
|
3176
|
+
{
|
|
3177
|
+
universalIdentifier: EXT_CHAT_INPUT_MODEL_ID_UID,
|
|
3178
|
+
name: "modelId",
|
|
3179
|
+
type: FieldType.TEXT,
|
|
3180
|
+
label: "Model id",
|
|
3181
|
+
description: 'Absent falls back to the single status="default" agent.',
|
|
3182
|
+
isNullable: true,
|
|
3183
|
+
defaultValue: null
|
|
3184
|
+
},
|
|
3185
|
+
{
|
|
3186
|
+
universalIdentifier: EXT_CHAT_INPUT_AGENT_NAME_UID,
|
|
3187
|
+
name: "agentName",
|
|
3188
|
+
type: FieldType.TEXT,
|
|
3189
|
+
label: "Agent name",
|
|
3190
|
+
isNullable: true,
|
|
3191
|
+
defaultValue: null
|
|
3192
|
+
},
|
|
3193
|
+
{
|
|
3194
|
+
universalIdentifier: EXT_CHAT_INPUT_GORGIAS_TICKET_ID_UID,
|
|
3195
|
+
name: "gorgiasTicketId",
|
|
3196
|
+
type: FieldType.TEXT,
|
|
3197
|
+
label: "Gorgias ticket id",
|
|
3198
|
+
isNullable: true,
|
|
3199
|
+
defaultValue: null
|
|
3200
|
+
}
|
|
3201
|
+
]
|
|
3202
|
+
};
|
|
3203
|
+
}
|
|
3204
|
+
function createExtChatHandler() {
|
|
3205
|
+
return (ctx, input) => extChatHandler(ctx, input ?? {});
|
|
3206
|
+
}
|
|
3207
|
+
async function extChatHandler(ctx, input) {
|
|
3208
|
+
const envelope = readSupportExtensionEnvelope(ctx);
|
|
3209
|
+
if (envelope.phase === "probe") return probeChatOwnership(ctx, input.modelId ?? null);
|
|
3210
|
+
return executeChat(ctx, envelope.userId, input);
|
|
3211
|
+
}
|
|
3212
|
+
async function probeChatOwnership(ctx, modelId) {
|
|
3213
|
+
if (modelId) return ownsAgent(ctx, modelId);
|
|
3214
|
+
const page = await ctx.api.list("agent", { filter: DEFAULT_AGENT_FILTER, limit: 1 });
|
|
3215
|
+
return page.items.length > 0 ? { claimed: true } : null;
|
|
3216
|
+
}
|
|
3217
|
+
async function executeChat(ctx, userId, input) {
|
|
3218
|
+
const contextMessages = await resolveMessages(ctx, input);
|
|
3219
|
+
const agent = await resolveAgent(ctx, input.modelId ?? null);
|
|
3220
|
+
const promptPort = createPlatformPromptPort(ctx.api, (message) => ctx.logger.warn(message));
|
|
3221
|
+
const promptRef = draftPromptRefFor(agent, { promptPrefix: "" });
|
|
3222
|
+
const resolvedPrompt = await promptPort.resolve(promptRef);
|
|
3223
|
+
const systemContent = applySignature(resolvedPrompt.text, input.agentName ?? void 0);
|
|
3224
|
+
const chatMessages = systemContent ? [{ role: "system", content: systemContent }, ...contextMessages] : contextMessages;
|
|
3225
|
+
const result = await ctx.api.llm.complete({
|
|
3226
|
+
messages: chatMessages,
|
|
3227
|
+
// H3/I16: the resolved Langfuse prompt's own model config WINS over the
|
|
3228
|
+
// agent's fallback modelId — every ported graph node applies this same
|
|
3229
|
+
// rule (`draft.ts`, `triage.ts`, …); this was the one `PromptPort
|
|
3230
|
+
// .resolve` consumer in the repo that dropped it.
|
|
3231
|
+
options: { model: resolvedPrompt.config?.model ?? agent.modelId },
|
|
3232
|
+
// Link-only (D-LF follow-up, option (b)): this function already resolved
|
|
3233
|
+
// its own prompt two lines above via `PromptPort` — `resolve: false`
|
|
3234
|
+
// links the completion to it in Langfuse WITHOUT re-triggering the
|
|
3235
|
+
// platform's own resolution (no `manifest.prompts[]` gate, no
|
|
3236
|
+
// system-message replacement of the `applySignature`-signed message just
|
|
3237
|
+
// composed above). `label` is the REAL resolved label — `promptRef
|
|
3238
|
+
// .label`, i.e. `agent.promptLabel ?? 'production'`
|
|
3239
|
+
// (`functions/records.ts`'s `draftPromptRefFor`) — not a hardcoded
|
|
3240
|
+
// 'production', so a staging-labelled agent's traces say so instead of
|
|
3241
|
+
// silently attributing to production.
|
|
3242
|
+
promptRef: {
|
|
3243
|
+
name: resolvedPrompt.name,
|
|
3244
|
+
version: resolvedPrompt.version,
|
|
3245
|
+
label: promptRef.label,
|
|
3246
|
+
resolve: false
|
|
3247
|
+
},
|
|
3248
|
+
trace: {
|
|
3249
|
+
sessionId: input.gorgiasTicketId ?? void 0,
|
|
3250
|
+
metadata: {
|
|
3251
|
+
// L2: the agent's own identity — `ctx.api.llm.complete`'s `trace`
|
|
3252
|
+
// has no dedicated `userId` field (unlike `graph/ports.ts`'s
|
|
3253
|
+
// `CompletionRequest`), only `metadata`. The prompt identity itself
|
|
3254
|
+
// no longer needs to travel here — `promptRef` above carries it.
|
|
3255
|
+
userId,
|
|
3256
|
+
model: agent.modelId,
|
|
3257
|
+
...input.gorgiasTicketId ? { ticketId: input.gorgiasTicketId } : {}
|
|
3258
|
+
}
|
|
3259
|
+
}
|
|
3260
|
+
});
|
|
3261
|
+
const answer = result.text?.trim();
|
|
3262
|
+
if (!answer) throw new ctx.NonRetriableError("Provider returned an empty response");
|
|
3263
|
+
return {
|
|
3264
|
+
answer,
|
|
3265
|
+
modelId: agent.id,
|
|
3266
|
+
langfuse_trace_id: result.traceId ?? null,
|
|
3267
|
+
langfuse_observation_id: result.observationId ?? null,
|
|
3268
|
+
prompt_name: resolvedPrompt.name,
|
|
3269
|
+
prompt_version: resolvedPrompt.version
|
|
3270
|
+
};
|
|
3271
|
+
}
|
|
3272
|
+
async function resolveMessages(ctx, input) {
|
|
3273
|
+
if (input.gorgiasTicketId) {
|
|
3274
|
+
const raw = await runBuildTicketContext(ctx, input.gorgiasTicketId);
|
|
3275
|
+
if (!Array.isArray(raw.messages) || raw.messages.length === 0) {
|
|
3276
|
+
throw new ctx.NonRetriableError(`No usable messages extracted for Gorgias ticket ${input.gorgiasTicketId}`);
|
|
3277
|
+
}
|
|
3278
|
+
return raw.messages.map((m) => toWireChatMessage(m));
|
|
3279
|
+
}
|
|
3280
|
+
if (Array.isArray(input.messages) && input.messages.length > 0) {
|
|
3281
|
+
return input.messages.map((m) => toWireChatMessage(m));
|
|
3282
|
+
}
|
|
3283
|
+
throw new ctx.NonRetriableError("`messages` must be a non-empty array, or provide `gorgiasTicketId`");
|
|
3284
|
+
}
|
|
3285
|
+
async function runBuildTicketContext(ctx, ticketId) {
|
|
3286
|
+
try {
|
|
3287
|
+
return await ctx.api.integrations.run("gorgias", "buildTicketContext", { ticketId });
|
|
3288
|
+
} catch (err) {
|
|
3289
|
+
if (isGorgiasNotFound(err)) {
|
|
3290
|
+
throw new ctx.NonRetriableError(`Gorgias ticket ${ticketId} not found`);
|
|
3291
|
+
}
|
|
3292
|
+
throw err;
|
|
3293
|
+
}
|
|
3294
|
+
}
|
|
3295
|
+
function isGorgiasNotFound(err) {
|
|
3296
|
+
if (typeof err !== "object" || err === null) return false;
|
|
3297
|
+
const { status } = err;
|
|
3298
|
+
return status === 404;
|
|
3299
|
+
}
|
|
3300
|
+
function toWireChatMessage(raw) {
|
|
3301
|
+
const role = raw.role;
|
|
3302
|
+
if (role !== "system" && role !== "user" && role !== "assistant") {
|
|
3303
|
+
throw new Error(`ext-chat: message role must be "system", "user" or "assistant", got ${JSON.stringify(role)}`);
|
|
3304
|
+
}
|
|
3305
|
+
return { role, content: typeof raw.content === "string" ? raw.content : "" };
|
|
3306
|
+
}
|
|
3307
|
+
async function resolveAgent(ctx, modelId) {
|
|
3308
|
+
if (modelId) {
|
|
3309
|
+
const record2 = await getOptional(ctx, "agent", modelId);
|
|
3310
|
+
if (!record2) throw new ctx.NonRetriableError(`Model not found (id=${modelId})`);
|
|
3311
|
+
return toAgent(record2);
|
|
3312
|
+
}
|
|
3313
|
+
const page = await ctx.api.list("agent", { filter: DEFAULT_AGENT_FILTER, limit: 1 });
|
|
3314
|
+
const record = page.items[0];
|
|
3315
|
+
if (!record) throw new ctx.NonRetriableError("No default model configured");
|
|
3316
|
+
return toAgent(record);
|
|
3317
|
+
}
|
|
3318
|
+
var SERVED_TO_CAP = 500;
|
|
3319
|
+
var MAX_SERVE_ATTEMPTS = 3;
|
|
3320
|
+
function buildExtFastResponseCheckFunctionDef(config) {
|
|
3321
|
+
return {
|
|
3322
|
+
universalIdentifier: identifierFor(config, "ext-fast-response-check"),
|
|
3323
|
+
name: "ext-fast-response-check",
|
|
3324
|
+
trigger: { type: "uiInvoke", minRole: "VIEWER" },
|
|
3325
|
+
input: [
|
|
3326
|
+
{
|
|
3327
|
+
universalIdentifier: EXT_FAST_RESPONSE_CHECK_INPUT_TICKET_ID_UID,
|
|
3328
|
+
name: "ticket_id",
|
|
3329
|
+
type: FieldType.TEXT,
|
|
3330
|
+
label: "Ticket id",
|
|
3331
|
+
isNullable: false
|
|
3332
|
+
}
|
|
3333
|
+
]
|
|
3334
|
+
};
|
|
3335
|
+
}
|
|
3336
|
+
function createExtFastResponseCheckHandler() {
|
|
3337
|
+
return (ctx, input) => extFastResponseCheckHandler(ctx, input);
|
|
3338
|
+
}
|
|
3339
|
+
var NOT_AVAILABLE = { available: false };
|
|
3340
|
+
async function extFastResponseCheckHandler(ctx, input) {
|
|
3341
|
+
const ticketId = typeof input?.ticket_id === "string" ? input.ticket_id.trim() : "";
|
|
3342
|
+
if (!ticketId) throw new ctx.NonRetriableError("`ticket_id` must be a non-empty string");
|
|
3343
|
+
const page = await ctx.api.list("generated-response", { filter: { ticketId, status: "ready" }, limit: 1 });
|
|
3344
|
+
const row = page.items[0];
|
|
3345
|
+
if (!row) {
|
|
3346
|
+
logReason(ctx, ticketId, "no_ready_job");
|
|
3347
|
+
return NOT_AVAILABLE;
|
|
3348
|
+
}
|
|
3349
|
+
const generatedResponse = toGeneratedResponse(row);
|
|
3350
|
+
const now = /* @__PURE__ */ new Date();
|
|
3351
|
+
const expiresAt = toDate(generatedResponse.expiresAt);
|
|
3352
|
+
if (expiresAt && expiresAt.getTime() < now.getTime()) {
|
|
3353
|
+
logReason(ctx, ticketId, "expired");
|
|
3354
|
+
await flipStatus(ctx, row.id, ticketId, "expired");
|
|
3355
|
+
return NOT_AVAILABLE;
|
|
3356
|
+
}
|
|
3357
|
+
let rawTicket;
|
|
3358
|
+
try {
|
|
3359
|
+
const fetched = await ctx.api.integrations.run("gorgias", "getRawTicket", { ticketId });
|
|
3360
|
+
if (!fetched.ticket || !fetched.ticket.messages || fetched.ticket.messages.length === 0) {
|
|
3361
|
+
logReason(ctx, ticketId, "gorgias_fetch_failed", "empty or missing ticket.messages");
|
|
3362
|
+
return NOT_AVAILABLE;
|
|
3363
|
+
}
|
|
3364
|
+
rawTicket = fetched.ticket;
|
|
3365
|
+
} catch (err) {
|
|
3366
|
+
logReason(ctx, ticketId, "gorgias_fetch_failed", err instanceof Error ? err.message : String(err));
|
|
3367
|
+
return NOT_AVAILABLE;
|
|
3368
|
+
}
|
|
3369
|
+
const divergence = checkDivergence(rawTicket, generatedResponse);
|
|
3370
|
+
if (divergence.diverged) {
|
|
3371
|
+
logReason(ctx, ticketId, `diverged[count(snap=${divergence.snappedCount},now=${divergence.count}),date(snap=${isoOrNull(divergence.snappedLastAt)},now=${isoOrNull(divergence.lastAt)})]`);
|
|
3372
|
+
await flipStatus(ctx, row.id, ticketId, "invalidated");
|
|
3373
|
+
return NOT_AVAILABLE;
|
|
3374
|
+
}
|
|
3375
|
+
const envelope = readSupportExtensionEnvelope(ctx);
|
|
3376
|
+
if (!envelope.userId) {
|
|
3377
|
+
throw new ctx.NonRetriableError("ext-fast-response-check: missing platform user id in the invocation envelope");
|
|
3378
|
+
}
|
|
3379
|
+
const served = await serveHit(ctx, row, envelope.userId, now);
|
|
3380
|
+
if (!served) {
|
|
3381
|
+
logReason(ctx, ticketId, "race_lost");
|
|
3382
|
+
return NOT_AVAILABLE;
|
|
3383
|
+
}
|
|
3384
|
+
const servedResponse = toGeneratedResponse(served);
|
|
3385
|
+
logReason(ctx, ticketId, `hit served_count=${servedResponse.servedCount}`);
|
|
3386
|
+
if (servedResponse.servedCount > SERVED_TO_CAP) {
|
|
3387
|
+
ctx.logger.warn(`ext-fast-response-check: ticket=${ticketId} servedTo capped at ${SERVED_TO_CAP} entries (served_count=${servedResponse.servedCount})`);
|
|
3388
|
+
}
|
|
3389
|
+
return buildAvailableResponse(ctx, servedResponse);
|
|
3390
|
+
}
|
|
3391
|
+
function logReason(ctx, ticketId, reason, detail) {
|
|
3392
|
+
const suffix = detail ? ` detail=${JSON.stringify(detail)}` : "";
|
|
3393
|
+
ctx.logger.info(`ext-fast-response-check: ticket=${ticketId} reason=${reason}${suffix}`);
|
|
3394
|
+
}
|
|
3395
|
+
function isoOrNull(date) {
|
|
3396
|
+
return date ? date.toISOString() : "null";
|
|
3397
|
+
}
|
|
3398
|
+
function checkDivergence(rawTicket, generatedResponse) {
|
|
3399
|
+
const snapshot = snapshotConversation(rawTicket);
|
|
3400
|
+
const snappedCount = generatedResponse.generatedMessageCount;
|
|
3401
|
+
const snappedLastAt = toDate(generatedResponse.generatedLastMessageAt);
|
|
3402
|
+
const divergedByCount = snapshot.count > snappedCount;
|
|
3403
|
+
const divergedByDate = !!snapshot.lastAt && (!snappedLastAt || snapshot.lastAt.getTime() > snappedLastAt.getTime());
|
|
3404
|
+
return { diverged: divergedByCount || divergedByDate, count: snapshot.count, lastAt: snapshot.lastAt, snappedCount, snappedLastAt };
|
|
3405
|
+
}
|
|
3406
|
+
async function flipStatus(ctx, id, ticketId, status) {
|
|
3407
|
+
await transitionGeneratedResponse(ctx.api, { id, ticketId, from: "ready", to: status });
|
|
3408
|
+
}
|
|
3409
|
+
async function serveHit(ctx, row, userId, now) {
|
|
3410
|
+
let current = row;
|
|
3411
|
+
for (let attempt = 0; attempt < MAX_SERVE_ATTEMPTS; attempt++) {
|
|
3412
|
+
const currentData = toGeneratedResponse(current);
|
|
3413
|
+
const { servedCount, servedTo } = currentData;
|
|
3414
|
+
const nextServedTo = servedCount < SERVED_TO_CAP ? [...servedTo, { user: userId, at: now.toISOString() }] : servedTo;
|
|
3415
|
+
try {
|
|
3416
|
+
return await ctx.api.update(
|
|
3417
|
+
"generated-response",
|
|
3418
|
+
current.id,
|
|
3419
|
+
{ servedCount: servedCount + 1, servedTo: nextServedTo },
|
|
3420
|
+
{ ifMatch: { servedCount } }
|
|
3421
|
+
);
|
|
3422
|
+
} catch (err) {
|
|
3423
|
+
if (!(err instanceof AppApiError) || err.status !== 409) throw err;
|
|
3424
|
+
const fresh = await getOptional(ctx, "generated-response", current.id);
|
|
3425
|
+
const freshStatus = fresh ? fresh.data.status : void 0;
|
|
3426
|
+
if (!fresh || !isGeneratedResponseStatus(freshStatus) || freshStatus !== "ready") return null;
|
|
3427
|
+
current = fresh;
|
|
3428
|
+
}
|
|
3429
|
+
}
|
|
3430
|
+
return null;
|
|
3431
|
+
}
|
|
3432
|
+
async function buildAvailableResponse(ctx, generatedResponse) {
|
|
3433
|
+
const category = await resolveCategoryRef(ctx, generatedResponse.categoryId);
|
|
3434
|
+
const agent = await resolveAgentRef(ctx, generatedResponse.agentId);
|
|
3435
|
+
const generatedAt = toDate(generatedResponse.generatedAt);
|
|
3436
|
+
if (!generatedAt) {
|
|
3437
|
+
throw new ctx.NonRetriableError(`generated-response ${generatedResponse.id} is ready but has no generatedAt`);
|
|
3438
|
+
}
|
|
3439
|
+
const verdictValue = isEvaluationVerdict(generatedResponse.verdict?.verdict) ? generatedResponse.verdict.verdict : null;
|
|
3440
|
+
return {
|
|
3441
|
+
available: true,
|
|
3442
|
+
response: generatedResponse.responseText ?? "",
|
|
3443
|
+
category,
|
|
3444
|
+
agent,
|
|
3445
|
+
langfuse_trace_id: generatedResponse.langfuseTraceId,
|
|
3446
|
+
langfuse_observation_id: generatedResponse.langfuseObservationId,
|
|
3447
|
+
prompt_name: generatedResponse.promptName,
|
|
3448
|
+
prompt_version: generatedResponse.promptVersion,
|
|
3449
|
+
generated_at: generatedAt.toISOString(),
|
|
3450
|
+
followup_required: requiresFollowup(verdictValue)
|
|
3451
|
+
};
|
|
3452
|
+
}
|
|
3453
|
+
async function resolveCategoryRef(ctx, categoryId) {
|
|
3454
|
+
if (!categoryId) return null;
|
|
3455
|
+
const record = await getOptional(ctx, "category", categoryId);
|
|
3456
|
+
if (!record) return null;
|
|
3457
|
+
const category = toCategory(record);
|
|
3458
|
+
return { _id: category.id, name: category.name };
|
|
3459
|
+
}
|
|
3460
|
+
async function resolveAgentRef(ctx, agentId) {
|
|
3461
|
+
if (!agentId) return null;
|
|
3462
|
+
const record = await getOptional(ctx, "agent", agentId);
|
|
3463
|
+
if (!record) return null;
|
|
3464
|
+
const agent = toAgent(record);
|
|
3465
|
+
return { _id: agent.id, name: agent.name, model_id: agent.modelId };
|
|
3466
|
+
}
|
|
3467
|
+
function buildExtEvaluationFunctionDef(config) {
|
|
3468
|
+
return {
|
|
3469
|
+
universalIdentifier: identifierFor(config, "ext-evaluation"),
|
|
3470
|
+
name: "ext-evaluation",
|
|
3471
|
+
trigger: { type: "uiInvoke", minRole: "VIEWER" },
|
|
3472
|
+
input: [
|
|
3473
|
+
{ universalIdentifier: EXT_EVALUATION_INPUT_MODEL_ID_UID, name: "modelId", type: FieldType.TEXT, label: "Model id", isNullable: false },
|
|
3474
|
+
{ universalIdentifier: EXT_EVALUATION_INPUT_SATISFIED_UID, name: "satisfied", type: FieldType.BOOLEAN, label: "Satisfied", isNullable: false },
|
|
3475
|
+
{
|
|
3476
|
+
universalIdentifier: EXT_EVALUATION_INPUT_MESSAGES_UID,
|
|
3477
|
+
name: "messages",
|
|
3478
|
+
type: FieldType.JSON,
|
|
3479
|
+
label: "Messages",
|
|
3480
|
+
description: "[{role, content}]",
|
|
3481
|
+
isNullable: true,
|
|
3482
|
+
defaultValue: null
|
|
3483
|
+
},
|
|
3484
|
+
{
|
|
3485
|
+
universalIdentifier: EXT_EVALUATION_INPUT_TICKET_URL_UID,
|
|
3486
|
+
name: "ticket_url",
|
|
3487
|
+
type: FieldType.TEXT,
|
|
3488
|
+
label: "Ticket URL",
|
|
3489
|
+
isNullable: true,
|
|
3490
|
+
defaultValue: null
|
|
3491
|
+
},
|
|
3492
|
+
{
|
|
3493
|
+
universalIdentifier: EXT_EVALUATION_INPUT_LANGFUSE_TRACE_ID_UID,
|
|
3494
|
+
name: "langfuse_trace_id",
|
|
3495
|
+
type: FieldType.TEXT,
|
|
3496
|
+
label: "Langfuse trace id",
|
|
3497
|
+
isNullable: true,
|
|
3498
|
+
defaultValue: null
|
|
3499
|
+
},
|
|
3500
|
+
{
|
|
3501
|
+
universalIdentifier: EXT_EVALUATION_INPUT_LANGFUSE_OBSERVATION_ID_UID,
|
|
3502
|
+
name: "langfuse_observation_id",
|
|
3503
|
+
type: FieldType.TEXT,
|
|
3504
|
+
label: "Langfuse observation id",
|
|
3505
|
+
isNullable: true,
|
|
3506
|
+
defaultValue: null
|
|
3507
|
+
}
|
|
3508
|
+
]
|
|
3509
|
+
};
|
|
3510
|
+
}
|
|
3511
|
+
function createExtEvaluationHandler() {
|
|
3512
|
+
return (ctx, input) => extEvaluationHandler(ctx, input);
|
|
3513
|
+
}
|
|
3514
|
+
async function extEvaluationHandler(ctx, input) {
|
|
3515
|
+
const envelope = readSupportExtensionEnvelope(ctx);
|
|
3516
|
+
if (envelope.phase === "probe") return ownsAgent(ctx, input?.modelId ?? null);
|
|
3517
|
+
return executeEvaluation(ctx, envelope.userId, input);
|
|
3518
|
+
}
|
|
3519
|
+
async function executeEvaluation(ctx, userId, input) {
|
|
3520
|
+
if (typeof input.satisfied !== "boolean") {
|
|
3521
|
+
throw new ctx.NonRetriableError("`satisfied` is a required boolean");
|
|
3522
|
+
}
|
|
3523
|
+
if (!userId) {
|
|
3524
|
+
throw new ctx.NonRetriableError("ext-evaluation: missing platform user id in the invocation envelope");
|
|
3525
|
+
}
|
|
3526
|
+
const modelId = input.modelId;
|
|
3527
|
+
if (!modelId) throw new ctx.NonRetriableError("modelId is required");
|
|
3528
|
+
const agentRecord2 = await getOptional(ctx, "agent", modelId);
|
|
3529
|
+
if (!agentRecord2) throw new ctx.NonRetriableError(`Model not found (id=${modelId})`);
|
|
3530
|
+
const agent = toAgent(agentRecord2);
|
|
3531
|
+
const satisfied = input.satisfied;
|
|
3532
|
+
const messages = Array.isArray(input.messages) ? input.messages : [];
|
|
3533
|
+
const ticketUrl = typeof input.ticket_url === "string" ? input.ticket_url : "";
|
|
3534
|
+
const traceId = typeof input.langfuse_trace_id === "string" && input.langfuse_trace_id.length > 0 ? input.langfuse_trace_id : null;
|
|
3535
|
+
const observationId = typeof input.langfuse_observation_id === "string" && input.langfuse_observation_id.length > 0 ? input.langfuse_observation_id : void 0;
|
|
3536
|
+
const created = await ctx.api.create("evaluation", {
|
|
3537
|
+
agentId: agent.id,
|
|
3538
|
+
satisfied,
|
|
3539
|
+
messages,
|
|
3540
|
+
ticketUrl,
|
|
3541
|
+
langfuseTraceId: traceId,
|
|
3542
|
+
langfuseObservationId: observationId ?? null,
|
|
3543
|
+
// Non-empty: guarded above (L11).
|
|
3544
|
+
supportUserKeyId: userId
|
|
3545
|
+
});
|
|
3546
|
+
if (traceId) {
|
|
3547
|
+
try {
|
|
3548
|
+
await ctx.api.langfuse.scores.create({
|
|
3549
|
+
id: `user-feedback-${traceId}`,
|
|
3550
|
+
traceId,
|
|
3551
|
+
observationId,
|
|
3552
|
+
name: "user-feedback",
|
|
3553
|
+
value: satisfied,
|
|
3554
|
+
dataType: "BOOLEAN",
|
|
3555
|
+
comment: `Thumbs ${satisfied ? "up" : "down"} from ${userId || "agent"} (model: ${agent.name}, ticket_url: ${ticketUrl || "none"})`
|
|
3556
|
+
});
|
|
3557
|
+
} catch (err) {
|
|
3558
|
+
ctx.logger.warn(`ext-evaluation: user-feedback score write failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
|
|
3559
|
+
}
|
|
3560
|
+
}
|
|
3561
|
+
return { ok: true, id: created.id };
|
|
3562
|
+
}
|
|
3563
|
+
var CORRECTIONS_DATASET = "cs-replies-corrections";
|
|
3564
|
+
function buildExtResponseComparisonFunctionDef(config) {
|
|
3565
|
+
return {
|
|
3566
|
+
universalIdentifier: identifierFor(config, "ext-response-comparison"),
|
|
3567
|
+
name: "ext-response-comparison",
|
|
3568
|
+
trigger: { type: "uiInvoke", minRole: "VIEWER" },
|
|
3569
|
+
input: [
|
|
3570
|
+
{
|
|
3571
|
+
universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_LAST_MESSAGE_GENERATED_UID,
|
|
3572
|
+
name: "last_message_generated",
|
|
3573
|
+
type: FieldType.TEXT,
|
|
3574
|
+
label: "Last message generated",
|
|
3575
|
+
isNullable: true,
|
|
3576
|
+
defaultValue: null
|
|
3577
|
+
},
|
|
3578
|
+
{
|
|
3579
|
+
universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_MESSAGE_ACTUAL_SENT_UID,
|
|
3580
|
+
name: "message_actual_sent",
|
|
3581
|
+
type: FieldType.TEXT,
|
|
3582
|
+
label: "Message actually sent",
|
|
3583
|
+
isNullable: false
|
|
3584
|
+
},
|
|
3585
|
+
{
|
|
3586
|
+
universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_TICKET_ID_UID,
|
|
3587
|
+
name: "ticket_id",
|
|
3588
|
+
type: FieldType.TEXT,
|
|
3589
|
+
label: "Ticket id",
|
|
3590
|
+
isNullable: true,
|
|
3591
|
+
defaultValue: null
|
|
3592
|
+
},
|
|
3593
|
+
{
|
|
3594
|
+
universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_TICKET_URL_UID,
|
|
3595
|
+
name: "ticket_url",
|
|
3596
|
+
type: FieldType.TEXT,
|
|
3597
|
+
label: "Ticket URL",
|
|
3598
|
+
isNullable: true,
|
|
3599
|
+
defaultValue: null
|
|
3600
|
+
},
|
|
3601
|
+
{
|
|
3602
|
+
universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_MODEL_CONFIG_ID_UID,
|
|
3603
|
+
name: "model_config_id",
|
|
3604
|
+
type: FieldType.TEXT,
|
|
3605
|
+
label: "Model config id",
|
|
3606
|
+
isNullable: true,
|
|
3607
|
+
defaultValue: null
|
|
3608
|
+
},
|
|
3609
|
+
{
|
|
3610
|
+
universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_TRACE_ID_UID,
|
|
3611
|
+
name: "langfuse_trace_id",
|
|
3612
|
+
type: FieldType.TEXT,
|
|
3613
|
+
label: "Langfuse trace id",
|
|
3614
|
+
isNullable: true,
|
|
3615
|
+
defaultValue: null
|
|
3616
|
+
},
|
|
3617
|
+
{
|
|
3618
|
+
universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_OBSERVATION_ID_UID,
|
|
3619
|
+
name: "langfuse_observation_id",
|
|
3620
|
+
type: FieldType.TEXT,
|
|
3621
|
+
label: "Langfuse observation id",
|
|
3622
|
+
isNullable: true,
|
|
3623
|
+
defaultValue: null
|
|
3624
|
+
},
|
|
3625
|
+
{
|
|
3626
|
+
universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_PROMPT_NAME_UID,
|
|
3627
|
+
name: "prompt_name",
|
|
3628
|
+
type: FieldType.TEXT,
|
|
3629
|
+
label: "Prompt name",
|
|
3630
|
+
isNullable: true,
|
|
3631
|
+
defaultValue: null
|
|
3632
|
+
},
|
|
3633
|
+
{
|
|
3634
|
+
universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_PROMPT_VERSION_UID,
|
|
3635
|
+
name: "prompt_version",
|
|
3636
|
+
type: FieldType.NUMBER,
|
|
3637
|
+
label: "Prompt version",
|
|
3638
|
+
isNullable: true,
|
|
3639
|
+
defaultValue: null
|
|
3640
|
+
},
|
|
3641
|
+
{
|
|
3642
|
+
universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_CONVERSATION_MESSAGES_UID,
|
|
3643
|
+
name: "conversation_messages",
|
|
3644
|
+
type: FieldType.JSON,
|
|
3645
|
+
label: "Conversation messages",
|
|
3646
|
+
description: "[{role, content}]",
|
|
3647
|
+
isNullable: true,
|
|
3648
|
+
defaultValue: null
|
|
3649
|
+
}
|
|
3650
|
+
]
|
|
3651
|
+
};
|
|
3652
|
+
}
|
|
3653
|
+
function createExtResponseComparisonHandler() {
|
|
3654
|
+
return (ctx, input) => extResponseComparisonHandler(ctx, input ?? {});
|
|
3655
|
+
}
|
|
3656
|
+
async function extResponseComparisonHandler(ctx, input) {
|
|
3657
|
+
const envelope = readSupportExtensionEnvelope(ctx);
|
|
3658
|
+
if (envelope.phase === "probe") return probeResponseComparisonOwnership(ctx, input);
|
|
3659
|
+
return executeResponseComparison(ctx, input);
|
|
3660
|
+
}
|
|
3661
|
+
async function probeResponseComparisonOwnership(ctx, input) {
|
|
3662
|
+
const modelConfigId = nonEmptyString(input.model_config_id);
|
|
3663
|
+
if (modelConfigId) {
|
|
3664
|
+
const claim = await ownsAgent(ctx, modelConfigId);
|
|
3665
|
+
if (claim) return claim;
|
|
3666
|
+
}
|
|
3667
|
+
const ticketId = nonEmptyString(input.ticket_id);
|
|
3668
|
+
if (!ticketId) return null;
|
|
3669
|
+
const page = await ctx.api.list("triage-decision", { filter: { ticketId }, limit: 1 });
|
|
3670
|
+
return page.items.length > 0 ? { claimed: true } : null;
|
|
3671
|
+
}
|
|
3672
|
+
async function executeResponseComparison(ctx, input) {
|
|
3673
|
+
if (!input.message_actual_sent) {
|
|
3674
|
+
throw new ctx.NonRetriableError("message_actual_sent is required");
|
|
3675
|
+
}
|
|
3676
|
+
if (!input.last_message_generated) {
|
|
3677
|
+
return null;
|
|
3678
|
+
}
|
|
3679
|
+
const generatedText = input.last_message_generated;
|
|
3680
|
+
const sentText = input.message_actual_sent;
|
|
3681
|
+
const ticketId = nonEmptyString(input.ticket_id);
|
|
3682
|
+
const ticketUrl = typeof input.ticket_url === "string" ? input.ticket_url : "";
|
|
3683
|
+
const modelConfigId = nonEmptyString(input.model_config_id);
|
|
3684
|
+
const traceId = nonEmptyString(input.langfuse_trace_id);
|
|
3685
|
+
const observationId = nonEmptyString(input.langfuse_observation_id) ?? void 0;
|
|
3686
|
+
const promptName = typeof input.prompt_name === "string" ? input.prompt_name : null;
|
|
3687
|
+
const promptVersion = typeof input.prompt_version === "number" ? input.prompt_version : null;
|
|
3688
|
+
const conversationMessages = Array.isArray(input.conversation_messages) ? input.conversation_messages : [];
|
|
3689
|
+
const created = await ctx.api.create("response-comparison", {
|
|
3690
|
+
generatedText,
|
|
3691
|
+
sentText,
|
|
3692
|
+
capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3693
|
+
ticketId,
|
|
3694
|
+
ticketUrl,
|
|
3695
|
+
agentId: modelConfigId,
|
|
3696
|
+
langfuseTraceId: traceId,
|
|
3697
|
+
langfuseObservationId: observationId ?? null,
|
|
3698
|
+
promptName,
|
|
3699
|
+
promptVersion,
|
|
3700
|
+
conversationMessages,
|
|
3701
|
+
diff: computeWordDiff(generatedText, sentText)
|
|
3702
|
+
});
|
|
3703
|
+
await captureCorrectionToLangfuse(ctx, {
|
|
3704
|
+
generatedText,
|
|
3705
|
+
sentText,
|
|
3706
|
+
ticketId,
|
|
3707
|
+
traceId,
|
|
3708
|
+
observationId,
|
|
3709
|
+
promptName,
|
|
3710
|
+
promptVersion,
|
|
3711
|
+
conversationMessages,
|
|
3712
|
+
tracedInput: Array.isArray(input.traced_input) ? input.traced_input : null
|
|
3713
|
+
});
|
|
3714
|
+
return { ok: true, id: created.id };
|
|
3715
|
+
}
|
|
3716
|
+
async function captureCorrectionToLangfuse(ctx, params) {
|
|
3717
|
+
const textChanged = params.sentText !== params.generatedText;
|
|
3718
|
+
if (!textChanged || !params.traceId) return;
|
|
3719
|
+
const itemId = params.observationId ? `${params.traceId}:${params.observationId}` : params.traceId;
|
|
3720
|
+
const expectedOutput = { role: "assistant", content: params.sentText, refusal: null, annotations: [] };
|
|
3721
|
+
const datasetInput = params.tracedInput && params.tracedInput.length > 0 ? params.tracedInput : params.conversationMessages;
|
|
3722
|
+
try {
|
|
3723
|
+
await ctx.api.langfuse.datasets.createItem({
|
|
3724
|
+
dataset: CORRECTIONS_DATASET,
|
|
3725
|
+
id: itemId,
|
|
3726
|
+
input: datasetInput,
|
|
3727
|
+
expectedOutput,
|
|
3728
|
+
sourceTraceId: params.traceId,
|
|
3729
|
+
sourceObservationId: params.observationId,
|
|
3730
|
+
metadata: {
|
|
3731
|
+
prompt_name: params.promptName,
|
|
3732
|
+
prompt_version: params.promptVersion,
|
|
3733
|
+
ticket_id: params.ticketId,
|
|
3734
|
+
edited: true
|
|
3735
|
+
}
|
|
3736
|
+
});
|
|
3737
|
+
} catch (err) {
|
|
3738
|
+
ctx.logger.warn(`ext-response-comparison: dataset item write failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
|
|
3739
|
+
}
|
|
3740
|
+
try {
|
|
3741
|
+
await ctx.api.langfuse.scores.create({
|
|
3742
|
+
id: itemId,
|
|
3743
|
+
traceId: params.traceId,
|
|
3744
|
+
name: "output",
|
|
3745
|
+
value: JSON.stringify(expectedOutput),
|
|
3746
|
+
dataType: "CORRECTION",
|
|
3747
|
+
comment: `Human correction from ticket ${params.ticketId ?? "unknown"} (prompt: ${params.promptName ?? "unknown"}, version: ${params.promptVersion ?? "unknown"})`
|
|
3748
|
+
});
|
|
3749
|
+
} catch (err) {
|
|
3750
|
+
ctx.logger.warn(`ext-response-comparison: correction score write failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
|
|
3751
|
+
}
|
|
3752
|
+
}
|
|
3753
|
+
function nonEmptyString(value) {
|
|
3754
|
+
return typeof value === "string" && value.length > 0 ? value : null;
|
|
3755
|
+
}
|
|
3756
|
+
|
|
3757
|
+
// src/pages/manifest.ts
|
|
3758
|
+
function pageIdentifierFor(config, key) {
|
|
3759
|
+
const id = config.identifiers[key];
|
|
3760
|
+
if (!id) {
|
|
3761
|
+
throw new Error(
|
|
3762
|
+
`SupportPipelineConfig.identifiers is missing a universalIdentifier for "${key}" \u2014 every support-kit page needs a stable id.`
|
|
3763
|
+
);
|
|
3764
|
+
}
|
|
3765
|
+
return id;
|
|
3766
|
+
}
|
|
3767
|
+
|
|
3768
|
+
// src/pipeline.ts
|
|
3769
|
+
var SUPPORT_KIT_GORGIAS_ACTIONS = [
|
|
3770
|
+
"applyTags",
|
|
3771
|
+
"buildTicketContext",
|
|
3772
|
+
"fetchTicketsFromView",
|
|
3773
|
+
"getRawTicket",
|
|
3774
|
+
"getTicketWithContext",
|
|
3775
|
+
"listViews",
|
|
3776
|
+
"postWhatsappNote",
|
|
3777
|
+
"renameTicket",
|
|
3778
|
+
"replyEmail"
|
|
3779
|
+
];
|
|
3780
|
+
var SUPPORT_KIT_CAPABILITIES = ["runs", "inbox", "approvals", "prompts", "langfuse"];
|
|
3781
|
+
var SUPPORT_KIT_ACTIONS = [
|
|
3782
|
+
...SUPPORT_KIT_GORGIAS_ACTIONS.map((action) => ({ provider: "gorgias", action })),
|
|
3783
|
+
{ provider: "llm", action: "complete" }
|
|
3784
|
+
];
|
|
3785
|
+
var SUPPORT_KIT_EMITS = [TRIAGE_RUN_REQUESTED_EVENT];
|
|
3786
|
+
var FUNCTION_ASSEMBLY = [
|
|
3787
|
+
{ key: "triage-tick", build: buildTriageTickFunctionDef, createHandler: createTriageTickHandler },
|
|
3788
|
+
{ key: "process-response", build: buildProcessResponseFunctionDef, createHandler: createProcessResponseHandler },
|
|
3789
|
+
{ key: "sweep", build: buildSweepFunctionDef, createHandler: () => createSweepHandler() },
|
|
3790
|
+
{ key: "handle-approval", build: buildHandleApprovalFunctionDef, createHandler: createHandleApprovalHandler },
|
|
3791
|
+
{ key: "run-triage-now", build: buildRunTriageNowFunctionDef, createHandler: createRunTriageNowHandler },
|
|
3792
|
+
{ key: "run-triage-batch", build: buildRunTriageBatchFunctionDef, createHandler: createRunTriageBatchHandler },
|
|
3793
|
+
{ key: "preview-triage", build: buildPreviewTriageFunctionDef, createHandler: createPreviewTriageHandler },
|
|
3794
|
+
{ key: "graph-dry-run", build: buildGraphDryRunFunctionDef, createHandler: createGraphDryRunHandler },
|
|
3795
|
+
{ key: "test-agents", build: buildTestAgentsFunctionDef, createHandler: createTestAgentsHandler },
|
|
3796
|
+
{ key: "suggest-prompt", build: buildSuggestPromptFunctionDef, createHandler: createSuggestPromptHandler },
|
|
3797
|
+
{ key: "run-diff-analysis", build: buildRunDiffAnalysisFunctionDef, createHandler: createRunDiffAnalysisHandler },
|
|
3798
|
+
{ key: "list-gorgias-views", build: buildListGorgiasViewsFunctionDef, createHandler: createListGorgiasViewsHandler },
|
|
3799
|
+
{ key: "create-agent", build: buildCreateAgentFunctionDef, createHandler: () => createCreateAgentHandler() },
|
|
3800
|
+
{
|
|
3801
|
+
key: "set-default-agent",
|
|
3802
|
+
build: buildSetDefaultAgentFunctionDef,
|
|
3803
|
+
createHandler: () => createSetDefaultAgentHandler()
|
|
3804
|
+
},
|
|
3805
|
+
{
|
|
3806
|
+
key: "create-shared-prompt-version",
|
|
3807
|
+
build: buildCreateSharedPromptVersionFunctionDef,
|
|
3808
|
+
createHandler: () => createCreateSharedPromptVersionHandler()
|
|
3809
|
+
},
|
|
3810
|
+
{
|
|
3811
|
+
key: "sync-agent-prompt-snapshot",
|
|
3812
|
+
build: buildSyncAgentPromptSnapshotFunctionDef,
|
|
3813
|
+
createHandler: () => createSyncAgentPromptSnapshotHandler()
|
|
3814
|
+
},
|
|
3815
|
+
{ key: "ext-models", build: buildExtModelsFunctionDef, createHandler: () => createExtModelsHandler() },
|
|
3816
|
+
{ key: "ext-categories", build: buildExtCategoriesFunctionDef, createHandler: () => createExtCategoriesHandler() },
|
|
3817
|
+
{ key: "ext-chat", build: buildExtChatFunctionDef, createHandler: () => createExtChatHandler() },
|
|
3818
|
+
{
|
|
3819
|
+
key: "ext-fast-response-check",
|
|
3820
|
+
build: buildExtFastResponseCheckFunctionDef,
|
|
3821
|
+
createHandler: () => createExtFastResponseCheckHandler()
|
|
3822
|
+
},
|
|
3823
|
+
{ key: "ext-evaluation", build: buildExtEvaluationFunctionDef, createHandler: () => createExtEvaluationHandler() },
|
|
3824
|
+
{
|
|
3825
|
+
key: "ext-response-comparison",
|
|
3826
|
+
build: buildExtResponseComparisonFunctionDef,
|
|
3827
|
+
createHandler: () => createExtResponseComparisonHandler()
|
|
3828
|
+
}
|
|
3829
|
+
];
|
|
3830
|
+
function buildPromptsAllowlist(config) {
|
|
3831
|
+
const prefixedSlots = PROMPT_SLOTS.filter((slot) => !slot.startsWith("shared/"));
|
|
3832
|
+
return [
|
|
3833
|
+
...prefixedSlots.map((slot) => resolvePromptName(slot, config)),
|
|
3834
|
+
resolveReviseName(config),
|
|
3835
|
+
// "No agent configured" sentinel (H5, `functions/records.ts`'s
|
|
3836
|
+
// `draftPromptRefFor`) — scoped by promptPrefix like every other name
|
|
3837
|
+
// above, so resolving it degrades cleanly instead of a guaranteed 403.
|
|
3838
|
+
`${config.promptPrefix}no-agent-configured`,
|
|
3839
|
+
// Agent prompts (`agent.promptName`) are free text, conventionally
|
|
3840
|
+
// `agent/<recordId>` (§3.7) — never promptPrefix-prefixed, so this is a
|
|
3841
|
+
// glob, not a `resolvePromptName` call.
|
|
3842
|
+
//
|
|
3843
|
+
// ACCEPTED RISK (owner decision, T25 review H1 — recorded, not fixed):
|
|
3844
|
+
// this glob is UNPREFIXED, so it matches `agent/<any-id>` regardless of
|
|
3845
|
+
// which audience app created that agent — under D-LF's single shared
|
|
3846
|
+
// Langfuse project there is no per-app namespace, and `*` matches `/`,
|
|
3847
|
+
// so `agent/*` cannot be scoped narrower than "every agent prompt, any
|
|
3848
|
+
// app" without inventing a real per-app agent-prompt namespace (which
|
|
3849
|
+
// would contradict §3.7's documented bare `agent/<recordId>` convention
|
|
3850
|
+
// outright). `app-prompts.controller.ts` applies this SAME allowlist to
|
|
3851
|
+
// WRITES too (`requirePromptAllowed` at `createVersion`/`promote`/
|
|
3852
|
+
// `deleteVersion`) for app-token callers — so one audience's app token
|
|
3853
|
+
// can read AND version-write another audience's `agent/<id>` prompt.
|
|
3854
|
+
// This is the documented cost of D-LF's single shared Langfuse
|
|
3855
|
+
// namespace, accepted explicitly by the repo owner rather than fixed
|
|
3856
|
+
// here (option (c) of the two open items this migration deferred — see
|
|
3857
|
+
// the migration progress journal's T25 entry). The mitigation NOT taken:
|
|
3858
|
+
// validating `agent.promptName` against the calling app's own agent
|
|
3859
|
+
// records at write time, which would need a DB read `app-prompts
|
|
3860
|
+
// .controller.ts` does not currently do and was not built.
|
|
3861
|
+
"agent/*",
|
|
3862
|
+
// `shared/style-email`/`shared/style-whatsapp` are company-wide by
|
|
3863
|
+
// design (§3.8) and are resolved by NAME off the settings fields' own
|
|
3864
|
+
// bare defaults, never through `resolvePromptName` — prefixing them
|
|
3865
|
+
// here would allowlist a name nothing ever requests. One glob covers
|
|
3866
|
+
// both today and any future `shared/*` prompt.
|
|
3867
|
+
"shared/*"
|
|
3868
|
+
];
|
|
3869
|
+
}
|
|
3870
|
+
function dedupe(items, keyOf) {
|
|
3871
|
+
const seen = /* @__PURE__ */ new Map();
|
|
3872
|
+
for (const item of items) seen.set(keyOf(item), item);
|
|
3873
|
+
return [...seen.values()];
|
|
3874
|
+
}
|
|
3875
|
+
function mergeActionRefs(actions) {
|
|
3876
|
+
return dedupe([...actions, ...SUPPORT_KIT_ACTIONS], (a) => `${a.provider}::${a.action}`);
|
|
3877
|
+
}
|
|
3878
|
+
var KIT_READ_ONLY_OBJECT_KEYS = ["category", "category-group"];
|
|
3879
|
+
var KIT_WRITE_ONLY_OBJECT_KEYS = ["evaluation", "diff-analysis"];
|
|
3880
|
+
function buildMergeRole(config) {
|
|
3881
|
+
const kitRecords = buildSupportKitRecords(config.slug);
|
|
3882
|
+
const refsExcluding = (excludedObjectKeys) => kitRecords.filter((record) => !excludedObjectKeys.includes(record.objectKey)).map((record) => targetRefFor(config.slug, record.objectKey));
|
|
3883
|
+
const kitReadRefs = refsExcluding(KIT_WRITE_ONLY_OBJECT_KEYS);
|
|
3884
|
+
const kitWriteRefs = refsExcluding(KIT_READ_ONLY_OBJECT_KEYS);
|
|
3885
|
+
const kitPrompts = buildPromptsAllowlist(config);
|
|
3886
|
+
return (role) => ({
|
|
3887
|
+
...role,
|
|
3888
|
+
reads: dedupe([...role.reads, ...kitReadRefs], (ref) => ref),
|
|
3889
|
+
writes: dedupe([...role.writes, ...kitWriteRefs], (ref) => ref),
|
|
3890
|
+
actions: mergeActionRefs(role.actions),
|
|
3891
|
+
capabilities: dedupe([...role.capabilities ?? [], ...SUPPORT_KIT_CAPABILITIES], (c) => c),
|
|
3892
|
+
prompts: dedupe([...role.prompts ?? [], ...kitPrompts], (p) => p)
|
|
3893
|
+
});
|
|
3894
|
+
}
|
|
3895
|
+
var KIT_PAGES = [
|
|
3896
|
+
{ key: "dashboard-page", path: "dashboard", title: "Tableau de bord", icon: "layout-dashboard" },
|
|
3897
|
+
{ key: "tickets-page", path: "tickets", title: "Demandes", icon: "ticket" },
|
|
3898
|
+
{ key: "pipeline-page", path: "pipeline", title: "Pipeline", icon: "inbox" },
|
|
3899
|
+
{ key: "agents-page", path: "agents", title: "Agents", icon: "bot" },
|
|
3900
|
+
{ key: "categories-page", path: "categories", title: "Cat\xE9gories", icon: "tags" },
|
|
3901
|
+
{ key: "escalations-page", path: "escalations", title: "Escalades", icon: "alert-triangle" },
|
|
3902
|
+
{ key: "corrections-page", path: "corrections", title: "Corrections", icon: "git-compare" },
|
|
3903
|
+
{ key: "graph-canvas-page", path: "graph-canvas", title: "Graphe", icon: "workflow" },
|
|
3904
|
+
{ key: "shared-prompts-page", path: "shared-prompts", title: "Prompts partag\xE9s", icon: "library" },
|
|
3905
|
+
{ key: "test-page", path: "test", title: "Banc de test", icon: "flask-conical" }
|
|
3906
|
+
];
|
|
3907
|
+
function buildPages(config) {
|
|
3908
|
+
return KIT_PAGES.map(({ key, path, title, icon }) => ({
|
|
3909
|
+
universalIdentifier: pageIdentifierFor(config, key),
|
|
3910
|
+
path,
|
|
3911
|
+
title,
|
|
3912
|
+
icon,
|
|
3913
|
+
entry: `dist/ui/${path}.js`
|
|
3914
|
+
}));
|
|
3915
|
+
}
|
|
3916
|
+
function buildNavigation(config) {
|
|
3917
|
+
return KIT_PAGES.map(({ path, title, icon }) => ({
|
|
3918
|
+
label: title,
|
|
3919
|
+
path,
|
|
3920
|
+
icon,
|
|
3921
|
+
...config.navigationSection !== void 0 ? { section: config.navigationSection } : {}
|
|
3922
|
+
}));
|
|
3923
|
+
}
|
|
3924
|
+
function buildSettingsPage(config) {
|
|
3925
|
+
return {
|
|
3926
|
+
universalIdentifier: pageIdentifierFor(config, "settings-page"),
|
|
3927
|
+
entry: "dist/ui/settings.js",
|
|
3928
|
+
title: "Param\xE8tres"
|
|
3929
|
+
};
|
|
3930
|
+
}
|
|
3931
|
+
function buildSupportPipeline(config) {
|
|
3932
|
+
const functions = FUNCTION_ASSEMBLY.map(({ build }) => build(config));
|
|
3933
|
+
const handlers = {};
|
|
3934
|
+
for (const { key, createHandler } of FUNCTION_ASSEMBLY) handlers[key] = createHandler(config);
|
|
3935
|
+
return {
|
|
3936
|
+
records: buildSupportKitRecords(config.slug),
|
|
3937
|
+
functions,
|
|
3938
|
+
settings: { fields: SUPPORT_KIT_SETTINGS_FIELDS },
|
|
3939
|
+
// DECISION 1 (see docs/plans/2026-09-02-gorgias-migration-progress.md's
|
|
3940
|
+
// T25 entry): always empty. §3.2's own fragment sketch types this
|
|
3941
|
+
// `PromptDef[] // seed Langfuse (§3.7)`, but §3.7 line 322 and D-LF both
|
|
3942
|
+
// say manifest.prompts[] is NOT used by the kit — it would seed an
|
|
3943
|
+
// `apps/<slug>/…` namespace that contradicts "same Langfuse project,
|
|
3944
|
+
// bare legacy names, zero write at migration time". A new audience's
|
|
3945
|
+
// prompts are seeded at first run via S3 createVersion (a RUNTIME
|
|
3946
|
+
// concern), not declared in the manifest.
|
|
3947
|
+
prompts: [],
|
|
3948
|
+
// T26 fills the four phase-2 pages + the settingsPage (§3.8); T27 part A
|
|
3949
|
+
// adds DashboardPage/TicketsPage/CorrectionsPage. Part B's remaining
|
|
3950
|
+
// phase-3 pages (GraphCanvasPage, SharedPromptsPage, TestPage) are still ahead.
|
|
3951
|
+
pages: buildPages(config),
|
|
3952
|
+
navigation: buildNavigation(config),
|
|
3953
|
+
settingsPage: buildSettingsPage(config),
|
|
3954
|
+
actions: SUPPORT_KIT_ACTIONS,
|
|
3955
|
+
emits: SUPPORT_KIT_EMITS,
|
|
3956
|
+
defaultRole: "NO_ACCESS",
|
|
3957
|
+
handlers,
|
|
3958
|
+
mergeRole: buildMergeRole(config),
|
|
3959
|
+
mergeActions: mergeActionRefs
|
|
3960
|
+
};
|
|
3961
|
+
}
|
|
3962
|
+
|
|
3963
|
+
export { buildCategoryRecord, buildDiffAnalysisRecord, buildEvaluationRecord, buildGeneratedResponseRecord, buildResponseComparisonRecord, buildSupportKitRecords, buildSupportPipeline, buildTriageDecisionRecord, categoryGroupRecord, createBudget, createPromptResolver, diffAnalysisUniqueKey, hasReferences, parseReferences, pipelineStateRecord, promptCacheRecord, targetRefFor };
|
|
3964
|
+
//# sourceMappingURL=index.js.map
|
|
3965
|
+
//# sourceMappingURL=index.js.map
|