@apotech-os/support-kit 5.0.1 → 6.0.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/dist/{chunk-ZFUWILDN.js → chunk-CRFNVCS7.js} +7 -4
- package/dist/chunk-CRFNVCS7.js.map +1 -0
- package/dist/index.cjs +397 -317
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +15 -5
- package/dist/index.d.ts +15 -5
- package/dist/index.js +331 -254
- package/dist/index.js.map +1 -1
- package/dist/ui/index.cjs +40 -4
- package/dist/ui/index.cjs.map +1 -1
- package/dist/ui/index.js +24 -5
- package/dist/ui/index.js.map +1 -1
- package/package.json +3 -3
- package/dist/chunk-ZFUWILDN.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { CATEGORY_GROUP_FIELD_NAME_UID, CATEGORY_GROUP_FIELD_ORDER_UID, PIPELINE_STATE_FIELD_SINGLETON_KEY_UID, PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID, PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID, PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID, PROMPT_CACHE_FIELD_PROMPT_KEY_UID, PROMPT_CACHE_FIELD_CONTENT_UID, PROMPT_CACHE_FIELD_VERSION_UID, PROMPT_CACHE_FIELD_LABEL_UID, PROMPT_CACHE_FIELD_CONFIG_UID, CATEGORY_GROUP_INDEX_NAME_UID, CATEGORY_GROUP_OBJECT_UID, PIPELINE_STATE_INDEX_SINGLETON_KEY_UID, PIPELINE_STATE_OBJECT_UID, PROMPT_CACHE_INDEX_PROMPT_KEY_UID, PROMPT_CACHE_OBJECT_UID, CATEGORY_INDEX_TAG_NAME_UID, CATEGORY_INDEX_NAME_UID, CATEGORY_INDEX_ORDER_UID, CATEGORY_FIELD_NAME_UID, CATEGORY_FIELD_TAG_NAME_UID, CATEGORY_FIELD_ORDER_UID, CATEGORY_FIELD_GROUP_ID_UID, CATEGORY_FIELD_AGENT_ID_UID, CATEGORY_FIELD_EXTRA_TAGS_UID, CATEGORY_FIELD_DESCRIPTION_UID, CATEGORY_FIELD_EXAMPLES_UID, CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID, CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID, CATEGORY_OBJECT_UID, TRIAGE_DECISION_INDEX_TICKET_ID_UID, TRIAGE_DECISION_INDEX_DECIDED_AT_UID, TRIAGE_DECISION_INDEX_ESCALATED_UID, TRIAGE_DECISION_FIELD_TICKET_ID_UID, TRIAGE_DECISION_FIELD_TICKET_URL_UID, TRIAGE_DECISION_FIELD_DECIDED_AT_UID, TRIAGE_DECISION_FIELD_CATEGORY_ID_UID, TRIAGE_DECISION_FIELD_TAG_UID, TRIAGE_DECISION_FIELD_CONFIDENCE_UID, TRIAGE_DECISION_FIELD_REASONING_UID, TRIAGE_DECISION_FIELD_CONVERSATION_OVER_UID, TRIAGE_DECISION_FIELD_ESCALATED_UID, TRIAGE_DECISION_FIELD_ESCALATION_CONFIDENCE_UID, TRIAGE_DECISION_FIELD_ESCALATION_REASONING_UID, TRIAGE_DECISION_FIELD_STATUS_UID, TRIAGE_DECISION_FIELD_ERROR_UID, TRIAGE_DECISION_FIELD_RUN_ID_UID, TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID, 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, MissingPromptError, validateSettings,
|
|
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, MissingPromptError, 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, runGuardrails, runTicket, settingsToProfile, stopOptOut, validateSettings, verifyReply, whatsappModeFromLegacyBoolean } from './chunk-
|
|
1
|
+
import { CATEGORY_GROUP_FIELD_NAME_UID, CATEGORY_GROUP_FIELD_ORDER_UID, PIPELINE_STATE_FIELD_SINGLETON_KEY_UID, PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID, PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID, PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID, PROMPT_CACHE_FIELD_PROMPT_KEY_UID, PROMPT_CACHE_FIELD_CONTENT_UID, PROMPT_CACHE_FIELD_VERSION_UID, PROMPT_CACHE_FIELD_LABEL_UID, PROMPT_CACHE_FIELD_CONFIG_UID, CATEGORY_GROUP_INDEX_NAME_UID, CATEGORY_GROUP_OBJECT_UID, PIPELINE_STATE_INDEX_SINGLETON_KEY_UID, PIPELINE_STATE_OBJECT_UID, PROMPT_CACHE_INDEX_PROMPT_KEY_UID, PROMPT_CACHE_OBJECT_UID, CATEGORY_INDEX_TAG_NAME_UID, CATEGORY_INDEX_NAME_UID, CATEGORY_INDEX_ORDER_UID, CATEGORY_FIELD_NAME_UID, CATEGORY_FIELD_TAG_NAME_UID, CATEGORY_FIELD_ORDER_UID, CATEGORY_FIELD_GROUP_ID_UID, CATEGORY_FIELD_AGENT_ID_UID, CATEGORY_FIELD_EXTRA_TAGS_UID, CATEGORY_FIELD_DESCRIPTION_UID, CATEGORY_FIELD_EXAMPLES_UID, CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID, CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID, CATEGORY_OBJECT_UID, TRIAGE_DECISION_INDEX_TICKET_ID_UID, TRIAGE_DECISION_INDEX_DECIDED_AT_UID, TRIAGE_DECISION_INDEX_ESCALATED_UID, TRIAGE_DECISION_FIELD_TICKET_ID_UID, TRIAGE_DECISION_FIELD_TICKET_URL_UID, TRIAGE_DECISION_FIELD_DECIDED_AT_UID, TRIAGE_DECISION_FIELD_CATEGORY_ID_UID, TRIAGE_DECISION_FIELD_TAG_UID, TRIAGE_DECISION_FIELD_CONFIDENCE_UID, TRIAGE_DECISION_FIELD_REASONING_UID, TRIAGE_DECISION_FIELD_CONVERSATION_OVER_UID, TRIAGE_DECISION_FIELD_ESCALATED_UID, TRIAGE_DECISION_FIELD_ESCALATION_CONFIDENCE_UID, TRIAGE_DECISION_FIELD_ESCALATION_REASONING_UID, TRIAGE_DECISION_FIELD_STATUS_UID, TRIAGE_DECISION_FIELD_ERROR_UID, TRIAGE_DECISION_FIELD_RUN_ID_UID, TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID, 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, MissingPromptError, validateSettings, settingsToProfile, buildPromptsTable, draftPromptRefFor, assertTransition, openTicketKeyFor, act, initialState, applyOutcomeTags, listCategories, resolveDraftAgent, runTicket, toCategoryReferential, toAgent, draftRebinder, resolvePromptName, isGeneratedResponseStatus, isInvalidatableStatus, DEFAULT_LLM_PROVIDER, toCategoryGroup, toCategory, toGeneratedResponse, NODE_NAMES, reclaimStalledSend, applySignature, isEvaluationVerdict, requiresFollowup, computeWordDiff, findCategoryByTag, isWhatsappTicket, isConversationOver, isFallbackClassification, hasNoDraftNode, hasCustomerAttachment, isTicketClosed, isWhatsappChevronNote } from './chunk-CRFNVCS7.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, MissingPromptError, 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, runGuardrails, runTicket, settingsToProfile, stopOptOut, validateSettings, verifyReply, whatsappModeFromLegacyBoolean } from './chunk-CRFNVCS7.js';
|
|
3
3
|
import { FieldType, APPROVAL_DECIDED_EVENT, AppApiError } from '@apotech-os/app-kit';
|
|
4
4
|
import { createHash } from 'node:crypto';
|
|
5
5
|
|
|
@@ -152,7 +152,9 @@ function createPromptResolver(deps) {
|
|
|
152
152
|
return null;
|
|
153
153
|
});
|
|
154
154
|
if (cached) {
|
|
155
|
-
|
|
155
|
+
const text2 = substituteVars(cached.content, vars);
|
|
156
|
+
if (text2.trim() !== "") return { name, text: text2, version: cached.version, config: null };
|
|
157
|
+
deps.onDegraded?.({ stage: "cache-empty", name, reason: "the prompt-cache mirror holds no text" });
|
|
156
158
|
}
|
|
157
159
|
const rawFallback = ref.fallback ?? "";
|
|
158
160
|
const text = hasReferences(rawFallback) ? await composeReferences(rawFallback, composeCtx, /* @__PURE__ */ new Set([name]), 0) : rawFallback;
|
|
@@ -176,18 +178,15 @@ function createPromptResolver(deps) {
|
|
|
176
178
|
deps.onDegraded?.({ stage: "platform-unavailable", name: ref.name, reason: reasonOf(err) });
|
|
177
179
|
return resolveFromCacheOrFallback(ref.name, label, ref, vars);
|
|
178
180
|
}
|
|
179
|
-
if (!hasReferences(resolved.content)) {
|
|
181
|
+
if (resolved.content.trim() !== "" && !hasReferences(resolved.content)) {
|
|
180
182
|
await deps.cache.write(persistKey, { content: resolved.content, version: resolved.version }).catch(() => void 0);
|
|
181
183
|
}
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
},
|
|
189
|
-
label
|
|
190
|
-
);
|
|
184
|
+
const text = substituteVars(resolved.content, vars);
|
|
185
|
+
if (text.trim() === "") {
|
|
186
|
+
deps.onDegraded?.({ stage: "platform-empty", name: ref.name, reason: "the platform read resolved to no text" });
|
|
187
|
+
return resolveFromCacheOrFallback(ref.name, label, ref, vars);
|
|
188
|
+
}
|
|
189
|
+
return { name: ref.name, text, version: resolved.version, config: toResolvedConfig(resolved.config) };
|
|
191
190
|
}
|
|
192
191
|
};
|
|
193
192
|
}
|
|
@@ -1494,216 +1493,6 @@ async function upsertPipelineState(api, patch) {
|
|
|
1494
1493
|
{ uniqueBy: ["singletonKey"] }
|
|
1495
1494
|
);
|
|
1496
1495
|
}
|
|
1497
|
-
|
|
1498
|
-
// src/functions/triage-tick.ts
|
|
1499
|
-
function buildTriageTickFunctionDef(config) {
|
|
1500
|
-
return {
|
|
1501
|
-
universalIdentifier: identifierFor(config, "triage-tick"),
|
|
1502
|
-
name: "triage-tick",
|
|
1503
|
-
trigger: { type: "cron", pattern: "*/5 * * * *" },
|
|
1504
|
-
retries: 0,
|
|
1505
|
-
concurrency: 1,
|
|
1506
|
-
notify: { onFailure: true, severity: "warning" }
|
|
1507
|
-
};
|
|
1508
|
-
}
|
|
1509
|
-
function createTriageTickHandler(config) {
|
|
1510
|
-
return (ctx) => triageTickHandler(ctx, config);
|
|
1511
|
-
}
|
|
1512
|
-
async function triageTickHandler(ctx, config) {
|
|
1513
|
-
const settings = await ctx.api.settings.get();
|
|
1514
|
-
const issues = validateSettings(settings);
|
|
1515
|
-
if (issues.length > 0) {
|
|
1516
|
-
ctx.logger.info("triage-tick: settings invalid, skipping", { issues });
|
|
1517
|
-
return;
|
|
1518
|
-
}
|
|
1519
|
-
if (!settings.triageEnabled) {
|
|
1520
|
-
ctx.logger.info("triage-tick: triageEnabled is off, skipping");
|
|
1521
|
-
return;
|
|
1522
|
-
}
|
|
1523
|
-
if (!settings.sourceViewId) {
|
|
1524
|
-
ctx.logger.info("triage-tick: no sourceViewId configured, skipping");
|
|
1525
|
-
return;
|
|
1526
|
-
}
|
|
1527
|
-
const clock = createRealClock();
|
|
1528
|
-
const now = clock.now();
|
|
1529
|
-
const pipelineState = await readPipelineState(ctx.api);
|
|
1530
|
-
const lastTriageAt = toDate(pipelineState?.data.lastTriageAt);
|
|
1531
|
-
if (lastTriageAt) {
|
|
1532
|
-
const dueAt = lastTriageAt.getTime() + settings.triageIntervalMinutes * 6e4;
|
|
1533
|
-
if (now.getTime() < dueAt) {
|
|
1534
|
-
ctx.logger.info("triage-tick: not due yet, skipping");
|
|
1535
|
-
return;
|
|
1536
|
-
}
|
|
1537
|
-
}
|
|
1538
|
-
await runTriageBatch(ctx, config, settings);
|
|
1539
|
-
}
|
|
1540
|
-
async function resolveTicketUrlBase(ctx) {
|
|
1541
|
-
try {
|
|
1542
|
-
const connections = await ctx.api.integrations.list("gorgias");
|
|
1543
|
-
const connection = connections.find((candidate) => candidate.isDefault) ?? connections[0];
|
|
1544
|
-
const result = await ctx.api.integrations.run(
|
|
1545
|
-
"gorgias",
|
|
1546
|
-
"getTicketUrlBase",
|
|
1547
|
-
{},
|
|
1548
|
-
connection ? { connectionId: connection.id } : void 0
|
|
1549
|
-
);
|
|
1550
|
-
return typeof result?.base === "string" && result.base !== "" ? result.base : null;
|
|
1551
|
-
} catch (err) {
|
|
1552
|
-
ctx.logger.warn("triage-tick: could not resolve the Gorgias ticket url base, decisions will carry no deep link", {
|
|
1553
|
-
error: err instanceof Error ? err.message : String(err)
|
|
1554
|
-
});
|
|
1555
|
-
return null;
|
|
1556
|
-
}
|
|
1557
|
-
}
|
|
1558
|
-
function ticketUrlFor(base, ticketId) {
|
|
1559
|
-
return base ? `${base}/${encodeURIComponent(ticketId)}` : null;
|
|
1560
|
-
}
|
|
1561
|
-
async function runTriageBatch(ctx, config, settings) {
|
|
1562
|
-
const dryRun = settings.dryRun === true;
|
|
1563
|
-
const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx), ctx.api) : buildTicketPorts(ctx);
|
|
1564
|
-
const categories = await listCategories(ctx.api);
|
|
1565
|
-
const batchDefaultAgent = await resolveDraftAgent(ctx.api, null);
|
|
1566
|
-
const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(batchDefaultAgent, config), settings.nodes));
|
|
1567
|
-
const ticketUrlBase = await resolveTicketUrlBase(ctx);
|
|
1568
|
-
const refs = await ports.conversation.listPending({ viewOrTag: settings.sourceViewId }, settings.batchLimit);
|
|
1569
|
-
const run = await ctx.api.runs.start({
|
|
1570
|
-
kind: "triage-tick",
|
|
1571
|
-
message: `${dryRun ? "Dry-run triage tick" : "Triage tick"} over ${refs.length} ticket(s)`,
|
|
1572
|
-
metadata: { sourceViewId: settings.sourceViewId, ticketCount: refs.length, dryRun }
|
|
1573
|
-
});
|
|
1574
|
-
let failureCount = 0;
|
|
1575
|
-
try {
|
|
1576
|
-
for (const ref of refs) {
|
|
1577
|
-
try {
|
|
1578
|
-
await processOneTicket(ctx, ref, {
|
|
1579
|
-
profile,
|
|
1580
|
-
categories,
|
|
1581
|
-
ports,
|
|
1582
|
-
runId: run.id,
|
|
1583
|
-
ticketUrlBase
|
|
1584
|
-
});
|
|
1585
|
-
} catch (err) {
|
|
1586
|
-
failureCount += 1;
|
|
1587
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
1588
|
-
ctx.logger.error(`triage-tick: ticket ${ref.id} failed, continuing with the rest of the batch`, { error: message });
|
|
1589
|
-
try {
|
|
1590
|
-
await ctx.api.create("triage-decision", {
|
|
1591
|
-
ticketId: ref.id,
|
|
1592
|
-
ticketUrl: ticketUrlFor(ticketUrlBase, ref.id),
|
|
1593
|
-
decidedAt: ports.clock.now(),
|
|
1594
|
-
status: "error",
|
|
1595
|
-
error: message,
|
|
1596
|
-
confidence: "low",
|
|
1597
|
-
runId: run.id,
|
|
1598
|
-
subjectRenamed: false
|
|
1599
|
-
});
|
|
1600
|
-
} catch (writeErr) {
|
|
1601
|
-
ctx.logger.error(`triage-tick: failed to record the error decision for ticket ${ref.id}`, {
|
|
1602
|
-
error: writeErr instanceof Error ? writeErr.message : String(writeErr)
|
|
1603
|
-
});
|
|
1604
|
-
}
|
|
1605
|
-
}
|
|
1606
|
-
}
|
|
1607
|
-
await ctx.api.runs.succeed(run.id, { ticketCount: refs.length, failureCount });
|
|
1608
|
-
} catch (err) {
|
|
1609
|
-
await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });
|
|
1610
|
-
throw err;
|
|
1611
|
-
} finally {
|
|
1612
|
-
await upsertPipelineState(ctx.api, { sourceViewId: settings.sourceViewId, lastTriageAt: ports.clock.now() });
|
|
1613
|
-
}
|
|
1614
|
-
return { ticketCount: refs.length, failureCount };
|
|
1615
|
-
}
|
|
1616
|
-
async function processOneTicket(ctx, ref, deps) {
|
|
1617
|
-
const { profile, categories, ports, runId, ticketUrlBase } = deps;
|
|
1618
|
-
let subjectRenamed = false;
|
|
1619
|
-
if (profile.rename) {
|
|
1620
|
-
const conversation2 = await ports.conversation.read(ref);
|
|
1621
|
-
const subject = conversation2.subject ?? "";
|
|
1622
|
-
if (subject.includes(profile.rename.from)) {
|
|
1623
|
-
await ports.state.rename(ref, subject.replace(profile.rename.from, profile.rename.to));
|
|
1624
|
-
subjectRenamed = true;
|
|
1625
|
-
}
|
|
1626
|
-
}
|
|
1627
|
-
const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });
|
|
1628
|
-
const state = await runTicket(
|
|
1629
|
-
{
|
|
1630
|
-
ref,
|
|
1631
|
-
profile,
|
|
1632
|
-
ports: { ...ports },
|
|
1633
|
-
toolContext: createNoToolContext(),
|
|
1634
|
-
budget,
|
|
1635
|
-
// Unknown until triage runs — no node reached in the `until:'triage'`
|
|
1636
|
-
// phase reads `deps.category` (`run-ticket.ts`'s early return happens
|
|
1637
|
-
// before any node touches it).
|
|
1638
|
-
category: { autoReplyEnabled: true, minConfidence: null },
|
|
1639
|
-
categories: toCategoryReferential(categories),
|
|
1640
|
-
log: (msg) => ctx.logger.debug(msg),
|
|
1641
|
-
send: { mode: "none" }
|
|
1642
|
-
},
|
|
1643
|
-
{ until: "triage" }
|
|
1644
|
-
);
|
|
1645
|
-
if (!state.classification) {
|
|
1646
|
-
await ctx.api.create("triage-decision", {
|
|
1647
|
-
ticketId: ref.id,
|
|
1648
|
-
ticketUrl: ticketUrlFor(ticketUrlBase, ref.id),
|
|
1649
|
-
decidedAt: ports.clock.now(),
|
|
1650
|
-
status: "error",
|
|
1651
|
-
error: "triage produced no classification",
|
|
1652
|
-
confidence: "low",
|
|
1653
|
-
runId,
|
|
1654
|
-
subjectRenamed
|
|
1655
|
-
});
|
|
1656
|
-
return;
|
|
1657
|
-
}
|
|
1658
|
-
const { classification } = state;
|
|
1659
|
-
const category = findCategoryByTag(categories, classification.category);
|
|
1660
|
-
const decision = await ctx.api.create("triage-decision", {
|
|
1661
|
-
ticketId: ref.id,
|
|
1662
|
-
ticketUrl: ticketUrlFor(ticketUrlBase, ref.id),
|
|
1663
|
-
decidedAt: ports.clock.now(),
|
|
1664
|
-
categoryId: category?.id ?? null,
|
|
1665
|
-
tag: classification.category,
|
|
1666
|
-
confidence: classification.confidence,
|
|
1667
|
-
reasoning: classification.reasoning,
|
|
1668
|
-
conversationOver: classification.conversationOver ?? false,
|
|
1669
|
-
escalated: state.escalated,
|
|
1670
|
-
status: "ok",
|
|
1671
|
-
runId,
|
|
1672
|
-
subjectRenamed
|
|
1673
|
-
});
|
|
1674
|
-
await ports.state.record(ref, classification, profile.audit);
|
|
1675
|
-
if (!isEligibleForGeneratedResponse(profile, classification, state.escalated, category)) return;
|
|
1676
|
-
const draftAgent = await resolveDraftAgent(ctx.api, category?.agentId ?? null);
|
|
1677
|
-
const conversation = state.conversation;
|
|
1678
|
-
const channel = conversation?.sourceChannel === "whatsapp" ? "whatsapp" : "email";
|
|
1679
|
-
const generatedAt = ports.clock.now();
|
|
1680
|
-
const expiresAt = new Date(generatedAt.getTime() + profile.schedule.fastResponseTtlMinutes * 6e4);
|
|
1681
|
-
try {
|
|
1682
|
-
await ctx.api.create("generated-response", {
|
|
1683
|
-
ticketId: ref.id,
|
|
1684
|
-
openTicketKey: openTicketKeyFor("pending", ref.id),
|
|
1685
|
-
status: "pending",
|
|
1686
|
-
triageDecisionId: decision.id,
|
|
1687
|
-
categoryId: category?.id ?? null,
|
|
1688
|
-
agentId: draftAgent?.id ?? null,
|
|
1689
|
-
channel,
|
|
1690
|
-
generatedAt,
|
|
1691
|
-
expiresAt,
|
|
1692
|
-
sources: [],
|
|
1693
|
-
tracedInput: [],
|
|
1694
|
-
guardrailHits: [],
|
|
1695
|
-
servedTo: [],
|
|
1696
|
-
servedCount: 0,
|
|
1697
|
-
followupRequired: false
|
|
1698
|
-
});
|
|
1699
|
-
} catch (err) {
|
|
1700
|
-
if (err instanceof AppApiError && err.status === 409) {
|
|
1701
|
-
ctx.logger.debug(`triage-tick: generated-response already pending for ticket ${ref.id}, skipping`);
|
|
1702
|
-
return;
|
|
1703
|
-
}
|
|
1704
|
-
throw err;
|
|
1705
|
-
}
|
|
1706
|
-
}
|
|
1707
1496
|
function buildSendSeam(params) {
|
|
1708
1497
|
const { api, clock, id, ticketId, fromStatus, extraClaimData } = params;
|
|
1709
1498
|
return {
|
|
@@ -1800,51 +1589,33 @@ async function finalizeNonSent(ctx, id, ticketId, toStatus, extra) {
|
|
|
1800
1589
|
return true;
|
|
1801
1590
|
} catch (err) {
|
|
1802
1591
|
if (err instanceof AppApiError && err.status === 409) {
|
|
1803
|
-
ctx.logger.info(`
|
|
1592
|
+
ctx.logger.info(`respond: generated-response ${id} was already moved off "pending" by another worker, abandoning`);
|
|
1804
1593
|
return false;
|
|
1805
1594
|
}
|
|
1806
1595
|
throw err;
|
|
1807
1596
|
}
|
|
1808
1597
|
}
|
|
1809
|
-
function
|
|
1810
|
-
return {
|
|
1811
|
-
universalIdentifier: identifierFor(config, "process-response"),
|
|
1812
|
-
name: "process-response",
|
|
1813
|
-
trigger: { type: "dbEvent", objectRef: `app:${config.slug}/generated-response`, operation: "created" },
|
|
1814
|
-
retries: 3,
|
|
1815
|
-
concurrency: 3,
|
|
1816
|
-
notify: { onFailure: true, severity: "warning" }
|
|
1817
|
-
};
|
|
1818
|
-
}
|
|
1819
|
-
function createProcessResponseHandler(config) {
|
|
1820
|
-
return (ctx) => processResponseHandler(ctx, config);
|
|
1821
|
-
}
|
|
1822
|
-
async function processResponseHandler(ctx, config) {
|
|
1823
|
-
const recordId = ctx.event.recordId;
|
|
1824
|
-
if (!recordId) {
|
|
1825
|
-
ctx.logger.warn("process-response: event carried no recordId, skipping");
|
|
1826
|
-
return;
|
|
1827
|
-
}
|
|
1598
|
+
async function respondToPendingResponse(ctx, config, recordId) {
|
|
1828
1599
|
const record = await getOptional(ctx, "generated-response", recordId);
|
|
1829
1600
|
if (!record) {
|
|
1830
|
-
ctx.logger.info(`
|
|
1601
|
+
ctx.logger.info(`respond: generated-response ${recordId} no longer exists, skipping`);
|
|
1831
1602
|
return;
|
|
1832
1603
|
}
|
|
1833
1604
|
const data = record.data;
|
|
1834
1605
|
if (data.status !== "pending") {
|
|
1835
|
-
ctx.logger.info(`
|
|
1606
|
+
ctx.logger.info(`respond: generated-response ${recordId} is not pending (status="${String(data.status)}"), skipping \u2014 already handled by another worker`);
|
|
1836
1607
|
return;
|
|
1837
1608
|
}
|
|
1838
1609
|
const settings = await ctx.api.settings.get();
|
|
1839
1610
|
if (validateSettings(settings).length > 0) {
|
|
1840
|
-
ctx.logger.info("
|
|
1611
|
+
ctx.logger.info("respond: settings invalid, skipping");
|
|
1841
1612
|
return;
|
|
1842
1613
|
}
|
|
1843
1614
|
const ticketId = data.ticketId;
|
|
1844
1615
|
const ref = { id: ticketId, channel: "gorgias" };
|
|
1845
1616
|
const decision = await getOptional(ctx, "triage-decision", data.triageDecisionId ?? null);
|
|
1846
1617
|
if (!decision) {
|
|
1847
|
-
ctx.logger.error(`
|
|
1618
|
+
ctx.logger.error(`respond: generated-response ${recordId} has no resolvable triage-decision, marking failed`);
|
|
1848
1619
|
await finalizeNonSent(ctx, recordId, ticketId, "failed", { error: "triage-decision not found" });
|
|
1849
1620
|
return;
|
|
1850
1621
|
}
|
|
@@ -1949,7 +1720,7 @@ async function processResponseHandler(ctx, config) {
|
|
|
1949
1720
|
await finalizeNonSent(ctx, recordId, ticketId, "failed", { ...draftExtra, error: "runTicket outcome: failed" });
|
|
1950
1721
|
return;
|
|
1951
1722
|
default:
|
|
1952
|
-
ctx.logger.error(`
|
|
1723
|
+
ctx.logger.error(`respond: generated-response ${recordId} resumed run ended with no outcome`);
|
|
1953
1724
|
}
|
|
1954
1725
|
}
|
|
1955
1726
|
async function transitionGeneratedResponse(api, params) {
|
|
@@ -1969,7 +1740,265 @@ async function transitionGeneratedResponse(api, params) {
|
|
|
1969
1740
|
}
|
|
1970
1741
|
}
|
|
1971
1742
|
|
|
1972
|
-
// src/functions/
|
|
1743
|
+
// src/functions/triage-tick.ts
|
|
1744
|
+
function buildTriageTickFunctionDef(config) {
|
|
1745
|
+
return {
|
|
1746
|
+
universalIdentifier: identifierFor(config, "triage-tick"),
|
|
1747
|
+
name: "triage-tick",
|
|
1748
|
+
trigger: { type: "cron", pattern: "*/5 * * * *" },
|
|
1749
|
+
retries: 0,
|
|
1750
|
+
concurrency: 1,
|
|
1751
|
+
notify: { onFailure: true, severity: "warning" }
|
|
1752
|
+
};
|
|
1753
|
+
}
|
|
1754
|
+
function createTriageTickHandler(config) {
|
|
1755
|
+
return (ctx) => triageTickHandler(ctx, config);
|
|
1756
|
+
}
|
|
1757
|
+
async function triageTickHandler(ctx, config) {
|
|
1758
|
+
const settings = await ctx.api.settings.get();
|
|
1759
|
+
const issues = validateSettings(settings);
|
|
1760
|
+
if (issues.length > 0) {
|
|
1761
|
+
ctx.logger.info("triage-tick: settings invalid, skipping", { issues });
|
|
1762
|
+
return;
|
|
1763
|
+
}
|
|
1764
|
+
if (!settings.triageEnabled) {
|
|
1765
|
+
ctx.logger.info("triage-tick: triageEnabled is off, skipping");
|
|
1766
|
+
return;
|
|
1767
|
+
}
|
|
1768
|
+
if (!settings.sourceViewId) {
|
|
1769
|
+
ctx.logger.info("triage-tick: no sourceViewId configured, skipping");
|
|
1770
|
+
return;
|
|
1771
|
+
}
|
|
1772
|
+
const clock = createRealClock();
|
|
1773
|
+
const now = clock.now();
|
|
1774
|
+
const pipelineState = await readPipelineState(ctx.api);
|
|
1775
|
+
const lastTriageAt = toDate(pipelineState?.data.lastTriageAt);
|
|
1776
|
+
if (lastTriageAt) {
|
|
1777
|
+
const dueAt = lastTriageAt.getTime() + settings.triageIntervalMinutes * 6e4;
|
|
1778
|
+
if (now.getTime() < dueAt) {
|
|
1779
|
+
ctx.logger.info("triage-tick: not due yet, skipping");
|
|
1780
|
+
return;
|
|
1781
|
+
}
|
|
1782
|
+
}
|
|
1783
|
+
await runTriageBatch(ctx, config, settings);
|
|
1784
|
+
}
|
|
1785
|
+
async function resolveTicketUrlBase(ctx) {
|
|
1786
|
+
try {
|
|
1787
|
+
const connections = await ctx.api.integrations.list("gorgias");
|
|
1788
|
+
const connection = connections.find((candidate) => candidate.isDefault) ?? connections[0];
|
|
1789
|
+
const result = await ctx.api.integrations.run(
|
|
1790
|
+
"gorgias",
|
|
1791
|
+
"getTicketUrlBase",
|
|
1792
|
+
{},
|
|
1793
|
+
connection ? { connectionId: connection.id } : void 0
|
|
1794
|
+
);
|
|
1795
|
+
return typeof result?.base === "string" && result.base !== "" ? result.base : null;
|
|
1796
|
+
} catch (err) {
|
|
1797
|
+
ctx.logger.warn("triage-tick: could not resolve the Gorgias ticket url base, decisions will carry no deep link", {
|
|
1798
|
+
error: err instanceof Error ? err.message : String(err)
|
|
1799
|
+
});
|
|
1800
|
+
return null;
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
function ticketUrlFor(base, ticketId) {
|
|
1804
|
+
return base ? `${base}/${encodeURIComponent(ticketId)}` : null;
|
|
1805
|
+
}
|
|
1806
|
+
async function runTriageBatch(ctx, config, settings) {
|
|
1807
|
+
const dryRun = settings.dryRun === true;
|
|
1808
|
+
const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx), ctx.api) : buildTicketPorts(ctx);
|
|
1809
|
+
const categories = await listCategories(ctx.api);
|
|
1810
|
+
const batchDefaultAgent = await resolveDraftAgent(ctx.api, null);
|
|
1811
|
+
const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(batchDefaultAgent, config), settings.nodes));
|
|
1812
|
+
const ticketUrlBase = await resolveTicketUrlBase(ctx);
|
|
1813
|
+
const refs = await ports.conversation.listPending({ viewOrTag: settings.sourceViewId }, settings.batchLimit);
|
|
1814
|
+
const run = await ctx.api.runs.start({
|
|
1815
|
+
kind: "triage-tick",
|
|
1816
|
+
message: `${dryRun ? "Dry-run triage tick" : "Triage tick"} over ${refs.length} ticket(s)`,
|
|
1817
|
+
metadata: { sourceViewId: settings.sourceViewId, ticketCount: refs.length, dryRun }
|
|
1818
|
+
});
|
|
1819
|
+
let failureCount = 0;
|
|
1820
|
+
try {
|
|
1821
|
+
for (const ref of refs) {
|
|
1822
|
+
try {
|
|
1823
|
+
await processOneTicket(ctx, ref, {
|
|
1824
|
+
config,
|
|
1825
|
+
profile,
|
|
1826
|
+
categories,
|
|
1827
|
+
ports,
|
|
1828
|
+
runId: run.id,
|
|
1829
|
+
ticketUrlBase
|
|
1830
|
+
});
|
|
1831
|
+
} catch (err) {
|
|
1832
|
+
failureCount += 1;
|
|
1833
|
+
await handleTicketFailure(ctx, ref, err, {
|
|
1834
|
+
profile,
|
|
1835
|
+
ports,
|
|
1836
|
+
runId: run.id,
|
|
1837
|
+
ticketUrlBase
|
|
1838
|
+
});
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
await ctx.api.runs.succeed(run.id, { ticketCount: refs.length, failureCount });
|
|
1842
|
+
} catch (err) {
|
|
1843
|
+
await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });
|
|
1844
|
+
throw err;
|
|
1845
|
+
} finally {
|
|
1846
|
+
await upsertPipelineState(ctx.api, { sourceViewId: settings.sourceViewId, lastTriageAt: ports.clock.now() });
|
|
1847
|
+
}
|
|
1848
|
+
return { ticketCount: refs.length, failureCount };
|
|
1849
|
+
}
|
|
1850
|
+
var ResponsePhaseError = class extends Error {
|
|
1851
|
+
generatedResponseId;
|
|
1852
|
+
constructor(generatedResponseId, cause) {
|
|
1853
|
+
super(cause instanceof Error ? cause.message : String(cause));
|
|
1854
|
+
this.name = "ResponsePhaseError";
|
|
1855
|
+
this.generatedResponseId = generatedResponseId;
|
|
1856
|
+
}
|
|
1857
|
+
};
|
|
1858
|
+
async function handleTicketFailure(ctx, ref, err, deps) {
|
|
1859
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1860
|
+
ctx.logger.error(`triage-tick: ticket ${ref.id} failed, escalating it and continuing with the rest of the batch`, {
|
|
1861
|
+
error: message
|
|
1862
|
+
});
|
|
1863
|
+
if (err instanceof ResponsePhaseError) {
|
|
1864
|
+
await finalizeFailedResponse(ctx, ref, err.generatedResponseId, message);
|
|
1865
|
+
} else {
|
|
1866
|
+
await writeErrorDecision(ctx, ref, message, deps);
|
|
1867
|
+
}
|
|
1868
|
+
await escalateTicket(ctx, ref, deps);
|
|
1869
|
+
}
|
|
1870
|
+
async function finalizeFailedResponse(ctx, ref, generatedResponseId, message) {
|
|
1871
|
+
try {
|
|
1872
|
+
await transitionGeneratedResponse(ctx.api, {
|
|
1873
|
+
id: generatedResponseId,
|
|
1874
|
+
ticketId: ref.id,
|
|
1875
|
+
from: "pending",
|
|
1876
|
+
to: "failed",
|
|
1877
|
+
extra: { error: message }
|
|
1878
|
+
});
|
|
1879
|
+
} catch (writeErr) {
|
|
1880
|
+
ctx.logger.error(`triage-tick: failed to finalise the response of ticket ${ref.id}`, {
|
|
1881
|
+
error: writeErr instanceof Error ? writeErr.message : String(writeErr)
|
|
1882
|
+
});
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
async function writeErrorDecision(ctx, ref, message, deps) {
|
|
1886
|
+
try {
|
|
1887
|
+
await ctx.api.create("triage-decision", {
|
|
1888
|
+
ticketId: ref.id,
|
|
1889
|
+
ticketUrl: ticketUrlFor(deps.ticketUrlBase, ref.id),
|
|
1890
|
+
decidedAt: deps.ports.clock.now(),
|
|
1891
|
+
status: "error",
|
|
1892
|
+
error: message,
|
|
1893
|
+
confidence: "low",
|
|
1894
|
+
runId: deps.runId,
|
|
1895
|
+
subjectRenamed: false
|
|
1896
|
+
});
|
|
1897
|
+
} catch (writeErr) {
|
|
1898
|
+
ctx.logger.error(`triage-tick: failed to record the error decision for ticket ${ref.id}`, {
|
|
1899
|
+
error: writeErr instanceof Error ? writeErr.message : String(writeErr)
|
|
1900
|
+
});
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
async function escalateTicket(ctx, ref, deps) {
|
|
1904
|
+
const tag = deps.profile.audit.escalationTag;
|
|
1905
|
+
if (!tag) {
|
|
1906
|
+
ctx.logger.warn(`triage-tick: ticket ${ref.id} failed but escalationTag is not configured \u2014 no tag applied`);
|
|
1907
|
+
return;
|
|
1908
|
+
}
|
|
1909
|
+
try {
|
|
1910
|
+
await deps.ports.state.flag(ref, tag);
|
|
1911
|
+
} catch (flagErr) {
|
|
1912
|
+
ctx.logger.error(`triage-tick: failed to escalate ticket ${ref.id} \u2014 it is NOT tagged for a human`, {
|
|
1913
|
+
error: flagErr instanceof Error ? flagErr.message : String(flagErr)
|
|
1914
|
+
});
|
|
1915
|
+
}
|
|
1916
|
+
}
|
|
1917
|
+
async function processOneTicket(ctx, ref, deps) {
|
|
1918
|
+
const { config, profile, categories, ports, runId, ticketUrlBase } = deps;
|
|
1919
|
+
let subjectRenamed = false;
|
|
1920
|
+
if (profile.rename) {
|
|
1921
|
+
const conversation2 = await ports.conversation.read(ref);
|
|
1922
|
+
const subject = conversation2.subject ?? "";
|
|
1923
|
+
if (subject.includes(profile.rename.from)) {
|
|
1924
|
+
await ports.state.rename(ref, subject.replace(profile.rename.from, profile.rename.to));
|
|
1925
|
+
subjectRenamed = true;
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });
|
|
1929
|
+
const state = await runTicket(
|
|
1930
|
+
{
|
|
1931
|
+
ref,
|
|
1932
|
+
profile,
|
|
1933
|
+
ports: { ...ports },
|
|
1934
|
+
toolContext: createNoToolContext(),
|
|
1935
|
+
budget,
|
|
1936
|
+
// Unknown until triage runs — no node reached in the `until:'triage'`
|
|
1937
|
+
// phase reads `deps.category` (`run-ticket.ts`'s early return happens
|
|
1938
|
+
// before any node touches it).
|
|
1939
|
+
category: { autoReplyEnabled: true, minConfidence: null },
|
|
1940
|
+
categories: toCategoryReferential(categories),
|
|
1941
|
+
log: (msg) => ctx.logger.debug(msg),
|
|
1942
|
+
send: { mode: "none" }
|
|
1943
|
+
},
|
|
1944
|
+
{ until: "triage" }
|
|
1945
|
+
);
|
|
1946
|
+
if (!state.classification) throw new Error("triage produced no classification");
|
|
1947
|
+
const { classification } = state;
|
|
1948
|
+
const category = findCategoryByTag(categories, classification.category);
|
|
1949
|
+
const decision = await ctx.api.create("triage-decision", {
|
|
1950
|
+
ticketId: ref.id,
|
|
1951
|
+
ticketUrl: ticketUrlFor(ticketUrlBase, ref.id),
|
|
1952
|
+
decidedAt: ports.clock.now(),
|
|
1953
|
+
categoryId: category?.id ?? null,
|
|
1954
|
+
tag: classification.category,
|
|
1955
|
+
confidence: classification.confidence,
|
|
1956
|
+
reasoning: classification.reasoning,
|
|
1957
|
+
conversationOver: classification.conversationOver ?? false,
|
|
1958
|
+
escalated: state.escalated,
|
|
1959
|
+
status: "ok",
|
|
1960
|
+
runId,
|
|
1961
|
+
subjectRenamed
|
|
1962
|
+
});
|
|
1963
|
+
await ports.state.record(ref, classification, profile.audit);
|
|
1964
|
+
if (!isEligibleForGeneratedResponse(profile, classification, state.escalated, category)) return;
|
|
1965
|
+
const draftAgent = await resolveDraftAgent(ctx.api, category?.agentId ?? null);
|
|
1966
|
+
const conversation = state.conversation;
|
|
1967
|
+
const channel = conversation?.sourceChannel === "whatsapp" ? "whatsapp" : "email";
|
|
1968
|
+
const generatedAt = ports.clock.now();
|
|
1969
|
+
const expiresAt = new Date(generatedAt.getTime() + profile.schedule.fastResponseTtlMinutes * 6e4);
|
|
1970
|
+
let created;
|
|
1971
|
+
try {
|
|
1972
|
+
created = await ctx.api.create("generated-response", {
|
|
1973
|
+
ticketId: ref.id,
|
|
1974
|
+
openTicketKey: openTicketKeyFor("pending", ref.id),
|
|
1975
|
+
status: "pending",
|
|
1976
|
+
triageDecisionId: decision.id,
|
|
1977
|
+
categoryId: category?.id ?? null,
|
|
1978
|
+
agentId: draftAgent?.id ?? null,
|
|
1979
|
+
channel,
|
|
1980
|
+
generatedAt,
|
|
1981
|
+
expiresAt,
|
|
1982
|
+
sources: [],
|
|
1983
|
+
tracedInput: [],
|
|
1984
|
+
guardrailHits: [],
|
|
1985
|
+
servedTo: [],
|
|
1986
|
+
servedCount: 0,
|
|
1987
|
+
followupRequired: false
|
|
1988
|
+
});
|
|
1989
|
+
} catch (err) {
|
|
1990
|
+
if (err instanceof AppApiError && err.status === 409) {
|
|
1991
|
+
ctx.logger.debug(`triage-tick: generated-response already pending for ticket ${ref.id}, skipping`);
|
|
1992
|
+
return;
|
|
1993
|
+
}
|
|
1994
|
+
throw err;
|
|
1995
|
+
}
|
|
1996
|
+
try {
|
|
1997
|
+
await respondToPendingResponse(ctx, config, created.id);
|
|
1998
|
+
} catch (err) {
|
|
1999
|
+
throw new ResponsePhaseError(created.id, err);
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
1973
2002
|
var STALE_SENDING_THRESHOLD_MS = 30 * 6e4;
|
|
1974
2003
|
var SWEEP_PAGE_SIZE = 500;
|
|
1975
2004
|
function buildSweepFunctionDef(config) {
|
|
@@ -2244,6 +2273,7 @@ var EXT_RESPONSE_COMPARISON_INPUT_CONVERSATION_MESSAGES_UID = "0a985d59-fd20-467
|
|
|
2244
2273
|
var CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID = "1039e196-cf6e-438e-8ec9-7ab422feaf4d";
|
|
2245
2274
|
var CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID = "10ffe3e1-972e-43b4-bb45-343c4664464f";
|
|
2246
2275
|
var SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID = "2f5d6cbb-1c69-4a76-9d8f-1a3f0a4e57c2";
|
|
2276
|
+
var INVALIDATE_RESPONSE_INPUT_GENERATED_RESPONSE_ID_UID = "9748baf5-97be-4a22-940d-46ef2f16a175";
|
|
2247
2277
|
|
|
2248
2278
|
// src/functions/run-triage-now.ts
|
|
2249
2279
|
var TRIAGE_RUN_REQUESTED_EVENT = "triage.run.requested";
|
|
@@ -2332,6 +2362,53 @@ function assertRunnable(ctx, settings, ignoreTriageDisabled) {
|
|
|
2332
2362
|
throw new ctx.NonRetriableError("Triage is disabled (triageEnabled is off) \u2014 pass ignoreTriageDisabled to override.");
|
|
2333
2363
|
}
|
|
2334
2364
|
}
|
|
2365
|
+
function buildInvalidateResponseFunctionDef(config) {
|
|
2366
|
+
return {
|
|
2367
|
+
universalIdentifier: identifierFor(config, "invalidate-response"),
|
|
2368
|
+
name: "invalidate-response",
|
|
2369
|
+
trigger: { type: "uiInvoke", minRole: "EDITOR", timeoutMs: 1e4 },
|
|
2370
|
+
input: [
|
|
2371
|
+
{
|
|
2372
|
+
universalIdentifier: INVALIDATE_RESPONSE_INPUT_GENERATED_RESPONSE_ID_UID,
|
|
2373
|
+
name: "generatedResponseId",
|
|
2374
|
+
type: FieldType.TEXT,
|
|
2375
|
+
label: "Generated response id",
|
|
2376
|
+
isNullable: false
|
|
2377
|
+
}
|
|
2378
|
+
]
|
|
2379
|
+
};
|
|
2380
|
+
}
|
|
2381
|
+
function createInvalidateResponseHandler() {
|
|
2382
|
+
return (ctx, input) => invalidateResponseHandler(ctx, input ?? {});
|
|
2383
|
+
}
|
|
2384
|
+
var REFUSALS = {
|
|
2385
|
+
sending: "La r\xE9ponse est en cours d'envoi \u2014 elle ne peut plus \xEAtre invalid\xE9e.",
|
|
2386
|
+
sent: "La r\xE9ponse a d\xE9j\xE0 \xE9t\xE9 envoy\xE9e au client \u2014 elle ne peut plus \xEAtre invalid\xE9e."
|
|
2387
|
+
};
|
|
2388
|
+
async function invalidateResponseHandler(ctx, input) {
|
|
2389
|
+
const id = input?.generatedResponseId?.trim();
|
|
2390
|
+
if (!id) throw new ctx.NonRetriableError("generatedResponseId is required");
|
|
2391
|
+
const record = await getOptional(ctx, "generated-response", id);
|
|
2392
|
+
if (!record) throw new ctx.NonRetriableError(`R\xE9ponse g\xE9n\xE9r\xE9e introuvable (${id}).`);
|
|
2393
|
+
const data = record.data;
|
|
2394
|
+
const status = String(data.status ?? "");
|
|
2395
|
+
if (status === "invalidated") return { status: "invalidated" };
|
|
2396
|
+
if (!isGeneratedResponseStatus(status) || !isInvalidatableStatus(status)) {
|
|
2397
|
+
throw new ctx.NonRetriableError(
|
|
2398
|
+
REFUSALS[status] ?? `La r\xE9ponse est en statut terminal "${status}" \u2014 le ticket est d\xE9j\xE0 libre d'\xEAtre retrait\xE9.`
|
|
2399
|
+
);
|
|
2400
|
+
}
|
|
2401
|
+
const moved = await transitionGeneratedResponse(ctx.api, {
|
|
2402
|
+
id,
|
|
2403
|
+
ticketId: String(data.ticketId ?? ""),
|
|
2404
|
+
from: status,
|
|
2405
|
+
to: "invalidated"
|
|
2406
|
+
});
|
|
2407
|
+
if (!moved) {
|
|
2408
|
+
throw new ctx.NonRetriableError("La r\xE9ponse a chang\xE9 d'\xE9tat entre-temps \u2014 actualisez la page avant de r\xE9essayer.");
|
|
2409
|
+
}
|
|
2410
|
+
return { status: "invalidated" };
|
|
2411
|
+
}
|
|
2335
2412
|
function buildPreviewTriageFunctionDef(config) {
|
|
2336
2413
|
return {
|
|
2337
2414
|
universalIdentifier: identifierFor(config, "preview-triage"),
|
|
@@ -3899,11 +3976,6 @@ var SUPPORT_KIT_INTEGRATIONS = [
|
|
|
3899
3976
|
var SUPPORT_KIT_EMITS = [TRIAGE_RUN_REQUESTED_EVENT];
|
|
3900
3977
|
var FUNCTION_ASSEMBLY = [
|
|
3901
3978
|
{ key: "triage-tick", build: buildTriageTickFunctionDef, createHandler: createTriageTickHandler },
|
|
3902
|
-
{
|
|
3903
|
-
key: "process-response",
|
|
3904
|
-
build: buildProcessResponseFunctionDef,
|
|
3905
|
-
createHandler: createProcessResponseHandler
|
|
3906
|
-
},
|
|
3907
3979
|
{ key: "sweep", build: buildSweepFunctionDef, createHandler: () => createSweepHandler() },
|
|
3908
3980
|
{
|
|
3909
3981
|
key: "handle-approval",
|
|
@@ -3920,6 +3992,11 @@ var FUNCTION_ASSEMBLY = [
|
|
|
3920
3992
|
build: buildRunTriageBatchFunctionDef,
|
|
3921
3993
|
createHandler: createRunTriageBatchHandler
|
|
3922
3994
|
},
|
|
3995
|
+
{
|
|
3996
|
+
key: "invalidate-response",
|
|
3997
|
+
build: buildInvalidateResponseFunctionDef,
|
|
3998
|
+
createHandler: () => createInvalidateResponseHandler()
|
|
3999
|
+
},
|
|
3923
4000
|
{
|
|
3924
4001
|
key: "preview-triage",
|
|
3925
4002
|
build: buildPreviewTriageFunctionDef,
|