@apotech-os/support-kit 5.0.1 → 6.1.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
@@ -157,14 +157,18 @@ function isStopMessage(message) {
157
157
  const cleaned = normalise(message).replace(/^[^\p{L}\d]+|[^\p{L}\d]+$/gu, "").replace(/\s+/g, " ");
158
158
  return STOP_PHRASES.has(cleaned);
159
159
  }
160
+ var ATTACHMENT_MARKER_ONLY = /^\[Pièces? jointes? : \d+ fichiers?\]$/;
161
+ function isCustomerTurnWithWords(message) {
162
+ return message.role === "user" && !ATTACHMENT_MARKER_ONLY.test(message.content.trim());
163
+ }
160
164
  function firstCustomerMessage(conversation) {
161
- return conversation.messages.find((m) => m.role === "user")?.content ?? null;
165
+ return conversation.messages.find(isCustomerTurnWithWords)?.content ?? null;
162
166
  }
163
167
  function lastCustomerMessage(conversation) {
164
168
  const { messages } = conversation;
165
169
  for (let i = messages.length - 1; i >= 0; i--) {
166
170
  const message = messages[i];
167
- if (message?.role === "user") return message.content;
171
+ if (message && isCustomerTurnWithWords(message)) return message.content;
168
172
  }
169
173
  return null;
170
174
  }
@@ -1094,7 +1098,7 @@ function isGeneratedResponseStatus(value) {
1094
1098
  return typeof value === "string" && GENERATED_RESPONSE_STATUSES.includes(value);
1095
1099
  }
1096
1100
  var ALLOWED_TRANSITIONS = {
1097
- pending: ["ready", "failed", "no_reply_needed", "sending"],
1101
+ pending: ["ready", "failed", "no_reply_needed", "sending", "invalidated"],
1098
1102
  ready: ["sending", "invalidated", "expired"],
1099
1103
  sending: ["sent", "ready"],
1100
1104
  sent: [],
@@ -1107,6 +1111,9 @@ function canTransition(from, to) {
1107
1111
  if (!isGeneratedResponseStatus(from) || !isGeneratedResponseStatus(to)) return false;
1108
1112
  return ALLOWED_TRANSITIONS[from].includes(to);
1109
1113
  }
1114
+ function isInvalidatableStatus(status) {
1115
+ return canTransition(status, "invalidated");
1116
+ }
1110
1117
  function isTerminalStatus(status) {
1111
1118
  if (!isGeneratedResponseStatus(status)) return false;
1112
1119
  return ALLOWED_TRANSITIONS[status].length === 0;
@@ -1240,7 +1247,9 @@ function createPromptResolver(deps) {
1240
1247
  return null;
1241
1248
  });
1242
1249
  if (cached) {
1243
- return served({ name, text: substituteVars(cached.content, vars), version: cached.version, config: null }, label);
1250
+ const text2 = substituteVars(cached.content, vars);
1251
+ if (text2.trim() !== "") return { name, text: text2, version: cached.version, config: null };
1252
+ deps.onDegraded?.({ stage: "cache-empty", name, reason: "the prompt-cache mirror holds no text" });
1244
1253
  }
1245
1254
  const rawFallback = ref.fallback ?? "";
1246
1255
  const text = hasReferences(rawFallback) ? await composeReferences(rawFallback, composeCtx, /* @__PURE__ */ new Set([name]), 0) : rawFallback;
@@ -1264,18 +1273,15 @@ function createPromptResolver(deps) {
1264
1273
  deps.onDegraded?.({ stage: "platform-unavailable", name: ref.name, reason: reasonOf(err) });
1265
1274
  return resolveFromCacheOrFallback(ref.name, label, ref, vars);
1266
1275
  }
1267
- if (!hasReferences(resolved.content)) {
1276
+ if (resolved.content.trim() !== "" && !hasReferences(resolved.content)) {
1268
1277
  await deps.cache.write(persistKey, { content: resolved.content, version: resolved.version }).catch(() => void 0);
1269
1278
  }
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
- );
1279
+ const text = substituteVars(resolved.content, vars);
1280
+ if (text.trim() === "") {
1281
+ deps.onDegraded?.({ stage: "platform-empty", name: ref.name, reason: "the platform read resolved to no text" });
1282
+ return resolveFromCacheOrFallback(ref.name, label, ref, vars);
1283
+ }
1284
+ return { name: ref.name, text, version: resolved.version, config: toResolvedConfig(resolved.config) };
1279
1285
  }
