@apotech-os/support-kit 2.9.1 → 2.10.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.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/graph/budget.ts","../src/prompts/references.ts","../src/prompts/resolver.ts","../src/records/target-ref.ts","../src/records/category.ts","../src/records/category-group.ts","../src/records/triage-decision.ts","../src/records/generated-response.ts","../src/records/response-comparison.ts","../src/records/evaluation.ts","../src/records/diff-analysis.ts","../src/records/pipeline-state.ts","../src/records/prompt-cache.ts","../src/records/derive-uid.ts","../src/records/scope-to-app.ts","../src/records/index.ts","../src/functions/config.ts","../src/adapters/conversation-mapping.ts","../src/adapters/gorgias-tags.ts","../src/adapters/ctx-ports.ts","../src/adapters/recording-ports.ts","../src/functions/context.ts","../src/functions/eligibility.ts","../src/functions/no-tool-context.ts","../src/functions/pipeline-state.ts","../src/functions/triage-tick.ts","../src/functions/claim-commit.ts","../src/functions/approval-key.ts","../src/functions/process-response.ts","../src/functions/generated-response-transition.ts","../src/functions/sweep.ts","../src/functions/handle-approval.ts","../src/functions/ids.ts","../src/functions/run-triage-now.ts","../src/functions/preview-triage.ts","../src/functions/graph-dry-run-core.ts","../src/functions/graph-dry-run.ts","../src/functions/test-agents.ts","../src/functions/validate-references.ts","../src/functions/suggest-prompt.ts","../src/functions/run-diff-analysis.ts","../src/functions/list-gorgias-views.ts","../src/functions/create-agent.ts","../src/functions/set-default-agent.ts","../src/functions/create-shared-prompt-version.ts","../src/functions/sync-agent-prompt-snapshot.ts","../src/functions/ext-models.ts","../src/functions/ext-categories.ts","../src/functions/ownership-probe.ts","../src/functions/support-extension-envelope.ts","../src/functions/ext-chat.ts","../src/functions/ext-fast-response-check.ts","../src/functions/ext-evaluation.ts","../src/functions/ext-response-comparison.ts","../src/pages/manifest.ts","../src/pipeline.ts"],"names":["FieldType","result","AppApiError","conversation","agentRecord","REF_RE","DEFAULT_LIMIT","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AAM,CAAA;AAAA,IACtC,OAAA,EAAS,mBAAA;AAAA,IACT,KAAA,EAAO,iBAAA;AAAA,IACP,WAAA,EAAa,WAAA;AAAA,IACb,QAAA;AAAA,IACA,SAAA,EAAW,eAAe,MAAM,CAAA;AAAA,IAChC,YAAA,EAAc;AAAA,GAChB;AACF","file":"index.js","sourcesContent":["// Spec: architecture_agent_graphe.md §6.3 (legacy `agent/budget.ts`).\n//\n// Ported unchanged: this bounds ONE run in tool calls and time, and tracks\n// its cost ledger (I15) — it has nothing to do with the worker-level\n// `RUN_DEADLINE_MS`/stale-lock scheduling the migration drops in favour of\n// Inngest retries/concurrency/timeouts (spec §3.3's \"différences assumées\").\n// The caller still supplies whatever `AbortSignal` represents its own\n// deadline; `Budget` only ever reads it.\nimport type { CostLedger, NodeCost, NodeKey, Usage } from '../domain';\n\nconst ZERO_COST: NodeCost = { input: 0, output: 0, reasoning: 0, usd: 0, pricingMissing: false };\n\n/**\n * Run budget: bounds a run in TOOL CALLS and TIME only, never in money —\n * cost is measured (`charge`, I15) and watched separately, not capped here.\n * Every method is a no-throw no-op past the allowance: exhausting the\n * budget must never fail a ticket (§6.3).\n */\nexport interface Budget {\n /** The run's deadline signal, forwarded unchanged to every LLM call. */\n signal: AbortSignal;\n consumeToolCall(): void;\n /** True once `maxToolCalls` is spent OR the run signal aborted. */\n exhausted(): boolean;\n /** Accumulates usage/cost for one node. Reasoning stays out of `output` (§6.3). */\n charge(node: NodeKey, usage: Usage, cost: { usd: number; pricingMissing: boolean }): void;\n /** Per-node breakdown for the ticket's provenance trail. */\n ledger(): CostLedger;\n /** Whole-run total — the per-ticket cost watched downstream. */\n total(): NodeCost;\n}\n\nfunction addCost(existing: NodeCost | undefined, usage: Usage, cost: { usd: number; pricingMissing: boolean }): NodeCost {\n const base = existing ?? ZERO_COST;\n return {\n input: base.input + usage.input,\n output: base.output + usage.output,\n reasoning: base.reasoning + usage.reasoning,\n usd: base.usd + cost.usd,\n // Sticky: one unpriced charge is enough to mark the whole node unpriced,\n // so a later zero-cost charge never makes it read as \"this was free\".\n pricingMissing: base.pricingMissing || cost.pricingMissing,\n };\n}\n\nexport function createBudget({ signal, maxToolCalls }: { signal: AbortSignal; maxToolCalls: number }): Budget {\n let toolCallsUsed = 0;\n const costs: CostLedger = {};\n\n return {\n signal,\n\n consumeToolCall(): void {\n toolCallsUsed += 1;\n },\n\n exhausted(): boolean {\n return toolCallsUsed >= maxToolCalls || signal.aborted;\n },\n\n charge(node, usage, cost): void {\n costs[node] = addCost(costs[node], usage, cost);\n },\n\n ledger(): CostLedger {\n return { ...costs };\n },\n\n total(): NodeCost {\n return Object.values(costs).reduce<NodeCost>(\n (acc, entry) => addCost(acc, entry, { usd: entry.usd, pricingMissing: entry.pricingMissing }),\n ZERO_COST,\n );\n },\n };\n}\n","/**\n * Parsing for Langfuse prompt-composition reference tags\n * (`@@@langfusePrompt:name=<name>|label=<label>@@@` or `|version=<n>@@@`).\n *\n * Ported from legacy `services/promptReferences.ts` (spec §3.7: \"la\n * composition … est résolue par le kit (port de `promptReferences.ts`)\").\n * `parseReferences`/`hasReferences` are pure and dependency-free, exactly as\n * in the legacy module, so `resolver.ts`'s composition pass and the\n * write-through cache guard can both depend on them without pulling in any\n * network/DB concern.\n *\n * `validateReferences` (the admin save-time validator) is NOT ported here:\n * it is an authoring-time concern for the prompt-editing UI (AgentsPage /\n * SharedPromptsPage, §3.8), not part of `PromptPort`'s runtime resolution\n * ladder — out of scope for T19. See the module doc in `resolver.ts` for the\n * runtime composition pass this package does own.\n *\n * `REFERENCE_TAG_SOURCE` (T23 post-review B3): the regex SOURCE, not the\n * stateful `g`-flagged object itself — `functions/validate-references.ts`\n * needs the exact same grammar to tell a well-formed tag from one that only\n * looks like one, and a hand-forked copy silently drifts the moment this\n * one gains a form. Exporting the source string (not `REF_RE`) keeps every\n * importer building its own `RegExp` instance, exactly like `hasReferences`\n * already does below — nobody shares, and therefore nobody can corrupt,\n * `REF_RE.lastIndex`.\n */\n\nconst REF_RE = /@@@langfusePrompt:name=([^|@]+)\\|(?:version=(\\d+)|label=([^@]+))@@@/g;\n\nexport const REFERENCE_TAG_SOURCE = REF_RE.source;\n\nexport interface PromptReference {\n name: string;\n version?: number;\n label?: string;\n raw: string;\n}\n\n/** Parse every well-formed reference tag out of `content`, in order of appearance. */\nexport function parseReferences(content: string): PromptReference[] {\n const refs: PromptReference[] = [];\n for (const [raw, name, version, label] of content.matchAll(REF_RE)) {\n refs.push(version !== undefined ? { name: name as string, version: Number(version), raw } : { name: name as string, label, raw });\n }\n return refs;\n}\n\n/**\n * Cheap synchronous check for \"does this content contain any reference tag\".\n * Used by the write-through cache guard (`resolver.ts`) to decide whether\n * raw content is safe to mirror into the `prompt-cache` record — a fresh\n * `new RegExp` avoids mutating the shared, stateful `REF_RE.lastIndex`.\n */\nexport function hasReferences(content: string): boolean {\n return new RegExp(REF_RE.source).test(content);\n}\n","/**\n * `PromptPort` implementation — §3.7's three-level fallback, ported from\n * legacy `services/promptStore.ts`'s `getActive` ladder:\n *\n * 1. `ctx.api.prompts.get(name, {label:'production', resolve:false})`\n * (T5's platform surface, reached only through the injected\n * `PlatformPromptReader` seam below — this package may not import\n * `@wopilo/*` or reach the network itself). A 60 s in-memory cache sits\n * in front of it, mirroring the legacy SDK's own `cacheTtlSeconds`.\n * Composition tags (`@@@langfusePrompt:name=…@@@`) are resolved by\n * THIS module (`composeReferences` below) — T5's surface reads raw\n * only, unlike legacy's `c.prompt.get` which flattened composition\n * server-side. Composition targets are read through the SAME memory\n * cache as the root prompt (post-review D1) — without that, a template\n * with N reference tags paid for N extra, uncached, sequentially\n * awaited Langfuse round-trips on every single call, TTL or not.\n * 2. The `prompt-cache` record mirror (T20's record, T21's adapter) —\n * reached only through the injected `PromptCachePort` seam. Written\n * through on every successful level-1 read, AFTER composition\n * (post-review C): the content mirrored is the fully composed,\n * tag-free text, not the raw pre-composition template. Composing first\n * means a Langfuse outage now degrades to the last-known-good COMPOSED\n * prompt instead of skipping the mirror for every prompt that uses\n * composition (`shared/style-email`/`shared/style-whatsapp` consumers,\n * in particular) — `hasReferences` stays as a cheap, should-never-fire\n * assertion guarding the same invariant it always did: no raw\n * `@@@…@@@` tag may ever reach the `prompt-cache` mirror.\n * 3. `ref.fallback` (the in-code default carried by the `PromptRef` the\n * caller passed in, itself populated from `config.defaults.prompts` at\n * `buildSupportPipeline` assembly time — T20).\n *\n * …and if that last rung is empty too, `MissingPromptError` (C5 as\n * amended, `graph/ports.ts`). This ladder used to terminate at empty\n * text, version 0 — a step reaching the model with no system message\n * at all, reported as a normal run. A step with no prompt is a broken\n * install: it fails the run, loudly, naming the prompt that resolved\n * to nothing. The settings-time half of the same rule is\n * `settings/validate.ts`, which refuses to run a pipeline whose active\n * steps name no prompt at all.\n *\n * Model config (`ResolvedPrompt.config`): populated from the level-1 read's\n * `RawPrompt.config` (T5's `PromptDetail.config`, once threaded through by\n * the platform adapter). Levels 2 and 3 still report `null` today, but for\n * different reasons now that T20 has landed the records: the `prompt-cache`\n * record (§3.4) DOES carry a `config JSON?` column — this module simply\n * neither writes nor reads it yet, so level 2 has a place to recover a\n * config from and does not use it (T21's `PromptCachePort` adapter is where\n * that gets wired). `PromptRef.fallback` carries no config field at all, so\n * level 3 is `null` by construction, not by omission.\n *\n * Cache scope: `createPromptResolver` holds NO module-level state — every\n * call returns a fresh closure over its own `Map`, so two calls (two\n * app instances, or two tests) never share a memory cache. A caller that\n * wants one long-lived resolver per app process constructs it once at\n * startup (T21); a test that wants a clean slate just calls the factory\n * again. The optional `now` hook replaces `Date.now()` for tests that need\n * to force an entry stale without `vi.useFakeTimers`.\n *\n * `onDegraded` (post-review E): the kit has no logging port, and should not\n * grow one just for this — but every point below where this ladder silently\n * empties a segment or falls a level is otherwise indistinguishable from a\n * correct run to an operator. This optional hook fires at each of those\n * points; T21 wires it to the platform logger.\n */\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { PromptRef } from '../domain/profile';\nimport { MissingPromptError, type PromptPort, type ResolvedPrompt } from '../graph/ports';\nimport { hasReferences, parseReferences, type PromptReference } from './references';\n\nconst PRODUCTION_LABEL = 'production';\nconst DEFAULT_TTL_MS = 60_000;\n\n/**\n * Langfuse's own prompt-composition resolver caps a reference chain at 5\n * levels; a linear A→B→C… chain here is otherwise bounded only by the\n * number of distinct prompt names, each hop a sequential awaited round-trip\n * inside the LLM path. Matching Langfuse's own cap keeps this module's\n * worst case aligned with the platform it is standing in for.\n *\n * Exported (T23 post-review B1) so `functions/validate-references.ts` can\n * reject, AT SAVE TIME, a chain that would silently degrade past this exact\n * cap at runtime — restating the number there would only let the two drift.\n */\nexport const MAX_COMPOSITION_DEPTH = 5;\n\n/** Back-compat key: the bare name for the default label, `name::label` otherwise (legacy `cacheId`). */\nfunction cacheKey(name: string, label: string): string {\n return label === PRODUCTION_LABEL ? name : `${name}::${label}`;\n}\n\n/**\n * Memory-cache key for a platform read. A version-pinned read (a composition\n * target naming `|version=n`) is keyed on the version, since a label can\n * float across versions but a pinned version never does — collapsing it onto\n * `cacheKey`'s label-shaped key would either merge two distinct versions\n * under one entry or never hit at all.\n */\nfunction memoryKey(name: string, opts: { label?: string; version?: number }): string {\n if (opts.version !== undefined) return `${name}::v${opts.version}`;\n return cacheKey(name, opts.label ?? PRODUCTION_LABEL);\n}\n\n/**\n * Mustache-style `{{var}}` substitution — mirrors legacy `compileFallback`.\n * Uses the function form of `replaceAll` (post-review D3): a plain string\n * replacement interprets `$&`/`` $` ``/`$'`/`$1` specially, so a value\n * containing a literal `$&` (a quoted ticket excerpt, for instance) would\n * silently splice the matched placeholder back into the compiled prompt.\n */\nfunction substituteVars(text: string, vars: Record<string, string> | undefined): string {\n if (!vars) return text;\n return Object.entries(vars).reduce((out, [key, value]) => out.replaceAll(`{{${key}}}`, () => value), text);\n}\n\n/** One reference tag's target config, as read off T5's `PromptDetail.config`. */\nexport interface RawPromptConfig {\n model?: string;\n temperature?: number;\n}\n\n/** Raw (uncompiled, composition-unresolved) prompt content read at a given name+label/version. */\nexport interface RawPrompt {\n version: number;\n content: string;\n /**\n * Model config carried by the platform prompt, when the endpoint returns\n * one. Optional/absent (not just `null`) so every existing raw literal\n * built before this field existed still type-checks unchanged.\n */\n config?: RawPromptConfig | null;\n}\n\n/**\n * Seam onto T5's `ctx.api.prompts.get(name, {label|version, resolve:false})`.\n * May throw (network error, 404, unconfigured Langfuse, …) — the resolver\n * treats any rejection as a level-1 miss and falls through the ladder. T21\n * supplies the real adapter; `testing/fakes` supplies a test double.\n */\nexport interface PlatformPromptReader {\n get(name: string, ref: { label?: string; version?: number }): Promise<RawPrompt>;\n}\n\n/** One entry of the `prompt-cache` mirror (§3.4) — always RESOLVED content, never a raw reference tag. */\nexport interface PromptCacheEntry {\n content: string;\n version: number;\n}\n\n/**\n * Seam onto the `prompt-cache` record (T20's schema, T21's adapter). Both\n * methods are best-effort from the resolver's point of view — a rejection\n * from either is caught and treated as a miss/no-op, exactly like legacy's\n * Mongo cache: a `prompt-cache` outage must never block the LLM path.\n */\nexport interface PromptCachePort {\n read(key: string): Promise<PromptCacheEntry | null>;\n write(key: string, entry: PromptCacheEntry): Promise<void>;\n}\n\n/**\n * One silent-degradation event (post-review E). `stage` names the point in\n * the ladder that gave up on the \"real\" answer and returned something safe\n * instead; `name` is the prompt/reference name involved; `reason` is a\n * human-readable cause, not a typed error (the kit has no logging/error\n * taxonomy to spend here — that is T21's job once this reaches a real\n * logger).\n */\nexport interface PromptDegradedEvent {\n stage:\n | 'platform-unavailable'\n | 'cache-unavailable'\n | 'composition-target-missing'\n | 'composition-target-forbidden'\n | 'composition-cycle'\n | 'composition-depth-exceeded'\n /**\n * Not a degradation but its terminus: the ladder resolved no text at any\n * level and the run is about to fail on `MissingPromptError`. Emitted\n * here anyway so an operator reading the degradation log sees the whole\n * ladder's story, ending in the reason, rather than the exception alone\n * with no trace of what was tried.\n */\n | 'prompt-missing';\n name: string;\n reason: string;\n}\n\nexport interface PromptResolverDeps {\n platform: PlatformPromptReader;\n cache: PromptCachePort;\n /** Memory-cache TTL override, ms. Defaults to 60 000 (§3.7). */\n ttlMs?: number;\n /** Injectable clock for the memory cache, defaults to `Date.now`. */\n now?: () => number;\n /** Fires at every silent-degradation point in the ladder (post-review E). */\n onDegraded?: (event: PromptDegradedEvent) => void;\n}\n\ninterface MemoryCacheEntry {\n /** Fully composed content — no remaining reference tag — never the raw fetch. */\n content: string;\n version: number;\n config?: RawPromptConfig | null;\n expiresAt: number;\n}\n\ninterface ComposeContext {\n platform: PlatformPromptReader;\n memory: Map<string, MemoryCacheEntry>;\n ttlMs: number;\n now: () => number;\n onDegraded?: (event: PromptDegradedEvent) => void;\n}\n\nfunction reasonOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * `parseReferences` returns one entry per OCCURRENCE, not per distinct\n * target (post-review D2) — a template that repeats the same tag twice must\n * still only fetch it once. `ref.raw` identifies the target uniquely enough\n * for this purpose: two occurrences of the same tag share the same raw\n * string, and `replaceAll` below already replaces every occurrence in one\n * pass once the tag is deduped.\n */\nfunction dedupeByRaw(refs: PromptReference[]): PromptReference[] {\n const seen = new Set<string>();\n return refs.filter((ref) => {\n if (seen.has(ref.raw)) return false;\n seen.add(ref.raw);\n return true;\n });\n}\n\nfunction stripReferences(content: string, refs: PromptReference[]): string {\n let out = content;\n for (const ref of dedupeByRaw(refs)) out = out.replaceAll(ref.raw, () => '');\n return out;\n}\n\n/**\n * Fetches `name` at `opts`, composes its references, and caches the\n * COMPOSED result (post-review D1) — shared by both the root prompt read\n * and every composition target, so a reference fetched once by any caller\n * within the TTL window is never fetched again, root or nested.\n */\nasync function readComposed(\n name: string,\n opts: { label?: string; version?: number },\n ctx: ComposeContext,\n visited: ReadonlySet<string>,\n depth: number,\n): Promise<MemoryCacheEntry> {\n const key = memoryKey(name, opts);\n const cached = ctx.memory.get(key);\n if (cached && cached.expiresAt > ctx.now()) return cached;\n\n const raw = await ctx.platform.get(name, opts);\n const content = await composeReferences(raw.content, ctx, visited, depth);\n const entry: MemoryCacheEntry = { content, version: raw.version, config: raw.config, expiresAt: ctx.now() + ctx.ttlMs };\n ctx.memory.set(key, entry);\n return entry;\n}\n\n/**\n * Resolves one reference tag to its replacement text: empty on a cycle\n * (visited) or an unresolvable target (fetch/compose throws), the target's\n * own composed content otherwise. Never leaves the literal tag in place —\n * the guarantee this module exists to hold (\"no raw tag reaches the LLM\")\n * applies here, not only through the write-through cache guard.\n */\nasync function resolveOneReference(\n ref: PromptReference,\n ctx: ComposeContext,\n visited: ReadonlySet<string>,\n depth: number,\n): Promise<string> {\n if (visited.has(ref.name)) {\n ctx.onDegraded?.({ stage: 'composition-cycle', name: ref.name, reason: 'cyclic composition reference' });\n return '';\n }\n\n const targetOpts = ref.version !== undefined ? { version: ref.version } : { label: ref.label };\n try {\n const target = await readComposed(ref.name, targetOpts, ctx, new Set([...visited, ref.name]), depth + 1);\n return target.content;\n } catch (err) {\n // M1 (T25 review): a 403 (the target exists but is outside this app's\n // role.prompts allowlist) is a MISCONFIGURATION, not a missing prompt —\n // reported under its own stage so `onDegraded` can name the allowlist\n // instead of reading identically to \"prompt/version/label not found\".\n // Still resolves to '' either way (PromptPort.resolve may never reject,\n // graph/ports.ts's C5) — this only makes the degradation legible.\n const forbidden = err instanceof AppApiError && err.status === 403;\n ctx.onDegraded?.({\n stage: forbidden ? 'composition-target-forbidden' : 'composition-target-missing',\n name: ref.name,\n reason: reasonOf(err),\n });\n return '';\n }\n}\n\n/**\n * Resolves every reference tag in `content`, one round-trip per DISTINCT\n * target (post-review D2), using the function form of `replaceAll`\n * (post-review D3 — see `substituteVars`'s doc comment for why). `depth`\n * bounds the chain at `MAX_COMPOSITION_DEPTH` (post-review D4): past it, the\n * remaining tags are stripped rather than followed one hop further, so a\n * long linear A→B→C… chain degrades instead of costing one sequential\n * round-trip per hop indefinitely.\n */\nasync function composeReferences(\n content: string,\n ctx: ComposeContext,\n visited: ReadonlySet<string>,\n depth: number,\n): Promise<string> {\n if (!hasReferences(content)) return content;\n\n const refs = parseReferences(content);\n if (depth >= MAX_COMPOSITION_DEPTH) {\n for (const ref of dedupeByRaw(refs)) {\n ctx.onDegraded?.({\n stage: 'composition-depth-exceeded',\n name: ref.name,\n reason: `composition chain exceeded ${MAX_COMPOSITION_DEPTH} levels`,\n });\n }\n return stripReferences(content, refs);\n }\n\n let resolved = content;\n for (const ref of dedupeByRaw(refs)) {\n const replacement = await resolveOneReference(ref, ctx, visited, depth);\n resolved = resolved.replaceAll(ref.raw, () => replacement);\n }\n return resolved;\n}\n\n/** Narrows a raw config blob to `ResolvedPrompt.config`'s stricter shape (model required, not just optional). */\nfunction toResolvedConfig(config: RawPromptConfig | null | undefined): ResolvedPrompt['config'] {\n if (!config || typeof config.model !== 'string' || config.model.length === 0) return null;\n return config.temperature !== undefined ? { model: config.model, temperature: config.temperature } : { model: config.model };\n}\n\n/** Builds a `PromptPort` implementing §3.7's three-level fallback ladder. */\nexport function createPromptResolver(deps: PromptResolverDeps): PromptPort {\n const ttlMs = deps.ttlMs ?? DEFAULT_TTL_MS;\n const now = deps.now ?? Date.now;\n const memory = new Map<string, MemoryCacheEntry>();\n const composeCtx: ComposeContext = { platform: deps.platform, memory, ttlMs, now, onDegraded: deps.onDegraded };\n\n async function resolveFromCacheOrFallback(\n name: string,\n label: string,\n ref: PromptRef,\n vars: Record<string, string> | undefined,\n ): Promise<ResolvedPrompt> {\n const cached = await deps.cache.read(cacheKey(name, label)).catch((err: unknown) => {\n deps.onDegraded?.({ stage: 'cache-unavailable', name, reason: reasonOf(err) });\n return null;\n });\n if (cached) {\n return served({ name, text: substituteVars(cached.content, vars), version: cached.version, config: null }, label);\n }\n\n // M3 (T25 review): `ref.fallback` (config.defaults.prompts, wired T25)\n // is the one rung of the ladder that used to skip composition entirely\n // — a fallback authored with the house `@@@langfusePrompt:...@@@` idiom\n // (the same syntax every legacy prompt already uses) would reach the\n // LLM as a literal, unresolved tag the moment Langfuse AND the\n // prompt-cache mirror were both unavailable, violating this module's\n // own \"no raw tag reaches the LLM\" guarantee. Composed through the same\n // `composeCtx` (and so the same memory cache) as every other level.\n const rawFallback = ref.fallback ?? '';\n const text = hasReferences(rawFallback)\n ? await composeReferences(rawFallback, composeCtx, new Set([name]), 0)\n : rawFallback;\n return served({ name, text: substituteVars(text, vars), version: 0, config: null }, label);\n }\n\n /**\n * The one exit every rung goes through: a resolution with no text is not a\n * prompt, whichever level produced it. Whitespace counts as empty — a\n * prompt of three newlines says nothing to a model, and a name that\n * resolves to one is the same broken install as a name that resolves to\n * nothing.\n */\n function served(resolved: ResolvedPrompt, label: string): ResolvedPrompt {\n if (resolved.text.trim() === '') {\n deps.onDegraded?.({ stage: 'prompt-missing', name: resolved.name, reason: 'no prompt content at any level' });\n throw new MissingPromptError(resolved.name, label);\n }\n return resolved;\n }\n\n return {\n async resolve(ref: PromptRef, vars?: Record<string, string>): Promise<ResolvedPrompt> {\n const label = ref.label?.trim() || PRODUCTION_LABEL;\n const persistKey = cacheKey(ref.name, label);\n\n let resolved: MemoryCacheEntry;\n try {\n resolved = await readComposed(ref.name, { label }, composeCtx, new Set([ref.name]), 0);\n } catch (err) {\n deps.onDegraded?.({ stage: 'platform-unavailable', name: ref.name, reason: reasonOf(err) });\n return resolveFromCacheOrFallback(ref.name, label, ref, vars);\n }\n\n // Write-through, AFTER composition (§3.7 invariant, post-review C):\n // only ever mirror composed, tag-free content. `hasReferences` here is\n // a should-never-fire assertion, not a decision point — composition\n // above already strips every matched tag by construction.\n if (!hasReferences(resolved.content)) {\n await deps.cache.write(persistKey, { content: resolved.content, version: resolved.version }).catch(() => undefined);\n }\n\n return served(\n {\n name: ref.name,\n text: substituteVars(resolved.content, vars),\n version: resolved.version,\n config: toResolvedConfig(resolved.config),\n },\n label,\n );\n },\n };\n}\n","/**\n * A relation's `targetRef` names the app the target record lives in\n * (`app:<slug>/<objectKey>`, resolved by `app-records.service.ts`), and the\n * kit is never installed under the slug `support-kit`: it is spread into\n * `experience-client`, `pro-sante`, … Every record carrying a relation is\n * therefore built per consuming app, from that app's own slug (§3.2's\n * `config.slug`), never from a literal.\n */\nexport function targetRefFor(slug: string, objectKey: string): string {\n return `app:${slug}/${objectKey}`;\n}\n","/**\n * `category` (ex-`Category`) — spec §3.4.\n *\n * `tagName` is matched exactly, case-sensitively, against Gorgias tags — it is\n * NOT normalised anywhere in this definition, on purpose: the handler that\n * applies tags (T22+) must compare byte-for-byte with what Gorgias sends back.\n *\n * The legacy `auto_reply_min_confidence` field is deliberately not ported —\n * the spec records it as already neutralised upstream in the legacy system.\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n CATEGORY_OBJECT_UID,\n CATEGORY_FIELD_NAME_UID,\n CATEGORY_FIELD_TAG_NAME_UID,\n CATEGORY_FIELD_ORDER_UID,\n CATEGORY_FIELD_GROUP_ID_UID,\n CATEGORY_FIELD_AGENT_ID_UID,\n CATEGORY_FIELD_EXTRA_TAGS_UID,\n CATEGORY_FIELD_DESCRIPTION_UID,\n CATEGORY_FIELD_EXAMPLES_UID,\n CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID,\n CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID,\n CATEGORY_INDEX_TAG_NAME_UID,\n CATEGORY_INDEX_NAME_UID,\n CATEGORY_INDEX_ORDER_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nexport function buildCategoryRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: CATEGORY_OBJECT_UID,\n objectKey: 'category',\n labelSingular: 'Category',\n labelPlural: 'Categories',\n description: 'A triage category, matched against a Gorgias tag.',\n fields: [\n {\n universalIdentifier: CATEGORY_FIELD_NAME_UID,\n name: 'name',\n type: FieldType.TEXT,\n label: 'Name',\n isNullable: false,\n },\n {\n universalIdentifier: CATEGORY_FIELD_TAG_NAME_UID,\n name: 'tagName',\n type: FieldType.TEXT,\n label: 'Gorgias tag',\n description: 'Matched exactly, case-sensitively, against Gorgias tags.',\n isNullable: false,\n },\n {\n universalIdentifier: CATEGORY_FIELD_ORDER_UID,\n name: 'order',\n type: FieldType.NUMBER,\n label: 'Order',\n isNullable: false,\n },\n {\n universalIdentifier: CATEGORY_FIELD_GROUP_ID_UID,\n name: 'groupId',\n type: FieldType.RELATION,\n label: 'Category group',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'category-group'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: CATEGORY_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: CATEGORY_FIELD_EXTRA_TAGS_UID,\n name: 'extraTags',\n type: FieldType.JSON,\n label: 'Extra tags',\n description: 'string[], at most 10 entries of at most 50 characters each.',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: CATEGORY_FIELD_DESCRIPTION_UID,\n name: 'description',\n type: FieldType.TEXT,\n label: 'Description',\n description:\n 'Short definition of what belongs in this category — 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.',\n // Nullable, and not merely by convention: every category already in a\n // tenant's base predates this field. A required one would fail the\n // read of every existing row.\n isNullable: true,\n },\n {\n universalIdentifier: CATEGORY_FIELD_EXAMPLES_UID,\n name: 'examples',\n type: FieldType.TEXT,\n label: 'Examples',\n description: 'At most 4000 characters.',\n isNullable: true,\n },\n {\n universalIdentifier: CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID,\n name: 'fastResponseEnabled',\n type: FieldType.BOOLEAN,\n label: 'Fast response enabled',\n isNullable: false,\n defaultValue: false,\n },\n {\n universalIdentifier: CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID,\n name: 'autoReplyEnabled',\n type: FieldType.BOOLEAN,\n label: 'Auto-reply enabled',\n isNullable: false,\n defaultValue: false,\n },\n ],\n indexes: [\n { universalIdentifier: CATEGORY_INDEX_TAG_NAME_UID, fields: ['tagName'], isUnique: true },\n { universalIdentifier: CATEGORY_INDEX_NAME_UID, fields: ['name'], isUnique: true },\n { universalIdentifier: CATEGORY_INDEX_ORDER_UID, fields: ['order'] },\n ],\n };\n}\n","/** `category-group` — spec §3.4. */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n CATEGORY_GROUP_OBJECT_UID,\n CATEGORY_GROUP_FIELD_NAME_UID,\n CATEGORY_GROUP_FIELD_ORDER_UID,\n CATEGORY_GROUP_INDEX_NAME_UID,\n} from './ids';\n\nexport const categoryGroupRecord: ObjectDef = {\n universalIdentifier: CATEGORY_GROUP_OBJECT_UID,\n objectKey: 'category-group',\n labelSingular: 'Category group',\n labelPlural: 'Category groups',\n fields: [\n {\n universalIdentifier: CATEGORY_GROUP_FIELD_NAME_UID,\n name: 'name',\n type: FieldType.TEXT,\n label: 'Name',\n isNullable: false,\n },\n {\n universalIdentifier: CATEGORY_GROUP_FIELD_ORDER_UID,\n name: 'order',\n type: FieldType.NUMBER,\n label: 'Order',\n isNullable: false,\n },\n ],\n indexes: [{ universalIdentifier: CATEGORY_GROUP_INDEX_NAME_UID, fields: ['name'], isUnique: true }],\n};\n","/**\n * `triage-decision` (ex-`TriageDecision`) — spec §3.4.\n *\n * `decidedAt` is indexed because the 24h/7d stat windows filter and bucket on\n * this DATA field, not on the system `createdAt` — a run replayed or\n * backfilled keeps the decision's own timestamp.\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n TRIAGE_DECISION_OBJECT_UID,\n TRIAGE_DECISION_FIELD_TICKET_ID_UID,\n TRIAGE_DECISION_FIELD_DECIDED_AT_UID,\n TRIAGE_DECISION_FIELD_CATEGORY_ID_UID,\n TRIAGE_DECISION_FIELD_TAG_UID,\n TRIAGE_DECISION_FIELD_CONFIDENCE_UID,\n TRIAGE_DECISION_FIELD_REASONING_UID,\n TRIAGE_DECISION_FIELD_CONVERSATION_OVER_UID,\n TRIAGE_DECISION_FIELD_ESCALATED_UID,\n TRIAGE_DECISION_FIELD_ESCALATION_CONFIDENCE_UID,\n TRIAGE_DECISION_FIELD_ESCALATION_REASONING_UID,\n TRIAGE_DECISION_FIELD_STATUS_UID,\n TRIAGE_DECISION_FIELD_ERROR_UID,\n TRIAGE_DECISION_FIELD_RUN_ID_UID,\n TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID,\n TRIAGE_DECISION_INDEX_TICKET_ID_UID,\n TRIAGE_DECISION_INDEX_DECIDED_AT_UID,\n TRIAGE_DECISION_INDEX_ESCALATED_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nconst CONFIDENCE_OPTIONS = ['high', 'low'] as const;\n\nexport function buildTriageDecisionRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: TRIAGE_DECISION_OBJECT_UID,\n objectKey: 'triage-decision',\n labelSingular: 'Triage decision',\n labelPlural: 'Triage decisions',\n fields: [\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_TICKET_ID_UID,\n name: 'ticketId',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_DECIDED_AT_UID,\n name: 'decidedAt',\n type: FieldType.DATE_TIME,\n label: 'Decided at',\n description: 'Backs the 24h/7d stat windows — not the system createdAt.',\n isNullable: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_CATEGORY_ID_UID,\n name: 'categoryId',\n type: FieldType.RELATION,\n label: 'Category',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'category'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_TAG_UID,\n name: 'tag',\n type: FieldType.TEXT,\n label: 'Tag',\n isNullable: true,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_CONFIDENCE_UID,\n name: 'confidence',\n type: FieldType.SELECT,\n label: 'Confidence',\n isNullable: false,\n options: [...CONFIDENCE_OPTIONS],\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_REASONING_UID,\n name: 'reasoning',\n type: FieldType.TEXT,\n label: 'Reasoning',\n description: 'At most 280 characters.',\n isNullable: true,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_CONVERSATION_OVER_UID,\n name: 'conversationOver',\n type: FieldType.BOOLEAN,\n label: 'Conversation over',\n isNullable: false,\n defaultValue: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_ESCALATED_UID,\n name: 'escalated',\n type: FieldType.BOOLEAN,\n label: 'Escalated',\n isNullable: false,\n defaultValue: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_ESCALATION_CONFIDENCE_UID,\n name: 'escalationConfidence',\n type: FieldType.SELECT,\n label: 'Escalation confidence',\n isNullable: true,\n options: [...CONFIDENCE_OPTIONS],\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_ESCALATION_REASONING_UID,\n name: 'escalationReasoning',\n type: FieldType.TEXT,\n label: 'Escalation reasoning',\n isNullable: true,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_STATUS_UID,\n name: 'status',\n type: FieldType.SELECT,\n label: 'Status',\n isNullable: false,\n options: ['ok', 'error'],\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_ERROR_UID,\n name: 'error',\n type: FieldType.TEXT,\n label: 'Error',\n isNullable: true,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_RUN_ID_UID,\n name: 'runId',\n type: FieldType.TEXT,\n label: 'Run id',\n description: 'The application run this decision was made under.',\n isNullable: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID,\n name: 'subjectRenamed',\n type: FieldType.BOOLEAN,\n label: 'Subject renamed',\n isNullable: false,\n defaultValue: false,\n },\n ],\n indexes: [\n { universalIdentifier: TRIAGE_DECISION_INDEX_TICKET_ID_UID, fields: ['ticketId'] },\n { universalIdentifier: TRIAGE_DECISION_INDEX_DECIDED_AT_UID, fields: ['decidedAt'] },\n { universalIdentifier: TRIAGE_DECISION_INDEX_ESCALATED_UID, fields: ['escalated'] },\n ],\n };\n}\n","/**\n * `generated-response` (ex-`FastResponse`) — spec §3.4. Both the send queue\n * and the response cache.\n *\n * `status`'s option list is `GENERATED_RESPONSE_STATUSES` from\n * `../status/machine` — the single source of truth T16 already built for the\n * status vocabulary and its terminal/open partition — rather than a second\n * hardcoded list that could drift from it.\n *\n * `openTicketKey` reconstitutes the legacy \"one open job per ticket\"\n * guarantee as a Postgres unique index (NULLs are distinct): it is\n * `openTicketKeyFor(status, ticketId)` at write time (a T22+ handler\n * concern), so this definition intentionally does NOT restate which statuses\n * count as \"open\" — it only declares the field and its unique index.\n *\n * `autoSendDecision` is the field `reclaimStalledSend()` (T16) writes into\n * alongside `status: 'ready'` on the sweep's stalled-send reclaim.\n *\n * `expiresAt` is non-nullable: it is `generatedAt + responseTtlMinutes`,\n * known at creation time, and the sweep (`ready` expired -> `expired`, T22)\n * plus the extension's TTL check both read it unconditionally — a null there\n * would be a row that never expires.\n *\n * The JSON LIST fields (`sources`, `tracedInput`, `guardrailHits`,\n * `servedTo`) are non-nullable with a `[]` default, so no reader has to\n * distinguish \"null\" from \"empty\" before iterating; the single-object\n * `verdict` stays nullable, where `null` really does mean \"not evaluated\".\n *\n * T22 additions (all nullable — absent until the field's own write path\n * runs):\n * - `generatedMessageCount`/`generatedLastMessageAt` — a snapshot of\n * `Conversation.messageCount`/`lastMessageAt` taken by `process-response`\n * right before `runTicket`'s resumed run. `handle-approval` rebuilds a\n * placeholder `Conversation` for the `act` node's `generatedFrom`\n * argument out of exactly these two fields (plus `channel`) — see\n * `functions/handle-approval.ts` for why `act` never reads anything else\n * off that snapshot. This is a \"close enough\" generation-time reading,\n * not a live one: `act` always re-reads the conversation for real before\n * posting (I8), so a slightly stale baseline here only affects whether\n * THAT re-read counts as diverged, never send safety itself.\n * - `sendingAt` — when the record entered `status: 'sending'` (written by\n * the claim in `functions/claim-commit.ts`). Nothing else on this record\n * timestamps a status transition, and `sweep` needs to know how long a\n * `sending` row has been stuck to reclaim it (§3.5's 30-minute rule).\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport { GENERATED_RESPONSE_STATUSES } from '../status/machine';\nimport {\n GENERATED_RESPONSE_OBJECT_UID,\n GENERATED_RESPONSE_FIELD_TICKET_ID_UID,\n GENERATED_RESPONSE_FIELD_OPEN_TICKET_KEY_UID,\n GENERATED_RESPONSE_FIELD_STATUS_UID,\n GENERATED_RESPONSE_FIELD_TRIAGE_DECISION_ID_UID,\n GENERATED_RESPONSE_FIELD_CATEGORY_ID_UID,\n GENERATED_RESPONSE_FIELD_AGENT_ID_UID,\n GENERATED_RESPONSE_FIELD_CHANNEL_UID,\n GENERATED_RESPONSE_FIELD_RESPONSE_TEXT_UID,\n GENERATED_RESPONSE_FIELD_SOURCES_UID,\n GENERATED_RESPONSE_FIELD_TRACED_INPUT_UID,\n GENERATED_RESPONSE_FIELD_VERDICT_UID,\n GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_UID,\n GENERATED_RESPONSE_FIELD_AUTO_SEND_DECISION_UID,\n GENERATED_RESPONSE_FIELD_FOLLOWUP_REQUIRED_UID,\n GENERATED_RESPONSE_FIELD_SERVED_COUNT_UID,\n GENERATED_RESPONSE_FIELD_SERVED_TO_UID,\n GENERATED_RESPONSE_FIELD_GENERATED_AT_UID,\n GENERATED_RESPONSE_FIELD_EXPIRES_AT_UID,\n GENERATED_RESPONSE_FIELD_SENT_AT_UID,\n GENERATED_RESPONSE_FIELD_SENT_MESSAGE_ID_UID,\n GENERATED_RESPONSE_FIELD_LANGFUSE_TRACE_ID_UID,\n GENERATED_RESPONSE_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n GENERATED_RESPONSE_FIELD_PROMPT_NAME_UID,\n GENERATED_RESPONSE_FIELD_PROMPT_VERSION_UID,\n GENERATED_RESPONSE_FIELD_ERROR_UID,\n GENERATED_RESPONSE_FIELD_GENERATED_MESSAGE_COUNT_UID,\n GENERATED_RESPONSE_FIELD_GENERATED_LAST_MESSAGE_AT_UID,\n GENERATED_RESPONSE_FIELD_SENDING_AT_UID,\n GENERATED_RESPONSE_INDEX_TICKET_ID_UID,\n GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID,\n GENERATED_RESPONSE_INDEX_STATUS_UID,\n GENERATED_RESPONSE_INDEX_TRIAGE_DECISION_ID_UID,\n GENERATED_RESPONSE_INDEX_GENERATED_AT_UID,\n GENERATED_RESPONSE_INDEX_EXPIRES_AT_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nexport function buildGeneratedResponseRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: GENERATED_RESPONSE_OBJECT_UID,\n objectKey: 'generated-response',\n labelSingular: 'Generated response',\n labelPlural: 'Generated responses',\n description: 'A drafted reply, from pending draft through its send outcome.',\n fields: [\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_TICKET_ID_UID,\n name: 'ticketId',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: false,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_OPEN_TICKET_KEY_UID,\n name: 'openTicketKey',\n type: FieldType.TEXT,\n label: 'Open ticket key',\n description: \"= ticketId while status is open, cleared on a terminal status. Unique — see openTicketKeyFor().\",\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_STATUS_UID,\n name: 'status',\n type: FieldType.SELECT,\n label: 'Status',\n isNullable: false,\n options: [...GENERATED_RESPONSE_STATUSES],\n defaultValue: 'pending',\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_TRIAGE_DECISION_ID_UID,\n name: 'triageDecisionId',\n type: FieldType.RELATION,\n label: 'Triage decision',\n isNullable: false,\n relation: {\n targetRef: targetRefFor(slug, 'triage-decision'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'CASCADE',\n },\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_CATEGORY_ID_UID,\n name: 'categoryId',\n type: FieldType.RELATION,\n label: 'Category',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'category'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_CHANNEL_UID,\n name: 'channel',\n type: FieldType.SELECT,\n label: 'Channel',\n isNullable: false,\n options: ['email', 'whatsapp'],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_RESPONSE_TEXT_UID,\n name: 'responseText',\n type: FieldType.TEXT,\n label: 'Response text',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SOURCES_UID,\n name: 'sources',\n type: FieldType.JSON,\n label: 'Sources',\n description: '[{name, arguments, observation}]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_TRACED_INPUT_UID,\n name: 'tracedInput',\n type: FieldType.JSON,\n label: 'Traced input',\n description: '[{role, content}]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_VERDICT_UID,\n name: 'verdict',\n type: FieldType.JSON,\n label: 'Verdict',\n description: '{verdict, confidence, reason, status}',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_UID,\n name: 'guardrailHits',\n type: FieldType.JSON,\n label: 'Guardrail hits',\n description: 'string[]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_AUTO_SEND_DECISION_UID,\n name: 'autoSendDecision',\n type: FieldType.SELECT,\n label: 'Auto-send decision',\n isNullable: true,\n options: ['auto', 'hold'],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_FOLLOWUP_REQUIRED_UID,\n name: 'followupRequired',\n type: FieldType.BOOLEAN,\n label: 'Followup required',\n isNullable: false,\n defaultValue: false,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SERVED_COUNT_UID,\n name: 'servedCount',\n type: FieldType.NUMBER,\n label: 'Served count',\n isNullable: false,\n defaultValue: 0,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SERVED_TO_UID,\n name: 'servedTo',\n type: FieldType.JSON,\n label: 'Served to',\n description: '[{user, at}], capped at 500 entries. Updated via S5 ifMatch + retry.',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_GENERATED_AT_UID,\n name: 'generatedAt',\n type: FieldType.DATE_TIME,\n label: 'Generated at',\n description: 'Backs the daily series stat.',\n isNullable: false,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_EXPIRES_AT_UID,\n name: 'expiresAt',\n type: FieldType.DATE_TIME,\n label: 'Expires at',\n isNullable: false,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SENT_AT_UID,\n name: 'sentAt',\n type: FieldType.DATE_TIME,\n label: 'Sent at',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SENT_MESSAGE_ID_UID,\n name: 'sentMessageId',\n type: FieldType.TEXT,\n label: 'Sent message id',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_LANGFUSE_TRACE_ID_UID,\n name: 'langfuseTraceId',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuseObservationId',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_PROMPT_VERSION_UID,\n name: 'promptVersion',\n type: FieldType.NUMBER,\n label: 'Prompt version',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_ERROR_UID,\n name: 'error',\n type: FieldType.TEXT,\n label: 'Error',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_GENERATED_MESSAGE_COUNT_UID,\n name: 'generatedMessageCount',\n type: FieldType.NUMBER,\n label: 'Generated message count',\n description: \"Conversation.messageCount snapshot at generation time — act()'s divergence baseline when replayed via handle-approval.\",\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_GENERATED_LAST_MESSAGE_AT_UID,\n name: 'generatedLastMessageAt',\n type: FieldType.DATE_TIME,\n label: 'Generated last message at',\n description: \"Conversation.lastMessageAt snapshot at generation time — act()'s divergence baseline when replayed via handle-approval.\",\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SENDING_AT_UID,\n name: 'sendingAt',\n type: FieldType.DATE_TIME,\n label: 'Sending at',\n description: \"When status became 'sending' — the sweep's staleness clock (§3.5).\",\n isNullable: true,\n },\n ],\n indexes: [\n { universalIdentifier: GENERATED_RESPONSE_INDEX_TICKET_ID_UID, fields: ['ticketId'] },\n {\n universalIdentifier: GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID,\n fields: ['openTicketKey'],\n isUnique: true,\n },\n { universalIdentifier: GENERATED_RESPONSE_INDEX_STATUS_UID, fields: ['status'] },\n {\n universalIdentifier: GENERATED_RESPONSE_INDEX_TRIAGE_DECISION_ID_UID,\n fields: ['triageDecisionId'],\n isUnique: true,\n },\n { universalIdentifier: GENERATED_RESPONSE_INDEX_GENERATED_AT_UID, fields: ['generatedAt'] },\n { universalIdentifier: GENERATED_RESPONSE_INDEX_EXPIRES_AT_UID, fields: ['expiresAt'] },\n ],\n };\n}\n","/** `response-comparison` (ex-`ResponseComparison`) — spec §3.4. */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n RESPONSE_COMPARISON_OBJECT_UID,\n RESPONSE_COMPARISON_FIELD_GENERATED_TEXT_UID,\n RESPONSE_COMPARISON_FIELD_SENT_TEXT_UID,\n RESPONSE_COMPARISON_FIELD_CAPTURED_AT_UID,\n RESPONSE_COMPARISON_FIELD_TICKET_ID_UID,\n RESPONSE_COMPARISON_FIELD_TICKET_URL_UID,\n RESPONSE_COMPARISON_FIELD_AGENT_ID_UID,\n RESPONSE_COMPARISON_FIELD_LANGFUSE_TRACE_ID_UID,\n RESPONSE_COMPARISON_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n RESPONSE_COMPARISON_FIELD_PROMPT_NAME_UID,\n RESPONSE_COMPARISON_FIELD_PROMPT_VERSION_UID,\n RESPONSE_COMPARISON_FIELD_CONVERSATION_MESSAGES_UID,\n RESPONSE_COMPARISON_FIELD_DIFF_UID,\n RESPONSE_COMPARISON_INDEX_CAPTURED_AT_UID,\n RESPONSE_COMPARISON_INDEX_TICKET_ID_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nexport function buildResponseComparisonRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: RESPONSE_COMPARISON_OBJECT_UID,\n objectKey: 'response-comparison',\n labelSingular: 'Response comparison',\n labelPlural: 'Response comparisons',\n description: \"Compares the agent's draft against what the human actually sent.\",\n fields: [\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_GENERATED_TEXT_UID,\n name: 'generatedText',\n type: FieldType.TEXT,\n label: 'Generated text',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_SENT_TEXT_UID,\n name: 'sentText',\n type: FieldType.TEXT,\n label: 'Sent text',\n isNullable: false,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_CAPTURED_AT_UID,\n name: 'capturedAt',\n type: FieldType.DATE_TIME,\n label: 'Captured at',\n description: 'Backs the rewrite-rate trend.',\n isNullable: false,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_TICKET_ID_UID,\n name: 'ticketId',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_TICKET_URL_UID,\n name: 'ticketUrl',\n type: FieldType.TEXT,\n label: 'Ticket URL',\n isNullable: false,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_LANGFUSE_TRACE_ID_UID,\n name: 'langfuseTraceId',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuseObservationId',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_PROMPT_VERSION_UID,\n name: 'promptVersion',\n type: FieldType.NUMBER,\n label: 'Prompt version',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_CONVERSATION_MESSAGES_UID,\n name: 'conversationMessages',\n type: FieldType.JSON,\n label: 'Conversation messages',\n description: '[{role, content}]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_DIFF_UID,\n name: 'diff',\n type: FieldType.JSON,\n label: 'Diff',\n description: 'Word-by-word diff, computed at write time.',\n isNullable: true,\n },\n ],\n indexes: [\n { universalIdentifier: RESPONSE_COMPARISON_INDEX_CAPTURED_AT_UID, fields: ['capturedAt'] },\n { universalIdentifier: RESPONSE_COMPARISON_INDEX_TICKET_ID_UID, fields: ['ticketId'] },\n ],\n };\n}\n","/** `evaluation` (ex-`Evaluation`) — spec §3.4. No indexes named for this record. */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n EVALUATION_OBJECT_UID,\n EVALUATION_FIELD_AGENT_ID_UID,\n EVALUATION_FIELD_SATISFIED_UID,\n EVALUATION_FIELD_MESSAGES_UID,\n EVALUATION_FIELD_TICKET_URL_UID,\n EVALUATION_FIELD_LANGFUSE_TRACE_ID_UID,\n EVALUATION_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n EVALUATION_FIELD_SUPPORT_USER_KEY_ID_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nexport function buildEvaluationRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: EVALUATION_OBJECT_UID,\n objectKey: 'evaluation',\n labelSingular: 'Evaluation',\n labelPlural: 'Evaluations',\n description: 'A human satisfaction verdict on an agent conversation.',\n fields: [\n {\n universalIdentifier: EVALUATION_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: false,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'CASCADE',\n },\n },\n {\n universalIdentifier: EVALUATION_FIELD_SATISFIED_UID,\n name: 'satisfied',\n type: FieldType.BOOLEAN,\n label: 'Satisfied',\n isNullable: false,\n },\n {\n universalIdentifier: EVALUATION_FIELD_MESSAGES_UID,\n name: 'messages',\n type: FieldType.JSON,\n label: 'Messages',\n description: '[{role, content}] — the conversation the verdict is about.',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: EVALUATION_FIELD_TICKET_URL_UID,\n name: 'ticketUrl',\n type: FieldType.TEXT,\n label: 'Ticket URL',\n isNullable: false,\n },\n {\n universalIdentifier: EVALUATION_FIELD_LANGFUSE_TRACE_ID_UID,\n name: 'langfuseTraceId',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n },\n {\n universalIdentifier: EVALUATION_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuseObservationId',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n },\n {\n universalIdentifier: EVALUATION_FIELD_SUPPORT_USER_KEY_ID_UID,\n name: 'supportUserKeyId',\n type: FieldType.TEXT,\n label: 'Support user key id',\n isNullable: true,\n },\n ],\n };\n}\n","/**\n * `diff-analysis` (ex-`DiffAnalysis`) — spec §3.4.\n *\n * `uniqueKey` is `<agentId>::<promptName>::<promptVersion>`, computed by the\n * write handler (T22+) — this definition only declares the field and its\n * unique index, the equivalent of the legacy composite uniqueness.\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n DIFF_ANALYSIS_OBJECT_UID,\n DIFF_ANALYSIS_FIELD_AGENT_ID_UID,\n DIFF_ANALYSIS_FIELD_PROMPT_NAME_UID,\n DIFF_ANALYSIS_FIELD_PROMPT_VERSION_UID,\n DIFF_ANALYSIS_FIELD_POINTS_UID,\n DIFF_ANALYSIS_FIELD_UNIQUE_KEY_UID,\n DIFF_ANALYSIS_INDEX_UNIQUE_KEY_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\n/** `<agentId>::<promptName>::<promptVersion>` — spec §3.4. */\nexport function diffAnalysisUniqueKey(\n agentId: string,\n promptName: string,\n promptVersion: number,\n): string {\n return `${agentId}::${promptName}::${promptVersion}`;\n}\n\nexport function buildDiffAnalysisRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: DIFF_ANALYSIS_OBJECT_UID,\n objectKey: 'diff-analysis',\n labelSingular: 'Diff analysis',\n labelPlural: 'Diff analyses',\n description: 'Correction patterns aggregated for one (agent, prompt, version).',\n fields: [\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: false,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'CASCADE',\n },\n },\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: false,\n },\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_PROMPT_VERSION_UID,\n name: 'promptVersion',\n type: FieldType.NUMBER,\n label: 'Prompt version',\n isNullable: false,\n },\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_POINTS_UID,\n name: 'points',\n type: FieldType.JSON,\n label: 'Points',\n description: 'string[]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_UNIQUE_KEY_UID,\n name: 'uniqueKey',\n type: FieldType.TEXT,\n label: 'Unique key',\n description: '<agentId>::<promptName>::<promptVersion>',\n isNullable: false,\n },\n ],\n indexes: [\n { universalIdentifier: DIFF_ANALYSIS_INDEX_UNIQUE_KEY_UID, fields: ['uniqueKey'], isUnique: true },\n ],\n };\n}\n","/**\n * `pipeline-state` — spec §3.4. Singleton per app; the kit's sole inter-app\n * contact point, read-only (`exposedToApps: ['*']`), purely informational —\n * §4's cross-app view-claim warning is what another app reads `sourceViewId`\n * for, to detect when two support-kit apps have been pointed at the same\n * Gorgias view.\n *\n * `sourceViewId` here mirrors the setting of the same name (§3.6) — it is\n * written by `triage-tick` (T22+), not by this definition.\n *\n * `singletonKey` (T22 hardening, A4 — a schema addition past §3.4's frozen\n * list, recorded as a deviation in the progress doc): `triage-tick` and\n * `sweep` are two independent crons that both fire every five minutes, and\n * on a fresh app both used to find the `list()` empty and both `create()` a\n * \"singleton\" row — nothing enforced only one existing, and `list` carries\n * no ordering guarantee, so `triage-tick` could thereafter read the\n * sweep-created row (no `lastTriageAt`) and silently skip its own cadence\n * gate on EVERY tick. A constant, always-the-same value plus a real unique\n * index turns \"singleton by convention\" into \"singleton by constraint\": both\n * functions now `upsert` on this key (`functions/pipeline-state.ts`), so the\n * platform's own `ON CONFLICT` — not a race between two `list()`+`create()`\n * pairs — is what decides there is exactly one row.\n */\nimport { FieldType } from '@apotech-os/app-kit';\nimport type { RecordDef } from './record-def';\nimport {\n PIPELINE_STATE_OBJECT_UID,\n PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID,\n PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID,\n PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID,\n PIPELINE_STATE_FIELD_SINGLETON_KEY_UID,\n PIPELINE_STATE_INDEX_SINGLETON_KEY_UID,\n} from './ids';\n\nexport const pipelineStateRecord: RecordDef = {\n universalIdentifier: PIPELINE_STATE_OBJECT_UID,\n objectKey: 'pipeline-state',\n labelSingular: 'Pipeline state',\n labelPlural: 'Pipeline state',\n description: 'Singleton run-cadence and view-claim state, readable by every installed app.',\n fields: [\n {\n universalIdentifier: PIPELINE_STATE_FIELD_SINGLETON_KEY_UID,\n name: 'singletonKey',\n type: FieldType.TEXT,\n label: 'Singleton key',\n description: 'Always the same constant value — the unique index below is what makes this record a true singleton, not just a convention.',\n isNullable: false,\n },\n {\n universalIdentifier: PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID,\n name: 'sourceViewId',\n type: FieldType.TEXT,\n label: 'Source view id',\n description: 'The claimed Gorgias view — supports the cross-app overlap warning (§4).',\n isNullable: true,\n },\n {\n universalIdentifier: PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID,\n name: 'lastTriageAt',\n type: FieldType.DATE_TIME,\n label: 'Last triage at',\n description: \"Gates triage-tick's cadence.\",\n isNullable: true,\n },\n {\n universalIdentifier: PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID,\n name: 'lastSweepAt',\n type: FieldType.DATE_TIME,\n label: 'Last sweep at',\n isNullable: true,\n },\n ],\n indexes: [{ universalIdentifier: PIPELINE_STATE_INDEX_SINGLETON_KEY_UID, fields: ['singletonKey'], isUnique: true }],\n exposedToApps: ['*'],\n};\n","/**\n * `prompt-cache` (ex-`PromptCache`) — spec §3.4, level-2 fallback of the\n * prompt ladder (§3.7).\n *\n * `config JSON?` — added beyond the spec's literal field list, on T19's\n * explicit deferral: the legacy cache carried the model config (not just the\n * compiled template), so invariant I16 (\"levels 2/3 keep working through a\n * Langfuse outage\") holds for the *prompt text* but not for the *config* a\n * caller needs alongside it — levels 2 and 3 of the resolver (T19) return\n * `config: null` today. Adding the column here is the minimal step: it makes\n * the record ABLE to carry a config without deciding its shape or wiring it\n * into the resolver. Follow-up (not T20): change `prompts/resolver.ts` to\n * read and write this column, and settle what \"config\" means for a cache row\n * (presumably the same `{model, reasoning}` shape used by `settings.nodes`).\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n PROMPT_CACHE_OBJECT_UID,\n PROMPT_CACHE_FIELD_PROMPT_KEY_UID,\n PROMPT_CACHE_FIELD_CONTENT_UID,\n PROMPT_CACHE_FIELD_VERSION_UID,\n PROMPT_CACHE_FIELD_LABEL_UID,\n PROMPT_CACHE_FIELD_CONFIG_UID,\n PROMPT_CACHE_INDEX_PROMPT_KEY_UID,\n} from './ids';\n\nexport const promptCacheRecord: ObjectDef = {\n universalIdentifier: PROMPT_CACHE_OBJECT_UID,\n objectKey: 'prompt-cache',\n labelSingular: 'Prompt cache entry',\n labelPlural: 'Prompt cache entries',\n description: 'Last-known-good snapshot of a Langfuse prompt, for the resolver fallback ladder.',\n fields: [\n {\n universalIdentifier: PROMPT_CACHE_FIELD_PROMPT_KEY_UID,\n name: 'promptKey',\n type: FieldType.TEXT,\n label: 'Prompt key',\n description: \"'name' or 'name::label'.\",\n isNullable: false,\n },\n {\n universalIdentifier: PROMPT_CACHE_FIELD_CONTENT_UID,\n name: 'content',\n type: FieldType.TEXT,\n label: 'Content',\n description: 'Raw, uncompiled template.',\n isNullable: false,\n },\n {\n universalIdentifier: PROMPT_CACHE_FIELD_VERSION_UID,\n name: 'version',\n type: FieldType.NUMBER,\n label: 'Version',\n isNullable: false,\n },\n {\n universalIdentifier: PROMPT_CACHE_FIELD_LABEL_UID,\n name: 'label',\n type: FieldType.TEXT,\n label: 'Label',\n isNullable: true,\n },\n {\n universalIdentifier: PROMPT_CACHE_FIELD_CONFIG_UID,\n name: 'config',\n type: FieldType.JSON,\n label: 'Config',\n description: 'Model config snapshot, for I16. Not yet written or read — see module doc.',\n isNullable: true,\n },\n ],\n indexes: [{ universalIdentifier: PROMPT_CACHE_INDEX_PROMPT_KEY_UID, fields: ['promptKey'], isUnique: true }],\n};\n","import { createHash } from 'node:crypto';\n\n/**\n * Kit-owned namespace UUID (RFC 4122 §4.3) — fixed and arbitrary, used only\n * as `deriveUid`'s namespace input. Never written to a manifest itself.\n */\nconst SUPPORT_KIT_UID_NAMESPACE = '2b6a9c0e-6c1e-4c1a-8b0e-2a2f4b8c9d3f';\n\nfunction uuidToBytes(uuid: string): Buffer {\n return Buffer.from(uuid.replace(/-/g, ''), 'hex');\n}\n\nfunction bytesToUuid(bytes: Buffer): string {\n const hex = bytes.toString('hex');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/**\n * A deterministic UUIDv5 over `seed` (RFC 4122 §4.3: SHA-1 of a namespace +\n * a name, with the version/variant bits fixed up). Same seed always yields\n * the same uid — no randomness, no `Date` — and different seeds yield\n * different uids with cryptographic collision resistance.\n *\n * Used by `scopeRecordToApp` (B1, T25 review) to turn the kit's own stable\n * per-record constants (`ids.ts`) into uids that are additionally scoped to\n * the consuming app's slug, so two different apps installing the same kit\n * never collide on `AppEntity.universalIdentifier` (globally unique on the\n * platform, not per application).\n */\nexport function deriveUid(seed: string): string {\n const hash = createHash('sha1').update(uuidToBytes(SUPPORT_KIT_UID_NAMESPACE)).update(seed, 'utf8').digest();\n const bytes = hash.subarray(0, 16);\n bytes[6] = (bytes[6]! & 0x0f) | 0x50; // version 5\n bytes[8] = (bytes[8]! & 0x3f) | 0x80; // variant RFC4122\n return bytesToUuid(bytes);\n}\n","import { deriveUid } from './derive-uid';\nimport type { RecordDef } from './record-def';\n\n/**\n * Rewrites every `universalIdentifier` in a kit record (object, fields,\n * indexes) from the kit's own stable constant (`ids.ts`) into one\n * deterministically derived from `(slug, that constant)` — B1, T25 review.\n *\n * Why: `ids.ts`'s constants are unique AMONG THEMSELVES, but the platform's\n * `AppEntity.universalIdentifier` is unique GLOBALLY, not per application\n * (`apps/api/prisma/schema.prisma`). Used as-is, the second app to install\n * this kit republishes the same 126 literals the first app already claimed\n * and hits an unhandled Prisma P2002 on publish. Scoping by slug keeps every\n * uid stable across rebuilds (pure function of the slug + the constant, no\n * randomness) while making two different consuming apps' uid sets disjoint.\n */\nexport function scopeRecordToApp(slug: string, record: RecordDef): RecordDef {\n return {\n ...record,\n universalIdentifier: deriveUid(`${slug}:${record.universalIdentifier}`),\n fields: record.fields.map((field) => ({\n ...field,\n universalIdentifier: deriveUid(`${slug}:${field.universalIdentifier}`),\n })),\n indexes: record.indexes?.map((index) => ({\n ...index,\n universalIdentifier: deriveUid(`${slug}:${index.universalIdentifier}`),\n })),\n };\n}\n","// Spec: spec-migration-gorgias-backoffice-v1.md §3.4 — the kit's own\n// `ObjectDef` fragments, one module per record, assembled here into the\n// array a consuming app's manifest spreads into its own `records: [...]`.\n//\n// Every record that declares a RELATION is a factory over the consuming\n// app's slug (§3.2's `config.slug`), because a relation's `targetRef` is\n// `app:<slug>/<objectKey>` and the kit is installed as `experience-client`,\n// `pro-sante`, … — never as `support-kit`. The four records with no\n// relation stay plain constants: nothing about them varies per app.\nexport { buildCategoryRecord } from './category';\nexport { categoryGroupRecord } from './category-group';\nexport { agentRecord, AGENT_STATUSES, DEFAULT_LLM_PROVIDER, type AgentStatus } from './agent';\nexport { buildTriageDecisionRecord } from './triage-decision';\nexport { buildGeneratedResponseRecord } from './generated-response';\nexport { buildResponseComparisonRecord } from './response-comparison';\nexport { buildEvaluationRecord } from './evaluation';\nexport { buildDiffAnalysisRecord, diffAnalysisUniqueKey } from './diff-analysis';\nexport { pipelineStateRecord } from './pipeline-state';\nexport { promptCacheRecord } from './prompt-cache';\nexport { targetRefFor } from './target-ref';\nexport type { RecordDef } from './record-def';\n\nimport { buildCategoryRecord } from './category';\nimport { categoryGroupRecord } from './category-group';\nimport { agentRecord } from './agent';\nimport { buildTriageDecisionRecord } from './triage-decision';\nimport { buildGeneratedResponseRecord } from './generated-response';\nimport { buildResponseComparisonRecord } from './response-comparison';\nimport { buildEvaluationRecord } from './evaluation';\nimport { buildDiffAnalysisRecord } from './diff-analysis';\nimport { pipelineStateRecord } from './pipeline-state';\nimport { promptCacheRecord } from './prompt-cache';\nimport { scopeRecordToApp } from './scope-to-app';\nimport type { RecordDef } from './record-def';\n\n/**\n * All 10 records of §3.4, in the order the spec lists them, bound to the\n * consuming app's `slug` — the single assembly point `buildSupportPipeline`\n * (T25) spreads into a manifest.\n *\n * Every record/field/index `universalIdentifier` is additionally scoped to\n * `slug` via `scopeRecordToApp` (B1, T25 review): `ids.ts`'s constants are\n * stable per-record keys, not final manifest uids — two different consuming\n * apps installing this kit must never publish the same\n * `AppEntity.universalIdentifier` (unique platform-wide).\n */\nexport function buildSupportKitRecords(slug: string): RecordDef[] {\n return [\n buildCategoryRecord(slug),\n categoryGroupRecord,\n agentRecord,\n buildTriageDecisionRecord(slug),\n buildGeneratedResponseRecord(slug),\n buildResponseComparisonRecord(slug),\n buildEvaluationRecord(slug),\n buildDiffAnalysisRecord(slug),\n pipelineStateRecord,\n promptCacheRecord,\n ].map((record) => scopeRecordToApp(slug, record));\n}\n","/**\n * `SupportKitFunctionConfig` — what each of the four T22 manifest fragments\n * (`triage-tick`/`process-response`/`sweep`/`handle-approval`) needs to\n * build its `FunctionDef` (spec §3.2's `SupportPipelineConfig`, the slice of\n * it these fragments actually read — `buildSupportPipeline`, T25, owns the\n * full shape and passes this down).\n */\nimport type { PromptNameConfig } from '../prompts/slots';\n\n/** Stable keys this module looks up `identifiers` by — documented here so a caller can't guess wrong. */\nexport const FUNCTION_IDENTIFIER_KEYS = [\n 'triage-tick',\n 'process-response',\n 'sweep',\n 'handle-approval',\n // T23 — the seven operator `uiInvoke` functions (§3.5's table).\n 'run-triage-now',\n // B5 — the event-triggered worker `run-triage-now` hands the batch to, so\n // the manual trigger answers inside its `uiInvoke` budget instead of\n // 504-ing halfway through a 30-ticket LLM pass (`run-triage-now.ts`'s doc).\n 'run-triage-batch',\n 'preview-triage',\n 'graph-dry-run',\n 'test-agents',\n 'suggest-prompt',\n 'run-diff-analysis',\n 'list-gorgias-views',\n // T26 rework — AgentsPage cannot create a valid agent or promote a default\n // one from raw record PATCHes alone (BLOCKER 3, BLOCKER 4); both are\n // write-handler concerns per records/agent.ts's own doc.\n 'create-agent',\n 'set-default-agent',\n // T27 part B — SharedPromptsPage's own write path: validates\n // `@@@langfusePrompt:…@@@` composition (`validateReferences`) before\n // writing a `shared/*` version, a check the raw S3 REST route does not run.\n 'create-shared-prompt-version',\n // §5.2 — `GET /models` serves `system_prompt` from `systemPromptSnapshot`\n // alone, so that snapshot has to be refreshed whenever a new version of an\n // agent's prompt starts being served.\n 'sync-agent-prompt-snapshot',\n // T24 — the six reserved `ext-*` functions (§5.2), the extension gateway's\n // only view of the kit.\n 'ext-models',\n 'ext-categories',\n 'ext-chat',\n 'ext-fast-response-check',\n 'ext-evaluation',\n 'ext-response-comparison',\n] as const;\n\nexport type FunctionIdentifierKey = (typeof FUNCTION_IDENTIFIER_KEYS)[number];\n\nexport interface SupportKitFunctionConfig extends PromptNameConfig {\n /** The consuming app's own slug — `app:<slug>/<objectKey>` dbEvent triggers, and the object relations. */\n slug: string;\n /**\n * §3.2's `SupportPipelineConfig.identifiers` — one `universalIdentifier`\n * per manifest function, keyed by the values in `FUNCTION_IDENTIFIER_KEYS`.\n * A manifest fragment with a missing id is broken by construction: looking\n * one up throws immediately rather than inventing a random one that would\n * drift on every rebuild.\n */\n identifiers: Record<string, string>;\n}\n\n/** Looks up `config.identifiers[key]`, throwing loudly on a missing entry (a broken manifest, not a runtime condition to recover from). */\nexport function identifierFor(config: SupportKitFunctionConfig, key: FunctionIdentifierKey): string {\n const id = config.identifiers[key];\n if (!id) {\n throw new Error(\n `SupportKitFunctionConfig.identifiers is missing a universalIdentifier for \"${key}\" — every support-kit function needs a stable id.`,\n );\n }\n return id;\n}\n","/**\n * Derives the kit's domain `Conversation` from the SINGLE\n * `getTicketWithContext` fetch (`ctx-ports.ts`'s\n * `createGorgiasConversationPort`; B, T21 review), which returns both:\n *\n * - the RAW payload the guardrail detectors need (`isWhatsappTicket`,\n * `isJudgemeTicket`, `isAutomatedSenderTicket`, `isTicketClosed`,\n * `hasCustomerAttachment` — `guardrails/raw-ticket.ts`) and this\n * module's own message-count/timestamp snapshot.\n * - the ALREADY-EXTRACTED chronological messages + customer-info block a\n * node actually drafts against — its HTML-to-text conversion and\n * \"Information Client\" synthetic prefix are Gorgias-specific rendering\n * this package does not re-derive.\n *\n * `getRawTicket` and `buildTicketContext` used to be called as two separate\n * actions reading the exact same Gorgias endpoint (§S1) — a `read()` call\n * paid for it twice, and worse, the two fetches could observe different\n * server states if a message landed between them. `getTicketWithContext`\n * (`@wopilo/gorgias-client`) fetches once and derives both halves from that\n * one payload, so the raw-based facts and the domain conversation are now\n * GUARANTEED — not just assumed — to describe the exact same server\n * response.\n */\nimport {\n hasCustomerAttachment,\n isTicketClosed,\n isWhatsappChevronNote,\n isWhatsappTicket,\n type RawTicket,\n} from '../guardrails';\nimport type { Conversation, ConversationRef, Message } from '../domain';\n\ntype RawMessage = NonNullable<RawTicket['messages']>[number];\n\n/** One turn of `buildTicketContext`'s already-extracted conversation. */\nexport interface RawTicketContextMessage {\n role: 'user' | 'assistant' | 'system';\n content: string;\n synthetic?: boolean;\n}\n\n/** The shape `ctx.api.integrations.run('gorgias', 'buildTicketContext', …)` returns. */\nexport interface RawTicketContext {\n messages: RawTicketContextMessage[];\n customerContext: string | null;\n customerName?: string | null;\n customerEmail?: string | null;\n}\n\n/**\n * Same predicate `guardrails/raw-ticket.ts` uses internally, un-exported\n * there. Duplicated here BY HAND, same precedent that module's own doc\n * gives for its copy of `@wopilo/gorgias-client`'s `isInternalNoteChannel`:\n * this package may not import that client, so the one-line rule is kept in\n * sync manually rather than reached for through a forbidden import.\n */\nfunction isInternalNoteChannel(message: RawMessage): boolean {\n return message.channel === 'internal-note' || message.source?.type === 'internal-note';\n}\n\n/**\n * Port of `@wopilo/gorgias-client`'s `countableMessages` (`ticket-context.ts`)\n * — the divergence-snapshot rule. This package cannot import that package\n * (dependency-allowlist), so it is kept in sync by hand.\n *\n * \"Has extractable text\" checks PRESENCE across `body_text`/`body_html`/\n * `stripped_text`/`stripped_html` — not conversion. The client's own\n * `extractMessageText` prefers HTML and runs it through `htmlToText`\n * (T3-review-A5: an HTML-only customer reply has a blank `body_text`, so\n * checking that field alone misses a real turn — invisible to\n * `Conversation.messageCount`/`lastMessageAt`, so `act`'s divergence check\n * never sees the customer replied and a stale draft gets auto-sent). This\n * package cannot port `htmlToText` in, so it stays on the SAFE side instead:\n * any non-blank field counts, even a `<br>`-only body that `htmlToText`\n * would reduce to nothing. That can only ever over-count — producing a\n * spurious *hold*, never a spurious send.\n */\nfunction countableMessages(messages: RawMessage[], isWhatsapp: boolean): RawMessage[] {\n return messages.filter((m) => {\n if (isInternalNoteChannel(m)) return isWhatsappChevronNote(m, isWhatsapp);\n const hasText = !!(m.body_text?.trim() || m.body_html?.trim() || m.stripped_text?.trim() || m.stripped_html?.trim());\n const hasAttachment = (m.attachments?.length ?? 0) > 0;\n return hasText || hasAttachment;\n });\n}\n\nexport interface ConversationSnapshot {\n count: number;\n lastAt: Date | null;\n}\n\n/** Message count + last-message timestamp — feeds `Conversation.messageCount`/`lastMessageAt` (I8's anti-divergence snapshot). */\nexport function snapshotConversation(raw: RawTicket): ConversationSnapshot {\n const isWhatsapp = isWhatsappTicket(raw);\n const messages = countableMessages(raw.messages ?? [], isWhatsapp);\n let lastAt: Date | null = null;\n for (const m of messages) {\n if (!m.created_datetime) continue;\n const at = new Date(m.created_datetime);\n if (!lastAt || at > lastAt) lastAt = at;\n }\n return { count: messages.length, lastAt };\n}\n\n/**\n * When an agent (human or our own auto-reply) last spoke. Deliberately\n * applies NO countability/text test of its own — it follows\n * `raw-ticket.ts`'s `hasAgentReplySince` (channel/chevron rule only),\n * generalised from a boolean since-a-date check to the timestamp itself,\n * since `Conversation.lastAgentReplyAt` needs the value, not a threshold.\n * That is the safe direction: an agent message with no extractable text\n * still counts as \"the agent spoke\", so this never under-reports the last\n * agent activity.\n */\nfunction lastAgentReplyAtOf(raw: RawTicket): Date | null {\n const isWhatsapp = isWhatsappTicket(raw);\n let latest: Date | null = null;\n for (const m of raw.messages ?? []) {\n if (m.from_agent !== true) continue;\n if (isInternalNoteChannel(m) && !isWhatsappChevronNote(m, isWhatsapp)) continue;\n if (!m.created_datetime) continue;\n const at = new Date(m.created_datetime);\n if (!latest || at > latest) latest = at;\n }\n return latest;\n}\n\n/**\n * Assembles the domain `Conversation`. `sourceChannel` honours the T15\n * contract restated in `graph/ports.ts`'s `Conversation` doc: `'whatsapp'`\n * IFF `isWhatsappTicket(raw)`, never a bare `raw.channel` read.\n */\nexport function toConversation(ref: ConversationRef, raw: RawTicket, context: RawTicketContext): Conversation {\n const snapshot = snapshotConversation(raw);\n const messages: Message[] = context.messages\n .filter((m): m is RawTicketContextMessage & { role: 'user' | 'assistant' } => m.role === 'user' || m.role === 'assistant')\n .map((m) => ({ role: m.role, content: m.content }));\n\n return {\n ref,\n subject: raw.subject ?? null,\n messages,\n customer: {\n name: context.customerName ?? null,\n email: context.customerEmail ?? null,\n orderContext: context.customerContext ?? null,\n },\n isClosed: isTicketClosed(raw),\n lastMessageAt: snapshot.lastAt,\n messageCount: snapshot.count,\n lastAgentReplyAt: lastAgentReplyAtOf(raw),\n hasCustomerAttachment: hasCustomerAttachment(raw),\n sourceChannel: isWhatsappTicket(raw) ? 'whatsapp' : (raw.channel ?? null),\n };\n}\n","/**\n * Shared by `ctx-ports.ts`'s real `StatePort.record` and\n * `recording-ports.ts`'s no-op one: the exact tag SET a triage decision\n * materialises, ported from legacy `ClassificationSink.record`\n * (`[category, ...extraTags, handledTag]`, deduplicated). Both need the\n * IDENTICAL computation — the recording port's whole point is to report the\n * tags production WOULD have applied, so a second, drifting copy here would\n * silently defeat that guarantee.\n *\n * The category lookup (`api.list('category', …)`) is a READ, not a write —\n * both the real and the recording `StatePort` perform it for real; only the\n * final `applyTags` call is what the recording port skips.\n */\nimport type { AuditTags } from '../graph/ports';\nimport type { Classification } from '../domain';\nimport type { SupportKitApi } from './api';\n\n/** Trims and deduplicates, in first-seen order, dropping blank entries. */\nexport function dedupeTagNames(tags: ReadonlyArray<string | null | undefined>): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const tag of tags) {\n const trimmed = (tag ?? '').trim();\n if (trimmed && !seen.has(trimmed)) {\n seen.add(trimmed);\n out.push(trimmed);\n }\n }\n return out;\n}\n\n/** The category's own additional tags, resolved by `tagName` — `[]` when no category matches. */\nasync function extraTagsFor(api: SupportKitApi, tagName: string): Promise<string[]> {\n const page = await api.list('category', { filter: { tagName }, limit: 1 });\n const data = page.items[0]?.data as { extraTags?: string[] } | undefined;\n return data?.extraTags ?? [];\n}\n\n/** The deduplicated tag set a triage decision applies: `[category, ...extraTags, handledTag]`. */\nexport async function resolveHandledTags(\n api: SupportKitApi,\n classification: Classification,\n audit: AuditTags,\n): Promise<string[]> {\n const extraTags = await extraTagsFor(api, classification.category);\n return dedupeTagNames([classification.category, ...extraTags, audit.handledTag]);\n}\n","/**\n * Real port implementations on `ctx` (spec §3.3 `adapters/ctx-ports.ts`):\n * Conversation/Reply/State via `ctx.api.integrations.run('gorgias', …)`\n * (S1), Llm via `ctx.api.llm.complete` v2 (S2), Prompt via §3.7's resolver\n * (T19), Clock over the real `Date`.\n *\n * `StatePort` deviation, kept from `graph/ports.ts`'s own header comment:\n * §3.3's table names it \"records\", but its actual traffic here is Gorgias\n * tag/rename calls (`applyTags`/`renameTicket`) — S1 integration writes, not\n * an AppRecord write. The one genuine AppRecord read in this file is\n * `StatePort.record`'s category `extraTags` lookup (`gorgias-tags.ts`).\n */\nimport type {\n ChatMessage,\n ClockPort,\n CompletionRequest,\n CompletionResult,\n ConversationPort,\n LlmPort,\n OutboundReply,\n PromptPort,\n ReplyPort,\n StatePort,\n} from '../graph/ports';\nimport type { ConversationRef } from '../domain';\nimport type { PlatformPromptReader, PromptCachePort, PromptDegradedEvent } from '../prompts/resolver';\nimport { createPromptResolver } from '../prompts/resolver';\nimport type { RawTicket } from '../guardrails';\nimport type { SupportKitApi } from './api';\nimport { toConversation, type RawTicketContext } from './conversation-mapping';\nimport { resolveHandledTags } from './gorgias-tags';\n\nfunction asRawTicket(value: unknown): RawTicket {\n return (value ?? {}) as RawTicket;\n}\n\n// --- ConversationPort --------------------------------------------------------\n\nexport function createGorgiasConversationPort(api: SupportKitApi): ConversationPort {\n return {\n async listPending(source, limit) {\n const tickets = (await api.integrations.run('gorgias', 'fetchTicketsFromView', {\n viewId: source.viewOrTag,\n limit,\n })) as Array<{ id: string | number }>;\n return tickets.map((t) => ({ id: String(t.id), channel: 'gorgias' as const }));\n },\n\n async read(ref: ConversationRef) {\n // ONE fetch (B, T21 review): `getTicketWithContext`\n // (@wopilo/gorgias-client) reads `GET /tickets/:id/` once and derives\n // both the raw payload and the extracted context from that single\n // response — see `conversation-mapping.ts`'s module doc. This used to\n // be two separate actions hitting the same endpoint in parallel,\n // which not only doubled the round trips but let the two halves\n // observe different server states if a message landed between them.\n const result = (await api.integrations.run('gorgias', 'getTicketWithContext', {\n ticketId: ref.id,\n })) as { ticket: unknown; context: RawTicketContext } | null;\n return toConversation(ref, asRawTicket(result?.ticket), result?.context ?? { messages: [], customerContext: null });\n },\n };\n}\n\n// --- ReplyPort ---------------------------------------------------------------\n\n/**\n * `OutboundReply.idempotencyKey` is NOT forwarded: neither `replyEmail` nor\n * `postWhatsappNote` accept it (Gorgias has no idempotency-key concept — see\n * `ReplyPort.post`'s own doc, \"NOT by channel idempotence\"). At-most-once is\n * already guaranteed upstream by the claim→post→commit state machine (I9);\n * this field exists for a FUTURE channel that does support one.\n */\nexport function createGorgiasReplyPort(api: SupportKitApi): ReplyPort {\n return {\n async post(ref: ConversationRef, reply: OutboundReply) {\n if (reply.mode === 'email') {\n const result = (await api.integrations.run('gorgias', 'replyEmail', {\n ticketId: ref.id,\n bodyHtml: reply.bodyHtml,\n bodyText: reply.bodyText,\n senderEmail: reply.fromAddress,\n toAddress: reply.receiverEmail,\n ...(reply.subject !== null ? { subject: reply.subject } : {}),\n ...(reply.receiverName !== null ? { receiverName: reply.receiverName } : {}),\n })) as { messageId: string };\n return { messageId: result.messageId };\n }\n const result = (await api.integrations.run('gorgias', 'postWhatsappNote', {\n ticketId: ref.id,\n text: reply.bodyText,\n })) as { messageId: string };\n return { messageId: result.messageId };\n },\n };\n}\n\n// --- StatePort -----------------------------------------------------------\n\nexport function createGorgiasStatePort(api: SupportKitApi): StatePort {\n return {\n async record(ref, classification, audit) {\n const names = await resolveHandledTags(api, classification, audit);\n if (names.length === 0) return;\n await api.integrations.run('gorgias', 'applyTags', { ticketId: ref.id, names });\n },\n async rename(ref, subject) {\n await api.integrations.run('gorgias', 'renameTicket', { ticketId: ref.id, subject });\n },\n async flag(ref, tag) {\n const trimmed = tag.trim();\n if (!trimmed) return;\n await api.integrations.run('gorgias', 'applyTags', { ticketId: ref.id, names: [trimmed] });\n },\n };\n}\n\n// --- LlmPort ---------------------------------------------------------------\n\n/**\n * `ctx.api.llm.complete` v2 carries no `tool`-role message and no `tools`\n * parameter (S2's surface, `app-api-client.ts`) — §6.2's tool loop has no\n * platform surface to run on YET. This is NOT dead ground: `graph/draft.ts`\n * already calls `buildToolSpecs(profile)` and populates `CompletionRequest\n * .tools` on every round, and already pushes `role: 'tool'` turns once the\n * model asks for one. Nothing in `draft.ts` gates on this adapter's\n * capabilities — what currently keeps `req.tools` empty is\n * `settings/to-profile.ts` hardcoding `tools: []` (\"default-deny until\n * T22\"). The moment that allowlist is populated, `complete()` below would\n * silently drop `req.tools` (this surface has nothing to forward it to) and\n * this port would keep returning `toolCalls: []` regardless of what the\n * model was asked to use — the loop terminates on round one, degraded: no\n * order lookup, no tracking lookup, `Draft.sources` empty, every\n * provenance display blank, the most expensive node hallucinating order\n * facts instead of fetching them. Silently, with no error anywhere.\n *\n * `complete()` below refuses that outcome outright: a request that asks for\n * tools throws, naming the missing surface, so enabling the allowlist\n * degrades loudly (a thrown error) rather than loudly-nothing. See\n * docs/plans/2026-09-02-gorgias-migration-progress.md for the spec gap this\n * leaves for T22 / the spec owner to close (S2 needs a tools/toolCalls\n * surface, or draft's `maxToolCalls` needs to go).\n */\nfunction toPlatformMessage(msg: ChatMessage): { role: 'system' | 'user' | 'assistant'; content: string } {\n // Reachable only once `req.tools` stops being empty (the guard below\n // throws before that point today) — kept exhaustive over `ChatMessage`\n // for type safety, not because production traffic hits these branches.\n if (msg.role === 'tool') return { role: 'user', content: msg.content };\n if (msg.role === 'assistant') return { role: 'assistant', content: msg.content ?? '' };\n return { role: msg.role, content: msg.content };\n}\n\n/** S2's `trace`, as a named type so a handler can build one without reaching into `CompletionRequest`. */\nexport type RunTrace = NonNullable<CompletionRequest['trace']>;\n\n/**\n * `trace` is stamped on every completion this port makes, unless the request\n * carries its own. The legacy grouped one ticket's calls under a single\n * Langfuse session — draft, evaluation and revision read as one conversation\n * instead of a handful of orphan generations — which is what makes a trace\n * navigable when a correction has to be traced back to what produced it\n * (§3.4's quality loop). Omitting it keeps today's untraced behaviour.\n */\nexport function createPlatformLlmPort(api: SupportKitApi, trace?: RunTrace): LlmPort {\n return {\n async complete(req: CompletionRequest): Promise<CompletionResult> {\n // Mirrors `FakeLlm`: an already-aborted signal fails before the\n // platform is reached — `ctx.api.llm.complete` takes no `signal` of\n // its own (I14's deadline is enforced by `budget`/the caller instead).\n if (req.signal?.aborted) {\n throw Object.assign(new Error('Request was aborted.'), { name: 'AbortError' });\n }\n\n // Fail loudly rather than silently ground the model (see the module\n // doc above): `ctx.api.llm.complete` v2 has no tool-calling surface,\n // so honouring `req.tools` here would mean dropping it on the floor.\n if (req.tools?.length) {\n throw new Error(\n 'createPlatformLlmPort: ctx.api.llm.complete v2 has no tool-calling surface (no `tools` parameter, no `role: \\'tool\\'` message) — cannot honour CompletionRequest.tools.',\n );\n }\n\n // A per-request `trace` wins over the port's own: a node that names\n // its own session knows something this port does not.\n const runTrace = req.trace ?? trace;\n const result = await api.llm.complete({\n messages: req.messages.map(toPlatformMessage),\n options: {\n model: req.model,\n reasoningEffort: req.reasoning,\n ...(req.responseSchema !== undefined\n ? { responseSchema: { name: req.label, schema: req.responseSchema as Record<string, unknown> } }\n : {}),\n },\n // `req.promptRef` (including `resolve`, see `CompletionRequest.promptRef`'s\n // own doc) is forwarded WHOLESALE — every caller in this package now\n // sets `resolve: false`, so this pass-through needs no code change of\n // its own to carry the new field; it already carries whatever shape\n // `CompletionRequest.promptRef` has.\n ...(req.promptRef ? { promptRef: req.promptRef } : {}),\n ...(runTrace ? { trace: runTrace } : {}),\n });\n\n return {\n text: result.text ?? null,\n // No tool-calling support on this surface today — see the module\n // doc above.\n toolCalls: [],\n usage: { input: result.usage.inputTokens, output: result.usage.outputTokens, reasoning: 0 },\n ...(result.traceId ? { traceId: result.traceId } : {}),\n ...(result.observationId ? { observationId: result.observationId } : {}),\n };\n },\n };\n}\n\n// --- PromptPort (§3.7 seams) -------------------------------------------------\n\n/** `PlatformPromptReader` over T5's `ctx.api.prompts.get(name, {label|version, resolve:false})` (T19's seam). */\nexport function createPlatformPromptReader(api: SupportKitApi): PlatformPromptReader {\n return {\n async get(name, ref) {\n const detail = await api.prompts.get(name, { ...ref, resolve: false });\n return { version: detail.version, content: detail.content, config: detail.config ?? null };\n },\n };\n}\n\n/** `PromptCachePort` over the `prompt-cache` record (T20's schema, T19's seam). */\nexport function createRecordPromptCachePort(api: SupportKitApi): PromptCachePort {\n return {\n async read(key) {\n const page = await api.list('prompt-cache', { filter: { promptKey: key }, limit: 1 });\n const data = page.items[0]?.data as { content: string; version: number } | undefined;\n return data ? { content: data.content, version: data.version } : null;\n },\n async write(key, entry) {\n await api.upsert(\n 'prompt-cache',\n [{ data: { promptKey: key, content: entry.content, version: entry.version } }],\n { uniqueBy: ['promptKey'] },\n );\n },\n };\n}\n\n/**\n * Assembles the real `PromptPort`: T19's resolver over the two seams above,\n * with `onDegraded` routed to the caller's logger (post-T19-review E) — the\n * kit carries no logging port of its own, so a silent-degradation event\n * (Langfuse down, cache down, a broken composition tag) would otherwise be\n * indistinguishable from a correct run.\n */\nexport function createPlatformPromptPort(api: SupportKitApi, log: (message: string) => void): PromptPort {\n return createPromptResolver({\n platform: createPlatformPromptReader(api),\n cache: createRecordPromptCachePort(api),\n onDegraded: (event: PromptDegradedEvent) => log(`prompt resolution degraded [${event.stage}] ${event.name}: ${event.reason}`),\n });\n}\n\n// --- ClockPort ---------------------------------------------------------------\n\nexport function createRealClock(): ClockPort {\n return { now: () => new Date() };\n}\n","/**\n * Recording ports for the dry-run replay (spec §3.3 `adapters/\n * recording-ports.ts`, §3.5's `graph-dry-run` row), ported from legacy\n * `services/graphDryRun.ts`'s `meta`/`sink`/`reply`/`recordingGateway`.\n *\n * The guarantee (§0's arbitrage, restated in §3.5): dry-run replays the\n * COMPLETE graph — every node, LLM included — but reaches ZERO external\n * action. `ReplyPort.post` and `StatePort.record`/`rename`/`flag` are\n * replaced here by recorders that never call Gorgias; `ConversationPort`,\n * `LlmPort` and `PromptPort` stay the REAL `ctx-ports.ts` adapters — a dry\n * run reads and thinks for real, it just never writes.\n *\n * `state.record`'s READ half (the category's `extraTags`, via\n * `gorgias-tags.ts`) still runs for real, so `wouldHaveTagged` reports the\n * EXACT tag set production would apply — only the final `applyTags` call is\n * skipped, by construction (there is no write call left to make).\n */\nimport type { AuditTags, CompletionRequest, LlmPort, OutboundReply, ReplyPort, StatePort, ToolCallRequest } from '../graph/ports';\nimport type { Classification, Usage } from '../domain';\nimport type { NodeDeps } from '../graph/state';\nimport type { SupportKitApi } from './api';\nimport { resolveHandledTags } from './gorgias-tags';\n\n// --- ReplyPort ---------------------------------------------------------------\n\nexport interface WouldHaveReplied {\n subject: string | null;\n body: string;\n}\n\nexport interface RecordingReplyPort {\n port: ReplyPort;\n /** The reply the run WOULD have posted, or `null` if `act` never ran. Nothing was posted. */\n wouldHaveReplied(): WouldHaveReplied | null;\n}\n\nexport function createRecordingReplyPort(): RecordingReplyPort {\n let wouldHaveReplied: WouldHaveReplied | null = null;\n return {\n port: {\n async post(_ref, reply: OutboundReply) {\n wouldHaveReplied = { subject: reply.mode === 'email' ? reply.subject : null, body: reply.bodyText };\n // A message id `act` can commit — nothing left the building.\n return { messageId: 'dry-run' };\n },\n },\n wouldHaveReplied: () => wouldHaveReplied,\n };\n}\n\n// --- StatePort -----------------------------------------------------------\n\nexport interface RecordingStatePort {\n port: StatePort;\n /** Tags the run WOULD have applied, in first-seen order. Nothing was applied. */\n wouldHaveTagged(): string[];\n}\n\nexport function createRecordingStatePort(api: SupportKitApi): RecordingStatePort {\n const tagged: string[] = [];\n const push = (tag: string): void => {\n const trimmed = tag.trim();\n if (trimmed && !tagged.includes(trimmed)) tagged.push(trimmed);\n };\n\n return {\n port: {\n async record(_ref, classification: Classification, audit: AuditTags) {\n const names = await resolveHandledTags(api, classification, audit);\n names.forEach(push);\n },\n async rename() {\n // A dry run renames nothing.\n },\n async flag(_ref, tag) {\n push(tag);\n },\n },\n wouldHaveTagged: () => [...tagged],\n };\n}\n\n// --- SendPort recorder (claim -> post -> commit persistence seam, I9) ------\n\ntype ClaimedSend = Extract<NodeDeps['send'], { mode: 'claimed' }>;\n\nexport interface RecordingSendPort {\n send: ClaimedSend;\n /** Every claim/commit call, in order — a dry run must never let these reach real persistence. */\n calls: Array<{ surface: 'send.claim' | 'send.commit'; args: readonly unknown[] }>;\n}\n\n/**\n * Recording `{mode: 'claimed'}` seam (post-T21-review C): when a production\n * dry run wires `deps.send` to `{mode: 'claimed'}` (the `act` node's own\n * gate — see its module doc), THIS package had no recording counterpart, so\n * nothing stopped that dry run's claim/commit calls from writing real rows.\n * `claim` always resolves `true` (a dry run never loses a contest — there is\n * nothing to contest), `commit` no-ops: neither touches persistence.\n */\nexport function createRecordingSendPort(): RecordingSendPort {\n const calls: RecordingSendPort['calls'] = [];\n return {\n calls,\n send: {\n mode: 'claimed',\n async claim(run) {\n calls.push({ surface: 'send.claim', args: [run] });\n return true;\n },\n async commit(messageId) {\n calls.push({ surface: 'send.commit', args: [messageId] });\n },\n },\n };\n}\n\n// --- The pair a production dry run substitutes ------------------------------\n\n/**\n * Swaps the two ports that can reach Gorgias — `reply` and `state` — for\n * their recorders, leaving every READ port (conversation, llm, prompt) and\n * the clock untouched.\n *\n * This is the `settings.dryRun` seam for the PRODUCTION pipeline\n * (`functions/triage-tick.ts`, `functions/process-response.ts`), where the\n * recorded output is deliberately dropped: those handlers report through\n * their records and their run, not through a `wouldHaveTagged()` payload —\n * only the \"never write to Gorgias\" half of the recorders matters there.\n * The `uiInvoke` dry runs that DO read the recordings back\n * (`functions/graph-dry-run-core.ts`) keep wiring the recorders themselves.\n */\nexport function withRecordingWritePorts<T extends { reply: ReplyPort; state: StatePort }>(ports: T, api: SupportKitApi): T {\n return { ...ports, reply: createRecordingReplyPort().port, state: createRecordingStatePort(api).port };\n}\n\n// --- LlmPort recorder (still a REAL call — only its trace is captured) -----\n\n/** One LLM call, as a dry-run page would show it: what was asked, what came back, what it cost. */\nexport interface RecordedCompletion {\n label: string;\n model: string;\n reasoning: string;\n messages: CompletionRequest['messages'];\n toolsOffered: string[];\n text: string | null;\n toolCalls: Array<{ name: string; arguments: Record<string, unknown> }>;\n usage: Usage;\n traceId: string | null;\n durationMs: number;\n error?: string;\n}\n\nexport interface RecordingLlmPort {\n port: LlmPort;\n completions: RecordedCompletion[];\n}\n\nfunction toRecordedToolCalls(calls: ToolCallRequest[]): Array<{ name: string; arguments: Record<string, unknown> }> {\n return calls.map((c) => ({ name: c.name, arguments: c.arguments }));\n}\n\n/** Wraps a REAL `LlmPort` (the LLM still runs — §3.5's \"LLM compris\") and records every completion. */\nexport function createRecordingLlmPort(llm: LlmPort): RecordingLlmPort {\n const completions: RecordedCompletion[] = [];\n return {\n completions,\n port: {\n async complete(req: CompletionRequest) {\n const startedAt = Date.now();\n const entry: RecordedCompletion = {\n label: req.label,\n model: req.model,\n reasoning: req.reasoning,\n messages: req.messages,\n toolsOffered: (req.tools ?? []).map((t) => t.name),\n text: null,\n toolCalls: [],\n usage: { input: 0, output: 0, reasoning: 0 },\n traceId: null,\n durationMs: 0,\n };\n completions.push(entry);\n try {\n const result = await llm.complete(req);\n entry.text = result.text;\n entry.toolCalls = toRecordedToolCalls(result.toolCalls);\n entry.usage = result.usage;\n entry.traceId = result.traceId ?? null;\n return result;\n } catch (err) {\n entry.error = err instanceof Error ? err.message : String(err);\n throw err;\n } finally {\n entry.durationMs = Date.now() - startedAt;\n }\n },\n },\n };\n}\n","/**\n * `SupportKitHandlerContext` — `AppHandlerContext` (`@apotech-os/app-kit`,\n * `handler.ts`) narrowed to `api: SupportKitApi` instead of the concrete\n * `AppApiClient` class.\n *\n * Same reasoning as `SupportKitApi` itself (T21/T22, `adapters/api.ts`): a\n * real `AppHandlerContext` built by the platform carries a real\n * `AppApiClient`, which is a structural superset of `SupportKitApi`, so it\n * is always assignable here — but a unit test can build `ctx.api` as a plain\n * object instead of a live HTTP client.\n *\n * Also the shared home (T22 hardening, E) for the bits every one of the four\n * pipeline handlers otherwise hand-copied: `getOptional` (a 404 read is an\n * ordinary \"not there\" outcome, not a thrown error, for every handler that\n * dereferences a possibly-stale record id), `DEFAULT_MAX_TOOL_CALLS` (the\n * `draft` node's tool budget when `nodes.draft.maxToolCalls` is unset), and\n * `buildTicketPorts` (the six-line `NodeDeps.ports` assembly `triage-tick`/\n * `process-response`/`handle-approval` each wrote out by hand, byte-for-byte\n * identical).\n */\nimport type { AppApiRecord, AppHandlerContext } from '@apotech-os/app-kit';\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { SupportKitApi } from '../adapters/api';\nimport {\n createGorgiasConversationPort,\n createGorgiasReplyPort,\n createGorgiasStatePort,\n createPlatformLlmPort,\n createPlatformPromptPort,\n createRealClock,\n type RunTrace,\n} from '../adapters/ctx-ports';\n\nexport type SupportKitHandlerContext = Omit<AppHandlerContext, 'api'> & { api: SupportKitApi };\n\n/** The `draft` node's tool budget when `nodes.draft.maxToolCalls` is unset (§3.6). */\nexport const DEFAULT_MAX_TOOL_CALLS = 5;\n\n/**\n * Reads `objectKey/id`, returning `null` on a 404 (a dangling relation or an\n * already-deleted record) instead of throwing — the shape every handler here\n * wants when dereferencing an id it did not just create itself. `id: null`\n * short-circuits to `null` without a round trip, for the optional relations\n * (`categoryId`, `agentId`) that may never have been set.\n */\nexport async function getOptional(ctx: SupportKitHandlerContext, objectKey: string, id: string | null): Promise<AppApiRecord | null> {\n if (!id) return null;\n try {\n return await ctx.api.get(objectKey, id);\n } catch (err) {\n if (err instanceof AppApiError && err.status === 404) return null;\n throw err;\n }\n}\n\n/**\n * The `NodeDeps.ports` bundle every handler that runs a ticket through the\n * graph needs — one real Gorgias/platform wiring, reused instead of re-typed\n * per call site.\n *\n * `trace` groups every completion of the run under one Langfuse session\n * (`RunTrace`); a handler that omits it gets today's untraced behaviour.\n */\nexport function buildTicketPorts(ctx: SupportKitHandlerContext, trace?: RunTrace) {\n return {\n conversation: createGorgiasConversationPort(ctx.api),\n reply: createGorgiasReplyPort(ctx.api),\n llm: createPlatformLlmPort(ctx.api, trace),\n prompt: createPlatformPromptPort(ctx.api, (message) => ctx.logger.warn(message)),\n state: createGorgiasStatePort(ctx.api),\n clock: createRealClock(),\n };\n}\n","/**\n * Whether a `generated-response{status:'pending'}` row is worth creating\n * for a just-triaged ticket (§3.5's \"si éligible, création generated-\n * response{status:'pending'}\").\n *\n * §3.5 does not spell out \"eligible\" — this is `triage-tick`'s own reading,\n * chosen to NEVER DRIFT from what `process-response`'s `runTicket(deps,\n * {resume})` would decide with the SAME classification: it calls the EXACT\n * SAME predicates `run-ticket.ts` branches on right after its own triage\n * phase (`isConversationOver`/`isFallbackClassification`/`hasNoDraftNode`,\n * exported from there — T22 hardening, so this can no longer silently drift\n * the way a hand-copied mirror could), up to (but not including)\n * `channelPreGates`/the WhatsApp not-our-turn check — those need a FRESH\n * conversation read to evaluate, which `triage-tick` does not have (and\n * should not pay for) at classification time. Any ticket this function\n * calls \"eligible\" that later turns out to hit a pre-gate is still\n * perfectly safe: `process-response` runs the real sequence and writes\n * whatever real outcome results, `triage-tick`'s job is only to avoid\n * paying for a draft that could NEVER have produced one — an escalated,\n * closed, or fallback-classified ticket.\n *\n * PER-CATEGORY OPT-IN (B3): the gate above is about what the graph COULD\n * produce; this one is about what the tenant ASKED for. §3.4's `category`\n * record carries `fastResponseEnabled` and `agentId` (with the cross\n * validation `fastResponseEnabled ⇒ agentId`), and the legacy enqueued a\n * fast-response job only for `matched && matched.fast_response_enabled &&\n * matched.agent` (`backoffice/src/services/triage.ts`). Nobody read those\n * fields here, so EVERY triable ticket paid a drafting — and then an\n * evaluation — LLM call, including for categories explicitly left out and\n * for tickets whose classification matched no category at all (drafted with\n * whatever the default agent happened to be). An unmatched or non-opted-in\n * category now stops at triage, as it did before the migration.\n *\n * ESCALATION (B3, connected decision): the legacy made this skip\n * CONDITIONAL on `profile.nodes.escalate.skipsFastResponse` — an escalated\n * ticket was still enqueued when that flag was off. That setting is gone\n * rather than restored: `graph/run-ticket.ts` finishes UNCONDITIONALLY on\n * `s.escalated` (`if (s.escalated) return finish(s, deps, 'escalated')`),\n * so a row created for an escalated ticket could never be fulfilled by\n * `process-response` — it would only ever be a pending row expiring on its\n * TTL. Honouring the flag would require re-opening that graph decision,\n * which §3.3 settled the other way; keeping it mapped-but-unread was the\n * worse of the three options.\n */\nimport type { Classification } from '../domain';\nimport type { AgentProfile } from '../domain/profile';\nimport { hasNoDraftNode, isConversationOver, isFallbackClassification } from '../graph/run-ticket';\nimport type { CategoryRecord } from './records';\n\nexport function isEligibleForGeneratedResponse(\n profile: AgentProfile,\n classification: Classification,\n escalated: boolean,\n category: CategoryRecord | null,\n): boolean {\n if (!category || !category.fastResponseEnabled || !category.agentId) return false;\n if (escalated) return false;\n if (isConversationOver(classification)) return false;\n if (isFallbackClassification(classification)) return false;\n if (hasNoDraftNode(profile)) return false;\n return true;\n}\n","/**\n * A `ToolContext` that refuses every call — used where `NodeDeps` requires\n * one but `AgentProfile.tools` is always `[]` (T22 leaves the §6.2 tool\n * allowlist at default-deny, see `settings/to-profile.ts`'s own doc: nothing\n * in `settingsToProfile` populates it, and `createPlatformLlmPort` throws on\n * a non-empty `CompletionRequest.tools` before ever reaching a provider).\n * With no tool ever exposed to the model, `draft` never calls this — these\n * throws are a loud, defensive backstop against that assumption silently\n * breaking, not a code path anything is expected to take today.\n */\nimport type { ToolContext } from '../graph/ports';\n\nfunction refuse(name: string): never {\n throw new Error(`no-tool-context: \"${name}\" called, but this pipeline configures no tools (profile.tools is always []).`);\n}\n\nexport function createNoToolContext(): ToolContext {\n return {\n getOrder: () => refuse('getOrder'),\n getTracking: () => refuse('getTracking'),\n searchKnowledge: () => refuse('searchKnowledge'),\n findSimilarTickets: () => refuse('findSimilarTickets'),\n };\n}\n","/**\n * The `pipeline-state` singleton (§3.4, `records/pipeline-state.ts`) —\n * shared reader/writer for `triage-tick` and `sweep`, the only two callers\n * (T22 hardening, A4). Both used to hand-roll their own `toDate`/\n * `readPipelineState`, byte-identical between the two files, and each wrote\n * with an independent `list()` + `create()`-or-`update()` pair with no\n * ordering guarantee between them — see `records/pipeline-state.ts`'s own\n * doc for why that raced two crons on a fresh app. Routing both functions\n * through the ONE reader here, and through `upsertPipelineState`'s\n * `singletonKey`-keyed `upsert`, is what makes \"exactly one row\" the\n * platform's own constraint instead of a hope.\n */\nimport type { AppApiRecord } from '@apotech-os/app-kit';\nimport type { SupportKitApi } from '../adapters/api';\n\n/** Always the same value — the field the record's unique index is built on. */\nexport const PIPELINE_STATE_SINGLETON_KEY = 'default';\n\nexport function toDate(value: unknown): Date | null {\n if (!value) return null;\n const date = value instanceof Date ? value : new Date(value as string);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\n/** The singleton `pipeline-state` row, or `null` if it has never been written. */\nexport async function readPipelineState(api: SupportKitApi): Promise<AppApiRecord | null> {\n const page = await api.list('pipeline-state', { filter: { singletonKey: PIPELINE_STATE_SINGLETON_KEY }, limit: 1 });\n return page.items[0] ?? null;\n}\n\n/**\n * Merges `patch` onto the singleton row, creating it on the first call. Both\n * `triage-tick` and `sweep` only ever set a slice of the record's fields\n * (`sourceViewId`+`lastTriageAt`, `lastSweepAt`) — `upsert`'s `ON CONFLICT\n * DO UPDATE` merges those onto whatever the other cron already wrote, the\n * same merge semantics `update()` already gives every other record in this\n * package.\n */\nexport async function upsertPipelineState(api: SupportKitApi, patch: Record<string, unknown>): Promise<void> {\n await api.upsert('pipeline-state', [{ data: { singletonKey: PIPELINE_STATE_SINGLETON_KEY, ...patch } }], {\n uniqueBy: ['singletonKey'],\n });\n}\n","/**\n * `triage-tick` (§3.5) — cron function. Classifies every pending ticket on\n * the claimed Gorgias view and, per ticket, materialises what `runTicket(deps,\n * {until:'triage'})` deliberately leaves unwritten (see that option's own\n * doc in `graph/run-ticket.ts`): the `triage-decision` row, the deduplicated\n * tag application, and — when eligible — a `generated-response{status:\n * 'pending'}` row for `process-response` to pick up.\n *\n * WRITE ORDER (T22 hardening, A2): the `triage-decision` row is written\n * BEFORE the Gorgias tags are applied, not after. A duplicate tag apply on a\n * retried/re-run ticket is idempotent (`dedupeTagNames`, `gorgias-tags.ts`);\n * a lost `triage-decision` is not — and if the claimed view filters on the\n * `handledTag` this tag step applies, a ticket tagged with no decision row\n * behind it never comes back into view again, so the classification the LLM\n * call already paid for would be lost OUTRIGHT, not merely re-billed. The\n * decision-first order means the ONLY window left where a crash can still\n * lose a classification is between `runTicket`'s checkpoint returning and\n * THIS row landing — everything after that point (the tag apply, the\n * `generated-response` create) is either idempotent or independently\n * recoverable.\n *\n * CRASH WINDOW that remains (documented, not fully closed — see the\n * module's own final report): `runTicket`'s own doc states it plainly — a\n * checkpointed run never calls `ports.state.record`, so the classification\n * only lives in the RETURNED `TicketRunState` until this function writes it\n * down. If the process dies between the checkpoint returning and the\n * `triage-decision` write above, that LLM call's result is lost with\n * nothing left to reconstruct it from — the ticket is simply re-classified\n * (and re-billed) on the next tick. This is the same trade-off `runTicket`'s\n * doc already names as \"iso-legacy and harmless today\"; nothing in T22\n * changes it.\n *\n * DRY RUN (B1): `settings.dryRun` was a declared, advertised, DEAD setting —\n * no handler read it, so the very first `triageEnabled` activation of the\n * spec's §6 switchover order (\"activate in `dryRun`, control the parity,\n * then `dryRun` off\") tagged and renamed REAL Gorgias tickets. It is read\n * here now, and it substitutes the two write ports (`reply`, `state`) for\n * the recorders of `adapters/recording-ports.ts`: the graph still runs in\n * FULL, LLM included (§0's arbitrage), it simply reaches no external action.\n *\n * What a trial tick still WRITES, deliberately: the `triage-decision` and\n * the `generated-response` rows, exactly as a live tick would. §6 asks the\n * operator to \"control the decisions\" before turning `dryRun` off — with no\n * rows there is nothing to control, and the Pipeline/Escalades pages would\n * show an empty trial. They are identifiable as a trial's through the\n * application run they carry the `runId` of, which is stamped\n * `metadata.dryRun: true` below (the record schemas are frozen by §3.4, so\n * the marker lives on the run, not on a new column). A trial row therefore\n * describes what production WOULD have done — `subjectRenamed: true` on a\n * dry run means \"the subject matched and would have been rewritten\",\n * nothing was sent to Gorgias.\n *\n * PER-TICKET ISOLATION (T22 hardening, A1): one failing ticket no longer\n * aborts the rest of the batch. `retries: 0` on this function (see the\n * manifest fragment below) means a tick that dies partway has no recovery —\n * tickets already processed dropped off the claimed view (their `handledTag`\n * is applied), so the NEXT tick would hit the same poison ticket first and\n * die at the same place, forever, while `lastTriageAt` was never stamped\n * (also re-billing every ticket the dead tick DID manage to finish). Each\n * ticket's own error is caught, logged, and recorded as a `triage-decision\n * {status:'error'}` row for that ticket alone; the loop moves on, and\n * `lastTriageAt` is stamped in a `finally` so the cadence gate always\n * advances once the batch has been attempted, degraded ticket or not.\n */\nimport type { AppApiRecord, AppHandler, FunctionDef } from '@apotech-os/app-kit';\nimport { AppApiError } from '@apotech-os/app-kit';\nimport { createBudget } from '../graph/budget';\nimport { runTicket } from '../graph/run-ticket';\nimport type { ConversationRef } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport { createRealClock } from '../adapters/ctx-ports';\nimport { withRecordingWritePorts } from '../adapters/recording-ports';\nimport { openTicketKeyFor } from '../status/machine';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { isEligibleForGeneratedResponse } from './eligibility';\nimport { createNoToolContext } from './no-tool-context';\nimport { readPipelineState, toDate, upsertPipelineState } from './pipeline-state';\nimport {\n buildPromptsTable,\n draftPromptRefFor,\n findCategoryByTag,\n listCategories,\n resolveDraftAgent,\n toCategoryReferential,\n} from './records';\n\n/**\n * The manifest fragment (§3.5's table row): every 5 minutes, no retries (a\n * failed tick is superseded by the next one 5 minutes later — retrying it\n * would just re-run against a possibly-already-advanced view), one run at a\n * time, and a warning alert on failure so an operator notices a stuck\n * pipeline. Cron has no timezone field in this schema (`FunctionTriggerSchema`,\n * `@apotech-os/app-kit` `contracts.ts`) — Europe/Paris from the spec table\n * has nowhere to go here; see this task's final report for that gap.\n */\nexport function buildTriageTickFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'triage-tick'),\n name: 'triage-tick',\n trigger: { type: 'cron', pattern: '*/5 * * * *' },\n retries: 0,\n concurrency: 1,\n notify: { onFailure: true, severity: 'warning' },\n };\n}\n\nexport function createTriageTickHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx) => triageTickHandler(ctx, config);\n}\n\nexport async function triageTickHandler(ctx: SupportKitHandlerContext, config: SupportKitFunctionConfig): Promise<void> {\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n ctx.logger.info('triage-tick: settings invalid, skipping', { issues });\n return;\n }\n if (!settings.triageEnabled) {\n ctx.logger.info('triage-tick: triageEnabled is off, skipping');\n return;\n }\n if (!settings.sourceViewId) {\n ctx.logger.info('triage-tick: no sourceViewId configured, skipping');\n return;\n }\n\n const clock = createRealClock();\n const now = clock.now();\n\n const pipelineState = await readPipelineState(ctx.api);\n const lastTriageAt = toDate(pipelineState?.data.lastTriageAt);\n if (lastTriageAt) {\n const dueAt = lastTriageAt.getTime() + settings.triageIntervalMinutes * 60_000;\n if (now.getTime() < dueAt) {\n ctx.logger.info('triage-tick: not due yet, skipping');\n return;\n }\n }\n\n await runTriageBatch(ctx, config, settings);\n}\n\n/**\n * The batch itself — every `triage-tick` guard (settings validity,\n * `triageEnabled`, `sourceViewId`, the cadence gate) has already returned by\n * the time this runs. Extracted (T23) so `run-triage-now`\n * (`functions/run-triage-now.ts`, §3.5's \"déclenchement manuel\") can run the\n * EXACT same batch on demand, bypassing only the cadence gate above — not a\n * second, independently-drifting copy of `listPending` → per-ticket triage →\n * `triage-decision` → `generated-response`.\n */\nexport async function runTriageBatch(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n settings: SupportKitSettings,\n): Promise<{ ticketCount: number; failureCount: number }> {\n const dryRun = settings.dryRun === true;\n const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx), ctx.api) : buildTicketPorts(ctx);\n\n const categories = await listCategories(ctx.api);\n // Draft agent for the WHOLE batch's profile — a placeholder until each\n // ticket's own category is known (see `records.ts`'s doc on\n // `resolveDraftAgent`). The per-ticket agent used on the created\n // `generated-response` row is resolved again below, after triage.\n const batchDefaultAgent = await resolveDraftAgent(ctx.api, null);\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(batchDefaultAgent, config), settings.nodes));\n\n const refs = await ports.conversation.listPending({ viewOrTag: settings.sourceViewId }, settings.batchLimit);\n\n // §3.5's \"run applicatif\" (T22 hardening, D): one run per tick, threaded\n // onto every `triage-decision` this tick writes (`runId` below) instead of\n // each decision minting its own `crypto.randomUUID()` — an operator can\n // now group a tick's decisions, or find the tick itself, in the platform\n // run history. Started only once we know there is real work to do (the\n // cadence/settings guards above already returned): a skipped tick has\n // nothing to report a run for.\n const run = await ctx.api.runs.start({\n kind: 'triage-tick',\n message: `${dryRun ? 'Dry-run triage tick' : 'Triage tick'} over ${refs.length} ticket(s)`,\n metadata: { sourceViewId: settings.sourceViewId, ticketCount: refs.length, dryRun },\n });\n\n let failureCount = 0;\n try {\n for (const ref of refs) {\n try {\n await processOneTicket(ctx, ref, {\n profile,\n categories,\n ports,\n runId: run.id,\n });\n } catch (err) {\n failureCount += 1;\n const message = err instanceof Error ? err.message : String(err);\n ctx.logger.error(`triage-tick: ticket ${ref.id} failed, continuing with the rest of the batch`, { error: message });\n try {\n await ctx.api.create('triage-decision', {\n ticketId: ref.id,\n decidedAt: ports.clock.now(),\n status: 'error',\n error: message,\n confidence: 'low',\n runId: run.id,\n subjectRenamed: false,\n });\n } catch (writeErr) {\n ctx.logger.error(`triage-tick: failed to record the error decision for ticket ${ref.id}`, {\n error: writeErr instanceof Error ? writeErr.message : String(writeErr),\n });\n }\n }\n }\n await ctx.api.runs.succeed(run.id, { ticketCount: refs.length, failureCount });\n } catch (err) {\n await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });\n throw err;\n } finally {\n // Stamped regardless of per-ticket failures (A1): the cadence gate must\n // advance once the batch has been ATTEMPTED, not only once every ticket\n // in it succeeded — otherwise a single poison ticket would keep\n // `lastTriageAt` frozen and every OTHER ticket in the batch would be\n // re-billed on the next tick too. Also stamped on a `run-triage-now`\n // manual batch, on purpose: it advances the SAME cadence gate\n // `triage-tick` reads, so a manual run just before a scheduled tick is\n // due does not immediately trigger a redundant second pass over the\n // same tickets.\n await upsertPipelineState(ctx.api, { sourceViewId: settings.sourceViewId, lastTriageAt: ports.clock.now() });\n }\n\n return { ticketCount: refs.length, failureCount };\n}\n\ninterface TickDeps {\n profile: ReturnType<typeof settingsToProfile>;\n categories: Awaited<ReturnType<typeof listCategories>>;\n ports: ReturnType<typeof buildTicketPorts>;\n runId: string;\n}\n\nasync function processOneTicket(ctx: SupportKitHandlerContext, ref: ConversationRef, deps: TickDeps): Promise<void> {\n const { profile, categories, ports, runId } = deps;\n\n // Optional rename (§3.6's `renameEnabled`/`renameFrom`/`renameTo`) — no\n // node in the graph performs it (see this module's own header doc), so it\n // is done here, once, before triage. `runTicket` re-reads the conversation\n // itself right after (`fetchContext`'s own \"always re-read\" contract) —\n // paying for one extra read here is the same trade-off the whole pipeline\n // already makes at every resume boundary.\n let subjectRenamed = false;\n if (profile.rename) {\n const conversation = await ports.conversation.read(ref);\n const subject = conversation.subject ?? '';\n if (subject.includes(profile.rename.from)) {\n await ports.state.rename(ref, subject.replace(profile.rename.from, profile.rename.to));\n subjectRenamed = true;\n }\n }\n\n const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n\n const state = await runTicket(\n {\n ref,\n profile,\n ports: { ...ports },\n toolContext: createNoToolContext(),\n budget,\n // Unknown until triage runs — no node reached in the `until:'triage'`\n // phase reads `deps.category` (`run-ticket.ts`'s early return happens\n // before any node touches it).\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: toCategoryReferential(categories),\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'none' },\n },\n { until: 'triage' },\n );\n\n if (!state.classification) {\n await ctx.api.create('triage-decision', {\n ticketId: ref.id,\n decidedAt: ports.clock.now(),\n status: 'error',\n error: 'triage produced no classification',\n confidence: 'low',\n runId,\n subjectRenamed,\n });\n return;\n }\n\n const { classification } = state;\n const category = findCategoryByTag(categories, classification.category);\n\n // Decision FIRST, tags SECOND (A2 — see this module's header doc for why\n // the order was inverted).\n const decision = await ctx.api.create('triage-decision', {\n ticketId: ref.id,\n decidedAt: ports.clock.now(),\n categoryId: category?.id ?? null,\n tag: classification.category,\n confidence: classification.confidence,\n reasoning: classification.reasoning,\n conversationOver: classification.conversationOver ?? false,\n escalated: state.escalated,\n status: 'ok',\n runId,\n subjectRenamed,\n });\n\n // The dedup+single-`applyTags` call §3.5 asks for already lives in\n // `StatePort.record` (`adapters/gorgias-tags.ts`'s `resolveHandledTags`) —\n // nothing to reimplement here beyond calling the port.\n await ports.state.record(ref, classification, profile.audit);\n\n // The category matched above is passed along, not re-read: §3.4's\n // `fastResponseEnabled`/`agentId` opt-in is half of what \"eligible\" means\n // (B3 — see `eligibility.ts`).\n if (!isEligibleForGeneratedResponse(profile, classification, state.escalated, category)) return;\n\n const draftAgent = await resolveDraftAgent(ctx.api, category?.agentId ?? null);\n const conversation = state.conversation;\n const channel = conversation?.sourceChannel === 'whatsapp' ? 'whatsapp' : 'email';\n const generatedAt = ports.clock.now();\n const expiresAt = new Date(generatedAt.getTime() + profile.schedule.fastResponseTtlMinutes * 60_000);\n\n try {\n await ctx.api.create('generated-response', {\n ticketId: ref.id,\n openTicketKey: openTicketKeyFor('pending', ref.id),\n status: 'pending',\n triageDecisionId: decision.id,\n categoryId: category?.id ?? null,\n agentId: draftAgent?.id ?? null,\n channel,\n generatedAt,\n expiresAt,\n sources: [],\n tracedInput: [],\n guardrailHits: [],\n servedTo: [],\n servedCount: 0,\n followupRequired: false,\n });\n } catch (err) {\n // §3.5: \"conflit d'unicité openTicketKey ⇒ ignoré, idempotent\" — another\n // tick (or a stray retry) already opened one for this ticket.\n if (err instanceof AppApiError && err.status === 409) {\n ctx.logger.debug(`triage-tick: generated-response already pending for ticket ${ref.id}, skipping`);\n return;\n }\n throw err;\n }\n}\n","/**\n * `buildSendSeam` — the ONE claim→post→commit persistence seam (I9) shared\n * by `process-response` (claims a `pending` row) and `handle-approval`\n * (claims a `ready` row after an operator approves). §8.4 demands a single\n * send path, not two independently-written ones: this is where that demand\n * actually lives at the persistence layer — both callers hand this function\n * their own `fromStatus` and get back the exact same `NodeDeps.send`\n * shape `act` drives.\n *\n * `assertTransition` runs BEFORE the write attempt (`status/machine.ts`'s own\n * doc): it is a local, in-process sanity check, distinct from the `ifMatch`\n * race below it, which is what actually decides which of two concurrent\n * claimants wins.\n *\n * A 409 from `api.update` is NOT an error here — §3.4/§8.4 read it as \"the\n * other worker already claimed this row\", the ordinary losing side of a\n * race. Any other rejection propagates so Inngest can retry the run.\n */\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { Draft, Verdict } from '../domain';\nimport type { ClockPort } from '../graph/ports';\nimport { assertTransition, openTicketKeyFor, type GeneratedResponseStatus } from '../status/machine';\nimport type { SupportKitApi } from '../adapters/api';\n\nexport interface SendSeam {\n claim: (run: { draft: Draft; verdict: Verdict | null }) => Promise<boolean>;\n commit: (messageId: string) => Promise<void>;\n}\n\nexport interface BuildSendSeamParams {\n api: SupportKitApi;\n clock: ClockPort;\n id: string;\n ticketId: string;\n /** The status this claim moves FROM — `'pending'` for `process-response`, `'ready'` for `handle-approval`. */\n fromStatus: Extract<GeneratedResponseStatus, 'pending' | 'ready'>;\n /**\n * Extra fields persisted on the SAME atomic claim write. `process-response`\n * uses this to persist the draft/verdict it just produced (the row had\n * none yet); `handle-approval` needs nothing extra — the row already\n * carries `responseText`/`verdict` from when it was drafted.\n */\n extraClaimData?: (run: { draft: Draft; verdict: Verdict | null }) => Record<string, unknown>;\n}\n\nexport function buildSendSeam(params: BuildSendSeamParams): SendSeam {\n const { api, clock, id, ticketId, fromStatus, extraClaimData } = params;\n\n return {\n async claim(run) {\n assertTransition(fromStatus, 'sending');\n try {\n await api.update(\n 'generated-response',\n id,\n {\n status: 'sending',\n sendingAt: clock.now(),\n openTicketKey: openTicketKeyFor('sending', ticketId),\n ...(extraClaimData ? extraClaimData(run) : {}),\n },\n { ifMatch: { status: fromStatus } },\n );\n return true;\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) return false;\n throw err;\n }\n },\n\n async commit(messageId) {\n assertTransition('sending', 'sent');\n await api.update(\n 'generated-response',\n id,\n {\n status: 'sent',\n sentAt: clock.now(),\n sentMessageId: messageId,\n openTicketKey: openTicketKeyFor('sent', ticketId),\n },\n { ifMatch: { status: 'sending' } },\n );\n },\n };\n}\n","/**\n * The `generated-response:<id>[:suffix]` key shape used by BOTH the\n * `ApprovalRequest.key`/`ApprovalDecidedPayload.key` pair (`process-response`\n * requests, `handle-approval` parses) and the `InboxAlert.key`s\n * `process-response`/`sweep` raise. Shared here so the format can never\n * drift between writers — hand-rolling the same template string twice (or\n * three times) is exactly the kind of duplication that quietly breaks the\n * moment one side changes.\n */\nconst PREFIX = 'generated-response:';\n\n/** The approval key for one `generated-response` row. */\nexport function buildApprovalKey(generatedResponseId: string): string {\n return `${PREFIX}${generatedResponseId}`;\n}\n\n/** The `generated-response` id encoded in `key`, or `null` if `key` isn't one of ours. */\nexport function parseApprovalKey(key: string): string | null {\n if (!key.startsWith(PREFIX)) return null;\n const id = key.slice(PREFIX.length);\n return id.length > 0 ? id : null;\n}\n\n/**\n * The `InboxAlert.key` for one `generated-response` row, optionally\n * suffixed (`sweep`'s `stalled-send` alert vs. `process-response`'s plain\n * `needs_human` one) — same PREFIX as the approval key above, on purpose:\n * both name the same underlying record, in a different platform surface.\n * Added alongside `buildApprovalKey` for the same reason that one exists:\n * `process-response` and `sweep` were each hand-rolling this template\n * string in a slightly different shape, two lines after importing\n * `buildApprovalKey` to avoid doing exactly that for the approval key.\n */\nexport function buildInboxKey(generatedResponseId: string, suffix?: string): string {\n return suffix ? `${PREFIX}${generatedResponseId}:${suffix}` : `${PREFIX}${generatedResponseId}`;\n}\n","/**\n * `process-response` (§3.5) — dbEvent function, triggered on\n * `generated-response{status:'pending'}` created. Resumes `runTicket` past\n * triage (`resume: {classification, escalated}`, reconstructed from the\n * `triage-decision` row) and persists whatever terminal outcome results.\n *\n * The dbEvent payload (`apps/api/src/platform-data/app-inngest-functions.ts`'s\n * `DbEventPayload`) carries only `{appSlug, objectKey, recordId,\n * updatedFields?, before?}` — never the record itself — so this handler's\n * first move is always its own `ctx.api.get('generated-response', recordId)`.\n *\n * DRY RUN (B1): `settings.dryRun` was read by NO handler — this one drafted\n * and, whenever auto-send was eligible, actually replied to the customer,\n * trial mode or not. It is read here now: the two write ports (`reply`,\n * `state`) are swapped for `adapters/recording-ports.ts`'s recorders and\n * `send` is forced to `{mode: 'none'}`, so the graph runs in FULL (LLM\n * included, §0's arbitrage) and reaches no external action. A trial run that\n * would have sent therefore comes back with `outcome: 'sent'` having sent\n * nothing, and is persisted as `ready` — the draft stays visible for §6's\n * parity control, and `ready` is the one status that says \"a human owns this\n * text now\". `awaiting_approval` raises no approval in a trial: granting one\n * would hand `handle-approval` a real send to perform.\n *\n * The claim→post→commit send seam (`functions/claim-commit.ts`) only covers\n * the ONE outcome where `act` actually runs (`sent`, and the narrow\n * `guardrail_hold` `act` itself can still produce post-claim — see below);\n * every other outcome (`ready`, `needs_human`, `awaiting_approval`,\n * `no_reply_needed`, `failed`, the pre-claim `guardrail_hold`) is written\n * directly here, since `act`/the claim were never reached for them.\n */\nimport type { AppApiRecord, AppHandler, FunctionDef } from '@apotech-os/app-kit';\nimport { AppApiError } from '@apotech-os/app-kit';\nimport { createBudget } from '../graph/budget';\nimport { runTicket } from '../graph/run-ticket';\nimport type { Classification, ConversationRef, DraftAttribution } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport { assertTransition, openTicketKeyFor, type GeneratedResponseStatus } from '../status/machine';\nimport { buildSendSeam } from './claim-commit';\nimport { buildApprovalKey, buildInboxKey } from './approval-key';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { withRecordingWritePorts } from '../adapters/recording-ports';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS, getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { createNoToolContext } from './no-tool-context';\nimport { buildPromptsTable, draftPromptRefFor, resolveDraftAgent, toAgent, toCategory } from './records';\n\n/**\n * Rebuilds the `Classification` `runTicket`'s `resume` needs, field-for-field\n * off the `triage-decision` row `triage-tick` wrote. `isFallback` is always\n * `false`: a `generated-response` is only ever created for a triage that\n * SUCCEEDED (`triage-tick` writes `status:'error'` and stops on a failed\n * classification, never creating one) — see `functions/eligibility.ts`.\n */\nfunction classificationFromDecision(decision: AppApiRecord): Classification {\n const data = decision.data as Record<string, unknown>;\n return {\n category: (data.tag as string) ?? '',\n confidence: (data.confidence as 'high' | 'low') ?? 'low',\n reasoning: (data.reasoning as string) ?? '',\n isFallback: false,\n conversationOver: (data.conversationOver as boolean | undefined) ?? false,\n };\n}\n\n/**\n * §3.4's four Langfuse columns, off the attribution the draft carries (B2).\n * WITHOUT a writer here `ext-fast-response-check` served `null` on every hit,\n * the extension echoed those nulls back, and `ext-response-comparison`'s\n * dataset/score capture — gated on a non-empty trace id — never fired for a\n * single pipeline response: the improvement loop had nothing to score.\n *\n * A run that produced no draft (a failed one) writes explicit `null`s rather\n * than nothing: the ids of a call that never finished would point the loop at\n * a generation nobody read.\n */\nfunction attributionFields(attribution: DraftAttribution | undefined): Record<string, unknown> {\n return {\n langfuseTraceId: attribution?.traceId ?? null,\n langfuseObservationId: attribution?.observationId ?? null,\n promptName: attribution?.promptName ?? null,\n promptVersion: attribution?.promptVersion ?? null,\n };\n}\n\nasync function finalizeNonSent(\n ctx: SupportKitHandlerContext,\n id: string,\n ticketId: string,\n toStatus: GeneratedResponseStatus,\n extra: Record<string, unknown>,\n): Promise<boolean> {\n assertTransition('pending', toStatus);\n try {\n await ctx.api.update(\n 'generated-response',\n id,\n { status: toStatus, openTicketKey: openTicketKeyFor(toStatus, ticketId), ...extra },\n { ifMatch: { status: 'pending' } },\n );\n return true;\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) {\n ctx.logger.info(`process-response: generated-response ${id} was already moved off \"pending\" by another worker, abandoning`);\n return false;\n }\n throw err;\n }\n}\n\nexport function buildProcessResponseFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'process-response'),\n name: 'process-response',\n trigger: { type: 'dbEvent', objectRef: `app:${config.slug}/generated-response`, operation: 'created' },\n retries: 3,\n concurrency: 3,\n notify: { onFailure: true, severity: 'warning' },\n };\n}\n\nexport function createProcessResponseHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx) => processResponseHandler(ctx, config);\n}\n\nexport async function processResponseHandler(ctx: SupportKitHandlerContext, config: SupportKitFunctionConfig): Promise<void> {\n const recordId = ctx.event.recordId as string | undefined;\n if (!recordId) {\n ctx.logger.warn('process-response: event carried no recordId, skipping');\n return;\n }\n\n const record = await getOptional(ctx, 'generated-response', recordId);\n if (!record) {\n ctx.logger.info(`process-response: generated-response ${recordId} no longer exists, skipping`);\n return;\n }\n const data = record.data as Record<string, unknown>;\n if (data.status !== 'pending') {\n ctx.logger.info(`process-response: generated-response ${recordId} is not pending (status=\"${String(data.status)}\"), skipping — already handled or a dbEvent redelivery`);\n return;\n }\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n if (validateSettings(settings as unknown as Record<string, unknown>).length > 0) {\n ctx.logger.info('process-response: settings invalid, skipping');\n return;\n }\n\n const ticketId = data.ticketId as string;\n const ref: ConversationRef = { id: ticketId, channel: 'gorgias' };\n\n const decision = await getOptional(ctx, 'triage-decision', (data.triageDecisionId as string) ?? null);\n if (!decision) {\n ctx.logger.error(`process-response: generated-response ${recordId} has no resolvable triage-decision, marking failed`);\n await finalizeNonSent(ctx, recordId, ticketId, 'failed', { error: 'triage-decision not found' });\n return;\n }\n const classification = classificationFromDecision(decision);\n const escalated = (decision.data as Record<string, unknown>).escalated === true;\n\n const categoryRecord = await getOptional(ctx, 'category', (data.categoryId as string | null) ?? null);\n const category = categoryRecord ? toCategory(categoryRecord) : null;\n const agentRecord = (data.agentId as string | null)\n ? await getOptional(ctx, 'agent', data.agentId as string)\n : null;\n const agent = agentRecord ? toAgent(agentRecord) : await resolveDraftAgent(ctx.api, null);\n\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));\n\n const dryRun = settings.dryRun === true;\n // Every completion of this ticket under one Langfuse session (§3.4's\n // quality loop reads a conversation, not a pile of orphan generations).\n const trace = { sessionId: ticketId, tags: [`app:${config.slug}`] };\n const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx, trace), ctx.api) : buildTicketPorts(ctx, trace);\n const { clock } = ports;\n\n // Generation-time snapshot for `act`'s divergence baseline WHEN this\n // record is later replayed through `handle-approval` (design decision (a)\n // in T22's brief): a `handle-approval` run has no live conversation read\n // of its own to source these from, and `act` always re-reads for real\n // before posting regardless (I8), so a snapshot taken here — moments\n // before `runTicket`'s own `fetchContext` re-read — is close enough\n // without weakening send safety.\n const conversationSnapshot = await ports.conversation.read(ref);\n\n const generatedAt = data.generatedAt instanceof Date ? data.generatedAt : new Date(data.generatedAt as string);\n const seam = buildSendSeam({\n api: ctx.api,\n clock,\n id: recordId,\n ticketId,\n fromStatus: 'pending',\n extraClaimData: (run) => ({\n responseText: run.draft.text,\n sources: run.draft.sources,\n verdict: run.verdict,\n generatedMessageCount: conversationSnapshot.messageCount,\n generatedLastMessageAt: conversationSnapshot.lastMessageAt,\n ...attributionFields(run.draft.attribution),\n }),\n });\n\n const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n\n const result = await runTicket(\n {\n ref,\n profile,\n ports,\n toolContext: createNoToolContext(),\n budget,\n category: { autoReplyEnabled: category?.autoReplyEnabled ?? false, minConfidence: null },\n categories: [],\n log: (msg) => ctx.logger.debug(msg),\n send: dryRun ? { mode: 'none' } : { mode: 'claimed', claim: seam.claim, commit: seam.commit },\n queuedAt: generatedAt,\n },\n { resume: { classification, escalated } },\n );\n\n const draftExtra = {\n responseText: result.draft?.text ?? null,\n sources: result.draft?.sources ?? [],\n verdict: result.verdict ?? null,\n generatedMessageCount: conversationSnapshot.messageCount,\n generatedLastMessageAt: conversationSnapshot.lastMessageAt,\n ...attributionFields(result.draft?.attribution),\n };\n\n switch (result.outcome) {\n case 'sent':\n // Nothing was sent on a dry run — `send: {mode: 'none'}` means no\n // claim/commit ever ran, so this record is still `pending` and would\n // stay there forever if this returned like the live path does.\n if (dryRun) {\n await finalizeNonSent(ctx, recordId, ticketId, 'ready', draftExtra);\n return;\n }\n // Already fully persisted by `seam.claim`/`seam.commit` inside `act`.\n return;\n case 'ready':\n case 'guardrail_hold':\n // `run-ticket.ts`'s own `finish()` doc: both are \"ready + a tag\", the\n // tag alone (already applied by `finish` via `StatePort.flag`)\n // distinguishes them for a human — the record's `status` does not.\n await finalizeNonSent(ctx, recordId, ticketId, 'ready', draftExtra);\n return;\n case 'needs_human': {\n const persisted = await finalizeNonSent(ctx, recordId, ticketId, 'ready', draftExtra);\n if (persisted) {\n await ctx.api.inbox.raise({\n key: buildInboxKey(recordId),\n severity: 'warning',\n title: `Réponse générée à revoir — ticket ${ticketId}`,\n entityRef: { appSlug: config.slug, objectKey: 'generated-response', id: recordId },\n });\n }\n return;\n }\n case 'awaiting_approval': {\n const persisted = await finalizeNonSent(ctx, recordId, ticketId, 'ready', draftExtra);\n if (persisted && !dryRun) {\n await ctx.api.approvals.request({\n key: buildApprovalKey(recordId),\n title: `Approuver l'envoi automatique — ticket ${ticketId}`,\n entityRef: { appSlug: config.slug, objectKey: 'generated-response', id: recordId },\n });\n }\n return;\n }\n case 'escalated':\n case 'triaged_only':\n case 'no_reply_needed':\n await finalizeNonSent(ctx, recordId, ticketId, 'no_reply_needed', draftExtra);\n return;\n case 'failed':\n await finalizeNonSent(ctx, recordId, ticketId, 'failed', { ...draftExtra, error: 'runTicket outcome: failed' });\n return;\n default:\n // `outcome` is `null` only mid-run — `runTicket` never returns it on\n // a resumed call (every path through `finish()` sets one).\n ctx.logger.error(`process-response: generated-response ${recordId} resumed run ended with no outcome`);\n }\n}\n","/**\n * `transitionGeneratedResponse` (M8 hardening) — the ONE conditional\n * `generated-response` status-write shape shared by every caller that only\n * needs to move a row from one status to another (S5 `ifMatch` + tolerate a\n * lost race as \"someone else already moved it\", not an error): `sweep`'s\n * `ready -> expired` TTL pass and `ext-fast-response-check`'s\n * `ready -> expired|invalidated` flips used to be two independent\n * implementations of the identical transition on the identical record —\n * anything added to one (a stamp, a metric, a different 409 policy) would\n * silently not happen on the other.\n *\n * Deliberately NOT used by `claim-commit.ts`'s `buildSendSeam` or\n * `sweep.ts`'s stalled-sending/stalled-pending passes: those write EXTRA\n * fields the caller computes from the in-flight `run`/reclaim shape\n * (`sendingAt`, `reclaimStalledSend()`'s `autoSendDecision` hold, the\n * `error` message) on the SAME atomic write, which this narrow helper's\n * `extra` param supports but was not the reported duplication — scope kept\n * to the transition the review actually flagged as duplicated.\n */\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { SupportKitApi } from '../adapters/api';\nimport { assertTransition, openTicketKeyFor, type GeneratedResponseStatus } from '../status/machine';\n\nexport interface TransitionGeneratedResponseParams {\n id: string;\n ticketId: string;\n from: GeneratedResponseStatus;\n to: GeneratedResponseStatus;\n /** Extra fields persisted on the SAME conditional write, alongside `status`/`openTicketKey`. */\n extra?: Record<string, unknown>;\n}\n\n/**\n * Attempts `from -> to` under `ifMatch: {status: from}`. Returns `true` when\n * the write landed, `false` when the row had already moved (a lost race —\n * not an error, exactly the same outcome either way for every caller today).\n */\nexport async function transitionGeneratedResponse(api: SupportKitApi, params: TransitionGeneratedResponseParams): Promise<boolean> {\n const { id, ticketId, from, to, extra } = params;\n assertTransition(from, to);\n try {\n await api.update(\n 'generated-response',\n id,\n { status: to, openTicketKey: openTicketKeyFor(to, ticketId), ...(extra ?? {}) },\n { ifMatch: { status: from } },\n );\n return true;\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) return false;\n throw err;\n }\n}\n","/**\n * `sweep` (§3.5) — cron function. Three independent janitor passes over\n * `generated-response`:\n * 1. `ready` rows past `expiresAt` → `expired` (the extension's TTL check\n * mirrored server-side, so a stale draft cannot be served forever).\n * 2. `sending` rows stuck past 30 minutes (a crash between `claim` and\n * `commit`, I9) → reclaimed to `ready` + `autoSendDecision: 'hold'`\n * via `reclaimStalledSend()` (`status/machine.ts`) — NEVER `status`\n * alone, which `reclaimStalledSend`'s own doc calls out as the one\n * write shape that would re-open the record as a legal, un-held claim\n * target and risk RE-SENDING the reply. Every reclaimed ticket is\n * handed to a human: the escalation tag is applied and an Inbox alert\n * raised, since a stuck send is exactly the kind of thing nobody\n * should have to notice on their own.\n * 3. `pending` rows past `expiresAt` → `failed` (T22 hardening, A3 — see\n * that pass's own doc below for why it exists).\n *\n * `sweep` never posts a reply and never calls the claim/commit seam — it\n * only ever touches `generated-response` rows and the Gorgias tag/alert\n * surfaces, which is what makes §8.4's invariant 2 (\"never re-sent\")\n * checkable against it directly.\n *\n * Known limitation: `SupportKitApi.list` carries no cursor, so a sweep pass\n * reads at most one page of `ready`/`sending`/`pending` rows. Acceptable for\n * now — all three sets are normally small and short-lived — but a tenant\n * with a large backlog would need pagination added to the interface first.\n *\n * SETTINGS VALIDATION (T22 hardening, C — a deliberate exemption, not an\n * omission): `sweep` does NOT call `validateSettings` the way the other\n * three handlers do, because it must keep reclaiming stalled sends even on\n * a tenant whose settings are currently incomplete — that reclaim is a\n * safety net, not a feature an operator opted into, and refusing to run it\n * on a misconfigured app would leave a stuck `sending` row (and a customer\n * who may or may not have already been emailed) unattended for longer, not\n * shorter. What IS guarded is the one settings field this file actually\n * reads, `escalationTag`: on an unconfigured tenant it used to be\n * `undefined`, and `StatePort.flag` calling `.trim()` on it threw a\n * `TypeError` mid-loop — with `retries: 0` that killed the rest of the\n * reclaim pass AND skipped `lastSweepAt`. Routing it through\n * `settingsToProfile` instead (as first suggested) would trade this crash\n * for a different one: that mapper dereferences `settings.nodes.triage.model`\n * unconditionally (`baseNode`), which throws just as readily on the exact\n * kind of incomplete settings blob this guard exists for. A direct,\n * narrow-scoped type check on the one field actually read is what stays\n * safe without introducing a new crash surface.\n */\nimport type { AppHandler, FunctionDef } from '@apotech-os/app-kit';\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { ConversationRef } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { createGorgiasStatePort, createRealClock } from '../adapters/ctx-ports';\nimport { assertTransition, openTicketKeyFor, reclaimStalledSend } from '../status/machine';\nimport { buildInboxKey } from './approval-key';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { transitionGeneratedResponse } from './generated-response-transition';\nimport { readPipelineState, toDate, upsertPipelineState } from './pipeline-state';\n\nconst STALE_SENDING_THRESHOLD_MS = 30 * 60_000;\nconst SWEEP_PAGE_SIZE = 500;\n\nexport function buildSweepFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'sweep'),\n name: 'sweep',\n trigger: { type: 'cron', pattern: '*/5 * * * *' },\n retries: 0,\n concurrency: 1,\n notify: { onFailure: true, severity: 'warning' },\n };\n}\n\nexport function createSweepHandler(): AppHandler {\n return (ctx) => sweepHandler(ctx);\n}\n\nexport async function sweepHandler(ctx: SupportKitHandlerContext): Promise<void> {\n const clock = createRealClock();\n const now = clock.now();\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const statePort = createGorgiasStatePort(ctx.api);\n // A narrow, defensive read — see this module's header doc (C) for why the\n // full `settingsToProfile` mapping is not used here.\n const escalationTag = typeof settings?.escalationTag === 'string' ? settings.escalationTag : '';\n if (!escalationTag) {\n ctx.logger.warn('sweep: escalationTag is not configured — a stalled-send reclaim will proceed without an escalation tag');\n }\n\n await sweepExpiredReady(ctx, now);\n await sweepStalledSending(ctx, now, escalationTag, statePort);\n await sweepStalledPending(ctx, now);\n\n await upsertPipelineState(ctx.api, { lastSweepAt: now });\n}\n\nasync function sweepExpiredReady(ctx: SupportKitHandlerContext, now: Date): Promise<void> {\n const page = await ctx.api.list('generated-response', { filter: { status: 'ready' }, limit: SWEEP_PAGE_SIZE });\n for (const row of page.items) {\n const expiresAt = toDate(row.data.expiresAt);\n if (!expiresAt || expiresAt.getTime() > now.getTime()) continue;\n\n // M8: the SAME `ready -> expired` conditional transition\n // `ext-fast-response-check`'s own TTL flip uses — see that module's\n // shared helper's own doc for why this used to be two independent\n // copies of the identical write.\n await transitionGeneratedResponse(ctx.api, { id: row.id, ticketId: row.data.ticketId as string, from: 'ready', to: 'expired' });\n }\n}\n\nasync function sweepStalledSending(\n ctx: SupportKitHandlerContext,\n now: Date,\n escalationTag: string,\n statePort: ReturnType<typeof createGorgiasStatePort>,\n): Promise<void> {\n const page = await ctx.api.list('generated-response', { filter: { status: 'sending' }, limit: SWEEP_PAGE_SIZE });\n for (const row of page.items) {\n const sendingAt = toDate(row.data.sendingAt);\n if (!sendingAt || now.getTime() - sendingAt.getTime() < STALE_SENDING_THRESHOLD_MS) continue;\n\n assertTransition('sending', 'ready');\n const ticketId = row.data.ticketId as string;\n let reclaimed: boolean;\n try {\n await ctx.api.update(\n 'generated-response',\n row.id,\n {\n // Status AND the hold together, in the SAME write — see the\n // module doc and `reclaimStalledSend`'s own doc for why splitting\n // this into two writes (or dropping the hold) would re-open the\n // record as a sendable `ready` row.\n ...reclaimStalledSend(),\n openTicketKey: openTicketKeyFor('ready', ticketId),\n },\n { ifMatch: { status: 'sending' } },\n );\n reclaimed = true;\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) {\n reclaimed = false; // already moved by another worker (e.g. a late commit landing)\n } else {\n throw err;\n }\n }\n if (!reclaimed) continue;\n\n const ref: ConversationRef = { id: ticketId, channel: 'gorgias' };\n await statePort.flag(ref, escalationTag);\n await ctx.api.inbox.raise({\n key: buildInboxKey(row.id, 'stalled-send'),\n severity: 'warning',\n title: `Envoi bloqué détecté — ticket ${ticketId}`,\n body: 'La réponse est restée en statut \"sending\" plus de 30 minutes et a été replacée en attente humaine.',\n });\n }\n}\n\n/**\n * A3: a `pending` row whose `process-response` handler threw is orphaned\n * FOREVER without this pass. `process-response` runs with `retries: 3`; once\n * those are exhausted the dbEvent is gone and nothing ever revisits the row\n * — `sweep`'s other two passes only ever scan `ready`/`sending`, never\n * `pending`. Worse, the stuck row keeps `openTicketKey` set (only a\n * TERMINAL status clears it, `openTicketKeyFor`'s own doc), so the unique\n * index makes any FUTURE `triage-tick` create for the same ticket 409\n * forever — that ticket could never be drafted again by any later tick.\n *\n * Chosen over the brief's other option (a top-level catch inside\n * `process-response` itself, finalising straight to `failed`): the row\n * already carries `expiresAt` (set at generation time, independent of\n * status), so this reuses the exact same staleness idiom `sweepExpiredReady`\n * above already established, instead of adding a second, different\n * failure-handling shape to `process-response`. It also covers cases a\n * try/catch inside the handler cannot — a dbEvent that never delivers at\n * all, or a process that dies before any `catch` runs.\n */\nasync function sweepStalledPending(ctx: SupportKitHandlerContext, now: Date): Promise<void> {\n const page = await ctx.api.list('generated-response', { filter: { status: 'pending' }, limit: SWEEP_PAGE_SIZE });\n for (const row of page.items) {\n const expiresAt = toDate(row.data.expiresAt);\n if (!expiresAt || expiresAt.getTime() > now.getTime()) continue;\n\n assertTransition('pending', 'failed');\n try {\n await ctx.api.update(\n 'generated-response',\n row.id,\n { status: 'failed', openTicketKey: openTicketKeyFor('failed', row.data.ticketId as string), error: 'orphaned pending row past its TTL (sweep)' },\n { ifMatch: { status: 'pending' } },\n );\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) continue; // already moved by another worker\n throw err;\n }\n }\n}\n\n","/**\n * `handle-approval` (§3.5) — event function, triggered on\n * `APPROVAL_DECIDED_EVENT` (`app.approval.decided`) for an approval\n * `process-response`'s `awaiting_approval` outcome requested.\n *\n * SEND PATH SHARING (§8.4's \"no forked second send implementation\"):\n * - `functions/claim-commit.ts`'s `buildSendSeam` is the SAME\n * claim/commit persistence pair `process-response` wires as\n * `NodeDeps.send` — only `fromStatus` differs ('pending' there,\n * 'ready' here).\n * - The actual reply-posting/anti-collision logic is `act`\n * (`graph/nodes/act.ts`) itself, called DIRECTLY here (there is no\n * triage/draft/evaluate to redo — only the send step remains), rather\n * than re-implemented.\n *\n * Rebuilding `act`'s `state.conversation` argument from stored fields is a\n * DELIBERATELY NARROW contract, verified by reading `act.ts` line by line\n * (T22): it reads exactly THREE fields off that argument —\n * `sourceChannel` (the email/whatsapp branch), `messageCount` and\n * `lastMessageAt` (the divergence check against its OWN fresh re-read,\n * `deps.ports.conversation.read`). Every other `Conversation` field\n * (`subject`, `messages`, `customer`, `isClosed`, `lastAgentReplyAt`,\n * `hasCustomerAttachment`) is read off the FRESH re-read `act` performs\n * itself, never off this placeholder — which is why they can be filled with\n * inert defaults below. If `act` ever starts reading more off its\n * `generatedFrom` argument, this placeholder silently stops being enough;\n * there is no compile-time guard for that today.\n */\nimport type { AppApiRecord, AppHandler, ApprovalDecidedPayload, FunctionDef } from '@apotech-os/app-kit';\nimport { APPROVAL_DECIDED_EVENT, AppApiError } from '@apotech-os/app-kit';\nimport { createBudget } from '../graph/budget';\nimport { act } from '../graph/nodes';\nimport { applyOutcomeTags } from '../graph/run-ticket';\nimport { initialState } from '../graph/state';\nimport type { Conversation, ConversationRef, Draft, ProposedAction, Verdict } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport { assertTransition, openTicketKeyFor } from '../status/machine';\nimport { parseApprovalKey } from './approval-key';\nimport { buildSendSeam } from './claim-commit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { createNoToolContext } from './no-tool-context';\nimport { buildPromptsTable, draftPromptRefFor } from './records';\n\nexport function buildHandleApprovalFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'handle-approval'),\n name: 'handle-approval',\n trigger: { type: 'event', name: APPROVAL_DECIDED_EVENT },\n retries: 3,\n // No `notify` — §3.5's table gives only the first three functions one.\n };\n}\n\nexport function createHandleApprovalHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx) => handleApprovalHandler(ctx, config);\n}\n\nexport async function handleApprovalHandler(ctx: SupportKitHandlerContext, config: SupportKitFunctionConfig): Promise<void> {\n const payload = ctx.event as unknown as ApprovalDecidedPayload;\n const id = parseApprovalKey(payload.key);\n if (!id) {\n ctx.logger.debug(`handle-approval: key \"${payload.key}\" is not a generated-response approval, ignoring`);\n return;\n }\n\n const record = await getOptional(ctx, 'generated-response', id);\n if (!record) {\n ctx.logger.info(`handle-approval: generated-response ${id} no longer exists, skipping`);\n return;\n }\n const data = record.data as Record<string, unknown>;\n if (data.status !== 'ready') {\n ctx.logger.info(`handle-approval: generated-response ${id} is not ready (status=\"${String(data.status)}\"), skipping — already handled or reclaimed`);\n return;\n }\n const ticketId = data.ticketId as string;\n\n if (payload.status === 'rejected') {\n try {\n await ctx.api.update('generated-response', id, { autoSendDecision: 'hold' }, { ifMatch: { status: 'ready' } });\n } catch (err) {\n if (!(err instanceof AppApiError && err.status === 409)) throw err;\n }\n return;\n }\n\n // §8.4 invariant 2's crux: a record the sweep reclaimed to `ready` carries\n // `autoSendDecision: 'hold'` — `status: 'ready'` alone makes it look like\n // an ordinary claimable draft again, but the hold means it may ONLY leave\n // this state through a FRESH approval request, never a silent resend of a\n // decision that already fired once. Nothing else in the pipeline checks\n // `autoSendDecision` before attempting to send (`act` itself has no idea\n // it exists) — this is the one place that gate has to live.\n if (data.autoSendDecision === 'hold') {\n ctx.logger.warn(`handle-approval: generated-response ${id} is on hold (autoSendDecision), refusing to send despite the approval`);\n return;\n }\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n ctx.logger.info('handle-approval: settings invalid, skipping', { issues });\n return;\n }\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(null, config), settings.nodes));\n\n // Empty-draft guard (T22 hardening, B3): `draft.text` below falls back to\n // `''` on a missing `responseText`, and `act` only refuses a MISSING draft\n // object, never an empty one — nothing today can reach this (every\n // `generated-response` reaching `ready` came through `process-response`,\n // which always writes a real `responseText`), but a future caller of\n // `finalizeNonSent`/a hand-edited record could leave one blank, and this\n // is the last line of defence before an empty email goes out. `ready ->\n // invalidated` is a legal transition (`status/machine.ts`) for exactly\n // this kind of \"this record cannot be acted on as-is\" case.\n const responseText = (data.responseText as string | null | undefined) ?? '';\n if (responseText.trim().length === 0) {\n ctx.logger.error(`handle-approval: generated-response ${id} has no responseText, refusing to send an empty reply`);\n assertTransition('ready', 'invalidated');\n try {\n await ctx.api.update('generated-response', id, { status: 'invalidated', openTicketKey: openTicketKeyFor('invalidated', ticketId) }, { ifMatch: { status: 'ready' } });\n } catch (err) {\n if (!(err instanceof AppApiError && err.status === 409)) throw err;\n }\n return;\n }\n\n const ports = buildTicketPorts(ctx);\n const { clock, state: statePort } = ports;\n\n const conversation: Conversation = {\n ref: { id: ticketId, channel: 'gorgias' },\n subject: null,\n messages: [],\n customer: { name: null, email: null, orderContext: null },\n isClosed: false,\n lastMessageAt: data.generatedLastMessageAt ? new Date(data.generatedLastMessageAt as string) : null,\n messageCount: (data.generatedMessageCount as number | undefined) ?? 0,\n lastAgentReplyAt: null,\n hasCustomerAttachment: false,\n sourceChannel: data.channel as string,\n };\n const draft: Draft = { text: responseText, sources: (data.sources as Draft['sources']) ?? [], revised: false };\n const proposedActions: ProposedAction[] = [{ kind: 'send_reply', args: {}, idempotencyKey: id, decision: 'auto' }];\n\n // Tracks the seam's OWN claim result (T22 hardening, B2) rather than\n // re-reading the record afterwards: `act` returns `{}` with zero\n // guardrail hits BOTH when the send actually completed AND when\n // `send.claim` returned `false` (another worker already claimed this row\n // — a concurrent decision or a retried delivery of this very event), so a\n // caller that only inspects `patch` cannot tell the two apart. Capturing\n // the seam's own return value is what `buildSendSeam`'s doc already names\n // as the deciding signal — surfaced here instead of silently discarded.\n const seam = buildSendSeam({ api: ctx.api, clock, id, ticketId, fromStatus: 'ready' });\n let claimed = true;\n const trackedSeam = {\n claim: async (run: Parameters<typeof seam.claim>[0]) => {\n claimed = await seam.claim(run);\n return claimed;\n },\n commit: seam.commit,\n };\n const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: 1 });\n const ref: ConversationRef = { id: ticketId, channel: 'gorgias' };\n const verdict = (data.verdict as Verdict | undefined) ?? null;\n\n const patch = await act(\n { ...initialState(), conversation, draft, verdict, proposedActions },\n {\n ref,\n profile,\n ports,\n toolContext: createNoToolContext(),\n budget,\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: [],\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'claimed', claim: trackedSeam.claim, commit: trackedSeam.commit },\n queuedAt: data.generatedAt ? new Date(data.generatedAt as string) : null,\n },\n );\n\n const guardrailHits = patch.guardrailHits ?? [];\n if (guardrailHits.length === 0) {\n if (!claimed) {\n ctx.logger.warn(\n `handle-approval: generated-response ${id} claim was lost — a concurrent worker already advanced this record, nothing to persist here`,\n );\n return;\n }\n // `act` claimed, posted and committed — apply the SAME outcome tag\n // `process-response`'s resumed `runTicket` would have applied via\n // `finish()` (B1: one shared function, so the two send routes cannot\n // diverge on the audit trail §3.6 defines).\n await applyOutcomeTags('sent', verdict, { ports: { state: statePort }, ref, audit: profile.audit });\n return;\n }\n\n // `act`'s own guardrail checks (customer_email_missing/ticket_closed/\n // agent_replied/diverged/run_deadline) all run BEFORE `send.claim`, so a\n // hit here means the claim was NEVER attempted — the record is still\n // `ready`. `ready -> no_reply_needed` is not a legal transition\n // (`status/machine.ts`'s `ALLOWED_TRANSITIONS`), so — unlike\n // `process-response` — there is no legal status change to make here; the\n // record stays `ready`. What DOES change is `autoSendDecision: 'hold'`,\n // so the very next approval decision cannot walk straight back into the\n // same hit, plus the escalation tag `applyOutcomeTags('guardrail_hold', …)`\n // applies for a human to look at why the send never went out.\n try {\n await ctx.api.update('generated-response', id, { autoSendDecision: 'hold' }, { ifMatch: { status: 'ready' } });\n } catch (err) {\n if (!(err instanceof AppApiError && err.status === 409)) throw err;\n }\n await applyOutcomeTags('guardrail_hold', verdict, { ports: { state: statePort }, ref, audit: profile.audit });\n}\n","/**\n * Stable universal identifiers for the T23 `uiInvoke` functions' `input`\n * field defs (§3.5) — same convention as `records/ids.ts`: generated once\n * and committed, never regenerated (a function's `input` is diffed by these\n * ids, not by field name).\n */\n/** Renamed from `dryRun` (T23 post-review D) — same field identity, same uid, honest name: it bypasses the `triageEnabled` kill switch and runs the real batch, the opposite of what \"dry run\" means everywhere else in this kit. */\nexport const RUN_TRIAGE_NOW_INPUT_IGNORE_TRIAGE_DISABLED_UID = 'dd175229-feee-4306-a429-b25ea5dd89e4';\n\nexport const PREVIEW_TRIAGE_INPUT_TICKET_ID_UID = 'b9d5da91-ce08-4aac-ae52-5ffef730fab0';\n\nexport const GRAPH_DRY_RUN_INPUT_TICKET_ID_UID = '5861e7be-3a28-4852-874c-1c14e82d4b35';\nexport const GRAPH_DRY_RUN_INPUT_CATEGORY_ID_UID = 'c47b8b57-6f7a-47d7-a9d1-a18fbf71a0f0';\nexport const GRAPH_DRY_RUN_INPUT_AGENT_ID_UID = '95d38506-bc22-4f91-ad43-797ff7b54f48';\nexport const GRAPH_DRY_RUN_INPUT_OVERRIDES_UID = '306a4f7d-db5d-4144-a6bd-865889e152e2';\n/** The pasted-ticket mode: `{body, subject?, channel?}` replacing `ticketId`, so the graph can be replayed with no Gorgias ticket at all. */\nexport const GRAPH_DRY_RUN_INPUT_INLINE_TICKET_UID = '2abcc895-2751-4944-b527-78bc4604eed0';\n\nexport const TEST_AGENTS_INPUT_VIEW_ID_UID = '20227a8f-95d8-4c20-a9cd-eccb0ce39e3e';\nexport const TEST_AGENTS_INPUT_TICKET_IDS_UID = '7d27acff-b558-4783-a3ac-722f676b71a7';\nexport const TEST_AGENTS_INPUT_AGENT_ID_UID = 'ea12d731-708b-4fcc-9ebb-6c4e0d04a60e';\nexport const TEST_AGENTS_INPUT_LIMIT_UID = '95151bdf-2966-41cd-8b6f-c5b0b10c427e';\n\nexport const SUGGEST_PROMPT_INPUT_AGENT_ID_UID = '40509afa-5931-419d-8467-a52cbac5c17e';\nexport const SUGGEST_PROMPT_INPUT_MAX_COMPARISONS_UID = '0c2e2f58-ffd3-4aee-a1b4-cb81d1762eb6';\n\nexport const RUN_DIFF_ANALYSIS_INPUT_AGENT_ID_UID = 'bfe1e895-1608-40d8-99e9-230ab9c41473';\nexport const RUN_DIFF_ANALYSIS_INPUT_LIMIT_UID = 'b1936472-a9dc-4b0b-8ef6-ab84733a2bfa';\n\nexport const LIST_GORGIAS_VIEWS_INPUT_CHECK_APP_SLUGS_UID = '1ac5eb02-32da-4fd4-9462-dac4ff23b208';\n\n/**\n * T26 rework (BLOCKER 3) — `create-agent`'s own `input` field defs. Assigns\n * the new agent's `promptName` server-side (`agent/<recordId>`, §3.4) — see\n * that function's own doc for why a plain `POST records/agent` cannot.\n */\nexport const CREATE_AGENT_INPUT_NAME_UID = '0cb57453-7b02-49ce-875b-7ff079a5810d';\nexport const CREATE_AGENT_INPUT_MODEL_ID_UID = 'f19f1c10-3145-482b-8c1d-6fd3576596ff';\nexport const CREATE_AGENT_INPUT_PROVIDER_UID = '0dd94db4-f31a-4cd2-b030-1b1a4da5b43e';\nexport const CREATE_AGENT_INPUT_SYSTEM_PROMPT_SNAPSHOT_UID = 'd50f3810-b6fe-4c90-b69b-3e36ba502cdb';\n\n/**\n * T26 rework (BLOCKER 4) — `set-default-agent`'s own `input` field def.\n * Demotes the incumbent default agent and promotes the target in one\n * server-side call — see that function's own doc for why two independent\n * client-side PATCHes cannot maintain the \"at most one default agent\"\n * invariant.\n */\nexport const SET_DEFAULT_AGENT_INPUT_AGENT_ID_UID = '0686c615-63f8-49a1-b3c7-3542bac76cd6';\n\n/**\n * T24 — the six reserved `ext-*` functions' `input` field defs (§5.2's\n * frozen wire payloads). `ext-models`/`ext-categories` have no input (the\n * gateway always sends `{}`), so they need none.\n */\nexport const EXT_CHAT_INPUT_MESSAGES_UID = '874e4408-74c0-4188-b923-a0791da4d096';\nexport const EXT_CHAT_INPUT_MODEL_ID_UID = 'd63f05b1-165d-45e0-9300-cabe5e22fa42';\nexport const EXT_CHAT_INPUT_AGENT_NAME_UID = '928f03e6-2d48-487e-85ee-15999b9cbbbb';\nexport const EXT_CHAT_INPUT_GORGIAS_TICKET_ID_UID = '86fcc5df-8545-4d77-b3d7-d741c6b1d5a5';\n\nexport const EXT_FAST_RESPONSE_CHECK_INPUT_TICKET_ID_UID = '4a597dbf-ba6f-4628-b526-759448e7ed17';\n\nexport const EXT_EVALUATION_INPUT_SATISFIED_UID = 'b1af323a-d1e0-40c7-b975-66a1e3cd4b21';\nexport const EXT_EVALUATION_INPUT_MESSAGES_UID = 'ea5d9df8-c7d5-459c-b25d-2cfe0b45ad45';\nexport const EXT_EVALUATION_INPUT_TICKET_URL_UID = '6648f361-e16b-46b2-a411-3d9cdf35e87a';\nexport const EXT_EVALUATION_INPUT_LANGFUSE_TRACE_ID_UID = '0d8d5556-2ffe-4d5e-aaca-55e0eab63066';\nexport const EXT_EVALUATION_INPUT_LANGFUSE_OBSERVATION_ID_UID = '8285ab1d-e20d-4088-b9b0-176236339d1c';\nexport const EXT_EVALUATION_INPUT_MODEL_ID_UID = '1646f686-57d9-4204-b901-9d7a8e1a8078';\n\nexport const EXT_RESPONSE_COMPARISON_INPUT_LAST_MESSAGE_GENERATED_UID = 'f2ad97ac-0abf-449a-9cc3-72efff6723c6';\nexport const EXT_RESPONSE_COMPARISON_INPUT_MESSAGE_ACTUAL_SENT_UID = '2dfe91f9-7177-4c44-8bcb-f841ff399ce0';\nexport const EXT_RESPONSE_COMPARISON_INPUT_TICKET_ID_UID = '63afd37e-4f0f-411b-aa62-6f480ef6cd3c';\nexport const EXT_RESPONSE_COMPARISON_INPUT_TICKET_URL_UID = '295c10ef-cb7c-4409-876a-1e384cfe6f45';\nexport const EXT_RESPONSE_COMPARISON_INPUT_MODEL_CONFIG_ID_UID = 'c48778a5-a8f5-4ee7-92b7-66de1bb543be';\nexport const EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_TRACE_ID_UID = '5113fc86-3865-4110-b65f-c91748816f02';\nexport const EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_OBSERVATION_ID_UID = 'e5310144-8004-4c20-9ce4-9c0c820e3577';\nexport const EXT_RESPONSE_COMPARISON_INPUT_PROMPT_NAME_UID = '4813f09d-88ac-4574-8f38-be5f87a6c9ac';\nexport const EXT_RESPONSE_COMPARISON_INPUT_PROMPT_VERSION_UID = 'e87e65e8-e078-47e3-92b7-104368952a56';\nexport const EXT_RESPONSE_COMPARISON_INPUT_CONVERSATION_MESSAGES_UID = '0a985d59-fd20-4672-91bb-4824b8dfb026';\n\n/**\n * T27 part B — `create-shared-prompt-version`'s own `input` field defs\n * (§3.8 SharedPromptsPage). Validates `@@@langfusePrompt:…@@@` composition\n * tags through `validateReferences` before writing (see that function's\n * own doc) — the ONE write path this page uses, scoped to `shared/*` names.\n */\nexport const CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID = '1039e196-cf6e-438e-8ec9-7ab422feaf4d';\nexport const CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID = '10ffe3e1-972e-43b4-bb45-343c4664464f';\n\n/**\n * `sync-agent-prompt-snapshot`'s own `input` field def (§5.2) — the\n * background refresh of `agent.systemPromptSnapshot` after a `createVersion`\n * /`promote` on that agent's prompt.\n */\nexport const SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID = '2f5d6cbb-1c69-4a76-9d8f-1a3f0a4e57c2';\n","/**\n * `run-triage-now` (§3.5) — `uiInvoke`, manual trigger equivalent to the\n * legacy `POST /triage/run`, and `run-triage-batch`, the event-triggered\n * function that actually carries the batch out.\n *\n * WHY TWO FUNCTIONS (B5). `uiInvoke` is a SYNCHRONOUS request: the platform\n * runs the handler in-process under a wall clock capped at 30 s\n * (`app-sync-invocation.service.ts`'s `DEFAULT_INVOKE_TIMEOUT_MS`, clamped\n * by `APP_SYNC_INVOKE_MAX_MS`). `runTriageBatch` processes up to\n * `settings.batchLimit` tickets (30 by default) SEQUENTIALLY, each costing\n * one triage LLM call plus several Gorgias round trips — minutes, not\n * seconds. Running it inline meant a guaranteed 504 for the operator while\n * the handler kept going unattended, and a second click starting a SECOND\n * concurrent batch: `triage-decision` rows are `create`d, not upserted, so\n * that duplicated both the rows and the LLM bill (only `generated-response`\n * is deduplicated, by its `openTicketKey` unique index).\n *\n * So the invocation now does only what fits in a request — open the run,\n * emit the event — and answers with the `runId` to follow. The batch itself\n * runs in `run-triage-batch`, a durable event-triggered function with no\n * wall clock. This is the platform's own documented pairing: see\n * `AppRunHandle.reused`'s doc in `@apotech-os/app-kit` — \"what links the\n * `uiInvoke` that triggers a treatment to the asynchronous function that\n * carries it out\".\n *\n * RE-ENTRANCE GUARD. `runs.start` is idempotent on `(kind, key)` while a\n * non-terminal run exists, so the fixed `(MANUAL_TRIAGE_RUN_KIND,\n * MANUAL_TRIAGE_RUN_KEY)` pair IS the guard: a second trigger while a batch\n * is in flight gets `reused: true` back, emits nothing, and reports the run\n * already running. The platform holds that state, not this handler — two\n * concurrent invocations cannot both win it, which a read of\n * `pipeline-state.lastTriageAt` could not have guaranteed (its cadence gate\n * is also stamped by the scheduled `triage-tick`, so it cannot tell \"a\n * manual batch is running right now\" from \"a tick just finished\"). The\n * counterpart is that `run-triage-batch` MUST terminate the run on every\n * path, including failure — see its `try`/`catch` below — otherwise the\n * guard would hold the button closed for good.\n *\n * `input.ignoreTriageDisabled` mirrors the legacy `{dry_run}` body field —\n * renamed here (T23 post-review D): it lets an operator ask for a run while\n * `triageEnabled` is off (the settings-level kill switch stays authoritative\n * for `triage-tick`'s own cron, but a human clicking \"run now\" already\n * knows they are overriding it). The legacy name is not worth preserving —\n * §0 defines \"dry run\" as \"no external action\", three sibling functions\n * (`preview-triage`, `graph-dry-run`, `test-agents`) implement exactly that,\n * and this flag does the OPPOSITE: it bypasses a kill switch and runs the\n * real batch. `ignoreTriageDisabled` does NOT change what the batch\n * writes — this function ALWAYS classifies for real and ALWAYS writes\n * `triage-decision`/`generated-response` rows, exactly like a scheduled\n * tick, whether or not the flag is set. The legacy `/triage/run` never\n * wrote anything different for a \"dry run\" either (`dry_run` only bypassed\n * `triage_enabled`) — a fully side-effect-free \"would triage-tick run\"\n * preview is `preview-triage`'s job (single ticket) and `graph-dry-run`'s\n * (full graph), not this one's (a real batch).\n *\n * `minRole: 'EDITOR'`: triggering a real classification pass — which spends\n * LLM budget and can tag/escalate real tickets — is an editing action, not a\n * read. `VIEWER` (T24's `ext-*` floor) would let a read-only support agent\n * fire a batch run; that is not this function's threat model.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { RUN_TRIAGE_NOW_INPUT_IGNORE_TRIAGE_DISABLED_UID } from './ids';\nimport { runTriageBatch } from './triage-tick';\n\n/**\n * The app custom event `run-triage-now` emits and `run-triage-batch`\n * subscribes to. Must be declared in the consuming app's `manifest.emits`\n * (`buildSupportPipeline`'s `emits` fragment) — the platform rejects an\n * undeclared name with 403, and refuses to sync a manifest whose event\n * trigger names one it does not emit.\n */\nexport const TRIAGE_RUN_REQUESTED_EVENT = 'triage.run.requested';\n\n/** `(kind, key)` of the applicative run — fixed, because it IS the re-entrance guard (see this module's header doc). */\nexport const MANUAL_TRIAGE_RUN_KIND = 'run-triage-now';\nexport const MANUAL_TRIAGE_RUN_KEY = 'manual';\n\nexport interface RunTriageNowInput {\n /** Bypasses the `triageEnabled` kill switch and runs the real batch anyway — NOT a dry run (see this module's own header doc). */\n ignoreTriageDisabled?: boolean;\n}\n\nexport interface RunTriageNowResult {\n /** The applicative run to follow (`useAppRuns({kind: 'run-triage-now'})`) — the batch's outcome lives there, not in this response. */\n runId: string;\n /** `'already-running'` when the re-entrance guard matched an in-flight batch and nothing new was queued. */\n status: 'queued' | 'already-running';\n}\n\n/** Payload of `TRIAGE_RUN_REQUESTED_EVENT`, as `run-triage-batch` receives it (the unwrapped event data). */\nexport interface TriageRunRequestedPayload {\n runId?: string;\n ignoreTriageDisabled?: boolean;\n}\n\nexport function buildRunTriageNowFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'run-triage-now'),\n name: 'run-triage-now',\n // The handler is two API calls now, not a batch: a budget well under the\n // platform's 15 s default states that, and turns a hung platform call\n // into a fast error instead of a slow one.\n trigger: { type: 'uiInvoke', minRole: 'EDITOR', timeoutMs: 10_000 },\n input: [\n {\n universalIdentifier: RUN_TRIAGE_NOW_INPUT_IGNORE_TRIAGE_DISABLED_UID,\n name: 'ignoreTriageDisabled',\n type: FieldType.BOOLEAN,\n label: 'Ignore triageEnabled',\n description: 'Bypass the triageEnabled kill switch and run the real batch anyway. This is NOT a dry run — tickets are classified and tagged for real.',\n isNullable: true,\n },\n ],\n };\n}\n\n/**\n * `retries: 0` and `concurrency: 1`, for `triage-tick`'s own reasons: a\n * retried batch re-classifies (and re-bills) every ticket it already\n * handled and writes a second `triage-decision` for each, and two batches\n * running at once over the same view do the same. The re-entrance guard in\n * `run-triage-now` closes the operator-facing door; `concurrency: 1` closes\n * the platform-facing one.\n */\nexport function buildRunTriageBatchFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'run-triage-batch'),\n name: 'run-triage-batch',\n trigger: { type: 'event', name: TRIAGE_RUN_REQUESTED_EVENT },\n retries: 0,\n concurrency: 1,\n notify: { onFailure: true, severity: 'warning' },\n };\n}\n\nexport function createRunTriageNowHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => runTriageNowHandler(ctx as SupportKitHandlerContext, config, (input as RunTriageNowInput) ?? {});\n}\n\nexport function createRunTriageBatchHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) =>\n runTriageBatchEventHandler(ctx as SupportKitHandlerContext, config, (input as TriageRunRequestedPayload) ?? {});\n}\n\nexport async function runTriageNowHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: RunTriageNowInput,\n): Promise<RunTriageNowResult> {\n const ignoreTriageDisabled = input.ignoreTriageDisabled ?? false;\n // Both guards are re-checked by `run-triage-batch` (an event can also be\n // replayed): they run HERE so the operator gets the refusal in their own\n // request, as a message on screen, instead of a queued run that fails out\n // of sight.\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n assertRunnable(ctx, settings, ignoreTriageDisabled);\n\n const run = await ctx.api.runs.start({\n kind: MANUAL_TRIAGE_RUN_KIND,\n key: MANUAL_TRIAGE_RUN_KEY,\n message: 'Triage manuel demandé',\n metadata: { ignoreTriageDisabled },\n });\n if (run.reused) {\n ctx.logger.info('run-triage-now: a manual batch is already running, not queueing a second one', { runId: run.id });\n return { runId: run.id, status: 'already-running' };\n }\n\n try {\n // `_key` deduplicates the emission itself at the Inngest level, so a\n // retried invocation cannot fan out into two batches for one run.\n await ctx.api.events.send(TRIAGE_RUN_REQUESTED_EVENT, {\n _key: run.id,\n runId: run.id,\n ignoreTriageDisabled,\n });\n } catch (err) {\n // A run left open would keep the guard closed forever — nothing else\n // will ever terminate it, since no batch was queued.\n await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });\n throw err;\n }\n\n return { runId: run.id, status: 'queued' };\n}\n\nexport async function runTriageBatchEventHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n payload: TriageRunRequestedPayload,\n): Promise<void> {\n const { runId } = payload;\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n\n try {\n assertRunnable(ctx, settings, payload.ignoreTriageDisabled ?? false);\n const result = await runTriageBatch(ctx, config, settings);\n if (runId) await ctx.api.runs.succeed(runId, result);\n } catch (err) {\n if (runId) await ctx.api.runs.fail(runId, { message: err instanceof Error ? err.message : String(err) });\n throw err;\n }\n}\n\n/** The two refusals shared by the trigger and the batch — invalid settings, and the `triageEnabled` kill switch. */\nfunction assertRunnable(ctx: SupportKitHandlerContext, settings: SupportKitSettings, ignoreTriageDisabled: boolean): void {\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(' ')}`);\n }\n if (!ignoreTriageDisabled && !settings.triageEnabled) {\n throw new ctx.NonRetriableError('Triage is disabled (triageEnabled is off) — pass ignoreTriageDisabled to override.');\n }\n}\n","/**\n * `preview-triage` (§3.5) — `uiInvoke`, dry-run classification of ONE\n * ticket, equivalent to the legacy `POST /triage/preview`. Runs\n * `runTicket(deps, {until:'triage'})` — the same checkpoint `triage-tick`\n * uses — but through the recording `state`/`reply` ports (`adapters/\n * recording-ports.ts`, T21) instead of the real Gorgias-writing ones, so\n * nothing is tagged and no `triage-decision`/`generated-response` row is\n * created. `conversation`/`llm`/`prompt` stay the REAL ctx adapters: a\n * preview reads and classifies for real, per §0's dry-run arbitrage\n * (\"aucune action externe (ni réponse, ni tag)\").\n *\n * Narrower than `graph-dry-run`: this stops at the SAME checkpoint\n * `triage-tick` does (triage + escalate only), never drafts. Use\n * `graph-dry-run` to see the full graph, including a draft, for one ticket.\n *\n * `minRole: 'VIEWER'`: a single classification preview spends one LLM call\n * but writes nothing and cannot escalate/send anything for real — the same\n * risk profile as a read.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport { createRecordingReplyPort, createRecordingStatePort } from '../adapters/recording-ports';\nimport { resolveHandledTags } from '../adapters/gorgias-tags';\nimport { createBudget } from '../graph/budget';\nimport { runTicket } from '../graph/run-ticket';\nimport type { Classification, ConversationRef } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { PREVIEW_TRIAGE_INPUT_TICKET_ID_UID } from './ids';\nimport { createNoToolContext } from './no-tool-context';\nimport { buildPromptsTable, draftPromptRefFor, listCategories, resolveDraftAgent, toCategoryReferential } from './records';\n\nexport interface PreviewTriageInput {\n ticketId: string;\n}\n\nexport interface PreviewTriageResult {\n ticketId: string;\n classification: Classification | null;\n escalated: boolean;\n /** Tags the run WOULD have applied. Nothing was applied. */\n wouldHaveTagged: string[];\n}\n\nexport function buildPreviewTriageFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'preview-triage'),\n name: 'preview-triage',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: PREVIEW_TRIAGE_INPUT_TICKET_ID_UID,\n name: 'ticketId',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createPreviewTriageHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => previewTriageHandler(ctx as SupportKitHandlerContext, config, input as unknown as PreviewTriageInput);\n}\n\nexport async function previewTriageHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: PreviewTriageInput,\n): Promise<PreviewTriageResult> {\n const ticketId = input?.ticketId?.trim();\n if (!ticketId) throw new ctx.NonRetriableError('ticketId is required');\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(' ')}`);\n }\n\n const categories = await listCategories(ctx.api);\n const agent = await resolveDraftAgent(ctx.api, null);\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));\n\n const realPorts = buildTicketPorts(ctx);\n const recordingState = createRecordingStatePort(ctx.api);\n const recordingReply = createRecordingReplyPort();\n\n const ref: ConversationRef = { id: ticketId, channel: 'gorgias' };\n const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n\n const state = await runTicket(\n {\n ref,\n profile,\n ports: {\n conversation: realPorts.conversation,\n reply: recordingReply.port,\n llm: realPorts.llm,\n prompt: realPorts.prompt,\n state: recordingState.port,\n clock: realPorts.clock,\n },\n toolContext: createNoToolContext(),\n budget,\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: toCategoryReferential(categories),\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'none' },\n },\n { until: 'triage' },\n );\n\n // `runTicket(deps, {until:'triage'})` deliberately never calls\n // `ports.state.record` (see its own doc in `graph/run-ticket.ts`) — the\n // recording port above never fires for this checkpoint, so the tag set a\n // REAL `triage-tick` would apply is computed here directly, off the same\n // `resolveHandledTags` both the real and recording `StatePort` share. No\n // write happens either way: this is a plain (already-read-only) lookup.\n const wouldHaveTagged = state.classification\n ? await resolveHandledTags(ctx.api, state.classification, profile.audit)\n : [];\n\n return {\n ticketId,\n classification: state.classification,\n escalated: state.escalated,\n wouldHaveTagged,\n };\n}\n","/**\n * `runGraphDryRun` — the graph-dry-run engine itself, split out from\n * `graph-dry-run.ts`'s ctx-wiring/overrides so it can be exercised directly\n * against `graph/run-ticket.fixtures.ts`'s `harness()` (real nodes, fake\n * ports) instead of a fully faked `SupportKitHandlerContext`. §0's dry-run\n * arbitrage: \"graphe complet tant qu'aucune action externe (ni réponse, ni\n * tag, ni écriture de record)\".\n *\n * Takes an already-assembled `NodeDeps` (`base`) — real ports in\n * production (`buildTicketPorts(ctx)`), fake ones in a graph-level test —\n * and overrides exactly the surfaces that could otherwise leak a write:\n * `ports.reply`, `ports.state`, `ports.llm`/`ports.evaluator` (still REAL\n * calls, only their trace is captured) and `send`. `send` is ALWAYS\n * overridden to the recording `{mode:'claimed', ...}` seam, never left as\n * whatever `base.send` was assembled with — a dry run must exercise `act`'s\n * claim→post→commit path for real (so an operator sees the graph actually\n * reach `act`, not silently stop short of it), not skip it because the\n * caller happened to assemble `base` with `{mode:'none'}` (post-T21-review\n * C, `adapters/recording-ports.ts`'s own doc on `createRecordingSendPort`).\n */\nimport { createRecordingLlmPort, createRecordingReplyPort, createRecordingSendPort, createRecordingStatePort } from '../adapters/recording-ports';\nimport type { RecordedCompletion, WouldHaveReplied } from '../adapters/recording-ports';\nimport type { SupportKitApi } from '../adapters/api';\nimport { NODE_NAMES, type NodeDeps, type NodeName, type NodeStep, type TicketRunState } from '../graph/state';\nimport { runTicket, type ResumeFrom } from '../graph/run-ticket';\n\n/**\n * A dry run may not outlive an admin's patience, nor the `uiInvoke`\n * request's own HTTP timeout (T23 post-review C2) — ported from the legacy\n * `DRY_RUN_DEADLINE_MS`. Both `graph-dry-run.ts` (one ticket) and\n * `test-agents.ts` (up to `MAX_LIMIT` tickets, sequential) build their\n * `AbortSignal` from this constant: without it, neither call site ever\n * aborted, so `test-agents` in particular could run up to 100 full graphs\n * with no bound until the platform itself killed the connection mid-flight\n * — every completion already billed, nothing returned to the operator.\n */\nexport const DRY_RUN_DEADLINE_MS = 3 * 60 * 1000;\n\nexport interface GraphDryRunDeps {\n /** Fully assembled `NodeDeps` — `reply`/`state`/`llm`/`evaluator`/`send` are overridden below regardless of what this carries. */\n base: NodeDeps;\n /** For the recording `StatePort`'s category `extraTags` lookup (a real read — see `recording-ports.ts`). */\n api: SupportKitApi;\n resume?: ResumeFrom;\n}\n\nexport interface GraphDryRunResult {\n ticketId: string;\n outcome: TicketRunState['outcome'];\n /** Nodes the graph called, in order. `evaluate` appears twice on a revision. */\n steps: NodeStep[];\n /** Nodes it did not call. */\n skipped: NodeName[];\n completions: RecordedCompletion[];\n /** Tags the run WOULD have applied. Nothing was applied. */\n wouldHaveTagged: string[];\n /** The reply it WOULD have posted, or `null` if `act` never ran. Nothing was posted. */\n wouldHaveReplied: WouldHaveReplied | null;\n /**\n * Whether the run actually reached `act`'s claim/commit seam — proof the\n * send path was exercised, not skipped because `send` defaulted to\n * `{mode: 'none'}` (see this module's own header doc).\n */\n sendSeamExercised: boolean;\n draft: TicketRunState['draft'];\n verdict: TicketRunState['verdict'];\n guardrailHits: string[];\n error?: string;\n}\n\nexport async function runGraphDryRun({ base, api, resume }: GraphDryRunDeps): Promise<GraphDryRunResult> {\n const recordingReply = createRecordingReplyPort();\n const recordingState = createRecordingStatePort(api);\n const recordingSend = createRecordingSendPort();\n const recordingLlm = createRecordingLlmPort(base.ports.llm);\n const recordingEvaluator = base.ports.evaluator ? createRecordingLlmPort(base.ports.evaluator) : null;\n\n const steps: NodeStep[] = [];\n const deps: NodeDeps = {\n ...base,\n ports: {\n ...base.ports,\n reply: recordingReply.port,\n state: recordingState.port,\n llm: recordingLlm.port,\n ...(recordingEvaluator ? { evaluator: recordingEvaluator.port } : {}),\n },\n send: recordingSend.send,\n trace: (step) => steps.push(step),\n };\n\n let result: TicketRunState | null = null;\n let error: string | undefined;\n try {\n result = await runTicket(deps, resume ? { resume } : undefined);\n } catch (err) {\n error = err instanceof Error ? err.message : String(err);\n }\n\n const seen = new Set(steps.map((s) => s.node));\n const completions = [...recordingLlm.completions, ...(recordingEvaluator?.completions ?? [])];\n\n return {\n ticketId: base.ref.id,\n outcome: result?.outcome ?? null,\n steps,\n skipped: NODE_NAMES.filter((name) => !seen.has(name)),\n completions,\n wouldHaveTagged: recordingState.wouldHaveTagged(),\n wouldHaveReplied: recordingReply.wouldHaveReplied(),\n sendSeamExercised: recordingSend.calls.length > 0,\n draft: result?.draft ?? null,\n verdict: result?.verdict ?? null,\n guardrailHits: result?.guardrailHits ?? [],\n ...(error ? { error } : {}),\n };\n}\n","/**\n * `graph-dry-run` (§3.5) — `uiInvoke`, replay of the FULL graph for one\n * ticket, equivalent to the legacy `POST /agents/graph-run`. Ports the\n * `GraphDryRunOverrides` switches from\n * `extension-overview/backoffice/src/services/graphDryRun.ts` verbatim\n * (T21 deferred them here — their semantics are non-obvious, see each\n * function's own doc below) and delegates the actual replay to\n * `runGraphDryRun` (`./graph-dry-run-core.ts`), which owns the\n * zero-external-action guarantee.\n *\n * `minRole: 'EDITOR'` (T23 post-review E): unlike `preview-triage`'s single\n * classification, this replays the FULL graph and can conjure trial\n * evaluate/revise nodes — real LLM spend against the app's shared quota,\n * re-invocable at will. `VIEWER` is the read-only support-agent floor;\n * \"writes nothing to Gorgias\" is the wrong axis to gate on when the\n * resource actually being spent is money.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { AgentProfile, Classification, Conversation } from '../domain';\nimport type { ConversationRef } from '../domain';\nimport type { ConversationPort } from '../graph/ports';\nimport type { EvaluateNodeConfig, ReviseNodeConfig } from '../domain/profile';\nimport { createBudget } from '../graph/budget';\nimport type { NodeDeps } from '../graph/state';\nimport type { ResumeFrom } from '../graph/run-ticket';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { GRAPH_DRY_RUN_INPUT_AGENT_ID_UID, GRAPH_DRY_RUN_INPUT_CATEGORY_ID_UID, GRAPH_DRY_RUN_INPUT_INLINE_TICKET_UID, GRAPH_DRY_RUN_INPUT_OVERRIDES_UID, GRAPH_DRY_RUN_INPUT_TICKET_ID_UID } from './ids';\nimport { createNoToolContext } from './no-tool-context';\nimport {\n buildPromptsTable,\n draftPromptRefFor,\n listCategories,\n resolveDraftAgent,\n toAgent,\n toCategoryReferential,\n} from './records';\nimport { DRY_RUN_DEADLINE_MS, runGraphDryRun, type GraphDryRunResult } from './graph-dry-run-core';\n\nexport interface GraphDryRunOverrides {\n /** Off skips the judge entirely — the graph then ends at `ready`. On conjures a trial judge when the tenant has none. */\n evaluate?: boolean;\n /** Off makes `needsRevision` always false. On resolves a revision node from the writer's model when the tenant has none. */\n revise?: boolean;\n /** Off empties the guardrail catalogue and forces `whatsappMode: 'auto_reply'`, to reach `act` without a hold. */\n guardrails?: boolean;\n /** On opens auto-send for this run only (still requires a real `senderEmail`). */\n autoSend?: boolean;\n}\n\n/**\n * A ticket typed by hand instead of read from Gorgias. `channel` is not\n * cosmetic: `sourceChannel === 'whatsapp'` is what the `whatsapp_stop` /\n * `not_customer_turn` guardrails and the WhatsApp style prompt key off\n * (`domain/conversation.ts`'s own contract note), so a pasted WhatsApp\n * message must be replayable as one.\n */\nexport interface GraphDryRunInlineTicket {\n /** The customer's message. The only required part — everything else has a defensible default. */\n body: string;\n subject?: string | null;\n channel?: 'email' | 'whatsapp';\n}\n\n/**\n * Every field is `| null` rather than merely optional, because the platform\n * validates this payload against the manifest with `fieldDefsToZod`\n * (`app-input-validation.ts`), where `isNullable: true` permits the VALUE\n * null but NOT an absent key — an omitted optional field is rejected with\n * `422 INVALID_INPUT` before the handler runs. Callers therefore send every\n * declared key, `null` when unset, and this type says so.\n */\nexport interface GraphDryRunInput {\n /** Mutually exclusive with `inlineTicket` — exactly one of the two. */\n ticketId?: string | null;\n /** Replay on a ticket that does not exist in Gorgias (see below). */\n inlineTicket?: GraphDryRunInlineTicket | null;\n /** Forces the writing agent; falls back to the category's, then to the default one. */\n agentId?: string | null;\n /** Forces the category — and with it the classification, so triage does not run. */\n categoryId?: string | null;\n overrides?: GraphDryRunOverrides | null;\n}\n\n/**\n * The revision switch (ported verbatim from `GraphDryRunOverrides.revise`'s\n * legacy doc): `false` removes the node; `true` CONJURES one from the\n * writer's own model when the tenant has none configured, so an operator\n * can try the correction pass on one ticket before turning it on for\n * everybody. `reasoning: 'off'` is required here — an unconfigured trial\n * revise node must never be rejected by a (model, effort) validation rule\n * the tenant never opted into.\n */\nfunction resolveReviseNode(profile: AgentProfile, override: boolean | undefined): ReviseNodeConfig | null {\n if (override === false) return null;\n if (profile.nodes.revise) return profile.nodes.revise;\n if (override !== true) return null;\n const writer = profile.nodes.draft;\n return writer ? { model: writer.model, provider: writer.provider, reasoning: 'off' } : null;\n}\n\n/**\n * The `evaluate` switch, in its FORCING direction (`true`): a tenant with no\n * judge gets a trial one, model left to the prompt (kit's own resolution),\n * threshold pinned to the tenant's own auto-send floor. `false` empties the\n * node outright — `applyOverrides` below is what does that, this helper\n * only ever ADDS a node.\n */\nfunction withTrialJudge(profile: AgentProfile, override: boolean | undefined): AgentProfile {\n if (override !== true || profile.nodes.evaluate) return profile;\n const trial: EvaluateNodeConfig = {\n model: profile.nodes.draft?.model ?? '',\n provider: 'openai',\n reasoning: 'off',\n minConfidence: profile.autoSend.minConfidence,\n escalationEnabled: false,\n };\n return { ...profile, nodes: { ...profile.nodes, evaluate: trial } };\n}\n\n/** Turns the per-run switches into a profile the graph reads normally — never persisted. */\nfunction applyOverrides(profile: AgentProfile, overrides: GraphDryRunOverrides): AgentProfile {\n const withEvaluate = overrides.evaluate === false ? { ...profile, nodes: { ...profile.nodes, evaluate: null } } : withTrialJudge(profile, overrides.evaluate);\n\n return {\n ...withEvaluate,\n nodes: { ...withEvaluate.nodes, revise: resolveReviseNode(withEvaluate, overrides.revise) },\n // `auto_reply`, not `draft_only`: `draft_only` blocks `isAutoSendEligible`\n // outright for a WhatsApp ticket, which would stop the run at `ready`\n // and defeat the whole point of this override — reaching `act` with\n // nothing standing in the way. The category opt-in is bypassed the same\n // way triage-tick's own dry-run-adjacent callers do it (see below,\n // `category: {autoReplyEnabled: true, …}`).\n //\n // `judgemeEscalateOnly: false` (T23 post-review C1): that rule is NOT\n // filtered through `active` (`graph/nodes/guardrails.ts` checks it\n // unconditionally) and `settingsToProfile` hardcodes it to `true` with\n // no settings surface to turn it off — so without this, an operator\n // dry-running a Judge.me ticket with guardrails off still gets held by\n // a guardrail this override exists specifically to bypass.\n guardrails:\n overrides.guardrails === false\n ? { active: [], params: { ...withEvaluate.guardrails.params, whatsappMode: 'auto_reply', judgemeEscalateOnly: false } }\n : withEvaluate.guardrails,\n autoSend: { ...withEvaluate.autoSend, enabled: overrides.autoSend === true && !!withEvaluate.autoSend.senderEmail },\n };\n}\n\n/**\n * The classification a forced category stands for. Confidence is `high` on\n * purpose: the operator asked for THIS category, so the run must not then\n * be held by the `triage_not_high` guardrail for a decision they made\n * themselves. Never claims the conversation is over on the operator's\n * behalf.\n */\nfunction forcedClassification(tagName: string): Classification {\n return { category: tagName, confidence: 'high', reasoning: 'operator: catégorie forcée', isFallback: false, conversationOver: false };\n}\n\n/**\n * The id a pasted ticket runs under. Not a Gorgias id and never mistakable\n * for one: it appears in the result, in the recorded tags and in the\n * would-have-replied payload, and reading it as a real ticket number would\n * send someone looking for a ticket that does not exist.\n */\nexport const INLINE_TICKET_ID = 'ticket-saisi';\n\n/**\n * A `ConversationPort` over a typed-in ticket — the ONE port that still\n * reached Gorgias during a dry run (`reply`/`state`/`send` are already\n * swapped for recorders by `runGraphDryRun`, and the read tools are\n * neutralised by `createNoToolContext`). With this in its place a dry run\n * touches no Gorgias endpoint at all.\n *\n * `read` returns the SAME conversation object on every call, which matters\n * for `act`: it re-reads the conversation right before sending and holds\n * the reply when `messageCount` has moved (the I8 anti-divergence check).\n * A port that rebuilt a fresh object per call would be fine today, but one\n * that recomputed the count from anything time-dependent would hold every\n * pasted run for a collision that never happened.\n *\n * `listPending` returns nothing: a pasted ticket belongs to no view, and\n * this port is only ever assembled for a single-ticket replay.\n */\nfunction createInlineConversationPort(ticket: GraphDryRunInlineTicket, now: Date): ConversationPort {\n const conversation: Conversation = {\n ref: { id: INLINE_TICKET_ID, channel: 'gorgias' },\n subject: ticket.subject?.trim() ? ticket.subject.trim() : null,\n messages: [{ role: 'user', content: ticket.body }],\n customer: { name: null, email: null, orderContext: null },\n isClosed: false,\n lastMessageAt: now,\n messageCount: 1,\n // No agent ever answered a ticket that was just typed: `null` is the\n // truth, and it is also what keeps `not_customer_turn` from holding the\n // run before a single node has looked at the text.\n lastAgentReplyAt: null,\n hasCustomerAttachment: false,\n // `sourceChannel`, NOT `ref.channel`: the latter names the ADAPTER\n // (gorgias) while every channel guardrail and the style prompt read this\n // one (`domain/conversation.ts`).\n sourceChannel: ticket.channel ?? 'email',\n };\n return {\n listPending: async () => [],\n read: async () => conversation,\n };\n}\n\nexport function buildGraphDryRunFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'graph-dry-run'),\n name: 'graph-dry-run',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n // Nullable since the pasted-ticket mode: the handler enforces \"exactly\n // one of ticketId/inlineTicket\", which a per-field flag cannot express.\n { universalIdentifier: GRAPH_DRY_RUN_INPUT_TICKET_ID_UID, name: 'ticketId', type: FieldType.TEXT, label: 'Ticket id', isNullable: true },\n {\n universalIdentifier: GRAPH_DRY_RUN_INPUT_INLINE_TICKET_UID,\n name: 'inlineTicket',\n type: FieldType.JSON,\n label: 'Inline ticket',\n description: '{body, subject?, channel?} — replays a typed-in ticket instead of reading one from Gorgias.',\n isNullable: true,\n },\n { universalIdentifier: GRAPH_DRY_RUN_INPUT_AGENT_ID_UID, name: 'agentId', type: FieldType.TEXT, label: 'Agent id', isNullable: true },\n { universalIdentifier: GRAPH_DRY_RUN_INPUT_CATEGORY_ID_UID, name: 'categoryId', type: FieldType.TEXT, label: 'Category id', isNullable: true },\n {\n universalIdentifier: GRAPH_DRY_RUN_INPUT_OVERRIDES_UID,\n name: 'overrides',\n type: FieldType.JSON,\n label: 'Overrides',\n description: '{evaluate?, revise?, guardrails?, autoSend?}',\n isNullable: true,\n },\n ],\n };\n}\n\nexport function createGraphDryRunHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => graphDryRunHandler(ctx as SupportKitHandlerContext, config, input as unknown as GraphDryRunInput);\n}\n\nexport async function graphDryRunHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: GraphDryRunInput,\n): Promise<GraphDryRunResult> {\n const ticketId = input?.ticketId?.trim();\n const inlineBody = input?.inlineTicket?.body?.trim();\n // Exactly one of the two. Refusing BOTH rather than silently preferring one\n // matters: a caller that sends a ticket id AND a pasted body has a bug, and\n // reading the wrong one would produce a plausible result about the wrong\n // ticket entirely.\n if (ticketId && inlineBody) throw new ctx.NonRetriableError('Provide either ticketId or inlineTicket, not both');\n if (!ticketId && !inlineBody) throw new ctx.NonRetriableError('ticketId or inlineTicket.body is required');\n const inlineTicket = inlineBody ? { ...(input.inlineTicket as GraphDryRunInlineTicket), body: inlineBody } : null;\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(' ')}`);\n }\n\n const categories = await listCategories(ctx.api);\n const forcedCategory = input.categoryId ? (categories.find((c) => c.id === input.categoryId) ?? null) : null;\n if (input.categoryId && !forcedCategory) throw new ctx.NonRetriableError(`Category \"${input.categoryId}\" not found`);\n\n const agent = input.agentId\n ? toAgent(await ctx.api.get('agent', input.agentId))\n : await resolveDraftAgent(ctx.api, forcedCategory?.agentId ?? null);\n\n const baseProfile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));\n const profile = applyOverrides(baseProfile, input.overrides ?? {});\n\n const realPorts = buildTicketPorts(ctx);\n const ref: ConversationRef = { id: inlineTicket ? INLINE_TICKET_ID : (ticketId as string), channel: 'gorgias' };\n const budget = createBudget({ signal: AbortSignal.timeout(DRY_RUN_DEADLINE_MS), maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n\n const base: NodeDeps = {\n ref,\n profile,\n ports: {\n conversation: inlineTicket ? createInlineConversationPort(inlineTicket, realPorts.clock.now()) : realPorts.conversation,\n reply: realPorts.reply,\n llm: realPorts.llm,\n prompt: realPorts.prompt,\n state: realPorts.state,\n clock: realPorts.clock,\n },\n toolContext: createNoToolContext(),\n budget,\n // Bypassed the same way `triage-tick`'s dry-run-adjacent batch is:\n // reaching `act` is what the `autoSend` override is for, and requiring\n // the category to ALSO have opted in would make the override inert on\n // every category that has auto-reply off — which is all of them today.\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: toCategoryReferential(categories),\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'none' }, // overridden unconditionally by `runGraphDryRun`\n };\n\n const resume: ResumeFrom | undefined = forcedCategory\n ? { classification: forcedClassification(forcedCategory.tagName), escalated: false }\n : undefined;\n\n return runGraphDryRun({ base, api: ctx.api, resume });\n}\n","/**\n * `test-agents` (§3.5) — `uiInvoke`, multi-ticket bench (legacy\n * `POST /agents/test`): runs `graph-dry-run`'s SAME zero-write replay\n * (`runGraphDryRun`, `./graph-dry-run-core.ts`) over either a Gorgias view\n * or an explicit list of ticket ids, so an operator can see what an agent\n * WOULD produce across a batch before turning it loose — nothing tagged,\n * nothing sent, nothing recorded, per §0's dry-run arbitrage.\n *\n * No `GraphDryRunOverrides` here (unlike `graph-dry-run`, which exists\n * precisely to explore an OFF branch on one ticket): a bench is only\n * useful if it reports what the agent does with its REAL configuration,\n * across many tickets — overriding it would just report the same forced\n * branch N times.\n *\n * `category.autoReplyEnabled` is the ONE exception to that, and it is\n * reported as such (T23 post-review C3): the per-ticket category is only\n * known once TRIAGE runs, which happens INSIDE the same full-graph replay\n * this function triggers — there is no category to read a real flag off of\n * before the run starts. `graph-dry-run` can justify forcing it to `true`\n * unconditionally (reaching `act` is that function's whole purpose); a bench\n * with no override cannot make the same claim, so `TestAgentsResult` carries\n * `autoReplyForced: true` alongside every run's outcome — an operator\n * reading \"would have sent\" across a batch sees, in the same response, that\n * every category's own auto-reply setting was bypassed to get there.\n *\n * Sequential on purpose: a batch runs the LLM/Gorgias reads for real\n * (§0/§3.5), and a small, predictable concurrency of 1 is the safer default\n * for a bench an operator triggers by hand — this can grow a concurrency\n * knob later without changing the contract.\n *\n * `minRole: 'EDITOR'` (T23 post-review E): up to `MAX_LIMIT` full graph\n * replays per invocation is real LLM spend against the app's shared quota,\n * not a read — `VIEWER` is the wrong floor for a tool that can burn budget\n * this fast, re-invocable at will.\n *\n * `DRY_RUN_DEADLINE_MS` bounds the WHOLE bench, not each ticket (T23\n * post-review C2, ported from the legacy's single-ticket deadline): past\n * it, the loop stops starting new replays and returns whatever finished —\n * partial results the operator can read, instead of the `uiInvoke` request\n * dying at the platform's own HTTP timeout with nothing returned and every\n * completion so far already billed.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { ConversationRef } from '../domain';\nimport { createBudget } from '../graph/budget';\nimport type { NodeDeps } from '../graph/state';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { DRY_RUN_DEADLINE_MS, runGraphDryRun, type GraphDryRunResult } from './graph-dry-run-core';\nimport { TEST_AGENTS_INPUT_AGENT_ID_UID, TEST_AGENTS_INPUT_LIMIT_UID, TEST_AGENTS_INPUT_TICKET_IDS_UID, TEST_AGENTS_INPUT_VIEW_ID_UID } from './ids';\nimport { createNoToolContext } from './no-tool-context';\nimport { buildPromptsTable, draftPromptRefFor, listCategories, resolveDraftAgent, toAgent, toCategoryReferential } from './records';\n\nconst DEFAULT_LIMIT = 20;\nconst MAX_LIMIT = 100;\n\nexport interface TestAgentsInput {\n viewId?: string;\n ticketIds?: string[];\n /** Forces the writing agent; falls back to the default one. */\n agentId?: string;\n limit?: number;\n}\n\nexport interface TestAgentsResult {\n results: GraphDryRunResult[];\n /**\n * `true` when every result above ran with `category.autoReplyEnabled`\n * forced on, regardless of that ticket's own category setting (T23\n * post-review C3) — see this module's own header doc for why a bench\n * cannot know the real per-category flag ahead of triage.\n */\n autoReplyForced: true;\n}\n\nexport function buildTestAgentsFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'test-agents'),\n name: 'test-agents',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n { universalIdentifier: TEST_AGENTS_INPUT_VIEW_ID_UID, name: 'viewId', type: FieldType.TEXT, label: 'View id', isNullable: true },\n { universalIdentifier: TEST_AGENTS_INPUT_TICKET_IDS_UID, name: 'ticketIds', type: FieldType.JSON, label: 'Ticket ids', description: 'string[]', isNullable: true },\n { universalIdentifier: TEST_AGENTS_INPUT_AGENT_ID_UID, name: 'agentId', type: FieldType.TEXT, label: 'Agent id', isNullable: true },\n { universalIdentifier: TEST_AGENTS_INPUT_LIMIT_UID, name: 'limit', type: FieldType.NUMBER, label: 'Limit', isNullable: true },\n ],\n };\n}\n\nexport function createTestAgentsHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => testAgentsHandler(ctx as SupportKitHandlerContext, config, input as unknown as TestAgentsInput);\n}\n\nexport async function testAgentsHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: TestAgentsInput,\n): Promise<TestAgentsResult> {\n const explicitIds = (input?.ticketIds ?? []).map((id) => id.trim()).filter(Boolean);\n const viewId = input?.viewId?.trim();\n if (!viewId && explicitIds.length === 0) {\n throw new ctx.NonRetriableError('Either viewId or ticketIds is required');\n }\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(' ')}`);\n }\n\n const limit = Math.min(input?.limit ?? DEFAULT_LIMIT, MAX_LIMIT);\n const categories = await listCategories(ctx.api);\n const agent = input.agentId ? toAgent(await ctx.api.get('agent', input.agentId)) : await resolveDraftAgent(ctx.api, null);\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));\n\n const realPorts = buildTicketPorts(ctx);\n const refs: ConversationRef[] = explicitIds.length\n ? explicitIds.slice(0, limit).map((id) => ({ id, channel: 'gorgias' as const }))\n : await realPorts.conversation.listPending({ viewOrTag: viewId! }, limit);\n\n // One deadline for the WHOLE bench (T23 post-review C2), not one per\n // ticket: past it, the loop below stops starting new replays rather than\n // let the platform's own HTTP timeout kill the request with nothing\n // returned. Every ticket's `Budget` shares this same signal, so an\n // in-flight LLM call is aborted at the same wall-clock moment the loop\n // itself gives up.\n const deadline = AbortSignal.timeout(DRY_RUN_DEADLINE_MS);\n\n const results: GraphDryRunResult[] = [];\n for (const ref of refs) {\n if (deadline.aborted) break; // partial results: the bench is out of time, not any one ticket\n const budget = createBudget({ signal: deadline, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n const base: NodeDeps = {\n ref,\n profile,\n ports: {\n conversation: realPorts.conversation,\n reply: realPorts.reply,\n llm: realPorts.llm,\n prompt: realPorts.prompt,\n state: realPorts.state,\n clock: realPorts.clock,\n },\n toolContext: createNoToolContext(),\n budget,\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: toCategoryReferential(categories),\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'none' }, // overridden unconditionally by `runGraphDryRun`\n };\n results.push(await runGraphDryRun({ base, api: ctx.api }));\n }\n\n return { results, autoReplyForced: true };\n}\n","/**\n * `validateReferences` — save-time validation for a prompt-composition tag\n * (`@@@langfusePrompt:name=…|label=…@@@` or `|version=…@@@`), ported from\n * legacy `services/promptReferences.ts`. Deferred by T19 (its own module doc\n * on `prompts/references.ts`: \"an admin save-time validator with no runtime-\n * resolution caller in this kit … out of scope for T19\") and picked up here\n * because `suggest-prompt` (§3.5) is the kit's first WRITE path for a\n * prompt's content — nothing gated writes before this.\n *\n * Five error classes, all five kept:\n * 1. Malformed tag (`findMalformedTags`) — a typo'd `label`/`version`\n * keyword, or a missing closing `@@@`.\n * 2. Self-reference — a prompt referencing its own name.\n * 3. Unresolvable target — the referenced prompt/version/label could not\n * be fetched (missing, or Langfuse unreachable; both read the same\n * here, same as legacy).\n * 4. A cycle back to the prompt being saved.\n * 5. A chain longer than the runtime resolver ever actually walks\n * (T23 post-review B1, below).\n *\n * Class 1 is now STRICTLY MORE IMPORTANT than in the legacy: Langfuse used\n * to store a typo'd tag as literal text and its own resolver caught DEEPER\n * cycles on the well-formed ones — but `createPromptResolver`\n * (`prompts/resolver.ts`) now resolves composition itself, reading raw\n * content via `resolve:false` and never asking Langfuse to flatten\n * anything. A typo'd tag saved here reaches the LLM completely verbatim,\n * with NOTHING server-side left to catch it — this validator is the sole\n * arbiter, at save time, of whether that string means anything at all.\n *\n * Class 4 is deepened past legacy's one hop for the identical reason:\n * legacy's own comment justified checking only one level with \"deeper\n * cycles are rejected by Langfuse's own resolver at fetch time\" — that\n * resolver is never consulted anymore (composition is entirely the kit's\n * own `resolveComposition`, `prompts/resolver.ts`), so a 2+-hop cycle saved\n * here would previously have gone uncaught at write time. `resolver.ts`'s\n * OWN runtime composition pass already survives a cycle at read time\n * (`visited`/`MAX_COMPOSITION_DEPTH`, degrading it to empty text) — this\n * validator closes the save-time half of the same gap: catching the\n * mistake when it is made, not silently degrading it forever after.\n *\n * Class 5 (T23 post-review B1) closes a DIFFERENT gap the cycle walk above\n * never covered: a purely LINEAR chain, A→B→C→D→E→F, has no cycle at all,\n * yet `resolver.ts`'s own `MAX_COMPOSITION_DEPTH` (imported below, not\n * restated — the previous revision claimed to mirror it while actually\n * enforcing an unrelated `MAX_CYCLE_DEPTH` that only ever bounded the CYCLE\n * walk's recursion) silently strips whatever sits past that depth at read\n * time. Without this check, such a chain \"saves fine\" and an operator only\n * discovers the loss when the composed prompt quietly stops including its\n * last segment.\n *\n * `MAX_CYCLE_DEPTH` remains its own, separate, larger safety valve: it\n * exists only so an adversarial/cyclic graph the cycle walk is exploring\n * cannot recurse forever, and has nothing to say about how long a valid\n * chain may be — that is `MAX_COMPOSITION_DEPTH`'s job, enforced by class 5.\n */\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { SupportKitApi } from '../adapters/api';\nimport { MAX_COMPOSITION_DEPTH } from '../prompts/resolver';\nimport { parseReferences, REFERENCE_TAG_SOURCE, type PromptReference } from '../prompts/references';\n\nconst LITERAL_PREFIX = '@@@langfusePrompt:';\nconst MALFORMED_SNIPPET_MAX_LEN = 60;\n/**\n * Bounds the CYCLE WALK's own recursion on adversarial/cyclic content — kept\n * deliberately larger than `MAX_COMPOSITION_DEPTH` (a valid, acyclic chain\n * that merely runs past the runtime cap is class 5's job, reported\n * separately and more usefully than \"cycle walk gave up\").\n */\nconst MAX_CYCLE_DEPTH = 10;\n\n/** Same grammar `parseReferences` matches (`prompts/references.ts`'s exported source) — a single definition, so the two can never drift apart (T23 post-review B3). */\nconst REF_RE = new RegExp(REFERENCE_TAG_SOURCE, 'g');\n\n/** A short, human-readable excerpt of the malformed tag, for the error message. */\nfunction snippetAt(content: string, index: number): string {\n const rest = content.slice(index);\n const closingIdx = rest.indexOf('@@@', LITERAL_PREFIX.length);\n const snippet = closingIdx === -1 ? rest.slice(0, MALFORMED_SNIPPET_MAX_LEN) : rest.slice(0, closingIdx + 3);\n return snippet.length > MALFORMED_SNIPPET_MAX_LEN ? `${snippet.slice(0, MALFORMED_SNIPPET_MAX_LEN)}…` : snippet;\n}\n\n/** Every literal `@@@langfusePrompt:` occurrence NOT part of a well-formed tag `parseReferences` would have matched. */\nfunction findMalformedTags(content: string): string[] {\n if (!content.includes(LITERAL_PREFIX)) return [];\n const validStarts = new Set([...content.matchAll(REF_RE)].map((m) => m.index ?? -1));\n const malformed: string[] = [];\n for (const m of content.matchAll(new RegExp(LITERAL_PREFIX, 'g'))) {\n const index = m.index ?? -1;\n if (!validStarts.has(index)) malformed.push(snippetAt(content, index));\n }\n return malformed;\n}\n\n/** Where a reference points, for an error message (\"version 3\" / label \"production\"). */\nfunction locatorFor(ref: PromptReference): string {\n return ref.version !== undefined ? `version ${ref.version}` : `label \"${ref.label}\"`;\n}\n\ninterface FetchedTarget {\n content: string;\n}\n\n/**\n * A reference target that failed to fetch, distinguishing WHY (M1, T25\n * review): `forbidden` (a 403 — the target exists but is outside this app's\n * `role.prompts` allowlist) is a misconfiguration to fix in the manifest, not\n * a typo'd or genuinely absent prompt name — reporting the two identically\n * sends an operator chasing a \"not found\" prompt that Langfuse would show\n * them exists.\n */\ninterface FetchFailure {\n forbidden: boolean;\n}\n\ntype FetchResult = FetchedTarget | FetchFailure;\n\nfunction isFetchFailure(result: FetchResult): result is FetchFailure {\n return !('content' in result);\n}\n\n/** Stable dedupe key for a reference target — a version-pinned ref and a label-pinned ref never collide, mirroring `resolver.ts`'s own `memoryKey`. */\nfunction targetKey(ref: PromptReference): string {\n return ref.version !== undefined ? `${ref.name}::v${ref.version}` : `${ref.name}::${ref.label}`;\n}\n\n/** `ctx.api.prompts.get(name, {label|version, resolve:false})` — a `FetchFailure` on any error, `forbidden` set only for a 403 (`AppApiError`). */\nasync function fetchTarget(api: SupportKitApi, ref: PromptReference): Promise<FetchResult> {\n try {\n const detail = await api.prompts.get(ref.name, {\n resolve: false,\n ...(ref.version !== undefined ? { version: ref.version } : { label: ref.label }),\n });\n return { content: detail.content };\n } catch (err) {\n return { forbidden: err instanceof AppApiError && err.status === 403 };\n }\n}\n\n/**\n * `fetchTarget`, deduped against `cache` (T23 post-review B2). The legacy\n * gap this closes: the cycle walk used to re-fetch a target the main loop\n * had just fetched, then re-fetch it again on every alternation of an\n * unrelated cycle it stumbled into — this is the one seam both the main\n * loop and the cycle/depth walks below share, so a given (name, version|label)\n * is ever fetched at most once per `validateReferences` call.\n */\nasync function fetchTargetCached(api: SupportKitApi, ref: PromptReference, cache: Map<string, FetchResult>): Promise<FetchResult> {\n const key = targetKey(ref);\n const cached = cache.get(key);\n if (cached) return cached;\n const target = await fetchTarget(api, ref);\n cache.set(key, target);\n return target;\n}\n\n/**\n * Walks the reference chain rooted at `content` looking for a hop back to\n * `origin` (the prompt being validated). `visited` (T23 post-review B2) is\n * THIS walk's own dedupe: once a target has been explored and did not lead\n * back to `origin`, revisiting it can only repeat the same negative answer —\n * skipping it turns \"re-walked alternately to `MAX_CYCLE_DEPTH`\" into \"walked\n * once\". `depth` still bounds the walk independently, for a graph `visited`\n * has not yet caught up with.\n */\nasync function hasPathToOrigin(\n api: SupportKitApi,\n content: string,\n origin: string,\n depth: number,\n cache: Map<string, FetchResult>,\n visited: Set<string>,\n): Promise<boolean> {\n if (depth > MAX_CYCLE_DEPTH) return false;\n\n for (const ref of parseReferences(content)) {\n if (ref.name === origin) return true;\n\n const key = targetKey(ref);\n if (visited.has(key)) continue;\n visited.add(key);\n\n const target = await fetchTargetCached(api, ref, cache);\n if (isFetchFailure(target)) continue; // unresolvable — reported separately, not a cycle\n\n if (await hasPathToOrigin(api, target.content, origin, depth + 1, cache, visited)) return true;\n }\n return false;\n}\n\n/**\n * Whether `content`'s reference chain runs past `MAX_COMPOSITION_DEPTH` —\n * the exact point `resolver.ts`'s own `composeReferences` stops following a\n * chain and silently strips whatever is left (T23 post-review B1). Mirrors\n * that function's `depth`/cap arithmetic precisely: `content` itself is\n * depth 0 (the prompt being saved, not yet fetched), each reference target\n * is one level deeper, and a target reached at `depth >= MAX_COMPOSITION_DEPTH`\n * is exactly the one the resolver would compose without following further —\n * anything nested inside IT is what gets silently lost at runtime.\n *\n * `visited` mirrors `resolver.ts`'s own cycle guard (keyed by prompt NAME,\n * same as `resolveOneReference`'s `visited.has(ref.name)`): a name already\n * on the path is a cycle, which the runtime resolver degrades to empty text\n * at THAT point regardless of depth, and which class 4 above already\n * reports on its own terms — without this, a short unrelated cycle inside\n * an otherwise-fine chain would recurse forever instead of matching what\n * the resolver actually does with it.\n */\nasync function exceedsCompositionDepth(\n api: SupportKitApi,\n content: string,\n depth: number,\n cache: Map<string, FetchResult>,\n visited: ReadonlySet<string>,\n): Promise<boolean> {\n const refs = parseReferences(content);\n if (refs.length === 0) return false;\n if (depth >= MAX_COMPOSITION_DEPTH) return true;\n\n for (const ref of refs) {\n if (visited.has(ref.name)) continue; // a cycle — reported separately by class 4, not a depth issue\n const target = await fetchTargetCached(api, ref, cache);\n if (isFetchFailure(target)) continue; // unresolvable — reported separately, not a depth issue\n if (await exceedsCompositionDepth(api, target.content, depth + 1, cache, new Set([...visited, ref.name]))) return true;\n }\n return false;\n}\n\n/**\n * Validate every reference tag in `content` (the prompt named `selfName`\n * about to be saved). Returns human-readable error strings; an empty array\n * means the content is valid.\n */\nexport async function validateReferences(api: SupportKitApi, content: string, selfName: string): Promise<string[]> {\n const errors: string[] = [];\n const cache = new Map<string, FetchResult>();\n\n for (const snippet of findMalformedTags(content)) {\n errors.push(`Malformed reference tag near \"${snippet}\": it will be saved as literal text instead of being resolved.`);\n }\n\n for (const ref of parseReferences(content)) {\n if (ref.name === selfName) {\n errors.push(`Reference \"${ref.raw}\" points to this same prompt (\"${selfName}\") — a prompt cannot reference itself.`);\n continue;\n }\n\n const target = await fetchTargetCached(api, ref, cache);\n if (isFetchFailure(target)) {\n errors.push(\n target.forbidden\n ? `Reference \"${ref.raw}\" points to prompt \"${ref.name}\", which exists but is outside this app's prompts allowlist (role.prompts) — it cannot be composed here even though it can be read elsewhere.`\n : `Reference \"${ref.raw}\" could not be resolved: prompt \"${ref.name}\" with ${locatorFor(ref)} was not found, or the prompt store could not be reached to verify it.`,\n );\n continue;\n }\n\n if (await hasPathToOrigin(api, target.content, selfName, 1, cache, new Set([targetKey(ref)]))) {\n errors.push(`Reference \"${ref.raw}\" creates a cycle: prompt \"${ref.name}\" (transitively) references this prompt (\"${selfName}\").`);\n }\n }\n\n if (errors.length === 0 && (await exceedsCompositionDepth(api, content, 0, cache, new Set([selfName])))) {\n errors.push(\n `Reference chain exceeds the runtime composition cap (${MAX_COMPOSITION_DEPTH} levels): the segment past that depth would be silently stripped when this prompt is resolved.`,\n );\n }\n\n return errors;\n}\n","/**\n * `suggest-prompt` (§3.5) — `uiInvoke`, LLM prompt suggestion from an\n * agent's `response-comparison` corrections, equivalent to legacy\n * `POST /models/:id/prompt-versions/suggest`. Writes with\n * `ctx.api.prompts.createVersion(...)` (S3), tag `ai_suggested`, gated by\n * `validateReferences` (`./validate-references.ts`, T19's deferred\n * validator) BEFORE the write — the first prompt-content write path in the\n * kit, and the first place a malformed/self-referencing/cyclic reference tag\n * could otherwise reach a live prompt.\n *\n * WHAT THIS CANNOT RECORD (T19): `CreatePromptVersionInput` is\n * `{content, labels?, tags?}` — no `config`, no `commitMessage`. Two losses\n * versus the legacy, both accepted here rather than invented on the\n * platform surface:\n * - No `commitMessage`: legacy wrote\n * `\"AI-suggested based on N comparisons from vX\"` as the version's own\n * changelog entry. That narrative has nowhere to go — the new version\n * carries no explanation of why it exists beyond the `ai_suggested` tag.\n * - No `config`: legacy explicitly inherited the ACTIVE version's model\n * config (\"a suggestion never silently resets a tuned temperature back\n * to the default\"). A version created here carries none — an operator\n * who tuned a model/temperature on the active version loses that\n * tuning the moment they accept a suggestion, silently, until S3 grows\n * a `config` field.\n *\n * `minRole: 'EDITOR'`: this writes a new prompt version (Langfuse), even\n * though it never PROMOTES it to `production` — creating one is still an\n * editing action, not a read.\n */\nimport { AppApiError, FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { SUGGEST_PROMPT_INPUT_AGENT_ID_UID, SUGGEST_PROMPT_INPUT_MAX_COMPARISONS_UID } from './ids';\nimport { resolvePromptName } from '../prompts/slots';\nimport { toAgent } from './records';\nimport { validateReferences } from './validate-references';\n\nconst DEFAULT_MAX_COMPARISONS = 50;\nconst MIN_COMPARISONS_REQUIRED = 3;\n\n/**\n * Level-3 fallback for the `suggest` slot (§3.7 point 3: \"fallback in-code\n * du kit, surchargé par `config.defaults.prompts`\") — used only when the\n * slot has no `production` version yet in the prompt store.\n */\nconst DEFAULT_SUGGEST_META_PROMPT = [\n 'Tu es un expert en rédaction de prompts système pour des assistants IA de support client.',\n \"Analyse les différences entre les réponses de l'IA et celles des agents humains dans les exemples fournis.\",\n 'Identifie les patterns récurrents (ton, structure, longueur, formulations) puis réécris le prompt système actuel pour en corriger les écarts.',\n 'Retourne UNIQUEMENT le texte du prompt système amélioré, sans explication ni mise en forme markdown.',\n \"Toute balise de référence de la forme @@@langfusePrompt:...@@@ présente dans le prompt actuel doit être reproduite telle quelle, sans modification.\",\n].join('\\n');\n\nexport interface SuggestPromptInput {\n agentId: string;\n maxComparisons?: number;\n}\n\nexport interface SuggestPromptResult {\n promptName: string;\n version: number;\n comparisonCount: number;\n}\n\nexport function buildSuggestPromptFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'suggest-prompt'),\n name: 'suggest-prompt',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n { universalIdentifier: SUGGEST_PROMPT_INPUT_AGENT_ID_UID, name: 'agentId', type: FieldType.TEXT, label: 'Agent id', isNullable: false },\n { universalIdentifier: SUGGEST_PROMPT_INPUT_MAX_COMPARISONS_UID, name: 'maxComparisons', type: FieldType.NUMBER, label: 'Max comparisons', isNullable: true },\n ],\n };\n}\n\nexport function createSuggestPromptHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => suggestPromptHandler(ctx as SupportKitHandlerContext, config, input as unknown as SuggestPromptInput);\n}\n\nfunction comparisonBlock(index: number, generatedText: string | null, sentText: string): string {\n const ai = generatedText?.trim() || '(aucune réponse générée)';\n return `### Exemple ${index + 1}\\nIA a généré :\\n${ai}\\n\\nAgent a réellement envoyé :\\n${sentText.trim()}`;\n}\n\nexport async function suggestPromptHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: SuggestPromptInput,\n): Promise<SuggestPromptResult> {\n const agentId = input?.agentId?.trim();\n if (!agentId) throw new ctx.NonRetriableError('agentId is required');\n\n const agent = toAgent(await ctx.api.get('agent', agentId));\n const promptName = agent.promptName;\n if (!promptName) throw new ctx.NonRetriableError(`Agent \"${agentId}\" has no promptName configured`);\n\n // Raw (unresolved) current content — the meta-prompt below must see any\n // `@@@langfusePrompt:...@@@` composition tag verbatim, so it rewrites the\n // template rather than an expansion of it (mirrors legacy's own\n // `getRaw` read, §3.7's \"aplatir\" concern).\n let currentContent: string;\n let promptVersion: number | null;\n try {\n const detail = await ctx.api.prompts.get(promptName, { label: 'production', resolve: false });\n currentContent = detail.content;\n promptVersion = detail.version;\n } catch (err) {\n // H4 (T25 review): a 403 means this agent's own promptName is outside\n // the app's role.prompts allowlist — a manifest/data misconfiguration,\n // not the legitimate \"no production version yet\" case the fallback to\n // systemPromptSnapshot exists for. Swallowing it here would rewrite a\n // STALE snapshot and hand the operator no error explaining why.\n if (err instanceof AppApiError && err.status === 403) {\n throw new ctx.NonRetriableError(\n `Agent \"${agentId}\"'s prompt \"${promptName}\" is outside this app's prompts allowlist (role.prompts) — suggest-prompt cannot read it. ${err.message}`,\n );\n }\n currentContent = agent.systemPromptSnapshot ?? '';\n promptVersion = agent.promptVersion;\n }\n\n // Scoped to the ACTIVE prompt version, not just the agent (legacy\n // behaviour, ported): a correction captured against v7 has nothing to say\n // about v8 — feeding it back in after the operator already accepted a\n // suggestion re-litigates a fix that was already made and drifts the\n // prompt further every round.\n const limit = Math.min(input?.maxComparisons ?? DEFAULT_MAX_COMPARISONS, DEFAULT_MAX_COMPARISONS);\n const page = await ctx.api.list('response-comparison', { filter: { agentId, promptName, promptVersion }, limit });\n const comparisons = page.items.map((r) => r.data as { generatedText: string | null; sentText: string });\n if (comparisons.length < MIN_COMPARISONS_REQUIRED) {\n throw new ctx.NonRetriableError(\n `Not enough comparison data (${comparisons.length} record(s), minimum ${MIN_COMPARISONS_REQUIRED} required)`,\n );\n }\n\n const metaPromptName = resolvePromptName('suggest', config);\n // §3.7 point 3 — the kit's own built-in text is the LAST resort;\n // `config.defaults.prompts.suggest` (T25) overrides it first.\n const configuredFallback = config.defaults?.prompts?.suggest ?? DEFAULT_SUGGEST_META_PROMPT;\n let metaPromptContent = configuredFallback;\n try {\n metaPromptContent = (await ctx.api.prompts.get(metaPromptName, { label: 'production' })).content || configuredFallback;\n } catch {\n // Level-3 fallback (§3.7) — the `suggest` slot has no `production`\n // version yet on this tenant.\n }\n\n const userMessage = [\n '--- PROMPT SYSTÈME ACTUEL ---',\n currentContent,\n '--- FIN DU PROMPT SYSTÈME ---',\n '',\n `Voici ${comparisons.length} exemples comparant ce que l'IA a généré avec ce que l'agent a réellement envoyé :`,\n '',\n comparisons.map((c, i) => comparisonBlock(i, c.generatedText, c.sentText)).join('\\n\\n---\\n\\n'),\n ].join('\\n');\n\n const result = await ctx.api.llm.complete({\n messages: [\n { role: 'system', content: metaPromptContent },\n { role: 'user', content: userMessage },\n ],\n options: { model: agent.modelId },\n promptRef: { name: metaPromptName, label: 'production', resolve: false },\n });\n\n const suggestedContent = result.text.trim();\n if (!suggestedContent) throw new ctx.NonRetriableError('The model returned an empty suggestion');\n\n const referenceErrors = await validateReferences(ctx.api, suggestedContent, promptName);\n if (referenceErrors.length > 0) {\n // The rejected content is included, not discarded (T23 post-review B4):\n // without it, an operator can neither see what the model produced nor\n // repair it by hand, and a retry re-spends the completion that already\n // paid for this exact (rejected) text.\n throw new ctx.NonRetriableError(\n [\n `Suggested content has invalid reference tags: ${referenceErrors.join(' ')}`,\n '--- REJECTED CONTENT ---',\n suggestedContent,\n ].join('\\n\\n'),\n );\n }\n\n let version: number;\n try {\n ({ version } = await ctx.api.prompts.createVersion(promptName, {\n content: suggestedContent,\n tags: ['ai_suggested'],\n }));\n } catch (err) {\n // H4 (T25 review): left unguarded, a 403 here (promptName outside\n // role.prompts) reached the caller as an opaque platform exception —\n // AFTER the llm.complete call above already paid for suggestedContent.\n // Same courtesy as the reference-validation rejection just above: name\n // the cause and include the content the operator already paid for,\n // rather than discarding it behind a generic failure.\n if (err instanceof AppApiError && err.status === 403) {\n throw new ctx.NonRetriableError(\n [\n `Cannot save this suggestion: prompt \"${promptName}\" is outside this app's prompts allowlist (role.prompts). ${err.message}`,\n '--- REJECTED CONTENT ---',\n suggestedContent,\n ].join('\\n\\n'),\n );\n }\n throw err;\n }\n\n return { promptName, version, comparisonCount: comparisons.length };\n}\n","/**\n * `run-diff-analysis` (§3.5) — `uiInvoke`, correction patterns → the\n * `diff-analysis` record (`records/diff-analysis.ts`), equivalent to legacy\n * `POST /response-comparisons/diff-analysis`.\n *\n * Simplification versus the legacy route (recorded here, not silently):\n * legacy computed a word-level diff (`serverWordDiff`) client-side and fed\n * the LLM the deleted/inserted word lists. The kit's `response-comparison`\n * record carries a `diff` field \"computed at write time\" by\n * `ext-response-comparison` (T24, `response-comparison-diff.ts`'s\n * `computeWordDiff` — `DiffToken[]`, `{op: 'equal'|'insert'|'delete',\n * text}`). Feeding the LLM the RAW `generatedText`/`sentText` pair for each\n * non-identical comparison is functionally equivalent for a\n * pattern-finding meta-prompt (arguably richer input than a pre-diffed\n * word list) and avoids this function depending on that intermediate shape\n * at all.\n *\n * `minRole: 'EDITOR'`: writes a `diff-analysis` row (an upsert, not a\n * prompt version) — still a write, not a read.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport { diffAnalysisUniqueKey } from '../records/diff-analysis';\nimport { resolvePromptName } from '../prompts/slots';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { RUN_DIFF_ANALYSIS_INPUT_AGENT_ID_UID, RUN_DIFF_ANALYSIS_INPUT_LIMIT_UID } from './ids';\nimport { toAgent } from './records';\n\nconst DEFAULT_LIMIT = 50;\nconst MAX_IMPROVEMENTS = 3;\n\nconst DEFAULT_DIFF_ANALYSIS_META_PROMPT = [\n \"Tu analyses des paires (réponse générée par l'IA, réponse réellement envoyée par un agent humain) pour un assistant de support client.\",\n 'Identifie au maximum 3 patterns récurrents de correction (ton, structure, longueur, formulations, niveau de détail).',\n 'Réponds uniquement avec un objet JSON {\"improvements\": string[]}, sans autre texte.',\n].join('\\n');\n\nconst RESPONSE_SCHEMA = {\n name: 'diff_analysis',\n schema: {\n type: 'object',\n properties: { improvements: { type: 'array', items: { type: 'string' } } },\n required: ['improvements'],\n additionalProperties: false,\n },\n};\n\nexport interface RunDiffAnalysisInput {\n agentId: string;\n limit?: number;\n}\n\nexport interface RunDiffAnalysisResult {\n agentId: string;\n promptName: string;\n promptVersion: number;\n points: string[];\n comparisonCount: number;\n}\n\nexport function buildRunDiffAnalysisFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'run-diff-analysis'),\n name: 'run-diff-analysis',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n { universalIdentifier: RUN_DIFF_ANALYSIS_INPUT_AGENT_ID_UID, name: 'agentId', type: FieldType.TEXT, label: 'Agent id', isNullable: false },\n { universalIdentifier: RUN_DIFF_ANALYSIS_INPUT_LIMIT_UID, name: 'limit', type: FieldType.NUMBER, label: 'Limit', isNullable: true },\n ],\n };\n}\n\nexport function createRunDiffAnalysisHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => runDiffAnalysisHandler(ctx as SupportKitHandlerContext, config, input as unknown as RunDiffAnalysisInput);\n}\n\nexport async function runDiffAnalysisHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: RunDiffAnalysisInput,\n): Promise<RunDiffAnalysisResult> {\n const agentId = input?.agentId?.trim();\n if (!agentId) throw new ctx.NonRetriableError('agentId is required');\n\n const agent = toAgent(await ctx.api.get('agent', agentId));\n const promptName = agent.promptName;\n if (!promptName) throw new ctx.NonRetriableError(`Agent \"${agentId}\" has no promptName configured`);\n\n let promptVersion = agent.promptVersion ?? 0;\n try {\n promptVersion = (await ctx.api.prompts.get(promptName, { label: 'production' })).version;\n } catch {\n // Prompt store unreachable/unconfigured — fall back to the agent's own last-known version.\n }\n\n // Scoped to the ACTIVE prompt version, not just the agent (legacy\n // behaviour, ported — see `suggest-prompt.ts`'s identical fix): a pattern\n // observed against a superseded version must not be stamped onto the\n // version that superseded it.\n const limit = Math.min(input?.limit ?? DEFAULT_LIMIT, DEFAULT_LIMIT);\n const page = await ctx.api.list('response-comparison', { filter: { agentId, promptName, promptVersion }, limit });\n const pairs = page.items\n .map((r) => r.data as { generatedText: string | null; sentText: string })\n .filter((c) => c.generatedText && c.generatedText.trim() !== c.sentText.trim());\n\n if (pairs.length === 0) {\n throw new ctx.NonRetriableError('No non-identical comparison found for this agent');\n }\n\n const metaPromptName = resolvePromptName('diff-analysis', config);\n // §3.7 point 3 — the kit's own built-in text is the LAST resort;\n // `config.defaults.prompts['diff-analysis']` (T25) overrides it first.\n const configuredFallback = config.defaults?.prompts?.['diff-analysis'] ?? DEFAULT_DIFF_ANALYSIS_META_PROMPT;\n let metaPromptContent = configuredFallback;\n try {\n metaPromptContent = (await ctx.api.prompts.get(metaPromptName, { label: 'production' })).content || configuredFallback;\n } catch {\n // Level-3 fallback (§3.7) — the `diff-analysis` slot has no `production` version yet.\n }\n\n const userMessage = pairs\n .map((c, i) => `### Exemple ${i + 1}\\nIA a généré :\\n${(c.generatedText ?? '').trim()}\\n\\nAgent a réellement envoyé :\\n${c.sentText.trim()}`)\n .join('\\n\\n---\\n\\n');\n\n const result = await ctx.api.llm.complete({\n messages: [\n { role: 'system', content: metaPromptContent },\n { role: 'user', content: userMessage },\n ],\n options: { model: agent.modelId, responseSchema: RESPONSE_SCHEMA },\n promptRef: { name: metaPromptName, label: 'production', resolve: false },\n });\n\n let points: string[];\n try {\n const parsed = JSON.parse(result.text) as { improvements?: unknown };\n points = Array.isArray(parsed.improvements) ? parsed.improvements.filter((p): p is string => typeof p === 'string').slice(0, MAX_IMPROVEMENTS) : [];\n } catch {\n throw new ctx.NonRetriableError('The model returned an invalid JSON response');\n }\n\n await ctx.api.upsert(\n 'diff-analysis',\n [\n {\n data: {\n agentId,\n promptName,\n promptVersion,\n points,\n uniqueKey: diffAnalysisUniqueKey(agentId, promptName, promptVersion),\n },\n },\n ],\n { uniqueBy: ['uniqueKey'] },\n );\n\n return { agentId, promptName, promptVersion, points, comparisonCount: pairs.length };\n}\n","/**\n * `list-gorgias-views` (§3.5) — `uiInvoke`, view autocomplete (S1\n * `listViews`) for the Settings page's `sourceViewId` field, plus §4's\n * cross-app view-claim warning: \"avertit si la vue configurée est déjà\n * revendiquée par une autre app support (lecture croisée du record\n * `pipeline-state` exposé `exposedToApps:['*']`, en lecture seule — seul\n * point de contact inter-apps, purement informatif)\".\n *\n * DELIBERATE EXCEPTION to \"every handler reads settings through\n * `validateSettings` before use\": this function is the checklist's OWN\n * step 2 tool for CHOOSING `sourceViewId` in the first place (§4's \"créer\n * une nouvelle audience\" checklist) — gating it on `validateSettings`,\n * which itself requires `sourceViewId` to be non-empty, would make the\n * autocomplete unusable on the exact first-run screen it exists for. Every\n * OTHER field `validateSettings` checks (`nodes.triage`, `senderEmail`) is\n * equally irrelevant to listing Gorgias views.\n *\n * ASSUMPTION (stated, not decided silently): the kit has no platform\n * capability to enumerate OTHER installed apps — `SupportKitApi` is scoped\n * to this app's own token, and nothing in §2's S1-S6 socle exposes an \"apps\n * of this kind\" listing. `input.checkAppSlugs` is therefore CALLER-SUPPLIED:\n * the Settings page (out of this task's scope) already has its own,\n * unrelated way to see the instance's installed apps (an admin-facing\n * listing this app's own token cannot and should not reach) and passes the\n * OTHER support-kit apps' slugs in. A slug that turns out not to expose\n * `pipeline-state` to this app (not installed, not a support-kit app, or a\n * true `403`) is reported in `uncheckedAppSlugs` rather than failing the\n * whole call — the warning is \"purement informatif\" (§4), never a gate.\n *\n * P1 (« Connexion Gorgias »): this function ALSO reports the instance's\n * Gorgias connections. The Settings page used to expose a free-text\n * `gorgiasConnectionId` that nothing read — every call in the kit goes\n * through `ctx.api.integrations.run('gorgias', …)` WITHOUT a\n * `connectionId`, so the platform resolves the default connection and the\n * field was decorative. The kit now states which connection answers instead\n * of pretending to choose it, and warns on the one configuration that\n * actually breaks: several connections with no default, which the platform\n * rejects with `409 AMBIGUOUS_CONNECTION`\n * (`app-integrations.controller.ts`). It lives here rather than in a new\n * `uiInvoke` function because the Settings page already calls this one for\n * the very same section, and a new function would cost the consuming app a\n * new `universalIdentifier` (`identifierFor` throws on a missing one) for\n * no added capability.\n *\n * `minRole: 'VIEWER'`: a pure read, informational only.\n *\n * T25 DECISION (spec §3.2, \"T25 or the Settings page must supply\n * `checkAppSlugs`\"): `SupportPipelineConfig` deliberately does NOT grow a\n * field for this. A config field would be a STATIC list, fixed at manifest\n * build/publish time — exactly wrong for \"which other support-kit apps\n * exist\", a fact that changes every time an audience is added or removed\n * without republishing this one. The Settings page (T26) is the only\n * correct owner: it already needs an admin-facing \"installed apps\" listing\n * this function's own scoped token cannot and should not reach (see the\n * ASSUMPTION above), and it is the one place that can pass a FRESH\n * `checkAppSlugs` on every invocation. Nothing changes here.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { LIST_GORGIAS_VIEWS_INPUT_CHECK_APP_SLUGS_UID } from './ids';\n\nexport interface ListGorgiasViewsInput {\n /** Other installed support-kit apps' slugs to check `sourceViewId` overlap against (§4) — see this module's own doc for why this is caller-supplied. */\n checkAppSlugs?: string[];\n}\n\nexport interface GorgiasViewOption {\n id: string;\n name: string;\n /** Other apps whose `pipeline-state.sourceViewId` already names this view. Empty when clear (or unverifiable). */\n claimedByAppSlugs: string[];\n}\n\nexport interface GorgiasConnection {\n id: string;\n label: string;\n isDefault: boolean;\n}\n\nexport interface ListGorgiasViewsResult {\n views: GorgiasViewOption[];\n /** `checkAppSlugs` entries that could not be read (not installed, not exposing `pipeline-state` to this app, or unreachable) — informational, never a failure. */\n uncheckedAppSlugs: string[];\n /**\n * The instance's Gorgias connections, credentials stripped by the platform\n * (`GET /data/integrations/gorgias/connections`). `null` means the listing\n * itself FAILED — distinct from `[]`, which means the instance genuinely\n * has no Gorgias connection and the pipeline cannot run at all. The\n * Settings page renders the two differently, so collapsing them would turn\n * a real misconfiguration into an unexplained blank.\n */\n connections: GorgiasConnection[] | null;\n}\n\nexport function buildListGorgiasViewsFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'list-gorgias-views'),\n name: 'list-gorgias-views',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: LIST_GORGIAS_VIEWS_INPUT_CHECK_APP_SLUGS_UID,\n name: 'checkAppSlugs',\n type: FieldType.JSON,\n label: 'Check app slugs',\n description: 'string[] — other support-kit app slugs to check for a sourceViewId overlap.',\n isNullable: true,\n },\n ],\n };\n}\n\nexport function createListGorgiasViewsHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => listGorgiasViewsHandler(ctx as SupportKitHandlerContext, config, (input as ListGorgiasViewsInput) ?? {});\n}\n\nconst PIPELINE_STATE_SINGLETON_KEY = 'default';\n\ntype ClaimedViewRead = { ok: true; claimedViewId: string | null } | { ok: false };\n\n/**\n * The view `appSlug` currently claims, or `null` when it claims none (a\n * SUCCESSFUL read of an empty/unset singleton — a fresh app that has never\n * triaged is \"checked, not claiming anything\", not \"unverifiable\"). `ok:\n * false` is reserved for an actual read FAILURE (not installed, not\n * exposing `pipeline-state` to this app, or unreachable) — the two must\n * stay distinct, or a legitimately-clear app would be reported as\n * unverifiable instead of clear.\n */\nasync function readClaimedView(ctx: SupportKitHandlerContext, appSlug: string): Promise<ClaimedViewRead> {\n try {\n const page = await ctx.api.crossApp.list(appSlug, 'pipeline-state', { filter: { singletonKey: PIPELINE_STATE_SINGLETON_KEY }, limit: 1 });\n const sourceViewId = page.items[0]?.data.sourceViewId;\n return { ok: true, claimedViewId: typeof sourceViewId === 'string' && sourceViewId.length > 0 ? sourceViewId : null };\n } catch {\n return { ok: false };\n }\n}\n\nexport async function listGorgiasViewsHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: ListGorgiasViewsInput,\n): Promise<ListGorgiasViewsResult> {\n const rawViews = (await ctx.api.integrations.run('gorgias', 'listViews', {})) as { views: Array<{ id: string | number; name: string }> };\n const views = rawViews.views.map((v) => ({ id: String(v.id), name: v.name }));\n\n // Reported, never thrown: which connection answers is a property of the\n // instance the operator cannot set from here (P1), so a failure to read it\n // must not take the view autocomplete — this function's actual job — down\n // with it.\n let connections: GorgiasConnection[] | null;\n try {\n connections = await ctx.api.integrations.list('gorgias');\n } catch {\n connections = null;\n }\n\n const candidateSlugs = (input.checkAppSlugs ?? []).filter((slug) => slug && slug !== config.slug);\n\n const claimedByViewId = new Map<string, string[]>();\n const uncheckedAppSlugs: string[] = [];\n for (const slug of candidateSlugs) {\n const read = await readClaimedView(ctx, slug);\n if (!read.ok) {\n uncheckedAppSlugs.push(slug);\n continue;\n }\n if (read.claimedViewId === null) continue; // checked, and it claims nothing\n const claimants = claimedByViewId.get(read.claimedViewId) ?? [];\n claimants.push(slug);\n claimedByViewId.set(read.claimedViewId, claimants);\n }\n\n return {\n views: views.map((v) => ({ id: v.id, name: v.name, claimedByAppSlugs: claimedByViewId.get(v.id) ?? [] })),\n uncheckedAppSlugs,\n connections,\n };\n}\n","/**\n * `create-agent` (§3.4) — `uiInvoke`, creates a new drafting agent with a\n * server-assigned `promptName` of `agent/<recordId>`.\n *\n * `agent.promptName` is `isNullable: false` with no default\n * (`records/agent.ts`) — the record's own id does not exist until AFTER the\n * create, so a plain `POST records/agent` from the browser has no legal\n * value to send for it. Before this function existed, AgentsPage's \"Nouvel\n * agent\" form posted with no `promptName` field at all, the write was\n * rejected, `save()` had no `.catch`, and the modal just sat there with no\n * feedback (T26 review, BLOCKER 3).\n *\n * The fix is the two-step create-then-patch the record id makes necessary,\n * done in ONE server-side round trip: the browser only ever sees the final,\n * fully-formed agent — never the placeholder `promptName` the first write is\n * forced to carry for the instant before the id is known.\n *\n * `minRole: 'EDITOR'`: creating an agent is an editing action, matching\n * every other agent-mutating control on AgentsPage.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport { DEFAULT_LLM_PROVIDER } from '../records/agent';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport {\n CREATE_AGENT_INPUT_MODEL_ID_UID,\n CREATE_AGENT_INPUT_NAME_UID,\n CREATE_AGENT_INPUT_PROVIDER_UID,\n CREATE_AGENT_INPUT_SYSTEM_PROMPT_SNAPSHOT_UID,\n} from './ids';\nimport { toAgent, type AgentRecord } from './records';\n\n/**\n * Placeholder `promptName` for the single instant between the create and the\n * patch that overwrites it with `agent/<id>` — this handler is the only\n * thing that ever reads a record carrying it, so its exact spelling has no\n * external contract.\n */\nconst PENDING_PROMPT_NAME = 'agent/pending';\n\nexport interface CreateAgentInput {\n name: string;\n modelId: string;\n provider?: string;\n systemPromptSnapshot?: string;\n}\n\nexport function buildCreateAgentFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'create-agent'),\n name: 'create-agent',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n { universalIdentifier: CREATE_AGENT_INPUT_NAME_UID, name: 'name', type: FieldType.TEXT, label: 'Name', isNullable: false },\n { universalIdentifier: CREATE_AGENT_INPUT_MODEL_ID_UID, name: 'modelId', type: FieldType.TEXT, label: 'Model id', isNullable: false },\n { universalIdentifier: CREATE_AGENT_INPUT_PROVIDER_UID, name: 'provider', type: FieldType.TEXT, label: 'Provider', isNullable: true },\n {\n universalIdentifier: CREATE_AGENT_INPUT_SYSTEM_PROMPT_SNAPSHOT_UID,\n name: 'systemPromptSnapshot',\n type: FieldType.TEXT,\n label: 'System prompt snapshot',\n isNullable: true,\n },\n ],\n };\n}\n\nexport function createCreateAgentHandler(): AppHandler {\n return (ctx, input) =>\n createAgentHandler(ctx as SupportKitHandlerContext, (input as unknown as CreateAgentInput) ?? {});\n}\n\nexport async function createAgentHandler(\n ctx: SupportKitHandlerContext,\n input: CreateAgentInput,\n): Promise<AgentRecord> {\n const name = input?.name?.trim();\n if (!name) throw new ctx.NonRetriableError('name is required');\n const modelId = input?.modelId?.trim();\n if (!modelId) throw new ctx.NonRetriableError('modelId is required');\n\n const created = await ctx.api.create('agent', {\n name,\n modelId,\n provider: input.provider?.trim() || DEFAULT_LLM_PROVIDER,\n status: 'available',\n promptName: PENDING_PROMPT_NAME,\n ...(input.systemPromptSnapshot?.trim() ? { systemPromptSnapshot: input.systemPromptSnapshot.trim() } : {}),\n });\n\n const withPromptName = await ctx.api.update('agent', created.id, { promptName: `agent/${created.id}` });\n return toAgent(withPromptName);\n}\n","/**\n * `set-default-agent` (§3.4) — `uiInvoke`, promotes one agent to\n * `status: 'default'` while demoting whatever agent currently holds it.\n *\n * `records/agent.ts` documents the invariant: \"at most one default agent\",\n * enforced by a unique index on `defaultKey`, which is set to `'default'`\n * exactly when `status === 'default'` and left absent otherwise (so Postgres\n * NULLs never collide) — and states that POPULATING `defaultKey` correctly\n * is \"a write-handler concern\", not the record definition's. Before this\n * function existed, nothing populated it at all: AgentsPage's \"Définir par\n * défaut\" button wrote `{status: 'default'}` alone, from the browser, as two\n * independent `PATCH` calls with no shared transaction — `defaultKey` never\n * moved, the unique index never fired, and clicking the button on a second\n * agent produced two rows with `status: 'default'` without demoting the\n * first. `resolveDraftAgent` (`functions/records.ts`) resolves the default\n * agent via `list('agent', {filter:{status:'default'}, limit:1})`, so which\n * of the two an uncategorised ticket drafts with became non-deterministic,\n * and `ext-models` would serve two \"default\" agents to the extension (T26\n * review, BLOCKER 4).\n *\n * This function does both writes from ONE server-side call, DEMOTING the\n * incumbent BEFORE promoting the target — not the other way round, and not\n * in parallel: `defaultKey` carries a unique index, so having the incumbent\n * and the target both hold `'default'` at once, even for one write, would\n * violate it. Demoting first means a failure between the two writes leaves\n * AT MOST ZERO default agents (a safe, if inconvenient, state an operator\n * can fix by retrying) rather than two — this kit has no cross-record\n * transaction to make the pair atomic, so \"the worst reachable state is\n * still a legal one\" is the best guarantee available without one.\n *\n * `minRole: 'EDITOR'`: matches AgentsPage's other agent-mutating controls.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { SET_DEFAULT_AGENT_INPUT_AGENT_ID_UID } from './ids';\nimport { toAgent, type AgentRecord } from './records';\n\nconst DEFAULT_KEY_VALUE = 'default';\n\nexport interface SetDefaultAgentInput {\n agentId: string;\n}\n\nexport function buildSetDefaultAgentFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'set-default-agent'),\n name: 'set-default-agent',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n {\n universalIdentifier: SET_DEFAULT_AGENT_INPUT_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.TEXT,\n label: 'Agent id',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createSetDefaultAgentHandler(): AppHandler {\n return (ctx, input) =>\n setDefaultAgentHandler(ctx as SupportKitHandlerContext, (input as unknown as SetDefaultAgentInput) ?? {});\n}\n\nexport async function setDefaultAgentHandler(\n ctx: SupportKitHandlerContext,\n input: SetDefaultAgentInput,\n): Promise<AgentRecord> {\n const agentId = input?.agentId?.trim();\n if (!agentId) throw new ctx.NonRetriableError('agentId is required');\n\n const target = toAgent(await ctx.api.get('agent', agentId));\n if (target.status === 'default') return target; // already the default — no-op, not an error.\n\n const incumbentPage = await ctx.api.list('agent', { filter: { status: 'default' }, limit: 1 });\n const incumbent = incumbentPage.items[0];\n if (incumbent && incumbent.id !== agentId) {\n await ctx.api.update('agent', incumbent.id, { status: 'available', defaultKey: null });\n }\n\n const promoted = await ctx.api.update('agent', agentId, {\n status: 'default',\n defaultKey: DEFAULT_KEY_VALUE,\n });\n return toAgent(promoted);\n}\n","/**\n * `create-shared-prompt-version` (§3.8 SharedPromptsPage, T27 part B) — the\n * ONE write path SharedPromptsPage uses to save a new `shared/*` prompt\n * version.\n *\n * Why this exists instead of the browser calling S3's own\n * `POST /data/apps/:appSlug/prompts/versions` directly (the way\n * `AgentsPage`'s `usePromptVersions.createVersion` already does for an\n * agent's prompt): that route writes whatever content it is given — it\n * does not run `validateReferences` (`./validate-references.ts`), and per\n * T19/T23's own review, nothing server-side does either. Since the kit\n * resolves `@@@langfusePrompt:…@@@` composition ITSELF (T19's\n * `prompts/resolver.ts`, reading with `resolve:false`), a malformed tag\n * saved through the raw REST route reaches every draft that composes\n * `shared/style-email`/`shared/style-whatsapp` verbatim, with nothing\n * server-side left to catch it — exactly the gap T23's review named for\n * `suggest-prompt`'s write path (§3.5). This is the same guard, for a\n * human operator's edit instead of an LLM suggestion.\n *\n * Scoped to `shared/` names only (refuses anything else): SharedPromptsPage\n * is a `shared/*` library editor, not a general prompt-writing surface.\n * `role.prompts`' `shared/*` glob (`pipeline.ts`'s `buildPromptsAllowlist`)\n * is the actual authorization boundary; this refusal is a narrower,\n * separate promise about what THIS function is for — `AgentsPage` keeps\n * writing an agent's own prompt through S3's raw route, unaffected.\n *\n * `minRole: 'EDITOR'`: a write, like every other prompt-mutating control\n * in the kit (`createVersion`/`promote`/`deleteVersion`, S3).\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID, CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID } from './ids';\nimport { validateReferences } from './validate-references';\n\nconst SHARED_PREFIX = 'shared/';\n\nexport interface CreateSharedPromptVersionInput {\n name: string;\n content: string;\n}\n\nexport interface CreateSharedPromptVersionResult {\n version: number;\n}\n\nexport function buildCreateSharedPromptVersionFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'create-shared-prompt-version'),\n name: 'create-shared-prompt-version',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n {\n universalIdentifier: CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID,\n name: 'name',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: false,\n },\n {\n universalIdentifier: CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID,\n name: 'content',\n type: FieldType.TEXT,\n label: 'Content',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createCreateSharedPromptVersionHandler(): AppHandler {\n return (ctx, input) =>\n createSharedPromptVersionHandler(\n ctx as SupportKitHandlerContext,\n (input as unknown as CreateSharedPromptVersionInput) ?? { name: '', content: '' },\n );\n}\n\nexport async function createSharedPromptVersionHandler(\n ctx: SupportKitHandlerContext,\n input: CreateSharedPromptVersionInput,\n): Promise<CreateSharedPromptVersionResult> {\n const name = input?.name?.trim();\n if (!name) throw new ctx.NonRetriableError('name is required');\n if (!name.startsWith(SHARED_PREFIX)) {\n throw new ctx.NonRetriableError(\n `\"${name}\" is not a shared/* prompt — create-shared-prompt-version only writes the shared/* library.`,\n );\n }\n const content = input?.content ?? '';\n if (!content.trim()) throw new ctx.NonRetriableError('content is required');\n\n const referenceErrors = await validateReferences(ctx.api, content, name);\n if (referenceErrors.length > 0) {\n throw new ctx.NonRetriableError(`Invalid reference tags: ${referenceErrors.join(' ')}`);\n }\n\n return ctx.api.prompts.createVersion(name, { content });\n}\n","/**\n * `sync-agent-prompt-snapshot` (§5.2) — `uiInvoke`, rewrites one agent's\n * `systemPromptSnapshot` with the prompt content that agent NOW serves.\n *\n * Why the snapshot needs a writer at all: `GET /models` serves\n * `system_prompt` from `agent.systemPromptSnapshot` ONLY (`ext-models.ts`)\n * — §5.2 forbids a synchronous Langfuse read there, because the extension\n * calls that route on every ticket change for every support agent. The spec\n * pays for that with one sentence: the snapshot is \"rafraîchi en tâche de\n * fond à chaque `createVersion`/`promote`\". Nothing did that. The only\n * writers were `create-agent` (from its input, once) and a hand edit in\n * AgentsPage, so promoting a new version moved what the PIPELINE drafts\n * with while the extension kept serving the text of whatever version was\n * current the day the agent was created — and `draftPromptRefFor`'s\n * level-3 fallback (`records.ts`) stayed pinned to that same stale text.\n *\n * Keyed by `promptName`, not by agent id, because the caller\n * (`ui/agents/use-prompt-versions.ts`) is a prompt-versions hook: it knows\n * the prompt it just wrote, never which record owns it. That also gives\n * the `shared/*` case its answer for free — a company-wide prompt belongs\n * to no agent, the lookup finds nothing, and the function is a no-op\n * rather than needing a namespace test of its own.\n *\n * WHAT IS SERVED, not what is newest: an agent pinned via\n * `agent.promptVersion` keeps drafting with that exact version, so its\n * snapshot must be that version's content — refreshing it to the newest\n * one would make `GET /models` advertise a prompt the pipeline does not\n * use. The ref built here is the same one `draftPromptRefFor` resolves.\n *\n * Read with `resolve: false`, like `createPlatformPromptReader`\n * (`adapters/ctx-ports.ts`): the kit flattens `@@@langfusePrompt:…@@@`\n * composition itself, so the snapshot must hold the RAW stored template —\n * the same text the resolver would have cached — not a pre-flattened\n * variant the fallback path would never produce.\n *\n * Never rejects on a resolution failure: by the time this runs, the\n * `createVersion`/`promote` it follows has already committed. Turning a\n * Langfuse outage into a failed promote would report a write that DID\n * happen as a write that did not; a stale snapshot is the lesser, and\n * self-correcting, harm (the next version write retries it).\n *\n * `minRole: 'EDITOR'`: it follows a prompt write, which is already\n * EDITOR-only (S3's own `createVersion`/`promote`).\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID } from './ids';\nimport { toAgent } from './records';\n\nexport interface SyncAgentPromptSnapshotInput {\n promptName: string;\n}\n\nexport interface SyncAgentPromptSnapshotResult {\n /** `false` also covers \"nothing to do\": no agent owns the prompt, the snapshot already matched, or the read failed. */\n updated: boolean;\n}\n\nexport function buildSyncAgentPromptSnapshotFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'sync-agent-prompt-snapshot'),\n name: 'sync-agent-prompt-snapshot',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n {\n universalIdentifier: SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createSyncAgentPromptSnapshotHandler(): AppHandler {\n return (ctx, input) =>\n syncAgentPromptSnapshotHandler(\n ctx as SupportKitHandlerContext,\n (input as unknown as SyncAgentPromptSnapshotInput) ?? { promptName: '' },\n );\n}\n\nexport async function syncAgentPromptSnapshotHandler(\n ctx: SupportKitHandlerContext,\n input: SyncAgentPromptSnapshotInput,\n): Promise<SyncAgentPromptSnapshotResult> {\n const promptName = input?.promptName?.trim();\n if (!promptName) throw new ctx.NonRetriableError('promptName is required');\n\n const page = await ctx.api.list('agent', { filter: { promptName }, limit: 1 });\n const record = page.items[0];\n if (!record) return { updated: false };\n const agent = toAgent(record);\n\n try {\n const ref =\n agent.promptVersion !== null ? { version: agent.promptVersion } : { label: agent.promptLabel ?? 'production' };\n const detail = await ctx.api.prompts.get(promptName, { ...ref, resolve: false });\n if (detail.content === agent.systemPromptSnapshot) return { updated: false };\n\n await ctx.api.update('agent', agent.id, { systemPromptSnapshot: detail.content });\n return { updated: true };\n } catch (error) {\n ctx.logger.warn(\n `sync-agent-prompt-snapshot: could not refresh \"${promptName}\" — GET /models keeps serving the previous snapshot (${String(error)})`,\n );\n return { updated: false };\n }\n}\n","/**\n * `ext-models` (§5.2, §3.5 line 291) — `uiInvoke`, reserved. Ports legacy\n * `GET /api/models` (extension-overview backoffice/src/routes/api.ts:27).\n * Reached only through the platform-served extension gateway (S6), always\n * as `phase: 'execute'`, fanned out to every accessible app and unioned —\n * this function MUST return an array: a non-array result is logged and\n * silently dropped from the union by the gateway\n * (`SupportExtensionService.invokeAll`), never surfaced as an error.\n *\n * `system_prompt` is served from `agent.systemPromptSnapshot` ONLY — never\n * a synchronous Langfuse resolution. §5.2 is explicit about why: this\n * endpoint is hit on every ticket change, by every agent, so a per-request\n * Langfuse round trip at that frequency is the exact cost the snapshot\n * exists to avoid. The snapshot itself is kept fresh out-of-band, by\n * whichever write path refreshes it on `createVersion`/`promote` — not this\n * function's job.\n *\n * `system_prompt_token_count` is kept (frozen data model, §5.2 — \"conservé\n * bien qu'ignoré par l'extension\") but is an APPROXIMATION, not tiktoken's\n * real count: the kit cannot depend on `tiktoken`\n * (`dependency-allowlist.ts`, spec §3.1 — it is a native/WASM dependency,\n * unsafe across an arbitrary app's ESM bundler). This ports the legacy\n * tokenizer's OWN documented fallback path verbatim\n * (`utils/tokenizer.ts`'s `catch` branch, `Math.ceil(text.length / 4)`) —\n * here it is the only implementation, not a fallback from a real\n * tokenizer. It is a rough estimate (English text averages roughly 4\n * characters per token; French/accented text and code both deviate\n * further from that ratio) and MUST NOT be treated as exact by any future\n * consumer — today's one consumer (the extension) explicitly ignores it.\n *\n * `archived` agents are excluded — legacy's `status: {$in: ['default',\n * 'available']}` filter. Legacy sorts `{status: 1, name: 1}`; ported here\n * for this function's OWN array. The GATEWAY re-sorts the union by\n * `(order, name)` (§S6, D3) and a model carries no `order` field, so the\n * final wire order across multiple support apps ends up name-alphabetical\n * rather than `(status, name)` — a documented S6/T8 divergence from the\n * legacy, not this function's to fix (see the migration progress journal's\n * T24 entry).\n *\n * SETTINGS VALIDATION: deliberately NOT called here, same reasoning as\n * `list-gorgias-views`'s own documented exception. This function reads no\n * field `validateSettings` checks (`sourceViewId`, `nodes.triage`,\n * `senderEmail`) — it is a pure read of `agent` records serving a human\n * agent's Gorgias sidebar model picker. Gating it on settings validity\n * would break that picker for a tenant mid-setup, for no correctness\n * reason: nothing here depends on the triage pipeline being configured.\n *\n * `minRole: 'VIEWER'` is load-bearing: `SupportExtensionService\n * .hasAllReservedFunctions` refuses to treat an app as a support app\n * unless all six reserved functions declare exactly `VIEWER`.\n */\nimport type { AppHandler, FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { toAgent } from './records';\n\nconst TOKEN_APPROXIMATION_CHARS_PER_TOKEN = 4;\nconst AGENT_PAGE_SIZE = 500;\n\nexport interface ExtModel {\n _id: string;\n name: string;\n provider: string;\n model_id: string;\n system_prompt: string;\n system_prompt_token_count: number;\n status: 'default' | 'available';\n}\n\nexport function buildExtModelsFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-models'),\n name: 'ext-models',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n };\n}\n\nexport function createExtModelsHandler(): AppHandler {\n return (ctx) => extModelsHandler(ctx as SupportKitHandlerContext);\n}\n\nexport async function extModelsHandler(ctx: SupportKitHandlerContext): Promise<ExtModel[]> {\n const page = await ctx.api.list('agent', { limit: AGENT_PAGE_SIZE });\n // L15: the migration's standing rule is \"no silent caps\" — past 500\n // agents the union would silently lose entries with no cursor and no\n // warning.\n if (page.items.length >= AGENT_PAGE_SIZE) {\n ctx.logger.warn(`ext-models: \"agent\" page came back full at ${page.items.length} rows — some may be silently missing from the response.`);\n }\n\n return page.items\n .map(toAgent)\n .filter((agent): agent is typeof agent & { status: 'default' | 'available' } => agent.status !== 'archived')\n .sort((a, b) => (a.status === b.status ? a.name.localeCompare(b.name) : a.status.localeCompare(b.status)))\n .map((agent) => {\n const systemPrompt = agent.systemPromptSnapshot ?? '';\n return {\n _id: agent.id,\n name: agent.name,\n provider: agent.provider,\n model_id: agent.modelId,\n system_prompt: systemPrompt,\n system_prompt_token_count: approximateTokenCount(systemPrompt),\n status: agent.status,\n };\n });\n}\n\nfunction approximateTokenCount(text: string): number {\n return Math.ceil(text.length / TOKEN_APPROXIMATION_CHARS_PER_TOKEN);\n}\n","/**\n * `ext-categories` (§5.2, §3.5 line 291) — `uiInvoke`, reserved. Ports\n * legacy `GET /api/categories` (extension-overview backoffice/src/routes\n * /api.ts:50). Reached only through the S6 gateway, always `phase:\n * 'execute'`, fanned out to every accessible app and unioned — MUST return\n * an array (a non-array is dropped by the gateway, same rule as\n * `ext-models`).\n *\n * Filter (legacy `Category.find({agent: {$ne: null}}).populate({path:\n * 'agent', match: {status: {$ne: 'archived'}}})` then `.filter(c => c.agent\n * !== null)`): a category counts only when it HAS an `agentId` AND that\n * agent resolves AND is not archived. §5.2's own response shape freezes\n * `agent: {...} | null`, but this filter means the `| null` branch is\n * UNREACHABLE through this handler today — kept in the type for wire\n * fidelity with the frozen contract, never actually emitted.\n *\n * Sort (composite, §5.2's own doc on this route): `group.order` ASC, with\n * ungrouped categories FIRST (`null` sorts as `-Infinity`) → `category\n * .order` ASC → `category.name` `localeCompare`. The category-group record\n * already exists (`records/category-group.ts`); this function is its\n * first reader.\n *\n * WIRE `order` IS NOT `category.order` (M4 hardening): the S6 gateway\n * unions every accessible app's categories and re-sorts by `(order, name)`\n * ONLY — it has no visibility into the group concept at all\n * (`support-extension.service.ts`'s own doc on `sortedUnion`). `order` is\n * per-GROUP, not global, so emitting the raw field would let the gateway's\n * blind re-sort silently destroy the group ordering this function just\n * computed (a single installed app is enough to observe it — no multi-app\n * edge case required). What is emitted instead is this category's own\n * POSITION in the fully sorted sequence above (0, 1, 2, …) — a composite\n * rank that already encodes group→order→name as one monotonic number, so\n * the gateway's re-sort is a genuine no-op on this app's contiguous slice,\n * not just a documented aspiration.\n *\n * SETTINGS VALIDATION: deliberately NOT called, same reasoning as\n * `ext-models` — a pure read of `category`/`agent` records serving a human\n * agent's Gorgias sidebar, gated on none of `validateSettings`'s fields.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n */\nimport type { AppHandler, FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { toAgent, toCategory, toCategoryGroup, type AgentRecord, type CategoryRecord } from './records';\n\nconst CATEGORY_PAGE_SIZE = 500;\nconst AGENT_PAGE_SIZE = 500;\n\nexport interface ExtCategoryAgent {\n _id: string;\n name: string;\n model_id: string;\n provider: string;\n}\n\nexport interface ExtCategory {\n _id: string;\n name: string;\n tag_name: string;\n order: number;\n agent: ExtCategoryAgent | null;\n}\n\nexport function buildExtCategoriesFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-categories'),\n name: 'ext-categories',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n };\n}\n\nexport function createExtCategoriesHandler(): AppHandler {\n return (ctx) => extCategoriesHandler(ctx as SupportKitHandlerContext);\n}\n\ninterface SortableEntry {\n category: CategoryRecord;\n agent: AgentRecord;\n groupOrder: number;\n}\n\nexport async function extCategoriesHandler(ctx: SupportKitHandlerContext): Promise<ExtCategory[]> {\n const [categoriesPage, groupsPage, agentsPage] = await Promise.all([\n ctx.api.list('category', { limit: CATEGORY_PAGE_SIZE }),\n ctx.api.list('category-group', { limit: CATEGORY_PAGE_SIZE }),\n // M7: ONE bulk read, not one `ctx.api.get` per category — this endpoint\n // runs on the same \"every ticket change, every agent\" cadence §5.2\n // documents for `/models` (which already does this), inside the\n // gateway's shared `FAN_OUT_BUDGET_MS`, so N+1 sequential round trips\n // risk a slow tenant's whole categories response silently dropping out\n // of the union on budget exhaustion.\n ctx.api.list('agent', { limit: AGENT_PAGE_SIZE }),\n ]);\n warnIfTruncated(ctx, 'category', categoriesPage.items.length, CATEGORY_PAGE_SIZE);\n warnIfTruncated(ctx, 'agent', agentsPage.items.length, AGENT_PAGE_SIZE);\n\n const groupOrderById = new Map(groupsPage.items.map(toCategoryGroup).map((g) => [g.id, g.order]));\n const agentById = new Map(agentsPage.items.map((record) => [record.id, toAgent(record)]));\n\n const entries: SortableEntry[] = [];\n for (const category of categoriesPage.items.map(toCategory)) {\n if (!category.agentId) continue;\n const agent = agentById.get(category.agentId);\n if (!agent) continue;\n if (agent.status === 'archived') continue;\n\n const groupOrder = category.groupId ? (groupOrderById.get(category.groupId) ?? -Infinity) : -Infinity;\n entries.push({ category, agent, groupOrder });\n }\n\n entries.sort((a, b) => {\n if (a.groupOrder !== b.groupOrder) return a.groupOrder - b.groupOrder;\n if (a.category.order !== b.category.order) return a.category.order - b.category.order;\n return a.category.name.localeCompare(b.category.name);\n });\n\n return entries.map(({ category, agent }, index) => ({\n _id: category.id,\n name: category.name,\n tag_name: category.tagName,\n // M4: this category's own POSITION in the fully sorted sequence, not\n // `category.order` verbatim — see this module's own doc.\n order: index,\n agent: { _id: agent.id, name: agent.name, model_id: agent.modelId, provider: agent.provider },\n }));\n}\n\n/** L15: the migration's standing rule is \"no silent caps\" — a page that comes back exactly full warrants a log, not a quiet truncation. */\nfunction warnIfTruncated(ctx: SupportKitHandlerContext, objectKey: string, itemCount: number, pageSize: number): void {\n if (itemCount >= pageSize) {\n ctx.logger.warn(`ext-categories: \"${objectKey}\" page came back full at ${itemCount} rows — some may be silently missing from the response.`);\n }\n}\n","/**\n * `ownsAgent` (L6) — the ONE `agent`-ownership probe check shared by\n * `ext-chat`, `ext-evaluation` and `ext-response-comparison`'s `phase:\n * 'probe'` branches (§S6 B1/B2): each restated the same `{claimed: true}`\n * sentinel, the same \"non-null claims / null disclaims / a genuine read\n * failure is never a disclaimer, it propagates as a real error\" contract,\n * and the same union return type. Three uses, so the no-premature-\n * abstraction rule does not shield the duplication.\n *\n * `id` absent/empty never claims — callers decide separately what to try\n * next on a `null` (`ext-chat` falls back to the default agent,\n * `ext-response-comparison` falls back to ticket ownership); this helper\n * only ever answers \"does this app own this one id\".\n */\nimport { getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\n\nexport interface ProbeClaim {\n claimed: true;\n}\n\nexport async function ownsAgent(ctx: SupportKitHandlerContext, id: string | null | undefined): Promise<ProbeClaim | null> {\n if (!id) return null;\n const record = await getOptional(ctx, 'agent', id);\n return record ? { claimed: true } : null;\n}\n","/**\n * `readSupportExtensionEnvelope` — the identity/phase the S6 gateway passes\n * on every reserved `ext-*` invocation\n * (`SupportExtensionService.invoke`'s `event: {supportExtension: {userId,\n * phase}}`, apps/api/src/platform-data/support-extension.service.ts).\n * Shared by every function that needs either half: `ext-chat`/\n * `ext-evaluation`/`ext-response-comparison` for the probe/execute split\n * (§5.1/§S6), `ext-evaluation` (`supportUserKeyId`) and\n * `ext-fast-response-check` (`servedTo`) for the platform user id itself.\n *\n * Defensive default, not a thrown error: an envelope that is missing or\n * malformed — which never happens through the real gateway, nothing else\n * invokes these reserved functions (§3.5 line 291) — resolves to `phase:\n * 'execute'` and `userId: ''` rather than crashing the whole handler on a\n * read. `'execute'` is the safe default direction for the phase: treating\n * an ambiguous call as `'probe'` would silently skip whatever real work the\n * caller actually wanted, while treating it as `'execute'` on a call that\n * WAS meant to be a cheap ownership probe only risks doing that same real\n * work anyway — never doing LESS than asked.\n *\n * `userId: ''` IS a safe default here — this is a pure READ with no side\n * effect. It is NOT safe symmetric treatment for the two call sites that\n * write it into an identity-bearing record (`ext-fast-response-check.ts`'s\n * `servedTo` push, `ext-evaluation.ts`'s `supportUserKeyId`) — §5.1\n * requires those records to carry the platform user id, so both callers\n * guard `!envelope.userId` themselves and fail the WRITE rather than\n * silently producing an anonymous-looking or null-identity row (L11\n * hardening). This function stays a defensive default, not a thrown error,\n * exactly as designed above; the burden of turning \"no identity\" into a\n * hard failure is on the two write sites that actually need one.\n */\nimport type { SupportKitHandlerContext } from './context';\n\nexport interface SupportExtensionEnvelope {\n userId: string;\n phase: 'probe' | 'execute';\n}\n\nexport function readSupportExtensionEnvelope(ctx: SupportKitHandlerContext): SupportExtensionEnvelope {\n const raw = (ctx.event as { supportExtension?: { userId?: unknown; phase?: unknown } } | undefined)?.supportExtension;\n return {\n userId: typeof raw?.userId === 'string' ? raw.userId : '',\n phase: raw?.phase === 'probe' ? 'probe' : 'execute',\n };\n}\n","/**\n * `ext-chat` (§5.2, §3.5 line 291) — `uiInvoke`, reserved, ownership-routed\n * (§S6). Ports legacy `POST /api/chat` (extension-overview backoffice/src\n * /routes/api.ts:147).\n *\n * OWNERSHIP PROBE (§S6 B1/B2): the gateway first calls this function with\n * `phase: 'probe'` and an id-only payload `{modelId}` — `modelId` may be\n * `undefined` (the legacy falls back to the single `status: 'default'`\n * model when it is absent). A probe MUST be cheap, local and side-effect-\n * free: no writes, no LLM call, no Gorgias fetch (`readSupportExtension\n * Envelope` picks the phase; the probe branch below only ever reads the\n * `agent` object). Claim rule, decided explicitly:\n * - `modelId` given → claim iff this app owns an `agent` record with\n * that id (any status — the legacy `ModelConfig.findById` applies no\n * status filter for chat, unlike `ext-models`).\n * - `modelId` absent → claim iff this app has a `status: 'default'`\n * agent.\n * AMBIGUITY, stated not hidden: with several installed support apps and no\n * `modelId`, more than one app can legitimately have its own default\n * agent, so more than one can claim the SAME probe. The gateway logs a\n * warning and routes to the first claimant (`SupportExtensionService\n * .invokeOwner`) — this function has no way to break that tie itself, and\n * does not try to. Returning any non-null value claims ownership; `null`\n * disclaims it. THROWING is never a way to say \"not mine\" (a genuine read\n * failure here propagates as a real error, exactly like every other\n * function — the gateway treats a probe throw as a fan-out failure, never\n * a disclaimer).\n *\n * EXECUTE: once ownership resolves, the gateway sends ONE `phase:\n * 'execute'` call with the full body — `{messages, modelId, agentName}` OR\n * `{gorgiasTicketId, modelId, agentName}`. When `gorgiasTicketId` is given\n * the conversation is rebuilt server-side via S1's `buildTicketContext`\n * action (NOT `getTicketWithContext` — only the extracted messages are\n * needed here, not the raw ticket payload `getTicketWithContext` also\n * fetches for the guardrail detectors elsewhere in the kit).\n *\n * PROMPT RESOLUTION reuses the kit's own §3.7 ladder\n * (`createPlatformPromptPort`) and `functions/records.ts`'s\n * `draftPromptRefFor` — the SAME binding `process-response` resolves the\n * `draft` node's prompt from (agent.promptName/promptLabel/\n * systemPromptSnapshot) — rather than writing a second resolver.\n *\n * `{{agent_name}}` SIGNATURE: §3.7 states the substitution is \"injectée\n * par `ext-chat`\" — this function calls the exact ported\n * `applySignature` (`graph/nodes/shared.ts`, exported for this reuse) on\n * the RESOLVED prompt text with the extension's own `agentName`, not the\n * generic `{{var}}` substitution `PromptPort.resolve`'s `vars` parameter\n * offers (which is a plain string replace, not `applySignature`'s full\n * rule set — appending a French signing instruction when there is no\n * placeholder at all). Reusing the ported function here — instead of a\n * second, subtly different implementation — was an explicit instruction in\n * this migration.\n *\n * SETTINGS VALIDATION: deliberately NOT called. Chat resolves its prompt\n * from the `agent` record's own binding, never from `validateSettings`'s\n * three checked fields (`sourceViewId`, `nodes.triage`, `senderEmail`) — a\n * misconfigured triage pipeline must not block an agent from testing a\n * model in the sidebar.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n *\n * POST-T24 REVIEW HARDENING:\n * - `options.model` now reads `resolvedPrompt.config?.model ?? agent\n * .modelId` (I16) — the resolved prompt's own model config wins, matching\n * every ported graph node; this was the one `PromptPort.resolve` consumer\n * that dropped it.\n * - `promptRef` IS forwarded to `ctx.api.llm.complete`, in LINK-ONLY mode\n * (`resolve: false`) — the D-LF follow-up task's resolution (option (b),\n * see the migration progress journal's T24 entry and its \"done\" correction):\n * the platform now decouples trace linkage from resolution, so a caller\n * that already resolved its own prompt (this function did, via\n * `PromptPort` two lines above) can link the completion to it in Langfuse\n * WITHOUT re-triggering the `manifest.prompts[]` declaration gate or the\n * system-message replacement (`app-integrations.controller.ts`'s\n * `llmComplete` JSDoc). This restores the same prompt-identity trace\n * linkage the platform's default mode gives every other caller, without\n * the 403/overwrite defect that forced the `trace.metadata` workaround\n * below during T24. The platform user id still travels on `trace.metadata`\n * (`ctx.api.llm.complete`'s `trace` has no dedicated `userId` field) — the\n * prompt identity no longer needs to, now that `promptRef` carries it. The\n * wire response is UNCHANGED — it still reports `prompt_name`/\n * `prompt_version` off `resolvedPrompt`.\n * The five graph nodes (`triage`/`escalate`/`draft`/`revise`/`evaluate`)\n * plus `suggest-prompt.ts`/`run-diff-analysis.ts` forward `promptRef` the\n * same link-only way now too — all seven sites adopted together.\n * - The gorgias-ticket branch now 400s on zero extracted messages, the same\n * guard the `input.messages` branch already had (M1) — an internal-notes-\n * only or automated-sender ticket must not pay for an LLM call with a\n * system message and no conversation.\n * - A Gorgias 404 (duck-typed off the caught error's `status`, since this\n * package has no dependency on `gorgias-client`'s `ProviderHttpError` to\n * `instanceof`-check) now throws `NonRetriableError` instead of a bare\n * rethrow (L1, PARTIAL). The legacy's other two mappings — \"not\n * configured\" → 503, else → 502 — are NOT reachable from here: every\n * `uiInvoke` throw funnels through `AppSyncInvocationService.toHttpError`\n * (`apps/api/src/platform-data/app-sync-invocation.service.ts`), which\n * recognises exactly two outcomes for an app-thrown error —\n * `AppNonRetriableError` → 422, anything else → 500 — regardless of what\n * `invokeOwner` does or doesn't wrap. 503/502 are outside this function's\n * reach without a platform change to that mapping.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { RawTicketContext } from '../adapters';\nimport { createPlatformPromptPort } from '../adapters/ctx-ports';\n// L9: through the barrel, not `./shared` directly — `graph/nodes/index.ts`'s\n// own doc names `applySignature` as its one curated export existing FOR this\n// reuse; importing straight from the file it lives in made that barrel entry\n// unused and its own justification inaccurate.\nimport { applySignature } from '../graph/nodes';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport {\n EXT_CHAT_INPUT_AGENT_NAME_UID,\n EXT_CHAT_INPUT_GORGIAS_TICKET_ID_UID,\n EXT_CHAT_INPUT_MESSAGES_UID,\n EXT_CHAT_INPUT_MODEL_ID_UID,\n} from './ids';\nimport { ownsAgent, type ProbeClaim } from './ownership-probe';\nimport { draftPromptRefFor, toAgent, type AgentRecord } from './records';\nimport { readSupportExtensionEnvelope } from './support-extension-envelope';\n\nconst DEFAULT_AGENT_FILTER = { status: 'default' } as const;\n\ninterface WireChatMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n}\n\nexport interface ExtChatInput {\n messages?: Array<{ role?: unknown; content?: unknown }> | null;\n modelId?: string | null;\n agentName?: string | null;\n gorgiasTicketId?: string | null;\n}\n\nexport interface ExtChatResult {\n answer: string;\n modelId: string;\n langfuse_trace_id: string | null;\n langfuse_observation_id: string | null;\n prompt_name: string | null;\n prompt_version: number | null;\n}\n\nexport function buildExtChatFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-chat'),\n name: 'ext-chat',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: EXT_CHAT_INPUT_MESSAGES_UID,\n name: 'messages',\n type: FieldType.JSON,\n label: 'Messages',\n description: '[{role, content}] — required unless gorgiasTicketId is given.',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_CHAT_INPUT_MODEL_ID_UID,\n name: 'modelId',\n type: FieldType.TEXT,\n label: 'Model id',\n description: 'Absent falls back to the single status=\"default\" agent.',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_CHAT_INPUT_AGENT_NAME_UID,\n name: 'agentName',\n type: FieldType.TEXT,\n label: 'Agent name',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_CHAT_INPUT_GORGIAS_TICKET_ID_UID,\n name: 'gorgiasTicketId',\n type: FieldType.TEXT,\n label: 'Gorgias ticket id',\n isNullable: true,\n defaultValue: null,\n },\n ],\n };\n}\n\nexport function createExtChatHandler(): AppHandler {\n return (ctx, input) => extChatHandler(ctx as SupportKitHandlerContext, (input as ExtChatInput) ?? {});\n}\n\nexport async function extChatHandler(ctx: SupportKitHandlerContext, input: ExtChatInput): Promise<ExtChatResult | ProbeClaim | null> {\n const envelope = readSupportExtensionEnvelope(ctx);\n if (envelope.phase === 'probe') return probeChatOwnership(ctx, input.modelId ?? null);\n return executeChat(ctx, envelope.userId, input);\n}\n\nasync function probeChatOwnership(ctx: SupportKitHandlerContext, modelId: string | null): Promise<ProbeClaim | null> {\n if (modelId) return ownsAgent(ctx, modelId);\n const page = await ctx.api.list('agent', { filter: DEFAULT_AGENT_FILTER, limit: 1 });\n return page.items.length > 0 ? { claimed: true } : null;\n}\n\nasync function executeChat(ctx: SupportKitHandlerContext, userId: string, input: ExtChatInput): Promise<ExtChatResult> {\n const contextMessages = await resolveMessages(ctx, input);\n const agent = await resolveAgent(ctx, input.modelId ?? null);\n\n const promptPort = createPlatformPromptPort(ctx.api, (message) => ctx.logger.warn(message));\n // H5 (T25 review): draftPromptRefFor's \"no agent configured\" sentinel is\n // scoped by promptPrefix — but createExtChatHandler() takes no\n // SupportKitFunctionConfig at all (unlike every other ext-* handler that\n // needs one, none of the six do), so this call site has no promptPrefix\n // to pass. `{ promptPrefix: '' }` keeps today's behaviour for\n // experience-client unchanged; a pro-sante (or later) audience installed\n // with a non-empty prefix still 403s on this specific path exactly as it\n // already did before this fix. Threading config through the S6 gateway's\n // internal ext-chat invocation is a wider change than this finding's\n // fix — flagged, not silently masked.\n const promptRef = draftPromptRefFor(agent, { promptPrefix: '' });\n const resolvedPrompt = await promptPort.resolve(promptRef);\n const systemContent = applySignature(resolvedPrompt.text, input.agentName ?? undefined);\n const chatMessages: WireChatMessage[] = systemContent\n ? [{ role: 'system', content: systemContent }, ...contextMessages]\n : contextMessages;\n\n const result = await ctx.api.llm.complete({\n messages: chatMessages,\n // H3/I16: the resolved Langfuse prompt's own model config WINS over the\n // agent's fallback modelId — every ported graph node applies this same\n // rule (`draft.ts`, `triage.ts`, …); this was the one `PromptPort\n // .resolve` consumer in the repo that dropped it.\n options: { model: resolvedPrompt.config?.model ?? agent.modelId },\n // Link-only (D-LF follow-up, option (b)): this function already resolved\n // its own prompt two lines above via `PromptPort` — `resolve: false`\n // links the completion to it in Langfuse WITHOUT re-triggering the\n // platform's own resolution (no `manifest.prompts[]` gate, no\n // system-message replacement of the `applySignature`-signed message just\n // composed above). `label` is the REAL resolved label — `promptRef\n // .label`, i.e. `agent.promptLabel ?? 'production'`\n // (`functions/records.ts`'s `draftPromptRefFor`) — not a hardcoded\n // 'production', so a staging-labelled agent's traces say so instead of\n // silently attributing to production.\n promptRef: {\n name: resolvedPrompt.name,\n version: resolvedPrompt.version,\n label: promptRef.label,\n resolve: false,\n },\n trace: {\n sessionId: input.gorgiasTicketId ?? undefined,\n metadata: {\n // L2: the agent's own identity — `ctx.api.llm.complete`'s `trace`\n // has no dedicated `userId` field (unlike `graph/ports.ts`'s\n // `CompletionRequest`), only `metadata`. The prompt identity itself\n // no longer needs to travel here — `promptRef` above carries it.\n userId,\n model: agent.modelId,\n ...(input.gorgiasTicketId ? { ticketId: input.gorgiasTicketId } : {}),\n },\n },\n });\n\n const answer = result.text?.trim();\n if (!answer) throw new ctx.NonRetriableError('Provider returned an empty response');\n\n return {\n answer,\n modelId: agent.id,\n langfuse_trace_id: result.traceId ?? null,\n langfuse_observation_id: result.observationId ?? null,\n prompt_name: resolvedPrompt.name,\n prompt_version: resolvedPrompt.version,\n };\n}\n\nasync function resolveMessages(ctx: SupportKitHandlerContext, input: ExtChatInput): Promise<WireChatMessage[]> {\n if (input.gorgiasTicketId) {\n // L10: the exported `RawTicketContext` shape (`adapters/index.ts`),\n // not a second inline redeclaration of it. Note the divergence this\n // reader and `toConversation` (`adapters/conversation-mapping.ts`) have\n // on the SAME action's output: this one admits `system` turns\n // (matching the legacy chat route), `toConversation` filters them out —\n // both correct for what each one feeds, neither aware of the other.\n const raw = (await runBuildTicketContext(ctx, input.gorgiasTicketId)) as RawTicketContext;\n // M1: the legacy's shared `messages.length === 0` 400-guard covered\n // BOTH the `input.messages` path and this `gorgiasTicketId` one — this\n // port only guarded the former. A ticket with nothing extractable\n // (internal notes only, an automated-sender thread) must 400 instantly,\n // not pay for an LLM call with a system message and no conversation.\n if (!Array.isArray(raw.messages) || raw.messages.length === 0) {\n throw new ctx.NonRetriableError(`No usable messages extracted for Gorgias ticket ${input.gorgiasTicketId}`);\n }\n return raw.messages.map((m) => toWireChatMessage(m));\n }\n if (Array.isArray(input.messages) && input.messages.length > 0) {\n return input.messages.map((m) => toWireChatMessage(m));\n }\n throw new ctx.NonRetriableError('`messages` must be a non-empty array, or provide `gorgiasTicketId`');\n}\n\n/**\n * L1, PARTIAL — see this module's own doc for what is and is not achievable\n * here. Distinguishes the one genuinely non-retriable Gorgias failure (the\n * ticket does not exist) from everything else (misconfiguration, the\n * provider being down, a timeout) by DUCK-TYPING the error shape\n * `@apotech-os/gorgias-client`'s `ProviderHttpError` carries — `status`/\n * `name` on the caught value — rather than an `instanceof` check: this\n * package has no dependency on `gorgias-client` at all\n * (`dependency-allowlist.ts`; an app cannot import a platform-internal\n * client), so a structural check is the only kind available.\n */\nasync function runBuildTicketContext(ctx: SupportKitHandlerContext, ticketId: string): Promise<unknown> {\n try {\n return await ctx.api.integrations.run('gorgias', 'buildTicketContext', { ticketId });\n } catch (err) {\n if (isGorgiasNotFound(err)) {\n throw new ctx.NonRetriableError(`Gorgias ticket ${ticketId} not found`);\n }\n // Everything else (misconfigured connection, the provider down, a\n // timeout) is NOT retried by throwing `NonRetriableError` — unlike a\n // missing ticket, a transient Gorgias outage may well succeed on the\n // next call. This still surfaces as a generic 500 to the extension: see\n // this module's own doc for why 503/502 are unreachable from here.\n throw err;\n }\n}\n\nfunction isGorgiasNotFound(err: unknown): boolean {\n if (typeof err !== 'object' || err === null) return false;\n const { status } = err as { status?: unknown };\n return status === 404;\n}\n\nfunction toWireChatMessage(raw: { role?: unknown; content?: unknown }): WireChatMessage {\n const role = raw.role;\n if (role !== 'system' && role !== 'user' && role !== 'assistant') {\n throw new Error(`ext-chat: message role must be \"system\", \"user\" or \"assistant\", got ${JSON.stringify(role)}`);\n }\n return { role, content: typeof raw.content === 'string' ? raw.content : '' };\n}\n\nasync function resolveAgent(ctx: SupportKitHandlerContext, modelId: string | null): Promise<AgentRecord> {\n if (modelId) {\n const record = await getOptional(ctx, 'agent', modelId);\n if (!record) throw new ctx.NonRetriableError(`Model not found (id=${modelId})`);\n return toAgent(record);\n }\n const page = await ctx.api.list('agent', { filter: DEFAULT_AGENT_FILTER, limit: 1 });\n const record = page.items[0];\n if (!record) throw new ctx.NonRetriableError('No default model configured');\n return toAgent(record);\n}\n","/**\n * `ext-fast-response-check` (§5.2, §3.5 line 291) — `uiInvoke`, reserved,\n * always `phase: 'execute'`, fanned out to every accessible app (§S6: \"au\n * plus un hit attendu — premier hit servi, hits multiples loggés en\n * anomalie\" — that fan-out/first-hit policy is the GATEWAY's, not this\n * function's). Ports legacy `POST /api/fast-response/check`\n * (extension-overview backoffice/src/routes/api.ts:291) — the most\n * defect-prone of the six, ported rule for rule:\n *\n * 1. Look up the `generated-response` row for `ticket_id` with `status:\n * 'ready'`. None → `{available: false}`.\n * 2. TTL: `expiresAt < now` → flip `ready -> expired` (conditional on still\n * being `ready`, S5 `ifMatch`) and return `{available: false}`.\n * 3. Divergence, RECOMPUTED SERVER-SIDE — never from client-supplied\n * values: re-fetch the ticket via S1's `getRawTicket` action and take\n * the snapshot with the kit's own `snapshotConversation`\n * (`adapters/conversation-mapping.ts`, already the symmetric port of the\n * extension's `countableMessages`/divergence rule — reused, not\n * re-derived). Diverged (`currentCount > snappedCount`, or\n * `currentLastAt` present and newer than `snappedLastAt`/absent) → flip\n * `ready -> invalidated` and return `{available: false}`.\n * 4. Gorgias fetch failure, OR a successful-but-unusable payload (no\n * `ticket`, or a `ticket` with no messages — H1 hardening: otherwise\n * `snapshotConversation({})` reads as zero messages, which can only ever\n * look like NO divergence and would serve a stale draft) ⇒ FAIL-CLOSED:\n * `{available: false}`, the row is left `ready`, nothing is written — a\n * transient Gorgias outage must never look like \"the draft was\n * invalidated\".\n * 5. Hit: `servedCount++`, push `{user, at}` onto `servedTo` (capped at 500\n * entries — `servedCount` keeps incrementing past the cap, only the\n * array stops growing) via S5 `ifMatch: {servedCount: <value just read>}`\n * PLUS A RETRY: the read-modify-write of the `servedTo` JSON array is not\n * atomic, so a lost `ifMatch` race (two concurrent `/check` calls on the\n * same ready row) re-reads the row and retries with the fresh count —\n * UNLESS the re-read shows the row is no longer `ready` (another writer\n * genuinely moved it: an expiry/divergence flip, or a send), in which\n * case this is a real miss, exactly the legacy's `race_lost` branch —\n * see `serveHit` below, bounded at `MAX_SERVE_ATTEMPTS`. CASing on\n * `status` here (H2 hardening) would be a no-op guard: this write never\n * changes `status`, so two concurrent hits would both pass an\n * `ifMatch: {status: 'ready'}` unconditionally and one serve record\n * would silently vanish — `servedCount` is the field that actually\n * discriminates concurrent writers.\n *\n * `followup_required` — DECISION (the brief asks for one, explicitly):\n * derived from the record's `verdict.verdict` field via the ported\n * `requiresFollowup` (legacy-faithful: `requiresFollowup(job\n * .evaluation_verdict)`), NOT read off a stored `followupRequired`\n * boolean. Checked before choosing: `records/generated-response.ts`\n * declares `followupRequired` with a `false` default, and grep across this\n * package shows exactly ONE writer — `triage-tick.ts` sets it `false` at\n * CREATION time — and no writer ever updates it once the real verdict is\n * known (`process-response.ts` persists `verdict` on the `ready` row but\n * never touches `followupRequired`). The stored field is therefore\n * effectively dead (always `false`); deriving from `verdict` is both\n * legacy-faithful and the only way to get a correct answer.\n *\n * `last_served_at` — the legacy also stamped this on every hit; the kit's\n * `generated-response` record (§3.4, frozen at T20) has no such field.\n * NOT silently dropped: nothing in this package reads it, and each\n * `servedTo[].at` entry already carries the same information (the most\n * recent entry IS the last-served timestamp) — so the cost is a query that\n * wants \"when was this last served\" needing to read the tail of `servedTo`\n * instead of one scalar field, not a loss of information.\n *\n * SETTINGS VALIDATION: deliberately NOT called. This function reads\n * `expiresAt` off the ROW itself — computed once at generation time from\n * `responseTtlMinutes`, already baked in — never a live settings read; none\n * of `validateSettings`'s three checks (`sourceViewId`, `nodes.triage`,\n * `senderEmail`) apply to serving an already-generated draft.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n */\nimport { AppApiError, type AppApiRecord, type AppHandler, FieldType, type FunctionDef } from '@apotech-os/app-kit';\nimport { snapshotConversation } from '../adapters/conversation-mapping';\nimport type { RawTicket } from '../guardrails';\nimport { isEvaluationVerdict, requiresFollowup } from '../domain';\nimport { isGeneratedResponseStatus, type GeneratedResponseStatus } from '../status/machine';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { transitionGeneratedResponse } from './generated-response-transition';\nimport { EXT_FAST_RESPONSE_CHECK_INPUT_TICKET_ID_UID } from './ids';\nimport { toDate } from './pipeline-state';\nimport { toAgent, toCategory, toGeneratedResponse, type GeneratedResponseRecord } from './records';\nimport { readSupportExtensionEnvelope } from './support-extension-envelope';\n\nconst SERVED_TO_CAP = 500;\nconst MAX_SERVE_ATTEMPTS = 3;\n\nexport interface ExtFastResponseCheckInput {\n ticket_id: string;\n}\n\nexport type ExtFastResponseCheckResult =\n | { available: false }\n | {\n available: true;\n response: string;\n category: { _id: string; name: string } | null;\n agent: { _id: string; name: string; model_id: string } | null;\n langfuse_trace_id: string | null;\n langfuse_observation_id: string | null;\n prompt_name: string | null;\n prompt_version: number | null;\n generated_at: string;\n followup_required: boolean;\n };\n\nexport function buildExtFastResponseCheckFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-fast-response-check'),\n name: 'ext-fast-response-check',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: EXT_FAST_RESPONSE_CHECK_INPUT_TICKET_ID_UID,\n name: 'ticket_id',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createExtFastResponseCheckHandler(): AppHandler {\n return (ctx, input) => extFastResponseCheckHandler(ctx as SupportKitHandlerContext, input as unknown as ExtFastResponseCheckInput);\n}\n\nconst NOT_AVAILABLE: ExtFastResponseCheckResult = { available: false };\n\nexport async function extFastResponseCheckHandler(\n ctx: SupportKitHandlerContext,\n input: ExtFastResponseCheckInput,\n): Promise<ExtFastResponseCheckResult> {\n const ticketId = typeof input?.ticket_id === 'string' ? input.ticket_id.trim() : '';\n if (!ticketId) throw new ctx.NonRetriableError('`ticket_id` must be a non-empty string');\n\n const page = await ctx.api.list('generated-response', { filter: { ticketId, status: 'ready' }, limit: 1 });\n const row = page.items[0];\n if (!row) {\n logReason(ctx, ticketId, 'no_ready_job');\n return NOT_AVAILABLE;\n }\n const generatedResponse = toGeneratedResponse(row);\n\n const now = new Date();\n\n const expiresAt = toDate(generatedResponse.expiresAt);\n if (expiresAt && expiresAt.getTime() < now.getTime()) {\n logReason(ctx, ticketId, 'expired');\n await flipStatus(ctx, row.id, ticketId, 'expired');\n return NOT_AVAILABLE;\n }\n\n let rawTicket: RawTicket;\n try {\n const fetched = (await ctx.api.integrations.run('gorgias', 'getRawTicket', { ticketId })) as { ticket?: RawTicket };\n // H1 hardening: a successful-but-unusable payload (no `ticket`, or a\n // `ticket` with no messages) is indistinguishable from a fetch failure\n // for divergence purposes — `snapshotConversation({})` would read as\n // \"0 messages, no last-message date\", which can only ever look like\n // NO divergence and would serve a draft that may already be stale.\n // Fail-closed the same way rule 4 does for a thrown fetch error.\n if (!fetched.ticket || !fetched.ticket.messages || fetched.ticket.messages.length === 0) {\n logReason(ctx, ticketId, 'gorgias_fetch_failed', 'empty or missing ticket.messages');\n return NOT_AVAILABLE;\n }\n rawTicket = fetched.ticket;\n } catch (err) {\n // Fail-closed (rule 4): cannot validate the draft is still fresh, so it\n // is unavailable — but the row itself is left untouched.\n logReason(ctx, ticketId, 'gorgias_fetch_failed', err instanceof Error ? err.message : String(err));\n return NOT_AVAILABLE;\n }\n\n const divergence = checkDivergence(rawTicket, generatedResponse);\n if (divergence.diverged) {\n logReason(ctx, ticketId, `diverged[count(snap=${divergence.snappedCount},now=${divergence.count}),date(snap=${isoOrNull(divergence.snappedLastAt)},now=${isoOrNull(divergence.lastAt)})]`);\n await flipStatus(ctx, row.id, ticketId, 'invalidated');\n return NOT_AVAILABLE;\n }\n\n const envelope = readSupportExtensionEnvelope(ctx);\n // L11: an empty platform user id must fail the WRITE, not silently push\n // `servedTo: [{user: '', at}]` — an anonymous entry indistinguishable\n // from a legitimate serve. `readSupportExtensionEnvelope`'s own doc notes\n // this never happens through the real gateway; this is the last line of\n // defence against a malformed envelope masquerading as a real one.\n if (!envelope.userId) {\n throw new ctx.NonRetriableError('ext-fast-response-check: missing platform user id in the invocation envelope');\n }\n const served = await serveHit(ctx, row, envelope.userId, now);\n if (!served) {\n logReason(ctx, ticketId, 'race_lost');\n return NOT_AVAILABLE;\n }\n const servedResponse = toGeneratedResponse(served);\n logReason(ctx, ticketId, `hit served_count=${servedResponse.servedCount}`);\n if (servedResponse.servedCount > SERVED_TO_CAP) {\n ctx.logger.warn(`ext-fast-response-check: ticket=${ticketId} servedTo capped at ${SERVED_TO_CAP} entries (served_count=${servedResponse.servedCount})`);\n }\n\n return buildAvailableResponse(ctx, servedResponse);\n}\n\nfunction logReason(ctx: SupportKitHandlerContext, ticketId: string, reason: string, detail?: string): void {\n const suffix = detail ? ` detail=${JSON.stringify(detail)}` : '';\n ctx.logger.info(`ext-fast-response-check: ticket=${ticketId} reason=${reason}${suffix}`);\n}\n\nfunction isoOrNull(date: Date | null): string {\n return date ? date.toISOString() : 'null';\n}\n\ninterface DivergenceCheck {\n diverged: boolean;\n count: number;\n lastAt: Date | null;\n snappedCount: number;\n snappedLastAt: Date | null;\n}\n\n/**\n * L3: a SECOND `hasDiverged`, deliberately not unified with `graph/nodes\n * /act.ts`'s own — that one uses `!==` on both count and timestamp (any\n * change, either direction, since a re-send must never fire on a run that\n * has already drifted in EITHER direction); this one is faithful to the\n * legacy's own `POST /api/fast-response/check` rule (`count >`, \"strictly\n * newer\") — a same-or-earlier snapshot is not a divergence for the purpose\n * of serving an already-generated draft. `handle-approval.ts:142-143` reads\n * the same two stored fields by hand a third time, for the same reason\n * `act`'s check does (I8's re-read).\n */\nfunction checkDivergence(rawTicket: RawTicket, generatedResponse: GeneratedResponseRecord): DivergenceCheck {\n const snapshot = snapshotConversation(rawTicket);\n const snappedCount = generatedResponse.generatedMessageCount;\n const snappedLastAt = toDate(generatedResponse.generatedLastMessageAt);\n\n const divergedByCount = snapshot.count > snappedCount;\n const divergedByDate = !!snapshot.lastAt && (!snappedLastAt || snapshot.lastAt.getTime() > snappedLastAt.getTime());\n return { diverged: divergedByCount || divergedByDate, count: snapshot.count, lastAt: snapshot.lastAt, snappedCount, snappedLastAt };\n}\n\n/** `ready -> expired|invalidated`, tolerating a lost race (someone else already moved the row) — the outcome (`{available:false}`) is the same either way. */\nasync function flipStatus(\n ctx: SupportKitHandlerContext,\n id: string,\n ticketId: string,\n status: Extract<GeneratedResponseStatus, 'expired' | 'invalidated'>,\n): Promise<void> {\n await transitionGeneratedResponse(ctx.api, { id, ticketId, from: 'ready', to: status });\n}\n\n/**\n * Rule 5's retry loop (see this module's own doc). Re-reads and retries on\n * a lost `ifMatch` race PROVIDED the row is still `ready` after the\n * re-read; a row that moved off `ready` — INCLUDING one an admin deleted\n * outright (L4: `getOptional`, not `api.get`, so a 404 here reads as the\n * same ordinary miss the legacy's `race_lost` names it, not an app failure\n * `fanOutSettled` would log as an anomaly) — is a genuine miss, returned as\n * `null` without a further retry.\n */\nasync function serveHit(ctx: SupportKitHandlerContext, row: AppApiRecord, userId: string, now: Date): Promise<AppApiRecord | null> {\n let current = row;\n for (let attempt = 0; attempt < MAX_SERVE_ATTEMPTS; attempt++) {\n const currentData = toGeneratedResponse(current);\n const { servedCount, servedTo } = currentData;\n const nextServedTo = servedCount < SERVED_TO_CAP ? [...servedTo, { user: userId, at: now.toISOString() }] : servedTo;\n\n try {\n // H2: CAS on the field this write actually changes (`servedCount`),\n // not `status` — the hit path never moves `status` off `ready`, so an\n // `ifMatch: {status: 'ready'}` guard would let two concurrent hits\n // both pass unconditionally (see this function's own doc, rule 5).\n return await ctx.api.update(\n 'generated-response',\n current.id,\n { servedCount: servedCount + 1, servedTo: nextServedTo },\n { ifMatch: { servedCount } },\n );\n } catch (err) {\n if (!(err instanceof AppApiError) || err.status !== 409) throw err;\n const fresh = await getOptional(ctx, 'generated-response', current.id);\n // L7: the untrusted-JSONB boundary — `isGeneratedResponseStatus`,\n // same guard `isEvaluationVerdict` applies to `verdict` a few lines\n // below, instead of a raw string compare against an unknown value.\n const freshStatus = fresh ? (fresh.data as Record<string, unknown>).status : undefined;\n if (!fresh || !isGeneratedResponseStatus(freshStatus) || freshStatus !== 'ready') return null;\n current = fresh;\n }\n }\n return null;\n}\n\nasync function buildAvailableResponse(ctx: SupportKitHandlerContext, generatedResponse: GeneratedResponseRecord): Promise<ExtFastResponseCheckResult> {\n const category = await resolveCategoryRef(ctx, generatedResponse.categoryId);\n const agent = await resolveAgentRef(ctx, generatedResponse.agentId);\n // L5: the legacy returned `served.generated_at` verbatim — no fabricated\n // \"now\" fallback. The real record declares `generatedAt` `isNullable:\n // false` (`records/generated-response.ts`), so a row reaching this point\n // without one is corrupted data, not a case to paper over: the extension\n // uses this field to show draft freshness, and silently reporting \"just\n // now\" on a possibly-stale draft is worse than a loud failure.\n const generatedAt = toDate(generatedResponse.generatedAt);\n if (!generatedAt) {\n throw new ctx.NonRetriableError(`generated-response ${generatedResponse.id} is ready but has no generatedAt`);\n }\n const verdictValue = isEvaluationVerdict(generatedResponse.verdict?.verdict) ? generatedResponse.verdict.verdict : null;\n\n return {\n available: true,\n response: generatedResponse.responseText ?? '',\n category,\n agent,\n langfuse_trace_id: generatedResponse.langfuseTraceId,\n langfuse_observation_id: generatedResponse.langfuseObservationId,\n prompt_name: generatedResponse.promptName,\n prompt_version: generatedResponse.promptVersion,\n generated_at: generatedAt.toISOString(),\n followup_required: requiresFollowup(verdictValue),\n };\n}\n\nasync function resolveCategoryRef(ctx: SupportKitHandlerContext, categoryId: string | null): Promise<{ _id: string; name: string } | null> {\n if (!categoryId) return null;\n const record = await getOptional(ctx, 'category', categoryId);\n if (!record) return null;\n const category = toCategory(record);\n return { _id: category.id, name: category.name };\n}\n\nasync function resolveAgentRef(\n ctx: SupportKitHandlerContext,\n agentId: string | null,\n): Promise<{ _id: string; name: string; model_id: string } | null> {\n if (!agentId) return null;\n const record = await getOptional(ctx, 'agent', agentId);\n if (!record) return null;\n const agent = toAgent(record);\n return { _id: agent.id, name: agent.name, model_id: agent.modelId };\n}\n","/**\n * `ext-evaluation` (§5.2, §3.5 line 291) — `uiInvoke`, reserved, ownership-\n * routed (§S6). Ports legacy `POST /api/models/:id/evaluation`\n * (extension-overview backoffice/src/routes/api.ts:96). The gateway hands\n * this function `{...body, modelId}` (`SupportExtensionService.evaluation`\n * injects the URL's `:modelId` into the body itself), so `modelId` is\n * always present on `phase: 'execute'`.\n *\n * OWNERSHIP PROBE: `{modelId}`, `modelId` always a real value here (unlike\n * `ext-chat`, there is no \"absent modelId\" branch — the legacy route always\n * has one, from the URL). Claim iff this app owns an `agent` record with\n * that id — a read only, no write/LLM/Gorgias call.\n *\n * EXECUTE: `{satisfied, messages, ticket_url, langfuse_trace_id,\n * langfuse_observation_id, modelId}` → `201` (body ignored by the\n * extension, §5.2). `satisfied` must be a boolean (legacy 400s otherwise).\n * Writes an `evaluation` record with `agentId` = the resolved agent and\n * `supportUserKeyId` = the platform user id read off\n * `ctx.event.supportExtension` (§5.1: \"les records servedTo/évaluations\n * portent l'id utilisateur plateforme\").\n *\n * `ticketUrl` GAP (recorded, not silently routed around; L12 — DECISION\n * made explicitly, not deferred): the extension's request body treats\n * `ticket_url` as optional (legacy: `ticket_url ?? null`), but the T20\n * `evaluation` record (`records/evaluation.ts`) declares `ticketUrl` as\n * `isNullable: false` — no default, no null. Rather than reach back into a\n * frozen T20 record definition (out of this task's scope) or silently\n * attempt an `undefined`/`null` write that would fail the object's own\n * field validation, an absent/non-string `ticket_url` is persisted as an\n * empty string.\n * This is WORSE here than the same gap on `response-comparison.ticketUrl`:\n * `evaluation` has NO `ticketId` field at all (grep `records/evaluation\n * .ts` — `agentId`, `satisfied`, `messages`, `ticketUrl`, the two Langfuse\n * ids, `supportUserKeyId`; nothing else), so `ticketUrl` is this record's\n * ONLY link back to a ticket. `''` is indistinguishable from a genuinely\n * empty URL, and a later backfill has no way to tell \"never sent\" from\n * \"sent empty\". The correct fix is making the field nullable and writing\n * `null` — DECLINED here, deliberately, because it means extending a\n * record definition the spec freezes at T20 (§3.4), which is a call for\n * whoever owns that record, not a T24 function. Flagged for whoever owns\n * `records/evaluation.ts` next, with the concrete cost spelled out above\n * rather than left implicit.\n *\n * LANGFUSE SCORE: when `langfuse_trace_id` is a non-empty string, writes a\n * `user-feedback` BOOLEAN score (S4) with the legacy's deterministic id\n * `user-feedback-<traceId>` (idempotent — toggling 👍/👎 updates the same\n * score instead of creating duplicates). `comment` folds in what the\n * legacy's dataset-store `metadata` carried (`model`, `ticket_url`) — S4's\n * `ctx.api.langfuse.scores.create` has no generic `metadata` field on the\n * platform surface (`CreateLangfuseScoreInput`), only `comment`. The\n * platform user's NAME is not available off `ctx.event` (only the user\n * id), so the comment uses the id instead of the legacy's `req.user.name`.\n * Both deviations are platform-surface limits, not this function's choice.\n * The score write is wrapped and its failure SWALLOWED — legacy is\n * explicit that this block is non-fatal and the 201 is guaranteed.\n *\n * SETTINGS VALIDATION: deliberately NOT called — writing an evaluation and\n * an optional score touches none of `validateSettings`'s three checked\n * fields.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport {\n EXT_EVALUATION_INPUT_LANGFUSE_OBSERVATION_ID_UID,\n EXT_EVALUATION_INPUT_LANGFUSE_TRACE_ID_UID,\n EXT_EVALUATION_INPUT_MESSAGES_UID,\n EXT_EVALUATION_INPUT_MODEL_ID_UID,\n EXT_EVALUATION_INPUT_SATISFIED_UID,\n EXT_EVALUATION_INPUT_TICKET_URL_UID,\n} from './ids';\nimport { ownsAgent, type ProbeClaim } from './ownership-probe';\nimport { toAgent } from './records';\nimport { readSupportExtensionEnvelope } from './support-extension-envelope';\n\nexport interface ExtEvaluationInput {\n modelId: string;\n satisfied?: unknown;\n messages?: Array<{ role: string; content: string }> | null;\n ticket_url?: string | null;\n langfuse_trace_id?: string | null;\n langfuse_observation_id?: string | null;\n}\n\nexport interface ExtEvaluationResult {\n ok: true;\n id: string;\n}\n\nexport function buildExtEvaluationFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-evaluation'),\n name: 'ext-evaluation',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n { universalIdentifier: EXT_EVALUATION_INPUT_MODEL_ID_UID, name: 'modelId', type: FieldType.TEXT, label: 'Model id', isNullable: false },\n { universalIdentifier: EXT_EVALUATION_INPUT_SATISFIED_UID, name: 'satisfied', type: FieldType.BOOLEAN, label: 'Satisfied', isNullable: false },\n {\n universalIdentifier: EXT_EVALUATION_INPUT_MESSAGES_UID,\n name: 'messages',\n type: FieldType.JSON,\n label: 'Messages',\n description: '[{role, content}]',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_EVALUATION_INPUT_TICKET_URL_UID,\n name: 'ticket_url',\n type: FieldType.TEXT,\n label: 'Ticket URL',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_EVALUATION_INPUT_LANGFUSE_TRACE_ID_UID,\n name: 'langfuse_trace_id',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_EVALUATION_INPUT_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuse_observation_id',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n defaultValue: null,\n },\n ],\n };\n}\n\nexport function createExtEvaluationHandler(): AppHandler {\n return (ctx, input) => extEvaluationHandler(ctx as SupportKitHandlerContext, input as unknown as ExtEvaluationInput);\n}\n\nexport async function extEvaluationHandler(\n ctx: SupportKitHandlerContext,\n input: ExtEvaluationInput,\n): Promise<ExtEvaluationResult | ProbeClaim | null> {\n const envelope = readSupportExtensionEnvelope(ctx);\n if (envelope.phase === 'probe') return ownsAgent(ctx, input?.modelId ?? null);\n return executeEvaluation(ctx, envelope.userId, input);\n}\n\nasync function executeEvaluation(\n ctx: SupportKitHandlerContext,\n userId: string,\n input: ExtEvaluationInput,\n): Promise<ExtEvaluationResult> {\n if (typeof input.satisfied !== 'boolean') {\n throw new ctx.NonRetriableError('`satisfied` is a required boolean');\n }\n // L11: an empty platform user id must fail the WRITE — §5.1 requires this\n // record to carry it, and silently writing `supportUserKeyId: null`\n // drops that requirement instead of refusing.\n if (!userId) {\n throw new ctx.NonRetriableError('ext-evaluation: missing platform user id in the invocation envelope');\n }\n const modelId = input.modelId;\n if (!modelId) throw new ctx.NonRetriableError('modelId is required');\n const agentRecord = await getOptional(ctx, 'agent', modelId);\n if (!agentRecord) throw new ctx.NonRetriableError(`Model not found (id=${modelId})`);\n const agent = toAgent(agentRecord);\n\n const satisfied = input.satisfied;\n const messages = Array.isArray(input.messages) ? input.messages : [];\n // See this module's doc — the record's `ticketUrl` is `isNullable: false`,\n // so an absent/non-string value is persisted as an empty string, not null.\n const ticketUrl = typeof input.ticket_url === 'string' ? input.ticket_url : '';\n const traceId = typeof input.langfuse_trace_id === 'string' && input.langfuse_trace_id.length > 0 ? input.langfuse_trace_id : null;\n const observationId =\n typeof input.langfuse_observation_id === 'string' && input.langfuse_observation_id.length > 0\n ? input.langfuse_observation_id\n : undefined;\n\n const created = await ctx.api.create('evaluation', {\n agentId: agent.id,\n satisfied,\n messages,\n ticketUrl,\n langfuseTraceId: traceId,\n langfuseObservationId: observationId ?? null,\n // Non-empty: guarded above (L11).\n supportUserKeyId: userId,\n });\n\n if (traceId) {\n try {\n await ctx.api.langfuse.scores.create({\n id: `user-feedback-${traceId}`,\n traceId,\n observationId,\n name: 'user-feedback',\n value: satisfied,\n dataType: 'BOOLEAN',\n comment: `Thumbs ${satisfied ? 'up' : 'down'} from ${userId || 'agent'} (model: ${agent.name}, ticket_url: ${ticketUrl || 'none'})`,\n });\n } catch (err) {\n // Non-fatal — legacy is explicit that the 201 is guaranteed regardless.\n ctx.logger.warn(`ext-evaluation: user-feedback score write failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n return { ok: true, id: created.id };\n}\n","/**\n * `ext-response-comparison` (§5.2, §3.5 line 291) — `uiInvoke`, reserved,\n * ownership-routed (§S6). Ports legacy `POST /api/response-comparisons`\n * (extension-overview backoffice/src/routes/api.ts:404).\n *\n * The gateway already short-circuits `last_message_generated == null` to a\n * `204` BEFORE ever invoking any app, and maps a `null` return from this\n * function to `204` too (`SupportExtensionController.responseComparison`).\n * This handler keeps its OWN guard anyway (per this migration's explicit\n * instruction) — belt and braces, and it is exercised directly by this\n * file's own tests, which do not go through the gateway.\n *\n * OWNERSHIP PROBE (§S6): `model_config_id` non-empty → probe payload\n * `{model_config_id}`, claim iff this app owns that `agent` record.\n * Otherwise → probe payload `{ticket_id, ticket_url}` (§S6: \"sinon fan-out\n * sur la propriété du ticket (`triage-decision`)\") — claim iff this app has\n * a `triage-decision` row for that `ticket_id` (the ticket was triaged by\n * THIS app, i.e. it belongs to this audience). `ticket_url` plays no part\n * in the ownership check (the legacy never used it for anything but\n * display either); it only reaches the WRITE below.\n *\n * EXECUTE: `message_actual_sent` missing → 400-equivalent (legacy 400s);\n * `last_message_generated` null → the guard above. Otherwise writes a\n * `response-comparison` record (`generatedText`/`sentText`/`capturedAt`\n * plus the frozen body's other fields, and `diff` — `response-comparison-\n * diff.ts`'s `computeWordDiff`, \"computed at write time\" per §3.4), then\n * attempts the Langfuse capture.\n *\n * `ticketUrl` GAP (L12 — DECISION made explicitly, not deferred) — the SAME\n * one `ext-evaluation.ts` documents for `evaluation.ticketUrl`: the T20\n * `response-comparison` record declares `ticketUrl` `isNullable: false`,\n * but the extension's own contract treats it as optional. An absent/\n * non-string value is persisted as an empty string, not `null`. Unlike\n * `evaluation`, this record DOES have its own `ticketId` field, so `''`\n * here is not the only link back to a ticket — a strictly smaller gap.\n * Making `ticketUrl` nullable and writing `null` is still the correct fix;\n * DECLINED here for the same reason as `ext-evaluation.ts`: it means\n * extending a T20-frozen record definition (§3.4), a call for whoever owns\n * `records/response-comparison.ts`, not this function.\n *\n * LANGFUSE CAPTURE — gates, decided explicitly: legacy gated on THREE\n * conditions — `CAPTURE_CORRECTIONS_TO_LANGFUSE === 'true'` (an env flag),\n * `message_actual_sent !== last_message_generated` (`textChanged`), and a\n * non-empty trace id. The kit has NO env access (§3.1) and the migration\n * spec §5.2 does not mention this flag at all, so it is DROPPED — the\n * remaining two gates stay: `textChanged` (an unedited reply is not a\n * correction and would poison the `cs-replies-corrections` dataset with\n * noise) and a non-empty trace id (nothing to link the correction back\n * to). Practical effect: this kit ALWAYS captures a genuine edit when a\n * trace id is present, where the legacy required an operator to also\n * enable a deployment flag — a deliberate widening, not an oversight.\n *\n * Dataset item id: the legacy's own deterministic\n * `<traceId>:<observationId>` (or `<traceId>` alone with no observation).\n * SCORE id: the legacy's `createCorrectionScore` had NONE (Langfuse\n * auto-assigns one on every call) — but S4's `ctx.api.langfuse.scores\n * .create` requires an `id` (`CreateLangfuseScoreInput.id`, non-optional).\n * This function reuses the SAME deterministic dataset-item id for the\n * score, which is required by the platform surface — NOT, despite the\n * tempting name, a general idempotency guarantee (H5/L14 correction of an\n * earlier overclaim in this doc):\n * - Langfuse keys a score on `(id, name, toDate(timestamp))`, and\n * `POST /api/public/scores` has no caller-supplied timestamp — a retry\n * that crosses a UTC day boundary from the original call creates a\n * SECOND score under the same id (`AppLangfuseService.createScore`'s\n * own doc, `apps/api/src/platform-data/app-langfuse.service.ts`).\n * - Two DIFFERENT edits on the same trace within the same day reuse this\n * same id and the SECOND CORRECTION score OVERWRITES the first — the\n * legacy minted a distinct score object per edit, so this is a real\n * narrowing, not a wash.\n * Same for the dataset item: a deterministic id genuinely IS a concurrency\n * safety net for the CONCURRENT case (two callers racing on the identical\n * id — Langfuse upserts by id, so the race has a defined winner instead of\n * two rows). What it is NOT is protection for the SEQUENTIAL case: reusing\n * that same deterministic id also means a SECOND, LATER correction on the\n * same generation (an agent edits and\n * sends, then the extension re-posts the same generation on a retry, or a\n * client retries after a lost 201) silently REPLACES `expectedOutput` with\n * the newer edit — last-write-wins, not accumulated history. The legacy\n * guarded exactly this (api.ts:490-497: skip the write when a\n * `ResponseComparison` with this `langfuse_observation_id` already has a\n * `dataset_item_created_at`); this port has no such field to guard on (the\n * T20-frozen `response-comparison` record declares none) and the guard was\n * dropped, not ported. DECIDED, not silently accepted: adding\n * `datasetItemCreatedAt` would mean extending a T20-frozen record\n * definition, out of this task's scope — documenting the real behaviour\n * here (drift toward the latest edit, not a hard guarantee) is the\n * alternative the review offered, and is what this paragraph now does.\n *\n * SCORE VALUE LENGTH — UNVERIFIED, flagged rather than guessed: `value:\n * JSON.stringify(expectedOutput)` embeds the full sent reply. If Langfuse\n * caps score values at some length (a commonly-cited limit for certain\n * value/comment fields is 500 characters, but this could not be confirmed\n * from code in this repo), a real support reply could exceed it. The write\n * is swallowed non-fatally below, so an over-length value would 400 here\n * silently — the feature would look like it works while writing nothing.\n * Treat this as a pre-ship manual probe (write a >500-char correction\n * against a real/staging Langfuse project and confirm the score lands),\n * not a guarantee this doc makes.\n *\n * `traced_input` — read defensively off the raw payload for the dataset\n * item's `input`, falling back to `conversation_messages` when absent\n * (legacy's own fallback rule) — NOT part of §5.2's frozen field table, so\n * it is not declared in this function's `input` FieldDef[] (an\n * undeclared/extra key reaches the handler unstripped; see\n * `app-input-validation.ts`'s zod-strip behaviour), but the extension may\n * still send it and its value should not be silently discarded when it\n * does.\n *\n * Both Langfuse writes (dataset item, score) are wrapped and their failure\n * SWALLOWED — legacy is explicit that this block is non-fatal.\n *\n * SETTINGS VALIDATION: deliberately NOT called — none of `validateSettings`'s\n * three checked fields apply to writing a comparison/capturing a\n * correction.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport {\n EXT_RESPONSE_COMPARISON_INPUT_CONVERSATION_MESSAGES_UID,\n EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_OBSERVATION_ID_UID,\n EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_TRACE_ID_UID,\n EXT_RESPONSE_COMPARISON_INPUT_LAST_MESSAGE_GENERATED_UID,\n EXT_RESPONSE_COMPARISON_INPUT_MESSAGE_ACTUAL_SENT_UID,\n EXT_RESPONSE_COMPARISON_INPUT_MODEL_CONFIG_ID_UID,\n EXT_RESPONSE_COMPARISON_INPUT_PROMPT_NAME_UID,\n EXT_RESPONSE_COMPARISON_INPUT_PROMPT_VERSION_UID,\n EXT_RESPONSE_COMPARISON_INPUT_TICKET_ID_UID,\n EXT_RESPONSE_COMPARISON_INPUT_TICKET_URL_UID,\n} from './ids';\nimport { ownsAgent, type ProbeClaim } from './ownership-probe';\nimport { computeWordDiff } from './response-comparison-diff';\nimport { readSupportExtensionEnvelope } from './support-extension-envelope';\n\nconst CORRECTIONS_DATASET = 'cs-replies-corrections';\n\nexport interface ExtResponseComparisonInput {\n last_message_generated?: string | null;\n message_actual_sent?: string;\n ticket_id?: string | null;\n ticket_url?: string | null;\n model_config_id?: string | null;\n langfuse_trace_id?: string | null;\n langfuse_observation_id?: string | null;\n prompt_name?: string | null;\n prompt_version?: number | null;\n conversation_messages?: unknown[] | null;\n /** Not part of §5.2's frozen field table — see this module's own doc. */\n traced_input?: unknown[] | null;\n}\n\nexport interface ExtResponseComparisonResult {\n ok: true;\n id: string;\n}\n\nexport function buildExtResponseComparisonFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-response-comparison'),\n name: 'ext-response-comparison',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_LAST_MESSAGE_GENERATED_UID,\n name: 'last_message_generated',\n type: FieldType.TEXT,\n label: 'Last message generated',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_MESSAGE_ACTUAL_SENT_UID,\n name: 'message_actual_sent',\n type: FieldType.TEXT,\n label: 'Message actually sent',\n isNullable: false,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_TICKET_ID_UID,\n name: 'ticket_id',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_TICKET_URL_UID,\n name: 'ticket_url',\n type: FieldType.TEXT,\n label: 'Ticket URL',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_MODEL_CONFIG_ID_UID,\n name: 'model_config_id',\n type: FieldType.TEXT,\n label: 'Model config id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_TRACE_ID_UID,\n name: 'langfuse_trace_id',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuse_observation_id',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_PROMPT_NAME_UID,\n name: 'prompt_name',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_PROMPT_VERSION_UID,\n name: 'prompt_version',\n type: FieldType.NUMBER,\n label: 'Prompt version',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_CONVERSATION_MESSAGES_UID,\n name: 'conversation_messages',\n type: FieldType.JSON,\n label: 'Conversation messages',\n description: '[{role, content}]',\n isNullable: true,\n defaultValue: null,\n },\n ],\n };\n}\n\nexport function createExtResponseComparisonHandler(): AppHandler {\n return (ctx, input) => extResponseComparisonHandler(ctx as SupportKitHandlerContext, (input as ExtResponseComparisonInput) ?? {});\n}\n\nexport async function extResponseComparisonHandler(\n ctx: SupportKitHandlerContext,\n input: ExtResponseComparisonInput,\n): Promise<ExtResponseComparisonResult | ProbeClaim | null> {\n const envelope = readSupportExtensionEnvelope(ctx);\n if (envelope.phase === 'probe') return probeResponseComparisonOwnership(ctx, input);\n return executeResponseComparison(ctx, input);\n}\n\nasync function probeResponseComparisonOwnership(\n ctx: SupportKitHandlerContext,\n input: ExtResponseComparisonInput,\n): Promise<ProbeClaim | null> {\n const modelConfigId = nonEmptyString(input.model_config_id);\n if (modelConfigId) {\n const claim = await ownsAgent(ctx, modelConfigId);\n if (claim) return claim;\n // M3: a dangling model_config_id (the agent was archived/deleted since\n // the draft that produced this correction) used to disclaim outright —\n // 204, the correction silently lost, with nothing to distinguish \"no\n // owner\" from \"we lost it\". Fall through to ticket ownership instead of\n // returning null immediately: the ticket itself still routes to the app\n // that triaged it, which is the better answer than losing the human\n // correction the whole cs-replies-corrections loop is built on.\n }\n\n const ticketId = nonEmptyString(input.ticket_id);\n if (!ticketId) return null;\n const page = await ctx.api.list('triage-decision', { filter: { ticketId }, limit: 1 });\n return page.items.length > 0 ? { claimed: true } : null;\n}\n\nasync function executeResponseComparison(\n ctx: SupportKitHandlerContext,\n input: ExtResponseComparisonInput,\n): Promise<ExtResponseComparisonResult | null> {\n if (!input.message_actual_sent) {\n throw new ctx.NonRetriableError('message_actual_sent is required');\n }\n if (!input.last_message_generated) {\n // M2: falsy, not `== null` — legacy tests `if (!last_message_generated)\n // return 204`, so an empty string must 204 too. `== null` let `''`\n // through and wrote a response-comparison with generatedText: '', a\n // trivially 100%-insert diff, and (with a trace id) a dataset item +\n // CORRECTION score teaching cs-replies-corrections that the model wrote\n // nothing and the human wrote the whole reply — dataset poisoning.\n return null; // -> 204, no write (own guard — see this module's doc)\n }\n\n const generatedText = input.last_message_generated;\n const sentText = input.message_actual_sent;\n const ticketId = nonEmptyString(input.ticket_id);\n // See this module's doc — the record's `ticketUrl` is `isNullable: false`.\n const ticketUrl = typeof input.ticket_url === 'string' ? input.ticket_url : '';\n const modelConfigId = nonEmptyString(input.model_config_id);\n const traceId = nonEmptyString(input.langfuse_trace_id);\n const observationId = nonEmptyString(input.langfuse_observation_id) ?? undefined;\n const promptName = typeof input.prompt_name === 'string' ? input.prompt_name : null;\n const promptVersion = typeof input.prompt_version === 'number' ? input.prompt_version : null;\n const conversationMessages = Array.isArray(input.conversation_messages) ? input.conversation_messages : [];\n\n const created = await ctx.api.create('response-comparison', {\n generatedText,\n sentText,\n capturedAt: new Date().toISOString(),\n ticketId,\n ticketUrl,\n agentId: modelConfigId,\n langfuseTraceId: traceId,\n langfuseObservationId: observationId ?? null,\n promptName,\n promptVersion,\n conversationMessages,\n diff: computeWordDiff(generatedText, sentText),\n });\n\n await captureCorrectionToLangfuse(ctx, {\n generatedText,\n sentText,\n ticketId,\n traceId,\n observationId,\n promptName,\n promptVersion,\n conversationMessages,\n tracedInput: Array.isArray(input.traced_input) ? input.traced_input : null,\n });\n\n return { ok: true, id: created.id };\n}\n\ninterface CorrectionCaptureParams {\n generatedText: string;\n sentText: string;\n ticketId: string | null;\n traceId: string | null;\n observationId: string | undefined;\n promptName: string | null;\n promptVersion: number | null;\n conversationMessages: unknown[];\n tracedInput: unknown[] | null;\n}\n\nasync function captureCorrectionToLangfuse(ctx: SupportKitHandlerContext, params: CorrectionCaptureParams): Promise<void> {\n const textChanged = params.sentText !== params.generatedText;\n if (!textChanged || !params.traceId) return;\n\n const itemId = params.observationId ? `${params.traceId}:${params.observationId}` : params.traceId;\n const expectedOutput = { role: 'assistant', content: params.sentText, refusal: null, annotations: [] as unknown[] };\n const datasetInput = params.tracedInput && params.tracedInput.length > 0 ? params.tracedInput : params.conversationMessages;\n\n try {\n await ctx.api.langfuse.datasets.createItem({\n dataset: CORRECTIONS_DATASET,\n id: itemId,\n input: datasetInput,\n expectedOutput,\n sourceTraceId: params.traceId,\n sourceObservationId: params.observationId,\n metadata: {\n prompt_name: params.promptName,\n prompt_version: params.promptVersion,\n ticket_id: params.ticketId,\n edited: true,\n },\n });\n } catch (err) {\n ctx.logger.warn(`ext-response-comparison: dataset item write failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n\n try {\n // M5: deliberately trace-level — NO `observationId`. Legacy's own\n // `createCorrectionScore` call passed none either (its doc labels this\n // \"Native trace-level CORRECTION score — renders as the 'Corrected\n // Output' on the trace itself\"); passing one here would move the panel\n // off the trace page. `CreateLangfuseScoreInput` has no generic\n // `metadata` field on the platform surface (only `comment`), so\n // prompt_name/prompt_version — the axis S7's quality loop reads\n // corrections along — fold into `comment` instead, the same way\n // `ext-evaluation.ts` folds its own score metadata.\n await ctx.api.langfuse.scores.create({\n id: itemId,\n traceId: params.traceId,\n name: 'output',\n value: JSON.stringify(expectedOutput),\n dataType: 'CORRECTION',\n comment: `Human correction from ticket ${params.ticketId ?? 'unknown'} (prompt: ${params.promptName ?? 'unknown'}, version: ${params.promptVersion ?? 'unknown'})`,\n });\n } catch (err) {\n ctx.logger.warn(`ext-response-comparison: correction score write failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nfunction nonEmptyString(value: unknown): string | null {\n return typeof value === 'string' && value.length > 0 ? value : null;\n}\n","/**\n * Page/settingsPage manifest fragments (spec §3.8) — the T26 counterpart of\n * `functions/config.ts`'s `FUNCTION_IDENTIFIER_KEYS`/`identifierFor`.\n *\n * Page `universalIdentifier`s come from `config.identifiers`, exactly like\n * function uids — NOT from the T25 `deriveUid`/`scopeRecordToApp` mechanism\n * `records/` uses. That mechanism exists because a RECORD's sub-ids (fields,\n * indexes) are numerous and entirely kit-owned, with no natural per-app\n * literal for a consuming app to author; deriving them from `(slug, a kit\n * constant)` is the only way to keep them both stable and disjoint across\n * apps. A page has exactly one id, no sub-ids, and `FUNCTION_IDENTIFIER_KEYS`\n * already established the pattern for exactly this shape: the CONSUMING\n * APP's own config supplies a literal, platform-wide-unique uuid per key —\n * the same discipline `docs/app-template/src/universal-identifiers.ts`\n * documents for every other manifest id an app authors directly.\n *\n * CORRECTION (T26 rework — the prior pass's own justification here was\n * false, and is fixed rather than just removed so the actual mechanism is\n * on record): `AppEntityType.PAGE` rows do land in the same `AppEntity`\n * table as records' OBJECT/FIELD/INDEX rows\n * (`apps/api/src/platform-data/app-entities.ts`), and\n * `AppEntity.universalIdentifier` IS `@unique` platform-wide\n * (`schema.prisma`) — but PAGE, like FUNCTION/VIEW/INDEX/NAV_ITEM, is\n * NAMESPACED before that constraint ever sees it: `buildEntities` computes\n * `deterministicUid('PAGE:<manifest uid>:<page uid>')`\n * (`app-entities.ts:172-175`), not the raw `page.universalIdentifier`\n * literal. Two apps publishing the IDENTICAL local page uid produce two\n * DIFFERENT `deterministicUid` hashes (their own manifest uids differ), so\n * they do not collide — a page id does NOT \"collide across apps exactly\n * like a record id would\". Only OBJECT (`app-entities.ts:84`) and FIELD\n * (`:101`, and `:205` for extension fields) write the raw literal straight\n * through — which is precisely why T25's `scopeRecordToApp` existed for\n * records and is NOT needed here.\n *\n * The mechanism below (config-supplied literal, mirroring\n * `FUNCTION_IDENTIFIER_KEYS`) is still the right choice — consistency with\n * the pattern T22/T23 already established for exactly this shape (one id,\n * no sub-ids, no natural per-app literal to derive from) — it is simply not\n * required by a collision risk that does not exist for this entity type.\n */\n\n/**\n * Stable keys `pageIdentifierFor` looks up `config.identifiers` by — the\n * four phase-2 pages (T26), the settingsPage (§3.8's SettingsPage row),\n * T27 part A's three phase-3 pages (`DashboardPage`, `TicketsPage`,\n * `CorrectionsPage`) and part B's `GraphCanvasPage`/`SharedPromptsPage`/\n * `TestPage` — §3.8's full page list, now complete.\n */\nexport const PAGE_IDENTIFIER_KEYS = [\n 'pipeline-page',\n 'agents-page',\n 'categories-page',\n 'escalations-page',\n 'settings-page',\n 'dashboard-page',\n 'tickets-page',\n 'corrections-page',\n 'graph-canvas-page',\n 'shared-prompts-page',\n 'test-page',\n] as const;\n\nexport type PageIdentifierKey = (typeof PAGE_IDENTIFIER_KEYS)[number];\n\nexport interface SupportKitPageConfig {\n /** Same map `functions/config.ts`'s `identifierFor` reads — one entry per `PAGE_IDENTIFIER_KEYS`, alongside the function ones. */\n identifiers: Record<string, string>;\n}\n\n/** Looks up `config.identifiers[key]`, throwing loudly on a missing entry — mirrors `functions/config.ts`'s `identifierFor` exactly. */\nexport function pageIdentifierFor(config: SupportKitPageConfig, key: PageIdentifierKey): string {\n const id = config.identifiers[key];\n if (!id) {\n throw new Error(\n `SupportPipelineConfig.identifiers is missing a universalIdentifier for \"${key}\" — every support-kit page needs a stable id.`,\n );\n }\n return id;\n}\n","/**\n * `buildSupportPipeline` (spec §3.2) — the single assembly point that turns\n * a consuming app's own config into every manifest fragment + handler this\n * kit provides. An audience app spreads the result into `defineApp({\n * manifest: {...baseManifest, ...kit-fragments}, handlers: kit.handlers })`.\n *\n * T25 is assembly, not invention: every fragment below is built from pieces\n * T20-T24 already shipped (`records/`, `functions/`, `settings/`,\n * `prompts/slots`) — this module's own job is wiring `config` through to\n * each of them consistently, plus `mergeRole`, the one piece with no prior\n * owner.\n */\nimport type {\n AppHandler,\n AppRole,\n AppSettings,\n FunctionDef,\n NavItem,\n PageDef,\n PromptDef,\n SettingsPage,\n} from '@apotech-os/app-kit';\nimport {\n FUNCTION_IDENTIFIER_KEYS,\n type FunctionIdentifierKey,\n type SupportKitFunctionConfig,\n} from './functions/config';\nimport {\n buildTriageTickFunctionDef,\n createTriageTickHandler,\n buildProcessResponseFunctionDef,\n createProcessResponseHandler,\n buildSweepFunctionDef,\n createSweepHandler,\n buildHandleApprovalFunctionDef,\n createHandleApprovalHandler,\n buildRunTriageNowFunctionDef,\n createRunTriageNowHandler,\n buildRunTriageBatchFunctionDef,\n createRunTriageBatchHandler,\n TRIAGE_RUN_REQUESTED_EVENT,\n buildPreviewTriageFunctionDef,\n createPreviewTriageHandler,\n buildGraphDryRunFunctionDef,\n createGraphDryRunHandler,\n buildTestAgentsFunctionDef,\n createTestAgentsHandler,\n buildSuggestPromptFunctionDef,\n createSuggestPromptHandler,\n buildRunDiffAnalysisFunctionDef,\n createRunDiffAnalysisHandler,\n buildListGorgiasViewsFunctionDef,\n createListGorgiasViewsHandler,\n buildCreateAgentFunctionDef,\n createCreateAgentHandler,\n buildSetDefaultAgentFunctionDef,\n createSetDefaultAgentHandler,\n buildCreateSharedPromptVersionFunctionDef,\n createCreateSharedPromptVersionHandler,\n buildSyncAgentPromptSnapshotFunctionDef,\n createSyncAgentPromptSnapshotHandler,\n buildExtModelsFunctionDef,\n createExtModelsHandler,\n buildExtCategoriesFunctionDef,\n createExtCategoriesHandler,\n buildExtChatFunctionDef,\n createExtChatHandler,\n buildExtFastResponseCheckFunctionDef,\n createExtFastResponseCheckHandler,\n buildExtEvaluationFunctionDef,\n createExtEvaluationHandler,\n buildExtResponseComparisonFunctionDef,\n createExtResponseComparisonHandler,\n} from './functions';\nimport { buildSupportKitRecords, targetRefFor, type RecordDef } from './records';\nimport { SUPPORT_KIT_SETTINGS_FIELDS } from './settings';\nimport type { PromptNameConfig } from './prompts/slots';\nimport { pageIdentifierFor } from './pages/manifest';\n\nexport interface SupportPipelineConfig extends SupportKitFunctionConfig {\n /** Human label shown in the platform's app picker, e.g. 'Expérience client'. */\n displayName: string;\n /**\n * §3.2's own sketch names this field, but has no consumer yet (L1, T25\n * review): `navigation` (this fragment's own `NavItem[]`) is always `[]`\n * today — T26/T27 own the kit's pages/nav (§3.8's phase-2/phase-3), and\n * with it, presumably, grouping those nav items under this section. A\n * caller may set it now for forward compatibility; nothing reads it yet.\n */\n navigationSection?: string;\n /**\n * §3.2's full `config.defaults` shape (`{channel?, prompts?}`), widening\n * `SupportKitFunctionConfig`'s own `defaults` (`{prompts?}` only) with\n * `channel` — `prompts`' shape is NOT restated here (L2, T25 review): it\n * is `PromptNameConfig['defaults']`'s own type, `prompts/slots.ts`'s\n * `PromptFallbackSlot`, referenced rather than copied, so this\n * declaration cannot silently narrow back to the wrong key set if that\n * one changes.\n *\n * `defaults.prompts` is wired to its real consumers: `buildPromptsTable`\n * (triage/escalate/evaluate/revise's `PromptRef.fallback`) and\n * `suggest-prompt`/`run-diff-analysis`'s own meta-prompt fallback.\n *\n * `defaults.channel` (DECISION 3, T25 — see the migration progress\n * journal's T25 entry) is accepted here for fidelity to the spec's own\n * sketch but has NO real consumer today: `settings/fields.ts` declares no\n * field named `channel`, and the nearest candidate, `whatsappMode`\n * (`escalate_only|draft_only|auto_reply`), has an incompatible value\n * domain from `'email'|'whatsapp'|'both'` — a mechanical seed would\n * corrupt it, not configure it. Wiring this for real means either adding\n * a settings field (§3.6 is T20-frozen; out of scope here) or picking an\n * arbitrary channel→whatsappMode mapping, both judgment calls beyond\n * assembly. Flagged for the spec owner, not routed around silently.\n */\n defaults?: PromptNameConfig['defaults'] & {\n channel?: 'email' | 'whatsapp' | 'both';\n };\n}\n\n/** `provider`/`action` pair — matches `AppManifest.actions[]`/`AppRole.actions[]`'s own shape (app-kit has no exported named type for it). */\nexport interface ActionRef {\n provider: string;\n action: string;\n}\n\nexport interface SupportPipelineFragments {\n records: RecordDef[];\n functions: FunctionDef[];\n /**\n * The app custom events the kit's own functions emit — spread into\n * `manifest.emits`. NOT optional in practice (B5): `run-triage-batch`\n * declares `trigger: {type:'event', name: TRIAGE_RUN_REQUESTED_EVENT}`,\n * and the platform refuses to sync a manifest whose event trigger names\n * an event the app does not declare\n * (`app-manifest-constraints.ts`'s `validateAppFunctionConstraints`), so\n * a consuming app that spreads `functions` must spread this too.\n */\n emits: string[];\n settings: AppSettings;\n prompts: PromptDef[];\n pages: PageDef[];\n navigation: NavItem[];\n /**\n * §3.8's SettingsPage row — the manifest's `settingsPage`, not a\n * `pages[]` entry (`AppManifestSchema`'s own refinements require it:\n * distinct `entry` from every page, no collision with the bundle the CLI\n * emits for a page `path`, distinct `universalIdentifier`). Not in §3.2's\n * own fragment sketch (T25's `pages`/`navigation` sketch predates T26) —\n * added here because a consuming app has no other way to spread it into\n * its manifest.\n */\n settingsPage: SettingsPage;\n actions: ActionRef[];\n /**\n * `'NO_ACCESS'` (H2, T25 review): with no `defaultRole`, the platform\n * grants every platform member `VIEWER` on install\n * (`app-lifecycle.service.ts:1211`) — a `pro-sante` clinician would read\n * `experience-client`'s `generated-response` rows (customer email bodies,\n * drafted replies) by default. Exposed as a named fragment, not baked\n * silently into a spread, so a consuming app can still override it\n * explicitly (`defaultRole: kit.defaultRole` in the common case, or a\n * different value if that app has a real reason to).\n */\n defaultRole: 'NO_ACCESS';\n handlers: Record<string, AppHandler>;\n mergeRole(role: AppRole): AppRole;\n /**\n * The `manifest.actions` counterpart of `mergeRole` (B2, T25 review):\n * `role.actions` must always be a subset of `manifest.actions`\n * (`validateActionCoupling`, enforced on every publish/sync) — before\n * this existed, a caller had to remember to fold the kit's own actions\n * into their manifest's `actions: [...]` by hand, on top of merging their\n * role separately, and a caller who forgot got a 422 at publish. Adds the\n * same kit action set `mergeRole` adds to `role.actions`, so\n * `actions: kit.mergeActions(ownActions)` paired with\n * `role: kit.mergeRole(ownRole)` keeps the two in lockstep by\n * construction.\n */\n mergeActions(actions: ActionRef[]): ActionRef[];\n}\n\n/**\n * The nine Gorgias connector actions the kit's adapters/functions actually\n * call — verified by grepping `ctx.api.integrations.run('gorgias', …)`\n * across `src/` (see `pipeline.spec.ts`'s own self-checking test, which\n * re-derives this set from the source tree so it cannot silently drift as\n * new call sites are added).\n */\nexport const SUPPORT_KIT_GORGIAS_ACTIONS = [\n 'applyTags',\n 'buildTicketContext',\n 'fetchTicketsFromView',\n 'getRawTicket',\n 'getTicketWithContext',\n 'listViews',\n 'postWhatsappNote',\n 'renameTicket',\n 'replyEmail',\n] as const;\n\n/** §3.2: `mergeRole` adds `capabilities: ['runs','inbox','approvals','prompts','langfuse']`. `'langfuse'` is load-bearing — `adapters/api.ts`'s `ctx.api.langfuse` 403s without it (T24). */\nexport const SUPPORT_KIT_CAPABILITIES = ['runs', 'inbox', 'approvals', 'prompts', 'langfuse'] as const;\n\n/**\n * The kit's whole action surface — `SUPPORT_KIT_GORGIAS_ACTIONS` plus\n * `llm.complete` — as `ActionRef`s. One derivation, reused by\n * `buildSupportPipeline`'s own `actions` fragment, `mergeRole`, and\n * `mergeActions` (M5, T25 review): before this constant existed, the same\n * `[...SUPPORT_KIT_GORGIAS_ACTIONS.map(...), {provider:'llm',action:'complete'}]`\n * expression was written out twice, free to drift apart silently.\n */\nexport const SUPPORT_KIT_ACTIONS: ActionRef[] = [\n ...SUPPORT_KIT_GORGIAS_ACTIONS.map((action) => ({ provider: 'gorgias', action })),\n { provider: 'llm', action: 'complete' },\n];\n\n/**\n * §3.2's `emits` fragment — one entry, the manual-triage hand-off\n * (`functions/run-triage-now.ts`'s own doc explains why that hand-off\n * exists at all).\n */\nexport const SUPPORT_KIT_EMITS: string[] = [TRIAGE_RUN_REQUESTED_EVENT];\n\nconst FUNCTION_ASSEMBLY: ReadonlyArray<{\n key: FunctionIdentifierKey;\n build: (config: SupportKitFunctionConfig) => FunctionDef;\n createHandler: (config: SupportKitFunctionConfig) => AppHandler;\n}> = [\n { key: 'triage-tick', build: buildTriageTickFunctionDef, createHandler: createTriageTickHandler },\n { key: 'process-response', build: buildProcessResponseFunctionDef, createHandler: createProcessResponseHandler },\n { key: 'sweep', build: buildSweepFunctionDef, createHandler: () => createSweepHandler() },\n { key: 'handle-approval', build: buildHandleApprovalFunctionDef, createHandler: createHandleApprovalHandler },\n { key: 'run-triage-now', build: buildRunTriageNowFunctionDef, createHandler: createRunTriageNowHandler },\n { key: 'run-triage-batch', build: buildRunTriageBatchFunctionDef, createHandler: createRunTriageBatchHandler },\n { key: 'preview-triage', build: buildPreviewTriageFunctionDef, createHandler: createPreviewTriageHandler },\n { key: 'graph-dry-run', build: buildGraphDryRunFunctionDef, createHandler: createGraphDryRunHandler },\n { key: 'test-agents', build: buildTestAgentsFunctionDef, createHandler: createTestAgentsHandler },\n { key: 'suggest-prompt', build: buildSuggestPromptFunctionDef, createHandler: createSuggestPromptHandler },\n { key: 'run-diff-analysis', build: buildRunDiffAnalysisFunctionDef, createHandler: createRunDiffAnalysisHandler },\n { key: 'list-gorgias-views', build: buildListGorgiasViewsFunctionDef, createHandler: createListGorgiasViewsHandler },\n { key: 'create-agent', build: buildCreateAgentFunctionDef, createHandler: () => createCreateAgentHandler() },\n {\n key: 'set-default-agent',\n build: buildSetDefaultAgentFunctionDef,\n createHandler: () => createSetDefaultAgentHandler(),\n },\n {\n key: 'create-shared-prompt-version',\n build: buildCreateSharedPromptVersionFunctionDef,\n createHandler: () => createCreateSharedPromptVersionHandler(),\n },\n {\n key: 'sync-agent-prompt-snapshot',\n build: buildSyncAgentPromptSnapshotFunctionDef,\n createHandler: () => createSyncAgentPromptSnapshotHandler(),\n },\n { key: 'ext-models', build: buildExtModelsFunctionDef, createHandler: () => createExtModelsHandler() },\n { key: 'ext-categories', build: buildExtCategoriesFunctionDef, createHandler: () => createExtCategoriesHandler() },\n { key: 'ext-chat', build: buildExtChatFunctionDef, createHandler: () => createExtChatHandler() },\n {\n key: 'ext-fast-response-check',\n build: buildExtFastResponseCheckFunctionDef,\n createHandler: () => createExtFastResponseCheckHandler(),\n },\n { key: 'ext-evaluation', build: buildExtEvaluationFunctionDef, createHandler: () => createExtEvaluationHandler() },\n {\n key: 'ext-response-comparison',\n build: buildExtResponseComparisonFunctionDef,\n createHandler: () => createExtResponseComparisonHandler(),\n },\n];\n\n// FUNCTION_ASSEMBLY must cover exactly FUNCTION_IDENTIFIER_KEYS — asserted\n// in pipeline.spec.ts, not re-asserted here (a compile-time array literal\n// has no length check to attach).\n\n/**\n * §3.7's `role.prompts` allowlist: the WHOLE Langfuse project, deliberately.\n *\n * Two narrowings preceded this one, and both failed the same way. First the\n * five derived slot names (`<prefix>triage`, …) — which stopped making sense\n * the day each graph step's prompt became an operator's choice\n * (`nodes.<step>.prompt`, picked on the SettingsPage from the catalogue THIS\n * allowlist filters): a choice restricted to the names that used to be\n * hardcoded is not a choice. Then `${promptPrefix}*` — bounded for a\n * prefixed audience, but `experience-client` passes `promptPrefix: ''`\n * (D-LF: one shared project, bare legacy names), so its glob was already the\n * whole project, while a `pro-sante/` install could not reach a single\n * prompt outside its own prefix.\n *\n * OWNER DECISION (09/09/2026): no limitation. An operator configuring a\n * pipeline must see every prompt of the project in the picker, whichever\n * audience the app serves. A prefix is a naming convention here, not a\n * tenancy boundary — under D-LF there is no per-app Langfuse namespace to\n * enforce one against, and `agent/*` had been unbounded from the start\n * anyway.\n *\n * WHAT THIS COSTS, stated rather than buried: `role.prompts` gates WRITES\n * too (`app-prompts.controller.ts`'s `requirePromptAllowed` on\n * `createVersion`/`promote`/`deleteVersion`). One audience's app token can\n * therefore read AND version-write another audience's prompts. That was\n * already true of every `agent/<id>` prompt (T25 review H1, accepted); it is\n * now true of all of them. The mitigation NOT taken remains a real per-app\n * Langfuse namespace, which contradicts D-LF and is a migration, not a flag.\n */\nfunction buildPromptsAllowlist(): string[] {\n return ['*'];\n}\n\nfunction dedupe<T>(items: readonly T[], keyOf: (item: T) => string): T[] {\n const seen = new Map<string, T>();\n for (const item of items) seen.set(keyOf(item), item);\n return [...seen.values()];\n}\n\nfunction mergeActionRefs(actions: readonly ActionRef[]): ActionRef[] {\n return dedupe([...actions, ...SUPPORT_KIT_ACTIONS], (a) => `${a.provider}::${a.action}`);\n}\n\n/**\n * `category`/`category-group` are the categorisation referential: every call\n * site in `src/` only ever `list`s or `get`s them (verified by grep, M2 in\n * the T25 review) — never `create`/`update`/`upsert`/`delete`. Granting\n * `writes` on them anyway lets the app's own token DELETE them, taking\n * triage offline for the whole audience.\n *\n * `agent` was in this list too until the T26 rework: `create-agent` and\n * `set-default-agent` (BLOCKER 3, BLOCKER 4) now `create`/`update` it from\n * inside a handler, via this same `ctx.api` — AgentsPage cannot assign a new\n * agent's `promptName` or maintain the \"at most one default agent\" invariant\n * from raw, unauthenticated-for-writes record PATCHes alone. `role.writes`\n * has no finer grain than \"create/update/delete\" as one bucket\n * (`SupportKitApi` itself exposes no `delete` method, but a raw app token\n * still could reach the generic records DELETE route with this grant) — this\n * IS a widened blast radius versus the prior read-only grant, accepted\n * because the alternative is an agent CRUD screen that cannot create or\n * promote an agent at all. Flagged for the spec owner, not routed around\n * silently.\n */\nconst KIT_READ_ONLY_OBJECT_KEYS = ['category', 'category-group'];\n\n/**\n * `evaluation`/`diff-analysis` are written (`create`/`upsert`) but never\n * `list`ed or `get`-ed anywhere in `src/` (M2) — the mirror over-grant of\n * `KIT_READ_ONLY_OBJECT_KEYS` above.\n */\nconst KIT_WRITE_ONLY_OBJECT_KEYS = ['evaluation', 'diff-analysis'];\n\nfunction buildMergeRole(config: SupportPipelineConfig): (role: AppRole) => AppRole {\n const kitRecords = buildSupportKitRecords(config.slug);\n const refsExcluding = (excludedObjectKeys: readonly string[]): string[] =>\n kitRecords\n .filter((record) => !excludedObjectKeys.includes(record.objectKey))\n .map((record) => targetRefFor(config.slug, record.objectKey));\n const kitReadRefs = refsExcluding(KIT_WRITE_ONLY_OBJECT_KEYS);\n const kitWriteRefs = refsExcluding(KIT_READ_ONLY_OBJECT_KEYS);\n const kitPrompts = buildPromptsAllowlist();\n\n return (role: AppRole): AppRole => ({\n ...role,\n reads: dedupe([...role.reads, ...kitReadRefs], (ref) => ref),\n writes: dedupe([...role.writes, ...kitWriteRefs], (ref) => ref),\n actions: mergeActionRefs(role.actions),\n capabilities: dedupe([...(role.capabilities ?? []), ...SUPPORT_KIT_CAPABILITIES], (c) => c),\n prompts: dedupe([...(role.prompts ?? []), ...kitPrompts], (p) => p),\n });\n}\n\n/**\n * §3.8's phase-2 pages (T26) plus T27 part A's three phase-3 pages\n * (`DashboardPage`, `TicketsPage`, `CorrectionsPage`) plus part B's\n * `GraphCanvasPage`/`SharedPromptsPage`/`TestPage` — §3.8's full page list,\n * now complete. `path` doubles as the CLI's bundle-derivation input\n * (`dist/ui/<path>.js`, `UI_ENTRY_REGEX`) and the component name exported\n * from `src/ui/index.ts` — kept in that 1:1 correspondence by `T26`'s own\n * build-then-verify step, not enforced by a type here (`PageDefSchema`\n * only constrains shape).\n */\nconst KIT_PAGES = [\n { key: 'dashboard-page', path: 'dashboard', title: 'Tableau de bord', icon: 'layout-dashboard' },\n { key: 'tickets-page', path: 'tickets', title: 'Demandes', icon: 'ticket' },\n { key: 'pipeline-page', path: 'pipeline', title: 'Pipeline', icon: 'inbox' },\n { key: 'agents-page', path: 'agents', title: 'Agents', icon: 'bot' },\n { key: 'categories-page', path: 'categories', title: 'Catégories', icon: 'tags' },\n { key: 'escalations-page', path: 'escalations', title: 'Escalades', icon: 'alert-triangle' },\n { key: 'corrections-page', path: 'corrections', title: 'Corrections', icon: 'git-compare' },\n { key: 'graph-canvas-page', path: 'graph-canvas', title: 'Graphe', icon: 'workflow' },\n { key: 'shared-prompts-page', path: 'shared-prompts', title: 'Prompts partagés', icon: 'library' },\n { key: 'test-page', path: 'test', title: 'Banc de test', icon: 'flask-conical' },\n] as const;\n\nfunction buildPages(config: SupportPipelineConfig): PageDef[] {\n return KIT_PAGES.map(({ key, path, title, icon }) => ({\n universalIdentifier: pageIdentifierFor(config, key),\n path,\n title,\n icon,\n entry: `dist/ui/${path}.js`,\n }));\n}\n\nfunction buildNavigation(config: SupportPipelineConfig): NavItem[] {\n return KIT_PAGES.map(({ path, title, icon }) => ({\n label: title,\n path,\n icon,\n ...(config.navigationSection !== undefined ? { section: config.navigationSection } : {}),\n }));\n}\n\nfunction buildSettingsPage(config: SupportPipelineConfig): SettingsPage {\n return {\n universalIdentifier: pageIdentifierFor(config, 'settings-page'),\n entry: 'dist/ui/settings.js',\n title: 'Paramètres',\n };\n}\n\nexport function buildSupportPipeline(config: SupportPipelineConfig): SupportPipelineFragments {\n const functions = FUNCTION_ASSEMBLY.map(({ build }) => build(config));\n const handlers: Record<string, AppHandler> = {};\n for (const { key, createHandler } of FUNCTION_ASSEMBLY) handlers[key] = createHandler(config);\n\n return {\n records: buildSupportKitRecords(config.slug),\n functions,\n settings: { fields: SUPPORT_KIT_SETTINGS_FIELDS },\n // DECISION 1 (see docs/plans/2026-09-02-gorgias-migration-progress.md's\n // T25 entry): always empty. §3.2's own fragment sketch types this\n // `PromptDef[] // seed Langfuse (§3.7)`, but §3.7 line 322 and D-LF both\n // say manifest.prompts[] is NOT used by the kit — it would seed an\n // `apps/<slug>/…` namespace that contradicts \"same Langfuse project,\n // bare legacy names, zero write at migration time\". A new audience's\n // prompts are seeded at first run via S3 createVersion (a RUNTIME\n // concern), not declared in the manifest.\n prompts: [],\n // T26 fills the four phase-2 pages + the settingsPage (§3.8); T27 part A\n // adds DashboardPage/TicketsPage/CorrectionsPage. Part B's remaining\n // phase-3 pages (GraphCanvasPage, SharedPromptsPage, TestPage) are still ahead.\n pages: buildPages(config),\n navigation: buildNavigation(config),\n settingsPage: buildSettingsPage(config),\n actions: SUPPORT_KIT_ACTIONS,\n emits: SUPPORT_KIT_EMITS,\n defaultRole: 'NO_ACCESS',\n handlers,\n mergeRole: buildMergeRole(config),\n mergeActions: mergeActionRefs,\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/graph/budget.ts","../src/prompts/references.ts","../src/prompts/resolver.ts","../src/records/target-ref.ts","../src/records/category.ts","../src/records/category-group.ts","../src/records/triage-decision.ts","../src/records/generated-response.ts","../src/records/response-comparison.ts","../src/records/evaluation.ts","../src/records/diff-analysis.ts","../src/records/pipeline-state.ts","../src/records/prompt-cache.ts","../src/records/derive-uid.ts","../src/records/scope-to-app.ts","../src/records/index.ts","../src/functions/config.ts","../src/adapters/conversation-mapping.ts","../src/adapters/gorgias-tags.ts","../src/adapters/ctx-ports.ts","../src/adapters/recording-ports.ts","../src/functions/context.ts","../src/functions/eligibility.ts","../src/functions/no-tool-context.ts","../src/functions/pipeline-state.ts","../src/functions/triage-tick.ts","../src/functions/claim-commit.ts","../src/functions/approval-key.ts","../src/functions/process-response.ts","../src/functions/generated-response-transition.ts","../src/functions/sweep.ts","../src/functions/handle-approval.ts","../src/functions/ids.ts","../src/functions/run-triage-now.ts","../src/functions/preview-triage.ts","../src/functions/graph-dry-run-core.ts","../src/functions/graph-dry-run.ts","../src/functions/test-agents.ts","../src/functions/validate-references.ts","../src/functions/suggest-prompt.ts","../src/functions/run-diff-analysis.ts","../src/functions/list-gorgias-views.ts","../src/functions/create-agent.ts","../src/functions/set-default-agent.ts","../src/functions/create-shared-prompt-version.ts","../src/functions/sync-agent-prompt-snapshot.ts","../src/functions/ext-models.ts","../src/functions/ext-categories.ts","../src/functions/ownership-probe.ts","../src/functions/support-extension-envelope.ts","../src/functions/ext-chat.ts","../src/functions/ext-fast-response-check.ts","../src/functions/ext-evaluation.ts","../src/functions/ext-response-comparison.ts","../src/pages/manifest.ts","../src/pipeline.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AE,CAAA;AACJ;AAEA,SAAS,kBAAkB,MAAA,EAA6C;AACtE,EAAA,OAAO;AAAA,IACL,mBAAA,EAAqB,iBAAA,CAAkB,MAAA,EAAQ,eAAe,CAAA;AAAA,IAC9D,KAAA,EAAO,qBAAA;AAAA,IACP,KAAA,EAAO;AAAA,GACT;AACF;AAEO,SAAS,qBAAqB,MAAA,EAAyD;AAC5F,EAAA,MAAM,SAAA,GAAY,kBAAkB,GAAA,CAAI,CAAC,EAAE,KAAA,EAAM,KAAM,KAAA,CAAM,MAAM,CAAC,CAAA;AACpE,EAAA,MAAM,WAAuC,EAAC;AAC9C,EAAA,KAAA,MAAW,EAAE,KAAK,aAAA,EAAc,IAAK,mBAAmB,QAAA,CAAS,GAAG,CAAA,GAAI,aAAA,CAAc,MAAM,CAAA;AAE5F,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,sBAAA,CAAuB,MAAA,CAAO,IAAI,CAAA;AAAA,IAC3C,SAAA;AAAA,IACA,QAAA,EAAU,EAAE,MAAA,EAAQ,2BAAA,EAA4B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAShD,SAAS,EAAC;AAAA;AAAA;AAAA;AAAA,IAIV,KAAA,EAAO,WAAW,MAAM,CAAA;AAAA,IACxB,UAAA,EAAY,gBAAgB,MAAM,CAAA;AAAA,IAClC,YAAA,EAAc,kBAAkB,MAAM,CAAA;AAAA,IACtC,OAAA,EAAS,mBAAA;AAAA,IACT,KAAA,EAAO,iBAAA;AAAA,IACP,WAAA,EAAa,WAAA;AAAA,IACb,QAAA;AAAA,IACA,SAAA,EAAW,eAAe,MAAM,CAAA;AAAA,IAChC,YAAA,EAAc;AAAA,GAChB;AACF","file":"index.js","sourcesContent":["// Spec: architecture_agent_graphe.md §6.3 (legacy `agent/budget.ts`).\n//\n// Ported unchanged: this bounds ONE run in tool calls and time, and tracks\n// its cost ledger (I15) — it has nothing to do with the worker-level\n// `RUN_DEADLINE_MS`/stale-lock scheduling the migration drops in favour of\n// Inngest retries/concurrency/timeouts (spec §3.3's \"différences assumées\").\n// The caller still supplies whatever `AbortSignal` represents its own\n// deadline; `Budget` only ever reads it.\nimport type { CostLedger, NodeCost, NodeKey, Usage } from '../domain';\n\nconst ZERO_COST: NodeCost = { input: 0, output: 0, reasoning: 0, usd: 0, pricingMissing: false };\n\n/**\n * Run budget: bounds a run in TOOL CALLS and TIME only, never in money —\n * cost is measured (`charge`, I15) and watched separately, not capped here.\n * Every method is a no-throw no-op past the allowance: exhausting the\n * budget must never fail a ticket (§6.3).\n */\nexport interface Budget {\n /** The run's deadline signal, forwarded unchanged to every LLM call. */\n signal: AbortSignal;\n consumeToolCall(): void;\n /** True once `maxToolCalls` is spent OR the run signal aborted. */\n exhausted(): boolean;\n /** Accumulates usage/cost for one node. Reasoning stays out of `output` (§6.3). */\n charge(node: NodeKey, usage: Usage, cost: { usd: number; pricingMissing: boolean }): void;\n /** Per-node breakdown for the ticket's provenance trail. */\n ledger(): CostLedger;\n /** Whole-run total — the per-ticket cost watched downstream. */\n total(): NodeCost;\n}\n\nfunction addCost(existing: NodeCost | undefined, usage: Usage, cost: { usd: number; pricingMissing: boolean }): NodeCost {\n const base = existing ?? ZERO_COST;\n return {\n input: base.input + usage.input,\n output: base.output + usage.output,\n reasoning: base.reasoning + usage.reasoning,\n usd: base.usd + cost.usd,\n // Sticky: one unpriced charge is enough to mark the whole node unpriced,\n // so a later zero-cost charge never makes it read as \"this was free\".\n pricingMissing: base.pricingMissing || cost.pricingMissing,\n };\n}\n\nexport function createBudget({ signal, maxToolCalls }: { signal: AbortSignal; maxToolCalls: number }): Budget {\n let toolCallsUsed = 0;\n const costs: CostLedger = {};\n\n return {\n signal,\n\n consumeToolCall(): void {\n toolCallsUsed += 1;\n },\n\n exhausted(): boolean {\n return toolCallsUsed >= maxToolCalls || signal.aborted;\n },\n\n charge(node, usage, cost): void {\n costs[node] = addCost(costs[node], usage, cost);\n },\n\n ledger(): CostLedger {\n return { ...costs };\n },\n\n total(): NodeCost {\n return Object.values(costs).reduce<NodeCost>(\n (acc, entry) => addCost(acc, entry, { usd: entry.usd, pricingMissing: entry.pricingMissing }),\n ZERO_COST,\n );\n },\n };\n}\n","/**\n * Parsing for Langfuse prompt-composition reference tags\n * (`@@@langfusePrompt:name=<name>|label=<label>@@@` or `|version=<n>@@@`).\n *\n * Ported from legacy `services/promptReferences.ts` (spec §3.7: \"la\n * composition … est résolue par le kit (port de `promptReferences.ts`)\").\n * `parseReferences`/`hasReferences` are pure and dependency-free, exactly as\n * in the legacy module, so `resolver.ts`'s composition pass and the\n * write-through cache guard can both depend on them without pulling in any\n * network/DB concern.\n *\n * `validateReferences` (the admin save-time validator) is NOT ported here:\n * it is an authoring-time concern for the prompt-editing UI (AgentsPage /\n * SharedPromptsPage, §3.8), not part of `PromptPort`'s runtime resolution\n * ladder — out of scope for T19. See the module doc in `resolver.ts` for the\n * runtime composition pass this package does own.\n *\n * `REFERENCE_TAG_SOURCE` (T23 post-review B3): the regex SOURCE, not the\n * stateful `g`-flagged object itself — `functions/validate-references.ts`\n * needs the exact same grammar to tell a well-formed tag from one that only\n * looks like one, and a hand-forked copy silently drifts the moment this\n * one gains a form. Exporting the source string (not `REF_RE`) keeps every\n * importer building its own `RegExp` instance, exactly like `hasReferences`\n * already does below — nobody shares, and therefore nobody can corrupt,\n * `REF_RE.lastIndex`.\n */\n\nconst REF_RE = /@@@langfusePrompt:name=([^|@]+)\\|(?:version=(\\d+)|label=([^@]+))@@@/g;\n\nexport const REFERENCE_TAG_SOURCE = REF_RE.source;\n\nexport interface PromptReference {\n name: string;\n version?: number;\n label?: string;\n raw: string;\n}\n\n/** Parse every well-formed reference tag out of `content`, in order of appearance. */\nexport function parseReferences(content: string): PromptReference[] {\n const refs: PromptReference[] = [];\n for (const [raw, name, version, label] of content.matchAll(REF_RE)) {\n refs.push(version !== undefined ? { name: name as string, version: Number(version), raw } : { name: name as string, label, raw });\n }\n return refs;\n}\n\n/**\n * Cheap synchronous check for \"does this content contain any reference tag\".\n * Used by the write-through cache guard (`resolver.ts`) to decide whether\n * raw content is safe to mirror into the `prompt-cache` record — a fresh\n * `new RegExp` avoids mutating the shared, stateful `REF_RE.lastIndex`.\n */\nexport function hasReferences(content: string): boolean {\n return new RegExp(REF_RE.source).test(content);\n}\n","/**\n * `PromptPort` implementation — §3.7's three-level fallback, ported from\n * legacy `services/promptStore.ts`'s `getActive` ladder:\n *\n * 1. `ctx.api.prompts.get(name, {label:'production', resolve:false})`\n * (T5's platform surface, reached only through the injected\n * `PlatformPromptReader` seam below — this package may not import\n * `@wopilo/*` or reach the network itself). A 60 s in-memory cache sits\n * in front of it, mirroring the legacy SDK's own `cacheTtlSeconds`.\n * Composition tags (`@@@langfusePrompt:name=…@@@`) are resolved by\n * THIS module (`composeReferences` below) — T5's surface reads raw\n * only, unlike legacy's `c.prompt.get` which flattened composition\n * server-side. Composition targets are read through the SAME memory\n * cache as the root prompt (post-review D1) — without that, a template\n * with N reference tags paid for N extra, uncached, sequentially\n * awaited Langfuse round-trips on every single call, TTL or not.\n * 2. The `prompt-cache` record mirror (T20's record, T21's adapter) —\n * reached only through the injected `PromptCachePort` seam. Written\n * through on every successful level-1 read, AFTER composition\n * (post-review C): the content mirrored is the fully composed,\n * tag-free text, not the raw pre-composition template. Composing first\n * means a Langfuse outage now degrades to the last-known-good COMPOSED\n * prompt instead of skipping the mirror for every prompt that uses\n * composition (`shared/style-email`/`shared/style-whatsapp` consumers,\n * in particular) — `hasReferences` stays as a cheap, should-never-fire\n * assertion guarding the same invariant it always did: no raw\n * `@@@…@@@` tag may ever reach the `prompt-cache` mirror.\n * 3. `ref.fallback` (the in-code default carried by the `PromptRef` the\n * caller passed in, itself populated from `config.defaults.prompts` at\n * `buildSupportPipeline` assembly time — T20).\n *\n * …and if that last rung is empty too, `MissingPromptError` (C5 as\n * amended, `graph/ports.ts`). This ladder used to terminate at empty\n * text, version 0 — a step reaching the model with no system message\n * at all, reported as a normal run. A step with no prompt is a broken\n * install: it fails the run, loudly, naming the prompt that resolved\n * to nothing. The settings-time half of the same rule is\n * `settings/validate.ts`, which refuses to run a pipeline whose active\n * steps name no prompt at all.\n *\n * Model config (`ResolvedPrompt.config`): populated from the level-1 read's\n * `RawPrompt.config` (T5's `PromptDetail.config`, once threaded through by\n * the platform adapter). Levels 2 and 3 still report `null` today, but for\n * different reasons now that T20 has landed the records: the `prompt-cache`\n * record (§3.4) DOES carry a `config JSON?` column — this module simply\n * neither writes nor reads it yet, so level 2 has a place to recover a\n * config from and does not use it (T21's `PromptCachePort` adapter is where\n * that gets wired). `PromptRef.fallback` carries no config field at all, so\n * level 3 is `null` by construction, not by omission.\n *\n * Cache scope: `createPromptResolver` holds NO module-level state — every\n * call returns a fresh closure over its own `Map`, so two calls (two\n * app instances, or two tests) never share a memory cache. A caller that\n * wants one long-lived resolver per app process constructs it once at\n * startup (T21); a test that wants a clean slate just calls the factory\n * again. The optional `now` hook replaces `Date.now()` for tests that need\n * to force an entry stale without `vi.useFakeTimers`.\n *\n * `onDegraded` (post-review E): the kit has no logging port, and should not\n * grow one just for this — but every point below where this ladder silently\n * empties a segment or falls a level is otherwise indistinguishable from a\n * correct run to an operator. This optional hook fires at each of those\n * points; T21 wires it to the platform logger.\n */\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { PromptRef } from '../domain/profile';\nimport { MissingPromptError, type PromptPort, type ResolvedPrompt } from '../graph/ports';\nimport { hasReferences, parseReferences, type PromptReference } from './references';\n\nconst PRODUCTION_LABEL = 'production';\nconst DEFAULT_TTL_MS = 60_000;\n\n/**\n * Langfuse's own prompt-composition resolver caps a reference chain at 5\n * levels; a linear A→B→C… chain here is otherwise bounded only by the\n * number of distinct prompt names, each hop a sequential awaited round-trip\n * inside the LLM path. Matching Langfuse's own cap keeps this module's\n * worst case aligned with the platform it is standing in for.\n *\n * Exported (T23 post-review B1) so `functions/validate-references.ts` can\n * reject, AT SAVE TIME, a chain that would silently degrade past this exact\n * cap at runtime — restating the number there would only let the two drift.\n */\nexport const MAX_COMPOSITION_DEPTH = 5;\n\n/** Back-compat key: the bare name for the default label, `name::label` otherwise (legacy `cacheId`). */\nfunction cacheKey(name: string, label: string): string {\n return label === PRODUCTION_LABEL ? name : `${name}::${label}`;\n}\n\n/**\n * Memory-cache key for a platform read. A version-pinned read (a composition\n * target naming `|version=n`) is keyed on the version, since a label can\n * float across versions but a pinned version never does — collapsing it onto\n * `cacheKey`'s label-shaped key would either merge two distinct versions\n * under one entry or never hit at all.\n */\nfunction memoryKey(name: string, opts: { label?: string; version?: number }): string {\n if (opts.version !== undefined) return `${name}::v${opts.version}`;\n return cacheKey(name, opts.label ?? PRODUCTION_LABEL);\n}\n\n/**\n * Mustache-style `{{var}}` substitution — mirrors legacy `compileFallback`.\n * Uses the function form of `replaceAll` (post-review D3): a plain string\n * replacement interprets `$&`/`` $` ``/`$'`/`$1` specially, so a value\n * containing a literal `$&` (a quoted ticket excerpt, for instance) would\n * silently splice the matched placeholder back into the compiled prompt.\n */\nfunction substituteVars(text: string, vars: Record<string, string> | undefined): string {\n if (!vars) return text;\n return Object.entries(vars).reduce((out, [key, value]) => out.replaceAll(`{{${key}}}`, () => value), text);\n}\n\n/** One reference tag's target config, as read off T5's `PromptDetail.config`. */\nexport interface RawPromptConfig {\n model?: string;\n temperature?: number;\n}\n\n/** Raw (uncompiled, composition-unresolved) prompt content read at a given name+label/version. */\nexport interface RawPrompt {\n version: number;\n content: string;\n /**\n * Model config carried by the platform prompt, when the endpoint returns\n * one. Optional/absent (not just `null`) so every existing raw literal\n * built before this field existed still type-checks unchanged.\n */\n config?: RawPromptConfig | null;\n}\n\n/**\n * Seam onto T5's `ctx.api.prompts.get(name, {label|version, resolve:false})`.\n * May throw (network error, 404, unconfigured Langfuse, …) — the resolver\n * treats any rejection as a level-1 miss and falls through the ladder. T21\n * supplies the real adapter; `testing/fakes` supplies a test double.\n */\nexport interface PlatformPromptReader {\n get(name: string, ref: { label?: string; version?: number }): Promise<RawPrompt>;\n}\n\n/** One entry of the `prompt-cache` mirror (§3.4) — always RESOLVED content, never a raw reference tag. */\nexport interface PromptCacheEntry {\n content: string;\n version: number;\n}\n\n/**\n * Seam onto the `prompt-cache` record (T20's schema, T21's adapter). Both\n * methods are best-effort from the resolver's point of view — a rejection\n * from either is caught and treated as a miss/no-op, exactly like legacy's\n * Mongo cache: a `prompt-cache` outage must never block the LLM path.\n */\nexport interface PromptCachePort {\n read(key: string): Promise<PromptCacheEntry | null>;\n write(key: string, entry: PromptCacheEntry): Promise<void>;\n}\n\n/**\n * One silent-degradation event (post-review E). `stage` names the point in\n * the ladder that gave up on the \"real\" answer and returned something safe\n * instead; `name` is the prompt/reference name involved; `reason` is a\n * human-readable cause, not a typed error (the kit has no logging/error\n * taxonomy to spend here — that is T21's job once this reaches a real\n * logger).\n */\nexport interface PromptDegradedEvent {\n stage:\n | 'platform-unavailable'\n | 'cache-unavailable'\n | 'composition-target-missing'\n | 'composition-target-forbidden'\n | 'composition-cycle'\n | 'composition-depth-exceeded'\n /**\n * Not a degradation but its terminus: the ladder resolved no text at any\n * level and the run is about to fail on `MissingPromptError`. Emitted\n * here anyway so an operator reading the degradation log sees the whole\n * ladder's story, ending in the reason, rather than the exception alone\n * with no trace of what was tried.\n */\n | 'prompt-missing';\n name: string;\n reason: string;\n}\n\nexport interface PromptResolverDeps {\n platform: PlatformPromptReader;\n cache: PromptCachePort;\n /** Memory-cache TTL override, ms. Defaults to 60 000 (§3.7). */\n ttlMs?: number;\n /** Injectable clock for the memory cache, defaults to `Date.now`. */\n now?: () => number;\n /** Fires at every silent-degradation point in the ladder (post-review E). */\n onDegraded?: (event: PromptDegradedEvent) => void;\n}\n\ninterface MemoryCacheEntry {\n /** Fully composed content — no remaining reference tag — never the raw fetch. */\n content: string;\n version: number;\n config?: RawPromptConfig | null;\n expiresAt: number;\n}\n\ninterface ComposeContext {\n platform: PlatformPromptReader;\n memory: Map<string, MemoryCacheEntry>;\n ttlMs: number;\n now: () => number;\n onDegraded?: (event: PromptDegradedEvent) => void;\n}\n\nfunction reasonOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * `parseReferences` returns one entry per OCCURRENCE, not per distinct\n * target (post-review D2) — a template that repeats the same tag twice must\n * still only fetch it once. `ref.raw` identifies the target uniquely enough\n * for this purpose: two occurrences of the same tag share the same raw\n * string, and `replaceAll` below already replaces every occurrence in one\n * pass once the tag is deduped.\n */\nfunction dedupeByRaw(refs: PromptReference[]): PromptReference[] {\n const seen = new Set<string>();\n return refs.filter((ref) => {\n if (seen.has(ref.raw)) return false;\n seen.add(ref.raw);\n return true;\n });\n}\n\nfunction stripReferences(content: string, refs: PromptReference[]): string {\n let out = content;\n for (const ref of dedupeByRaw(refs)) out = out.replaceAll(ref.raw, () => '');\n return out;\n}\n\n/**\n * Fetches `name` at `opts`, composes its references, and caches the\n * COMPOSED result (post-review D1) — shared by both the root prompt read\n * and every composition target, so a reference fetched once by any caller\n * within the TTL window is never fetched again, root or nested.\n */\nasync function readComposed(\n name: string,\n opts: { label?: string; version?: number },\n ctx: ComposeContext,\n visited: ReadonlySet<string>,\n depth: number,\n): Promise<MemoryCacheEntry> {\n const key = memoryKey(name, opts);\n const cached = ctx.memory.get(key);\n if (cached && cached.expiresAt > ctx.now()) return cached;\n\n const raw = await ctx.platform.get(name, opts);\n const content = await composeReferences(raw.content, ctx, visited, depth);\n const entry: MemoryCacheEntry = { content, version: raw.version, config: raw.config, expiresAt: ctx.now() + ctx.ttlMs };\n ctx.memory.set(key, entry);\n return entry;\n}\n\n/**\n * Resolves one reference tag to its replacement text: empty on a cycle\n * (visited) or an unresolvable target (fetch/compose throws), the target's\n * own composed content otherwise. Never leaves the literal tag in place —\n * the guarantee this module exists to hold (\"no raw tag reaches the LLM\")\n * applies here, not only through the write-through cache guard.\n */\nasync function resolveOneReference(\n ref: PromptReference,\n ctx: ComposeContext,\n visited: ReadonlySet<string>,\n depth: number,\n): Promise<string> {\n if (visited.has(ref.name)) {\n ctx.onDegraded?.({ stage: 'composition-cycle', name: ref.name, reason: 'cyclic composition reference' });\n return '';\n }\n\n const targetOpts = ref.version !== undefined ? { version: ref.version } : { label: ref.label };\n try {\n const target = await readComposed(ref.name, targetOpts, ctx, new Set([...visited, ref.name]), depth + 1);\n return target.content;\n } catch (err) {\n // M1 (T25 review): a 403 (the target exists but is outside this app's\n // role.prompts allowlist) is a MISCONFIGURATION, not a missing prompt —\n // reported under its own stage so `onDegraded` can name the allowlist\n // instead of reading identically to \"prompt/version/label not found\".\n // Still resolves to '' either way (PromptPort.resolve may never reject,\n // graph/ports.ts's C5) — this only makes the degradation legible.\n const forbidden = err instanceof AppApiError && err.status === 403;\n ctx.onDegraded?.({\n stage: forbidden ? 'composition-target-forbidden' : 'composition-target-missing',\n name: ref.name,\n reason: reasonOf(err),\n });\n return '';\n }\n}\n\n/**\n * Resolves every reference tag in `content`, one round-trip per DISTINCT\n * target (post-review D2), using the function form of `replaceAll`\n * (post-review D3 — see `substituteVars`'s doc comment for why). `depth`\n * bounds the chain at `MAX_COMPOSITION_DEPTH` (post-review D4): past it, the\n * remaining tags are stripped rather than followed one hop further, so a\n * long linear A→B→C… chain degrades instead of costing one sequential\n * round-trip per hop indefinitely.\n */\nasync function composeReferences(\n content: string,\n ctx: ComposeContext,\n visited: ReadonlySet<string>,\n depth: number,\n): Promise<string> {\n if (!hasReferences(content)) return content;\n\n const refs = parseReferences(content);\n if (depth >= MAX_COMPOSITION_DEPTH) {\n for (const ref of dedupeByRaw(refs)) {\n ctx.onDegraded?.({\n stage: 'composition-depth-exceeded',\n name: ref.name,\n reason: `composition chain exceeded ${MAX_COMPOSITION_DEPTH} levels`,\n });\n }\n return stripReferences(content, refs);\n }\n\n let resolved = content;\n for (const ref of dedupeByRaw(refs)) {\n const replacement = await resolveOneReference(ref, ctx, visited, depth);\n resolved = resolved.replaceAll(ref.raw, () => replacement);\n }\n return resolved;\n}\n\n/** Narrows a raw config blob to `ResolvedPrompt.config`'s stricter shape (model required, not just optional). */\nfunction toResolvedConfig(config: RawPromptConfig | null | undefined): ResolvedPrompt['config'] {\n if (!config || typeof config.model !== 'string' || config.model.length === 0) return null;\n return config.temperature !== undefined ? { model: config.model, temperature: config.temperature } : { model: config.model };\n}\n\n/** Builds a `PromptPort` implementing §3.7's three-level fallback ladder. */\nexport function createPromptResolver(deps: PromptResolverDeps): PromptPort {\n const ttlMs = deps.ttlMs ?? DEFAULT_TTL_MS;\n const now = deps.now ?? Date.now;\n const memory = new Map<string, MemoryCacheEntry>();\n const composeCtx: ComposeContext = { platform: deps.platform, memory, ttlMs, now, onDegraded: deps.onDegraded };\n\n async function resolveFromCacheOrFallback(\n name: string,\n label: string,\n ref: PromptRef,\n vars: Record<string, string> | undefined,\n ): Promise<ResolvedPrompt> {\n const cached = await deps.cache.read(cacheKey(name, label)).catch((err: unknown) => {\n deps.onDegraded?.({ stage: 'cache-unavailable', name, reason: reasonOf(err) });\n return null;\n });\n if (cached) {\n return served({ name, text: substituteVars(cached.content, vars), version: cached.version, config: null }, label);\n }\n\n // M3 (T25 review): `ref.fallback` (config.defaults.prompts, wired T25)\n // is the one rung of the ladder that used to skip composition entirely\n // — a fallback authored with the house `@@@langfusePrompt:...@@@` idiom\n // (the same syntax every legacy prompt already uses) would reach the\n // LLM as a literal, unresolved tag the moment Langfuse AND the\n // prompt-cache mirror were both unavailable, violating this module's\n // own \"no raw tag reaches the LLM\" guarantee. Composed through the same\n // `composeCtx` (and so the same memory cache) as every other level.\n const rawFallback = ref.fallback ?? '';\n const text = hasReferences(rawFallback)\n ? await composeReferences(rawFallback, composeCtx, new Set([name]), 0)\n : rawFallback;\n return served({ name, text: substituteVars(text, vars), version: 0, config: null }, label);\n }\n\n /**\n * The one exit every rung goes through: a resolution with no text is not a\n * prompt, whichever level produced it. Whitespace counts as empty — a\n * prompt of three newlines says nothing to a model, and a name that\n * resolves to one is the same broken install as a name that resolves to\n * nothing.\n */\n function served(resolved: ResolvedPrompt, label: string): ResolvedPrompt {\n if (resolved.text.trim() === '') {\n deps.onDegraded?.({ stage: 'prompt-missing', name: resolved.name, reason: 'no prompt content at any level' });\n throw new MissingPromptError(resolved.name, label);\n }\n return resolved;\n }\n\n return {\n async resolve(ref: PromptRef, vars?: Record<string, string>): Promise<ResolvedPrompt> {\n const label = ref.label?.trim() || PRODUCTION_LABEL;\n const persistKey = cacheKey(ref.name, label);\n\n let resolved: MemoryCacheEntry;\n try {\n resolved = await readComposed(ref.name, { label }, composeCtx, new Set([ref.name]), 0);\n } catch (err) {\n deps.onDegraded?.({ stage: 'platform-unavailable', name: ref.name, reason: reasonOf(err) });\n return resolveFromCacheOrFallback(ref.name, label, ref, vars);\n }\n\n // Write-through, AFTER composition (§3.7 invariant, post-review C):\n // only ever mirror composed, tag-free content. `hasReferences` here is\n // a should-never-fire assertion, not a decision point — composition\n // above already strips every matched tag by construction.\n if (!hasReferences(resolved.content)) {\n await deps.cache.write(persistKey, { content: resolved.content, version: resolved.version }).catch(() => undefined);\n }\n\n return served(\n {\n name: ref.name,\n text: substituteVars(resolved.content, vars),\n version: resolved.version,\n config: toResolvedConfig(resolved.config),\n },\n label,\n );\n },\n };\n}\n","/**\n * A relation's `targetRef` names the app the target record lives in\n * (`app:<slug>/<objectKey>`, resolved by `app-records.service.ts`), and the\n * kit is never installed under the slug `support-kit`: it is spread into\n * `experience-client`, `pro-sante`, … Every record carrying a relation is\n * therefore built per consuming app, from that app's own slug (§3.2's\n * `config.slug`), never from a literal.\n */\nexport function targetRefFor(slug: string, objectKey: string): string {\n return `app:${slug}/${objectKey}`;\n}\n","/**\n * `category` (ex-`Category`) — spec §3.4.\n *\n * `tagName` is matched exactly, case-sensitively, against Gorgias tags — it is\n * NOT normalised anywhere in this definition, on purpose: the handler that\n * applies tags (T22+) must compare byte-for-byte with what Gorgias sends back.\n *\n * The legacy `auto_reply_min_confidence` field is deliberately not ported —\n * the spec records it as already neutralised upstream in the legacy system.\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n CATEGORY_OBJECT_UID,\n CATEGORY_FIELD_NAME_UID,\n CATEGORY_FIELD_TAG_NAME_UID,\n CATEGORY_FIELD_ORDER_UID,\n CATEGORY_FIELD_GROUP_ID_UID,\n CATEGORY_FIELD_AGENT_ID_UID,\n CATEGORY_FIELD_EXTRA_TAGS_UID,\n CATEGORY_FIELD_DESCRIPTION_UID,\n CATEGORY_FIELD_EXAMPLES_UID,\n CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID,\n CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID,\n CATEGORY_INDEX_TAG_NAME_UID,\n CATEGORY_INDEX_NAME_UID,\n CATEGORY_INDEX_ORDER_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nexport function buildCategoryRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: CATEGORY_OBJECT_UID,\n objectKey: 'category',\n labelSingular: 'Category',\n labelPlural: 'Categories',\n description: 'A triage category, matched against a Gorgias tag.',\n fields: [\n {\n universalIdentifier: CATEGORY_FIELD_NAME_UID,\n name: 'name',\n type: FieldType.TEXT,\n label: 'Name',\n isNullable: false,\n },\n {\n universalIdentifier: CATEGORY_FIELD_TAG_NAME_UID,\n name: 'tagName',\n type: FieldType.TEXT,\n label: 'Gorgias tag',\n description: 'Matched exactly, case-sensitively, against Gorgias tags.',\n isNullable: false,\n },\n {\n universalIdentifier: CATEGORY_FIELD_ORDER_UID,\n name: 'order',\n type: FieldType.NUMBER,\n label: 'Order',\n isNullable: false,\n },\n {\n universalIdentifier: CATEGORY_FIELD_GROUP_ID_UID,\n name: 'groupId',\n type: FieldType.RELATION,\n label: 'Category group',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'category-group'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: CATEGORY_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: CATEGORY_FIELD_EXTRA_TAGS_UID,\n name: 'extraTags',\n type: FieldType.JSON,\n label: 'Extra tags',\n description: 'string[], at most 10 entries of at most 50 characters each.',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: CATEGORY_FIELD_DESCRIPTION_UID,\n name: 'description',\n type: FieldType.TEXT,\n label: 'Description',\n description:\n 'Short definition of what belongs in this category — 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.',\n // Nullable, and not merely by convention: every category already in a\n // tenant's base predates this field. A required one would fail the\n // read of every existing row.\n isNullable: true,\n },\n {\n universalIdentifier: CATEGORY_FIELD_EXAMPLES_UID,\n name: 'examples',\n type: FieldType.TEXT,\n label: 'Examples',\n description: 'At most 4000 characters.',\n isNullable: true,\n },\n {\n universalIdentifier: CATEGORY_FIELD_FAST_RESPONSE_ENABLED_UID,\n name: 'fastResponseEnabled',\n type: FieldType.BOOLEAN,\n label: 'Fast response enabled',\n isNullable: false,\n defaultValue: false,\n },\n {\n universalIdentifier: CATEGORY_FIELD_AUTO_REPLY_ENABLED_UID,\n name: 'autoReplyEnabled',\n type: FieldType.BOOLEAN,\n label: 'Auto-reply enabled',\n isNullable: false,\n defaultValue: false,\n },\n ],\n indexes: [\n { universalIdentifier: CATEGORY_INDEX_TAG_NAME_UID, fields: ['tagName'], isUnique: true },\n { universalIdentifier: CATEGORY_INDEX_NAME_UID, fields: ['name'], isUnique: true },\n { universalIdentifier: CATEGORY_INDEX_ORDER_UID, fields: ['order'] },\n ],\n };\n}\n","/** `category-group` — spec §3.4. */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n CATEGORY_GROUP_OBJECT_UID,\n CATEGORY_GROUP_FIELD_NAME_UID,\n CATEGORY_GROUP_FIELD_ORDER_UID,\n CATEGORY_GROUP_INDEX_NAME_UID,\n} from './ids';\n\nexport const categoryGroupRecord: ObjectDef = {\n universalIdentifier: CATEGORY_GROUP_OBJECT_UID,\n objectKey: 'category-group',\n labelSingular: 'Category group',\n labelPlural: 'Category groups',\n fields: [\n {\n universalIdentifier: CATEGORY_GROUP_FIELD_NAME_UID,\n name: 'name',\n type: FieldType.TEXT,\n label: 'Name',\n isNullable: false,\n },\n {\n universalIdentifier: CATEGORY_GROUP_FIELD_ORDER_UID,\n name: 'order',\n type: FieldType.NUMBER,\n label: 'Order',\n isNullable: false,\n },\n ],\n indexes: [{ universalIdentifier: CATEGORY_GROUP_INDEX_NAME_UID, fields: ['name'], isUnique: true }],\n};\n","/**\n * `triage-decision` (ex-`TriageDecision`) — spec §3.4.\n *\n * `decidedAt` is indexed because the 24h/7d stat windows filter and bucket on\n * this DATA field, not on the system `createdAt` — a run replayed or\n * backfilled keeps the decision's own timestamp.\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n TRIAGE_DECISION_OBJECT_UID,\n TRIAGE_DECISION_FIELD_TICKET_ID_UID,\n TRIAGE_DECISION_FIELD_DECIDED_AT_UID,\n TRIAGE_DECISION_FIELD_CATEGORY_ID_UID,\n TRIAGE_DECISION_FIELD_TAG_UID,\n TRIAGE_DECISION_FIELD_CONFIDENCE_UID,\n TRIAGE_DECISION_FIELD_REASONING_UID,\n TRIAGE_DECISION_FIELD_CONVERSATION_OVER_UID,\n TRIAGE_DECISION_FIELD_ESCALATED_UID,\n TRIAGE_DECISION_FIELD_ESCALATION_CONFIDENCE_UID,\n TRIAGE_DECISION_FIELD_ESCALATION_REASONING_UID,\n TRIAGE_DECISION_FIELD_STATUS_UID,\n TRIAGE_DECISION_FIELD_ERROR_UID,\n TRIAGE_DECISION_FIELD_RUN_ID_UID,\n TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID,\n TRIAGE_DECISION_INDEX_TICKET_ID_UID,\n TRIAGE_DECISION_INDEX_DECIDED_AT_UID,\n TRIAGE_DECISION_INDEX_ESCALATED_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nconst CONFIDENCE_OPTIONS = ['high', 'low'] as const;\n\nexport function buildTriageDecisionRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: TRIAGE_DECISION_OBJECT_UID,\n objectKey: 'triage-decision',\n labelSingular: 'Triage decision',\n labelPlural: 'Triage decisions',\n fields: [\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_TICKET_ID_UID,\n name: 'ticketId',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_DECIDED_AT_UID,\n name: 'decidedAt',\n type: FieldType.DATE_TIME,\n label: 'Decided at',\n description: 'Backs the 24h/7d stat windows — not the system createdAt.',\n isNullable: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_CATEGORY_ID_UID,\n name: 'categoryId',\n type: FieldType.RELATION,\n label: 'Category',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'category'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_TAG_UID,\n name: 'tag',\n type: FieldType.TEXT,\n label: 'Tag',\n isNullable: true,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_CONFIDENCE_UID,\n name: 'confidence',\n type: FieldType.SELECT,\n label: 'Confidence',\n isNullable: false,\n options: [...CONFIDENCE_OPTIONS],\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_REASONING_UID,\n name: 'reasoning',\n type: FieldType.TEXT,\n label: 'Reasoning',\n description: 'At most 280 characters.',\n isNullable: true,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_CONVERSATION_OVER_UID,\n name: 'conversationOver',\n type: FieldType.BOOLEAN,\n label: 'Conversation over',\n isNullable: false,\n defaultValue: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_ESCALATED_UID,\n name: 'escalated',\n type: FieldType.BOOLEAN,\n label: 'Escalated',\n isNullable: false,\n defaultValue: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_ESCALATION_CONFIDENCE_UID,\n name: 'escalationConfidence',\n type: FieldType.SELECT,\n label: 'Escalation confidence',\n isNullable: true,\n options: [...CONFIDENCE_OPTIONS],\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_ESCALATION_REASONING_UID,\n name: 'escalationReasoning',\n type: FieldType.TEXT,\n label: 'Escalation reasoning',\n isNullable: true,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_STATUS_UID,\n name: 'status',\n type: FieldType.SELECT,\n label: 'Status',\n isNullable: false,\n options: ['ok', 'error'],\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_ERROR_UID,\n name: 'error',\n type: FieldType.TEXT,\n label: 'Error',\n isNullable: true,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_RUN_ID_UID,\n name: 'runId',\n type: FieldType.TEXT,\n label: 'Run id',\n description: 'The application run this decision was made under.',\n isNullable: false,\n },\n {\n universalIdentifier: TRIAGE_DECISION_FIELD_SUBJECT_RENAMED_UID,\n name: 'subjectRenamed',\n type: FieldType.BOOLEAN,\n label: 'Subject renamed',\n isNullable: false,\n defaultValue: false,\n },\n ],\n indexes: [\n { universalIdentifier: TRIAGE_DECISION_INDEX_TICKET_ID_UID, fields: ['ticketId'] },\n { universalIdentifier: TRIAGE_DECISION_INDEX_DECIDED_AT_UID, fields: ['decidedAt'] },\n { universalIdentifier: TRIAGE_DECISION_INDEX_ESCALATED_UID, fields: ['escalated'] },\n ],\n };\n}\n","/**\n * `generated-response` (ex-`FastResponse`) — spec §3.4. Both the send queue\n * and the response cache.\n *\n * `status`'s option list is `GENERATED_RESPONSE_STATUSES` from\n * `../status/machine` — the single source of truth T16 already built for the\n * status vocabulary and its terminal/open partition — rather than a second\n * hardcoded list that could drift from it.\n *\n * `openTicketKey` reconstitutes the legacy \"one open job per ticket\"\n * guarantee as a Postgres unique index (NULLs are distinct): it is\n * `openTicketKeyFor(status, ticketId)` at write time (a T22+ handler\n * concern), so this definition intentionally does NOT restate which statuses\n * count as \"open\" — it only declares the field and its unique index.\n *\n * `autoSendDecision` is the field `reclaimStalledSend()` (T16) writes into\n * alongside `status: 'ready'` on the sweep's stalled-send reclaim.\n *\n * `expiresAt` is non-nullable: it is `generatedAt + responseTtlMinutes`,\n * known at creation time, and the sweep (`ready` expired -> `expired`, T22)\n * plus the extension's TTL check both read it unconditionally — a null there\n * would be a row that never expires.\n *\n * The JSON LIST fields (`sources`, `tracedInput`, `guardrailHits`,\n * `servedTo`) are non-nullable with a `[]` default, so no reader has to\n * distinguish \"null\" from \"empty\" before iterating; the single-object\n * `verdict` stays nullable, where `null` really does mean \"not evaluated\".\n *\n * T22 additions (all nullable — absent until the field's own write path\n * runs):\n * - `generatedMessageCount`/`generatedLastMessageAt` — a snapshot of\n * `Conversation.messageCount`/`lastMessageAt` taken by `process-response`\n * right before `runTicket`'s resumed run. `handle-approval` rebuilds a\n * placeholder `Conversation` for the `act` node's `generatedFrom`\n * argument out of exactly these two fields (plus `channel`) — see\n * `functions/handle-approval.ts` for why `act` never reads anything else\n * off that snapshot. This is a \"close enough\" generation-time reading,\n * not a live one: `act` always re-reads the conversation for real before\n * posting (I8), so a slightly stale baseline here only affects whether\n * THAT re-read counts as diverged, never send safety itself.\n * - `sendingAt` — when the record entered `status: 'sending'` (written by\n * the claim in `functions/claim-commit.ts`). Nothing else on this record\n * timestamps a status transition, and `sweep` needs to know how long a\n * `sending` row has been stuck to reclaim it (§3.5's 30-minute rule).\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport { GENERATED_RESPONSE_STATUSES } from '../status/machine';\nimport {\n GENERATED_RESPONSE_OBJECT_UID,\n GENERATED_RESPONSE_FIELD_TICKET_ID_UID,\n GENERATED_RESPONSE_FIELD_OPEN_TICKET_KEY_UID,\n GENERATED_RESPONSE_FIELD_STATUS_UID,\n GENERATED_RESPONSE_FIELD_TRIAGE_DECISION_ID_UID,\n GENERATED_RESPONSE_FIELD_CATEGORY_ID_UID,\n GENERATED_RESPONSE_FIELD_AGENT_ID_UID,\n GENERATED_RESPONSE_FIELD_CHANNEL_UID,\n GENERATED_RESPONSE_FIELD_RESPONSE_TEXT_UID,\n GENERATED_RESPONSE_FIELD_SOURCES_UID,\n GENERATED_RESPONSE_FIELD_TRACED_INPUT_UID,\n GENERATED_RESPONSE_FIELD_VERDICT_UID,\n GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_UID,\n GENERATED_RESPONSE_FIELD_AUTO_SEND_DECISION_UID,\n GENERATED_RESPONSE_FIELD_FOLLOWUP_REQUIRED_UID,\n GENERATED_RESPONSE_FIELD_SERVED_COUNT_UID,\n GENERATED_RESPONSE_FIELD_SERVED_TO_UID,\n GENERATED_RESPONSE_FIELD_GENERATED_AT_UID,\n GENERATED_RESPONSE_FIELD_EXPIRES_AT_UID,\n GENERATED_RESPONSE_FIELD_SENT_AT_UID,\n GENERATED_RESPONSE_FIELD_SENT_MESSAGE_ID_UID,\n GENERATED_RESPONSE_FIELD_LANGFUSE_TRACE_ID_UID,\n GENERATED_RESPONSE_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n GENERATED_RESPONSE_FIELD_PROMPT_NAME_UID,\n GENERATED_RESPONSE_FIELD_PROMPT_VERSION_UID,\n GENERATED_RESPONSE_FIELD_ERROR_UID,\n GENERATED_RESPONSE_FIELD_GENERATED_MESSAGE_COUNT_UID,\n GENERATED_RESPONSE_FIELD_GENERATED_LAST_MESSAGE_AT_UID,\n GENERATED_RESPONSE_FIELD_SENDING_AT_UID,\n GENERATED_RESPONSE_INDEX_TICKET_ID_UID,\n GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID,\n GENERATED_RESPONSE_INDEX_STATUS_UID,\n GENERATED_RESPONSE_INDEX_TRIAGE_DECISION_ID_UID,\n GENERATED_RESPONSE_INDEX_GENERATED_AT_UID,\n GENERATED_RESPONSE_INDEX_EXPIRES_AT_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nexport function buildGeneratedResponseRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: GENERATED_RESPONSE_OBJECT_UID,\n objectKey: 'generated-response',\n labelSingular: 'Generated response',\n labelPlural: 'Generated responses',\n description: 'A drafted reply, from pending draft through its send outcome.',\n fields: [\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_TICKET_ID_UID,\n name: 'ticketId',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: false,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_OPEN_TICKET_KEY_UID,\n name: 'openTicketKey',\n type: FieldType.TEXT,\n label: 'Open ticket key',\n description: \"= ticketId while status is open, cleared on a terminal status. Unique — see openTicketKeyFor().\",\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_STATUS_UID,\n name: 'status',\n type: FieldType.SELECT,\n label: 'Status',\n isNullable: false,\n options: [...GENERATED_RESPONSE_STATUSES],\n defaultValue: 'pending',\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_TRIAGE_DECISION_ID_UID,\n name: 'triageDecisionId',\n type: FieldType.RELATION,\n label: 'Triage decision',\n isNullable: false,\n relation: {\n targetRef: targetRefFor(slug, 'triage-decision'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'CASCADE',\n },\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_CATEGORY_ID_UID,\n name: 'categoryId',\n type: FieldType.RELATION,\n label: 'Category',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'category'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_CHANNEL_UID,\n name: 'channel',\n type: FieldType.SELECT,\n label: 'Channel',\n isNullable: false,\n options: ['email', 'whatsapp'],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_RESPONSE_TEXT_UID,\n name: 'responseText',\n type: FieldType.TEXT,\n label: 'Response text',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SOURCES_UID,\n name: 'sources',\n type: FieldType.JSON,\n label: 'Sources',\n description: '[{name, arguments, observation}]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_TRACED_INPUT_UID,\n name: 'tracedInput',\n type: FieldType.JSON,\n label: 'Traced input',\n description: '[{role, content}]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_VERDICT_UID,\n name: 'verdict',\n type: FieldType.JSON,\n label: 'Verdict',\n description: '{verdict, confidence, reason, status}',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_GUARDRAIL_HITS_UID,\n name: 'guardrailHits',\n type: FieldType.JSON,\n label: 'Guardrail hits',\n description: 'string[]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_AUTO_SEND_DECISION_UID,\n name: 'autoSendDecision',\n type: FieldType.SELECT,\n label: 'Auto-send decision',\n isNullable: true,\n options: ['auto', 'hold'],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_FOLLOWUP_REQUIRED_UID,\n name: 'followupRequired',\n type: FieldType.BOOLEAN,\n label: 'Followup required',\n isNullable: false,\n defaultValue: false,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SERVED_COUNT_UID,\n name: 'servedCount',\n type: FieldType.NUMBER,\n label: 'Served count',\n isNullable: false,\n defaultValue: 0,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SERVED_TO_UID,\n name: 'servedTo',\n type: FieldType.JSON,\n label: 'Served to',\n description: '[{user, at}], capped at 500 entries. Updated via S5 ifMatch + retry.',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_GENERATED_AT_UID,\n name: 'generatedAt',\n type: FieldType.DATE_TIME,\n label: 'Generated at',\n description: 'Backs the daily series stat.',\n isNullable: false,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_EXPIRES_AT_UID,\n name: 'expiresAt',\n type: FieldType.DATE_TIME,\n label: 'Expires at',\n isNullable: false,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SENT_AT_UID,\n name: 'sentAt',\n type: FieldType.DATE_TIME,\n label: 'Sent at',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SENT_MESSAGE_ID_UID,\n name: 'sentMessageId',\n type: FieldType.TEXT,\n label: 'Sent message id',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_LANGFUSE_TRACE_ID_UID,\n name: 'langfuseTraceId',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuseObservationId',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_PROMPT_VERSION_UID,\n name: 'promptVersion',\n type: FieldType.NUMBER,\n label: 'Prompt version',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_ERROR_UID,\n name: 'error',\n type: FieldType.TEXT,\n label: 'Error',\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_GENERATED_MESSAGE_COUNT_UID,\n name: 'generatedMessageCount',\n type: FieldType.NUMBER,\n label: 'Generated message count',\n description: \"Conversation.messageCount snapshot at generation time — act()'s divergence baseline when replayed via handle-approval.\",\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_GENERATED_LAST_MESSAGE_AT_UID,\n name: 'generatedLastMessageAt',\n type: FieldType.DATE_TIME,\n label: 'Generated last message at',\n description: \"Conversation.lastMessageAt snapshot at generation time — act()'s divergence baseline when replayed via handle-approval.\",\n isNullable: true,\n },\n {\n universalIdentifier: GENERATED_RESPONSE_FIELD_SENDING_AT_UID,\n name: 'sendingAt',\n type: FieldType.DATE_TIME,\n label: 'Sending at',\n description: \"When status became 'sending' — the sweep's staleness clock (§3.5).\",\n isNullable: true,\n },\n ],\n indexes: [\n { universalIdentifier: GENERATED_RESPONSE_INDEX_TICKET_ID_UID, fields: ['ticketId'] },\n {\n universalIdentifier: GENERATED_RESPONSE_INDEX_OPEN_TICKET_KEY_UID,\n fields: ['openTicketKey'],\n isUnique: true,\n },\n { universalIdentifier: GENERATED_RESPONSE_INDEX_STATUS_UID, fields: ['status'] },\n {\n universalIdentifier: GENERATED_RESPONSE_INDEX_TRIAGE_DECISION_ID_UID,\n fields: ['triageDecisionId'],\n isUnique: true,\n },\n { universalIdentifier: GENERATED_RESPONSE_INDEX_GENERATED_AT_UID, fields: ['generatedAt'] },\n { universalIdentifier: GENERATED_RESPONSE_INDEX_EXPIRES_AT_UID, fields: ['expiresAt'] },\n ],\n };\n}\n","/** `response-comparison` (ex-`ResponseComparison`) — spec §3.4. */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n RESPONSE_COMPARISON_OBJECT_UID,\n RESPONSE_COMPARISON_FIELD_GENERATED_TEXT_UID,\n RESPONSE_COMPARISON_FIELD_SENT_TEXT_UID,\n RESPONSE_COMPARISON_FIELD_CAPTURED_AT_UID,\n RESPONSE_COMPARISON_FIELD_TICKET_ID_UID,\n RESPONSE_COMPARISON_FIELD_TICKET_URL_UID,\n RESPONSE_COMPARISON_FIELD_AGENT_ID_UID,\n RESPONSE_COMPARISON_FIELD_LANGFUSE_TRACE_ID_UID,\n RESPONSE_COMPARISON_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n RESPONSE_COMPARISON_FIELD_PROMPT_NAME_UID,\n RESPONSE_COMPARISON_FIELD_PROMPT_VERSION_UID,\n RESPONSE_COMPARISON_FIELD_CONVERSATION_MESSAGES_UID,\n RESPONSE_COMPARISON_FIELD_DIFF_UID,\n RESPONSE_COMPARISON_INDEX_CAPTURED_AT_UID,\n RESPONSE_COMPARISON_INDEX_TICKET_ID_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nexport function buildResponseComparisonRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: RESPONSE_COMPARISON_OBJECT_UID,\n objectKey: 'response-comparison',\n labelSingular: 'Response comparison',\n labelPlural: 'Response comparisons',\n description: \"Compares the agent's draft against what the human actually sent.\",\n fields: [\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_GENERATED_TEXT_UID,\n name: 'generatedText',\n type: FieldType.TEXT,\n label: 'Generated text',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_SENT_TEXT_UID,\n name: 'sentText',\n type: FieldType.TEXT,\n label: 'Sent text',\n isNullable: false,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_CAPTURED_AT_UID,\n name: 'capturedAt',\n type: FieldType.DATE_TIME,\n label: 'Captured at',\n description: 'Backs the rewrite-rate trend.',\n isNullable: false,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_TICKET_ID_UID,\n name: 'ticketId',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_TICKET_URL_UID,\n name: 'ticketUrl',\n type: FieldType.TEXT,\n label: 'Ticket URL',\n isNullable: false,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: true,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'SET_NULL',\n },\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_LANGFUSE_TRACE_ID_UID,\n name: 'langfuseTraceId',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuseObservationId',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_PROMPT_VERSION_UID,\n name: 'promptVersion',\n type: FieldType.NUMBER,\n label: 'Prompt version',\n isNullable: true,\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_CONVERSATION_MESSAGES_UID,\n name: 'conversationMessages',\n type: FieldType.JSON,\n label: 'Conversation messages',\n description: '[{role, content}]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: RESPONSE_COMPARISON_FIELD_DIFF_UID,\n name: 'diff',\n type: FieldType.JSON,\n label: 'Diff',\n description: 'Word-by-word diff, computed at write time.',\n isNullable: true,\n },\n ],\n indexes: [\n { universalIdentifier: RESPONSE_COMPARISON_INDEX_CAPTURED_AT_UID, fields: ['capturedAt'] },\n { universalIdentifier: RESPONSE_COMPARISON_INDEX_TICKET_ID_UID, fields: ['ticketId'] },\n ],\n };\n}\n","/** `evaluation` (ex-`Evaluation`) — spec §3.4. No indexes named for this record. */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n EVALUATION_OBJECT_UID,\n EVALUATION_FIELD_AGENT_ID_UID,\n EVALUATION_FIELD_SATISFIED_UID,\n EVALUATION_FIELD_MESSAGES_UID,\n EVALUATION_FIELD_TICKET_URL_UID,\n EVALUATION_FIELD_LANGFUSE_TRACE_ID_UID,\n EVALUATION_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n EVALUATION_FIELD_SUPPORT_USER_KEY_ID_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\nexport function buildEvaluationRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: EVALUATION_OBJECT_UID,\n objectKey: 'evaluation',\n labelSingular: 'Evaluation',\n labelPlural: 'Evaluations',\n description: 'A human satisfaction verdict on an agent conversation.',\n fields: [\n {\n universalIdentifier: EVALUATION_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: false,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'CASCADE',\n },\n },\n {\n universalIdentifier: EVALUATION_FIELD_SATISFIED_UID,\n name: 'satisfied',\n type: FieldType.BOOLEAN,\n label: 'Satisfied',\n isNullable: false,\n },\n {\n universalIdentifier: EVALUATION_FIELD_MESSAGES_UID,\n name: 'messages',\n type: FieldType.JSON,\n label: 'Messages',\n description: '[{role, content}] — the conversation the verdict is about.',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: EVALUATION_FIELD_TICKET_URL_UID,\n name: 'ticketUrl',\n type: FieldType.TEXT,\n label: 'Ticket URL',\n isNullable: false,\n },\n {\n universalIdentifier: EVALUATION_FIELD_LANGFUSE_TRACE_ID_UID,\n name: 'langfuseTraceId',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n },\n {\n universalIdentifier: EVALUATION_FIELD_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuseObservationId',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n },\n {\n universalIdentifier: EVALUATION_FIELD_SUPPORT_USER_KEY_ID_UID,\n name: 'supportUserKeyId',\n type: FieldType.TEXT,\n label: 'Support user key id',\n isNullable: true,\n },\n ],\n };\n}\n","/**\n * `diff-analysis` (ex-`DiffAnalysis`) — spec §3.4.\n *\n * `uniqueKey` is `<agentId>::<promptName>::<promptVersion>`, computed by the\n * write handler (T22+) — this definition only declares the field and its\n * unique index, the equivalent of the legacy composite uniqueness.\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n DIFF_ANALYSIS_OBJECT_UID,\n DIFF_ANALYSIS_FIELD_AGENT_ID_UID,\n DIFF_ANALYSIS_FIELD_PROMPT_NAME_UID,\n DIFF_ANALYSIS_FIELD_PROMPT_VERSION_UID,\n DIFF_ANALYSIS_FIELD_POINTS_UID,\n DIFF_ANALYSIS_FIELD_UNIQUE_KEY_UID,\n DIFF_ANALYSIS_INDEX_UNIQUE_KEY_UID,\n} from './ids';\nimport { targetRefFor } from './target-ref';\n\n/** `<agentId>::<promptName>::<promptVersion>` — spec §3.4. */\nexport function diffAnalysisUniqueKey(\n agentId: string,\n promptName: string,\n promptVersion: number,\n): string {\n return `${agentId}::${promptName}::${promptVersion}`;\n}\n\nexport function buildDiffAnalysisRecord(slug: string): ObjectDef {\n return {\n universalIdentifier: DIFF_ANALYSIS_OBJECT_UID,\n objectKey: 'diff-analysis',\n labelSingular: 'Diff analysis',\n labelPlural: 'Diff analyses',\n description: 'Correction patterns aggregated for one (agent, prompt, version).',\n fields: [\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.RELATION,\n label: 'Agent',\n isNullable: false,\n relation: {\n targetRef: targetRefFor(slug, 'agent'),\n relationType: 'MANY_TO_ONE',\n onDelete: 'CASCADE',\n },\n },\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: false,\n },\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_PROMPT_VERSION_UID,\n name: 'promptVersion',\n type: FieldType.NUMBER,\n label: 'Prompt version',\n isNullable: false,\n },\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_POINTS_UID,\n name: 'points',\n type: FieldType.JSON,\n label: 'Points',\n description: 'string[]',\n isNullable: false,\n defaultValue: [],\n },\n {\n universalIdentifier: DIFF_ANALYSIS_FIELD_UNIQUE_KEY_UID,\n name: 'uniqueKey',\n type: FieldType.TEXT,\n label: 'Unique key',\n description: '<agentId>::<promptName>::<promptVersion>',\n isNullable: false,\n },\n ],\n indexes: [\n { universalIdentifier: DIFF_ANALYSIS_INDEX_UNIQUE_KEY_UID, fields: ['uniqueKey'], isUnique: true },\n ],\n };\n}\n","/**\n * `pipeline-state` — spec §3.4. Singleton per app; the kit's sole inter-app\n * contact point, read-only (`exposedToApps: ['*']`), purely informational —\n * §4's cross-app view-claim warning is what another app reads `sourceViewId`\n * for, to detect when two support-kit apps have been pointed at the same\n * Gorgias view.\n *\n * `sourceViewId` here mirrors the setting of the same name (§3.6) — it is\n * written by `triage-tick` (T22+), not by this definition.\n *\n * `singletonKey` (T22 hardening, A4 — a schema addition past §3.4's frozen\n * list, recorded as a deviation in the progress doc): `triage-tick` and\n * `sweep` are two independent crons that both fire every five minutes, and\n * on a fresh app both used to find the `list()` empty and both `create()` a\n * \"singleton\" row — nothing enforced only one existing, and `list` carries\n * no ordering guarantee, so `triage-tick` could thereafter read the\n * sweep-created row (no `lastTriageAt`) and silently skip its own cadence\n * gate on EVERY tick. A constant, always-the-same value plus a real unique\n * index turns \"singleton by convention\" into \"singleton by constraint\": both\n * functions now `upsert` on this key (`functions/pipeline-state.ts`), so the\n * platform's own `ON CONFLICT` — not a race between two `list()`+`create()`\n * pairs — is what decides there is exactly one row.\n */\nimport { FieldType } from '@apotech-os/app-kit';\nimport type { RecordDef } from './record-def';\nimport {\n PIPELINE_STATE_OBJECT_UID,\n PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID,\n PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID,\n PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID,\n PIPELINE_STATE_FIELD_SINGLETON_KEY_UID,\n PIPELINE_STATE_INDEX_SINGLETON_KEY_UID,\n} from './ids';\n\nexport const pipelineStateRecord: RecordDef = {\n universalIdentifier: PIPELINE_STATE_OBJECT_UID,\n objectKey: 'pipeline-state',\n labelSingular: 'Pipeline state',\n labelPlural: 'Pipeline state',\n description: 'Singleton run-cadence and view-claim state, readable by every installed app.',\n fields: [\n {\n universalIdentifier: PIPELINE_STATE_FIELD_SINGLETON_KEY_UID,\n name: 'singletonKey',\n type: FieldType.TEXT,\n label: 'Singleton key',\n description: 'Always the same constant value — the unique index below is what makes this record a true singleton, not just a convention.',\n isNullable: false,\n },\n {\n universalIdentifier: PIPELINE_STATE_FIELD_SOURCE_VIEW_ID_UID,\n name: 'sourceViewId',\n type: FieldType.TEXT,\n label: 'Source view id',\n description: 'The claimed Gorgias view — supports the cross-app overlap warning (§4).',\n isNullable: true,\n },\n {\n universalIdentifier: PIPELINE_STATE_FIELD_LAST_TRIAGE_AT_UID,\n name: 'lastTriageAt',\n type: FieldType.DATE_TIME,\n label: 'Last triage at',\n description: \"Gates triage-tick's cadence.\",\n isNullable: true,\n },\n {\n universalIdentifier: PIPELINE_STATE_FIELD_LAST_SWEEP_AT_UID,\n name: 'lastSweepAt',\n type: FieldType.DATE_TIME,\n label: 'Last sweep at',\n isNullable: true,\n },\n ],\n indexes: [{ universalIdentifier: PIPELINE_STATE_INDEX_SINGLETON_KEY_UID, fields: ['singletonKey'], isUnique: true }],\n exposedToApps: ['*'],\n};\n","/**\n * `prompt-cache` (ex-`PromptCache`) — spec §3.4, level-2 fallback of the\n * prompt ladder (§3.7).\n *\n * `config JSON?` — added beyond the spec's literal field list, on T19's\n * explicit deferral: the legacy cache carried the model config (not just the\n * compiled template), so invariant I16 (\"levels 2/3 keep working through a\n * Langfuse outage\") holds for the *prompt text* but not for the *config* a\n * caller needs alongside it — levels 2 and 3 of the resolver (T19) return\n * `config: null` today. Adding the column here is the minimal step: it makes\n * the record ABLE to carry a config without deciding its shape or wiring it\n * into the resolver. Follow-up (not T20): change `prompts/resolver.ts` to\n * read and write this column, and settle what \"config\" means for a cache row\n * (presumably the same `{model, reasoning}` shape used by `settings.nodes`).\n */\nimport { FieldType, type ObjectDef } from '@apotech-os/app-kit';\nimport {\n PROMPT_CACHE_OBJECT_UID,\n PROMPT_CACHE_FIELD_PROMPT_KEY_UID,\n PROMPT_CACHE_FIELD_CONTENT_UID,\n PROMPT_CACHE_FIELD_VERSION_UID,\n PROMPT_CACHE_FIELD_LABEL_UID,\n PROMPT_CACHE_FIELD_CONFIG_UID,\n PROMPT_CACHE_INDEX_PROMPT_KEY_UID,\n} from './ids';\n\nexport const promptCacheRecord: ObjectDef = {\n universalIdentifier: PROMPT_CACHE_OBJECT_UID,\n objectKey: 'prompt-cache',\n labelSingular: 'Prompt cache entry',\n labelPlural: 'Prompt cache entries',\n description: 'Last-known-good snapshot of a Langfuse prompt, for the resolver fallback ladder.',\n fields: [\n {\n universalIdentifier: PROMPT_CACHE_FIELD_PROMPT_KEY_UID,\n name: 'promptKey',\n type: FieldType.TEXT,\n label: 'Prompt key',\n description: \"'name' or 'name::label'.\",\n isNullable: false,\n },\n {\n universalIdentifier: PROMPT_CACHE_FIELD_CONTENT_UID,\n name: 'content',\n type: FieldType.TEXT,\n label: 'Content',\n description: 'Raw, uncompiled template.',\n isNullable: false,\n },\n {\n universalIdentifier: PROMPT_CACHE_FIELD_VERSION_UID,\n name: 'version',\n type: FieldType.NUMBER,\n label: 'Version',\n isNullable: false,\n },\n {\n universalIdentifier: PROMPT_CACHE_FIELD_LABEL_UID,\n name: 'label',\n type: FieldType.TEXT,\n label: 'Label',\n isNullable: true,\n },\n {\n universalIdentifier: PROMPT_CACHE_FIELD_CONFIG_UID,\n name: 'config',\n type: FieldType.JSON,\n label: 'Config',\n description: 'Model config snapshot, for I16. Not yet written or read — see module doc.',\n isNullable: true,\n },\n ],\n indexes: [{ universalIdentifier: PROMPT_CACHE_INDEX_PROMPT_KEY_UID, fields: ['promptKey'], isUnique: true }],\n};\n","import { createHash } from 'node:crypto';\n\n/**\n * Kit-owned namespace UUID (RFC 4122 §4.3) — fixed and arbitrary, used only\n * as `deriveUid`'s namespace input. Never written to a manifest itself.\n */\nconst SUPPORT_KIT_UID_NAMESPACE = '2b6a9c0e-6c1e-4c1a-8b0e-2a2f4b8c9d3f';\n\nfunction uuidToBytes(uuid: string): Buffer {\n return Buffer.from(uuid.replace(/-/g, ''), 'hex');\n}\n\nfunction bytesToUuid(bytes: Buffer): string {\n const hex = bytes.toString('hex');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/**\n * A deterministic UUIDv5 over `seed` (RFC 4122 §4.3: SHA-1 of a namespace +\n * a name, with the version/variant bits fixed up). Same seed always yields\n * the same uid — no randomness, no `Date` — and different seeds yield\n * different uids with cryptographic collision resistance.\n *\n * Used by `scopeRecordToApp` (B1, T25 review) to turn the kit's own stable\n * per-record constants (`ids.ts`) into uids that are additionally scoped to\n * the consuming app's slug, so two different apps installing the same kit\n * never collide on `AppEntity.universalIdentifier` (globally unique on the\n * platform, not per application).\n */\nexport function deriveUid(seed: string): string {\n const hash = createHash('sha1').update(uuidToBytes(SUPPORT_KIT_UID_NAMESPACE)).update(seed, 'utf8').digest();\n const bytes = hash.subarray(0, 16);\n bytes[6] = (bytes[6]! & 0x0f) | 0x50; // version 5\n bytes[8] = (bytes[8]! & 0x3f) | 0x80; // variant RFC4122\n return bytesToUuid(bytes);\n}\n","import { deriveUid } from './derive-uid';\nimport type { RecordDef } from './record-def';\n\n/**\n * Rewrites every `universalIdentifier` in a kit record (object, fields,\n * indexes) from the kit's own stable constant (`ids.ts`) into one\n * deterministically derived from `(slug, that constant)` — B1, T25 review.\n *\n * Why: `ids.ts`'s constants are unique AMONG THEMSELVES, but the platform's\n * `AppEntity.universalIdentifier` is unique GLOBALLY, not per application\n * (`apps/api/prisma/schema.prisma`). Used as-is, the second app to install\n * this kit republishes the same 126 literals the first app already claimed\n * and hits an unhandled Prisma P2002 on publish. Scoping by slug keeps every\n * uid stable across rebuilds (pure function of the slug + the constant, no\n * randomness) while making two different consuming apps' uid sets disjoint.\n */\nexport function scopeRecordToApp(slug: string, record: RecordDef): RecordDef {\n return {\n ...record,\n universalIdentifier: deriveUid(`${slug}:${record.universalIdentifier}`),\n fields: record.fields.map((field) => ({\n ...field,\n universalIdentifier: deriveUid(`${slug}:${field.universalIdentifier}`),\n })),\n indexes: record.indexes?.map((index) => ({\n ...index,\n universalIdentifier: deriveUid(`${slug}:${index.universalIdentifier}`),\n })),\n };\n}\n","// Spec: spec-migration-gorgias-backoffice-v1.md §3.4 — the kit's own\n// `ObjectDef` fragments, one module per record, assembled here into the\n// array a consuming app's manifest spreads into its own `records: [...]`.\n//\n// Every record that declares a RELATION is a factory over the consuming\n// app's slug (§3.2's `config.slug`), because a relation's `targetRef` is\n// `app:<slug>/<objectKey>` and the kit is installed as `experience-client`,\n// `pro-sante`, … — never as `support-kit`. The four records with no\n// relation stay plain constants: nothing about them varies per app.\nexport { buildCategoryRecord } from './category';\nexport { categoryGroupRecord } from './category-group';\nexport { agentRecord, AGENT_STATUSES, DEFAULT_LLM_PROVIDER, type AgentStatus } from './agent';\nexport { buildTriageDecisionRecord } from './triage-decision';\nexport { buildGeneratedResponseRecord } from './generated-response';\nexport { buildResponseComparisonRecord } from './response-comparison';\nexport { buildEvaluationRecord } from './evaluation';\nexport { buildDiffAnalysisRecord, diffAnalysisUniqueKey } from './diff-analysis';\nexport { pipelineStateRecord } from './pipeline-state';\nexport { promptCacheRecord } from './prompt-cache';\nexport { targetRefFor } from './target-ref';\nexport type { RecordDef } from './record-def';\n\nimport { buildCategoryRecord } from './category';\nimport { categoryGroupRecord } from './category-group';\nimport { agentRecord } from './agent';\nimport { buildTriageDecisionRecord } from './triage-decision';\nimport { buildGeneratedResponseRecord } from './generated-response';\nimport { buildResponseComparisonRecord } from './response-comparison';\nimport { buildEvaluationRecord } from './evaluation';\nimport { buildDiffAnalysisRecord } from './diff-analysis';\nimport { pipelineStateRecord } from './pipeline-state';\nimport { promptCacheRecord } from './prompt-cache';\nimport { scopeRecordToApp } from './scope-to-app';\nimport type { RecordDef } from './record-def';\n\n/**\n * All 10 records of §3.4, in the order the spec lists them, bound to the\n * consuming app's `slug` — the single assembly point `buildSupportPipeline`\n * (T25) spreads into a manifest.\n *\n * Every record/field/index `universalIdentifier` is additionally scoped to\n * `slug` via `scopeRecordToApp` (B1, T25 review): `ids.ts`'s constants are\n * stable per-record keys, not final manifest uids — two different consuming\n * apps installing this kit must never publish the same\n * `AppEntity.universalIdentifier` (unique platform-wide).\n */\nexport function buildSupportKitRecords(slug: string): RecordDef[] {\n return [\n buildCategoryRecord(slug),\n categoryGroupRecord,\n agentRecord,\n buildTriageDecisionRecord(slug),\n buildGeneratedResponseRecord(slug),\n buildResponseComparisonRecord(slug),\n buildEvaluationRecord(slug),\n buildDiffAnalysisRecord(slug),\n pipelineStateRecord,\n promptCacheRecord,\n ].map((record) => scopeRecordToApp(slug, record));\n}\n","/**\n * `SupportKitFunctionConfig` — what each of the four T22 manifest fragments\n * (`triage-tick`/`process-response`/`sweep`/`handle-approval`) needs to\n * build its `FunctionDef` (spec §3.2's `SupportPipelineConfig`, the slice of\n * it these fragments actually read — `buildSupportPipeline`, T25, owns the\n * full shape and passes this down).\n */\nimport type { PromptNameConfig } from '../prompts/slots';\n\n/** Stable keys this module looks up `identifiers` by — documented here so a caller can't guess wrong. */\nexport const FUNCTION_IDENTIFIER_KEYS = [\n 'triage-tick',\n 'process-response',\n 'sweep',\n 'handle-approval',\n // T23 — the seven operator `uiInvoke` functions (§3.5's table).\n 'run-triage-now',\n // B5 — the event-triggered worker `run-triage-now` hands the batch to, so\n // the manual trigger answers inside its `uiInvoke` budget instead of\n // 504-ing halfway through a 30-ticket LLM pass (`run-triage-now.ts`'s doc).\n 'run-triage-batch',\n 'preview-triage',\n 'graph-dry-run',\n 'test-agents',\n 'suggest-prompt',\n 'run-diff-analysis',\n 'list-gorgias-views',\n // T26 rework — AgentsPage cannot create a valid agent or promote a default\n // one from raw record PATCHes alone (BLOCKER 3, BLOCKER 4); both are\n // write-handler concerns per records/agent.ts's own doc.\n 'create-agent',\n 'set-default-agent',\n // T27 part B — SharedPromptsPage's own write path: validates\n // `@@@langfusePrompt:…@@@` composition (`validateReferences`) before\n // writing a `shared/*` version, a check the raw S3 REST route does not run.\n 'create-shared-prompt-version',\n // §5.2 — `GET /models` serves `system_prompt` from `systemPromptSnapshot`\n // alone, so that snapshot has to be refreshed whenever a new version of an\n // agent's prompt starts being served.\n 'sync-agent-prompt-snapshot',\n // T24 — the six reserved `ext-*` functions (§5.2), the extension gateway's\n // only view of the kit.\n 'ext-models',\n 'ext-categories',\n 'ext-chat',\n 'ext-fast-response-check',\n 'ext-evaluation',\n 'ext-response-comparison',\n] as const;\n\nexport type FunctionIdentifierKey = (typeof FUNCTION_IDENTIFIER_KEYS)[number];\n\nexport interface SupportKitFunctionConfig extends PromptNameConfig {\n /** The consuming app's own slug — `app:<slug>/<objectKey>` dbEvent triggers, and the object relations. */\n slug: string;\n /**\n * §3.2's `SupportPipelineConfig.identifiers` — one `universalIdentifier`\n * per manifest function, keyed by the values in `FUNCTION_IDENTIFIER_KEYS`.\n * A manifest fragment with a missing id is broken by construction: looking\n * one up throws immediately rather than inventing a random one that would\n * drift on every rebuild.\n */\n identifiers: Record<string, string>;\n}\n\n/** Looks up `config.identifiers[key]`, throwing loudly on a missing entry (a broken manifest, not a runtime condition to recover from). */\nexport function identifierFor(config: SupportKitFunctionConfig, key: FunctionIdentifierKey): string {\n const id = config.identifiers[key];\n if (!id) {\n throw new Error(\n `SupportKitFunctionConfig.identifiers is missing a universalIdentifier for \"${key}\" — every support-kit function needs a stable id.`,\n );\n }\n return id;\n}\n","/**\n * Derives the kit's domain `Conversation` from the SINGLE\n * `getTicketWithContext` fetch (`ctx-ports.ts`'s\n * `createGorgiasConversationPort`; B, T21 review), which returns both:\n *\n * - the RAW payload the guardrail detectors need (`isWhatsappTicket`,\n * `isJudgemeTicket`, `isAutomatedSenderTicket`, `isTicketClosed`,\n * `hasCustomerAttachment` — `guardrails/raw-ticket.ts`) and this\n * module's own message-count/timestamp snapshot.\n * - the ALREADY-EXTRACTED chronological messages + customer-info block a\n * node actually drafts against — its HTML-to-text conversion and\n * \"Information Client\" synthetic prefix are Gorgias-specific rendering\n * this package does not re-derive.\n *\n * `getRawTicket` and `buildTicketContext` used to be called as two separate\n * actions reading the exact same Gorgias endpoint (§S1) — a `read()` call\n * paid for it twice, and worse, the two fetches could observe different\n * server states if a message landed between them. `getTicketWithContext`\n * (`@wopilo/gorgias-client`) fetches once and derives both halves from that\n * one payload, so the raw-based facts and the domain conversation are now\n * GUARANTEED — not just assumed — to describe the exact same server\n * response.\n */\nimport {\n hasCustomerAttachment,\n isTicketClosed,\n isWhatsappChevronNote,\n isWhatsappTicket,\n type RawTicket,\n} from '../guardrails';\nimport type { Conversation, ConversationRef, Message } from '../domain';\n\ntype RawMessage = NonNullable<RawTicket['messages']>[number];\n\n/** One turn of `buildTicketContext`'s already-extracted conversation. */\nexport interface RawTicketContextMessage {\n role: 'user' | 'assistant' | 'system';\n content: string;\n synthetic?: boolean;\n}\n\n/** The shape `ctx.api.integrations.run('gorgias', 'buildTicketContext', …)` returns. */\nexport interface RawTicketContext {\n messages: RawTicketContextMessage[];\n customerContext: string | null;\n customerName?: string | null;\n customerEmail?: string | null;\n}\n\n/**\n * Same predicate `guardrails/raw-ticket.ts` uses internally, un-exported\n * there. Duplicated here BY HAND, same precedent that module's own doc\n * gives for its copy of `@wopilo/gorgias-client`'s `isInternalNoteChannel`:\n * this package may not import that client, so the one-line rule is kept in\n * sync manually rather than reached for through a forbidden import.\n */\nfunction isInternalNoteChannel(message: RawMessage): boolean {\n return message.channel === 'internal-note' || message.source?.type === 'internal-note';\n}\n\n/**\n * Port of `@wopilo/gorgias-client`'s `countableMessages` (`ticket-context.ts`)\n * — the divergence-snapshot rule. This package cannot import that package\n * (dependency-allowlist), so it is kept in sync by hand.\n *\n * \"Has extractable text\" checks PRESENCE across `body_text`/`body_html`/\n * `stripped_text`/`stripped_html` — not conversion. The client's own\n * `extractMessageText` prefers HTML and runs it through `htmlToText`\n * (T3-review-A5: an HTML-only customer reply has a blank `body_text`, so\n * checking that field alone misses a real turn — invisible to\n * `Conversation.messageCount`/`lastMessageAt`, so `act`'s divergence check\n * never sees the customer replied and a stale draft gets auto-sent). This\n * package cannot port `htmlToText` in, so it stays on the SAFE side instead:\n * any non-blank field counts, even a `<br>`-only body that `htmlToText`\n * would reduce to nothing. That can only ever over-count — producing a\n * spurious *hold*, never a spurious send.\n */\nfunction countableMessages(messages: RawMessage[], isWhatsapp: boolean): RawMessage[] {\n return messages.filter((m) => {\n if (isInternalNoteChannel(m)) return isWhatsappChevronNote(m, isWhatsapp);\n const hasText = !!(m.body_text?.trim() || m.body_html?.trim() || m.stripped_text?.trim() || m.stripped_html?.trim());\n const hasAttachment = (m.attachments?.length ?? 0) > 0;\n return hasText || hasAttachment;\n });\n}\n\nexport interface ConversationSnapshot {\n count: number;\n lastAt: Date | null;\n}\n\n/** Message count + last-message timestamp — feeds `Conversation.messageCount`/`lastMessageAt` (I8's anti-divergence snapshot). */\nexport function snapshotConversation(raw: RawTicket): ConversationSnapshot {\n const isWhatsapp = isWhatsappTicket(raw);\n const messages = countableMessages(raw.messages ?? [], isWhatsapp);\n let lastAt: Date | null = null;\n for (const m of messages) {\n if (!m.created_datetime) continue;\n const at = new Date(m.created_datetime);\n if (!lastAt || at > lastAt) lastAt = at;\n }\n return { count: messages.length, lastAt };\n}\n\n/**\n * When an agent (human or our own auto-reply) last spoke. Deliberately\n * applies NO countability/text test of its own — it follows\n * `raw-ticket.ts`'s `hasAgentReplySince` (channel/chevron rule only),\n * generalised from a boolean since-a-date check to the timestamp itself,\n * since `Conversation.lastAgentReplyAt` needs the value, not a threshold.\n * That is the safe direction: an agent message with no extractable text\n * still counts as \"the agent spoke\", so this never under-reports the last\n * agent activity.\n */\nfunction lastAgentReplyAtOf(raw: RawTicket): Date | null {\n const isWhatsapp = isWhatsappTicket(raw);\n let latest: Date | null = null;\n for (const m of raw.messages ?? []) {\n if (m.from_agent !== true) continue;\n if (isInternalNoteChannel(m) && !isWhatsappChevronNote(m, isWhatsapp)) continue;\n if (!m.created_datetime) continue;\n const at = new Date(m.created_datetime);\n if (!latest || at > latest) latest = at;\n }\n return latest;\n}\n\n/**\n * Assembles the domain `Conversation`. `sourceChannel` honours the T15\n * contract restated in `graph/ports.ts`'s `Conversation` doc: `'whatsapp'`\n * IFF `isWhatsappTicket(raw)`, never a bare `raw.channel` read.\n */\nexport function toConversation(ref: ConversationRef, raw: RawTicket, context: RawTicketContext): Conversation {\n const snapshot = snapshotConversation(raw);\n const messages: Message[] = context.messages\n .filter((m): m is RawTicketContextMessage & { role: 'user' | 'assistant' } => m.role === 'user' || m.role === 'assistant')\n .map((m) => ({ role: m.role, content: m.content }));\n\n return {\n ref,\n subject: raw.subject ?? null,\n messages,\n customer: {\n name: context.customerName ?? null,\n email: context.customerEmail ?? null,\n orderContext: context.customerContext ?? null,\n },\n isClosed: isTicketClosed(raw),\n lastMessageAt: snapshot.lastAt,\n messageCount: snapshot.count,\n lastAgentReplyAt: lastAgentReplyAtOf(raw),\n hasCustomerAttachment: hasCustomerAttachment(raw),\n sourceChannel: isWhatsappTicket(raw) ? 'whatsapp' : (raw.channel ?? null),\n };\n}\n","/**\n * Shared by `ctx-ports.ts`'s real `StatePort.record` and\n * `recording-ports.ts`'s no-op one: the exact tag SET a triage decision\n * materialises, ported from legacy `ClassificationSink.record`\n * (`[category, ...extraTags, handledTag]`, deduplicated). Both need the\n * IDENTICAL computation — the recording port's whole point is to report the\n * tags production WOULD have applied, so a second, drifting copy here would\n * silently defeat that guarantee.\n *\n * The category lookup (`api.list('category', …)`) is a READ, not a write —\n * both the real and the recording `StatePort` perform it for real; only the\n * final `applyTags` call is what the recording port skips.\n */\nimport type { AuditTags } from '../graph/ports';\nimport type { Classification } from '../domain';\nimport type { SupportKitApi } from './api';\n\n/** Trims and deduplicates, in first-seen order, dropping blank entries. */\nexport function dedupeTagNames(tags: ReadonlyArray<string | null | undefined>): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const tag of tags) {\n const trimmed = (tag ?? '').trim();\n if (trimmed && !seen.has(trimmed)) {\n seen.add(trimmed);\n out.push(trimmed);\n }\n }\n return out;\n}\n\n/** The category's own additional tags, resolved by `tagName` — `[]` when no category matches. */\nasync function extraTagsFor(api: SupportKitApi, tagName: string): Promise<string[]> {\n const page = await api.list('category', { filter: { tagName }, limit: 1 });\n const data = page.items[0]?.data as { extraTags?: string[] } | undefined;\n return data?.extraTags ?? [];\n}\n\n/** The deduplicated tag set a triage decision applies: `[category, ...extraTags, handledTag]`. */\nexport async function resolveHandledTags(\n api: SupportKitApi,\n classification: Classification,\n audit: AuditTags,\n): Promise<string[]> {\n const extraTags = await extraTagsFor(api, classification.category);\n return dedupeTagNames([classification.category, ...extraTags, audit.handledTag]);\n}\n","/**\n * Real port implementations on `ctx` (spec §3.3 `adapters/ctx-ports.ts`):\n * Conversation/Reply/State via `ctx.api.integrations.run('gorgias', …)`\n * (S1), Llm via `ctx.api.llm.complete` v2 (S2), Prompt via §3.7's resolver\n * (T19), Clock over the real `Date`.\n *\n * `StatePort` deviation, kept from `graph/ports.ts`'s own header comment:\n * §3.3's table names it \"records\", but its actual traffic here is Gorgias\n * tag/rename calls (`applyTags`/`renameTicket`) — S1 integration writes, not\n * an AppRecord write. The one genuine AppRecord read in this file is\n * `StatePort.record`'s category `extraTags` lookup (`gorgias-tags.ts`).\n */\nimport type {\n ChatMessage,\n ClockPort,\n CompletionRequest,\n CompletionResult,\n ConversationPort,\n LlmPort,\n OutboundReply,\n PromptPort,\n ReplyPort,\n StatePort,\n} from '../graph/ports';\nimport type { ConversationRef } from '../domain';\nimport type { PlatformPromptReader, PromptCachePort, PromptDegradedEvent } from '../prompts/resolver';\nimport { createPromptResolver } from '../prompts/resolver';\nimport type { RawTicket } from '../guardrails';\nimport type { SupportKitApi } from './api';\nimport { toConversation, type RawTicketContext } from './conversation-mapping';\nimport { resolveHandledTags } from './gorgias-tags';\n\nfunction asRawTicket(value: unknown): RawTicket {\n return (value ?? {}) as RawTicket;\n}\n\n// --- ConversationPort --------------------------------------------------------\n\nexport function createGorgiasConversationPort(api: SupportKitApi): ConversationPort {\n return {\n async listPending(source, limit) {\n const tickets = (await api.integrations.run('gorgias', 'fetchTicketsFromView', {\n viewId: source.viewOrTag,\n limit,\n })) as Array<{ id: string | number }>;\n return tickets.map((t) => ({ id: String(t.id), channel: 'gorgias' as const }));\n },\n\n async read(ref: ConversationRef) {\n // ONE fetch (B, T21 review): `getTicketWithContext`\n // (@wopilo/gorgias-client) reads `GET /tickets/:id/` once and derives\n // both the raw payload and the extracted context from that single\n // response — see `conversation-mapping.ts`'s module doc. This used to\n // be two separate actions hitting the same endpoint in parallel,\n // which not only doubled the round trips but let the two halves\n // observe different server states if a message landed between them.\n const result = (await api.integrations.run('gorgias', 'getTicketWithContext', {\n ticketId: ref.id,\n })) as { ticket: unknown; context: RawTicketContext } | null;\n return toConversation(ref, asRawTicket(result?.ticket), result?.context ?? { messages: [], customerContext: null });\n },\n };\n}\n\n// --- ReplyPort ---------------------------------------------------------------\n\n/**\n * `OutboundReply.idempotencyKey` is NOT forwarded: neither `replyEmail` nor\n * `postWhatsappNote` accept it (Gorgias has no idempotency-key concept — see\n * `ReplyPort.post`'s own doc, \"NOT by channel idempotence\"). At-most-once is\n * already guaranteed upstream by the claim→post→commit state machine (I9);\n * this field exists for a FUTURE channel that does support one.\n */\nexport function createGorgiasReplyPort(api: SupportKitApi): ReplyPort {\n return {\n async post(ref: ConversationRef, reply: OutboundReply) {\n if (reply.mode === 'email') {\n const result = (await api.integrations.run('gorgias', 'replyEmail', {\n ticketId: ref.id,\n bodyHtml: reply.bodyHtml,\n bodyText: reply.bodyText,\n senderEmail: reply.fromAddress,\n toAddress: reply.receiverEmail,\n ...(reply.subject !== null ? { subject: reply.subject } : {}),\n ...(reply.receiverName !== null ? { receiverName: reply.receiverName } : {}),\n })) as { messageId: string };\n return { messageId: result.messageId };\n }\n const result = (await api.integrations.run('gorgias', 'postWhatsappNote', {\n ticketId: ref.id,\n text: reply.bodyText,\n })) as { messageId: string };\n return { messageId: result.messageId };\n },\n };\n}\n\n// --- StatePort -----------------------------------------------------------\n\nexport function createGorgiasStatePort(api: SupportKitApi): StatePort {\n return {\n async record(ref, classification, audit) {\n const names = await resolveHandledTags(api, classification, audit);\n if (names.length === 0) return;\n await api.integrations.run('gorgias', 'applyTags', { ticketId: ref.id, names });\n },\n async rename(ref, subject) {\n await api.integrations.run('gorgias', 'renameTicket', { ticketId: ref.id, subject });\n },\n async flag(ref, tag) {\n const trimmed = tag.trim();\n if (!trimmed) return;\n await api.integrations.run('gorgias', 'applyTags', { ticketId: ref.id, names: [trimmed] });\n },\n };\n}\n\n// --- LlmPort ---------------------------------------------------------------\n\n/**\n * `ctx.api.llm.complete` v2 carries no `tool`-role message and no `tools`\n * parameter (S2's surface, `app-api-client.ts`) — §6.2's tool loop has no\n * platform surface to run on YET. This is NOT dead ground: `graph/draft.ts`\n * already calls `buildToolSpecs(profile)` and populates `CompletionRequest\n * .tools` on every round, and already pushes `role: 'tool'` turns once the\n * model asks for one. Nothing in `draft.ts` gates on this adapter's\n * capabilities — what currently keeps `req.tools` empty is\n * `settings/to-profile.ts` hardcoding `tools: []` (\"default-deny until\n * T22\"). The moment that allowlist is populated, `complete()` below would\n * silently drop `req.tools` (this surface has nothing to forward it to) and\n * this port would keep returning `toolCalls: []` regardless of what the\n * model was asked to use — the loop terminates on round one, degraded: no\n * order lookup, no tracking lookup, `Draft.sources` empty, every\n * provenance display blank, the most expensive node hallucinating order\n * facts instead of fetching them. Silently, with no error anywhere.\n *\n * `complete()` below refuses that outcome outright: a request that asks for\n * tools throws, naming the missing surface, so enabling the allowlist\n * degrades loudly (a thrown error) rather than loudly-nothing. See\n * docs/plans/2026-09-02-gorgias-migration-progress.md for the spec gap this\n * leaves for T22 / the spec owner to close (S2 needs a tools/toolCalls\n * surface, or draft's `maxToolCalls` needs to go).\n */\nfunction toPlatformMessage(msg: ChatMessage): { role: 'system' | 'user' | 'assistant'; content: string } {\n // Reachable only once `req.tools` stops being empty (the guard below\n // throws before that point today) — kept exhaustive over `ChatMessage`\n // for type safety, not because production traffic hits these branches.\n if (msg.role === 'tool') return { role: 'user', content: msg.content };\n if (msg.role === 'assistant') return { role: 'assistant', content: msg.content ?? '' };\n return { role: msg.role, content: msg.content };\n}\n\n/** S2's `trace`, as a named type so a handler can build one without reaching into `CompletionRequest`. */\nexport type RunTrace = NonNullable<CompletionRequest['trace']>;\n\n/**\n * `trace` is stamped on every completion this port makes, unless the request\n * carries its own. The legacy grouped one ticket's calls under a single\n * Langfuse session — draft, evaluation and revision read as one conversation\n * instead of a handful of orphan generations — which is what makes a trace\n * navigable when a correction has to be traced back to what produced it\n * (§3.4's quality loop). Omitting it keeps today's untraced behaviour.\n */\nexport function createPlatformLlmPort(api: SupportKitApi, trace?: RunTrace): LlmPort {\n return {\n async complete(req: CompletionRequest): Promise<CompletionResult> {\n // Mirrors `FakeLlm`: an already-aborted signal fails before the\n // platform is reached — `ctx.api.llm.complete` takes no `signal` of\n // its own (I14's deadline is enforced by `budget`/the caller instead).\n if (req.signal?.aborted) {\n throw Object.assign(new Error('Request was aborted.'), { name: 'AbortError' });\n }\n\n // Fail loudly rather than silently ground the model (see the module\n // doc above): `ctx.api.llm.complete` v2 has no tool-calling surface,\n // so honouring `req.tools` here would mean dropping it on the floor.\n if (req.tools?.length) {\n throw new Error(\n 'createPlatformLlmPort: ctx.api.llm.complete v2 has no tool-calling surface (no `tools` parameter, no `role: \\'tool\\'` message) — cannot honour CompletionRequest.tools.',\n );\n }\n\n // A per-request `trace` wins over the port's own: a node that names\n // its own session knows something this port does not.\n const runTrace = req.trace ?? trace;\n const result = await api.llm.complete({\n messages: req.messages.map(toPlatformMessage),\n options: {\n model: req.model,\n reasoningEffort: req.reasoning,\n ...(req.responseSchema !== undefined\n ? { responseSchema: { name: req.label, schema: req.responseSchema as Record<string, unknown> } }\n : {}),\n },\n // `req.promptRef` (including `resolve`, see `CompletionRequest.promptRef`'s\n // own doc) is forwarded WHOLESALE — every caller in this package now\n // sets `resolve: false`, so this pass-through needs no code change of\n // its own to carry the new field; it already carries whatever shape\n // `CompletionRequest.promptRef` has.\n ...(req.promptRef ? { promptRef: req.promptRef } : {}),\n ...(runTrace ? { trace: runTrace } : {}),\n });\n\n return {\n text: result.text ?? null,\n // No tool-calling support on this surface today — see the module\n // doc above.\n toolCalls: [],\n usage: { input: result.usage.inputTokens, output: result.usage.outputTokens, reasoning: 0 },\n ...(result.traceId ? { traceId: result.traceId } : {}),\n ...(result.observationId ? { observationId: result.observationId } : {}),\n };\n },\n };\n}\n\n// --- PromptPort (§3.7 seams) -------------------------------------------------\n\n/** `PlatformPromptReader` over T5's `ctx.api.prompts.get(name, {label|version, resolve:false})` (T19's seam). */\nexport function createPlatformPromptReader(api: SupportKitApi): PlatformPromptReader {\n return {\n async get(name, ref) {\n const detail = await api.prompts.get(name, { ...ref, resolve: false });\n return { version: detail.version, content: detail.content, config: detail.config ?? null };\n },\n };\n}\n\n/** `PromptCachePort` over the `prompt-cache` record (T20's schema, T19's seam). */\nexport function createRecordPromptCachePort(api: SupportKitApi): PromptCachePort {\n return {\n async read(key) {\n const page = await api.list('prompt-cache', { filter: { promptKey: key }, limit: 1 });\n const data = page.items[0]?.data as { content: string; version: number } | undefined;\n return data ? { content: data.content, version: data.version } : null;\n },\n async write(key, entry) {\n await api.upsert(\n 'prompt-cache',\n [{ data: { promptKey: key, content: entry.content, version: entry.version } }],\n { uniqueBy: ['promptKey'] },\n );\n },\n };\n}\n\n/**\n * Assembles the real `PromptPort`: T19's resolver over the two seams above,\n * with `onDegraded` routed to the caller's logger (post-T19-review E) — the\n * kit carries no logging port of its own, so a silent-degradation event\n * (Langfuse down, cache down, a broken composition tag) would otherwise be\n * indistinguishable from a correct run.\n */\nexport function createPlatformPromptPort(api: SupportKitApi, log: (message: string) => void): PromptPort {\n return createPromptResolver({\n platform: createPlatformPromptReader(api),\n cache: createRecordPromptCachePort(api),\n onDegraded: (event: PromptDegradedEvent) => log(`prompt resolution degraded [${event.stage}] ${event.name}: ${event.reason}`),\n });\n}\n\n// --- ClockPort ---------------------------------------------------------------\n\nexport function createRealClock(): ClockPort {\n return { now: () => new Date() };\n}\n","/**\n * Recording ports for the dry-run replay (spec §3.3 `adapters/\n * recording-ports.ts`, §3.5's `graph-dry-run` row), ported from legacy\n * `services/graphDryRun.ts`'s `meta`/`sink`/`reply`/`recordingGateway`.\n *\n * The guarantee (§0's arbitrage, restated in §3.5): dry-run replays the\n * COMPLETE graph — every node, LLM included — but reaches ZERO external\n * action. `ReplyPort.post` and `StatePort.record`/`rename`/`flag` are\n * replaced here by recorders that never call Gorgias; `ConversationPort`,\n * `LlmPort` and `PromptPort` stay the REAL `ctx-ports.ts` adapters — a dry\n * run reads and thinks for real, it just never writes.\n *\n * `state.record`'s READ half (the category's `extraTags`, via\n * `gorgias-tags.ts`) still runs for real, so `wouldHaveTagged` reports the\n * EXACT tag set production would apply — only the final `applyTags` call is\n * skipped, by construction (there is no write call left to make).\n */\nimport type { AuditTags, CompletionRequest, LlmPort, OutboundReply, ReplyPort, StatePort, ToolCallRequest } from '../graph/ports';\nimport type { Classification, Usage } from '../domain';\nimport type { NodeDeps } from '../graph/state';\nimport type { SupportKitApi } from './api';\nimport { resolveHandledTags } from './gorgias-tags';\n\n// --- ReplyPort ---------------------------------------------------------------\n\nexport interface WouldHaveReplied {\n subject: string | null;\n body: string;\n}\n\nexport interface RecordingReplyPort {\n port: ReplyPort;\n /** The reply the run WOULD have posted, or `null` if `act` never ran. Nothing was posted. */\n wouldHaveReplied(): WouldHaveReplied | null;\n}\n\nexport function createRecordingReplyPort(): RecordingReplyPort {\n let wouldHaveReplied: WouldHaveReplied | null = null;\n return {\n port: {\n async post(_ref, reply: OutboundReply) {\n wouldHaveReplied = { subject: reply.mode === 'email' ? reply.subject : null, body: reply.bodyText };\n // A message id `act` can commit — nothing left the building.\n return { messageId: 'dry-run' };\n },\n },\n wouldHaveReplied: () => wouldHaveReplied,\n };\n}\n\n// --- StatePort -----------------------------------------------------------\n\nexport interface RecordingStatePort {\n port: StatePort;\n /** Tags the run WOULD have applied, in first-seen order. Nothing was applied. */\n wouldHaveTagged(): string[];\n}\n\nexport function createRecordingStatePort(api: SupportKitApi): RecordingStatePort {\n const tagged: string[] = [];\n const push = (tag: string): void => {\n const trimmed = tag.trim();\n if (trimmed && !tagged.includes(trimmed)) tagged.push(trimmed);\n };\n\n return {\n port: {\n async record(_ref, classification: Classification, audit: AuditTags) {\n const names = await resolveHandledTags(api, classification, audit);\n names.forEach(push);\n },\n async rename() {\n // A dry run renames nothing.\n },\n async flag(_ref, tag) {\n push(tag);\n },\n },\n wouldHaveTagged: () => [...tagged],\n };\n}\n\n// --- SendPort recorder (claim -> post -> commit persistence seam, I9) ------\n\ntype ClaimedSend = Extract<NodeDeps['send'], { mode: 'claimed' }>;\n\nexport interface RecordingSendPort {\n send: ClaimedSend;\n /** Every claim/commit call, in order — a dry run must never let these reach real persistence. */\n calls: Array<{ surface: 'send.claim' | 'send.commit'; args: readonly unknown[] }>;\n}\n\n/**\n * Recording `{mode: 'claimed'}` seam (post-T21-review C): when a production\n * dry run wires `deps.send` to `{mode: 'claimed'}` (the `act` node's own\n * gate — see its module doc), THIS package had no recording counterpart, so\n * nothing stopped that dry run's claim/commit calls from writing real rows.\n * `claim` always resolves `true` (a dry run never loses a contest — there is\n * nothing to contest), `commit` no-ops: neither touches persistence.\n */\nexport function createRecordingSendPort(): RecordingSendPort {\n const calls: RecordingSendPort['calls'] = [];\n return {\n calls,\n send: {\n mode: 'claimed',\n async claim(run) {\n calls.push({ surface: 'send.claim', args: [run] });\n return true;\n },\n async commit(messageId) {\n calls.push({ surface: 'send.commit', args: [messageId] });\n },\n },\n };\n}\n\n// --- The pair a production dry run substitutes ------------------------------\n\n/**\n * Swaps the two ports that can reach Gorgias — `reply` and `state` — for\n * their recorders, leaving every READ port (conversation, llm, prompt) and\n * the clock untouched.\n *\n * This is the `settings.dryRun` seam for the PRODUCTION pipeline\n * (`functions/triage-tick.ts`, `functions/process-response.ts`), where the\n * recorded output is deliberately dropped: those handlers report through\n * their records and their run, not through a `wouldHaveTagged()` payload —\n * only the \"never write to Gorgias\" half of the recorders matters there.\n * The `uiInvoke` dry runs that DO read the recordings back\n * (`functions/graph-dry-run-core.ts`) keep wiring the recorders themselves.\n */\nexport function withRecordingWritePorts<T extends { reply: ReplyPort; state: StatePort }>(ports: T, api: SupportKitApi): T {\n return { ...ports, reply: createRecordingReplyPort().port, state: createRecordingStatePort(api).port };\n}\n\n// --- LlmPort recorder (still a REAL call — only its trace is captured) -----\n\n/** One LLM call, as a dry-run page would show it: what was asked, what came back, what it cost. */\nexport interface RecordedCompletion {\n label: string;\n model: string;\n reasoning: string;\n messages: CompletionRequest['messages'];\n toolsOffered: string[];\n text: string | null;\n toolCalls: Array<{ name: string; arguments: Record<string, unknown> }>;\n usage: Usage;\n traceId: string | null;\n durationMs: number;\n error?: string;\n}\n\nexport interface RecordingLlmPort {\n port: LlmPort;\n completions: RecordedCompletion[];\n}\n\nfunction toRecordedToolCalls(calls: ToolCallRequest[]): Array<{ name: string; arguments: Record<string, unknown> }> {\n return calls.map((c) => ({ name: c.name, arguments: c.arguments }));\n}\n\n/** Wraps a REAL `LlmPort` (the LLM still runs — §3.5's \"LLM compris\") and records every completion. */\nexport function createRecordingLlmPort(llm: LlmPort): RecordingLlmPort {\n const completions: RecordedCompletion[] = [];\n return {\n completions,\n port: {\n async complete(req: CompletionRequest) {\n const startedAt = Date.now();\n const entry: RecordedCompletion = {\n label: req.label,\n model: req.model,\n reasoning: req.reasoning,\n messages: req.messages,\n toolsOffered: (req.tools ?? []).map((t) => t.name),\n text: null,\n toolCalls: [],\n usage: { input: 0, output: 0, reasoning: 0 },\n traceId: null,\n durationMs: 0,\n };\n completions.push(entry);\n try {\n const result = await llm.complete(req);\n entry.text = result.text;\n entry.toolCalls = toRecordedToolCalls(result.toolCalls);\n entry.usage = result.usage;\n entry.traceId = result.traceId ?? null;\n return result;\n } catch (err) {\n entry.error = err instanceof Error ? err.message : String(err);\n throw err;\n } finally {\n entry.durationMs = Date.now() - startedAt;\n }\n },\n },\n };\n}\n","/**\n * `SupportKitHandlerContext` — `AppHandlerContext` (`@apotech-os/app-kit`,\n * `handler.ts`) narrowed to `api: SupportKitApi` instead of the concrete\n * `AppApiClient` class.\n *\n * Same reasoning as `SupportKitApi` itself (T21/T22, `adapters/api.ts`): a\n * real `AppHandlerContext` built by the platform carries a real\n * `AppApiClient`, which is a structural superset of `SupportKitApi`, so it\n * is always assignable here — but a unit test can build `ctx.api` as a plain\n * object instead of a live HTTP client.\n *\n * Also the shared home (T22 hardening, E) for the bits every one of the four\n * pipeline handlers otherwise hand-copied: `getOptional` (a 404 read is an\n * ordinary \"not there\" outcome, not a thrown error, for every handler that\n * dereferences a possibly-stale record id), `DEFAULT_MAX_TOOL_CALLS` (the\n * `draft` node's tool budget when `nodes.draft.maxToolCalls` is unset), and\n * `buildTicketPorts` (the six-line `NodeDeps.ports` assembly `triage-tick`/\n * `process-response`/`handle-approval` each wrote out by hand, byte-for-byte\n * identical).\n */\nimport type { AppApiRecord, AppHandlerContext } from '@apotech-os/app-kit';\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { SupportKitApi } from '../adapters/api';\nimport {\n createGorgiasConversationPort,\n createGorgiasReplyPort,\n createGorgiasStatePort,\n createPlatformLlmPort,\n createPlatformPromptPort,\n createRealClock,\n type RunTrace,\n} from '../adapters/ctx-ports';\n\nexport type SupportKitHandlerContext = Omit<AppHandlerContext, 'api'> & { api: SupportKitApi };\n\n/** The `draft` node's tool budget when `nodes.draft.maxToolCalls` is unset (§3.6). */\nexport const DEFAULT_MAX_TOOL_CALLS = 5;\n\n/**\n * Reads `objectKey/id`, returning `null` on a 404 (a dangling relation or an\n * already-deleted record) instead of throwing — the shape every handler here\n * wants when dereferencing an id it did not just create itself. `id: null`\n * short-circuits to `null` without a round trip, for the optional relations\n * (`categoryId`, `agentId`) that may never have been set.\n */\nexport async function getOptional(ctx: SupportKitHandlerContext, objectKey: string, id: string | null): Promise<AppApiRecord | null> {\n if (!id) return null;\n try {\n return await ctx.api.get(objectKey, id);\n } catch (err) {\n if (err instanceof AppApiError && err.status === 404) return null;\n throw err;\n }\n}\n\n/**\n * The `NodeDeps.ports` bundle every handler that runs a ticket through the\n * graph needs — one real Gorgias/platform wiring, reused instead of re-typed\n * per call site.\n *\n * `trace` groups every completion of the run under one Langfuse session\n * (`RunTrace`); a handler that omits it gets today's untraced behaviour.\n */\nexport function buildTicketPorts(ctx: SupportKitHandlerContext, trace?: RunTrace) {\n return {\n conversation: createGorgiasConversationPort(ctx.api),\n reply: createGorgiasReplyPort(ctx.api),\n llm: createPlatformLlmPort(ctx.api, trace),\n prompt: createPlatformPromptPort(ctx.api, (message) => ctx.logger.warn(message)),\n state: createGorgiasStatePort(ctx.api),\n clock: createRealClock(),\n };\n}\n","/**\n * Whether a `generated-response{status:'pending'}` row is worth creating\n * for a just-triaged ticket (§3.5's \"si éligible, création generated-\n * response{status:'pending'}\").\n *\n * §3.5 does not spell out \"eligible\" — this is `triage-tick`'s own reading,\n * chosen to NEVER DRIFT from what `process-response`'s `runTicket(deps,\n * {resume})` would decide with the SAME classification: it calls the EXACT\n * SAME predicates `run-ticket.ts` branches on right after its own triage\n * phase (`isConversationOver`/`isFallbackClassification`/`hasNoDraftNode`,\n * exported from there — T22 hardening, so this can no longer silently drift\n * the way a hand-copied mirror could), up to (but not including)\n * `channelPreGates`/the WhatsApp not-our-turn check — those need a FRESH\n * conversation read to evaluate, which `triage-tick` does not have (and\n * should not pay for) at classification time. Any ticket this function\n * calls \"eligible\" that later turns out to hit a pre-gate is still\n * perfectly safe: `process-response` runs the real sequence and writes\n * whatever real outcome results, `triage-tick`'s job is only to avoid\n * paying for a draft that could NEVER have produced one — an escalated,\n * closed, or fallback-classified ticket.\n *\n * PER-CATEGORY OPT-IN (B3): the gate above is about what the graph COULD\n * produce; this one is about what the tenant ASKED for. §3.4's `category`\n * record carries `fastResponseEnabled` and `agentId` (with the cross\n * validation `fastResponseEnabled ⇒ agentId`), and the legacy enqueued a\n * fast-response job only for `matched && matched.fast_response_enabled &&\n * matched.agent` (`backoffice/src/services/triage.ts`). Nobody read those\n * fields here, so EVERY triable ticket paid a drafting — and then an\n * evaluation — LLM call, including for categories explicitly left out and\n * for tickets whose classification matched no category at all (drafted with\n * whatever the default agent happened to be). An unmatched or non-opted-in\n * category now stops at triage, as it did before the migration.\n *\n * ESCALATION (B3, connected decision): the legacy made this skip\n * CONDITIONAL on `profile.nodes.escalate.skipsFastResponse` — an escalated\n * ticket was still enqueued when that flag was off. That setting is gone\n * rather than restored: `graph/run-ticket.ts` finishes UNCONDITIONALLY on\n * `s.escalated` (`if (s.escalated) return finish(s, deps, 'escalated')`),\n * so a row created for an escalated ticket could never be fulfilled by\n * `process-response` — it would only ever be a pending row expiring on its\n * TTL. Honouring the flag would require re-opening that graph decision,\n * which §3.3 settled the other way; keeping it mapped-but-unread was the\n * worse of the three options.\n */\nimport type { Classification } from '../domain';\nimport type { AgentProfile } from '../domain/profile';\nimport { hasNoDraftNode, isConversationOver, isFallbackClassification } from '../graph/run-ticket';\nimport type { CategoryRecord } from './records';\n\nexport function isEligibleForGeneratedResponse(\n profile: AgentProfile,\n classification: Classification,\n escalated: boolean,\n category: CategoryRecord | null,\n): boolean {\n if (!category || !category.fastResponseEnabled || !category.agentId) return false;\n if (escalated) return false;\n if (isConversationOver(classification)) return false;\n if (isFallbackClassification(classification)) return false;\n if (hasNoDraftNode(profile)) return false;\n return true;\n}\n","/**\n * A `ToolContext` that refuses every call — used where `NodeDeps` requires\n * one but `AgentProfile.tools` is always `[]` (T22 leaves the §6.2 tool\n * allowlist at default-deny, see `settings/to-profile.ts`'s own doc: nothing\n * in `settingsToProfile` populates it, and `createPlatformLlmPort` throws on\n * a non-empty `CompletionRequest.tools` before ever reaching a provider).\n * With no tool ever exposed to the model, `draft` never calls this — these\n * throws are a loud, defensive backstop against that assumption silently\n * breaking, not a code path anything is expected to take today.\n */\nimport type { ToolContext } from '../graph/ports';\n\nfunction refuse(name: string): never {\n throw new Error(`no-tool-context: \"${name}\" called, but this pipeline configures no tools (profile.tools is always []).`);\n}\n\nexport function createNoToolContext(): ToolContext {\n return {\n getOrder: () => refuse('getOrder'),\n getTracking: () => refuse('getTracking'),\n searchKnowledge: () => refuse('searchKnowledge'),\n findSimilarTickets: () => refuse('findSimilarTickets'),\n };\n}\n","/**\n * The `pipeline-state` singleton (§3.4, `records/pipeline-state.ts`) —\n * shared reader/writer for `triage-tick` and `sweep`, the only two callers\n * (T22 hardening, A4). Both used to hand-roll their own `toDate`/\n * `readPipelineState`, byte-identical between the two files, and each wrote\n * with an independent `list()` + `create()`-or-`update()` pair with no\n * ordering guarantee between them — see `records/pipeline-state.ts`'s own\n * doc for why that raced two crons on a fresh app. Routing both functions\n * through the ONE reader here, and through `upsertPipelineState`'s\n * `singletonKey`-keyed `upsert`, is what makes \"exactly one row\" the\n * platform's own constraint instead of a hope.\n */\nimport type { AppApiRecord } from '@apotech-os/app-kit';\nimport type { SupportKitApi } from '../adapters/api';\n\n/** Always the same value — the field the record's unique index is built on. */\nexport const PIPELINE_STATE_SINGLETON_KEY = 'default';\n\nexport function toDate(value: unknown): Date | null {\n if (!value) return null;\n const date = value instanceof Date ? value : new Date(value as string);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\n/** The singleton `pipeline-state` row, or `null` if it has never been written. */\nexport async function readPipelineState(api: SupportKitApi): Promise<AppApiRecord | null> {\n const page = await api.list('pipeline-state', { filter: { singletonKey: PIPELINE_STATE_SINGLETON_KEY }, limit: 1 });\n return page.items[0] ?? null;\n}\n\n/**\n * Merges `patch` onto the singleton row, creating it on the first call. Both\n * `triage-tick` and `sweep` only ever set a slice of the record's fields\n * (`sourceViewId`+`lastTriageAt`, `lastSweepAt`) — `upsert`'s `ON CONFLICT\n * DO UPDATE` merges those onto whatever the other cron already wrote, the\n * same merge semantics `update()` already gives every other record in this\n * package.\n */\nexport async function upsertPipelineState(api: SupportKitApi, patch: Record<string, unknown>): Promise<void> {\n await api.upsert('pipeline-state', [{ data: { singletonKey: PIPELINE_STATE_SINGLETON_KEY, ...patch } }], {\n uniqueBy: ['singletonKey'],\n });\n}\n","/**\n * `triage-tick` (§3.5) — cron function. Classifies every pending ticket on\n * the claimed Gorgias view and, per ticket, materialises what `runTicket(deps,\n * {until:'triage'})` deliberately leaves unwritten (see that option's own\n * doc in `graph/run-ticket.ts`): the `triage-decision` row, the deduplicated\n * tag application, and — when eligible — a `generated-response{status:\n * 'pending'}` row for `process-response` to pick up.\n *\n * WRITE ORDER (T22 hardening, A2): the `triage-decision` row is written\n * BEFORE the Gorgias tags are applied, not after. A duplicate tag apply on a\n * retried/re-run ticket is idempotent (`dedupeTagNames`, `gorgias-tags.ts`);\n * a lost `triage-decision` is not — and if the claimed view filters on the\n * `handledTag` this tag step applies, a ticket tagged with no decision row\n * behind it never comes back into view again, so the classification the LLM\n * call already paid for would be lost OUTRIGHT, not merely re-billed. The\n * decision-first order means the ONLY window left where a crash can still\n * lose a classification is between `runTicket`'s checkpoint returning and\n * THIS row landing — everything after that point (the tag apply, the\n * `generated-response` create) is either idempotent or independently\n * recoverable.\n *\n * CRASH WINDOW that remains (documented, not fully closed — see the\n * module's own final report): `runTicket`'s own doc states it plainly — a\n * checkpointed run never calls `ports.state.record`, so the classification\n * only lives in the RETURNED `TicketRunState` until this function writes it\n * down. If the process dies between the checkpoint returning and the\n * `triage-decision` write above, that LLM call's result is lost with\n * nothing left to reconstruct it from — the ticket is simply re-classified\n * (and re-billed) on the next tick. This is the same trade-off `runTicket`'s\n * doc already names as \"iso-legacy and harmless today\"; nothing in T22\n * changes it.\n *\n * DRY RUN (B1): `settings.dryRun` was a declared, advertised, DEAD setting —\n * no handler read it, so the very first `triageEnabled` activation of the\n * spec's §6 switchover order (\"activate in `dryRun`, control the parity,\n * then `dryRun` off\") tagged and renamed REAL Gorgias tickets. It is read\n * here now, and it substitutes the two write ports (`reply`, `state`) for\n * the recorders of `adapters/recording-ports.ts`: the graph still runs in\n * FULL, LLM included (§0's arbitrage), it simply reaches no external action.\n *\n * What a trial tick still WRITES, deliberately: the `triage-decision` and\n * the `generated-response` rows, exactly as a live tick would. §6 asks the\n * operator to \"control the decisions\" before turning `dryRun` off — with no\n * rows there is nothing to control, and the Pipeline/Escalades pages would\n * show an empty trial. They are identifiable as a trial's through the\n * application run they carry the `runId` of, which is stamped\n * `metadata.dryRun: true` below (the record schemas are frozen by §3.4, so\n * the marker lives on the run, not on a new column). A trial row therefore\n * describes what production WOULD have done — `subjectRenamed: true` on a\n * dry run means \"the subject matched and would have been rewritten\",\n * nothing was sent to Gorgias.\n *\n * PER-TICKET ISOLATION (T22 hardening, A1): one failing ticket no longer\n * aborts the rest of the batch. `retries: 0` on this function (see the\n * manifest fragment below) means a tick that dies partway has no recovery —\n * tickets already processed dropped off the claimed view (their `handledTag`\n * is applied), so the NEXT tick would hit the same poison ticket first and\n * die at the same place, forever, while `lastTriageAt` was never stamped\n * (also re-billing every ticket the dead tick DID manage to finish). Each\n * ticket's own error is caught, logged, and recorded as a `triage-decision\n * {status:'error'}` row for that ticket alone; the loop moves on, and\n * `lastTriageAt` is stamped in a `finally` so the cadence gate always\n * advances once the batch has been attempted, degraded ticket or not.\n */\nimport type { AppApiRecord, AppHandler, FunctionDef } from '@apotech-os/app-kit';\nimport { AppApiError } from '@apotech-os/app-kit';\nimport { createBudget } from '../graph/budget';\nimport { runTicket } from '../graph/run-ticket';\nimport type { ConversationRef } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport { createRealClock } from '../adapters/ctx-ports';\nimport { withRecordingWritePorts } from '../adapters/recording-ports';\nimport { openTicketKeyFor } from '../status/machine';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { isEligibleForGeneratedResponse } from './eligibility';\nimport { createNoToolContext } from './no-tool-context';\nimport { readPipelineState, toDate, upsertPipelineState } from './pipeline-state';\nimport {\n buildPromptsTable,\n draftPromptRefFor,\n findCategoryByTag,\n listCategories,\n resolveDraftAgent,\n toCategoryReferential,\n} from './records';\n\n/**\n * The manifest fragment (§3.5's table row): every 5 minutes, no retries (a\n * failed tick is superseded by the next one 5 minutes later — retrying it\n * would just re-run against a possibly-already-advanced view), one run at a\n * time, and a warning alert on failure so an operator notices a stuck\n * pipeline. Cron has no timezone field in this schema (`FunctionTriggerSchema`,\n * `@apotech-os/app-kit` `contracts.ts`) — Europe/Paris from the spec table\n * has nowhere to go here; see this task's final report for that gap.\n */\nexport function buildTriageTickFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'triage-tick'),\n name: 'triage-tick',\n trigger: { type: 'cron', pattern: '*/5 * * * *' },\n retries: 0,\n concurrency: 1,\n notify: { onFailure: true, severity: 'warning' },\n };\n}\n\nexport function createTriageTickHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx) => triageTickHandler(ctx, config);\n}\n\nexport async function triageTickHandler(ctx: SupportKitHandlerContext, config: SupportKitFunctionConfig): Promise<void> {\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n ctx.logger.info('triage-tick: settings invalid, skipping', { issues });\n return;\n }\n if (!settings.triageEnabled) {\n ctx.logger.info('triage-tick: triageEnabled is off, skipping');\n return;\n }\n if (!settings.sourceViewId) {\n ctx.logger.info('triage-tick: no sourceViewId configured, skipping');\n return;\n }\n\n const clock = createRealClock();\n const now = clock.now();\n\n const pipelineState = await readPipelineState(ctx.api);\n const lastTriageAt = toDate(pipelineState?.data.lastTriageAt);\n if (lastTriageAt) {\n const dueAt = lastTriageAt.getTime() + settings.triageIntervalMinutes * 60_000;\n if (now.getTime() < dueAt) {\n ctx.logger.info('triage-tick: not due yet, skipping');\n return;\n }\n }\n\n await runTriageBatch(ctx, config, settings);\n}\n\n/**\n * The batch itself — every `triage-tick` guard (settings validity,\n * `triageEnabled`, `sourceViewId`, the cadence gate) has already returned by\n * the time this runs. Extracted (T23) so `run-triage-now`\n * (`functions/run-triage-now.ts`, §3.5's \"déclenchement manuel\") can run the\n * EXACT same batch on demand, bypassing only the cadence gate above — not a\n * second, independently-drifting copy of `listPending` → per-ticket triage →\n * `triage-decision` → `generated-response`.\n */\nexport async function runTriageBatch(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n settings: SupportKitSettings,\n): Promise<{ ticketCount: number; failureCount: number }> {\n const dryRun = settings.dryRun === true;\n const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx), ctx.api) : buildTicketPorts(ctx);\n\n const categories = await listCategories(ctx.api);\n // Draft agent for the WHOLE batch's profile — a placeholder until each\n // ticket's own category is known (see `records.ts`'s doc on\n // `resolveDraftAgent`). The per-ticket agent used on the created\n // `generated-response` row is resolved again below, after triage.\n const batchDefaultAgent = await resolveDraftAgent(ctx.api, null);\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(batchDefaultAgent, config), settings.nodes));\n\n const refs = await ports.conversation.listPending({ viewOrTag: settings.sourceViewId }, settings.batchLimit);\n\n // §3.5's \"run applicatif\" (T22 hardening, D): one run per tick, threaded\n // onto every `triage-decision` this tick writes (`runId` below) instead of\n // each decision minting its own `crypto.randomUUID()` — an operator can\n // now group a tick's decisions, or find the tick itself, in the platform\n // run history. Started only once we know there is real work to do (the\n // cadence/settings guards above already returned): a skipped tick has\n // nothing to report a run for.\n const run = await ctx.api.runs.start({\n kind: 'triage-tick',\n message: `${dryRun ? 'Dry-run triage tick' : 'Triage tick'} over ${refs.length} ticket(s)`,\n metadata: { sourceViewId: settings.sourceViewId, ticketCount: refs.length, dryRun },\n });\n\n let failureCount = 0;\n try {\n for (const ref of refs) {\n try {\n await processOneTicket(ctx, ref, {\n profile,\n categories,\n ports,\n runId: run.id,\n });\n } catch (err) {\n failureCount += 1;\n const message = err instanceof Error ? err.message : String(err);\n ctx.logger.error(`triage-tick: ticket ${ref.id} failed, continuing with the rest of the batch`, { error: message });\n try {\n await ctx.api.create('triage-decision', {\n ticketId: ref.id,\n decidedAt: ports.clock.now(),\n status: 'error',\n error: message,\n confidence: 'low',\n runId: run.id,\n subjectRenamed: false,\n });\n } catch (writeErr) {\n ctx.logger.error(`triage-tick: failed to record the error decision for ticket ${ref.id}`, {\n error: writeErr instanceof Error ? writeErr.message : String(writeErr),\n });\n }\n }\n }\n await ctx.api.runs.succeed(run.id, { ticketCount: refs.length, failureCount });\n } catch (err) {\n await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });\n throw err;\n } finally {\n // Stamped regardless of per-ticket failures (A1): the cadence gate must\n // advance once the batch has been ATTEMPTED, not only once every ticket\n // in it succeeded — otherwise a single poison ticket would keep\n // `lastTriageAt` frozen and every OTHER ticket in the batch would be\n // re-billed on the next tick too. Also stamped on a `run-triage-now`\n // manual batch, on purpose: it advances the SAME cadence gate\n // `triage-tick` reads, so a manual run just before a scheduled tick is\n // due does not immediately trigger a redundant second pass over the\n // same tickets.\n await upsertPipelineState(ctx.api, { sourceViewId: settings.sourceViewId, lastTriageAt: ports.clock.now() });\n }\n\n return { ticketCount: refs.length, failureCount };\n}\n\ninterface TickDeps {\n profile: ReturnType<typeof settingsToProfile>;\n categories: Awaited<ReturnType<typeof listCategories>>;\n ports: ReturnType<typeof buildTicketPorts>;\n runId: string;\n}\n\nasync function processOneTicket(ctx: SupportKitHandlerContext, ref: ConversationRef, deps: TickDeps): Promise<void> {\n const { profile, categories, ports, runId } = deps;\n\n // Optional rename (§3.6's `renameEnabled`/`renameFrom`/`renameTo`) — no\n // node in the graph performs it (see this module's own header doc), so it\n // is done here, once, before triage. `runTicket` re-reads the conversation\n // itself right after (`fetchContext`'s own \"always re-read\" contract) —\n // paying for one extra read here is the same trade-off the whole pipeline\n // already makes at every resume boundary.\n let subjectRenamed = false;\n if (profile.rename) {\n const conversation = await ports.conversation.read(ref);\n const subject = conversation.subject ?? '';\n if (subject.includes(profile.rename.from)) {\n await ports.state.rename(ref, subject.replace(profile.rename.from, profile.rename.to));\n subjectRenamed = true;\n }\n }\n\n const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n\n const state = await runTicket(\n {\n ref,\n profile,\n ports: { ...ports },\n toolContext: createNoToolContext(),\n budget,\n // Unknown until triage runs — no node reached in the `until:'triage'`\n // phase reads `deps.category` (`run-ticket.ts`'s early return happens\n // before any node touches it).\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: toCategoryReferential(categories),\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'none' },\n },\n { until: 'triage' },\n );\n\n if (!state.classification) {\n await ctx.api.create('triage-decision', {\n ticketId: ref.id,\n decidedAt: ports.clock.now(),\n status: 'error',\n error: 'triage produced no classification',\n confidence: 'low',\n runId,\n subjectRenamed,\n });\n return;\n }\n\n const { classification } = state;\n const category = findCategoryByTag(categories, classification.category);\n\n // Decision FIRST, tags SECOND (A2 — see this module's header doc for why\n // the order was inverted).\n const decision = await ctx.api.create('triage-decision', {\n ticketId: ref.id,\n decidedAt: ports.clock.now(),\n categoryId: category?.id ?? null,\n tag: classification.category,\n confidence: classification.confidence,\n reasoning: classification.reasoning,\n conversationOver: classification.conversationOver ?? false,\n escalated: state.escalated,\n status: 'ok',\n runId,\n subjectRenamed,\n });\n\n // The dedup+single-`applyTags` call §3.5 asks for already lives in\n // `StatePort.record` (`adapters/gorgias-tags.ts`'s `resolveHandledTags`) —\n // nothing to reimplement here beyond calling the port.\n await ports.state.record(ref, classification, profile.audit);\n\n // The category matched above is passed along, not re-read: §3.4's\n // `fastResponseEnabled`/`agentId` opt-in is half of what \"eligible\" means\n // (B3 — see `eligibility.ts`).\n if (!isEligibleForGeneratedResponse(profile, classification, state.escalated, category)) return;\n\n const draftAgent = await resolveDraftAgent(ctx.api, category?.agentId ?? null);\n const conversation = state.conversation;\n const channel = conversation?.sourceChannel === 'whatsapp' ? 'whatsapp' : 'email';\n const generatedAt = ports.clock.now();\n const expiresAt = new Date(generatedAt.getTime() + profile.schedule.fastResponseTtlMinutes * 60_000);\n\n try {\n await ctx.api.create('generated-response', {\n ticketId: ref.id,\n openTicketKey: openTicketKeyFor('pending', ref.id),\n status: 'pending',\n triageDecisionId: decision.id,\n categoryId: category?.id ?? null,\n agentId: draftAgent?.id ?? null,\n channel,\n generatedAt,\n expiresAt,\n sources: [],\n tracedInput: [],\n guardrailHits: [],\n servedTo: [],\n servedCount: 0,\n followupRequired: false,\n });\n } catch (err) {\n // §3.5: \"conflit d'unicité openTicketKey ⇒ ignoré, idempotent\" — another\n // tick (or a stray retry) already opened one for this ticket.\n if (err instanceof AppApiError && err.status === 409) {\n ctx.logger.debug(`triage-tick: generated-response already pending for ticket ${ref.id}, skipping`);\n return;\n }\n throw err;\n }\n}\n","/**\n * `buildSendSeam` — the ONE claim→post→commit persistence seam (I9) shared\n * by `process-response` (claims a `pending` row) and `handle-approval`\n * (claims a `ready` row after an operator approves). §8.4 demands a single\n * send path, not two independently-written ones: this is where that demand\n * actually lives at the persistence layer — both callers hand this function\n * their own `fromStatus` and get back the exact same `NodeDeps.send`\n * shape `act` drives.\n *\n * `assertTransition` runs BEFORE the write attempt (`status/machine.ts`'s own\n * doc): it is a local, in-process sanity check, distinct from the `ifMatch`\n * race below it, which is what actually decides which of two concurrent\n * claimants wins.\n *\n * A 409 from `api.update` is NOT an error here — §3.4/§8.4 read it as \"the\n * other worker already claimed this row\", the ordinary losing side of a\n * race. Any other rejection propagates so Inngest can retry the run.\n */\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { Draft, Verdict } from '../domain';\nimport type { ClockPort } from '../graph/ports';\nimport { assertTransition, openTicketKeyFor, type GeneratedResponseStatus } from '../status/machine';\nimport type { SupportKitApi } from '../adapters/api';\n\nexport interface SendSeam {\n claim: (run: { draft: Draft; verdict: Verdict | null }) => Promise<boolean>;\n commit: (messageId: string) => Promise<void>;\n}\n\nexport interface BuildSendSeamParams {\n api: SupportKitApi;\n clock: ClockPort;\n id: string;\n ticketId: string;\n /** The status this claim moves FROM — `'pending'` for `process-response`, `'ready'` for `handle-approval`. */\n fromStatus: Extract<GeneratedResponseStatus, 'pending' | 'ready'>;\n /**\n * Extra fields persisted on the SAME atomic claim write. `process-response`\n * uses this to persist the draft/verdict it just produced (the row had\n * none yet); `handle-approval` needs nothing extra — the row already\n * carries `responseText`/`verdict` from when it was drafted.\n */\n extraClaimData?: (run: { draft: Draft; verdict: Verdict | null }) => Record<string, unknown>;\n}\n\nexport function buildSendSeam(params: BuildSendSeamParams): SendSeam {\n const { api, clock, id, ticketId, fromStatus, extraClaimData } = params;\n\n return {\n async claim(run) {\n assertTransition(fromStatus, 'sending');\n try {\n await api.update(\n 'generated-response',\n id,\n {\n status: 'sending',\n sendingAt: clock.now(),\n openTicketKey: openTicketKeyFor('sending', ticketId),\n ...(extraClaimData ? extraClaimData(run) : {}),\n },\n { ifMatch: { status: fromStatus } },\n );\n return true;\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) return false;\n throw err;\n }\n },\n\n async commit(messageId) {\n assertTransition('sending', 'sent');\n await api.update(\n 'generated-response',\n id,\n {\n status: 'sent',\n sentAt: clock.now(),\n sentMessageId: messageId,\n openTicketKey: openTicketKeyFor('sent', ticketId),\n },\n { ifMatch: { status: 'sending' } },\n );\n },\n };\n}\n","/**\n * The `generated-response:<id>[:suffix]` key shape used by BOTH the\n * `ApprovalRequest.key`/`ApprovalDecidedPayload.key` pair (`process-response`\n * requests, `handle-approval` parses) and the `InboxAlert.key`s\n * `process-response`/`sweep` raise. Shared here so the format can never\n * drift between writers — hand-rolling the same template string twice (or\n * three times) is exactly the kind of duplication that quietly breaks the\n * moment one side changes.\n */\nconst PREFIX = 'generated-response:';\n\n/** The approval key for one `generated-response` row. */\nexport function buildApprovalKey(generatedResponseId: string): string {\n return `${PREFIX}${generatedResponseId}`;\n}\n\n/** The `generated-response` id encoded in `key`, or `null` if `key` isn't one of ours. */\nexport function parseApprovalKey(key: string): string | null {\n if (!key.startsWith(PREFIX)) return null;\n const id = key.slice(PREFIX.length);\n return id.length > 0 ? id : null;\n}\n\n/**\n * The `InboxAlert.key` for one `generated-response` row, optionally\n * suffixed (`sweep`'s `stalled-send` alert vs. `process-response`'s plain\n * `needs_human` one) — same PREFIX as the approval key above, on purpose:\n * both name the same underlying record, in a different platform surface.\n * Added alongside `buildApprovalKey` for the same reason that one exists:\n * `process-response` and `sweep` were each hand-rolling this template\n * string in a slightly different shape, two lines after importing\n * `buildApprovalKey` to avoid doing exactly that for the approval key.\n */\nexport function buildInboxKey(generatedResponseId: string, suffix?: string): string {\n return suffix ? `${PREFIX}${generatedResponseId}:${suffix}` : `${PREFIX}${generatedResponseId}`;\n}\n","/**\n * `process-response` (§3.5) — dbEvent function, triggered on\n * `generated-response{status:'pending'}` created. Resumes `runTicket` past\n * triage (`resume: {classification, escalated}`, reconstructed from the\n * `triage-decision` row) and persists whatever terminal outcome results.\n *\n * The dbEvent payload (`apps/api/src/platform-data/app-inngest-functions.ts`'s\n * `DbEventPayload`) carries only `{appSlug, objectKey, recordId,\n * updatedFields?, before?}` — never the record itself — so this handler's\n * first move is always its own `ctx.api.get('generated-response', recordId)`.\n *\n * DRY RUN (B1): `settings.dryRun` was read by NO handler — this one drafted\n * and, whenever auto-send was eligible, actually replied to the customer,\n * trial mode or not. It is read here now: the two write ports (`reply`,\n * `state`) are swapped for `adapters/recording-ports.ts`'s recorders and\n * `send` is forced to `{mode: 'none'}`, so the graph runs in FULL (LLM\n * included, §0's arbitrage) and reaches no external action. A trial run that\n * would have sent therefore comes back with `outcome: 'sent'` having sent\n * nothing, and is persisted as `ready` — the draft stays visible for §6's\n * parity control, and `ready` is the one status that says \"a human owns this\n * text now\". `awaiting_approval` raises no approval in a trial: granting one\n * would hand `handle-approval` a real send to perform.\n *\n * The claim→post→commit send seam (`functions/claim-commit.ts`) only covers\n * the ONE outcome where `act` actually runs (`sent`, and the narrow\n * `guardrail_hold` `act` itself can still produce post-claim — see below);\n * every other outcome (`ready`, `needs_human`, `awaiting_approval`,\n * `no_reply_needed`, `failed`, the pre-claim `guardrail_hold`) is written\n * directly here, since `act`/the claim were never reached for them.\n */\nimport type { AppApiRecord, AppHandler, FunctionDef } from '@apotech-os/app-kit';\nimport { AppApiError } from '@apotech-os/app-kit';\nimport { createBudget } from '../graph/budget';\nimport { runTicket } from '../graph/run-ticket';\nimport type { Classification, ConversationRef, DraftAttribution } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport { assertTransition, openTicketKeyFor, type GeneratedResponseStatus } from '../status/machine';\nimport { buildSendSeam } from './claim-commit';\nimport { buildApprovalKey, buildInboxKey } from './approval-key';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { withRecordingWritePorts } from '../adapters/recording-ports';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS, getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { createNoToolContext } from './no-tool-context';\nimport { buildPromptsTable, draftPromptRefFor, resolveDraftAgent, toAgent, toCategory } from './records';\n\n/**\n * Rebuilds the `Classification` `runTicket`'s `resume` needs, field-for-field\n * off the `triage-decision` row `triage-tick` wrote. `isFallback` is always\n * `false`: a `generated-response` is only ever created for a triage that\n * SUCCEEDED (`triage-tick` writes `status:'error'` and stops on a failed\n * classification, never creating one) — see `functions/eligibility.ts`.\n */\nfunction classificationFromDecision(decision: AppApiRecord): Classification {\n const data = decision.data as Record<string, unknown>;\n return {\n category: (data.tag as string) ?? '',\n confidence: (data.confidence as 'high' | 'low') ?? 'low',\n reasoning: (data.reasoning as string) ?? '',\n isFallback: false,\n conversationOver: (data.conversationOver as boolean | undefined) ?? false,\n };\n}\n\n/**\n * §3.4's four Langfuse columns, off the attribution the draft carries (B2).\n * WITHOUT a writer here `ext-fast-response-check` served `null` on every hit,\n * the extension echoed those nulls back, and `ext-response-comparison`'s\n * dataset/score capture — gated on a non-empty trace id — never fired for a\n * single pipeline response: the improvement loop had nothing to score.\n *\n * A run that produced no draft (a failed one) writes explicit `null`s rather\n * than nothing: the ids of a call that never finished would point the loop at\n * a generation nobody read.\n */\nfunction attributionFields(attribution: DraftAttribution | undefined): Record<string, unknown> {\n return {\n langfuseTraceId: attribution?.traceId ?? null,\n langfuseObservationId: attribution?.observationId ?? null,\n promptName: attribution?.promptName ?? null,\n promptVersion: attribution?.promptVersion ?? null,\n };\n}\n\nasync function finalizeNonSent(\n ctx: SupportKitHandlerContext,\n id: string,\n ticketId: string,\n toStatus: GeneratedResponseStatus,\n extra: Record<string, unknown>,\n): Promise<boolean> {\n assertTransition('pending', toStatus);\n try {\n await ctx.api.update(\n 'generated-response',\n id,\n { status: toStatus, openTicketKey: openTicketKeyFor(toStatus, ticketId), ...extra },\n { ifMatch: { status: 'pending' } },\n );\n return true;\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) {\n ctx.logger.info(`process-response: generated-response ${id} was already moved off \"pending\" by another worker, abandoning`);\n return false;\n }\n throw err;\n }\n}\n\nexport function buildProcessResponseFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'process-response'),\n name: 'process-response',\n trigger: { type: 'dbEvent', objectRef: `app:${config.slug}/generated-response`, operation: 'created' },\n retries: 3,\n concurrency: 3,\n notify: { onFailure: true, severity: 'warning' },\n };\n}\n\nexport function createProcessResponseHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx) => processResponseHandler(ctx, config);\n}\n\nexport async function processResponseHandler(ctx: SupportKitHandlerContext, config: SupportKitFunctionConfig): Promise<void> {\n const recordId = ctx.event.recordId as string | undefined;\n if (!recordId) {\n ctx.logger.warn('process-response: event carried no recordId, skipping');\n return;\n }\n\n const record = await getOptional(ctx, 'generated-response', recordId);\n if (!record) {\n ctx.logger.info(`process-response: generated-response ${recordId} no longer exists, skipping`);\n return;\n }\n const data = record.data as Record<string, unknown>;\n if (data.status !== 'pending') {\n ctx.logger.info(`process-response: generated-response ${recordId} is not pending (status=\"${String(data.status)}\"), skipping — already handled or a dbEvent redelivery`);\n return;\n }\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n if (validateSettings(settings as unknown as Record<string, unknown>).length > 0) {\n ctx.logger.info('process-response: settings invalid, skipping');\n return;\n }\n\n const ticketId = data.ticketId as string;\n const ref: ConversationRef = { id: ticketId, channel: 'gorgias' };\n\n const decision = await getOptional(ctx, 'triage-decision', (data.triageDecisionId as string) ?? null);\n if (!decision) {\n ctx.logger.error(`process-response: generated-response ${recordId} has no resolvable triage-decision, marking failed`);\n await finalizeNonSent(ctx, recordId, ticketId, 'failed', { error: 'triage-decision not found' });\n return;\n }\n const classification = classificationFromDecision(decision);\n const escalated = (decision.data as Record<string, unknown>).escalated === true;\n\n const categoryRecord = await getOptional(ctx, 'category', (data.categoryId as string | null) ?? null);\n const category = categoryRecord ? toCategory(categoryRecord) : null;\n const agentRecord = (data.agentId as string | null)\n ? await getOptional(ctx, 'agent', data.agentId as string)\n : null;\n const agent = agentRecord ? toAgent(agentRecord) : await resolveDraftAgent(ctx.api, null);\n\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));\n\n const dryRun = settings.dryRun === true;\n // Every completion of this ticket under one Langfuse session (§3.4's\n // quality loop reads a conversation, not a pile of orphan generations).\n const trace = { sessionId: ticketId, tags: [`app:${config.slug}`] };\n const ports = dryRun ? withRecordingWritePorts(buildTicketPorts(ctx, trace), ctx.api) : buildTicketPorts(ctx, trace);\n const { clock } = ports;\n\n // Generation-time snapshot for `act`'s divergence baseline WHEN this\n // record is later replayed through `handle-approval` (design decision (a)\n // in T22's brief): a `handle-approval` run has no live conversation read\n // of its own to source these from, and `act` always re-reads for real\n // before posting regardless (I8), so a snapshot taken here — moments\n // before `runTicket`'s own `fetchContext` re-read — is close enough\n // without weakening send safety.\n const conversationSnapshot = await ports.conversation.read(ref);\n\n const generatedAt = data.generatedAt instanceof Date ? data.generatedAt : new Date(data.generatedAt as string);\n const seam = buildSendSeam({\n api: ctx.api,\n clock,\n id: recordId,\n ticketId,\n fromStatus: 'pending',\n extraClaimData: (run) => ({\n responseText: run.draft.text,\n sources: run.draft.sources,\n verdict: run.verdict,\n generatedMessageCount: conversationSnapshot.messageCount,\n generatedLastMessageAt: conversationSnapshot.lastMessageAt,\n ...attributionFields(run.draft.attribution),\n }),\n });\n\n const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n\n const result = await runTicket(\n {\n ref,\n profile,\n ports,\n toolContext: createNoToolContext(),\n budget,\n category: { autoReplyEnabled: category?.autoReplyEnabled ?? false, minConfidence: null },\n categories: [],\n log: (msg) => ctx.logger.debug(msg),\n send: dryRun ? { mode: 'none' } : { mode: 'claimed', claim: seam.claim, commit: seam.commit },\n queuedAt: generatedAt,\n },\n { resume: { classification, escalated } },\n );\n\n const draftExtra = {\n responseText: result.draft?.text ?? null,\n sources: result.draft?.sources ?? [],\n verdict: result.verdict ?? null,\n generatedMessageCount: conversationSnapshot.messageCount,\n generatedLastMessageAt: conversationSnapshot.lastMessageAt,\n ...attributionFields(result.draft?.attribution),\n };\n\n switch (result.outcome) {\n case 'sent':\n // Nothing was sent on a dry run — `send: {mode: 'none'}` means no\n // claim/commit ever ran, so this record is still `pending` and would\n // stay there forever if this returned like the live path does.\n if (dryRun) {\n await finalizeNonSent(ctx, recordId, ticketId, 'ready', draftExtra);\n return;\n }\n // Already fully persisted by `seam.claim`/`seam.commit` inside `act`.\n return;\n case 'ready':\n case 'guardrail_hold':\n // `run-ticket.ts`'s own `finish()` doc: both are \"ready + a tag\", the\n // tag alone (already applied by `finish` via `StatePort.flag`)\n // distinguishes them for a human — the record's `status` does not.\n await finalizeNonSent(ctx, recordId, ticketId, 'ready', draftExtra);\n return;\n case 'needs_human': {\n const persisted = await finalizeNonSent(ctx, recordId, ticketId, 'ready', draftExtra);\n if (persisted) {\n await ctx.api.inbox.raise({\n key: buildInboxKey(recordId),\n severity: 'warning',\n title: `Réponse générée à revoir — ticket ${ticketId}`,\n entityRef: { appSlug: config.slug, objectKey: 'generated-response', id: recordId },\n });\n }\n return;\n }\n case 'awaiting_approval': {\n const persisted = await finalizeNonSent(ctx, recordId, ticketId, 'ready', draftExtra);\n if (persisted && !dryRun) {\n await ctx.api.approvals.request({\n key: buildApprovalKey(recordId),\n title: `Approuver l'envoi automatique — ticket ${ticketId}`,\n entityRef: { appSlug: config.slug, objectKey: 'generated-response', id: recordId },\n });\n }\n return;\n }\n case 'escalated':\n case 'triaged_only':\n case 'no_reply_needed':\n await finalizeNonSent(ctx, recordId, ticketId, 'no_reply_needed', draftExtra);\n return;\n case 'failed':\n await finalizeNonSent(ctx, recordId, ticketId, 'failed', { ...draftExtra, error: 'runTicket outcome: failed' });\n return;\n default:\n // `outcome` is `null` only mid-run — `runTicket` never returns it on\n // a resumed call (every path through `finish()` sets one).\n ctx.logger.error(`process-response: generated-response ${recordId} resumed run ended with no outcome`);\n }\n}\n","/**\n * `transitionGeneratedResponse` (M8 hardening) — the ONE conditional\n * `generated-response` status-write shape shared by every caller that only\n * needs to move a row from one status to another (S5 `ifMatch` + tolerate a\n * lost race as \"someone else already moved it\", not an error): `sweep`'s\n * `ready -> expired` TTL pass and `ext-fast-response-check`'s\n * `ready -> expired|invalidated` flips used to be two independent\n * implementations of the identical transition on the identical record —\n * anything added to one (a stamp, a metric, a different 409 policy) would\n * silently not happen on the other.\n *\n * Deliberately NOT used by `claim-commit.ts`'s `buildSendSeam` or\n * `sweep.ts`'s stalled-sending/stalled-pending passes: those write EXTRA\n * fields the caller computes from the in-flight `run`/reclaim shape\n * (`sendingAt`, `reclaimStalledSend()`'s `autoSendDecision` hold, the\n * `error` message) on the SAME atomic write, which this narrow helper's\n * `extra` param supports but was not the reported duplication — scope kept\n * to the transition the review actually flagged as duplicated.\n */\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { SupportKitApi } from '../adapters/api';\nimport { assertTransition, openTicketKeyFor, type GeneratedResponseStatus } from '../status/machine';\n\nexport interface TransitionGeneratedResponseParams {\n id: string;\n ticketId: string;\n from: GeneratedResponseStatus;\n to: GeneratedResponseStatus;\n /** Extra fields persisted on the SAME conditional write, alongside `status`/`openTicketKey`. */\n extra?: Record<string, unknown>;\n}\n\n/**\n * Attempts `from -> to` under `ifMatch: {status: from}`. Returns `true` when\n * the write landed, `false` when the row had already moved (a lost race —\n * not an error, exactly the same outcome either way for every caller today).\n */\nexport async function transitionGeneratedResponse(api: SupportKitApi, params: TransitionGeneratedResponseParams): Promise<boolean> {\n const { id, ticketId, from, to, extra } = params;\n assertTransition(from, to);\n try {\n await api.update(\n 'generated-response',\n id,\n { status: to, openTicketKey: openTicketKeyFor(to, ticketId), ...(extra ?? {}) },\n { ifMatch: { status: from } },\n );\n return true;\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) return false;\n throw err;\n }\n}\n","/**\n * `sweep` (§3.5) — cron function. Three independent janitor passes over\n * `generated-response`:\n * 1. `ready` rows past `expiresAt` → `expired` (the extension's TTL check\n * mirrored server-side, so a stale draft cannot be served forever).\n * 2. `sending` rows stuck past 30 minutes (a crash between `claim` and\n * `commit`, I9) → reclaimed to `ready` + `autoSendDecision: 'hold'`\n * via `reclaimStalledSend()` (`status/machine.ts`) — NEVER `status`\n * alone, which `reclaimStalledSend`'s own doc calls out as the one\n * write shape that would re-open the record as a legal, un-held claim\n * target and risk RE-SENDING the reply. Every reclaimed ticket is\n * handed to a human: the escalation tag is applied and an Inbox alert\n * raised, since a stuck send is exactly the kind of thing nobody\n * should have to notice on their own.\n * 3. `pending` rows past `expiresAt` → `failed` (T22 hardening, A3 — see\n * that pass's own doc below for why it exists).\n *\n * `sweep` never posts a reply and never calls the claim/commit seam — it\n * only ever touches `generated-response` rows and the Gorgias tag/alert\n * surfaces, which is what makes §8.4's invariant 2 (\"never re-sent\")\n * checkable against it directly.\n *\n * Known limitation: `SupportKitApi.list` carries no cursor, so a sweep pass\n * reads at most one page of `ready`/`sending`/`pending` rows. Acceptable for\n * now — all three sets are normally small and short-lived — but a tenant\n * with a large backlog would need pagination added to the interface first.\n *\n * SETTINGS VALIDATION (T22 hardening, C — a deliberate exemption, not an\n * omission): `sweep` does NOT call `validateSettings` the way the other\n * three handlers do, because it must keep reclaiming stalled sends even on\n * a tenant whose settings are currently incomplete — that reclaim is a\n * safety net, not a feature an operator opted into, and refusing to run it\n * on a misconfigured app would leave a stuck `sending` row (and a customer\n * who may or may not have already been emailed) unattended for longer, not\n * shorter. What IS guarded is the one settings field this file actually\n * reads, `escalationTag`: on an unconfigured tenant it used to be\n * `undefined`, and `StatePort.flag` calling `.trim()` on it threw a\n * `TypeError` mid-loop — with `retries: 0` that killed the rest of the\n * reclaim pass AND skipped `lastSweepAt`. Routing it through\n * `settingsToProfile` instead (as first suggested) would trade this crash\n * for a different one: that mapper dereferences `settings.nodes.triage.model`\n * unconditionally (`baseNode`), which throws just as readily on the exact\n * kind of incomplete settings blob this guard exists for. A direct,\n * narrow-scoped type check on the one field actually read is what stays\n * safe without introducing a new crash surface.\n */\nimport type { AppHandler, FunctionDef } from '@apotech-os/app-kit';\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { ConversationRef } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { createGorgiasStatePort, createRealClock } from '../adapters/ctx-ports';\nimport { assertTransition, openTicketKeyFor, reclaimStalledSend } from '../status/machine';\nimport { buildInboxKey } from './approval-key';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { transitionGeneratedResponse } from './generated-response-transition';\nimport { readPipelineState, toDate, upsertPipelineState } from './pipeline-state';\n\nconst STALE_SENDING_THRESHOLD_MS = 30 * 60_000;\nconst SWEEP_PAGE_SIZE = 500;\n\nexport function buildSweepFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'sweep'),\n name: 'sweep',\n trigger: { type: 'cron', pattern: '*/5 * * * *' },\n retries: 0,\n concurrency: 1,\n notify: { onFailure: true, severity: 'warning' },\n };\n}\n\nexport function createSweepHandler(): AppHandler {\n return (ctx) => sweepHandler(ctx);\n}\n\nexport async function sweepHandler(ctx: SupportKitHandlerContext): Promise<void> {\n const clock = createRealClock();\n const now = clock.now();\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const statePort = createGorgiasStatePort(ctx.api);\n // A narrow, defensive read — see this module's header doc (C) for why the\n // full `settingsToProfile` mapping is not used here.\n const escalationTag = typeof settings?.escalationTag === 'string' ? settings.escalationTag : '';\n if (!escalationTag) {\n ctx.logger.warn('sweep: escalationTag is not configured — a stalled-send reclaim will proceed without an escalation tag');\n }\n\n await sweepExpiredReady(ctx, now);\n await sweepStalledSending(ctx, now, escalationTag, statePort);\n await sweepStalledPending(ctx, now);\n\n await upsertPipelineState(ctx.api, { lastSweepAt: now });\n}\n\nasync function sweepExpiredReady(ctx: SupportKitHandlerContext, now: Date): Promise<void> {\n const page = await ctx.api.list('generated-response', { filter: { status: 'ready' }, limit: SWEEP_PAGE_SIZE });\n for (const row of page.items) {\n const expiresAt = toDate(row.data.expiresAt);\n if (!expiresAt || expiresAt.getTime() > now.getTime()) continue;\n\n // M8: the SAME `ready -> expired` conditional transition\n // `ext-fast-response-check`'s own TTL flip uses — see that module's\n // shared helper's own doc for why this used to be two independent\n // copies of the identical write.\n await transitionGeneratedResponse(ctx.api, { id: row.id, ticketId: row.data.ticketId as string, from: 'ready', to: 'expired' });\n }\n}\n\nasync function sweepStalledSending(\n ctx: SupportKitHandlerContext,\n now: Date,\n escalationTag: string,\n statePort: ReturnType<typeof createGorgiasStatePort>,\n): Promise<void> {\n const page = await ctx.api.list('generated-response', { filter: { status: 'sending' }, limit: SWEEP_PAGE_SIZE });\n for (const row of page.items) {\n const sendingAt = toDate(row.data.sendingAt);\n if (!sendingAt || now.getTime() - sendingAt.getTime() < STALE_SENDING_THRESHOLD_MS) continue;\n\n assertTransition('sending', 'ready');\n const ticketId = row.data.ticketId as string;\n let reclaimed: boolean;\n try {\n await ctx.api.update(\n 'generated-response',\n row.id,\n {\n // Status AND the hold together, in the SAME write — see the\n // module doc and `reclaimStalledSend`'s own doc for why splitting\n // this into two writes (or dropping the hold) would re-open the\n // record as a sendable `ready` row.\n ...reclaimStalledSend(),\n openTicketKey: openTicketKeyFor('ready', ticketId),\n },\n { ifMatch: { status: 'sending' } },\n );\n reclaimed = true;\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) {\n reclaimed = false; // already moved by another worker (e.g. a late commit landing)\n } else {\n throw err;\n }\n }\n if (!reclaimed) continue;\n\n const ref: ConversationRef = { id: ticketId, channel: 'gorgias' };\n await statePort.flag(ref, escalationTag);\n await ctx.api.inbox.raise({\n key: buildInboxKey(row.id, 'stalled-send'),\n severity: 'warning',\n title: `Envoi bloqué détecté — ticket ${ticketId}`,\n body: 'La réponse est restée en statut \"sending\" plus de 30 minutes et a été replacée en attente humaine.',\n });\n }\n}\n\n/**\n * A3: a `pending` row whose `process-response` handler threw is orphaned\n * FOREVER without this pass. `process-response` runs with `retries: 3`; once\n * those are exhausted the dbEvent is gone and nothing ever revisits the row\n * — `sweep`'s other two passes only ever scan `ready`/`sending`, never\n * `pending`. Worse, the stuck row keeps `openTicketKey` set (only a\n * TERMINAL status clears it, `openTicketKeyFor`'s own doc), so the unique\n * index makes any FUTURE `triage-tick` create for the same ticket 409\n * forever — that ticket could never be drafted again by any later tick.\n *\n * Chosen over the brief's other option (a top-level catch inside\n * `process-response` itself, finalising straight to `failed`): the row\n * already carries `expiresAt` (set at generation time, independent of\n * status), so this reuses the exact same staleness idiom `sweepExpiredReady`\n * above already established, instead of adding a second, different\n * failure-handling shape to `process-response`. It also covers cases a\n * try/catch inside the handler cannot — a dbEvent that never delivers at\n * all, or a process that dies before any `catch` runs.\n */\nasync function sweepStalledPending(ctx: SupportKitHandlerContext, now: Date): Promise<void> {\n const page = await ctx.api.list('generated-response', { filter: { status: 'pending' }, limit: SWEEP_PAGE_SIZE });\n for (const row of page.items) {\n const expiresAt = toDate(row.data.expiresAt);\n if (!expiresAt || expiresAt.getTime() > now.getTime()) continue;\n\n assertTransition('pending', 'failed');\n try {\n await ctx.api.update(\n 'generated-response',\n row.id,\n { status: 'failed', openTicketKey: openTicketKeyFor('failed', row.data.ticketId as string), error: 'orphaned pending row past its TTL (sweep)' },\n { ifMatch: { status: 'pending' } },\n );\n } catch (err) {\n if (err instanceof AppApiError && err.status === 409) continue; // already moved by another worker\n throw err;\n }\n }\n}\n\n","/**\n * `handle-approval` (§3.5) — event function, triggered on\n * `APPROVAL_DECIDED_EVENT` (`app.approval.decided`) for an approval\n * `process-response`'s `awaiting_approval` outcome requested.\n *\n * SEND PATH SHARING (§8.4's \"no forked second send implementation\"):\n * - `functions/claim-commit.ts`'s `buildSendSeam` is the SAME\n * claim/commit persistence pair `process-response` wires as\n * `NodeDeps.send` — only `fromStatus` differs ('pending' there,\n * 'ready' here).\n * - The actual reply-posting/anti-collision logic is `act`\n * (`graph/nodes/act.ts`) itself, called DIRECTLY here (there is no\n * triage/draft/evaluate to redo — only the send step remains), rather\n * than re-implemented.\n *\n * Rebuilding `act`'s `state.conversation` argument from stored fields is a\n * DELIBERATELY NARROW contract, verified by reading `act.ts` line by line\n * (T22): it reads exactly THREE fields off that argument —\n * `sourceChannel` (the email/whatsapp branch), `messageCount` and\n * `lastMessageAt` (the divergence check against its OWN fresh re-read,\n * `deps.ports.conversation.read`). Every other `Conversation` field\n * (`subject`, `messages`, `customer`, `isClosed`, `lastAgentReplyAt`,\n * `hasCustomerAttachment`) is read off the FRESH re-read `act` performs\n * itself, never off this placeholder — which is why they can be filled with\n * inert defaults below. If `act` ever starts reading more off its\n * `generatedFrom` argument, this placeholder silently stops being enough;\n * there is no compile-time guard for that today.\n */\nimport type { AppApiRecord, AppHandler, ApprovalDecidedPayload, FunctionDef } from '@apotech-os/app-kit';\nimport { APPROVAL_DECIDED_EVENT, AppApiError } from '@apotech-os/app-kit';\nimport { createBudget } from '../graph/budget';\nimport { act } from '../graph/nodes';\nimport { applyOutcomeTags } from '../graph/run-ticket';\nimport { initialState } from '../graph/state';\nimport type { Conversation, ConversationRef, Draft, ProposedAction, Verdict } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport { assertTransition, openTicketKeyFor } from '../status/machine';\nimport { parseApprovalKey } from './approval-key';\nimport { buildSendSeam } from './claim-commit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { createNoToolContext } from './no-tool-context';\nimport { buildPromptsTable, draftPromptRefFor } from './records';\n\nexport function buildHandleApprovalFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'handle-approval'),\n name: 'handle-approval',\n trigger: { type: 'event', name: APPROVAL_DECIDED_EVENT },\n retries: 3,\n // No `notify` — §3.5's table gives only the first three functions one.\n };\n}\n\nexport function createHandleApprovalHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx) => handleApprovalHandler(ctx, config);\n}\n\nexport async function handleApprovalHandler(ctx: SupportKitHandlerContext, config: SupportKitFunctionConfig): Promise<void> {\n const payload = ctx.event as unknown as ApprovalDecidedPayload;\n const id = parseApprovalKey(payload.key);\n if (!id) {\n ctx.logger.debug(`handle-approval: key \"${payload.key}\" is not a generated-response approval, ignoring`);\n return;\n }\n\n const record = await getOptional(ctx, 'generated-response', id);\n if (!record) {\n ctx.logger.info(`handle-approval: generated-response ${id} no longer exists, skipping`);\n return;\n }\n const data = record.data as Record<string, unknown>;\n if (data.status !== 'ready') {\n ctx.logger.info(`handle-approval: generated-response ${id} is not ready (status=\"${String(data.status)}\"), skipping — already handled or reclaimed`);\n return;\n }\n const ticketId = data.ticketId as string;\n\n if (payload.status === 'rejected') {\n try {\n await ctx.api.update('generated-response', id, { autoSendDecision: 'hold' }, { ifMatch: { status: 'ready' } });\n } catch (err) {\n if (!(err instanceof AppApiError && err.status === 409)) throw err;\n }\n return;\n }\n\n // §8.4 invariant 2's crux: a record the sweep reclaimed to `ready` carries\n // `autoSendDecision: 'hold'` — `status: 'ready'` alone makes it look like\n // an ordinary claimable draft again, but the hold means it may ONLY leave\n // this state through a FRESH approval request, never a silent resend of a\n // decision that already fired once. Nothing else in the pipeline checks\n // `autoSendDecision` before attempting to send (`act` itself has no idea\n // it exists) — this is the one place that gate has to live.\n if (data.autoSendDecision === 'hold') {\n ctx.logger.warn(`handle-approval: generated-response ${id} is on hold (autoSendDecision), refusing to send despite the approval`);\n return;\n }\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n ctx.logger.info('handle-approval: settings invalid, skipping', { issues });\n return;\n }\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(null, config), settings.nodes));\n\n // Empty-draft guard (T22 hardening, B3): `draft.text` below falls back to\n // `''` on a missing `responseText`, and `act` only refuses a MISSING draft\n // object, never an empty one — nothing today can reach this (every\n // `generated-response` reaching `ready` came through `process-response`,\n // which always writes a real `responseText`), but a future caller of\n // `finalizeNonSent`/a hand-edited record could leave one blank, and this\n // is the last line of defence before an empty email goes out. `ready ->\n // invalidated` is a legal transition (`status/machine.ts`) for exactly\n // this kind of \"this record cannot be acted on as-is\" case.\n const responseText = (data.responseText as string | null | undefined) ?? '';\n if (responseText.trim().length === 0) {\n ctx.logger.error(`handle-approval: generated-response ${id} has no responseText, refusing to send an empty reply`);\n assertTransition('ready', 'invalidated');\n try {\n await ctx.api.update('generated-response', id, { status: 'invalidated', openTicketKey: openTicketKeyFor('invalidated', ticketId) }, { ifMatch: { status: 'ready' } });\n } catch (err) {\n if (!(err instanceof AppApiError && err.status === 409)) throw err;\n }\n return;\n }\n\n const ports = buildTicketPorts(ctx);\n const { clock, state: statePort } = ports;\n\n const conversation: Conversation = {\n ref: { id: ticketId, channel: 'gorgias' },\n subject: null,\n messages: [],\n customer: { name: null, email: null, orderContext: null },\n isClosed: false,\n lastMessageAt: data.generatedLastMessageAt ? new Date(data.generatedLastMessageAt as string) : null,\n messageCount: (data.generatedMessageCount as number | undefined) ?? 0,\n lastAgentReplyAt: null,\n hasCustomerAttachment: false,\n sourceChannel: data.channel as string,\n };\n const draft: Draft = { text: responseText, sources: (data.sources as Draft['sources']) ?? [], revised: false };\n const proposedActions: ProposedAction[] = [{ kind: 'send_reply', args: {}, idempotencyKey: id, decision: 'auto' }];\n\n // Tracks the seam's OWN claim result (T22 hardening, B2) rather than\n // re-reading the record afterwards: `act` returns `{}` with zero\n // guardrail hits BOTH when the send actually completed AND when\n // `send.claim` returned `false` (another worker already claimed this row\n // — a concurrent decision or a retried delivery of this very event), so a\n // caller that only inspects `patch` cannot tell the two apart. Capturing\n // the seam's own return value is what `buildSendSeam`'s doc already names\n // as the deciding signal — surfaced here instead of silently discarded.\n const seam = buildSendSeam({ api: ctx.api, clock, id, ticketId, fromStatus: 'ready' });\n let claimed = true;\n const trackedSeam = {\n claim: async (run: Parameters<typeof seam.claim>[0]) => {\n claimed = await seam.claim(run);\n return claimed;\n },\n commit: seam.commit,\n };\n const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: 1 });\n const ref: ConversationRef = { id: ticketId, channel: 'gorgias' };\n const verdict = (data.verdict as Verdict | undefined) ?? null;\n\n const patch = await act(\n { ...initialState(), conversation, draft, verdict, proposedActions },\n {\n ref,\n profile,\n ports,\n toolContext: createNoToolContext(),\n budget,\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: [],\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'claimed', claim: trackedSeam.claim, commit: trackedSeam.commit },\n queuedAt: data.generatedAt ? new Date(data.generatedAt as string) : null,\n },\n );\n\n const guardrailHits = patch.guardrailHits ?? [];\n if (guardrailHits.length === 0) {\n if (!claimed) {\n ctx.logger.warn(\n `handle-approval: generated-response ${id} claim was lost — a concurrent worker already advanced this record, nothing to persist here`,\n );\n return;\n }\n // `act` claimed, posted and committed — apply the SAME outcome tag\n // `process-response`'s resumed `runTicket` would have applied via\n // `finish()` (B1: one shared function, so the two send routes cannot\n // diverge on the audit trail §3.6 defines).\n await applyOutcomeTags('sent', verdict, { ports: { state: statePort }, ref, audit: profile.audit });\n return;\n }\n\n // `act`'s own guardrail checks (customer_email_missing/ticket_closed/\n // agent_replied/diverged/run_deadline) all run BEFORE `send.claim`, so a\n // hit here means the claim was NEVER attempted — the record is still\n // `ready`. `ready -> no_reply_needed` is not a legal transition\n // (`status/machine.ts`'s `ALLOWED_TRANSITIONS`), so — unlike\n // `process-response` — there is no legal status change to make here; the\n // record stays `ready`. What DOES change is `autoSendDecision: 'hold'`,\n // so the very next approval decision cannot walk straight back into the\n // same hit, plus the escalation tag `applyOutcomeTags('guardrail_hold', …)`\n // applies for a human to look at why the send never went out.\n try {\n await ctx.api.update('generated-response', id, { autoSendDecision: 'hold' }, { ifMatch: { status: 'ready' } });\n } catch (err) {\n if (!(err instanceof AppApiError && err.status === 409)) throw err;\n }\n await applyOutcomeTags('guardrail_hold', verdict, { ports: { state: statePort }, ref, audit: profile.audit });\n}\n","/**\n * Stable universal identifiers for the T23 `uiInvoke` functions' `input`\n * field defs (§3.5) — same convention as `records/ids.ts`: generated once\n * and committed, never regenerated (a function's `input` is diffed by these\n * ids, not by field name).\n */\n/** Renamed from `dryRun` (T23 post-review D) — same field identity, same uid, honest name: it bypasses the `triageEnabled` kill switch and runs the real batch, the opposite of what \"dry run\" means everywhere else in this kit. */\nexport const RUN_TRIAGE_NOW_INPUT_IGNORE_TRIAGE_DISABLED_UID = 'dd175229-feee-4306-a429-b25ea5dd89e4';\n\nexport const PREVIEW_TRIAGE_INPUT_TICKET_ID_UID = 'b9d5da91-ce08-4aac-ae52-5ffef730fab0';\n\nexport const GRAPH_DRY_RUN_INPUT_TICKET_ID_UID = '5861e7be-3a28-4852-874c-1c14e82d4b35';\nexport const GRAPH_DRY_RUN_INPUT_CATEGORY_ID_UID = 'c47b8b57-6f7a-47d7-a9d1-a18fbf71a0f0';\nexport const GRAPH_DRY_RUN_INPUT_AGENT_ID_UID = '95d38506-bc22-4f91-ad43-797ff7b54f48';\nexport const GRAPH_DRY_RUN_INPUT_OVERRIDES_UID = '306a4f7d-db5d-4144-a6bd-865889e152e2';\n/** The pasted-ticket mode: `{body, subject?, channel?}` replacing `ticketId`, so the graph can be replayed with no Gorgias ticket at all. */\nexport const GRAPH_DRY_RUN_INPUT_INLINE_TICKET_UID = '2abcc895-2751-4944-b527-78bc4604eed0';\n\nexport const TEST_AGENTS_INPUT_VIEW_ID_UID = '20227a8f-95d8-4c20-a9cd-eccb0ce39e3e';\nexport const TEST_AGENTS_INPUT_TICKET_IDS_UID = '7d27acff-b558-4783-a3ac-722f676b71a7';\nexport const TEST_AGENTS_INPUT_AGENT_ID_UID = 'ea12d731-708b-4fcc-9ebb-6c4e0d04a60e';\nexport const TEST_AGENTS_INPUT_LIMIT_UID = '95151bdf-2966-41cd-8b6f-c5b0b10c427e';\n\nexport const SUGGEST_PROMPT_INPUT_AGENT_ID_UID = '40509afa-5931-419d-8467-a52cbac5c17e';\nexport const SUGGEST_PROMPT_INPUT_MAX_COMPARISONS_UID = '0c2e2f58-ffd3-4aee-a1b4-cb81d1762eb6';\n\nexport const RUN_DIFF_ANALYSIS_INPUT_AGENT_ID_UID = 'bfe1e895-1608-40d8-99e9-230ab9c41473';\nexport const RUN_DIFF_ANALYSIS_INPUT_LIMIT_UID = 'b1936472-a9dc-4b0b-8ef6-ab84733a2bfa';\n\nexport const LIST_GORGIAS_VIEWS_INPUT_CHECK_APP_SLUGS_UID = '1ac5eb02-32da-4fd4-9462-dac4ff23b208';\n\n/**\n * T26 rework (BLOCKER 3) — `create-agent`'s own `input` field defs. Assigns\n * the new agent's `promptName` server-side (`agent/<recordId>`, §3.4) — see\n * that function's own doc for why a plain `POST records/agent` cannot.\n */\nexport const CREATE_AGENT_INPUT_NAME_UID = '0cb57453-7b02-49ce-875b-7ff079a5810d';\nexport const CREATE_AGENT_INPUT_MODEL_ID_UID = 'f19f1c10-3145-482b-8c1d-6fd3576596ff';\nexport const CREATE_AGENT_INPUT_PROVIDER_UID = '0dd94db4-f31a-4cd2-b030-1b1a4da5b43e';\nexport const CREATE_AGENT_INPUT_SYSTEM_PROMPT_SNAPSHOT_UID = 'd50f3810-b6fe-4c90-b69b-3e36ba502cdb';\n/**\n * Agent-prompt-ref rework — an agent may be created pointing at a Langfuse\n * prompt that ALREADY exists (Gorgias migration: 16 agents whose prompts\n * predate their records), instead of the server-derived `agent/<recordId>`.\n */\nexport const CREATE_AGENT_INPUT_PROMPT_NAME_UID = '102d412a-3299-42a2-ac62-6f7c4155508d';\nexport const CREATE_AGENT_INPUT_PROMPT_LABEL_UID = '04f8eeba-2d0b-4814-8009-a4a3d1530760';\n\n/**\n * T26 rework (BLOCKER 4) — `set-default-agent`'s own `input` field def.\n * Demotes the incumbent default agent and promotes the target in one\n * server-side call — see that function's own doc for why two independent\n * client-side PATCHes cannot maintain the \"at most one default agent\"\n * invariant.\n */\nexport const SET_DEFAULT_AGENT_INPUT_AGENT_ID_UID = '0686c615-63f8-49a1-b3c7-3542bac76cd6';\n\n/**\n * T24 — the six reserved `ext-*` functions' `input` field defs (§5.2's\n * frozen wire payloads). `ext-models`/`ext-categories` have no input (the\n * gateway always sends `{}`), so they need none.\n */\nexport const EXT_CHAT_INPUT_MESSAGES_UID = '874e4408-74c0-4188-b923-a0791da4d096';\nexport const EXT_CHAT_INPUT_MODEL_ID_UID = 'd63f05b1-165d-45e0-9300-cabe5e22fa42';\nexport const EXT_CHAT_INPUT_AGENT_NAME_UID = '928f03e6-2d48-487e-85ee-15999b9cbbbb';\nexport const EXT_CHAT_INPUT_GORGIAS_TICKET_ID_UID = '86fcc5df-8545-4d77-b3d7-d741c6b1d5a5';\n\nexport const EXT_FAST_RESPONSE_CHECK_INPUT_TICKET_ID_UID = '4a597dbf-ba6f-4628-b526-759448e7ed17';\n\nexport const EXT_EVALUATION_INPUT_SATISFIED_UID = 'b1af323a-d1e0-40c7-b975-66a1e3cd4b21';\nexport const EXT_EVALUATION_INPUT_MESSAGES_UID = 'ea5d9df8-c7d5-459c-b25d-2cfe0b45ad45';\nexport const EXT_EVALUATION_INPUT_TICKET_URL_UID = '6648f361-e16b-46b2-a411-3d9cdf35e87a';\nexport const EXT_EVALUATION_INPUT_LANGFUSE_TRACE_ID_UID = '0d8d5556-2ffe-4d5e-aaca-55e0eab63066';\nexport const EXT_EVALUATION_INPUT_LANGFUSE_OBSERVATION_ID_UID = '8285ab1d-e20d-4088-b9b0-176236339d1c';\nexport const EXT_EVALUATION_INPUT_MODEL_ID_UID = '1646f686-57d9-4204-b901-9d7a8e1a8078';\n\nexport const EXT_RESPONSE_COMPARISON_INPUT_LAST_MESSAGE_GENERATED_UID = 'f2ad97ac-0abf-449a-9cc3-72efff6723c6';\nexport const EXT_RESPONSE_COMPARISON_INPUT_MESSAGE_ACTUAL_SENT_UID = '2dfe91f9-7177-4c44-8bcb-f841ff399ce0';\nexport const EXT_RESPONSE_COMPARISON_INPUT_TICKET_ID_UID = '63afd37e-4f0f-411b-aa62-6f480ef6cd3c';\nexport const EXT_RESPONSE_COMPARISON_INPUT_TICKET_URL_UID = '295c10ef-cb7c-4409-876a-1e384cfe6f45';\nexport const EXT_RESPONSE_COMPARISON_INPUT_MODEL_CONFIG_ID_UID = 'c48778a5-a8f5-4ee7-92b7-66de1bb543be';\nexport const EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_TRACE_ID_UID = '5113fc86-3865-4110-b65f-c91748816f02';\nexport const EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_OBSERVATION_ID_UID = 'e5310144-8004-4c20-9ce4-9c0c820e3577';\nexport const EXT_RESPONSE_COMPARISON_INPUT_PROMPT_NAME_UID = '4813f09d-88ac-4574-8f38-be5f87a6c9ac';\nexport const EXT_RESPONSE_COMPARISON_INPUT_PROMPT_VERSION_UID = 'e87e65e8-e078-47e3-92b7-104368952a56';\nexport const EXT_RESPONSE_COMPARISON_INPUT_CONVERSATION_MESSAGES_UID = '0a985d59-fd20-4672-91bb-4824b8dfb026';\n\n/**\n * T27 part B — `create-shared-prompt-version`'s own `input` field defs\n * (§3.8 SharedPromptsPage). Validates `@@@langfusePrompt:…@@@` composition\n * tags through `validateReferences` before writing (see that function's\n * own doc) — the ONE write path this page uses, scoped to `shared/*` names.\n */\nexport const CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID = '1039e196-cf6e-438e-8ec9-7ab422feaf4d';\nexport const CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID = '10ffe3e1-972e-43b4-bb45-343c4664464f';\n\n/**\n * `sync-agent-prompt-snapshot`'s own `input` field def (§5.2) — the\n * background refresh of `agent.systemPromptSnapshot` after a `createVersion`\n * /`promote` on that agent's prompt.\n */\nexport const SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID = '2f5d6cbb-1c69-4a76-9d8f-1a3f0a4e57c2';\n","/**\n * `run-triage-now` (§3.5) — `uiInvoke`, manual trigger equivalent to the\n * legacy `POST /triage/run`, and `run-triage-batch`, the event-triggered\n * function that actually carries the batch out.\n *\n * WHY TWO FUNCTIONS (B5). `uiInvoke` is a SYNCHRONOUS request: the platform\n * runs the handler in-process under a wall clock capped at 30 s\n * (`app-sync-invocation.service.ts`'s `DEFAULT_INVOKE_TIMEOUT_MS`, clamped\n * by `APP_SYNC_INVOKE_MAX_MS`). `runTriageBatch` processes up to\n * `settings.batchLimit` tickets (30 by default) SEQUENTIALLY, each costing\n * one triage LLM call plus several Gorgias round trips — minutes, not\n * seconds. Running it inline meant a guaranteed 504 for the operator while\n * the handler kept going unattended, and a second click starting a SECOND\n * concurrent batch: `triage-decision` rows are `create`d, not upserted, so\n * that duplicated both the rows and the LLM bill (only `generated-response`\n * is deduplicated, by its `openTicketKey` unique index).\n *\n * So the invocation now does only what fits in a request — open the run,\n * emit the event — and answers with the `runId` to follow. The batch itself\n * runs in `run-triage-batch`, a durable event-triggered function with no\n * wall clock. This is the platform's own documented pairing: see\n * `AppRunHandle.reused`'s doc in `@apotech-os/app-kit` — \"what links the\n * `uiInvoke` that triggers a treatment to the asynchronous function that\n * carries it out\".\n *\n * RE-ENTRANCE GUARD. `runs.start` is idempotent on `(kind, key)` while a\n * non-terminal run exists, so the fixed `(MANUAL_TRIAGE_RUN_KIND,\n * MANUAL_TRIAGE_RUN_KEY)` pair IS the guard: a second trigger while a batch\n * is in flight gets `reused: true` back, emits nothing, and reports the run\n * already running. The platform holds that state, not this handler — two\n * concurrent invocations cannot both win it, which a read of\n * `pipeline-state.lastTriageAt` could not have guaranteed (its cadence gate\n * is also stamped by the scheduled `triage-tick`, so it cannot tell \"a\n * manual batch is running right now\" from \"a tick just finished\"). The\n * counterpart is that `run-triage-batch` MUST terminate the run on every\n * path, including failure — see its `try`/`catch` below — otherwise the\n * guard would hold the button closed for good.\n *\n * `input.ignoreTriageDisabled` mirrors the legacy `{dry_run}` body field —\n * renamed here (T23 post-review D): it lets an operator ask for a run while\n * `triageEnabled` is off (the settings-level kill switch stays authoritative\n * for `triage-tick`'s own cron, but a human clicking \"run now\" already\n * knows they are overriding it). The legacy name is not worth preserving —\n * §0 defines \"dry run\" as \"no external action\", three sibling functions\n * (`preview-triage`, `graph-dry-run`, `test-agents`) implement exactly that,\n * and this flag does the OPPOSITE: it bypasses a kill switch and runs the\n * real batch. `ignoreTriageDisabled` does NOT change what the batch\n * writes — this function ALWAYS classifies for real and ALWAYS writes\n * `triage-decision`/`generated-response` rows, exactly like a scheduled\n * tick, whether or not the flag is set. The legacy `/triage/run` never\n * wrote anything different for a \"dry run\" either (`dry_run` only bypassed\n * `triage_enabled`) — a fully side-effect-free \"would triage-tick run\"\n * preview is `preview-triage`'s job (single ticket) and `graph-dry-run`'s\n * (full graph), not this one's (a real batch).\n *\n * `minRole: 'EDITOR'`: triggering a real classification pass — which spends\n * LLM budget and can tag/escalate real tickets — is an editing action, not a\n * read. `VIEWER` (T24's `ext-*` floor) would let a read-only support agent\n * fire a batch run; that is not this function's threat model.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { RUN_TRIAGE_NOW_INPUT_IGNORE_TRIAGE_DISABLED_UID } from './ids';\nimport { runTriageBatch } from './triage-tick';\n\n/**\n * The app custom event `run-triage-now` emits and `run-triage-batch`\n * subscribes to. Must be declared in the consuming app's `manifest.emits`\n * (`buildSupportPipeline`'s `emits` fragment) — the platform rejects an\n * undeclared name with 403, and refuses to sync a manifest whose event\n * trigger names one it does not emit.\n */\nexport const TRIAGE_RUN_REQUESTED_EVENT = 'triage.run.requested';\n\n/** `(kind, key)` of the applicative run — fixed, because it IS the re-entrance guard (see this module's header doc). */\nexport const MANUAL_TRIAGE_RUN_KIND = 'run-triage-now';\nexport const MANUAL_TRIAGE_RUN_KEY = 'manual';\n\nexport interface RunTriageNowInput {\n /** Bypasses the `triageEnabled` kill switch and runs the real batch anyway — NOT a dry run (see this module's own header doc). */\n ignoreTriageDisabled?: boolean;\n}\n\nexport interface RunTriageNowResult {\n /** The applicative run to follow (`useAppRuns({kind: 'run-triage-now'})`) — the batch's outcome lives there, not in this response. */\n runId: string;\n /** `'already-running'` when the re-entrance guard matched an in-flight batch and nothing new was queued. */\n status: 'queued' | 'already-running';\n}\n\n/** Payload of `TRIAGE_RUN_REQUESTED_EVENT`, as `run-triage-batch` receives it (the unwrapped event data). */\nexport interface TriageRunRequestedPayload {\n runId?: string;\n ignoreTriageDisabled?: boolean;\n}\n\nexport function buildRunTriageNowFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'run-triage-now'),\n name: 'run-triage-now',\n // The handler is two API calls now, not a batch: a budget well under the\n // platform's 15 s default states that, and turns a hung platform call\n // into a fast error instead of a slow one.\n trigger: { type: 'uiInvoke', minRole: 'EDITOR', timeoutMs: 10_000 },\n input: [\n {\n universalIdentifier: RUN_TRIAGE_NOW_INPUT_IGNORE_TRIAGE_DISABLED_UID,\n name: 'ignoreTriageDisabled',\n type: FieldType.BOOLEAN,\n label: 'Ignore triageEnabled',\n description: 'Bypass the triageEnabled kill switch and run the real batch anyway. This is NOT a dry run — tickets are classified and tagged for real.',\n isNullable: true,\n },\n ],\n };\n}\n\n/**\n * `retries: 0` and `concurrency: 1`, for `triage-tick`'s own reasons: a\n * retried batch re-classifies (and re-bills) every ticket it already\n * handled and writes a second `triage-decision` for each, and two batches\n * running at once over the same view do the same. The re-entrance guard in\n * `run-triage-now` closes the operator-facing door; `concurrency: 1` closes\n * the platform-facing one.\n */\nexport function buildRunTriageBatchFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'run-triage-batch'),\n name: 'run-triage-batch',\n trigger: { type: 'event', name: TRIAGE_RUN_REQUESTED_EVENT },\n retries: 0,\n concurrency: 1,\n notify: { onFailure: true, severity: 'warning' },\n };\n}\n\nexport function createRunTriageNowHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => runTriageNowHandler(ctx as SupportKitHandlerContext, config, (input as RunTriageNowInput) ?? {});\n}\n\nexport function createRunTriageBatchHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) =>\n runTriageBatchEventHandler(ctx as SupportKitHandlerContext, config, (input as TriageRunRequestedPayload) ?? {});\n}\n\nexport async function runTriageNowHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: RunTriageNowInput,\n): Promise<RunTriageNowResult> {\n const ignoreTriageDisabled = input.ignoreTriageDisabled ?? false;\n // Both guards are re-checked by `run-triage-batch` (an event can also be\n // replayed): they run HERE so the operator gets the refusal in their own\n // request, as a message on screen, instead of a queued run that fails out\n // of sight.\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n assertRunnable(ctx, settings, ignoreTriageDisabled);\n\n const run = await ctx.api.runs.start({\n kind: MANUAL_TRIAGE_RUN_KIND,\n key: MANUAL_TRIAGE_RUN_KEY,\n message: 'Triage manuel demandé',\n metadata: { ignoreTriageDisabled },\n });\n if (run.reused) {\n ctx.logger.info('run-triage-now: a manual batch is already running, not queueing a second one', { runId: run.id });\n return { runId: run.id, status: 'already-running' };\n }\n\n try {\n // `_key` deduplicates the emission itself at the Inngest level, so a\n // retried invocation cannot fan out into two batches for one run.\n await ctx.api.events.send(TRIAGE_RUN_REQUESTED_EVENT, {\n _key: run.id,\n runId: run.id,\n ignoreTriageDisabled,\n });\n } catch (err) {\n // A run left open would keep the guard closed forever — nothing else\n // will ever terminate it, since no batch was queued.\n await ctx.api.runs.fail(run.id, { message: err instanceof Error ? err.message : String(err) });\n throw err;\n }\n\n return { runId: run.id, status: 'queued' };\n}\n\nexport async function runTriageBatchEventHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n payload: TriageRunRequestedPayload,\n): Promise<void> {\n const { runId } = payload;\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n\n try {\n assertRunnable(ctx, settings, payload.ignoreTriageDisabled ?? false);\n const result = await runTriageBatch(ctx, config, settings);\n if (runId) await ctx.api.runs.succeed(runId, result);\n } catch (err) {\n if (runId) await ctx.api.runs.fail(runId, { message: err instanceof Error ? err.message : String(err) });\n throw err;\n }\n}\n\n/** The two refusals shared by the trigger and the batch — invalid settings, and the `triageEnabled` kill switch. */\nfunction assertRunnable(ctx: SupportKitHandlerContext, settings: SupportKitSettings, ignoreTriageDisabled: boolean): void {\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(' ')}`);\n }\n if (!ignoreTriageDisabled && !settings.triageEnabled) {\n throw new ctx.NonRetriableError('Triage is disabled (triageEnabled is off) — pass ignoreTriageDisabled to override.');\n }\n}\n","/**\n * `preview-triage` (§3.5) — `uiInvoke`, dry-run classification of ONE\n * ticket, equivalent to the legacy `POST /triage/preview`. Runs\n * `runTicket(deps, {until:'triage'})` — the same checkpoint `triage-tick`\n * uses — but through the recording `state`/`reply` ports (`adapters/\n * recording-ports.ts`, T21) instead of the real Gorgias-writing ones, so\n * nothing is tagged and no `triage-decision`/`generated-response` row is\n * created. `conversation`/`llm`/`prompt` stay the REAL ctx adapters: a\n * preview reads and classifies for real, per §0's dry-run arbitrage\n * (\"aucune action externe (ni réponse, ni tag)\").\n *\n * Narrower than `graph-dry-run`: this stops at the SAME checkpoint\n * `triage-tick` does (triage + escalate only), never drafts. Use\n * `graph-dry-run` to see the full graph, including a draft, for one ticket.\n *\n * `minRole: 'VIEWER'`: a single classification preview spends one LLM call\n * but writes nothing and cannot escalate/send anything for real — the same\n * risk profile as a read.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport { createRecordingReplyPort, createRecordingStatePort } from '../adapters/recording-ports';\nimport { resolveHandledTags } from '../adapters/gorgias-tags';\nimport { createBudget } from '../graph/budget';\nimport { runTicket } from '../graph/run-ticket';\nimport type { Classification, ConversationRef } from '../domain';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { PREVIEW_TRIAGE_INPUT_TICKET_ID_UID } from './ids';\nimport { createNoToolContext } from './no-tool-context';\nimport { buildPromptsTable, draftPromptRefFor, listCategories, resolveDraftAgent, toCategoryReferential } from './records';\n\nexport interface PreviewTriageInput {\n ticketId: string;\n}\n\nexport interface PreviewTriageResult {\n ticketId: string;\n classification: Classification | null;\n escalated: boolean;\n /** Tags the run WOULD have applied. Nothing was applied. */\n wouldHaveTagged: string[];\n}\n\nexport function buildPreviewTriageFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'preview-triage'),\n name: 'preview-triage',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: PREVIEW_TRIAGE_INPUT_TICKET_ID_UID,\n name: 'ticketId',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createPreviewTriageHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => previewTriageHandler(ctx as SupportKitHandlerContext, config, input as unknown as PreviewTriageInput);\n}\n\nexport async function previewTriageHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: PreviewTriageInput,\n): Promise<PreviewTriageResult> {\n const ticketId = input?.ticketId?.trim();\n if (!ticketId) throw new ctx.NonRetriableError('ticketId is required');\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(' ')}`);\n }\n\n const categories = await listCategories(ctx.api);\n const agent = await resolveDraftAgent(ctx.api, null);\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));\n\n const realPorts = buildTicketPorts(ctx);\n const recordingState = createRecordingStatePort(ctx.api);\n const recordingReply = createRecordingReplyPort();\n\n const ref: ConversationRef = { id: ticketId, channel: 'gorgias' };\n const budget = createBudget({ signal: new AbortController().signal, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n\n const state = await runTicket(\n {\n ref,\n profile,\n ports: {\n conversation: realPorts.conversation,\n reply: recordingReply.port,\n llm: realPorts.llm,\n prompt: realPorts.prompt,\n state: recordingState.port,\n clock: realPorts.clock,\n },\n toolContext: createNoToolContext(),\n budget,\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: toCategoryReferential(categories),\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'none' },\n },\n { until: 'triage' },\n );\n\n // `runTicket(deps, {until:'triage'})` deliberately never calls\n // `ports.state.record` (see its own doc in `graph/run-ticket.ts`) — the\n // recording port above never fires for this checkpoint, so the tag set a\n // REAL `triage-tick` would apply is computed here directly, off the same\n // `resolveHandledTags` both the real and recording `StatePort` share. No\n // write happens either way: this is a plain (already-read-only) lookup.\n const wouldHaveTagged = state.classification\n ? await resolveHandledTags(ctx.api, state.classification, profile.audit)\n : [];\n\n return {\n ticketId,\n classification: state.classification,\n escalated: state.escalated,\n wouldHaveTagged,\n };\n}\n","/**\n * `runGraphDryRun` — the graph-dry-run engine itself, split out from\n * `graph-dry-run.ts`'s ctx-wiring/overrides so it can be exercised directly\n * against `graph/run-ticket.fixtures.ts`'s `harness()` (real nodes, fake\n * ports) instead of a fully faked `SupportKitHandlerContext`. §0's dry-run\n * arbitrage: \"graphe complet tant qu'aucune action externe (ni réponse, ni\n * tag, ni écriture de record)\".\n *\n * Takes an already-assembled `NodeDeps` (`base`) — real ports in\n * production (`buildTicketPorts(ctx)`), fake ones in a graph-level test —\n * and overrides exactly the surfaces that could otherwise leak a write:\n * `ports.reply`, `ports.state`, `ports.llm`/`ports.evaluator` (still REAL\n * calls, only their trace is captured) and `send`. `send` is ALWAYS\n * overridden to the recording `{mode:'claimed', ...}` seam, never left as\n * whatever `base.send` was assembled with — a dry run must exercise `act`'s\n * claim→post→commit path for real (so an operator sees the graph actually\n * reach `act`, not silently stop short of it), not skip it because the\n * caller happened to assemble `base` with `{mode:'none'}` (post-T21-review\n * C, `adapters/recording-ports.ts`'s own doc on `createRecordingSendPort`).\n */\nimport { createRecordingLlmPort, createRecordingReplyPort, createRecordingSendPort, createRecordingStatePort } from '../adapters/recording-ports';\nimport type { RecordedCompletion, WouldHaveReplied } from '../adapters/recording-ports';\nimport type { SupportKitApi } from '../adapters/api';\nimport { NODE_NAMES, type NodeDeps, type NodeName, type NodeStep, type TicketRunState } from '../graph/state';\nimport { runTicket, type ResumeFrom } from '../graph/run-ticket';\n\n/**\n * A dry run may not outlive an admin's patience, nor the `uiInvoke`\n * request's own HTTP timeout (T23 post-review C2) — ported from the legacy\n * `DRY_RUN_DEADLINE_MS`. Both `graph-dry-run.ts` (one ticket) and\n * `test-agents.ts` (up to `MAX_LIMIT` tickets, sequential) build their\n * `AbortSignal` from this constant: without it, neither call site ever\n * aborted, so `test-agents` in particular could run up to 100 full graphs\n * with no bound until the platform itself killed the connection mid-flight\n * — every completion already billed, nothing returned to the operator.\n */\nexport const DRY_RUN_DEADLINE_MS = 3 * 60 * 1000;\n\nexport interface GraphDryRunDeps {\n /** Fully assembled `NodeDeps` — `reply`/`state`/`llm`/`evaluator`/`send` are overridden below regardless of what this carries. */\n base: NodeDeps;\n /** For the recording `StatePort`'s category `extraTags` lookup (a real read — see `recording-ports.ts`). */\n api: SupportKitApi;\n resume?: ResumeFrom;\n}\n\nexport interface GraphDryRunResult {\n ticketId: string;\n outcome: TicketRunState['outcome'];\n /** Nodes the graph called, in order. `evaluate` appears twice on a revision. */\n steps: NodeStep[];\n /** Nodes it did not call. */\n skipped: NodeName[];\n completions: RecordedCompletion[];\n /** Tags the run WOULD have applied. Nothing was applied. */\n wouldHaveTagged: string[];\n /** The reply it WOULD have posted, or `null` if `act` never ran. Nothing was posted. */\n wouldHaveReplied: WouldHaveReplied | null;\n /**\n * Whether the run actually reached `act`'s claim/commit seam — proof the\n * send path was exercised, not skipped because `send` defaulted to\n * `{mode: 'none'}` (see this module's own header doc).\n */\n sendSeamExercised: boolean;\n draft: TicketRunState['draft'];\n verdict: TicketRunState['verdict'];\n guardrailHits: string[];\n error?: string;\n}\n\nexport async function runGraphDryRun({ base, api, resume }: GraphDryRunDeps): Promise<GraphDryRunResult> {\n const recordingReply = createRecordingReplyPort();\n const recordingState = createRecordingStatePort(api);\n const recordingSend = createRecordingSendPort();\n const recordingLlm = createRecordingLlmPort(base.ports.llm);\n const recordingEvaluator = base.ports.evaluator ? createRecordingLlmPort(base.ports.evaluator) : null;\n\n const steps: NodeStep[] = [];\n const deps: NodeDeps = {\n ...base,\n ports: {\n ...base.ports,\n reply: recordingReply.port,\n state: recordingState.port,\n llm: recordingLlm.port,\n ...(recordingEvaluator ? { evaluator: recordingEvaluator.port } : {}),\n },\n send: recordingSend.send,\n trace: (step) => steps.push(step),\n };\n\n let result: TicketRunState | null = null;\n let error: string | undefined;\n try {\n result = await runTicket(deps, resume ? { resume } : undefined);\n } catch (err) {\n error = err instanceof Error ? err.message : String(err);\n }\n\n const seen = new Set(steps.map((s) => s.node));\n const completions = [...recordingLlm.completions, ...(recordingEvaluator?.completions ?? [])];\n\n return {\n ticketId: base.ref.id,\n outcome: result?.outcome ?? null,\n steps,\n skipped: NODE_NAMES.filter((name) => !seen.has(name)),\n completions,\n wouldHaveTagged: recordingState.wouldHaveTagged(),\n wouldHaveReplied: recordingReply.wouldHaveReplied(),\n sendSeamExercised: recordingSend.calls.length > 0,\n draft: result?.draft ?? null,\n verdict: result?.verdict ?? null,\n guardrailHits: result?.guardrailHits ?? [],\n ...(error ? { error } : {}),\n };\n}\n","/**\n * `graph-dry-run` (§3.5) — `uiInvoke`, replay of the FULL graph for one\n * ticket, equivalent to the legacy `POST /agents/graph-run`. Ports the\n * `GraphDryRunOverrides` switches from\n * `extension-overview/backoffice/src/services/graphDryRun.ts` verbatim\n * (T21 deferred them here — their semantics are non-obvious, see each\n * function's own doc below) and delegates the actual replay to\n * `runGraphDryRun` (`./graph-dry-run-core.ts`), which owns the\n * zero-external-action guarantee.\n *\n * `minRole: 'EDITOR'` (T23 post-review E): unlike `preview-triage`'s single\n * classification, this replays the FULL graph and can conjure trial\n * evaluate/revise nodes — real LLM spend against the app's shared quota,\n * re-invocable at will. `VIEWER` is the read-only support-agent floor;\n * \"writes nothing to Gorgias\" is the wrong axis to gate on when the\n * resource actually being spent is money.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { AgentProfile, Classification, Conversation } from '../domain';\nimport type { ConversationRef } from '../domain';\nimport type { ConversationPort } from '../graph/ports';\nimport type { EvaluateNodeConfig, ReviseNodeConfig } from '../domain/profile';\nimport { createBudget } from '../graph/budget';\nimport type { NodeDeps } from '../graph/state';\nimport type { ResumeFrom } from '../graph/run-ticket';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { GRAPH_DRY_RUN_INPUT_AGENT_ID_UID, GRAPH_DRY_RUN_INPUT_CATEGORY_ID_UID, GRAPH_DRY_RUN_INPUT_INLINE_TICKET_UID, GRAPH_DRY_RUN_INPUT_OVERRIDES_UID, GRAPH_DRY_RUN_INPUT_TICKET_ID_UID } from './ids';\nimport { createNoToolContext } from './no-tool-context';\nimport {\n buildPromptsTable,\n draftPromptRefFor,\n listCategories,\n resolveDraftAgent,\n toAgent,\n toCategoryReferential,\n} from './records';\nimport { DRY_RUN_DEADLINE_MS, runGraphDryRun, type GraphDryRunResult } from './graph-dry-run-core';\n\nexport interface GraphDryRunOverrides {\n /** Off skips the judge entirely — the graph then ends at `ready`. On conjures a trial judge when the tenant has none. */\n evaluate?: boolean;\n /** Off makes `needsRevision` always false. On resolves a revision node from the writer's model when the tenant has none. */\n revise?: boolean;\n /** Off empties the guardrail catalogue and forces `whatsappMode: 'auto_reply'`, to reach `act` without a hold. */\n guardrails?: boolean;\n /** On opens auto-send for this run only (still requires a real `senderEmail`). */\n autoSend?: boolean;\n}\n\n/**\n * A ticket typed by hand instead of read from Gorgias. `channel` is not\n * cosmetic: `sourceChannel === 'whatsapp'` is what the `whatsapp_stop` /\n * `not_customer_turn` guardrails and the WhatsApp style prompt key off\n * (`domain/conversation.ts`'s own contract note), so a pasted WhatsApp\n * message must be replayable as one.\n */\nexport interface GraphDryRunInlineTicket {\n /** The customer's message. The only required part — everything else has a defensible default. */\n body: string;\n subject?: string | null;\n channel?: 'email' | 'whatsapp';\n}\n\n/**\n * Every field is `| null` rather than merely optional, because the platform\n * validates this payload against the manifest with `fieldDefsToZod`\n * (`app-input-validation.ts`), where `isNullable: true` permits the VALUE\n * null but NOT an absent key — an omitted optional field is rejected with\n * `422 INVALID_INPUT` before the handler runs. Callers therefore send every\n * declared key, `null` when unset, and this type says so.\n */\nexport interface GraphDryRunInput {\n /** Mutually exclusive with `inlineTicket` — exactly one of the two. */\n ticketId?: string | null;\n /** Replay on a ticket that does not exist in Gorgias (see below). */\n inlineTicket?: GraphDryRunInlineTicket | null;\n /** Forces the writing agent; falls back to the category's, then to the default one. */\n agentId?: string | null;\n /** Forces the category — and with it the classification, so triage does not run. */\n categoryId?: string | null;\n overrides?: GraphDryRunOverrides | null;\n}\n\n/**\n * The revision switch (ported verbatim from `GraphDryRunOverrides.revise`'s\n * legacy doc): `false` removes the node; `true` CONJURES one from the\n * writer's own model when the tenant has none configured, so an operator\n * can try the correction pass on one ticket before turning it on for\n * everybody. `reasoning: 'off'` is required here — an unconfigured trial\n * revise node must never be rejected by a (model, effort) validation rule\n * the tenant never opted into.\n */\nfunction resolveReviseNode(profile: AgentProfile, override: boolean | undefined): ReviseNodeConfig | null {\n if (override === false) return null;\n if (profile.nodes.revise) return profile.nodes.revise;\n if (override !== true) return null;\n const writer = profile.nodes.draft;\n return writer ? { model: writer.model, provider: writer.provider, reasoning: 'off' } : null;\n}\n\n/**\n * The `evaluate` switch, in its FORCING direction (`true`): a tenant with no\n * judge gets a trial one, model left to the prompt (kit's own resolution),\n * threshold pinned to the tenant's own auto-send floor. `false` empties the\n * node outright — `applyOverrides` below is what does that, this helper\n * only ever ADDS a node.\n */\nfunction withTrialJudge(profile: AgentProfile, override: boolean | undefined): AgentProfile {\n if (override !== true || profile.nodes.evaluate) return profile;\n const trial: EvaluateNodeConfig = {\n model: profile.nodes.draft?.model ?? '',\n provider: 'openai',\n reasoning: 'off',\n minConfidence: profile.autoSend.minConfidence,\n escalationEnabled: false,\n };\n return { ...profile, nodes: { ...profile.nodes, evaluate: trial } };\n}\n\n/** Turns the per-run switches into a profile the graph reads normally — never persisted. */\nfunction applyOverrides(profile: AgentProfile, overrides: GraphDryRunOverrides): AgentProfile {\n const withEvaluate = overrides.evaluate === false ? { ...profile, nodes: { ...profile.nodes, evaluate: null } } : withTrialJudge(profile, overrides.evaluate);\n\n return {\n ...withEvaluate,\n nodes: { ...withEvaluate.nodes, revise: resolveReviseNode(withEvaluate, overrides.revise) },\n // `auto_reply`, not `draft_only`: `draft_only` blocks `isAutoSendEligible`\n // outright for a WhatsApp ticket, which would stop the run at `ready`\n // and defeat the whole point of this override — reaching `act` with\n // nothing standing in the way. The category opt-in is bypassed the same\n // way triage-tick's own dry-run-adjacent callers do it (see below,\n // `category: {autoReplyEnabled: true, …}`).\n //\n // `judgemeEscalateOnly: false` (T23 post-review C1): that rule is NOT\n // filtered through `active` (`graph/nodes/guardrails.ts` checks it\n // unconditionally) and `settingsToProfile` hardcodes it to `true` with\n // no settings surface to turn it off — so without this, an operator\n // dry-running a Judge.me ticket with guardrails off still gets held by\n // a guardrail this override exists specifically to bypass.\n guardrails:\n overrides.guardrails === false\n ? { active: [], params: { ...withEvaluate.guardrails.params, whatsappMode: 'auto_reply', judgemeEscalateOnly: false } }\n : withEvaluate.guardrails,\n autoSend: { ...withEvaluate.autoSend, enabled: overrides.autoSend === true && !!withEvaluate.autoSend.senderEmail },\n };\n}\n\n/**\n * The classification a forced category stands for. Confidence is `high` on\n * purpose: the operator asked for THIS category, so the run must not then\n * be held by the `triage_not_high` guardrail for a decision they made\n * themselves. Never claims the conversation is over on the operator's\n * behalf.\n */\nfunction forcedClassification(tagName: string): Classification {\n return { category: tagName, confidence: 'high', reasoning: 'operator: catégorie forcée', isFallback: false, conversationOver: false };\n}\n\n/**\n * The id a pasted ticket runs under. Not a Gorgias id and never mistakable\n * for one: it appears in the result, in the recorded tags and in the\n * would-have-replied payload, and reading it as a real ticket number would\n * send someone looking for a ticket that does not exist.\n */\nexport const INLINE_TICKET_ID = 'ticket-saisi';\n\n/**\n * A `ConversationPort` over a typed-in ticket — the ONE port that still\n * reached Gorgias during a dry run (`reply`/`state`/`send` are already\n * swapped for recorders by `runGraphDryRun`, and the read tools are\n * neutralised by `createNoToolContext`). With this in its place a dry run\n * touches no Gorgias endpoint at all.\n *\n * `read` returns the SAME conversation object on every call, which matters\n * for `act`: it re-reads the conversation right before sending and holds\n * the reply when `messageCount` has moved (the I8 anti-divergence check).\n * A port that rebuilt a fresh object per call would be fine today, but one\n * that recomputed the count from anything time-dependent would hold every\n * pasted run for a collision that never happened.\n *\n * `listPending` returns nothing: a pasted ticket belongs to no view, and\n * this port is only ever assembled for a single-ticket replay.\n */\nfunction createInlineConversationPort(ticket: GraphDryRunInlineTicket, now: Date): ConversationPort {\n const conversation: Conversation = {\n ref: { id: INLINE_TICKET_ID, channel: 'gorgias' },\n subject: ticket.subject?.trim() ? ticket.subject.trim() : null,\n messages: [{ role: 'user', content: ticket.body }],\n customer: { name: null, email: null, orderContext: null },\n isClosed: false,\n lastMessageAt: now,\n messageCount: 1,\n // No agent ever answered a ticket that was just typed: `null` is the\n // truth, and it is also what keeps `not_customer_turn` from holding the\n // run before a single node has looked at the text.\n lastAgentReplyAt: null,\n hasCustomerAttachment: false,\n // `sourceChannel`, NOT `ref.channel`: the latter names the ADAPTER\n // (gorgias) while every channel guardrail and the style prompt read this\n // one (`domain/conversation.ts`).\n sourceChannel: ticket.channel ?? 'email',\n };\n return {\n listPending: async () => [],\n read: async () => conversation,\n };\n}\n\nexport function buildGraphDryRunFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'graph-dry-run'),\n name: 'graph-dry-run',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n // Nullable since the pasted-ticket mode: the handler enforces \"exactly\n // one of ticketId/inlineTicket\", which a per-field flag cannot express.\n { universalIdentifier: GRAPH_DRY_RUN_INPUT_TICKET_ID_UID, name: 'ticketId', type: FieldType.TEXT, label: 'Ticket id', isNullable: true },\n {\n universalIdentifier: GRAPH_DRY_RUN_INPUT_INLINE_TICKET_UID,\n name: 'inlineTicket',\n type: FieldType.JSON,\n label: 'Inline ticket',\n description: '{body, subject?, channel?} — replays a typed-in ticket instead of reading one from Gorgias.',\n isNullable: true,\n },\n { universalIdentifier: GRAPH_DRY_RUN_INPUT_AGENT_ID_UID, name: 'agentId', type: FieldType.TEXT, label: 'Agent id', isNullable: true },\n { universalIdentifier: GRAPH_DRY_RUN_INPUT_CATEGORY_ID_UID, name: 'categoryId', type: FieldType.TEXT, label: 'Category id', isNullable: true },\n {\n universalIdentifier: GRAPH_DRY_RUN_INPUT_OVERRIDES_UID,\n name: 'overrides',\n type: FieldType.JSON,\n label: 'Overrides',\n description: '{evaluate?, revise?, guardrails?, autoSend?}',\n isNullable: true,\n },\n ],\n };\n}\n\nexport function createGraphDryRunHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => graphDryRunHandler(ctx as SupportKitHandlerContext, config, input as unknown as GraphDryRunInput);\n}\n\nexport async function graphDryRunHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: GraphDryRunInput,\n): Promise<GraphDryRunResult> {\n const ticketId = input?.ticketId?.trim();\n const inlineBody = input?.inlineTicket?.body?.trim();\n // Exactly one of the two. Refusing BOTH rather than silently preferring one\n // matters: a caller that sends a ticket id AND a pasted body has a bug, and\n // reading the wrong one would produce a plausible result about the wrong\n // ticket entirely.\n if (ticketId && inlineBody) throw new ctx.NonRetriableError('Provide either ticketId or inlineTicket, not both');\n if (!ticketId && !inlineBody) throw new ctx.NonRetriableError('ticketId or inlineTicket.body is required');\n const inlineTicket = inlineBody ? { ...(input.inlineTicket as GraphDryRunInlineTicket), body: inlineBody } : null;\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(' ')}`);\n }\n\n const categories = await listCategories(ctx.api);\n const forcedCategory = input.categoryId ? (categories.find((c) => c.id === input.categoryId) ?? null) : null;\n if (input.categoryId && !forcedCategory) throw new ctx.NonRetriableError(`Category \"${input.categoryId}\" not found`);\n\n const agent = input.agentId\n ? toAgent(await ctx.api.get('agent', input.agentId))\n : await resolveDraftAgent(ctx.api, forcedCategory?.agentId ?? null);\n\n const baseProfile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));\n const profile = applyOverrides(baseProfile, input.overrides ?? {});\n\n const realPorts = buildTicketPorts(ctx);\n const ref: ConversationRef = { id: inlineTicket ? INLINE_TICKET_ID : (ticketId as string), channel: 'gorgias' };\n const budget = createBudget({ signal: AbortSignal.timeout(DRY_RUN_DEADLINE_MS), maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n\n const base: NodeDeps = {\n ref,\n profile,\n ports: {\n conversation: inlineTicket ? createInlineConversationPort(inlineTicket, realPorts.clock.now()) : realPorts.conversation,\n reply: realPorts.reply,\n llm: realPorts.llm,\n prompt: realPorts.prompt,\n state: realPorts.state,\n clock: realPorts.clock,\n },\n toolContext: createNoToolContext(),\n budget,\n // Bypassed the same way `triage-tick`'s dry-run-adjacent batch is:\n // reaching `act` is what the `autoSend` override is for, and requiring\n // the category to ALSO have opted in would make the override inert on\n // every category that has auto-reply off — which is all of them today.\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: toCategoryReferential(categories),\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'none' }, // overridden unconditionally by `runGraphDryRun`\n };\n\n const resume: ResumeFrom | undefined = forcedCategory\n ? { classification: forcedClassification(forcedCategory.tagName), escalated: false }\n : undefined;\n\n return runGraphDryRun({ base, api: ctx.api, resume });\n}\n","/**\n * `test-agents` (§3.5) — `uiInvoke`, multi-ticket bench (legacy\n * `POST /agents/test`): runs `graph-dry-run`'s SAME zero-write replay\n * (`runGraphDryRun`, `./graph-dry-run-core.ts`) over either a Gorgias view\n * or an explicit list of ticket ids, so an operator can see what an agent\n * WOULD produce across a batch before turning it loose — nothing tagged,\n * nothing sent, nothing recorded, per §0's dry-run arbitrage.\n *\n * No `GraphDryRunOverrides` here (unlike `graph-dry-run`, which exists\n * precisely to explore an OFF branch on one ticket): a bench is only\n * useful if it reports what the agent does with its REAL configuration,\n * across many tickets — overriding it would just report the same forced\n * branch N times.\n *\n * `category.autoReplyEnabled` is the ONE exception to that, and it is\n * reported as such (T23 post-review C3): the per-ticket category is only\n * known once TRIAGE runs, which happens INSIDE the same full-graph replay\n * this function triggers — there is no category to read a real flag off of\n * before the run starts. `graph-dry-run` can justify forcing it to `true`\n * unconditionally (reaching `act` is that function's whole purpose); a bench\n * with no override cannot make the same claim, so `TestAgentsResult` carries\n * `autoReplyForced: true` alongside every run's outcome — an operator\n * reading \"would have sent\" across a batch sees, in the same response, that\n * every category's own auto-reply setting was bypassed to get there.\n *\n * Sequential on purpose: a batch runs the LLM/Gorgias reads for real\n * (§0/§3.5), and a small, predictable concurrency of 1 is the safer default\n * for a bench an operator triggers by hand — this can grow a concurrency\n * knob later without changing the contract.\n *\n * `minRole: 'EDITOR'` (T23 post-review E): up to `MAX_LIMIT` full graph\n * replays per invocation is real LLM spend against the app's shared quota,\n * not a read — `VIEWER` is the wrong floor for a tool that can burn budget\n * this fast, re-invocable at will.\n *\n * `DRY_RUN_DEADLINE_MS` bounds the WHOLE bench, not each ticket (T23\n * post-review C2, ported from the legacy's single-ticket deadline): past\n * it, the loop stops starting new replays and returns whatever finished —\n * partial results the operator can read, instead of the `uiInvoke` request\n * dying at the platform's own HTTP timeout with nothing returned and every\n * completion so far already billed.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { ConversationRef } from '../domain';\nimport { createBudget } from '../graph/budget';\nimport type { NodeDeps } from '../graph/state';\nimport type { SupportKitSettings } from '../settings/to-profile';\nimport { settingsToProfile } from '../settings/to-profile';\nimport { validateSettings } from '../settings/validate';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { buildTicketPorts, DEFAULT_MAX_TOOL_CALLS } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { DRY_RUN_DEADLINE_MS, runGraphDryRun, type GraphDryRunResult } from './graph-dry-run-core';\nimport { TEST_AGENTS_INPUT_AGENT_ID_UID, TEST_AGENTS_INPUT_LIMIT_UID, TEST_AGENTS_INPUT_TICKET_IDS_UID, TEST_AGENTS_INPUT_VIEW_ID_UID } from './ids';\nimport { createNoToolContext } from './no-tool-context';\nimport { buildPromptsTable, draftPromptRefFor, listCategories, resolveDraftAgent, toAgent, toCategoryReferential } from './records';\n\nconst DEFAULT_LIMIT = 20;\nconst MAX_LIMIT = 100;\n\nexport interface TestAgentsInput {\n viewId?: string;\n ticketIds?: string[];\n /** Forces the writing agent; falls back to the default one. */\n agentId?: string;\n limit?: number;\n}\n\nexport interface TestAgentsResult {\n results: GraphDryRunResult[];\n /**\n * `true` when every result above ran with `category.autoReplyEnabled`\n * forced on, regardless of that ticket's own category setting (T23\n * post-review C3) — see this module's own header doc for why a bench\n * cannot know the real per-category flag ahead of triage.\n */\n autoReplyForced: true;\n}\n\nexport function buildTestAgentsFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'test-agents'),\n name: 'test-agents',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n { universalIdentifier: TEST_AGENTS_INPUT_VIEW_ID_UID, name: 'viewId', type: FieldType.TEXT, label: 'View id', isNullable: true },\n { universalIdentifier: TEST_AGENTS_INPUT_TICKET_IDS_UID, name: 'ticketIds', type: FieldType.JSON, label: 'Ticket ids', description: 'string[]', isNullable: true },\n { universalIdentifier: TEST_AGENTS_INPUT_AGENT_ID_UID, name: 'agentId', type: FieldType.TEXT, label: 'Agent id', isNullable: true },\n { universalIdentifier: TEST_AGENTS_INPUT_LIMIT_UID, name: 'limit', type: FieldType.NUMBER, label: 'Limit', isNullable: true },\n ],\n };\n}\n\nexport function createTestAgentsHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => testAgentsHandler(ctx as SupportKitHandlerContext, config, input as unknown as TestAgentsInput);\n}\n\nexport async function testAgentsHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: TestAgentsInput,\n): Promise<TestAgentsResult> {\n const explicitIds = (input?.ticketIds ?? []).map((id) => id.trim()).filter(Boolean);\n const viewId = input?.viewId?.trim();\n if (!viewId && explicitIds.length === 0) {\n throw new ctx.NonRetriableError('Either viewId or ticketIds is required');\n }\n\n const settings = await ctx.api.settings.get<SupportKitSettings>();\n const issues = validateSettings(settings as unknown as Record<string, unknown>);\n if (issues.length > 0) {\n throw new ctx.NonRetriableError(`Settings are invalid: ${issues.map((i) => i.message).join(' ')}`);\n }\n\n const limit = Math.min(input?.limit ?? DEFAULT_LIMIT, MAX_LIMIT);\n const categories = await listCategories(ctx.api);\n const agent = input.agentId ? toAgent(await ctx.api.get('agent', input.agentId)) : await resolveDraftAgent(ctx.api, null);\n const profile = settingsToProfile(settings, buildPromptsTable(config, draftPromptRefFor(agent, config), settings.nodes));\n\n const realPorts = buildTicketPorts(ctx);\n const refs: ConversationRef[] = explicitIds.length\n ? explicitIds.slice(0, limit).map((id) => ({ id, channel: 'gorgias' as const }))\n : await realPorts.conversation.listPending({ viewOrTag: viewId! }, limit);\n\n // One deadline for the WHOLE bench (T23 post-review C2), not one per\n // ticket: past it, the loop below stops starting new replays rather than\n // let the platform's own HTTP timeout kill the request with nothing\n // returned. Every ticket's `Budget` shares this same signal, so an\n // in-flight LLM call is aborted at the same wall-clock moment the loop\n // itself gives up.\n const deadline = AbortSignal.timeout(DRY_RUN_DEADLINE_MS);\n\n const results: GraphDryRunResult[] = [];\n for (const ref of refs) {\n if (deadline.aborted) break; // partial results: the bench is out of time, not any one ticket\n const budget = createBudget({ signal: deadline, maxToolCalls: profile.nodes.draft?.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS });\n const base: NodeDeps = {\n ref,\n profile,\n ports: {\n conversation: realPorts.conversation,\n reply: realPorts.reply,\n llm: realPorts.llm,\n prompt: realPorts.prompt,\n state: realPorts.state,\n clock: realPorts.clock,\n },\n toolContext: createNoToolContext(),\n budget,\n category: { autoReplyEnabled: true, minConfidence: null },\n categories: toCategoryReferential(categories),\n log: (msg) => ctx.logger.debug(msg),\n send: { mode: 'none' }, // overridden unconditionally by `runGraphDryRun`\n };\n results.push(await runGraphDryRun({ base, api: ctx.api }));\n }\n\n return { results, autoReplyForced: true };\n}\n","/**\n * `validateReferences` — save-time validation for a prompt-composition tag\n * (`@@@langfusePrompt:name=…|label=…@@@` or `|version=…@@@`), ported from\n * legacy `services/promptReferences.ts`. Deferred by T19 (its own module doc\n * on `prompts/references.ts`: \"an admin save-time validator with no runtime-\n * resolution caller in this kit … out of scope for T19\") and picked up here\n * because `suggest-prompt` (§3.5) is the kit's first WRITE path for a\n * prompt's content — nothing gated writes before this.\n *\n * Five error classes, all five kept:\n * 1. Malformed tag (`findMalformedTags`) — a typo'd `label`/`version`\n * keyword, or a missing closing `@@@`.\n * 2. Self-reference — a prompt referencing its own name.\n * 3. Unresolvable target — the referenced prompt/version/label could not\n * be fetched (missing, or Langfuse unreachable; both read the same\n * here, same as legacy).\n * 4. A cycle back to the prompt being saved.\n * 5. A chain longer than the runtime resolver ever actually walks\n * (T23 post-review B1, below).\n *\n * Class 1 is now STRICTLY MORE IMPORTANT than in the legacy: Langfuse used\n * to store a typo'd tag as literal text and its own resolver caught DEEPER\n * cycles on the well-formed ones — but `createPromptResolver`\n * (`prompts/resolver.ts`) now resolves composition itself, reading raw\n * content via `resolve:false` and never asking Langfuse to flatten\n * anything. A typo'd tag saved here reaches the LLM completely verbatim,\n * with NOTHING server-side left to catch it — this validator is the sole\n * arbiter, at save time, of whether that string means anything at all.\n *\n * Class 4 is deepened past legacy's one hop for the identical reason:\n * legacy's own comment justified checking only one level with \"deeper\n * cycles are rejected by Langfuse's own resolver at fetch time\" — that\n * resolver is never consulted anymore (composition is entirely the kit's\n * own `resolveComposition`, `prompts/resolver.ts`), so a 2+-hop cycle saved\n * here would previously have gone uncaught at write time. `resolver.ts`'s\n * OWN runtime composition pass already survives a cycle at read time\n * (`visited`/`MAX_COMPOSITION_DEPTH`, degrading it to empty text) — this\n * validator closes the save-time half of the same gap: catching the\n * mistake when it is made, not silently degrading it forever after.\n *\n * Class 5 (T23 post-review B1) closes a DIFFERENT gap the cycle walk above\n * never covered: a purely LINEAR chain, A→B→C→D→E→F, has no cycle at all,\n * yet `resolver.ts`'s own `MAX_COMPOSITION_DEPTH` (imported below, not\n * restated — the previous revision claimed to mirror it while actually\n * enforcing an unrelated `MAX_CYCLE_DEPTH` that only ever bounded the CYCLE\n * walk's recursion) silently strips whatever sits past that depth at read\n * time. Without this check, such a chain \"saves fine\" and an operator only\n * discovers the loss when the composed prompt quietly stops including its\n * last segment.\n *\n * `MAX_CYCLE_DEPTH` remains its own, separate, larger safety valve: it\n * exists only so an adversarial/cyclic graph the cycle walk is exploring\n * cannot recurse forever, and has nothing to say about how long a valid\n * chain may be — that is `MAX_COMPOSITION_DEPTH`'s job, enforced by class 5.\n */\nimport { AppApiError } from '@apotech-os/app-kit';\nimport type { SupportKitApi } from '../adapters/api';\nimport { MAX_COMPOSITION_DEPTH } from '../prompts/resolver';\nimport { parseReferences, REFERENCE_TAG_SOURCE, type PromptReference } from '../prompts/references';\n\nconst LITERAL_PREFIX = '@@@langfusePrompt:';\nconst MALFORMED_SNIPPET_MAX_LEN = 60;\n/**\n * Bounds the CYCLE WALK's own recursion on adversarial/cyclic content — kept\n * deliberately larger than `MAX_COMPOSITION_DEPTH` (a valid, acyclic chain\n * that merely runs past the runtime cap is class 5's job, reported\n * separately and more usefully than \"cycle walk gave up\").\n */\nconst MAX_CYCLE_DEPTH = 10;\n\n/** Same grammar `parseReferences` matches (`prompts/references.ts`'s exported source) — a single definition, so the two can never drift apart (T23 post-review B3). */\nconst REF_RE = new RegExp(REFERENCE_TAG_SOURCE, 'g');\n\n/** A short, human-readable excerpt of the malformed tag, for the error message. */\nfunction snippetAt(content: string, index: number): string {\n const rest = content.slice(index);\n const closingIdx = rest.indexOf('@@@', LITERAL_PREFIX.length);\n const snippet = closingIdx === -1 ? rest.slice(0, MALFORMED_SNIPPET_MAX_LEN) : rest.slice(0, closingIdx + 3);\n return snippet.length > MALFORMED_SNIPPET_MAX_LEN ? `${snippet.slice(0, MALFORMED_SNIPPET_MAX_LEN)}…` : snippet;\n}\n\n/** Every literal `@@@langfusePrompt:` occurrence NOT part of a well-formed tag `parseReferences` would have matched. */\nfunction findMalformedTags(content: string): string[] {\n if (!content.includes(LITERAL_PREFIX)) return [];\n const validStarts = new Set([...content.matchAll(REF_RE)].map((m) => m.index ?? -1));\n const malformed: string[] = [];\n for (const m of content.matchAll(new RegExp(LITERAL_PREFIX, 'g'))) {\n const index = m.index ?? -1;\n if (!validStarts.has(index)) malformed.push(snippetAt(content, index));\n }\n return malformed;\n}\n\n/** Where a reference points, for an error message (\"version 3\" / label \"production\"). */\nfunction locatorFor(ref: PromptReference): string {\n return ref.version !== undefined ? `version ${ref.version}` : `label \"${ref.label}\"`;\n}\n\ninterface FetchedTarget {\n content: string;\n}\n\n/**\n * A reference target that failed to fetch, distinguishing WHY (M1, T25\n * review): `forbidden` (a 403 — the target exists but is outside this app's\n * `role.prompts` allowlist) is a misconfiguration to fix in the manifest, not\n * a typo'd or genuinely absent prompt name — reporting the two identically\n * sends an operator chasing a \"not found\" prompt that Langfuse would show\n * them exists.\n */\ninterface FetchFailure {\n forbidden: boolean;\n}\n\ntype FetchResult = FetchedTarget | FetchFailure;\n\nfunction isFetchFailure(result: FetchResult): result is FetchFailure {\n return !('content' in result);\n}\n\n/** Stable dedupe key for a reference target — a version-pinned ref and a label-pinned ref never collide, mirroring `resolver.ts`'s own `memoryKey`. */\nfunction targetKey(ref: PromptReference): string {\n return ref.version !== undefined ? `${ref.name}::v${ref.version}` : `${ref.name}::${ref.label}`;\n}\n\n/** `ctx.api.prompts.get(name, {label|version, resolve:false})` — a `FetchFailure` on any error, `forbidden` set only for a 403 (`AppApiError`). */\nasync function fetchTarget(api: SupportKitApi, ref: PromptReference): Promise<FetchResult> {\n try {\n const detail = await api.prompts.get(ref.name, {\n resolve: false,\n ...(ref.version !== undefined ? { version: ref.version } : { label: ref.label }),\n });\n return { content: detail.content };\n } catch (err) {\n return { forbidden: err instanceof AppApiError && err.status === 403 };\n }\n}\n\n/**\n * `fetchTarget`, deduped against `cache` (T23 post-review B2). The legacy\n * gap this closes: the cycle walk used to re-fetch a target the main loop\n * had just fetched, then re-fetch it again on every alternation of an\n * unrelated cycle it stumbled into — this is the one seam both the main\n * loop and the cycle/depth walks below share, so a given (name, version|label)\n * is ever fetched at most once per `validateReferences` call.\n */\nasync function fetchTargetCached(api: SupportKitApi, ref: PromptReference, cache: Map<string, FetchResult>): Promise<FetchResult> {\n const key = targetKey(ref);\n const cached = cache.get(key);\n if (cached) return cached;\n const target = await fetchTarget(api, ref);\n cache.set(key, target);\n return target;\n}\n\n/**\n * Walks the reference chain rooted at `content` looking for a hop back to\n * `origin` (the prompt being validated). `visited` (T23 post-review B2) is\n * THIS walk's own dedupe: once a target has been explored and did not lead\n * back to `origin`, revisiting it can only repeat the same negative answer —\n * skipping it turns \"re-walked alternately to `MAX_CYCLE_DEPTH`\" into \"walked\n * once\". `depth` still bounds the walk independently, for a graph `visited`\n * has not yet caught up with.\n */\nasync function hasPathToOrigin(\n api: SupportKitApi,\n content: string,\n origin: string,\n depth: number,\n cache: Map<string, FetchResult>,\n visited: Set<string>,\n): Promise<boolean> {\n if (depth > MAX_CYCLE_DEPTH) return false;\n\n for (const ref of parseReferences(content)) {\n if (ref.name === origin) return true;\n\n const key = targetKey(ref);\n if (visited.has(key)) continue;\n visited.add(key);\n\n const target = await fetchTargetCached(api, ref, cache);\n if (isFetchFailure(target)) continue; // unresolvable — reported separately, not a cycle\n\n if (await hasPathToOrigin(api, target.content, origin, depth + 1, cache, visited)) return true;\n }\n return false;\n}\n\n/**\n * Whether `content`'s reference chain runs past `MAX_COMPOSITION_DEPTH` —\n * the exact point `resolver.ts`'s own `composeReferences` stops following a\n * chain and silently strips whatever is left (T23 post-review B1). Mirrors\n * that function's `depth`/cap arithmetic precisely: `content` itself is\n * depth 0 (the prompt being saved, not yet fetched), each reference target\n * is one level deeper, and a target reached at `depth >= MAX_COMPOSITION_DEPTH`\n * is exactly the one the resolver would compose without following further —\n * anything nested inside IT is what gets silently lost at runtime.\n *\n * `visited` mirrors `resolver.ts`'s own cycle guard (keyed by prompt NAME,\n * same as `resolveOneReference`'s `visited.has(ref.name)`): a name already\n * on the path is a cycle, which the runtime resolver degrades to empty text\n * at THAT point regardless of depth, and which class 4 above already\n * reports on its own terms — without this, a short unrelated cycle inside\n * an otherwise-fine chain would recurse forever instead of matching what\n * the resolver actually does with it.\n */\nasync function exceedsCompositionDepth(\n api: SupportKitApi,\n content: string,\n depth: number,\n cache: Map<string, FetchResult>,\n visited: ReadonlySet<string>,\n): Promise<boolean> {\n const refs = parseReferences(content);\n if (refs.length === 0) return false;\n if (depth >= MAX_COMPOSITION_DEPTH) return true;\n\n for (const ref of refs) {\n if (visited.has(ref.name)) continue; // a cycle — reported separately by class 4, not a depth issue\n const target = await fetchTargetCached(api, ref, cache);\n if (isFetchFailure(target)) continue; // unresolvable — reported separately, not a depth issue\n if (await exceedsCompositionDepth(api, target.content, depth + 1, cache, new Set([...visited, ref.name]))) return true;\n }\n return false;\n}\n\n/**\n * Validate every reference tag in `content` (the prompt named `selfName`\n * about to be saved). Returns human-readable error strings; an empty array\n * means the content is valid.\n */\nexport async function validateReferences(api: SupportKitApi, content: string, selfName: string): Promise<string[]> {\n const errors: string[] = [];\n const cache = new Map<string, FetchResult>();\n\n for (const snippet of findMalformedTags(content)) {\n errors.push(`Malformed reference tag near \"${snippet}\": it will be saved as literal text instead of being resolved.`);\n }\n\n for (const ref of parseReferences(content)) {\n if (ref.name === selfName) {\n errors.push(`Reference \"${ref.raw}\" points to this same prompt (\"${selfName}\") — a prompt cannot reference itself.`);\n continue;\n }\n\n const target = await fetchTargetCached(api, ref, cache);\n if (isFetchFailure(target)) {\n errors.push(\n target.forbidden\n ? `Reference \"${ref.raw}\" points to prompt \"${ref.name}\", which exists but is outside this app's prompts allowlist (role.prompts) — it cannot be composed here even though it can be read elsewhere.`\n : `Reference \"${ref.raw}\" could not be resolved: prompt \"${ref.name}\" with ${locatorFor(ref)} was not found, or the prompt store could not be reached to verify it.`,\n );\n continue;\n }\n\n if (await hasPathToOrigin(api, target.content, selfName, 1, cache, new Set([targetKey(ref)]))) {\n errors.push(`Reference \"${ref.raw}\" creates a cycle: prompt \"${ref.name}\" (transitively) references this prompt (\"${selfName}\").`);\n }\n }\n\n if (errors.length === 0 && (await exceedsCompositionDepth(api, content, 0, cache, new Set([selfName])))) {\n errors.push(\n `Reference chain exceeds the runtime composition cap (${MAX_COMPOSITION_DEPTH} levels): the segment past that depth would be silently stripped when this prompt is resolved.`,\n );\n }\n\n return errors;\n}\n","/**\n * `suggest-prompt` (§3.5) — `uiInvoke`, LLM prompt suggestion from an\n * agent's `response-comparison` corrections, equivalent to legacy\n * `POST /models/:id/prompt-versions/suggest`. Writes with\n * `ctx.api.prompts.createVersion(...)` (S3), tag `ai_suggested`, gated by\n * `validateReferences` (`./validate-references.ts`, T19's deferred\n * validator) BEFORE the write — the first prompt-content write path in the\n * kit, and the first place a malformed/self-referencing/cyclic reference tag\n * could otherwise reach a live prompt.\n *\n * WHAT THIS CANNOT RECORD (T19): `CreatePromptVersionInput` is\n * `{content, labels?, tags?}` — no `config`, no `commitMessage`. Two losses\n * versus the legacy, both accepted here rather than invented on the\n * platform surface:\n * - No `commitMessage`: legacy wrote\n * `\"AI-suggested based on N comparisons from vX\"` as the version's own\n * changelog entry. That narrative has nowhere to go — the new version\n * carries no explanation of why it exists beyond the `ai_suggested` tag.\n * - No `config`: legacy explicitly inherited the ACTIVE version's model\n * config (\"a suggestion never silently resets a tuned temperature back\n * to the default\"). A version created here carries none — an operator\n * who tuned a model/temperature on the active version loses that\n * tuning the moment they accept a suggestion, silently, until S3 grows\n * a `config` field.\n *\n * `minRole: 'EDITOR'`: this writes a new prompt version (Langfuse), even\n * though it never PROMOTES it to `production` — creating one is still an\n * editing action, not a read.\n */\nimport { AppApiError, FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { SUGGEST_PROMPT_INPUT_AGENT_ID_UID, SUGGEST_PROMPT_INPUT_MAX_COMPARISONS_UID } from './ids';\nimport { resolvePromptName } from '../prompts/slots';\nimport { toAgent } from './records';\nimport { validateReferences } from './validate-references';\n\nconst DEFAULT_MAX_COMPARISONS = 50;\nconst MIN_COMPARISONS_REQUIRED = 3;\n\n/**\n * Level-3 fallback for the `suggest` slot (§3.7 point 3: \"fallback in-code\n * du kit, surchargé par `config.defaults.prompts`\") — used only when the\n * slot has no `production` version yet in the prompt store.\n */\nconst DEFAULT_SUGGEST_META_PROMPT = [\n 'Tu es un expert en rédaction de prompts système pour des assistants IA de support client.',\n \"Analyse les différences entre les réponses de l'IA et celles des agents humains dans les exemples fournis.\",\n 'Identifie les patterns récurrents (ton, structure, longueur, formulations) puis réécris le prompt système actuel pour en corriger les écarts.',\n 'Retourne UNIQUEMENT le texte du prompt système amélioré, sans explication ni mise en forme markdown.',\n \"Toute balise de référence de la forme @@@langfusePrompt:...@@@ présente dans le prompt actuel doit être reproduite telle quelle, sans modification.\",\n].join('\\n');\n\nexport interface SuggestPromptInput {\n agentId: string;\n maxComparisons?: number;\n}\n\nexport interface SuggestPromptResult {\n promptName: string;\n version: number;\n comparisonCount: number;\n}\n\nexport function buildSuggestPromptFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'suggest-prompt'),\n name: 'suggest-prompt',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n { universalIdentifier: SUGGEST_PROMPT_INPUT_AGENT_ID_UID, name: 'agentId', type: FieldType.TEXT, label: 'Agent id', isNullable: false },\n { universalIdentifier: SUGGEST_PROMPT_INPUT_MAX_COMPARISONS_UID, name: 'maxComparisons', type: FieldType.NUMBER, label: 'Max comparisons', isNullable: true },\n ],\n };\n}\n\nexport function createSuggestPromptHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => suggestPromptHandler(ctx as SupportKitHandlerContext, config, input as unknown as SuggestPromptInput);\n}\n\nfunction comparisonBlock(index: number, generatedText: string | null, sentText: string): string {\n const ai = generatedText?.trim() || '(aucune réponse générée)';\n return `### Exemple ${index + 1}\\nIA a généré :\\n${ai}\\n\\nAgent a réellement envoyé :\\n${sentText.trim()}`;\n}\n\nexport async function suggestPromptHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: SuggestPromptInput,\n): Promise<SuggestPromptResult> {\n const agentId = input?.agentId?.trim();\n if (!agentId) throw new ctx.NonRetriableError('agentId is required');\n\n const agent = toAgent(await ctx.api.get('agent', agentId));\n const promptName = agent.promptName;\n if (!promptName) throw new ctx.NonRetriableError(`Agent \"${agentId}\" has no promptName configured`);\n\n // Raw (unresolved) current content — the meta-prompt below must see any\n // `@@@langfusePrompt:...@@@` composition tag verbatim, so it rewrites the\n // template rather than an expansion of it (mirrors legacy's own\n // `getRaw` read, §3.7's \"aplatir\" concern).\n let currentContent: string;\n let promptVersion: number | null;\n try {\n const detail = await ctx.api.prompts.get(promptName, { label: 'production', resolve: false });\n currentContent = detail.content;\n promptVersion = detail.version;\n } catch (err) {\n // H4 (T25 review): a 403 means this agent's own promptName is outside\n // the app's role.prompts allowlist — a manifest/data misconfiguration,\n // not the legitimate \"no production version yet\" case the fallback to\n // systemPromptSnapshot exists for. Swallowing it here would rewrite a\n // STALE snapshot and hand the operator no error explaining why.\n if (err instanceof AppApiError && err.status === 403) {\n throw new ctx.NonRetriableError(\n `Agent \"${agentId}\"'s prompt \"${promptName}\" is outside this app's prompts allowlist (role.prompts) — suggest-prompt cannot read it. ${err.message}`,\n );\n }\n currentContent = agent.systemPromptSnapshot ?? '';\n promptVersion = agent.promptVersion;\n }\n\n // Scoped to the ACTIVE prompt version, not just the agent (legacy\n // behaviour, ported): a correction captured against v7 has nothing to say\n // about v8 — feeding it back in after the operator already accepted a\n // suggestion re-litigates a fix that was already made and drifts the\n // prompt further every round.\n const limit = Math.min(input?.maxComparisons ?? DEFAULT_MAX_COMPARISONS, DEFAULT_MAX_COMPARISONS);\n const page = await ctx.api.list('response-comparison', { filter: { agentId, promptName, promptVersion }, limit });\n const comparisons = page.items.map((r) => r.data as { generatedText: string | null; sentText: string });\n if (comparisons.length < MIN_COMPARISONS_REQUIRED) {\n throw new ctx.NonRetriableError(\n `Not enough comparison data (${comparisons.length} record(s), minimum ${MIN_COMPARISONS_REQUIRED} required)`,\n );\n }\n\n const metaPromptName = resolvePromptName('suggest', config);\n // §3.7 point 3 — the kit's own built-in text is the LAST resort;\n // `config.defaults.prompts.suggest` (T25) overrides it first.\n const configuredFallback = config.defaults?.prompts?.suggest ?? DEFAULT_SUGGEST_META_PROMPT;\n let metaPromptContent = configuredFallback;\n try {\n metaPromptContent = (await ctx.api.prompts.get(metaPromptName, { label: 'production' })).content || configuredFallback;\n } catch {\n // Level-3 fallback (§3.7) — the `suggest` slot has no `production`\n // version yet on this tenant.\n }\n\n const userMessage = [\n '--- PROMPT SYSTÈME ACTUEL ---',\n currentContent,\n '--- FIN DU PROMPT SYSTÈME ---',\n '',\n `Voici ${comparisons.length} exemples comparant ce que l'IA a généré avec ce que l'agent a réellement envoyé :`,\n '',\n comparisons.map((c, i) => comparisonBlock(i, c.generatedText, c.sentText)).join('\\n\\n---\\n\\n'),\n ].join('\\n');\n\n const result = await ctx.api.llm.complete({\n messages: [\n { role: 'system', content: metaPromptContent },\n { role: 'user', content: userMessage },\n ],\n options: { model: agent.modelId },\n promptRef: { name: metaPromptName, label: 'production', resolve: false },\n });\n\n const suggestedContent = result.text.trim();\n if (!suggestedContent) throw new ctx.NonRetriableError('The model returned an empty suggestion');\n\n const referenceErrors = await validateReferences(ctx.api, suggestedContent, promptName);\n if (referenceErrors.length > 0) {\n // The rejected content is included, not discarded (T23 post-review B4):\n // without it, an operator can neither see what the model produced nor\n // repair it by hand, and a retry re-spends the completion that already\n // paid for this exact (rejected) text.\n throw new ctx.NonRetriableError(\n [\n `Suggested content has invalid reference tags: ${referenceErrors.join(' ')}`,\n '--- REJECTED CONTENT ---',\n suggestedContent,\n ].join('\\n\\n'),\n );\n }\n\n let version: number;\n try {\n ({ version } = await ctx.api.prompts.createVersion(promptName, {\n content: suggestedContent,\n tags: ['ai_suggested'],\n }));\n } catch (err) {\n // H4 (T25 review): left unguarded, a 403 here (promptName outside\n // role.prompts) reached the caller as an opaque platform exception —\n // AFTER the llm.complete call above already paid for suggestedContent.\n // Same courtesy as the reference-validation rejection just above: name\n // the cause and include the content the operator already paid for,\n // rather than discarding it behind a generic failure.\n if (err instanceof AppApiError && err.status === 403) {\n throw new ctx.NonRetriableError(\n [\n `Cannot save this suggestion: prompt \"${promptName}\" is outside this app's prompts allowlist (role.prompts). ${err.message}`,\n '--- REJECTED CONTENT ---',\n suggestedContent,\n ].join('\\n\\n'),\n );\n }\n throw err;\n }\n\n return { promptName, version, comparisonCount: comparisons.length };\n}\n","/**\n * `run-diff-analysis` (§3.5) — `uiInvoke`, correction patterns → the\n * `diff-analysis` record (`records/diff-analysis.ts`), equivalent to legacy\n * `POST /response-comparisons/diff-analysis`.\n *\n * Simplification versus the legacy route (recorded here, not silently):\n * legacy computed a word-level diff (`serverWordDiff`) client-side and fed\n * the LLM the deleted/inserted word lists. The kit's `response-comparison`\n * record carries a `diff` field \"computed at write time\" by\n * `ext-response-comparison` (T24, `response-comparison-diff.ts`'s\n * `computeWordDiff` — `DiffToken[]`, `{op: 'equal'|'insert'|'delete',\n * text}`). Feeding the LLM the RAW `generatedText`/`sentText` pair for each\n * non-identical comparison is functionally equivalent for a\n * pattern-finding meta-prompt (arguably richer input than a pre-diffed\n * word list) and avoids this function depending on that intermediate shape\n * at all.\n *\n * `minRole: 'EDITOR'`: writes a `diff-analysis` row (an upsert, not a\n * prompt version) — still a write, not a read.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport { diffAnalysisUniqueKey } from '../records/diff-analysis';\nimport { resolvePromptName } from '../prompts/slots';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { RUN_DIFF_ANALYSIS_INPUT_AGENT_ID_UID, RUN_DIFF_ANALYSIS_INPUT_LIMIT_UID } from './ids';\nimport { toAgent } from './records';\n\nconst DEFAULT_LIMIT = 50;\nconst MAX_IMPROVEMENTS = 3;\n\nconst DEFAULT_DIFF_ANALYSIS_META_PROMPT = [\n \"Tu analyses des paires (réponse générée par l'IA, réponse réellement envoyée par un agent humain) pour un assistant de support client.\",\n 'Identifie au maximum 3 patterns récurrents de correction (ton, structure, longueur, formulations, niveau de détail).',\n 'Réponds uniquement avec un objet JSON {\"improvements\": string[]}, sans autre texte.',\n].join('\\n');\n\nconst RESPONSE_SCHEMA = {\n name: 'diff_analysis',\n schema: {\n type: 'object',\n properties: { improvements: { type: 'array', items: { type: 'string' } } },\n required: ['improvements'],\n additionalProperties: false,\n },\n};\n\nexport interface RunDiffAnalysisInput {\n agentId: string;\n limit?: number;\n}\n\nexport interface RunDiffAnalysisResult {\n agentId: string;\n promptName: string;\n promptVersion: number;\n points: string[];\n comparisonCount: number;\n}\n\nexport function buildRunDiffAnalysisFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'run-diff-analysis'),\n name: 'run-diff-analysis',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n { universalIdentifier: RUN_DIFF_ANALYSIS_INPUT_AGENT_ID_UID, name: 'agentId', type: FieldType.TEXT, label: 'Agent id', isNullable: false },\n { universalIdentifier: RUN_DIFF_ANALYSIS_INPUT_LIMIT_UID, name: 'limit', type: FieldType.NUMBER, label: 'Limit', isNullable: true },\n ],\n };\n}\n\nexport function createRunDiffAnalysisHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => runDiffAnalysisHandler(ctx as SupportKitHandlerContext, config, input as unknown as RunDiffAnalysisInput);\n}\n\nexport async function runDiffAnalysisHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: RunDiffAnalysisInput,\n): Promise<RunDiffAnalysisResult> {\n const agentId = input?.agentId?.trim();\n if (!agentId) throw new ctx.NonRetriableError('agentId is required');\n\n const agent = toAgent(await ctx.api.get('agent', agentId));\n const promptName = agent.promptName;\n if (!promptName) throw new ctx.NonRetriableError(`Agent \"${agentId}\" has no promptName configured`);\n\n let promptVersion = agent.promptVersion ?? 0;\n try {\n promptVersion = (await ctx.api.prompts.get(promptName, { label: 'production' })).version;\n } catch {\n // Prompt store unreachable/unconfigured — fall back to the agent's own last-known version.\n }\n\n // Scoped to the ACTIVE prompt version, not just the agent (legacy\n // behaviour, ported — see `suggest-prompt.ts`'s identical fix): a pattern\n // observed against a superseded version must not be stamped onto the\n // version that superseded it.\n const limit = Math.min(input?.limit ?? DEFAULT_LIMIT, DEFAULT_LIMIT);\n const page = await ctx.api.list('response-comparison', { filter: { agentId, promptName, promptVersion }, limit });\n const pairs = page.items\n .map((r) => r.data as { generatedText: string | null; sentText: string })\n .filter((c) => c.generatedText && c.generatedText.trim() !== c.sentText.trim());\n\n if (pairs.length === 0) {\n throw new ctx.NonRetriableError('No non-identical comparison found for this agent');\n }\n\n const metaPromptName = resolvePromptName('diff-analysis', config);\n // §3.7 point 3 — the kit's own built-in text is the LAST resort;\n // `config.defaults.prompts['diff-analysis']` (T25) overrides it first.\n const configuredFallback = config.defaults?.prompts?.['diff-analysis'] ?? DEFAULT_DIFF_ANALYSIS_META_PROMPT;\n let metaPromptContent = configuredFallback;\n try {\n metaPromptContent = (await ctx.api.prompts.get(metaPromptName, { label: 'production' })).content || configuredFallback;\n } catch {\n // Level-3 fallback (§3.7) — the `diff-analysis` slot has no `production` version yet.\n }\n\n const userMessage = pairs\n .map((c, i) => `### Exemple ${i + 1}\\nIA a généré :\\n${(c.generatedText ?? '').trim()}\\n\\nAgent a réellement envoyé :\\n${c.sentText.trim()}`)\n .join('\\n\\n---\\n\\n');\n\n const result = await ctx.api.llm.complete({\n messages: [\n { role: 'system', content: metaPromptContent },\n { role: 'user', content: userMessage },\n ],\n options: { model: agent.modelId, responseSchema: RESPONSE_SCHEMA },\n promptRef: { name: metaPromptName, label: 'production', resolve: false },\n });\n\n let points: string[];\n try {\n const parsed = JSON.parse(result.text) as { improvements?: unknown };\n points = Array.isArray(parsed.improvements) ? parsed.improvements.filter((p): p is string => typeof p === 'string').slice(0, MAX_IMPROVEMENTS) : [];\n } catch {\n throw new ctx.NonRetriableError('The model returned an invalid JSON response');\n }\n\n await ctx.api.upsert(\n 'diff-analysis',\n [\n {\n data: {\n agentId,\n promptName,\n promptVersion,\n points,\n uniqueKey: diffAnalysisUniqueKey(agentId, promptName, promptVersion),\n },\n },\n ],\n { uniqueBy: ['uniqueKey'] },\n );\n\n return { agentId, promptName, promptVersion, points, comparisonCount: pairs.length };\n}\n","/**\n * `list-gorgias-views` (§3.5) — `uiInvoke`, view autocomplete (S1\n * `listViews`) for the Settings page's `sourceViewId` field, plus §4's\n * cross-app view-claim warning: \"avertit si la vue configurée est déjà\n * revendiquée par une autre app support (lecture croisée du record\n * `pipeline-state` exposé `exposedToApps:['*']`, en lecture seule — seul\n * point de contact inter-apps, purement informatif)\".\n *\n * DELIBERATE EXCEPTION to \"every handler reads settings through\n * `validateSettings` before use\": this function is the checklist's OWN\n * step 2 tool for CHOOSING `sourceViewId` in the first place (§4's \"créer\n * une nouvelle audience\" checklist) — gating it on `validateSettings`,\n * which itself requires `sourceViewId` to be non-empty, would make the\n * autocomplete unusable on the exact first-run screen it exists for. Every\n * OTHER field `validateSettings` checks (`nodes.triage`, `senderEmail`) is\n * equally irrelevant to listing Gorgias views.\n *\n * ASSUMPTION (stated, not decided silently): the kit has no platform\n * capability to enumerate OTHER installed apps — `SupportKitApi` is scoped\n * to this app's own token, and nothing in §2's S1-S6 socle exposes an \"apps\n * of this kind\" listing. `input.checkAppSlugs` is therefore CALLER-SUPPLIED:\n * the Settings page (out of this task's scope) already has its own,\n * unrelated way to see the instance's installed apps (an admin-facing\n * listing this app's own token cannot and should not reach) and passes the\n * OTHER support-kit apps' slugs in. A slug that turns out not to expose\n * `pipeline-state` to this app (not installed, not a support-kit app, or a\n * true `403`) is reported in `uncheckedAppSlugs` rather than failing the\n * whole call — the warning is \"purement informatif\" (§4), never a gate.\n *\n * P1 (« Connexion Gorgias »): this function ALSO reports the instance's\n * Gorgias connections. The Settings page used to expose a free-text\n * `gorgiasConnectionId` that nothing read — every call in the kit goes\n * through `ctx.api.integrations.run('gorgias', …)` WITHOUT a\n * `connectionId`, so the platform resolves the default connection and the\n * field was decorative. The kit now states which connection answers instead\n * of pretending to choose it, and warns on the one configuration that\n * actually breaks: several connections with no default, which the platform\n * rejects with `409 AMBIGUOUS_CONNECTION`\n * (`app-integrations.controller.ts`). It lives here rather than in a new\n * `uiInvoke` function because the Settings page already calls this one for\n * the very same section, and a new function would cost the consuming app a\n * new `universalIdentifier` (`identifierFor` throws on a missing one) for\n * no added capability.\n *\n * `minRole: 'VIEWER'`: a pure read, informational only.\n *\n * T25 DECISION (spec §3.2, \"T25 or the Settings page must supply\n * `checkAppSlugs`\"): `SupportPipelineConfig` deliberately does NOT grow a\n * field for this. A config field would be a STATIC list, fixed at manifest\n * build/publish time — exactly wrong for \"which other support-kit apps\n * exist\", a fact that changes every time an audience is added or removed\n * without republishing this one. The Settings page (T26) is the only\n * correct owner: it already needs an admin-facing \"installed apps\" listing\n * this function's own scoped token cannot and should not reach (see the\n * ASSUMPTION above), and it is the one place that can pass a FRESH\n * `checkAppSlugs` on every invocation. Nothing changes here.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { LIST_GORGIAS_VIEWS_INPUT_CHECK_APP_SLUGS_UID } from './ids';\n\nexport interface ListGorgiasViewsInput {\n /** Other installed support-kit apps' slugs to check `sourceViewId` overlap against (§4) — see this module's own doc for why this is caller-supplied. */\n checkAppSlugs?: string[];\n}\n\nexport interface GorgiasViewOption {\n id: string;\n name: string;\n /** Other apps whose `pipeline-state.sourceViewId` already names this view. Empty when clear (or unverifiable). */\n claimedByAppSlugs: string[];\n}\n\nexport interface GorgiasConnection {\n id: string;\n label: string;\n isDefault: boolean;\n}\n\nexport interface ListGorgiasViewsResult {\n views: GorgiasViewOption[];\n /** `checkAppSlugs` entries that could not be read (not installed, not exposing `pipeline-state` to this app, or unreachable) — informational, never a failure. */\n uncheckedAppSlugs: string[];\n /**\n * The instance's Gorgias connections, credentials stripped by the platform\n * (`GET /data/integrations/gorgias/connections`). `null` means the listing\n * itself FAILED — distinct from `[]`, which means the instance genuinely\n * has no Gorgias connection and the pipeline cannot run at all. The\n * Settings page renders the two differently, so collapsing them would turn\n * a real misconfiguration into an unexplained blank.\n */\n connections: GorgiasConnection[] | null;\n}\n\nexport function buildListGorgiasViewsFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'list-gorgias-views'),\n name: 'list-gorgias-views',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: LIST_GORGIAS_VIEWS_INPUT_CHECK_APP_SLUGS_UID,\n name: 'checkAppSlugs',\n type: FieldType.JSON,\n label: 'Check app slugs',\n description: 'string[] — other support-kit app slugs to check for a sourceViewId overlap.',\n isNullable: true,\n },\n ],\n };\n}\n\nexport function createListGorgiasViewsHandler(config: SupportKitFunctionConfig): AppHandler {\n return (ctx, input) => listGorgiasViewsHandler(ctx as SupportKitHandlerContext, config, (input as ListGorgiasViewsInput) ?? {});\n}\n\nconst PIPELINE_STATE_SINGLETON_KEY = 'default';\n\ntype ClaimedViewRead = { ok: true; claimedViewId: string | null } | { ok: false };\n\n/**\n * The view `appSlug` currently claims, or `null` when it claims none (a\n * SUCCESSFUL read of an empty/unset singleton — a fresh app that has never\n * triaged is \"checked, not claiming anything\", not \"unverifiable\"). `ok:\n * false` is reserved for an actual read FAILURE (not installed, not\n * exposing `pipeline-state` to this app, or unreachable) — the two must\n * stay distinct, or a legitimately-clear app would be reported as\n * unverifiable instead of clear.\n */\nasync function readClaimedView(ctx: SupportKitHandlerContext, appSlug: string): Promise<ClaimedViewRead> {\n try {\n const page = await ctx.api.crossApp.list(appSlug, 'pipeline-state', { filter: { singletonKey: PIPELINE_STATE_SINGLETON_KEY }, limit: 1 });\n const sourceViewId = page.items[0]?.data.sourceViewId;\n return { ok: true, claimedViewId: typeof sourceViewId === 'string' && sourceViewId.length > 0 ? sourceViewId : null };\n } catch {\n return { ok: false };\n }\n}\n\nexport async function listGorgiasViewsHandler(\n ctx: SupportKitHandlerContext,\n config: SupportKitFunctionConfig,\n input: ListGorgiasViewsInput,\n): Promise<ListGorgiasViewsResult> {\n const rawViews = (await ctx.api.integrations.run('gorgias', 'listViews', {})) as { views: Array<{ id: string | number; name: string }> };\n const views = rawViews.views.map((v) => ({ id: String(v.id), name: v.name }));\n\n // Reported, never thrown: which connection answers is a property of the\n // instance the operator cannot set from here (P1), so a failure to read it\n // must not take the view autocomplete — this function's actual job — down\n // with it.\n let connections: GorgiasConnection[] | null;\n try {\n connections = await ctx.api.integrations.list('gorgias');\n } catch {\n connections = null;\n }\n\n const candidateSlugs = (input.checkAppSlugs ?? []).filter((slug) => slug && slug !== config.slug);\n\n const claimedByViewId = new Map<string, string[]>();\n const uncheckedAppSlugs: string[] = [];\n for (const slug of candidateSlugs) {\n const read = await readClaimedView(ctx, slug);\n if (!read.ok) {\n uncheckedAppSlugs.push(slug);\n continue;\n }\n if (read.claimedViewId === null) continue; // checked, and it claims nothing\n const claimants = claimedByViewId.get(read.claimedViewId) ?? [];\n claimants.push(slug);\n claimedByViewId.set(read.claimedViewId, claimants);\n }\n\n return {\n views: views.map((v) => ({ id: v.id, name: v.name, claimedByAppSlugs: claimedByViewId.get(v.id) ?? [] })),\n uncheckedAppSlugs,\n connections,\n };\n}\n","/**\n * `create-agent` (§3.4) — `uiInvoke`, creates a new drafting agent with a\n * server-assigned `promptName` of `agent/<recordId>`, unless the caller\n * names an existing Langfuse prompt (`input.promptName`, written verbatim).\n *\n * `agent.promptName` is `isNullable: false` with no default\n * (`records/agent.ts`) — the record's own id does not exist until AFTER the\n * create, so a plain `POST records/agent` from the browser has no legal\n * value to send for it. Before this function existed, AgentsPage's \"Nouvel\n * agent\" form posted with no `promptName` field at all, the write was\n * rejected, `save()` had no `.catch`, and the modal just sat there with no\n * feedback (T26 review, BLOCKER 3).\n *\n * The fix is the two-step create-then-patch the record id makes necessary,\n * done in ONE server-side round trip: the browser only ever sees the final,\n * fully-formed agent — never the placeholder `promptName` the first write is\n * forced to carry for the instant before the id is known.\n *\n * `minRole: 'EDITOR'`: creating an agent is an editing action, matching\n * every other agent-mutating control on AgentsPage.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport { DEFAULT_LLM_PROVIDER } from '../records/agent';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport {\n CREATE_AGENT_INPUT_MODEL_ID_UID,\n CREATE_AGENT_INPUT_NAME_UID,\n CREATE_AGENT_INPUT_PROMPT_LABEL_UID,\n CREATE_AGENT_INPUT_PROMPT_NAME_UID,\n CREATE_AGENT_INPUT_PROVIDER_UID,\n CREATE_AGENT_INPUT_SYSTEM_PROMPT_SNAPSHOT_UID,\n} from './ids';\nimport { toAgent, type AgentRecord } from './records';\n\n/**\n * Placeholder `promptName` for the single instant between the create and the\n * patch that overwrites it with `agent/<id>` — this handler is the only\n * thing that ever reads a record carrying it, so its exact spelling has no\n * external contract.\n */\nconst PENDING_PROMPT_NAME = 'agent/pending';\n\nexport interface CreateAgentInput {\n name: string;\n modelId: string;\n provider?: string;\n systemPromptSnapshot?: string;\n /**\n * Langfuse prompt this agent uses, written VERBATIM (trim only — no case,\n * accent or dash normalisation: `agent/Prompt 7 — Client Satisfait & Avis`\n * must land byte for byte). Absent or empty → the legacy server-derived\n * `agent/<recordId>`.\n */\n promptName?: string;\n /**\n * Langfuse label the agent follows. Absent or empty → stays null, the\n * convention `draftPromptRefFor` reads as \"follow `production`\" — never\n * frozen to the literal string at write time.\n */\n promptLabel?: string;\n}\n\nexport function buildCreateAgentFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'create-agent'),\n name: 'create-agent',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n { universalIdentifier: CREATE_AGENT_INPUT_NAME_UID, name: 'name', type: FieldType.TEXT, label: 'Name', isNullable: false },\n { universalIdentifier: CREATE_AGENT_INPUT_MODEL_ID_UID, name: 'modelId', type: FieldType.TEXT, label: 'Model id', isNullable: false },\n { universalIdentifier: CREATE_AGENT_INPUT_PROVIDER_UID, name: 'provider', type: FieldType.TEXT, label: 'Provider', isNullable: true },\n {\n universalIdentifier: CREATE_AGENT_INPUT_SYSTEM_PROMPT_SNAPSHOT_UID,\n name: 'systemPromptSnapshot',\n type: FieldType.TEXT,\n label: 'System prompt snapshot',\n isNullable: true,\n },\n {\n universalIdentifier: CREATE_AGENT_INPUT_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: true,\n },\n {\n universalIdentifier: CREATE_AGENT_INPUT_PROMPT_LABEL_UID,\n name: 'promptLabel',\n type: FieldType.TEXT,\n label: 'Prompt label',\n isNullable: true,\n },\n ],\n };\n}\n\nexport function createCreateAgentHandler(): AppHandler {\n return (ctx, input) =>\n createAgentHandler(ctx as SupportKitHandlerContext, (input as unknown as CreateAgentInput) ?? {});\n}\n\nexport async function createAgentHandler(\n ctx: SupportKitHandlerContext,\n input: CreateAgentInput,\n): Promise<AgentRecord> {\n const name = input?.name?.trim();\n if (!name) throw new ctx.NonRetriableError('name is required');\n const modelId = input?.modelId?.trim();\n if (!modelId) throw new ctx.NonRetriableError('modelId is required');\n\n const base = {\n name,\n modelId,\n provider: input.provider?.trim() || DEFAULT_LLM_PROVIDER,\n status: 'available',\n ...(input.systemPromptSnapshot?.trim() ? { systemPromptSnapshot: input.systemPromptSnapshot.trim() } : {}),\n ...(input.promptLabel?.trim() ? { promptLabel: input.promptLabel.trim() } : {}),\n };\n\n // An explicit promptName is written verbatim in ONE create: no placeholder,\n // and no id-derived overwrite — deriving would silently detach the agent\n // from the pre-existing Langfuse prompt the caller just named.\n const promptName = input.promptName?.trim();\n if (promptName) {\n return toAgent(await ctx.api.create('agent', { ...base, promptName }));\n }\n\n const created = await ctx.api.create('agent', { ...base, promptName: PENDING_PROMPT_NAME });\n const withPromptName = await ctx.api.update('agent', created.id, { promptName: `agent/${created.id}` });\n return toAgent(withPromptName);\n}\n","/**\n * `set-default-agent` (§3.4) — `uiInvoke`, promotes one agent to\n * `status: 'default'` while demoting whatever agent currently holds it.\n *\n * `records/agent.ts` documents the invariant: \"at most one default agent\",\n * enforced by a unique index on `defaultKey`, which is set to `'default'`\n * exactly when `status === 'default'` and left absent otherwise (so Postgres\n * NULLs never collide) — and states that POPULATING `defaultKey` correctly\n * is \"a write-handler concern\", not the record definition's. Before this\n * function existed, nothing populated it at all: AgentsPage's \"Définir par\n * défaut\" button wrote `{status: 'default'}` alone, from the browser, as two\n * independent `PATCH` calls with no shared transaction — `defaultKey` never\n * moved, the unique index never fired, and clicking the button on a second\n * agent produced two rows with `status: 'default'` without demoting the\n * first. `resolveDraftAgent` (`functions/records.ts`) resolves the default\n * agent via `list('agent', {filter:{status:'default'}, limit:1})`, so which\n * of the two an uncategorised ticket drafts with became non-deterministic,\n * and `ext-models` would serve two \"default\" agents to the extension (T26\n * review, BLOCKER 4).\n *\n * This function does both writes from ONE server-side call, DEMOTING the\n * incumbent BEFORE promoting the target — not the other way round, and not\n * in parallel: `defaultKey` carries a unique index, so having the incumbent\n * and the target both hold `'default'` at once, even for one write, would\n * violate it. Demoting first means a failure between the two writes leaves\n * AT MOST ZERO default agents (a safe, if inconvenient, state an operator\n * can fix by retrying) rather than two — this kit has no cross-record\n * transaction to make the pair atomic, so \"the worst reachable state is\n * still a legal one\" is the best guarantee available without one.\n *\n * `minRole: 'EDITOR'`: matches AgentsPage's other agent-mutating controls.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { SET_DEFAULT_AGENT_INPUT_AGENT_ID_UID } from './ids';\nimport { toAgent, type AgentRecord } from './records';\n\nconst DEFAULT_KEY_VALUE = 'default';\n\nexport interface SetDefaultAgentInput {\n agentId: string;\n}\n\nexport function buildSetDefaultAgentFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'set-default-agent'),\n name: 'set-default-agent',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n {\n universalIdentifier: SET_DEFAULT_AGENT_INPUT_AGENT_ID_UID,\n name: 'agentId',\n type: FieldType.TEXT,\n label: 'Agent id',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createSetDefaultAgentHandler(): AppHandler {\n return (ctx, input) =>\n setDefaultAgentHandler(ctx as SupportKitHandlerContext, (input as unknown as SetDefaultAgentInput) ?? {});\n}\n\nexport async function setDefaultAgentHandler(\n ctx: SupportKitHandlerContext,\n input: SetDefaultAgentInput,\n): Promise<AgentRecord> {\n const agentId = input?.agentId?.trim();\n if (!agentId) throw new ctx.NonRetriableError('agentId is required');\n\n const target = toAgent(await ctx.api.get('agent', agentId));\n if (target.status === 'default') return target; // already the default — no-op, not an error.\n\n const incumbentPage = await ctx.api.list('agent', { filter: { status: 'default' }, limit: 1 });\n const incumbent = incumbentPage.items[0];\n if (incumbent && incumbent.id !== agentId) {\n await ctx.api.update('agent', incumbent.id, { status: 'available', defaultKey: null });\n }\n\n const promoted = await ctx.api.update('agent', agentId, {\n status: 'default',\n defaultKey: DEFAULT_KEY_VALUE,\n });\n return toAgent(promoted);\n}\n","/**\n * `create-shared-prompt-version` (§3.8 SharedPromptsPage, T27 part B) — the\n * ONE write path SharedPromptsPage uses to save a new `shared/*` prompt\n * version.\n *\n * Why this exists instead of the browser calling S3's own\n * `POST /data/apps/:appSlug/prompts/versions` directly (the way\n * `AgentsPage`'s `usePromptVersions.createVersion` already does for an\n * agent's prompt): that route writes whatever content it is given — it\n * does not run `validateReferences` (`./validate-references.ts`), and per\n * T19/T23's own review, nothing server-side does either. Since the kit\n * resolves `@@@langfusePrompt:…@@@` composition ITSELF (T19's\n * `prompts/resolver.ts`, reading with `resolve:false`), a malformed tag\n * saved through the raw REST route reaches every draft that composes\n * `shared/style-email`/`shared/style-whatsapp` verbatim, with nothing\n * server-side left to catch it — exactly the gap T23's review named for\n * `suggest-prompt`'s write path (§3.5). This is the same guard, for a\n * human operator's edit instead of an LLM suggestion.\n *\n * Scoped to `shared/` names only (refuses anything else): SharedPromptsPage\n * is a `shared/*` library editor, not a general prompt-writing surface.\n * `role.prompts`' `shared/*` glob (`pipeline.ts`'s `buildPromptsAllowlist`)\n * is the actual authorization boundary; this refusal is a narrower,\n * separate promise about what THIS function is for — `AgentsPage` keeps\n * writing an agent's own prompt through S3's raw route, unaffected.\n *\n * `minRole: 'EDITOR'`: a write, like every other prompt-mutating control\n * in the kit (`createVersion`/`promote`/`deleteVersion`, S3).\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID, CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID } from './ids';\nimport { validateReferences } from './validate-references';\n\nconst SHARED_PREFIX = 'shared/';\n\nexport interface CreateSharedPromptVersionInput {\n name: string;\n content: string;\n}\n\nexport interface CreateSharedPromptVersionResult {\n version: number;\n}\n\nexport function buildCreateSharedPromptVersionFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'create-shared-prompt-version'),\n name: 'create-shared-prompt-version',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n {\n universalIdentifier: CREATE_SHARED_PROMPT_VERSION_INPUT_NAME_UID,\n name: 'name',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: false,\n },\n {\n universalIdentifier: CREATE_SHARED_PROMPT_VERSION_INPUT_CONTENT_UID,\n name: 'content',\n type: FieldType.TEXT,\n label: 'Content',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createCreateSharedPromptVersionHandler(): AppHandler {\n return (ctx, input) =>\n createSharedPromptVersionHandler(\n ctx as SupportKitHandlerContext,\n (input as unknown as CreateSharedPromptVersionInput) ?? { name: '', content: '' },\n );\n}\n\nexport async function createSharedPromptVersionHandler(\n ctx: SupportKitHandlerContext,\n input: CreateSharedPromptVersionInput,\n): Promise<CreateSharedPromptVersionResult> {\n const name = input?.name?.trim();\n if (!name) throw new ctx.NonRetriableError('name is required');\n if (!name.startsWith(SHARED_PREFIX)) {\n throw new ctx.NonRetriableError(\n `\"${name}\" is not a shared/* prompt — create-shared-prompt-version only writes the shared/* library.`,\n );\n }\n const content = input?.content ?? '';\n if (!content.trim()) throw new ctx.NonRetriableError('content is required');\n\n const referenceErrors = await validateReferences(ctx.api, content, name);\n if (referenceErrors.length > 0) {\n throw new ctx.NonRetriableError(`Invalid reference tags: ${referenceErrors.join(' ')}`);\n }\n\n return ctx.api.prompts.createVersion(name, { content });\n}\n","/**\n * `sync-agent-prompt-snapshot` (§5.2) — `uiInvoke`, rewrites one agent's\n * `systemPromptSnapshot` with the prompt content that agent NOW serves.\n *\n * Why the snapshot needs a writer at all: `GET /models` serves\n * `system_prompt` from `agent.systemPromptSnapshot` ONLY (`ext-models.ts`)\n * — §5.2 forbids a synchronous Langfuse read there, because the extension\n * calls that route on every ticket change for every support agent. The spec\n * pays for that with one sentence: the snapshot is \"rafraîchi en tâche de\n * fond à chaque `createVersion`/`promote`\". Nothing did that. The only\n * writers were `create-agent` (from its input, once) and a hand edit in\n * AgentsPage, so promoting a new version moved what the PIPELINE drafts\n * with while the extension kept serving the text of whatever version was\n * current the day the agent was created — and `draftPromptRefFor`'s\n * level-3 fallback (`records.ts`) stayed pinned to that same stale text.\n *\n * Keyed by `promptName`, not by agent id, because the caller\n * (`ui/agents/use-prompt-versions.ts`) is a prompt-versions hook: it knows\n * the prompt it just wrote, never which record owns it. That also gives\n * the `shared/*` case its answer for free — a company-wide prompt belongs\n * to no agent, the lookup finds nothing, and the function is a no-op\n * rather than needing a namespace test of its own.\n *\n * WHAT IS SERVED, not what is newest: an agent pinned via\n * `agent.promptVersion` keeps drafting with that exact version, so its\n * snapshot must be that version's content — refreshing it to the newest\n * one would make `GET /models` advertise a prompt the pipeline does not\n * use. The ref built here is the same one `draftPromptRefFor` resolves.\n *\n * Read with `resolve: false`, like `createPlatformPromptReader`\n * (`adapters/ctx-ports.ts`): the kit flattens `@@@langfusePrompt:…@@@`\n * composition itself, so the snapshot must hold the RAW stored template —\n * the same text the resolver would have cached — not a pre-flattened\n * variant the fallback path would never produce.\n *\n * Never rejects on a resolution failure: by the time this runs, the\n * `createVersion`/`promote` it follows has already committed. Turning a\n * Langfuse outage into a failed promote would report a write that DID\n * happen as a write that did not; a stale snapshot is the lesser, and\n * self-correcting, harm (the next version write retries it).\n *\n * `minRole: 'EDITOR'`: it follows a prompt write, which is already\n * EDITOR-only (S3's own `createVersion`/`promote`).\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID } from './ids';\nimport { toAgent } from './records';\n\nexport interface SyncAgentPromptSnapshotInput {\n promptName: string;\n}\n\nexport interface SyncAgentPromptSnapshotResult {\n /** `false` also covers \"nothing to do\": no agent owns the prompt, the snapshot already matched, or the read failed. */\n updated: boolean;\n}\n\nexport function buildSyncAgentPromptSnapshotFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'sync-agent-prompt-snapshot'),\n name: 'sync-agent-prompt-snapshot',\n trigger: { type: 'uiInvoke', minRole: 'EDITOR' },\n input: [\n {\n universalIdentifier: SYNC_AGENT_PROMPT_SNAPSHOT_INPUT_PROMPT_NAME_UID,\n name: 'promptName',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createSyncAgentPromptSnapshotHandler(): AppHandler {\n return (ctx, input) =>\n syncAgentPromptSnapshotHandler(\n ctx as SupportKitHandlerContext,\n (input as unknown as SyncAgentPromptSnapshotInput) ?? { promptName: '' },\n );\n}\n\nexport async function syncAgentPromptSnapshotHandler(\n ctx: SupportKitHandlerContext,\n input: SyncAgentPromptSnapshotInput,\n): Promise<SyncAgentPromptSnapshotResult> {\n const promptName = input?.promptName?.trim();\n if (!promptName) throw new ctx.NonRetriableError('promptName is required');\n\n // EVERY agent carrying the name, not `limit: 1`: two agents may point at\n // the same Langfuse prompt (pin vs follow), and refreshing only whichever\n // one the list returned first left the other serving a stale snapshot in\n // silence.\n const page = await ctx.api.list('agent', { filter: { promptName } });\n let updated = false;\n\n for (const record of page.items) {\n const agent = toAgent(record);\n try {\n const ref =\n agent.promptVersion !== null ? { version: agent.promptVersion } : { label: agent.promptLabel ?? 'production' };\n const detail = await ctx.api.prompts.get(promptName, { ...ref, resolve: false });\n if (detail.content === agent.systemPromptSnapshot) continue;\n\n await ctx.api.update('agent', agent.id, { systemPromptSnapshot: detail.content });\n updated = true;\n } catch (error) {\n ctx.logger.warn(\n `sync-agent-prompt-snapshot: could not refresh \"${promptName}\" for agent ${agent.id} — GET /models keeps serving the previous snapshot (${String(error)})`,\n );\n }\n }\n\n return { updated };\n}\n","/**\n * `ext-models` (§5.2, §3.5 line 291) — `uiInvoke`, reserved. Ports legacy\n * `GET /api/models` (extension-overview backoffice/src/routes/api.ts:27).\n * Reached only through the platform-served extension gateway (S6), always\n * as `phase: 'execute'`, fanned out to every accessible app and unioned —\n * this function MUST return an array: a non-array result is logged and\n * silently dropped from the union by the gateway\n * (`SupportExtensionService.invokeAll`), never surfaced as an error.\n *\n * `system_prompt` is served from `agent.systemPromptSnapshot` ONLY — never\n * a synchronous Langfuse resolution. §5.2 is explicit about why: this\n * endpoint is hit on every ticket change, by every agent, so a per-request\n * Langfuse round trip at that frequency is the exact cost the snapshot\n * exists to avoid. The snapshot itself is kept fresh out-of-band, by\n * whichever write path refreshes it on `createVersion`/`promote` — not this\n * function's job.\n *\n * `system_prompt_token_count` is kept (frozen data model, §5.2 — \"conservé\n * bien qu'ignoré par l'extension\") but is an APPROXIMATION, not tiktoken's\n * real count: the kit cannot depend on `tiktoken`\n * (`dependency-allowlist.ts`, spec §3.1 — it is a native/WASM dependency,\n * unsafe across an arbitrary app's ESM bundler). This ports the legacy\n * tokenizer's OWN documented fallback path verbatim\n * (`utils/tokenizer.ts`'s `catch` branch, `Math.ceil(text.length / 4)`) —\n * here it is the only implementation, not a fallback from a real\n * tokenizer. It is a rough estimate (English text averages roughly 4\n * characters per token; French/accented text and code both deviate\n * further from that ratio) and MUST NOT be treated as exact by any future\n * consumer — today's one consumer (the extension) explicitly ignores it.\n *\n * `archived` agents are excluded — legacy's `status: {$in: ['default',\n * 'available']}` filter. Legacy sorts `{status: 1, name: 1}`; ported here\n * for this function's OWN array. The GATEWAY re-sorts the union by\n * `(order, name)` (§S6, D3) and a model carries no `order` field, so the\n * final wire order across multiple support apps ends up name-alphabetical\n * rather than `(status, name)` — a documented S6/T8 divergence from the\n * legacy, not this function's to fix (see the migration progress journal's\n * T24 entry).\n *\n * SETTINGS VALIDATION: deliberately NOT called here, same reasoning as\n * `list-gorgias-views`'s own documented exception. This function reads no\n * field `validateSettings` checks (`sourceViewId`, `nodes.triage`,\n * `senderEmail`) — it is a pure read of `agent` records serving a human\n * agent's Gorgias sidebar model picker. Gating it on settings validity\n * would break that picker for a tenant mid-setup, for no correctness\n * reason: nothing here depends on the triage pipeline being configured.\n *\n * `minRole: 'VIEWER'` is load-bearing: `SupportExtensionService\n * .hasAllReservedFunctions` refuses to treat an app as a support app\n * unless all six reserved functions declare exactly `VIEWER`.\n */\nimport type { AppHandler, FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { toAgent } from './records';\n\nconst TOKEN_APPROXIMATION_CHARS_PER_TOKEN = 4;\nconst AGENT_PAGE_SIZE = 500;\n\nexport interface ExtModel {\n _id: string;\n name: string;\n provider: string;\n model_id: string;\n system_prompt: string;\n system_prompt_token_count: number;\n status: 'default' | 'available';\n}\n\nexport function buildExtModelsFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-models'),\n name: 'ext-models',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n };\n}\n\nexport function createExtModelsHandler(): AppHandler {\n return (ctx) => extModelsHandler(ctx as SupportKitHandlerContext);\n}\n\nexport async function extModelsHandler(ctx: SupportKitHandlerContext): Promise<ExtModel[]> {\n const page = await ctx.api.list('agent', { limit: AGENT_PAGE_SIZE });\n // L15: the migration's standing rule is \"no silent caps\" — past 500\n // agents the union would silently lose entries with no cursor and no\n // warning.\n if (page.items.length >= AGENT_PAGE_SIZE) {\n ctx.logger.warn(`ext-models: \"agent\" page came back full at ${page.items.length} rows — some may be silently missing from the response.`);\n }\n\n return page.items\n .map(toAgent)\n .filter((agent): agent is typeof agent & { status: 'default' | 'available' } => agent.status !== 'archived')\n .sort((a, b) => (a.status === b.status ? a.name.localeCompare(b.name) : a.status.localeCompare(b.status)))\n .map((agent) => {\n const systemPrompt = agent.systemPromptSnapshot ?? '';\n return {\n _id: agent.id,\n name: agent.name,\n provider: agent.provider,\n model_id: agent.modelId,\n system_prompt: systemPrompt,\n system_prompt_token_count: approximateTokenCount(systemPrompt),\n status: agent.status,\n };\n });\n}\n\nfunction approximateTokenCount(text: string): number {\n return Math.ceil(text.length / TOKEN_APPROXIMATION_CHARS_PER_TOKEN);\n}\n","/**\n * `ext-categories` (§5.2, §3.5 line 291) — `uiInvoke`, reserved. Ports\n * legacy `GET /api/categories` (extension-overview backoffice/src/routes\n * /api.ts:50). Reached only through the S6 gateway, always `phase:\n * 'execute'`, fanned out to every accessible app and unioned — MUST return\n * an array (a non-array is dropped by the gateway, same rule as\n * `ext-models`).\n *\n * Filter (legacy `Category.find({agent: {$ne: null}}).populate({path:\n * 'agent', match: {status: {$ne: 'archived'}}})` then `.filter(c => c.agent\n * !== null)`): a category counts only when it HAS an `agentId` AND that\n * agent resolves AND is not archived. §5.2's own response shape freezes\n * `agent: {...} | null`, but this filter means the `| null` branch is\n * UNREACHABLE through this handler today — kept in the type for wire\n * fidelity with the frozen contract, never actually emitted.\n *\n * Sort (composite, §5.2's own doc on this route): `group.order` ASC, with\n * ungrouped categories FIRST (`null` sorts as `-Infinity`) → `category\n * .order` ASC → `category.name` `localeCompare`. The category-group record\n * already exists (`records/category-group.ts`); this function is its\n * first reader.\n *\n * WIRE `order` IS NOT `category.order` (M4 hardening): the S6 gateway\n * unions every accessible app's categories and re-sorts by `(order, name)`\n * ONLY — it has no visibility into the group concept at all\n * (`support-extension.service.ts`'s own doc on `sortedUnion`). `order` is\n * per-GROUP, not global, so emitting the raw field would let the gateway's\n * blind re-sort silently destroy the group ordering this function just\n * computed (a single installed app is enough to observe it — no multi-app\n * edge case required). What is emitted instead is this category's own\n * POSITION in the fully sorted sequence above (0, 1, 2, …) — a composite\n * rank that already encodes group→order→name as one monotonic number, so\n * the gateway's re-sort is a genuine no-op on this app's contiguous slice,\n * not just a documented aspiration.\n *\n * SETTINGS VALIDATION: deliberately NOT called, same reasoning as\n * `ext-models` — a pure read of `category`/`agent` records serving a human\n * agent's Gorgias sidebar, gated on none of `validateSettings`'s fields.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n */\nimport type { AppHandler, FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport { toAgent, toCategory, toCategoryGroup, type AgentRecord, type CategoryRecord } from './records';\n\nconst CATEGORY_PAGE_SIZE = 500;\nconst AGENT_PAGE_SIZE = 500;\n\nexport interface ExtCategoryAgent {\n _id: string;\n name: string;\n model_id: string;\n provider: string;\n}\n\nexport interface ExtCategory {\n _id: string;\n name: string;\n tag_name: string;\n order: number;\n agent: ExtCategoryAgent | null;\n}\n\nexport function buildExtCategoriesFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-categories'),\n name: 'ext-categories',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n };\n}\n\nexport function createExtCategoriesHandler(): AppHandler {\n return (ctx) => extCategoriesHandler(ctx as SupportKitHandlerContext);\n}\n\ninterface SortableEntry {\n category: CategoryRecord;\n agent: AgentRecord;\n groupOrder: number;\n}\n\nexport async function extCategoriesHandler(ctx: SupportKitHandlerContext): Promise<ExtCategory[]> {\n const [categoriesPage, groupsPage, agentsPage] = await Promise.all([\n ctx.api.list('category', { limit: CATEGORY_PAGE_SIZE }),\n ctx.api.list('category-group', { limit: CATEGORY_PAGE_SIZE }),\n // M7: ONE bulk read, not one `ctx.api.get` per category — this endpoint\n // runs on the same \"every ticket change, every agent\" cadence §5.2\n // documents for `/models` (which already does this), inside the\n // gateway's shared `FAN_OUT_BUDGET_MS`, so N+1 sequential round trips\n // risk a slow tenant's whole categories response silently dropping out\n // of the union on budget exhaustion.\n ctx.api.list('agent', { limit: AGENT_PAGE_SIZE }),\n ]);\n warnIfTruncated(ctx, 'category', categoriesPage.items.length, CATEGORY_PAGE_SIZE);\n warnIfTruncated(ctx, 'agent', agentsPage.items.length, AGENT_PAGE_SIZE);\n\n const groupOrderById = new Map(groupsPage.items.map(toCategoryGroup).map((g) => [g.id, g.order]));\n const agentById = new Map(agentsPage.items.map((record) => [record.id, toAgent(record)]));\n\n const entries: SortableEntry[] = [];\n for (const category of categoriesPage.items.map(toCategory)) {\n if (!category.agentId) continue;\n const agent = agentById.get(category.agentId);\n if (!agent) continue;\n if (agent.status === 'archived') continue;\n\n const groupOrder = category.groupId ? (groupOrderById.get(category.groupId) ?? -Infinity) : -Infinity;\n entries.push({ category, agent, groupOrder });\n }\n\n entries.sort((a, b) => {\n if (a.groupOrder !== b.groupOrder) return a.groupOrder - b.groupOrder;\n if (a.category.order !== b.category.order) return a.category.order - b.category.order;\n return a.category.name.localeCompare(b.category.name);\n });\n\n return entries.map(({ category, agent }, index) => ({\n _id: category.id,\n name: category.name,\n tag_name: category.tagName,\n // M4: this category's own POSITION in the fully sorted sequence, not\n // `category.order` verbatim — see this module's own doc.\n order: index,\n agent: { _id: agent.id, name: agent.name, model_id: agent.modelId, provider: agent.provider },\n }));\n}\n\n/** L15: the migration's standing rule is \"no silent caps\" — a page that comes back exactly full warrants a log, not a quiet truncation. */\nfunction warnIfTruncated(ctx: SupportKitHandlerContext, objectKey: string, itemCount: number, pageSize: number): void {\n if (itemCount >= pageSize) {\n ctx.logger.warn(`ext-categories: \"${objectKey}\" page came back full at ${itemCount} rows — some may be silently missing from the response.`);\n }\n}\n","/**\n * `ownsAgent` (L6) — the ONE `agent`-ownership probe check shared by\n * `ext-chat`, `ext-evaluation` and `ext-response-comparison`'s `phase:\n * 'probe'` branches (§S6 B1/B2): each restated the same `{claimed: true}`\n * sentinel, the same \"non-null claims / null disclaims / a genuine read\n * failure is never a disclaimer, it propagates as a real error\" contract,\n * and the same union return type. Three uses, so the no-premature-\n * abstraction rule does not shield the duplication.\n *\n * `id` absent/empty never claims — callers decide separately what to try\n * next on a `null` (`ext-chat` falls back to the default agent,\n * `ext-response-comparison` falls back to ticket ownership); this helper\n * only ever answers \"does this app own this one id\".\n */\nimport { getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\n\nexport interface ProbeClaim {\n claimed: true;\n}\n\nexport async function ownsAgent(ctx: SupportKitHandlerContext, id: string | null | undefined): Promise<ProbeClaim | null> {\n if (!id) return null;\n const record = await getOptional(ctx, 'agent', id);\n return record ? { claimed: true } : null;\n}\n","/**\n * `readSupportExtensionEnvelope` — the identity/phase the S6 gateway passes\n * on every reserved `ext-*` invocation\n * (`SupportExtensionService.invoke`'s `event: {supportExtension: {userId,\n * phase}}`, apps/api/src/platform-data/support-extension.service.ts).\n * Shared by every function that needs either half: `ext-chat`/\n * `ext-evaluation`/`ext-response-comparison` for the probe/execute split\n * (§5.1/§S6), `ext-evaluation` (`supportUserKeyId`) and\n * `ext-fast-response-check` (`servedTo`) for the platform user id itself.\n *\n * Defensive default, not a thrown error: an envelope that is missing or\n * malformed — which never happens through the real gateway, nothing else\n * invokes these reserved functions (§3.5 line 291) — resolves to `phase:\n * 'execute'` and `userId: ''` rather than crashing the whole handler on a\n * read. `'execute'` is the safe default direction for the phase: treating\n * an ambiguous call as `'probe'` would silently skip whatever real work the\n * caller actually wanted, while treating it as `'execute'` on a call that\n * WAS meant to be a cheap ownership probe only risks doing that same real\n * work anyway — never doing LESS than asked.\n *\n * `userId: ''` IS a safe default here — this is a pure READ with no side\n * effect. It is NOT safe symmetric treatment for the two call sites that\n * write it into an identity-bearing record (`ext-fast-response-check.ts`'s\n * `servedTo` push, `ext-evaluation.ts`'s `supportUserKeyId`) — §5.1\n * requires those records to carry the platform user id, so both callers\n * guard `!envelope.userId` themselves and fail the WRITE rather than\n * silently producing an anonymous-looking or null-identity row (L11\n * hardening). This function stays a defensive default, not a thrown error,\n * exactly as designed above; the burden of turning \"no identity\" into a\n * hard failure is on the two write sites that actually need one.\n */\nimport type { SupportKitHandlerContext } from './context';\n\nexport interface SupportExtensionEnvelope {\n userId: string;\n phase: 'probe' | 'execute';\n}\n\nexport function readSupportExtensionEnvelope(ctx: SupportKitHandlerContext): SupportExtensionEnvelope {\n const raw = (ctx.event as { supportExtension?: { userId?: unknown; phase?: unknown } } | undefined)?.supportExtension;\n return {\n userId: typeof raw?.userId === 'string' ? raw.userId : '',\n phase: raw?.phase === 'probe' ? 'probe' : 'execute',\n };\n}\n","/**\n * `ext-chat` (§5.2, §3.5 line 291) — `uiInvoke`, reserved, ownership-routed\n * (§S6). Ports legacy `POST /api/chat` (extension-overview backoffice/src\n * /routes/api.ts:147).\n *\n * OWNERSHIP PROBE (§S6 B1/B2): the gateway first calls this function with\n * `phase: 'probe'` and an id-only payload `{modelId}` — `modelId` may be\n * `undefined` (the legacy falls back to the single `status: 'default'`\n * model when it is absent). A probe MUST be cheap, local and side-effect-\n * free: no writes, no LLM call, no Gorgias fetch (`readSupportExtension\n * Envelope` picks the phase; the probe branch below only ever reads the\n * `agent` object). Claim rule, decided explicitly:\n * - `modelId` given → claim iff this app owns an `agent` record with\n * that id (any status — the legacy `ModelConfig.findById` applies no\n * status filter for chat, unlike `ext-models`).\n * - `modelId` absent → claim iff this app has a `status: 'default'`\n * agent.\n * AMBIGUITY, stated not hidden: with several installed support apps and no\n * `modelId`, more than one app can legitimately have its own default\n * agent, so more than one can claim the SAME probe. The gateway logs a\n * warning and routes to the first claimant (`SupportExtensionService\n * .invokeOwner`) — this function has no way to break that tie itself, and\n * does not try to. Returning any non-null value claims ownership; `null`\n * disclaims it. THROWING is never a way to say \"not mine\" (a genuine read\n * failure here propagates as a real error, exactly like every other\n * function — the gateway treats a probe throw as a fan-out failure, never\n * a disclaimer).\n *\n * EXECUTE: once ownership resolves, the gateway sends ONE `phase:\n * 'execute'` call with the full body — `{messages, modelId, agentName}` OR\n * `{gorgiasTicketId, modelId, agentName}`. When `gorgiasTicketId` is given\n * the conversation is rebuilt server-side via S1's `buildTicketContext`\n * action (NOT `getTicketWithContext` — only the extracted messages are\n * needed here, not the raw ticket payload `getTicketWithContext` also\n * fetches for the guardrail detectors elsewhere in the kit).\n *\n * PROMPT RESOLUTION reuses the kit's own §3.7 ladder\n * (`createPlatformPromptPort`) and `functions/records.ts`'s\n * `draftPromptRefFor` — the SAME binding `process-response` resolves the\n * `draft` node's prompt from (agent.promptName/promptLabel/\n * systemPromptSnapshot) — rather than writing a second resolver.\n *\n * `{{agent_name}}` SIGNATURE: §3.7 states the substitution is \"injectée\n * par `ext-chat`\" — this function calls the exact ported\n * `applySignature` (`graph/nodes/shared.ts`, exported for this reuse) on\n * the RESOLVED prompt text with the extension's own `agentName`, not the\n * generic `{{var}}` substitution `PromptPort.resolve`'s `vars` parameter\n * offers (which is a plain string replace, not `applySignature`'s full\n * rule set — appending a French signing instruction when there is no\n * placeholder at all). Reusing the ported function here — instead of a\n * second, subtly different implementation — was an explicit instruction in\n * this migration.\n *\n * SETTINGS VALIDATION: deliberately NOT called. Chat resolves its prompt\n * from the `agent` record's own binding, never from `validateSettings`'s\n * three checked fields (`sourceViewId`, `nodes.triage`, `senderEmail`) — a\n * misconfigured triage pipeline must not block an agent from testing a\n * model in the sidebar.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n *\n * POST-T24 REVIEW HARDENING:\n * - `options.model` now reads `resolvedPrompt.config?.model ?? agent\n * .modelId` (I16) — the resolved prompt's own model config wins, matching\n * every ported graph node; this was the one `PromptPort.resolve` consumer\n * that dropped it.\n * - `promptRef` IS forwarded to `ctx.api.llm.complete`, in LINK-ONLY mode\n * (`resolve: false`) — the D-LF follow-up task's resolution (option (b),\n * see the migration progress journal's T24 entry and its \"done\" correction):\n * the platform now decouples trace linkage from resolution, so a caller\n * that already resolved its own prompt (this function did, via\n * `PromptPort` two lines above) can link the completion to it in Langfuse\n * WITHOUT re-triggering the `manifest.prompts[]` declaration gate or the\n * system-message replacement (`app-integrations.controller.ts`'s\n * `llmComplete` JSDoc). This restores the same prompt-identity trace\n * linkage the platform's default mode gives every other caller, without\n * the 403/overwrite defect that forced the `trace.metadata` workaround\n * below during T24. The platform user id still travels on `trace.metadata`\n * (`ctx.api.llm.complete`'s `trace` has no dedicated `userId` field) — the\n * prompt identity no longer needs to, now that `promptRef` carries it. The\n * wire response is UNCHANGED — it still reports `prompt_name`/\n * `prompt_version` off `resolvedPrompt`.\n * The five graph nodes (`triage`/`escalate`/`draft`/`revise`/`evaluate`)\n * plus `suggest-prompt.ts`/`run-diff-analysis.ts` forward `promptRef` the\n * same link-only way now too — all seven sites adopted together.\n * - The gorgias-ticket branch now 400s on zero extracted messages, the same\n * guard the `input.messages` branch already had (M1) — an internal-notes-\n * only or automated-sender ticket must not pay for an LLM call with a\n * system message and no conversation.\n * - A Gorgias 404 (duck-typed off the caught error's `status`, since this\n * package has no dependency on `gorgias-client`'s `ProviderHttpError` to\n * `instanceof`-check) now throws `NonRetriableError` instead of a bare\n * rethrow (L1, PARTIAL). The legacy's other two mappings — \"not\n * configured\" → 503, else → 502 — are NOT reachable from here: every\n * `uiInvoke` throw funnels through `AppSyncInvocationService.toHttpError`\n * (`apps/api/src/platform-data/app-sync-invocation.service.ts`), which\n * recognises exactly two outcomes for an app-thrown error —\n * `AppNonRetriableError` → 422, anything else → 500 — regardless of what\n * `invokeOwner` does or doesn't wrap. 503/502 are outside this function's\n * reach without a platform change to that mapping.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { RawTicketContext } from '../adapters';\nimport { createPlatformPromptPort } from '../adapters/ctx-ports';\n// L9: through the barrel, not `./shared` directly — `graph/nodes/index.ts`'s\n// own doc names `applySignature` as its one curated export existing FOR this\n// reuse; importing straight from the file it lives in made that barrel entry\n// unused and its own justification inaccurate.\nimport { applySignature } from '../graph/nodes';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport {\n EXT_CHAT_INPUT_AGENT_NAME_UID,\n EXT_CHAT_INPUT_GORGIAS_TICKET_ID_UID,\n EXT_CHAT_INPUT_MESSAGES_UID,\n EXT_CHAT_INPUT_MODEL_ID_UID,\n} from './ids';\nimport { ownsAgent, type ProbeClaim } from './ownership-probe';\nimport { draftPromptRefFor, toAgent, type AgentRecord } from './records';\nimport { readSupportExtensionEnvelope } from './support-extension-envelope';\n\nconst DEFAULT_AGENT_FILTER = { status: 'default' } as const;\n\ninterface WireChatMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n}\n\nexport interface ExtChatInput {\n messages?: Array<{ role?: unknown; content?: unknown }> | null;\n modelId?: string | null;\n agentName?: string | null;\n gorgiasTicketId?: string | null;\n}\n\nexport interface ExtChatResult {\n answer: string;\n modelId: string;\n langfuse_trace_id: string | null;\n langfuse_observation_id: string | null;\n prompt_name: string | null;\n prompt_version: number | null;\n}\n\nexport function buildExtChatFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-chat'),\n name: 'ext-chat',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: EXT_CHAT_INPUT_MESSAGES_UID,\n name: 'messages',\n type: FieldType.JSON,\n label: 'Messages',\n description: '[{role, content}] — required unless gorgiasTicketId is given.',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_CHAT_INPUT_MODEL_ID_UID,\n name: 'modelId',\n type: FieldType.TEXT,\n label: 'Model id',\n description: 'Absent falls back to the single status=\"default\" agent.',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_CHAT_INPUT_AGENT_NAME_UID,\n name: 'agentName',\n type: FieldType.TEXT,\n label: 'Agent name',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_CHAT_INPUT_GORGIAS_TICKET_ID_UID,\n name: 'gorgiasTicketId',\n type: FieldType.TEXT,\n label: 'Gorgias ticket id',\n isNullable: true,\n defaultValue: null,\n },\n ],\n };\n}\n\nexport function createExtChatHandler(): AppHandler {\n return (ctx, input) => extChatHandler(ctx as SupportKitHandlerContext, (input as ExtChatInput) ?? {});\n}\n\nexport async function extChatHandler(ctx: SupportKitHandlerContext, input: ExtChatInput): Promise<ExtChatResult | ProbeClaim | null> {\n const envelope = readSupportExtensionEnvelope(ctx);\n if (envelope.phase === 'probe') return probeChatOwnership(ctx, input.modelId ?? null);\n return executeChat(ctx, envelope.userId, input);\n}\n\nasync function probeChatOwnership(ctx: SupportKitHandlerContext, modelId: string | null): Promise<ProbeClaim | null> {\n if (modelId) return ownsAgent(ctx, modelId);\n const page = await ctx.api.list('agent', { filter: DEFAULT_AGENT_FILTER, limit: 1 });\n return page.items.length > 0 ? { claimed: true } : null;\n}\n\nasync function executeChat(ctx: SupportKitHandlerContext, userId: string, input: ExtChatInput): Promise<ExtChatResult> {\n const contextMessages = await resolveMessages(ctx, input);\n const agent = await resolveAgent(ctx, input.modelId ?? null);\n\n const promptPort = createPlatformPromptPort(ctx.api, (message) => ctx.logger.warn(message));\n // H5 (T25 review): draftPromptRefFor's \"no agent configured\" sentinel is\n // scoped by promptPrefix — but createExtChatHandler() takes no\n // SupportKitFunctionConfig at all (unlike every other ext-* handler that\n // needs one, none of the six do), so this call site has no promptPrefix\n // to pass. `{ promptPrefix: '' }` keeps today's behaviour for\n // experience-client unchanged; a pro-sante (or later) audience installed\n // with a non-empty prefix still 403s on this specific path exactly as it\n // already did before this fix. Threading config through the S6 gateway's\n // internal ext-chat invocation is a wider change than this finding's\n // fix — flagged, not silently masked.\n const promptRef = draftPromptRefFor(agent, { promptPrefix: '' });\n const resolvedPrompt = await promptPort.resolve(promptRef);\n const systemContent = applySignature(resolvedPrompt.text, input.agentName ?? undefined);\n const chatMessages: WireChatMessage[] = systemContent\n ? [{ role: 'system', content: systemContent }, ...contextMessages]\n : contextMessages;\n\n const result = await ctx.api.llm.complete({\n messages: chatMessages,\n // H3/I16: the resolved Langfuse prompt's own model config WINS over the\n // agent's fallback modelId — every ported graph node applies this same\n // rule (`draft.ts`, `triage.ts`, …); this was the one `PromptPort\n // .resolve` consumer in the repo that dropped it.\n options: { model: resolvedPrompt.config?.model ?? agent.modelId },\n // Link-only (D-LF follow-up, option (b)): this function already resolved\n // its own prompt two lines above via `PromptPort` — `resolve: false`\n // links the completion to it in Langfuse WITHOUT re-triggering the\n // platform's own resolution (no `manifest.prompts[]` gate, no\n // system-message replacement of the `applySignature`-signed message just\n // composed above). `label` is the REAL resolved label — `promptRef\n // .label`, i.e. `agent.promptLabel ?? 'production'`\n // (`functions/records.ts`'s `draftPromptRefFor`) — not a hardcoded\n // 'production', so a staging-labelled agent's traces say so instead of\n // silently attributing to production.\n promptRef: {\n name: resolvedPrompt.name,\n version: resolvedPrompt.version,\n label: promptRef.label,\n resolve: false,\n },\n trace: {\n sessionId: input.gorgiasTicketId ?? undefined,\n metadata: {\n // L2: the agent's own identity — `ctx.api.llm.complete`'s `trace`\n // has no dedicated `userId` field (unlike `graph/ports.ts`'s\n // `CompletionRequest`), only `metadata`. The prompt identity itself\n // no longer needs to travel here — `promptRef` above carries it.\n userId,\n model: agent.modelId,\n ...(input.gorgiasTicketId ? { ticketId: input.gorgiasTicketId } : {}),\n },\n },\n });\n\n const answer = result.text?.trim();\n if (!answer) throw new ctx.NonRetriableError('Provider returned an empty response');\n\n return {\n answer,\n modelId: agent.id,\n langfuse_trace_id: result.traceId ?? null,\n langfuse_observation_id: result.observationId ?? null,\n prompt_name: resolvedPrompt.name,\n prompt_version: resolvedPrompt.version,\n };\n}\n\nasync function resolveMessages(ctx: SupportKitHandlerContext, input: ExtChatInput): Promise<WireChatMessage[]> {\n if (input.gorgiasTicketId) {\n // L10: the exported `RawTicketContext` shape (`adapters/index.ts`),\n // not a second inline redeclaration of it. Note the divergence this\n // reader and `toConversation` (`adapters/conversation-mapping.ts`) have\n // on the SAME action's output: this one admits `system` turns\n // (matching the legacy chat route), `toConversation` filters them out —\n // both correct for what each one feeds, neither aware of the other.\n const raw = (await runBuildTicketContext(ctx, input.gorgiasTicketId)) as RawTicketContext;\n // M1: the legacy's shared `messages.length === 0` 400-guard covered\n // BOTH the `input.messages` path and this `gorgiasTicketId` one — this\n // port only guarded the former. A ticket with nothing extractable\n // (internal notes only, an automated-sender thread) must 400 instantly,\n // not pay for an LLM call with a system message and no conversation.\n if (!Array.isArray(raw.messages) || raw.messages.length === 0) {\n throw new ctx.NonRetriableError(`No usable messages extracted for Gorgias ticket ${input.gorgiasTicketId}`);\n }\n return raw.messages.map((m) => toWireChatMessage(m));\n }\n if (Array.isArray(input.messages) && input.messages.length > 0) {\n return input.messages.map((m) => toWireChatMessage(m));\n }\n throw new ctx.NonRetriableError('`messages` must be a non-empty array, or provide `gorgiasTicketId`');\n}\n\n/**\n * L1, PARTIAL — see this module's own doc for what is and is not achievable\n * here. Distinguishes the one genuinely non-retriable Gorgias failure (the\n * ticket does not exist) from everything else (misconfiguration, the\n * provider being down, a timeout) by DUCK-TYPING the error shape\n * `@apotech-os/gorgias-client`'s `ProviderHttpError` carries — `status`/\n * `name` on the caught value — rather than an `instanceof` check: this\n * package has no dependency on `gorgias-client` at all\n * (`dependency-allowlist.ts`; an app cannot import a platform-internal\n * client), so a structural check is the only kind available.\n */\nasync function runBuildTicketContext(ctx: SupportKitHandlerContext, ticketId: string): Promise<unknown> {\n try {\n return await ctx.api.integrations.run('gorgias', 'buildTicketContext', { ticketId });\n } catch (err) {\n if (isGorgiasNotFound(err)) {\n throw new ctx.NonRetriableError(`Gorgias ticket ${ticketId} not found`);\n }\n // Everything else (misconfigured connection, the provider down, a\n // timeout) is NOT retried by throwing `NonRetriableError` — unlike a\n // missing ticket, a transient Gorgias outage may well succeed on the\n // next call. This still surfaces as a generic 500 to the extension: see\n // this module's own doc for why 503/502 are unreachable from here.\n throw err;\n }\n}\n\nfunction isGorgiasNotFound(err: unknown): boolean {\n if (typeof err !== 'object' || err === null) return false;\n const { status } = err as { status?: unknown };\n return status === 404;\n}\n\nfunction toWireChatMessage(raw: { role?: unknown; content?: unknown }): WireChatMessage {\n const role = raw.role;\n if (role !== 'system' && role !== 'user' && role !== 'assistant') {\n throw new Error(`ext-chat: message role must be \"system\", \"user\" or \"assistant\", got ${JSON.stringify(role)}`);\n }\n return { role, content: typeof raw.content === 'string' ? raw.content : '' };\n}\n\nasync function resolveAgent(ctx: SupportKitHandlerContext, modelId: string | null): Promise<AgentRecord> {\n if (modelId) {\n const record = await getOptional(ctx, 'agent', modelId);\n if (!record) throw new ctx.NonRetriableError(`Model not found (id=${modelId})`);\n return toAgent(record);\n }\n const page = await ctx.api.list('agent', { filter: DEFAULT_AGENT_FILTER, limit: 1 });\n const record = page.items[0];\n if (!record) throw new ctx.NonRetriableError('No default model configured');\n return toAgent(record);\n}\n","/**\n * `ext-fast-response-check` (§5.2, §3.5 line 291) — `uiInvoke`, reserved,\n * always `phase: 'execute'`, fanned out to every accessible app (§S6: \"au\n * plus un hit attendu — premier hit servi, hits multiples loggés en\n * anomalie\" — that fan-out/first-hit policy is the GATEWAY's, not this\n * function's). Ports legacy `POST /api/fast-response/check`\n * (extension-overview backoffice/src/routes/api.ts:291) — the most\n * defect-prone of the six, ported rule for rule:\n *\n * 1. Look up the `generated-response` row for `ticket_id` with `status:\n * 'ready'`. None → `{available: false}`.\n * 2. TTL: `expiresAt < now` → flip `ready -> expired` (conditional on still\n * being `ready`, S5 `ifMatch`) and return `{available: false}`.\n * 3. Divergence, RECOMPUTED SERVER-SIDE — never from client-supplied\n * values: re-fetch the ticket via S1's `getRawTicket` action and take\n * the snapshot with the kit's own `snapshotConversation`\n * (`adapters/conversation-mapping.ts`, already the symmetric port of the\n * extension's `countableMessages`/divergence rule — reused, not\n * re-derived). Diverged (`currentCount > snappedCount`, or\n * `currentLastAt` present and newer than `snappedLastAt`/absent) → flip\n * `ready -> invalidated` and return `{available: false}`.\n * 4. Gorgias fetch failure, OR a successful-but-unusable payload (no\n * `ticket`, or a `ticket` with no messages — H1 hardening: otherwise\n * `snapshotConversation({})` reads as zero messages, which can only ever\n * look like NO divergence and would serve a stale draft) ⇒ FAIL-CLOSED:\n * `{available: false}`, the row is left `ready`, nothing is written — a\n * transient Gorgias outage must never look like \"the draft was\n * invalidated\".\n * 5. Hit: `servedCount++`, push `{user, at}` onto `servedTo` (capped at 500\n * entries — `servedCount` keeps incrementing past the cap, only the\n * array stops growing) via S5 `ifMatch: {servedCount: <value just read>}`\n * PLUS A RETRY: the read-modify-write of the `servedTo` JSON array is not\n * atomic, so a lost `ifMatch` race (two concurrent `/check` calls on the\n * same ready row) re-reads the row and retries with the fresh count —\n * UNLESS the re-read shows the row is no longer `ready` (another writer\n * genuinely moved it: an expiry/divergence flip, or a send), in which\n * case this is a real miss, exactly the legacy's `race_lost` branch —\n * see `serveHit` below, bounded at `MAX_SERVE_ATTEMPTS`. CASing on\n * `status` here (H2 hardening) would be a no-op guard: this write never\n * changes `status`, so two concurrent hits would both pass an\n * `ifMatch: {status: 'ready'}` unconditionally and one serve record\n * would silently vanish — `servedCount` is the field that actually\n * discriminates concurrent writers.\n *\n * `followup_required` — DECISION (the brief asks for one, explicitly):\n * derived from the record's `verdict.verdict` field via the ported\n * `requiresFollowup` (legacy-faithful: `requiresFollowup(job\n * .evaluation_verdict)`), NOT read off a stored `followupRequired`\n * boolean. Checked before choosing: `records/generated-response.ts`\n * declares `followupRequired` with a `false` default, and grep across this\n * package shows exactly ONE writer — `triage-tick.ts` sets it `false` at\n * CREATION time — and no writer ever updates it once the real verdict is\n * known (`process-response.ts` persists `verdict` on the `ready` row but\n * never touches `followupRequired`). The stored field is therefore\n * effectively dead (always `false`); deriving from `verdict` is both\n * legacy-faithful and the only way to get a correct answer.\n *\n * `last_served_at` — the legacy also stamped this on every hit; the kit's\n * `generated-response` record (§3.4, frozen at T20) has no such field.\n * NOT silently dropped: nothing in this package reads it, and each\n * `servedTo[].at` entry already carries the same information (the most\n * recent entry IS the last-served timestamp) — so the cost is a query that\n * wants \"when was this last served\" needing to read the tail of `servedTo`\n * instead of one scalar field, not a loss of information.\n *\n * SETTINGS VALIDATION: deliberately NOT called. This function reads\n * `expiresAt` off the ROW itself — computed once at generation time from\n * `responseTtlMinutes`, already baked in — never a live settings read; none\n * of `validateSettings`'s three checks (`sourceViewId`, `nodes.triage`,\n * `senderEmail`) apply to serving an already-generated draft.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n */\nimport { AppApiError, type AppApiRecord, type AppHandler, FieldType, type FunctionDef } from '@apotech-os/app-kit';\nimport { snapshotConversation } from '../adapters/conversation-mapping';\nimport type { RawTicket } from '../guardrails';\nimport { isEvaluationVerdict, requiresFollowup } from '../domain';\nimport { isGeneratedResponseStatus, type GeneratedResponseStatus } from '../status/machine';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport { transitionGeneratedResponse } from './generated-response-transition';\nimport { EXT_FAST_RESPONSE_CHECK_INPUT_TICKET_ID_UID } from './ids';\nimport { toDate } from './pipeline-state';\nimport { toAgent, toCategory, toGeneratedResponse, type GeneratedResponseRecord } from './records';\nimport { readSupportExtensionEnvelope } from './support-extension-envelope';\n\nconst SERVED_TO_CAP = 500;\nconst MAX_SERVE_ATTEMPTS = 3;\n\nexport interface ExtFastResponseCheckInput {\n ticket_id: string;\n}\n\nexport type ExtFastResponseCheckResult =\n | { available: false }\n | {\n available: true;\n response: string;\n category: { _id: string; name: string } | null;\n agent: { _id: string; name: string; model_id: string } | null;\n langfuse_trace_id: string | null;\n langfuse_observation_id: string | null;\n prompt_name: string | null;\n prompt_version: number | null;\n generated_at: string;\n followup_required: boolean;\n };\n\nexport function buildExtFastResponseCheckFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-fast-response-check'),\n name: 'ext-fast-response-check',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: EXT_FAST_RESPONSE_CHECK_INPUT_TICKET_ID_UID,\n name: 'ticket_id',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: false,\n },\n ],\n };\n}\n\nexport function createExtFastResponseCheckHandler(): AppHandler {\n return (ctx, input) => extFastResponseCheckHandler(ctx as SupportKitHandlerContext, input as unknown as ExtFastResponseCheckInput);\n}\n\nconst NOT_AVAILABLE: ExtFastResponseCheckResult = { available: false };\n\nexport async function extFastResponseCheckHandler(\n ctx: SupportKitHandlerContext,\n input: ExtFastResponseCheckInput,\n): Promise<ExtFastResponseCheckResult> {\n const ticketId = typeof input?.ticket_id === 'string' ? input.ticket_id.trim() : '';\n if (!ticketId) throw new ctx.NonRetriableError('`ticket_id` must be a non-empty string');\n\n const page = await ctx.api.list('generated-response', { filter: { ticketId, status: 'ready' }, limit: 1 });\n const row = page.items[0];\n if (!row) {\n logReason(ctx, ticketId, 'no_ready_job');\n return NOT_AVAILABLE;\n }\n const generatedResponse = toGeneratedResponse(row);\n\n const now = new Date();\n\n const expiresAt = toDate(generatedResponse.expiresAt);\n if (expiresAt && expiresAt.getTime() < now.getTime()) {\n logReason(ctx, ticketId, 'expired');\n await flipStatus(ctx, row.id, ticketId, 'expired');\n return NOT_AVAILABLE;\n }\n\n let rawTicket: RawTicket;\n try {\n const fetched = (await ctx.api.integrations.run('gorgias', 'getRawTicket', { ticketId })) as { ticket?: RawTicket };\n // H1 hardening: a successful-but-unusable payload (no `ticket`, or a\n // `ticket` with no messages) is indistinguishable from a fetch failure\n // for divergence purposes — `snapshotConversation({})` would read as\n // \"0 messages, no last-message date\", which can only ever look like\n // NO divergence and would serve a draft that may already be stale.\n // Fail-closed the same way rule 4 does for a thrown fetch error.\n if (!fetched.ticket || !fetched.ticket.messages || fetched.ticket.messages.length === 0) {\n logReason(ctx, ticketId, 'gorgias_fetch_failed', 'empty or missing ticket.messages');\n return NOT_AVAILABLE;\n }\n rawTicket = fetched.ticket;\n } catch (err) {\n // Fail-closed (rule 4): cannot validate the draft is still fresh, so it\n // is unavailable — but the row itself is left untouched.\n logReason(ctx, ticketId, 'gorgias_fetch_failed', err instanceof Error ? err.message : String(err));\n return NOT_AVAILABLE;\n }\n\n const divergence = checkDivergence(rawTicket, generatedResponse);\n if (divergence.diverged) {\n logReason(ctx, ticketId, `diverged[count(snap=${divergence.snappedCount},now=${divergence.count}),date(snap=${isoOrNull(divergence.snappedLastAt)},now=${isoOrNull(divergence.lastAt)})]`);\n await flipStatus(ctx, row.id, ticketId, 'invalidated');\n return NOT_AVAILABLE;\n }\n\n const envelope = readSupportExtensionEnvelope(ctx);\n // L11: an empty platform user id must fail the WRITE, not silently push\n // `servedTo: [{user: '', at}]` — an anonymous entry indistinguishable\n // from a legitimate serve. `readSupportExtensionEnvelope`'s own doc notes\n // this never happens through the real gateway; this is the last line of\n // defence against a malformed envelope masquerading as a real one.\n if (!envelope.userId) {\n throw new ctx.NonRetriableError('ext-fast-response-check: missing platform user id in the invocation envelope');\n }\n const served = await serveHit(ctx, row, envelope.userId, now);\n if (!served) {\n logReason(ctx, ticketId, 'race_lost');\n return NOT_AVAILABLE;\n }\n const servedResponse = toGeneratedResponse(served);\n logReason(ctx, ticketId, `hit served_count=${servedResponse.servedCount}`);\n if (servedResponse.servedCount > SERVED_TO_CAP) {\n ctx.logger.warn(`ext-fast-response-check: ticket=${ticketId} servedTo capped at ${SERVED_TO_CAP} entries (served_count=${servedResponse.servedCount})`);\n }\n\n return buildAvailableResponse(ctx, servedResponse);\n}\n\nfunction logReason(ctx: SupportKitHandlerContext, ticketId: string, reason: string, detail?: string): void {\n const suffix = detail ? ` detail=${JSON.stringify(detail)}` : '';\n ctx.logger.info(`ext-fast-response-check: ticket=${ticketId} reason=${reason}${suffix}`);\n}\n\nfunction isoOrNull(date: Date | null): string {\n return date ? date.toISOString() : 'null';\n}\n\ninterface DivergenceCheck {\n diverged: boolean;\n count: number;\n lastAt: Date | null;\n snappedCount: number;\n snappedLastAt: Date | null;\n}\n\n/**\n * L3: a SECOND `hasDiverged`, deliberately not unified with `graph/nodes\n * /act.ts`'s own — that one uses `!==` on both count and timestamp (any\n * change, either direction, since a re-send must never fire on a run that\n * has already drifted in EITHER direction); this one is faithful to the\n * legacy's own `POST /api/fast-response/check` rule (`count >`, \"strictly\n * newer\") — a same-or-earlier snapshot is not a divergence for the purpose\n * of serving an already-generated draft. `handle-approval.ts:142-143` reads\n * the same two stored fields by hand a third time, for the same reason\n * `act`'s check does (I8's re-read).\n */\nfunction checkDivergence(rawTicket: RawTicket, generatedResponse: GeneratedResponseRecord): DivergenceCheck {\n const snapshot = snapshotConversation(rawTicket);\n const snappedCount = generatedResponse.generatedMessageCount;\n const snappedLastAt = toDate(generatedResponse.generatedLastMessageAt);\n\n const divergedByCount = snapshot.count > snappedCount;\n const divergedByDate = !!snapshot.lastAt && (!snappedLastAt || snapshot.lastAt.getTime() > snappedLastAt.getTime());\n return { diverged: divergedByCount || divergedByDate, count: snapshot.count, lastAt: snapshot.lastAt, snappedCount, snappedLastAt };\n}\n\n/** `ready -> expired|invalidated`, tolerating a lost race (someone else already moved the row) — the outcome (`{available:false}`) is the same either way. */\nasync function flipStatus(\n ctx: SupportKitHandlerContext,\n id: string,\n ticketId: string,\n status: Extract<GeneratedResponseStatus, 'expired' | 'invalidated'>,\n): Promise<void> {\n await transitionGeneratedResponse(ctx.api, { id, ticketId, from: 'ready', to: status });\n}\n\n/**\n * Rule 5's retry loop (see this module's own doc). Re-reads and retries on\n * a lost `ifMatch` race PROVIDED the row is still `ready` after the\n * re-read; a row that moved off `ready` — INCLUDING one an admin deleted\n * outright (L4: `getOptional`, not `api.get`, so a 404 here reads as the\n * same ordinary miss the legacy's `race_lost` names it, not an app failure\n * `fanOutSettled` would log as an anomaly) — is a genuine miss, returned as\n * `null` without a further retry.\n */\nasync function serveHit(ctx: SupportKitHandlerContext, row: AppApiRecord, userId: string, now: Date): Promise<AppApiRecord | null> {\n let current = row;\n for (let attempt = 0; attempt < MAX_SERVE_ATTEMPTS; attempt++) {\n const currentData = toGeneratedResponse(current);\n const { servedCount, servedTo } = currentData;\n const nextServedTo = servedCount < SERVED_TO_CAP ? [...servedTo, { user: userId, at: now.toISOString() }] : servedTo;\n\n try {\n // H2: CAS on the field this write actually changes (`servedCount`),\n // not `status` — the hit path never moves `status` off `ready`, so an\n // `ifMatch: {status: 'ready'}` guard would let two concurrent hits\n // both pass unconditionally (see this function's own doc, rule 5).\n return await ctx.api.update(\n 'generated-response',\n current.id,\n { servedCount: servedCount + 1, servedTo: nextServedTo },\n { ifMatch: { servedCount } },\n );\n } catch (err) {\n if (!(err instanceof AppApiError) || err.status !== 409) throw err;\n const fresh = await getOptional(ctx, 'generated-response', current.id);\n // L7: the untrusted-JSONB boundary — `isGeneratedResponseStatus`,\n // same guard `isEvaluationVerdict` applies to `verdict` a few lines\n // below, instead of a raw string compare against an unknown value.\n const freshStatus = fresh ? (fresh.data as Record<string, unknown>).status : undefined;\n if (!fresh || !isGeneratedResponseStatus(freshStatus) || freshStatus !== 'ready') return null;\n current = fresh;\n }\n }\n return null;\n}\n\nasync function buildAvailableResponse(ctx: SupportKitHandlerContext, generatedResponse: GeneratedResponseRecord): Promise<ExtFastResponseCheckResult> {\n const category = await resolveCategoryRef(ctx, generatedResponse.categoryId);\n const agent = await resolveAgentRef(ctx, generatedResponse.agentId);\n // L5: the legacy returned `served.generated_at` verbatim — no fabricated\n // \"now\" fallback. The real record declares `generatedAt` `isNullable:\n // false` (`records/generated-response.ts`), so a row reaching this point\n // without one is corrupted data, not a case to paper over: the extension\n // uses this field to show draft freshness, and silently reporting \"just\n // now\" on a possibly-stale draft is worse than a loud failure.\n const generatedAt = toDate(generatedResponse.generatedAt);\n if (!generatedAt) {\n throw new ctx.NonRetriableError(`generated-response ${generatedResponse.id} is ready but has no generatedAt`);\n }\n const verdictValue = isEvaluationVerdict(generatedResponse.verdict?.verdict) ? generatedResponse.verdict.verdict : null;\n\n return {\n available: true,\n response: generatedResponse.responseText ?? '',\n category,\n agent,\n langfuse_trace_id: generatedResponse.langfuseTraceId,\n langfuse_observation_id: generatedResponse.langfuseObservationId,\n prompt_name: generatedResponse.promptName,\n prompt_version: generatedResponse.promptVersion,\n generated_at: generatedAt.toISOString(),\n followup_required: requiresFollowup(verdictValue),\n };\n}\n\nasync function resolveCategoryRef(ctx: SupportKitHandlerContext, categoryId: string | null): Promise<{ _id: string; name: string } | null> {\n if (!categoryId) return null;\n const record = await getOptional(ctx, 'category', categoryId);\n if (!record) return null;\n const category = toCategory(record);\n return { _id: category.id, name: category.name };\n}\n\nasync function resolveAgentRef(\n ctx: SupportKitHandlerContext,\n agentId: string | null,\n): Promise<{ _id: string; name: string; model_id: string } | null> {\n if (!agentId) return null;\n const record = await getOptional(ctx, 'agent', agentId);\n if (!record) return null;\n const agent = toAgent(record);\n return { _id: agent.id, name: agent.name, model_id: agent.modelId };\n}\n","/**\n * `ext-evaluation` (§5.2, §3.5 line 291) — `uiInvoke`, reserved, ownership-\n * routed (§S6). Ports legacy `POST /api/models/:id/evaluation`\n * (extension-overview backoffice/src/routes/api.ts:96). The gateway hands\n * this function `{...body, modelId}` (`SupportExtensionService.evaluation`\n * injects the URL's `:modelId` into the body itself), so `modelId` is\n * always present on `phase: 'execute'`.\n *\n * OWNERSHIP PROBE: `{modelId}`, `modelId` always a real value here (unlike\n * `ext-chat`, there is no \"absent modelId\" branch — the legacy route always\n * has one, from the URL). Claim iff this app owns an `agent` record with\n * that id — a read only, no write/LLM/Gorgias call.\n *\n * EXECUTE: `{satisfied, messages, ticket_url, langfuse_trace_id,\n * langfuse_observation_id, modelId}` → `201` (body ignored by the\n * extension, §5.2). `satisfied` must be a boolean (legacy 400s otherwise).\n * Writes an `evaluation` record with `agentId` = the resolved agent and\n * `supportUserKeyId` = the platform user id read off\n * `ctx.event.supportExtension` (§5.1: \"les records servedTo/évaluations\n * portent l'id utilisateur plateforme\").\n *\n * `ticketUrl` GAP (recorded, not silently routed around; L12 — DECISION\n * made explicitly, not deferred): the extension's request body treats\n * `ticket_url` as optional (legacy: `ticket_url ?? null`), but the T20\n * `evaluation` record (`records/evaluation.ts`) declares `ticketUrl` as\n * `isNullable: false` — no default, no null. Rather than reach back into a\n * frozen T20 record definition (out of this task's scope) or silently\n * attempt an `undefined`/`null` write that would fail the object's own\n * field validation, an absent/non-string `ticket_url` is persisted as an\n * empty string.\n * This is WORSE here than the same gap on `response-comparison.ticketUrl`:\n * `evaluation` has NO `ticketId` field at all (grep `records/evaluation\n * .ts` — `agentId`, `satisfied`, `messages`, `ticketUrl`, the two Langfuse\n * ids, `supportUserKeyId`; nothing else), so `ticketUrl` is this record's\n * ONLY link back to a ticket. `''` is indistinguishable from a genuinely\n * empty URL, and a later backfill has no way to tell \"never sent\" from\n * \"sent empty\". The correct fix is making the field nullable and writing\n * `null` — DECLINED here, deliberately, because it means extending a\n * record definition the spec freezes at T20 (§3.4), which is a call for\n * whoever owns that record, not a T24 function. Flagged for whoever owns\n * `records/evaluation.ts` next, with the concrete cost spelled out above\n * rather than left implicit.\n *\n * LANGFUSE SCORE: when `langfuse_trace_id` is a non-empty string, writes a\n * `user-feedback` BOOLEAN score (S4) with the legacy's deterministic id\n * `user-feedback-<traceId>` (idempotent — toggling 👍/👎 updates the same\n * score instead of creating duplicates). `comment` folds in what the\n * legacy's dataset-store `metadata` carried (`model`, `ticket_url`) — S4's\n * `ctx.api.langfuse.scores.create` has no generic `metadata` field on the\n * platform surface (`CreateLangfuseScoreInput`), only `comment`. The\n * platform user's NAME is not available off `ctx.event` (only the user\n * id), so the comment uses the id instead of the legacy's `req.user.name`.\n * Both deviations are platform-surface limits, not this function's choice.\n * The score write is wrapped and its failure SWALLOWED — legacy is\n * explicit that this block is non-fatal and the 201 is guaranteed.\n *\n * SETTINGS VALIDATION: deliberately NOT called — writing an evaluation and\n * an optional score touches none of `validateSettings`'s three checked\n * fields.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport { getOptional } from './context';\nimport type { SupportKitHandlerContext } from './context';\nimport {\n EXT_EVALUATION_INPUT_LANGFUSE_OBSERVATION_ID_UID,\n EXT_EVALUATION_INPUT_LANGFUSE_TRACE_ID_UID,\n EXT_EVALUATION_INPUT_MESSAGES_UID,\n EXT_EVALUATION_INPUT_MODEL_ID_UID,\n EXT_EVALUATION_INPUT_SATISFIED_UID,\n EXT_EVALUATION_INPUT_TICKET_URL_UID,\n} from './ids';\nimport { ownsAgent, type ProbeClaim } from './ownership-probe';\nimport { toAgent } from './records';\nimport { readSupportExtensionEnvelope } from './support-extension-envelope';\n\nexport interface ExtEvaluationInput {\n modelId: string;\n satisfied?: unknown;\n messages?: Array<{ role: string; content: string }> | null;\n ticket_url?: string | null;\n langfuse_trace_id?: string | null;\n langfuse_observation_id?: string | null;\n}\n\nexport interface ExtEvaluationResult {\n ok: true;\n id: string;\n}\n\nexport function buildExtEvaluationFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-evaluation'),\n name: 'ext-evaluation',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n { universalIdentifier: EXT_EVALUATION_INPUT_MODEL_ID_UID, name: 'modelId', type: FieldType.TEXT, label: 'Model id', isNullable: false },\n { universalIdentifier: EXT_EVALUATION_INPUT_SATISFIED_UID, name: 'satisfied', type: FieldType.BOOLEAN, label: 'Satisfied', isNullable: false },\n {\n universalIdentifier: EXT_EVALUATION_INPUT_MESSAGES_UID,\n name: 'messages',\n type: FieldType.JSON,\n label: 'Messages',\n description: '[{role, content}]',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_EVALUATION_INPUT_TICKET_URL_UID,\n name: 'ticket_url',\n type: FieldType.TEXT,\n label: 'Ticket URL',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_EVALUATION_INPUT_LANGFUSE_TRACE_ID_UID,\n name: 'langfuse_trace_id',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_EVALUATION_INPUT_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuse_observation_id',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n defaultValue: null,\n },\n ],\n };\n}\n\nexport function createExtEvaluationHandler(): AppHandler {\n return (ctx, input) => extEvaluationHandler(ctx as SupportKitHandlerContext, input as unknown as ExtEvaluationInput);\n}\n\nexport async function extEvaluationHandler(\n ctx: SupportKitHandlerContext,\n input: ExtEvaluationInput,\n): Promise<ExtEvaluationResult | ProbeClaim | null> {\n const envelope = readSupportExtensionEnvelope(ctx);\n if (envelope.phase === 'probe') return ownsAgent(ctx, input?.modelId ?? null);\n return executeEvaluation(ctx, envelope.userId, input);\n}\n\nasync function executeEvaluation(\n ctx: SupportKitHandlerContext,\n userId: string,\n input: ExtEvaluationInput,\n): Promise<ExtEvaluationResult> {\n if (typeof input.satisfied !== 'boolean') {\n throw new ctx.NonRetriableError('`satisfied` is a required boolean');\n }\n // L11: an empty platform user id must fail the WRITE — §5.1 requires this\n // record to carry it, and silently writing `supportUserKeyId: null`\n // drops that requirement instead of refusing.\n if (!userId) {\n throw new ctx.NonRetriableError('ext-evaluation: missing platform user id in the invocation envelope');\n }\n const modelId = input.modelId;\n if (!modelId) throw new ctx.NonRetriableError('modelId is required');\n const agentRecord = await getOptional(ctx, 'agent', modelId);\n if (!agentRecord) throw new ctx.NonRetriableError(`Model not found (id=${modelId})`);\n const agent = toAgent(agentRecord);\n\n const satisfied = input.satisfied;\n const messages = Array.isArray(input.messages) ? input.messages : [];\n // See this module's doc — the record's `ticketUrl` is `isNullable: false`,\n // so an absent/non-string value is persisted as an empty string, not null.\n const ticketUrl = typeof input.ticket_url === 'string' ? input.ticket_url : '';\n const traceId = typeof input.langfuse_trace_id === 'string' && input.langfuse_trace_id.length > 0 ? input.langfuse_trace_id : null;\n const observationId =\n typeof input.langfuse_observation_id === 'string' && input.langfuse_observation_id.length > 0\n ? input.langfuse_observation_id\n : undefined;\n\n const created = await ctx.api.create('evaluation', {\n agentId: agent.id,\n satisfied,\n messages,\n ticketUrl,\n langfuseTraceId: traceId,\n langfuseObservationId: observationId ?? null,\n // Non-empty: guarded above (L11).\n supportUserKeyId: userId,\n });\n\n if (traceId) {\n try {\n await ctx.api.langfuse.scores.create({\n id: `user-feedback-${traceId}`,\n traceId,\n observationId,\n name: 'user-feedback',\n value: satisfied,\n dataType: 'BOOLEAN',\n comment: `Thumbs ${satisfied ? 'up' : 'down'} from ${userId || 'agent'} (model: ${agent.name}, ticket_url: ${ticketUrl || 'none'})`,\n });\n } catch (err) {\n // Non-fatal — legacy is explicit that the 201 is guaranteed regardless.\n ctx.logger.warn(`ext-evaluation: user-feedback score write failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n return { ok: true, id: created.id };\n}\n","/**\n * `ext-response-comparison` (§5.2, §3.5 line 291) — `uiInvoke`, reserved,\n * ownership-routed (§S6). Ports legacy `POST /api/response-comparisons`\n * (extension-overview backoffice/src/routes/api.ts:404).\n *\n * The gateway already short-circuits `last_message_generated == null` to a\n * `204` BEFORE ever invoking any app, and maps a `null` return from this\n * function to `204` too (`SupportExtensionController.responseComparison`).\n * This handler keeps its OWN guard anyway (per this migration's explicit\n * instruction) — belt and braces, and it is exercised directly by this\n * file's own tests, which do not go through the gateway.\n *\n * OWNERSHIP PROBE (§S6): `model_config_id` non-empty → probe payload\n * `{model_config_id}`, claim iff this app owns that `agent` record.\n * Otherwise → probe payload `{ticket_id, ticket_url}` (§S6: \"sinon fan-out\n * sur la propriété du ticket (`triage-decision`)\") — claim iff this app has\n * a `triage-decision` row for that `ticket_id` (the ticket was triaged by\n * THIS app, i.e. it belongs to this audience). `ticket_url` plays no part\n * in the ownership check (the legacy never used it for anything but\n * display either); it only reaches the WRITE below.\n *\n * EXECUTE: `message_actual_sent` missing → 400-equivalent (legacy 400s);\n * `last_message_generated` null → the guard above. Otherwise writes a\n * `response-comparison` record (`generatedText`/`sentText`/`capturedAt`\n * plus the frozen body's other fields, and `diff` — `response-comparison-\n * diff.ts`'s `computeWordDiff`, \"computed at write time\" per §3.4), then\n * attempts the Langfuse capture.\n *\n * `ticketUrl` GAP (L12 — DECISION made explicitly, not deferred) — the SAME\n * one `ext-evaluation.ts` documents for `evaluation.ticketUrl`: the T20\n * `response-comparison` record declares `ticketUrl` `isNullable: false`,\n * but the extension's own contract treats it as optional. An absent/\n * non-string value is persisted as an empty string, not `null`. Unlike\n * `evaluation`, this record DOES have its own `ticketId` field, so `''`\n * here is not the only link back to a ticket — a strictly smaller gap.\n * Making `ticketUrl` nullable and writing `null` is still the correct fix;\n * DECLINED here for the same reason as `ext-evaluation.ts`: it means\n * extending a T20-frozen record definition (§3.4), a call for whoever owns\n * `records/response-comparison.ts`, not this function.\n *\n * LANGFUSE CAPTURE — gates, decided explicitly: legacy gated on THREE\n * conditions — `CAPTURE_CORRECTIONS_TO_LANGFUSE === 'true'` (an env flag),\n * `message_actual_sent !== last_message_generated` (`textChanged`), and a\n * non-empty trace id. The kit has NO env access (§3.1) and the migration\n * spec §5.2 does not mention this flag at all, so it is DROPPED — the\n * remaining two gates stay: `textChanged` (an unedited reply is not a\n * correction and would poison the `cs-replies-corrections` dataset with\n * noise) and a non-empty trace id (nothing to link the correction back\n * to). Practical effect: this kit ALWAYS captures a genuine edit when a\n * trace id is present, where the legacy required an operator to also\n * enable a deployment flag — a deliberate widening, not an oversight.\n *\n * Dataset item id: the legacy's own deterministic\n * `<traceId>:<observationId>` (or `<traceId>` alone with no observation).\n * SCORE id: the legacy's `createCorrectionScore` had NONE (Langfuse\n * auto-assigns one on every call) — but S4's `ctx.api.langfuse.scores\n * .create` requires an `id` (`CreateLangfuseScoreInput.id`, non-optional).\n * This function reuses the SAME deterministic dataset-item id for the\n * score, which is required by the platform surface — NOT, despite the\n * tempting name, a general idempotency guarantee (H5/L14 correction of an\n * earlier overclaim in this doc):\n * - Langfuse keys a score on `(id, name, toDate(timestamp))`, and\n * `POST /api/public/scores` has no caller-supplied timestamp — a retry\n * that crosses a UTC day boundary from the original call creates a\n * SECOND score under the same id (`AppLangfuseService.createScore`'s\n * own doc, `apps/api/src/platform-data/app-langfuse.service.ts`).\n * - Two DIFFERENT edits on the same trace within the same day reuse this\n * same id and the SECOND CORRECTION score OVERWRITES the first — the\n * legacy minted a distinct score object per edit, so this is a real\n * narrowing, not a wash.\n * Same for the dataset item: a deterministic id genuinely IS a concurrency\n * safety net for the CONCURRENT case (two callers racing on the identical\n * id — Langfuse upserts by id, so the race has a defined winner instead of\n * two rows). What it is NOT is protection for the SEQUENTIAL case: reusing\n * that same deterministic id also means a SECOND, LATER correction on the\n * same generation (an agent edits and\n * sends, then the extension re-posts the same generation on a retry, or a\n * client retries after a lost 201) silently REPLACES `expectedOutput` with\n * the newer edit — last-write-wins, not accumulated history. The legacy\n * guarded exactly this (api.ts:490-497: skip the write when a\n * `ResponseComparison` with this `langfuse_observation_id` already has a\n * `dataset_item_created_at`); this port has no such field to guard on (the\n * T20-frozen `response-comparison` record declares none) and the guard was\n * dropped, not ported. DECIDED, not silently accepted: adding\n * `datasetItemCreatedAt` would mean extending a T20-frozen record\n * definition, out of this task's scope — documenting the real behaviour\n * here (drift toward the latest edit, not a hard guarantee) is the\n * alternative the review offered, and is what this paragraph now does.\n *\n * SCORE VALUE LENGTH — UNVERIFIED, flagged rather than guessed: `value:\n * JSON.stringify(expectedOutput)` embeds the full sent reply. If Langfuse\n * caps score values at some length (a commonly-cited limit for certain\n * value/comment fields is 500 characters, but this could not be confirmed\n * from code in this repo), a real support reply could exceed it. The write\n * is swallowed non-fatally below, so an over-length value would 400 here\n * silently — the feature would look like it works while writing nothing.\n * Treat this as a pre-ship manual probe (write a >500-char correction\n * against a real/staging Langfuse project and confirm the score lands),\n * not a guarantee this doc makes.\n *\n * `traced_input` — read defensively off the raw payload for the dataset\n * item's `input`, falling back to `conversation_messages` when absent\n * (legacy's own fallback rule) — NOT part of §5.2's frozen field table, so\n * it is not declared in this function's `input` FieldDef[] (an\n * undeclared/extra key reaches the handler unstripped; see\n * `app-input-validation.ts`'s zod-strip behaviour), but the extension may\n * still send it and its value should not be silently discarded when it\n * does.\n *\n * Both Langfuse writes (dataset item, score) are wrapped and their failure\n * SWALLOWED — legacy is explicit that this block is non-fatal.\n *\n * SETTINGS VALIDATION: deliberately NOT called — none of `validateSettings`'s\n * three checked fields apply to writing a comparison/capturing a\n * correction.\n *\n * `minRole: 'VIEWER'` is load-bearing — see `ext-models.ts`'s doc.\n */\nimport { FieldType, type AppHandler, type FunctionDef } from '@apotech-os/app-kit';\nimport type { SupportKitFunctionConfig } from './config';\nimport { identifierFor } from './config';\nimport type { SupportKitHandlerContext } from './context';\nimport {\n EXT_RESPONSE_COMPARISON_INPUT_CONVERSATION_MESSAGES_UID,\n EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_OBSERVATION_ID_UID,\n EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_TRACE_ID_UID,\n EXT_RESPONSE_COMPARISON_INPUT_LAST_MESSAGE_GENERATED_UID,\n EXT_RESPONSE_COMPARISON_INPUT_MESSAGE_ACTUAL_SENT_UID,\n EXT_RESPONSE_COMPARISON_INPUT_MODEL_CONFIG_ID_UID,\n EXT_RESPONSE_COMPARISON_INPUT_PROMPT_NAME_UID,\n EXT_RESPONSE_COMPARISON_INPUT_PROMPT_VERSION_UID,\n EXT_RESPONSE_COMPARISON_INPUT_TICKET_ID_UID,\n EXT_RESPONSE_COMPARISON_INPUT_TICKET_URL_UID,\n} from './ids';\nimport { ownsAgent, type ProbeClaim } from './ownership-probe';\nimport { computeWordDiff } from './response-comparison-diff';\nimport { readSupportExtensionEnvelope } from './support-extension-envelope';\n\nconst CORRECTIONS_DATASET = 'cs-replies-corrections';\n\nexport interface ExtResponseComparisonInput {\n last_message_generated?: string | null;\n message_actual_sent?: string;\n ticket_id?: string | null;\n ticket_url?: string | null;\n model_config_id?: string | null;\n langfuse_trace_id?: string | null;\n langfuse_observation_id?: string | null;\n prompt_name?: string | null;\n prompt_version?: number | null;\n conversation_messages?: unknown[] | null;\n /** Not part of §5.2's frozen field table — see this module's own doc. */\n traced_input?: unknown[] | null;\n}\n\nexport interface ExtResponseComparisonResult {\n ok: true;\n id: string;\n}\n\nexport function buildExtResponseComparisonFunctionDef(config: SupportKitFunctionConfig): FunctionDef {\n return {\n universalIdentifier: identifierFor(config, 'ext-response-comparison'),\n name: 'ext-response-comparison',\n trigger: { type: 'uiInvoke', minRole: 'VIEWER' },\n input: [\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_LAST_MESSAGE_GENERATED_UID,\n name: 'last_message_generated',\n type: FieldType.TEXT,\n label: 'Last message generated',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_MESSAGE_ACTUAL_SENT_UID,\n name: 'message_actual_sent',\n type: FieldType.TEXT,\n label: 'Message actually sent',\n isNullable: false,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_TICKET_ID_UID,\n name: 'ticket_id',\n type: FieldType.TEXT,\n label: 'Ticket id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_TICKET_URL_UID,\n name: 'ticket_url',\n type: FieldType.TEXT,\n label: 'Ticket URL',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_MODEL_CONFIG_ID_UID,\n name: 'model_config_id',\n type: FieldType.TEXT,\n label: 'Model config id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_TRACE_ID_UID,\n name: 'langfuse_trace_id',\n type: FieldType.TEXT,\n label: 'Langfuse trace id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_LANGFUSE_OBSERVATION_ID_UID,\n name: 'langfuse_observation_id',\n type: FieldType.TEXT,\n label: 'Langfuse observation id',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_PROMPT_NAME_UID,\n name: 'prompt_name',\n type: FieldType.TEXT,\n label: 'Prompt name',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_PROMPT_VERSION_UID,\n name: 'prompt_version',\n type: FieldType.NUMBER,\n label: 'Prompt version',\n isNullable: true,\n defaultValue: null,\n },\n {\n universalIdentifier: EXT_RESPONSE_COMPARISON_INPUT_CONVERSATION_MESSAGES_UID,\n name: 'conversation_messages',\n type: FieldType.JSON,\n label: 'Conversation messages',\n description: '[{role, content}]',\n isNullable: true,\n defaultValue: null,\n },\n ],\n };\n}\n\nexport function createExtResponseComparisonHandler(): AppHandler {\n return (ctx, input) => extResponseComparisonHandler(ctx as SupportKitHandlerContext, (input as ExtResponseComparisonInput) ?? {});\n}\n\nexport async function extResponseComparisonHandler(\n ctx: SupportKitHandlerContext,\n input: ExtResponseComparisonInput,\n): Promise<ExtResponseComparisonResult | ProbeClaim | null> {\n const envelope = readSupportExtensionEnvelope(ctx);\n if (envelope.phase === 'probe') return probeResponseComparisonOwnership(ctx, input);\n return executeResponseComparison(ctx, input);\n}\n\nasync function probeResponseComparisonOwnership(\n ctx: SupportKitHandlerContext,\n input: ExtResponseComparisonInput,\n): Promise<ProbeClaim | null> {\n const modelConfigId = nonEmptyString(input.model_config_id);\n if (modelConfigId) {\n const claim = await ownsAgent(ctx, modelConfigId);\n if (claim) return claim;\n // M3: a dangling model_config_id (the agent was archived/deleted since\n // the draft that produced this correction) used to disclaim outright —\n // 204, the correction silently lost, with nothing to distinguish \"no\n // owner\" from \"we lost it\". Fall through to ticket ownership instead of\n // returning null immediately: the ticket itself still routes to the app\n // that triaged it, which is the better answer than losing the human\n // correction the whole cs-replies-corrections loop is built on.\n }\n\n const ticketId = nonEmptyString(input.ticket_id);\n if (!ticketId) return null;\n const page = await ctx.api.list('triage-decision', { filter: { ticketId }, limit: 1 });\n return page.items.length > 0 ? { claimed: true } : null;\n}\n\nasync function executeResponseComparison(\n ctx: SupportKitHandlerContext,\n input: ExtResponseComparisonInput,\n): Promise<ExtResponseComparisonResult | null> {\n if (!input.message_actual_sent) {\n throw new ctx.NonRetriableError('message_actual_sent is required');\n }\n if (!input.last_message_generated) {\n // M2: falsy, not `== null` — legacy tests `if (!last_message_generated)\n // return 204`, so an empty string must 204 too. `== null` let `''`\n // through and wrote a response-comparison with generatedText: '', a\n // trivially 100%-insert diff, and (with a trace id) a dataset item +\n // CORRECTION score teaching cs-replies-corrections that the model wrote\n // nothing and the human wrote the whole reply — dataset poisoning.\n return null; // -> 204, no write (own guard — see this module's doc)\n }\n\n const generatedText = input.last_message_generated;\n const sentText = input.message_actual_sent;\n const ticketId = nonEmptyString(input.ticket_id);\n // See this module's doc — the record's `ticketUrl` is `isNullable: false`.\n const ticketUrl = typeof input.ticket_url === 'string' ? input.ticket_url : '';\n const modelConfigId = nonEmptyString(input.model_config_id);\n const traceId = nonEmptyString(input.langfuse_trace_id);\n const observationId = nonEmptyString(input.langfuse_observation_id) ?? undefined;\n const promptName = typeof input.prompt_name === 'string' ? input.prompt_name : null;\n const promptVersion = typeof input.prompt_version === 'number' ? input.prompt_version : null;\n const conversationMessages = Array.isArray(input.conversation_messages) ? input.conversation_messages : [];\n\n const created = await ctx.api.create('response-comparison', {\n generatedText,\n sentText,\n capturedAt: new Date().toISOString(),\n ticketId,\n ticketUrl,\n agentId: modelConfigId,\n langfuseTraceId: traceId,\n langfuseObservationId: observationId ?? null,\n promptName,\n promptVersion,\n conversationMessages,\n diff: computeWordDiff(generatedText, sentText),\n });\n\n await captureCorrectionToLangfuse(ctx, {\n generatedText,\n sentText,\n ticketId,\n traceId,\n observationId,\n promptName,\n promptVersion,\n conversationMessages,\n tracedInput: Array.isArray(input.traced_input) ? input.traced_input : null,\n });\n\n return { ok: true, id: created.id };\n}\n\ninterface CorrectionCaptureParams {\n generatedText: string;\n sentText: string;\n ticketId: string | null;\n traceId: string | null;\n observationId: string | undefined;\n promptName: string | null;\n promptVersion: number | null;\n conversationMessages: unknown[];\n tracedInput: unknown[] | null;\n}\n\nasync function captureCorrectionToLangfuse(ctx: SupportKitHandlerContext, params: CorrectionCaptureParams): Promise<void> {\n const textChanged = params.sentText !== params.generatedText;\n if (!textChanged || !params.traceId) return;\n\n const itemId = params.observationId ? `${params.traceId}:${params.observationId}` : params.traceId;\n const expectedOutput = { role: 'assistant', content: params.sentText, refusal: null, annotations: [] as unknown[] };\n const datasetInput = params.tracedInput && params.tracedInput.length > 0 ? params.tracedInput : params.conversationMessages;\n\n try {\n await ctx.api.langfuse.datasets.createItem({\n dataset: CORRECTIONS_DATASET,\n id: itemId,\n input: datasetInput,\n expectedOutput,\n sourceTraceId: params.traceId,\n sourceObservationId: params.observationId,\n metadata: {\n prompt_name: params.promptName,\n prompt_version: params.promptVersion,\n ticket_id: params.ticketId,\n edited: true,\n },\n });\n } catch (err) {\n ctx.logger.warn(`ext-response-comparison: dataset item write failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n\n try {\n // M5: deliberately trace-level — NO `observationId`. Legacy's own\n // `createCorrectionScore` call passed none either (its doc labels this\n // \"Native trace-level CORRECTION score — renders as the 'Corrected\n // Output' on the trace itself\"); passing one here would move the panel\n // off the trace page. `CreateLangfuseScoreInput` has no generic\n // `metadata` field on the platform surface (only `comment`), so\n // prompt_name/prompt_version — the axis S7's quality loop reads\n // corrections along — fold into `comment` instead, the same way\n // `ext-evaluation.ts` folds its own score metadata.\n await ctx.api.langfuse.scores.create({\n id: itemId,\n traceId: params.traceId,\n name: 'output',\n value: JSON.stringify(expectedOutput),\n dataType: 'CORRECTION',\n comment: `Human correction from ticket ${params.ticketId ?? 'unknown'} (prompt: ${params.promptName ?? 'unknown'}, version: ${params.promptVersion ?? 'unknown'})`,\n });\n } catch (err) {\n ctx.logger.warn(`ext-response-comparison: correction score write failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nfunction nonEmptyString(value: unknown): string | null {\n return typeof value === 'string' && value.length > 0 ? value : null;\n}\n","/**\n * Page/settingsPage manifest fragments (spec §3.8) — the T26 counterpart of\n * `functions/config.ts`'s `FUNCTION_IDENTIFIER_KEYS`/`identifierFor`.\n *\n * Page `universalIdentifier`s come from `config.identifiers`, exactly like\n * function uids — NOT from the T25 `deriveUid`/`scopeRecordToApp` mechanism\n * `records/` uses. That mechanism exists because a RECORD's sub-ids (fields,\n * indexes) are numerous and entirely kit-owned, with no natural per-app\n * literal for a consuming app to author; deriving them from `(slug, a kit\n * constant)` is the only way to keep them both stable and disjoint across\n * apps. A page has exactly one id, no sub-ids, and `FUNCTION_IDENTIFIER_KEYS`\n * already established the pattern for exactly this shape: the CONSUMING\n * APP's own config supplies a literal, platform-wide-unique uuid per key —\n * the same discipline `docs/app-template/src/universal-identifiers.ts`\n * documents for every other manifest id an app authors directly.\n *\n * CORRECTION (T26 rework — the prior pass's own justification here was\n * false, and is fixed rather than just removed so the actual mechanism is\n * on record): `AppEntityType.PAGE` rows do land in the same `AppEntity`\n * table as records' OBJECT/FIELD/INDEX rows\n * (`apps/api/src/platform-data/app-entities.ts`), and\n * `AppEntity.universalIdentifier` IS `@unique` platform-wide\n * (`schema.prisma`) — but PAGE, like FUNCTION/VIEW/INDEX/NAV_ITEM, is\n * NAMESPACED before that constraint ever sees it: `buildEntities` computes\n * `deterministicUid('PAGE:<manifest uid>:<page uid>')`\n * (`app-entities.ts:172-175`), not the raw `page.universalIdentifier`\n * literal. Two apps publishing the IDENTICAL local page uid produce two\n * DIFFERENT `deterministicUid` hashes (their own manifest uids differ), so\n * they do not collide — a page id does NOT \"collide across apps exactly\n * like a record id would\". Only OBJECT (`app-entities.ts:84`) and FIELD\n * (`:101`, and `:205` for extension fields) write the raw literal straight\n * through — which is precisely why T25's `scopeRecordToApp` existed for\n * records and is NOT needed here.\n *\n * The mechanism below (config-supplied literal, mirroring\n * `FUNCTION_IDENTIFIER_KEYS`) is still the right choice — consistency with\n * the pattern T22/T23 already established for exactly this shape (one id,\n * no sub-ids, no natural per-app literal to derive from) — it is simply not\n * required by a collision risk that does not exist for this entity type.\n */\n\n/**\n * Stable keys `pageIdentifierFor` looks up `config.identifiers` by — the\n * four phase-2 pages (T26), the settingsPage (§3.8's SettingsPage row),\n * T27 part A's three phase-3 pages (`DashboardPage`, `TicketsPage`,\n * `CorrectionsPage`) and part B's `GraphCanvasPage`/`SharedPromptsPage`/\n * `TestPage` — §3.8's full page list, now complete.\n */\nexport const PAGE_IDENTIFIER_KEYS = [\n 'pipeline-page',\n 'agents-page',\n 'categories-page',\n 'escalations-page',\n 'settings-page',\n 'dashboard-page',\n 'tickets-page',\n 'corrections-page',\n 'graph-canvas-page',\n 'shared-prompts-page',\n 'test-page',\n] as const;\n\nexport type PageIdentifierKey = (typeof PAGE_IDENTIFIER_KEYS)[number];\n\nexport interface SupportKitPageConfig {\n /** Same map `functions/config.ts`'s `identifierFor` reads — one entry per `PAGE_IDENTIFIER_KEYS`, alongside the function ones. */\n identifiers: Record<string, string>;\n}\n\n/** Looks up `config.identifiers[key]`, throwing loudly on a missing entry — mirrors `functions/config.ts`'s `identifierFor` exactly. */\nexport function pageIdentifierFor(config: SupportKitPageConfig, key: PageIdentifierKey): string {\n const id = config.identifiers[key];\n if (!id) {\n throw new Error(\n `SupportPipelineConfig.identifiers is missing a universalIdentifier for \"${key}\" — every support-kit page needs a stable id.`,\n );\n }\n return id;\n}\n","/**\n * `buildSupportPipeline` (spec §3.2) — the single assembly point that turns\n * a consuming app's own config into every manifest fragment + handler this\n * kit provides. An audience app spreads the result into `defineApp({\n * manifest: {...baseManifest, ...kit-fragments}, handlers: kit.handlers })`.\n *\n * T25 is assembly, not invention: every fragment below is built from pieces\n * T20-T24 already shipped (`records/`, `functions/`, `settings/`,\n * `prompts/slots`) — this module's own job is wiring `config` through to\n * each of them consistently, plus `mergeRole`, the one piece with no prior\n * owner.\n */\nimport type {\n AppHandler,\n AppRole,\n AppSettings,\n FunctionDef,\n NavItem,\n PageDef,\n PromptDef,\n SettingsPage,\n} from '@apotech-os/app-kit';\nimport {\n FUNCTION_IDENTIFIER_KEYS,\n type FunctionIdentifierKey,\n type SupportKitFunctionConfig,\n} from './functions/config';\nimport {\n buildTriageTickFunctionDef,\n createTriageTickHandler,\n buildProcessResponseFunctionDef,\n createProcessResponseHandler,\n buildSweepFunctionDef,\n createSweepHandler,\n buildHandleApprovalFunctionDef,\n createHandleApprovalHandler,\n buildRunTriageNowFunctionDef,\n createRunTriageNowHandler,\n buildRunTriageBatchFunctionDef,\n createRunTriageBatchHandler,\n TRIAGE_RUN_REQUESTED_EVENT,\n buildPreviewTriageFunctionDef,\n createPreviewTriageHandler,\n buildGraphDryRunFunctionDef,\n createGraphDryRunHandler,\n buildTestAgentsFunctionDef,\n createTestAgentsHandler,\n buildSuggestPromptFunctionDef,\n createSuggestPromptHandler,\n buildRunDiffAnalysisFunctionDef,\n createRunDiffAnalysisHandler,\n buildListGorgiasViewsFunctionDef,\n createListGorgiasViewsHandler,\n buildCreateAgentFunctionDef,\n createCreateAgentHandler,\n buildSetDefaultAgentFunctionDef,\n createSetDefaultAgentHandler,\n buildCreateSharedPromptVersionFunctionDef,\n createCreateSharedPromptVersionHandler,\n buildSyncAgentPromptSnapshotFunctionDef,\n createSyncAgentPromptSnapshotHandler,\n buildExtModelsFunctionDef,\n createExtModelsHandler,\n buildExtCategoriesFunctionDef,\n createExtCategoriesHandler,\n buildExtChatFunctionDef,\n createExtChatHandler,\n buildExtFastResponseCheckFunctionDef,\n createExtFastResponseCheckHandler,\n buildExtEvaluationFunctionDef,\n createExtEvaluationHandler,\n buildExtResponseComparisonFunctionDef,\n createExtResponseComparisonHandler,\n} from './functions';\nimport { buildSupportKitRecords, targetRefFor, type RecordDef } from './records';\nimport { SUPPORT_KIT_SETTINGS_FIELDS } from './settings';\nimport type { PromptNameConfig } from './prompts/slots';\nimport { pageIdentifierFor } from './pages/manifest';\n\nexport interface SupportPipelineConfig extends SupportKitFunctionConfig {\n /** Human label shown in the platform's app picker, e.g. 'Expérience client'. */\n displayName: string;\n /**\n * §3.2's own sketch names this field, but has no consumer yet (L1, T25\n * review): `navigation` (this fragment's own `NavItem[]`) is always `[]`\n * today — T26/T27 own the kit's pages/nav (§3.8's phase-2/phase-3), and\n * with it, presumably, grouping those nav items under this section. A\n * caller may set it now for forward compatibility; nothing reads it yet.\n */\n navigationSection?: string;\n /**\n * §3.2's full `config.defaults` shape (`{channel?, prompts?}`), widening\n * `SupportKitFunctionConfig`'s own `defaults` (`{prompts?}` only) with\n * `channel` — `prompts`' shape is NOT restated here (L2, T25 review): it\n * is `PromptNameConfig['defaults']`'s own type, `prompts/slots.ts`'s\n * `PromptFallbackSlot`, referenced rather than copied, so this\n * declaration cannot silently narrow back to the wrong key set if that\n * one changes.\n *\n * `defaults.prompts` is wired to its real consumers: `buildPromptsTable`\n * (triage/escalate/evaluate/revise's `PromptRef.fallback`) and\n * `suggest-prompt`/`run-diff-analysis`'s own meta-prompt fallback.\n *\n * `defaults.channel` (DECISION 3, T25 — see the migration progress\n * journal's T25 entry) is accepted here for fidelity to the spec's own\n * sketch but has NO real consumer today: `settings/fields.ts` declares no\n * field named `channel`, and the nearest candidate, `whatsappMode`\n * (`escalate_only|draft_only|auto_reply`), has an incompatible value\n * domain from `'email'|'whatsapp'|'both'` — a mechanical seed would\n * corrupt it, not configure it. Wiring this for real means either adding\n * a settings field (§3.6 is T20-frozen; out of scope here) or picking an\n * arbitrary channel→whatsappMode mapping, both judgment calls beyond\n * assembly. Flagged for the spec owner, not routed around silently.\n */\n defaults?: PromptNameConfig['defaults'] & {\n channel?: 'email' | 'whatsapp' | 'both';\n };\n}\n\n/** `provider`/`action` pair — matches `AppManifest.actions[]`/`AppRole.actions[]`'s own shape (app-kit has no exported named type for it). */\nexport interface ActionRef {\n provider: string;\n action: string;\n}\n\nexport interface SupportPipelineFragments {\n records: RecordDef[];\n functions: FunctionDef[];\n /**\n * The app custom events the kit's own functions emit — spread into\n * `manifest.emits`. NOT optional in practice (B5): `run-triage-batch`\n * declares `trigger: {type:'event', name: TRIAGE_RUN_REQUESTED_EVENT}`,\n * and the platform refuses to sync a manifest whose event trigger names\n * an event the app does not declare\n * (`app-manifest-constraints.ts`'s `validateAppFunctionConstraints`), so\n * a consuming app that spreads `functions` must spread this too.\n */\n emits: string[];\n settings: AppSettings;\n prompts: PromptDef[];\n pages: PageDef[];\n navigation: NavItem[];\n /**\n * §3.8's SettingsPage row — the manifest's `settingsPage`, not a\n * `pages[]` entry (`AppManifestSchema`'s own refinements require it:\n * distinct `entry` from every page, no collision with the bundle the CLI\n * emits for a page `path`, distinct `universalIdentifier`). Not in §3.2's\n * own fragment sketch (T25's `pages`/`navigation` sketch predates T26) —\n * added here because a consuming app has no other way to spread it into\n * its manifest.\n */\n settingsPage: SettingsPage;\n actions: ActionRef[];\n /**\n * `'NO_ACCESS'` (H2, T25 review): with no `defaultRole`, the platform\n * grants every platform member `VIEWER` on install\n * (`app-lifecycle.service.ts:1211`) — a `pro-sante` clinician would read\n * `experience-client`'s `generated-response` rows (customer email bodies,\n * drafted replies) by default. Exposed as a named fragment, not baked\n * silently into a spread, so a consuming app can still override it\n * explicitly (`defaultRole: kit.defaultRole` in the common case, or a\n * different value if that app has a real reason to).\n */\n defaultRole: 'NO_ACCESS';\n handlers: Record<string, AppHandler>;\n mergeRole(role: AppRole): AppRole;\n /**\n * The `manifest.actions` counterpart of `mergeRole` (B2, T25 review):\n * `role.actions` must always be a subset of `manifest.actions`\n * (`validateActionCoupling`, enforced on every publish/sync) — before\n * this existed, a caller had to remember to fold the kit's own actions\n * into their manifest's `actions: [...]` by hand, on top of merging their\n * role separately, and a caller who forgot got a 422 at publish. Adds the\n * same kit action set `mergeRole` adds to `role.actions`, so\n * `actions: kit.mergeActions(ownActions)` paired with\n * `role: kit.mergeRole(ownRole)` keeps the two in lockstep by\n * construction.\n */\n mergeActions(actions: ActionRef[]): ActionRef[];\n}\n\n/**\n * The nine Gorgias connector actions the kit's adapters/functions actually\n * call — verified by grepping `ctx.api.integrations.run('gorgias', …)`\n * across `src/` (see `pipeline.spec.ts`'s own self-checking test, which\n * re-derives this set from the source tree so it cannot silently drift as\n * new call sites are added).\n */\nexport const SUPPORT_KIT_GORGIAS_ACTIONS = [\n 'applyTags',\n 'buildTicketContext',\n 'fetchTicketsFromView',\n 'getRawTicket',\n 'getTicketWithContext',\n 'listViews',\n 'postWhatsappNote',\n 'renameTicket',\n 'replyEmail',\n] as const;\n\n/** §3.2: `mergeRole` adds `capabilities: ['runs','inbox','approvals','prompts','langfuse']`. `'langfuse'` is load-bearing — `adapters/api.ts`'s `ctx.api.langfuse` 403s without it (T24). */\nexport const SUPPORT_KIT_CAPABILITIES = ['runs', 'inbox', 'approvals', 'prompts', 'langfuse'] as const;\n\n/**\n * The kit's whole action surface — `SUPPORT_KIT_GORGIAS_ACTIONS` plus\n * `llm.complete` — as `ActionRef`s. One derivation, reused by\n * `buildSupportPipeline`'s own `actions` fragment, `mergeRole`, and\n * `mergeActions` (M5, T25 review): before this constant existed, the same\n * `[...SUPPORT_KIT_GORGIAS_ACTIONS.map(...), {provider:'llm',action:'complete'}]`\n * expression was written out twice, free to drift apart silently.\n */\nexport const SUPPORT_KIT_ACTIONS: ActionRef[] = [\n ...SUPPORT_KIT_GORGIAS_ACTIONS.map((action) => ({ provider: 'gorgias', action })),\n { provider: 'llm', action: 'complete' },\n];\n\n/**\n * §3.2's `emits` fragment — one entry, the manual-triage hand-off\n * (`functions/run-triage-now.ts`'s own doc explains why that hand-off\n * exists at all).\n */\nexport const SUPPORT_KIT_EMITS: string[] = [TRIAGE_RUN_REQUESTED_EVENT];\n\nconst FUNCTION_ASSEMBLY: ReadonlyArray<{\n key: FunctionIdentifierKey;\n build: (config: SupportKitFunctionConfig) => FunctionDef;\n createHandler: (config: SupportKitFunctionConfig) => AppHandler;\n}> = [\n { key: 'triage-tick', build: buildTriageTickFunctionDef, createHandler: createTriageTickHandler },\n { key: 'process-response', build: buildProcessResponseFunctionDef, createHandler: createProcessResponseHandler },\n { key: 'sweep', build: buildSweepFunctionDef, createHandler: () => createSweepHandler() },\n { key: 'handle-approval', build: buildHandleApprovalFunctionDef, createHandler: createHandleApprovalHandler },\n { key: 'run-triage-now', build: buildRunTriageNowFunctionDef, createHandler: createRunTriageNowHandler },\n { key: 'run-triage-batch', build: buildRunTriageBatchFunctionDef, createHandler: createRunTriageBatchHandler },\n { key: 'preview-triage', build: buildPreviewTriageFunctionDef, createHandler: createPreviewTriageHandler },\n { key: 'graph-dry-run', build: buildGraphDryRunFunctionDef, createHandler: createGraphDryRunHandler },\n { key: 'test-agents', build: buildTestAgentsFunctionDef, createHandler: createTestAgentsHandler },\n { key: 'suggest-prompt', build: buildSuggestPromptFunctionDef, createHandler: createSuggestPromptHandler },\n { key: 'run-diff-analysis', build: buildRunDiffAnalysisFunctionDef, createHandler: createRunDiffAnalysisHandler },\n { key: 'list-gorgias-views', build: buildListGorgiasViewsFunctionDef, createHandler: createListGorgiasViewsHandler },\n { key: 'create-agent', build: buildCreateAgentFunctionDef, createHandler: () => createCreateAgentHandler() },\n {\n key: 'set-default-agent',\n build: buildSetDefaultAgentFunctionDef,\n createHandler: () => createSetDefaultAgentHandler(),\n },\n {\n key: 'create-shared-prompt-version',\n build: buildCreateSharedPromptVersionFunctionDef,\n createHandler: () => createCreateSharedPromptVersionHandler(),\n },\n {\n key: 'sync-agent-prompt-snapshot',\n build: buildSyncAgentPromptSnapshotFunctionDef,\n createHandler: () => createSyncAgentPromptSnapshotHandler(),\n },\n { key: 'ext-models', build: buildExtModelsFunctionDef, createHandler: () => createExtModelsHandler() },\n { key: 'ext-categories', build: buildExtCategoriesFunctionDef, createHandler: () => createExtCategoriesHandler() },\n { key: 'ext-chat', build: buildExtChatFunctionDef, createHandler: () => createExtChatHandler() },\n {\n key: 'ext-fast-response-check',\n build: buildExtFastResponseCheckFunctionDef,\n createHandler: () => createExtFastResponseCheckHandler(),\n },\n { key: 'ext-evaluation', build: buildExtEvaluationFunctionDef, createHandler: () => createExtEvaluationHandler() },\n {\n key: 'ext-response-comparison',\n build: buildExtResponseComparisonFunctionDef,\n createHandler: () => createExtResponseComparisonHandler(),\n },\n];\n\n// FUNCTION_ASSEMBLY must cover exactly FUNCTION_IDENTIFIER_KEYS — asserted\n// in pipeline.spec.ts, not re-asserted here (a compile-time array literal\n// has no length check to attach).\n\n/**\n * §3.7's `role.prompts` allowlist: the WHOLE Langfuse project, deliberately.\n *\n * Two narrowings preceded this one, and both failed the same way. First the\n * five derived slot names (`<prefix>triage`, …) — which stopped making sense\n * the day each graph step's prompt became an operator's choice\n * (`nodes.<step>.prompt`, picked on the SettingsPage from the catalogue THIS\n * allowlist filters): a choice restricted to the names that used to be\n * hardcoded is not a choice. Then `${promptPrefix}*` — bounded for a\n * prefixed audience, but `experience-client` passes `promptPrefix: ''`\n * (D-LF: one shared project, bare legacy names), so its glob was already the\n * whole project, while a `pro-sante/` install could not reach a single\n * prompt outside its own prefix.\n *\n * OWNER DECISION (09/09/2026): no limitation. An operator configuring a\n * pipeline must see every prompt of the project in the picker, whichever\n * audience the app serves. A prefix is a naming convention here, not a\n * tenancy boundary — under D-LF there is no per-app Langfuse namespace to\n * enforce one against, and `agent/*` had been unbounded from the start\n * anyway.\n *\n * WHAT THIS COSTS, stated rather than buried: `role.prompts` gates WRITES\n * too (`app-prompts.controller.ts`'s `requirePromptAllowed` on\n * `createVersion`/`promote`/`deleteVersion`). One audience's app token can\n * therefore read AND version-write another audience's prompts. That was\n * already true of every `agent/<id>` prompt (T25 review H1, accepted); it is\n * now true of all of them. The mitigation NOT taken remains a real per-app\n * Langfuse namespace, which contradicts D-LF and is a migration, not a flag.\n */\nfunction buildPromptsAllowlist(): string[] {\n return ['*'];\n}\n\nfunction dedupe<T>(items: readonly T[], keyOf: (item: T) => string): T[] {\n const seen = new Map<string, T>();\n for (const item of items) seen.set(keyOf(item), item);\n return [...seen.values()];\n}\n\nfunction mergeActionRefs(actions: readonly ActionRef[]): ActionRef[] {\n return dedupe([...actions, ...SUPPORT_KIT_ACTIONS], (a) => `${a.provider}::${a.action}`);\n}\n\n/**\n * `category`/`category-group` are the categorisation referential: every call\n * site in `src/` only ever `list`s or `get`s them (verified by grep, M2 in\n * the T25 review) — never `create`/`update`/`upsert`/`delete`. Granting\n * `writes` on them anyway lets the app's own token DELETE them, taking\n * triage offline for the whole audience.\n *\n * `agent` was in this list too until the T26 rework: `create-agent` and\n * `set-default-agent` (BLOCKER 3, BLOCKER 4) now `create`/`update` it from\n * inside a handler, via this same `ctx.api` — AgentsPage cannot assign a new\n * agent's `promptName` or maintain the \"at most one default agent\" invariant\n * from raw, unauthenticated-for-writes record PATCHes alone. `role.writes`\n * has no finer grain than \"create/update/delete\" as one bucket\n * (`SupportKitApi` itself exposes no `delete` method, but a raw app token\n * still could reach the generic records DELETE route with this grant) — this\n * IS a widened blast radius versus the prior read-only grant, accepted\n * because the alternative is an agent CRUD screen that cannot create or\n * promote an agent at all. Flagged for the spec owner, not routed around\n * silently.\n */\nconst KIT_READ_ONLY_OBJECT_KEYS = ['category', 'category-group'];\n\n/**\n * `evaluation`/`diff-analysis` are written (`create`/`upsert`) but never\n * `list`ed or `get`-ed anywhere in `src/` (M2) — the mirror over-grant of\n * `KIT_READ_ONLY_OBJECT_KEYS` above.\n */\nconst KIT_WRITE_ONLY_OBJECT_KEYS = ['evaluation', 'diff-analysis'];\n\nfunction buildMergeRole(config: SupportPipelineConfig): (role: AppRole) => AppRole {\n const kitRecords = buildSupportKitRecords(config.slug);\n const refsExcluding = (excludedObjectKeys: readonly string[]): string[] =>\n kitRecords\n .filter((record) => !excludedObjectKeys.includes(record.objectKey))\n .map((record) => targetRefFor(config.slug, record.objectKey));\n const kitReadRefs = refsExcluding(KIT_WRITE_ONLY_OBJECT_KEYS);\n const kitWriteRefs = refsExcluding(KIT_READ_ONLY_OBJECT_KEYS);\n const kitPrompts = buildPromptsAllowlist();\n\n return (role: AppRole): AppRole => ({\n ...role,\n reads: dedupe([...role.reads, ...kitReadRefs], (ref) => ref),\n writes: dedupe([...role.writes, ...kitWriteRefs], (ref) => ref),\n actions: mergeActionRefs(role.actions),\n capabilities: dedupe([...(role.capabilities ?? []), ...SUPPORT_KIT_CAPABILITIES], (c) => c),\n prompts: dedupe([...(role.prompts ?? []), ...kitPrompts], (p) => p),\n });\n}\n\n/**\n * §3.8's phase-2 pages (T26) plus T27 part A's three phase-3 pages\n * (`DashboardPage`, `TicketsPage`, `CorrectionsPage`) plus part B's\n * `GraphCanvasPage`/`SharedPromptsPage`/`TestPage` — §3.8's full page list,\n * now complete. `path` doubles as the CLI's bundle-derivation input\n * (`dist/ui/<path>.js`, `UI_ENTRY_REGEX`) and the component name exported\n * from `src/ui/index.ts` — kept in that 1:1 correspondence by `T26`'s own\n * build-then-verify step, not enforced by a type here (`PageDefSchema`\n * only constrains shape).\n */\nconst KIT_PAGES = [\n { key: 'dashboard-page', path: 'dashboard', title: 'Tableau de bord', icon: 'layout-dashboard' },\n { key: 'tickets-page', path: 'tickets', title: 'Demandes', icon: 'ticket' },\n { key: 'pipeline-page', path: 'pipeline', title: 'Pipeline', icon: 'inbox' },\n { key: 'agents-page', path: 'agents', title: 'Agents', icon: 'bot' },\n { key: 'categories-page', path: 'categories', title: 'Catégories', icon: 'tags' },\n { key: 'escalations-page', path: 'escalations', title: 'Escalades', icon: 'alert-triangle' },\n { key: 'corrections-page', path: 'corrections', title: 'Corrections', icon: 'git-compare' },\n { key: 'graph-canvas-page', path: 'graph-canvas', title: 'Graphe', icon: 'workflow' },\n { key: 'shared-prompts-page', path: 'shared-prompts', title: 'Prompts partagés', icon: 'library' },\n { key: 'test-page', path: 'test', title: 'Banc de test', icon: 'flask-conical' },\n] as const;\n\nfunction buildPages(config: SupportPipelineConfig): PageDef[] {\n return KIT_PAGES.map(({ key, path, title, icon }) => ({\n universalIdentifier: pageIdentifierFor(config, key),\n path,\n title,\n icon,\n entry: `dist/ui/${path}.js`,\n }));\n}\n\nfunction buildNavigation(config: SupportPipelineConfig): NavItem[] {\n return KIT_PAGES.map(({ path, title, icon }) => ({\n label: title,\n path,\n icon,\n ...(config.navigationSection !== undefined ? { section: config.navigationSection } : {}),\n }));\n}\n\nfunction buildSettingsPage(config: SupportPipelineConfig): SettingsPage {\n return {\n universalIdentifier: pageIdentifierFor(config, 'settings-page'),\n entry: 'dist/ui/settings.js',\n title: 'Paramètres',\n };\n}\n\nexport function buildSupportPipeline(config: SupportPipelineConfig): SupportPipelineFragments {\n const functions = FUNCTION_ASSEMBLY.map(({ build }) => build(config));\n const handlers: Record<string, AppHandler> = {};\n for (const { key, createHandler } of FUNCTION_ASSEMBLY) handlers[key] = createHandler(config);\n\n return {\n records: buildSupportKitRecords(config.slug),\n functions,\n settings: { fields: SUPPORT_KIT_SETTINGS_FIELDS },\n // DECISION 1 (see docs/plans/2026-09-02-gorgias-migration-progress.md's\n // T25 entry): always empty. §3.2's own fragment sketch types this\n // `PromptDef[] // seed Langfuse (§3.7)`, but §3.7 line 322 and D-LF both\n // say manifest.prompts[] is NOT used by the kit — it would seed an\n // `apps/<slug>/…` namespace that contradicts \"same Langfuse project,\n // bare legacy names, zero write at migration time\". A new audience's\n // prompts are seeded at first run via S3 createVersion (a RUNTIME\n // concern), not declared in the manifest.\n prompts: [],\n // T26 fills the four phase-2 pages + the settingsPage (§3.8); T27 part A\n // adds DashboardPage/TicketsPage/CorrectionsPage. Part B's remaining\n // phase-3 pages (GraphCanvasPage, SharedPromptsPage, TestPage) are still ahead.\n pages: buildPages(config),\n navigation: buildNavigation(config),\n settingsPage: buildSettingsPage(config),\n actions: SUPPORT_KIT_ACTIONS,\n emits: SUPPORT_KIT_EMITS,\n defaultRole: 'NO_ACCESS',\n handlers,\n mergeRole: buildMergeRole(config),\n mergeActions: mergeActionRefs,\n };\n}\n"]}