@lobu/gateway 3.0.5 → 3.0.7

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