@apotech-os/support-kit 10.1.1 → 10.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -93,7 +93,7 @@ var OUTCOMES = [
93
93
  "triaged_only",
94
94
  // tenant/ticket has no draft step to run
95
95
  "no_reply_needed",
96
- // triage read the thread as already closed → NO tag, like 'ready' (whatsapp spec §5.2)
96
+ // the end-of-conversation step judged the thread finished — set on response rows, never returned by runTicket
97
97
  "failed"
98
98
  ];
99
99
  function isOutcome(value) {
@@ -418,16 +418,37 @@ function snapshotConversation(raw) {
418
418
  }
419
419
  function lastAgentReplyAtOf(raw) {
420
420
  const isWhatsapp = isWhatsappTicket(raw);
421
+ return latestAt(raw, (m) => isAgentReply(m, isWhatsapp));
422
+ }
423
+ function latestAt(raw, counts) {
421
424
  let latest = null;
422
425
  for (const m of raw.messages ?? []) {
423
- if (m.from_agent !== true) continue;
424
- if (isInternalNoteChannel2(m) && !isWhatsappChevronNote(m, isWhatsapp)) continue;
426
+ if (!counts(m)) continue;
425
427
  if (!m.created_datetime) continue;
426
428
  const at = new Date(m.created_datetime);
427
429
  if (!latest || at > latest) latest = at;
428
430
  }
429
431
  return latest;
430
432
  }
433
+ function isAgentReply(m, isWhatsapp) {
434
+ if (m.from_agent !== true) return false;
435
+ return !isInternalNoteChannel2(m) || isWhatsappChevronNote(m, isWhatsapp);
436
+ }
437
+ function isRuleMessage(m) {
438
+ return m.via === "rule";
439
+ }
440
+ function awaitingSinceOf(raw) {
441
+ const isWhatsapp = isWhatsappTicket(raw);
442
+ const lastAgentReplyAt = latestAt(raw, (m) => isAgentReply(m, isWhatsapp) && !isRuleMessage(m));
443
+ let first = null;
444
+ for (const m of countableMessages(raw.messages ?? [], isWhatsapp)) {
445
+ if (m.from_agent === true || isInternalNoteChannel2(m) || !m.created_datetime) continue;
446
+ const at = new Date(m.created_datetime);
447
+ if (lastAgentReplyAt && at <= lastAgentReplyAt) continue;
448
+ if (!first || at < first.at) first = { at, messageId: m.id == null ? null : String(m.id) };
449
+ }
450
+ return first;
451
+ }
431
452
  function toConversation(ref, raw, context) {
432
453
  const snapshot = snapshotConversation(raw);
433
454
  const messages = context.messages.filter((m) => m.role === "user" || m.role === "assistant").map((m) => ({ role: m.role, content: m.content }));
@@ -445,6 +466,7 @@ function toConversation(ref, raw, context) {
445
466
  lastMessageAt: snapshot.lastAt,
446
467
  messageCount: snapshot.count,
447
468
  lastAgentReplyAt: lastAgentReplyAtOf(raw),
469
+ awaitingSince: awaitingSinceOf(raw),
448
470
  answerableChannels: answerableChannels(raw),
449
471
  customerChannelAddress: customerChannelAddress(raw, sourceChannel),
450
472
  accountChannelAddress: accountChannelAddress(raw, sourceChannel),
@@ -615,10 +637,9 @@ var TRIAGE_SCHEMA = {
615
637
  properties: {
616
638
  tag: { type: "string" },
617
639
  confidence: { type: "string", enum: ["high", "low"] },
618
- reasoning: { type: "string", maxLength: REASONING_MAX_LEN },
619
- conversationOver: { type: "boolean" }
640
+ reasoning: { type: "string", maxLength: REASONING_MAX_LEN }
620
641
  },
621
- required: ["tag", "confidence", "reasoning", "conversationOver"],
642
+ required: ["tag", "confidence", "reasoning"],
622
643
  additionalProperties: false
623
644
  };
624
645
  function renderCategories(categories) {
@@ -638,9 +659,7 @@ function fallback(unknownTag, reason) {
638
659
  category: unknownTag,
639
660
  confidence: "low",
640
661
  reasoning: reason.slice(0, REASONING_MAX_LEN),
641
- isFallback: true,
642
- conversationOver: false
643
- // fail-safe (§5.2): never close on an error
662
+ isFallback: true
644
663
  };
645
664
  }
646
665
  var triage = async (state, deps) => {
@@ -687,8 +706,7 @@ ${last}`);
687
706
  category: parsed.tag,
688
707
  confidence: parsed.confidence,
689
708
  reasoning: String(parsed.reasoning ?? "").slice(0, REASONING_MAX_LEN),
690
- isFallback: false,
691
- conversationOver: parsed.conversationOver === true
709
+ isFallback: false
692
710
  }
693
711
  };
694
712
  } catch (err) {
@@ -1271,9 +1289,6 @@ async function finish2(state, deps, outcome2) {
1271
1289
  await applyOutcomeTags(outcome2, final.verdict, { ports: deps.ports, ref: deps.ref, audit });
1272
1290
  return final;
1273
1291
  }
1274
- function isConversationOver(classification) {
1275
- return classification?.conversationOver === true;
1276
- }
1277
1292
  function isFallbackClassification(classification) {
1278
1293
  return classification?.isFallback === true;
1279
1294
  }
@@ -1296,7 +1311,6 @@ async function runTicket(deps, options = {}) {
1296
1311
  if (s.escalated) return finish2(s, deps, "escalated");
1297
1312
  const stopHits = s.conversation ? stopOptOut(s.conversation) : [];
1298
1313
  if (stopHits.length) return finish2(merge(s, { guardrailHits: stopHits }), deps, "guardrail_hold");
1299
- if (isConversationOver(s.classification)) return finish2(s, deps, "no_reply_needed");
1300
1314
  if (isFallbackClassification(s.classification)) return finish2(s, deps, "triaged_only");
1301
1315
  if (hasNoDraftNode(profile)) return finish2(s, deps, "triaged_only");
1302
1316
  if (s.conversation) {
@@ -1711,6 +1725,26 @@ var PROMPT_CACHE_FIELD_VERSION_UID = "87b77921-6261-4179-a9e6-823e8321ccfd";
1711
1725
  var PROMPT_CACHE_FIELD_LABEL_UID = "ce36ed5b-42e2-45bd-8915-3ef0317e6665";
1712
1726
  var PROMPT_CACHE_FIELD_CONFIG_UID = "306cdb0b-433b-44c8-8a5b-6b993d3f0da3";
1713
1727
  var PROMPT_CACHE_INDEX_PROMPT_KEY_UID = "df06ab57-bfc0-4155-a3d6-e22edab8a853";
1728
+ var REPLY_TIMING_OBJECT_UID = "15646c19-965f-4e71-9ada-8dec22cdbb26";
1729
+ var REPLY_TIMING_FIELD_TICKET_ID_UID = "57faafe3-2846-4d92-b670-295c73b20702";
1730
+ var REPLY_TIMING_FIELD_TURN_KEY_UID = "f4365847-09d6-47e2-8c99-95d4138981bd";
1731
+ var REPLY_TIMING_FIELD_CUSTOMER_MESSAGE_AT_UID = "a96ce8da-d2b8-4d3f-9728-ea6116fff784";
1732
+ var REPLY_TIMING_FIELD_REPLIED_AT_UID = "f9cca111-6da5-4fe1-acc0-d3eebbdb1056";
1733
+ var REPLY_TIMING_FIELD_RESPONDER_UID = "8b2e951e-dde9-4e2d-a032-073fe0342861";
1734
+ var REPLY_TIMING_FIELD_RESPONDER_VIA_UID = "125086c7-efea-4d7b-b6a1-49caf77f6866";
1735
+ var REPLY_TIMING_FIELD_DELAY_SECONDS_UID = "dcabc93e-2b4b-4219-ac6a-444744227364";
1736
+ var REPLY_TIMING_FIELD_DELAY_BUCKET_UID = "37d50e89-d9a6-4ac1-b1ce-e4d9861e88d8";
1737
+ var REPLY_TIMING_FIELD_CATEGORY_ID_UID = "8be48fa6-9faf-4349-ba89-613776fe44d9";
1738
+ var REPLY_TIMING_FIELD_SOURCE_CHANNEL_UID = "ff1c1adc-741b-4607-b067-390e25225ec8";
1739
+ var REPLY_TIMING_FIELD_GENERATED_RESPONSE_ID_UID = "5b73871d-d731-4230-b21f-61565187ab56";
1740
+ var REPLY_TIMING_FIELD_NEXT_CHECK_AT_UID = "623fc8ad-b810-45b2-b602-9fdf47826716";
1741
+ var REPLY_TIMING_FIELD_BACKFILLED_UID = "a773b310-6394-480b-b1c3-6e680e9bd9f6";
1742
+ var REPLY_TIMING_FIELD_ORIGIN_UID = "d195f7ca-f469-4725-a92e-58afe8dd0d01";
1743
+ var REPLY_TIMING_INDEX_TURN_KEY_UID = "4f2bcfc1-8b2b-4771-9866-fdcbb7bce201";
1744
+ var REPLY_TIMING_INDEX_TICKET_ID_UID = "0d482d11-e45e-4bd2-9d9c-86601e1aed40";
1745
+ var REPLY_TIMING_INDEX_CUSTOMER_MESSAGE_AT_UID = "78459d0a-dbe8-459f-96f5-8025dc6daf2f";
1746
+ var REPLY_TIMING_INDEX_RESPONDER_UID = "5fd58fc5-d67c-4936-bdd1-a9daa7d6d4e3";
1747
+ var REPLY_TIMING_INDEX_NEXT_CHECK_AT_UID = "cdb66f06-7368-4c30-908e-006a6b3d3a73";
1714
1748
 
1715
1749
  // src/records/target-ref.ts
1716
1750
  function targetRefFor(slug, objectKey) {
@@ -2670,176 +2704,592 @@ function buildDiffAnalysisRecord(slug) {
2670
2704
  ]
2671
2705
  };
2672
2706
  }
2673
- var pipelineStateRecord = {
2674
- universalIdentifier: PIPELINE_STATE_OBJECT_UID,
2675
- objectKey: "pipeline-state",
2676
- labelSingular: "Pipeline state",
2677
- labelPlural: "Pipeline state",
2678
- description: "Singleton run-cadence and view-claim state, readable by every installed app.",
2679
- fields: [
2680
- {
2681
- universalIdentifier: PIPELINE_STATE_FIELD_SINGLETON_KEY_UID,
2682
- name: "singletonKey",
2683
- type: appKit.FieldType.TEXT,
2684
- label: "Singleton key",
2685
- description: "Always the same constant value \u2014 the unique index below is what makes this record a true singleton, not just a convention.",
2686
- isNullable: false
2687
- },
2688
- {
2689
- universalIdentifier: PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID,
2690
- name: "sourceViewId",
2691
- type: appKit.FieldType.TEXT,
2692
- label: "Source view id",
2693
- description: "The claimed Gorgias view \u2014 supports the cross-app overlap warning (\xA74).",
2694
- isNullable: true
2695
- },
2696
- {
2697
- universalIdentifier: PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID,
2698
- name: "lastTriageAt",
2699
- type: appKit.FieldType.DATE_TIME,
2700
- label: "Last triage at",
2701
- description: "Gates triage-tick's cadence.",
2702
- isNullable: true
2703
- },
2704
- {
2705
- universalIdentifier: PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID,
2706
- name: "lastSweepAt",
2707
- type: appKit.FieldType.DATE_TIME,
2708
- label: "Last sweep at",
2709
- isNullable: true
2710
- }
2711
- ],
2712
- indexes: [{ universalIdentifier: PIPELINE_STATE_INDEX_SINGLETON_KEY_UID, fields: ["singletonKey"], isUnique: true }],
2713
- exposedToApps: ["*"]
2714
- };
2715
- var promptCacheRecord = {
2716
- universalIdentifier: PROMPT_CACHE_OBJECT_UID,
2717
- objectKey: "prompt-cache",
2718
- labelSingular: "Prompt cache entry",
2719
- labelPlural: "Prompt cache entries",
2720
- description: "Last-known-good snapshot of a Langfuse prompt, for the resolver fallback ladder.",
2721
- fields: [
2722
- {
2723
- universalIdentifier: PROMPT_CACHE_FIELD_PROMPT_KEY_UID,
2724
- name: "promptKey",
2725
- type: appKit.FieldType.TEXT,
2726
- label: "Prompt key",
2727
- description: "'name' or 'name::label'.",
2728
- isNullable: false
2729
- },
2730
- {
2731
- universalIdentifier: PROMPT_CACHE_FIELD_CONTENT_UID,
2732
- name: "content",
2733
- type: appKit.FieldType.TEXT,
2734
- label: "Content",
2735
- description: "Raw, uncompiled template.",
2736
- isNullable: false
2737
- },
2738
- {
2739
- universalIdentifier: PROMPT_CACHE_FIELD_VERSION_UID,
2740
- name: "version",
2741
- type: appKit.FieldType.NUMBER,
2742
- label: "Version",
2743
- isNullable: false
2744
- },
2745
- {
2746
- universalIdentifier: PROMPT_CACHE_FIELD_LABEL_UID,
2747
- name: "label",
2748
- type: appKit.FieldType.TEXT,
2749
- label: "Label",
2750
- isNullable: true
2751
- },
2752
- {
2753
- universalIdentifier: PROMPT_CACHE_FIELD_CONFIG_UID,
2754
- name: "config",
2755
- type: appKit.FieldType.JSON,
2756
- label: "Config",
2757
- description: "Model config snapshot, for I16. Not yet written or read \u2014 see module doc.",
2758
- isNullable: true
2759
- }
2760
- ],
2761
- indexes: [{ universalIdentifier: PROMPT_CACHE_INDEX_PROMPT_KEY_UID, fields: ["promptKey"], isUnique: true }]
2707
+
2708
+ // src/domain/dashboard-stats.ts
2709
+ function sumCounts(rows, countField = "count") {
2710
+ return rows.reduce((sum, row) => sum + (Number(row[countField]) || 0), 0);
2711
+ }
2712
+ function bucketDay(row) {
2713
+ return String(row["bucket"]).slice(0, 10);
2714
+ }
2715
+ var EMPTY_TOTALS = {
2716
+ auto: 0,
2717
+ human: 0,
2718
+ inProgress: 0,
2719
+ noReplyNeeded: 0
2762
2720
  };
2763
- var SUPPORT_KIT_UID_NAMESPACE = "2b6a9c0e-6c1e-4c1a-8b0e-2a2f4b8c9d3f";
2764
- function uuidToBytes(uuid) {
2765
- return Buffer.from(uuid.replace(/-/g, ""), "hex");
2721
+ function countFailed(rows) {
2722
+ return sumCounts(rows.filter((row) => row["status"] === "failed"));
2766
2723
  }
2767
- function bytesToUuid(bytes) {
2768
- const hex = bytes.toString("hex");
2769
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
2724
+ var HUMAN_OUTCOMES = /* @__PURE__ */ new Set(["needs_human", "guardrail_hold", "escalated", "awaiting_approval"]);
2725
+ function isUnautomatedTriage(decision) {
2726
+ return decision.escalated === "true" || decision.escalated === true || decision.status === "error";
2770
2727
  }
2771
- function deriveUid(seed) {
2772
- const hash = node_crypto.createHash("sha1").update(uuidToBytes(SUPPORT_KIT_UID_NAMESPACE)).update(seed, "utf8").digest();
2773
- const bytes = hash.subarray(0, 16);
2774
- bytes[6] = bytes[6] & 15 | 80;
2775
- bytes[8] = bytes[8] & 63 | 128;
2776
- return bytesToUuid(bytes);
2728
+ function countOf(row) {
2729
+ return Number(row["count"]) || 0;
2777
2730
  }
2778
-
2779
- // src/records/scope-to-app.ts
2780
- function scopeRecordToApp(slug, record) {
2781
- return {
2782
- ...record,
2783
- universalIdentifier: deriveUid(`${slug}:${record.universalIdentifier}`),
2784
- fields: record.fields.map((field) => ({
2785
- ...field,
2786
- universalIdentifier: deriveUid(`${slug}:${field.universalIdentifier}`)
2787
- })),
2788
- indexes: record.indexes?.map((index) => ({
2789
- ...index,
2790
- universalIdentifier: deriveUid(`${slug}:${index.universalIdentifier}`)
2791
- }))
2731
+ function outcomeOf(row) {
2732
+ const status = row["status"];
2733
+ const autoSendDecision = row["autoSendDecision"];
2734
+ if (status === "test_draft" || status === "superseded") return null;
2735
+ if (status === "sent") return "auto";
2736
+ if (status === "no_reply_needed") return "noReplyNeeded";
2737
+ if (status === "failed") return "human";
2738
+ if (status === "invalidated" || status === "expired") return "human";
2739
+ const outcome2 = row["outcome"];
2740
+ if (typeof outcome2 === "string" && HUMAN_OUTCOMES.has(outcome2)) return "human";
2741
+ if (outcome2 === "no_reply_needed") return "noReplyNeeded";
2742
+ if (outcome2 === "triaged_only") return null;
2743
+ return autoSendDecision === "hold" ? "human" : "inProgress";
2744
+ }
2745
+ function foldOutcomes(rows, triageRows = []) {
2746
+ const totals = { ...EMPTY_TOTALS };
2747
+ for (const row of rows) {
2748
+ const outcome2 = outcomeOf(row);
2749
+ if (outcome2 !== null) totals[outcome2] += countOf(row);
2750
+ }
2751
+ for (const row of triageRows) {
2752
+ if (isUnautomatedTriage(row)) totals.human += countOf(row);
2753
+ }
2754
+ return totals;
2755
+ }
2756
+ function settledCount(totals) {
2757
+ return totals.auto + totals.human;
2758
+ }
2759
+ function autonomyRate(totals) {
2760
+ const settled = settledCount(totals);
2761
+ return settled > 0 ? totals.auto / settled : Number.NaN;
2762
+ }
2763
+ function foldDailyOutcomes(rows, triageRows = []) {
2764
+ const byDay = /* @__PURE__ */ new Map();
2765
+ const totalsFor = (day) => {
2766
+ const existing = byDay.get(day);
2767
+ if (existing !== void 0) return existing;
2768
+ const fresh = { ...EMPTY_TOTALS };
2769
+ byDay.set(day, fresh);
2770
+ return fresh;
2792
2771
  };
2772
+ for (const row of rows) {
2773
+ const outcome2 = outcomeOf(row);
2774
+ if (outcome2 === null) continue;
2775
+ totalsFor(bucketDay(row))[outcome2] += countOf(row);
2776
+ }
2777
+ for (const row of triageRows) {
2778
+ if (isUnautomatedTriage(row)) totalsFor(bucketDay(row)).human += countOf(row);
2779
+ }
2780
+ return [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, totals]) => ({
2781
+ day,
2782
+ auto: totals.auto,
2783
+ human: totals.human,
2784
+ rate: settledCount(totals) > 0 ? autonomyRate(totals) : null
2785
+ }));
2793
2786
  }
2794
-
2795
- // src/records/index.ts
2796
- function buildSupportKitRecords(slug) {
2797
- return [
2798
- buildCategoryRecord(slug),
2799
- categoryGroupRecord,
2800
- agentRecord,
2801
- buildTriageDecisionRecord(slug),
2802
- buildGeneratedResponseRecord(slug),
2803
- buildResponseComparisonRecord(slug),
2804
- buildEvaluationRecord(slug),
2805
- buildDiffAnalysisRecord(slug),
2806
- pipelineStateRecord,
2807
- promptCacheRecord
2808
- ].map((record) => scopeRecordToApp(slug, record));
2787
+ function fillMissingDays(series, fromIso, toIso) {
2788
+ const from = Date.parse(fromIso.slice(0, 10));
2789
+ const to = Date.parse(toIso.slice(0, 10));
2790
+ if (Number.isNaN(from) || Number.isNaN(to) || to < from) return series;
2791
+ const measured = new Map(series.map((point) => [point.day, point]));
2792
+ const filled = [];
2793
+ for (let t = from; t <= to; t += 864e5) {
2794
+ const day = new Date(t).toISOString().slice(0, 10);
2795
+ filled.push(measured.get(day) ?? { day, auto: 0, human: 0, rate: null });
2796
+ }
2797
+ return filled;
2809
2798
  }
2810
-
2811
- // src/settings/fields.ts
2812
- var DEFAULT_STATS_TIMEZONE = "Europe/Paris";
2813
- var SUPPORT_KIT_SETTINGS_FIELDS = [
2814
- // Source
2815
- // NO `gorgiasConnectionId`: every Gorgias call in this kit is
2816
- // `ctx.api.integrations.run('gorgias', …)` with no `connectionId`, so the
2817
- // platform resolves the instance's default connection. A settings key here
2818
- // would be written by an operator and read by nobody — see the Source
2819
- // section of `ui/settings/settings-page.tsx`, which STATES the resolved
2820
- // connection instead of pretending to choose it.
2821
- {
2822
- key: "sourceViewId",
2823
- type: "string",
2824
- label: "Gorgias source view"
2825
- // No default — see module doc.
2826
- },
2827
- { key: "batchLimit", type: "number", label: "Batch limit", default: 30 },
2828
- { key: "triageEnabled", type: "boolean", label: "Triage enabled", default: false },
2829
- {
2830
- key: "triageIntervalMinutes",
2831
- type: "number",
2832
- label: "Triage interval (minutes)",
2833
- default: 15
2834
- },
2835
- { key: "dryRun", type: "boolean", label: "Dry run", default: false },
2836
- // Nodes
2837
- // `{triage, escalate, draft, evaluate, revise}`, `null` per key disabling
2838
- // that graph step (§3.6). NO default, same reasoning as `sourceViewId`:
2839
- // the only shape that could be defaulted here ("every step null") is a
2840
- // pipeline that triages nothing, and it would install itself silently.
2841
- // `validateSettings` refuses to run until `nodes.triage` is configured.
2842
- { key: "nodes", type: "json", label: "Graph node overrides" },
2799
+ function ratePoints(rate, compareRate) {
2800
+ return Number.isNaN(rate) || Number.isNaN(compareRate) ? null : (rate - compareRate) * 100;
2801
+ }
2802
+ var SIGNAL_MIN_VOLUME = 20;
2803
+ var SIGNAL_MIN_POINTS = 3;
2804
+ function dashboardSignals(totals, compare, failed2 = 0) {
2805
+ const signals = [];
2806
+ const settled = settledCount(totals);
2807
+ const rate = autonomyRate(totals);
2808
+ if (compare !== null && settled >= SIGNAL_MIN_VOLUME && settledCount(compare) >= SIGNAL_MIN_VOLUME) {
2809
+ const points = ratePoints(rate, autonomyRate(compare));
2810
+ if (points !== null && Math.abs(points) >= SIGNAL_MIN_POINTS) {
2811
+ const move = points < 0 ? "recule" : "progresse";
2812
+ signals.push({
2813
+ level: points < 0 ? "creuser" : "info",
2814
+ text: `Le taux d\u2019autonomie ${move} de ${Math.abs(Math.round(points))} points par rapport \xE0 la p\xE9riode pr\xE9c\xE9dente.`
2815
+ });
2816
+ }
2817
+ }
2818
+ if (failed2 > 0) {
2819
+ signals.push({
2820
+ level: "creuser",
2821
+ text: `${failed2} g\xE9n\xE9ration${failed2 > 1 ? "s ont" : " a"} \xE9chou\xE9 techniquement : ${failed2 > 1 ? "ces demandes n\u2019ont" : "cette demande n\u2019a"} jamais eu de brouillon et ${failed2 > 1 ? "sont retomb\xE9es" : "est retomb\xE9e"} sur un humain.`
2822
+ });
2823
+ }
2824
+ if (totals.inProgress > 0) {
2825
+ signals.push({
2826
+ level: "info",
2827
+ text: `${totals.inProgress} r\xE9ponse${totals.inProgress > 1 ? "s sont" : " est"} encore en cours : ${totals.inProgress > 1 ? "elles ne comptent" : "elle ne compte"} dans aucun des deux camps.`
2828
+ });
2829
+ }
2830
+ if (totals.noReplyNeeded > 0) {
2831
+ signals.push({
2832
+ level: "info",
2833
+ text: `${totals.noReplyNeeded} demande${totals.noReplyNeeded > 1 ? "s" : ""} ne n\xE9cessitai${totals.noReplyNeeded > 1 ? "ent" : "t"} aucune r\xE9ponse : hors du taux d\u2019autonomie.`
2834
+ });
2835
+ }
2836
+ if (compare !== null && settled > 0 && settledCount(compare) < SIGNAL_MIN_VOLUME) {
2837
+ signals.push({
2838
+ level: "info",
2839
+ text: "La p\xE9riode pr\xE9c\xE9dente compte trop peu de demandes r\xE9gl\xE9es pour que la comparaison veuille dire quelque chose."
2840
+ });
2841
+ }
2842
+ return signals;
2843
+ }
2844
+ function foldHumanReasons(rows, triageRows = []) {
2845
+ const reasons = { blocked: 0, invalidated: 0, expired: 0, escalatedNoDraft: 0, failed: 0 };
2846
+ for (const row of rows) {
2847
+ if (outcomeOf(row) !== "human") continue;
2848
+ const count = countOf(row);
2849
+ if (row["status"] === "invalidated") reasons.invalidated += count;
2850
+ else if (row["status"] === "expired") reasons.expired += count;
2851
+ else if (row["status"] === "failed") reasons.failed += count;
2852
+ else reasons.blocked += count;
2853
+ }
2854
+ for (const row of triageRows) {
2855
+ if (isUnautomatedTriage(row)) reasons.escalatedNoDraft += countOf(row);
2856
+ }
2857
+ return reasons;
2858
+ }
2859
+ var CATEGORY_TOP_N = 10;
2860
+ function foldCategoryOutcomes(triageRows, responseRows, categoryNames, topN = CATEGORY_TOP_N) {
2861
+ const byId = /* @__PURE__ */ new Map();
2862
+ const barFor = (id) => {
2863
+ const name = typeof id === "string" ? categoryNames.get(id) : void 0;
2864
+ if (name === void 0) return null;
2865
+ const existing = byId.get(id);
2866
+ if (existing !== void 0) return existing;
2867
+ const bar = {
2868
+ label: name,
2869
+ total: 0,
2870
+ auto: 0,
2871
+ human: 0,
2872
+ noReply: 0,
2873
+ undrafted: 0
2874
+ };
2875
+ byId.set(id, bar);
2876
+ return bar;
2877
+ };
2878
+ for (const row of triageRows) {
2879
+ const bar = barFor(row["categoryId"]);
2880
+ if (bar === null) continue;
2881
+ const count = countOf(row);
2882
+ bar.total += count;
2883
+ if (isUnautomatedTriage(row)) bar.human += count;
2884
+ }
2885
+ for (const row of responseRows) {
2886
+ const bar = barFor(row["categoryId"]);
2887
+ if (bar === null) continue;
2888
+ const outcome2 = outcomeOf(row);
2889
+ const count = countOf(row);
2890
+ if (outcome2 === "auto") bar.auto += count;
2891
+ else if (outcome2 === "human") bar.human += count;
2892
+ else if (outcome2 === "noReplyNeeded") bar.noReply += count;
2893
+ }
2894
+ const bars = [...byId.values()].map((bar) => {
2895
+ const accounted = bar.auto + bar.human + bar.noReply;
2896
+ return {
2897
+ ...bar,
2898
+ total: Math.max(bar.total, accounted),
2899
+ undrafted: Math.max(0, bar.total - accounted)
2900
+ };
2901
+ }).filter((bar) => bar.total > 0).sort((a, b) => b.total - a.total);
2902
+ if (bars.length <= topN + 1) return bars;
2903
+ const tail = bars.slice(topN).reduce(
2904
+ (sum, bar) => ({
2905
+ label: "Autres",
2906
+ total: sum.total + bar.total,
2907
+ auto: sum.auto + bar.auto,
2908
+ human: sum.human + bar.human,
2909
+ noReply: sum.noReply + bar.noReply,
2910
+ undrafted: sum.undrafted + bar.undrafted
2911
+ }),
2912
+ { label: "Autres", total: 0, auto: 0, human: 0, noReply: 0, undrafted: 0 }
2913
+ );
2914
+ return [...bars.slice(0, topN), tail];
2915
+ }
2916
+
2917
+ // src/domain/reply-timing.ts
2918
+ var RESPONDERS = ["ai", "human", "human_ai_assisted", "other", "none"];
2919
+ var DELAY_BUCKETS = ["lt_5m", "5_15m", "15_60m", "1_4h", "4_24h", "gt_24h"];
2920
+ var BUCKET_FLOORS_SECONDS = [0, 5 * 60, 15 * 60, 60 * 60, 4 * 3600, 24 * 3600];
2921
+ var FIRST_CHECK_DELAY_MS = 15 * 6e4;
2922
+ function bucketFor(delaySeconds) {
2923
+ for (let index = DELAY_BUCKETS.length - 1; index > 0; index -= 1) {
2924
+ if (delaySeconds >= BUCKET_FLOORS_SECONDS[index]) return DELAY_BUCKETS[index];
2925
+ }
2926
+ return DELAY_BUCKETS[0];
2927
+ }
2928
+ function turnKeyFor(ticketId, awaitingSince) {
2929
+ return `${ticketId}:${awaitingSince.messageId ?? awaitingSince.at.toISOString()}`;
2930
+ }
2931
+ function closingFields(customerMessageAt, repliedAt, responder, responderVia = null) {
2932
+ const delaySeconds = Math.max(
2933
+ 0,
2934
+ Math.round((repliedAt.getTime() - customerMessageAt.getTime()) / 1e3)
2935
+ );
2936
+ return {
2937
+ repliedAt,
2938
+ responder,
2939
+ responderVia,
2940
+ delaySeconds,
2941
+ delayBucket: bucketFor(delaySeconds),
2942
+ nextCheckAt: null
2943
+ };
2944
+ }
2945
+
2946
+ // src/records/reply-timing.ts
2947
+ function buildReplyTimingRecord(slug) {
2948
+ return {
2949
+ universalIdentifier: REPLY_TIMING_OBJECT_UID,
2950
+ objectKey: "reply-timing",
2951
+ labelSingular: "Reply timing",
2952
+ labelPlural: "Reply timings",
2953
+ description: "How long a customer turn waited for its first reply, and who gave it.",
2954
+ fields: [
2955
+ {
2956
+ universalIdentifier: REPLY_TIMING_FIELD_TICKET_ID_UID,
2957
+ name: "ticketId",
2958
+ type: appKit.FieldType.TEXT,
2959
+ label: "Ticket id",
2960
+ isNullable: false
2961
+ },
2962
+ {
2963
+ universalIdentifier: REPLY_TIMING_FIELD_TURN_KEY_UID,
2964
+ name: "turnKey",
2965
+ type: appKit.FieldType.TEXT,
2966
+ label: "Turn key",
2967
+ description: "`${ticketId}:${customerMessageId}` \u2014 the message instant when Gorgias gave no id. Unique.",
2968
+ isNullable: false
2969
+ },
2970
+ {
2971
+ universalIdentifier: REPLY_TIMING_FIELD_CUSTOMER_MESSAGE_AT_UID,
2972
+ name: "customerMessageAt",
2973
+ type: appKit.FieldType.DATE_TIME,
2974
+ label: "Customer message at",
2975
+ description: "Start of the wait: the first unanswered customer message (the last one on a backfilled row).",
2976
+ isNullable: false
2977
+ },
2978
+ {
2979
+ universalIdentifier: REPLY_TIMING_FIELD_REPLIED_AT_UID,
2980
+ name: "repliedAt",
2981
+ type: appKit.FieldType.DATE_TIME,
2982
+ label: "Replied at",
2983
+ description: "When the first reply after the customer message was posted. Null while the turn is open.",
2984
+ isNullable: true
2985
+ },
2986
+ {
2987
+ universalIdentifier: REPLY_TIMING_FIELD_RESPONDER_UID,
2988
+ name: "responder",
2989
+ type: appKit.FieldType.SELECT,
2990
+ label: "Responder",
2991
+ description: "Who answered. 'none': no reply after 7 days or on a closed ticket. Null while the turn is open.",
2992
+ isNullable: true,
2993
+ options: [...RESPONDERS]
2994
+ },
2995
+ {
2996
+ universalIdentifier: REPLY_TIMING_FIELD_RESPONDER_VIA_UID,
2997
+ name: "responderVia",
2998
+ type: appKit.FieldType.TEXT,
2999
+ label: "Responder via",
3000
+ description: "The raw Gorgias `via` of the reply \u2014 what explains an 'other'.",
3001
+ isNullable: true
3002
+ },
3003
+ {
3004
+ universalIdentifier: REPLY_TIMING_FIELD_DELAY_SECONDS_UID,
3005
+ name: "delaySeconds",
3006
+ type: appKit.FieldType.NUMBER,
3007
+ label: "Delay (seconds)",
3008
+ description: "repliedAt \u2212 customerMessageAt, wall clock.",
3009
+ isNullable: true
3010
+ },
3011
+ {
3012
+ universalIdentifier: REPLY_TIMING_FIELD_DELAY_BUCKET_UID,
3013
+ name: "delayBucket",
3014
+ type: appKit.FieldType.SELECT,
3015
+ label: "Delay bucket",
3016
+ isNullable: true,
3017
+ options: [...DELAY_BUCKETS]
3018
+ },
3019
+ {
3020
+ universalIdentifier: REPLY_TIMING_FIELD_CATEGORY_ID_UID,
3021
+ name: "categoryId",
3022
+ type: appKit.FieldType.RELATION,
3023
+ label: "Category",
3024
+ isNullable: true,
3025
+ relation: {
3026
+ targetRef: targetRefFor(slug, "category"),
3027
+ relationType: "MANY_TO_ONE",
3028
+ onDelete: "SET_NULL"
3029
+ }
3030
+ },
3031
+ {
3032
+ universalIdentifier: REPLY_TIMING_FIELD_SOURCE_CHANNEL_UID,
3033
+ name: "sourceChannel",
3034
+ type: appKit.FieldType.TEXT,
3035
+ label: "Source channel",
3036
+ description: "The channel Gorgias reported \u2014 same vocabulary as generated-response.sourceChannel.",
3037
+ isNullable: true
3038
+ },
3039
+ {
3040
+ universalIdentifier: REPLY_TIMING_FIELD_GENERATED_RESPONSE_ID_UID,
3041
+ name: "generatedResponseId",
3042
+ type: appKit.FieldType.RELATION,
3043
+ label: "Generated response",
3044
+ description: "The draft written for this turn, if any.",
3045
+ isNullable: true,
3046
+ relation: {
3047
+ targetRef: targetRefFor(slug, "generated-response"),
3048
+ relationType: "MANY_TO_ONE",
3049
+ onDelete: "SET_NULL"
3050
+ }
3051
+ },
3052
+ {
3053
+ universalIdentifier: REPLY_TIMING_FIELD_NEXT_CHECK_AT_UID,
3054
+ name: "nextCheckAt",
3055
+ type: appKit.FieldType.DATE_TIME,
3056
+ label: "Next check at",
3057
+ description: "When the sweep re-reads the ticket to find who answered. Null once closed.",
3058
+ isNullable: true
3059
+ },
3060
+ {
3061
+ universalIdentifier: REPLY_TIMING_FIELD_BACKFILLED_UID,
3062
+ name: "backfilled",
3063
+ type: appKit.FieldType.BOOLEAN,
3064
+ label: "Backfilled",
3065
+ description: "Rebuilt after the fact: customerMessageAt is then the LAST customer message, not the first unanswered one.",
3066
+ isNullable: false,
3067
+ defaultValue: false
3068
+ },
3069
+ {
3070
+ universalIdentifier: REPLY_TIMING_FIELD_ORIGIN_UID,
3071
+ name: "origin",
3072
+ type: appKit.FieldType.TEXT,
3073
+ label: "Origin",
3074
+ description: ORIGIN_DESCRIPTION,
3075
+ isNullable: false,
3076
+ defaultValue: DEFAULT_DECISION_ORIGIN
3077
+ }
3078
+ ],
3079
+ indexes: [
3080
+ { universalIdentifier: REPLY_TIMING_INDEX_TURN_KEY_UID, fields: ["turnKey"], isUnique: true },
3081
+ { universalIdentifier: REPLY_TIMING_INDEX_TICKET_ID_UID, fields: ["ticketId"] },
3082
+ {
3083
+ universalIdentifier: REPLY_TIMING_INDEX_CUSTOMER_MESSAGE_AT_UID,
3084
+ fields: ["customerMessageAt"]
3085
+ },
3086
+ { universalIdentifier: REPLY_TIMING_INDEX_RESPONDER_UID, fields: ["responder"] },
3087
+ { universalIdentifier: REPLY_TIMING_INDEX_NEXT_CHECK_AT_UID, fields: ["nextCheckAt"] }
3088
+ ]
3089
+ };
3090
+ }
3091
+ var pipelineStateRecord = {
3092
+ universalIdentifier: PIPELINE_STATE_OBJECT_UID,
3093
+ objectKey: "pipeline-state",
3094
+ labelSingular: "Pipeline state",
3095
+ labelPlural: "Pipeline state",
3096
+ description: "Singleton run-cadence and view-claim state, readable by every installed app.",
3097
+ fields: [
3098
+ {
3099
+ universalIdentifier: PIPELINE_STATE_FIELD_SINGLETON_KEY_UID,
3100
+ name: "singletonKey",
3101
+ type: appKit.FieldType.TEXT,
3102
+ label: "Singleton key",
3103
+ description: "Always the same constant value \u2014 the unique index below is what makes this record a true singleton, not just a convention.",
3104
+ isNullable: false
3105
+ },
3106
+ {
3107
+ universalIdentifier: PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID,
3108
+ name: "sourceViewId",
3109
+ type: appKit.FieldType.TEXT,
3110
+ label: "Source view id",
3111
+ description: "The claimed Gorgias view \u2014 supports the cross-app overlap warning (\xA74).",
3112
+ isNullable: true
3113
+ },
3114
+ {
3115
+ universalIdentifier: PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID,
3116
+ name: "lastTriageAt",
3117
+ type: appKit.FieldType.DATE_TIME,
3118
+ label: "Last triage at",
3119
+ description: "Gates triage-tick's cadence.",
3120
+ isNullable: true
3121
+ },
3122
+ {
3123
+ universalIdentifier: PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID,
3124
+ name: "lastSweepAt",
3125
+ type: appKit.FieldType.DATE_TIME,
3126
+ label: "Last sweep at",
3127
+ isNullable: true
3128
+ }
3129
+ ],
3130
+ indexes: [{ universalIdentifier: PIPELINE_STATE_INDEX_SINGLETON_KEY_UID, fields: ["singletonKey"], isUnique: true }],
3131
+ exposedToApps: ["*"]
3132
+ };
3133
+ var promptCacheRecord = {
3134
+ universalIdentifier: PROMPT_CACHE_OBJECT_UID,
3135
+ objectKey: "prompt-cache",
3136
+ labelSingular: "Prompt cache entry",
3137
+ labelPlural: "Prompt cache entries",
3138
+ description: "Last-known-good snapshot of a Langfuse prompt, for the resolver fallback ladder.",
3139
+ fields: [
3140
+ {
3141
+ universalIdentifier: PROMPT_CACHE_FIELD_PROMPT_KEY_UID,
3142
+ name: "promptKey",
3143
+ type: appKit.FieldType.TEXT,
3144
+ label: "Prompt key",
3145
+ description: "'name' or 'name::label'.",
3146
+ isNullable: false
3147
+ },
3148
+ {
3149
+ universalIdentifier: PROMPT_CACHE_FIELD_CONTENT_UID,
3150
+ name: "content",
3151
+ type: appKit.FieldType.TEXT,
3152
+ label: "Content",
3153
+ description: "Raw, uncompiled template.",
3154
+ isNullable: false
3155
+ },
3156
+ {
3157
+ universalIdentifier: PROMPT_CACHE_FIELD_VERSION_UID,
3158
+ name: "version",
3159
+ type: appKit.FieldType.NUMBER,
3160
+ label: "Version",
3161
+ isNullable: false
3162
+ },
3163
+ {
3164
+ universalIdentifier: PROMPT_CACHE_FIELD_LABEL_UID,
3165
+ name: "label",
3166
+ type: appKit.FieldType.TEXT,
3167
+ label: "Label",
3168
+ isNullable: true
3169
+ },
3170
+ {
3171
+ universalIdentifier: PROMPT_CACHE_FIELD_CONFIG_UID,
3172
+ name: "config",
3173
+ type: appKit.FieldType.JSON,
3174
+ label: "Config",
3175
+ description: "Model config snapshot, for I16. Not yet written or read \u2014 see module doc.",
3176
+ isNullable: true
3177
+ }
3178
+ ],
3179
+ indexes: [{ universalIdentifier: PROMPT_CACHE_INDEX_PROMPT_KEY_UID, fields: ["promptKey"], isUnique: true }]
3180
+ };
3181
+ var SUPPORT_KIT_UID_NAMESPACE = "2b6a9c0e-6c1e-4c1a-8b0e-2a2f4b8c9d3f";
3182
+ function uuidToBytes(uuid) {
3183
+ return Buffer.from(uuid.replace(/-/g, ""), "hex");
3184
+ }
3185
+ function bytesToUuid(bytes) {
3186
+ const hex = bytes.toString("hex");
3187
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
3188
+ }
3189
+ function deriveUid(seed) {
3190
+ const hash = node_crypto.createHash("sha1").update(uuidToBytes(SUPPORT_KIT_UID_NAMESPACE)).update(seed, "utf8").digest();
3191
+ const bytes = hash.subarray(0, 16);
3192
+ bytes[6] = bytes[6] & 15 | 80;
3193
+ bytes[8] = bytes[8] & 63 | 128;
3194
+ return bytesToUuid(bytes);
3195
+ }
3196
+
3197
+ // src/records/scope-to-app.ts
3198
+ function scopeRecordToApp(slug, record) {
3199
+ return {
3200
+ ...record,
3201
+ universalIdentifier: deriveUid(`${slug}:${record.universalIdentifier}`),
3202
+ fields: record.fields.map((field) => ({
3203
+ ...field,
3204
+ universalIdentifier: deriveUid(`${slug}:${field.universalIdentifier}`)
3205
+ })),
3206
+ indexes: record.indexes?.map((index) => ({
3207
+ ...index,
3208
+ universalIdentifier: deriveUid(`${slug}:${index.universalIdentifier}`)
3209
+ }))
3210
+ };
3211
+ }
3212
+
3213
+ // src/records/index.ts
3214
+ function buildSupportKitRecords(slug) {
3215
+ return [
3216
+ buildCategoryRecord(slug),
3217
+ categoryGroupRecord,
3218
+ agentRecord,
3219
+ buildTriageDecisionRecord(slug),
3220
+ buildGeneratedResponseRecord(slug),
3221
+ buildResponseComparisonRecord(slug),
3222
+ buildEvaluationRecord(slug),
3223
+ buildDiffAnalysisRecord(slug),
3224
+ pipelineStateRecord,
3225
+ promptCacheRecord,
3226
+ buildReplyTimingRecord(slug)
3227
+ ].map((record) => scopeRecordToApp(slug, record));
3228
+ }
3229
+
3230
+ // src/settings/conversation-end.ts
3231
+ var CONVERSATION_END_ACTIONS = ["disabled", "tag", "close"];
3232
+ var DEFAULT_CONVERSATION_END_ACTION = "disabled";
3233
+ var DEFAULT_CONVERSATION_END_TAG = "wai/conversation-ended";
3234
+ function readConversationEnd(settings) {
3235
+ const raw = settings;
3236
+ const rawAction = raw.conversationEndAction;
3237
+ const action = CONVERSATION_END_ACTIONS.includes(rawAction) ? rawAction : DEFAULT_CONVERSATION_END_ACTION;
3238
+ const tag = typeof raw.conversationEndTag === "string" ? raw.conversationEndTag.trim() : DEFAULT_CONVERSATION_END_TAG;
3239
+ return { action, tag, prompt: readPrompt(raw.conversationEndPrompt) };
3240
+ }
3241
+ function endConfigOf({
3242
+ action,
3243
+ tag
3244
+ }) {
3245
+ return action === "disabled" ? null : { action, tag };
3246
+ }
3247
+ function toConversationEnd(settings) {
3248
+ return endConfigOf(readConversationEnd(settings));
3249
+ }
3250
+ function conversationEndEffects(end) {
3251
+ if (!end) return { tags: [], close: false };
3252
+ return end.action === "tag" ? { tags: [end.tag], close: false } : { tags: [], close: true };
3253
+ }
3254
+ function readPrompt(raw) {
3255
+ if (typeof raw !== "object" || raw === null) return null;
3256
+ const { name, label } = raw;
3257
+ if (typeof name !== "string" || name === "") return null;
3258
+ return typeof label === "string" && label !== "" ? { name, label } : { name };
3259
+ }
3260
+
3261
+ // src/settings/fields.ts
3262
+ var DEFAULT_STATS_TIMEZONE = "Europe/Paris";
3263
+ var SUPPORT_KIT_SETTINGS_FIELDS = [
3264
+ // Source
3265
+ // NO `gorgiasConnectionId`: every Gorgias call in this kit is
3266
+ // `ctx.api.integrations.run('gorgias', …)` with no `connectionId`, so the
3267
+ // platform resolves the instance's default connection. A settings key here
3268
+ // would be written by an operator and read by nobody — see the Source
3269
+ // section of `ui/settings/settings-page.tsx`, which STATES the resolved
3270
+ // connection instead of pretending to choose it.
3271
+ {
3272
+ key: "sourceViewId",
3273
+ type: "string",
3274
+ label: "Gorgias source view"
3275
+ // No default — see module doc.
3276
+ },
3277
+ { key: "batchLimit", type: "number", label: "Batch limit", default: 30 },
3278
+ { key: "triageEnabled", type: "boolean", label: "Triage enabled", default: false },
3279
+ {
3280
+ key: "triageIntervalMinutes",
3281
+ type: "number",
3282
+ label: "Triage interval (minutes)",
3283
+ default: 15
3284
+ },
3285
+ { key: "dryRun", type: "boolean", label: "Dry run", default: false },
3286
+ // Nodes
3287
+ // `{triage, escalate, draft, evaluate, revise}`, `null` per key disabling
3288
+ // that graph step (§3.6). NO default, same reasoning as `sourceViewId`:
3289
+ // the only shape that could be defaulted here ("every step null") is a
3290
+ // pipeline that triages nothing, and it would install itself silently.
3291
+ // `validateSettings` refuses to run until `nodes.triage` is configured.
3292
+ { key: "nodes", type: "json", label: "Graph node overrides" },
2843
3293
  // Audit tags
2844
3294
  { key: "unknownTag", type: "string", label: "Unknown tag", default: "wai/unknown" },
2845
3295
  { key: "handledTag", type: "string", label: "Handled tag", default: "wai/triaged" },
@@ -2861,6 +3311,24 @@ var SUPPORT_KIT_SETTINGS_FIELDS = [
2861
3311
  // this?". No usable default for the same reason: a mark two apps have in
2862
3312
  // common marks nothing. `validateSettings` refuses to run until it is set.
2863
3313
  { key: "appScopeTag", type: "string", label: "App ticket tag", default: "" },
3314
+ // End of conversation (spec-fin-de-conversation-v1 §5). Off by default (D9):
3315
+ // a new LLM step, with its cost and its false positives, is never switched
3316
+ // on for every app without an explicit decision.
3317
+ {
3318
+ key: "conversationEndAction",
3319
+ type: "select",
3320
+ label: "End-of-conversation action",
3321
+ options: [...CONVERSATION_END_ACTIONS],
3322
+ default: DEFAULT_CONVERSATION_END_ACTION
3323
+ },
3324
+ {
3325
+ key: "conversationEndTag",
3326
+ type: "string",
3327
+ label: "End-of-conversation tag",
3328
+ default: DEFAULT_CONVERSATION_END_TAG
3329
+ },
3330
+ // No default, like every step prompt: `validateSettings` requires it once the action is on.
3331
+ { key: "conversationEndPrompt", type: "json", label: "End-of-conversation prompt" },
2864
3332
  // Sending
2865
3333
  { key: "autoSendEnabled", type: "boolean", label: "Auto-send enabled", default: false },
2866
3334
  { key: "senderEmail", type: "string", label: "Sender email", default: "" },
@@ -2958,8 +3426,35 @@ function validateSettings(settings) {
2958
3426
  message: "senderEmail is required when autoSendEnabled is on, unless whatsappMode is 'auto_reply'."
2959
3427
  });
2960
3428
  }
3429
+ const end = readConversationEnd(settings);
3430
+ if (end.action === "tag" && end.tag === "") {
3431
+ issues.push({
3432
+ key: "conversationEndTag",
3433
+ message: 'conversationEndTag is required when the end-of-conversation action is "tag".'
3434
+ });
3435
+ } else if (end.tag !== "" && reservedTags(settings).includes(end.tag)) {
3436
+ issues.push({
3437
+ key: "conversationEndTag",
3438
+ message: "conversationEndTag must differ from escalationTag, needsReviewTag, followupTag, appScopeTag and handledTag."
3439
+ });
3440
+ }
3441
+ if (end.action !== "disabled" && end.prompt === null) {
3442
+ issues.push({
3443
+ key: "conversationEndPrompt",
3444
+ message: "conversationEndPrompt is required when the end-of-conversation action is on."
3445
+ });
3446
+ }
2961
3447
  return issues;
2962
3448
  }
3449
+ function reservedTags(settings) {
3450
+ return [
3451
+ settings.escalationTag,
3452
+ settings.needsReviewTag,
3453
+ settings.followupTag,
3454
+ settings.appScopeTag,
3455
+ settings.handledTag
3456
+ ].filter(isNonEmptyString).map((tag) => tag.trim());
3457
+ }
2963
3458
  function isNonEmptyString(value) {
2964
3459
  return typeof value === "string" && value.length > 0;
2965
3460
  }
@@ -3137,6 +3632,9 @@ function identifierFor(config, key) {
3137
3632
  return id;
3138
3633
  }
3139
3634
  function mcpToolIdentifierFor(config, key) {
3635
+ return derivedIdentifierFor(config, key);
3636
+ }
3637
+ function derivedIdentifierFor(config, key) {
3140
3638
  return config.identifiers[key] ?? deriveUid(`${config.slug}:function:${key}`);
3141
3639
  }
3142
3640
 
@@ -3445,12 +3943,111 @@ function buildTicketPorts(ctx, trace) {
3445
3943
  clock: createRealClock()
3446
3944
  };
3447
3945
  }
3946
+ async function transitionGeneratedResponse(api, params) {
3947
+ const { id, ticketId, from, to, extra } = params;
3948
+ assertTransition(from, to);
3949
+ try {
3950
+ await api.update(
3951
+ "generated-response",
3952
+ id,
3953
+ { status: to, openTicketKey: openTicketKeyFor(to, ticketId), ...extra ?? {} },
3954
+ { ifMatch: { status: from } }
3955
+ );
3956
+ return true;
3957
+ } catch (err) {
3958
+ if (err instanceof appKit.AppApiError && err.status === 409) return false;
3959
+ throw err;
3960
+ }
3961
+ }
3962
+
3963
+ // src/functions/conversation-end.ts
3964
+ var CONVERSATION_END_LABEL = "conversation-end";
3965
+ var CONVERSATION_END_SCHEMA = {
3966
+ type: "object",
3967
+ properties: {
3968
+ finished: { type: "boolean" },
3969
+ confidence: { type: "string", enum: ["high", "low"] },
3970
+ reasoning: { type: "string", maxLength: REASONING_MAX_LEN }
3971
+ },
3972
+ required: ["finished", "confidence", "reasoning"],
3973
+ additionalProperties: false
3974
+ };
3975
+ function conversationEndJudgeConfig(settings, end) {
3976
+ return {
3977
+ // An empty name cannot resolve: the judge then stands down and the
3978
+ // customer is answered (D5). `validateSettings` makes it unreachable.
3979
+ promptRef: { name: end.prompt?.name ?? "", label: end.prompt?.label ?? "production" },
3980
+ model: settings.nodes.triage.model,
3981
+ reasoning: settings.nodes.triage.reasoning ?? "off"
3982
+ };
3983
+ }
3984
+ async function judgeConversationEnd(deps, messages) {
3985
+ try {
3986
+ const resolved = await deps.prompt.resolve(deps.promptRef);
3987
+ const result = await deps.llm.complete({
3988
+ label: CONVERSATION_END_LABEL,
3989
+ model: deps.model,
3990
+ reasoning: deps.reasoning,
3991
+ messages: [
3992
+ { role: "system", content: resolved.text },
3993
+ { role: "user", content: renderThread(messages) }
3994
+ ],
3995
+ responseSchema: CONVERSATION_END_SCHEMA,
3996
+ promptRef: { name: resolved.name, version: resolved.version, resolve: false }
3997
+ });
3998
+ const parsed = JSON.parse(result.text ?? "");
3999
+ if (typeof parsed.finished !== "boolean" || parsed.confidence !== "high" && parsed.confidence !== "low") {
4000
+ throw new Error(`Invalid conversation-end payload: ${result.text}`);
4001
+ }
4002
+ return {
4003
+ finished: parsed.finished && parsed.confidence === "high",
4004
+ reason: String(parsed.reasoning ?? "").slice(0, REASONING_MAX_LEN)
4005
+ };
4006
+ } catch (err) {
4007
+ return {
4008
+ finished: false,
4009
+ reason: `\xC9tape en erreur, on r\xE9pond : ${err.message}`.slice(0, REASONING_MAX_LEN)
4010
+ };
4011
+ }
4012
+ }
4013
+ function renderThread(messages) {
4014
+ const lines = messages.map(
4015
+ (message) => `${message.role === "user" ? "Client" : "Nous"} : ${message.content}`
4016
+ );
4017
+ const lastOurs = messages.map((message) => message.role).lastIndexOf("assistant");
4018
+ const pending = messages.slice(lastOurs + 1).filter((message) => message.role === "user").map((message) => message.content);
4019
+ return `## Fil de la conversation
4020
+ ${lines.join("\n")}
4021
+
4022
+ ## Messages du client depuis notre derni\xE8re r\xE9ponse
4023
+ ${pending.join("\n")}`;
4024
+ }
4025
+ function describeEndAction(action, tag, simulated) {
4026
+ const what = action === "tag" ? `tag \xAB ${tag} \xBB` : "fermeture du ticket";
4027
+ return simulated ? `action pr\xE9vue : ${what} (aucun effet Gorgias)` : `action : ${what}`;
4028
+ }
4029
+ async function applyConversationEnd(ctx, ticketId, end) {
4030
+ const { tags, close } = conversationEndEffects(end);
4031
+ if (tags.length > 0)
4032
+ await ctx.api.integrations.run("gorgias", "applyTags", { ticketId, names: tags });
4033
+ if (close) await ctx.api.integrations.run("gorgias", "closeTicket", { ticketId });
4034
+ }
4035
+ async function finishConversationEnd(ctx, params) {
4036
+ const { responseId, ticketId, end, simulated, extra } = params;
4037
+ if (!simulated) await applyConversationEnd(ctx, ticketId, end);
4038
+ await transitionGeneratedResponse(ctx.api, {
4039
+ id: responseId,
4040
+ ticketId,
4041
+ from: "pending",
4042
+ to: "no_reply_needed",
4043
+ extra
4044
+ });
4045
+ }
3448
4046
 
3449
4047
  // src/functions/eligibility.ts
3450
4048
  function isEligibleForGeneratedResponse(profile, classification, escalated, category) {
3451
4049
  if (!category || !category.fastResponseEnabled || !category.agentId) return false;
3452
4050
  if (escalated) return false;
3453
- if (isConversationOver(classification)) return false;
3454
4051
  if (isFallbackClassification(classification)) return false;
3455
4052
  if (hasNoDraftNode(profile)) return false;
3456
4053
  return true;
@@ -3502,8 +4099,106 @@ async function upsertPipelineState(api, patch) {
3502
4099
  { uniqueBy: ["singletonKey"] }
3503
4100
  );
3504
4101
  }
4102
+ var OPEN_TURNS_PAGE_SIZE = 50;
4103
+ async function openReplyTiming(ctx, turn) {
4104
+ const { awaitingSince } = turn.conversation;
4105
+ if (!awaitingSince) return null;
4106
+ try {
4107
+ return await createTurn(ctx, turn, awaitingSince);
4108
+ } catch (err) {
4109
+ logFailure(ctx, `could not open the turn of ticket ${turn.ticketId}`, err);
4110
+ return null;
4111
+ }
4112
+ }
4113
+ async function linkReplyTimingToDraft(ctx, replyTimingId, draft2) {
4114
+ try {
4115
+ await ctx.api.update(
4116
+ "reply-timing",
4117
+ replyTimingId,
4118
+ {
4119
+ generatedResponseId: draft2.id,
4120
+ ...draft2.categoryId ? { categoryId: draft2.categoryId } : {}
4121
+ },
4122
+ { ifMatch: { generatedResponseId: null } }
4123
+ );
4124
+ } catch (err) {
4125
+ if (isConflict(err)) return;
4126
+ logFailure(ctx, `could not link turn ${replyTimingId} to its draft`, err);
4127
+ }
4128
+ }
4129
+ async function closeReplyTimingAsAi(ctx, ticketId, sentAt, generatedResponseId) {
4130
+ try {
4131
+ const turn = await turnAnsweredBy(ctx, ticketId, sentAt, generatedResponseId);
4132
+ if (!turn) return;
4133
+ await ctx.api.update(
4134
+ "reply-timing",
4135
+ turn.row.id,
4136
+ closingFields(turn.customerMessageAt, sentAt, "ai"),
4137
+ { ifMatch: { responder: null } }
4138
+ );
4139
+ } catch (err) {
4140
+ if (isConflict(err)) return;
4141
+ logFailure(ctx, `could not close the turn of ticket ${ticketId}`, err);
4142
+ }
4143
+ }
4144
+ async function findTurn(ctx, turnKey) {
4145
+ const page = await ctx.api.list("reply-timing", { filter: { turnKey }, limit: 1 });
4146
+ return page.items[0]?.id ?? null;
4147
+ }
4148
+ async function createTurn(ctx, turn, awaitingSince) {
4149
+ const turnKey = turnKeyFor(turn.ticketId, awaitingSince);
4150
+ try {
4151
+ const created = await ctx.api.create("reply-timing", {
4152
+ ticketId: turn.ticketId,
4153
+ turnKey,
4154
+ customerMessageAt: awaitingSince.at,
4155
+ // Written as explicit nulls: `ifMatch` only matches a key that exists.
4156
+ repliedAt: null,
4157
+ responder: null,
4158
+ responderVia: null,
4159
+ delaySeconds: null,
4160
+ delayBucket: null,
4161
+ categoryId: turn.categoryId,
4162
+ sourceChannel: turn.conversation.sourceChannel,
4163
+ generatedResponseId: null,
4164
+ nextCheckAt: new Date(awaitingSince.at.getTime() + FIRST_CHECK_DELAY_MS),
4165
+ backfilled: false,
4166
+ origin: turn.origin
4167
+ });
4168
+ return created.id;
4169
+ } catch (err) {
4170
+ if (isConflict(err)) return findTurn(ctx, turnKey);
4171
+ throw err;
4172
+ }
4173
+ }
4174
+ async function turnAnsweredBy(ctx, ticketId, sentAt, generatedResponseId) {
4175
+ const page = await ctx.api.list("reply-timing", {
4176
+ filter: { ticketId, responder: null },
4177
+ limit: OPEN_TURNS_PAGE_SIZE
4178
+ });
4179
+ let latest = null;
4180
+ for (const row of page.items) {
4181
+ const customerMessageAt = toDate(row.data.customerMessageAt);
4182
+ if (!customerMessageAt) continue;
4183
+ if (row.data.generatedResponseId === generatedResponseId) return { row, customerMessageAt };
4184
+ if (customerMessageAt > sentAt) continue;
4185
+ if (!latest || customerMessageAt > latest.customerMessageAt)
4186
+ latest = { row, customerMessageAt };
4187
+ }
4188
+ return latest;
4189
+ }
4190
+ function isConflict(err) {
4191
+ return err instanceof appKit.AppApiError && err.status === 409;
4192
+ }
4193
+ function logFailure(ctx, what, err) {
4194
+ ctx.logger.error(`reply-timing: ${what} \u2014 the measure is skipped, the pipeline goes on`, {
4195
+ error: err instanceof Error ? err.message : String(err)
4196
+ });
4197
+ }
4198
+
4199
+ // src/functions/claim-commit.ts
3505
4200
  function buildSendSeam(params) {
3506
- const { api, clock, id, ticketId, fromStatus, extraClaimData } = params;
4201
+ const { api, clock, logger, id, ticketId, fromStatus, extraClaimData } = params;
3507
4202
  return {
3508
4203
  async claim(run) {
3509
4204
  assertTransition(fromStatus, "sending");
@@ -3527,6 +4222,7 @@ function buildSendSeam(params) {
3527
4222
  },
3528
4223
  async commit(messageId) {
3529
4224
  assertTransition("sending", "sent");
4225
+ const sentAt = clock.now();
3530
4226
  await api.update(
3531
4227
  "generated-response",
3532
4228
  id,
@@ -3537,12 +4233,13 @@ function buildSendSeam(params) {
3537
4233
  // send) — so stamping the outcome here covers both without either
3538
4234
  // needing to remember to.
3539
4235
  outcome: "sent",
3540
- sentAt: clock.now(),
4236
+ sentAt,
3541
4237
  sentMessageId: messageId,
3542
4238
  openTicketKey: openTicketKeyFor("sent", ticketId)
3543
4239
  },
3544
4240
  { ifMatch: { status: "sending" } }
3545
4241
  );
4242
+ await closeReplyTimingAsAi({ api, logger }, ticketId, sentAt, id);
3546
4243
  }
3547
4244
  };
3548
4245
  }
@@ -3838,8 +4535,7 @@ function classificationFromDecision(decision) {
3838
4535
  category: data.tag ?? "",
3839
4536
  confidence: data.confidence ?? "low",
3840
4537
  reasoning: data.reasoning ?? "",
3841
- isFallback: false,
3842
- conversationOver: data.conversationOver ?? false
4538
+ isFallback: false
3843
4539
  };
3844
4540
  }
3845
4541
  function attributionFields(attribution) {
@@ -3924,6 +4620,7 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
3924
4620
  const seam = buildSendSeam({
3925
4621
  api: ctx.api,
3926
4622
  clock,
4623
+ logger: ctx.logger,
3927
4624
  id: recordId,
3928
4625
  ticketId,
3929
4626
  fromStatus: "pending",
@@ -4012,7 +4709,6 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
4012
4709
  }
4013
4710
  case "escalated":
4014
4711
  case "triaged_only":
4015
- case "no_reply_needed":
4016
4712
  await finalizeNonSent(ctx, recordId, ticketId, testRun ? restingStatus : "no_reply_needed", draftExtra);
4017
4713
  return result.outcome;
4018
4714
  case "failed":
@@ -4023,22 +4719,6 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
4023
4719
  return null;
4024
4720
  }
4025
4721
  }
4026
- async function transitionGeneratedResponse(api, params) {
4027
- const { id, ticketId, from, to, extra } = params;
4028
- assertTransition(from, to);
4029
- try {
4030
- await api.update(
4031
- "generated-response",
4032
- id,
4033
- { status: to, openTicketKey: openTicketKeyFor(to, ticketId), ...extra ?? {} },
4034
- { ifMatch: { status: from } }
4035
- );
4036
- return true;
4037
- } catch (err) {
4038
- if (err instanceof appKit.AppApiError && err.status === 409) return false;
4039
- throw err;
4040
- }
4041
- }
4042
4722
 
4043
4723
  // src/functions/ticket-url.ts
4044
4724
  async function resolveTicketUrlBase(ctx) {
@@ -4087,7 +4767,7 @@ function recordTriageTraces(llm) {
4087
4767
  },
4088
4768
  fields() {
4089
4769
  const traceId = results.get(TRIAGE_LABEL)?.traceId;
4090
- const observationIds = [TRIAGE_LABEL, ESCALATION_LABEL].map((label) => results.get(label)?.observationId).filter((id) => Boolean(id));
4770
+ const observationIds = [TRIAGE_LABEL, ESCALATION_LABEL, CONVERSATION_END_LABEL].map((label) => results.get(label)?.observationId).filter((id) => Boolean(id));
4091
4771
  return {
4092
4772
  ...traceId ? { langfuseTraceId: traceId } : {},
4093
4773
  ...observationIds.length > 0 ? { langfuseObservationIds: observationIds } : {}
@@ -4146,6 +4826,7 @@ async function runTriageBatch(ctx, config, settings) {
4146
4826
  const batchDefaultAgent = await resolveDraftAgent(ctx.api, null);
4147
4827
  const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(batchDefaultAgent, config), settings.nodes));
4148
4828
  const ticketUrlBase = await resolveTicketUrlBase(ctx);
4829
+ const conversationEnd = conversationEndFor(settings, ports);
4149
4830
  const refs = await ports.conversation.listPending({ viewOrTag: settings.sourceViewId }, settings.batchLimit);
4150
4831
  const run = await ctx.api.runs.start({
4151
4832
  kind: "triage-tick",
@@ -4162,7 +4843,9 @@ async function runTriageBatch(ctx, config, settings) {
4162
4843
  categories,
4163
4844
  ports,
4164
4845
  runId: run.id,
4165
- ticketUrlBase
4846
+ ticketUrlBase,
4847
+ dryRun,
4848
+ conversationEnd
4166
4849
  });
4167
4850
  } catch (err) {
4168
4851
  failureCount += 1;
@@ -4183,6 +4866,12 @@ async function runTriageBatch(ctx, config, settings) {
4183
4866
  }
4184
4867
  return { ticketCount: refs.length, failureCount };
4185
4868
  }
4869
+ function conversationEndFor(settings, ports) {
4870
+ const endSettings = readConversationEnd(settings);
4871
+ const config = endConfigOf(endSettings);
4872
+ if (!config) return null;
4873
+ return { config, judge: { prompt: ports.prompt, ...conversationEndJudgeConfig(settings, endSettings) } };
4874
+ }
4186
4875
  var ResponsePhaseError = class extends Error {
4187
4876
  generatedResponseId;
4188
4877
  constructor(generatedResponseId, cause) {
@@ -4264,11 +4953,11 @@ async function flagEscalation(ctx, ref, tag, ports) {
4264
4953
  }
4265
4954
  }
4266
4955
  async function processOneTicket(ctx, ref, deps) {
4267
- const { config, profile, categories, ports, runId, ticketUrlBase } = deps;
4956
+ const { config, profile, categories, ports, runId, ticketUrlBase, dryRun } = deps;
4268
4957
  let subjectRenamed = false;
4269
4958
  if (profile.rename) {
4270
- const conversation2 = await ports.conversation.read(ref);
4271
- const subject = conversation2.subject ?? "";
4959
+ const conversation = await ports.conversation.read(ref);
4960
+ const subject = conversation.subject ?? "";
4272
4961
  if (subject.includes(profile.rename.from)) {
4273
4962
  await ports.state.rename(ref, subject.replace(profile.rename.from, profile.rename.to));
4274
4963
  subjectRenamed = true;
@@ -4298,6 +4987,9 @@ async function processOneTicket(ctx, ref, deps) {
4298
4987
  if (!state.classification) throw new Error("triage produced no classification");
4299
4988
  const { classification } = state;
4300
4989
  const category = findCategoryByTag(categories, classification.category);
4990
+ const judgement = await judgeFirstMessage(state, deps, traces.llm);
4991
+ const finished = judgement?.finished === true;
4992
+ const end = deps.conversationEnd?.config;
4301
4993
  const decision = await ctx.api.create("triage-decision", {
4302
4994
  ticketId: ref.id,
4303
4995
  ticketUrl,
@@ -4305,8 +4997,10 @@ async function processOneTicket(ctx, ref, deps) {
4305
4997
  categoryId: category?.id ?? null,
4306
4998
  tag: classification.category,
4307
4999
  confidence: classification.confidence,
4308
- reasoning: classification.reasoning,
4309
- conversationOver: classification.conversationOver ?? false,
5000
+ // §6 — the action applied (or planned, in dryRun) and the step's reason.
5001
+ reasoning: finished ? `${classification.reasoning} \u2014 Fin de conversation (${describeEndAction(end.action, end.tag, deps.dryRun)}) : ${judgement.reason}`.slice(0, REASONING_MAX_LEN) : classification.reasoning,
5002
+ // D1 — the end-of-conversation step's verdict, never the triage's.
5003
+ conversationOver: finished,
4310
5004
  escalated: state.escalated,
4311
5005
  status: "ok",
4312
5006
  runId,
@@ -4314,45 +5008,97 @@ async function processOneTicket(ctx, ref, deps) {
4314
5008
  origin: "triage",
4315
5009
  ...traces.fields()
4316
5010
  });
5011
+ const replyTimingId = dryRun || finished || !state.conversation ? null : await openReplyTiming(ctx, {
5012
+ ticketId: ref.id,
5013
+ conversation: state.conversation,
5014
+ categoryId: category?.id ?? null,
5015
+ origin: "triage"
5016
+ });
4317
5017
  await ports.state.record(ref, classification, profile.audit);
4318
5018
  if (state.escalated) await flagEscalation(ctx, ref, profile.audit.escalationTag, ports);
5019
+ if (finished) return endFirstMessage(ctx, ref, deps, { decisionId: decision.id, category, conversation: state.conversation });
4319
5020
  if (!isEligibleForGeneratedResponse(profile, classification, state.escalated, category)) return;
4320
5021
  const draftAgent = await resolveDraftAgent(ctx.api, category?.agentId ?? null);
4321
- const conversation = state.conversation;
5022
+ const created = await openPendingResponse(
5023
+ ctx,
5024
+ ref,
5025
+ pendingResponseFields(deps, { decisionId: decision.id, category, agentId: draftAgent?.id ?? null, conversation: state.conversation })
5026
+ );
5027
+ if (!created) return;
5028
+ if (replyTimingId) await linkReplyTimingToDraft(ctx, replyTimingId, { id: created.id, categoryId: category?.id ?? null });
5029
+ try {
5030
+ await respondToPendingResponse(ctx, config, created.id);
5031
+ } catch (err) {
5032
+ throw new ResponsePhaseError(created.id, err);
5033
+ }
5034
+ }
5035
+ function pendingResponseFields(deps, input) {
5036
+ const { conversation } = input;
4322
5037
  const channel = conversation?.sourceChannel === "whatsapp" ? "whatsapp" : "email";
4323
5038
  const sourceChannel = conversation?.sourceChannel ?? null;
4324
- const generatedAt = ports.clock.now();
4325
- const expiresAt = new Date(generatedAt.getTime() + profile.schedule.fastResponseTtlMinutes * 6e4);
4326
- let created;
5039
+ const generatedAt = deps.ports.clock.now();
5040
+ const expiresAt = new Date(generatedAt.getTime() + deps.profile.schedule.fastResponseTtlMinutes * 6e4);
5041
+ return {
5042
+ triageDecisionId: input.decisionId,
5043
+ categoryId: input.category?.id ?? null,
5044
+ agentId: input.agentId,
5045
+ channel,
5046
+ sourceChannel,
5047
+ generatedAt,
5048
+ expiresAt,
5049
+ sources: [],
5050
+ tracedInput: [],
5051
+ guardrailHits: [],
5052
+ servedTo: [],
5053
+ servedCount: 0,
5054
+ followupRequired: false,
5055
+ origin: "triage"
5056
+ };
5057
+ }
5058
+ async function openPendingResponse(ctx, ref, fields) {
4327
5059
  try {
4328
- created = await ctx.api.create("generated-response", {
5060
+ return await ctx.api.create("generated-response", {
4329
5061
  ticketId: ref.id,
4330
5062
  openTicketKey: openTicketKeyFor("pending", ref.id),
4331
5063
  status: "pending",
4332
- triageDecisionId: decision.id,
4333
- categoryId: category?.id ?? null,
4334
- agentId: draftAgent?.id ?? null,
4335
- channel,
4336
- sourceChannel,
4337
- generatedAt,
4338
- expiresAt,
4339
- sources: [],
4340
- tracedInput: [],
4341
- guardrailHits: [],
4342
- servedTo: [],
4343
- servedCount: 0,
4344
- followupRequired: false,
4345
- origin: "triage"
5064
+ ...fields
4346
5065
  });
4347
5066
  } catch (err) {
4348
5067
  if (err instanceof appKit.AppApiError && err.status === 409) {
4349
5068
  ctx.logger.debug(`triage-tick: generated-response already pending for ticket ${ref.id}, skipping`);
4350
- return;
5069
+ return null;
4351
5070
  }
4352
5071
  throw err;
4353
5072
  }
5073
+ }
5074
+ async function judgeFirstMessage(state, deps, llm) {
5075
+ if (!deps.conversationEnd || state.escalated || !state.conversation) return null;
5076
+ if (stopOptOut(state.conversation).length > 0) return null;
5077
+ return judgeConversationEnd({ ...deps.conversationEnd.judge, llm }, state.conversation.messages);
5078
+ }
5079
+ async function endFirstMessage(ctx, ref, deps, input) {
5080
+ const { conversation } = input;
5081
+ const created = await openPendingResponse(ctx, ref, {
5082
+ // D16 — nobody writes a draft on a finished conversation, so the row names no writer.
5083
+ ...pendingResponseFields(deps, { ...input, agentId: null }),
5084
+ outcome: "no_reply_needed"
5085
+ });
5086
+ if (!created) {
5087
+ throw new Error(
5088
+ `triage-tick: another open response holds ticket ${ref.id}, end action not applied`
5089
+ );
5090
+ }
4354
5091
  try {
4355
- await respondToPendingResponse(ctx, config, created.id);
5092
+ await finishConversationEnd(ctx, {
5093
+ responseId: created.id,
5094
+ ticketId: ref.id,
5095
+ end: deps.conversationEnd.config,
5096
+ simulated: deps.dryRun,
5097
+ extra: {
5098
+ generatedMessageCount: conversation.messageCount,
5099
+ generatedLastMessageAt: conversation.lastMessageAt
5100
+ }
5101
+ });
4356
5102
  } catch (err) {
4357
5103
  throw new ResponsePhaseError(created.id, err);
4358
5104
  }
@@ -4542,7 +5288,7 @@ async function handleApprovalHandler(ctx, config) {
4542
5288
  revised: false
4543
5289
  };
4544
5290
  const proposedActions = [{ kind: "send_reply", args: {}, idempotencyKey: id, decision: "auto" }];
4545
- const seam = buildSendSeam({ api: ctx.api, clock, id, ticketId, fromStatus: "ready" });
5291
+ const seam = buildSendSeam({ api: ctx.api, clock, logger: ctx.logger, id, ticketId, fromStatus: "ready" });
4546
5292
  let claimed = true;
4547
5293
  const trackedSeam = {
4548
5294
  claim: async (run) => {
@@ -4646,6 +5392,7 @@ var LIST_TICKETS_INPUT_CHANNEL_UID = "a03a94ef-ccc6-48d9-a088-656406bb1585";
4646
5392
  var LIST_TICKETS_INPUT_STATUS_UID = "e2fdddae-0464-496d-9526-bb017c544f09";
4647
5393
  var LIST_TICKETS_INPUT_CURSOR_UID = "dfba83d4-8a6b-4e8b-bcfb-f3fc3cf663eb";
4648
5394
  var EXPLAIN_TICKET_INPUT_TICKET_ID_UID = "7b0e5d3a-42c1-4f6e-9a58-0d1c6f3e8b24";
5395
+ var BACKFILL_REPLY_TIMING_INPUT_SINCE_DAYS_UID = "8039f58a-b452-45ef-8920-3bc8acd748be";
4649
5396
 
4650
5397
  // src/functions/run-triage-now.ts
4651
5398
  var TRIAGE_RUN_REQUESTED_EVENT = "triage.run.requested";
@@ -4975,7 +5722,7 @@ function applyOverrides(profile, overrides) {
4975
5722
  };
4976
5723
  }
4977
5724
  function forcedClassification(tagName) {
4978
- return { category: tagName, confidence: "high", reasoning: "operator: cat\xE9gorie forc\xE9e", isFallback: false, conversationOver: false };
5725
+ return { category: tagName, confidence: "high", reasoning: "operator: cat\xE9gorie forc\xE9e", isFallback: false };
4979
5726
  }
4980
5727
  var INLINE_TICKET_ID = "ticket-saisi";
4981
5728
  function createInlineConversationPort(ticket, now) {
@@ -5429,6 +6176,113 @@ async function listGorgiasViewsHandler(ctx, config, input) {
5429
6176
  connections
5430
6177
  };
5431
6178
  }
6179
+ var DEFAULT_BACKFILL_DAYS = 30;
6180
+ var MAX_BACKFILL_DAYS = 90;
6181
+ var PAGE_SIZE = 500;
6182
+ var LOOKUP_CHUNK = 500;
6183
+ var UPSERT_CHUNK = 100;
6184
+ function buildBackfillReplyTimingFunctionDef(config) {
6185
+ return {
6186
+ universalIdentifier: derivedIdentifierFor(config, "backfill-reply-timing"),
6187
+ name: "backfill-reply-timing",
6188
+ trigger: { type: "uiInvoke", minRole: "ADMIN", timeoutMs: 3e4 },
6189
+ input: [
6190
+ {
6191
+ universalIdentifier: BACKFILL_REPLY_TIMING_INPUT_SINCE_DAYS_UID,
6192
+ name: "sinceDays",
6193
+ type: appKit.FieldType.NUMBER,
6194
+ label: "Since (days)",
6195
+ description: `How many days back to rebuild, ${DEFAULT_BACKFILL_DAYS} by default.`,
6196
+ isNullable: true
6197
+ }
6198
+ ]
6199
+ };
6200
+ }
6201
+ function createBackfillReplyTimingHandler() {
6202
+ return (ctx, input) => backfillReplyTimingHandler(
6203
+ ctx,
6204
+ input ?? {}
6205
+ );
6206
+ }
6207
+ async function backfillReplyTimingHandler(ctx, input, now = /* @__PURE__ */ new Date()) {
6208
+ const sinceDays = input.sinceDays ?? DEFAULT_BACKFILL_DAYS;
6209
+ if (!Number.isInteger(sinceDays) || sinceDays < 1 || sinceDays > MAX_BACKFILL_DAYS) {
6210
+ throw new ctx.NonRetriableError(
6211
+ `sinceDays doit \xEAtre un nombre entier de jours entre 1 et ${MAX_BACKFILL_DAYS}.`
6212
+ );
6213
+ }
6214
+ const since = new Date(now.getTime() - sinceDays * 864e5);
6215
+ const sent = await listAll(ctx.api, "generated-response", {
6216
+ status: "sent",
6217
+ generatedAt: { gte: since.toISOString() }
6218
+ });
6219
+ const turns = sent.flatMap((row) => {
6220
+ const turn = backfilledTurnOf(toGeneratedResponse(row));
6221
+ return turn ? [turn] : [];
6222
+ });
6223
+ const known = await knownSignatures(ctx.api, [
6224
+ ...new Set(turns.map((turn) => String(turn.ticketId)))
6225
+ ]);
6226
+ const missing = turns.filter((turn) => {
6227
+ const signatures = signaturesOf(turn);
6228
+ if (signatures.some((signature) => known.has(signature))) return false;
6229
+ signatures.forEach((signature) => known.add(signature));
6230
+ return true;
6231
+ });
6232
+ for (let start = 0; start < missing.length; start += UPSERT_CHUNK) {
6233
+ const chunk = missing.slice(start, start + UPSERT_CHUNK).map((data) => ({ data }));
6234
+ await ctx.api.upsert("reply-timing", chunk, { uniqueBy: ["turnKey"] });
6235
+ }
6236
+ return { created: missing.length, skipped: turns.length - missing.length };
6237
+ }
6238
+ function backfilledTurnOf(response) {
6239
+ const customerMessageAt = toDate(response.generatedLastMessageAt);
6240
+ const sentAt = toDate(response.sentAt);
6241
+ if (!customerMessageAt || !sentAt) return null;
6242
+ return {
6243
+ ticketId: response.ticketId,
6244
+ turnKey: turnKeyFor(response.ticketId, { at: customerMessageAt, messageId: null }),
6245
+ customerMessageAt,
6246
+ ...closingFields(customerMessageAt, sentAt, "ai"),
6247
+ categoryId: response.categoryId,
6248
+ sourceChannel: response.sourceChannel,
6249
+ generatedResponseId: response.id,
6250
+ backfilled: true,
6251
+ origin: response.origin
6252
+ };
6253
+ }
6254
+ function signaturesOf(turn) {
6255
+ const repliedAt = toDate(turn.repliedAt);
6256
+ return [
6257
+ `key:${String(turn.turnKey)}`,
6258
+ ...turn.generatedResponseId ? [`response:${String(turn.generatedResponseId)}`] : [],
6259
+ ...repliedAt ? [`reply:${String(turn.ticketId)}@${repliedAt.getTime()}`] : []
6260
+ ];
6261
+ }
6262
+ async function knownSignatures(api, ticketIds) {
6263
+ const known = /* @__PURE__ */ new Set();
6264
+ for (let start = 0; start < ticketIds.length; start += LOOKUP_CHUNK) {
6265
+ const chunk = ticketIds.slice(start, start + LOOKUP_CHUNK);
6266
+ for (const row of await listAll(api, "reply-timing", { ticketId: { in: chunk } })) {
6267
+ signaturesOf(row.data).forEach((signature) => known.add(signature));
6268
+ }
6269
+ }
6270
+ return known;
6271
+ }
6272
+ async function listAll(api, objectKey, filter) {
6273
+ const rows = [];
6274
+ let cursor;
6275
+ do {
6276
+ const page = await api.list(objectKey, {
6277
+ filter,
6278
+ limit: PAGE_SIZE,
6279
+ ...cursor ? { cursor } : {}
6280
+ });
6281
+ rows.push(...page.items);
6282
+ cursor = page.nextCursor ?? void 0;
6283
+ } while (cursor);
6284
+ return rows;
6285
+ }
5432
6286
  var PENDING_PROMPT_NAME = "agent/pending";
5433
6287
  function buildCreateAgentFunctionDef(config) {
5434
6288
  return {
@@ -6379,6 +7233,7 @@ var LABELS = {
6379
7233
  G6: "Aucune reprise humaine",
6380
7234
  G7: "Cat\xE9gorie r\xE9solue et opt\xE9e",
6381
7235
  G8: "Nouveau message client",
7236
+ FC: "Fin de conversation",
6382
7237
  G9: "R\xE9ponse ouverte pr\xE9empt\xE9e"
6383
7238
  };
6384
7239
  function humanTakeoverTags(settings) {
@@ -6404,29 +7259,45 @@ function completeFollowupLadder(results) {
6404
7259
  const missing = ALL_FOLLOWUP_GATES.filter((gate) => !evaluated.has(gate));
6405
7260
  return missing.length === 0 ? results : [...results, ...skippedFollowupGates(missing)];
6406
7261
  }
6407
- var FRESH_READ_GATES = ["G5", "G6", "G7", "G8"];
6408
- var ALL_FOLLOWUP_GATES = ["G1", "G2", ...FRESH_READ_GATES, "G9"];
7262
+ var FRESH_READ_GATES = ["G5", "G6", "G8"];
7263
+ var PAYLOAD_GATES = ["G5", "G6", "G7", "G8"];
7264
+ var ALL_FOLLOWUP_GATES = ["G1", "G2", ...FRESH_READ_GATES, "FC", "G7", "G9"];
6409
7265
  function evaluateTicketGates(input) {
6410
- const {
6411
- settings,
6412
- tags,
6413
- categories,
6414
- conversation,
6415
- anchor,
6416
- openResponse = null,
6417
- ignoreCategoryOptIn = false
6418
- } = input;
7266
+ const { settings, tags, conversation, anchor, openResponse = null } = input;
6419
7267
  const trace = newTrace(FRESH_READ_GATES);
6420
7268
  trace.record(scopeTagOnTicket(settings, tags));
6421
7269
  trace.record(noHumanTakeover(settings, tags));
6422
- const match = trace.record(categoryGate(categories, tags, ignoreCategoryOptIn));
6423
- if (match) trace.category = match;
6424
7270
  trace.record(newCustomerMessage(conversation, anchor, openResponse));
6425
7271
  return trace.done();
6426
7272
  }
7273
+ function evaluateCategoryGate(input) {
7274
+ const { category, ...result } = categoryGate(input.categories, input.tags, input.ignoreCategoryOptIn ?? false);
7275
+ return { result, category: result.status === "passed" ? category ?? null : null };
7276
+ }
7277
+ function bestMatchingCategory(categories, tags) {
7278
+ return matchingCategories(categories, tags).sort(byRank)[0] ?? null;
7279
+ }
7280
+ function byRank(a, b) {
7281
+ return a.order - b.order || a.id.localeCompare(b.id);
7282
+ }
7283
+ function conversationEndDisabled() {
7284
+ return passed("FC", "D\xE9sactiv\xE9e dans les r\xE9glages : le message suit le chemin habituel.");
7285
+ }
7286
+ function conversationEndJudged(judgement, action = "") {
7287
+ return judgement.finished ? stopped("FC", `Conversation finie \u2014 ${action}. ${judgement.reason}`.trim()) : passed("FC", `Le message appelle une r\xE9ponse. ${judgement.reason}`.trim());
7288
+ }
7289
+ function conversationEndBlocked(detail) {
7290
+ return stopped("FC", `Conversation finie, mais aucune action de fin : ${detail}`);
7291
+ }
7292
+ function conversationEndSkippedForOptOut() {
7293
+ return passed("FC", "Opt-out STOP : jamais jug\xE9 fin de conversation, le chemin opt-out suit son cours.");
7294
+ }
7295
+ function conversationEndPredicted(promptName) {
7296
+ return muted("FC", `Jug\xE9e au passage r\xE9el par le prompt \xAB ${promptName} \xBB \u2014 le diagnostic n\u2019appelle pas le LLM.`);
7297
+ }
6427
7298
  function evaluatePayloadGates(input) {
6428
7299
  const { settings, body, categories, anchor } = input;
6429
- const trace = newTrace(FRESH_READ_GATES);
7300
+ const trace = newTrace(PAYLOAD_GATES);
6430
7301
  const tags = body.tags;
6431
7302
  if (tags === null) {
6432
7303
  const detail = "Les tags du ticket n\u2019ont pas pu \xEAtre lus dans la charge utile \u2014 la lecture fra\xEEche tranchera.";
@@ -6452,7 +7323,7 @@ function noHumanTakeover(settings, tags) {
6452
7323
  function categoryGate(categories, tags, ignoreOptIn) {
6453
7324
  const matches = matchingCategories(categories, tags);
6454
7325
  if (matches.length === 0) return noMatchingCategory();
6455
- const eligible = matches.filter((category2) => (ignoreOptIn || category2.followupFastResponseEnabled) && category2.agentId).sort((a, b) => a.order - b.order || a.id.localeCompare(b.id));
7326
+ const eligible = matches.filter((category2) => (ignoreOptIn || category2.followupFastResponseEnabled) && category2.agentId).sort(byRank);
6456
7327
  if (eligible.length === 0) return noEligibleCategory(matches, ignoreOptIn);
6457
7328
  const category = eligible[0];
6458
7329
  const detail = matches.length === 1 ? `Cat\xE9gorie \xAB ${category.name} \xBB (tag \xAB ${category.tagName} \xBB).` : `Cat\xE9gorie \xAB ${category.name} \xBB (tag \xAB ${category.tagName} \xBB), retenue parmi ${matches.length} cat\xE9gories correspondantes (${tagList(matches)}).`;
@@ -6526,13 +7397,11 @@ function newTrace(gates) {
6526
7397
  const results = [];
6527
7398
  let stop2 = null;
6528
7399
  return {
6529
- category: null,
6530
- /** Records `result` unless the run already stopped; returns the category it resolved, if any. */
7400
+ /** Records `result` unless the run already stopped. */
6531
7401
  record(result) {
6532
- if (stop2) return null;
7402
+ if (stop2) return;
6533
7403
  results.push({ gate: result.gate, label: result.label, status: result.status, detail: result.detail });
6534
7404
  if (result.status === "stopped") stop2 = result;
6535
- return result.category ?? null;
6536
7405
  },
6537
7406
  done() {
6538
7407
  const evaluated = new Set(results.map((result) => result.gate));
@@ -6541,7 +7410,7 @@ function newTrace(gates) {
6541
7410
  results.push({ gate, label: LABELS[gate], status: "skipped", detail: "Non \xE9valu\xE9 : un gate pr\xE9c\xE9dent a arr\xEAt\xE9 le traitement." });
6542
7411
  }
6543
7412
  }
6544
- return { results, stop: stop2, category: stop2 ? null : this.category };
7413
+ return { results, stop: stop2 };
6545
7414
  }
6546
7415
  };
6547
7416
  }
@@ -6719,20 +7588,51 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
6719
7588
  const ticket = await ctx.api.integrations.run("gorgias", "getTicketWithContext", { ticketId });
6720
7589
  const raw = ticket?.ticket ?? {};
6721
7590
  const conversation = toConversation(ref, raw, ticket?.context ?? { messages: [], customerContext: null });
6722
- const gates = evaluateTicketGates({
6723
- settings,
6724
- tags: ticketTagNames(raw),
6725
- categories,
6726
- conversation,
6727
- anchor,
6728
- openResponse,
6729
- ignoreCategoryOptIn: generateOnly
6730
- });
7591
+ const tags = ticketTagNames(raw);
7592
+ const gates = evaluateTicketGates({ settings, tags, conversation, anchor, openResponse });
6731
7593
  ladder.push(...gates.results);
6732
- if (gates.stop || !gates.category) {
6733
- return stopAt(ctx, ticketId, gates.stop ?? unresolvedCategory(), ladder);
7594
+ if (gates.stop) return stopAt(ctx, ticketId, gates.stop, ladder);
7595
+ const endSettings = readConversationEnd(settings);
7596
+ const end = endConfigOf(endSettings);
7597
+ if (!end) {
7598
+ ladder.push(conversationEndDisabled());
7599
+ } else if (stopOptOut(conversation).length > 0) {
7600
+ ladder.push(conversationEndSkippedForOptOut());
7601
+ } else {
7602
+ const { llm, prompt } = buildTicketPorts(ctx, {
7603
+ sessionId: ticketId,
7604
+ tags: [`app:${config.slug}`],
7605
+ metadata: { ticket_id: ticketId, origin: "followup" }
7606
+ });
7607
+ const judgement = await judgeConversationEnd(
7608
+ {
7609
+ llm,
7610
+ prompt,
7611
+ ...conversationEndJudgeConfig(settings, endSettings)
7612
+ },
7613
+ conversation.messages
7614
+ );
7615
+ if (judgement.finished) {
7616
+ return endConversation(ctx, run, ladder, {
7617
+ ticketId,
7618
+ conversation,
7619
+ settings,
7620
+ openResponse,
7621
+ generateOnly,
7622
+ end,
7623
+ judgement,
7624
+ channel: body.channel,
7625
+ category: bestMatchingCategory(categories, tags)
7626
+ });
7627
+ }
7628
+ ladder.push(conversationEndJudged(judgement));
7629
+ }
7630
+ await clearConversationEndTag(ctx, ticketId, raw, endSettings.tag, generateOnly || settings.dryRun === true);
7631
+ const { result: categoryResult, category } = evaluateCategoryGate({ categories, tags, ignoreCategoryOptIn: generateOnly });
7632
+ ladder.push(categoryResult);
7633
+ if (!category) {
7634
+ return stopAt(ctx, ticketId, categoryResult.status === "stopped" ? categoryResult : unresolvedCategory(), ladder);
6734
7635
  }
6735
- const category = gates.category;
6736
7636
  const preemption = openResponse ? generateOnly ? stopped("G9", "Une r\xE9ponse est d\xE9j\xE0 ouverte sur ce ticket : l'essai ne la remplace pas, contrairement \xE0 un passage r\xE9el.") : await preemptOpenResponse(ctx, ticketId, openResponse) : passed("G9", "Aucune r\xE9ponse ouverte sur ce ticket.");
6737
7637
  if (preemption.status === "stopped") {
6738
7638
  ladder.push(preemption);
@@ -6744,7 +7644,16 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
6744
7644
  metadata: { ticketId, categoryTag: category.tagName, channel: body.channel, generateOnly }
6745
7645
  })).id;
6746
7646
  const ticketUrl = ticketUrlFor(await resolveTicketUrlBase(ctx), ticketId);
6747
- const created = await openFollowupResponse(ctx, { ticketId, category, conversation, settings, runId: run.id, ticketUrl, generateOnly });
7647
+ const created = await openFollowupResponse(ctx, {
7648
+ ticketId,
7649
+ category,
7650
+ conversation,
7651
+ settings,
7652
+ runId: run.id,
7653
+ ticketUrl,
7654
+ generateOnly,
7655
+ conversationEnd: null
7656
+ });
6748
7657
  if (!created) {
6749
7658
  const lost = stopped(
6750
7659
  "G9",
@@ -6771,6 +7680,60 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
6771
7680
  responseId: created.id
6772
7681
  };
6773
7682
  }
7683
+ async function endConversation(ctx, run, ladder, input) {
7684
+ const { ticketId, settings, openResponse, generateOnly, end, judgement, category } = input;
7685
+ const simulated = generateOnly || settings.dryRun === true;
7686
+ let draftNote = "";
7687
+ if (openResponse && generateOnly) {
7688
+ draftNote = " ; une r\xE9ponse ouverte serait annul\xE9e";
7689
+ } else if (openResponse) {
7690
+ const cancel = await preemptOpenResponse(ctx, ticketId, openResponse, { waitForSend: false });
7691
+ if (cancel.status === "stopped") {
7692
+ const blocked = conversationEndBlocked(cancel.detail);
7693
+ ladder.push(blocked);
7694
+ return stopAt(ctx, ticketId, blocked, ladder);
7695
+ }
7696
+ draftNote = ` ; ${cancel.detail}`;
7697
+ }
7698
+ const action = describeEndAction(end.action, end.tag, simulated);
7699
+ ladder.push(conversationEndJudged(judgement, `${action}${draftNote}`));
7700
+ run.id ??= (await ctx.api.runs.start({
7701
+ kind: FOLLOWUP_RUN_KIND,
7702
+ message: `Message suivant \u2014 ticket ${ticketId}`,
7703
+ metadata: { ticketId, categoryTag: category?.tagName ?? null, channel: input.channel, generateOnly }
7704
+ })).id;
7705
+ const ticketUrl = ticketUrlFor(await resolveTicketUrlBase(ctx), ticketId);
7706
+ const created = await openFollowupResponse(ctx, {
7707
+ ticketId,
7708
+ category,
7709
+ conversation: input.conversation,
7710
+ settings,
7711
+ runId: run.id,
7712
+ ticketUrl,
7713
+ generateOnly,
7714
+ conversationEnd: { reason: judgement.reason, action }
7715
+ });
7716
+ if (!created) {
7717
+ const lost = stopped("G9", "Une autre ex\xE9cution a ouvert la r\xE9ponse en premier.");
7718
+ ladder.push(lost);
7719
+ return stopAt(ctx, ticketId, lost, ladder);
7720
+ }
7721
+ if (!generateOnly) {
7722
+ await finishConversationEnd(ctx, { responseId: created.id, ticketId, end, simulated });
7723
+ }
7724
+ return {
7725
+ ticketId,
7726
+ ticketUrl,
7727
+ stoppedAt: "FC",
7728
+ reason: `conversation finie \u2014 ${action}`,
7729
+ gates: completeFollowupLadder(ladder),
7730
+ categoryId: category?.id ?? null,
7731
+ categoryName: category?.name ?? null,
7732
+ agentId: null,
7733
+ outcome: "no_reply_needed",
7734
+ responseId: created.id
7735
+ };
7736
+ }
6774
7737
  async function readFollowupAnchor(ctx, ticketId) {
6775
7738
  const page = await ctx.api.list("generated-response", { filter: { ticketId }, limit: ANCHOR_LOOKUP_LIMIT });
6776
7739
  let anchor = null;
@@ -6792,16 +7755,19 @@ async function readFollowupAnchor(ctx, ticketId) {
6792
7755
  var SEND_SETTLE_POLL_MS = 2e3;
6793
7756
  var SEND_SETTLE_ATTEMPTS = 4;
6794
7757
  var PREEMPT_ATTEMPTS = 3;
6795
- async function preemptOpenResponse(ctx, ticketId, open) {
7758
+ async function preemptOpenResponse(ctx, ticketId, open, options = {}) {
6796
7759
  let status = open.status;
6797
7760
  for (let attempt = 1; attempt <= PREEMPT_ATTEMPTS; attempt += 1) {
6798
7761
  if (status === null) {
6799
7762
  return stopped("G9", "Une r\xE9ponse ouverte porte un statut illisible : elle doit \xEAtre d\xE9bloqu\xE9e \xE0 la main.");
6800
7763
  }
6801
7764
  if (isTerminalStatus(status)) {
7765
+ if (options.waitForSend === false && status === "sent")
7766
+ return stopped("G9", "la r\xE9ponse ouverte vient d'\xEAtre envoy\xE9e");
6802
7767
  return passed("G9", "La r\xE9ponse ouverte s'est termin\xE9e d'elle-m\xEAme : le ticket est libre.");
6803
7768
  }
6804
7769
  if (status === "sending") {
7770
+ if (options.waitForSend === false) return stopped("G9", "une r\xE9ponse est en cours d'envoi et ne peut pas \xEAtre annul\xE9e");
6805
7771
  status = await awaitSettledSend(ctx, open.id);
6806
7772
  if (status === "sending") {
6807
7773
  ctx.logger.warn(
@@ -6858,8 +7824,26 @@ function ticketTagNames(raw) {
6858
7824
  }
6859
7825
  return names;
6860
7826
  }
7827
+ function ticketTagIds(raw, name) {
7828
+ if (!Array.isArray(raw.tags) || name === "") return [];
7829
+ return raw.tags.flatMap((entry) => {
7830
+ if (typeof entry !== "object" || entry === null) return [];
7831
+ const { id, name: tagName } = entry;
7832
+ return tagName === name && typeof id === "number" ? [id] : [];
7833
+ });
7834
+ }
7835
+ async function clearConversationEndTag(ctx, ticketId, raw, tag, simulated) {
7836
+ const ids = ticketTagIds(raw, tag);
7837
+ if (ids.length === 0) return;
7838
+ if (simulated) {
7839
+ ctx.logger.info(`gorgias-webhook: would remove \xAB ${tag} \xBB from ticket ${ticketId} (trial, no Gorgias effect)`);
7840
+ return;
7841
+ }
7842
+ await ctx.api.integrations.run("gorgias", "removeTags", { ticketId, ids });
7843
+ ctx.logger.info(`gorgias-webhook: removed \xAB ${tag} \xBB from ticket ${ticketId} \u2014 the customer wrote again`);
7844
+ }
6861
7845
  async function openFollowupResponse(ctx, input) {
6862
- const { ticketId, category, conversation, settings, runId } = input;
7846
+ const { ticketId, category, conversation, settings, runId, conversationEnd } = input;
6863
7847
  const decision = await ctx.api.create("triage-decision", {
6864
7848
  ticketId,
6865
7849
  // Resolved by the caller AFTER every gate (`ticket-url.ts`), so a
@@ -6868,8 +7852,8 @@ async function openFollowupResponse(ctx, input) {
6868
7852
  // degrades to `null` rather than failing the pass.
6869
7853
  ticketUrl: input.ticketUrl,
6870
7854
  decidedAt: /* @__PURE__ */ new Date(),
6871
- categoryId: category.id,
6872
- tag: category.tagName,
7855
+ categoryId: category?.id ?? null,
7856
+ tag: category?.tagName ?? null,
6873
7857
  // §7.2 — NULL, and it is the honest value: no classifier ran on this pass
6874
7858
  // (D3 — the category is inherited from the tag the first pass applied), so
6875
7859
  // there is no confidence to state. The column was widened to allow it
@@ -6881,26 +7865,32 @@ async function openFollowupResponse(ctx, input) {
6881
7865
  // that does not exist — see `applyFollowupSendPolicy` in
6882
7866
  // `process-response.ts` for the decision and what it replaces.
6883
7867
  confidence: null,
6884
- reasoning: `Message suivant \u2014 cat\xE9gorie r\xE9solue par le tag ${category.tagName}`,
6885
- // The customer has just written, so the thread is by definition not over;
6886
- // and the escalation decision belongs to the first pass, which this one
6887
- // deliberately does not replay (D5).
6888
- conversationOver: false,
7868
+ reasoning: conversationEnd ? `Message suivant \u2014 conversation finie (${conversationEnd.action}) : ${conversationEnd.reason}`.slice(0, REASONING_MAX_LEN) : `Message suivant \u2014 cat\xE9gorie r\xE9solue par le tag ${category?.tagName}`,
7869
+ // spec-fin-de-conversation-v1 D16 — the end step's verdict; the timeline's
7870
+ // « Conversation close » badge and the stats read it. The escalation
7871
+ // decision belongs to the first pass, which this one deliberately does not
7872
+ // replay (D5).
7873
+ conversationOver: conversationEnd !== null,
6889
7874
  escalated: false,
6890
7875
  status: "ok",
6891
7876
  runId,
6892
7877
  subjectRenamed: false,
6893
7878
  origin: "followup"
6894
7879
  });
6895
- const agent = await resolveDraftAgent(ctx.api, category.agentId);
7880
+ const measured = !input.generateOnly && settings.dryRun !== true && conversationEnd === null;
7881
+ const replyTimingId = measured ? await openReplyTiming(ctx, { ticketId, conversation, categoryId: category?.id ?? null, origin: "followup" }) : null;
7882
+ const agent = conversationEnd ? null : await resolveDraftAgent(ctx.api, category?.agentId ?? null);
7883
+ const status = conversationEnd && input.generateOnly ? "test_draft" : "pending";
6896
7884
  const generatedAt = /* @__PURE__ */ new Date();
7885
+ let created;
6897
7886
  try {
6898
- return await ctx.api.create("generated-response", {
7887
+ created = await ctx.api.create("generated-response", {
6899
7888
  ticketId,
6900
- openTicketKey: openTicketKeyFor("pending", ticketId),
6901
- status: "pending",
7889
+ openTicketKey: openTicketKeyFor(status, ticketId),
7890
+ status,
6902
7891
  triageDecisionId: decision.id,
6903
- categoryId: category.id,
7892
+ categoryId: category?.id ?? null,
7893
+ ...conversationEnd ? { outcome: "no_reply_needed" } : {},
6904
7894
  agentId: agent?.id ?? null,
6905
7895
  channel: conversation.sourceChannel === "whatsapp" ? "whatsapp" : "email",
6906
7896
  sourceChannel: conversation.sourceChannel ?? null,
@@ -6928,6 +7918,8 @@ async function openFollowupResponse(ctx, input) {
6928
7918
  if (err instanceof appKit.AppApiError && err.status === 409) return null;
6929
7919
  throw err;
6930
7920
  }
7921
+ if (replyTimingId) await linkReplyTimingToDraft(ctx, replyTimingId, { id: created.id, categoryId: category?.id ?? null });
7922
+ return created;
6931
7923
  }
6932
7924
  function unresolvedCategory() {
6933
7925
  return stopped("G7", "Aucune cat\xE9gorie r\xE9solue.");
@@ -7005,9 +7997,17 @@ async function diagnose(ctx, ticketId) {
7005
7997
  const ticket = await ctx.api.integrations.run("gorgias", "getTicketWithContext", { ticketId });
7006
7998
  const raw = ticket?.ticket ?? {};
7007
7999
  const conversation = toConversation(ref, raw, ticket?.context ?? { messages: [], customerContext: null });
7008
- const trace = evaluateTicketGates({ settings, tags: ticketTagNames(raw), categories, conversation, anchor });
8000
+ const tags = ticketTagNames(raw);
8001
+ const trace = evaluateTicketGates({ settings, tags, conversation, anchor });
7009
8002
  gates.push(...trace.results);
7010
- if (!trace.stop) gates.push(predictPreemption(openResponse));
8003
+ if (trace.stop) return finish3(gates, ticketId);
8004
+ const end = readConversationEnd(settings);
8005
+ if (end.action === "disabled") gates.push(conversationEndDisabled());
8006
+ else if (stopOptOut(conversation).length > 0) gates.push(conversationEndSkippedForOptOut());
8007
+ else gates.push(conversationEndPredicted(end.prompt?.name ?? ""));
8008
+ const { result: categoryResult } = evaluateCategoryGate({ categories, tags });
8009
+ gates.push(categoryResult);
8010
+ if (categoryResult.status !== "stopped") gates.push(predictPreemption(openResponse));
7011
8011
  return finish3(gates, ticketId);
7012
8012
  }
7013
8013
  function predictPreemption(openResponse) {
@@ -7144,215 +8144,6 @@ function lengthInDays(range) {
7144
8144
  return (dayToMs(range.to) - dayToMs(range.from)) / MS_PER_DAY + 1;
7145
8145
  }
7146
8146
 
7147
- // src/domain/dashboard-stats.ts
7148
- function sumCounts(rows, countField = "count") {
7149
- return rows.reduce((sum, row) => sum + (Number(row[countField]) || 0), 0);
7150
- }
7151
- function bucketDay(row) {
7152
- return String(row["bucket"]).slice(0, 10);
7153
- }
7154
- var EMPTY_TOTALS = {
7155
- auto: 0,
7156
- human: 0,
7157
- inProgress: 0,
7158
- noReplyNeeded: 0
7159
- };
7160
- function countFailed(rows) {
7161
- return sumCounts(rows.filter((row) => row["status"] === "failed"));
7162
- }
7163
- var HUMAN_OUTCOMES = /* @__PURE__ */ new Set(["needs_human", "guardrail_hold", "escalated", "awaiting_approval"]);
7164
- function isUnautomatedTriage(decision) {
7165
- return decision.escalated === "true" || decision.escalated === true || decision.status === "error";
7166
- }
7167
- function countOf(row) {
7168
- return Number(row["count"]) || 0;
7169
- }
7170
- function outcomeOf(row) {
7171
- const status = row["status"];
7172
- const autoSendDecision = row["autoSendDecision"];
7173
- if (status === "test_draft" || status === "superseded") return null;
7174
- if (status === "sent") return "auto";
7175
- if (status === "no_reply_needed") return "noReplyNeeded";
7176
- if (status === "failed") return "human";
7177
- if (status === "invalidated" || status === "expired") return "human";
7178
- const outcome2 = row["outcome"];
7179
- if (typeof outcome2 === "string" && HUMAN_OUTCOMES.has(outcome2)) return "human";
7180
- if (outcome2 === "no_reply_needed") return "noReplyNeeded";
7181
- if (outcome2 === "triaged_only") return null;
7182
- return autoSendDecision === "hold" ? "human" : "inProgress";
7183
- }
7184
- function foldOutcomes(rows, triageRows = []) {
7185
- const totals = { ...EMPTY_TOTALS };
7186
- for (const row of rows) {
7187
- const outcome2 = outcomeOf(row);
7188
- if (outcome2 !== null) totals[outcome2] += countOf(row);
7189
- }
7190
- for (const row of triageRows) {
7191
- if (isUnautomatedTriage(row)) totals.human += countOf(row);
7192
- }
7193
- return totals;
7194
- }
7195
- function settledCount(totals) {
7196
- return totals.auto + totals.human;
7197
- }
7198
- function autonomyRate(totals) {
7199
- const settled = settledCount(totals);
7200
- return settled > 0 ? totals.auto / settled : Number.NaN;
7201
- }
7202
- function foldDailyOutcomes(rows, triageRows = []) {
7203
- const byDay = /* @__PURE__ */ new Map();
7204
- const totalsFor = (day) => {
7205
- const existing = byDay.get(day);
7206
- if (existing !== void 0) return existing;
7207
- const fresh = { ...EMPTY_TOTALS };
7208
- byDay.set(day, fresh);
7209
- return fresh;
7210
- };
7211
- for (const row of rows) {
7212
- const outcome2 = outcomeOf(row);
7213
- if (outcome2 === null) continue;
7214
- totalsFor(bucketDay(row))[outcome2] += countOf(row);
7215
- }
7216
- for (const row of triageRows) {
7217
- if (isUnautomatedTriage(row)) totalsFor(bucketDay(row)).human += countOf(row);
7218
- }
7219
- return [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, totals]) => ({
7220
- day,
7221
- auto: totals.auto,
7222
- human: totals.human,
7223
- rate: settledCount(totals) > 0 ? autonomyRate(totals) : null
7224
- }));
7225
- }
7226
- function fillMissingDays(series, fromIso, toIso) {
7227
- const from = Date.parse(fromIso.slice(0, 10));
7228
- const to = Date.parse(toIso.slice(0, 10));
7229
- if (Number.isNaN(from) || Number.isNaN(to) || to < from) return series;
7230
- const measured = new Map(series.map((point) => [point.day, point]));
7231
- const filled = [];
7232
- for (let t = from; t <= to; t += 864e5) {
7233
- const day = new Date(t).toISOString().slice(0, 10);
7234
- filled.push(measured.get(day) ?? { day, auto: 0, human: 0, rate: null });
7235
- }
7236
- return filled;
7237
- }
7238
- function ratePoints(rate, compareRate) {
7239
- return Number.isNaN(rate) || Number.isNaN(compareRate) ? null : (rate - compareRate) * 100;
7240
- }
7241
- var SIGNAL_MIN_VOLUME = 20;
7242
- var SIGNAL_MIN_POINTS = 3;
7243
- function dashboardSignals(totals, compare, failed2 = 0) {
7244
- const signals = [];
7245
- const settled = settledCount(totals);
7246
- const rate = autonomyRate(totals);
7247
- if (compare !== null && settled >= SIGNAL_MIN_VOLUME && settledCount(compare) >= SIGNAL_MIN_VOLUME) {
7248
- const points = ratePoints(rate, autonomyRate(compare));
7249
- if (points !== null && Math.abs(points) >= SIGNAL_MIN_POINTS) {
7250
- const move = points < 0 ? "recule" : "progresse";
7251
- signals.push({
7252
- level: points < 0 ? "creuser" : "info",
7253
- text: `Le taux d\u2019autonomie ${move} de ${Math.abs(Math.round(points))} points par rapport \xE0 la p\xE9riode pr\xE9c\xE9dente.`
7254
- });
7255
- }
7256
- }
7257
- if (failed2 > 0) {
7258
- signals.push({
7259
- level: "creuser",
7260
- text: `${failed2} g\xE9n\xE9ration${failed2 > 1 ? "s ont" : " a"} \xE9chou\xE9 techniquement : ${failed2 > 1 ? "ces demandes n\u2019ont" : "cette demande n\u2019a"} jamais eu de brouillon et ${failed2 > 1 ? "sont retomb\xE9es" : "est retomb\xE9e"} sur un humain.`
7261
- });
7262
- }
7263
- if (totals.inProgress > 0) {
7264
- signals.push({
7265
- level: "info",
7266
- text: `${totals.inProgress} r\xE9ponse${totals.inProgress > 1 ? "s sont" : " est"} encore en cours : ${totals.inProgress > 1 ? "elles ne comptent" : "elle ne compte"} dans aucun des deux camps.`
7267
- });
7268
- }
7269
- if (totals.noReplyNeeded > 0) {
7270
- signals.push({
7271
- level: "info",
7272
- text: `${totals.noReplyNeeded} demande${totals.noReplyNeeded > 1 ? "s" : ""} ne n\xE9cessitai${totals.noReplyNeeded > 1 ? "ent" : "t"} aucune r\xE9ponse : hors du taux d\u2019autonomie.`
7273
- });
7274
- }
7275
- if (compare !== null && settled > 0 && settledCount(compare) < SIGNAL_MIN_VOLUME) {
7276
- signals.push({
7277
- level: "info",
7278
- text: "La p\xE9riode pr\xE9c\xE9dente compte trop peu de demandes r\xE9gl\xE9es pour que la comparaison veuille dire quelque chose."
7279
- });
7280
- }
7281
- return signals;
7282
- }
7283
- function foldHumanReasons(rows, triageRows = []) {
7284
- const reasons = { blocked: 0, invalidated: 0, expired: 0, escalatedNoDraft: 0, failed: 0 };
7285
- for (const row of rows) {
7286
- if (outcomeOf(row) !== "human") continue;
7287
- const count = countOf(row);
7288
- if (row["status"] === "invalidated") reasons.invalidated += count;
7289
- else if (row["status"] === "expired") reasons.expired += count;
7290
- else if (row["status"] === "failed") reasons.failed += count;
7291
- else reasons.blocked += count;
7292
- }
7293
- for (const row of triageRows) {
7294
- if (isUnautomatedTriage(row)) reasons.escalatedNoDraft += countOf(row);
7295
- }
7296
- return reasons;
7297
- }
7298
- var CATEGORY_TOP_N = 10;
7299
- function foldCategoryOutcomes(triageRows, responseRows, categoryNames, topN = CATEGORY_TOP_N) {
7300
- const byId = /* @__PURE__ */ new Map();
7301
- const barFor = (id) => {
7302
- const name = typeof id === "string" ? categoryNames.get(id) : void 0;
7303
- if (name === void 0) return null;
7304
- const existing = byId.get(id);
7305
- if (existing !== void 0) return existing;
7306
- const bar = {
7307
- label: name,
7308
- total: 0,
7309
- auto: 0,
7310
- human: 0,
7311
- noReply: 0,
7312
- undrafted: 0
7313
- };
7314
- byId.set(id, bar);
7315
- return bar;
7316
- };
7317
- for (const row of triageRows) {
7318
- const bar = barFor(row["categoryId"]);
7319
- if (bar === null) continue;
7320
- const count = countOf(row);
7321
- bar.total += count;
7322
- if (isUnautomatedTriage(row)) bar.human += count;
7323
- }
7324
- for (const row of responseRows) {
7325
- const bar = barFor(row["categoryId"]);
7326
- if (bar === null) continue;
7327
- const outcome2 = outcomeOf(row);
7328
- const count = countOf(row);
7329
- if (outcome2 === "auto") bar.auto += count;
7330
- else if (outcome2 === "human") bar.human += count;
7331
- else if (outcome2 === "noReplyNeeded") bar.noReply += count;
7332
- }
7333
- const bars = [...byId.values()].map((bar) => {
7334
- const accounted = bar.auto + bar.human + bar.noReply;
7335
- return {
7336
- ...bar,
7337
- total: Math.max(bar.total, accounted),
7338
- undrafted: Math.max(0, bar.total - accounted)
7339
- };
7340
- }).filter((bar) => bar.total > 0).sort((a, b) => b.total - a.total);
7341
- if (bars.length <= topN + 1) return bars;
7342
- const tail = bars.slice(topN).reduce(
7343
- (sum, bar) => ({
7344
- label: "Autres",
7345
- total: sum.total + bar.total,
7346
- auto: sum.auto + bar.auto,
7347
- human: sum.human + bar.human,
7348
- noReply: sum.noReply + bar.noReply,
7349
- undrafted: sum.undrafted + bar.undrafted
7350
- }),
7351
- { label: "Autres", total: 0, auto: 0, human: 0, noReply: 0, undrafted: 0 }
7352
- );
7353
- return [...bars.slice(0, topN), tail];
7354
- }
7355
-
7356
8147
  // src/domain/ticket-outcome.ts
7357
8148
  var REPORTED_OUTCOMES = [...OUTCOMES, "invalidated", "expired"];
7358
8149
  function emptyOutcomeCounts() {
@@ -7420,7 +8211,7 @@ var STAT_DEFINITIONS = {
7420
8211
  awaiting_approval: "An action is waiting for a human\u2019s approval.",
7421
8212
  escalated: "Request escalated at triage, or triage error: no draft written.",
7422
8213
  triaged_only: "Triaged, with no drafting step to run.",
7423
- no_reply_needed: "Conversation already closed: no reply needed, outside the autonomy rate.",
8214
+ no_reply_needed: "The end-of-conversation step judged the thread finished: no reply needed, outside the autonomy rate.",
7424
8215
  failed: "Generation failed technically; the ticket went up to a human.",
7425
8216
  invalidated: "Draft invalidated (an agent replied before it was served): taken over by a human, whatever the outcome decided at generation.",
7426
8217
  expired: "Draft expired (the serving window closed without it being used): taken over by a human, whatever the outcome decided at generation."
@@ -7861,6 +8652,8 @@ function deliveryReason(facts) {
7861
8652
  case "test_draft":
7862
8653
  return { code: "test_draft" };
7863
8654
  default:
8655
+ if (job.status === "no_reply_needed" && job.outcome === "no_reply_needed")
8656
+ return { code: "no_reply_needed" };
7864
8657
  return { code: "unexpected_status", status: job.status };
7865
8658
  }
7866
8659
  }
@@ -7977,7 +8770,8 @@ function toDeliveryPolicy(raw) {
7977
8770
  whatsappMode: typeof settings.whatsappMode === "string" ? settings.whatsappMode : null,
7978
8771
  autoSendChannels: Array.isArray(settings.autoSendChannels) ? settings.autoSendChannels : [...DEFAULT_AUTO_SEND_CHANNELS],
7979
8772
  dryRun: settings.dryRun === true,
7980
- audit: toAuditTags(settings)
8773
+ audit: toAuditTags(settings),
8774
+ conversationEnd: toConversationEnd(settings)
7981
8775
  };
7982
8776
  }
7983
8777
 
@@ -8236,6 +9030,7 @@ function promptNamesChosenIn(settings) {
8236
9030
  const stepPrompts = nodes.map((node) => node?.prompt?.name);
8237
9031
  return [
8238
9032
  ...stepPrompts,
9033
+ readConversationEnd(settings).prompt?.name,
8239
9034
  settings.channelPromptEmail || DEFAULT_CHANNEL_PROMPT_EMAIL,
8240
9035
  settings.channelPromptWhatsapp || DEFAULT_CHANNEL_PROMPT_WHATSAPP
8241
9036
  ];
@@ -8385,6 +9180,12 @@ var FUNCTION_ASSEMBLY = [
8385
9180
  build: buildTestGorgiasWebhookFunctionDef,
8386
9181
  createHandler: createTestGorgiasWebhookHandler
8387
9182
  },
9183
+ // spec-delais-de-reponse-v1 §6 — derived identifier, like the MCP tools below.
9184
+ {
9185
+ key: "backfill-reply-timing",
9186
+ build: buildBackfillReplyTimingFunctionDef,
9187
+ createHandler: () => createBackfillReplyTimingHandler()
9188
+ },
8388
9189
  // The read-only MCP tools (spec §5.3). Their identifiers are optional —
8389
9190
  // `mcpToolIdentifierFor` derives them — so they sit outside
8390
9191
  // FUNCTION_IDENTIFIER_KEYS and this assembly covers that list PLUS the MCP tools below.
@@ -8545,10 +9346,12 @@ exports.AGENT_TOOLS = AGENT_TOOLS;
8545
9346
  exports.ATTACHMENT_MARKER_ONLY = ATTACHMENT_MARKER_ONLY;
8546
9347
  exports.CANDIDATE_MIN_LENGTH = CANDIDATE_MIN_LENGTH;
8547
9348
  exports.COLLISION_GUARDRAILS = COLLISION_GUARDRAILS;
9349
+ exports.CONVERSATION_END_ACTIONS = CONVERSATION_END_ACTIONS;
8548
9350
  exports.DECISION_ORIGINS = DECISION_ORIGINS;
8549
9351
  exports.DEFAULT_AUTO_SEND_CHANNELS = DEFAULT_AUTO_SEND_CHANNELS;
8550
9352
  exports.DEFAULT_CHANNEL_PROMPT_EMAIL = DEFAULT_CHANNEL_PROMPT_EMAIL;
8551
9353
  exports.DEFAULT_CHANNEL_PROMPT_WHATSAPP = DEFAULT_CHANNEL_PROMPT_WHATSAPP;
9354
+ exports.DEFAULT_CONVERSATION_END_TAG = DEFAULT_CONVERSATION_END_TAG;
8552
9355
  exports.DEFAULT_DECISION_ORIGIN = DEFAULT_DECISION_ORIGIN;
8553
9356
  exports.DEFAULT_LLM_PROVIDER = DEFAULT_LLM_PROVIDER;
8554
9357
  exports.DEFAULT_PROFILE_KEY = DEFAULT_PROFILE_KEY;
@@ -8576,6 +9379,7 @@ exports.buildCategoryRecord = buildCategoryRecord;
8576
9379
  exports.buildDiffAnalysisRecord = buildDiffAnalysisRecord;
8577
9380
  exports.buildEvaluationRecord = buildEvaluationRecord;
8578
9381
  exports.buildGeneratedResponseRecord = buildGeneratedResponseRecord;
9382
+ exports.buildReplyTimingRecord = buildReplyTimingRecord;
8579
9383
  exports.buildResponseComparisonRecord = buildResponseComparisonRecord;
8580
9384
  exports.buildSupportKitRecords = buildSupportKitRecords;
8581
9385
  exports.buildSupportPipeline = buildSupportPipeline;
@@ -8583,6 +9387,7 @@ exports.buildTriageDecisionRecord = buildTriageDecisionRecord;
8583
9387
  exports.canTransition = canTransition;
8584
9388
  exports.categoryGroupRecord = categoryGroupRecord;
8585
9389
  exports.channelPreGates = channelPreGates;
9390
+ exports.conversationEndEffects = conversationEndEffects;
8586
9391
  exports.createBudget = createBudget;
8587
9392
  exports.createPromptResolver = createPromptResolver;
8588
9393
  exports.customerChannelAddress = customerChannelAddress;
@@ -8616,6 +9421,7 @@ exports.pipelineStateRecord = pipelineStateRecord;
8616
9421
  exports.promptCacheRecord = promptCacheRecord;
8617
9422
  exports.publicationMode = publicationMode;
8618
9423
  exports.rawTicketFactsAt = rawTicketFactsAt;
9424
+ exports.readConversationEnd = readConversationEnd;
8619
9425
  exports.reclaimStalledSend = reclaimStalledSend;
8620
9426
  exports.reconstructGuardrailHits = reconstructGuardrailHits;
8621
9427
  exports.requiresFollowup = requiresFollowup;
@@ -8626,6 +9432,7 @@ exports.settingsToProfile = settingsToProfile;
8626
9432
  exports.settingsWarnings = settingsWarnings;
8627
9433
  exports.stopOptOut = stopOptOut;
8628
9434
  exports.targetRefFor = targetRefFor;
9435
+ exports.toConversationEnd = toConversationEnd;
8629
9436
  exports.toDecisionOrigin = toDecisionOrigin;
8630
9437
  exports.validateSettings = validateSettings;
8631
9438
  exports.verifyReply = verifyReply;