@apotech-os/support-kit 10.1.0 → 10.3.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) => {
@@ -665,9 +684,8 @@ ${last}`);
665
684
  try {
666
685
  const result = await deps.ports.llm.complete({
667
686
  label: TRIAGE_LABEL,
668
- // The resolved Langfuse prompt's own model config WINS over the
669
- // profile's fallback (I16) — see `PromptPort.resolve`'s doc.
670
- model: resolvedPrompt.config?.model ?? node.model,
687
+ // The model stored in the OS wins; the prompt's Langfuse config is ignored.
688
+ model: node.model,
671
689
  reasoning: node.reasoning,
672
690
  messages: [
673
691
  { role: "system", content: resolvedPrompt.text },
@@ -688,8 +706,7 @@ ${last}`);
688
706
  category: parsed.tag,
689
707
  confidence: parsed.confidence,
690
708
  reasoning: String(parsed.reasoning ?? "").slice(0, REASONING_MAX_LEN),
691
- isFallback: false,
692
- conversationOver: parsed.conversationOver === true
709
+ isFallback: false
693
710
  }
694
711
  };
695
712
  } catch (err) {
@@ -725,7 +742,7 @@ ${conversation.customer.orderContext}`);
725
742
  ${message}`);
726
743
  const result = await deps.ports.llm.complete({
727
744
  label: ESCALATION_LABEL,
728
- model: resolvedPrompt.config?.model ?? node.model,
745
+ model: node.model,
729
746
  reasoning: node.reasoning,
730
747
  messages: [
731
748
  { role: "system", content: resolvedPrompt.text },
@@ -894,7 +911,7 @@ async function runToolCall(profile, call, ctx) {
894
911
  // src/graph/draft.ts
895
912
  var MAX_LOOP_ROUNDS = 25;
896
913
  async function draftWithTools(params) {
897
- const { profile, llm, budget, toolContext, messages, label, model, promptRef } = params;
914
+ const { profile, llm, budget, toolContext, messages, label, promptRef } = params;
898
915
  const node = profile.nodes.draft;
899
916
  if (!node) throw new Error("draftWithTools requires profile.nodes.draft to be configured.");
900
917
  const conversation = [...messages];
@@ -904,7 +921,7 @@ async function draftWithTools(params) {
904
921
  const tools = offerTools ? toolsOrUndefined(buildToolSpecs(profile)) : [];
905
922
  const result = await llm.complete({
906
923
  label,
907
- model: model ?? node.model,
924
+ model: node.model,
908
925
  reasoning: node.reasoning,
909
926
  messages: conversation,
910
927
  tools,
@@ -982,9 +999,6 @@ var draft = async (state, deps) => {
982
999
  toolContext: deps.toolContext,
983
1000
  messages,
984
1001
  label: LABEL,
985
- // The resolved Langfuse prompt's own model config WINS over the
986
- // profile's fallback (I16) — see `PromptPort.resolve`'s doc.
987
- model: resolvedPrompt.config?.model ?? node.model,
988
1002
  promptRef: { name: resolvedPrompt.name, version: resolvedPrompt.version, resolve: false }
989
1003
  });
990
1004
  return { draft: result };
@@ -1023,9 +1037,8 @@ var evaluate = async (state, deps) => {
1023
1037
  try {
1024
1038
  const result = await (deps.ports.evaluator ?? deps.ports.llm).complete({
1025
1039
  label: "evaluation",
1026
- // The resolved Langfuse prompt's own model config WINS over the
1027
- // profile's fallback (I16) — see `PromptPort.resolve`'s doc.
1028
- model: evaluatePrompt.config?.model ?? node.model,
1040
+ // The model stored in the OS wins; the prompt's Langfuse config is ignored.
1041
+ model: node.model,
1029
1042
  reasoning: node.reasoning,
1030
1043
  messages: buildMessages({
1031
1044
  conversation: state.conversation,
@@ -1276,9 +1289,6 @@ async function finish2(state, deps, outcome2) {
1276
1289
  await applyOutcomeTags(outcome2, final.verdict, { ports: deps.ports, ref: deps.ref, audit });
1277
1290
  return final;
1278
1291
  }
1279
- function isConversationOver(classification) {
1280
- return classification?.conversationOver === true;
1281
- }
1282
1292
  function isFallbackClassification(classification) {
1283
1293
  return classification?.isFallback === true;
1284
1294
  }
@@ -1301,7 +1311,6 @@ async function runTicket(deps, options = {}) {
1301
1311
  if (s.escalated) return finish2(s, deps, "escalated");
1302
1312
  const stopHits = s.conversation ? stopOptOut(s.conversation) : [];
1303
1313
  if (stopHits.length) return finish2(merge(s, { guardrailHits: stopHits }), deps, "guardrail_hold");
1304
- if (isConversationOver(s.classification)) return finish2(s, deps, "no_reply_needed");
1305
1314
  if (isFallbackClassification(s.classification)) return finish2(s, deps, "triaged_only");
1306
1315
  if (hasNoDraftNode(profile)) return finish2(s, deps, "triaged_only");
1307
1316
  if (s.conversation) {
@@ -1716,6 +1725,26 @@ var PROMPT_CACHE_FIELD_VERSION_UID = "87b77921-6261-4179-a9e6-823e8321ccfd";
1716
1725
  var PROMPT_CACHE_FIELD_LABEL_UID = "ce36ed5b-42e2-45bd-8915-3ef0317e6665";
1717
1726
  var PROMPT_CACHE_FIELD_CONFIG_UID = "306cdb0b-433b-44c8-8a5b-6b993d3f0da3";
1718
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";
1719
1748
 
1720
1749
  // src/records/target-ref.ts
1721
1750
  function targetRefFor(slug, objectKey) {
@@ -2675,172 +2704,588 @@ function buildDiffAnalysisRecord(slug) {
2675
2704
  ]
2676
2705
  };
2677
2706
  }
2678
- var pipelineStateRecord = {
2679
- universalIdentifier: PIPELINE_STATE_OBJECT_UID,
2680
- objectKey: "pipeline-state",
2681
- labelSingular: "Pipeline state",
2682
- labelPlural: "Pipeline state",
2683
- description: "Singleton run-cadence and view-claim state, readable by every installed app.",
2684
- fields: [
2685
- {
2686
- universalIdentifier: PIPELINE_STATE_FIELD_SINGLETON_KEY_UID,
2687
- name: "singletonKey",
2688
- type: appKit.FieldType.TEXT,
2689
- label: "Singleton key",
2690
- description: "Always the same constant value \u2014 the unique index below is what makes this record a true singleton, not just a convention.",
2691
- isNullable: false
2692
- },
2693
- {
2694
- universalIdentifier: PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID,
2695
- name: "sourceViewId",
2696
- type: appKit.FieldType.TEXT,
2697
- label: "Source view id",
2698
- description: "The claimed Gorgias view \u2014 supports the cross-app overlap warning (\xA74).",
2699
- isNullable: true
2700
- },
2701
- {
2702
- universalIdentifier: PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID,
2703
- name: "lastTriageAt",
2704
- type: appKit.FieldType.DATE_TIME,
2705
- label: "Last triage at",
2706
- description: "Gates triage-tick's cadence.",
2707
- isNullable: true
2708
- },
2709
- {
2710
- universalIdentifier: PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID,
2711
- name: "lastSweepAt",
2712
- type: appKit.FieldType.DATE_TIME,
2713
- label: "Last sweep at",
2714
- isNullable: true
2715
- }
2716
- ],
2717
- indexes: [{ universalIdentifier: PIPELINE_STATE_INDEX_SINGLETON_KEY_UID, fields: ["singletonKey"], isUnique: true }],
2718
- exposedToApps: ["*"]
2719
- };
2720
- var promptCacheRecord = {
2721
- universalIdentifier: PROMPT_CACHE_OBJECT_UID,
2722
- objectKey: "prompt-cache",
2723
- labelSingular: "Prompt cache entry",
2724
- labelPlural: "Prompt cache entries",
2725
- description: "Last-known-good snapshot of a Langfuse prompt, for the resolver fallback ladder.",
2726
- fields: [
2727
- {
2728
- universalIdentifier: PROMPT_CACHE_FIELD_PROMPT_KEY_UID,
2729
- name: "promptKey",
2730
- type: appKit.FieldType.TEXT,
2731
- label: "Prompt key",
2732
- description: "'name' or 'name::label'.",
2733
- isNullable: false
2734
- },
2735
- {
2736
- universalIdentifier: PROMPT_CACHE_FIELD_CONTENT_UID,
2737
- name: "content",
2738
- type: appKit.FieldType.TEXT,
2739
- label: "Content",
2740
- description: "Raw, uncompiled template.",
2741
- isNullable: false
2742
- },
2743
- {
2744
- universalIdentifier: PROMPT_CACHE_FIELD_VERSION_UID,
2745
- name: "version",
2746
- type: appKit.FieldType.NUMBER,
2747
- label: "Version",
2748
- isNullable: false
2749
- },
2750
- {
2751
- universalIdentifier: PROMPT_CACHE_FIELD_LABEL_UID,
2752
- name: "label",
2753
- type: appKit.FieldType.TEXT,
2754
- label: "Label",
2755
- isNullable: true
2756
- },
2757
- {
2758
- universalIdentifier: PROMPT_CACHE_FIELD_CONFIG_UID,
2759
- name: "config",
2760
- type: appKit.FieldType.JSON,
2761
- label: "Config",
2762
- description: "Model config snapshot, for I16. Not yet written or read \u2014 see module doc.",
2763
- isNullable: true
2764
- }
2765
- ],
2766
- 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
2767
2720
  };
2768
- var SUPPORT_KIT_UID_NAMESPACE = "2b6a9c0e-6c1e-4c1a-8b0e-2a2f4b8c9d3f";
2769
- function uuidToBytes(uuid) {
2770
- return Buffer.from(uuid.replace(/-/g, ""), "hex");
2721
+ function countFailed(rows) {
2722
+ return sumCounts(rows.filter((row) => row["status"] === "failed"));
2771
2723
  }
2772
- function bytesToUuid(bytes) {
2773
- const hex = bytes.toString("hex");
2774
- 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";
2775
2727
  }
2776
- function deriveUid(seed) {
2777
- const hash = node_crypto.createHash("sha1").update(uuidToBytes(SUPPORT_KIT_UID_NAMESPACE)).update(seed, "utf8").digest();
2778
- const bytes = hash.subarray(0, 16);
2779
- bytes[6] = bytes[6] & 15 | 80;
2780
- bytes[8] = bytes[8] & 63 | 128;
2781
- return bytesToUuid(bytes);
2728
+ function countOf(row) {
2729
+ return Number(row["count"]) || 0;
2782
2730
  }
2783
-
2784
- // src/records/scope-to-app.ts
2785
- function scopeRecordToApp(slug, record) {
2786
- return {
2787
- ...record,
2788
- universalIdentifier: deriveUid(`${slug}:${record.universalIdentifier}`),
2789
- fields: record.fields.map((field) => ({
2790
- ...field,
2791
- universalIdentifier: deriveUid(`${slug}:${field.universalIdentifier}`)
2792
- })),
2793
- indexes: record.indexes?.map((index) => ({
2794
- ...index,
2795
- universalIdentifier: deriveUid(`${slug}:${index.universalIdentifier}`)
2796
- }))
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;
2797
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
+ }));
2798
2786
  }
2799
-
2800
- // src/records/index.ts
2801
- function buildSupportKitRecords(slug) {
2802
- return [
2803
- buildCategoryRecord(slug),
2804
- categoryGroupRecord,
2805
- agentRecord,
2806
- buildTriageDecisionRecord(slug),
2807
- buildGeneratedResponseRecord(slug),
2808
- buildResponseComparisonRecord(slug),
2809
- buildEvaluationRecord(slug),
2810
- buildDiffAnalysisRecord(slug),
2811
- pipelineStateRecord,
2812
- promptCacheRecord
2813
- ].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;
2814
2798
  }
2815
-
2816
- // src/settings/fields.ts
2817
- var DEFAULT_STATS_TIMEZONE = "Europe/Paris";
2818
- var SUPPORT_KIT_SETTINGS_FIELDS = [
2819
- // Source
2820
- // NO `gorgiasConnectionId`: every Gorgias call in this kit is
2821
- // `ctx.api.integrations.run('gorgias', …)` with no `connectionId`, so the
2822
- // platform resolves the instance's default connection. A settings key here
2823
- // would be written by an operator and read by nobody — see the Source
2824
- // section of `ui/settings/settings-page.tsx`, which STATES the resolved
2825
- // connection instead of pretending to choose it.
2826
- {
2827
- key: "sourceViewId",
2828
- type: "string",
2829
- label: "Gorgias source view"
2830
- // No default — see module doc.
2831
- },
2832
- { key: "batchLimit", type: "number", label: "Batch limit", default: 30 },
2833
- { key: "triageEnabled", type: "boolean", label: "Triage enabled", default: false },
2834
- {
2835
- key: "triageIntervalMinutes",
2836
- type: "number",
2837
- label: "Triage interval (minutes)",
2838
- default: 15
2839
- },
2840
- { key: "dryRun", type: "boolean", label: "Dry run", default: false },
2841
- // Nodes
2842
- // `{triage, escalate, draft, evaluate, revise}`, `null` per key disabling
2843
- // that graph step (§3.6). NO default, same reasoning as `sourceViewId`:
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`:
2844
3289
  // the only shape that could be defaulted here ("every step null") is a
2845
3290
  // pipeline that triages nothing, and it would install itself silently.
2846
3291
  // `validateSettings` refuses to run until `nodes.triage` is configured.
@@ -2866,6 +3311,24 @@ var SUPPORT_KIT_SETTINGS_FIELDS = [
2866
3311
  // this?". No usable default for the same reason: a mark two apps have in
2867
3312
  // common marks nothing. `validateSettings` refuses to run until it is set.
2868
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" },
2869
3332
  // Sending
2870
3333
  { key: "autoSendEnabled", type: "boolean", label: "Auto-send enabled", default: false },
2871
3334
  { key: "senderEmail", type: "string", label: "Sender email", default: "" },
@@ -2963,8 +3426,35 @@ function validateSettings(settings) {
2963
3426
  message: "senderEmail is required when autoSendEnabled is on, unless whatsappMode is 'auto_reply'."
2964
3427
  });
2965
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
+ }
2966
3447
  return issues;
2967
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
+ }
2968
3458
  function isNonEmptyString(value) {
2969
3459
  return typeof value === "string" && value.length > 0;
2970
3460
  }
@@ -3142,6 +3632,9 @@ function identifierFor(config, key) {
3142
3632
  return id;
3143
3633
  }
3144
3634
  function mcpToolIdentifierFor(config, key) {
3635
+ return derivedIdentifierFor(config, key);
3636
+ }
3637
+ function derivedIdentifierFor(config, key) {
3145
3638
  return config.identifiers[key] ?? deriveUid(`${config.slug}:function:${key}`);
3146
3639
  }
3147
3640
 
@@ -3450,12 +3943,111 @@ function buildTicketPorts(ctx, trace) {
3450
3943
  clock: createRealClock()
3451
3944
  };
3452
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
+ }
3453
4046
 
3454
4047
  // src/functions/eligibility.ts
3455
4048
  function isEligibleForGeneratedResponse(profile, classification, escalated, category) {
3456
4049
  if (!category || !category.fastResponseEnabled || !category.agentId) return false;
3457
4050
  if (escalated) return false;
3458
- if (isConversationOver(classification)) return false;
3459
4051
  if (isFallbackClassification(classification)) return false;
3460
4052
  if (hasNoDraftNode(profile)) return false;
3461
4053
  return true;
@@ -3507,8 +4099,106 @@ async function upsertPipelineState(api, patch) {
3507
4099
  { uniqueBy: ["singletonKey"] }
3508
4100
  );
3509
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
3510
4200
  function buildSendSeam(params) {
3511
- const { api, clock, id, ticketId, fromStatus, extraClaimData } = params;
4201
+ const { api, clock, logger, id, ticketId, fromStatus, extraClaimData } = params;
3512
4202
  return {
3513
4203
  async claim(run) {
3514
4204
  assertTransition(fromStatus, "sending");
@@ -3532,6 +4222,7 @@ function buildSendSeam(params) {
3532
4222
  },
3533
4223
  async commit(messageId) {
3534
4224
  assertTransition("sending", "sent");
4225
+ const sentAt = clock.now();
3535
4226
  await api.update(
3536
4227
  "generated-response",
3537
4228
  id,
@@ -3542,12 +4233,13 @@ function buildSendSeam(params) {
3542
4233
  // send) — so stamping the outcome here covers both without either
3543
4234
  // needing to remember to.
3544
4235
  outcome: "sent",
3545
- sentAt: clock.now(),
4236
+ sentAt,
3546
4237
  sentMessageId: messageId,
3547
4238
  openTicketKey: openTicketKeyFor("sent", ticketId)
3548
4239
  },
3549
4240
  { ifMatch: { status: "sending" } }
3550
4241
  );
4242
+ await closeReplyTimingAsAi({ api, logger }, ticketId, sentAt, id);
3551
4243
  }
3552
4244
  };
3553
4245
  }
@@ -3843,8 +4535,7 @@ function classificationFromDecision(decision) {
3843
4535
  category: data.tag ?? "",
3844
4536
  confidence: data.confidence ?? "low",
3845
4537
  reasoning: data.reasoning ?? "",
3846
- isFallback: false,
3847
- conversationOver: data.conversationOver ?? false
4538
+ isFallback: false
3848
4539
  };
3849
4540
  }
3850
4541
  function attributionFields(attribution) {
@@ -3929,6 +4620,7 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
3929
4620
  const seam = buildSendSeam({
3930
4621
  api: ctx.api,
3931
4622
  clock,
4623
+ logger: ctx.logger,
3932
4624
  id: recordId,
3933
4625
  ticketId,
3934
4626
  fromStatus: "pending",
@@ -4017,7 +4709,6 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
4017
4709
  }
4018
4710
  case "escalated":
4019
4711
  case "triaged_only":
4020
- case "no_reply_needed":
4021
4712
  await finalizeNonSent(ctx, recordId, ticketId, testRun ? restingStatus : "no_reply_needed", draftExtra);
4022
4713
  return result.outcome;
4023
4714
  case "failed":
@@ -4028,22 +4719,6 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
4028
4719
  return null;
4029
4720
  }
4030
4721
  }
4031
- async function transitionGeneratedResponse(api, params) {
4032
- const { id, ticketId, from, to, extra } = params;
4033
- assertTransition(from, to);
4034
- try {
4035
- await api.update(
4036
- "generated-response",
4037
- id,
4038
- { status: to, openTicketKey: openTicketKeyFor(to, ticketId), ...extra ?? {} },
4039
- { ifMatch: { status: from } }
4040
- );
4041
- return true;
4042
- } catch (err) {
4043
- if (err instanceof appKit.AppApiError && err.status === 409) return false;
4044
- throw err;
4045
- }
4046
- }
4047
4722
 
4048
4723
  // src/functions/ticket-url.ts
4049
4724
  async function resolveTicketUrlBase(ctx) {
@@ -4092,7 +4767,7 @@ function recordTriageTraces(llm) {
4092
4767
  },
4093
4768
  fields() {
4094
4769
  const traceId = results.get(TRIAGE_LABEL)?.traceId;
4095
- 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));
4096
4771
  return {
4097
4772
  ...traceId ? { langfuseTraceId: traceId } : {},
4098
4773
  ...observationIds.length > 0 ? { langfuseObservationIds: observationIds } : {}
@@ -4151,6 +4826,7 @@ async function runTriageBatch(ctx, config, settings) {
4151
4826
  const batchDefaultAgent = await resolveDraftAgent(ctx.api, null);
4152
4827
  const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(batchDefaultAgent, config), settings.nodes));
4153
4828
  const ticketUrlBase = await resolveTicketUrlBase(ctx);
4829
+ const conversationEnd = conversationEndFor(settings, ports);
4154
4830
  const refs = await ports.conversation.listPending({ viewOrTag: settings.sourceViewId }, settings.batchLimit);
4155
4831
  const run = await ctx.api.runs.start({
4156
4832
  kind: "triage-tick",
@@ -4167,7 +4843,9 @@ async function runTriageBatch(ctx, config, settings) {
4167
4843
  categories,
4168
4844
  ports,
4169
4845
  runId: run.id,
4170
- ticketUrlBase
4846
+ ticketUrlBase,
4847
+ dryRun,
4848
+ conversationEnd
4171
4849
  });
4172
4850
  } catch (err) {
4173
4851
  failureCount += 1;
@@ -4188,6 +4866,12 @@ async function runTriageBatch(ctx, config, settings) {
4188
4866
  }
4189
4867
  return { ticketCount: refs.length, failureCount };
4190
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
+ }
4191
4875
  var ResponsePhaseError = class extends Error {
4192
4876
  generatedResponseId;
4193
4877
  constructor(generatedResponseId, cause) {
@@ -4269,11 +4953,11 @@ async function flagEscalation(ctx, ref, tag, ports) {
4269
4953
  }
4270
4954
  }
4271
4955
  async function processOneTicket(ctx, ref, deps) {
4272
- const { config, profile, categories, ports, runId, ticketUrlBase } = deps;
4956
+ const { config, profile, categories, ports, runId, ticketUrlBase, dryRun } = deps;
4273
4957
  let subjectRenamed = false;
4274
4958
  if (profile.rename) {
4275
- const conversation2 = await ports.conversation.read(ref);
4276
- const subject = conversation2.subject ?? "";
4959
+ const conversation = await ports.conversation.read(ref);
4960
+ const subject = conversation.subject ?? "";
4277
4961
  if (subject.includes(profile.rename.from)) {
4278
4962
  await ports.state.rename(ref, subject.replace(profile.rename.from, profile.rename.to));
4279
4963
  subjectRenamed = true;
@@ -4303,6 +4987,9 @@ async function processOneTicket(ctx, ref, deps) {
4303
4987
  if (!state.classification) throw new Error("triage produced no classification");
4304
4988
  const { classification } = state;
4305
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;
4306
4993
  const decision = await ctx.api.create("triage-decision", {
4307
4994
  ticketId: ref.id,
4308
4995
  ticketUrl,
@@ -4310,8 +4997,10 @@ async function processOneTicket(ctx, ref, deps) {
4310
4997
  categoryId: category?.id ?? null,
4311
4998
  tag: classification.category,
4312
4999
  confidence: classification.confidence,
4313
- reasoning: classification.reasoning,
4314
- 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,
4315
5004
  escalated: state.escalated,
4316
5005
  status: "ok",
4317
5006
  runId,
@@ -4319,45 +5008,97 @@ async function processOneTicket(ctx, ref, deps) {
4319
5008
  origin: "triage",
4320
5009
  ...traces.fields()
4321
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
+ });
4322
5017
  await ports.state.record(ref, classification, profile.audit);
4323
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 });
4324
5020
  if (!isEligibleForGeneratedResponse(profile, classification, state.escalated, category)) return;
4325
5021
  const draftAgent = await resolveDraftAgent(ctx.api, category?.agentId ?? null);
4326
- 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;
4327
5037
  const channel = conversation?.sourceChannel === "whatsapp" ? "whatsapp" : "email";
4328
5038
  const sourceChannel = conversation?.sourceChannel ?? null;
4329
- const generatedAt = ports.clock.now();
4330
- const expiresAt = new Date(generatedAt.getTime() + profile.schedule.fastResponseTtlMinutes * 6e4);
4331
- 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) {
4332
5059
  try {
4333
- created = await ctx.api.create("generated-response", {
5060
+ return await ctx.api.create("generated-response", {
4334
5061
  ticketId: ref.id,
4335
5062
  openTicketKey: openTicketKeyFor("pending", ref.id),
4336
5063
  status: "pending",
4337
- triageDecisionId: decision.id,
4338
- categoryId: category?.id ?? null,
4339
- agentId: draftAgent?.id ?? null,
4340
- channel,
4341
- sourceChannel,
4342
- generatedAt,
4343
- expiresAt,
4344
- sources: [],
4345
- tracedInput: [],
4346
- guardrailHits: [],
4347
- servedTo: [],
4348
- servedCount: 0,
4349
- followupRequired: false,
4350
- origin: "triage"
5064
+ ...fields
4351
5065
  });
4352
5066
  } catch (err) {
4353
5067
  if (err instanceof appKit.AppApiError && err.status === 409) {
4354
5068
  ctx.logger.debug(`triage-tick: generated-response already pending for ticket ${ref.id}, skipping`);
4355
- return;
5069
+ return null;
4356
5070
  }
4357
5071
  throw err;
4358
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
+ }
4359
5091
  try {
4360
- 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
+ });
4361
5102
  } catch (err) {
4362
5103
  throw new ResponsePhaseError(created.id, err);
4363
5104
  }
@@ -4547,7 +5288,7 @@ async function handleApprovalHandler(ctx, config) {
4547
5288
  revised: false
4548
5289
  };
4549
5290
  const proposedActions = [{ kind: "send_reply", args: {}, idempotencyKey: id, decision: "auto" }];
4550
- 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" });
4551
5292
  let claimed = true;
4552
5293
  const trackedSeam = {
4553
5294
  claim: async (run) => {
@@ -4651,6 +5392,7 @@ var LIST_TICKETS_INPUT_CHANNEL_UID = "a03a94ef-ccc6-48d9-a088-656406bb1585";
4651
5392
  var LIST_TICKETS_INPUT_STATUS_UID = "e2fdddae-0464-496d-9526-bb017c544f09";
4652
5393
  var LIST_TICKETS_INPUT_CURSOR_UID = "dfba83d4-8a6b-4e8b-bcfb-f3fc3cf663eb";
4653
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";
4654
5396
 
4655
5397
  // src/functions/run-triage-now.ts
4656
5398
  var TRIAGE_RUN_REQUESTED_EVENT = "triage.run.requested";
@@ -4980,7 +5722,7 @@ function applyOverrides(profile, overrides) {
4980
5722
  };
4981
5723
  }
4982
5724
  function forcedClassification(tagName) {
4983
- 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 };
4984
5726
  }
4985
5727
  var INLINE_TICKET_ID = "ticket-saisi";
4986
5728
  function createInlineConversationPort(ticket, now) {
@@ -5434,6 +6176,113 @@ async function listGorgiasViewsHandler(ctx, config, input) {
5434
6176
  connections
5435
6177
  };
5436
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
+ }
5437
6286
  var PENDING_PROMPT_NAME = "agent/pending";
5438
6287
  function buildCreateAgentFunctionDef(config) {
5439
6288
  return {
@@ -5812,11 +6661,9 @@ async function executeChat(ctx, userId, input) {
5812
6661
  const chatMessages = systemContent ? [{ role: "system", content: systemContent }, ...contextMessages] : contextMessages;
5813
6662
  const result = await ctx.api.llm.complete({
5814
6663
  messages: chatMessages,
5815
- // H3/I16: the resolved Langfuse prompt's own model config WINS over the
5816
- // agent's fallback modelId — every ported graph node applies this same
5817
- // rule (`draft.ts`, `triage.ts`, …); this was the one `PromptPort
5818
- // .resolve` consumer in the repo that dropped it.
5819
- options: { model: resolvedPrompt.config?.model ?? agent.modelId },
6664
+ // The agent's modelId stored in the OS wins; the prompt's Langfuse
6665
+ // config is ignored, like every graph node (`draft.ts`, `triage.ts`, …).
6666
+ options: { model: agent.modelId },
5820
6667
  // Link-only (D-LF follow-up, option (b)): this function already resolved
5821
6668
  // its own prompt two lines above via `PromptPort` — `resolve: false`
5822
6669
  // links the completion to it in Langfuse WITHOUT re-triggering the
@@ -6386,6 +7233,7 @@ var LABELS = {
6386
7233
  G6: "Aucune reprise humaine",
6387
7234
  G7: "Cat\xE9gorie r\xE9solue et opt\xE9e",
6388
7235
  G8: "Nouveau message client",
7236
+ FC: "Fin de conversation",
6389
7237
  G9: "R\xE9ponse ouverte pr\xE9empt\xE9e"
6390
7238
  };
6391
7239
  function humanTakeoverTags(settings) {
@@ -6411,29 +7259,45 @@ function completeFollowupLadder(results) {
6411
7259
  const missing = ALL_FOLLOWUP_GATES.filter((gate) => !evaluated.has(gate));
6412
7260
  return missing.length === 0 ? results : [...results, ...skippedFollowupGates(missing)];
6413
7261
  }
6414
- var FRESH_READ_GATES = ["G5", "G6", "G7", "G8"];
6415
- 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"];
6416
7265
  function evaluateTicketGates(input) {
6417
- const {
6418
- settings,
6419
- tags,
6420
- categories,
6421
- conversation,
6422
- anchor,
6423
- openResponse = null,
6424
- ignoreCategoryOptIn = false
6425
- } = input;
7266
+ const { settings, tags, conversation, anchor, openResponse = null } = input;
6426
7267
  const trace = newTrace(FRESH_READ_GATES);
6427
7268
  trace.record(scopeTagOnTicket(settings, tags));
6428
7269
  trace.record(noHumanTakeover(settings, tags));
6429
- const match = trace.record(categoryGate(categories, tags, ignoreCategoryOptIn));
6430
- if (match) trace.category = match;
6431
7270
  trace.record(newCustomerMessage(conversation, anchor, openResponse));
6432
7271
  return trace.done();
6433
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
+ }
6434
7298
  function evaluatePayloadGates(input) {
6435
7299
  const { settings, body, categories, anchor } = input;
6436
- const trace = newTrace(FRESH_READ_GATES);
7300
+ const trace = newTrace(PAYLOAD_GATES);
6437
7301
  const tags = body.tags;
6438
7302
  if (tags === null) {
6439
7303
  const detail = "Les tags du ticket n\u2019ont pas pu \xEAtre lus dans la charge utile \u2014 la lecture fra\xEEche tranchera.";
@@ -6459,7 +7323,7 @@ function noHumanTakeover(settings, tags) {
6459
7323
  function categoryGate(categories, tags, ignoreOptIn) {
6460
7324
  const matches = matchingCategories(categories, tags);
6461
7325
  if (matches.length === 0) return noMatchingCategory();
6462
- 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);
6463
7327
  if (eligible.length === 0) return noEligibleCategory(matches, ignoreOptIn);
6464
7328
  const category = eligible[0];
6465
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)}).`;
@@ -6533,13 +7397,11 @@ function newTrace(gates) {
6533
7397
  const results = [];
6534
7398
  let stop2 = null;
6535
7399
  return {
6536
- category: null,
6537
- /** Records `result` unless the run already stopped; returns the category it resolved, if any. */
7400
+ /** Records `result` unless the run already stopped. */
6538
7401
  record(result) {
6539
- if (stop2) return null;
7402
+ if (stop2) return;
6540
7403
  results.push({ gate: result.gate, label: result.label, status: result.status, detail: result.detail });
6541
7404
  if (result.status === "stopped") stop2 = result;
6542
- return result.category ?? null;
6543
7405
  },
6544
7406
  done() {
6545
7407
  const evaluated = new Set(results.map((result) => result.gate));
@@ -6548,7 +7410,7 @@ function newTrace(gates) {
6548
7410
  results.push({ gate, label: LABELS[gate], status: "skipped", detail: "Non \xE9valu\xE9 : un gate pr\xE9c\xE9dent a arr\xEAt\xE9 le traitement." });
6549
7411
  }
6550
7412
  }
6551
- return { results, stop: stop2, category: stop2 ? null : this.category };
7413
+ return { results, stop: stop2 };
6552
7414
  }
6553
7415
  };
6554
7416
  }
@@ -6726,20 +7588,51 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
6726
7588
  const ticket = await ctx.api.integrations.run("gorgias", "getTicketWithContext", { ticketId });
6727
7589
  const raw = ticket?.ticket ?? {};
6728
7590
  const conversation = toConversation(ref, raw, ticket?.context ?? { messages: [], customerContext: null });
6729
- const gates = evaluateTicketGates({
6730
- settings,
6731
- tags: ticketTagNames(raw),
6732
- categories,
6733
- conversation,
6734
- anchor,
6735
- openResponse,
6736
- ignoreCategoryOptIn: generateOnly
6737
- });
7591
+ const tags = ticketTagNames(raw);
7592
+ const gates = evaluateTicketGates({ settings, tags, conversation, anchor, openResponse });
6738
7593
  ladder.push(...gates.results);
6739
- if (gates.stop || !gates.category) {
6740
- 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);
6741
7635
  }
6742
- const category = gates.category;
6743
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.");
6744
7637
  if (preemption.status === "stopped") {
6745
7638
  ladder.push(preemption);
@@ -6751,7 +7644,16 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
6751
7644
  metadata: { ticketId, categoryTag: category.tagName, channel: body.channel, generateOnly }
6752
7645
  })).id;
6753
7646
  const ticketUrl = ticketUrlFor(await resolveTicketUrlBase(ctx), ticketId);
6754
- 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
+ });
6755
7657
  if (!created) {
6756
7658
  const lost = stopped(
6757
7659
  "G9",
@@ -6778,6 +7680,60 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
6778
7680
  responseId: created.id
6779
7681
  };
6780
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
+ }
6781
7737
  async function readFollowupAnchor(ctx, ticketId) {
6782
7738
  const page = await ctx.api.list("generated-response", { filter: { ticketId }, limit: ANCHOR_LOOKUP_LIMIT });
6783
7739
  let anchor = null;
@@ -6799,16 +7755,19 @@ async function readFollowupAnchor(ctx, ticketId) {
6799
7755
  var SEND_SETTLE_POLL_MS = 2e3;
6800
7756
  var SEND_SETTLE_ATTEMPTS = 4;
6801
7757
  var PREEMPT_ATTEMPTS = 3;
6802
- async function preemptOpenResponse(ctx, ticketId, open) {
7758
+ async function preemptOpenResponse(ctx, ticketId, open, options = {}) {
6803
7759
  let status = open.status;
6804
7760
  for (let attempt = 1; attempt <= PREEMPT_ATTEMPTS; attempt += 1) {
6805
7761
  if (status === null) {
6806
7762
  return stopped("G9", "Une r\xE9ponse ouverte porte un statut illisible : elle doit \xEAtre d\xE9bloqu\xE9e \xE0 la main.");
6807
7763
  }
6808
7764
  if (isTerminalStatus(status)) {
7765
+ if (options.waitForSend === false && status === "sent")
7766
+ return stopped("G9", "la r\xE9ponse ouverte vient d'\xEAtre envoy\xE9e");
6809
7767
  return passed("G9", "La r\xE9ponse ouverte s'est termin\xE9e d'elle-m\xEAme : le ticket est libre.");
6810
7768
  }
6811
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");
6812
7771
  status = await awaitSettledSend(ctx, open.id);
6813
7772
  if (status === "sending") {
6814
7773
  ctx.logger.warn(
@@ -6865,8 +7824,26 @@ function ticketTagNames(raw) {
6865
7824
  }
6866
7825
  return names;
6867
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
+ }
6868
7845
  async function openFollowupResponse(ctx, input) {
6869
- const { ticketId, category, conversation, settings, runId } = input;
7846
+ const { ticketId, category, conversation, settings, runId, conversationEnd } = input;
6870
7847
  const decision = await ctx.api.create("triage-decision", {
6871
7848
  ticketId,
6872
7849
  // Resolved by the caller AFTER every gate (`ticket-url.ts`), so a
@@ -6875,8 +7852,8 @@ async function openFollowupResponse(ctx, input) {
6875
7852
  // degrades to `null` rather than failing the pass.
6876
7853
  ticketUrl: input.ticketUrl,
6877
7854
  decidedAt: /* @__PURE__ */ new Date(),
6878
- categoryId: category.id,
6879
- tag: category.tagName,
7855
+ categoryId: category?.id ?? null,
7856
+ tag: category?.tagName ?? null,
6880
7857
  // §7.2 — NULL, and it is the honest value: no classifier ran on this pass
6881
7858
  // (D3 — the category is inherited from the tag the first pass applied), so
6882
7859
  // there is no confidence to state. The column was widened to allow it
@@ -6888,26 +7865,32 @@ async function openFollowupResponse(ctx, input) {
6888
7865
  // that does not exist — see `applyFollowupSendPolicy` in
6889
7866
  // `process-response.ts` for the decision and what it replaces.
6890
7867
  confidence: null,
6891
- reasoning: `Message suivant \u2014 cat\xE9gorie r\xE9solue par le tag ${category.tagName}`,
6892
- // The customer has just written, so the thread is by definition not over;
6893
- // and the escalation decision belongs to the first pass, which this one
6894
- // deliberately does not replay (D5).
6895
- 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,
6896
7874
  escalated: false,
6897
7875
  status: "ok",
6898
7876
  runId,
6899
7877
  subjectRenamed: false,
6900
7878
  origin: "followup"
6901
7879
  });
6902
- 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";
6903
7884
  const generatedAt = /* @__PURE__ */ new Date();
7885
+ let created;
6904
7886
  try {
6905
- return await ctx.api.create("generated-response", {
7887
+ created = await ctx.api.create("generated-response", {
6906
7888
  ticketId,
6907
- openTicketKey: openTicketKeyFor("pending", ticketId),
6908
- status: "pending",
7889
+ openTicketKey: openTicketKeyFor(status, ticketId),
7890
+ status,
6909
7891
  triageDecisionId: decision.id,
6910
- categoryId: category.id,
7892
+ categoryId: category?.id ?? null,
7893
+ ...conversationEnd ? { outcome: "no_reply_needed" } : {},
6911
7894
  agentId: agent?.id ?? null,
6912
7895
  channel: conversation.sourceChannel === "whatsapp" ? "whatsapp" : "email",
6913
7896
  sourceChannel: conversation.sourceChannel ?? null,
@@ -6935,6 +7918,8 @@ async function openFollowupResponse(ctx, input) {
6935
7918
  if (err instanceof appKit.AppApiError && err.status === 409) return null;
6936
7919
  throw err;
6937
7920
  }
7921
+ if (replyTimingId) await linkReplyTimingToDraft(ctx, replyTimingId, { id: created.id, categoryId: category?.id ?? null });
7922
+ return created;
6938
7923
  }
6939
7924
  function unresolvedCategory() {
6940
7925
  return stopped("G7", "Aucune cat\xE9gorie r\xE9solue.");
@@ -7012,9 +7997,17 @@ async function diagnose(ctx, ticketId) {
7012
7997
  const ticket = await ctx.api.integrations.run("gorgias", "getTicketWithContext", { ticketId });
7013
7998
  const raw = ticket?.ticket ?? {};
7014
7999
  const conversation = toConversation(ref, raw, ticket?.context ?? { messages: [], customerContext: null });
7015
- const trace = evaluateTicketGates({ settings, tags: ticketTagNames(raw), categories, conversation, anchor });
8000
+ const tags = ticketTagNames(raw);
8001
+ const trace = evaluateTicketGates({ settings, tags, conversation, anchor });
7016
8002
  gates.push(...trace.results);
7017
- 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));
7018
8011
  return finish3(gates, ticketId);
7019
8012
  }
7020
8013
  function predictPreemption(openResponse) {
@@ -7151,215 +8144,6 @@ function lengthInDays(range) {
7151
8144
  return (dayToMs(range.to) - dayToMs(range.from)) / MS_PER_DAY + 1;
7152
8145
  }
7153
8146
 
7154
- // src/domain/dashboard-stats.ts
7155
- function sumCounts(rows, countField = "count") {
7156
- return rows.reduce((sum, row) => sum + (Number(row[countField]) || 0), 0);
7157
- }
7158
- function bucketDay(row) {
7159
- return String(row["bucket"]).slice(0, 10);
7160
- }
7161
- var EMPTY_TOTALS = {
7162
- auto: 0,
7163
- human: 0,
7164
- inProgress: 0,
7165
- noReplyNeeded: 0
7166
- };
7167
- function countFailed(rows) {
7168
- return sumCounts(rows.filter((row) => row["status"] === "failed"));
7169
- }
7170
- var HUMAN_OUTCOMES = /* @__PURE__ */ new Set(["needs_human", "guardrail_hold", "escalated", "awaiting_approval"]);
7171
- function isUnautomatedTriage(decision) {
7172
- return decision.escalated === "true" || decision.escalated === true || decision.status === "error";
7173
- }
7174
- function countOf(row) {
7175
- return Number(row["count"]) || 0;
7176
- }
7177
- function outcomeOf(row) {
7178
- const status = row["status"];
7179
- const autoSendDecision = row["autoSendDecision"];
7180
- if (status === "test_draft" || status === "superseded") return null;
7181
- if (status === "sent") return "auto";
7182
- if (status === "no_reply_needed") return "noReplyNeeded";
7183
- if (status === "failed") return "human";
7184
- if (status === "invalidated" || status === "expired") return "human";
7185
- const outcome2 = row["outcome"];
7186
- if (typeof outcome2 === "string" && HUMAN_OUTCOMES.has(outcome2)) return "human";
7187
- if (outcome2 === "no_reply_needed") return "noReplyNeeded";
7188
- if (outcome2 === "triaged_only") return null;
7189
- return autoSendDecision === "hold" ? "human" : "inProgress";
7190
- }
7191
- function foldOutcomes(rows, triageRows = []) {
7192
- const totals = { ...EMPTY_TOTALS };
7193
- for (const row of rows) {
7194
- const outcome2 = outcomeOf(row);
7195
- if (outcome2 !== null) totals[outcome2] += countOf(row);
7196
- }
7197
- for (const row of triageRows) {
7198
- if (isUnautomatedTriage(row)) totals.human += countOf(row);
7199
- }
7200
- return totals;
7201
- }
7202
- function settledCount(totals) {
7203
- return totals.auto + totals.human;
7204
- }
7205
- function autonomyRate(totals) {
7206
- const settled = settledCount(totals);
7207
- return settled > 0 ? totals.auto / settled : Number.NaN;
7208
- }
7209
- function foldDailyOutcomes(rows, triageRows = []) {
7210
- const byDay = /* @__PURE__ */ new Map();
7211
- const totalsFor = (day) => {
7212
- const existing = byDay.get(day);
7213
- if (existing !== void 0) return existing;
7214
- const fresh = { ...EMPTY_TOTALS };
7215
- byDay.set(day, fresh);
7216
- return fresh;
7217
- };
7218
- for (const row of rows) {
7219
- const outcome2 = outcomeOf(row);
7220
- if (outcome2 === null) continue;
7221
- totalsFor(bucketDay(row))[outcome2] += countOf(row);
7222
- }
7223
- for (const row of triageRows) {
7224
- if (isUnautomatedTriage(row)) totalsFor(bucketDay(row)).human += countOf(row);
7225
- }
7226
- return [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, totals]) => ({
7227
- day,
7228
- auto: totals.auto,
7229
- human: totals.human,
7230
- rate: settledCount(totals) > 0 ? autonomyRate(totals) : null
7231
- }));
7232
- }
7233
- function fillMissingDays(series, fromIso, toIso) {
7234
- const from = Date.parse(fromIso.slice(0, 10));
7235
- const to = Date.parse(toIso.slice(0, 10));
7236
- if (Number.isNaN(from) || Number.isNaN(to) || to < from) return series;
7237
- const measured = new Map(series.map((point) => [point.day, point]));
7238
- const filled = [];
7239
- for (let t = from; t <= to; t += 864e5) {
7240
- const day = new Date(t).toISOString().slice(0, 10);
7241
- filled.push(measured.get(day) ?? { day, auto: 0, human: 0, rate: null });
7242
- }
7243
- return filled;
7244
- }
7245
- function ratePoints(rate, compareRate) {
7246
- return Number.isNaN(rate) || Number.isNaN(compareRate) ? null : (rate - compareRate) * 100;
7247
- }
7248
- var SIGNAL_MIN_VOLUME = 20;
7249
- var SIGNAL_MIN_POINTS = 3;
7250
- function dashboardSignals(totals, compare, failed2 = 0) {
7251
- const signals = [];
7252
- const settled = settledCount(totals);
7253
- const rate = autonomyRate(totals);
7254
- if (compare !== null && settled >= SIGNAL_MIN_VOLUME && settledCount(compare) >= SIGNAL_MIN_VOLUME) {
7255
- const points = ratePoints(rate, autonomyRate(compare));
7256
- if (points !== null && Math.abs(points) >= SIGNAL_MIN_POINTS) {
7257
- const move = points < 0 ? "recule" : "progresse";
7258
- signals.push({
7259
- level: points < 0 ? "creuser" : "info",
7260
- text: `Le taux d\u2019autonomie ${move} de ${Math.abs(Math.round(points))} points par rapport \xE0 la p\xE9riode pr\xE9c\xE9dente.`
7261
- });
7262
- }
7263
- }
7264
- if (failed2 > 0) {
7265
- signals.push({
7266
- level: "creuser",
7267
- 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.`
7268
- });
7269
- }
7270
- if (totals.inProgress > 0) {
7271
- signals.push({
7272
- level: "info",
7273
- 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.`
7274
- });
7275
- }
7276
- if (totals.noReplyNeeded > 0) {
7277
- signals.push({
7278
- level: "info",
7279
- text: `${totals.noReplyNeeded} demande${totals.noReplyNeeded > 1 ? "s" : ""} ne n\xE9cessitai${totals.noReplyNeeded > 1 ? "ent" : "t"} aucune r\xE9ponse : hors du taux d\u2019autonomie.`
7280
- });
7281
- }
7282
- if (compare !== null && settled > 0 && settledCount(compare) < SIGNAL_MIN_VOLUME) {
7283
- signals.push({
7284
- level: "info",
7285
- text: "La p\xE9riode pr\xE9c\xE9dente compte trop peu de demandes r\xE9gl\xE9es pour que la comparaison veuille dire quelque chose."
7286
- });
7287
- }
7288
- return signals;
7289
- }
7290
- function foldHumanReasons(rows, triageRows = []) {
7291
- const reasons = { blocked: 0, invalidated: 0, expired: 0, escalatedNoDraft: 0, failed: 0 };
7292
- for (const row of rows) {
7293
- if (outcomeOf(row) !== "human") continue;
7294
- const count = countOf(row);
7295
- if (row["status"] === "invalidated") reasons.invalidated += count;
7296
- else if (row["status"] === "expired") reasons.expired += count;
7297
- else if (row["status"] === "failed") reasons.failed += count;
7298
- else reasons.blocked += count;
7299
- }
7300
- for (const row of triageRows) {
7301
- if (isUnautomatedTriage(row)) reasons.escalatedNoDraft += countOf(row);
7302
- }
7303
- return reasons;
7304
- }
7305
- var CATEGORY_TOP_N = 10;
7306
- function foldCategoryOutcomes(triageRows, responseRows, categoryNames, topN = CATEGORY_TOP_N) {
7307
- const byId = /* @__PURE__ */ new Map();
7308
- const barFor = (id) => {
7309
- const name = typeof id === "string" ? categoryNames.get(id) : void 0;
7310
- if (name === void 0) return null;
7311
- const existing = byId.get(id);
7312
- if (existing !== void 0) return existing;
7313
- const bar = {
7314
- label: name,
7315
- total: 0,
7316
- auto: 0,
7317
- human: 0,
7318
- noReply: 0,
7319
- undrafted: 0
7320
- };
7321
- byId.set(id, bar);
7322
- return bar;
7323
- };
7324
- for (const row of triageRows) {
7325
- const bar = barFor(row["categoryId"]);
7326
- if (bar === null) continue;
7327
- const count = countOf(row);
7328
- bar.total += count;
7329
- if (isUnautomatedTriage(row)) bar.human += count;
7330
- }
7331
- for (const row of responseRows) {
7332
- const bar = barFor(row["categoryId"]);
7333
- if (bar === null) continue;
7334
- const outcome2 = outcomeOf(row);
7335
- const count = countOf(row);
7336
- if (outcome2 === "auto") bar.auto += count;
7337
- else if (outcome2 === "human") bar.human += count;
7338
- else if (outcome2 === "noReplyNeeded") bar.noReply += count;
7339
- }
7340
- const bars = [...byId.values()].map((bar) => {
7341
- const accounted = bar.auto + bar.human + bar.noReply;
7342
- return {
7343
- ...bar,
7344
- total: Math.max(bar.total, accounted),
7345
- undrafted: Math.max(0, bar.total - accounted)
7346
- };
7347
- }).filter((bar) => bar.total > 0).sort((a, b) => b.total - a.total);
7348
- if (bars.length <= topN + 1) return bars;
7349
- const tail = bars.slice(topN).reduce(
7350
- (sum, bar) => ({
7351
- label: "Autres",
7352
- total: sum.total + bar.total,
7353
- auto: sum.auto + bar.auto,
7354
- human: sum.human + bar.human,
7355
- noReply: sum.noReply + bar.noReply,
7356
- undrafted: sum.undrafted + bar.undrafted
7357
- }),
7358
- { label: "Autres", total: 0, auto: 0, human: 0, noReply: 0, undrafted: 0 }
7359
- );
7360
- return [...bars.slice(0, topN), tail];
7361
- }
7362
-
7363
8147
  // src/domain/ticket-outcome.ts
7364
8148
  var REPORTED_OUTCOMES = [...OUTCOMES, "invalidated", "expired"];
7365
8149
  function emptyOutcomeCounts() {
@@ -7427,7 +8211,7 @@ var STAT_DEFINITIONS = {
7427
8211
  awaiting_approval: "An action is waiting for a human\u2019s approval.",
7428
8212
  escalated: "Request escalated at triage, or triage error: no draft written.",
7429
8213
  triaged_only: "Triaged, with no drafting step to run.",
7430
- 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.",
7431
8215
  failed: "Generation failed technically; the ticket went up to a human.",
7432
8216
  invalidated: "Draft invalidated (an agent replied before it was served): taken over by a human, whatever the outcome decided at generation.",
7433
8217
  expired: "Draft expired (the serving window closed without it being used): taken over by a human, whatever the outcome decided at generation."
@@ -7868,6 +8652,8 @@ function deliveryReason(facts) {
7868
8652
  case "test_draft":
7869
8653
  return { code: "test_draft" };
7870
8654
  default:
8655
+ if (job.status === "no_reply_needed" && job.outcome === "no_reply_needed")
8656
+ return { code: "no_reply_needed" };
7871
8657
  return { code: "unexpected_status", status: job.status };
7872
8658
  }
7873
8659
  }
@@ -7984,7 +8770,8 @@ function toDeliveryPolicy(raw) {
7984
8770
  whatsappMode: typeof settings.whatsappMode === "string" ? settings.whatsappMode : null,
7985
8771
  autoSendChannels: Array.isArray(settings.autoSendChannels) ? settings.autoSendChannels : [...DEFAULT_AUTO_SEND_CHANNELS],
7986
8772
  dryRun: settings.dryRun === true,
7987
- audit: toAuditTags(settings)
8773
+ audit: toAuditTags(settings),
8774
+ conversationEnd: toConversationEnd(settings)
7988
8775
  };
7989
8776
  }
7990
8777
 
@@ -8243,6 +9030,7 @@ function promptNamesChosenIn(settings) {
8243
9030
  const stepPrompts = nodes.map((node) => node?.prompt?.name);
8244
9031
  return [
8245
9032
  ...stepPrompts,
9033
+ readConversationEnd(settings).prompt?.name,
8246
9034
  settings.channelPromptEmail || DEFAULT_CHANNEL_PROMPT_EMAIL,
8247
9035
  settings.channelPromptWhatsapp || DEFAULT_CHANNEL_PROMPT_WHATSAPP
8248
9036
  ];
@@ -8392,6 +9180,12 @@ var FUNCTION_ASSEMBLY = [
8392
9180
  build: buildTestGorgiasWebhookFunctionDef,
8393
9181
  createHandler: createTestGorgiasWebhookHandler
8394
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
+ },
8395
9189
  // The read-only MCP tools (spec §5.3). Their identifiers are optional —
8396
9190
  // `mcpToolIdentifierFor` derives them — so they sit outside
8397
9191
  // FUNCTION_IDENTIFIER_KEYS and this assembly covers that list PLUS the MCP tools below.
@@ -8552,10 +9346,12 @@ exports.AGENT_TOOLS = AGENT_TOOLS;
8552
9346
  exports.ATTACHMENT_MARKER_ONLY = ATTACHMENT_MARKER_ONLY;
8553
9347
  exports.CANDIDATE_MIN_LENGTH = CANDIDATE_MIN_LENGTH;
8554
9348
  exports.COLLISION_GUARDRAILS = COLLISION_GUARDRAILS;
9349
+ exports.CONVERSATION_END_ACTIONS = CONVERSATION_END_ACTIONS;
8555
9350
  exports.DECISION_ORIGINS = DECISION_ORIGINS;
8556
9351
  exports.DEFAULT_AUTO_SEND_CHANNELS = DEFAULT_AUTO_SEND_CHANNELS;
8557
9352
  exports.DEFAULT_CHANNEL_PROMPT_EMAIL = DEFAULT_CHANNEL_PROMPT_EMAIL;
8558
9353
  exports.DEFAULT_CHANNEL_PROMPT_WHATSAPP = DEFAULT_CHANNEL_PROMPT_WHATSAPP;
9354
+ exports.DEFAULT_CONVERSATION_END_TAG = DEFAULT_CONVERSATION_END_TAG;
8559
9355
  exports.DEFAULT_DECISION_ORIGIN = DEFAULT_DECISION_ORIGIN;
8560
9356
  exports.DEFAULT_LLM_PROVIDER = DEFAULT_LLM_PROVIDER;
8561
9357
  exports.DEFAULT_PROFILE_KEY = DEFAULT_PROFILE_KEY;
@@ -8583,6 +9379,7 @@ exports.buildCategoryRecord = buildCategoryRecord;
8583
9379
  exports.buildDiffAnalysisRecord = buildDiffAnalysisRecord;
8584
9380
  exports.buildEvaluationRecord = buildEvaluationRecord;
8585
9381
  exports.buildGeneratedResponseRecord = buildGeneratedResponseRecord;
9382
+ exports.buildReplyTimingRecord = buildReplyTimingRecord;
8586
9383
  exports.buildResponseComparisonRecord = buildResponseComparisonRecord;
8587
9384
  exports.buildSupportKitRecords = buildSupportKitRecords;
8588
9385
  exports.buildSupportPipeline = buildSupportPipeline;
@@ -8590,6 +9387,7 @@ exports.buildTriageDecisionRecord = buildTriageDecisionRecord;
8590
9387
  exports.canTransition = canTransition;
8591
9388
  exports.categoryGroupRecord = categoryGroupRecord;
8592
9389
  exports.channelPreGates = channelPreGates;
9390
+ exports.conversationEndEffects = conversationEndEffects;
8593
9391
  exports.createBudget = createBudget;
8594
9392
  exports.createPromptResolver = createPromptResolver;
8595
9393
  exports.customerChannelAddress = customerChannelAddress;
@@ -8623,6 +9421,7 @@ exports.pipelineStateRecord = pipelineStateRecord;
8623
9421
  exports.promptCacheRecord = promptCacheRecord;
8624
9422
  exports.publicationMode = publicationMode;
8625
9423
  exports.rawTicketFactsAt = rawTicketFactsAt;
9424
+ exports.readConversationEnd = readConversationEnd;
8626
9425
  exports.reclaimStalledSend = reclaimStalledSend;
8627
9426
  exports.reconstructGuardrailHits = reconstructGuardrailHits;
8628
9427
  exports.requiresFollowup = requiresFollowup;
@@ -8633,6 +9432,7 @@ exports.settingsToProfile = settingsToProfile;
8633
9432
  exports.settingsWarnings = settingsWarnings;
8634
9433
  exports.stopOptOut = stopOptOut;
8635
9434
  exports.targetRefFor = targetRefFor;
9435
+ exports.toConversationEnd = toConversationEnd;
8636
9436
  exports.toDecisionOrigin = toDecisionOrigin;
8637
9437
  exports.validateSettings = validateSettings;
8638
9438
  exports.verifyReply = verifyReply;