@alvera-ai/platform-sdk 0.10.0-rc.8 → 0.11.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.
Files changed (66) hide show
  1. package/.agent/AGENTS.md +499 -0
  2. package/.agent/account_management.md +456 -0
  3. package/.agent/action_status_updaters.md +264 -0
  4. package/.agent/ai_agents.md +462 -0
  5. package/.agent/ai_sandbox.md +265 -0
  6. package/.agent/async.md +112 -0
  7. package/.agent/connected_apps.md +408 -0
  8. package/.agent/cookbook/_fixtures/README.md +106 -0
  9. package/.agent/cookbook/_fixtures/accounts_receivable/_customers_accounts_receivable_customer.liquid +32 -0
  10. package/.agent/cookbook/_fixtures/accounts_receivable/_customers_accounts_receivable_mdm.liquid +20 -0
  11. package/.agent/cookbook/_fixtures/accounts_receivable/stripe_customers_batch1.csv +5 -0
  12. package/.agent/cookbook/_fixtures/foundation/_lead_submissions_foundation_generic_table.liquid +33 -0
  13. package/.agent/cookbook/_fixtures/foundation/_lead_submissions_foundation_legal_entity.liquid +88 -0
  14. package/.agent/cookbook/_fixtures/foundation/_lead_submissions_foundation_mdm.liquid +48 -0
  15. package/.agent/cookbook/_fixtures/healthcare/_cahps_appointments_healthcare_appointment.liquid +47 -0
  16. package/.agent/cookbook/_fixtures/healthcare/_cahps_appointments_healthcare_mdm.liquid +24 -0
  17. package/.agent/cookbook/_fixtures/healthcare/_cahps_appointments_healthcare_patient.liquid +38 -0
  18. package/.agent/cookbook/_fixtures/healthcare/memorandum-of-association-01.png +0 -0
  19. package/.agent/cookbook/_fixtures/healthcare/sample_two_page.pdf +43 -0
  20. package/.agent/cookbook/_fixtures/payment_risk/_compliance_screenings_payment_risk_compliance_screening.liquid +59 -0
  21. package/.agent/cookbook/_fixtures/payment_risk/_compliance_screenings_payment_risk_mdm.liquid +36 -0
  22. package/.agent/cookbook/_fixtures/payment_risk/_payment_accounts_payment_risk_mdm.liquid +30 -0
  23. package/.agent/cookbook/_fixtures/payment_risk/_payment_accounts_payment_risk_payment_account.liquid +55 -0
  24. package/.agent/cookbook/_setup/accounts_receivable.md +282 -0
  25. package/.agent/cookbook/_setup/foundation.md +277 -0
  26. package/.agent/cookbook/_setup/healthcare.md +279 -0
  27. package/.agent/cookbook/_setup/payment_risk.md +283 -0
  28. package/.agent/cookbook/action-status-updaters.md +212 -0
  29. package/.agent/cookbook/ai-agent-invoke.md +243 -0
  30. package/.agent/cookbook/appointment-review-sms-workflow.md +761 -0
  31. package/.agent/cookbook/birthday-greeting-sms-trigger.md +656 -0
  32. package/.agent/cookbook/bulk-ingest.md +254 -0
  33. package/.agent/cookbook/contact-us-triage-with-llm.md +622 -0
  34. package/.agent/cookbook/custom-tables.md +201 -0
  35. package/.agent/cookbook/dunning-sms-for-delinquent.md +619 -0
  36. package/.agent/cookbook/invite-team.md +194 -0
  37. package/.agent/cookbook/kyc-notification-on-account-activation.md +619 -0
  38. package/.agent/cookbook/rest-fetch.md +246 -0
  39. package/.agent/cookbook/sanctions-screening-with-agent-review.md +733 -0
  40. package/.agent/cookbook/score-leads-with-llm-categorization.md +624 -0
  41. package/.agent/cookbook/system-templates.md +129 -0
  42. package/.agent/cookbook/triage-prospects-by-priority.md +533 -0
  43. package/.agent/cookbook/welcome-sms-for-customers.md +607 -0
  44. package/.agent/data_activation_clients.md +559 -0
  45. package/.agent/data_sources.md +235 -0
  46. package/.agent/datalakes.md +714 -0
  47. package/.agent/debugging.md +137 -0
  48. package/.agent/errors.md +190 -0
  49. package/.agent/generic_tables.md +351 -0
  50. package/.agent/interoperability_contracts.md +417 -0
  51. package/.agent/mdm.md +293 -0
  52. package/.agent/mutations.md +126 -0
  53. package/.agent/templates.md +98 -0
  54. package/.agent/tool-call-configs.md +90 -0
  55. package/.agent/tools.md +547 -0
  56. package/.agent/type_naming.md +129 -0
  57. package/.agent/workflows.md +617 -0
  58. package/README.md +178 -0
  59. package/dist/bin/platform-sdk.d.mts +1 -0
  60. package/dist/bin/platform-sdk.mjs +106 -0
  61. package/dist/bin/platform-sdk.mjs.map +1 -0
  62. package/dist/index.d.mts +1310 -44116
  63. package/dist/index.d.mts.map +1 -1
  64. package/dist/index.mjs +1194 -7344
  65. package/dist/index.mjs.map +1 -1
  66. package/package.json +19 -10
