@apotech-os/support-kit 2.6.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/README.md +67 -0
- package/dist/chunk-KDOL3MLH.js +1766 -0
- package/dist/chunk-KDOL3MLH.js.map +1 -0
- package/dist/index.cjs +5744 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +2010 -0
- package/dist/index.d.ts +2010 -0
- package/dist/index.js +3965 -0
- package/dist/index.js.map +1 -0
- package/dist/ui/index.cjs +4946 -0
- package/dist/ui/index.cjs.map +1 -0
- package/dist/ui/index.d.cts +25 -0
- package/dist/ui/index.d.ts +25 -0
- package/dist/ui/index.js +4464 -0
- package/dist/ui/index.js.map +1 -0
- package/package.json +68 -0
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,2010 @@
|
|
|
1
|
+
import { ObjectDef, SettingsField, FunctionDef, AppSettings, PromptDef, PageDef, NavItem, SettingsPage, AppHandler, AppRole } from '@apotech-os/app-kit';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The channels a `ConversationPort`/`ReplyPort` pair can adapt today or in
|
|
5
|
+
* the roadmap (P5 folds into "a new adapter set + a profile" — the union
|
|
6
|
+
* grows there, not by generalising this type away).
|
|
7
|
+
*/
|
|
8
|
+
type ChannelKind = 'gorgias' | 'whatsapp' | 'instagram';
|
|
9
|
+
|
|
10
|
+
interface ConversationRef {
|
|
11
|
+
/** Opaque channel-side identifier (Gorgias ticket id, WhatsApp thread id…). */
|
|
12
|
+
id: string;
|
|
13
|
+
channel: ChannelKind;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* A turn in the conversation, user or assistant only. The synthetic
|
|
17
|
+
* "Information Client" prefix a channel adapter prepends to give the model
|
|
18
|
+
* order/customer context is a channel-rendering detail with its own
|
|
19
|
+
* `role: 'system'` marker there — it never crosses into the domain. That
|
|
20
|
+
* context lives instead in `CustomerInfo.orderContext` below, rendered once
|
|
21
|
+
* and passed explicitly.
|
|
22
|
+
*/
|
|
23
|
+
interface Message {
|
|
24
|
+
role: 'user' | 'assistant';
|
|
25
|
+
content: string;
|
|
26
|
+
}
|
|
27
|
+
interface CustomerInfo {
|
|
28
|
+
name: string | null;
|
|
29
|
+
email: string | null;
|
|
30
|
+
/** Rendered order/account context (may be absent — not every ticket has one). */
|
|
31
|
+
orderContext: string | null;
|
|
32
|
+
}
|
|
33
|
+
interface Conversation {
|
|
34
|
+
ref: ConversationRef;
|
|
35
|
+
subject: string | null;
|
|
36
|
+
messages: Message[];
|
|
37
|
+
customer: CustomerInfo;
|
|
38
|
+
isClosed: boolean;
|
|
39
|
+
lastMessageAt: Date | null;
|
|
40
|
+
/**
|
|
41
|
+
* Feeds the anti-divergence snapshot taken right before send (I8) and the
|
|
42
|
+
* one served by the fast-response check: a re-read whose count has moved
|
|
43
|
+
* means the conversation changed under the run and the reply must be held
|
|
44
|
+
* rather than posted.
|
|
45
|
+
*/
|
|
46
|
+
messageCount: number;
|
|
47
|
+
/**
|
|
48
|
+
* When an agent (human or bot) last answered, null if none ever did.
|
|
49
|
+
*
|
|
50
|
+
* Separate from `messageCount` on purpose: the anti-collision check has to
|
|
51
|
+
* catch a reply that landed BEFORE generation but after the job was queued
|
|
52
|
+
* (I8's window gap), and both snapshots already include it, so the counts
|
|
53
|
+
* match and divergence alone stays blind to it.
|
|
54
|
+
*/
|
|
55
|
+
lastAgentReplyAt: Date | null;
|
|
56
|
+
/**
|
|
57
|
+
* True when a CUSTOMER message carries an attachment. Agent messages and
|
|
58
|
+
* internal notes do not count — an agent attaching a document must not hold
|
|
59
|
+
* the reply. Feeds the `attachment` guardrail: a photo of a damaged
|
|
60
|
+
* product is context the model never saw, so the answer needs a human.
|
|
61
|
+
*/
|
|
62
|
+
hasCustomerAttachment: boolean;
|
|
63
|
+
/**
|
|
64
|
+
* The channel the conversation actually came in on ('email', 'whatsapp',
|
|
65
|
+
* 'chat'…), null when the payload does not say.
|
|
66
|
+
*
|
|
67
|
+
* Deliberately NOT `ref.channel`, which names the ADAPTER ('gorgias'): a
|
|
68
|
+
* Gorgias ticket can carry any of Gorgias' own channels, and the WhatsApp
|
|
69
|
+
* guardrail is defined against that one.
|
|
70
|
+
*
|
|
71
|
+
* CONTRACT (T15 review B3): `sourceChannel === 'whatsapp'` IFF
|
|
72
|
+
* `isWhatsappTicket(raw)` (`guardrails/raw-ticket.ts`) — i.e. the ticket's
|
|
73
|
+
* OWN channel is whatsapp, OR ANY of its messages came through whatsapp.
|
|
74
|
+
* It is NOT simply `ticket.channel` (a ticket can be 'email' by channel
|
|
75
|
+
* while carrying whatsapp messages). Every guardrail gated on
|
|
76
|
+
* `sourceChannel !== 'whatsapp'` (`stopOptOut`, `channelPreGates`) relies
|
|
77
|
+
* on this — an adapter that sets `sourceChannel: ticket.channel ?? null`
|
|
78
|
+
* instead silently disables `whatsapp_stop`/`not_customer_turn` for such a
|
|
79
|
+
* ticket, and a customer's STOP goes unheard.
|
|
80
|
+
*/
|
|
81
|
+
sourceChannel: string | null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Safety bound on every model-written justification field in the graph
|
|
86
|
+
* (`Classification.reasoning`, `escalate`'s own reasoning, `Verdict.reason`)
|
|
87
|
+
* — one domain rule, one constant, so `triage`/`escalate`/`evaluate` stop
|
|
88
|
+
* each declaring their own `280` under a different local name.
|
|
89
|
+
*/
|
|
90
|
+
declare const REASONING_MAX_LEN = 280;
|
|
91
|
+
interface Classification {
|
|
92
|
+
/** The `tag_name` of the profile's Category referential, never a channel tag. */
|
|
93
|
+
category: string;
|
|
94
|
+
confidence: 'high' | 'low';
|
|
95
|
+
/** Written justification, ≤ 280 chars — NOT the model's reasoning effort/trace. */
|
|
96
|
+
reasoning: string;
|
|
97
|
+
/** True when triage failed and this is the `unknown_tag` fallback decision (I1). */
|
|
98
|
+
isFallback: boolean;
|
|
99
|
+
/**
|
|
100
|
+
* True when triage judged the LAST customer message closes the thread
|
|
101
|
+
* (« merci », « ok parfait »…) — the graph then exits `no_reply_needed`
|
|
102
|
+
* before `draft` ever runs (whatsapp spec §5.2). Optional: some existing
|
|
103
|
+
* fixtures and older wire-decoded values omit it — absent means `false`.
|
|
104
|
+
*/
|
|
105
|
+
conversationOver?: boolean;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* One tool invocation made while drafting, kept for provenance display and
|
|
110
|
+
* audit — not replayed. `observation` is the tool's result as handed back
|
|
111
|
+
* to the model, already serialised to text. Field names mirror
|
|
112
|
+
* `ToolCallRequest` (`graph/ports.ts`) rather than a `tool`/`args` pair, so a
|
|
113
|
+
* record can be built directly from the request it answers.
|
|
114
|
+
*/
|
|
115
|
+
interface ToolCallRecord {
|
|
116
|
+
name: string;
|
|
117
|
+
arguments: Record<string, unknown>;
|
|
118
|
+
observation: string;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Langfuse attribution of the completion that produced the draft's text, and
|
|
122
|
+
* of the prompt version that produced its system message (I17, §3.4's
|
|
123
|
+
* `langfuseTraceId`/`langfuseObservationId`/`promptName`/`promptVersion`).
|
|
124
|
+
*
|
|
125
|
+
* Carried on the draft rather than read back off the LLM port afterwards: a
|
|
126
|
+
* run makes several completions (a tool round, then the answer, then maybe a
|
|
127
|
+
* revision) and only the one that actually wrote the served text is the one
|
|
128
|
+
* the quality loop must score. Legacy convention, kept: the LAST completion
|
|
129
|
+
* to produce text wins — a revised draft is attributed to `revise`, not to
|
|
130
|
+
* the draft it replaced.
|
|
131
|
+
*/
|
|
132
|
+
interface DraftAttribution {
|
|
133
|
+
traceId: string | null;
|
|
134
|
+
observationId: string | null;
|
|
135
|
+
promptName: string | null;
|
|
136
|
+
/** The version `PromptPort` actually served — `0` on the in-code fallback (§3.7 level 3). */
|
|
137
|
+
promptVersion: number | null;
|
|
138
|
+
}
|
|
139
|
+
interface Draft {
|
|
140
|
+
text: string;
|
|
141
|
+
sources: ToolCallRecord[];
|
|
142
|
+
/** True once `revise` has produced this text (at most one pass). */
|
|
143
|
+
revised: boolean;
|
|
144
|
+
/**
|
|
145
|
+
* Absent when the text came from something other than a traced completion
|
|
146
|
+
* (a fake gateway, tracing off, a draft rebuilt from a stored record) —
|
|
147
|
+
* never a placeholder: an id that names no real generation is worse for
|
|
148
|
+
* the quality loop than no id at all.
|
|
149
|
+
*/
|
|
150
|
+
attribution?: DraftAttribution;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
declare const EVALUATION_VERDICTS: readonly ["send", "send_and_escalate", "hold"];
|
|
154
|
+
type EvaluationVerdict = (typeof EVALUATION_VERDICTS)[number];
|
|
155
|
+
declare function isEvaluationVerdict(value: unknown): value is EvaluationVerdict;
|
|
156
|
+
/** Verdicts whose reply may go out — the follow-up one included (spec §4.3). */
|
|
157
|
+
declare function isSendableVerdict(verdict: EvaluationVerdict | null): boolean;
|
|
158
|
+
/** True when the reply is sendable but owes the customer a human follow-up. */
|
|
159
|
+
declare function requiresFollowup(verdict: EvaluationVerdict | null): boolean;
|
|
160
|
+
|
|
161
|
+
interface Verdict {
|
|
162
|
+
verdict: EvaluationVerdict | null;
|
|
163
|
+
/** [0, 1]. */
|
|
164
|
+
confidence: number | null;
|
|
165
|
+
reason: string;
|
|
166
|
+
status: 'success' | 'error';
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
type ActionDecision = 'auto' | 'needs_approval' | 'forbidden';
|
|
170
|
+
interface ProposedAction {
|
|
171
|
+
/** 'send_reply' | 'refund' | … — the write-side actions introduced in P3. */
|
|
172
|
+
kind: string;
|
|
173
|
+
args: Record<string, unknown>;
|
|
174
|
+
idempotencyKey: string;
|
|
175
|
+
/** Set by the `authorize` node, never by the model (§3). */
|
|
176
|
+
decision?: ActionDecision;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Maps to the LLM provider's native reasoning-effort parameter. An invalid
|
|
181
|
+
* (model, effort) pair is rejected at profile-load time, never silently
|
|
182
|
+
* ignored — this type only carries the vocabulary, not the validation.
|
|
183
|
+
*/
|
|
184
|
+
type ReasoningEffort = 'off' | 'low' | 'medium' | 'high';
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* The key set of the LLM nodes — exactly the steps a profile's `nodes` and
|
|
188
|
+
* `prompts` carry a config for. Not every node runs on every ticket
|
|
189
|
+
* (escalate/draft/evaluate/revise are optional), but the set of possible
|
|
190
|
+
* keys is fixed.
|
|
191
|
+
*/
|
|
192
|
+
type NodeKey = 'triage' | 'escalate' | 'draft' | 'evaluate' | 'revise';
|
|
193
|
+
/**
|
|
194
|
+
* Token usage for one completion. Reasoning tokens are tracked separately
|
|
195
|
+
* from output tokens (§6.3) so the cost of the `reasoning` profile setting
|
|
196
|
+
* stays visible and steerable, instead of being buried inside `output`.
|
|
197
|
+
*/
|
|
198
|
+
interface Usage {
|
|
199
|
+
input: number;
|
|
200
|
+
output: number;
|
|
201
|
+
reasoning: number;
|
|
202
|
+
}
|
|
203
|
+
/** Aggregated cost for a single node across a run — one entry per key it charged. */
|
|
204
|
+
interface NodeCost extends Usage {
|
|
205
|
+
usd: number;
|
|
206
|
+
/**
|
|
207
|
+
* True when `usd` is `0` because pricing had no row for the model, not
|
|
208
|
+
* because usage was genuinely free.
|
|
209
|
+
*/
|
|
210
|
+
pricingMissing: boolean;
|
|
211
|
+
}
|
|
212
|
+
/** Per-node cost breakdown for one ticket run (I15). Only ran nodes are keyed. */
|
|
213
|
+
type CostLedger = Partial<Record<NodeKey, NodeCost>>;
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Key of the single tenant that exists before any second profile is created.
|
|
217
|
+
* Named once here so every scoped collection shares one source of truth
|
|
218
|
+
* instead of repeating the literal `'customer'`.
|
|
219
|
+
*/
|
|
220
|
+
declare const DEFAULT_PROFILE_KEY = "customer";
|
|
221
|
+
/**
|
|
222
|
+
* Per-tenant WhatsApp authorisation (whatsapp spec §9.1), replacing the old
|
|
223
|
+
* `whatsappEscalateOnly` boolean:
|
|
224
|
+
* - `escalate_only` — today's behaviour (and the default/rollback state):
|
|
225
|
+
* the `whatsapp` guardrail holds every WhatsApp ticket for a human.
|
|
226
|
+
* - `draft_only` — the channel rules apply and a draft is produced
|
|
227
|
+
* (`ready`), but it is NEVER auto-sent — a human publishes it.
|
|
228
|
+
* - `auto_reply` — reserved for a later lot (note-chevron publishing).
|
|
229
|
+
* Settable ahead of time, but nothing gives it any effect beyond what
|
|
230
|
+
* `draft_only` already does until the WhatsApp send path exists.
|
|
231
|
+
*/
|
|
232
|
+
declare const WHATSAPP_MODES: readonly ["escalate_only", "draft_only", "auto_reply"];
|
|
233
|
+
type WhatsappMode = (typeof WHATSAPP_MODES)[number];
|
|
234
|
+
/**
|
|
235
|
+
* The fail-safe reading everywhere a `whatsapp_mode` field might be absent
|
|
236
|
+
* (a document that predates it) — the gate must never be silently open
|
|
237
|
+
* (§9.1). One constant so every fallback site agrees, instead of copies of
|
|
238
|
+
* the string literal.
|
|
239
|
+
*/
|
|
240
|
+
declare const DEFAULT_WHATSAPP_MODE: WhatsappMode;
|
|
241
|
+
/**
|
|
242
|
+
* Iso-behaviour mapping (§9.1) from the old boolean to the new mode:
|
|
243
|
+
* `true → escalate_only`, `false → draft_only`. `auto_reply` is never
|
|
244
|
+
* produced by this function — reaching it is an explicit operator opt-in,
|
|
245
|
+
* never something derived on anyone's behalf.
|
|
246
|
+
*/
|
|
247
|
+
declare function whatsappModeFromLegacyBoolean(escalateOnly: boolean | undefined): WhatsappMode;
|
|
248
|
+
/**
|
|
249
|
+
* Per-tenant channel prompt names (replaces the `/whatsapp` sibling prompt
|
|
250
|
+
* mechanism): just the NAME of the Langfuse text prompt whose content is
|
|
251
|
+
* substituted for `{{channel_prompt}}` in the agent's own prompt, one per
|
|
252
|
+
* channel.
|
|
253
|
+
*/
|
|
254
|
+
declare const DEFAULT_CHANNEL_PROMPT_EMAIL = "shared/style-email";
|
|
255
|
+
declare const DEFAULT_CHANNEL_PROMPT_WHATSAPP = "shared/style-whatsapp";
|
|
256
|
+
/**
|
|
257
|
+
* Langfuse prompt reference carried by a profile — name + label + fallback
|
|
258
|
+
* body (§5.3 "nom Langfuse + label + fallback (I16)").
|
|
259
|
+
*/
|
|
260
|
+
interface PromptRef {
|
|
261
|
+
name: string;
|
|
262
|
+
label: string;
|
|
263
|
+
/** Prompt body served when Langfuse is unreachable or unconfigured (I16). */
|
|
264
|
+
fallback?: string;
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* A timestamped run outcome. Mirrors the legacy `*_last_run_started_at` /
|
|
268
|
+
* `_completed_at` / `_status` field triples, nested once per profile.
|
|
269
|
+
*/
|
|
270
|
+
interface RunStamp {
|
|
271
|
+
startedAt: Date | null;
|
|
272
|
+
completedAt: Date | null;
|
|
273
|
+
status: string | null;
|
|
274
|
+
}
|
|
275
|
+
interface TriageNodeConfig {
|
|
276
|
+
model: string;
|
|
277
|
+
provider: string;
|
|
278
|
+
reasoning: ReasoningEffort;
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* No `skipsFastResponse` (B3): the legacy's per-profile "escalate but still
|
|
282
|
+
* pre-generate" switch has no meaning here — `graph/run-ticket.ts` finishes
|
|
283
|
+
* unconditionally on `escalated`, so nothing downstream could act on it.
|
|
284
|
+
*/
|
|
285
|
+
interface EscalateNodeConfig {
|
|
286
|
+
model: string;
|
|
287
|
+
provider: string;
|
|
288
|
+
reasoning: ReasoningEffort;
|
|
289
|
+
}
|
|
290
|
+
interface DraftNodeConfig {
|
|
291
|
+
model: string;
|
|
292
|
+
provider: string;
|
|
293
|
+
reasoning: ReasoningEffort;
|
|
294
|
+
maxToolCalls: number;
|
|
295
|
+
}
|
|
296
|
+
interface EvaluateNodeConfig {
|
|
297
|
+
model: string;
|
|
298
|
+
provider: string;
|
|
299
|
+
reasoning: ReasoningEffort;
|
|
300
|
+
minConfidence: number;
|
|
301
|
+
escalationEnabled: boolean;
|
|
302
|
+
}
|
|
303
|
+
interface ReviseNodeConfig {
|
|
304
|
+
model: string;
|
|
305
|
+
provider: string;
|
|
306
|
+
reasoning: ReasoningEffort;
|
|
307
|
+
}
|
|
308
|
+
interface AgentProfile {
|
|
309
|
+
/** 'customer' | 'partner' | 'social' … — the tenant identifier. */
|
|
310
|
+
key: string;
|
|
311
|
+
/** At most one profile; serves the public surfaces. */
|
|
312
|
+
isDefault: boolean;
|
|
313
|
+
enabled: boolean;
|
|
314
|
+
/**
|
|
315
|
+
* Tenant colour for the admin UI chrome. Optional — absent/`null` falls
|
|
316
|
+
* back to a deterministic hash of `key`, so a profile needs no
|
|
317
|
+
* configuration to get a stable colour across sessions.
|
|
318
|
+
*/
|
|
319
|
+
color?: string | null;
|
|
320
|
+
source: {
|
|
321
|
+
channel: ChannelKind;
|
|
322
|
+
viewOrTag: string;
|
|
323
|
+
};
|
|
324
|
+
schedule: {
|
|
325
|
+
triageIntervalMinutes: number;
|
|
326
|
+
triageBatchLimit: number;
|
|
327
|
+
triageConcurrency: number;
|
|
328
|
+
fastResponseIntervalSeconds: number;
|
|
329
|
+
fastResponseBatchLimit: number;
|
|
330
|
+
fastResponseConcurrency: number;
|
|
331
|
+
fastResponseTtlMinutes: number;
|
|
332
|
+
};
|
|
333
|
+
/**
|
|
334
|
+
* Each optional step is nullable; `null` = step absent for this tenant.
|
|
335
|
+
* Real modes: `draft: null` = tenant "triage only"; `evaluate: null` =
|
|
336
|
+
* generation without evaluation (always `ready`, auto-send impossible).
|
|
337
|
+
* `model`/`provider` are FALLBACKS ONLY: when the resolved Langfuse
|
|
338
|
+
* prompt carries a model config, it wins (I16).
|
|
339
|
+
*/
|
|
340
|
+
nodes: {
|
|
341
|
+
triage: TriageNodeConfig;
|
|
342
|
+
escalate: EscalateNodeConfig | null;
|
|
343
|
+
draft: DraftNodeConfig | null;
|
|
344
|
+
evaluate: EvaluateNodeConfig | null;
|
|
345
|
+
revise: ReviseNodeConfig | null;
|
|
346
|
+
};
|
|
347
|
+
prompts: Record<NodeKey, PromptRef>;
|
|
348
|
+
/** Tool names resolved against the registry (§6.2). */
|
|
349
|
+
tools: string[];
|
|
350
|
+
guardrails: {
|
|
351
|
+
/** Rules active among the catalogue (§6.5, I7). */
|
|
352
|
+
active: string[];
|
|
353
|
+
/**
|
|
354
|
+
* NB: `UNCERTAINTY_MARKERS` stays a code constant, deliberately NOT
|
|
355
|
+
* configurable per profile — the sole exception to "params are per
|
|
356
|
+
* tenant" (§6.5).
|
|
357
|
+
*/
|
|
358
|
+
params: {
|
|
359
|
+
noreplySenders: string[];
|
|
360
|
+
blocklist: string[];
|
|
361
|
+
whatsappMode: WhatsappMode;
|
|
362
|
+
judgemeEscalateOnly: boolean;
|
|
363
|
+
/** Langfuse prompt NAME substituted for `{{channel_prompt}}`, per channel. */
|
|
364
|
+
channelPromptEmail: string;
|
|
365
|
+
channelPromptWhatsapp: string;
|
|
366
|
+
};
|
|
367
|
+
};
|
|
368
|
+
/** Per action kind (P3). */
|
|
369
|
+
authorization: Record<string, ActionDecision>;
|
|
370
|
+
/** Materialisation tags (I20). */
|
|
371
|
+
audit: {
|
|
372
|
+
unknownTag: string;
|
|
373
|
+
handledTag: string;
|
|
374
|
+
escalationTag: string;
|
|
375
|
+
sentTag: string;
|
|
376
|
+
needsHumanTag: string;
|
|
377
|
+
followupTag: string;
|
|
378
|
+
};
|
|
379
|
+
autoSend: {
|
|
380
|
+
enabled: boolean;
|
|
381
|
+
senderEmail: string | null;
|
|
382
|
+
minConfidence: number;
|
|
383
|
+
requireHighTriage: boolean;
|
|
384
|
+
};
|
|
385
|
+
rename: {
|
|
386
|
+
enabled: boolean;
|
|
387
|
+
from: string;
|
|
388
|
+
to: string;
|
|
389
|
+
} | null;
|
|
390
|
+
/** Execution state PER TENANT (I13). */
|
|
391
|
+
runtime: {
|
|
392
|
+
triageLock: {
|
|
393
|
+
acquiredAt: Date | null;
|
|
394
|
+
owner: string | null;
|
|
395
|
+
};
|
|
396
|
+
fastResponseLock: {
|
|
397
|
+
acquiredAt: Date | null;
|
|
398
|
+
owner: string | null;
|
|
399
|
+
};
|
|
400
|
+
triageLastRun: RunStamp;
|
|
401
|
+
fastResponseLastRun: RunStamp;
|
|
402
|
+
lastAutoSendDecisionAt: Date | null;
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Run budget: bounds a run in TOOL CALLS and TIME only, never in money —
|
|
408
|
+
* cost is measured (`charge`, I15) and watched separately, not capped here.
|
|
409
|
+
* Every method is a no-throw no-op past the allowance: exhausting the
|
|
410
|
+
* budget must never fail a ticket (§6.3).
|
|
411
|
+
*/
|
|
412
|
+
interface Budget {
|
|
413
|
+
/** The run's deadline signal, forwarded unchanged to every LLM call. */
|
|
414
|
+
signal: AbortSignal;
|
|
415
|
+
consumeToolCall(): void;
|
|
416
|
+
/** True once `maxToolCalls` is spent OR the run signal aborted. */
|
|
417
|
+
exhausted(): boolean;
|
|
418
|
+
/** Accumulates usage/cost for one node. Reasoning stays out of `output` (§6.3). */
|
|
419
|
+
charge(node: NodeKey, usage: Usage, cost: {
|
|
420
|
+
usd: number;
|
|
421
|
+
pricingMissing: boolean;
|
|
422
|
+
}): void;
|
|
423
|
+
/** Per-node breakdown for the ticket's provenance trail. */
|
|
424
|
+
ledger(): CostLedger;
|
|
425
|
+
/** Whole-run total — the per-ticket cost watched downstream. */
|
|
426
|
+
total(): NodeCost;
|
|
427
|
+
}
|
|
428
|
+
declare function createBudget({ signal, maxToolCalls }: {
|
|
429
|
+
signal: AbortSignal;
|
|
430
|
+
maxToolCalls: number;
|
|
431
|
+
}): Budget;
|
|
432
|
+
|
|
433
|
+
interface SourceDescriptor {
|
|
434
|
+
viewOrTag: string;
|
|
435
|
+
}
|
|
436
|
+
interface ConversationPort {
|
|
437
|
+
/**
|
|
438
|
+
* The adapter receives the source descriptor, never the profile: it stays
|
|
439
|
+
* profile-agnostic. Resolving profile → source belongs to the caller.
|
|
440
|
+
*/
|
|
441
|
+
listPending(source: SourceDescriptor, limit: number): Promise<ConversationRef[]>;
|
|
442
|
+
read(ref: ConversationRef): Promise<Conversation>;
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* What `ReplyPort.post` needs to publish a reply — modelled on the legacy
|
|
446
|
+
* `sendReply` for `mode: 'email'`.
|
|
447
|
+
*
|
|
448
|
+
* `mode: 'whatsapp_note'` (whatsapp spec §4.1) is a second publication shape
|
|
449
|
+
* on the SAME adapter, not a new channel: the reply becomes a chevron-note
|
|
450
|
+
* on Gorgias, raw text, no email envelope.
|
|
451
|
+
*
|
|
452
|
+
* A discriminated union, not one interface with optional email fields: the
|
|
453
|
+
* envelope (`bodyHtml`/`subject`/`fromAddress`/`receiverEmail`) is REQUIRED
|
|
454
|
+
* whenever `mode: 'email'`, so a caller that forgets one fails to compile
|
|
455
|
+
* instead of silently posting an empty address.
|
|
456
|
+
*/
|
|
457
|
+
type OutboundReply = {
|
|
458
|
+
mode: 'email';
|
|
459
|
+
bodyText: string;
|
|
460
|
+
bodyHtml: string;
|
|
461
|
+
subject: string | null;
|
|
462
|
+
/** Outbound address shown to the customer (a channel email/sender integration). */
|
|
463
|
+
fromAddress: string;
|
|
464
|
+
receiverName: string | null;
|
|
465
|
+
receiverEmail: string;
|
|
466
|
+
/** Forwarded to channels that support it, as defence in depth only — see guarantee below. */
|
|
467
|
+
idempotencyKey: string;
|
|
468
|
+
} | {
|
|
469
|
+
mode: 'whatsapp_note';
|
|
470
|
+
bodyText: string;
|
|
471
|
+
/** Forwarded to channels that support it, as defence in depth only — see guarantee below. */
|
|
472
|
+
idempotencyKey: string;
|
|
473
|
+
};
|
|
474
|
+
interface ReplyPort {
|
|
475
|
+
/**
|
|
476
|
+
* Publishes the reply. Guarantee: AT-MOST-ONCE, obtained by the caller's
|
|
477
|
+
* claim → post → commit state machine (I9), NOT by channel idempotence —
|
|
478
|
+
* Gorgias has no idempotency key. On an unknown outcome (timeout/5xx), the
|
|
479
|
+
* caller NEVER calls post again; the job stays `sending` for the sweep.
|
|
480
|
+
* `idempotencyKey` is forwarded to channels that support it, as defence in
|
|
481
|
+
* depth only.
|
|
482
|
+
*/
|
|
483
|
+
post(ref: ConversationRef, reply: OutboundReply): Promise<{
|
|
484
|
+
messageId: string;
|
|
485
|
+
}>;
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Generic JSON value shape. `responseSchema`/`ToolSpec.inputSchema` need to
|
|
489
|
+
* describe arbitrary structured-output/tool schemas without hand-modelling
|
|
490
|
+
* the full JSON Schema grammar — a recursive JSON-value type is precise
|
|
491
|
+
* enough for that and keeps this file free of `any`.
|
|
492
|
+
*/
|
|
493
|
+
type JsonSchema = string | number | boolean | null | JsonSchema[] | {
|
|
494
|
+
[key: string]: JsonSchema;
|
|
495
|
+
};
|
|
496
|
+
type ChatMessage = {
|
|
497
|
+
role: 'system';
|
|
498
|
+
content: string;
|
|
499
|
+
} | {
|
|
500
|
+
role: 'user';
|
|
501
|
+
content: string;
|
|
502
|
+
} | {
|
|
503
|
+
role: 'assistant';
|
|
504
|
+
content: string | null;
|
|
505
|
+
toolCalls?: ToolCallRequest[];
|
|
506
|
+
}
|
|
507
|
+
/** Tool result fed back into the conversation for the next completion (§6.2 tool loop). */
|
|
508
|
+
| {
|
|
509
|
+
role: 'tool';
|
|
510
|
+
toolCallId: string;
|
|
511
|
+
content: string;
|
|
512
|
+
};
|
|
513
|
+
/**
|
|
514
|
+
* Tool exposed to the model for one completion — no handler, unlike a
|
|
515
|
+
* registry `ToolDefinition`: execution is the caller's job, gated by the
|
|
516
|
+
* node's tool policy (§6.2).
|
|
517
|
+
*/
|
|
518
|
+
interface ToolSpec {
|
|
519
|
+
name: string;
|
|
520
|
+
description: string;
|
|
521
|
+
inputSchema: JsonSchema;
|
|
522
|
+
}
|
|
523
|
+
interface ToolCallRequest {
|
|
524
|
+
id: string;
|
|
525
|
+
name: string;
|
|
526
|
+
arguments: Record<string, unknown>;
|
|
527
|
+
}
|
|
528
|
+
interface CompletionRequest {
|
|
529
|
+
/** Langfuse generation name (I17). */
|
|
530
|
+
label: string;
|
|
531
|
+
model: string;
|
|
532
|
+
reasoning: ReasoningEffort;
|
|
533
|
+
messages: ChatMessage[];
|
|
534
|
+
tools?: ToolSpec[];
|
|
535
|
+
/** Structured output strict schema. */
|
|
536
|
+
responseSchema?: JsonSchema;
|
|
537
|
+
/** Run deadline (I14). */
|
|
538
|
+
signal?: AbortSignal;
|
|
539
|
+
/**
|
|
540
|
+
* Links this generation to the prompt version that produced `messages`
|
|
541
|
+
* (S2's `ctx.api.llm.complete` v2 already accepts this field verbatim), so
|
|
542
|
+
* Langfuse's generation↔prompt-version attribution — the link S7's
|
|
543
|
+
* experiments and reviews are built on — survives prompt resolution having
|
|
544
|
+
* moved inside the node (T19 resolves `PromptPort` itself now, not the
|
|
545
|
+
* worker). Absent means no linked prompt (e.g. the node built its messages
|
|
546
|
+
* without going through `PromptPort`).
|
|
547
|
+
*
|
|
548
|
+
* `resolve: false` is set by every caller in this package (D-LF follow-up,
|
|
549
|
+
* link-only mode): the kit always resolves its own prompt via `PromptPort`
|
|
550
|
+
* before building `messages`, so it never wants the platform to resolve
|
|
551
|
+
* `promptRef` again — only to link the trace to the prompt that already
|
|
552
|
+
* produced the system message. See `app-integrations.controller.ts`'s
|
|
553
|
+
* `llmComplete` JSDoc for the full contract; `resolve: false` skips the
|
|
554
|
+
* `manifest.prompts[]` declaration gate that would otherwise 403 every one
|
|
555
|
+
* of these calls under D-LF (`manifest.prompts[]` stays permanently empty).
|
|
556
|
+
*/
|
|
557
|
+
promptRef?: {
|
|
558
|
+
name: string;
|
|
559
|
+
version?: number;
|
|
560
|
+
label?: string;
|
|
561
|
+
resolve?: boolean;
|
|
562
|
+
};
|
|
563
|
+
/** Forwarded verbatim to `ctx.api.llm.complete` v2's `trace` (S2). */
|
|
564
|
+
trace?: {
|
|
565
|
+
sessionId?: string;
|
|
566
|
+
tags?: string[];
|
|
567
|
+
metadata?: Record<string, string>;
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
interface CompletionResult {
|
|
571
|
+
text: string | null;
|
|
572
|
+
toolCalls: ToolCallRequest[];
|
|
573
|
+
usage: Usage;
|
|
574
|
+
/**
|
|
575
|
+
* Langfuse ids of THIS completion (I17), absent when tracing is off or the
|
|
576
|
+
* gateway is a fake. Carried per-result rather than read back from the
|
|
577
|
+
* gateway afterwards: a run makes several calls, and "the last trace" is
|
|
578
|
+
* whichever one happened to finish last.
|
|
579
|
+
*/
|
|
580
|
+
traceId?: string;
|
|
581
|
+
observationId?: string;
|
|
582
|
+
}
|
|
583
|
+
interface LlmPort {
|
|
584
|
+
/**
|
|
585
|
+
* One completion call. `reasoning` is translated to the provider's native
|
|
586
|
+
* parameter; an invalid (model, effort) pair is refused AT PROFILE LOAD
|
|
587
|
+
* TIME, never silently ignored.
|
|
588
|
+
*/
|
|
589
|
+
complete(req: CompletionRequest): Promise<CompletionResult>;
|
|
590
|
+
}
|
|
591
|
+
interface ResolvedPrompt {
|
|
592
|
+
/** Prompt name actually served — normally `ref.name`, carried here too so a caller never has to hold onto the ref just to build `CompletionRequest.promptRef`. */
|
|
593
|
+
name: string;
|
|
594
|
+
text: string;
|
|
595
|
+
/**
|
|
596
|
+
* The Langfuse prompt version actually served. The in-code fallback (§3.7
|
|
597
|
+
* level 3) reports `0`, per spec — never `null` (C6): this value flows
|
|
598
|
+
* into T19's `prompt-cache` mirror and onto a UI page, and a fallback
|
|
599
|
+
* silently reporting a different "no version" shape than the spec's `0`
|
|
600
|
+
* would make those two surfaces disagree.
|
|
601
|
+
*/
|
|
602
|
+
version: number;
|
|
603
|
+
/**
|
|
604
|
+
* Model config carried by the resolved Langfuse prompt, when it declares
|
|
605
|
+
* one. WINS over `AgentProfile.nodes.<node>`'s own `model`/`provider`
|
|
606
|
+
* (I16 — see `domain/profile.ts`'s `AgentProfile.nodes` doc: those fields
|
|
607
|
+
* are fallbacks only). `null`/absent means "no override", the profile's
|
|
608
|
+
* own settings apply unchanged.
|
|
609
|
+
*/
|
|
610
|
+
config?: {
|
|
611
|
+
model: string;
|
|
612
|
+
temperature?: number;
|
|
613
|
+
} | null;
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* Resolves rendered prompt text for one node's prompt reference (§3.7's
|
|
617
|
+
* three-level fallback: Langfuse → prompt-cache mirror → in-code default). A
|
|
618
|
+
* node calls this instead of reading `AgentProfile.prompts` directly (the
|
|
619
|
+
* legacy shortcut), which is what lets T19 change the resolution strategy
|
|
620
|
+
* without a single node changing.
|
|
621
|
+
*
|
|
622
|
+
* `vars` are substituted into the resolved text ONCE, at this boundary
|
|
623
|
+
* (§3.7: `{{categories}}`, `{{channel_prompt}}`, `{{agent_name}}`) — a node
|
|
624
|
+
* never substitutes for itself, which is what keeps a raw
|
|
625
|
+
* `@@@langfusePrompt:…@@@` composition tag from ever being able to reach the
|
|
626
|
+
* LLM (T19's stated guarantee): the one place substitution happens is also
|
|
627
|
+
* the one place the composition tag gets resolved.
|
|
628
|
+
*
|
|
629
|
+
* Contract (C5): `resolve` NEVER REJECTS. Every failure at levels 1-2 of the
|
|
630
|
+
* ladder falls through to the in-code default (level 3), which always
|
|
631
|
+
* terminates it. This matters because resolution now happens INSIDE the
|
|
632
|
+
* node rather than being pre-resolved by the worker: if `resolve` could
|
|
633
|
+
* reject, that rejection would be absorbed by whichever node called it under
|
|
634
|
+
* that node's own error policy — `escalate`'s fail-open would read a
|
|
635
|
+
* Langfuse outage as "nothing to escalate", `evaluate`'s fail-safe would
|
|
636
|
+
* turn it into a hold — both silently, and both after the run already paid
|
|
637
|
+
* for `fetchContext` and `triage`. T19 must pin this property with a total-
|
|
638
|
+
* outage test (Langfuse and the `prompt-cache` mirror both unavailable).
|
|
639
|
+
*/
|
|
640
|
+
interface PromptPort {
|
|
641
|
+
resolve(ref: PromptRef, vars?: Record<string, string>): Promise<ResolvedPrompt>;
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* Tag names used to materialise pipeline decisions on the channel (I20).
|
|
645
|
+
* "Tag" does not exist in the domain — it is the channel's rendering of a
|
|
646
|
+
* `Classification` or outcome, and these are the exact strings a profile's
|
|
647
|
+
* `audit` config resolves per tenant.
|
|
648
|
+
*/
|
|
649
|
+
interface AuditTags {
|
|
650
|
+
unknownTag: string;
|
|
651
|
+
handledTag: string;
|
|
652
|
+
escalationTag: string;
|
|
653
|
+
sentTag: string;
|
|
654
|
+
needsHumanTag: string;
|
|
655
|
+
followupTag: string;
|
|
656
|
+
}
|
|
657
|
+
interface StatePort {
|
|
658
|
+
/** Materialises the triage decision (ex `ClassificationSink.record`). */
|
|
659
|
+
record(ref: ConversationRef, classification: Classification, audit: AuditTags): Promise<void>;
|
|
660
|
+
/** ex `ConversationMeta.rename`. */
|
|
661
|
+
rename(ref: ConversationRef, subject: string): Promise<void>;
|
|
662
|
+
/** Audit tag application (I20) — not a triage classification. ex `ConversationMeta.flag`. */
|
|
663
|
+
flag(ref: ConversationRef, tag: string): Promise<void>;
|
|
664
|
+
}
|
|
665
|
+
interface ClockPort {
|
|
666
|
+
now(): Date;
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* The spec's six named ports (§3.3), as a closed union. `testing/fakes`'s
|
|
670
|
+
* `PORT_SURFACES` types its map off THIS, rather than the other way around
|
|
671
|
+
* (C4): a hand-written literal typing its own input is invisible to the
|
|
672
|
+
* compiler when it drifts — `PromptPort` was once silently absent from
|
|
673
|
+
* `PORT_SURFACES` and every contract test still passed. Typing the map
|
|
674
|
+
* `Record<PortName, …>` makes a missing port a compile error, and
|
|
675
|
+
* `satisfies readonly (keyof ThatPort)[]` on each entry makes a renamed
|
|
676
|
+
* method one too.
|
|
677
|
+
*/
|
|
678
|
+
type PortName = 'ConversationPort' | 'ReplyPort' | 'LlmPort' | 'PromptPort' | 'StatePort' | 'ClockPort';
|
|
679
|
+
/**
|
|
680
|
+
* What the read tools of §6.2 look things up in. A real adapter reads
|
|
681
|
+
* Shopify/order data off the ticket payload and platform records; the node
|
|
682
|
+
* itself only ever sees this interface, never a network call or a DB import
|
|
683
|
+
* (§1's invariant).
|
|
684
|
+
*
|
|
685
|
+
* `searchKnowledge` is a seam on purpose — the choice of knowledge base and
|
|
686
|
+
* its indexing is a separate decision; a node only has to consume it behind
|
|
687
|
+
* this method.
|
|
688
|
+
*/
|
|
689
|
+
interface ToolContext {
|
|
690
|
+
getOrder(orderId: string): Promise<OrderSummary | null>;
|
|
691
|
+
getTracking(orderId: string): Promise<TrackingSummary | null>;
|
|
692
|
+
searchKnowledge(query: string): Promise<KnowledgeHit[]>;
|
|
693
|
+
findSimilarTickets(query: string, limit: number): Promise<SimilarTicket[]>;
|
|
694
|
+
}
|
|
695
|
+
/** What a resolved tool may be used for (§6.2). */
|
|
696
|
+
type ToolPolicy = 'read' | 'requires_approval' | 'forbidden';
|
|
697
|
+
interface CatalogueTool {
|
|
698
|
+
name: string;
|
|
699
|
+
policy: ToolPolicy;
|
|
700
|
+
}
|
|
701
|
+
/**
|
|
702
|
+
* `name → policy` map for the four read tools above (§6.2) — ported
|
|
703
|
+
* verbatim from legacy `agent/profile/catalogue.ts`'s `AGENT_TOOLS` (T15
|
|
704
|
+
* review E2). `AgentProfile.tools` (`domain/profile.ts`) is a bare
|
|
705
|
+
* `string[]` "resolved against the registry"; this is that registry.
|
|
706
|
+
*
|
|
707
|
+
* Ported now, not deferred to T17, because T17's `draft` node needs it for
|
|
708
|
+
* two things nothing else in this kit provides: building the `ToolSpec[]`
|
|
709
|
+
* to hand the model, and gating actual execution by policy — a node cannot
|
|
710
|
+
* do either from `ToolContext` alone, which only says WHAT the four methods
|
|
711
|
+
* return, not whether a given profile may call them.
|
|
712
|
+
*
|
|
713
|
+
* `gorgias.rename_conversation` and the other write tools are absent ON
|
|
714
|
+
* PURPOSE: §6.2 states the write tools are never exposed to the model — the
|
|
715
|
+
* rename stays a code step of the worker. Nothing here grows into a write
|
|
716
|
+
* tool by editing a policy value; a `forbidden`/`requires_approval` tool
|
|
717
|
+
* would need its own catalogue entry, added deliberately.
|
|
718
|
+
*
|
|
719
|
+
* `supportsReasoning` (the model-family check next to `AGENT_TOOLS` in the
|
|
720
|
+
* legacy catalogue) is deliberately NOT ported alongside it — the API
|
|
721
|
+
* package already owns it, a provider concern outside this kit.
|
|
722
|
+
*/
|
|
723
|
+
declare const AGENT_TOOLS: Record<string, CatalogueTool>;
|
|
724
|
+
interface OrderSummary {
|
|
725
|
+
id: string;
|
|
726
|
+
status: string;
|
|
727
|
+
/** ISO date string — omitted when the source data doesn't carry one. */
|
|
728
|
+
placedAt?: string;
|
|
729
|
+
}
|
|
730
|
+
interface TrackingSummary {
|
|
731
|
+
orderId: string;
|
|
732
|
+
carrier: string;
|
|
733
|
+
trackingNumber: string;
|
|
734
|
+
status: string;
|
|
735
|
+
url: string | null;
|
|
736
|
+
}
|
|
737
|
+
interface KnowledgeHit {
|
|
738
|
+
id: string;
|
|
739
|
+
title: string;
|
|
740
|
+
content: string;
|
|
741
|
+
url?: string | null;
|
|
742
|
+
}
|
|
743
|
+
interface SimilarTicket {
|
|
744
|
+
id: string;
|
|
745
|
+
excerpt: string;
|
|
746
|
+
category: string;
|
|
747
|
+
resolution?: string | null;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
type Outcome = 'sent' | 'ready' | 'needs_human' | 'guardrail_hold' | 'awaiting_approval' | 'escalated' | 'triaged_only' | 'no_reply_needed' | 'failed' | null;
|
|
751
|
+
interface TicketRunState {
|
|
752
|
+
conversation: Conversation | null;
|
|
753
|
+
classification: Classification | null;
|
|
754
|
+
escalated: boolean;
|
|
755
|
+
draft: Draft | null;
|
|
756
|
+
verdict: Verdict | null;
|
|
757
|
+
reviseCount: 0 | 1;
|
|
758
|
+
guardrailHits: string[];
|
|
759
|
+
proposedActions: ProposedAction[];
|
|
760
|
+
outcome: Outcome;
|
|
761
|
+
}
|
|
762
|
+
declare function initialState(): TicketRunState;
|
|
763
|
+
/**
|
|
764
|
+
* The category-level auto-reply policy for this ticket — resolved by the
|
|
765
|
+
* caller from the `category` record, which a node may not touch (§1).
|
|
766
|
+
*/
|
|
767
|
+
interface CategoryPolicy {
|
|
768
|
+
autoReplyEnabled: boolean;
|
|
769
|
+
/**
|
|
770
|
+
* Per-category override of the auto-send confidence threshold. Carried
|
|
771
|
+
* here because the caller resolves it, but deliberately UNUSED by
|
|
772
|
+
* `isSendable`/`isAutoSendEligible` (`verdict/policy.ts`, T16) — the
|
|
773
|
+
* legacy's assumed simplification drops the second confidence check this
|
|
774
|
+
* used to feed.
|
|
775
|
+
*/
|
|
776
|
+
minConfidence: number | null;
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* One entry of the profile's Category referential (§3.7's `{{categories}}`
|
|
780
|
+
* substitution) — the taxonomy `triage` shows the model so it classifies
|
|
781
|
+
* against the tenant's real Gorgias categories instead of inventing a tag.
|
|
782
|
+
* Rendered by the caller and handed down, like `CategoryPolicy` above: a
|
|
783
|
+
* node may not reach the referential itself (§1).
|
|
784
|
+
*/
|
|
785
|
+
interface CategoryReferentialEntry {
|
|
786
|
+
/** Human label shown alongside `tag` — the classifier's output display name. */
|
|
787
|
+
name?: string;
|
|
788
|
+
/** The real Gorgias tag. */
|
|
789
|
+
tag: string;
|
|
790
|
+
desc: string;
|
|
791
|
+
examples?: string;
|
|
792
|
+
}
|
|
793
|
+
interface NodeDeps {
|
|
794
|
+
ref: ConversationRef;
|
|
795
|
+
profile: AgentProfile;
|
|
796
|
+
ports: {
|
|
797
|
+
conversation: ConversationPort;
|
|
798
|
+
reply: ReplyPort;
|
|
799
|
+
llm: LlmPort;
|
|
800
|
+
prompt: PromptPort;
|
|
801
|
+
state: StatePort;
|
|
802
|
+
clock: ClockPort;
|
|
803
|
+
/**
|
|
804
|
+
* The judge's own gateway. `evaluate` may run on a different provider
|
|
805
|
+
* than the writer, which means a different API key and a different
|
|
806
|
+
* Langfuse prompt link — sharing `llm` silently fails every verdict as
|
|
807
|
+
* soon as the two providers differ. Absent means "same gateway as the
|
|
808
|
+
* writer", today's single-provider install.
|
|
809
|
+
*/
|
|
810
|
+
evaluator?: LlmPort;
|
|
811
|
+
};
|
|
812
|
+
toolContext: ToolContext;
|
|
813
|
+
/**
|
|
814
|
+
* Bounds THIS run's tool calls/time and measures its cost (I15). Nothing
|
|
815
|
+
* on `TicketRunState` mirrors `budget.ledger()` — the ledger it accumulates
|
|
816
|
+
* IS the run's cost record; a caller who needs it after the run reads
|
|
817
|
+
* `budget.ledger()`/`budget.total()` directly rather than through a second,
|
|
818
|
+
* separately-populated copy on the state.
|
|
819
|
+
*/
|
|
820
|
+
budget: Budget;
|
|
821
|
+
category: CategoryPolicy;
|
|
822
|
+
categories: CategoryReferentialEntry[];
|
|
823
|
+
log: (msg: string) => void;
|
|
824
|
+
/**
|
|
825
|
+
* Claim → post → commit persistence seam (I9). A node may never touch a
|
|
826
|
+
* database directly (§1), so the state machine that makes send-once safe
|
|
827
|
+
* under concurrency lives behind this pair, gated by an explicit `mode`
|
|
828
|
+
* rather than by whether the fields happen to be set.
|
|
829
|
+
*
|
|
830
|
+
* `{mode: 'none'}` is "no persistence layer" — `act` treats the run as its
|
|
831
|
+
* own uncontested claim, as every node test does today. It is a REQUIRED
|
|
832
|
+
* field, not an optional one left unset (post-T14 review, C7): the legacy
|
|
833
|
+
* shape (`claim?`/`commit?` as bare optional `NodeDeps` fields) let an
|
|
834
|
+
* assembly forget to wire persistence and silently degrade to
|
|
835
|
+
* send-once-safety-off, with no compile error — and the same omission
|
|
836
|
+
* would have been invisible to T21's dry-run assertion ("not a single
|
|
837
|
+
* write port was called"), since fields outside `ports` are nothing a
|
|
838
|
+
* recording wrapper walking `ports` would ever see. Requiring the choice
|
|
839
|
+
* turns that silent omission into a decision every assembly site states
|
|
840
|
+
* out loud, without forcing a node test that does not care about
|
|
841
|
+
* persistence to implement one (`{mode: 'none'}` is a one-line literal,
|
|
842
|
+
* not a persistence layer).
|
|
843
|
+
*
|
|
844
|
+
* Everything the run produced travels WITH the claim so the claiming write
|
|
845
|
+
* can persist it in the same atomic operation: a crash between claim and
|
|
846
|
+
* commit then leaves a complete record for the sweep to escalate, never a
|
|
847
|
+
* lost generation.
|
|
848
|
+
*/
|
|
849
|
+
send: {
|
|
850
|
+
mode: 'none';
|
|
851
|
+
} | {
|
|
852
|
+
mode: 'claimed';
|
|
853
|
+
claim: (run: {
|
|
854
|
+
draft: Draft;
|
|
855
|
+
verdict: Verdict | null;
|
|
856
|
+
}) => Promise<boolean>;
|
|
857
|
+
commit: (messageId: string) => Promise<void>;
|
|
858
|
+
};
|
|
859
|
+
/**
|
|
860
|
+
* When this run was queued. `act` compares an agent reply against it to
|
|
861
|
+
* catch one that landed before generation started (I8's window gap), which
|
|
862
|
+
* the divergence count cannot see. Null means "unknown" and makes `act`
|
|
863
|
+
* treat any agent reply as disqualifying.
|
|
864
|
+
*/
|
|
865
|
+
queuedAt?: Date | null;
|
|
866
|
+
/**
|
|
867
|
+
* Step observer for the admin's graph debugger. Absent in production — the
|
|
868
|
+
* caller pays nothing for it (`run-ticket.ts` calls the node directly when
|
|
869
|
+
* there is no observer). Never a control point: it observes, it cannot
|
|
870
|
+
* change the sequence, which is what keeps the debugged run the SAME run
|
|
871
|
+
* as production.
|
|
872
|
+
*/
|
|
873
|
+
trace?: (step: NodeStep) => void;
|
|
874
|
+
}
|
|
875
|
+
/** The nodes `runTicket` can call, in the order the diagram draws them. */
|
|
876
|
+
declare const NODE_NAMES: readonly ["fetchContext", "triage", "escalate", "draft", "evaluate", "revise", "guardrails", "authorize", "act"];
|
|
877
|
+
type NodeName = (typeof NODE_NAMES)[number];
|
|
878
|
+
/**
|
|
879
|
+
* One executed node. A node the graph decided NOT to call emits nothing —
|
|
880
|
+
* "skipped" is derived by the reader from `NODE_NAMES` minus what it saw,
|
|
881
|
+
* so the graph never has to announce its own omissions.
|
|
882
|
+
*
|
|
883
|
+
* `evaluate` legitimately appears twice: once on the first draft, once after
|
|
884
|
+
* `revise` (the revision loop).
|
|
885
|
+
*/
|
|
886
|
+
interface NodeStep {
|
|
887
|
+
node: NodeName;
|
|
888
|
+
/** The state patch the node produced — empty when it threw. */
|
|
889
|
+
patch: Partial<TicketRunState>;
|
|
890
|
+
durationMs: number;
|
|
891
|
+
/** Present only when the node threw; the throw itself still propagates. */
|
|
892
|
+
error?: string;
|
|
893
|
+
}
|
|
894
|
+
/**
|
|
895
|
+
* The contract every node conforms to (§6.1): a pure transition from state
|
|
896
|
+
* to state-patch over injected ports, never a direct side effect on a
|
|
897
|
+
* database or the network.
|
|
898
|
+
*/
|
|
899
|
+
type Node = (state: Readonly<TicketRunState>, deps: NodeDeps) => Promise<Partial<TicketRunState>>;
|
|
900
|
+
|
|
901
|
+
/**
|
|
902
|
+
* Resume point. §3.5 keeps TWO workers/functions: `triage-tick` classifies a
|
|
903
|
+
* ticket and hands off, `process-response` picks it up later. Persisting
|
|
904
|
+
* `TicketRunState`'s classification/escalated flag and re-entering here with
|
|
905
|
+
* `resume` set is how the second run avoids re-classifying — which would
|
|
906
|
+
* both cost a second LLM call and risk re-escalating a ticket that already
|
|
907
|
+
* passed.
|
|
908
|
+
*/
|
|
909
|
+
interface ResumeFrom {
|
|
910
|
+
classification: TicketRunState['classification'];
|
|
911
|
+
escalated: boolean;
|
|
912
|
+
}
|
|
913
|
+
/**
|
|
914
|
+
* How far `runTicket` is allowed to go this call. The only value today,
|
|
915
|
+
* `'triage'`, names the LAST phase the run may complete — triage AND
|
|
916
|
+
* escalate, escalate being folded into the same phase (§3.3's own
|
|
917
|
+
* sequencing keeps the two together, never a decision point on their own) —
|
|
918
|
+
* so there is no adjacent value ("before escalate"?) to misread this as: the
|
|
919
|
+
* run either completes the triage phase in full, or (when this option is
|
|
920
|
+
* absent) keeps going to a terminal outcome.
|
|
921
|
+
*/
|
|
922
|
+
type RunUntil = 'triage';
|
|
923
|
+
interface RunTicketOptions {
|
|
924
|
+
resume?: ResumeFrom;
|
|
925
|
+
/**
|
|
926
|
+
* Stop right after triage + escalate, before any exit check or `draft`.
|
|
927
|
+
* `triage-tick` (§3.5) uses this to persist the triage decision without
|
|
928
|
+
* ever paying for a draft `process-response` may not need. The returned
|
|
929
|
+
* state carries no `outcome` and no tag was written — `finish` runs on the
|
|
930
|
+
* LATER, resumed call instead, once the full sequence below decides one.
|
|
931
|
+
*
|
|
932
|
+
* This is a DELIBERATE non-materialisation, not an oversight: a
|
|
933
|
+
* checkpointed run never calls `ports.state.record`, so the classification
|
|
934
|
+
* it just paid for is only held in the returned `TicketRunState`, nowhere
|
|
935
|
+
* else. §3.5 assigns writing it down to the CALLER — `triage-tick` runs
|
|
936
|
+
* `runTicket(deps, {until:'triage'})`, applies the deduplicated tags,
|
|
937
|
+
* writes the `triage-decision` record, then creates the `generated-response`
|
|
938
|
+
* if eligible. A caller that drops this returned state (crash, unhandled
|
|
939
|
+
* rejection, a resumed call that never happens) loses a paid-for LLM
|
|
940
|
+
* decision with nothing left to reconstruct it from.
|
|
941
|
+
*/
|
|
942
|
+
until?: RunUntil;
|
|
943
|
+
}
|
|
944
|
+
declare function runTicket(deps: NodeDeps, options?: RunTicketOptions): Promise<TicketRunState>;
|
|
945
|
+
|
|
946
|
+
/** `short_answer` fires under this length (candidate answer, trimmed). */
|
|
947
|
+
declare const CANDIDATE_MIN_LENGTH = 20;
|
|
948
|
+
/**
|
|
949
|
+
* Uncertainty phrases that should trigger a hold. A code constant,
|
|
950
|
+
* deliberately NOT configurable per profile — the sole exception to "params
|
|
951
|
+
* are per tenant" (§6.5 legacy / §3.9).
|
|
952
|
+
*
|
|
953
|
+
* Genuinely frozen (T15 review C), not just documented as such: `as const` +
|
|
954
|
+
* `Object.freeze` so a consumer's stray `.push(...)` is both a compile error
|
|
955
|
+
* (readonly array — no `push` method) and, should it slip past the compiler
|
|
956
|
+
* (`as any`), a runtime `TypeError` instead of a silent per-process mutation
|
|
957
|
+
* of a guardrail meant to be identical for every tenant.
|
|
958
|
+
*/
|
|
959
|
+
declare const UNCERTAINTY_MARKERS: readonly string[];
|
|
960
|
+
/**
|
|
961
|
+
* STOP opt-out phrases (whatsapp spec §5.1) — frozen in code, not
|
|
962
|
+
* configurable per profile ("liste exacte à figer en implémentation, courte
|
|
963
|
+
* et non configurable dans un premier temps"). Each entry is the French
|
|
964
|
+
* SMS/WhatsApp regulatory opt-out convention (a lone "STOP" keyword,
|
|
965
|
+
* optionally suffixed).
|
|
966
|
+
*
|
|
967
|
+
* Typed `ReadonlySet<string>` (T15 review C): only `.has` is ever called
|
|
968
|
+
* against it, and this type has no `add`/`delete` at all, so a consumer
|
|
969
|
+
* calling either is a compile error. `Object.freeze` would not add anything
|
|
970
|
+
* here — a `Set`'s `add`/`delete` are prototype methods a frozen instance
|
|
971
|
+
* still runs — so the type is the real guard, same as it is for every other
|
|
972
|
+
* live-object port in this package.
|
|
973
|
+
*/
|
|
974
|
+
declare const STOP_PHRASES: ReadonlySet<string>;
|
|
975
|
+
/**
|
|
976
|
+
* Exhaustive guardrail identifiers (§3.9, I7) — verified one by one against
|
|
977
|
+
* what `runGuardrails`/`channelPreGates`/`verifyReply` actually push into
|
|
978
|
+
* `guardrailHits`, so this list cannot drift from the runtime behaviour it
|
|
979
|
+
* names:
|
|
980
|
+
* - `whatsapp`, `whatsapp_stop`, `not_customer_turn`, `judgeme`,
|
|
981
|
+
* `noreply_sender` — channel/sender pre-gates.
|
|
982
|
+
* - `triage_not_high`, `escalated` — upstream pre-gates.
|
|
983
|
+
* - `blocklist` — the FAMILY name. The runtime hit is `blocklist:<term>`
|
|
984
|
+
* (one per matched term, see `guardrailBucket`); a profile enables/
|
|
985
|
+
* disables the rule as a whole, never a single term.
|
|
986
|
+
* - `attachment`, `short_answer`, `uncertainty_marker` — content rules.
|
|
987
|
+
* - `evaluation_missing` — verdict gate.
|
|
988
|
+
*
|
|
989
|
+
* Two things are intentionally NOT here (§3.9 draws the line explicitly):
|
|
990
|
+
* - `ticket_closed`, `agent_replied`, `diverged`, `run_deadline`,
|
|
991
|
+
* `customer_email_missing` — pure code inside `act`'s claim→post→commit
|
|
992
|
+
* anti-collision check (T17), never profile-configurable.
|
|
993
|
+
* - `UNCERTAINTY_MARKERS`/`STOP_PHRASES` themselves stay code constants —
|
|
994
|
+
* the identifier is toggleable per profile, the phrase list it matches
|
|
995
|
+
* against is not.
|
|
996
|
+
*/
|
|
997
|
+
declare const AGENT_GUARDRAILS: readonly ["whatsapp", "whatsapp_stop", "not_customer_turn", "judgeme", "noreply_sender", "triage_not_high", "escalated", "blocklist", "attachment", "short_answer", "uncertainty_marker", "evaluation_missing"];
|
|
998
|
+
type GuardrailId = (typeof AGENT_GUARDRAILS)[number];
|
|
999
|
+
|
|
1000
|
+
/**
|
|
1001
|
+
* Superset-compatible with `@wopilo/gorgias-client`'s `RawGorgiasTicketPayload`
|
|
1002
|
+
* (B1): this package may not import `@wopilo/*` (dependency-allowlist.spec.ts),
|
|
1003
|
+
* so this is a local, structural declaration rather than an import — but
|
|
1004
|
+
* every field the client actually returns must still be ASSIGNABLE here, or
|
|
1005
|
+
* T21's adapter/T24's `ext-*` functions (both of which hold a real client
|
|
1006
|
+
* payload) hit `strict: true` compile errors and reach for `as unknown as`,
|
|
1007
|
+
* which defeats the point of a typed shape. Pinned by an assignability
|
|
1008
|
+
* assertion in `packages/gorgias-client` so the two cannot silently drift
|
|
1009
|
+
* apart again.
|
|
1010
|
+
*/
|
|
1011
|
+
interface RawTicketMessage {
|
|
1012
|
+
channel?: string | null;
|
|
1013
|
+
from_agent?: boolean;
|
|
1014
|
+
body_text?: string | null;
|
|
1015
|
+
/**
|
|
1016
|
+
* HTML/stripped variants (T3-review-A5 parity, `conversation-mapping.ts`'s
|
|
1017
|
+
* `countableMessages`): a message whose sole content is HTML has a blank
|
|
1018
|
+
* `body_text`, so a text-presence check reading `body_text` alone misses a
|
|
1019
|
+
* real customer turn. Declared here — not converted to text, just checked
|
|
1020
|
+
* for non-blank presence — so this package can detect that case without
|
|
1021
|
+
* porting `htmlToText`.
|
|
1022
|
+
*/
|
|
1023
|
+
body_html?: string | null;
|
|
1024
|
+
stripped_text?: string | null;
|
|
1025
|
+
stripped_html?: string | null;
|
|
1026
|
+
attachments?: unknown[];
|
|
1027
|
+
created_datetime?: string | null;
|
|
1028
|
+
/** See `isInternalNoteChannel` below (B2). */
|
|
1029
|
+
source?: {
|
|
1030
|
+
type?: string;
|
|
1031
|
+
} | null;
|
|
1032
|
+
}
|
|
1033
|
+
interface RawTicket {
|
|
1034
|
+
channel?: string | null;
|
|
1035
|
+
subject?: string | null;
|
|
1036
|
+
status?: string | null;
|
|
1037
|
+
customer?: {
|
|
1038
|
+
email?: string | null;
|
|
1039
|
+
} | null;
|
|
1040
|
+
messages?: RawTicketMessage[];
|
|
1041
|
+
}
|
|
1042
|
+
declare const WHATSAPP_NOTE_CHEVRON = ">";
|
|
1043
|
+
/**
|
|
1044
|
+
* True for a `from_agent` internal note whose body starts with the
|
|
1045
|
+
* chevron — the note Gorgias' WhatsApp integration turns into an outbound
|
|
1046
|
+
* message (whatsapp spec §7/§8.2, unfavourable case). An ordinary internal
|
|
1047
|
+
* note (no chevron) is deliberately NOT matched, and `isWhatsappConversation`
|
|
1048
|
+
* must be true for anything to match — quoting a customer in a note is a
|
|
1049
|
+
* normal habit on EMAIL tickets and must not be caught here.
|
|
1050
|
+
*/
|
|
1051
|
+
declare function isWhatsappChevronNote(message: RawTicketMessage, isWhatsappConversation: boolean): boolean;
|
|
1052
|
+
/**
|
|
1053
|
+
* True when a CUSTOMER message carries an attachment. Agent messages and
|
|
1054
|
+
* internal notes must not trigger the `attachment` guardrail — an agent
|
|
1055
|
+
* uploading a return label is not a reason to hold the reply.
|
|
1056
|
+
*/
|
|
1057
|
+
declare function hasCustomerAttachment(rawTicket: RawTicket | null | undefined): boolean;
|
|
1058
|
+
/**
|
|
1059
|
+
* True when the ticket is a WhatsApp conversation — the ticket channel is
|
|
1060
|
+
* whatsapp, or any message came through the whatsapp channel.
|
|
1061
|
+
*/
|
|
1062
|
+
declare function isWhatsappTicket(rawTicket: RawTicket | null | undefined): boolean;
|
|
1063
|
+
/**
|
|
1064
|
+
* True when the ticket is a Judge.me review-notification email. Deterministic,
|
|
1065
|
+
* no LLM: matches the ticket subject, or the first customer message body.
|
|
1066
|
+
* Judge.me puts the customer in From/Reply-To, so the sender is unusable — we
|
|
1067
|
+
* key off the subject and body markers instead.
|
|
1068
|
+
*
|
|
1069
|
+
* Thin wrapper over `isJudgemeConversation` (`channel-pre-gates.ts`): the two
|
|
1070
|
+
* differ only in HOW they get to (subject, first customer message) — this one
|
|
1071
|
+
* reads it off the raw ticket's messages, the other takes it pre-resolved
|
|
1072
|
+
* from a `Conversation`. The matching logic itself lives in exactly one
|
|
1073
|
+
* place.
|
|
1074
|
+
*/
|
|
1075
|
+
declare function isJudgemeTicket(rawTicket: RawTicket | null | undefined): boolean;
|
|
1076
|
+
/**
|
|
1077
|
+
* True when the ticket customer email matches an entry of `senders`.
|
|
1078
|
+
* Deterministic, no LLM: unlike Judge.me, an automated no-reply sender (e.g.
|
|
1079
|
+
* Bigblue) does not usurp the customer field, so matching the sender email
|
|
1080
|
+
* is reliable. Pure — the caller resolves the configured list.
|
|
1081
|
+
*
|
|
1082
|
+
* Each entry supports three forms: an exact address (strict equality), a
|
|
1083
|
+
* `@domain` suffix (endsWith), or a `local@` prefix (startsWith). Empty/blank
|
|
1084
|
+
* entries are skipped — they must never match everything.
|
|
1085
|
+
*
|
|
1086
|
+
* NOT a thin wrapper over `isAutomatedSenderEmail` (`channel-pre-gates.ts`),
|
|
1087
|
+
* and vice versa: for a malformed entry like a bare `'@'`, this function
|
|
1088
|
+
* tries EVERY form for an entry before giving up on it (three separate
|
|
1089
|
+
* `if`s), while `isAutomatedSenderEmail` commits to the first matching form
|
|
1090
|
+
* and returns whatever it decides. The two already disagreed here in the
|
|
1091
|
+
* legacy codebase — see that function's doc for the concrete case. Ported
|
|
1092
|
+
* as-is rather than silently reconciled.
|
|
1093
|
+
*/
|
|
1094
|
+
declare function isAutomatedSenderTicket(rawTicket: RawTicket | null | undefined, senders: string[]): boolean;
|
|
1095
|
+
/**
|
|
1096
|
+
* True when the Gorgias ticket is explicitly closed. Absent/unknown status
|
|
1097
|
+
* counts as open — never block every send on an API schema drift.
|
|
1098
|
+
*/
|
|
1099
|
+
declare function isTicketClosed(rawTicket: RawTicket | null | undefined): boolean;
|
|
1100
|
+
|
|
1101
|
+
interface RunGuardrailsInput {
|
|
1102
|
+
firstCustomerMessage: string;
|
|
1103
|
+
candidateAnswer: string;
|
|
1104
|
+
hasAttachment: boolean;
|
|
1105
|
+
blocklist: string[];
|
|
1106
|
+
}
|
|
1107
|
+
/**
|
|
1108
|
+
* Run all deterministic content guardrails and return the list of hits, in
|
|
1109
|
+
* their exact evaluation order (§3.9):
|
|
1110
|
+
* 1. Blocklist — accent/case-insensitive substring match against the FIRST
|
|
1111
|
+
* customer message (not the draft), one hit per matched term.
|
|
1112
|
+
* 2. Attachment.
|
|
1113
|
+
* 3. Short answer (`candidateAnswer.trim().length < CANDIDATE_MIN_LENGTH`).
|
|
1114
|
+
* 4. Uncertainty markers — first match only.
|
|
1115
|
+
*/
|
|
1116
|
+
declare function runGuardrails(input: RunGuardrailsInput): string[];
|
|
1117
|
+
/**
|
|
1118
|
+
* Reason bucket of a guardrail hit — `blocklist:<term>` all collapse into
|
|
1119
|
+
* `blocklist`. Lives here because this module owns the hit encoding.
|
|
1120
|
+
*/
|
|
1121
|
+
declare function guardrailBucket(hit: string): string;
|
|
1122
|
+
|
|
1123
|
+
/**
|
|
1124
|
+
* A judged candidate reply, as produced by the evaluation agent (agent 4).
|
|
1125
|
+
* @deprecated Legacy `verifyReply` vocabulary — see this module's header
|
|
1126
|
+
* comment. New code reads `AgentProfile.guardrails.params` and the graph
|
|
1127
|
+
* `guardrails` node (T17) instead.
|
|
1128
|
+
*/
|
|
1129
|
+
interface JudgedReply {
|
|
1130
|
+
verdict: EvaluationVerdict;
|
|
1131
|
+
confidence: number;
|
|
1132
|
+
reason: string;
|
|
1133
|
+
}
|
|
1134
|
+
/**
|
|
1135
|
+
* The subset of the legacy settings document `verifyReply` reads. Field
|
|
1136
|
+
* names are the legacy `auto_reply_*` ones on purpose (see module comment).
|
|
1137
|
+
* @deprecated Legacy `verifyReply` vocabulary — see this module's header
|
|
1138
|
+
* comment. New code reads `AgentProfile.guardrails.params` and the graph
|
|
1139
|
+
* `guardrails` node (T17) instead.
|
|
1140
|
+
*/
|
|
1141
|
+
interface AutoReplyGuardSettings {
|
|
1142
|
+
auto_reply_whatsapp_mode?: WhatsappMode;
|
|
1143
|
+
auto_reply_judgeme_escalate_only?: boolean;
|
|
1144
|
+
auto_reply_require_high_triage?: boolean;
|
|
1145
|
+
auto_reply_blocklist?: string[];
|
|
1146
|
+
}
|
|
1147
|
+
/**
|
|
1148
|
+
* @deprecated Legacy `verifyReply` vocabulary — see this module's header
|
|
1149
|
+
* comment. New code reads `AgentProfile.guardrails.params` and the graph
|
|
1150
|
+
* `guardrails` node (T17) instead.
|
|
1151
|
+
*/
|
|
1152
|
+
interface VerifyReplyInput {
|
|
1153
|
+
/** First customer message in the thread (used for blocklist), not the latest. */
|
|
1154
|
+
firstCustomerMessage: string;
|
|
1155
|
+
candidateAnswer: string;
|
|
1156
|
+
hasAttachment: boolean;
|
|
1157
|
+
/**
|
|
1158
|
+
* True when the ticket has at least one WhatsApp message. Combined with
|
|
1159
|
+
* settings.auto_reply_whatsapp_mode, it forces a hold — WhatsApp threads
|
|
1160
|
+
* are usually opened by us, so we never auto-answer them.
|
|
1161
|
+
*/
|
|
1162
|
+
isWhatsapp: boolean;
|
|
1163
|
+
/**
|
|
1164
|
+
* True when the ticket is a Judge.me review notification. Combined with
|
|
1165
|
+
* settings.auto_reply_judgeme_escalate_only, it forces a hold — a review
|
|
1166
|
+
* notification is not a support request, so we never auto-answer it.
|
|
1167
|
+
*/
|
|
1168
|
+
isJudgeme: boolean;
|
|
1169
|
+
/**
|
|
1170
|
+
* True when the ticket customer email matches the configured
|
|
1171
|
+
* `auto_reply_noreply_senders` list — combined by the caller. It forces a
|
|
1172
|
+
* hold: the "customer" is an automated no-reply sender (e.g. Bigblue), so we
|
|
1173
|
+
* never auto-answer it.
|
|
1174
|
+
*/
|
|
1175
|
+
isAutomatedSender: boolean;
|
|
1176
|
+
triageConfidence: 'high' | 'low' | null;
|
|
1177
|
+
/**
|
|
1178
|
+
* Escalation decision from the triage run (agent 2). `true` blocks the
|
|
1179
|
+
* auto-reply outright — a ticket flagged for a human is never auto-answered.
|
|
1180
|
+
* null/undefined = escalation disabled or not executed.
|
|
1181
|
+
*/
|
|
1182
|
+
escalated?: boolean | null;
|
|
1183
|
+
/**
|
|
1184
|
+
* Already-resolved confidence threshold.
|
|
1185
|
+
* The CALLER (worker) resolves the per-category override:
|
|
1186
|
+
* category.auto_reply_min_confidence ?? settings.auto_reply_min_confidence
|
|
1187
|
+
*/
|
|
1188
|
+
minConfidence: number;
|
|
1189
|
+
settings: AutoReplyGuardSettings;
|
|
1190
|
+
/**
|
|
1191
|
+
* Evaluation-agent result (agent 4), produced by processJob when
|
|
1192
|
+
* settings.evaluation_enabled. It is the ONLY source of the send verdict:
|
|
1193
|
+
* absent/null (evaluation disabled, or errored) forces a hold.
|
|
1194
|
+
*/
|
|
1195
|
+
evaluation?: JudgedReply | null;
|
|
1196
|
+
}
|
|
1197
|
+
/**
|
|
1198
|
+
* @deprecated Legacy `verifyReply` vocabulary — see this module's header
|
|
1199
|
+
* comment. New code reads `AgentProfile.guardrails.params` and the graph
|
|
1200
|
+
* `guardrails` node (T17) instead.
|
|
1201
|
+
*/
|
|
1202
|
+
interface VerifyReplyResult {
|
|
1203
|
+
decision: 'send' | 'hold';
|
|
1204
|
+
confidence: number;
|
|
1205
|
+
reason: string;
|
|
1206
|
+
guardrailHits: string[];
|
|
1207
|
+
}
|
|
1208
|
+
/**
|
|
1209
|
+
* Verify whether a candidate reply is safe to send automatically.
|
|
1210
|
+
*
|
|
1211
|
+
* @deprecated Ported verbatim from the legacy fast-response worker (see this
|
|
1212
|
+
* module's header comment) — new code should drive auto-send off the graph
|
|
1213
|
+
* `guardrails` node (T17), built on `runGuardrails`/`guardrailBucket` and
|
|
1214
|
+
* `AgentProfile.guardrails.params`, not off this function's legacy
|
|
1215
|
+
* `auto_reply_*` vocabulary.
|
|
1216
|
+
*
|
|
1217
|
+
* Evaluation order (cheapest first):
|
|
1218
|
+
* 1. Triage pre-gate + escalation pre-gate (no LLM call)
|
|
1219
|
+
* 2. Deterministic guardrails (no LLM call)
|
|
1220
|
+
* 3. Evaluation verdict (agent 4) — mandatory: no verdict, no send
|
|
1221
|
+
* 4. Final decision: send iff verdict ∈ {send, send_and_escalate} AND
|
|
1222
|
+
* confidence >= minConfidence
|
|
1223
|
+
*
|
|
1224
|
+
* This function performs NO LLM call of its own — the verdict is always the
|
|
1225
|
+
* evaluation agent's.
|
|
1226
|
+
*/
|
|
1227
|
+
declare function verifyReply(input: VerifyReplyInput): VerifyReplyResult;
|
|
1228
|
+
|
|
1229
|
+
/**
|
|
1230
|
+
* First customer turn in a conversation, or `null` when there is none. The
|
|
1231
|
+
* blocklist input, and the `subject`/first-message pair `isJudgemeConversation`
|
|
1232
|
+
* matches against.
|
|
1233
|
+
*
|
|
1234
|
+
* Ported from legacy `agent/nodes/shared.ts`, exported from here rather than
|
|
1235
|
+
* from `raw-ticket.ts` (where a differently-shaped `extractFirstCustomerMessage`
|
|
1236
|
+
* used to live, over bare `Message[]`): T17's nodes only ever hold a
|
|
1237
|
+
* `Conversation`, and this module is already where its sibling
|
|
1238
|
+
* `lastCustomerMessage` lives — one entry shape, one home, for both halves
|
|
1239
|
+
* of the same prerequisite.
|
|
1240
|
+
*/
|
|
1241
|
+
declare function firstCustomerMessage(conversation: Conversation): string | null;
|
|
1242
|
+
/**
|
|
1243
|
+
* Last customer turn in a conversation, or `null` when there is none — the
|
|
1244
|
+
* mirror of `firstCustomerMessage`, walking from the end (a plain backward
|
|
1245
|
+
* index loop rather than `[...].reverse().find()`, so a caller that already
|
|
1246
|
+
* runs this once per conversation does not copy the whole array to read one
|
|
1247
|
+
* element). Exported (T15 review E1): legacy documents this as a shared
|
|
1248
|
+
* prerequisite of the whatsapp pre-gates AND of `triage` (T17's first
|
|
1249
|
+
* consumer), so declaring it module-private here would force T17 to
|
|
1250
|
+
* redeclare it.
|
|
1251
|
+
*/
|
|
1252
|
+
declare function lastCustomerMessage(conversation: Conversation): string | null;
|
|
1253
|
+
/**
|
|
1254
|
+
* Whatsapp spec §5.1 alone — deterministic, no LLM: the customer asked to
|
|
1255
|
+
* never be contacted again. Matched against the LAST customer message (the
|
|
1256
|
+
* opt-out can arrive at any point of a multi-turn thread, not just the
|
|
1257
|
+
* opening one).
|
|
1258
|
+
*
|
|
1259
|
+
* Split out from `channelPreGates` because the graph evaluates it EARLIER
|
|
1260
|
+
* than its sibling: a STOP has to outrank the `no_reply_needed` exit, which
|
|
1261
|
+
* applies no tag and would leave the opt-out no trace (T17/T18's concern).
|
|
1262
|
+
*/
|
|
1263
|
+
declare function stopOptOut(conversation: Conversation): string[];
|
|
1264
|
+
/**
|
|
1265
|
+
* The whatsapp spec §5.1/§5.3 pre-gates, pure over `Conversation` alone (no
|
|
1266
|
+
* profile params: unlike `whatsapp`, neither is configurable). Both evaluate
|
|
1267
|
+
* only in WhatsApp and both return at most one hit each, in a fixed order
|
|
1268
|
+
* (`whatsapp_stop` before `not_customer_turn`).
|
|
1269
|
+
*/
|
|
1270
|
+
declare function channelPreGates(conversation: Conversation): string[];
|
|
1271
|
+
/**
|
|
1272
|
+
* Judge.me review-notification detector — the same two patterns as
|
|
1273
|
+
* `isJudgemeTicket` (`raw-ticket.ts`), adapted to take domain data (subject +
|
|
1274
|
+
* first customer message) instead of a raw Gorgias ticket, which a node may
|
|
1275
|
+
* never read (§9). Ported verbatim from legacy `agent/nodes/shared.ts`.
|
|
1276
|
+
*/
|
|
1277
|
+
declare function isJudgemeConversation(subject: string | null, firstMessage: string | null): boolean;
|
|
1278
|
+
/**
|
|
1279
|
+
* No-reply sender detector — the same three match forms (exact / `@domain`
|
|
1280
|
+
* suffix / `local@` prefix) as `isAutomatedSenderTicket` (`raw-ticket.ts`),
|
|
1281
|
+
* adapted to a plain email string instead of a raw ticket. Ported verbatim
|
|
1282
|
+
* from legacy `agent/nodes/shared.ts`.
|
|
1283
|
+
*
|
|
1284
|
+
* NOT a thin wrapper over `isAutomatedSenderTicket`, and vice versa: the two
|
|
1285
|
+
* already disagreed in the legacy codebase for a malformed entry like a bare
|
|
1286
|
+
* `'@'`. This function picks ONE match form per entry and returns as soon as
|
|
1287
|
+
* it does (`if (e.startsWith('@')) return …`) — if that form doesn't match,
|
|
1288
|
+
* the entry is done, even though the OTHER forms might. `isAutomatedSenderTicket`
|
|
1289
|
+
* instead falls through to try the next form when the current one fails. For
|
|
1290
|
+
* entry `'@'` and an email itself starting with `@`, that difference flips
|
|
1291
|
+
* the result. Ported as-is rather than silently reconciled — reconciling
|
|
1292
|
+
* would have to pick a winner the legacy code never did.
|
|
1293
|
+
*/
|
|
1294
|
+
declare function isAutomatedSenderEmail(email: string | null, senders: string[]): boolean;
|
|
1295
|
+
|
|
1296
|
+
/**
|
|
1297
|
+
* Evaluation succeeded, the verdict is sendable, confidence clears the
|
|
1298
|
+
* profile's bar, and any follow-up it demands is a feature this profile has
|
|
1299
|
+
* turned on.
|
|
1300
|
+
*/
|
|
1301
|
+
declare function isSendable(verdict: Verdict | null, profile: AgentProfile): boolean;
|
|
1302
|
+
/**
|
|
1303
|
+
* Whether the ticket may even be offered to auto-send: the tenant opted in,
|
|
1304
|
+
* this category opted in, there is an address to send from, and a verdict
|
|
1305
|
+
* was actually produced. Takes `deps` rather than just `profile` (unlike the
|
|
1306
|
+
* spec's pseudocode) because category opt-in is resolved by the caller into
|
|
1307
|
+
* `NodeDeps.category`, not carried on the profile itself.
|
|
1308
|
+
*
|
|
1309
|
+
* Whatsapp spec §9.1's own table is explicit that `draft_only` NEVER
|
|
1310
|
+
* auto-sends ("le brouillon est produit (`ready`), **jamais** envoyé
|
|
1311
|
+
* automatiquement") — `draft_only` is excluded here explicitly, on purpose.
|
|
1312
|
+
*
|
|
1313
|
+
* `escalate_only` is deliberately NOT excluded here, even though it also
|
|
1314
|
+
* never sends: it is caught downstream instead, by the `whatsapp` guardrail
|
|
1315
|
+
* hit (reached exactly because this predicate stays true), which produces
|
|
1316
|
+
* `guardrail_hold` + the escalation tag — the audit trail the spec wants
|
|
1317
|
+
* ("un humain acte l'opt-out"). Excluding `escalate_only` here too would
|
|
1318
|
+
* make that hit unreachable (this predicate gates entry to the `guardrails`
|
|
1319
|
+
* node) and silently swap every `escalate_only` WhatsApp ticket's outcome
|
|
1320
|
+
* from `guardrail_hold`+tag to `ready`+no tag — losing the tag is a bigger
|
|
1321
|
+
* behaviour change than the one this predicate closes.
|
|
1322
|
+
*
|
|
1323
|
+
* Whatsapp spec §4.4: `autoSend.senderEmail` is required in EMAIL mode only
|
|
1324
|
+
* — a WhatsApp note has no "from" email address to send with. The sender
|
|
1325
|
+
* exemption below is scoped to `whatsappMode === 'auto_reply'` specifically
|
|
1326
|
+
* — the ONE mode where a WhatsApp note is actually the reply that would go
|
|
1327
|
+
* out — NOT to every WhatsApp ticket, to keep `escalate_only` iso-behaviour
|
|
1328
|
+
* to the byte.
|
|
1329
|
+
*/
|
|
1330
|
+
declare function isAutoSendEligible(state: TicketRunState, deps: Pick<NodeDeps, 'profile' | 'category'>): boolean;
|
|
1331
|
+
/**
|
|
1332
|
+
* Whether the draft gets a correction pass (one pass maximum, §6.1).
|
|
1333
|
+
*
|
|
1334
|
+
* `send_and_escalate` is SENDABLE (I6) and therefore never revised: the
|
|
1335
|
+
* reply goes out and a human follows up afterwards, so rewriting it would
|
|
1336
|
+
* replace an answer the judge already accepted. An evaluation in `error` is
|
|
1337
|
+
* not revised either — fail-safe means needs_human (I5), and there is no
|
|
1338
|
+
* judgement to correct against.
|
|
1339
|
+
*/
|
|
1340
|
+
declare function needsRevision(verdict: Verdict | null, profile: AgentProfile, reviseCount: number): boolean;
|
|
1341
|
+
|
|
1342
|
+
/** The `generated-response` record's `status` field (§3.4). */
|
|
1343
|
+
declare const GENERATED_RESPONSE_STATUSES: readonly ["pending", "ready", "sending", "sent", "failed", "no_reply_needed", "invalidated", "expired"];
|
|
1344
|
+
type GeneratedResponseStatus = (typeof GENERATED_RESPONSE_STATUSES)[number];
|
|
1345
|
+
/**
|
|
1346
|
+
* `status` lives in `AppRecord` JSONB (§3.4), so it reaches this module as an
|
|
1347
|
+
* untrusted string: a record written by another app version, or hand-edited,
|
|
1348
|
+
* can carry anything. Parse at that boundary rather than dereferencing the
|
|
1349
|
+
* transition table blindly — same reason `domain/evaluation-verdict.ts` ships
|
|
1350
|
+
* `isEvaluationVerdict`.
|
|
1351
|
+
*/
|
|
1352
|
+
declare function isGeneratedResponseStatus(value: unknown): value is GeneratedResponseStatus;
|
|
1353
|
+
declare function canTransition(from: GeneratedResponseStatus, to: GeneratedResponseStatus): boolean;
|
|
1354
|
+
/** A status with no outgoing transition — nothing may ever move it again. */
|
|
1355
|
+
declare function isTerminalStatus(status: GeneratedResponseStatus): boolean;
|
|
1356
|
+
declare class InvalidStatusTransitionError extends Error {
|
|
1357
|
+
readonly from: GeneratedResponseStatus;
|
|
1358
|
+
readonly to: GeneratedResponseStatus;
|
|
1359
|
+
constructor(from: GeneratedResponseStatus, to: GeneratedResponseStatus);
|
|
1360
|
+
}
|
|
1361
|
+
/** Throws {@link InvalidStatusTransitionError} unless `canTransition(from, to)`. */
|
|
1362
|
+
declare function assertTransition(from: GeneratedResponseStatus, to: GeneratedResponseStatus): void;
|
|
1363
|
+
/**
|
|
1364
|
+
* §3.4: `openTicketKey` equals the ticket id while the record is still open
|
|
1365
|
+
* (`pending`, `ready`, `sending`), and is cleared in a terminal status — the
|
|
1366
|
+
* Postgres-unique-index equivalent of the legacy "one open job per ticket"
|
|
1367
|
+
* guarantee (NULLs are distinct under a unique index, so clearing the key
|
|
1368
|
+
* frees the ticket for a fresh `pending` record).
|
|
1369
|
+
*
|
|
1370
|
+
* Derived from `isTerminalStatus` rather than a second hardcoded status set:
|
|
1371
|
+
* "open" and "terminal" are already the same partition this module tracks
|
|
1372
|
+
* for transitions, and duplicating that partition here is exactly the kind
|
|
1373
|
+
* of drift this module exists to prevent.
|
|
1374
|
+
*/
|
|
1375
|
+
declare function openTicketKeyFor(status: GeneratedResponseStatus, ticketId: string): string | null;
|
|
1376
|
+
/**
|
|
1377
|
+
* The sweep's `sending -> ready` reclaim (§3.5), as a patch rather than a bare
|
|
1378
|
+
* status.
|
|
1379
|
+
*
|
|
1380
|
+
* The "**jamais de ré-émission**" promise is carried by `autoSendDecision`,
|
|
1381
|
+
* NOT by the status: a record back at `ready` *without* the hold is a
|
|
1382
|
+
* perfectly legal claim target for `act`/`handle-approval` via
|
|
1383
|
+
* `ifMatch:{status:'ready'}`, so a sweep that sets the status and forgets the
|
|
1384
|
+
* flag re-sends the reply — the one outcome §3.5 forbids in bold, and one
|
|
1385
|
+
* `assertTransition('sending','ready')` would happily wave through. Deriving
|
|
1386
|
+
* the pair here means T22 cannot express the reclaim without the hold.
|
|
1387
|
+
*/
|
|
1388
|
+
declare function reclaimStalledSend(): {
|
|
1389
|
+
status: Extract<GeneratedResponseStatus, 'ready'>;
|
|
1390
|
+
autoSendDecision: 'hold';
|
|
1391
|
+
};
|
|
1392
|
+
|
|
1393
|
+
/** One reference tag's target config, as read off T5's `PromptDetail.config`. */
|
|
1394
|
+
interface RawPromptConfig {
|
|
1395
|
+
model?: string;
|
|
1396
|
+
temperature?: number;
|
|
1397
|
+
}
|
|
1398
|
+
/** Raw (uncompiled, composition-unresolved) prompt content read at a given name+label/version. */
|
|
1399
|
+
interface RawPrompt {
|
|
1400
|
+
version: number;
|
|
1401
|
+
content: string;
|
|
1402
|
+
/**
|
|
1403
|
+
* Model config carried by the platform prompt, when the endpoint returns
|
|
1404
|
+
* one. Optional/absent (not just `null`) so every existing raw literal
|
|
1405
|
+
* built before this field existed still type-checks unchanged.
|
|
1406
|
+
*/
|
|
1407
|
+
config?: RawPromptConfig | null;
|
|
1408
|
+
}
|
|
1409
|
+
/**
|
|
1410
|
+
* Seam onto T5's `ctx.api.prompts.get(name, {label|version, resolve:false})`.
|
|
1411
|
+
* May throw (network error, 404, unconfigured Langfuse, …) — the resolver
|
|
1412
|
+
* treats any rejection as a level-1 miss and falls through the ladder. T21
|
|
1413
|
+
* supplies the real adapter; `testing/fakes` supplies a test double.
|
|
1414
|
+
*/
|
|
1415
|
+
interface PlatformPromptReader {
|
|
1416
|
+
get(name: string, ref: {
|
|
1417
|
+
label?: string;
|
|
1418
|
+
version?: number;
|
|
1419
|
+
}): Promise<RawPrompt>;
|
|
1420
|
+
}
|
|
1421
|
+
/** One entry of the `prompt-cache` mirror (§3.4) — always RESOLVED content, never a raw reference tag. */
|
|
1422
|
+
interface PromptCacheEntry {
|
|
1423
|
+
content: string;
|
|
1424
|
+
version: number;
|
|
1425
|
+
}
|
|
1426
|
+
/**
|
|
1427
|
+
* Seam onto the `prompt-cache` record (T20's schema, T21's adapter). Both
|
|
1428
|
+
* methods are best-effort from the resolver's point of view — a rejection
|
|
1429
|
+
* from either is caught and treated as a miss/no-op, exactly like legacy's
|
|
1430
|
+
* Mongo cache: a `prompt-cache` outage must never block the LLM path.
|
|
1431
|
+
*/
|
|
1432
|
+
interface PromptCachePort {
|
|
1433
|
+
read(key: string): Promise<PromptCacheEntry | null>;
|
|
1434
|
+
write(key: string, entry: PromptCacheEntry): Promise<void>;
|
|
1435
|
+
}
|
|
1436
|
+
/**
|
|
1437
|
+
* One silent-degradation event (post-review E). `stage` names the point in
|
|
1438
|
+
* the ladder that gave up on the "real" answer and returned something safe
|
|
1439
|
+
* instead; `name` is the prompt/reference name involved; `reason` is a
|
|
1440
|
+
* human-readable cause, not a typed error (the kit has no logging/error
|
|
1441
|
+
* taxonomy to spend here — that is T21's job once this reaches a real
|
|
1442
|
+
* logger).
|
|
1443
|
+
*/
|
|
1444
|
+
interface PromptDegradedEvent {
|
|
1445
|
+
stage: 'platform-unavailable' | 'cache-unavailable' | 'composition-target-missing' | 'composition-target-forbidden' | 'composition-cycle' | 'composition-depth-exceeded';
|
|
1446
|
+
name: string;
|
|
1447
|
+
reason: string;
|
|
1448
|
+
}
|
|
1449
|
+
interface PromptResolverDeps {
|
|
1450
|
+
platform: PlatformPromptReader;
|
|
1451
|
+
cache: PromptCachePort;
|
|
1452
|
+
/** Memory-cache TTL override, ms. Defaults to 60 000 (§3.7). */
|
|
1453
|
+
ttlMs?: number;
|
|
1454
|
+
/** Injectable clock for the memory cache, defaults to `Date.now`. */
|
|
1455
|
+
now?: () => number;
|
|
1456
|
+
/** Fires at every silent-degradation point in the ladder (post-review E). */
|
|
1457
|
+
onDegraded?: (event: PromptDegradedEvent) => void;
|
|
1458
|
+
}
|
|
1459
|
+
/** Builds a `PromptPort` implementing §3.7's three-level fallback ladder. */
|
|
1460
|
+
declare function createPromptResolver(deps: PromptResolverDeps): PromptPort;
|
|
1461
|
+
|
|
1462
|
+
interface PromptReference {
|
|
1463
|
+
name: string;
|
|
1464
|
+
version?: number;
|
|
1465
|
+
label?: string;
|
|
1466
|
+
raw: string;
|
|
1467
|
+
}
|
|
1468
|
+
/** Parse every well-formed reference tag out of `content`, in order of appearance. */
|
|
1469
|
+
declare function parseReferences(content: string): PromptReference[];
|
|
1470
|
+
/**
|
|
1471
|
+
* Cheap synchronous check for "does this content contain any reference tag".
|
|
1472
|
+
* Used by the write-through cache guard (`resolver.ts`) to decide whether
|
|
1473
|
+
* raw content is safe to mirror into the `prompt-cache` record — a fresh
|
|
1474
|
+
* `new RegExp` avoids mutating the shared, stateful `REF_RE.lastIndex`.
|
|
1475
|
+
*/
|
|
1476
|
+
declare function hasReferences(content: string): boolean;
|
|
1477
|
+
|
|
1478
|
+
/**
|
|
1479
|
+
* Slot → Langfuse prompt name resolution (spec §3.7).
|
|
1480
|
+
*
|
|
1481
|
+
* Every kit slot resolves to a Langfuse name via `config.promptNames`
|
|
1482
|
+
* (explicit override) or else `<promptPrefix><slot>` — D-LF: no namespacing,
|
|
1483
|
+
* no migration, the resolved name is used against the legacy Langfuse
|
|
1484
|
+
* project's prompts exactly as they already exist.
|
|
1485
|
+
*
|
|
1486
|
+
* `experience-client` passes `promptPrefix: ''`, so its slots resolve to the
|
|
1487
|
+
* bare legacy names (`triage`, `escalation`, `shared/style-email`, …) with
|
|
1488
|
+
* zero Langfuse writes at migration time. A later audience (`pro-sante`)
|
|
1489
|
+
* passes `promptPrefix: 'pro-sante/'`, reproducing the legacy's own
|
|
1490
|
+
* multi-tenant `<key>/<node>` convention.
|
|
1491
|
+
*/
|
|
1492
|
+
/** The seven kit slots §3.7 names. Agent prompts (`agent.promptName`) are NOT a slot — they live on the `agent` record, resolved by its own `PromptRef`, never through this table. */
|
|
1493
|
+
declare const PROMPT_SLOTS: readonly ["triage", "escalation", "evaluation", "suggest", "diff-analysis", "shared/style-email", "shared/style-whatsapp"];
|
|
1494
|
+
type PromptSlot = (typeof PROMPT_SLOTS)[number];
|
|
1495
|
+
/**
|
|
1496
|
+
* The keys `config.defaults.prompts` actually honours (M7, T25 review) —
|
|
1497
|
+
* deliberately NOT `PromptSlot`: `shared/style-email`/`shared/style-whatsapp`
|
|
1498
|
+
* are two `PromptSlot`s nothing ever reads a fallback for (they resolve by
|
|
1499
|
+
* bare NAME off the settings fields' own defaults, never through a
|
|
1500
|
+
* `PromptRef.fallback`), so accepting them here silently drops whatever a
|
|
1501
|
+
* caller sets. `revise` is the opposite gap: not a `PromptSlot` at all, yet
|
|
1502
|
+
* the one node `buildPromptsTable` DOES bind a `PromptRef` for — before this
|
|
1503
|
+
* type existed, a caller had no way to express its fallback under a Langfuse
|
|
1504
|
+
* outage with a cold cache, the one resolved prompt §3.7's level 3 leaves
|
|
1505
|
+
* unreachable.
|
|
1506
|
+
*/
|
|
1507
|
+
type PromptFallbackSlot = Exclude<PromptSlot, 'shared/style-email' | 'shared/style-whatsapp'> | 'revise';
|
|
1508
|
+
interface PromptNameConfig {
|
|
1509
|
+
/**
|
|
1510
|
+
* Required, not defaulted (H3, T25 review): §4's checklist for a new
|
|
1511
|
+
* audience always passes it explicitly (`promptPrefix: '<slug>/'`), and
|
|
1512
|
+
* `experience-client` must say `promptPrefix: ''` out loud rather than
|
|
1513
|
+
* omit the field — an omission used to resolve every slot to the BARE
|
|
1514
|
+
* legacy name (`triage`, not `pro-sante/triage`), silently pointing a new
|
|
1515
|
+
* audience's triage/escalation/evaluation at experience-client's live
|
|
1516
|
+
* production prompts, with no error to reveal the mistake (the allowlist
|
|
1517
|
+
* is derived from the same default, so nothing 403s either).
|
|
1518
|
+
*/
|
|
1519
|
+
promptPrefix: string;
|
|
1520
|
+
promptNames?: Partial<Record<PromptSlot, string>>;
|
|
1521
|
+
/**
|
|
1522
|
+
* §3.2's `config.defaults.prompts` — the level-3 in-code fallback TEXT
|
|
1523
|
+
* (`PromptRef.fallback`, §3.7 point 3) a caller can override per slot,
|
|
1524
|
+
* read by `buildPromptsTable` (triage/escalation/evaluation/revise) and
|
|
1525
|
+
* by `suggest-prompt`/`run-diff-analysis`'s own meta-prompt constants
|
|
1526
|
+
* (`suggest`/`diff-analysis`). Typed as `PromptFallbackSlot`, not
|
|
1527
|
+
* `PromptSlot` (M7): the accepted key set must match what is actually
|
|
1528
|
+
* honoured in both directions, not just default to every §3.7 slot name.
|
|
1529
|
+
*/
|
|
1530
|
+
defaults?: {
|
|
1531
|
+
prompts?: Partial<Record<PromptFallbackSlot, string>>;
|
|
1532
|
+
};
|
|
1533
|
+
}
|
|
1534
|
+
/** Resolve one slot to its Langfuse prompt name for a given `buildSupportPipeline` config. */
|
|
1535
|
+
declare function resolvePromptName(slot: PromptSlot, config: PromptNameConfig): string;
|
|
1536
|
+
/**
|
|
1537
|
+
* `revise` has no `PROMPT_SLOTS` entry (see the module doc — it is not one
|
|
1538
|
+
* of the seven §3.7 slots) but resolves via the exact same
|
|
1539
|
+
* `promptNames?.revise ?? <prefix>revise` pattern the other slots use. One
|
|
1540
|
+
* function so `buildPromptsTable` (the graph's own consumer) and
|
|
1541
|
+
* `mergeRole`'s `role.prompts` allowlist (T25) cannot drift apart on how
|
|
1542
|
+
* that name is computed.
|
|
1543
|
+
*/
|
|
1544
|
+
declare function resolveReviseName(config: PromptNameConfig): string;
|
|
1545
|
+
|
|
1546
|
+
/**
|
|
1547
|
+
* `category` (ex-`Category`) — spec §3.4.
|
|
1548
|
+
*
|
|
1549
|
+
* `tagName` is matched exactly, case-sensitively, against Gorgias tags — it is
|
|
1550
|
+
* NOT normalised anywhere in this definition, on purpose: the handler that
|
|
1551
|
+
* applies tags (T22+) must compare byte-for-byte with what Gorgias sends back.
|
|
1552
|
+
*
|
|
1553
|
+
* The legacy `auto_reply_min_confidence` field is deliberately not ported —
|
|
1554
|
+
* the spec records it as already neutralised upstream in the legacy system.
|
|
1555
|
+
*/
|
|
1556
|
+
|
|
1557
|
+
declare function buildCategoryRecord(slug: string): ObjectDef;
|
|
1558
|
+
|
|
1559
|
+
/** `category-group` — spec §3.4. */
|
|
1560
|
+
|
|
1561
|
+
declare const categoryGroupRecord: ObjectDef;
|
|
1562
|
+
|
|
1563
|
+
/**
|
|
1564
|
+
* `agent` (ex-`ModelConfig`) — spec §3.4.
|
|
1565
|
+
*
|
|
1566
|
+
* `defaultKey` is the equivalent of the legacy partial unique index: it is
|
|
1567
|
+
* only ever set to `'default'` when `status === 'default'`, and left absent
|
|
1568
|
+
* (`null`) otherwise, so a unique index on it enforces "at most one default
|
|
1569
|
+
* agent" the same way a Postgres unique index treats NULLs as distinct
|
|
1570
|
+
* (already the pattern `generated-response.openTicketKey` uses below).
|
|
1571
|
+
* Populating it correctly is a write-handler concern (T22+), not this
|
|
1572
|
+
* definition's.
|
|
1573
|
+
*
|
|
1574
|
+
* `reasoningEffort` reuses `ReasoningEffort` from `../domain/reasoning` — the
|
|
1575
|
+
* kit's one vocabulary for this concept — rather than a second hardcoded
|
|
1576
|
+
* option list.
|
|
1577
|
+
*
|
|
1578
|
+
* Deletion detaching `category.agentId` (the legacy Mongoose hook) is a
|
|
1579
|
+
* delete-handler rule (T22+), not expressed here.
|
|
1580
|
+
*/
|
|
1581
|
+
|
|
1582
|
+
declare const AGENT_STATUSES: readonly ["default", "available", "archived"];
|
|
1583
|
+
type AgentStatus = (typeof AGENT_STATUSES)[number];
|
|
1584
|
+
/**
|
|
1585
|
+
* The provider an agent (and every graph node built from settings) uses
|
|
1586
|
+
* unless one is stated. Named here, next to the field it defaults, so
|
|
1587
|
+
* `settings/to-profile.ts` fills `nodes.*.provider` with the same value the
|
|
1588
|
+
* record does instead of a second literal.
|
|
1589
|
+
*/
|
|
1590
|
+
declare const DEFAULT_LLM_PROVIDER = "openai";
|
|
1591
|
+
declare const agentRecord: ObjectDef;
|
|
1592
|
+
|
|
1593
|
+
/**
|
|
1594
|
+
* `triage-decision` (ex-`TriageDecision`) — spec §3.4.
|
|
1595
|
+
*
|
|
1596
|
+
* `decidedAt` is indexed because the 24h/7d stat windows filter and bucket on
|
|
1597
|
+
* this DATA field, not on the system `createdAt` — a run replayed or
|
|
1598
|
+
* backfilled keeps the decision's own timestamp.
|
|
1599
|
+
*/
|
|
1600
|
+
|
|
1601
|
+
declare function buildTriageDecisionRecord(slug: string): ObjectDef;
|
|
1602
|
+
|
|
1603
|
+
/**
|
|
1604
|
+
* `generated-response` (ex-`FastResponse`) — spec §3.4. Both the send queue
|
|
1605
|
+
* and the response cache.
|
|
1606
|
+
*
|
|
1607
|
+
* `status`'s option list is `GENERATED_RESPONSE_STATUSES` from
|
|
1608
|
+
* `../status/machine` — the single source of truth T16 already built for the
|
|
1609
|
+
* status vocabulary and its terminal/open partition — rather than a second
|
|
1610
|
+
* hardcoded list that could drift from it.
|
|
1611
|
+
*
|
|
1612
|
+
* `openTicketKey` reconstitutes the legacy "one open job per ticket"
|
|
1613
|
+
* guarantee as a Postgres unique index (NULLs are distinct): it is
|
|
1614
|
+
* `openTicketKeyFor(status, ticketId)` at write time (a T22+ handler
|
|
1615
|
+
* concern), so this definition intentionally does NOT restate which statuses
|
|
1616
|
+
* count as "open" — it only declares the field and its unique index.
|
|
1617
|
+
*
|
|
1618
|
+
* `autoSendDecision` is the field `reclaimStalledSend()` (T16) writes into
|
|
1619
|
+
* alongside `status: 'ready'` on the sweep's stalled-send reclaim.
|
|
1620
|
+
*
|
|
1621
|
+
* `expiresAt` is non-nullable: it is `generatedAt + responseTtlMinutes`,
|
|
1622
|
+
* known at creation time, and the sweep (`ready` expired -> `expired`, T22)
|
|
1623
|
+
* plus the extension's TTL check both read it unconditionally — a null there
|
|
1624
|
+
* would be a row that never expires.
|
|
1625
|
+
*
|
|
1626
|
+
* The JSON LIST fields (`sources`, `tracedInput`, `guardrailHits`,
|
|
1627
|
+
* `servedTo`) are non-nullable with a `[]` default, so no reader has to
|
|
1628
|
+
* distinguish "null" from "empty" before iterating; the single-object
|
|
1629
|
+
* `verdict` stays nullable, where `null` really does mean "not evaluated".
|
|
1630
|
+
*
|
|
1631
|
+
* T22 additions (all nullable — absent until the field's own write path
|
|
1632
|
+
* runs):
|
|
1633
|
+
* - `generatedMessageCount`/`generatedLastMessageAt` — a snapshot of
|
|
1634
|
+
* `Conversation.messageCount`/`lastMessageAt` taken by `process-response`
|
|
1635
|
+
* right before `runTicket`'s resumed run. `handle-approval` rebuilds a
|
|
1636
|
+
* placeholder `Conversation` for the `act` node's `generatedFrom`
|
|
1637
|
+
* argument out of exactly these two fields (plus `channel`) — see
|
|
1638
|
+
* `functions/handle-approval.ts` for why `act` never reads anything else
|
|
1639
|
+
* off that snapshot. This is a "close enough" generation-time reading,
|
|
1640
|
+
* not a live one: `act` always re-reads the conversation for real before
|
|
1641
|
+
* posting (I8), so a slightly stale baseline here only affects whether
|
|
1642
|
+
* THAT re-read counts as diverged, never send safety itself.
|
|
1643
|
+
* - `sendingAt` — when the record entered `status: 'sending'` (written by
|
|
1644
|
+
* the claim in `functions/claim-commit.ts`). Nothing else on this record
|
|
1645
|
+
* timestamps a status transition, and `sweep` needs to know how long a
|
|
1646
|
+
* `sending` row has been stuck to reclaim it (§3.5's 30-minute rule).
|
|
1647
|
+
*/
|
|
1648
|
+
|
|
1649
|
+
declare function buildGeneratedResponseRecord(slug: string): ObjectDef;
|
|
1650
|
+
|
|
1651
|
+
/** `response-comparison` (ex-`ResponseComparison`) — spec §3.4. */
|
|
1652
|
+
|
|
1653
|
+
declare function buildResponseComparisonRecord(slug: string): ObjectDef;
|
|
1654
|
+
|
|
1655
|
+
/** `evaluation` (ex-`Evaluation`) — spec §3.4. No indexes named for this record. */
|
|
1656
|
+
|
|
1657
|
+
declare function buildEvaluationRecord(slug: string): ObjectDef;
|
|
1658
|
+
|
|
1659
|
+
/**
|
|
1660
|
+
* `diff-analysis` (ex-`DiffAnalysis`) — spec §3.4.
|
|
1661
|
+
*
|
|
1662
|
+
* `uniqueKey` is `<agentId>::<promptName>::<promptVersion>`, computed by the
|
|
1663
|
+
* write handler (T22+) — this definition only declares the field and its
|
|
1664
|
+
* unique index, the equivalent of the legacy composite uniqueness.
|
|
1665
|
+
*/
|
|
1666
|
+
|
|
1667
|
+
/** `<agentId>::<promptName>::<promptVersion>` — spec §3.4. */
|
|
1668
|
+
declare function diffAnalysisUniqueKey(agentId: string, promptName: string, promptVersion: number): string;
|
|
1669
|
+
declare function buildDiffAnalysisRecord(slug: string): ObjectDef;
|
|
1670
|
+
|
|
1671
|
+
/**
|
|
1672
|
+
* `ObjectDef` plus the one manifest-level `records[]` property it doesn't
|
|
1673
|
+
* carry itself: `exposedToApps` (P2-10 bilateral consent, §3.4). Only
|
|
1674
|
+
* `pipeline-state` uses it — it is the kit's sole cross-app contact point
|
|
1675
|
+
* (§4's overlap warning) — but the type is shared so every record definition
|
|
1676
|
+
* in this directory has a single declared shape.
|
|
1677
|
+
*/
|
|
1678
|
+
type RecordDef = ObjectDef & {
|
|
1679
|
+
exposedToApps?: string[];
|
|
1680
|
+
};
|
|
1681
|
+
|
|
1682
|
+
declare const pipelineStateRecord: RecordDef;
|
|
1683
|
+
|
|
1684
|
+
/**
|
|
1685
|
+
* `prompt-cache` (ex-`PromptCache`) — spec §3.4, level-2 fallback of the
|
|
1686
|
+
* prompt ladder (§3.7).
|
|
1687
|
+
*
|
|
1688
|
+
* `config JSON?` — added beyond the spec's literal field list, on T19's
|
|
1689
|
+
* explicit deferral: the legacy cache carried the model config (not just the
|
|
1690
|
+
* compiled template), so invariant I16 ("levels 2/3 keep working through a
|
|
1691
|
+
* Langfuse outage") holds for the *prompt text* but not for the *config* a
|
|
1692
|
+
* caller needs alongside it — levels 2 and 3 of the resolver (T19) return
|
|
1693
|
+
* `config: null` today. Adding the column here is the minimal step: it makes
|
|
1694
|
+
* the record ABLE to carry a config without deciding its shape or wiring it
|
|
1695
|
+
* into the resolver. Follow-up (not T20): change `prompts/resolver.ts` to
|
|
1696
|
+
* read and write this column, and settle what "config" means for a cache row
|
|
1697
|
+
* (presumably the same `{model, reasoning}` shape used by `settings.nodes`).
|
|
1698
|
+
*/
|
|
1699
|
+
|
|
1700
|
+
declare const promptCacheRecord: ObjectDef;
|
|
1701
|
+
|
|
1702
|
+
/**
|
|
1703
|
+
* A relation's `targetRef` names the app the target record lives in
|
|
1704
|
+
* (`app:<slug>/<objectKey>`, resolved by `app-records.service.ts`), and the
|
|
1705
|
+
* kit is never installed under the slug `support-kit`: it is spread into
|
|
1706
|
+
* `experience-client`, `pro-sante`, … Every record carrying a relation is
|
|
1707
|
+
* therefore built per consuming app, from that app's own slug (§3.2's
|
|
1708
|
+
* `config.slug`), never from a literal.
|
|
1709
|
+
*/
|
|
1710
|
+
declare function targetRefFor(slug: string, objectKey: string): string;
|
|
1711
|
+
|
|
1712
|
+
/**
|
|
1713
|
+
* All 10 records of §3.4, in the order the spec lists them, bound to the
|
|
1714
|
+
* consuming app's `slug` — the single assembly point `buildSupportPipeline`
|
|
1715
|
+
* (T25) spreads into a manifest.
|
|
1716
|
+
*
|
|
1717
|
+
* Every record/field/index `universalIdentifier` is additionally scoped to
|
|
1718
|
+
* `slug` via `scopeRecordToApp` (B1, T25 review): `ids.ts`'s constants are
|
|
1719
|
+
* stable per-record keys, not final manifest uids — two different consuming
|
|
1720
|
+
* apps installing this kit must never publish the same
|
|
1721
|
+
* `AppEntity.universalIdentifier` (unique platform-wide).
|
|
1722
|
+
*/
|
|
1723
|
+
declare function buildSupportKitRecords(slug: string): RecordDef[];
|
|
1724
|
+
|
|
1725
|
+
/**
|
|
1726
|
+
* Settings fields (spec §3.6) — replaces the legacy `AgentProfile` +
|
|
1727
|
+
* `AppSettings`. Assembled into a consuming app's manifest `settings.fields`.
|
|
1728
|
+
*
|
|
1729
|
+
* `sourceViewId` deliberately has NO `default` — §0 (D-EXT arbitration) and
|
|
1730
|
+
* §3.6 both insist: it is the field that separates tickets between apps
|
|
1731
|
+
* sharing one Gorgias connection, so a default would silently let two apps
|
|
1732
|
+
* observe the same view. `validateSettings` (`./validate`) is what enforces
|
|
1733
|
+
* this at read time; this file only declares the field shape.
|
|
1734
|
+
*
|
|
1735
|
+
* Several `default`s are not spelled out in the spec (the tag/prompt fields
|
|
1736
|
+
* carry an explicit legacy default, and so do `batchLimit` (30) and
|
|
1737
|
+
* `triageIntervalMinutes` (15), both stated by §3.5/§3.6). Where the spec is
|
|
1738
|
+
* silent, this file defaults booleans to `false` (every switch here is an
|
|
1739
|
+
* opt-in kill-switch), `whatsappMode` to `DEFAULT_WHATSAPP_MODE` (the most
|
|
1740
|
+
* conservative channel behaviour) and `guardrailsActive` to the whole
|
|
1741
|
+
* catalogue (default-deny sending, not default-allow). `nodes` carries no
|
|
1742
|
+
* default at all — see the field itself. None of these is enforced by
|
|
1743
|
+
* `validateSettings`, so a SettingsPage can still override them per-app.
|
|
1744
|
+
*/
|
|
1745
|
+
|
|
1746
|
+
declare const SUPPORT_KIT_SETTINGS_FIELDS: SettingsField[];
|
|
1747
|
+
|
|
1748
|
+
/**
|
|
1749
|
+
* `validateSettings` — spec §3.6, single point of DRY validation shared by
|
|
1750
|
+
* the SettingsPage and every handler.
|
|
1751
|
+
*
|
|
1752
|
+
* Returns a plain list of issues rather than throwing: a SettingsPage maps
|
|
1753
|
+
* `issues` by `key` to show a per-field error, and a handler simply checks
|
|
1754
|
+
* `issues.length > 0` to refuse a run — one shape, two callers, no
|
|
1755
|
+
* try/catch-driven control flow on either side.
|
|
1756
|
+
*/
|
|
1757
|
+
/**
|
|
1758
|
+
* Every issue `validateSettings` can raise, by its own `key` — a closed
|
|
1759
|
+
* union, not `string` (T27 rework, pass 2 of 2): `ui/shared/
|
|
1760
|
+
* settings-issue-labels.ts`'s `SETTINGS_ISSUE_LABELS` is keyed on this same
|
|
1761
|
+
* type, so a new issue this function starts raising without a matching
|
|
1762
|
+
* French translation is now a COMPILE ERROR in that map, not a silent
|
|
1763
|
+
* English leak an operator discovers on a live settings page.
|
|
1764
|
+
*/
|
|
1765
|
+
type SettingsIssueKey = 'sourceViewId' | 'nodes' | 'senderEmail';
|
|
1766
|
+
interface SettingsValidationIssue {
|
|
1767
|
+
/** The offending settings key. */
|
|
1768
|
+
key: SettingsIssueKey;
|
|
1769
|
+
/** Human-readable reason, safe to show in the SettingsPage. */
|
|
1770
|
+
message: string;
|
|
1771
|
+
}
|
|
1772
|
+
/**
|
|
1773
|
+
* The two cross-field rules the spec names, plus the one shape rule no
|
|
1774
|
+
* schema can express: `nodes.triage` must be configured. `nodes` has no
|
|
1775
|
+
* default (a defaulted "every step null" would install a pipeline that
|
|
1776
|
+
* triages nothing), and `AgentProfile.nodes.triage` is non-nullable — this
|
|
1777
|
+
* check is what makes both safe. Per-field typing (e.g. `batchLimit` being a
|
|
1778
|
+
* number) stays the settings API's job at write time, not this function's.
|
|
1779
|
+
*/
|
|
1780
|
+
declare function validateSettings(settings: Record<string, unknown>): SettingsValidationIssue[];
|
|
1781
|
+
|
|
1782
|
+
/**
|
|
1783
|
+
* `settings` (§3.6) → `AgentProfile` (architecture_agent_graphe.md §5.3).
|
|
1784
|
+
*
|
|
1785
|
+
* The graph reads a profile, the platform stores flat settings; this is the
|
|
1786
|
+
* single, pure translation between the two. Keeping it pure (no `ctx`, no
|
|
1787
|
+
* record read, no clock) is what lets every node test build a profile from
|
|
1788
|
+
* the same settings an operator actually edits.
|
|
1789
|
+
*
|
|
1790
|
+
* Three name mismatches are deliberate, and are the reason this mapping is
|
|
1791
|
+
* written out by hand instead of being a spread:
|
|
1792
|
+
* - `autoRepliedTag` → `audit.sentTag` (same tag, `wai/auto-replied`).
|
|
1793
|
+
* - `needsReviewTag` → `audit.needsHumanTag`: the graph's `needs_human`
|
|
1794
|
+
* outcome is tagged `wai/needs-review` (the value every fixture carries
|
|
1795
|
+
* in `audit.needsHumanTag`). The similarly-named `needsHumanTag`
|
|
1796
|
+
* setting (`wai/needs-human`) is the LEGACY tag and has no outcome in
|
|
1797
|
+
* the ported graph — mapping by name would silently retag every
|
|
1798
|
+
* escalation.
|
|
1799
|
+
* - `responseTtlMinutes` → `schedule.fastResponseTtlMinutes`, `batchLimit`
|
|
1800
|
+
* → `schedule.triageBatchLimit`.
|
|
1801
|
+
*
|
|
1802
|
+
* Four settings have no profile counterpart on purpose:
|
|
1803
|
+
* `gorgiasConnectionId` (addresses the integration from `ctx`),
|
|
1804
|
+
* `dryRun` (read by the HANDLERS — `functions/triage-tick.ts` and
|
|
1805
|
+
* `functions/process-response.ts` swap the `reply`/`state` ports for the
|
|
1806
|
+
* recorders of `adapters/recording-ports.ts` and force `send: {mode:
|
|
1807
|
+
* 'none'}` — not by the graph, which must run identically either way),
|
|
1808
|
+
* `statsTimezone` (a §3.8 rendering concern) and `needsHumanTag` (above). `to-profile.spec.ts` pins that list, so a new
|
|
1809
|
+
* settings field cannot be forgotten here.
|
|
1810
|
+
*
|
|
1811
|
+
* `prompts` is a PARAMETER, not derived from settings: `prompts.draft` is
|
|
1812
|
+
* the agent record's own Langfuse binding (§3.4) and the other slots come
|
|
1813
|
+
* from `resolvePromptName` over the `buildSupportPipeline` config (§3.7) —
|
|
1814
|
+
* neither is knowable from a settings blob. T22 assembles the table and
|
|
1815
|
+
* passes it in.
|
|
1816
|
+
*/
|
|
1817
|
+
|
|
1818
|
+
/** One entry of the `nodes` settings json (§3.6); `null` disables the step. */
|
|
1819
|
+
interface SupportKitNodeSettings {
|
|
1820
|
+
model: string;
|
|
1821
|
+
/** Falls back to the same provider the `agent` record defaults to. */
|
|
1822
|
+
provider?: string;
|
|
1823
|
+
reasoning?: ReasoningEffort;
|
|
1824
|
+
/** `draft` only. */
|
|
1825
|
+
maxToolCalls?: number;
|
|
1826
|
+
/** `evaluate` only. */
|
|
1827
|
+
minConfidence?: number;
|
|
1828
|
+
/** `evaluate` only. */
|
|
1829
|
+
escalationEnabled?: boolean;
|
|
1830
|
+
}
|
|
1831
|
+
/**
|
|
1832
|
+
* The settings a consuming app stores, typed. The platform hands them over
|
|
1833
|
+
* as a `Record<string, unknown>` JSONB blob: a caller narrows it to this
|
|
1834
|
+
* type after `validateSettings` returns no issue — in particular
|
|
1835
|
+
* `nodes.triage`, which that function is what guarantees.
|
|
1836
|
+
*/
|
|
1837
|
+
interface SupportKitSettings {
|
|
1838
|
+
gorgiasConnectionId: string;
|
|
1839
|
+
sourceViewId: string;
|
|
1840
|
+
batchLimit: number;
|
|
1841
|
+
triageEnabled: boolean;
|
|
1842
|
+
triageIntervalMinutes: number;
|
|
1843
|
+
dryRun: boolean;
|
|
1844
|
+
nodes: {
|
|
1845
|
+
triage: SupportKitNodeSettings;
|
|
1846
|
+
escalate?: SupportKitNodeSettings | null;
|
|
1847
|
+
draft?: SupportKitNodeSettings | null;
|
|
1848
|
+
evaluate?: SupportKitNodeSettings | null;
|
|
1849
|
+
revise?: SupportKitNodeSettings | null;
|
|
1850
|
+
};
|
|
1851
|
+
unknownTag: string;
|
|
1852
|
+
handledTag: string;
|
|
1853
|
+
escalationTag: string;
|
|
1854
|
+
needsHumanTag: string;
|
|
1855
|
+
autoRepliedTag: string;
|
|
1856
|
+
needsReviewTag: string;
|
|
1857
|
+
followupTag: string;
|
|
1858
|
+
autoSendEnabled: boolean;
|
|
1859
|
+
senderEmail: string;
|
|
1860
|
+
requireHighTriageConfidence: boolean;
|
|
1861
|
+
whatsappMode: WhatsappMode;
|
|
1862
|
+
responseTtlMinutes: number;
|
|
1863
|
+
guardrailsActive: string[];
|
|
1864
|
+
blocklist: string[];
|
|
1865
|
+
noreplySenders: string[];
|
|
1866
|
+
channelPromptEmail: string;
|
|
1867
|
+
channelPromptWhatsapp: string;
|
|
1868
|
+
renameEnabled: boolean;
|
|
1869
|
+
renameFrom: string;
|
|
1870
|
+
renameTo: string;
|
|
1871
|
+
statsTimezone: string;
|
|
1872
|
+
}
|
|
1873
|
+
declare function settingsToProfile(settings: SupportKitSettings, prompts: Record<NodeKey, PromptRef>): AgentProfile;
|
|
1874
|
+
|
|
1875
|
+
/**
|
|
1876
|
+
* `SupportKitFunctionConfig` — what each of the four T22 manifest fragments
|
|
1877
|
+
* (`triage-tick`/`process-response`/`sweep`/`handle-approval`) needs to
|
|
1878
|
+
* build its `FunctionDef` (spec §3.2's `SupportPipelineConfig`, the slice of
|
|
1879
|
+
* it these fragments actually read — `buildSupportPipeline`, T25, owns the
|
|
1880
|
+
* full shape and passes this down).
|
|
1881
|
+
*/
|
|
1882
|
+
|
|
1883
|
+
interface SupportKitFunctionConfig extends PromptNameConfig {
|
|
1884
|
+
/** The consuming app's own slug — `app:<slug>/<objectKey>` dbEvent triggers, and the object relations. */
|
|
1885
|
+
slug: string;
|
|
1886
|
+
/**
|
|
1887
|
+
* §3.2's `SupportPipelineConfig.identifiers` — one `universalIdentifier`
|
|
1888
|
+
* per manifest function, keyed by the values in `FUNCTION_IDENTIFIER_KEYS`.
|
|
1889
|
+
* A manifest fragment with a missing id is broken by construction: looking
|
|
1890
|
+
* one up throws immediately rather than inventing a random one that would
|
|
1891
|
+
* drift on every rebuild.
|
|
1892
|
+
*/
|
|
1893
|
+
identifiers: Record<string, string>;
|
|
1894
|
+
}
|
|
1895
|
+
|
|
1896
|
+
/**
|
|
1897
|
+
* `buildSupportPipeline` (spec §3.2) — the single assembly point that turns
|
|
1898
|
+
* a consuming app's own config into every manifest fragment + handler this
|
|
1899
|
+
* kit provides. An audience app spreads the result into `defineApp({
|
|
1900
|
+
* manifest: {...baseManifest, ...kit-fragments}, handlers: kit.handlers })`.
|
|
1901
|
+
*
|
|
1902
|
+
* T25 is assembly, not invention: every fragment below is built from pieces
|
|
1903
|
+
* T20-T24 already shipped (`records/`, `functions/`, `settings/`,
|
|
1904
|
+
* `prompts/slots`) — this module's own job is wiring `config` through to
|
|
1905
|
+
* each of them consistently, plus `mergeRole`, the one piece with no prior
|
|
1906
|
+
* owner.
|
|
1907
|
+
*/
|
|
1908
|
+
|
|
1909
|
+
interface SupportPipelineConfig extends SupportKitFunctionConfig {
|
|
1910
|
+
/** Human label shown in the platform's app picker, e.g. 'Expérience client'. */
|
|
1911
|
+
displayName: string;
|
|
1912
|
+
/**
|
|
1913
|
+
* §3.2's own sketch names this field, but has no consumer yet (L1, T25
|
|
1914
|
+
* review): `navigation` (this fragment's own `NavItem[]`) is always `[]`
|
|
1915
|
+
* today — T26/T27 own the kit's pages/nav (§3.8's phase-2/phase-3), and
|
|
1916
|
+
* with it, presumably, grouping those nav items under this section. A
|
|
1917
|
+
* caller may set it now for forward compatibility; nothing reads it yet.
|
|
1918
|
+
*/
|
|
1919
|
+
navigationSection?: string;
|
|
1920
|
+
/**
|
|
1921
|
+
* §3.2's full `config.defaults` shape (`{channel?, prompts?}`), widening
|
|
1922
|
+
* `SupportKitFunctionConfig`'s own `defaults` (`{prompts?}` only) with
|
|
1923
|
+
* `channel` — `prompts`' shape is NOT restated here (L2, T25 review): it
|
|
1924
|
+
* is `PromptNameConfig['defaults']`'s own type, `prompts/slots.ts`'s
|
|
1925
|
+
* `PromptFallbackSlot`, referenced rather than copied, so this
|
|
1926
|
+
* declaration cannot silently narrow back to the wrong key set if that
|
|
1927
|
+
* one changes.
|
|
1928
|
+
*
|
|
1929
|
+
* `defaults.prompts` is wired to its real consumers: `buildPromptsTable`
|
|
1930
|
+
* (triage/escalate/evaluate/revise's `PromptRef.fallback`) and
|
|
1931
|
+
* `suggest-prompt`/`run-diff-analysis`'s own meta-prompt fallback.
|
|
1932
|
+
*
|
|
1933
|
+
* `defaults.channel` (DECISION 3, T25 — see the migration progress
|
|
1934
|
+
* journal's T25 entry) is accepted here for fidelity to the spec's own
|
|
1935
|
+
* sketch but has NO real consumer today: `settings/fields.ts` declares no
|
|
1936
|
+
* field named `channel`, and the nearest candidate, `whatsappMode`
|
|
1937
|
+
* (`escalate_only|draft_only|auto_reply`), has an incompatible value
|
|
1938
|
+
* domain from `'email'|'whatsapp'|'both'` — a mechanical seed would
|
|
1939
|
+
* corrupt it, not configure it. Wiring this for real means either adding
|
|
1940
|
+
* a settings field (§3.6 is T20-frozen; out of scope here) or picking an
|
|
1941
|
+
* arbitrary channel→whatsappMode mapping, both judgment calls beyond
|
|
1942
|
+
* assembly. Flagged for the spec owner, not routed around silently.
|
|
1943
|
+
*/
|
|
1944
|
+
defaults?: PromptNameConfig['defaults'] & {
|
|
1945
|
+
channel?: 'email' | 'whatsapp' | 'both';
|
|
1946
|
+
};
|
|
1947
|
+
}
|
|
1948
|
+
/** `provider`/`action` pair — matches `AppManifest.actions[]`/`AppRole.actions[]`'s own shape (app-kit has no exported named type for it). */
|
|
1949
|
+
interface ActionRef {
|
|
1950
|
+
provider: string;
|
|
1951
|
+
action: string;
|
|
1952
|
+
}
|
|
1953
|
+
interface SupportPipelineFragments {
|
|
1954
|
+
records: RecordDef[];
|
|
1955
|
+
functions: FunctionDef[];
|
|
1956
|
+
/**
|
|
1957
|
+
* The app custom events the kit's own functions emit — spread into
|
|
1958
|
+
* `manifest.emits`. NOT optional in practice (B5): `run-triage-batch`
|
|
1959
|
+
* declares `trigger: {type:'event', name: TRIAGE_RUN_REQUESTED_EVENT}`,
|
|
1960
|
+
* and the platform refuses to sync a manifest whose event trigger names
|
|
1961
|
+
* an event the app does not declare
|
|
1962
|
+
* (`app-manifest-constraints.ts`'s `validateAppFunctionConstraints`), so
|
|
1963
|
+
* a consuming app that spreads `functions` must spread this too.
|
|
1964
|
+
*/
|
|
1965
|
+
emits: string[];
|
|
1966
|
+
settings: AppSettings;
|
|
1967
|
+
prompts: PromptDef[];
|
|
1968
|
+
pages: PageDef[];
|
|
1969
|
+
navigation: NavItem[];
|
|
1970
|
+
/**
|
|
1971
|
+
* §3.8's SettingsPage row — the manifest's `settingsPage`, not a
|
|
1972
|
+
* `pages[]` entry (`AppManifestSchema`'s own refinements require it:
|
|
1973
|
+
* distinct `entry` from every page, no collision with the bundle the CLI
|
|
1974
|
+
* emits for a page `path`, distinct `universalIdentifier`). Not in §3.2's
|
|
1975
|
+
* own fragment sketch (T25's `pages`/`navigation` sketch predates T26) —
|
|
1976
|
+
* added here because a consuming app has no other way to spread it into
|
|
1977
|
+
* its manifest.
|
|
1978
|
+
*/
|
|
1979
|
+
settingsPage: SettingsPage;
|
|
1980
|
+
actions: ActionRef[];
|
|
1981
|
+
/**
|
|
1982
|
+
* `'NO_ACCESS'` (H2, T25 review): with no `defaultRole`, the platform
|
|
1983
|
+
* grants every platform member `VIEWER` on install
|
|
1984
|
+
* (`app-lifecycle.service.ts:1211`) — a `pro-sante` clinician would read
|
|
1985
|
+
* `experience-client`'s `generated-response` rows (customer email bodies,
|
|
1986
|
+
* drafted replies) by default. Exposed as a named fragment, not baked
|
|
1987
|
+
* silently into a spread, so a consuming app can still override it
|
|
1988
|
+
* explicitly (`defaultRole: kit.defaultRole` in the common case, or a
|
|
1989
|
+
* different value if that app has a real reason to).
|
|
1990
|
+
*/
|
|
1991
|
+
defaultRole: 'NO_ACCESS';
|
|
1992
|
+
handlers: Record<string, AppHandler>;
|
|
1993
|
+
mergeRole(role: AppRole): AppRole;
|
|
1994
|
+
/**
|
|
1995
|
+
* The `manifest.actions` counterpart of `mergeRole` (B2, T25 review):
|
|
1996
|
+
* `role.actions` must always be a subset of `manifest.actions`
|
|
1997
|
+
* (`validateActionCoupling`, enforced on every publish/sync) — before
|
|
1998
|
+
* this existed, a caller had to remember to fold the kit's own actions
|
|
1999
|
+
* into their manifest's `actions: [...]` by hand, on top of merging their
|
|
2000
|
+
* role separately, and a caller who forgot got a 422 at publish. Adds the
|
|
2001
|
+
* same kit action set `mergeRole` adds to `role.actions`, so
|
|
2002
|
+
* `actions: kit.mergeActions(ownActions)` paired with
|
|
2003
|
+
* `role: kit.mergeRole(ownRole)` keeps the two in lockstep by
|
|
2004
|
+
* construction.
|
|
2005
|
+
*/
|
|
2006
|
+
mergeActions(actions: ActionRef[]): ActionRef[];
|
|
2007
|
+
}
|
|
2008
|
+
declare function buildSupportPipeline(config: SupportPipelineConfig): SupportPipelineFragments;
|
|
2009
|
+
|
|
2010
|
+
export { AGENT_GUARDRAILS, AGENT_STATUSES, AGENT_TOOLS, type ActionDecision, type AgentProfile, type AgentStatus, type AuditTags, type AutoReplyGuardSettings, type Budget, CANDIDATE_MIN_LENGTH, type CatalogueTool, type CategoryPolicy, type CategoryReferentialEntry, type ChannelKind, type ChatMessage, type Classification, type ClockPort, type CompletionRequest, type CompletionResult, type Conversation, type ConversationPort, type ConversationRef, type CostLedger, type CustomerInfo, DEFAULT_CHANNEL_PROMPT_EMAIL, DEFAULT_CHANNEL_PROMPT_WHATSAPP, DEFAULT_LLM_PROVIDER, DEFAULT_PROFILE_KEY, DEFAULT_WHATSAPP_MODE, type Draft, type DraftAttribution, type DraftNodeConfig, EVALUATION_VERDICTS, type EscalateNodeConfig, type EvaluateNodeConfig, type EvaluationVerdict, GENERATED_RESPONSE_STATUSES, type GeneratedResponseStatus, type GuardrailId, InvalidStatusTransitionError, type JsonSchema, type JudgedReply, type KnowledgeHit, type LlmPort, type Message, NODE_NAMES, type Node, type NodeCost, type NodeDeps, type NodeKey, type NodeName, type NodeStep, type OrderSummary, type OutboundReply, type Outcome, PROMPT_SLOTS, type PlatformPromptReader, type PortName, type PromptCacheEntry, type PromptCachePort, type PromptDegradedEvent, type PromptNameConfig, type PromptPort, type PromptRef, type PromptReference, type PromptResolverDeps, type PromptSlot, type ProposedAction, REASONING_MAX_LEN, type RawPrompt, type RawPromptConfig, type RawTicket, type ReasoningEffort, type RecordDef, type ReplyPort, type ResolvedPrompt, type ResumeFrom, type ReviseNodeConfig, type RunGuardrailsInput, type RunStamp, type RunTicketOptions, type RunUntil, STOP_PHRASES, SUPPORT_KIT_SETTINGS_FIELDS, type SettingsIssueKey, type SettingsValidationIssue, type SimilarTicket, type SourceDescriptor, type StatePort, type SupportKitNodeSettings, type SupportKitSettings, type SupportPipelineConfig, type SupportPipelineFragments, type TicketRunState, type ToolCallRecord, type ToolCallRequest, type ToolContext, type ToolPolicy, type ToolSpec, type TrackingSummary, type TriageNodeConfig, UNCERTAINTY_MARKERS, type Usage, type Verdict, type VerifyReplyInput, type VerifyReplyResult, WHATSAPP_MODES, WHATSAPP_NOTE_CHEVRON, type WhatsappMode, agentRecord, assertTransition, buildCategoryRecord, buildDiffAnalysisRecord, buildEvaluationRecord, buildGeneratedResponseRecord, buildResponseComparisonRecord, buildSupportKitRecords, buildSupportPipeline, buildTriageDecisionRecord, canTransition, categoryGroupRecord, channelPreGates, createBudget, createPromptResolver, diffAnalysisUniqueKey, firstCustomerMessage, guardrailBucket, hasCustomerAttachment, hasReferences, initialState, isAutoSendEligible, isAutomatedSenderEmail, isAutomatedSenderTicket, isEvaluationVerdict, isGeneratedResponseStatus, isJudgemeConversation, isJudgemeTicket, isSendable, isSendableVerdict, isTerminalStatus, isTicketClosed, isWhatsappChevronNote, isWhatsappTicket, lastCustomerMessage, needsRevision, openTicketKeyFor, parseReferences, pipelineStateRecord, promptCacheRecord, reclaimStalledSend, requiresFollowup, resolvePromptName, resolveReviseName, runGuardrails, runTicket, settingsToProfile, stopOptOut, targetRefFor, validateSettings, verifyReply, whatsappModeFromLegacyBoolean };
|