@lobu/gateway 2.8.0 → 3.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/package.json +2 -2
  2. package/src/__tests__/agent-config-routes.test.ts +254 -0
  3. package/src/__tests__/agent-history-routes.test.ts +72 -0
  4. package/src/__tests__/agent-routes.test.ts +68 -0
  5. package/src/__tests__/agent-schedules-routes.test.ts +59 -0
  6. package/src/__tests__/agent-settings-store.test.ts +323 -0
  7. package/src/__tests__/chat-instance-manager-slack.test.ts +204 -0
  8. package/src/__tests__/chat-response-bridge.test.ts +131 -0
  9. package/src/__tests__/config-memory-plugins.test.ts +92 -0
  10. package/src/__tests__/config-request-store.test.ts +127 -0
  11. package/src/__tests__/connection-routes.test.ts +144 -0
  12. package/src/__tests__/core-services-store-selection.test.ts +92 -0
  13. package/src/__tests__/docker-deployment.test.ts +1211 -0
  14. package/src/__tests__/embedded-deployment.test.ts +342 -0
  15. package/src/__tests__/grant-store.test.ts +148 -0
  16. package/src/__tests__/http-proxy.test.ts +281 -0
  17. package/src/__tests__/instruction-service.test.ts +37 -0
  18. package/src/__tests__/link-buttons.test.ts +112 -0
  19. package/src/__tests__/lobu.test.ts +32 -0
  20. package/src/__tests__/mcp-config-service.test.ts +347 -0
  21. package/src/__tests__/mcp-proxy.test.ts +696 -0
  22. package/src/__tests__/message-handler-bridge.test.ts +17 -0
  23. package/src/__tests__/model-selection.test.ts +172 -0
  24. package/src/__tests__/oauth-templates.test.ts +39 -0
  25. package/src/__tests__/platform-adapter-slack-send.test.ts +114 -0
  26. package/src/__tests__/platform-helpers-model-resolution.test.ts +253 -0
  27. package/src/__tests__/provider-inheritance.test.ts +212 -0
  28. package/src/__tests__/routes/cli-auth.test.ts +337 -0
  29. package/src/__tests__/routes/interactions.test.ts +121 -0
  30. package/src/__tests__/secret-proxy.test.ts +85 -0
  31. package/src/__tests__/session-manager.test.ts +572 -0
  32. package/src/__tests__/setup.ts +133 -0
  33. package/src/__tests__/skill-and-mcp-registry.test.ts +203 -0
  34. package/src/__tests__/slack-routes.test.ts +161 -0
  35. package/src/__tests__/system-config-resolver.test.ts +75 -0
  36. package/src/__tests__/system-message-limiter.test.ts +89 -0
  37. package/src/__tests__/system-skills-service.test.ts +362 -0
  38. package/src/__tests__/transcription-service.test.ts +222 -0
  39. package/src/__tests__/utils/rate-limiter.test.ts +102 -0
  40. package/src/__tests__/worker-connection-manager.test.ts +497 -0
  41. package/src/__tests__/worker-job-router.test.ts +722 -0
  42. package/src/api/index.ts +1 -0
  43. package/src/api/platform.ts +292 -0
  44. package/src/api/response-renderer.ts +157 -0
  45. package/src/auth/agent-metadata-store.ts +168 -0
  46. package/src/auth/api-auth-middleware.ts +69 -0
  47. package/src/auth/api-key-provider-module.ts +213 -0
  48. package/src/auth/base-provider-module.ts +201 -0
  49. package/src/auth/chatgpt/chatgpt-oauth-module.ts +185 -0
  50. package/src/auth/chatgpt/device-code-client.ts +218 -0
  51. package/src/auth/chatgpt/index.ts +1 -0
  52. package/src/auth/claude/oauth-module.ts +280 -0
  53. package/src/auth/cli/token-service.ts +249 -0
  54. package/src/auth/external/client.ts +560 -0
  55. package/src/auth/external/device-code-client.ts +225 -0
  56. package/src/auth/mcp/config-service.ts +392 -0
  57. package/src/auth/mcp/proxy.ts +1088 -0
  58. package/src/auth/mcp/string-substitution.ts +17 -0
  59. package/src/auth/mcp/tool-cache.ts +90 -0
  60. package/src/auth/oauth/base-client.ts +267 -0
  61. package/src/auth/oauth/client.ts +153 -0
  62. package/src/auth/oauth/credentials.ts +7 -0
  63. package/src/auth/oauth/providers.ts +69 -0
  64. package/src/auth/oauth/state-store.ts +150 -0
  65. package/src/auth/oauth-templates.ts +179 -0
  66. package/src/auth/provider-catalog.ts +220 -0
  67. package/src/auth/provider-model-options.ts +41 -0
  68. package/src/auth/settings/agent-settings-store.ts +565 -0
  69. package/src/auth/settings/auth-profiles-manager.ts +216 -0
  70. package/src/auth/settings/index.ts +12 -0
  71. package/src/auth/settings/model-preference-store.ts +52 -0
  72. package/src/auth/settings/model-selection.ts +135 -0
  73. package/src/auth/settings/resolved-settings-view.ts +298 -0
  74. package/src/auth/settings/template-utils.ts +44 -0
  75. package/src/auth/settings/token-service.ts +88 -0
  76. package/src/auth/system-env-store.ts +98 -0
  77. package/src/auth/user-agents-store.ts +68 -0
  78. package/src/channels/binding-service.ts +214 -0
  79. package/src/channels/index.ts +4 -0
  80. package/src/cli/gateway.ts +1304 -0
  81. package/src/cli/index.ts +74 -0
  82. package/src/commands/built-in-commands.ts +80 -0
  83. package/src/commands/command-dispatcher.ts +94 -0
  84. package/src/commands/command-reply-adapters.ts +27 -0
  85. package/src/config/file-loader.ts +618 -0
  86. package/src/config/index.ts +588 -0
  87. package/src/config/network-allowlist.ts +71 -0
  88. package/src/connections/chat-instance-manager.ts +1284 -0
  89. package/src/connections/chat-response-bridge.ts +618 -0
  90. package/src/connections/index.ts +7 -0
  91. package/src/connections/interaction-bridge.ts +831 -0
  92. package/src/connections/message-handler-bridge.ts +415 -0
  93. package/src/connections/platform-auth-methods.ts +15 -0
  94. package/src/connections/types.ts +84 -0
  95. package/src/gateway/connection-manager.ts +291 -0
  96. package/src/gateway/index.ts +700 -0
  97. package/src/gateway/job-router.ts +201 -0
  98. package/src/gateway-main.ts +200 -0
  99. package/src/index.ts +41 -0
  100. package/src/infrastructure/queue/index.ts +12 -0
  101. package/src/infrastructure/queue/queue-producer.ts +148 -0
  102. package/src/infrastructure/queue/redis-queue.ts +361 -0
  103. package/src/infrastructure/queue/types.ts +133 -0
  104. package/src/infrastructure/redis/system-message-limiter.ts +94 -0
  105. package/src/interactions/config-request-store.ts +198 -0
  106. package/src/interactions.ts +363 -0
  107. package/src/lobu.ts +311 -0
  108. package/src/metrics/prometheus.ts +159 -0
  109. package/src/modules/module-system.ts +179 -0
  110. package/src/orchestration/base-deployment-manager.ts +900 -0
  111. package/src/orchestration/deployment-utils.ts +98 -0
  112. package/src/orchestration/impl/docker-deployment.ts +620 -0
  113. package/src/orchestration/impl/embedded-deployment.ts +268 -0
  114. package/src/orchestration/impl/index.ts +8 -0
  115. package/src/orchestration/impl/k8s/deployment.ts +1061 -0
  116. package/src/orchestration/impl/k8s/helpers.ts +610 -0
  117. package/src/orchestration/impl/k8s/index.ts +1 -0
  118. package/src/orchestration/index.ts +333 -0
  119. package/src/orchestration/message-consumer.ts +584 -0
  120. package/src/orchestration/scheduled-wakeup.ts +704 -0
  121. package/src/permissions/approval-policy.ts +36 -0
  122. package/src/permissions/grant-store.ts +219 -0
  123. package/src/platform/file-handler.ts +66 -0
  124. package/src/platform/link-buttons.ts +57 -0
  125. package/src/platform/renderer-utils.ts +44 -0
  126. package/src/platform/response-renderer.ts +84 -0
  127. package/src/platform/unified-thread-consumer.ts +187 -0
  128. package/src/platform.ts +318 -0
  129. package/src/proxy/http-proxy.ts +752 -0
  130. package/src/proxy/proxy-manager.ts +81 -0
  131. package/src/proxy/secret-proxy.ts +402 -0
  132. package/src/proxy/token-refresh-job.ts +143 -0
  133. package/src/routes/internal/audio.ts +141 -0
  134. package/src/routes/internal/device-auth.ts +566 -0
  135. package/src/routes/internal/files.ts +226 -0
  136. package/src/routes/internal/history.ts +69 -0
  137. package/src/routes/internal/images.ts +127 -0
  138. package/src/routes/internal/interactions.ts +84 -0
  139. package/src/routes/internal/middleware.ts +23 -0
  140. package/src/routes/internal/schedule.ts +226 -0
  141. package/src/routes/internal/types.ts +22 -0
  142. package/src/routes/openapi-auto.ts +239 -0
  143. package/src/routes/public/agent-access.ts +23 -0
  144. package/src/routes/public/agent-config.ts +675 -0
  145. package/src/routes/public/agent-history.ts +422 -0
  146. package/src/routes/public/agent-schedules.ts +296 -0
  147. package/src/routes/public/agent.ts +1086 -0
  148. package/src/routes/public/agents.ts +373 -0
  149. package/src/routes/public/channels.ts +191 -0
  150. package/src/routes/public/cli-auth.ts +883 -0
  151. package/src/routes/public/connections.ts +574 -0
  152. package/src/routes/public/landing.ts +16 -0
  153. package/src/routes/public/oauth.ts +147 -0
  154. package/src/routes/public/settings-auth.ts +104 -0
  155. package/src/routes/public/slack.ts +173 -0
  156. package/src/routes/shared/agent-ownership.ts +101 -0
  157. package/src/routes/shared/token-verifier.ts +34 -0
  158. package/src/services/core-services.ts +1053 -0
  159. package/src/services/image-generation-service.ts +257 -0
  160. package/src/services/instruction-service.ts +318 -0
  161. package/src/services/mcp-registry.ts +94 -0
  162. package/src/services/platform-helpers.ts +287 -0
  163. package/src/services/session-manager.ts +262 -0
  164. package/src/services/settings-resolver.ts +74 -0
  165. package/src/services/system-config-resolver.ts +90 -0
  166. package/src/services/system-skills-service.ts +229 -0
  167. package/src/services/transcription-service.ts +684 -0
  168. package/src/session.ts +110 -0
  169. package/src/spaces/index.ts +1 -0
  170. package/src/spaces/space-resolver.ts +17 -0
  171. package/src/stores/in-memory-agent-store.ts +403 -0
  172. package/src/stores/redis-agent-store.ts +279 -0
  173. package/src/utils/public-url.ts +44 -0
  174. package/src/utils/rate-limiter.ts +94 -0
  175. package/tsconfig.json +33 -0
