@apotech-os/support-kit 2.8.0 → 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
  }
@@ -2503,6 +2523,13 @@ function validateSettings(settings) {
2503
2523
  message: "nodes.triage must be configured \u2014 a null triage step would triage nothing."
2504
2524
  });
2505
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
+ }
2506
2533
  const autoSendEnabled = settings.autoSendEnabled === true;
2507
2534
  const isWhatsappAutoReply = settings.whatsappMode === "auto_reply";
2508
2535
  if (autoSendEnabled && !isWhatsappAutoReply && !isNonEmptyString(settings.senderEmail)) {
@@ -2516,6 +2543,20 @@ function validateSettings(settings) {
2516
2543
  function isNonEmptyString(value) {
2517
2544
  return typeof value === "string" && value.length > 0;
2518
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
+ }
2519
2560
  function isConfiguredNode(nodes) {
2520
2561
  if (typeof nodes !== "object" || nodes === null) return false;
2521
2562
  const triage2 = nodes.triage;
@@ -3122,18 +3163,19 @@ function draftPromptRefFor(agent, config) {
3122
3163
  ...agent.systemPromptSnapshot ? { fallback: agent.systemPromptSnapshot } : {}
3123
3164
  };
3124
3165
  }
3125
- function buildPromptsTable(config, draft2) {
3126
- const label = "production";
3127
- const withFallback = (name, fallback2) => ({
3128
- name,
3129
- 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,
3130
3171
  ...fallback2 ? { fallback: fallback2 } : {}
3131
3172
  });
3173
+ const prompts = config.defaults?.prompts;
3132
3174
  return {
3133
- triage: withFallback(resolvePromptName("triage", config), config.defaults?.prompts?.triage),
3134
- escalate: withFallback(resolvePromptName("escalation", config), config.defaults?.prompts?.escalation),
3135
- evaluate: withFallback(resolvePromptName("evaluation", config), config.defaults?.prompts?.evaluation),
3136
- 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),
3137
3179
  draft: draft2
3138
3180
  };
3139
3181
  }
@@ -3185,7 +3227,7 @@ async function runTriageBatch(ctx, config, settings) {
3185
3227
  const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx), ctx.api) : buildTicketPorts(ctx);
3186
3228
  const categories = await listCategories(ctx.api);
3187
3229
  const batchDefaultAgent = await resolveDraftAgent(ctx.api, null);
3188
- const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(batchDefaultAgent, config)));
3230
+ const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(batchDefaultAgent, config), settings.nodes));
3189
3231
  const refs = await ports.conversation.listPending({ viewOrTag: settings.sourceViewId }, settings.batchLimit);
3190
3232
  const run = await ctx.api.runs.start({
3191
3233
  kind: "triage-tick",
@@ -3460,7 +3502,7 @@ async function processResponseHandler(ctx, config) {
3460
3502
  const category = categoryRecord ? toCategory(categoryRecord) : null;
3461
3503
  const agentRecord2 = data.agentId ? await getOptional(ctx, "agent", data.agentId) : null;
3462
3504
  const agent = agentRecord2 ? toAgent(agentRecord2) : await resolveDraftAgent(ctx.api, null);
3463
- const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config)));
3505
+ const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));
3464
3506
  const dryRun = settings.dryRun === true;
3465
3507
  const trace = { sessionId: ticketId, tags: [`app:${config.slug}`] };
3466
3508
  const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx, trace), ctx.api) : buildTicketPorts(ctx, trace);
@@ -3715,7 +3757,7 @@ async function handleApprovalHandler(ctx, config) {
3715
3757
  ctx.logger.info("handle-approval: settings invalid, skipping", { issues });
3716
3758
  return;
3717
3759
  }
3718
- const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(null, config)));
3760
+ const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(null, config), settings.nodes));
3719
3761
  const responseText = data.responseText ?? "";
3720
3762
  if (responseText.trim().length === 0) {
3721
3763
  ctx.logger.error(`handle-approval: generated-response ${id} has no responseText, refusing to send an empty reply`);
@@ -3948,7 +3990,7 @@ async function previewTriageHandler(ctx, config, input) {
3948
3990
  }
3949
3991
  const categories = await listCategories(ctx.api);
3950
3992
  const agent = await resolveDraftAgent(ctx.api, null);
3951
- const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config)));
3993
+ const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));
3952
3994
  const realPorts = buildTicketPorts(ctx);
3953
3995
  const recordingState = createRecordingStatePort(ctx.api);
3954
3996
  const recordingReply = createRecordingReplyPort();
@@ -4147,7 +4189,7 @@ async function graphDryRunHandler(ctx, config, input) {
4147
4189
  const forcedCategory = input.categoryId ? categories.find((c) => c.id === input.categoryId) ?? null : null;
4148
4190
  if (input.categoryId && !forcedCategory) throw new ctx.NonRetriableError(`Category "${input.categoryId}" not found`);
4149
4191
  const agent = input.agentId ? toAgent(await ctx.api.get("agent", input.agentId)) : await resolveDraftAgent(ctx.api, forcedCategory?.agentId ?? null);
4150
- const baseProfile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config)));
4192
+ const baseProfile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));
4151
4193
  const profile = applyOverrides(baseProfile, input.overrides ?? {});