@@ -0,0 +1,624 @@
1
+ ---
2
+ title: Score inbound leads into four bands via an LLM agent and route each band to a tailored SMS
3
+ summary: End-to-end agent-driven workflow — a chat-completion LLM agent classifies each lead submission into hot/warm/cold/spam, the workflow's decision interpolates the agent's band, four SMS actions (one per band) fan out, and the run is verified row-by-row so every WEL carries exactly one matched action and three skipped.
4
+ industry: foundation
5
+ slug: score-leads-with-llm-categorization
6
+ vitest_source:
7
+ - integration-tests/tests/foundation/agent-driven-workflow.test.ts
8
+ - integration-tests/tests/foundation/generic-tables.test.ts
9
+ - integration-tests/tests/foundation/tools.test.ts
10
+ - integration-tests/tests/foundation/bootstrap.test.ts
11
+ status: green
12
+ ---
13
+
14
+ # Problem
15
+
16
+ The previous foundation cookbook (`birthday-greeting-sms-trigger`)
17
+ demonstrated a static decision: the workflow's decision_config was a
18
+ literal Liquid array naming one fixed decision key, and a single SMS
19
+ action fired for every matched row. Many real outbound engagements
20
+ need the opposite: the action that fires depends on what the row
21
+ says, not just on the fact that it matched the filter.
22
+
23
+ A B2B lead-scoring scenario is the canonical shape. A submission on a
24
+ contact-us form might be a hot prospect ready to buy, a warm explorer
25
+ who needs nurture, a cold tire-kicker, or outright spam. The same
26
+ workflow should pick the right tone of SMS for each. The
27
+ classification is a language task, not a rules task — applying a
28
+ hand-coded keyword filter would either over-fit the training set or
29
+ miss every variation of phrasing.
30
+
31
+ The Alvera platform's agent-driven workflow primitive flips the
32
+ decision step into an LLM enrichment plus a Liquid interpolation. An
33
+ AI agent receives the row's free-text via a context-mapping template,
34
+ returns a JSON object whose `band` field is one of the four enum
35
+ values, and the workflow's decision_config interpolates that band
36
+ into a one-element decision array
37
+ (`["{{ additional_context["agent-slug"].band }}"]`). Four SMS actions
38
+ are registered against the workflow, one per band; the agent's output
39
+ picks which one runs.
40
+
41
+ This cookbook walks the **whole** scenario: it provisions the custom
42
+ dataset, agent, and workflow, ingests lead rows through the
43
+ generic-table's auto-provisioned default DAC, runs the workflow so the
44
+ agent classifies each row, and verifies the routing row-by-row —
45
+ every Workflow Execution Log carries exactly one matched action and
46
+ three skipped, proving the agent's band actually steered the fan-out.
47
+
48
+ The scenario is anchored to
49
+ `platform/integration-tests/tests/foundation/agent-driven-workflow.test.ts`
50
+ — a green end-to-end test (§1–§5). The setup file `_setup/foundation.md`
51
+ already provisioned the tenant + datalake + tenant-scoped client; this
52
+ cookbook starts from there.
53
+
54
+ # Composition
55
+
56
+ | Resource provisioned | Owner |
57
+ |----------------------------------|-------------|
58
+ | Lead Submissions generic table | build |
59
+ | SMS tool (SNS-backed) | build |
60
+ | LLM tool (Ollama chat completion)| build |
61
+ | Score Lead AI agent | build |
62
+ | Score Lead workflow | build |
63
+
64
+ The generic table's **default DAC** — auto-provisioned by the
65
+ platform when the generic table is created — is reused for ingestion;
66
+ no separate data source / tool / interop contract / DAC is created.
67
+ The setup file `_setup/foundation.md` already provisioned the tenant +
68
+ datalake + tenant-scoped client; this cookbook starts from there.
69
+
70
+ # Walkthrough
71
+
72
+ ## 001 — create the Lead Submissions generic table
73
+
74
+ The agent-driven workflow targets a Generic Table dataset
75
+ (`dataset_type: 'generic_table'`) rather than a regulated domain
76
+ entity, because lead-capture form rows do not fit a canonical industry
77
+ entity. The table's columns mirror the shape an Airtable/Google-Sheets
78
+ export would produce; the `message` and `lead_source` columns are what
79
+ the agent reads, and `band` is what the agent eventually writes back
80
+ in production. The server-derived `name` is captured — the workflow
81
+ run in §009 addresses the regulated table as `regulated_<name>`.
82
+
83
+ ```typescript
84
+ const genericTableResp = await api.genericTables.create(tenantSlug, datalakeSlug, {
85
+ title: `Cookbook Lead Submissions ${runSuffix}`,
86
+ description: 'Inbound lead-capture form rows the Score Lead agent classifies.',
87
+ columns: [
88
+ {
89
+ name: 'submission_id',
90
+ title: 'Submission ID',
91
+ type: 'string',
92
+ description: 'Vendor-supplied unique submission id',
93
+ is_unique: true,
94
+ privacy_requirement: 'none',
95
+ },
96
+ {
97
+ name: 'name',
98
+ title: 'Name',
99
+ type: 'string',
100
+ description: 'Submitter full name',
101
+ is_unique: false,
102
+ privacy_requirement: 'tokenize',
103
+ },
104
+ {
105
+ name: 'email',
106
+ title: 'Email',
107
+ type: 'string',
108
+ description: 'Submitter email — also the legal-entity identifier',
109
+ is_unique: false,
110
+ privacy_requirement: 'tokenize',
111
+ },
112
+ {
113
+ name: 'message',
114
+ title: 'Message',
115
+ type: 'string',
116
+ description: 'Free-text lead message — the agent classifies this',
117
+ is_unique: false,
118
+ privacy_requirement: 'none',
119
+ },
120
+ {
121
+ name: 'lead_source',
122
+ title: 'Lead Source',
123
+ type: 'string',
124
+ description: 'utm_source / sheet tab id',
125
+ is_unique: false,
126
+ privacy_requirement: 'none',
127
+ },
128
+ {
129
+ name: 'band',
130
+ title: 'Band',
131
+ type: 'string',
132
+ description: 'Lead-scoring band assigned by Score Lead agent',
133
+ is_unique: false,
134
+ privacy_requirement: 'none',
135
+ },
136
+ ],
137
+ })
138
+ genericTableId = genericTableResp.data.id!
139
+ ctx.gtName = genericTableResp.data.name!
140
+ ```
141
+
142
+ ## 002 — create the SMS tool
143
+
144
+ A single SMS tool dispatches every band's outbound message; the
145
+ per-band SMS body lives on each workflow action, not on the tool. Same
146
+ SNS-backed LocalStack wiring as the birthday cookbook — `intent: 'sms'`
147
+ tags it for workflow-action use.
148
+
149
+ ```typescript
150
+ const smsToolResp = await api.tools.create(tenantSlug, datalakeSlug, {
151
+ name: `Cookbook SMS Tool ${runSuffix}`,
152
+ description: 'SNS-backed SMS dispatcher for the Score Lead workflow, wired to LocalStack.',
153
+ intent: 'sms',
154
+ status: 'active',
155
+ datalake_id: ctx.datalakeId,
156
+ body: {
157
+ tool_body_type: 'sns',
158
+ auth_method: 'access_key',
159
+ region: 'us-east-1',
160
+ phone_number: '+15551234567',
161
+ endpoint_url: 'http://localhost:4566',
162
+ access_key_id: 'test',
163
+ secret_access_key: 'test',
164
+ },
165
+ })
166
+ toolId = smsToolResp.data.id!
167
+ ```
168
+
169
+ ## 003 — create the LLM tool
170
+
171
+ The Score Lead agent calls a chat-completion endpoint to classify each
172
+ row. The tool's `intent: 'llm_enrichment'` distinguishes it from the
173
+ SMS tool above. It is a **provider adapter**: `base_body` authors the
174
+ provider's request — here Ollama's native `/api/chat` shape with
175
+ `think: false` and a `format` schema so the model returns clean,
176
+ schema-constrained JSON — and `response_extractor` maps the provider's
177
+ envelope back to the canonical `{ output_json, … }` the platform reads.
178
+ The extractor's `output_schema` is required for an `llm_enrichment`
179
+ tool. The `api_key`/`auth_method` pair satisfies the REST tool's schema
180
+ even though Ollama ignores the header.
181
+
182
+ ```typescript
183
+ const ENRICHMENT_OUTPUT_SCHEMA = {
184
+ type: 'object',
185
+ properties: {
186
+ output_json: {},
187
+ input_tokens: { type: ['integer', 'null'] },
188
+ output_tokens: { type: ['integer', 'null'] },
189
+ total_tokens: { type: ['integer', 'null'] },
190
+ explanation: { type: ['string', 'null'] },
191
+ },
192
+ required: ['output_json'],
193
+ }
194
+
195
+ const OLLAMA_BASE_BODY =
196
+ '{"model": "{{ model }}", "messages": [{"role": "user", "content": "{{ rendered_prompt | json_escape }}", "images": [{% for img in images %}{% unless forloop.first %}, {% endunless %}"{{ img.data }}"{% endfor %}]}], "stream": false, "think": false, "options": {"temperature": 0, "num_ctx": 40960}, "format": {{ schema | to_json }}}'
197
+
198
+ const OLLAMA_EXTRACTOR =
199
+ '{"output_json": "{{ msg.message.content | json_escape }}", "explanation": "{{ msg.message.thinking | json_escape }}", "input_tokens": {{ msg.prompt_eval_count | default: 0 }}, "output_tokens": {{ msg.eval_count | default: 0 }}, "total_tokens": {{ msg.prompt_eval_count | default: 0 | plus: msg.eval_count }}}'
200
+
201
+ const llmToolResp = await api.tools.create(tenantSlug, datalakeSlug, {
202
+ name: `Cookbook LLM Tool ${runSuffix}`,
203
+ description: 'Ollama-backed chat-completion adapter for Score Lead classification.',
204
+ intent: 'llm_enrichment',
205
+ status: 'active',
206
+ datalake_id: ctx.datalakeId,
207
+ response_extractor: { type: 'custom', body: OLLAMA_EXTRACTOR, output_schema: ENRICHMENT_OUTPUT_SCHEMA },
208
+ body: {
209
+ tool_body_type: 'rest_api',
210
+ base_url: 'http://localhost:11434',
211
+ base_path: { type: 'custom', body: '/api/chat' },
212
+ auth_method: 'api_key',
213
+ api_key: 'stub-key',
214
+ api_key_name: 'Authorization',
215
+ api_key_location: 'header',
216
+ request_type: 'json',
217
+ response_type: 'json',
218
+ timeout_ms: 60_000,
219
+ base_body: { type: 'custom', body: OLLAMA_BASE_BODY },
220
+ },
221
+ })
222
+ ctx.llmToolId = llmToolResp.data.id!
223
+ ```
224
+
225
+ ## 004 — create the Score Lead AI agent
226
+
227
+ The agent binds three things: the model name (sent on every inference
228
+ call), an input schema the workflow's context-mapping must satisfy,
229
+ and a response schema the agent's output must match. The response
230
+ schema's `enum: ['hot','warm','cold','spam']` constraint is what
231
+ guards the downstream decision interpolation from emitting a band the
232
+ workflow has no SMS action for. `temperature: 0.0` removes sampling
233
+ noise so identical inputs classify identically. `data_access:
234
+ 'unregulated'` says the agent only ever sees the tokenized projection
235
+ of each row, never the regulated identifiers.
236
+
237
+ ```typescript
238
+ const SCORE_INPUT_SCHEMA = {
239
+ type: 'object',
240
+ properties: {
241
+ name: { type: 'string' },
242
+ message: { type: 'string' },
243
+ lead_source: { type: 'string' },
244
+ },
245
+ required: ['name', 'message'],
246
+ }
247
+
248
+ const SCORE_RESPONSE_SCHEMA = {
249
+ type: 'object',
250
+ properties: {
251
+ band: { type: 'string', enum: ['hot', 'warm', 'cold', 'spam'] },
252
+ },
253
+ required: ['band'],
254
+ }
255
+
256
+ const AGENT_PROMPT_BODY = `You are a B2B lead-scoring assistant. Classify the following lead's intent into EXACTLY ONE of these bands:
257
+
258
+ - "hot" — clear buying intent, decision maker, ready to engage
259
+ - "warm" — interested but exploratory, requires nurture
260
+ - "cold" — generic/lukewarm interest, low conversion signal
261
+ - "spam" — promotional, irrelevant, or low-quality submission
262
+
263
+ Lead name: {{ name }}
264
+ Lead message: {{ message }}
265
+ Lead source: {{ lead_source }}
266
+
267
+ Respond with a JSON object: {"band": "<one of hot|warm|cold|spam>"}`
268
+
269
+ const agentResp = await api.aiAgents.create(tenantSlug, datalakeSlug, {
270
+ name: `Cookbook Score Lead Agent ${runSuffix}`,
271
+ tool_id: ctx.llmToolId,
272
+ model: 'qwen3-vl:8b-instruct',
273
+ data_access: 'unregulated',
274
+ temperature: 0.0,
275
+ max_tokens: 1024,
276
+ enabled: true,
277
+ input_schema: SCORE_INPUT_SCHEMA,
278
+ llm_response_schema: SCORE_RESPONSE_SCHEMA,
279
+ prompt_config: { type: 'custom', body: AGENT_PROMPT_BODY },
280
+ })
281
+ aiAgentId = agentResp.data.id!
282
+ ctx.agentSlug = agentResp.data.slug!
283
+ ```
284
+
285
+ ## 005 — create the Score Lead workflow
286
+
287
+ The workflow has the standard shape — filter, decision, actions — but
288
+ two things distinguish it from the birthday cookbook's static
289
+ workflow. First, the Score Lead agent is **nested** in the workflow
290
+ create body (the `workflow_ai_agents` array — a `cast_assoc`, not a
291
+ separate attach call), binding it into the workflow's enrichment phase
292
+ with a Liquid `context_mapping_config` that projects each lead row's
293
+ fields into the agent's input schema.
294
+ Second, the `decision_config` body is a Liquid template that
295
+ interpolates the agent's `band` output (read from
296
+ `additional_context["<agent-slug>"].band`) into a single-element
297
+ decision array. The four `actions` are keyed `decision_key:
298
+ hot|warm|cold|spam`; whichever band the agent emits picks the action
299
+ that fires, leaving the other three `:skipped`.
300
+
301
+ Bracket access (`additional_context["..."]`) is required because the
302
+ agent's slug contains hyphens, which Solid's dot parser would
303
+ otherwise read as subtraction operators.
304
+
305
+ ```typescript
306
+ const BANDS = ['hot', 'warm', 'cold', 'spam'] as const
307
+
308
+ const CONTEXT_MAPPING_BODY = JSON.stringify({
309
+ name: '{{ event_dataset.name }}',
310
+ message: '{{ event_dataset.message }}',
311
+ lead_source: '{{ event_dataset.lead_source }}',
312
+ })
313
+
314
+ const DECISION_CONFIG_BODY = `["{{ additional_context["${ctx.agentSlug}"].band }}"]`
315
+ const DECISION_OUTPUT_SCHEMA = { type: 'array', items: { type: 'string' } }
316
+
317
+ const workflowResp = await api.workflows.create(tenantSlug, datalakeSlug, {
318
+ name: `Cookbook Score Lead Workflow ${runSuffix}`,
319
+ description: 'Classifies lead_submissions into hot/warm/cold/spam via an LLM agent; one SMS action per band.',
320
+ dataset_type: 'generic_table',
321
+ generic_table_id: genericTableId,
322
+ skip_mdm_resolution: true,
323
+ status: 'live',
324
+ filter_config: {
325
+ type: 'custom',
326
+ body: 'true',
327
+ output_schema: { type: 'boolean' },
328
+ },
329
+ decision_config: {
330
+ type: 'custom',
331
+ body: DECISION_CONFIG_BODY,
332
+ output_schema: DECISION_OUTPUT_SCHEMA,
333
+ },
334
+ actions: BANDS.map((band) => ({
335
+ decision_key: band,
336
+ action_type: 'sms',
337
+ tool_id: toolId,
338
+ position: 0,
339
+ trigger_template: 'now',
340
+ idempotency_template: `{{ subject_id }}-{{ action_id }}-${band}-{{ "" | uuid }}`,
341
+ tool_call: {
342
+ tool_call_type: 'sms_request',
343
+ to: { type: 'custom', body: '+15551234567' },
344
+ body: {
345
+ type: 'custom',
346
+ body: `Lead band [${band}]: {{ event_dataset.message }}`,
347
+ },
348
+ sms_type: 'transactional',
349
+ },
350
+ })),
351
+ // Nest the scoring agent inline. Workflow joins omit output_schema —
352
+ // the server pins it from the agent's input_schema.
353
+ workflow_ai_agents: [
354
+ {
355
+ ai_agent_id: aiAgentId,
356
+ position: 0,
357
+ context_mapping_config: { type: 'custom', body: CONTEXT_MAPPING_BODY },
358
+ },
359
+ ],
360
+ })
361
+ workflowId = workflowResp.data.id!
362
+ ctx.workflowSlug = workflowResp.data.slug!
363
+ ```
364
+
365
+ ## 006 — find the generic table's auto-provisioned default DAC
366
+
367
+ Creating a generic table provisions two things automatically: an
368
+ identity interoperability contract and a default Data Activation
369
+ Client bound to it (name pattern
370
+ `<datalake> <gt_name> DataActivationClient`, `tool_call:
371
+ manual_upload`). No data source, tool, interop contract, or DAC needs
372
+ to be created by hand for plain row ingestion into the table — the
373
+ default DAC is found by GT-name convention in the DAC listing.
374
+
375
+ ```typescript
376
+ const deadline = Date.now() + 30_000
377
+ let found: { slug?: string | null; name?: string | null } | undefined
378
+ while (Date.now() < deadline && !found) {
379
+ const { data } = await api.dataActivationClients.list(tenantSlug, datalakeSlug)
380
+ found = (data.data ?? []).find((d) => (d.name ?? '').includes(ctx.gtName))
381
+ if (!found) await new Promise((r) => setTimeout(r, 1_000))
382
+ }
383
+ if (!found?.slug) {
384
+ throw new Error(`no default DAC found for GT ${ctx.gtName} within 30s`)
385
+ }
386
+ ctx.dacSlug = found.slug
387
+ ```
388
+
389
+ ## 007 — ingest three lead rows through the default DAC
390
+
391
+ Three rows, ingested as inline JSON through the default DAC. Each
392
+ carries a deliberately distinct `message` — a clear buying signal, a
393
+ lukewarm browse, and obvious promotional spam — so the agent has
394
+ something unambiguous to classify. The `band` column is left unset on
395
+ ingest; it is the agent's job to assign one. Each ingest call returns
396
+ its own batch id; all three are pinned for the run scope in §009.
397
+
398
+ ```typescript
399
+ const leadRows = [
400
+ {
401
+ submission_id: `LEAD-HOT-${runSuffix}`,
402
+ name: 'Dana Decisive',
403
+ email: `dana-${runSuffix}@example.com`,
404
+ message:
405
+ 'We have budget approved and need to roll out to 500 seats this quarter — can we start onboarding next week?',
406
+ lead_source: 'cookbook_score_leads',
407
+ },
408
+ {
409
+ submission_id: `LEAD-COLD-${runSuffix}`,
410
+ name: 'Sam Browsing',
411
+ email: `sam-${runSuffix}@example.com`,
412
+ message: 'Just browsing — found your site via a blog post. No particular need right now.',
413
+ lead_source: 'cookbook_score_leads',
414
+ },
415
+ {
416
+ submission_id: `LEAD-SPAM-${runSuffix}`,
417
+ name: 'Promo Bot',
418
+ email: `promo-${runSuffix}@example.com`,
419
+ message:
420
+ 'BUY CHEAP FOLLOWERS NOW!!! 90% off SEO backlinks, crypto giveaways, click here click here!!!',
421
+ lead_source: 'cookbook_score_leads',
422
+ },
423
+ ]
424
+
425
+ const ingestResults = await Promise.all(
426
+ leadRows.map((row) =>
427
+ api.dataActivationClients.ingest(tenantSlug, datalakeSlug, ctx.dacSlug, { data: row }),
428
+ ),
429
+ )
430
+ ctx.leadBatchIds = ingestResults.map((r) => r.data.batch_id!)
431
+ if (ctx.leadBatchIds.length !== 3) {
432
+ throw new Error(`expected 3 ingest batch ids, got ${ctx.leadBatchIds.length}`)
433
+ }
434
+ ```
435
+
436
+ ## 008 — wait for the three ingest batches to reach steady-state
437
+
438
+ Ingestion is async — the DAC enqueues per-row jobs that drain into the
439
+ generic table. Poll the DAC's activation logs until every batch shows
440
+ a row with `dataset_updated >= 1` (the lead row was upserted into the
441
+ table).
442
+
443
+ ```typescript
444
+ const targetBatches = new Set<string>(ctx.leadBatchIds)
445
+ const deadline = Date.now() + 90_000
446
+ let greenCount = 0
447
+ while (Date.now() < deadline) {
448
+ const { data } = await api.dataActivationClients.logs.list(tenantSlug, datalakeSlug, ctx.dacSlug)
449
+ const green = new Set<string>()
450
+ for (const row of (data.data ?? []) as Array<Record<string, unknown>>) {
451
+ const b = row.batch_id
452
+ if (typeof b !== 'string' || !targetBatches.has(b)) continue
453
+ if (typeof row.dataset_updated !== 'number' || row.dataset_updated < 1) continue
454
+ green.add(b)
455
+ }
456
+ greenCount = green.size
457
+ if (greenCount === targetBatches.size) break
458
+ await new Promise((r) => setTimeout(r, 1_000))
459
+ }
460
+ if (greenCount !== targetBatches.size) {
461
+ throw new Error(`only ${greenCount}/3 lead-row batches reached steady-state within 90s`)
462
+ }
463
+ ```
464
+
465
+ ## 009 — run the workflow against the three lead rows
466
+
467
+ `workflows.run` triggers the full agent-driven pipeline per row:
468
+ filter → agent enrichment (the Ollama call that classifies the lead)
469
+ → decision (the band interpolated into the decision array) → action
470
+ fan-out. The SQL where-clause scopes the run to exactly the three
471
+ batches §007 ingested (`regulated_<gt_name>` is the regulated mirror
472
+ the run-query addresses).
473
+
474
+ Unlike the birthday workflow, the Score Lead actions use
475
+ `trigger_template: 'now'`, so they dispatch immediately and the run
476
+ reaches a terminal status — poll `batchLogs.refresh` until it leaves
477
+ `:pending`. The window is generous because each row's enrichment is a
478
+ live LLM inference call.
479
+
480
+ ```typescript
481
+ const regulatedTable = `regulated_${ctx.gtName}`
482
+ const batchList = (ctx.leadBatchIds as string[]).map((b) => `'${b}'`).join(', ')
483
+
484
+ const runResp = await api.workflows.run(tenantSlug, datalakeSlug, ctx.workflowSlug, {
485
+ sql_where_clause: `${regulatedTable}.batch_id IN (${batchList})`,
486
+ mode: 'live',
487
+ manual_override: true,
488
+ })
489
+ ctx.runLogId = runResp.data.workflow_run_log_id!
490
+ ctx.runBatchId = runResp.data.batch_id!
491
+
492
+ const deadline = Date.now() + 240_000
493
+ let status: string | null = null
494
+ while (Date.now() < deadline) {
495
+ const { data: log } = await api.workflows.batchLogs.refresh(tenantSlug, datalakeSlug, ctx.workflowSlug, ctx.runLogId)
496
+ status = log.status ?? null
497
+ if (status && status !== 'pending') break
498
+ await new Promise((r) => setTimeout(r, 2_000))
499
+ }
500
+ if (status === 'failed') {
501
+ throw new Error('agent-driven workflow run reached :failed')
502
+ }
503
+ if (!status || status === 'pending') {
504
+ throw new Error('workflow run did not leave :pending within 240s')
505
+ }
506
+ ```
507
+
508
+ ## 010 — verify the agent's band steered the fan-out
509
+
510
+ This is the assertion the old shallow cookbook could never make,
511
+ because it never ran the workflow. Each lead row produced a Workflow
512
+ Execution Log. Every WEL has exactly **four** action execution logs —
513
+ one per band — and exactly **one** is matched (`:pending` or
514
+ `:completed`, the band the agent emitted) while the other **three**
515
+ are `:skipped`. A run where a WEL had two matched actions, or zero,
516
+ would mean the agent's output did not actually steer the decision;
517
+ this step fails loudly in that case.
518
+
519
+ ```typescript
520
+ const { data: wfLogs } = await api.workflows.workflowLogs.list(tenantSlug, datalakeSlug, ctx.workflowSlug)
521
+ const ourWels = (wfLogs.data ?? []).filter(
522
+ (w) => (w as { batch_id?: string }).batch_id === ctx.runBatchId,
523
+ )
524
+ if (ourWels.length !== 3) {
525
+ throw new Error(`expected 3 WELs for the run, got ${ourWels.length}`)
526
+ }
527
+
528
+ for (const wel of ourWels) {
529
+ const welId = (wel as { id?: string }).id
530
+ const aels =
531
+ (wel as { action_execution_logs?: Array<{ status?: string }> }).action_execution_logs ?? []
532
+ if (aels.length !== 4) {
533
+ throw new Error(`WEL ${welId}: expected 4 AELs (one per band), got ${aels.length}`)
534
+ }
535
+ const byStatus: Record<string, number> = {}
536
+ for (const ael of aels) {
537
+ const st = ael.status ?? 'unknown'
538
+ byStatus[st] = (byStatus[st] ?? 0) + 1
539
+ }
540
+ const matched = (byStatus.pending ?? 0) + (byStatus.completed ?? 0)
541
+ if (matched !== 1) {
542
+ throw new Error(`WEL ${welId}: expected exactly 1 matched AEL, got ${matched} — ${JSON.stringify(byStatus)}`)
543
+ }
544
+ if ((byStatus.skipped ?? 0) !== 3) {
545
+ throw new Error(`WEL ${welId}: expected 3 :skipped AELs — ${JSON.stringify(byStatus)}`)
546
+ }
547
+ }
548
+ ```
549
+
550
+ # Branches
551
+
552
+ - **The filter is permissive** — `filter_config.body: 'true'` passes
553
+ every row, so all three lead rows reach the agent. The interesting
554
+ routing happens at the decision step, not the filter. A production
555
+ scoring workflow might gate on `lead_source` or a not-yet-contacted
556
+ flag in the filter; that polarity is covered by the standard-workflow
557
+ cookbook.
558
+ - **Agent emits an out-of-enum band** — the LLM response schema's
559
+ `enum: ['hot','warm','cold','spam']` constraint guards the decision
560
+ interpolation. If the model returned an unexpected string the
561
+ workflow row's execution log would land `:failed`. The anchor vitest
562
+ treats that as a model-quality failure rather than a platform bug;
563
+ production deployments either tighten the prompt or add a `default`
564
+ SMS action as a fallback band.
565
+ - **Per-band SMS template variation** — each action in the `actions`
566
+ array carries its own `tool_call.body.body` Liquid template. The
567
+ cookbook renders the same body shape with the band name interpolated
568
+ for clarity; production scenarios would author distinct messages per
569
+ band (a thank-you for hot, a nurture link for warm, an
570
+ unsubscribe-friendly close for cold, no message at all for spam by
571
+ omitting that action).
572
+
573
+ # Rollback
574
+
575
+ The cookbook doctest harness does not currently tear down created
576
+ resources. The `_setup/foundation.md` setup file's runSuffix-scoped
577
+ tenant / datalake / user names mean each run is naturally isolated;
578
+ the seeded local DB is cheap to reset (`mix ecto.reset` on the
579
+ platform repo).
580
+
581
+ # Outcome
582
+
583
+ After this cookbook's ten steps run green:
584
+
585
+ - A foundation tenant exists with a foundation-domain datalake
586
+ - A Lead Submissions Generic Table, an SMS tool, a chat-completion LLM
587
+ tool, a Score Lead AI agent (qwen3-vl:8b-instruct, four-band response schema),
588
+ and a Score Lead agent-driven workflow are all registered
589
+ - Three lead rows have been ingested through the table's
590
+ auto-provisioned default DAC
591
+ - Running the workflow drove each row through the agent: the LLM
592
+ classified the lead, the decision interpolated the band, and the
593
+ matching band's SMS action fired
594
+ - The routing is verified row-by-row — every Workflow Execution Log
595
+ carries exactly one matched action and three `:skipped`, proving the
596
+ agent's output actually steered the fan-out
597
+
598
+ The business outcome — inbound leads classified by an LLM and routed
599
+ to band-specific outreach — is demonstrated end-to-end, not merely
600
+ provisioned.
601
+
602
+ # See also
603
+
604
+ - `_setup/foundation.md` — the inlined bootstrap that provisions the
605
+ tenant + datalake this cookbook starts from
606
+ - `birthday-greeting-sms-trigger.md` — the static-decision counterpart
607
+ in foundation; same SMS wiring, full data-activation chain, no agent
608
+ - `.agent/tools.md` — SMS and chat-completion tool body shapes; intent
609
+ classification
610
+ - `.agent/ai_agents.md` — AI agent registration shape; input + response
611
+ schemas; prompt config
612
+ - `.agent/workflows.md` — standard and agent-driven workflow
613
+ primitives; `ai_agents`, `context_mapping_config`, and agent-output
614
+ decision interpolation
615
+ - `.agent/generic_tables.md` — generic-table creation and the
616
+ auto-provisioned identity contract + default DAC
617
+ - `.agent/ai_sandbox.md` — bounds on the Liquid sandbox the
618
+ context-mapping and decision templates execute inside
619
+ - `integration-tests/tests/foundation/agent-driven-workflow.test.ts` —
620
+ the anchor green test (§1–§5) these snippets are lifted from
621
+ - `integration-tests/tests/foundation/generic-tables.test.ts` — §2 the
622
+ Generic Table create snippet is lifted from
623
+ - `integration-tests/tests/foundation/tools.test.ts` — the SMS tool
624
+ create snippet is lifted from