@apotech-os/support-kit 8.1.0 → 8.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
@@ -747,9 +747,9 @@ async function draftWithTools(params) {
747
747
  return finish(null, sources, messages, null);
748
748
  }
749
749
  function finish(text, sources, messages, attribution) {
750
- const trimmed = (text ?? "").trim();
751
- if (!trimmed) throw new Error("Provider returned empty response");
752
- return { text: trimmed, sources, messages, revised: false, ...attribution ? { attribution } : {} };
750
+ const trimmed2 = (text ?? "").trim();
751
+ if (!trimmed2) throw new Error("Provider returned empty response");
752
+ return { text: trimmed2, sources, messages, revised: false, ...attribution ? { attribution } : {} };
753
753
  }
754
754
  function attributionOf(result, promptRef) {
755
755
  return {
@@ -896,9 +896,9 @@ function buildMessages(input) {
896
896
  ];
897
897
  }
898
898
  function section(title, body) {
899
- const trimmed = body?.trim();
900
- return trimmed ? `## ${title}
901
- ${trimmed}` : null;
899
+ const trimmed2 = body?.trim();
900
+ return trimmed2 ? `## ${title}
901
+ ${trimmed2}` : null;
902
902
  }
903
903
 
904
904
  // src/graph/revise.ts
@@ -2578,6 +2578,15 @@ var SUPPORT_KIT_SETTINGS_FIELDS = [
2578
2578
  { key: "autoRepliedTag", type: "string", label: "Auto-replied tag", default: "wai/auto-replied" },
2579
2579
  { key: "needsReviewTag", type: "string", label: "Review-before-send tag", default: "wai/escalated" },
2580
2580
  { key: "followupTag", type: "string", label: "Followup tag", default: "wai/human-required" },
2581
+ // The app's OWNERSHIP mark: applied to every ticket its triage sees, in the
2582
+ // same call as the tags above (`adapters/gorgias-tags.ts`), so that a later
2583
+ // pass can tell this app's tickets from a neighbouring app's on a SHARED
2584
+ // Gorgias account. Every other audit tag here ships the same default in
2585
+ // every app — `handledTag` is `wai/triaged` everywhere — so none of them can
2586
+ // answer "whose ticket is this?". Empty by default for the same reason a
2587
+ // shared default would be useless: an ownership mark two apps have in common
2588
+ // marks nothing. Empty means "stamp nothing".
2589
+ { key: "appScopeTag", type: "string", label: "App scope tag", default: "" },
2581
2590
  // Follow-up webhook (spec-gorgias-followup-webhook-v1 D2)
2582
2591
  // The tag a ticket must ALREADY carry for this app to answer a SUBSEQUENT
2583
2592
  // customer message on it. Deliberately empty by default, twice over:
@@ -2701,6 +2710,37 @@ function isConfiguredNode(nodes) {
2701
2710
  return typeof triage2 === "object" && triage2 !== null;
2702
2711
  }
2703
2712
 
2713
+ // src/settings/warnings.ts
2714
+ var HUMAN_TAKEOVER_KEYS = ["escalationTag", "needsReviewTag", "followupTag"];
2715
+ var AUDIT_TAG_KEYS = ["unknownTag", "handledTag", "escalationTag", "autoRepliedTag", "needsReviewTag", "followupTag"];
2716
+ function settingsWarnings(settings) {
2717
+ const warnings = [];
2718
+ const appScopeTag = trimmed(settings.appScopeTag);
2719
+ const webhookScopeTag = trimmed(settings.webhookScopeTag);
2720
+ const collidesWith = (keys) => appScopeTag ? keys.filter((key) => trimmed(settings[key]) === appScopeTag) : [];
2721
+ if (collidesWith(HUMAN_TAKEOVER_KEYS).length > 0) {
2722
+ warnings.push({
2723
+ key: "appScopeTagVetoesFollowups",
2724
+ message: "Le tag d\u2019appartenance est l\u2019un des tags de reprise humaine (escalade, relecture, suivi) : le webhook de suivi consid\xE9rera que chaque ticket tri\xE9 a \xE9t\xE9 repris par un humain et ne r\xE9pondra plus \xE0 aucun message suivant."
2725
+ });
2726
+ } else if (collidesWith(AUDIT_TAG_KEYS).length > 0) {
2727
+ warnings.push({
2728
+ key: "appScopeTagCollision",
2729
+ message: "Le tag d\u2019appartenance est l\u2019un des autres tags d\u2019audit, que toutes les apps posent avec la m\xEAme valeur par d\xE9faut : il ne distingue donc pas cette app d\u2019une autre install\xE9e sur le m\xEAme compte Gorgias."
2730
+ });
2731
+ }
2732
+ if (appScopeTag && webhookScopeTag && appScopeTag !== webhookScopeTag) {
2733
+ warnings.push({
2734
+ key: "scopeTagMismatch",
2735
+ message: "Le tag de p\xE9rim\xE8tre du webhook de suivi n\u2019est pas celui que cette app pose sur ses tickets : le webhook ne r\xE9pondra sur aucun ticket tri\xE9 ici."
2736
+ });
2737
+ }
2738
+ return warnings;
2739
+ }
2740
+ function trimmed(value) {
2741
+ return typeof value === "string" ? value.trim() : "";
2742
+ }
2743
+
2704
2744
  // src/settings/to-profile.ts
2705
2745
  var DEFAULT_REASONING = "off";
2706
2746
  var DEFAULT_MAX_TOOL_CALLS = 5;
@@ -2711,7 +2751,8 @@ function toAuditTags(settings) {
2711
2751
  escalationTag: settings.escalationTag,
2712
2752
  sentTag: settings.autoRepliedTag,
2713
2753
  needsHumanTag: settings.needsReviewTag,
2714
- followupTag: settings.followupTag
2754
+ followupTag: settings.followupTag,
2755
+ appScopeTag: settings.appScopeTag
2715
2756
  };
2716
2757
  }
2717
2758
  var DEFAULT_MIN_CONFIDENCE = 0.8;
@@ -2881,10 +2922,10 @@ function dedupeTagNames(tags) {
2881
2922
  const seen = /* @__PURE__ */ new Set();
2882
2923
  const out = [];
2883
2924
  for (const tag of tags) {
2884
- const trimmed = (tag ?? "").trim();
2885
- if (trimmed && !seen.has(trimmed)) {
2886
- seen.add(trimmed);
2887
- out.push(trimmed);
2925
+ const trimmed2 = (tag ?? "").trim();
2926
+ if (trimmed2 && !seen.has(trimmed2)) {
2927
+ seen.add(trimmed2);
2928
+ out.push(trimmed2);
2888
2929
  }
2889
2930
  }
2890
2931
  return out;
@@ -2896,7 +2937,7 @@ async function extraTagsFor(api, tagName) {
2896
2937
  }
2897
2938
  async function resolveHandledTags(api, classification, audit) {
2898
2939
  const extraTags = await extraTagsFor(api, classification.category);
2899
- return dedupeTagNames([classification.category, ...extraTags, audit.handledTag]);
2940
+ return dedupeTagNames([classification.category, ...extraTags, audit.handledTag, audit.appScopeTag]);
2900
2941
  }
2901
2942
 
2902
2943
  // src/adapters/ctx-ports.ts
@@ -2954,9 +2995,9 @@ function createGorgiasStatePort(api) {
2954
2995
  await api.integrations.run("gorgias", "renameTicket", { ticketId: ref.id, subject });
2955
2996
  },
2956
2997
  async flag(ref, tag) {
2957
- const trimmed = tag.trim();
2958
- if (!trimmed) return;
2959
- await api.integrations.run("gorgias", "applyTags", { ticketId: ref.id, names: [trimmed] });
2998
+ const trimmed2 = tag.trim();
2999
+ if (!trimmed2) return;
3000
+ await api.integrations.run("gorgias", "applyTags", { ticketId: ref.id, names: [trimmed2] });
2960
3001
  }
2961
3002
  };
2962
3003
  }
@@ -2976,7 +3017,15 @@ function createPlatformLlmPort(api, trace) {
2976
3017
  "createPlatformLlmPort: ctx.api.llm.complete v2 has no tool-calling surface (no `tools` parameter, no `role: 'tool'` message) \u2014 cannot honour CompletionRequest.tools."
2977
3018
  );
2978
3019
  }
