@apotech-os/support-kit 2.7.1 → 2.9.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
@@ -55,6 +55,16 @@ var NODE_NAMES = [
55
55
  ];
56
56
 
57
57
  // src/graph/ports.ts
58
+ var MissingPromptError = class extends Error {
59
+ constructor(promptName, label) {
60
+ super(`No prompt content resolved for "${promptName}" (label "${label}") \u2014 Langfuse, the prompt-cache mirror and the in-code fallback are all empty.`);
61
+ this.promptName = promptName;
62
+ this.label = label;
63
+ this.name = "MissingPromptError";
64
+ }
65
+ promptName;
66
+ label;
67
+ };
58
68
  var AGENT_TOOLS = {
59
69
  get_order: { name: "get_order", policy: "read" },
60
70
  get_tracking: { name: "get_tracking", policy: "read" },
@@ -470,13 +480,13 @@ var escalate = async (state, deps) => {
470
480
  if (!node || !conversation) return { escalated: false };
471
481
  const message = firstCustomerMessage(conversation);
472
482
  if (!message) return { escalated: false };
483
+ const resolvedPrompt = await deps.ports.prompt.resolve(profile.prompts.escalate);
473
484
  try {
474
485
  const userParts = [];
475
486
  if (conversation.customer.orderContext) userParts.push(`## Contexte client
476
487
  ${conversation.customer.orderContext}`);
477
488
  userParts.push(`## Message \xE0 classifier
478
489
  ${message}`);
479
- const resolvedPrompt = await deps.ports.prompt.resolve(profile.prompts.escalate);
480
490
  const result = await deps.ports.llm.complete({
481
491
  label: "escalation",
482
492
  model: resolvedPrompt.config?.model ?? node.model,
@@ -792,9 +802,9 @@ var evaluate = async (state, deps) => {
792
802
  if (!node || !state.conversation || !state.draft) {
793
803
  return { verdict: failed(new Error("evaluate ran without a configured node, conversation or draft")) };
794
804
  }
805
+ const evaluatePrompt = await deps.ports.prompt.resolve(profile.prompts.evaluate);
806
+ const draftPrompt = await deps.ports.prompt.resolve(profile.prompts.draft);
795
807
  try {
796
- const evaluatePrompt = await deps.ports.prompt.resolve(profile.prompts.evaluate);
797
- const draftPrompt = await deps.ports.prompt.resolve(profile.prompts.draft);
798
808
  const result = await (deps.ports.evaluator ?? deps.ports.llm).complete({
799
809
  label: "evaluation",
800
810
  // The resolved Langfuse prompt's own model config WINS over the
@@ -1223,11 +1233,18 @@ function createPromptResolver(deps) {
1223
1233
  return null;
1224
1234
  });
1225
1235
  if (cached) {
1226
- return { name, text: substituteVars(cached.content, vars), version: cached.version, config: null };
1236
+ return served({ name, text: substituteVars(cached.content, vars), version: cached.version, config: null }, label);
1227
1237
  }
1228
1238
  const rawFallback = ref.fallback ?? "";
1229
1239
  const text = hasReferences(rawFallback) ? await composeReferences(rawFallback, composeCtx, /* @__PURE__ */ new Set([name]), 0) : rawFallback;
1230
- return { name, text: substituteVars(text, vars), version: 0, config: null };
1240
+ return served({ name, text: substituteVars(text, vars), version: 0, config: null }, label);
1241
+ }
1242
+ function served(resolved, label) {
1243
+ if (resolved.text.trim() === "") {
1244
+ deps.onDegraded?.({ stage: "prompt-missing", name: resolved.name, reason: "no prompt content at any level" });
1245
+ throw new MissingPromptError(resolved.name, label);
1246
+ }
1247
+ return resolved;
1231
1248
  }
1232
1249
  return {
1233
1250
  async resolve(ref, vars) {
@@ -1243,12 +1260,15 @@ function createPromptResolver(deps) {
1243
1260
  if (!hasReferences(resolved.content)) {
1244
1261
  await deps.cache.write(persistKey, { content: resolved.content, version: resolved.version }).catch(() => void 0);
1245
1262
  }
1246
- return {
1247
- name: ref.name,
1248
- text: substituteVars(resolved.content, vars),
1249
- version: resolved.version,
1250
- config: toResolvedConfig(resolved.config)
1251
- };
1263
+ return served(
1264
+ {
1265
+ name: ref.name,
1266
+ text: substituteVars(resolved.content, vars),
1267
+ version: resolved.version,
1268
+ config: toResolvedConfig(resolved.config)
1269
+ },
1270
+ label
1271
+ );
1252
1272
  }
1253
1273
  };
1254
1274
  }
@@ -1287,6 +1307,7 @@ var CATEGORY_FIELD_ORDER_UID = "25e85490-f365-4d28-98cd-87f93b24f653";
1287
1307
  var CATEGORY_FIELD_GROUP_ID_UID = "667697a4-9877-4df7-9b41-86e60b8b0039";
1288
1308
  var CATEGORY_FIELD_AGENT_ID_UID = "96e36d98-537c-4db1-ab84-2bb3c188b078";
1289
1309
  var CATEGORY_FIELD_EXTRA_TAGS_UID = "8673a239-1a7d-4e4f-b951-b6c5c9d4787e";
1310
+ var CATEGORY_FIELD_DESCRIPTION_UID = "fa2aeb51-47b0-4c26-845a-0b9f543f0c89";
1290
1311
  var CATEGORY_FIELD_EXAMPLES_UID = "39e52ad6-34b1-4151-a70b-7f996648b9b0";
1291
1312
  var CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID = "4fa75e78-b826-4741-9612-b6cf28bde9f9";
1292
1313
  var CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID = "c6822551-821f-4255-b220-be40c9b56052";
@@ -1467,6 +1488,17 @@ function buildCategoryRecord(slug) {
1467
1488
  isNullable: false,
1468
1489
  defaultValue: []
1469
1490
  },
1491
+ {
1492
+ universalIdentifier: CATEGORY_FIELD_DESCRIPTION_UID,
1493
+ name: "description",
1494
+ type: appKit.FieldType.TEXT,
1495
+ label: "Description",
1496
+ description: "Short definition of what belongs in this category \u2014 what triage shows the model to choose between categories. `examples` stays what it says: sample customer messages. Kept separate because the two feed the referential under different keys, and folding one into the other sends the same text twice.",
1497
+ // Nullable, and not merely by convention: every category already in a
1498
+ // tenant's base predates this field. A required one would fail the
1499
+ // read of every existing row.
1500
+ isNullable: true
1501
+ },
1470
1502
  {
1471
1503
  universalIdentifier: CATEGORY_FIELD_EXAMPLES_UID,
1472
1504
  name: "examples",
@@ -2491,6 +2523,13 @@ function validateSettings(settings) {
2491
2523
  message: "nodes.triage must be configured \u2014 a null triage step would triage nothing."
2492
2524
  });
2493
2525
  }
2526
+ const stepsWithoutPrompt = stepsMissingPrompt(settings.nodes);
2527
+ if (stepsWithoutPrompt.length > 0) {
2528
+ issues.push({
2529
+ key: "nodePrompt",
2530
+ message: `Every active step needs a Langfuse prompt \u2014 missing on: ${stepsWithoutPrompt.join(", ")}.`
2531
+ });
2532
+ }
2494
2533
  const autoSendEnabled = settings.autoSendEnabled === true;
2495
2534
  const isWhatsappAutoReply = settings.whatsappMode === "auto_reply";
2496
2535
  if (autoSendEnabled && !isWhatsappAutoReply && !isNonEmptyString(settings.senderEmail)) {
@@ -2504,6 +2543,20 @@ function validateSettings(settings) {
2504
2543
  function isNonEmptyString(value) {
2505
2544
  return typeof value === "string" && value.length > 0;
2506
2545
  }
2546
+ var STEPS_REQUIRING_PROMPT = ["triage", "escalate", "evaluate", "revise"];
2547
+ function stepsMissingPrompt(nodes) {
2548
+ if (typeof nodes !== "object" || nodes === null) return [];
2549
+ const byStep = nodes;
2550
+ return STEPS_REQUIRING_PROMPT.filter((step2) => {
2551
+ const node = byStep[step2];
2552
+ if (typeof node !== "object" || node === null) return false;
2553
+ return !isNonEmptyString(promptNameOf(node));
2554
+ });
2555
+ }
2556
+ function promptNameOf(node) {
2557
+ const prompt = node.prompt;
2558
+ return typeof prompt === "object" && prompt !== null ? prompt.name : void 0;
2559
+ }
2507
2560
  function isConfiguredNode(nodes) {
2508
2561
  if (typeof nodes !== "object" || nodes === null) return false;
2509
2562
  const triage2 = nodes.triage;
@@ -3024,6 +3077,7 @@ function toCategory(record) {
3024
3077
  groupId: data.groupId ?? null,
3025
3078
  order: data.order ?? 0,
3026
3079
  extraTags: data.extraTags ?? [],
3080
+ description: data.description ?? null,
3027
3081
  examples: data.examples ?? null,
3028
3082
  autoReplyEnabled: data.autoReplyEnabled ?? false,
3029
3083
  fastResponseEnabled: data.fastResponseEnabled ?? false
@@ -3086,7 +3140,7 @@ function toCategoryReferential(categories) {
3086
3140
  return categories.map((c) => ({
3087
3141
  name: c.name,
3088
3142
  tag: c.tagName,
3089
- desc: c.examples ?? c.name,
3143
+ desc: c.description ?? c.examples ?? c.name,
3090
3144
  ...c.examples ? { examples: c.examples } : {}
3091
3145
  }));
3092
3146
  }
@@ -3109,18 +3163,19 @@ function draftPromptRefFor(agent, config) {
3109
3163
  ...agent.systemPromptSnapshot ? { fallback: agent.systemPromptSnapshot } : {}
3110
3164
  };
3111
3165
  }
3112
- function buildPromptsTable(config, draft2) {
3113
- const label = "production";
3114
- const withFallback = (name, fallback2) => ({
3115
- name,
3116
- label,
3166
+ function buildPromptsTable(config, draft2, nodes) {
3167
+ const DEFAULT_LABEL = "production";
3168
+ const refFor = (node, derivedName, fallback2) => ({
3169
+ name: node?.prompt?.name ?? derivedName,
3170
+ label: node?.prompt?.label ?? DEFAULT_LABEL,
3117
3171
  ...fallback2 ? { fallback: fallback2 } : {}
3118
3172
  });
3173
+ const prompts = config.defaults?.prompts;
3119
3174
  return {
3120
- triage: withFallback(resolvePromptName("triage", config), config.defaults?.prompts?.triage),
3121
- escalate: withFallback(resolvePromptName("escalation", config), config.defaults?.prompts?.escalation),
3122
- evaluate: withFallback(resolvePromptName("evaluation", config), config.defaults?.prompts?.evaluation),
3123
- revise: withFallback(resolveReviseName(config), config.defaults?.prompts?.revise),
3175
+ triage: refFor(nodes.triage, resolvePromptName("triage", config), prompts?.triage),
3176
+ escalate: refFor(nodes.escalate, resolvePromptName("escalation", config), prompts?.escalation),
3177
+ evaluate: refFor(nodes.evaluate, resolvePromptName("evaluation", config), prompts?.evaluation),
3178
+ revise: refFor(nodes.revise, resolveReviseName(config), prompts?.revise),
3124
3179
  draft: draft2
3125
3180
  };
3126
3181
  }
@@ -3172,7 +3227,7 @@ async function runTriageBatch(ctx, config, settings) {
3172
3227
  const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx), ctx.api) : buildTicketPorts(ctx);
3173
3228
  const categories = await listCategories(ctx.api);
3174
3229
  const batchDefaultAgent = await resolveDraftAgent(ctx.api, null);
3175
- const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(batchDefaultAgent, config)));
3230
+ const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(batchDefaultAgent, config), settings.nodes));
3176
3231
  const refs = await ports.conversation.listPending({ viewOrTag: settings.sourceViewId }, settings.batchLimit);
3177
3232
  const run = await ctx.api.runs.start({
3178
3233
  kind: "triage-tick",
@@ -3447,7 +3502,7 @@ async function processResponseHandler(ctx, config) {
3447
3502
  const category = categoryRecord ? toCategory(categoryRecord) : null;
3448
3503
  const agentRecord2 = data.agentId ? await getOptional(ctx, "agent", data.agentId) : null;
3449
3504
  const agent = agentRecord2 ? toAgent(agentRecord2) : await resolveDraftAgent(ctx.api, null);
3450
- const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config)));
3505
+ const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));
3451
3506
  const dryRun = settings.dryRun === true;
3452
3507
  const trace = { sessionId: ticketId, tags: [`app:${config.slug}`] };
3453
3508
  const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx, trace), ctx.api) : buildTicketPorts(ctx, trace);
@@ -3702,7 +3757,7 @@ async function handleApprovalHandler(ctx, config) {
3702
3757
  ctx.logger.info("handle-approval: settings invalid, skipping", { issues });
3703
3758
  return;
3704
3759
  }
3705
- const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(null, config)));
3760
+ const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(null, config), settings.nodes));
3706
3761
  const responseText = data.responseText ?? "";