@@ -0,0 +1,150 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { createLogger, type Logger } from "@lobu/core";
3
+ import type Redis from "ioredis";
4
+
5
+ /**
6
+ * Generic OAuth state store for CSRF protection
7
+ * Pattern: {keyPrefix}:{state}
8
+ * TTL: 5 minutes
9
+ */
10
+ export class OAuthStateStore<T extends object> {
11
+ private static readonly TTL_SECONDS = 5 * 60; // 5 minutes
12
+ protected logger: Logger;
13
+
14
+ constructor(
15
+ private redis: Redis,
16
+ private keyPrefix: string,
17
+ loggerName: string
18
+ ) {
19
+ this.logger = createLogger(loggerName);
20
+ }
21
+
22
+ /**
23
+ * Create a new OAuth state with data
24
+ * Returns the state string to use in OAuth flow
25
+ */
26
+ async create(data: T): Promise<string> {
27
+ const state = this.generateState();
28
+ const key = this.getKey(state);
29
+
30
+ const stateData = {
31
+ ...data,
32
+ createdAt: Date.now(),
33
+ };
34
+
35
+ await this.redis.setex(
36
+ key,
37
+ OAuthStateStore.TTL_SECONDS,
38
+ JSON.stringify(stateData)
39
+ );
40
+
41
+ const userId =
42
+ typeof (data as { userId?: unknown }).userId === "string"
43
+ ? (data as { userId: string }).userId
44
+ : undefined;
45
+ this.logger.info(
46
+ userId ? `Created OAuth state for user ${userId}` : "Created OAuth state",
47
+ { state }
48
+ );
49
+ return state;
50
+ }
51
+
52
+ /**
53
+ * Validate and consume an OAuth state
54
+ * Returns the state data if valid, null if invalid or expired
55
+ * Deletes the state after retrieval (one-time use)
56
+ */
57
+ async consume(state: string): Promise<(T & { createdAt: number }) | null> {
58
+ const key = this.getKey(state);
59
+
60
+ // Get and delete in one operation
61
+ const data = await this.redis.getdel(key);
62
+
63
+ if (!data) {
64
+ this.logger.warn(`Invalid or expired OAuth state: ${state}`);
65
+ return null;
66
+ }
67
+
68
+ try {
69
+ const stateData = JSON.parse(data) as T & { createdAt: number };
70
+ const stateDataWithUser = stateData as unknown as { userId?: unknown };
71
+ const userId =
72
+ typeof stateDataWithUser.userId === "string"
73
+ ? stateDataWithUser.userId
74
+ : undefined;
75
+ this.logger.info(
76
+ userId
77
+ ? `Consumed OAuth state for user ${userId}`
78
+ : "Consumed OAuth state",
79
+ { state }
80
+ );
81
+ return stateData;
82
+ } catch (error) {
83
+ this.logger.error(`Failed to parse OAuth state: ${state}`, { error });
84
+ return null;
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Generate a cryptographically secure random state string
90
+ */
91
+ private generateState(): string {
92
+ return randomBytes(32).toString("base64url");
93
+ }
94
+
95
+ private getKey(state: string): string {
96
+ return `${this.keyPrefix}:${state}`;
97
+ }
98
+ }
99
+
100
+ // ============================================================================
101
+ // Provider OAuth State Types and Factory
102
+ // ============================================================================
103
+
104
+ /**
105
+ * Context for routing auth completion back to the originating platform.
106
+ */
107
+ export interface OAuthPlatformContext {
108
+ platform: string;
109
+ channelId: string; // chatJid for WhatsApp, channel for Slack
110
+ conversationId?: string;
111
+ }
112
+
113
+ export interface ProviderOAuthStateData {
114
+ userId: string;
115
+ agentId: string;
116
+ codeVerifier: string;
117
+ context?: OAuthPlatformContext;
118
+ }
119
+
120
+ export type ProviderOAuthState = ProviderOAuthStateData & {
121
+ createdAt: number;
122
+ };
123
+
124
+ /**
125
+ * Create a provider OAuth state store for PKCE flow
126
+ */
127
+ export function createOAuthStateStore(
128
+ providerId: string,
129
+ redis: Redis
130
+ ): OAuthStateStore<ProviderOAuthStateData> {
131
+ return new OAuthStateStore(
132
+ redis,
133
+ `${providerId}:oauth_state`,
134
+ `${providerId}-oauth-state`
135
+ );
136
+ }
137
+
138
+ export interface SlackInstallStateData {
139
+ redirectUri: string;
140
+ }
141
+
142
+ export type SlackInstallState = SlackInstallStateData & { createdAt: number };
143
+
144
+ export function createSlackInstallStateStore(
145
+ redis: Redis
146
+ ): OAuthStateStore<SlackInstallStateData> {
147
+ return new OAuthStateStore(redis, "slack:oauth:state", "slack-install-state");
148
+ }
149
+
150
+ export type ProviderOAuthStateStore = OAuthStateStore<ProviderOAuthStateData>;
@@ -0,0 +1,179 @@
1
+ /**
2
+ * HTML templates for OAuth flow
3
+ */
4
+
5
+ function escapeHtml(value: string): string {
6
+ return value.replace(/[&<>"'`]/g, (char) => {
7
+ switch (char) {
8
+ case "&":
9
+ return "&amp;";
10
+ case "<":
11
+ return "&lt;";
12
+ case ">":
13
+ return "&gt;";
14
+ case '"':
15
+ return "&quot;";
16
+ case "'":
17
+ return "&#39;";
18
+ case "`":
19
+ return "&#96;";
20
+ default:
21
+ return char;
22
+ }
23
+ });
24
+ }
25
+
26
+ /**
27
+ * Render a success page that auto-closes the tab (for in-app browsers)
28
+ * and provides a fallback link to agent configuration when available.
29
+ */
30
+ export function renderOAuthSuccessPage(
31
+ name: string,
32
+ settingsUrl?: string,
33
+ options?: {
34
+ title?: string;
35
+ description?: string;
36
+ details?: string;
37
+ closeNote?: string;
38
+ }
39
+ ): string {
40
+ const safeName = escapeHtml(name);
41
+ const safeSettingsUrl = settingsUrl ? escapeHtml(settingsUrl) : "";
42
+ const safeTitle = escapeHtml(options?.title || "Connected!");
43
+ const safeDescription = escapeHtml(
44
+ options?.description || `Successfully authenticated with ${name}`
45
+ );
46
+ const safeDetails = options?.details ? escapeHtml(options.details) : "";
47
+ const safeCloseNote = escapeHtml(
48
+ options?.closeNote || "You can close this tab and return to your chat."
49
+ );
50
+
51
+ return `
52
+ <!DOCTYPE html>
53
+ <html>
54
+ <head>
55
+ <title>Connected</title>
56
+ <style>
57
+ body {
58
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
59
+ display: flex;
60
+ align-items: center;
61
+ justify-content: center;
62
+ height: 100vh;
63
+ margin: 0;
64
+ background: linear-gradient(135deg, #334155 0%, #0f172a 100%);
65
+ }
66
+ .container {
67
+ background: white;
68
+ padding: 2.5rem;
69
+ border-radius: 12px;
70
+ text-align: center;
71
+ box-shadow: 0 20px 60px rgba(0,0,0,0.3);
72
+ max-width: 360px;
73
+ }
74
+ .icon { font-size: 3rem; margin-bottom: 0.75rem; }
75
+ h1 { color: #2d3748; margin: 0 0 0.5rem 0; font-size: 1.25rem; }
76
+ p { color: #718096; line-height: 1.5; font-size: 0.875rem; margin: 0 0 1rem 0; }
77
+ .btn {
78
+ display: inline-block;
79
+ padding: 0.625rem 1.25rem;
80
+ background: linear-gradient(to right, #334155, #1e293b);
81
+ color: white;
82
+ text-decoration: none;
83
+ border-radius: 8px;
84
+ font-size: 0.875rem;
85
+ font-weight: 600;
86
+ }
87
+ .btn:hover { opacity: 0.9; }
88
+ .close-note { color: #94a3b8; font-size: 0.75rem; margin-top: 1rem; }
89
+ </style>
90
+ </head>
91
+ <body>
92
+ <div class="container">
93
+ <div class="icon">&#9989;</div>
94
+ <h1>${safeTitle}</h1>
95
+ <p>${safeDescription.includes(safeName) ? safeDescription : `${safeDescription} <strong>${safeName}</strong>`}</p>
96
+ ${safeDetails ? `<p>${safeDetails}</p>` : ""}
97
+ ${safeSettingsUrl ? `<a class="btn" href="${safeSettingsUrl}">Open Configuration</a>` : ""}
98
+ <p class="close-note">${safeCloseNote}</p>
99
+ </div>
100
+ <script>
101
+ // Auto-close for Telegram in-app browser
102
+ if (window.Telegram && window.Telegram.WebApp) {
103
+ window.Telegram.WebApp.close();
104
+ }
105
+ // Try to close the window/tab after a brief moment
106
+ setTimeout(function() { window.close(); }, 1500);
107
+ </script>
108
+ </body>
109
+ </html>
110
+ `;
111
+ }
112
+
113
+ export function renderOAuthErrorPage(
114
+ error: string,
115
+ description?: string
116
+ ): string {
117
+ const safeError = escapeHtml(error);
118
+ const safeDescription = escapeHtml(
119
+ description || "An error occurred during authentication"
120
+ );
121
+
122
+ return `
123
+ <!DOCTYPE html>
124
+ <html>
125
+ <head>
126
+ <title>Authentication Failed</title>
127
+ <style>
128
+ body {
129
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
130
+ display: flex;
131
+ align-items: center;
132
+ justify-content: center;
133
+ height: 100vh;
134
+ margin: 0;
135
+ background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
136
+ }
137
+ .container {
138
+ background: white;
139
+ padding: 3rem;
140
+ border-radius: 12px;
141
+ text-align: center;
142
+ box-shadow: 0 20px 60px rgba(0,0,0,0.3);
143
+ max-width: 400px;
144
+ }
145
+ .error-icon {
146
+ font-size: 4rem;
147
+ margin-bottom: 1rem;
148
+ }
149
+ h1 {
150
+ color: #2d3748;
151
+ margin: 0 0 1rem 0;
152
+ }
153
+ p {
154
+ color: #718096;
155
+ line-height: 1.6;
156
+ }
157
+ .error-code {
158
+ background: #f7fafc;
159
+ padding: 0.5rem;
160
+ border-radius: 6px;
161
+ font-family: monospace;
162
+ font-size: 0.875rem;
163
+ color: #e53e3e;
164
+ margin-top: 1rem;
165
+ }
166
+ </style>
167
+ </head>
168
+ <body>
169
+ <div class="container">
170
+ <div class="error-icon">❌</div>
171
+ <h1>Authentication Failed</h1>
172
+ <p>${safeDescription}</p>
173
+ <div class="error-code">${safeError}</div>
174
+ <p style="margin-top: 2rem;">Please close this window and try again.</p>
175
+ </div>
176
+ </body>
177
+ </html>
178
+ `;
179
+ }
@@ -0,0 +1,220 @@
1
+ import { createLogger, type InstalledProvider } from "@lobu/core";
2
+ import {
3
+ getModelProviderModules,
4
+ type ModelProviderModule,
5
+ } from "../modules/module-system";
6
+ import type { AgentSettingsStore } from "./settings/agent-settings-store";
7
+ import type { AuthProfilesManager } from "./settings/auth-profiles-manager";
8
+ import { reconcileModelSelectionForInstalledProviders } from "./settings/model-selection";
9
+
10
+ const logger = createLogger("provider-catalog");
11
+
12
+ /**
13
+ * Resolve an agent's installed providers, falling back to the base agent's
14
+ * providers for sandbox agents that have none of their own.
15
+ */
16
+ export async function resolveInstalledProviders(
17
+ agentSettingsStore: AgentSettingsStore,
18
+ agentId: string
19
+ ): Promise<InstalledProvider[]> {
20
+ const settings = await agentSettingsStore.getEffectiveSettings(agentId);
21
+ return settings?.installedProviders || [];
22
+ }
23
+
24
+ /**
25
+ * ProviderCatalogService wraps the module registry to provide
26
+ * per-agent provider install/uninstall/reorder operations.
27
+ *
28
+ * Providers are registered globally in the module registry,
29
+ * but each agent chooses which providers to install from the catalog.
30
+ */
31
+ export class ProviderCatalogService {
32
+ constructor(
33
+ private agentSettingsStore: AgentSettingsStore,
34
+ private authProfilesManager: AuthProfilesManager
35
+ ) {}
36
+
37
+ /**
38
+ * List all catalog-visible providers from the module registry.
39
+ */
40
+ listCatalogProviders(): ModelProviderModule[] {
41
+ return getModelProviderModules().filter((m) => m.catalogVisible !== false);
42
+ }
43
+
44
+ /**
45
+ * Resolve an agent's installedProviders to their module instances.
46
+ * Returns modules in the agent's install order.
47
+ */
48
+ async getInstalledModules(agentId: string): Promise<ModelProviderModule[]> {
49
+ const installed = await resolveInstalledProviders(
50
+ this.agentSettingsStore,
51
+ agentId
52
+ );
53
+ if (installed.length === 0) return [];
54
+
55
+ const allModules = getModelProviderModules();
56
+ const moduleMap = new Map(allModules.map((m) => [m.providerId, m]));
57
+
58
+ return installed
59
+ .map((ip) => moduleMap.get(ip.providerId))
60
+ .filter((m): m is ModelProviderModule => m !== undefined);
61
+ }
62
+
63
+ /**
64
+ * Get raw installed provider entries for an agent.
65
+ */
66
+ async getInstalledProviders(agentId: string): Promise<InstalledProvider[]> {
67
+ return resolveInstalledProviders(this.agentSettingsStore, agentId);
68
+ }
69
+
70
+ /**
71
+ * Install a provider for an agent. Appends to the end of the list.
72
+ */
73
+ async installProvider(
74
+ agentId: string,
75
+ providerId: string,
76
+ config?: InstalledProvider["config"]
77
+ ): Promise<void> {
78
+ const allModules = getModelProviderModules();
79
+ const module = allModules.find((m) => m.providerId === providerId);
80
+ if (!module) {
81
+ throw new Error(`Unknown provider: ${providerId}`);
82
+ }
83
+
84
+ const { localSettings, effectiveSettings } =
85
+ await this.agentSettingsStore.getSettingsContext(agentId);
86
+ const installed = effectiveSettings?.installedProviders || [];
87
+
88
+ if (installed.some((ip) => ip.providerId === providerId)) {
89
+ logger.info(
90
+ `Provider ${providerId} already installed for agent ${agentId}`
91
+ );
92
+ return;
93
+ }
94
+
95
+ const entry: InstalledProvider = {
96
+ providerId,
97
+ installedAt: Date.now(),
98
+ ...(config ? { config } : {}),
99
+ };
100
+ const nextInstalledProviders = [...installed, entry];
101
+ const reconciled = reconcileModelSelectionForInstalledProviders({
102
+ model: localSettings?.model ?? effectiveSettings?.model,
103
+ modelSelection:
104
+ localSettings?.modelSelection ?? effectiveSettings?.modelSelection,
105
+ providerModelPreferences:
106
+ localSettings?.providerModelPreferences ??
107
+ effectiveSettings?.providerModelPreferences,
108
+ installedProviders: nextInstalledProviders,
109
+ });
110
+
111
+ await this.agentSettingsStore.updateSettings(agentId, {
112
+ installedProviders: nextInstalledProviders,
113
+ ...reconciled,
114
+ });
115
+
116
+ logger.info(`Installed provider ${providerId} for agent ${agentId}`);
117
+ }
118
+
119
+ /**
120
+ * Uninstall a provider from an agent. Also cleans up auth profiles.
121
+ */
122
+ async uninstallProvider(agentId: string, providerId: string): Promise<void> {
123
+ const { localSettings, effectiveSettings } =
124
+ await this.agentSettingsStore.getSettingsContext(agentId);
125
+ const installed = effectiveSettings?.installedProviders || [];
126
+
127
+ const filtered = installed.filter((ip) => ip.providerId !== providerId);
128
+ if (filtered.length === installed.length) {
129
+ logger.info(
130
+ `Provider ${providerId} not installed for agent ${agentId}, nothing to uninstall`
131
+ );
132
+ return;
133
+ }
134
+
135
+ // Clean up auth profiles for this provider
136
+ await this.authProfilesManager.deleteProviderProfiles(agentId, providerId);
137
+ const reconciled = reconcileModelSelectionForInstalledProviders({
138
+ model: localSettings?.model ?? effectiveSettings?.model,
139
+ modelSelection:
140
+ localSettings?.modelSelection ?? effectiveSettings?.modelSelection,
141
+ providerModelPreferences:
142
+ localSettings?.providerModelPreferences ??
143
+ effectiveSettings?.providerModelPreferences,
144
+ installedProviders: filtered,
145
+ });
146
+
147
+ await this.agentSettingsStore.updateSettings(agentId, {
148
+ installedProviders: filtered,
149
+ ...reconciled,
150
+ });
151
+
152
+ logger.info(`Uninstalled provider ${providerId} for agent ${agentId}`);
153
+ }
154
+
155
+ /**
156
+ * Find the provider module whose model options include the given model string.
157
+ */
158
+ async findProviderForModel(
159
+ model: string,
160
+ providers?: ModelProviderModule[]
161
+ ): Promise<ModelProviderModule | undefined> {
162
+ const candidates = providers || getModelProviderModules();
163
+ for (const provider of candidates) {
164
+ if (!provider.getModelOptions) continue;
165
+ const options = await provider.getModelOptions("", "");
166
+ if (options.some((opt) => opt.value === model)) {
167
+ return provider;
168
+ }
169
+ }
170
+ return undefined;
171
+ }
172
+
173
+ /**
174
+ * Reorder installed providers. The orderedIds must contain
175
+ * exactly the same provider IDs as currently installed.
176
+ */
177
+ async reorderProviders(agentId: string, orderedIds: string[]): Promise<void> {
178
+ const { localSettings, effectiveSettings } =
179
+ await this.agentSettingsStore.getSettingsContext(agentId);
180
+ const installed = effectiveSettings?.installedProviders || [];
181
+
182
+ const installedMap = new Map(installed.map((ip) => [ip.providerId, ip]));
183
+
184
+ // Validate all ordered IDs exist in installed
185
+ for (const id of orderedIds) {
186
+ if (!installedMap.has(id)) {
187
+ throw new Error(`Provider ${id} is not installed`);
188
+ }
189
+ }
190
+
191
+ const reordered = orderedIds
192
+ .map((id) => installedMap.get(id))
193
+ .filter((ip): ip is InstalledProvider => ip !== undefined);
194
+
195
+ // Append any installed providers not in orderedIds (shouldn't happen but safety)
196
+ for (const ip of installed) {
197
+ if (!orderedIds.includes(ip.providerId)) {
198
+ reordered.push(ip);
199
+ }
200
+ }
201
+ const reconciled = reconcileModelSelectionForInstalledProviders({
202
+ model: localSettings?.model ?? effectiveSettings?.model,
203
+ modelSelection:
204
+ localSettings?.modelSelection ?? effectiveSettings?.modelSelection,
205
+ providerModelPreferences:
206
+ localSettings?.providerModelPreferences ??
207
+ effectiveSettings?.providerModelPreferences,
208
+ installedProviders: reordered,
209
+ });
210
+
211
+ await this.agentSettingsStore.updateSettings(agentId, {
212
+ installedProviders: reordered,
213
+ ...reconciled,
214
+ });
215
+
216
+ logger.info(
217
+ `Reordered providers for agent ${agentId}: ${orderedIds.join(", ")}`
218
+ );
219
+ }
220
+ }
@@ -0,0 +1,41 @@
1
+ import { createLogger } from "@lobu/core";
2
+ import {
3
+ getModelProviderModules,
4
+ type ModelOption,
5
+ } from "../modules/module-system";
6
+
7
+ const logger = createLogger("provider-model-options");
8
+
9
+ export async function collectProviderModelOptions(
10
+ agentId: string,
11
+ userId: string
12
+ ): Promise<Record<string, ModelOption[]>> {
13
+ const modules = getModelProviderModules();
14
+
15
+ const results: Record<string, ModelOption[]> = {};
16
+
17
+ await Promise.all(
18
+ modules.map(async (mod) => {
19
+ try {
20
+ if (typeof mod.getModelOptions !== "function") {
21
+ results[mod.providerId] = [];
22
+ return;
23
+ }
24
+
25
+ const options = await mod.getModelOptions(agentId, userId);
26
+ results[mod.providerId] = Array.isArray(options) ? options : [];
27
+ } catch (error) {
28
+ results[mod.providerId] = [];
29
+ logger.warn(
30
+ {
31
+ providerId: mod.providerId,
32
+ error: error instanceof Error ? error.message : String(error),
33
+ },
34
+ "Failed to collect model options for provider"
35
+ );
36
+ }
37
+ })
38
+ );
39
+
40
+ return results;
41
+ }