4152
4194
  const realPorts = buildTicketPorts(ctx);
4153
4195
  const ref = { id: inlineTicket ? INLINE_TICKET_ID : ticketId, channel: "gorgias" };
@@ -4210,7 +4252,7 @@ async function testAgentsHandler(ctx, config, input) {
4210
4252
  const limit = Math.min(input?.limit ?? DEFAULT_LIMIT, MAX_LIMIT);
4211
4253
  const categories = await listCategories(ctx.api);
4212
4254
  const agent = input.agentId ? toAgent(await ctx.api.get("agent", input.agentId)) : await resolveDraftAgent(ctx.api, null);
4213
- const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config)));
4255
+ const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));
4214
4256
  const realPorts = buildTicketPorts(ctx);
4215
4257
  const refs = explicitIds.length ? explicitIds.slice(0, limit).map((id) => ({ id, channel: "gorgias" })) : await realPorts.conversation.listPending({ viewOrTag: viewId }, limit);
4216
4258
  const deadline = AbortSignal.timeout(DRY_RUN_DEADLINE_MS);
@@ -5595,42 +5637,13 @@ var FUNCTION_ASSEMBLY = [
5595
5637
  }
5596
5638
  ];
5597
5639
  function buildPromptsAllowlist(config) {
5598
- const prefixedSlots = PROMPT_SLOTS.filter((slot) => !slot.startsWith("shared/"));
5599
5640
  return [
5600
- ...prefixedSlots.map((slot) => resolvePromptName(slot, config)),
5601
- resolveReviseName(config),
5602
- // "No agent configured" sentinel (H5, `functions/records.ts`'s
5603
- // `draftPromptRefFor`) — scoped by promptPrefix like every other name
5604
- // above, so resolving it degrades cleanly instead of a guaranteed 403.
5605
- `${config.promptPrefix}no-agent-configured`,
5606
- // Agent prompts (`agent.promptName`) are free text, conventionally
5607
- // `agent/<recordId>` (§3.7) — never promptPrefix-prefixed, so this is a
5608
- // glob, not a `resolvePromptName` call.
5609
- //
5610
- // ACCEPTED RISK (owner decision, T25 review H1 — recorded, not fixed):
5611
- // this glob is UNPREFIXED, so it matches `agent/<any-id>` regardless of
5612
- // which audience app created that agent — under D-LF's single shared
5613
- // Langfuse project there is no per-app namespace, and `*` matches `/`,
5614
- // so `agent/*` cannot be scoped narrower than "every agent prompt, any
5615
- // app" without inventing a real per-app agent-prompt namespace (which
5616
- // would contradict §3.7's documented bare `agent/<recordId>` convention
5617
- // outright). `app-prompts.controller.ts` applies this SAME allowlist to
5618
- // WRITES too (`requirePromptAllowed` at `createVersion`/`promote`/
5619
- // `deleteVersion`) for app-token callers — so one audience's app token
5620
- // can read AND version-write another audience's `agent/<id>` prompt.
5621
- // This is the documented cost of D-LF's single shared Langfuse
5622
- // namespace, accepted explicitly by the repo owner rather than fixed
5623
- // here (option (c) of the two open items this migration deferred — see
5624
- // the migration progress journal's T25 entry). The mitigation NOT taken:
5625
- // validating `agent.promptName` against the calling app's own agent
5626
- // records at write time, which would need a DB read `app-prompts
5627
- // .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.
5628
5644
  "agent/*",
5629
- // `shared/style-email`/`shared/style-whatsapp` are company-wide by
5630
- // design (§3.8) and are resolved by NAME off the settings fields' own
5631
- // bare defaults, never through `resolvePromptName` — prefixing them
5632
- // here would allowlist a name nothing ever requests. One glob covers
5633
- // 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.
5634
5647
  "shared/*"
5635
5648
  ];
5636
5649
  }
@@ -5739,6 +5752,7 @@ exports.DEFAULT_WHATSAPP_MODE = DEFAULT_WHATSAPP_MODE;
5739
5752
  exports.EVALUATION_VERDICTS = EVALUATION_VERDICTS;
5740
5753
  exports.GENERATED_RESPONSE_STATUSES = GENERATED_RESPONSE_STATUSES;
5741
5754
  exports.InvalidStatusTransitionError = InvalidStatusTransitionError;
5755
+ exports.MissingPromptError = MissingPromptError;
5742
5756
  exports.NODE_NAMES = NODE_NAMES;
5743
5757
  exports.PROMPT_SLOTS = PROMPT_SLOTS;
5744
5758
  exports.REASONING_MAX_LEN = REASONING_MAX_LEN;