2979
- const runTrace = req.trace ?? trace;
3020
+ const baseTrace = req.trace ?? trace;
3021
+ const runTrace = baseTrace && req.promptRef?.name ? {
3022
+ ...baseTrace,
3023
+ metadata: {
3024
+ ...baseTrace.metadata,
3025
+ prompt_name: req.promptRef.name,
3026
+ ...typeof req.promptRef.version === "number" ? { prompt_version: String(req.promptRef.version) } : {}
3027
+ }
3028
+ } : baseTrace;
2980
3029
  const result = await api.llm.complete({
2981
3030
  messages: req.messages.map(toPlatformMessage),
2982
3031
  options: {
@@ -3055,8 +3104,8 @@ function createRecordingReplyPort() {
3055
3104
  function createRecordingStatePort(api) {
3056
3105
  const tagged = [];
3057
3106
  const push = (tag) => {
3058
- const trimmed = tag.trim();
3059
- if (trimmed && !tagged.includes(trimmed)) tagged.push(trimmed);
3107
+ const trimmed2 = tag.trim();
3108
+ if (trimmed2 && !tagged.includes(trimmed2)) tagged.push(trimmed2);
3060
3109
  };
3061
3110
  return {
3062
3111
  port: {
@@ -3497,7 +3546,18 @@ async function respondToPendingResponse(ctx, config, recordId, options = {}) {
3497
3546
  );
3498
3547
  const testRun = options.testRun === true;
3499
3548
  const dryRun = settings.dryRun === true || testRun;
3500
- const trace = { sessionId: ticketId, tags: [`app:${config.slug}`] };
3549
+ const decisionTicketUrl = decision.data.ticketUrl;
3550
+ const trace = {
3551
+ sessionId: ticketId,
3552
+ tags: [`app:${config.slug}`, ...agent ? [`agent:${agent.name}`] : []],
3553
+ metadata: {
3554
+ ticket_id: ticketId,
3555
+ ...typeof decisionTicketUrl === "string" && decisionTicketUrl !== "" ? { conversation_url: decisionTicketUrl } : {},
3556
+ ...agent ? { model: agent.name, model_id: agent.modelId } : {},
3557
+ ...category ? { category: category.tagName } : {},
3558
+ origin
3559
+ }
3560
+ };
3501
3561
  const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx, trace), ctx.api) : buildTicketPorts(ctx, trace);
3502
3562
  const { clock } = ports;
3503
3563
  const conversationSnapshot = await ports.conversation.read(ref);
@@ -3613,6 +3673,29 @@ async function transitionGeneratedResponse(api, params) {
3613
3673
  }
3614
3674
  }
3615
3675
 
3676
+ // src/functions/ticket-url.ts
3677
+ async function resolveTicketUrlBase(ctx) {
3678
+ try {
3679
+ const connections = await ctx.api.integrations.list("gorgias");
3680
+ const connection = connections.find((candidate) => candidate.isDefault) ?? connections[0];
3681
+ const result = await ctx.api.integrations.run(
3682
+ "gorgias",
3683
+ "getTicketUrlBase",
3684
+ {},
3685
+ connection ? { connectionId: connection.id } : void 0
3686
+ );
3687
+ return typeof result?.base === "string" && result.base !== "" ? result.base : null;
3688
+ } catch (err) {
3689
+ ctx.logger.warn("ticket-url: could not resolve the Gorgias ticket url base, rows will carry no deep link", {
3690
+ error: err instanceof Error ? err.message : String(err)
3691
+ });
3692
+ return null;
3693
+ }
3694
+ }
3695
+ function ticketUrlFor(base, ticketId) {
3696
+ return base ? `${base}/${encodeURIComponent(ticketId)}` : null;
3697
+ }
3698
+
3616
3699
  // src/functions/triage-tick.ts
3617
3700
  function buildTriageTickFunctionDef(config) {
3618
3701
  return {
@@ -3655,30 +3738,10 @@ async function triageTickHandler(ctx, config) {
3655
3738
  }
3656
3739
  await runTriageBatch(ctx, config, settings);
3657
3740
  }
3658
- async function resolveTicketUrlBase(ctx) {
3659
- try {
3660
- const connections = await ctx.api.integrations.list("gorgias");
3661
- const connection = connections.find((candidate) => candidate.isDefault) ?? connections[0];
3662
- const result = await ctx.api.integrations.run(
3663
- "gorgias",
3664
- "getTicketUrlBase",
3665
- {},
3666
- connection ? { connectionId: connection.id } : void 0
3667
- );
3668
- return typeof result?.base === "string" && result.base !== "" ? result.base : null;
3669
- } catch (err) {
3670
- ctx.logger.warn("triage-tick: could not resolve the Gorgias ticket url base, decisions will carry no deep link", {
3671
- error: err instanceof Error ? err.message : String(err)
3672
- });
3673
- return null;
3674
- }
3675
- }
3676
- function ticketUrlFor(base, ticketId) {
3677
- return base ? `${base}/${encodeURIComponent(ticketId)}` : null;
3678
- }
3679
3741
  async function runTriageBatch(ctx, config, settings) {
3680
3742
  const dryRun = settings.dryRun === true;
3681
- const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx), ctx.api) : buildTicketPorts(ctx);
3743
+ const batchTrace = { tags: [`app:${config.slug}`] };
3744
+ const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx, batchTrace), ctx.api) : buildTicketPorts(ctx, batchTrace);
3682
3745
  const categories = await listCategories(ctx.api);
3683
3746
  const batchDefaultAgent = await resolveDraftAgent(ctx.api, null);
3684
3747
  const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(batchDefaultAgent, config), settings.nodes));
