@apotech-os/support-kit 5.0.0 → 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/index.cjs CHANGED
@@ -1094,7 +1094,7 @@ function isGeneratedResponseStatus(value) {
1094
1094
  return typeof value === "string" && GENERATED_RESPONSE_STATUSES.includes(value);
1095
1095
  }
1096
1096
  var ALLOWED_TRANSITIONS = {
1097
- pending: ["ready", "failed", "no_reply_needed", "sending"],
1097
+ pending: ["ready", "failed", "no_reply_needed", "sending", "invalidated"],
1098
1098
  ready: ["sending", "invalidated", "expired"],
1099
1099
  sending: ["sent", "ready"],
1100
1100
  sent: [],
@@ -1107,6 +1107,9 @@ function canTransition(from, to) {
1107
1107
  if (!isGeneratedResponseStatus(from) || !isGeneratedResponseStatus(to)) return false;
1108
1108
  return ALLOWED_TRANSITIONS[from].includes(to);
1109
1109
  }
1110
+ function isInvalidatableStatus(status) {
1111
+ return canTransition(status, "invalidated");
1112
+ }
1110
1113
  function isTerminalStatus(status) {
1111
1114
  if (!isGeneratedResponseStatus(status)) return false;
1112
1115
  return ALLOWED_TRANSITIONS[status].length === 0;
@@ -1240,7 +1243,9 @@ function createPromptResolver(deps) {
1240
1243
  return null;
1241
1244
  });
1242
1245
  if (cached) {
1243
- return served({ name, text: substituteVars(cached.content, vars), version: cached.version, config: null }, label);
1246
+ const text2 = substituteVars(cached.content, vars);
1247
+ if (text2.trim() !== "") return { name, text: text2, version: cached.version, config: null };
1248
+ deps.onDegraded?.({ stage: "cache-empty", name, reason: "the prompt-cache mirror holds no text" });
1244
1249
  }
1245
1250
  const rawFallback = ref.fallback ?? "";
1246
1251
  const text = hasReferences(rawFallback) ? await composeReferences(rawFallback, composeCtx, /* @__PURE__ */ new Set([name]), 0) : rawFallback;
@@ -1264,18 +1269,15 @@ function createPromptResolver(deps) {
1264
1269
  deps.onDegraded?.({ stage: "platform-unavailable", name: ref.name, reason: reasonOf(err) });
1265
1270
  return resolveFromCacheOrFallback(ref.name, label, ref, vars);
1266
1271
  }
1267
- if (!hasReferences(resolved.content)) {
1272
+ if (resolved.content.trim() !== "" && !hasReferences(resolved.content)) {
1268
1273
  await deps.cache.write(persistKey, { content: resolved.content, version: resolved.version }).catch(() => void 0);
1269
1274
  }
1270
- return served(
1271
- {
1272
- name: ref.name,
1273
- text: substituteVars(resolved.content, vars),
1274
- version: resolved.version,
1275
- config: toResolvedConfig(resolved.config)
1276
- },
1277
- label
1278
- );
1275
+ const text = substituteVars(resolved.content, vars);
1276
+ if (text.trim() === "") {
1277
+ deps.onDegraded?.({ stage: "platform-empty", name: ref.name, reason: "the platform read resolved to no text" });
1278
+ return resolveFromCacheOrFallback(ref.name, label, ref, vars);
1279
+ }
1280
+ return { name: ref.name, text, version: resolved.version, config: toResolvedConfig(resolved.config) };
1279
1281
  }
1280
1282
  };
1281
1283
  }
@@ -2462,7 +2464,7 @@ var SUPPORT_KIT_SETTINGS_FIELDS = [
2462
2464
  { key: "escalationTag", type: "string", label: "Escalation tag", default: "wai/escalated" },
2463
2465
  { key: "autoRepliedTag", type: "string", label: "Auto-replied tag", default: "wai/auto-replied" },
2464
2466
  { key: "needsReviewTag", type: "string", label: "Review-before-send tag", default: "wai/escalated" },
2465
- { key: "followupTag", type: "string", label: "Followup tag", default: "wai/followup-required" },
2467
+ { key: "followupTag", type: "string", label: "Followup tag", default: "wai/human-required" },
2466
2468
  // Sending
2467
2469
  { key: "autoSendEnabled", type: "boolean", label: "Auto-send enabled", default: false },
2468
2470
  { key: "senderEmail", type: "string", label: "Sender email", default: "" },
@@ -3080,6 +3082,70 @@ async function upsertPipelineState(api, patch) {
3080
3082
  { uniqueBy: ["singletonKey"] }
3081
3083
  );
3082
3084
  }
