@kuralle-agents/messaging 0.2.0 → 0.3.1

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/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 CHANGED
@@ -17,7 +17,16 @@ Provides the `PlatformClient` interface that every messaging vendor package impl
17
17
  - **`SessionResolver`** — maps inbound messages to Kuralle session IDs. Default: `{platform}:{threadId}`. Swap in `ThreadIdResolver`, `PhoneLookupResolver`, or a custom `SessionResolverChain`.
18
18
  - **`StreamMapper`** — consumes `AsyncIterable<HarnessStreamPart>`, sends typing indicators during streaming, delegates final output to a `ResponseMapper`.
19
19
  - **`MessageDeduplicator`** — LRU cache that prevents duplicate webhook processing.
20
- - **`WindowTracker`** — tracks 24-hour messaging windows per thread; used by `createMessagingRouter` to detect expired windows.
20
+ - **`WindowTracker`** / **`WindowStore`** — tracks 24-hour messaging windows per thread; used by `createMessagingRouter` to detect expired windows.
21
+ - **`OutboundPipeline`** + **`windowGuard`** — window-safe outbound path (see below).
22
+
23
+ ### Window-safe outbound
24
+
25
+ Every outbound send — default `StreamMapper` text replies, custom `responseMapper` (`ResponseContext.sendText` / `sendInteractive` / `sendMedia`), and router `fallbackMessage` on runtime errors — traverses an `OutboundPipeline` with a non-removable, terminal `windowGuard` middleware. The driver reads `WindowStore.get(threadId)` once per send and sets `req.meta.window`; when the window is closed, free-form payloads (text, media, interactive) **defer** (`{ kind: 'deferred', reason: 'window-closed' }`) with zero client calls. Templates are window-agnostic and pass through.
26
+
27
+ `createMessagingRouter` accepts optional `windowStore` (default `InMemoryWindowStore`) and `outbound` (extra middleware installed **before** `windowGuard`). Custom `responseMapper` closures still return `Promise<SendResult>`; deferred sends resolve to a synthetic result with an empty `messageId` (not delivered).
28
+
29
+ `WhatsAppClient.sendTextOrTemplate` is **deprecated** — it bypasses this pipeline. Use `OutboundPipeline` / the router instead.
21
30
  - Error classes: `MessagingError`, `RateLimitError` (with `retryAfterMs`), `WindowClosedError` (with `suggestedTemplates`), `AuthenticationError`, `PermissionError`, `RecipientError`, `TemplateError`, `MediaError`, `WebhookVerificationError`.
22
31
 
23
32
  ## Usage
