@apotech-os/support-kit 3.3.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -698,7 +698,7 @@ async function draftWithTools(params) {
698
698
  promptRef
699
699
  });
700
700
  budget.charge("draft", result.usage, { usd: 0, pricingMissing: true });
701
- if (result.toolCalls.length === 0) return finish(result.text, sources, attributionOf(result, promptRef));
701
+ if (result.toolCalls.length === 0) return finish(result.text, sources, messages, attributionOf(result, promptRef));
702
702
  conversation.push({ role: "assistant", content: result.text, toolCalls: result.toolCalls });
703
703
  for (const call of result.toolCalls) {
704
704
  budget.consumeToolCall();
@@ -707,12 +707,12 @@ async function draftWithTools(params) {
707
707
  conversation.push({ role: "tool", toolCallId: call.id, content: observation });
708
708
  }
709
709
  }
710
- return finish(null, sources, null);
710
+ return finish(null, sources, messages, null);
711
711
  }
712
- function finish(text, sources, attribution) {
712
+ function finish(text, sources, messages, attribution) {
713
713
  const trimmed = (text ?? "").trim();
714
714
  if (!trimmed) throw new Error("Provider returned empty response");
715
- return { text: trimmed, sources, revised: false, ...attribution ? { attribution } : {} };
715
+ return { text: trimmed, sources, messages, revised: false, ...attribution ? { attribution } : {} };
716
716
  }
717
717
  function attributionOf(result, promptRef) {
718
718
  return {
@@ -793,7 +793,9 @@ function failed(err) {
793
793
  verdict: null,
794
794
  confidence: null,
795
795
  reason: `evaluation error: ${message}`.slice(0, REASONING_MAX_LEN),
796
- status: "error"
796
+ status: "error",
797
+ // A call that never returned names no observation worth linking to.
798
+ observationId: null
797
799
  };
798
800
  }
799
801
  var evaluate = async (state, deps) => {
@@ -822,12 +824,12 @@ var evaluate = async (state, deps) => {
822
824
  promptRef: { name: evaluatePrompt.name, version: evaluatePrompt.version, resolve: false }
823
825
  });
824
826
  deps.budget.charge("evaluate", result.usage, { usd: 0, pricingMissing: true });
825
- return { verdict: parseVerdict(result.text) };
827
+ return { verdict: parseVerdict(result.text, result.observationId ?? null) };
826
828
  } catch (err) {
827
829
  return { verdict: failed(err) };
828
830
  }
829
831
  };