1280
1286
  };
1281
1287
  }
@@ -3080,6 +3086,70 @@ async function upsertPipelineState(api, patch) {
3080
3086
  { uniqueBy: ["singletonKey"] }
3081
3087
  );
3082
3088
  }
3089
+ function buildSendSeam(params) {
3090
+ const { api, clock, id, ticketId, fromStatus, extraClaimData } = params;
3091
+ return {
3092
+ async claim(run) {
3093
+ assertTransition(fromStatus, "sending");
3094
+ try {
3095
+ await api.update(
3096
+ "generated-response",
3097
+ id,
3098
+ {
3099
+ status: "sending",
3100
+ sendingAt: clock.now(),
3101
+ openTicketKey: openTicketKeyFor("sending", ticketId),
3102
+ ...extraClaimData ? extraClaimData(run) : {}
3103
+ },
3104
+ { ifMatch: { status: fromStatus } }
3105
+ );
3106
+ return true;
3107
+ } catch (err) {
3108
+ if (err instanceof appKit.AppApiError && err.status === 409) return false;
3109
+ throw err;
3110
+ }
3111
+ },
3112
+ async commit(messageId) {
3113
+ assertTransition("sending", "sent");
3114
+ await api.update(
3115
+ "generated-response",
3116
+ id,
3117
+ {
3118
+ status: "sent",
3119
+ sentAt: clock.now(),
3120
+ sentMessageId: messageId,
3121
+ openTicketKey: openTicketKeyFor("sent", ticketId)
3122
+ },
3123
+ { ifMatch: { status: "sending" } }
3124
+ );
3125
+ }
3126
+ };
3127
+ }
3128
+
3129
+ // src/functions/approval-key.ts
3130
+ var PREFIX = "generated-response:";
3131
+ function buildApprovalKey(generatedResponseId) {
3132
+ return `${PREFIX}${generatedResponseId}`;
3133
+ }
3134
+ function parseApprovalKey(key) {
3135
+ if (!key.startsWith(PREFIX)) return null;
3136
+ const id = key.slice(PREFIX.length);
3137
+ return id.length > 0 ? id : null;
3138
+ }
3139
+ function buildInboxKey(generatedResponseId, suffix) {
3140
+ return suffix ? `${PREFIX}${generatedResponseId}:${suffix}` : `${PREFIX}${generatedResponseId}`;
3141
+ }
3142
+
3143
+ // src/functions/traced-input.ts
3144
+ var TRACED_INPUT_MAX_CHARS = 4e3;
3145
+ var TRUNCATION_MARK = "\u2026 [tronqu\xE9]";
3146
+ function toTracedInput(messages) {
3147
+ return messages.map((message) => ({ role: message.role, content: cap(message.content ?? "") }));
3148
+ }
3149
+ function cap(content) {
3150
+ if (content.length <= TRACED_INPUT_MAX_CHARS) return content;
3151
+ return `${content.slice(0, TRACED_INPUT_MAX_CHARS)}${TRUNCATION_MARK}`;
3152
+ }
3083
3153
 
3084
3154
  // src/functions/records.ts
3085
3155
  function toAgent(record) {
@@ -3216,6 +3286,188 @@ function buildPromptsTable(config, draft2, nodes) {
3216
3286
  };
3217
3287
  }
3218
3288
 