3707
3762
  if (responseText.trim().length === 0) {
3708
3763
  ctx.logger.error(`handle-approval: generated-response ${id} has no responseText, refusing to send an empty reply`);
@@ -3935,7 +3990,7 @@ async function previewTriageHandler(ctx, config, input) {
3935
3990
  }
3936
3991
  const categories = await listCategories(ctx.api);
3937
3992
  const agent = await resolveDraftAgent(ctx.api, null);
3938
- const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config)));
3993
+ const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));
3939
3994
  const realPorts = buildTicketPorts(ctx);
3940
3995
  const recordingState = createRecordingStatePort(ctx.api);
3941
3996
  const recordingReply = createRecordingReplyPort();
@@ -4134,7 +4189,7 @@ async function graphDryRunHandler(ctx, config, input) {
4134
4189
  const forcedCategory = input.categoryId ? categories.find((c) => c.id === input.categoryId) ?? null : null;
4135
4190
  if (input.categoryId && !forcedCategory) throw new ctx.NonRetriableError(`Category "${input.categoryId}" not found`);
4136
4191
  const agent = input.agentId ? toAgent(await ctx.api.get("agent", input.agentId)) : await resolveDraftAgent(ctx.api, forcedCategory?.agentId ?? null);
4137
- const baseProfile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config)));
4192
+ const baseProfile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));
4138
4193
  const profile = applyOverrides(baseProfile, input.overrides ?? {});