830
- function parseVerdict(text) {
832
+ function parseVerdict(text, observationId) {
831
833
  const parsed = JSON.parse(text ?? "");
832
834
  const confidence = parsed.confidence;
833
835
  if (!isEvaluationVerdict(parsed.verdict)) throw new Error(`Invalid evaluation verdict: ${text}`);
@@ -838,7 +840,8 @@ function parseVerdict(text) {
838
840
  verdict: parsed.verdict,
839
841
  confidence,
840
842
  reason: String(parsed.reason ?? "").slice(0, REASONING_MAX_LEN),
841
- status: "success"
843
+ status: "success",
844
+ observationId
842
845
  };
843
846
  }
844
847
  function buildMessages(input) {
@@ -885,7 +888,13 @@ async function reviseDraft(params) {
885
888
  budget.charge("revise", result.usage, { usd: 0, pricingMissing: true });
886
889
  const revisedText = result.text?.trim();
887
890
  if (!revisedText) return draft2;
888
- return { text: revisedText, sources: draft2.sources, revised: true, attribution: attributionOf(result, promptRef) };
891
+ return {
892
+ text: revisedText,
893
+ sources: draft2.sources,
894
+ messages: draft2.messages,
895
+ revised: true,
896
+ attribution: attributionOf(result, promptRef)
897
+ };
889
898
  }
890
899
  function buildRevisionTurn(draft2, verdict) {
891
900
  return [
@@ -3139,6 +3148,8 @@ function toGeneratedResponse(record) {
3139
3148
  promptVersion: data.promptVersion ?? null,
3140
3149
  servedCount: data.servedCount ?? 0,
3141
3150
  servedTo: data.servedTo ?? [],
3151
+ tracedInput: Array.isArray(data.tracedInput) ? data.tracedInput : [],
3152
+ sources: Array.isArray(data.sources) ? data.sources : [],
3142
3153
  verdict: toVerdict(data.verdict),
3143
3154
  guardrailHits: data.guardrailHits ?? [],
3144
3155
  triageDecisionId: data.triageDecisionId ?? null,
@@ -3468,6 +3479,17 @@ function buildInboxKey(generatedResponseId, suffix) {
3468
3479
  return suffix ? `${PREFIX}${generatedResponseId}:${suffix}` : `${PREFIX}${generatedResponseId}`;
3469
3480
  }
3470
3481
 
3482
+ // src/functions/traced-input.ts
3483
+ var TRACED_INPUT_MAX_CHARS = 4e3;
3484
+ var TRUNCATION_MARK = "\u2026 [tronqu\xE9]";
3485
+ function toTracedInput(messages) {
3486
+ return messages.map((message) => ({ role: message.role, content: cap(message.content ?? "") }));
3487
+ }
3488
+ function cap(content) {
3489
+ if (content.length <= TRACED_INPUT_MAX_CHARS) return content;
3490
+ return `${content.slice(0, TRACED_INPUT_MAX_CHARS)}${TRUNCATION_MARK}`;
3491
+ }
3492
+
3471
3493
  // src/functions/process-response.ts
3472
3494
  function classificationFromDecision(decision) {
3473
3495
  const data = decision.data;
@@ -3569,6 +3591,7 @@ async function processResponseHandler(ctx, config) {
3569
3591
  extraClaimData: (run) => ({
3570
3592
  responseText: run.draft.text,
3571
3593
  sources: run.draft.sources,
3594
+ tracedInput: toTracedInput(run.draft.messages),
3572
3595
  verdict: run.verdict,
3573
3596
  generatedMessageCount: conversationSnapshot.messageCount,
3574
3597
  generatedLastMessageAt: conversationSnapshot.lastMessageAt,
@@ -3594,6 +3617,11 @@ async function processResponseHandler(ctx, config) {
3594
3617
  const draftExtra = {
3595
3618
  responseText: result.draft?.text ?? null,
3596
3619
  sources: result.draft?.sources ?? [],
3620
+ // The rendered system prompt and the customer's own turns, which nothing
3621
+ // else persists (spec-vue-tickets-unifiee-v1 §4.1). Written on BOTH write
3622
+ // paths — the send seam's claim above and this finalisation — because a
3623
+ // sent reply and a held one are read by the same timeline.
3624
+ tracedInput: toTracedInput(result.draft?.messages ?? []),
3597
3625
  verdict: result.verdict ?? null,
3598
3626
  generatedMessageCount: conversationSnapshot.messageCount,
3599
3627
  generatedLastMessageAt: conversationSnapshot.lastMessageAt,
@@ -3834,7 +3862,15 @@ async function handleApprovalHandler(ctx, config) {
3834
3862
  hasCustomerAttachment: false,
3835
3863
  sourceChannel: data.channel
3836
3864
  };
3837
- const draft2 = { text: responseText, sources: data.sources ?? [], revised: false };
3865
+ const draft2 = {
3866
+ text: responseText,
3867
+ sources: data.sources ?? [],
3868
+ // Replayed from the record, not re-read: `tracedInput` is what the
3869
+ // original drafting call was given (spec-vue-tickets-unifiee-v1 §4.1).
3870
+ // Empty on a row written before that capture existed.
3871
+ messages: data.tracedInput ?? [],
3872
+ revised: false
3873
+ };
3838
3874
  const proposedActions = [{ kind: "send_reply", args: {}, idempotencyKey: id, decision: "auto" }];
3839
3875
  const seam = buildSendSeam({ api: ctx.api, clock, id, ticketId, fromStatus: "ready" });
3840
3876
  let claimed = true;
@@ -3881,6 +3917,7 @@ async function handleApprovalHandler(ctx, config) {
3881
3917
  // src/functions/ids.ts
3882
3918
  var RUN_TRIAGE_NOW_INPUT_IGNORE_TRIAGE_DISABLED_UID = "dd175229-feee-4306-a429-b25ea5dd89e4";
3883
3919
  var PREVIEW_TRIAGE_INPUT_TICKET_ID_UID = "b9d5da91-ce08-4aac-ae52-5ffef730fab0";
3920
+ var GET_TICKET_CONVERSATION_INPUT_TICKET_ID_UID = "88c62cf9-d3d4-4c1b-a6ae-5ee8cbfd44fd";
3884
3921
  var GRAPH_DRY_RUN_INPUT_TICKET_ID_UID = "5861e7be-3a28-4852-874c-1c14e82d4b35";
3885
3922
  var GRAPH_DRY_RUN_INPUT_CATEGORY_ID_UID = "c47b8b57-6f7a-47d7-a9d1-a18fbf71a0f0";
3886
3923
  var GRAPH_DRY_RUN_INPUT_AGENT_ID_UID = "95d38506-bc22-4f91-ad43-797ff7b54f48";
@@ -3892,8 +3929,6 @@ var TEST_AGENTS_INPUT_AGENT_ID_UID = "ea12d731-708b-4fcc-9ebb-6c4e0d04a60e";
3892
3929
  var TEST_AGENTS_INPUT_LIMIT_UID = "95151bdf-2966-41cd-8b6f-c5b0b10c427e";
3893
3930
  var SUGGEST_PROMPT_INPUT_AGENT_ID_UID = "40509afa-5931-419d-8467-a52cbac5c17e";
3894
3931
  var SUGGEST_PROMPT_INPUT_MAX_COMPARISONS_UID = "0c2e2f58-ffd3-4aee-a1b4-cb81d1762eb6";
3895
- var RUN_DIFF_ANALYSIS_INPUT_AGENT_ID_UID = "bfe1e895-1608-40d8-99e9-230ab9c41473";
3896
- var RUN_DIFF_ANALYSIS_INPUT_LIMIT_UID = "b1936472-a9dc-4b0b-8ef6-ab84733a2bfa";
3897
3932
  var LIST_GORGIAS_VIEWS_INPUT_CHECK_APP_SLUGS_UID = "1ac5eb02-32da-4fd4-9462-dac4ff23b208";
3898
3933
  var CREATE_AGENT_INPUT_NAME_UID = "0cb57453-7b02-49ce-875b-7ff079a5810d";
3899
3934
  var CREATE_AGENT_INPUT_MODEL_ID_UID = "f19f1c10-3145-482b-8c1d-6fd3576596ff";
@@ -4078,6 +4113,38 @@ async function previewTriageHandler(ctx, config, input) {
4078
4113
  wouldHaveTagged
4079
4114
  };
4080
4115
  }
4116
+ function buildGetTicketConversationFunctionDef(config) {
4117
+ return {
4118
+ universalIdentifier: identifierFor(config, "get-ticket-conversation"),
4119
+ name: "get-ticket-conversation",
4120
+ trigger: { type: "uiInvoke", minRole: "VIEWER" },
4121
+ input: [
4122
+ {
4123
+ universalIdentifier: GET_TICKET_CONVERSATION_INPUT_TICKET_ID_UID,
4124
+ name: "ticketId",
4125
+ type: appKit.FieldType.TEXT,
4126
+ label: "Ticket id",
4127
+ isNullable: false
4128
+ }
4129
+ ]
4130
+ };
4131
+ }
4132
+ function createGetTicketConversationHandler() {
4133
+ return (ctx, input) => getTicketConversationHandler(ctx, input ?? { ticketId: "" });
4134
+ }
4135
+ async function getTicketConversationHandler(ctx, input) {
4136
+ const ticketId = input?.ticketId?.trim();
4137
+ if (!ticketId) throw new ctx.NonRetriableError("ticketId is required");
4138
+ const ref = { id: ticketId, channel: "gorgias" };
4139
+ const conversation = await buildTicketPorts(ctx).conversation.read(ref);
4140
+ return {
4141
+ ticketId,
4142
+ subject: conversation.subject,
4143
+ messages: conversation.messages.map((message) => ({ role: message.role, content: message.content })),
4144
+ lastMessageAt: conversation.lastMessageAt ? conversation.lastMessageAt.toISOString() : null,
4145
+ isClosed: conversation.isClosed
4146
+ };
4147
+ }
4081
4148
 
4082
4149
  // src/functions/graph-dry-run-core.ts
4083
4150
  var DRY_RUN_DEADLINE_MS = 3 * 60 * 1e3;
@@ -4567,98 +4634,6 @@ async function suggestPromptHandler(ctx, config, input) {
4567
4634
  }
4568
4635
  return { promptName, version, comparisonCount: comparisons.length };
4569
4636
  }
4570
- var DEFAULT_LIMIT2 = 50;
4571
- var MAX_IMPROVEMENTS = 3;
4572
- var DEFAULT_DIFF_ANALYSIS_META_PROMPT = [
4573
- "Tu analyses des paires (r\xE9ponse g\xE9n\xE9r\xE9e par l'IA, r\xE9ponse r\xE9ellement envoy\xE9e par un agent humain) pour un assistant de support client.",
4574
- "Identifie au maximum 3 patterns r\xE9currents de correction (ton, structure, longueur, formulations, niveau de d\xE9tail).",
4575
- 'R\xE9ponds uniquement avec un objet JSON {"improvements": string[]}, sans autre texte.'
4576
- ].join("\n");
4577
- var RESPONSE_SCHEMA = {
4578
- name: "diff_analysis",
4579
- schema: {
4580
- type: "object",
4581
- properties: { improvements: { type: "array", items: { type: "string" } } },
4582
- required: ["improvements"],
4583
- additionalProperties: false
4584
- }
4585
- };
4586
- function buildRunDiffAnalysisFunctionDef(config) {
4587
- return {
4588
- universalIdentifier: identifierFor(config, "run-diff-analysis"),
4589
- name: "run-diff-analysis",
4590
- trigger: { type: "uiInvoke", minRole: "EDITOR" },
4591
- input: [
4592
- { universalIdentifier: RUN_DIFF_ANALYSIS_INPUT_AGENT_ID_UID, name: "agentId", type: appKit.FieldType.TEXT, label: "Agent id", isNullable: false },
4593
- { universalIdentifier: RUN_DIFF_ANALYSIS_INPUT_LIMIT_UID, name: "limit", type: appKit.FieldType.NUMBER, label: "Limit", isNullable: true }
4594
- ]
4595
- };
4596
- }
4597
- function createRunDiffAnalysisHandler(config) {
4598
- return (ctx, input) => runDiffAnalysisHandler(ctx, config, input);
4599
- }
4600
- async function runDiffAnalysisHandler(ctx, config, input) {
4601
- const agentId = input?.agentId?.trim();
4602
- if (!agentId) throw new ctx.NonRetriableError("agentId is required");
4603
- const agent = toAgent(await ctx.api.get("agent", agentId));
4604
- const promptName = agent.promptName;
4605
- if (!promptName) throw new ctx.NonRetriableError(`Agent "${agentId}" has no promptName configured`);
4606
- let promptVersion = agent.promptVersion ?? 0;
4607
- try {
4608
- promptVersion = (await ctx.api.prompts.get(promptName, { label: "production" })).version;
4609
- } catch {
4610
- }
4611
- const limit = Math.min(input?.limit ?? DEFAULT_LIMIT2, DEFAULT_LIMIT2);
4612
- const page = await ctx.api.list("response-comparison", { filter: { agentId, promptName, promptVersion }, limit });
4613
- const pairs = page.items.map((r) => r.data).filter((c) => c.generatedText && c.generatedText.trim() !== c.sentText.trim());
4614
- if (pairs.length === 0) {
4615
- throw new ctx.NonRetriableError("No non-identical comparison found for this agent");
4616
- }
4617
- const metaPromptName = resolvePromptName("diff-analysis", config);
4618
- const configuredFallback = config.defaults?.prompts?.["diff-analysis"] ?? DEFAULT_DIFF_ANALYSIS_META_PROMPT;
4619
- let metaPromptContent = configuredFallback;
4620
- try {
4621
- metaPromptContent = (await ctx.api.prompts.get(metaPromptName, { label: "production" })).content || configuredFallback;
4622
- } catch {
4623
- }
4624
- const userMessage = pairs.map((c, i) => `### Exemple ${i + 1}
4625
- IA a g\xE9n\xE9r\xE9 :
4626
- ${(c.generatedText ?? "").trim()}
4627
-
4628
- Agent a r\xE9ellement envoy\xE9 :
4629
- ${c.sentText.trim()}`).join("\n\n---\n\n");
4630
- const result = await ctx.api.llm.complete({
4631
- messages: [
4632
- { role: "system", content: metaPromptContent },
4633
- { role: "user", content: userMessage }
4634
- ],
4635
- options: { model: agent.modelId, responseSchema: RESPONSE_SCHEMA },
4636
- promptRef: { name: metaPromptName, label: "production", resolve: false }
4637
- });
4638
- let points;
4639
- try {
4640
- const parsed = JSON.parse(result.text);
4641
- points = Array.isArray(parsed.improvements) ? parsed.improvements.filter((p) => typeof p === "string").slice(0, MAX_IMPROVEMENTS) : [];
4642
- } catch {
4643
- throw new ctx.NonRetriableError("The model returned an invalid JSON response");
4644
- }
4645
- await ctx.api.upsert(
4646
- "diff-analysis",
4647
- [
4648
- {
4649
- data: {
4650
- agentId,
4651
- promptName,
4652
- promptVersion,
4653
- points,
4654
- uniqueKey: diffAnalysisUniqueKey(agentId, promptName, promptVersion)
4655
- }
4656
- }
4657
- ],
4658
- { uniqueBy: ["uniqueKey"] }
4659
- );
4660
- return { agentId, promptName, promptVersion, points, comparisonCount: pairs.length };
4661
- }
4662
4637
  function buildListGorgiasViewsFunctionDef(config) {
4663
4638
  return {
4664
4639
  universalIdentifier: identifierFor(config, "list-gorgias-views"),
@@ -5710,6 +5685,11 @@ var FUNCTION_ASSEMBLY = [
5710
5685
  build: buildPreviewTriageFunctionDef,
5711
5686
  createHandler: createPreviewTriageHandler
5712
5687
  },
5688
+ {
5689
+ key: "get-ticket-conversation",
5690
+ build: buildGetTicketConversationFunctionDef,
5691
+ createHandler: () => createGetTicketConversationHandler()
5692
+ },
5713
5693
  {
5714
5694
  key: "graph-dry-run",
5715
5695
  build: buildGraphDryRunFunctionDef,
@@ -5721,11 +5701,6 @@ var FUNCTION_ASSEMBLY = [
5721
5701
  build: buildSuggestPromptFunctionDef,
5722
5702
  createHandler: createSuggestPromptHandler
5723
5703
  },
5724
- {
5725
- key: "run-diff-analysis",
5726
- build: buildRunDiffAnalysisFunctionDef,
5727
- createHandler: createRunDiffAnalysisHandler
5728
- },
5729
5704
  {
5730
5705
  key: "list-gorgias-views",
5731
5706
  build: buildListGorgiasViewsFunctionDef,
@@ -5808,12 +5783,9 @@ function buildMergeRole(config) {
5808
5783
  }
5809
5784
  var KIT_PAGES = [
5810
5785
  { key: "dashboard-page", path: "dashboard", title: "Tableau de bord", icon: "layout-dashboard" },
5811
- { key: "tickets-page", path: "tickets", title: "Demandes", icon: "ticket" },
5812
- { key: "pipeline-page", path: "pipeline", title: "Pipeline", icon: "inbox" },
5786
+ { key: "tickets-page", path: "tickets", title: "Tickets", icon: "inbox" },
5813
5787
  { key: "agents-page", path: "agents", title: "Agents", icon: "bot" },
5814
5788
  { key: "categories-page", path: "categories", title: "Cat\xE9gories", icon: "tags" },
5815
- { key: "escalations-page", path: "escalations", title: "Escalades", icon: "alert-triangle" },
5816
- { key: "corrections-page", path: "corrections", title: "Corrections", icon: "git-compare" },
5817
5789
  { key: "graph-canvas-page", path: "graph-canvas", title: "Graphe", icon: "workflow" },
5818
5790
  {
5819
5791
  key: "shared-prompts-page",