3289
+ // src/functions/process-response.ts
3290
+ function classificationFromDecision(decision) {
3291
+ const data = decision.data;
3292
+ return {
3293
+ category: data.tag ?? "",
3294
+ confidence: data.confidence ?? "low",
3295
+ reasoning: data.reasoning ?? "",
3296
+ isFallback: false,
3297
+ conversationOver: data.conversationOver ?? false
3298
+ };
3299
+ }
3300
+ function attributionFields(attribution) {
3301
+ return {
3302
+ langfuseTraceId: attribution?.traceId ?? null,
3303
+ langfuseObservationId: attribution?.observationId ?? null,
3304
+ promptName: attribution?.promptName ?? null,
3305
+ promptVersion: attribution?.promptVersion ?? null
3306
+ };
3307
+ }
3308
+ async function finalizeNonSent(ctx, id, ticketId, toStatus, extra) {
3309
+ assertTransition("pending", toStatus);
3310
+ try {
3311
+ await ctx.api.update(
3312
+ "generated-response",
3313
+ id,
3314
+ { status: toStatus, openTicketKey: openTicketKeyFor(toStatus, ticketId), ...extra },
3315
+ { ifMatch: { status: "pending" } }
3316
+ );
3317
+ return true;
3318
+ } catch (err) {
3319
+ if (err instanceof appKit.AppApiError && err.status === 409) {
3320
+ ctx.logger.info(`respond: generated-response ${id} was already moved off "pending" by another worker, abandoning`);
3321
+ return false;
3322
+ }
3323
+ throw err;
3324
+ }
3325
+ }
3326
+ async function respondToPendingResponse(ctx, config, recordId) {
3327
+ const record = await getOptional(ctx, "generated-response", recordId);
3328
+ if (!record) {
3329
+ ctx.logger.info(`respond: generated-response ${recordId} no longer exists, skipping`);
3330
+ return;
3331
+ }
3332
+ const data = record.data;
3333
+ if (data.status !== "pending") {
3334
+ ctx.logger.info(`respond: generated-response ${recordId} is not pending (status="${String(data.status)}"), skipping \u2014 already handled by another worker`);
3335
+ return;
3336
+ }
3337
+ const settings = await ctx.api.settings.get();
3338
+ if (validateSettings(settings).length > 0) {
3339
+ ctx.logger.info("respond: settings invalid, skipping");
3340
+ return;
3341
+ }
3342
+ const ticketId = data.ticketId;
3343
+ const ref = { id: ticketId, channel: "gorgias" };
3344
+ const decision = await getOptional(ctx, "triage-decision", data.triageDecisionId ?? null);
3345
+ if (!decision) {
3346
+ ctx.logger.error(`respond: generated-response ${recordId} has no resolvable triage-decision, marking failed`);
3347
+ await finalizeNonSent(ctx, recordId, ticketId, "failed", { error: "triage-decision not found" });
3348
+ return;
3349
+ }
3350
+ const classification = classificationFromDecision(decision);
3351
+ const escalated = decision.data.escalated === true;
3352
+ const categoryRecord = await getOptional(ctx, "category", data.categoryId ?? null);
3353
+ const category = categoryRecord ? toCategory(categoryRecord) : null;
3354
+ const agentRecord2 = data.agentId ? await getOptional(ctx, "agent", data.agentId) : null;
3355
+ const agent = agentRecord2 ? toAgent(agentRecord2) : await resolveDraftAgent(ctx.api, null);
3356
+ const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));
3357
+ const dryRun = settings.dryRun === true;
3358
+ const trace = { sessionId: ticketId, tags: [`app:${config.slug}`] };
3359
+ const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx, trace), ctx.api) : buildTicketPorts(ctx, trace);
3360
+ const { clock } = ports;
3361
+ const conversationSnapshot = await ports.conversation.read(ref);
3362
+ const generatedAt = data.generatedAt instanceof Date ? data.generatedAt : new Date(data.generatedAt);
3363
+ const seam = buildSendSeam({
3364
+ api: ctx.api,
3365
+ clock,
3366
+ id: recordId,
3367
+ ticketId,
3368
+ fromStatus: "pending",
3369
+ extraClaimData: (run) => ({
3370
+ responseText: run.draft.text,
3371
+ sources: run.draft.sources,
3372
+ tracedInput: toTracedInput(run.draft.messages),
3373
+ verdict: run.verdict,
3374
+ generatedMessageCount: conversationSnapshot.messageCount,
3375
+ generatedLastMessageAt: conversationSnapshot.lastMessageAt,
3376
+ ...attributionFields(run.draft.attribution)
3377
+ })
3378
+ });
3379
+ const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS2 });
3380
+ const result = await runTicket(
3381
+ {
3382
+ ref,
3383
+ profile,
3384
+ ports,
3385
+ toolContext: createNoToolContext(),
3386
+ budget,
3387
+ category: { autoReplyEnabled: category?.autoReplyEnabled ?? false, minConfidence: null },
3388
+ categories: [],
3389
+ log: (msg) => ctx.logger.debug(msg),
3390
+ send: dryRun ? { mode: "none" } : { mode: "claimed", claim: seam.claim, commit: seam.commit },
3391
+ queuedAt: generatedAt
3392
+ },
3393
+ { resume: { classification, escalated } }
3394
+ );
3395
+ const draftExtra = {
3396
+ responseText: result.draft?.text ?? null,
3397
+ sources: result.draft?.sources ?? [],
3398
+ // The rendered system prompt and the customer's own turns, which nothing
3399
+ // else persists (spec-vue-tickets-unifiee-v1 §4.1). Written on BOTH write
3400
+ // paths — the send seam's claim above and this finalisation — because a
3401
+ // sent reply and a held one are read by the same timeline.
3402
+ tracedInput: toTracedInput(result.draft?.messages ?? []),
3403
+ verdict: result.verdict ?? null,
3404
+ generatedMessageCount: conversationSnapshot.messageCount,
3405
+ generatedLastMessageAt: conversationSnapshot.lastMessageAt,
3406
+ ...attributionFields(result.draft?.attribution)
3407
+ };
3408
+ switch (result.outcome) {
3409
+ case "sent":
3410
+ if (dryRun) {
3411
+ await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3412
+ return;
3413
+ }
3414
+ return;
3415
+ case "ready":
3416
+ case "guardrail_hold":
3417
+ await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3418
+ return;
3419
+ case "needs_human": {
3420
+ const persisted = await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3421
+ if (persisted) {
3422
+ await ctx.api.inbox.raise({
3423
+ key: buildInboxKey(recordId),
3424
+ severity: "warning",
3425
+ title: `R\xE9ponse g\xE9n\xE9r\xE9e \xE0 revoir \u2014 ticket ${ticketId}`,
3426
+ entityRef: { appSlug: config.slug, objectKey: "generated-response", id: recordId }
3427
+ });
3428
+ }
3429
+ return;
3430
+ }
3431
+ case "awaiting_approval": {
3432
+ const persisted = await finalizeNonSent(ctx, recordId, ticketId, "ready", draftExtra);
3433
+ if (persisted && !dryRun) {
3434
+ await ctx.api.approvals.request({
3435
+ key: buildApprovalKey(recordId),
3436
+ title: `Approuver l'envoi automatique \u2014 ticket ${ticketId}`,
3437
+ entityRef: { appSlug: config.slug, objectKey: "generated-response", id: recordId }
3438
+ });
3439
+ }
3440
+ return;
3441
+ }
3442
+ case "escalated":
3443
+ case "triaged_only":
3444
+ case "no_reply_needed":
3445
+ await finalizeNonSent(ctx, recordId, ticketId, "no_reply_needed", draftExtra);
3446
+ return;
3447
+ case "failed":
3448
+ await finalizeNonSent(ctx, recordId, ticketId, "failed", { ...draftExtra, error: "runTicket outcome: failed" });
3449
+ return;
3450
+ default:
3451
+ ctx.logger.error(`respond: generated-response ${recordId} resumed run ended with no outcome`);
3452
+ }
3453
+ }
3454
+ async function transitionGeneratedResponse(api, params) {
3455
+ const { id, ticketId, from, to, extra } = params;
3456
+ assertTransition(from, to);
3457
+ try {
3458
+ await api.update(
3459
+ "generated-response",
3460
+ id,
3461
+ { status: to, openTicketKey: openTicketKeyFor(to, ticketId), ...extra ?? {} },
3462
+ { ifMatch: { status: from } }
3463
+ );
3464
+ return true;
3465
+ } catch (err) {
3466
+ if (err instanceof appKit.AppApiError && err.status === 409) return false;
3467
+ throw err;
3468
+ }
3469
+ }
3470
+
3219
3471
  // src/functions/triage-tick.ts