3085
+ function buildSendSeam(params) {
3086
+ const { api, clock, id, ticketId, fromStatus, extraClaimData } = params;
3087
+ return {
3088
+ async claim(run) {
3089
+ assertTransition(fromStatus, "sending");
3090
+ try {
3091
+ await api.update(
3092
+ "generated-response",
3093
+ id,
3094
+ {
3095
+ status: "sending",
3096
+ sendingAt: clock.now(),
3097
+ openTicketKey: openTicketKeyFor("sending", ticketId),
3098
+ ...extraClaimData ? extraClaimData(run) : {}
3099
+ },
3100
+ { ifMatch: { status: fromStatus } }
3101
+ );
3102
+ return true;
3103
+ } catch (err) {
3104
+ if (err instanceof appKit.AppApiError && err.status === 409) return false;
3105
+ throw err;
3106
+ }
3107
+ },
3108
+ async commit(messageId) {
3109
+ assertTransition("sending", "sent");
3110
+ await api.update(
3111
+ "generated-response",
3112
+ id,
3113
+ {
3114
+ status: "sent",
3115
+ sentAt: clock.now(),
3116
+ sentMessageId: messageId,
3117
+ openTicketKey: openTicketKeyFor("sent", ticketId)
3118
+ },
3119
+ { ifMatch: { status: "sending" } }
3120
+ );
3121
+ }
3122
+ };
3123
+ }
3124
+
3125
+ // src/functions/approval-key.ts
3126
+ var PREFIX = "generated-response:";
3127
+ function buildApprovalKey(generatedResponseId) {
3128
+ return `${PREFIX}${generatedResponseId}`;
3129
+ }
3130
+ function parseApprovalKey(key) {
3131
+ if (!key.startsWith(PREFIX)) return null;
3132
+ const id = key.slice(PREFIX.length);
3133
+ return id.length > 0 ? id : null;
3134
+ }
3135
+ function buildInboxKey(generatedResponseId, suffix) {
3136
+ return suffix ? `${PREFIX}${generatedResponseId}:${suffix}` : `${PREFIX}${generatedResponseId}`;
3137
+ }
3138
+
3139
+ // src/functions/traced-input.ts
3140
+ var TRACED_INPUT_MAX_CHARS = 4e3;
3141
+ var TRUNCATION_MARK = "\u2026 [tronqu\xE9]";
3142
+ function toTracedInput(messages) {
3143
+ return messages.map((message) => ({ role: message.role, content: cap(message.content ?? "") }));
3144
+ }
3145
+ function cap(content) {
3146
+ if (content.length <= TRACED_INPUT_MAX_CHARS) return content;
3147
+ return `${content.slice(0, TRACED_INPUT_MAX_CHARS)}${TRUNCATION_MARK}`;
3148
+ }
3083
3149
 
3084
3150
  // src/functions/records.ts
3085
3151
  function toAgent(record) {
@@ -3216,6 +3282,188 @@ function buildPromptsTable(config, draft2, nodes) {
3216
3282
  };
3217
3283
  }
3218
3284
 
