@lobu/gateway 3.0.8 → 3.0.12

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 (219) hide show
  1. package/dist/api/platform.d.ts.map +1 -1
  2. package/dist/api/platform.js +8 -26
  3. package/dist/api/platform.js.map +1 -1
  4. package/dist/auth/mcp/proxy.d.ts +14 -0
  5. package/dist/auth/mcp/proxy.d.ts.map +1 -1
  6. package/dist/auth/mcp/proxy.js +149 -13
  7. package/dist/auth/mcp/proxy.js.map +1 -1
  8. package/dist/cli/gateway.d.ts.map +1 -1
  9. package/dist/cli/gateway.js +29 -0
  10. package/dist/cli/gateway.js.map +1 -1
  11. package/dist/cli/index.js +2 -2
  12. package/dist/cli/index.js.map +1 -1
  13. package/dist/connections/chat-instance-manager.d.ts.map +1 -1
  14. package/dist/connections/chat-instance-manager.js +2 -1
  15. package/dist/connections/chat-instance-manager.js.map +1 -1
  16. package/dist/connections/interaction-bridge.d.ts +9 -2
  17. package/dist/connections/interaction-bridge.d.ts.map +1 -1
  18. package/dist/connections/interaction-bridge.js +132 -230
  19. package/dist/connections/interaction-bridge.js.map +1 -1
  20. package/dist/connections/message-handler-bridge.d.ts.map +1 -1
  21. package/dist/connections/message-handler-bridge.js +44 -26
  22. package/dist/connections/message-handler-bridge.js.map +1 -1
  23. package/dist/interactions.d.ts +9 -43
  24. package/dist/interactions.d.ts.map +1 -1
  25. package/dist/interactions.js +10 -52
  26. package/dist/interactions.js.map +1 -1
  27. package/dist/orchestration/base-deployment-manager.js +7 -7
  28. package/dist/orchestration/base-deployment-manager.js.map +1 -1
  29. package/dist/platform/unified-thread-consumer.d.ts.map +1 -1
  30. package/dist/platform/unified-thread-consumer.js +38 -34
  31. package/dist/platform/unified-thread-consumer.js.map +1 -1
  32. package/dist/routes/public/agent.d.ts +4 -0
  33. package/dist/routes/public/agent.d.ts.map +1 -1
  34. package/dist/routes/public/agent.js +21 -0
  35. package/dist/routes/public/agent.js.map +1 -1
  36. package/dist/services/core-services.d.ts.map +1 -1
  37. package/dist/services/core-services.js +4 -0
  38. package/dist/services/core-services.js.map +1 -1
  39. package/package.json +2 -2
  40. package/src/__tests__/agent-config-routes.test.ts +0 -254
  41. package/src/__tests__/agent-history-routes.test.ts +0 -72
  42. package/src/__tests__/agent-routes.test.ts +0 -68
  43. package/src/__tests__/agent-schedules-routes.test.ts +0 -59
  44. package/src/__tests__/agent-settings-store.test.ts +0 -323
  45. package/src/__tests__/bedrock-model-catalog.test.ts +0 -40
  46. package/src/__tests__/bedrock-openai-service.test.ts +0 -157
  47. package/src/__tests__/bedrock-provider-module.test.ts +0 -56
  48. package/src/__tests__/chat-instance-manager-slack.test.ts +0 -204
  49. package/src/__tests__/chat-response-bridge.test.ts +0 -131
  50. package/src/__tests__/config-memory-plugins.test.ts +0 -92
  51. package/src/__tests__/config-request-store.test.ts +0 -127
  52. package/src/__tests__/connection-routes.test.ts +0 -144
  53. package/src/__tests__/core-services-store-selection.test.ts +0 -92
  54. package/src/__tests__/docker-deployment.test.ts +0 -1211
  55. package/src/__tests__/embedded-deployment.test.ts +0 -342
  56. package/src/__tests__/grant-store.test.ts +0 -148
  57. package/src/__tests__/http-proxy.test.ts +0 -281
  58. package/src/__tests__/instruction-service.test.ts +0 -37
  59. package/src/__tests__/link-buttons.test.ts +0 -112
  60. package/src/__tests__/lobu.test.ts +0 -32
  61. package/src/__tests__/mcp-config-service.test.ts +0 -347
  62. package/src/__tests__/mcp-proxy.test.ts +0 -694
  63. package/src/__tests__/message-handler-bridge.test.ts +0 -17
  64. package/src/__tests__/model-selection.test.ts +0 -172
  65. package/src/__tests__/oauth-templates.test.ts +0 -39
  66. package/src/__tests__/platform-adapter-slack-send.test.ts +0 -114
  67. package/src/__tests__/platform-helpers-model-resolution.test.ts +0 -253
  68. package/src/__tests__/provider-inheritance.test.ts +0 -212
  69. package/src/__tests__/routes/cli-auth.test.ts +0 -337
  70. package/src/__tests__/routes/interactions.test.ts +0 -121
  71. package/src/__tests__/secret-proxy.test.ts +0 -85
  72. package/src/__tests__/session-manager.test.ts +0 -572
  73. package/src/__tests__/setup.ts +0 -133
  74. package/src/__tests__/skill-and-mcp-registry.test.ts +0 -203
  75. package/src/__tests__/slack-routes.test.ts +0 -161
  76. package/src/__tests__/system-config-resolver.test.ts +0 -75
  77. package/src/__tests__/system-message-limiter.test.ts +0 -89
  78. package/src/__tests__/system-skills-service.test.ts +0 -362
  79. package/src/__tests__/transcription-service.test.ts +0 -222
  80. package/src/__tests__/utils/rate-limiter.test.ts +0 -102
  81. package/src/__tests__/worker-connection-manager.test.ts +0 -497
  82. package/src/__tests__/worker-job-router.test.ts +0 -722
  83. package/src/api/index.ts +0 -1
  84. package/src/api/platform.ts +0 -292
  85. package/src/api/response-renderer.ts +0 -157
  86. package/src/auth/agent-metadata-store.ts +0 -168
  87. package/src/auth/api-auth-middleware.ts +0 -69
  88. package/src/auth/api-key-provider-module.ts +0 -213
  89. package/src/auth/base-provider-module.ts +0 -201
  90. package/src/auth/bedrock/provider-module.ts +0 -110
  91. package/src/auth/chatgpt/chatgpt-oauth-module.ts +0 -185
  92. package/src/auth/chatgpt/device-code-client.ts +0 -218
  93. package/src/auth/chatgpt/index.ts +0 -1
  94. package/src/auth/claude/oauth-module.ts +0 -280
  95. package/src/auth/cli/token-service.ts +0 -249
  96. package/src/auth/external/client.ts +0 -560
  97. package/src/auth/external/device-code-client.ts +0 -235
  98. package/src/auth/mcp/config-service.ts +0 -420
  99. package/src/auth/mcp/proxy.ts +0 -1086
  100. package/src/auth/mcp/string-substitution.ts +0 -17
  101. package/src/auth/mcp/tool-cache.ts +0 -90
  102. package/src/auth/oauth/base-client.ts +0 -267
  103. package/src/auth/oauth/client.ts +0 -153
  104. package/src/auth/oauth/credentials.ts +0 -7
  105. package/src/auth/oauth/providers.ts +0 -69
  106. package/src/auth/oauth/state-store.ts +0 -150
  107. package/src/auth/oauth-templates.ts +0 -179
  108. package/src/auth/provider-catalog.ts +0 -220
  109. package/src/auth/provider-model-options.ts +0 -41
  110. package/src/auth/settings/agent-settings-store.ts +0 -565
  111. package/src/auth/settings/auth-profiles-manager.ts +0 -216
  112. package/src/auth/settings/index.ts +0 -12
  113. package/src/auth/settings/model-preference-store.ts +0 -52
  114. package/src/auth/settings/model-selection.ts +0 -135
  115. package/src/auth/settings/resolved-settings-view.ts +0 -298
  116. package/src/auth/settings/template-utils.ts +0 -44
  117. package/src/auth/settings/token-service.ts +0 -88
  118. package/src/auth/system-env-store.ts +0 -98
  119. package/src/auth/user-agents-store.ts +0 -68
  120. package/src/channels/binding-service.ts +0 -214
  121. package/src/channels/index.ts +0 -4
  122. package/src/cli/gateway.ts +0 -1312
  123. package/src/cli/index.ts +0 -74
  124. package/src/commands/built-in-commands.ts +0 -80
  125. package/src/commands/command-dispatcher.ts +0 -94
  126. package/src/commands/command-reply-adapters.ts +0 -27
  127. package/src/config/file-loader.ts +0 -618
  128. package/src/config/index.ts +0 -588
  129. package/src/config/network-allowlist.ts +0 -71
  130. package/src/connections/chat-instance-manager.ts +0 -1284
  131. package/src/connections/chat-response-bridge.ts +0 -618
  132. package/src/connections/index.ts +0 -7
  133. package/src/connections/interaction-bridge.ts +0 -831
  134. package/src/connections/message-handler-bridge.ts +0 -415
  135. package/src/connections/platform-auth-methods.ts +0 -15
  136. package/src/connections/types.ts +0 -84
  137. package/src/gateway/connection-manager.ts +0 -291
  138. package/src/gateway/index.ts +0 -698
  139. package/src/gateway/job-router.ts +0 -201
  140. package/src/gateway-main.ts +0 -200
  141. package/src/index.ts +0 -41
  142. package/src/infrastructure/queue/index.ts +0 -12
  143. package/src/infrastructure/queue/queue-producer.ts +0 -148
  144. package/src/infrastructure/queue/redis-queue.ts +0 -361
  145. package/src/infrastructure/queue/types.ts +0 -133
  146. package/src/infrastructure/redis/system-message-limiter.ts +0 -94
  147. package/src/interactions/config-request-store.ts +0 -198
  148. package/src/interactions.ts +0 -363
  149. package/src/lobu.ts +0 -311
  150. package/src/metrics/prometheus.ts +0 -159
  151. package/src/modules/module-system.ts +0 -179
  152. package/src/orchestration/base-deployment-manager.ts +0 -900
  153. package/src/orchestration/deployment-utils.ts +0 -98
  154. package/src/orchestration/impl/docker-deployment.ts +0 -620
  155. package/src/orchestration/impl/embedded-deployment.ts +0 -268
  156. package/src/orchestration/impl/index.ts +0 -8
  157. package/src/orchestration/impl/k8s/deployment.ts +0 -1061
  158. package/src/orchestration/impl/k8s/helpers.ts +0 -610
  159. package/src/orchestration/impl/k8s/index.ts +0 -1
  160. package/src/orchestration/index.ts +0 -333
  161. package/src/orchestration/message-consumer.ts +0 -584
  162. package/src/orchestration/scheduled-wakeup.ts +0 -704
  163. package/src/permissions/approval-policy.ts +0 -36
  164. package/src/permissions/grant-store.ts +0 -219
  165. package/src/platform/file-handler.ts +0 -66
  166. package/src/platform/link-buttons.ts +0 -57
  167. package/src/platform/renderer-utils.ts +0 -44
  168. package/src/platform/response-renderer.ts +0 -84
  169. package/src/platform/unified-thread-consumer.ts +0 -187
  170. package/src/platform.ts +0 -318
  171. package/src/proxy/http-proxy.ts +0 -752
  172. package/src/proxy/proxy-manager.ts +0 -81
  173. package/src/proxy/secret-proxy.ts +0 -402
  174. package/src/proxy/token-refresh-job.ts +0 -143
  175. package/src/routes/internal/audio.ts +0 -141
  176. package/src/routes/internal/device-auth.ts +0 -652
  177. package/src/routes/internal/files.ts +0 -226
  178. package/src/routes/internal/history.ts +0 -69
  179. package/src/routes/internal/images.ts +0 -127
  180. package/src/routes/internal/interactions.ts +0 -84
  181. package/src/routes/internal/middleware.ts +0 -23
  182. package/src/routes/internal/schedule.ts +0 -226
  183. package/src/routes/internal/types.ts +0 -22
  184. package/src/routes/openapi-auto.ts +0 -239
  185. package/src/routes/public/agent-access.ts +0 -23
  186. package/src/routes/public/agent-config.ts +0 -675
  187. package/src/routes/public/agent-history.ts +0 -422
  188. package/src/routes/public/agent-schedules.ts +0 -296
  189. package/src/routes/public/agent.ts +0 -1086
  190. package/src/routes/public/agents.ts +0 -373
  191. package/src/routes/public/channels.ts +0 -191
  192. package/src/routes/public/cli-auth.ts +0 -896
  193. package/src/routes/public/connections.ts +0 -574
  194. package/src/routes/public/landing.ts +0 -16
  195. package/src/routes/public/oauth.ts +0 -147
  196. package/src/routes/public/settings-auth.ts +0 -104
  197. package/src/routes/public/slack.ts +0 -173
  198. package/src/routes/shared/agent-ownership.ts +0 -101
  199. package/src/routes/shared/token-verifier.ts +0 -34
  200. package/src/services/bedrock-model-catalog.ts +0 -217
  201. package/src/services/bedrock-openai-service.ts +0 -658
  202. package/src/services/core-services.ts +0 -1072
  203. package/src/services/image-generation-service.ts +0 -257
  204. package/src/services/instruction-service.ts +0 -318
  205. package/src/services/mcp-registry.ts +0 -94
  206. package/src/services/platform-helpers.ts +0 -287
  207. package/src/services/session-manager.ts +0 -262
  208. package/src/services/settings-resolver.ts +0 -74
  209. package/src/services/system-config-resolver.ts +0 -89
  210. package/src/services/system-skills-service.ts +0 -229
  211. package/src/services/transcription-service.ts +0 -684
  212. package/src/session.ts +0 -110
  213. package/src/spaces/index.ts +0 -1
  214. package/src/spaces/space-resolver.ts +0 -17
  215. package/src/stores/in-memory-agent-store.ts +0 -403
  216. package/src/stores/redis-agent-store.ts +0 -279
  217. package/src/utils/public-url.ts +0 -44
  218. package/src/utils/rate-limiter.ts +0 -94
  219. package/tsconfig.json +0 -33
@@ -1,36 +0,0 @@
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
- }
@@ -1,219 +0,0 @@
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
- }
@@ -1,66 +0,0 @@
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
- }
@@ -1,57 +0,0 @@
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
- }
@@ -1,44 +0,0 @@
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
- }
@@ -1,84 +0,0 @@
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
- }
@@ -1,187 +0,0 @@
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
- }