@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,257 +0,0 @@
1
- import type { AuthProfile } from "@lobu/core";
2
- import { createLogger } from "@lobu/core";
3
- import type { AuthProfilesManager } from "../auth/settings/auth-profiles-manager";
4
-
5
- const logger = createLogger("image-generation-service");
6
-
7
- export type ImageGenerationProvider = "openai";
8
-
9
- interface ImageGenerationConfig {
10
- profileProviderId: string;
11
- displayName: string;
12
- provider: ImageGenerationProvider;
13
- apiKey: string;
14
- }
15
-
16
- export interface ImageGenerationSuccess {
17
- imageBuffer: Buffer;
18
- mimeType: string;
19
- provider: ImageGenerationProvider;
20
- }
21
-
22
- export interface ImageGenerationError {
23
- error: string;
24
- availableProviders: ImageGenerationProvider[];
25
- }
26
-
27
- export type ImageGenerationResult =
28
- | ImageGenerationSuccess
29
- | ImageGenerationError;
30
-
31
- export interface ImageGenerationOptions {
32
- size?: "1024x1024" | "1024x1536" | "1536x1024" | "auto";
33
- quality?: "low" | "medium" | "high" | "auto";
34
- background?: "transparent" | "opaque" | "auto";
35
- format?: "png" | "jpeg" | "webp";
36
- }
37
-
38
- const IMAGE_CAPABLE_PROVIDERS: {
39
- profileProviderId: string;
40
- provider: ImageGenerationProvider;
41
- displayName: string;
42
- }[] = [
43
- {
44
- profileProviderId: "chatgpt",
45
- provider: "openai",
46
- displayName: "OpenAI",
47
- },
48
- {
49
- profileProviderId: "openai",
50
- provider: "openai",
51
- displayName: "OpenAI-compatible",
52
- },
53
- ];
54
-
55
- function parseJwtScopes(token: string): Set<string> | null {
56
- const parts = token.split(".");
57
- if (parts.length < 2) return null;
58
- try {
59
- const payload = JSON.parse(
60
- Buffer.from(parts[1] || "", "base64url").toString("utf-8")
61
- ) as {
62
- scope?: unknown;
63
- scp?: unknown;
64
- };
65
- const scopes: string[] = [];
66
- if (typeof payload.scope === "string") {
67
- scopes.push(...payload.scope.split(/\s+/));
68
- }
69
- if (typeof payload.scp === "string") {
70
- scopes.push(...payload.scp.split(/\s+/));
71
- }
72
- if (Array.isArray(payload.scp)) {
73
- scopes.push(
74
- ...payload.scp.filter(
75
- (value): value is string => typeof value === "string"
76
- )
77
- );
78
- }
79
- const cleaned = scopes.map((scope) => scope.trim()).filter(Boolean);
80
- return cleaned.length > 0 ? new Set(cleaned) : null;
81
- } catch {
82
- return null;
83
- }
84
- }
85
-
86
- function hasImageGenerationAccess(
87
- profileProviderId: string,
88
- profile: AuthProfile
89
- ): boolean {
90
- if (profileProviderId !== "chatgpt") return true;
91
- if (profile.authType === "api-key") return true;
92
-
93
- const scopes = parseJwtScopes(profile.credential);
94
- if (!scopes) return true;
95
- return (
96
- scopes.has("api.model.image.request") ||
97
- scopes.has("api.model.request") ||
98
- scopes.has("model.image.request")
99
- );
100
- }
101
-
102
- export class ImageGenerationService {
103
- constructor(private readonly authProfilesManager: AuthProfilesManager) {}
104
-
105
- async getConfig(agentId: string): Promise<ImageGenerationConfig | null> {
106
- for (const {
107
- profileProviderId,
108
- provider,
109
- displayName,
110
- } of IMAGE_CAPABLE_PROVIDERS) {
111
- const profile = await this.authProfilesManager.getBestProfile(
112
- agentId,
113
- profileProviderId
114
- );
115
- if (!profile?.credential) continue;
116
- if (!hasImageGenerationAccess(profileProviderId, profile)) {
117
- logger.info("Skipping provider without image-generation scope", {
118
- agentId,
119
- profileProviderId,
120
- authType: profile.authType,
121
- });
122
- continue;
123
- }
124
- return {
125
- profileProviderId,
126
- displayName,
127
- provider,
128
- apiKey: profile.credential,
129
- };
130
- }
131
- return null;
132
- }
133
-
134
- getProviderInfo(): Array<{
135
- provider: ImageGenerationProvider;
136
- name: string;
137
- }> {
138
- return IMAGE_CAPABLE_PROVIDERS.map(({ provider, displayName }) => ({
139
- provider,
140
- name: displayName,
141
- }));
142
- }
143
-
144
- async generate(
145
- prompt: string,
146
- agentId: string,
147
- options: ImageGenerationOptions = {}
148
- ): Promise<ImageGenerationResult> {
149
- const config = await this.getConfig(agentId);
150
- if (!config) {
151
- return this.noProviderError(
152
- "No image generation provider configured",
153
- agentId
154
- );
155
- }
156
-
157
- logger.info("Generating image", {
158
- agentId,
159
- provider: config.provider,
160
- profileProviderId: config.profileProviderId,
161
- promptLength: prompt.length,
162
- size: options.size,
163
- quality: options.quality,
164
- background: options.background,
165
- format: options.format,
166
- });
167
-
168
- try {
169
- const result = await this.generateWithOpenAI(
170
- prompt,
171
- config.apiKey,
172
- options
173
- );
174
- return {
175
- imageBuffer: result.imageBuffer,
176
- mimeType: result.mimeType,
177
- provider: config.provider,
178
- };
179
- } catch (error) {
180
- const errorMessage =
181
- error instanceof Error ? error.message : String(error);
182
- logger.error("Image generation failed", {
183
- agentId,
184
- provider: config.provider,
185
- profileProviderId: config.profileProviderId,
186
- error: errorMessage,
187
- });
188
- return {
189
- error: `Image generation failed with ${config.displayName}: ${errorMessage}`,
190
- availableProviders: [config.provider],
191
- };
192
- }
193
- }
194
-
195
- private noProviderError(
196
- message: string,
197
- agentId: string
198
- ): ImageGenerationError {
199
- const availableProviders = IMAGE_CAPABLE_PROVIDERS.map((p) => p.provider);
200
- logger.info(message, { agentId, availableProviders });
201
- return { error: message, availableProviders };
202
- }
203
-
204
- private async generateWithOpenAI(
205
- prompt: string,
206
- apiKey: string,
207
- options: ImageGenerationOptions
208
- ): Promise<{ imageBuffer: Buffer; mimeType: string }> {
209
- const format = options.format || "png";
210
- const response = await fetch(
211
- "https://api.openai.com/v1/images/generations",
212
- {
213
- method: "POST",
214
- headers: {
215
- Authorization: `Bearer ${apiKey}`,
216
- "Content-Type": "application/json",
217
- },
218
- body: JSON.stringify({
219
- model: "gpt-image-1",
220
- prompt,
221
- size: options.size || "1024x1024",
222
- quality: options.quality || "auto",
223
- background: options.background || "auto",
224
- output_format: format,
225
- response_format: "b64_json",
226
- }),
227
- }
228
- );
229
-
230
- if (!response.ok) {
231
- const errorText = await response.text();
232
- throw new Error(
233
- `OpenAI Images API error: ${response.status} - ${errorText}`
234
- );
235
- }
236
-
237
- const data = (await response.json()) as {
238
- data?: Array<{ b64_json?: string }>;
239
- };
240
- const b64 = data.data?.[0]?.b64_json;
241
- if (!b64) {
242
- throw new Error("OpenAI Images API returned no image payload");
243
- }
244
-
245
- const mimeType =
246
- format === "jpeg"
247
- ? "image/jpeg"
248
- : format === "webp"
249
- ? "image/webp"
250
- : "image/png";
251
-
252
- return {
253
- imageBuffer: Buffer.from(b64, "base64"),
254
- mimeType,
255
- };
256
- }
257
- }
@@ -1,318 +0,0 @@
1
- #!/usr/bin/env bun
2
-
3
- import {
4
- buildUnconfiguredAgentNotice,
5
- createLogger,
6
- type InstructionContext,
7
- type InstructionProvider,
8
- } from "@lobu/core";
9
- import type { McpConfigService } from "../auth/mcp/config-service";
10
- import type { AgentSettingsStore } from "../auth/settings/agent-settings-store";
11
-
12
- const logger = createLogger("instruction-service");
13
-
14
- interface McpStatus {
15
- id: string;
16
- name: string;
17
- requiresAuth: boolean;
18
- requiresInput: boolean;
19
- }
20
-
21
- interface SessionContextData {
22
- agentInstructions: string;
23
- platformInstructions: string;
24
- networkInstructions: string;
25
- skillsInstructions: string;
26
- mcpStatus: McpStatus[];
27
- }
28
-
29
- /**
30
- * Provides instructions from enabled skills for the agent.
31
- * Fetches skill content from AgentSettings and injects as instructions.
32
- * Falls back to generic skills.sh discovery instructions if no skills configured.
33
- */
34
- class SkillsInstructionProvider implements InstructionProvider {
35
- name = "skills";
36
- priority = 15;
37
-
38
- constructor(private agentSettingsStore?: AgentSettingsStore) {}
39
-
40
- async getInstructions(context: InstructionContext): Promise<string> {
41
- // If no settings store or agentId, return generic skills.sh instructions
42
- if (!this.agentSettingsStore || !context.agentId) {
43
- return this.getGenericSkillsInstructions();
44
- }
45
-
46
- try {
47
- const settings = await this.agentSettingsStore.getSettings(
48
- context.agentId
49
- );
50
- const skills = settings?.skillsConfig?.skills || [];
51
- const enabledSkills = skills.filter((s) => s.enabled && s.content);
52
-
53
- if (enabledSkills.length === 0) {
54
- return this.getGenericSkillsInstructions();
55
- }
56
-
57
- // Progressive disclosure: inject only metadata (name + description + model/thinking tags)
58
- // to reduce prompt size. Agent reads full SKILL.md on demand.
59
- const skillSummaries = enabledSkills
60
- .map((skill) => {
61
- const desc = skill.description ? ` - ${skill.description}` : "";
62
- const tags: string[] = [];
63
- if (skill.modelPreference) {
64
- tags.push(`[model: ${skill.modelPreference}]`);
65
- }
66
- if (skill.thinkingLevel) {
67
- tags.push(`[thinking: ${skill.thinkingLevel}]`);
68
- }
69
- const tagStr = tags.length > 0 ? ` ${tags.join(" ")}` : "";
70
- const line = `- **${skill.name}**${desc} (\`${skill.repo}\`)${tagStr}`;
71
- if (skill.instructions?.trim()) {
72
- return `${line}\n → ${skill.instructions.trim()}`;
73
- }
74
- return line;
75
- })
76
- .join("\n");
77
-
78
- return `# Enabled Skills
79
-
80
- The following skills are installed and available. When a task matches a skill, read the full skill instructions before using it. Skills tagged with [model: ...] prefer a specific model — delegate to the corresponding coding agent when available.
81
-
82
- ${skillSummaries}
83
-
84
- **To read full skill instructions:** \`cat .skills/*/SKILL.md\` to read the relevant SKILL.md file.
85
-
86
- ---
87
-
88
- ${this.getGenericSkillsInstructions()}`;
89
- } catch (error) {
90
- logger.error("Failed to get skills instructions", { error });
91
- return this.getGenericSkillsInstructions();
92
- }
93
- }
94
-
95
- private getGenericSkillsInstructions(): string {
96
- return `## Skills
97
-
98
- Your available skills are listed above. To read full instructions for a skill, use: \`cat .skills/{skillName}/SKILL.md\``;
99
- }
100
- }
101
-
102
- /**
103
- * Provides information about network access rules and allowed domains
104
- */
105
- class NetworkInstructionProvider implements InstructionProvider {
106
- name = "network";
107
- priority = 20;
108
-
109
- getInstructions(_context: InstructionContext): string {
110
- const allowedDomains = process.env.WORKER_ALLOWED_DOMAINS?.trim() || "";
111
- const disallowedDomains =
112
- process.env.WORKER_DISALLOWED_DOMAINS?.trim() || "";
113
-
114
- // Unrestricted mode
115
- if (allowedDomains === "*") {
116
- if (disallowedDomains) {
117
- const blockedList = disallowedDomains
118
- .split(",")
119
- .map((d) => ` - ${d.trim()}`)
120
- .filter((d) => d.length > 4)
121
- .join("\n");
122
- return `## Network Access
123
-
124
- **Internet Access:** Unrestricted (all domains allowed)
125
-
126
- **Blocked domains:**
127
- ${blockedList}
128
-
129
- You can access any external service except the blocked domains listed above.`;
130
- }
131
- return `## Network Access
132
-
133
- **Internet Access:** Unrestricted (all domains allowed)
134
-
135
- You can access any external service without restrictions.`;
136
- }
137
-
138
- // Complete isolation
139
- if (!allowedDomains) {
140
- return `## Network Access
141
-
142
- **Internet Access:** Complete isolation (no external access)
143
-
144
- You do NOT have access to the internet. All external requests (curl, wget, npm, pip, etc.) will fail. Network access is configured via lobu.toml or the gateway configuration APIs. Only local operations and MCP tools are available.`;
145
- }
146
-
147
- // Allowlist mode
148
- const allowedList = allowedDomains
149
- .split(",")
150
- .map((d) => ` - ${d.trim()}`)
151
- .filter((d) => d.length > 4)
152
- .join("\n");
153
-
154
- let instructions = `## Network Access
155
-
156
- **Internet Access:** Filtered (allowlist mode)
157
-
158
- **Allowed domains:**
159
- ${allowedList}`;
160
-
161
- if (disallowedDomains) {
162
- const blockedList = disallowedDomains
163
- .split(",")
164
- .map((d) => ` - ${d.trim()}`)
165
- .filter((d) => d.length > 4)
166
- .join("\n");
167
- instructions += `
168
-
169
- **Blocked domains:**
170
- ${blockedList}`;
171
- }
172
-
173
- instructions += `
174
-
175
- You can only access the allowed domains listed above. All other external requests will be blocked by the proxy. Network access is configured via lobu.toml or the gateway configuration APIs. Plan your work accordingly and use available MCP tools when possible.`;
176
-
177
- return instructions;
178
- }
179
- }
180
-
181
- /**
182
- * Aggregates session context data for workers
183
- * Returns raw data (not built instructions) so workers can format as needed
184
- */
185
- export class InstructionService {
186
- private platformProviders = new Map<string, InstructionProvider>();
187
- private mcpConfigService?: McpConfigService;
188
- private agentSettingsStore?: AgentSettingsStore;
189
- private skillsProvider: SkillsInstructionProvider;
190
-
191
- constructor(
192
- mcpConfigService?: McpConfigService,
193
- agentSettingsStore?: AgentSettingsStore
194
- ) {
195
- this.mcpConfigService = mcpConfigService;
196
- this.agentSettingsStore = agentSettingsStore;
197
- this.skillsProvider = new SkillsInstructionProvider(agentSettingsStore);
198
- }
199
-
200
- /**
201
- * Register a platform-specific instruction provider
202
- * Called by platform adapters during initialization
203
- */
204
- registerPlatformProvider(
205
- platform: string,
206
- provider: InstructionProvider
207
- ): void {
208
- this.platformProviders.set(platform, provider);
209
- logger.info(
210
- `Registered instruction provider for platform: ${platform} (${provider.name})`
211
- );
212
- }
213
-
214
- /**
215
- * Get session context data for a worker
216
- */
217
- async getSessionContext(
218
- platform: string,
219
- context: InstructionContext,
220
- options?: { settingsUrl?: string }
221
- ): Promise<SessionContextData> {
222
- // Get platform-specific instructions
223
- let platformInstructions = "";
224
- const platformProvider = this.platformProviders.get(platform);
225
- if (platformProvider) {
226
- try {
227
- platformInstructions = await platformProvider.getInstructions(context);
228
- logger.info(
229
- `Got ${platform} platform instructions (${platformInstructions.length} chars)`
230
- );
231
- } catch (error) {
232
- logger.error(
233
- `Failed to get instructions from ${platform} provider:`,
234
- error
235
- );
236
- }
237
- }
238
-
239
- // Get network access instructions
240
- let networkInstructions = "";
241
- const networkProvider = new NetworkInstructionProvider();
242
- try {
243
- networkInstructions = await networkProvider.getInstructions(context);
244
- logger.info(
245
- `Got network instructions (${networkInstructions.length} chars)`
246
- );
247
- } catch (error) {
248
- logger.error("Failed to get network instructions:", error);
249
- }
250
-
251
- // Build agent instructions from identity/soul/user settings
252
- let agentInstructions = "";
253
- if (this.agentSettingsStore && context.agentId) {
254
- try {
255
- const settings = await this.agentSettingsStore.getSettings(
256
- context.agentId
257
- );
258
- if (settings) {
259
- const sections: string[] = [];
260
- if (settings.identityMd?.trim()) {
261
- sections.push(`## Agent Identity\n\n${settings.identityMd.trim()}`);
262
- }
263
- if (settings.soulMd?.trim()) {
264
- sections.push(`## Agent Instructions\n\n${settings.soulMd.trim()}`);
265
- }
266
- if (settings.userMd?.trim()) {
267
- sections.push(`## User Context\n\n${settings.userMd.trim()}`);
268
- }
269
- agentInstructions = sections.join("\n\n");
270
- }
271
-
272
- // When soul is unconfigured, tell the agent to defer to admin config.
273
- if (!agentInstructions.trim()) {
274
- agentInstructions = buildUnconfiguredAgentNotice(
275
- options?.settingsUrl
276
- );
277
- }
278
-
279
- logger.info(
280
- `Built agent instructions (${agentInstructions.length} chars)`
281
- );
282
- } catch (error) {
283
- logger.error("Failed to build agent instructions:", error);
284
- }
285
- }
286
-
287
- // Get skills instructions (includes enabled skills from agent settings)
288
- let skillsInstructions = "";
289
- try {
290
- skillsInstructions = await this.skillsProvider.getInstructions(context);
291
- logger.info(
292
- `Got skills instructions (${skillsInstructions.length} chars)`
293
- );
294
- } catch (error) {
295
- logger.error("Failed to get skills instructions:", error);
296
- }
297
-
298
- // Get MCP status data
299
- let mcpStatus: McpStatus[] = [];
300
- if (this.mcpConfigService) {
301
- try {
302
- mcpStatus =
303
- (await this.mcpConfigService.getMcpStatus(context.agentId)) || [];
304
- logger.info(`Got MCP status for ${mcpStatus.length} MCPs`);
305
- } catch (error) {
306
- logger.error("Failed to get MCP status:", error);
307
- }
308
- }
309
-
310
- return {
311
- agentInstructions,
312
- platformInstructions,
313
- networkInstructions,
314
- skillsInstructions,
315
- mcpStatus,
316
- };
317
- }
318
- }
@@ -1,94 +0,0 @@
1
- import { createLogger } from "@lobu/core";
2
- import type { SystemConfigResolver } from "./system-config-resolver";
3
-
4
- const logger = createLogger("mcp-registry");
5
-
6
- /**
7
- * MCP server entry from the registry
8
- */
9
- export interface McpRegistryEntry {
10
- id: string;
11
- name: string;
12
- description: string;
13
- type: "oauth" | "stdio" | "sse" | "api-key";
14
- config: Record<string, unknown>;
15
- setupInstructions?: string;
16
- }
17
-
18
- /**
19
- * Service for accessing the MCP server registry.
20
- */
21
- export class McpRegistryService {
22
- /**
23
- * Curated list of popular MCPs for quick-add chips in the settings UI.
24
- */
25
- static readonly CURATED_MCP_IDS = [
26
- "sentry",
27
- "playwright",
28
- "github",
29
- "notion",
30
- "linear",
31
- ];
32
-
33
- private registry: McpRegistryEntry[] = [];
34
- private loaded = false;
35
-
36
- constructor(private readonly resolver?: SystemConfigResolver) {}
37
-
38
- private async ensureLoaded(): Promise<void> {
39
- if (this.loaded) return;
40
- this.loaded = true;
41
-
42
- if (!this.resolver) {
43
- logger.warn("MCP registry resolver not configured");
44
- return;
45
- }
46
-
47
- const resolved = await this.resolver.getMcpRegistryServers();
48
- this.registry = resolved.map((entry) => ({
49
- id: entry.id,
50
- name: entry.name,
51
- description: entry.description,
52
- type: entry.type,
53
- config: entry.config,
54
- }));
55
-
56
- logger.info(`Loaded ${this.registry.length} MCPs from resolver`);
57
- }
58
-
59
- async getCurated(): Promise<McpRegistryEntry[]> {
60
- await this.ensureLoaded();
61
-
62
- const curated = this.registry.filter((mcp) =>
63
- McpRegistryService.CURATED_MCP_IDS.includes(mcp.id)
64
- );
65
-
66
- return curated.length > 0 ? curated : this.registry.slice(0, 5);
67
- }
68
-
69
- async search(query: string, limit = 20): Promise<McpRegistryEntry[]> {
70
- await this.ensureLoaded();
71
-
72
- const trimmed = query.toLowerCase().trim();
73
- if (!trimmed) return this.registry.slice(0, limit);
74
-
75
- return this.registry
76
- .filter(
77
- (entry) =>
78
- entry.name.toLowerCase().includes(trimmed) ||
79
- entry.description.toLowerCase().includes(trimmed) ||
80
- entry.id.toLowerCase().includes(trimmed)
81
- )
82
- .slice(0, limit);
83
- }
84
-
85
- async getAll(): Promise<McpRegistryEntry[]> {
86
- await this.ensureLoaded();
87
- return this.registry;
88
- }
89
-
90
- async getById(id: string): Promise<McpRegistryEntry | null> {
91
- await this.ensureLoaded();
92
- return this.registry.find((entry) => entry.id === id) || null;
93
- }
94
- }