3285
+ // src/functions/process-response.ts
3286
+ function classificationFromDecision(decision) {
3287
+ const data = decision.data;
3288
+ return {
3289
+ category: data.tag ?? "",
3290
+ confidence: data.confidence ?? "low",
3291
+ reasoning: data.reasoning ?? "",
3292
+ isFallback: false,
3293
+ conversationOver: data.conversationOver ?? false
3294
+ };
3295
+ }
3296
+ function attributionFields(attribution) {
3297
+ return {
3298
+ langfuseTraceId: attribution?.traceId ?? null,
3299
+ langfuseObservationId: attribution?.observationId ?? null,
3300
+ promptName: attribution?.promptName ?? null,
3301
+ promptVersion: attribution?.promptVersion ?? null
3302
+ };
3303
+ }
3304
+ async function finalizeNonSent(ctx, id, ticketId, toStatus, extra) {
3305
+ assertTransition("pending", toStatus);
3306
+ try {
3307
+ await ctx.api.update(
3308
+ "generated-response",
3309
+ id,
3310
+ { status: toStatus, openTicketKey: openTicketKeyFor(toStatus, ticketId), ...extra },
3311
+ { ifMatch: { status: "pending" } }
3312
+ );
3313
+ return true;
3314
+ } catch (err) {
3315
+ if (err instanceof appKit.AppApiError && err.status === 409) {
3316
+ ctx.logger.info(`respond: generated-response ${id} was already moved off "pending" by another worker, abandoning`);
3317
+ return false;
3318
+ }
3319
+ throw err;
3320
+ }
3321
+ }
3322
+ async function respondToPendingResponse(ctx, config, recordId) {
3323
+ const record = await getOptional(ctx, "generated-response", recordId);
3324
+ if (!record) {
3325
+ ctx.logger.info(`respond: generated-response ${recordId} no longer exists, skipping`);
3326
+ return;
3327
+ }
3328
+ const data = record.data;
3329
+ if (data.status !== "pending") {
3330
+ ctx.logger.info(`respond: generated-response ${recordId} is not pending (status="${String(data.status)}"), skipping \u2014 already handled by another worker`);
3331
+ return;
3332
+ }
3333
+ const settings = await ctx.api.settings.get();
3334
+ if (validateSettings(settings).length > 0) {
3335
+ ctx.logger.info("respond: settings invalid, skipping");
3336
+ return;
3337
+ }
3338
+ const ticketId = data.ticketId;
3339
+ const ref = { id: ticketId, channel: "gorgias" };
3340
+ const decision = await getOptional(ctx, "triage-decision", data.triageDecisionId ?? null);
3341
+ if (!decision) {
3342
+ ctx.logger.error(`respond: generated-response ${recordId} has no resolvable triage-decision, marking failed`);
3343
+ await finalizeNonSent(ctx, recordId, ticketId, "failed", { error: "triage-decision not found" });
3344
+ return;
3345
+ }
3346
+ const classification = classificationFromDecision(decision);
3347
+ const escalated = decision.data.escalated === true;
3348
+ const categoryRecord = await getOptional(ctx, "category", data.categoryId ?? null);
3349
+ const category = categoryRecord ? toCategory(categoryRecord) : null;
3350
+ const agentRecord2 = data.agentId ? await getOptional(ctx, "agent", data.agentId) : null;
3351
+ const agent = agentRecord2 ? toAgent(agentRecord2) : await resolveDraftAgent(ctx.api, null);
3352
+ const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));
3353
+ const dryRun = settings.dryRun === true;
3354
+ const trace = { sessionId: ticketId, tags: [`app:${config.slug}`] };
3355
+ const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx, trace), ctx.api) : buildTicketPorts(ctx, trace);
3356
+ const { clock } = ports;
3357
+ const conversationSnapshot = await ports.conversation.read(ref);
3358
+ const generatedAt = data.generatedAt instanceof Date ? data.generatedAt : new Date(data.generatedAt);
3359
+ const seam = buildSendSeam({
3360
+ api: ctx.api,
3361
+ clock,
3362
+ id: recordId,
3363
+ ticketId,
3364
+ fromStatus: "pending",
3365
+ extraClaimData: (run) => ({
3366
+ responseText: run.draft.text,
3367
+ sources: run.draft.sources,
3368
+ tracedInput: toTracedInput(run.draft.messages),
3369
+ verdict: run.verdict,
3370
+ generatedMessageCount: conversationSnapshot.messageCount,
3371
+ generatedLastMessageAt: conversationSnapshot.lastMessageAt,
3372
+ ...attributionFields(run.draft.attribution)
3373
+ })
3374
+ });
3375
+ const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS2 });
3376
+ const result = await runTicket(
3377
+ {
3378
+ ref,
3379
+ profile,
3380
+ ports,
3381
+ toolContext: createNoToolContext(),
3382
+ budget,
3383
+ category: { autoReplyEnabled: category?.autoReplyEnabled ?? false, minConfidence: null },
3384
+ categories: [],
3385
+ log: (msg) => ctx.logger.debug(msg),
3386
+ send: dryRun ? { mode: "none" } : { mode: "claimed", claim: seam.claim, commit: seam.commit },
3387
+ queuedAt: generatedAt
3388
+ },
3389
+ { resume: { classification, escalated } }
3390
+ );
3391
+ const draftExtra = {
3392
+ responseText: result.draft?.text ?? null,
3393
+ sources: result.draft?.sources ?? [],
3394
+ // The rendered system prompt and the customer's own turns, which nothing
3395
+ // else persists (spec-vue-tickets-unifiee-v1 §4.1). Written on BOTH write
3396
+ // paths — the send seam's claim above and this finalisation — because a
3397
+ // sent reply and a held one are read by the same timeline.
3398
+ tracedInput: toTracedInput(result.draft?.messages ?? []),
3399
+ verdict: result.verdict ?? null,
3400
+ generatedMessageCount: conversationSnapshot.messageCount,
3401
+ generatedLastMessageAt: conversationSnapshot.lastMessageAt,
3402
+ ...attributionFields(result.draft?.attribution)
3403
+ };
3404
+ switch (result.outcome) {
3405
+ case "sent":
3406
+ if (dryRun) {
3407
+ await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3408
+ return;
3409
+ }
3410
+ return;
3411
+ case "ready":
3412
+ case "guardrail_hold":
3413
+ await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3414
+ return;
3415
+ case "needs_human": {
3416
+ const persisted = await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3417
+ if (persisted) {
3418
+ await ctx.api.inbox.raise({
3419
+ key: buildInboxKey(recordId),
3420
+ severity: "warning",
3421
+ title: `R\xE9ponse g\xE9n\xE9r\xE9e \xE0 revoir \u2014 ticket ${ticketId}`,
3422
+ entityRef: { appSlug: config.slug, objectKey: "generated-response", id: recordId }
3423
+ });
3424
+ }
3425
+ return;
3426
+ }
3427
+ case "awaiting_approval": {
3428
+ const persisted = await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3429
+ if (persisted && !dryRun) {
3430
+ await ctx.api.approvals.request({
3431
+ key: buildApprovalKey(recordId),
3432
+ title: `Approuver l'envoi automatique \u2014 ticket ${ticketId}`,
3433
+ entityRef: { appSlug: config.slug, objectKey: "generated-response", id: recordId }
3434
+ });
3435
+ }
3436
+ return;
3437
+ }
3438
+ case "escalated":
3439
+ case "triaged_only":
3440
+ case "no_reply_needed":
3441
+ await finalizeNonSent(ctx, recordId, ticketId, "no_reply_needed", draftExtra);
3442
+ return;
3443
+ case "failed":
3444
+ await finalizeNonSent(ctx, recordId, ticketId, "failed", { ...draftExtra, error: "runTicket outcome: failed" });
3445
+ return;
3446
+ default:
3447
+ ctx.logger.error(`respond: generated-response ${recordId} resumed run ended with no outcome`);
3448
+ }
3449
+ }
3450
+ async function transitionGeneratedResponse(api, params) {
3451
+ const { id, ticketId, from, to, extra } = params;
3452
+ assertTransition(from, to);
3453
+ try {
3454
+ await api.update(
3455
+ "generated-response",
3456
+ id,
3457
+ { status: to, openTicketKey: openTicketKeyFor(to, ticketId), ...extra ?? {} },
3458
+ { ifMatch: { status: from } }
3459
+ );
3460
+ return true;
3461
+ } catch (err) {
3462
+ if (err instanceof appKit.AppApiError && err.status === 409) return false;
3463
+ throw err;
3464
+ }
3465
+ }
3466
+
3219
3467
  // src/functions/triage-tick.ts
