@kuralle-agents/engagement 0.3.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 (51) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +114 -0
  3. package/dist/authoring.d.ts +2 -0
  4. package/dist/authoring.js +3 -0
  5. package/dist/broadcast-ledger.d.ts +10 -0
  6. package/dist/broadcast-ledger.js +25 -0
  7. package/dist/broadcast.d.ts +23 -0
  8. package/dist/broadcast.js +28 -0
  9. package/dist/catalog.d.ts +13 -0
  10. package/dist/catalog.js +109 -0
  11. package/dist/closed-window-recovery.d.ts +3 -0
  12. package/dist/closed-window-recovery.js +31 -0
  13. package/dist/consent.d.ts +11 -0
  14. package/dist/consent.js +75 -0
  15. package/dist/drip.d.ts +26 -0
  16. package/dist/drip.js +94 -0
  17. package/dist/engagement.d.ts +22 -0
  18. package/dist/engagement.js +66 -0
  19. package/dist/index.d.ts +24 -0
  20. package/dist/index.js +23 -0
  21. package/dist/interactive-renderer.d.ts +19 -0
  22. package/dist/interactive-renderer.js +120 -0
  23. package/dist/nodes.d.ts +10 -0
  24. package/dist/nodes.js +15 -0
  25. package/dist/ownership.d.ts +5 -0
  26. package/dist/ownership.js +62 -0
  27. package/dist/policies/instagram.d.ts +7 -0
  28. package/dist/policies/instagram.js +15 -0
  29. package/dist/policies/web.d.ts +3 -0
  30. package/dist/policies/web.js +22 -0
  31. package/dist/policies/whatsapp.d.ts +11 -0
  32. package/dist/policies/whatsapp.js +23 -0
  33. package/dist/policy.d.ts +27 -0
  34. package/dist/policy.js +1 -0
  35. package/dist/render-instagram-interactive.d.ts +14 -0
  36. package/dist/render-instagram-interactive.js +78 -0
  37. package/dist/resolve-inbound-instagram.d.ts +6 -0
  38. package/dist/resolve-inbound-instagram.js +10 -0
  39. package/dist/resolve-inbound-whatsapp.d.ts +7 -0
  40. package/dist/resolve-inbound-whatsapp.js +17 -0
  41. package/dist/scheduler.d.ts +27 -0
  42. package/dist/scheduler.js +36 -0
  43. package/dist/selector.d.ts +3 -0
  44. package/dist/selector.js +45 -0
  45. package/dist/simulator.d.ts +44 -0
  46. package/dist/simulator.js +161 -0
  47. package/dist/strategist-middleware.d.ts +3 -0
  48. package/dist/strategist-middleware.js +19 -0
  49. package/dist/strategist.d.ts +67 -0
  50. package/dist/strategist.js +55 -0
  51. package/package.json +44 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,114 @@
