@lobu/gateway 3.0.5 → 3.0.6

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 (175) hide show
  1. package/package.json +2 -2
  2. package/src/__tests__/agent-config-routes.test.ts +254 -0
  3. package/src/__tests__/agent-history-routes.test.ts +72 -0
  4. package/src/__tests__/agent-routes.test.ts +68 -0
  5. package/src/__tests__/agent-schedules-routes.test.ts +59 -0
  6. package/src/__tests__/agent-settings-store.test.ts +323 -0
  7. package/src/__tests__/chat-instance-manager-slack.test.ts +204 -0
  8. package/src/__tests__/chat-response-bridge.test.ts +131 -0
  9. package/src/__tests__/config-memory-plugins.test.ts +92 -0
  10. package/src/__tests__/config-request-store.test.ts +127 -0
  11. package/src/__tests__/connection-routes.test.ts +144 -0
  12. package/src/__tests__/core-services-store-selection.test.ts +92 -0
  13. package/src/__tests__/docker-deployment.test.ts +1211 -0
  14. package/src/__tests__/embedded-deployment.test.ts +342 -0
  15. package/src/__tests__/grant-store.test.ts +148 -0
  16. package/src/__tests__/http-proxy.test.ts +281 -0
  17. package/src/__tests__/instruction-service.test.ts +37 -0
  18. package/src/__tests__/link-buttons.test.ts +112 -0
  19. package/src/__tests__/lobu.test.ts +32 -0
  20. package/src/__tests__/mcp-config-service.test.ts +347 -0
  21. package/src/__tests__/mcp-proxy.test.ts +696 -0
  22. package/src/__tests__/message-handler-bridge.test.ts +17 -0
  23. package/src/__tests__/model-selection.test.ts +172 -0
  24. package/src/__tests__/oauth-templates.test.ts +39 -0
  25. package/src/__tests__/platform-adapter-slack-send.test.ts +114 -0
  26. package/src/__tests__/platform-helpers-model-resolution.test.ts +253 -0
  27. package/src/__tests__/provider-inheritance.test.ts +212 -0
  28. package/src/__tests__/routes/cli-auth.test.ts +337 -0
  29. package/src/__tests__/routes/interactions.test.ts +121 -0
  30. package/src/__tests__/secret-proxy.test.ts +85 -0
  31. package/src/__tests__/session-manager.test.ts +572 -0
  32. package/src/__tests__/setup.ts +133 -0
  33. package/src/__tests__/skill-and-mcp-registry.test.ts +203 -0
  34. package/src/__tests__/slack-routes.test.ts +161 -0
  35. package/src/__tests__/system-config-resolver.test.ts +75 -0
  36. package/src/__tests__/system-message-limiter.test.ts +89 -0
  37. package/src/__tests__/system-skills-service.test.ts +362 -0
  38. package/src/__tests__/transcription-service.test.ts +222 -0
  39. package/src/__tests__/utils/rate-limiter.test.ts +102 -0
  40. package/src/__tests__/worker-connection-manager.test.ts +497 -0
  41. package/src/__tests__/worker-job-router.test.ts +722 -0
  42. package/src/api/index.ts +1 -0
  43. package/src/api/platform.ts +292 -0
  44. package/src/api/response-renderer.ts +157 -0
  45. package/src/auth/agent-metadata-store.ts +168 -0
  46. package/src/auth/api-auth-middleware.ts +69 -0
  47. package/src/auth/api-key-provider-module.ts +213 -0
  48. package/src/auth/base-provider-module.ts +201 -0
  49. package/src/auth/chatgpt/chatgpt-oauth-module.ts +185 -0
  50. package/src/auth/chatgpt/device-code-client.ts +218 -0
  51. package/src/auth/chatgpt/index.ts +1 -0
  52. package/src/auth/claude/oauth-module.ts +280 -0
  53. package/src/auth/cli/token-service.ts +249 -0
  54. package/src/auth/external/client.ts +560 -0
  55. package/src/auth/external/device-code-client.ts +225 -0
  56. package/src/auth/mcp/config-service.ts +392 -0
  57. package/src/auth/mcp/proxy.ts +1088 -0
  58. package/src/auth/mcp/string-substitution.ts +17 -0
  59. package/src/auth/mcp/tool-cache.ts +90 -0
  60. package/src/auth/oauth/base-client.ts +267 -0
  61. package/src/auth/oauth/client.ts +153 -0
  62. package/src/auth/oauth/credentials.ts +7 -0
  63. package/src/auth/oauth/providers.ts +69 -0
  64. package/src/auth/oauth/state-store.ts +150 -0
  65. package/src/auth/oauth-templates.ts +179 -0
  66. package/src/auth/provider-catalog.ts +220 -0
  67. package/src/auth/provider-model-options.ts +41 -0
  68. package/src/auth/settings/agent-settings-store.ts +565 -0
  69. package/src/auth/settings/auth-profiles-manager.ts +216 -0
  70. package/src/auth/settings/index.ts +12 -0
  71. package/src/auth/settings/model-preference-store.ts +52 -0
  72. package/src/auth/settings/model-selection.ts +135 -0
  73. package/src/auth/settings/resolved-settings-view.ts +298 -0
  74. package/src/auth/settings/template-utils.ts +44 -0
  75. package/src/auth/settings/token-service.ts +88 -0
  76. package/src/auth/system-env-store.ts +98 -0
  77. package/src/auth/user-agents-store.ts +68 -0
  78. package/src/channels/binding-service.ts +214 -0
  79. package/src/channels/index.ts +4 -0
  80. package/src/cli/gateway.ts +1304 -0
  81. package/src/cli/index.ts +74 -0
  82. package/src/commands/built-in-commands.ts +80 -0
  83. package/src/commands/command-dispatcher.ts +94 -0
  84. package/src/commands/command-reply-adapters.ts +27 -0
  85. package/src/config/file-loader.ts +618 -0
  86. package/src/config/index.ts +588 -0
  87. package/src/config/network-allowlist.ts +71 -0
  88. package/src/connections/chat-instance-manager.ts +1284 -0
  89. package/src/connections/chat-response-bridge.ts +618 -0
  90. package/src/connections/index.ts +7 -0
  91. package/src/connections/interaction-bridge.ts +831 -0
  92. package/src/connections/message-handler-bridge.ts +415 -0
  93. package/src/connections/platform-auth-methods.ts +15 -0
  94. package/src/connections/types.ts +84 -0
  95. package/src/gateway/connection-manager.ts +291 -0
  96. package/src/gateway/index.ts +700 -0
  97. package/src/gateway/job-router.ts +201 -0
  98. package/src/gateway-main.ts +200 -0
  99. package/src/index.ts +41 -0
  100. package/src/infrastructure/queue/index.ts +12 -0
  101. package/src/infrastructure/queue/queue-producer.ts +148 -0
  102. package/src/infrastructure/queue/redis-queue.ts +361 -0
  103. package/src/infrastructure/queue/types.ts +133 -0
  104. package/src/infrastructure/redis/system-message-limiter.ts +94 -0
  105. package/src/interactions/config-request-store.ts +198 -0
  106. package/src/interactions.ts +363 -0
  107. package/src/lobu.ts +311 -0
  108. package/src/metrics/prometheus.ts +159 -0
  109. package/src/modules/module-system.ts +179 -0
  110. package/src/orchestration/base-deployment-manager.ts +900 -0
  111. package/src/orchestration/deployment-utils.ts +98 -0
  112. package/src/orchestration/impl/docker-deployment.ts +620 -0
  113. package/src/orchestration/impl/embedded-deployment.ts +268 -0
  114. package/src/orchestration/impl/index.ts +8 -0
  115. package/src/orchestration/impl/k8s/deployment.ts +1061 -0
  116. package/src/orchestration/impl/k8s/helpers.ts +610 -0
  117. package/src/orchestration/impl/k8s/index.ts +1 -0
  118. package/src/orchestration/index.ts +333 -0
  119. package/src/orchestration/message-consumer.ts +584 -0
  120. package/src/orchestration/scheduled-wakeup.ts +704 -0
  121. package/src/permissions/approval-policy.ts +36 -0
  122. package/src/permissions/grant-store.ts +219 -0
  123. package/src/platform/file-handler.ts +66 -0
  124. package/src/platform/link-buttons.ts +57 -0
  125. package/src/platform/renderer-utils.ts +44 -0
  126. package/src/platform/response-renderer.ts +84 -0
  127. package/src/platform/unified-thread-consumer.ts +187 -0
  128. package/src/platform.ts +318 -0
  129. package/src/proxy/http-proxy.ts +752 -0
  130. package/src/proxy/proxy-manager.ts +81 -0
  131. package/src/proxy/secret-proxy.ts +402 -0
  132. package/src/proxy/token-refresh-job.ts +143 -0
  133. package/src/routes/internal/audio.ts +141 -0
  134. package/src/routes/internal/device-auth.ts +566 -0
  135. package/src/routes/internal/files.ts +226 -0
  136. package/src/routes/internal/history.ts +69 -0
  137. package/src/routes/internal/images.ts +127 -0
  138. package/src/routes/internal/interactions.ts +84 -0
  139. package/src/routes/internal/middleware.ts +23 -0
  140. package/src/routes/internal/schedule.ts +226 -0
  141. package/src/routes/internal/types.ts +22 -0
  142. package/src/routes/openapi-auto.ts +239 -0
  143. package/src/routes/public/agent-access.ts +23 -0
  144. package/src/routes/public/agent-config.ts +675 -0
  145. package/src/routes/public/agent-history.ts +422 -0
  146. package/src/routes/public/agent-schedules.ts +296 -0
  147. package/src/routes/public/agent.ts +1086 -0
  148. package/src/routes/public/agents.ts +373 -0
  149. package/src/routes/public/channels.ts +191 -0
  150. package/src/routes/public/cli-auth.ts +883 -0
  151. package/src/routes/public/connections.ts +574 -0
  152. package/src/routes/public/landing.ts +16 -0
  153. package/src/routes/public/oauth.ts +147 -0
  154. package/src/routes/public/settings-auth.ts +104 -0
  155. package/src/routes/public/slack.ts +173 -0
  156. package/src/routes/shared/agent-ownership.ts +101 -0
  157. package/src/routes/shared/token-verifier.ts +34 -0
  158. package/src/services/core-services.ts +1053 -0
  159. package/src/services/image-generation-service.ts +257 -0
  160. package/src/services/instruction-service.ts +318 -0
  161. package/src/services/mcp-registry.ts +94 -0
  162. package/src/services/platform-helpers.ts +287 -0
  163. package/src/services/session-manager.ts +262 -0
  164. package/src/services/settings-resolver.ts +74 -0
  165. package/src/services/system-config-resolver.ts +90 -0
  166. package/src/services/system-skills-service.ts +229 -0
  167. package/src/services/transcription-service.ts +684 -0
  168. package/src/session.ts +110 -0
  169. package/src/spaces/index.ts +1 -0
  170. package/src/spaces/space-resolver.ts +17 -0
  171. package/src/stores/in-memory-agent-store.ts +403 -0
  172. package/src/stores/redis-agent-store.ts +279 -0
  173. package/src/utils/public-url.ts +44 -0
  174. package/src/utils/rate-limiter.ts +94 -0
  175. package/tsconfig.json +33 -0