3220
3472
  function buildTriageTickFunctionDef(config) {
3221
3473
  return {
@@ -3297,6 +3549,7 @@ async function runTriageBatch(ctx, config, settings) {
3297
3549
  for (const ref of refs) {
3298
3550
  try {
3299
3551
  await processOneTicket(ctx, ref, {
3552
+ config,
3300
3553
  profile,
3301
3554
  categories,
3302
3555
  ports,
@@ -3305,24 +3558,12 @@ async function runTriageBatch(ctx, config, settings) {
3305
3558
  });
3306
3559
  } catch (err) {
3307
3560
  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
- }
3561
+ await handleTicketFailure(ctx, ref, err, {
3562
+ profile,
3563
+ ports,
3564
+ runId: run.id,
3565
+ ticketUrlBase
3566
+ });
3326
3567
  }
3327
3568
  }
3328
3569
  await ctx.api.runs.succeed(run.id, { ticketCount: refs.length, failureCount });
@@ -3334,10 +3575,77 @@ async function runTriageBatch(ctx, config, settings) {
3334
3575
  }
3335
3576
  return { ticketCount: refs.length, failureCount };
3336
3577
  }
3337
- async function processOneTicket(ctx, ref, deps) {
3338
- const { profile, categories, ports, runId, ticketUrlBase } = deps;
3339
- let subjectRenamed = false;
3340
- if (profile.rename) {
3578
+ var ResponsePhaseError = class extends Error {
3579
+ generatedResponseId;
3580
+ constructor(generatedResponseId, cause) {
3581
+ super(cause instanceof Error ? cause.message : String(cause));
3582
+ this.name = "ResponsePhaseError";
3583
+ this.generatedResponseId = generatedResponseId;
3584
+ }
3585
+ };
3586
+ async function handleTicketFailure(ctx, ref, err, deps) {
3587
+ const message = err instanceof Error ? err.message : String(err);
3588
+ ctx.logger.error(`triage-tick: ticket ${ref.id} failed, escalating it and continuing with the rest of the batch`, {
3589
+ error: message
3590
+ });
3591
+ if (err instanceof ResponsePhaseError) {
3592
+ await finalizeFailedResponse(ctx, ref, err.generatedResponseId, message);
3593
+ } else {
3594
+ await writeErrorDecision(ctx, ref, message, deps);
3595
+ }
3596
+ await escalateTicket(ctx, ref, deps);
3597
+ }
3598
+ async function finalizeFailedResponse(ctx, ref, generatedResponseId, message) {
3599
+ try {
3600
+ await transitionGeneratedResponse(ctx.api, {
3601
+ id: generatedResponseId,
3602
+ ticketId: ref.id,
3603
+ from: "pending",
3604
+ to: "failed",
3605
+ extra: { error: message }
3606
+ });
3607
+ } catch (writeErr) {
3608
+ ctx.logger.error(`triage-tick: failed to finalise the response of ticket ${ref.id}`, {
3609
+ error: writeErr instanceof Error ? writeErr.message : String(writeErr)
3610
+ });
3611
+ }
3612
+ }
3613
+ async function writeErrorDecision(ctx, ref, message, deps) {
3614
+ try {
3615
+ await ctx.api.create("triage-decision", {
3616
+ ticketId: ref.id,
3617
+ ticketUrl: ticketUrlFor(deps.ticketUrlBase, ref.id),
3618
+ decidedAt: deps.ports.clock.now(),
3619
+ status: "error",
3620
+ error: message,
3621
+ confidence: "low",
3622
+ runId: deps.runId,
3623
+ subjectRenamed: false
3624
+ });
3625
+ } catch (writeErr) {
3626
+ ctx.logger.error(`triage-tick: failed to record the error decision for ticket ${ref.id}`, {
3627
+ error: writeErr instanceof Error ? writeErr.message : String(writeErr)
3628
+ });
3629
+ }
3630
+ }
3631
+ async function escalateTicket(ctx, ref, deps) {
3632
+ const tag = deps.profile.audit.escalationTag;
3633
+ if (!tag) {
3634
+ ctx.logger.warn(`triage-tick: ticket ${ref.id} failed but escalationTag is not configured \u2014 no tag applied`);
3635
+ return;
3636
+ }
3637
+ try {
3638
+ await deps.ports.state.flag(ref, tag);
3639
+ } catch (flagErr) {
3640
+ ctx.logger.error(`triage-tick: failed to escalate ticket ${ref.id} \u2014 it is NOT tagged for a human`, {
3641
+ error: flagErr instanceof Error ? flagErr.message : String(flagErr)
3642
+ });
3643
+ }
3644
+ }
3645
+ async function processOneTicket(ctx, ref, deps) {
3646
+ const { config, profile, categories, ports, runId, ticketUrlBase } = deps;
3647
+ let subjectRenamed = false;
3648
+ if (profile.rename) {
3341
3649
  const conversation2 = await ports.conversation.read(ref);
3342
3650
  const subject = conversation2.subject ?? "";
3343
3651
  if (subject.includes(profile.rename.from)) {
@@ -3363,19 +3671,7 @@ async function processOneTicket(ctx, ref, deps) {
3363
3671
  },
3364
3672
  { until: "triage" }
3365
3673
  );
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
- }
3674
+ if (!state.classification) throw new Error("triage produced no classification");
3379
3675
  const { classification } = state;
3380
3676
  const category = findCategoryByTag(categories, classification.category);
3381
3677
  const decision = await ctx.api.create("triage-decision", {
@@ -3399,8 +3695,9 @@ async function processOneTicket(ctx, ref, deps) {
3399
3695
  const channel = conversation?.sourceChannel === "whatsapp" ? "whatsapp" : "email";
3400
3696
  const generatedAt = ports.clock.now();
3401
3697
  const expiresAt = new Date(generatedAt.getTime() + profile.schedule.fastResponseTtlMinutes * 6e4);
3698
+ let created;
3402
3699
  try {
3403
- await ctx.api.create("generated-response", {
3700
+ created = await ctx.api.create("generated-response", {
3404
3701
  ticketId: ref.id,
3405
3702
  openTicketKey: openTicketKeyFor("pending", ref.id),
3406
3703
  status: "pending",
@@ -3424,273 +3721,12 @@ async function processOneTicket(ctx, ref, deps) {
3424
3721
  }
3425
3722
  throw err;
3426
3723
  }
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
3724
  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;
3725
+ await respondToPendingResponse(ctx, config, created.id);
3522
3726
  } 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;
3727
+ throw new ResponsePhaseError(created.id, err);
3528
3728
  }
3529
3729
  }
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
3730
  var STALE_SENDING_THRESHOLD_MS = 30 * 6e4;
3695
3731
  var SWEEP_PAGE_SIZE = 500;
3696
3732
  function buildSweepFunctionDef(config) {
@@ -3961,6 +3997,7 @@ var EXT_RESPONSE_COMPARISON_INPUT_CONVERSATION_MESSAGES_UID = "0a985d59-fd20-467
3961
3997
  var CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID = "1039e196-cf6e-438e-8ec9-7ab422feaf4d";
3962
3998
  var CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID = "10ffe3e1-972e-43b4-bb45-343c4664464f";
3963
3999
  var SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID = "2f5d6cbb-1c69-4a76-9d8f-1a3f0a4e57c2";
4000
+ var INVALIDATE_RESPONSE_INPUT_GENERATED_RESPONSE_ID_UID = "9748baf5-97be-4a22-940d-46ef2f16a175";
3964
4001
 
3965
4002
  // src/functions/run-triage-now.ts
3966
4003
  var TRIAGE_RUN_REQUESTED_EVENT = "triage.run.requested";
@@ -4049,6 +4086,53 @@ function assertRunnable(ctx, settings, ignoreTriageDisabled) {
4049
4086
  throw new ctx.NonRetriableError("Triage is disabled (triageEnabled is off) \u2014 pass ignoreTriageDisabled to override.");
4050
4087
  }
4051
4088
  }
4089
+ function buildInvalidateResponseFunctionDef(config) {
4090
+ return {
4091
+ universalIdentifier: identifierFor(config, "invalidate-response"),
4092
+ name: "invalidate-response",
4093
+ trigger: { type: "uiInvoke", minRole: "EDITOR", timeoutMs: 1e4 },
4094
+ input: [
4095
+ {
4096
+ universalIdentifier: INVALIDATE_RESPONSE_INPUT_GENERATED_RESPONSE_ID_UID,
4097
+ name: "generatedResponseId",
4098
+ type: appKit.FieldType.TEXT,
4099
+ label: "Generated response id",
4100
+ isNullable: false
4101
+ }
4102
+ ]
4103
+ };
4104
+ }
4105
+ function createInvalidateResponseHandler() {
4106
+ return (ctx, input) => invalidateResponseHandler(ctx, input ?? {});
4107
+ }
4108
+ var REFUSALS = {
4109
+ sending: "La r\xE9ponse est en cours d'envoi \u2014 elle ne peut plus \xEAtre invalid\xE9e.",
4110
+ sent: "La r\xE9ponse a d\xE9j\xE0 \xE9t\xE9 envoy\xE9e au client \u2014 elle ne peut plus \xEAtre invalid\xE9e."
4111
+ };
4112
+ async function invalidateResponseHandler(ctx, input) {
4113
+ const id = input?.generatedResponseId?.trim();
4114
+ if (!id) throw new ctx.NonRetriableError("generatedResponseId is required");
4115
+ const record = await getOptional(ctx, "generated-response", id);
4116
+ if (!record) throw new ctx.NonRetriableError(`R\xE9ponse g\xE9n\xE9r\xE9e introuvable (${id}).`);
4117
+ const data = record.data;
4118
+ const status = String(data.status ?? "");
4119
+ if (status === "invalidated") return { status: "invalidated" };
4120
+ if (!isGeneratedResponseStatus(status) || !isInvalidatableStatus(status)) {
4121
+ throw new ctx.NonRetriableError(
4122
+ REFUSALS[status] ?? `La r\xE9ponse est en statut terminal "${status}" \u2014 le ticket est d\xE9j\xE0 libre d'\xEAtre retrait\xE9.`
4123
+ );
4124
+ }
4125
+ const moved = await transitionGeneratedResponse(ctx.api, {
4126
+ id,
4127
+ ticketId: String(data.ticketId ?? ""),
4128
+ from: status,
4129
+ to: "invalidated"
4130
+ });
4131
+ if (!moved) {
4132
+ throw new ctx.NonRetriableError("La r\xE9ponse a chang\xE9 d'\xE9tat entre-temps \u2014 actualisez la page avant de r\xE9essayer.");
4133
+ }
4134
+ return { status: "invalidated" };
4135
+ }
4052
4136
  function buildPreviewTriageFunctionDef(config) {
4053
4137
  return {
4054
4138
  universalIdentifier: identifierFor(config, "preview-triage"),
@@ -4748,9 +4832,22 @@ async function createAgentHandler(ctx, input) {
4748
4832
  return toAgent(await ctx.api.create("agent", { ...base, promptName }));
4749
4833
  }
4750
4834
  const created = await ctx.api.create("agent", { ...base, promptName: PENDING_PROMPT_NAME });
4751
- const withPromptName = await ctx.api.update("agent", created.id, { promptName: `agent/${created.id}` });
4835
+ const derivedName = `agent/${created.id}`;
4836
+ const withPromptName = await ctx.api.update("agent", created.id, { promptName: derivedName });
4837
+ await seedInitialVersion(ctx, derivedName, input.systemPromptSnapshot?.trim() ?? "");
4752
4838
  return toAgent(withPromptName);
4753
4839
  }
4840
+ async function seedInitialVersion(ctx, promptName, content) {
4841
+ if (!content) return;
4842
+ try {
4843
+ const { version } = await ctx.api.prompts.createVersion(promptName, { content });
4844
+ await ctx.api.prompts.promote(promptName, version, "production");
4845
+ } catch (err) {
4846
+ ctx.logger.warn(
4847
+ `create-agent: could not seed "${promptName}" with its initial version \u2014 the text is kept as the agent's fallback (${err instanceof Error ? err.message : String(err)})`
4848
+ );
4849
+ }
4850
+ }
4754
4851
  var DEFAULT_KEY_VALUE = "default";
4755
4852
  function buildSetDefaultAgentFunctionDef(config) {
4756
4853
  return {
@@ -5652,11 +5749,6 @@ var SUPPORT_KIT_INTEGRATIONS = [
5652
5749
  var SUPPORT_KIT_EMITS = [TRIAGE_RUN_REQUESTED_EVENT];
5653
5750
  var FUNCTION_ASSEMBLY = [
5654
5751
  { key: "triage-tick", build: buildTriageTickFunctionDef, createHandler: createTriageTickHandler },
5655
- {
5656
- key: "process-response",
5657
- build: buildProcessResponseFunctionDef,
5658
- createHandler: createProcessResponseHandler
5659
- },
5660
5752
  { key: "sweep", build: buildSweepFunctionDef, createHandler: () => createSweepHandler() },
5661
5753
  {
5662
5754
  key: "handle-approval",
@@ -5673,6 +5765,11 @@ var FUNCTION_ASSEMBLY = [
5673
5765
  build: buildRunTriageBatchFunctionDef,
5674
5766
  createHandler: createRunTriageBatchHandler
5675
5767
  },
5768
+ {
5769
+ key: "invalidate-response",
5770
+ build: buildInvalidateResponseFunctionDef,
5771
+ createHandler: () => createInvalidateResponseHandler()
5772
+ },
5676
5773
  {
5677
5774
  key: "preview-triage",
5678
5775
  build: buildPreviewTriageFunctionDef,
@@ -5853,6 +5950,7 @@ function buildSupportPipeline(config) {
5853
5950
  exports.AGENT_GUARDRAILS = AGENT_GUARDRAILS;
5854
5951
  exports.AGENT_STATUSES = AGENT_STATUSES;
5855
5952
  exports.AGENT_TOOLS = AGENT_TOOLS;
5953
+ exports.ATTACHMENT_MARKER_ONLY = ATTACHMENT_MARKER_ONLY;
5856
5954
  exports.CANDIDATE_MIN_LENGTH = CANDIDATE_MIN_LENGTH;
5857
5955
  exports.DEFAULT_CHANNEL_PROMPT_EMAIL = DEFAULT_CHANNEL_PROMPT_EMAIL;
5858
5956
  exports.DEFAULT_CHANNEL_PROMPT_WHATSAPP = DEFAULT_CHANNEL_PROMPT_WHATSAPP;