@@ -3737,6 +3800,7 @@ async function handleTicketFailure(ctx, ref, err, deps) {
3737
3800
  await finalizeFailedResponse(ctx, ref, err.generatedResponseId, message);
3738
3801
  } else {
3739
3802
  await writeErrorDecision(ctx, ref, message, deps);
3803
+ await stampAppScope(ctx, ref, deps.profile.audit.appScopeTag, deps.ports);
3740
3804
  }
3741
3805
  await escalateTicket(ctx, ref, deps);
3742
3806
  }
@@ -3776,6 +3840,16 @@ async function writeErrorDecision(ctx, ref, message, deps) {
3776
3840
  async function escalateTicket(ctx, ref, deps) {
3777
3841
  await flagEscalation(ctx, ref, deps.profile.audit.escalationTag, deps.ports);
3778
3842
  }
3843
+ async function stampAppScope(ctx, ref, tag, ports) {
3844
+ if (!tag) return;
3845
+ try {
3846
+ await ports.state.flag(ref, tag);
3847
+ } catch (err) {
3848
+ ctx.logger.error(`triage-tick: failed to stamp the app scope tag on ticket ${ref.id}`, {
3849
+ error: err instanceof Error ? err.message : String(err)
3850
+ });
3851
+ }
3852
+ }
3779
3853
  async function flagEscalation(ctx, ref, tag, ports) {
3780
3854
  if (!tag) {
3781
3855
  ctx.logger.warn(`triage-tick: ticket ${ref.id} is escalated but escalationTag is not configured \u2014 no tag applied`);
@@ -4028,7 +4102,11 @@ async function handleApprovalHandler(ctx, config) {
4028
4102
  }
4029
4103
  return;
4030
4104
  }
4031
- const ports = buildTicketPorts(ctx);
4105
+ const ports = buildTicketPorts(ctx, {
4106
+ sessionId: ticketId,
4107
+ tags: [`app:${config.slug}`],
4108
+ metadata: { ticket_id: ticketId }
4109
+ });
4032
4110
  const { clock, state: statePort } = ports;
4033
4111
  const conversation = {
4034
4112
  ref: { id: ticketId, channel: "gorgias" },
@@ -6080,8 +6158,8 @@ function parseTicketId(raw) {
6080
6158
  }
6081
6159
  function parseText(raw) {
6082
6160
  if (typeof raw !== "string") return null;
6083
- const trimmed = raw.trim();
6084
- return trimmed === "" ? null : trimmed;
6161
+ const trimmed2 = raw.trim();
6162
+ return trimmed2 === "" ? null : trimmed2;
6085
6163
  }
6086
6164
  function parseDate(raw) {
6087
6165
  if (typeof raw !== "string") return null;
@@ -6217,11 +6295,13 @@ async function runFollowupPass(ctx, config, rawBody, run, generateOnly) {
6217
6295
  message: `Message suivant \u2014 ticket ${ticketId}`,
6218
6296
  metadata: { ticketId, categoryTag: category.tagName, channel: body.channel, generateOnly }
6219
6297
  })).id;
6220
- const created = await openFollowupResponse(ctx, { ticketId, category, conversation, settings, runId: run.id });
6298
+ const ticketUrl = ticketUrlFor(await resolveTicketUrlBase(ctx), ticketId);
6299
+ const created = await openFollowupResponse(ctx, { ticketId, category, conversation, settings, runId: run.id, ticketUrl });
6221
6300
  if (!created) return stop(ctx, ticketId, "G9", "une autre ex\xE9cution a ouvert la r\xE9ponse en premier", ladder);
6222
6301
  const outcome2 = await respondToPendingResponse(ctx, config, created.id, { testRun: generateOnly });
6223
6302
  return {
6224
6303
  ticketId,
6304
+ ticketUrl,
6225
6305
  stoppedAt: null,
6226
6306
  reason: generateOnly ? `r\xE9ponse de suite g\xE9n\xE9r\xE9e sans envoi (cat\xE9gorie \xAB ${category.name} \xBB)` : `r\xE9ponse de suite g\xE9n\xE9r\xE9e (cat\xE9gorie \xAB ${category.name} \xBB)`,
6227
6307
  gates: completeFollowupLadder(ladder),
@@ -6276,10 +6356,11 @@ async function openFollowupResponse(ctx, input) {
6276
6356
  const { ticketId, category, conversation, settings, runId } = input;
6277
6357
  const decision = await ctx.api.create("triage-decision", {
6278
6358
  ticketId,
6279
- // Not resolved: `getTicketUrlBase` is a SECOND Gorgias call and this
6280
- // function runs once per message of the whole account. The field is
6281
- // documented nullable for exactly this kind of row.
6282
- ticketUrl: null,
6359
+ // Resolved by the caller AFTER every gate (`ticket-url.ts`), so a
6360
+ // refused message — the common case on an account-wide event stream —
6361
+ // never pays the extra Gorgias call. Still nullable: resolution
6362
+ // degrades to `null` rather than failing the pass.
6363
+ ticketUrl: input.ticketUrl,
6283
6364
  decidedAt: /* @__PURE__ */ new Date(),
6284
6365
  categoryId: category.id,
6285
6366
  tag: category.tagName,
@@ -6354,7 +6435,8 @@ function stop(ctx, ticketId, gate, reason, ladder) {
6354
6435
  categoryName: null,
6355
6436
  agentId: null,
6356
6437
  outcome: null,
6357
- responseId: null
6438
+ responseId: null,
6439
+ ticketUrl: null
6358
6440
  };
6359
6441
  }
6360
6442
  function buildTestGorgiasWebhookFunctionDef(config) {
@@ -6782,6 +6864,7 @@ exports.resolvePromptName = resolvePromptName;
6782
6864
  exports.runGuardrails = runGuardrails;
6783
6865
  exports.runTicket = runTicket;
6784
6866
  exports.settingsToProfile = settingsToProfile;
6867
+ exports.settingsWarnings = settingsWarnings;
6785
6868
  exports.stopOptOut = stopOptOut;
6786
6869
  exports.targetRefFor = targetRefFor;
6787
6870
  exports.toDecisionOrigin = toDecisionOrigin;