@lobu/gateway 3.0.9 → 3.0.13

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 (212) hide show
  1. package/dist/api/platform.d.ts.map +1 -1
  2. package/dist/api/platform.js +7 -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/connections/chat-instance-manager.d.ts.map +1 -1
  12. package/dist/connections/chat-instance-manager.js +2 -1
  13. package/dist/connections/chat-instance-manager.js.map +1 -1
  14. package/dist/connections/interaction-bridge.d.ts +9 -2
  15. package/dist/connections/interaction-bridge.d.ts.map +1 -1
  16. package/dist/connections/interaction-bridge.js +121 -261
  17. package/dist/connections/interaction-bridge.js.map +1 -1
  18. package/dist/gateway/index.js +1 -1
  19. package/dist/gateway/index.js.map +1 -1
  20. package/dist/interactions.d.ts +9 -43
  21. package/dist/interactions.d.ts.map +1 -1
  22. package/dist/interactions.js +10 -52
  23. package/dist/interactions.js.map +1 -1
  24. package/dist/routes/public/agent.d.ts +4 -0
  25. package/dist/routes/public/agent.d.ts.map +1 -1
  26. package/dist/routes/public/agent.js +21 -0
  27. package/dist/routes/public/agent.js.map +1 -1
  28. package/dist/services/core-services.d.ts.map +1 -1
  29. package/dist/services/core-services.js +4 -0
  30. package/dist/services/core-services.js.map +1 -1
  31. package/package.json +9 -9
  32. package/src/__tests__/agent-config-routes.test.ts +0 -254
  33. package/src/__tests__/agent-history-routes.test.ts +0 -72
  34. package/src/__tests__/agent-routes.test.ts +0 -68
  35. package/src/__tests__/agent-schedules-routes.test.ts +0 -59
  36. package/src/__tests__/agent-settings-store.test.ts +0 -323
  37. package/src/__tests__/bedrock-model-catalog.test.ts +0 -40
  38. package/src/__tests__/bedrock-openai-service.test.ts +0 -157
  39. package/src/__tests__/bedrock-provider-module.test.ts +0 -56
  40. package/src/__tests__/chat-instance-manager-slack.test.ts +0 -204
  41. package/src/__tests__/chat-response-bridge.test.ts +0 -131
  42. package/src/__tests__/config-memory-plugins.test.ts +0 -92
  43. package/src/__tests__/config-request-store.test.ts +0 -127
  44. package/src/__tests__/connection-routes.test.ts +0 -144
  45. package/src/__tests__/core-services-store-selection.test.ts +0 -92
  46. package/src/__tests__/docker-deployment.test.ts +0 -1211
  47. package/src/__tests__/embedded-deployment.test.ts +0 -342
  48. package/src/__tests__/grant-store.test.ts +0 -148
  49. package/src/__tests__/http-proxy.test.ts +0 -281
  50. package/src/__tests__/instruction-service.test.ts +0 -37
  51. package/src/__tests__/link-buttons.test.ts +0 -112
  52. package/src/__tests__/lobu.test.ts +0 -32
  53. package/src/__tests__/mcp-config-service.test.ts +0 -347
  54. package/src/__tests__/mcp-proxy.test.ts +0 -694
  55. package/src/__tests__/message-handler-bridge.test.ts +0 -17
  56. package/src/__tests__/model-selection.test.ts +0 -172
  57. package/src/__tests__/oauth-templates.test.ts +0 -39
  58. package/src/__tests__/platform-adapter-slack-send.test.ts +0 -114
  59. package/src/__tests__/platform-helpers-model-resolution.test.ts +0 -253
  60. package/src/__tests__/provider-inheritance.test.ts +0 -212
  61. package/src/__tests__/routes/cli-auth.test.ts +0 -337
  62. package/src/__tests__/routes/interactions.test.ts +0 -121
  63. package/src/__tests__/secret-proxy.test.ts +0 -85
  64. package/src/__tests__/session-manager.test.ts +0 -572
  65. package/src/__tests__/setup.ts +0 -133
  66. package/src/__tests__/skill-and-mcp-registry.test.ts +0 -203
  67. package/src/__tests__/slack-routes.test.ts +0 -161
  68. package/src/__tests__/system-config-resolver.test.ts +0 -75
  69. package/src/__tests__/system-message-limiter.test.ts +0 -89
  70. package/src/__tests__/system-skills-service.test.ts +0 -362
  71. package/src/__tests__/transcription-service.test.ts +0 -222
  72. package/src/__tests__/utils/rate-limiter.test.ts +0 -102
  73. package/src/__tests__/worker-connection-manager.test.ts +0 -497
  74. package/src/__tests__/worker-job-router.test.ts +0 -722
  75. package/src/api/index.ts +0 -1
  76. package/src/api/platform.ts +0 -292
  77. package/src/api/response-renderer.ts +0 -157
  78. package/src/auth/agent-metadata-store.ts +0 -168
  79. package/src/auth/api-auth-middleware.ts +0 -69
  80. package/src/auth/api-key-provider-module.ts +0 -213
  81. package/src/auth/base-provider-module.ts +0 -201
  82. package/src/auth/bedrock/provider-module.ts +0 -110
  83. package/src/auth/chatgpt/chatgpt-oauth-module.ts +0 -185
  84. package/src/auth/chatgpt/device-code-client.ts +0 -218
  85. package/src/auth/chatgpt/index.ts +0 -1
  86. package/src/auth/claude/oauth-module.ts +0 -280
  87. package/src/auth/cli/token-service.ts +0 -249
  88. package/src/auth/external/client.ts +0 -560
  89. package/src/auth/external/device-code-client.ts +0 -235
  90. package/src/auth/mcp/config-service.ts +0 -420
  91. package/src/auth/mcp/proxy.ts +0 -1086
  92. package/src/auth/mcp/string-substitution.ts +0 -17
  93. package/src/auth/mcp/tool-cache.ts +0 -90
  94. package/src/auth/oauth/base-client.ts +0 -267
  95. package/src/auth/oauth/client.ts +0 -153
  96. package/src/auth/oauth/credentials.ts +0 -7
  97. package/src/auth/oauth/providers.ts +0 -69
  98. package/src/auth/oauth/state-store.ts +0 -150
  99. package/src/auth/oauth-templates.ts +0 -179
  100. package/src/auth/provider-catalog.ts +0 -220
  101. package/src/auth/provider-model-options.ts +0 -41
  102. package/src/auth/settings/agent-settings-store.ts +0 -565
  103. package/src/auth/settings/auth-profiles-manager.ts +0 -216
  104. package/src/auth/settings/index.ts +0 -12
  105. package/src/auth/settings/model-preference-store.ts +0 -52
  106. package/src/auth/settings/model-selection.ts +0 -135
  107. package/src/auth/settings/resolved-settings-view.ts +0 -298
  108. package/src/auth/settings/template-utils.ts +0 -44
  109. package/src/auth/settings/token-service.ts +0 -88
  110. package/src/auth/system-env-store.ts +0 -98
  111. package/src/auth/user-agents-store.ts +0 -68
  112. package/src/channels/binding-service.ts +0 -214
  113. package/src/channels/index.ts +0 -4
  114. package/src/cli/gateway.ts +0 -1312
  115. package/src/cli/index.ts +0 -74
  116. package/src/commands/built-in-commands.ts +0 -80
  117. package/src/commands/command-dispatcher.ts +0 -94
  118. package/src/commands/command-reply-adapters.ts +0 -27
  119. package/src/config/file-loader.ts +0 -618
  120. package/src/config/index.ts +0 -588
  121. package/src/config/network-allowlist.ts +0 -71
  122. package/src/connections/chat-instance-manager.ts +0 -1284
  123. package/src/connections/chat-response-bridge.ts +0 -618
  124. package/src/connections/index.ts +0 -7
  125. package/src/connections/interaction-bridge.ts +0 -831
  126. package/src/connections/message-handler-bridge.ts +0 -440
  127. package/src/connections/platform-auth-methods.ts +0 -15
  128. package/src/connections/types.ts +0 -84
  129. package/src/gateway/connection-manager.ts +0 -291
  130. package/src/gateway/index.ts +0 -698
  131. package/src/gateway/job-router.ts +0 -201
  132. package/src/gateway-main.ts +0 -200
  133. package/src/index.ts +0 -41
  134. package/src/infrastructure/queue/index.ts +0 -12
  135. package/src/infrastructure/queue/queue-producer.ts +0 -148
  136. package/src/infrastructure/queue/redis-queue.ts +0 -361
  137. package/src/infrastructure/queue/types.ts +0 -133
  138. package/src/infrastructure/redis/system-message-limiter.ts +0 -94
  139. package/src/interactions/config-request-store.ts +0 -198
  140. package/src/interactions.ts +0 -363
  141. package/src/lobu.ts +0 -311
  142. package/src/metrics/prometheus.ts +0 -159
  143. package/src/modules/module-system.ts +0 -179
  144. package/src/orchestration/base-deployment-manager.ts +0 -900
  145. package/src/orchestration/deployment-utils.ts +0 -98
  146. package/src/orchestration/impl/docker-deployment.ts +0 -620
  147. package/src/orchestration/impl/embedded-deployment.ts +0 -268
  148. package/src/orchestration/impl/index.ts +0 -8
  149. package/src/orchestration/impl/k8s/deployment.ts +0 -1061
  150. package/src/orchestration/impl/k8s/helpers.ts +0 -610
  151. package/src/orchestration/impl/k8s/index.ts +0 -1
  152. package/src/orchestration/index.ts +0 -333
  153. package/src/orchestration/message-consumer.ts +0 -584
  154. package/src/orchestration/scheduled-wakeup.ts +0 -704
  155. package/src/permissions/approval-policy.ts +0 -36
  156. package/src/permissions/grant-store.ts +0 -219
  157. package/src/platform/file-handler.ts +0 -66
  158. package/src/platform/link-buttons.ts +0 -57
  159. package/src/platform/renderer-utils.ts +0 -44
  160. package/src/platform/response-renderer.ts +0 -84
  161. package/src/platform/unified-thread-consumer.ts +0 -194
  162. package/src/platform.ts +0 -318
  163. package/src/proxy/http-proxy.ts +0 -752
  164. package/src/proxy/proxy-manager.ts +0 -81
  165. package/src/proxy/secret-proxy.ts +0 -402
  166. package/src/proxy/token-refresh-job.ts +0 -143
  167. package/src/routes/internal/audio.ts +0 -141
  168. package/src/routes/internal/device-auth.ts +0 -652
  169. package/src/routes/internal/files.ts +0 -226
  170. package/src/routes/internal/history.ts +0 -69
  171. package/src/routes/internal/images.ts +0 -127
  172. package/src/routes/internal/interactions.ts +0 -84
  173. package/src/routes/internal/middleware.ts +0 -23
  174. package/src/routes/internal/schedule.ts +0 -226
  175. package/src/routes/internal/types.ts +0 -22
  176. package/src/routes/openapi-auto.ts +0 -239
  177. package/src/routes/public/agent-access.ts +0 -23
  178. package/src/routes/public/agent-config.ts +0 -675
  179. package/src/routes/public/agent-history.ts +0 -422
  180. package/src/routes/public/agent-schedules.ts +0 -296
  181. package/src/routes/public/agent.ts +0 -1086
  182. package/src/routes/public/agents.ts +0 -373
  183. package/src/routes/public/channels.ts +0 -191
  184. package/src/routes/public/cli-auth.ts +0 -896
  185. package/src/routes/public/connections.ts +0 -574
  186. package/src/routes/public/landing.ts +0 -16
  187. package/src/routes/public/oauth.ts +0 -147
  188. package/src/routes/public/settings-auth.ts +0 -104
  189. package/src/routes/public/slack.ts +0 -173
  190. package/src/routes/shared/agent-ownership.ts +0 -101
  191. package/src/routes/shared/token-verifier.ts +0 -34
  192. package/src/services/bedrock-model-catalog.ts +0 -217
  193. package/src/services/bedrock-openai-service.ts +0 -658
  194. package/src/services/core-services.ts +0 -1072
  195. package/src/services/image-generation-service.ts +0 -257
  196. package/src/services/instruction-service.ts +0 -318
  197. package/src/services/mcp-registry.ts +0 -94
  198. package/src/services/platform-helpers.ts +0 -287
  199. package/src/services/session-manager.ts +0 -262
  200. package/src/services/settings-resolver.ts +0 -74
  201. package/src/services/system-config-resolver.ts +0 -89
  202. package/src/services/system-skills-service.ts +0 -229
  203. package/src/services/transcription-service.ts +0 -684
  204. package/src/session.ts +0 -110
  205. package/src/spaces/index.ts +0 -1
  206. package/src/spaces/space-resolver.ts +0 -17
  207. package/src/stores/in-memory-agent-store.ts +0 -403
  208. package/src/stores/redis-agent-store.ts +0 -279
  209. package/src/utils/public-url.ts +0 -44
  210. package/src/utils/rate-limiter.ts +0 -94
  211. package/tsconfig.json +0 -33
  212. package/tsconfig.tsbuildinfo +0 -1