1
+ # @kuralle-agents/engagement
2
+
3
+ Channel-agnostic engagement layer for Kuralle agents: window-safe outbound, closed-window recovery, interactive fidelity, handoff ownership, consent, and proactive messaging (broadcasts and drips).
4
+
5
+ Install with your messaging stack:
6
+
7
+ ```bash
8
+ npm install @kuralle-agents/engagement @kuralle-agents/messaging @kuralle-agents/messaging-meta @kuralle-agents/core
9
+ ```
10
+
11
+ ## What it does
12
+
13
+ `@kuralle-agents/engagement` sits between **`createMessagingRouter`** (`@kuralle-agents/messaging`) and your **Runtime** (`@kuralle-agents/core`). You write flows and agents once; per-channel behavior (24h windows, template recovery, button/list rendering, inbound id routing) lives in **`ChannelPolicy`** adapters, not in bot code.
14
+
15
+ ## `engagement({ policies })`
16
+
17
+ The single wiring call returns `{ bridge, broadcasts }`:
18
+
19
+ | Export | Role |
20
+ |--------|------|
21
+ | **`bridge`** | Fields to spread into `createMessagingRouter`: `outbound`, `inputResolver`, `windowStore`, `ownership`, `consent` |
22
+ | **`broadcasts`** | `BroadcastApi` for campaign sends (requires `broadcastPipeline` — see below) |
23
+
24
+ ```typescript
25
+ import { createMessagingRouter, InMemoryWindowStore } from '@kuralle-agents/messaging';
26
+ import {
27
+ engagement,
28
+ whatsappPolicy,
29
+ webPolicy,
30
+ instagramPolicy,
31
+ sessionConsentStore,
32
+ sessionOwnershipStore,
33
+ } from '@kuralle-agents/engagement';
34
+
35
+ const windowStore = new InMemoryWindowStore();
36
+ const eng = engagement({
37
+ policies: [
38
+ whatsappPolicy({ client: whatsapp, selector, windowStore, wabaId }),
39
+ webPolicy(),
40
+ instagramPolicy({ client: instagram, windowStore }),
41
+ ],
42
+ consent: sessionConsentStore(sessionStore),
43
+ ownership: sessionOwnershipStore(sessionStore),
44
+ windowStore,
45
+ broadcastPipeline, // optional — required for eng.broadcasts.send()
46
+ });
47
+
48
+ const router = createMessagingRouter({
49
+ runtime,
50
+ platforms: { whatsapp, instagram },
51
+ ...eng.bridge,
52
+ });
53
+ ```
54
+
55
+ ### Outbound pipeline (window-safe)
56
+
57
+ `bridge.outbound` is built in order (gates only when the store is provided):
58
+
59
+ 1. **`consentGate`** — blocks sends when the customer has opted out
60
+ 2. **`ownershipGate`** — suppresses bot sends while a thread is human-owned
61
+ 3. **`closedWindowRecovery`** — applies each policy’s `ClosedWindowStrategy` (templates, message tags, or defer)
62
+ 4. **`interactiveRenderer`** — turns `{ type: 'interactive' }` stream parts into channel-native payloads
63
+
64
+ **`windowGuard` is not in `bridge.outbound`.** `createMessagingRouter` appends it as the terminal middleware (`buildOutboundChain(extra) = [...extra, windowGuard]`). A closed window never leaks free-form text/media/interactive to the client.
65
+
66
+ ### Inbound
67
+
68
+ `bridge.inputResolver` is `[policyInboundResolver(policies)]`, which dispatches `policy.resolveInbound(message)` by `message.platform`. Unmatched platforms fall through to the router’s default text handling.
69
+
70
+ ### Broadcasts
71
+
72
+ Policies do not expose outbound clients, so **`engagement()` does not construct a broadcast pipeline from policies alone**. Pass **`broadcastPipeline`** (an `OutboundPipeline` you build for the target platform, e.g. WhatsApp) plus optional **`ledger`**. Without `broadcastPipeline`, `broadcasts.send()` throws — `bridge` still works for conversational traffic.
73
+
74
+ ## Channel policies
75
+
76
+ Each policy implements `ChannelPolicy`: window model, closed-window strategy, interactive rendering, and inbound mapping.
77
+
78
+ | Policy | Window | Closed window | Interactive |
79
+ |--------|--------|---------------|-------------|
80
+ | **`whatsappPolicy`** | 24h via `WindowStore` | AI template strategist (`kind: 'template'`) | Buttons (≤3), list (≤10), CTA, Flows |
81
+ | **`webPolicy`** | Always open (`hasWindow: false`) | `kind: 'none'` | Web UI buttons/lists |
82
+ | **`instagramPolicy`** | 24h | `HUMAN_AGENT` message tag for text only | Quick replies, button/generic templates |
83
+
84
+ ```typescript
85
+ import { whatsappPolicy, webPolicy, instagramPolicy } from '@kuralle-agents/engagement';
86
+ ```
87
+
88
+ ## Authoring: choices and smart send
89
+
90
+ - **`withChoices(node, options)`** — attaches `ChoiceOption[]` to a `collect`/`decide` node; the runtime emits `{ type: 'interactive', nodeId, options, prompt }` for `interactiveRenderer`.
91
+ - **`smartSend(...)`** — action node that invokes the shared closed-window strategist (WhatsApp templates when the window is closed).
92
+ - Inbound routing uses **stable option ids** (`billing`, `support`, …), not display labels — `resolveInbound` maps button/list/postback payloads to `selection.id`.
93
+
94
+ ## Consent, ownership, proactive
95
+
96
+ - **`sessionConsentStore` / `consentGate`** — opt-in/opt-out and STOP handling (customer-keyed).
97
+ - **`sessionOwnershipStore` / `ownershipGate`** — bot vs human thread ownership; human-owned inbound does not run flows.
98
+ - **`createBroadcasts` / `createDrip`** — campaign ledger idempotency and drip schedules (see exports in `src/index.ts`).
99
+
100
+ ## Example
101
+
102
+ The multi-platform demo wires all three policies on one runtime:
103
+
104
+ `packages/kuralle-messaging-meta/examples/multi-platform/server.ts`
105
+
106
+ Offline E2E: `packages/kuralle-engagement/test/same-bot-across-channels.test.ts`.
107
+
108
+ ## Related packages
109
+
110
+ - **`@kuralle-agents/messaging`** — `createMessagingRouter`, `OutboundPipeline`, `windowGuard`, `WindowStore`
111
+ - **`@kuralle-agents/messaging-meta`** — WhatsApp and Instagram clients
112
+ - **`@kuralle-agents/core`** — agents, flows, runtime
113
+
114
+ RFC: [`rfcs/whatsapp-engagement/`](../../rfcs/whatsapp-engagement/).
@@ -0,0 +1,2 @@
1
+ import type { ChoiceOption, CollectNode, DecideNode } from '@kuralle-agents/core';
2
+ export declare function withChoices<N extends CollectNode | DecideNode>(node: N, options: ChoiceOption[]): N;
@@ -0,0 +1,3 @@
1
+ export function withChoices(node, options) {
2
+ return { ...node, choices: options };
3
+ }
@@ -0,0 +1,10 @@
1
+ import { type RedisLikeClient } from '@kuralle-agents/messaging';
2
+ export interface BroadcastLedger {
3
+ /** Atomic compare-and-set. Returns true if newly added, false if the key already existed. */
4
+ putIfAbsent(key: string): Promise<boolean>;
5
+ }
6
+ export declare function createInMemoryBroadcastLedger(): BroadcastLedger;
7
+ export declare function createRedisBroadcastLedger(client: RedisLikeClient, opts?: {
8
+ keyPrefix?: string;
9
+ ttlMs?: number;
10
+ }): BroadcastLedger;
@@ -0,0 +1,25 @@
1
+ import { redisSetSucceeded, } from '@kuralle-agents/messaging';
2
+ export function createInMemoryBroadcastLedger() {
3
+ const seen = new Set();
4
+ return {
5
+ async putIfAbsent(key) {
6
+ if (seen.has(key))
7
+ return false;
8
+ seen.add(key);
9
+ return true;
10
+ },
11
+ };
12
+ }
13
+ export function createRedisBroadcastLedger(client, opts) {
14
+ const prefix = opts?.keyPrefix ?? '';
15
+ return {
16
+ async putIfAbsent(key) {
17
+ const redisKey = `${prefix}bcast:${key}`;
18
+ const setOpts = { nx: true };
19
+ if (opts?.ttlMs !== undefined)
20
+ setOpts.pxMs = opts.ttlMs;
21
+ const result = await client.set(redisKey, '1', setOpts);
22
+ return redisSetSucceeded(result);
23
+ },
24
+ };
25
+ }
@@ -0,0 +1,23 @@
1
+ import type { OutboundPipeline, OutboundTemplate, WindowState, ConsentStore } from '@kuralle-agents/messaging';
2
+ import type { BroadcastLedger } from './broadcast-ledger.js';
3
+ export interface Campaign {
4
+ id: string;
5
+ template: OutboundTemplate;
6
+ recipients: {
7
+ customerId: string;
8
+ threadId: string;
9
+ }[];
10
+ }
11
+ export interface BroadcastApi {
12
+ send(campaign: Campaign): Promise<{
13
+ sent: number;
14
+ skipped: number;
15
+ }>;
16
+ }
17
+ export declare function createBroadcasts(opts: {
18
+ pipeline: OutboundPipeline;
19
+ consent: ConsentStore;
20
+ ledger: BroadcastLedger;
21
+ platform: string;
22
+ window?: (threadId: string) => Promise<WindowState>;
23
+ }): BroadcastApi;
@@ -0,0 +1,28 @@
1
+ export function createBroadcasts(opts) {
2
+ return {
3
+ async send(campaign) {
4
+ let sent = 0;
5
+ let skipped = 0;
6
+ for (const r of campaign.recipients) {
7
+ if (!(await opts.consent.isOptedIn(r.customerId))) {
8
+ skipped++;
9
+ continue;
10
+ }
11
+ const key = `${campaign.id}:${r.customerId}`;
12
+ if (!(await opts.ledger.putIfAbsent(key))) {
13
+ skipped++;
14
+ continue;
15
+ }
16
+ const window = (await opts.window?.(r.threadId)) ?? { open: false, expiresAt: null };
17
+ await opts.pipeline.send({
18
+ threadId: r.threadId,
19
+ platform: opts.platform,
20
+ payload: { kind: 'template', template: campaign.template },
21
+ meta: { window, parts: [], sessionId: r.threadId, userId: r.customerId },
22
+ });
23
+ sent++;
24
+ }
25
+ return { sent, skipped };
26
+ },
27
+ };
28
+ }
@@ -0,0 +1,13 @@
1
+ import type { TemplateInfo } from '@kuralle-agents/messaging-meta/whatsapp';
2
+ import type { TemplateCatalog, TemplateDescriptor } from './strategist.js';
3
+ export interface WhatsAppTemplateCatalogClient {
4
+ templates: {
5
+ list(wabaId: string): Promise<TemplateInfo[]>;
6
+ };
7
+ }
8
+ export declare function mapTemplateInfoToDescriptor(info: TemplateInfo): TemplateDescriptor;
9
+ export declare function isApprovedNonPaused(descriptor: TemplateDescriptor, info: TemplateInfo): boolean;
10
+ export declare function whatsappTemplateCatalog(opts: {
11
+ client: WhatsAppTemplateCatalogClient;
12
+ wabaId: string;
13
+ }): TemplateCatalog;
@@ -0,0 +1,109 @@
1
+ const PLACEHOLDER_RE = /\{\{([^}]+)\}\}/g;
2
+ function mapStatus(status) {
3
+ const upper = status.toUpperCase();
4
+ if (upper === 'APPROVED' || upper === 'PENDING' || upper === 'REJECTED') {
5
+ return upper;
6
+ }
7
+ return 'PENDING';
8
+ }
9
+ function mapCategory(category) {
10
+ const lower = category.toLowerCase();
11
+ if (lower === 'authentication' || lower === 'marketing' || lower === 'utility') {
12
+ return lower;
13
+ }
14
+ return 'utility';
15
+ }
16
+ function mapQuality(quality) {
17
+ if (!quality)
18
+ return 'UNKNOWN';
19
+ const upper = quality.toUpperCase();
20
+ if (upper === 'GREEN' ||
21
+ upper === 'YELLOW' ||
22
+ upper === 'RED' ||
23
+ upper === 'PAUSED' ||
24
+ upper === 'DISABLED') {
25
+ return upper;
26
+ }
27
+ return 'UNKNOWN';
28
+ }
29
+ function deriveParams(info) {
30
+ const keys = new Set();
31
+ for (const component of info.components) {
32
+ const text = component.text;
33
+ if (!text)
34
+ continue;
35
+ for (const match of text.matchAll(PLACEHOLDER_RE)) {
36
+ const key = match[1]?.trim();
37
+ if (key)
38
+ keys.add(key);
39
+ }
40
+ }
41
+ return [...keys].map((key) => ({ key, required: true }));
42
+ }
43
+ export function mapTemplateInfoToDescriptor(info) {
44
+ return {
45
+ name: info.name,
46
+ language: info.language,
47
+ category: mapCategory(info.category),
48
+ status: mapStatus(info.status),
49
+ quality: mapQuality(info.quality),
50
+ params: deriveParams(info),
51
+ };
52
+ }
53
+ export function isApprovedNonPaused(descriptor, info) {
54
+ if (descriptor.status !== 'APPROVED')
55
+ return false;
56
+ if (info.paused === true)
57
+ return false;
58
+ if (descriptor.quality === 'PAUSED' || descriptor.quality === 'DISABLED')
59
+ return false;
60
+ return true;
61
+ }
62
+ export function whatsappTemplateCatalog(opts) {
63
+ let approvedCache = null;
64
+ let descriptorByName = null;
65
+ async function ensureLoaded() {
66
+ if (approvedCache !== null)
67
+ return;
68
+ const rows = await opts.client.templates.list(opts.wabaId);
69
+ const byName = new Map();
70
+ const approved = [];
71
+ for (const info of rows) {
72
+ const descriptor = mapTemplateInfoToDescriptor(info);
73
+ byName.set(descriptor.name, descriptor);
74
+ if (isApprovedNonPaused(descriptor, info)) {
75
+ approved.push(descriptor);
76
+ }
77
+ }
78
+ descriptorByName = byName;
79
+ approvedCache = approved;
80
+ }
81
+ return {
82
+ async approved() {
83
+ await ensureLoaded();
84
+ return approvedCache;
85
+ },
86
+ validateParams(name, params) {
87
+ if (!descriptorByName) {
88
+ return { ok: false, errors: ['unknown template'] };
89
+ }
90
+ const descriptor = descriptorByName.get(name);
91
+ if (!descriptor) {
92
+ return { ok: false, errors: ['unknown template'] };
93
+ }
94
+ const errors = [];
95
+ for (const { key, required } of descriptor.params) {
96
+ if (required && (params[key] === undefined || params[key] === '')) {
97
+ errors.push(`missing required param: ${key}`);
98
+ }
99
+ }
100
+ const declared = new Set(descriptor.params.map((p) => p.key));
101
+ for (const key of Object.keys(params)) {
102
+ if (!declared.has(key)) {
103
+ errors.push(`unknown param: ${key}`);
104
+ }
105
+ }
106
+ return errors.length > 0 ? { ok: false, errors } : { ok: true };
107
+ },
108
+ };
109
+ }
@@ -0,0 +1,3 @@
1
+ import type { OutboundMiddleware } from '@kuralle-agents/messaging';
2
+ import type { ChannelPolicy } from './policy.js';
3
+ export declare function closedWindowRecovery(policies: ChannelPolicy[]): OutboundMiddleware;
@@ -0,0 +1,31 @@
1
+ export function closedWindowRecovery(policies) {
2
+ const byChannel = new Map(policies.map((p) => [p.channel, p]));
3
+ return {
4
+ name: 'closed-window-recovery',
5
+ async send(req, next) {
6
+ const policy = byChannel.get(req.platform);
7
+ if (!policy || !policy.hasWindow || (await policy.isWindowOpen(req.threadId))) {
8
+ return next(req);
9
+ }
10
+ const cw = policy.closedWindow;
11
+ if (cw.kind === 'template') {
12
+ if (req.payload.kind !== 'text')
13
+ return next(req);
14
+ const d = await cw.strategist.decide({ text: req.payload.text, window: req.meta.window });
15
+ if (d.kind === 'template') {
16
+ return next({ ...req, payload: { kind: 'template', template: d.template } });
17
+ }
18
+ if (d.kind === 'defer')
19
+ return { kind: 'deferred', reason: d.reason };
20
+ return next(req);
21
+ }
22
+ if (cw.kind === 'message-tag') {
23
+ if (req.payload.kind === 'text') {
24
+ return next({ ...req, payload: { ...req.payload, tag: cw.tag } });
25
+ }
26
+ return { kind: 'deferred', reason: 'window-closed-tag-text-only' };
27
+ }
28
+ return { kind: 'deferred', reason: 'window-closed-no-recovery' };
29
+ },
30
+ };
31
+ }
@@ -0,0 +1,11 @@
1
+ import type { SessionStore } from '@kuralle-agents/core';
2
+ import type { ConsentStore, OutboundMiddleware } from '@kuralle-agents/messaging';
3
+ export declare const CONSENT_WM_KEY = "__consentOptedIn";
4
+ /**
5
+ * SessionStore-backed consent keyed by customerId.
6
+ * Default when unset: opted-out (`defaultOptedIn: false`) per REQ-11.
7
+ */
8
+ export declare function sessionConsentStore(sessionStore: SessionStore, opts?: {
9
+ defaultOptedIn?: boolean;
10
+ }): ConsentStore;
11
+ export declare function consentGate(consent: ConsentStore): OutboundMiddleware;
@@ -0,0 +1,75 @@
1
+ export const CONSENT_WM_KEY = '__consentOptedIn';
2
+ function consentSessionId(customerId) {
3
+ return `consent:${customerId}`;
4
+ }
5
+ function loadOrCreate(sessionStore, customerId) {
6
+ const id = consentSessionId(customerId);
7
+ return sessionStore.get(id).then((session) => {
8
+ if (session)
9
+ return session;
10
+ const now = new Date();
11
+ return {
12
+ id,
13
+ conversationId: id,
14
+ channelId: 'api',
15
+ createdAt: now,
16
+ updatedAt: now,
17
+ messages: [],
18
+ workingMemory: {},
19
+ currentAgent: 'main',
20
+ agentStates: {},
21
+ handoffHistory: [],
22
+ metadata: {
23
+ createdAt: now,
24
+ lastActiveAt: now,
25
+ totalTokens: 0,
26
+ totalSteps: 0,
27
+ handoffHistory: [],
28
+ },
29
+ };
30
+ });
31
+ }
32
+ /**
33
+ * SessionStore-backed consent keyed by customerId.
34
+ * Default when unset: opted-out (`defaultOptedIn: false`) per REQ-11.
35
+ */
36
+ export function sessionConsentStore(sessionStore, opts) {
37
+ const defaultOptedIn = opts?.defaultOptedIn ?? false;
38
+ return {
39
+ async isOptedIn(customerId) {
40
+ const session = await sessionStore.get(consentSessionId(customerId));
41
+ if (!session)
42
+ return defaultOptedIn;
43
+ const flag = session.workingMemory[CONSENT_WM_KEY];
44
+ if (flag === true)
45
+ return true;
46
+ if (flag === false)
47
+ return false;
48
+ return defaultOptedIn;
49
+ },
50
+ async optOut(customerId) {
51
+ const session = await loadOrCreate(sessionStore, customerId);
52
+ session.workingMemory[CONSENT_WM_KEY] = false;
53
+ session.updatedAt = new Date();
54
+ await sessionStore.save(session);
55
+ },
56
+ async optIn(customerId) {
57
+ const session = await loadOrCreate(sessionStore, customerId);
58
+ session.workingMemory[CONSENT_WM_KEY] = true;
59
+ session.updatedAt = new Date();
60
+ await sessionStore.save(session);
61
+ },
62
+ };
63
+ }
64
+ export function consentGate(consent) {
65
+ return {
66
+ name: 'consent-gate',
67
+ async send(req, next) {
68
+ const customerId = req.meta.userId;
69
+ if (!customerId || !(await consent.isOptedIn(customerId))) {
70
+ return { kind: 'deferred', reason: 'not-opted-in' };
71
+ }
72
+ return next(req);
73
+ },
74
+ };
75
+ }