@@ -0,0 +1,36 @@
1
+ /**
2
+ * MCP Tool Approval Policy
3
+ *
4
+ * Uses MCP protocol tool annotations to determine whether a tool call
5
+ * requires explicit user approval (grant) before execution.
6
+ *
7
+ * Per the MCP spec, the default assumption is destructiveHint=true,
8
+ * so tools without annotations require approval (conservative default).
9
+ */
10
+
11
+ export interface McpToolAnnotations {
12
+ readOnlyHint?: boolean;
13
+ destructiveHint?: boolean;
14
+ idempotentHint?: boolean;
15
+ openWorldHint?: boolean;
16
+ }
17
+
18
+ /**
19
+ * Determine if a tool call requires user approval based on its annotations.
20
+ *
21
+ * Returns false (no approval needed) when:
22
+ * - readOnlyHint is explicitly true
23
+ * - destructiveHint is explicitly false
24
+ *
25
+ * Returns true (approval required) otherwise, including when:
26
+ * - No annotations provided (conservative default)
27
+ * - destructiveHint is true (default per MCP spec)
28
+ */
29
+ export function requiresToolApproval(
30
+ annotations?: McpToolAnnotations
31
+ ): boolean {
32
+ if (!annotations) return true;
33
+ if (annotations.readOnlyHint === true) return false;
34
+ if (annotations.destructiveHint === false) return false;
35
+ return true;
36
+ }
@@ -0,0 +1,219 @@
1
+ import { createLogger } from "@lobu/core";
2
+
3
+ const logger = createLogger("grant-store");
4
+
5
+ export interface Grant {
6
+ pattern: string;
7
+ expiresAt: number | null; // Absolute timestamp (ms). null = never expires.
8
+ grantedAt: number;
9
+ denied?: boolean; // true = explicitly deny this pattern
10
+ }
11
+
12
+ const KEY_PREFIX = "grant:";
13
+
14
+ /**
15
+ * Unified grant store for URL-pattern permissions.
16
+ *
17
+ * Patterns can be:
18
+ * - Domain: "api.openai.com", "*.npmjs.org"
19
+ * - MCP tool: "/mcp/gmail/tools/send_email"
20
+ * - MCP wildcard: "/mcp/gmail/tools/*"
21
+ *
22
+ * Grants are stored in Redis with TTL matching expiresAt for automatic cleanup.
23
+ */
24
+ export class GrantStore {
25
+ constructor(private readonly redis: any) {}
26
+
27
+ /**
28
+ * Grant access to a pattern for an agent.
29
+ * If expiresAt is null, the grant never expires (no Redis TTL).
30
+ * If denied is true, the grant explicitly denies access.
31
+ */
32
+ async grant(
33
+ agentId: string,
34
+ pattern: string,
35
+ expiresAt: number | null,
36
+ denied?: boolean
37
+ ): Promise<void> {
38
+ const key = this.buildKey(agentId, pattern);
39
+ const value = JSON.stringify({
40
+ expiresAt,
41
+ grantedAt: Date.now(),
42
+ ...(denied && { denied: true }),
43
+ });
44
+
45
+ try {
46
+ if (expiresAt === null) {
47
+ await this.redis.set(key, value);
48
+ } else {
49
+ const ttlSeconds = Math.max(
50
+ 1,
51
+ Math.ceil((expiresAt - Date.now()) / 1000)
52
+ );
53
+ await this.redis.set(key, value, "EX", ttlSeconds);
54
+ }
55
+ logger.info("Granted access", { agentId, pattern, expiresAt });
56
+ } catch (error) {
57
+ logger.error("Failed to grant access", { agentId, pattern, error });
58
+ throw error;
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Parse a raw Redis value into its stored object.
64
+ * Returns null if the value is missing or malformed.
65
+ */
66
+ private parseValue(
67
+ raw: string | null
68
+ ): { expiresAt: number | null; grantedAt: number; denied?: boolean } | null {
69
+ if (!raw) return null;
70
+ try {
71
+ return JSON.parse(raw);
72
+ } catch {
73
+ return null;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Check if an agent has a grant for a pattern.
79
+ * Checks exact match first, then wildcard parents.
80
+ * Returns false if the grant has `denied: true`.
81
+ */
82
+ async hasGrant(agentId: string, pattern: string): Promise<boolean> {
83
+ // Exact match
84
+ const exactKey = this.buildKey(agentId, pattern);
85
+ try {
86
+ const parsed = this.parseValue(await this.redis.get(exactKey));
87
+ if (parsed) return !parsed.denied;
88
+ } catch (error) {
89
+ logger.error("Failed to check grant", { agentId, pattern, error });
90
+ return false;
91
+ }
92
+
93
+ // Wildcard check for MCP tool patterns:
94
+ // "/mcp/gmail/tools/send_email" is covered by "/mcp/gmail/tools/*"
95
+ if (pattern.startsWith("/mcp/")) {
96
+ const lastSlash = pattern.lastIndexOf("/");
97
+ if (lastSlash > 0) {
98
+ const wildcardPattern = `${pattern.substring(0, lastSlash)}/*`;
99
+ const wildcardKey = this.buildKey(agentId, wildcardPattern);
100
+ try {
101
+ const parsed = this.parseValue(await this.redis.get(wildcardKey));
102
+ if (parsed) return !parsed.denied;
103
+ } catch (error) {
104
+ logger.error("Failed to check wildcard grant", {
105
+ agentId,
106
+ pattern: wildcardPattern,
107
+ error,
108
+ });
109
+ }
110
+ }
111
+ }
112
+
113
+ // Wildcard check for domain patterns:
114
+ // "sub.example.com" is covered by "*.example.com"
115
+ if (!pattern.startsWith("/")) {
116
+ const parts = pattern.split(".");
117
+ if (parts.length > 2) {
118
+ const wildcardDomain = `*.${parts.slice(1).join(".")}`;
119
+ const wildcardKey = this.buildKey(agentId, wildcardDomain);
120
+ try {
121
+ const parsed = this.parseValue(await this.redis.get(wildcardKey));
122
+ if (parsed) return !parsed.denied;
123
+ } catch (error) {
124
+ logger.error("Failed to check wildcard domain grant", {
125
+ agentId,
126
+ pattern: wildcardDomain,
127
+ error,
128
+ });
129
+ }
130
+ }
131
+ }
132
+
133
+ return false;
134
+ }
135
+
136
+ /**
137
+ * Check if a pattern is explicitly denied for an agent.
138
+ */
139
+ async isDenied(agentId: string, pattern: string): Promise<boolean> {
140
+ const key = this.buildKey(agentId, pattern);
141
+ try {
142
+ const parsed = this.parseValue(await this.redis.get(key));
143
+ return parsed?.denied === true;
144
+ } catch (error) {
145
+ logger.error("Failed to check denied grant", {
146
+ agentId,
147
+ pattern,
148
+ error,
149
+ });
150
+ return false;
151
+ }
152
+ }
153
+
154
+ /**
155
+ * List all active grants for an agent.
156
+ * Uses Redis SCAN to find matching keys.
157
+ */
158
+ async listGrants(agentId: string): Promise<Grant[]> {
159
+ const prefix = `${KEY_PREFIX}${agentId}:`;
160
+ const grants: Grant[] = [];
161
+
162
+ try {
163
+ let cursor = "0";
164
+ do {
165
+ const [nextCursor, keys] = await this.redis.scan(
166
+ cursor,
167
+ "MATCH",
168
+ `${prefix}*`,
169
+ "COUNT",
170
+ 100
171
+ );
172
+ cursor = nextCursor;
173
+
174
+ if (keys.length > 0) {
175
+ const values = await this.redis.mget(...keys);
176
+ for (let i = 0; i < keys.length; i++) {
177
+ const val = values[i];
178
+ if (!val) continue;
179
+
180
+ try {
181
+ const parsed = JSON.parse(val);
182
+ const pattern = (keys[i] as string).substring(prefix.length);
183
+ grants.push({
184
+ pattern,
185
+ expiresAt: parsed.expiresAt ?? null,
186
+ grantedAt: parsed.grantedAt,
187
+ ...(parsed.denied && { denied: true }),
188
+ });
189
+ } catch {
190
+ // Skip malformed entries
191
+ }
192
+ }
193
+ }
194
+ } while (cursor !== "0");
195
+ } catch (error) {
196
+ logger.error("Failed to list grants", { agentId, error });
197
+ }
198
+
199
+ return grants;
200
+ }
201
+
202
+ /**
203
+ * Revoke a grant for an agent.
204
+ */
205
+ async revoke(agentId: string, pattern: string): Promise<void> {
206
+ const key = this.buildKey(agentId, pattern);
207
+ try {
208
+ await this.redis.del(key);
209
+ logger.info("Revoked grant", { agentId, pattern });
210
+ } catch (error) {
211
+ logger.error("Failed to revoke grant", { agentId, pattern, error });
212
+ throw error;
213
+ }
214
+ }
215
+
216
+ private buildKey(agentId: string, pattern: string): string {
217
+ return `${KEY_PREFIX}${agentId}:${pattern}`;
218
+ }
219
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * File handler interface for platform-specific file operations.
3
+ */
4
+
5
+ import type { Readable } from "node:stream";
6
+
7
+ export interface FileMetadata {
8
+ id: string;
9
+ name: string;
10
+ mimetype?: string;
11
+ size: number;
12
+ url: string;
13
+ downloadUrl?: string;
14
+ permalink?: string;
15
+ timestamp?: number;
16
+ }
17
+
18
+ export interface FileUploadResult {
19
+ fileId: string;
20
+ permalink: string;
21
+ name: string;
22
+ size: number;
23
+ }
24
+
25
+ export interface FileUploadOptions {
26
+ filename: string;
27
+ channelId: string;
28
+ threadTs?: string;
29
+ title?: string;
30
+ initialComment?: string;
31
+ sessionKey?: string;
32
+ /** Send as voice message (ptt) on platforms that support it */
33
+ voiceMessage?: boolean;
34
+ }
35
+
36
+ export interface IFileHandler {
37
+ /**
38
+ * Download a file by its platform-specific ID.
39
+ * Each platform implementation handles its own authentication internally.
40
+ */
41
+ downloadFile(
42
+ fileId: string
43
+ ): Promise<{ stream: Readable; metadata: FileMetadata }>;
44
+
45
+ uploadFile(
46
+ fileStream: Readable,
47
+ options: FileUploadOptions
48
+ ): Promise<FileUploadResult>;
49
+
50
+ generateFileToken(
51
+ sessionKey: string,
52
+ fileId: string,
53
+ expiresIn?: number
54
+ ): string;
55
+
56
+ validateFileToken(token: string): {
57
+ valid: boolean;
58
+ sessionKey?: string;
59
+ fileId?: string;
60
+ error?: string;
61
+ };
62
+
63
+ getSessionFiles(sessionKey: string): string[];
64
+
65
+ cleanupSession(sessionKey: string): void;
66
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Extract settings link buttons from markdown content.
3
+ *
4
+ * Scans for markdown links pointing to `/connect/claim?claim=...` URLs and
5
+ * returns them as structured button data, stripping the link syntax
6
+ * from the content so platforms can render native buttons instead.
7
+ */
8
+
9
+ const SETTINGS_LINK_RE =
10
+ /\[([^\]]+)\]\((https?:\/\/[^)]*\/(?:connect\/claim|agent)\?claim=[^)]+)\)/g;
11
+
12
+ /**
13
+ * Returns true when the URL points to a loopback address that
14
+ * Telegram (and other platforms) reject for inline keyboard buttons.
15
+ */
16
+ function isLocalhostUrl(url: string): boolean {
17
+ try {
18
+ const u = new URL(url);
19
+ return (
20
+ u.hostname === "localhost" ||
21
+ u.hostname === "127.0.0.1" ||
22
+ u.hostname === "::1"
23
+ );
24
+ } catch {
25
+ return true;
26
+ }
27
+ }
28
+
29
+ export interface LinkButton {
30
+ text: string;
31
+ url: string;
32
+ }
33
+
34
+ /**
35
+ * Extract `[label](settingsUrl)` markdown links and return them as
36
+ * structured buttons. The link syntax is replaced with just the label
37
+ * text so the surrounding prose still reads naturally.
38
+ */
39
+ export function extractSettingsLinkButtons(content: string): {
40
+ processedContent: string;
41
+ linkButtons: LinkButton[];
42
+ } {
43
+ const linkButtons: LinkButton[] = [];
44
+
45
+ const processedContent = content.replace(
46
+ SETTINGS_LINK_RE,
47
+ (_match, text: string, url: string) => {
48
+ if (!isLocalhostUrl(url)) {
49
+ linkButtons.push({ text, url });
50
+ }
51
+ // Replace the markdown link with just the label text
52
+ return text;
53
+ }
54
+ );
55
+
56
+ return { processedContent, linkButtons };
57
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Shared renderer and markdown utilities.
3
+ * Extracts common helpers duplicated across Telegram, WhatsApp, and Slack converters/renderers.
4
+ */
5
+
6
+ /**
7
+ * Chunk a long message into smaller parts, breaking at natural boundaries.
8
+ */
9
+ export function chunkMessage(text: string, maxLength: number): string[] {
10
+ if (text.length <= maxLength) {
11
+ return [text];
12
+ }
13
+
14
+ const chunks: string[] = [];
15
+ let remaining = text;
16
+
17
+ while (remaining.length > 0) {
18
+ if (remaining.length <= maxLength) {
19
+ chunks.push(remaining);
20
+ break;
21
+ }
22
+
23
+ let breakPoint = maxLength;
24
+
25
+ const newlineIndex = remaining.lastIndexOf("\n", maxLength);
26
+ if (newlineIndex > maxLength * 0.5) {
27
+ breakPoint = newlineIndex + 1;
28
+ } else {
29
+ const spaceIndex = remaining.lastIndexOf(" ", maxLength);
30
+ if (spaceIndex > maxLength * 0.5) {
31
+ breakPoint = spaceIndex + 1;
32
+ }
33
+ }
34
+
35
+ chunks.push(remaining.substring(0, breakPoint).trim());
36
+ remaining = remaining.substring(breakPoint).trim();
37
+ }
38
+
39
+ return chunks.filter((c) => c.length > 0);
40
+ }
41
+
42
+ export function delay(ms: number): Promise<void> {
43
+ return new Promise((resolve) => setTimeout(resolve, ms));
44
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Response renderer interface for platform-specific message rendering.
3
+ * Each platform implements this interface to handle thread responses
4
+ * in a platform-appropriate way (streaming, buffering, formatting).
5
+ */
6
+
7
+ import type { ThreadResponsePayload } from "../infrastructure/queue/types";
8
+
9
+ /**
10
+ * Interface for rendering thread responses to a specific platform.
11
+ * Implementations handle platform-specific concerns like:
12
+ * - Streaming vs buffered messages
13
+ * - Rich formatting (Slack blocks) vs plain text (WhatsApp)
14
+ * - Status indicators (thread status vs typing)
15
+ */
16
+ export interface ResponseRenderer {
17
+ /**
18
+ * Handle streaming delta content.
19
+ * Platforms that support streaming (Slack) update messages in real-time.
20
+ * Platforms without streaming (WhatsApp) buffer content for later delivery.
21
+ *
22
+ * @param payload - The thread response payload containing delta content
23
+ * @param sessionKey - Unique key for this response session (userId:messageId)
24
+ * @returns Message ID/timestamp if a message was created/updated, null otherwise
25
+ */
26
+ handleDelta?(
27
+ payload: ThreadResponsePayload,
28
+ sessionKey: string
29
+ ): Promise<string | null>;
30
+
31
+ /**
32
+ * Handle completion of response processing.
33
+ * Called when all content has been processed (processedMessageIds is set).
34
+ * Should finalize any streams, send buffered content, clear status indicators.
35
+ *
36
+ * @param payload - The thread response payload
37
+ * @param sessionKey - Unique key for this response session
38
+ */
39
+ handleCompletion(
40
+ payload: ThreadResponsePayload,
41
+ sessionKey: string
42
+ ): Promise<void>;
43
+
44
+ /**
45
+ * Handle error response.
46
+ * Display error in platform-appropriate format.
47
+ *
48
+ * @param payload - The thread response payload containing error
49
+ * @param sessionKey - Unique key for this response session
50
+ */
51
+ handleError(
52
+ payload: ThreadResponsePayload,
53
+ sessionKey: string
54
+ ): Promise<void>;
55
+
56
+ /**
57
+ * Handle status updates (heartbeat with elapsed time).
58
+ * Used to show "is running...", progress indicators, etc.
59
+ *
60
+ * @param payload - The thread response payload with statusUpdate field
61
+ */
62
+ handleStatusUpdate?(payload: ThreadResponsePayload): Promise<void>;
63
+
64
+ /**
65
+ * Handle ephemeral messages (visible only to specific user).
66
+ * Used for OAuth/auth flows, temporary notifications.
67
+ *
68
+ * @param payload - The thread response payload with ephemeral content
69
+ */
70
+ handleEphemeral?(payload: ThreadResponsePayload): Promise<void>;
71
+
72
+ /**
73
+ * Stop any active streams for a conversation.
74
+ * Called when an interaction is created to prevent messages appearing
75
+ * after the interaction prompt.
76
+ *
77
+ * @param userId - User ID
78
+ * @param conversationId - Conversation identifier
79
+ */
80
+ stopStreamForConversation?(
81
+ userId: string,
82
+ conversationId: string
83
+ ): Promise<void>;
84
+ }
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Unified thread response consumer.
3
+ * Single consumer that routes responses to platform-specific renderers
4
+ * via the PlatformRegistry, eliminating duplicate queue filtering logic.
5
+ */
6
+
7
+ import { createLogger } from "@lobu/core";
8
+ import type { ChatResponseBridge } from "../connections/chat-response-bridge";
9
+ import type {
10
+ IMessageQueue,
11
+ QueueJob,
12
+ ThreadResponsePayload,
13
+ } from "../infrastructure/queue";
14
+ import type { PlatformRegistry } from "../platform";
15
+ import type { ResponseRenderer } from "./response-renderer";
16
+
17
+ const logger = createLogger("unified-thread-consumer");
18
+
19
+ /**
20
+ * Unified consumer for thread_response queue.
21
+ * Routes responses to the appropriate platform adapter based on payload.platform field.
22
+ */
23
+ export class UnifiedThreadResponseConsumer {
24
+ private isRunning = false;
25
+
26
+ private chatResponseBridge?: ChatResponseBridge;
27
+
28
+ constructor(
29
+ private queue: IMessageQueue,
30
+ private platformRegistry: PlatformRegistry
31
+ ) {}
32
+
33
+ setChatResponseBridge(bridge: ChatResponseBridge): void {
34
+ this.chatResponseBridge = bridge;
35
+ }
36
+
37
+ /**
38
+ * Start consuming thread_response messages.
39
+ */
40
+ async start(): Promise<void> {
41
+ try {
42
+ await this.queue.start();
43
+ await this.queue.createQueue("thread_response");
44
+
45
+ await this.queue.work(
46
+ "thread_response",
47
+ this.handleThreadResponse.bind(this)
48
+ );
49
+
50
+ this.isRunning = true;
51
+ logger.debug("Unified thread response consumer started");
52
+ } catch (error) {
53
+ logger.error("Failed to start unified thread response consumer:", error);
54
+ throw error;
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Stop the consumer.
60
+ */
61
+ async stop(): Promise<void> {
62
+ this.isRunning = false;
63
+ await this.queue.stop();
64
+ logger.info("Unified thread response consumer stopped");
65
+ }
66
+
67
+ /**
68
+ * Handle a thread response job by routing to the appropriate platform renderer.
69
+ */
70
+ private async handleThreadResponse(
71
+ job: QueueJob<ThreadResponsePayload>
72
+ ): Promise<void> {
73
+ const data = job.data;
74
+
75
+ if (!data || !data.messageId) {
76
+ logger.error(`Invalid thread response data: ${JSON.stringify(data)}`);
77
+ return;
78
+ }
79
+
80
+ // Check if this response belongs to a Chat SDK connection — handle before legacy routing
81
+ if (this.chatResponseBridge?.canHandle(data)) {
82
+ const sessionKey = `${data.userId}:${data.originalMessageId || data.messageId}`;
83
+ try {
84
+ await this.routeToRenderer(this.chatResponseBridge, data, sessionKey);
85
+ } catch (error) {
86
+ logger.error("Error processing Chat SDK response:", error);
87
+ throw error;
88
+ }
89
+ return;
90
+ }
91
+
92
+ // Use platform field, fall back to teamId
93
+ const platformName = data.platform || data.teamId;
94
+ if (!platformName) {
95
+ logger.warn(
96
+ `Missing platform in thread response for message ${data.messageId}, skipping`
97
+ );
98
+ return;
99
+ }
100
+
101
+ // Get platform adapter from registry
102
+ const platform = this.platformRegistry.get(platformName);
103
+ if (!platform) {
104
+ logger.warn(
105
+ `No platform adapter registered for: ${platformName}, skipping message ${data.messageId}`
106
+ );
107
+ return;
108
+ }
109
+
110
+ // Get renderer from platform
111
+ const renderer = platform.getResponseRenderer?.();
112
+ if (!renderer) {
113
+ logger.warn(
114
+ `Platform ${platformName} does not provide a response renderer, skipping message ${data.messageId}`
115
+ );
116
+ return;
117
+ }
118
+
119
+ // Create session key for tracking
120
+ const sessionKey = `${data.userId}:${data.originalMessageId || data.messageId}`;
121
+
122
+ logger.info(
123
+ `Processing thread response for platform=${platformName}, message=${data.messageId}, session=${sessionKey}`
124
+ );
125
+
126
+ try {
127
+ await this.routeToRenderer(renderer, data, sessionKey);
128
+ } catch (error) {
129
+ logger.error(
130
+ `Error processing thread response for ${platformName}:`,
131
+ error
132
+ );
133
+ // Let queue handle retry logic
134
+ throw error;
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Route the payload to the appropriate renderer method.
140
+ */
141
+ private async routeToRenderer(
142
+ renderer: ResponseRenderer,
143
+ data: ThreadResponsePayload,
144
+ sessionKey: string
145
+ ): Promise<void> {
146
+ // Handle ephemeral messages (OAuth/auth flows)
147
+ if (data.ephemeral && data.content && renderer.handleEphemeral) {
148
+ await renderer.handleEphemeral(data);
149
+ return;
150
+ }
151
+
152
+ // Handle status updates (heartbeat with elapsed time)
153
+ if (data.statusUpdate && renderer.handleStatusUpdate) {
154
+ await renderer.handleStatusUpdate(data);
155
+ return;
156
+ }
157
+
158
+ // Handle streaming delta
159
+ if (data.delta && renderer.handleDelta) {
160
+ await renderer.handleDelta(data, sessionKey);
161
+ // Early return if no error - delta processing is complete
162
+ if (!data.error) {
163
+ return;
164
+ }
165
+ }
166
+
167
+ // Handle error
168
+ if (data.error) {
169
+ await renderer.handleError(data, sessionKey);
170
+ // Also complete session on error
171
+ await renderer.handleCompletion(data, sessionKey);
172
+ return;
173
+ }
174
+
175
+ // Handle completion
176
+ if (data.processedMessageIds?.length) {
177
+ await renderer.handleCompletion(data, sessionKey);
178
+ }
179
+ }
180
+
181
+ /**
182
+ * Check if consumer is healthy.
183
+ */
184
+ isHealthy(): boolean {
185
+ return this.isRunning;
186
+ }
187
+ }