4139
4194
  const realPorts = buildTicketPorts(ctx);
4140
4195
  const ref = { id: inlineTicket ? INLINE_TICKET_ID : ticketId, channel: "gorgias" };
@@ -4197,7 +4252,7 @@ async function testAgentsHandler(ctx, config, input) {
4197
4252
  const limit = Math.min(input?.limit ?? DEFAULT_LIMIT, MAX_LIMIT);
4198
4253
  const categories = await listCategories(ctx.api);
4199
4254
  const agent = input.agentId ? toAgent(await ctx.api.get("agent", input.agentId)) : await resolveDraftAgent(ctx.api, null);
4200
- const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config)));
4255
+ const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));
4201
4256
  const realPorts = buildTicketPorts(ctx);
4202
4257
  const refs = explicitIds.length ? explicitIds.slice(0, limit).map((id) => ({ id, channel: "gorgias" })) : await realPorts.conversation.listPending({ viewOrTag: viewId }, limit);
4203
4258
  const deadline = AbortSignal.timeout(DRY_RUN_DEADLINE_MS);
@@ -5582,42 +5637,13 @@ var FUNCTION_ASSEMBLY = [
5582
5637
  }
5583
5638
  ];
5584
5639
  function buildPromptsAllowlist(config) {
5585
- const prefixedSlots = PROMPT_SLOTS.filter((slot) => !slot.startsWith("shared/"));
5586
5640
  return [
5587
- ...prefixedSlots.map((slot) => resolvePromptName(slot, config)),
5588
- resolveReviseName(config),
5589
- // "No agent configured" sentinel (H5, `functions/records.ts`'s
5590
- // `draftPromptRefFor`) — scoped by promptPrefix like every other name
5591
- // above, so resolving it degrades cleanly instead of a guaranteed 403.
5592
- `${config.promptPrefix}no-agent-configured`,
5593
- // Agent prompts (`agent.promptName`) are free text, conventionally
5594
- // `agent/<recordId>` (§3.7) — never promptPrefix-prefixed, so this is a
5595
- // glob, not a `resolvePromptName` call.
5596
- //
5597
- // ACCEPTED RISK (owner decision, T25 review H1 — recorded, not fixed):
5598
- // this glob is UNPREFIXED, so it matches `agent/<any-id>` regardless of
5599
- // which audience app created that agent — under D-LF's single shared
5600
- // Langfuse project there is no per-app namespace, and `*` matches `/`,
5601
- // so `agent/*` cannot be scoped narrower than "every agent prompt, any
5602
- // app" without inventing a real per-app agent-prompt namespace (which
5603
- // would contradict §3.7's documented bare `agent/<recordId>` convention
5604
- // outright). `app-prompts.controller.ts` applies this SAME allowlist to
5605
- // WRITES too (`requirePromptAllowed` at `createVersion`/`promote`/
5606
- // `deleteVersion`) for app-token callers — so one audience's app token
5607
- // can read AND version-write another audience's `agent/<id>` prompt.
5608
- // This is the documented cost of D-LF's single shared Langfuse
5609
- // namespace, accepted explicitly by the repo owner rather than fixed
5610
- // here (option (c) of the two open items this migration deferred — see
5611
- // the migration progress journal's T25 entry). The mitigation NOT taken:
5612
- // validating `agent.promptName` against the calling app's own agent
5613
- // records at write time, which would need a DB read `app-prompts
5614
- // .controller.ts` does not currently do and was not built.
5641
+ `${config.promptPrefix}*`,
5642
+ // Agent prompts are free text, conventionally `agent/<recordId>` (§3.7)
5643
+ // — never promptPrefix-prefixed, so they need their own glob.
5615
5644
  "agent/*",
5616
- // `shared/style-email`/`shared/style-whatsapp` are company-wide by
5617
- // design (§3.8) and are resolved by NAME off the settings fields' own
5618
- // bare defaults, never through `resolvePromptName` — prefixing them
5619
- // here would allowlist a name nothing ever requests. One glob covers
5620
- // both today and any future `shared/*` prompt.
5645
+ // Company-wide by design (§3.8), resolved by bare NAME off the settings
5646
+ // fields' own defaults — outside every audience prefix.
5621
5647
  "shared/*"
5622
5648
  ];
5623
5649
  }
@@ -5726,6 +5752,7 @@ exports.DEFAULT_WHATSAPP_MODE = DEFAULT_WHATSAPP_MODE;
5726
5752
  exports.EVALUATION_VERDICTS = EVALUATION_VERDICTS;
5727
5753
  exports.GENERATED_RESPONSE_STATUSES = GENERATED_RESPONSE_STATUSES;
5728
5754
  exports.InvalidStatusTransitionError = InvalidStatusTransitionError;
5755
+ exports.MissingPromptError = MissingPromptError;
5729
5756
  exports.NODE_NAMES = NODE_NAMES;
5730
5757
  exports.PROMPT_SLOTS = PROMPT_SLOTS;
5731
5758
  exports.REASONING_MAX_LEN = REASONING_MAX_LEN;