3220
3468
  function buildTriageTickFunctionDef(config) {
3221
3469
  return {
@@ -3297,6 +3545,7 @@ async function runTriageBatch(ctx, config, settings) {
3297
3545
  for (const ref of refs) {
3298
3546
  try {
3299
3547
  await processOneTicket(ctx, ref, {
3548
+ config,
3300
3549
  profile,
3301
3550
  categories,
3302
3551
  ports,
@@ -3305,24 +3554,12 @@ async function runTriageBatch(ctx, config, settings) {
3305
3554
  });
3306
3555
  } catch (err) {
3307
3556
  failureCount += 1;
3308
- const message = err instanceof Error ? err.message : String(err);
3309
- ctx.logger.error(`triage-tick: ticket ${ref.id} failed, continuing with the rest of the batch`, { error: message });
3310
- try {
3311
- await ctx.api.create("triage-decision", {
3312
- ticketId: ref.id,
3313
- ticketUrl: ticketUrlFor(ticketUrlBase, ref.id),
3314
- decidedAt: ports.clock.now(),
3315
- status: "error",
3316
- error: message,
3317
- confidence: "low",
3318
- runId: run.id,
3319
- subjectRenamed: false
3320
- });
3321
- } catch (writeErr) {
3322
- ctx.logger.error(`triage-tick: failed to record the error decision for ticket ${ref.id}`, {
3323
- error: writeErr instanceof Error ? writeErr.message : String(writeErr)
3324
- });
3325
- }
3557
+ await handleTicketFailure(ctx, ref, err, {
3558
+ profile,
3559
+ ports,
3560
+ runId: run.id,
3561
+ ticketUrlBase
3562
+ });
3326
3563
  }
3327
3564
  }
3328
3565
  await ctx.api.runs.succeed(run.id, { ticketCount: refs.length, failureCount });
@@ -3334,11 +3571,78 @@ async function runTriageBatch(ctx, config, settings) {
3334
3571
  }
3335
3572
  return { ticketCount: refs.length, failureCount };
3336
3573
  }
3337
- async function processOneTicket(ctx, ref, deps) {
3338
- const { profile, categories, ports, runId, ticketUrlBase } = deps;
3339
- let subjectRenamed = false;
3340
- if (profile.rename) {
3341
- const conversation2 = await ports.conversation.read(ref);
3574
+ var ResponsePhaseError = class extends Error {
3575
+ generatedResponseId;
3576
+ constructor(generatedResponseId, cause) {
3577
+ super(cause instanceof Error ? cause.message : String(cause));
3578
+ this.name = "ResponsePhaseError";
3579
+ this.generatedResponseId = generatedResponseId;
3580
+ }
3581
+ };
3582
+ async function handleTicketFailure(ctx, ref, err, deps) {
3583
+ const message = err instanceof Error ? err.message : String(err);
3584
+ ctx.logger.error(`triage-tick: ticket ${ref.id} failed, escalating it and continuing with the rest of the batch`, {
3585
+ error: message
3586
+ });
3587
+ if (err instanceof ResponsePhaseError) {
3588
+ await finalizeFailedResponse(ctx, ref, err.generatedResponseId, message);
3589
+ } else {
3590
+ await writeErrorDecision(ctx, ref, message, deps);
3591
+ }
3592
+ await escalateTicket(ctx, ref, deps);
3593
+ }
3594
+ async function finalizeFailedResponse(ctx, ref, generatedResponseId, message) {
3595
+ try {
3596
+ await transitionGeneratedResponse(ctx.api, {
3597
+ id: generatedResponseId,
3598
+ ticketId: ref.id,
3599
+ from: "pending",
3600
+ to: "failed",
3601
+ extra: { error: message }
3602
+ });
3603
+ } catch (writeErr) {
3604
+ ctx.logger.error(`triage-tick: failed to finalise the response of ticket ${ref.id}`, {
3605
+ error: writeErr instanceof Error ? writeErr.message : String(writeErr)
3606
+ });
3607
+ }
3608
+ }
3609
+ async function writeErrorDecision(ctx, ref, message, deps) {
3610
+ try {
3611
+ await ctx.api.create("triage-decision", {
3612
+ ticketId: ref.id,
3613
+ ticketUrl: ticketUrlFor(deps.ticketUrlBase, ref.id),
3614
+ decidedAt: deps.ports.clock.now(),
3615
+ status: "error",
3616
+ error: message,
3617
+ confidence: "low",
3618
+ runId: deps.runId,
3619
+ subjectRenamed: false
3620
+ });
3621
+ } catch (writeErr) {
3622
+ ctx.logger.error(`triage-tick: failed to record the error decision for ticket ${ref.id}`, {
3623
+ error: writeErr instanceof Error ? writeErr.message : String(writeErr)
3624
+ });
3625
+ }
3626
+ }
3627
+ async function escalateTicket(ctx, ref, deps) {
3628
+ const tag = deps.profile.audit.escalationTag;
3629
+ if (!tag) {
3630
+ ctx.logger.warn(`triage-tick: ticket ${ref.id} failed but escalationTag is not configured \u2014 no tag applied`);
3631
+ return;
3632
+ }
3633
+ try {
3634
+ await deps.ports.state.flag(ref, tag);
3635
+ } catch (flagErr) {
3636
+ ctx.logger.error(`triage-tick: failed to escalate ticket ${ref.id} \u2014 it is NOT tagged for a human`, {
3637
+ error: flagErr instanceof Error ? flagErr.message : String(flagErr)
3638
+ });
3639
+ }
3640
+ }
3641
+ async function processOneTicket(ctx, ref, deps) {
3642
+ const { config, profile, categories, ports, runId, ticketUrlBase } = deps;
3643
+ let subjectRenamed = false;
3644
+ if (profile.rename) {
3645
+ const conversation2 = await ports.conversation.read(ref);
3342
3646
  const subject = conversation2.subject ?? "";
3343
3647
  if (subject.includes(profile.rename.from)) {
3344
3648
  await ports.state.rename(ref, subject.replace(profile.rename.from, profile.rename.to));
@@ -3363,19 +3667,7 @@ async function processOneTicket(ctx, ref, deps) {
3363
3667
  },
3364
3668
  { until: "triage" }
3365
3669
  );
3366
- if (!state.classification) {
3367
- await ctx.api.create("triage-decision", {
3368
- ticketId: ref.id,
3369
- ticketUrl: ticketUrlFor(ticketUrlBase, ref.id),
3370
- decidedAt: ports.clock.now(),
3371
- status: "error",
3372
- error: "triage produced no classification",
3373
- confidence: "low",
3374
- runId,
3375
- subjectRenamed
3376
- });
3377
- return;
3378
- }
3670
+ if (!state.classification) throw new Error("triage produced no classification");
3379
3671
  const { classification } = state;
3380
3672
  const category = findCategoryByTag(categories, classification.category);
3381
3673
  const decision = await ctx.api.create("triage-decision", {
@@ -3399,8 +3691,9 @@ async function processOneTicket(ctx, ref, deps) {
3399
3691
  const channel = conversation?.sourceChannel === "whatsapp" ? "whatsapp" : "email";
3400
3692
  const generatedAt = ports.clock.now();
3401
3693
  const expiresAt = new Date(generatedAt.getTime() + profile.schedule.fastResponseTtlMinutes * 6e4);
3694
+ let created;
3402
3695
  try {
3403
- await ctx.api.create("generated-response", {
3696
+ created = await ctx.api.create("generated-response", {
3404
3697
  ticketId: ref.id,
3405
3698
  openTicketKey: openTicketKeyFor("pending", ref.id),
3406
3699
  status: "pending",
@@ -3424,273 +3717,12 @@ async function processOneTicket(ctx, ref, deps) {
3424
3717
  }
3425
3718
  throw err;
3426
3719
  }
3427
- }
3428
- function buildSendSeam(params) {
3429
- const { api, clock, id, ticketId, fromStatus, extraClaimData } = params;
3430
- return {
3431
- async claim(run) {
3432
- assertTransition(fromStatus, "sending");
3433
- try {
3434
- await api.update(
3435
- "generated-response",
3436
- id,
3437
- {
3438
- status: "sending",
3439
- sendingAt: clock.now(),
3440
- openTicketKey: openTicketKeyFor("sending", ticketId),
3441
- ...extraClaimData ? extraClaimData(run) : {}
3442
- },
3443
- { ifMatch: { status: fromStatus } }
3444
- );
3445
- return true;
3446
- } catch (err) {
3447
- if (err instanceof appKit.AppApiError && err.status === 409) return false;
3448
- throw err;
3449
- }
3450
- },
3451
- async commit(messageId) {
3452
- assertTransition("sending", "sent");
3453
- await api.update(
3454
- "generated-response",
3455
- id,
3456
- {
3457
- status: "sent",
3458
- sentAt: clock.now(),
3459
- sentMessageId: messageId,
3460
- openTicketKey: openTicketKeyFor("sent", ticketId)
3461
- },
3462
- { ifMatch: { status: "sending" } }
3463
- );
3464
- }
3465
- };
3466
- }
3467
-
3468
- // src/functions/approval-key.ts
3469
- var PREFIX = "generated-response:";
3470
- function buildApprovalKey(generatedResponseId) {
3471
- return `${PREFIX}${generatedResponseId}`;
3472
- }
3473
- function parseApprovalKey(key) {
3474
- if (!key.startsWith(PREFIX)) return null;
3475
- const id = key.slice(PREFIX.length);
3476
- return id.length > 0 ? id : null;
3477
- }
3478
- function buildInboxKey(generatedResponseId, suffix) {
3479
- return suffix ? `${PREFIX}${generatedResponseId}:${suffix}` : `${PREFIX}${generatedResponseId}`;
3480
- }
3481
-
3482
- // src/functions/traced-input.ts
3483
- var TRACED_INPUT_MAX_CHARS = 4e3;
3484
- var TRUNCATION_MARK = "\u2026 [tronqu\xE9]";
3485
- function toTracedInput(messages) {
3486
- return messages.map((message) => ({ role: message.role, content: cap(message.content ?? "") }));
3487
- }
3488
- function cap(content) {
3489
- if (content.length <= TRACED_INPUT_MAX_CHARS) return content;
3490
- return `${content.slice(0, TRACED_INPUT_MAX_CHARS)}${TRUNCATION_MARK}`;
3491
- }
3492
-
3493
- // src/functions/process-response.ts
3494
- function classificationFromDecision(decision) {
3495
- const data = decision.data;
3496
- return {
3497
- category: data.tag ?? "",
3498
- confidence: data.confidence ?? "low",
3499
- reasoning: data.reasoning ?? "",
3500
- isFallback: false,
3501
- conversationOver: data.conversationOver ?? false
3502
- };
3503
- }
3504
- function attributionFields(attribution) {
3505
- return {
3506
- langfuseTraceId: attribution?.traceId ?? null,
3507
- langfuseObservationId: attribution?.observationId ?? null,
3508
- promptName: attribution?.promptName ?? null,
3509
- promptVersion: attribution?.promptVersion ?? null
3510
- };
3511
- }
3512
- async function finalizeNonSent(ctx, id, ticketId, toStatus, extra) {
3513
- assertTransition("pending", toStatus);
3514
3720
  try {
3515
- await ctx.api.update(
3516
- "generated-response",
3517
- id,
3518
- { status: toStatus, openTicketKey: openTicketKeyFor(toStatus, ticketId), ...extra },
3519
- { ifMatch: { status: "pending" } }
3520
- );
3521
- return true;
3721
+ await respondToPendingResponse(ctx, config, created.id);
3522
3722
  } catch (err) {
3523
- if (err instanceof appKit.AppApiError && err.status === 409) {
3524
- ctx.logger.info(`process-response: generated-response ${id} was already moved off "pending" by another worker, abandoning`);
3525
- return false;
3526
- }
3527
- throw err;
3723
+ throw new ResponsePhaseError(created.id, err);
3528
3724
  }
3529
3725
  }
3530
- function buildProcessResponseFunctionDef(config) {
3531
- return {
3532
- universalIdentifier: identifierFor(config, "process-response"),
3533
- name: "process-response",
3534
- trigger: { type: "dbEvent", objectRef: `app:${config.slug}/generated-response`, operation: "created" },
3535
- retries: 3,
3536
- concurrency: 3,
3537
- notify: { onFailure: true, severity: "warning" }
3538
- };
3539
- }
3540
- function createProcessResponseHandler(config) {
3541
- return (ctx) => processResponseHandler(ctx, config);
3542
- }
3543
- async function processResponseHandler(ctx, config) {
3544
- const recordId = ctx.event.recordId;
3545
- if (!recordId) {
3546
- ctx.logger.warn("process-response: event carried no recordId, skipping");
3547
- return;
3548
- }
3549
- const record = await getOptional(ctx, "generated-response", recordId);
3550
- if (!record) {
3551
- ctx.logger.info(`process-response: generated-response ${recordId} no longer exists, skipping`);
3552
- return;
3553
- }
3554
- const data = record.data;
3555
- if (data.status !== "pending") {
3556
- ctx.logger.info(`process-response: generated-response ${recordId} is not pending (status="${String(data.status)}"), skipping \u2014 already handled or a dbEvent redelivery`);
3557
- return;
3558
- }
3559
- const settings = await ctx.api.settings.get();
3560
- if (validateSettings(settings).length > 0) {
3561
- ctx.logger.info("process-response: settings invalid, skipping");
3562
- return;
3563
- }
3564
- const ticketId = data.ticketId;
3565
- const ref = { id: ticketId, channel: "gorgias" };
3566
- const decision = await getOptional(ctx, "triage-decision", data.triageDecisionId ?? null);
3567
- if (!decision) {
3568
- ctx.logger.error(`process-response: generated-response ${recordId} has no resolvable triage-decision, marking failed`);
3569
- await finalizeNonSent(ctx, recordId, ticketId, "failed", { error: "triage-decision not found" });
3570
- return;
3571
- }
3572
- const classification = classificationFromDecision(decision);
3573
- const escalated = decision.data.escalated === true;
3574
- const categoryRecord = await getOptional(ctx, "category", data.categoryId ?? null);
3575
- const category = categoryRecord ? toCategory(categoryRecord) : null;
3576
- const agentRecord2 = data.agentId ? await getOptional(ctx, "agent", data.agentId) : null;
3577
- const agent = agentRecord2 ? toAgent(agentRecord2) : await resolveDraftAgent(ctx.api, null);
3578
- const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));
3579
- const dryRun = settings.dryRun === true;
3580
- const trace = { sessionId: ticketId, tags: [`app:${config.slug}`] };
3581
- const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx, trace), ctx.api) : buildTicketPorts(ctx, trace);
3582
- const { clock } = ports;
3583
- const conversationSnapshot = await ports.conversation.read(ref);
3584
- const generatedAt = data.generatedAt instanceof Date ? data.generatedAt : new Date(data.generatedAt);
3585
- const seam = buildSendSeam({
3586
- api: ctx.api,
3587
- clock,
3588
- id: recordId,
3589
- ticketId,
3590
- fromStatus: "pending",
3591
- extraClaimData: (run) => ({
3592
- responseText: run.draft.text,
3593
- sources: run.draft.sources,
3594
- tracedInput: toTracedInput(run.draft.messages),
3595
- verdict: run.verdict,
3596
- generatedMessageCount: conversationSnapshot.messageCount,
3597
- generatedLastMessageAt: conversationSnapshot.lastMessageAt,
3598
- ...attributionFields(run.draft.attribution)
3599
- })
3600
- });
3601
- const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS2 });
3602
- const result = await runTicket(
3603
- {
3604
- ref,
3605
- profile,
3606
- ports,
3607
- toolContext: createNoToolContext(),
3608
- budget,
3609
- category: { autoReplyEnabled: category?.autoReplyEnabled ?? false, minConfidence: null },
3610
- categories: [],
3611
- log: (msg) => ctx.logger.debug(msg),
3612
- send: dryRun ? { mode: "none" } : { mode: "claimed", claim: seam.claim, commit: seam.commit },
3613
- queuedAt: generatedAt
3614
- },
3615
- { resume: { classification, escalated } }
3616
- );
3617
- const draftExtra = {
3618
- responseText: result.draft?.text ?? null,
3619
- sources: result.draft?.sources ?? [],
3620
- // The rendered system prompt and the customer's own turns, which nothing
3621
- // else persists (spec-vue-tickets-unifiee-v1 §4.1). Written on BOTH write
3622
- // paths — the send seam's claim above and this finalisation — because a
3623
- // sent reply and a held one are read by the same timeline.
3624
- tracedInput: toTracedInput(result.draft?.messages ?? []),
3625
- verdict: result.verdict ?? null,
3626
- generatedMessageCount: conversationSnapshot.messageCount,
3627
- generatedLastMessageAt: conversationSnapshot.lastMessageAt,
3628
- ...attributionFields(result.draft?.attribution)
3629
- };
3630
- switch (result.outcome) {
3631
- case "sent":
3632
- if (dryRun) {
3633
- await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3634
- return;
3635
- }
3636
- return;
3637
- case "ready":
3638
- case "guardrail_hold":
3639
- await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3640
- return;
3641
- case "needs_human": {
3642
- const persisted = await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3643
- if (persisted) {
3644
- await ctx.api.inbox.raise({
3645
- key: buildInboxKey(recordId),
3646
- severity: "warning",
3647
- title: `R\xE9ponse g\xE9n\xE9r\xE9e \xE0 revoir \u2014 ticket ${ticketId}`,
3648
- entityRef: { appSlug: config.slug, objectKey: "generated-response", id: recordId }
3649
- });
3650
- }
3651
- return;
3652
- }
3653
- case "awaiting_approval": {
3654
- const persisted = await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3655
- if (persisted && !dryRun) {
3656
- await ctx.api.approvals.request({
3657
- key: buildApprovalKey(recordId),
3658
- title: `Approuver l'envoi automatique \u2014 ticket ${ticketId}`,
3659
- entityRef: { appSlug: config.slug, objectKey: "generated-response", id: recordId }
3660
- });
3661
- }
3662
- return;
3663
- }
3664
- case "escalated":
3665
- case "triaged_only":
3666
- case "no_reply_needed":
3667
- await finalizeNonSent(ctx, recordId, ticketId, "no_reply_needed", draftExtra);
3668
- return;
3669
- case "failed":
3670
- await finalizeNonSent(ctx, recordId, ticketId, "failed", { ...draftExtra, error: "runTicket outcome: failed" });
3671
- return;
3672
- default:
3673
- ctx.logger.error(`process-response: generated-response ${recordId} resumed run ended with no outcome`);
3674
- }
3675
- }
3676
- async function transitionGeneratedResponse(api, params) {
3677
- const { id, ticketId, from, to, extra } = params;
3678
- assertTransition(from, to);
3679
- try {
3680
- await api.update(
3681
- "generated-response",
3682
- id,
3683
- { status: to, openTicketKey: openTicketKeyFor(to, ticketId), ...extra ?? {} },
3684
- { ifMatch: { status: from } }
3685
- );
3686
- return true;
3687
- } catch (err) {
3688
- if (err instanceof appKit.AppApiError && err.status === 409) return false;
3689
- throw err;
3690
- }
3691
- }
3692
-
3693
- // src/functions/sweep.ts
3694
3726
  var STALE_SENDING_THRESHOLD_MS = 30 * 6e4;
3695
3727
  var SWEEP_PAGE_SIZE = 500;
3696
3728
  function buildSweepFunctionDef(config) {
@@ -3961,6 +3993,7 @@ var EXT_RESPONSE_COMPARISON_INPUT_CONVERSATION_MESSAGES_UID = "0a985d59-fd20-467
3961
3993
  var CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID = "1039e196-cf6e-438e-8ec9-7ab422feaf4d";
3962
3994
  var CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID = "10ffe3e1-972e-43b4-bb45-343c4664464f";
3963
3995
  var SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID = "2f5d6cbb-1c69-4a76-9d8f-1a3f0a4e57c2";
3996
+ var INVALIDATE_RESPONSE_INPUT_GENERATED_RESPONSE_ID_UID = "9748baf5-97be-4a22-940d-46ef2f16a175";
3964
3997
 
3965
3998
  // src/functions/run-triage-now.ts
3966
3999
  var TRIAGE_RUN_REQUESTED_EVENT = "triage.run.requested";
@@ -4049,6 +4082,53 @@ function assertRunnable(ctx, settings, ignoreTriageDisabled) {
4049
4082
  throw new ctx.NonRetriableError("Triage is disabled (triageEnabled is off) \u2014 pass ignoreTriageDisabled to override.");
4050
4083
  }
4051
4084
  }
4085
+ function buildInvalidateResponseFunctionDef(config) {
4086
+ return {
4087
+ universalIdentifier: identifierFor(config, "invalidate-response"),
4088
+ name: "invalidate-response",
4089
+ trigger: { type: "uiInvoke", minRole: "EDITOR", timeoutMs: 1e4 },
4090
+ input: [
4091
+ {
4092
+ universalIdentifier: INVALIDATE_RESPONSE_INPUT_GENERATED_RESPONSE_ID_UID,
4093
+ name: "generatedResponseId",
4094
+ type: appKit.FieldType.TEXT,
4095
+ label: "Generated response id",
4096
+ isNullable: false
4097
+ }
4098
+ ]
4099
+ };
4100
+ }
4101
+ function createInvalidateResponseHandler() {
4102
+ return (ctx, input) => invalidateResponseHandler(ctx, input ?? {});
4103
+ }
4104
+ var REFUSALS = {
4105
+ sending: "La r\xE9ponse est en cours d'envoi \u2014 elle ne peut plus \xEAtre invalid\xE9e.",
4106
+ sent: "La r\xE9ponse a d\xE9j\xE0 \xE9t\xE9 envoy\xE9e au client \u2014 elle ne peut plus \xEAtre invalid\xE9e."
4107
+ };
4108
+ async function invalidateResponseHandler(ctx, input) {
4109
+ const id = input?.generatedResponseId?.trim();
4110
+ if (!id) throw new ctx.NonRetriableError("generatedResponseId is required");
4111
+ const record = await getOptional(ctx, "generated-response", id);
4112
+ if (!record) throw new ctx.NonRetriableError(`R\xE9ponse g\xE9n\xE9r\xE9e introuvable (${id}).`);
4113
+ const data = record.data;
4114
+ const status = String(data.status ?? "");
4115
+ if (status === "invalidated") return { status: "invalidated" };
4116
+ if (!isGeneratedResponseStatus(status) || !isInvalidatableStatus(status)) {
4117
+ throw new ctx.NonRetriableError(
4118
+ REFUSALS[status] ?? `La r\xE9ponse est en statut terminal "${status}" \u2014 le ticket est d\xE9j\xE0 libre d'\xEAtre retrait\xE9.`
4119
+ );
4120
+ }
4121
+ const moved = await transitionGeneratedResponse(ctx.api, {
4122
+ id,
4123
+ ticketId: String(data.ticketId ?? ""),
4124
+ from: status,
4125
+ to: "invalidated"
4126
+ });
4127
+ if (!moved) {
4128
+ throw new ctx.NonRetriableError("La r\xE9ponse a chang\xE9 d'\xE9tat entre-temps \u2014 actualisez la page avant de r\xE9essayer.");
4129
+ }
4130
+ return { status: "invalidated" };
4131
+ }
4052
4132
  function buildPreviewTriageFunctionDef(config) {
4053
4133
  return {
4054
4134
  universalIdentifier: identifierFor(config, "preview-triage"),
@@ -5652,11 +5732,6 @@ var SUPPORT_KIT_INTEGRATIONS = [
5652
5732
  var SUPPORT_KIT_EMITS = [TRIAGE_RUN_REQUESTED_EVENT];
5653
5733
  var FUNCTION_ASSEMBLY = [
5654
5734
  { key: "triage-tick", build: buildTriageTickFunctionDef, createHandler: createTriageTickHandler },
5655
- {
5656
- key: "process-response",
5657
- build: buildProcessResponseFunctionDef,
5658
- createHandler: createProcessResponseHandler
5659
- },
5660
5735
  { key: "sweep", build: buildSweepFunctionDef, createHandler: () => createSweepHandler() },
5661
5736
  {
5662
5737
  key: "handle-approval",
@@ -5673,6 +5748,11 @@ var FUNCTION_ASSEMBLY = [
5673
5748
  build: buildRunTriageBatchFunctionDef,
5674
5749
  createHandler: createRunTriageBatchHandler
5675
5750
  },
5751
+ {
5752
+ key: "invalidate-response",
5753
+ build: buildInvalidateResponseFunctionDef,
5754
+ createHandler: () => createInvalidateResponseHandler()
5755
+ },
5676
5756
  {
5677
5757
  key: "preview-triage",
5678
5758
  build: buildPreviewTriageFunctionDef,