@@ -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,194 +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 { createChildSpan, createLogger, flushTracing } 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
- // Create child span for response processing (linked to original trace)
81
- const traceparent = data.platformMetadata?.traceparent as
82
- | string
83
- | undefined;
84
- const span = createChildSpan("response_delivery", traceparent, {
85
- "lobu.message_id": data.messageId,
86
- "lobu.user_id": data.userId,
87
- "lobu.platform": data.platform || data.teamId || "unknown",
88
- });
89
-
90
- try {
91
- // Check if this response belongs to a Chat SDK connection — handle before legacy routing
92
- if (this.chatResponseBridge?.canHandle(data)) {
93
- const sessionKey = `${data.userId}:${data.originalMessageId || data.messageId}`;
94
- await this.routeToRenderer(this.chatResponseBridge, data, sessionKey);
95
- return;
96
- }
97
-
98
- // Use platform field, fall back to teamId
99
- const platformName = data.platform || data.teamId;
100
- if (!platformName) {
101
- logger.warn(
102
- `Missing platform in thread response for message ${data.messageId}, skipping`
103
- );
104
- return;
105
- }
106
-
107
- // Get platform adapter from registry
108
- const platform = this.platformRegistry.get(platformName);
109
- if (!platform) {
110
- logger.warn(
111
- `No platform adapter registered for: ${platformName}, skipping message ${data.messageId}`
112
- );
113
- return;
114
- }
115
-
116
- // Get renderer from platform
117
- const renderer = platform.getResponseRenderer?.();
118
- if (!renderer) {
119
- logger.warn(
120
- `Platform ${platformName} does not provide a response renderer, skipping message ${data.messageId}`
121
- );
122
- return;
123
- }
124
-
125
- // Create session key for tracking
126
- const sessionKey = `${data.userId}:${data.originalMessageId || data.messageId}`;
127
-
128
- logger.info(
129
- `Processing thread response for platform=${platformName}, message=${data.messageId}, session=${sessionKey}`
130
- );
131
-
132
- await this.routeToRenderer(renderer, data, sessionKey);
133
- } catch (error) {
134
- logger.error(
135
- `Error processing thread response for message ${data.messageId}:`,
136
- error
137
- );
138
- throw error;
139
- } finally {
140
- span?.end();
141
- void flushTracing();
142
- }
143
- }
144
-
145
- /**
146
- * Route the payload to the appropriate renderer method.
147
- */
148
- private async routeToRenderer(
149
- renderer: ResponseRenderer,
150
- data: ThreadResponsePayload,
151
- sessionKey: string
152
- ): Promise<void> {
153
- // Handle ephemeral messages (OAuth/auth flows)
154
- if (data.ephemeral && data.content && renderer.handleEphemeral) {
155
- await renderer.handleEphemeral(data);
156
- return;
157
- }
158
-
159
- // Handle status updates (heartbeat with elapsed time)
160
- if (data.statusUpdate && renderer.handleStatusUpdate) {
161
- await renderer.handleStatusUpdate(data);
162
- return;
163
- }
164
-
165
- // Handle streaming delta
166
- if (data.delta && renderer.handleDelta) {
167
- await renderer.handleDelta(data, sessionKey);
168
- // Early return if no error - delta processing is complete
169
- if (!data.error) {
170
- return;
171
- }
172
- }
173
-
174
- // Handle error
175
- if (data.error) {
176
- await renderer.handleError(data, sessionKey);
177
- // Also complete session on error
178
- await renderer.handleCompletion(data, sessionKey);
179
- return;
180
- }
181
-
182
- // Handle completion
183
- if (data.processedMessageIds?.length) {
184
- await renderer.handleCompletion(data, sessionKey);
185
- }
186
- }
187
-
188
- /**
189
- * Check if consumer is healthy.
190
- */
191
- isHealthy(): boolean {
192
- return this.isRunning;
193
- }
194
- }