@@ -0,0 +1,6 @@
1
+ /** Customer consent for outbound messaging (RFC §4.7 / REQ-11, REQ-19). */
2
+ export interface ConsentStore {
3
+ isOptedIn(customerId: string): Promise<boolean>;
4
+ optOut(customerId: string): Promise<void>;
5
+ optIn(customerId: string): Promise<void>;
6
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -12,7 +12,7 @@ import type { MessagingRouterConfig } from '../types.js';
12
12
  * and dispatches to the registered message handler
13
13
  * 2. The handler deduplicates the message, tracks the conversation window,
14
14
  * resolves the session, and streams the runtime response
15
- * 3. The stream mapper sends the response back through the platform client
15
+ * 3. The stream mapper sends the response back through the outbound pipeline
16
16
  *
17
17
  * @param config - Router configuration with runtime, platforms, and optional customizations.
18
18
  * @returns A Hono app with webhook routes mounted for each platform.
@@ -1,8 +1,47 @@
1
1
  import { Hono } from 'hono';
2
2
  import { MessageDeduplicator } from '../shared/deduplicator.js';
3
- import { WindowTracker } from './window-tracker.js';
3
+ import { InMemoryWindowStore } from './window-store.js';
4
4
  import { defaultSessionResolver } from './session-resolver.js';
5
+ import { InboundResolverChain, defaultInboundChain, } from './input-resolver-chain.js';
5
6
  import { StreamMapper } from './stream-mapper.js';
7
+ import { OutboundPipeline } from './outbound-pipeline.js';
8
+ import { windowGuard } from './middleware/window-guard.js';
9
+ function buildOutboundChain(extra) {
10
+ return [...(extra ?? []), windowGuard];
11
+ }
12
+ function emptySession(sessionId, userId) {
13
+ const now = new Date();
14
+ return {
15
+ id: sessionId,
16
+ conversationId: sessionId,
17
+ channelId: 'api',
18
+ userId,
19
+ createdAt: now,
20
+ updatedAt: now,
21
+ messages: [],
22
+ workingMemory: {},
23
+ currentAgent: 'main',
24
+ agentStates: {},
25
+ handoffHistory: [],
26
+ metadata: {
27
+ createdAt: now,
28
+ lastActiveAt: now,
29
+ totalTokens: 0,
30
+ totalSteps: 0,
31
+ handoffHistory: [],
32
+ },
33
+ };
34
+ }
35
+ async function recordInboundToHistory(config, sessionId, message, userId) {
36
+ const store = config.runtime.getSessionStore();
37
+ let session = await store.get(sessionId);
38
+ if (!session) {
39
+ session = emptySession(sessionId, userId);
40
+ }
41
+ session.messages.push({ role: 'user', content: message.text ?? '' });
42
+ session.updatedAt = new Date();
43
+ await store.save(session);
44
+ }
6
45
  /**
7
46
  * Create a Hono router that bridges messaging platform webhooks with the Kuralle runtime.
8
47
  *
@@ -15,7 +54,7 @@ import { StreamMapper } from './stream-mapper.js';
15
54
  * and dispatches to the registered message handler
16
55
  * 2. The handler deduplicates the message, tracks the conversation window,
17
56
  * resolves the session, and streams the runtime response
18
- * 3. The stream mapper sends the response back through the platform client
57
+ * 3. The stream mapper sends the response back through the outbound pipeline
19
58
  *
20
59
  * @param config - Router configuration with runtime, platforms, and optional customizations.
21
60
  * @returns A Hono app with webhook routes mounted for each platform.
@@ -39,40 +78,57 @@ import { StreamMapper } from './stream-mapper.js';
39
78
  export function createMessagingRouter(config) {
40
79
  const app = new Hono();
41
80
  const deduplicator = new MessageDeduplicator();
42
- const windowTracker = new WindowTracker();
81
+ const windowStore = config.windowStore ?? new InMemoryWindowStore();
43
82
  const sessionResolver = config.sessionResolver ?? defaultSessionResolver;
83
+ const inboundChain = config.inputResolver
84
+ ? new InboundResolverChain(config.inputResolver)
85
+ : defaultInboundChain();
44
86
  const streamMapper = new StreamMapper();
45
87
  const fallbackMessage = config.fallbackMessage ?? "Sorry, I'm having trouble right now. Please try again.";
46
88
  for (const [name, platform] of Object.entries(config.platforms)) {
47
- // -------------------------------------------------------
48
- // Register message handler
49
- // -------------------------------------------------------
89
+ const pipeline = new OutboundPipeline(buildOutboundChain(config.outbound), platform);
50
90
  platform.onMessage(async (message) => {
51
- // Deduplicate — webhooks can be retried by the platform
52
91
  if (deduplicator.isDuplicate(message.id))
53
92
  return;
54
- // Track the messaging window
55
- windowTracker.recordInbound(message.threadId, message.timestamp);
56
- // Resolve Kuralle session
93
+ await windowStore.recordInbound(message.threadId, message.timestamp);
94
+ if (config.consent && message.text?.trim().toUpperCase() === 'STOP') {
95
+ await config.consent.optOut(message.customerId);
96
+ return;
97
+ }
57
98
  const { sessionId, userId } = await sessionResolver.resolve(message);
58
- // Extract text input fall back to a type indicator for non-text messages
59
- const input = message.text ?? `[${message.type}]`;
99
+ if (config.ownership && (await config.ownership.owner(message.threadId)) === 'human') {
100
+ await recordInboundToHistory(config, sessionId, message, userId);
101
+ return;
102
+ }
103
+ const { input, selection } = await inboundChain.resolve(message);
60
104
  try {
61
- // Stream from the Kuralle runtime
62
105
  const handle = config.runtime.run({
63
106
  input,
64
107
  sessionId,
65
108
  userId,
109
+ selection,
66
110
  });
67
- // Map the stream output to platform messages
68
- await streamMapper.mapStream(handle.events, platform, message.threadId, {
111
+ const parts = await streamMapper.mapStream(handle.events, platform, message.threadId, {
69
112
  responseMapper: config.responseMapper,
113
+ pipeline,
114
+ windowStore,
115
+ sessionId,
116
+ userId,
70
117
  });
118
+ if (config.ownership &&
119
+ parts.some((p) => p.type === 'handoff' && p.targetAgent === 'human')) {
120
+ await config.ownership.claim(message.threadId, 'human');
121
+ }
71
122
  }
72
123
  catch (error) {
73
- // Attempt to send a fallback message
74
124
  try {
75
- await platform.sendText(message.threadId, fallbackMessage);
125
+ const window = await windowStore.get(message.threadId);
126
+ await pipeline.send({
127
+ threadId: message.threadId,
128
+ platform: name,
129
+ payload: { kind: 'text', text: fallbackMessage },
130
+ meta: { window, parts: [], sessionId, userId },
131
+ });
76
132
  }
77
133
  catch {
78
134
  // Cannot even send fallback — nothing more we can do
@@ -85,35 +141,19 @@ export function createMessagingRouter(config) {
85
141
  config.onError?.(error, errorContext);
86
142
  }
87
143
  });
88
- // -------------------------------------------------------
89
- // Register status handler
90
- // -------------------------------------------------------
91
144
  platform.onStatus(async (status) => {
92
- // Track window expiry from platform-reported conversation info.
93
- // Use status.threadId (set by platform clients in the same format as
94
- // inbound messages) so the window tracker key matches recordInbound().
95
145
  if (status.conversation?.expirationTimestamp && status.threadId) {
96
- windowTracker.recordExpiry(status.threadId, status.conversation.expirationTimestamp);
146
+ await windowStore.recordExpiry(status.threadId, status.conversation.expirationTimestamp);
97
147
  }
98
- // Forward to user-provided status handler
99
148
  config.onStatus?.(status);
100
149
  });
101
- // -------------------------------------------------------
102
- // Mount webhook routes
103
- // -------------------------------------------------------
104
- // GET — webhook verification (e.g. Meta's hub.verify_token challenge)
105
150
  app.get(`/${name}/webhook`, async (c) => {
106
151
  return platform.handleWebhook(c.req.raw);
107
152
  });
108
- // POST — incoming events (messages, statuses, reactions)
109
153
  app.post(`/${name}/webhook`, async (c) => {
110
154
  return platform.handleWebhook(c.req.raw);
111
155
  });
112
156
  }
113
- // -------------------------------------------------------
114
- // /health — aggregated probe. Included when at least one
115
- // platform client implements the optional healthCheck().
116
- // -------------------------------------------------------
117
157
  const hasAnyProbe = Object.values(config.platforms).some((p) => typeof p.healthCheck === 'function');
118
158
  if (hasAnyProbe) {
119
159
  app.get('/health', async (c) => {
@@ -0,0 +1,32 @@
1
+ import type { ResolvedSelection } from '@kuralle-agents/core';
2
+ import type { InboundMessage } from '../types/messages.js';
3
+ export interface InboundResolverPlugin {
4
+ readonly name: string;
5
+ tryResolve(m: InboundMessage): Promise<{
6
+ input: string;
7
+ selection?: ResolvedSelection;
8
+ } | undefined>;
9
+ }
10
+ export declare class InteractiveResolver implements InboundResolverPlugin {
11
+ readonly name = "interactive";
12
+ tryResolve(m: InboundMessage): Promise<{
13
+ input: string;
14
+ selection?: ResolvedSelection;
15
+ } | undefined>;
16
+ }
17
+ export declare class TextResolver implements InboundResolverPlugin {
18
+ readonly name = "text";
19
+ tryResolve(m: InboundMessage): Promise<{
20
+ input: string;
21
+ selection?: ResolvedSelection;
22
+ }>;
23
+ }
24
+ export declare class InboundResolverChain {
25
+ private readonly plugins;
26
+ constructor(plugins: InboundResolverPlugin[]);
27
+ resolve(m: InboundMessage): Promise<{
28
+ input: string;
29
+ selection?: ResolvedSelection;
30
+ }>;
31
+ }
32
+ export declare function defaultInboundChain(): InboundResolverChain;
@@ -0,0 +1,45 @@
1
+ export class InteractiveResolver {
2
+ name = 'interactive';
3
+ async tryResolve(m) {
4
+ const interactiveId = m.interactive?.id;
5
+ if (interactiveId) {
6
+ return { input: interactiveId, selection: { id: interactiveId } };
7
+ }
8
+ if (m.button?.payload) {
9
+ return { input: m.button.payload, selection: { id: m.button.payload } };
10
+ }
11
+ if (m.interactive?.formResponse) {
12
+ return {
13
+ input: '__flow__',
14
+ selection: { formData: m.interactive.formResponse },
15
+ };
16
+ }
17
+ return undefined;
18
+ }
19
+ }
20
+ export class TextResolver {
21
+ name = 'text';
22
+ async tryResolve(m) {
23
+ return { input: m.text ?? '', selection: undefined };
24
+ }
25
+ }
26
+ export class InboundResolverChain {
27
+ plugins;
28
+ constructor(plugins) {
29
+ this.plugins = plugins;
30
+ if (plugins.length === 0) {
31
+ throw new Error('InboundResolverChain requires at least one plugin');
32
+ }
33
+ }
34
+ async resolve(m) {
35
+ for (const plugin of this.plugins) {
36
+ const result = await plugin.tryResolve(m);
37
+ if (result !== undefined)
38
+ return result;
39
+ }
40
+ throw new Error('no inbound resolver matched');
41
+ }
42
+ }
43
+ export function defaultInboundChain() {
44
+ return new InboundResolverChain([new InteractiveResolver(), new TextResolver()]);
45
+ }
@@ -0,0 +1,4 @@
1
+ import type { OutboundMiddleware } from '../../types/outbound.js';
2
+ /** Non-removable, terminal middleware: blocks free-form payloads outside the window (REQ-1/REQ-16).
3
+ * Templates are window-agnostic and pass. A closed window DEFERS (Sprint 2 adds template conversion). */
4
+ export declare const windowGuard: OutboundMiddleware;
@@ -0,0 +1,14 @@
1
+ /** Non-removable, terminal middleware: blocks free-form payloads outside the window (REQ-1/REQ-16).
2
+ * Templates are window-agnostic and pass. A closed window DEFERS (Sprint 2 adds template conversion). */
3
+ export const windowGuard = {
4
+ name: 'window-guard',
5
+ async send(req, next) {
6
+ if (req.payload.kind === 'template')
7
+ return next(req);
8
+ if (req.payload.kind === 'text' && req.payload.tag)
9
+ return next(req);
10
+ if (req.meta.window.open)
11
+ return next(req);
12
+ return { kind: 'deferred', reason: 'window-closed' };
13
+ },
14
+ };
@@ -0,0 +1,8 @@
1
+ import type { OutboundMiddleware, OutboundRequest, OutboundSink, SendOutcome } from '../types/outbound.js';
2
+ export declare class OutboundPipeline {
3
+ private readonly mw;
4
+ private readonly sink;
5
+ constructor(mw: OutboundMiddleware[], sink: OutboundSink);
6
+ send(req: OutboundRequest): Promise<SendOutcome>;
7
+ private terminal;
8
+ }
@@ -0,0 +1,52 @@
1
+ import { isTagCapable } from '../types/outbound.js';
2
+ const WINDOW_GUARD = 'window-guard';
3
+ export class OutboundPipeline {
4
+ mw;
5
+ sink;
6
+ constructor(mw, sink) {
7
+ this.mw = mw;
8
+ this.sink = sink;
9
+ const idx = mw.findIndex((m) => m.name === WINDOW_GUARD);
10
+ if (idx === -1) {
11
+ throw new Error('window-guard middleware is required (window safety)');
12
+ }
13
+ if (idx !== mw.length - 1) {
14
+ throw new Error('window-guard must be terminal (the last middleware before the sink)');
15
+ }
16
+ }
17
+ send(req) {
18
+ const run = (i, r) => i < this.mw.length
19
+ ? this.mw[i].send(r, (nr) => run(i + 1, nr))
20
+ : this.terminal(r);
21
+ return run(0, req);
22
+ }
23
+ async terminal(r) {
24
+ const { payload, threadId } = r;
25
+ switch (payload.kind) {
26
+ case 'text':
27
+ if (payload.tag && isTagCapable(this.sink)) {
28
+ return {
29
+ kind: 'sent',
30
+ result: await this.sink.sendTextWithTag(threadId, payload.text, payload.tag),
31
+ };
32
+ }
33
+ return { kind: 'sent', result: await this.sink.sendText(threadId, payload.text) };
34
+ case 'interactive':
35
+ return {
36
+ kind: 'sent',
37
+ result: await this.sink.sendInteractive(threadId, payload.interactive),
38
+ };
39
+ case 'media':
40
+ return { kind: 'sent', result: await this.sink.sendMedia(threadId, payload.media) };
41
+ case 'template': {
42
+ if (typeof this.sink.sendTemplate !== 'function') {
43
+ throw new Error('sink has no template capability');
44
+ }
45
+ return {
46
+ kind: 'sent',
47
+ result: await this.sink.sendTemplate(threadId, payload.template),
48
+ };
49
+ }
50
+ }
51
+ }
52
+ }
@@ -0,0 +1,7 @@
1
+ /** Conversation ownership: bot vs human (RFC §4.7 / REQ-10). */
2
+ export type ConversationOwner = 'bot' | 'human';
3
+ export interface OwnershipStore {
4
+ owner(threadId: string): Promise<ConversationOwner>;
5
+ claim(threadId: string, by: string): Promise<void>;
6
+ release(threadId: string): Promise<void>;
7
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Minimal Redis client surface for durable messaging stores.
3
+ * Satisfied by ioredis, node-redis, and @upstash/redis — pass the native client
4
+ * through a thin adapter that maps `set` to PX/NX when `opts` is provided.
5
+ */
6
+ export interface RedisLikeClient {
7
+ get(key: string): Promise<string | null>;
8
+ set(key: string, value: string, opts?: {
9
+ pxMs?: number;
10
+ nx?: boolean;
11
+ }): Promise<unknown>;
12
+ del(key: string): Promise<unknown>;
13
+ }
14
+ export declare function redisSetSucceeded(result: unknown): boolean;
@@ -0,0 +1,7 @@
1
+ export function redisSetSucceeded(result) {
2
+ if (result == null)
3
+ return false;
4
+ if (result === 'OK' || result === true)
5
+ return true;
6
+ return false;
7
+ }
@@ -0,0 +1,5 @@
1
+ import type { RedisLikeClient } from './redis-client.js';
2
+ import type { WindowStore } from './window-store.js';
3
+ export declare function createRedisWindowStore(client: RedisLikeClient, opts?: {
4
+ keyPrefix?: string;
5
+ }): WindowStore;
@@ -0,0 +1,45 @@
1
+ const DEFAULT_WINDOW_MS = 24 * 60 * 60 * 1000;
2
+ function windowKey(prefix, threadId) {
3
+ return `${prefix}win:${threadId}`;
4
+ }
5
+ function parseExpiryMs(raw) {
6
+ const ms = Number(raw);
7
+ if (!Number.isFinite(ms))
8
+ return null;
9
+ return new Date(ms);
10
+ }
11
+ export function createRedisWindowStore(client, opts) {
12
+ const prefix = opts?.keyPrefix ?? '';
13
+ return {
14
+ async get(threadId) {
15
+ const raw = await client.get(windowKey(prefix, threadId));
16
+ if (raw === null)
17
+ return { open: false, expiresAt: null };
18
+ const expiresAt = parseExpiryMs(raw);
19
+ if (!expiresAt)
20
+ return { open: false, expiresAt: null };
21
+ const now = new Date();
22
+ return expiresAt > now
23
+ ? { open: true, expiresAt }
24
+ : { open: false, expiresAt };
25
+ },
26
+ async recordInbound(threadId, ts) {
27
+ const key = windowKey(prefix, threadId);
28
+ const candidate = new Date(ts.getTime() + DEFAULT_WINDOW_MS);
29
+ const raw = await client.get(key);
30
+ let expiry = candidate;
31
+ if (raw !== null) {
32
+ const existing = parseExpiryMs(raw);
33
+ if (existing && existing > expiry)
34
+ expiry = existing;
35
+ }
36
+ const pxMs = Math.max(1, expiry.getTime() - Date.now());
37
+ await client.set(key, String(expiry.getTime()), { pxMs });
38
+ },
39
+ async recordExpiry(threadId, at) {
40
+ const key = windowKey(prefix, threadId);
41
+ const pxMs = Math.max(1, at.getTime() - Date.now());
42
+ await client.set(key, String(at.getTime()), { pxMs });
43
+ },
44
+ };
45
+ }
@@ -2,11 +2,8 @@ import type { SessionResolver } from '../types.js';
2
2
  /**
3
3
  * Default session resolver that maps inbound messages to Kuralle sessions.
4
4
  *
5
- * Session ID format: `{platform}:{threadId}` — ensures uniqueness across
6
- * platforms even when thread IDs collide (e.g. phone numbers used as both
7
- * WhatsApp and SMS thread IDs).
8
- *
9
- * User ID is taken from the message sender's contact ID.
5
+ * `threadId` is already platform-scoped (e.g. `whatsapp:{phoneNumberId}:{from}`).
6
+ * User ID prefers {@link InboundMessage.customerId} over {@link ContactInfo.id}.
10
7
  */
11
8
  export declare const defaultSessionResolver: SessionResolver;
12
9
  export type { SessionResolver } from '../types.js';
@@ -1,17 +1,14 @@
1
1
  /**
2
2
  * Default session resolver that maps inbound messages to Kuralle sessions.
3
3
  *
4
- * Session ID format: `{platform}:{threadId}` — ensures uniqueness across
5
- * platforms even when thread IDs collide (e.g. phone numbers used as both
6
- * WhatsApp and SMS thread IDs).
7
- *
8
- * User ID is taken from the message sender's contact ID.
4
+ * `threadId` is already platform-scoped (e.g. `whatsapp:{phoneNumberId}:{from}`).
5
+ * User ID prefers {@link InboundMessage.customerId} over {@link ContactInfo.id}.
9
6
  */
10
7
  export const defaultSessionResolver = {
11
8
  async resolve(message) {
12
9
  return {
13
- sessionId: `${message.platform}:${message.threadId}`,
14
- userId: message.from.id,
10
+ sessionId: message.threadId,
11
+ userId: message.customerId ?? message.from.id,
15
12
  };
16
13
  },
17
14
  };
@@ -1,32 +1,8 @@
1
1
  import type { HarnessStreamPart } from '@kuralle-agents/core';
2
2
  import type { PlatformClient, StreamMapperOptions } from '../types.js';
3
- /**
4
- * Maps an Kuralle runtime stream to platform messages.
5
- *
6
- * The mapper:
7
- * 1. Starts a typing indicator interval on the platform
8
- * 2. Buffers all `text-delta` events into a complete response string
9
- * 3. Collects metadata events (suggested-questions, handoff, flow-end, done)
10
- * 4. When the stream completes, either delegates to a custom `ResponseMapper`
11
- * or uses the default behavior:
12
- * - Sends the accumulated text via `platform.sendText()`
13
- * - If suggested questions exist, sends them as interactive buttons
14
- * 5. Clears the typing indicator
15
- * 6. Returns all collected stream parts
16
- */
17
3
  export declare class StreamMapper {
18
- /**
19
- * Consume an Kuralle runtime stream and send the response to a platform.
20
- *
21
- * @param stream - The async iterable from `runtime.stream()`.
22
- * @param platform - The platform client to send messages through.
23
- * @param threadId - The thread to send responses to.
24
- * @param options - Optional configuration for response mapping and typing interval.
25
- * @returns All collected stream parts for inspection or logging.
26
- */
27
- mapStream(stream: AsyncIterable<HarnessStreamPart>, platform: PlatformClient, threadId: string, options?: StreamMapperOptions): Promise<HarnessStreamPart[]>;
28
- /**
29
- * Default response mapping: send accumulated text and optional suggested questions.
30
- */
4
+ mapStream(stream: AsyncIterable<HarnessStreamPart>, platform: PlatformClient, threadId: string, options: StreamMapperOptions): Promise<HarnessStreamPart[]>;
5
+ private buildMeta;
6
+ private sendFreeform;
31
7
  private defaultMapResponse;
32
8
  }
@@ -1,34 +1,16 @@
1
1
  /** Default interval for sending typing indicators during streaming (ms). */
2
2
  const DEFAULT_TYPING_INTERVAL_MS = 5_000;
3
- /**
4
- * Maps an Kuralle runtime stream to platform messages.
5
- *
6
- * The mapper:
7
- * 1. Starts a typing indicator interval on the platform
8
- * 2. Buffers all `text-delta` events into a complete response string
9
- * 3. Collects metadata events (suggested-questions, handoff, flow-end, done)
10
- * 4. When the stream completes, either delegates to a custom `ResponseMapper`
11
- * or uses the default behavior:
12
- * - Sends the accumulated text via `platform.sendText()`
13
- * - If suggested questions exist, sends them as interactive buttons
14
- * 5. Clears the typing indicator
15
- * 6. Returns all collected stream parts
16
- */
3
+ function outcomeToSendResult(threadId, outcome) {
4
+ if (outcome.kind === 'sent' || outcome.kind === 'converted') {
5
+ return outcome.result;
6
+ }
7
+ return { messageId: '', threadId, timestamp: new Date() };
8
+ }
17
9
  export class StreamMapper {
18
- /**
19
- * Consume an Kuralle runtime stream and send the response to a platform.
20
- *
21
- * @param stream - The async iterable from `runtime.stream()`.
22
- * @param platform - The platform client to send messages through.
23
- * @param threadId - The thread to send responses to.
24
- * @param options - Optional configuration for response mapping and typing interval.
25
- * @returns All collected stream parts for inspection or logging.
26
- */
27
10
  async mapStream(stream, platform, threadId, options) {
28
11
  const parts = [];
29
12
  let textBuffer = '';
30
- const typingIntervalMs = options?.typingIntervalMs ?? DEFAULT_TYPING_INTERVAL_MS;
31
- // Start typing indicator loop
13
+ const typingIntervalMs = options.typingIntervalMs ?? DEFAULT_TYPING_INTERVAL_MS;
32
14
  let typingActive = true;
33
15
  const typingInterval = setInterval(async () => {
34
16
  if (!typingActive)
@@ -37,10 +19,9 @@ export class StreamMapper {
37
19
  await platform.sendTypingIndicator(threadId);
38
20
  }
39
21
  catch {
40
- // Typing indicator failures are non-critical — silently ignore
22
+ // Non-critical
41
23
  }
42
24
  }, typingIntervalMs);
43
- // Send an initial typing indicator immediately
44
25
  try {
45
26
  await platform.sendTypingIndicator(threadId);
46
27
  }
@@ -50,46 +31,66 @@ export class StreamMapper {
50
31
  try {
51
32
  for await (const part of stream) {
52
33
  parts.push(part);
53
- switch (part.type) {
54
- case 'text-delta':
55
- textBuffer += part.text;
56
- break;
57
- // All other event types are collected for the response mapper
58
- // but don't require special handling during streaming
34
+ if (part.type === 'text-delta') {
35
+ textBuffer += part.text;
59
36
  }
60
37
  }
61
- // Stop typing indicator
62
38
  typingActive = false;
63
39
  clearInterval(typingInterval);
64
- // Delegate to custom response mapper or use default behavior
65
- if (options?.responseMapper) {
40
+ const meta = await this.buildMeta(options.windowStore, threadId, parts, options.sessionId, options.userId);
41
+ if (options.responseMapper) {
66
42
  await options.responseMapper.mapResponse(parts, {
67
43
  threadId,
68
44
  platform: platform.platform,
69
- sendText: (text) => platform.sendText(threadId, text),
70
- sendInteractive: (msg) => platform.sendInteractive(threadId, msg),
71
- sendMedia: (media) => platform.sendMedia(threadId, media),
45
+ sendText: (text) => this.sendFreeform(options.pipeline, platform, threadId, { kind: 'text', text }, meta),
46
+ sendInteractive: (msg) => this.sendFreeform(options.pipeline, platform, threadId, { kind: 'interactive', interactive: msg }, meta),
47
+ sendMedia: (media) => this.sendFreeform(options.pipeline, platform, threadId, { kind: 'media', media }, meta),
72
48
  });
73
49
  }
74
50
  else {
75
- await this.defaultMapResponse(platform, threadId, textBuffer, parts);
51
+ await this.defaultMapResponse(options.pipeline, platform, threadId, textBuffer, meta);
76
52
  }
77
53
  }
78
54
  finally {
79
- // Ensure typing indicator is always cleaned up
80
55
  typingActive = false;
81
56
  clearInterval(typingInterval);
82
57
  }
83
58
  return parts;
84
59
  }
85
- /**
86
- * Default response mapping: send accumulated text and optional suggested questions.
87
- */
88
- async defaultMapResponse(platform, threadId, text, parts) {
89
- // Send the accumulated text response
90
- if (text.trim().length > 0) {
91
- const formatted = platform.formatConverter.toPlatformFormat(text);
92
- await platform.sendText(threadId, formatted);
60
+ async buildMeta(windowStore, threadId, parts, sessionId, userId) {
61
+ const window = await windowStore.get(threadId);
62
+ return { window, parts, sessionId, userId };
63
+ }
64
+ async sendFreeform(pipeline, platform, threadId, payload, meta) {
65
+ const outcome = await pipeline.send({
66
+ threadId,
67
+ platform: platform.platform,
68
+ payload,
69
+ meta,
70
+ });
71
+ if (outcome.kind === 'deferred' || outcome.kind === 'suppressed') {
72
+ return outcomeToSendResult(threadId, outcome);
73
+ }
74
+ if (outcome.kind === 'sent' || outcome.kind === 'converted') {
75
+ return outcome.result;
76
+ }
77
+ return outcomeToSendResult(threadId, outcome);
78
+ }
79
+ async defaultMapResponse(pipeline, platform, threadId, text, meta) {
80
+ if (text.trim().length === 0)
81
+ return;
82
+ const formatted = platform.formatConverter.toPlatformFormat(text);
83
+ const outcome = await pipeline.send({
84
+ threadId,
85
+ platform: platform.platform,
86
+ payload: { kind: 'text', text: formatted },
87
+ meta,
88
+ });
89
+ if (outcome.kind === 'sent' || outcome.kind === 'converted') {
90
+ return;
91
+ }
92
+ if (outcome.kind === 'deferred' || outcome.kind === 'suppressed') {
93
+ return;
93
94
  }
94
95
  }
95
96
  }
@@ -0,0 +1,23 @@
1
+ import { WindowTracker } from './window-tracker.js';
2
+ /** Window state value type (RFC §4.1/§4.9). */
3
+ export type WindowState = {
4
+ open: true;
5
+ expiresAt: Date;
6
+ } | {
7
+ open: false;
8
+ expiresAt: Date | null;
9
+ };
10
+ /** Pluggable messaging-window store (RFC §4.9 / REQ-18). Fail-closed on a miss. */
11
+ export interface WindowStore {
12
+ get(threadId: string): Promise<WindowState>;
13
+ recordInbound(threadId: string, ts: Date): Promise<void>;
14
+ recordExpiry(threadId: string, at: Date): Promise<void>;
15
+ }
16
+ /** In-memory default; wraps WindowTracker. For single-process/dev (REQ-18 — durable adapter is backlog). */
17
+ export declare class InMemoryWindowStore implements WindowStore {
18
+ private readonly tracker;
19
+ constructor(tracker?: WindowTracker);
20
+ get(threadId: string): Promise<WindowState>;
21
+ recordInbound(threadId: string, ts: Date): Promise<void>;
22
+ recordExpiry(threadId: string, at: Date): Promise<void>;
23
+ }
@@ -0,0 +1,22 @@
1
+ import { WindowTracker } from './window-tracker.js';
2
+ /** In-memory default; wraps WindowTracker. For single-process/dev (REQ-18 — durable adapter is backlog). */
3
+ export class InMemoryWindowStore {
4
+ tracker;
5
+ constructor(tracker) {
6
+ this.tracker = tracker ?? new WindowTracker();
7
+ }
8
+ async get(threadId) {
9
+ const expiresAt = this.tracker.getExpiry(threadId);
10
+ if (!expiresAt)
11
+ return { open: false, expiresAt: null };
12
+ return expiresAt > new Date()
13
+ ? { open: true, expiresAt }
14
+ : { open: false, expiresAt };
15
+ }
16
+ async recordInbound(threadId, ts) {
17
+ this.tracker.recordInbound(threadId, ts);
18
+ }
19
+ async recordExpiry(threadId, at) {
20
+ this.tracker.recordExpiry(threadId, at);
21
+ }
22
+ }
package/dist/index.d.ts CHANGED
@@ -4,8 +4,17 @@ export { createMessagingRouter } from './adapter/createMessagingRouter.js';
4
4
  export { defaultSessionResolver } from './adapter/session-resolver.js';
5
5
  export { SessionResolverChain, ThreadIdResolver, PhoneLookupResolver, } from './adapter/session-resolver-chain.js';
6
6
  export type { SessionResolverPlugin } from './adapter/session-resolver-chain.js';
7
+ export { InboundResolverChain, InteractiveResolver, TextResolver, defaultInboundChain, } from './adapter/input-resolver-chain.js';
8
+ export type { InboundResolverPlugin } from './adapter/input-resolver-chain.js';
7
9
  export { StreamMapper } from './adapter/stream-mapper.js';
8
10
  export { WindowTracker } from './adapter/window-tracker.js';
11
+ export type { WindowStore, WindowState } from './adapter/window-store.js';
12
+ export { InMemoryWindowStore } from './adapter/window-store.js';
13
+ export type { RedisLikeClient } from './adapter/redis-client.js';
14
+ export { redisSetSucceeded } from './adapter/redis-client.js';
15
+ export { createRedisWindowStore } from './adapter/redis-window-store.js';
16
+ export type { OwnershipStore, ConversationOwner } from './adapter/ownership-store.js';
17
+ export type { ConsentStore } from './adapter/consent-store.js';
9
18
  export { MessageDeduplicator } from './shared/deduplicator.js';
10
19
  export { passthroughFormatter } from './shared/format-base.js';
11
20
  export type { MessageFormatter } from './shared/format-base.js';
@@ -14,3 +23,7 @@ export type { MediaCacheConfig, CachedMedia } from './shared/media-cache.js';
14
23
  export { HttpUrlStrategy, UploadStrategy, FileHashDedupStrategy, } from './shared/media-strategy.js';
15
24
  export type { MediaStrategy, ResolvedMedia, MediaUploader, UploadHandleStore, } from './shared/media-strategy.js';
16
25
  export { filterStreamParts } from './stream-filter.js';
26
+ export { OutboundPipeline } from './adapter/outbound-pipeline.js';
27
+ export { windowGuard } from './adapter/middleware/window-guard.js';
28
+ export type { OutboundSink, OutboundTemplate, OutboundTemplateComponent, OutboundMiddleware, OutboundNext, OutboundRequest, OutboundPayload, OutboundMeta, SendOutcome, DeferReason, } from './types/outbound.js';
29
+ export { isTemplateCapable, isTagCapable } from './types/outbound.js';
package/dist/index.js CHANGED
@@ -8,8 +8,12 @@ export { MessagingError, RateLimitError, WindowClosedError, AuthenticationError,
8
8
  export { createMessagingRouter } from './adapter/createMessagingRouter.js';
9
9
  export { defaultSessionResolver } from './adapter/session-resolver.js';
10
10
  export { SessionResolverChain, ThreadIdResolver, PhoneLookupResolver, } from './adapter/session-resolver-chain.js';
11
+ export { InboundResolverChain, InteractiveResolver, TextResolver, defaultInboundChain, } from './adapter/input-resolver-chain.js';
11
12
  export { StreamMapper } from './adapter/stream-mapper.js';
12
13
  export { WindowTracker } from './adapter/window-tracker.js';
14
+ export { InMemoryWindowStore } from './adapter/window-store.js';
15
+ export { redisSetSucceeded } from './adapter/redis-client.js';
16
+ export { createRedisWindowStore } from './adapter/redis-window-store.js';
13
17
  // ====================================
14
18
  // Shared
15
19
  // ====================================
@@ -21,3 +25,9 @@ export { HttpUrlStrategy, UploadStrategy, FileHashDedupStrategy, } from './share
21
25
  // Stream filter
22
26
  // ====================================
23
27
  export { filterStreamParts } from './stream-filter.js';
28
+ // ====================================
29
+ // Outbound
30
+ // ====================================
31
+ export { OutboundPipeline } from './adapter/outbound-pipeline.js';
32
+ export { windowGuard } from './adapter/middleware/window-guard.js';
33
+ export { isTemplateCapable, isTagCapable } from './types/outbound.js';
@@ -5,6 +5,12 @@
5
5
  * router config, and stream mapper options.
6
6
  */
7
7
  import type { RuntimeLike, HarnessStreamPart } from '@kuralle-agents/core';
8
+ import type { OutboundPipeline } from '../adapter/outbound-pipeline.js';
9
+ import type { WindowStore } from '../adapter/window-store.js';
10
+ import type { ConsentStore } from '../adapter/consent-store.js';
11
+ import type { OwnershipStore } from '../adapter/ownership-store.js';
12
+ import type { InboundResolverPlugin } from '../adapter/input-resolver-chain.js';
13
+ import type { OutboundMiddleware } from './outbound.js';
8
14
  import type { InboundMessage, InteractiveMessage, MediaPayload } from './messages.js';
9
15
  import type { SendResult } from './responses.js';
10
16
  import type { PlatformClient, StatusHandler } from './client.js';
@@ -45,14 +51,28 @@ export interface MessagingRouterConfig {
45
51
  runtime: RuntimeLike;
46
52
  platforms: Record<string, PlatformClient>;
47
53
  sessionResolver?: SessionResolver;
54
+ /** Custom inbound input resolvers; defaults to `[InteractiveResolver, TextResolver]`. */
55
+ inputResolver?: InboundResolverPlugin[];
48
56
  responseMapper?: ResponseMapper;
49
57
  onStatus?: StatusHandler;
50
58
  onError?: (error: Error, context: ErrorContext) => void;
51
59
  fallbackMessage?: string;
60
+ /** Extra outbound middleware installed before the non-removable terminal `windowGuard`. */
61
+ outbound?: OutboundMiddleware[];
62
+ /** Pluggable window store; defaults to in-memory (fail-closed on miss). */
63
+ windowStore?: WindowStore;
64
+ /** When set, human-owned threads skip `runtime.run` on inbound (REQ-21). */
65
+ ownership?: OwnershipStore;
66
+ /** When set, STOP inbound opts the customer out; outbound uses `consentGate` (REQ-11). */
67
+ consent?: ConsentStore;
52
68
  }
53
69
  /** Options for the stream mapper. */
54
70
  export interface StreamMapperOptions {
55
71
  responseMapper?: ResponseMapper;
56
72
  /** Interval in ms for sending typing indicators during streaming. Default: 5000. */
57
73
  typingIntervalMs?: number;
74
+ pipeline: OutboundPipeline;
75
+ windowStore: WindowStore;
76
+ sessionId: string;
77
+ userId?: string;
58
78
  }
@@ -125,6 +125,8 @@ export interface InteractiveReply {
125
125
  description?: string;
126
126
  /** Raw payload from the platform. */
127
127
  payload?: string;
128
+ /** Parsed Flow submission (`nfm_reply.response_json`). */
129
+ formResponse?: Record<string, unknown>;
128
130
  }
129
131
  /** A reaction event on a message. */
130
132
  export interface ReactionData {
@@ -177,6 +179,8 @@ export interface InboundMessage {
177
179
  platform: string;
178
180
  /** Conversation or thread identifier. */
179
181
  threadId: string;
182
+ /** Platform-scoped customer identity (e.g. WhatsApp wa_id), distinct from session/thread. */
183
+ customerId: string;
180
184
  /** Sender information. */
181
185
  from: ContactInfo;
182
186
  /** When the message was sent. */
@@ -193,6 +197,11 @@ export interface InboundMessage {
193
197
  contacts?: ContactInfo[];
194
198
  /** Interactive reply data (for interactive responses). */
195
199
  interactive?: InteractiveReply;
200
+ /** Template quick-reply tap (top-level `button`, not `interactive.button_reply`). */
201
+ button?: {
202
+ payload: string;
203
+ text: string;
204
+ };
196
205
  /** Reaction data (for reaction events). */
197
206
  reaction?: ReactionData;
198
207
  /** Reply context if this message is a reply. */
@@ -0,0 +1,83 @@
1
+ import type { HarnessStreamPart } from '@kuralle-agents/core';
2
+ import type { WindowState } from '../adapter/window-store.js';
3
+ import type { InteractiveMessage, MediaPayload } from './messages.js';
4
+ import type { SendResult } from './responses.js';
5
+ import type { PlatformClient } from './client.js';
6
+ /** Channel-neutral template component (R-10). Maps to the platform's native shape at the sink. */
7
+ export interface OutboundTemplateComponent {
8
+ type: 'header' | 'body' | 'button';
9
+ /** Positional parameter values for this component. */
10
+ params?: string[];
11
+ /** Button sub-type (e.g. `quick_reply`, `url`). */
12
+ subType?: string;
13
+ /** Zero-based button index. */
14
+ index?: number;
15
+ }
16
+ /** A channel-neutral template payload (RFC §4.2). */
17
+ export interface OutboundTemplate {
18
+ name: string;
19
+ language: string;
20
+ namedParams?: Record<string, string>;
21
+ positionalParams?: string[];
22
+ components?: OutboundTemplateComponent[];
23
+ raw?: unknown;
24
+ }
25
+ /** The channel-neutral send surface the OutboundPipeline terminates in (RFC §4.2). */
26
+ export interface OutboundSink {
27
+ sendText(to: string, text: string): Promise<SendResult>;
28
+ sendTextWithTag?(to: string, text: string, tag: string): Promise<SendResult>;
29
+ sendInteractive(to: string, msg: InteractiveMessage): Promise<SendResult>;
30
+ sendMedia(to: string, media: MediaPayload): Promise<SendResult>;
31
+ sendTemplate?(to: string, t: OutboundTemplate): Promise<SendResult>;
32
+ }
33
+ /** Capability detection — true when the client can send templates (window-agnostic payload). */
34
+ export declare function isTemplateCapable(c: PlatformClient): c is PlatformClient & Required<Pick<OutboundSink, 'sendTemplate'>>;
35
+ /** Capability detection — true when the sink can send tagged text (RFC §4.12 message-tag). */
36
+ export declare function isTagCapable(c: OutboundSink): c is OutboundSink & Required<Pick<OutboundSink, 'sendTextWithTag'>>;
37
+ export type OutboundPayload = {
38
+ kind: 'text';
39
+ text: string;
40
+ tag?: string;
41
+ } | {
42
+ kind: 'interactive';
43
+ interactive: InteractiveMessage;
44
+ } | {
45
+ kind: 'media';
46
+ media: MediaPayload;
47
+ } | {
48
+ kind: 'template';
49
+ template: OutboundTemplate;
50
+ };
51
+ export interface OutboundMeta {
52
+ window: WindowState;
53
+ parts: HarnessStreamPart[];
54
+ sessionId: string;
55
+ userId?: string;
56
+ }
57
+ export interface OutboundRequest {
58
+ threadId: string;
59
+ platform: string;
60
+ payload: OutboundPayload;
61
+ meta: OutboundMeta;
62
+ }
63
+ export type DeferReason = 'window-closed' | 'window-closed-no-recovery' | (string & {});
64
+ export type SendOutcome = {
65
+ kind: 'sent';
66
+ result: SendResult;
67
+ } | {
68
+ kind: 'converted';
69
+ result: SendResult;
70
+ template: string;
71
+ from: string;
72
+ } | {
73
+ kind: 'deferred';
74
+ reason: DeferReason;
75
+ } | {
76
+ kind: 'suppressed';
77
+ reason: string;
78
+ };
79
+ export type OutboundNext = (req: OutboundRequest) => Promise<SendOutcome>;
80
+ export interface OutboundMiddleware {
81
+ readonly name: string;
82
+ send(req: OutboundRequest, next: OutboundNext): Promise<SendOutcome>;
83
+ }
@@ -0,0 +1,8 @@
1
+ /** Capability detection — true when the client can send templates (window-agnostic payload). */
2
+ export function isTemplateCapable(c) {
3
+ return typeof c.sendTemplate === 'function';
4
+ }
5
+ /** Capability detection — true when the sink can send tagged text (RFC §4.12 message-tag). */
6
+ export function isTagCapable(c) {
7
+ return typeof c.sendTextWithTag === 'function';
8
+ }
package/package.json CHANGED
@@ -1,6 +1,12 @@
1
1
  {
2
2
  "name": "@kuralle-agents/messaging",
3
- "version": "0.2.0",
3
+ "license": "Apache-2.0",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "git+https://github.com/kuralle/kuralle-agents.git",
7
+ "directory": "packages/kuralle-messaging"
8
+ },
9
+ "version": "0.3.1",
4
10
  "description": "Core interfaces and Kuralle adapter for messaging platforms",
5
11
  "type": "module",
6
12
  "main": "dist/index.js",
@@ -20,12 +26,11 @@
20
26
  ],
21
27
  "dependencies": {
22
28
  "hono": "^4.7.4",
23
- "@kuralle-agents/core": "0.2.0"
29
+ "@kuralle-agents/core": "0.3.1"
24
30
  },
25
31
  "devDependencies": {
26
32
  "typescript": "^5.8.2",
27
- "@types/node": "^22.13.4",
28
- "@kuralle-agents/core": "0.2.0"
33
+ "@types/node": "^22.13.4"
29
34
  },
30
35
  "scripts": {
31
36
  "prebuild": "rm -rf dist",