@lobu/gateway 3.0.5 → 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.
- package/package.json +2 -2
- package/src/__tests__/agent-config-routes.test.ts +254 -0
- package/src/__tests__/agent-history-routes.test.ts +72 -0
- package/src/__tests__/agent-routes.test.ts +68 -0
- package/src/__tests__/agent-schedules-routes.test.ts +59 -0
- package/src/__tests__/agent-settings-store.test.ts +323 -0
- package/src/__tests__/chat-instance-manager-slack.test.ts +204 -0
- package/src/__tests__/chat-response-bridge.test.ts +131 -0
- package/src/__tests__/config-memory-plugins.test.ts +92 -0
- package/src/__tests__/config-request-store.test.ts +127 -0
- package/src/__tests__/connection-routes.test.ts +144 -0
- package/src/__tests__/core-services-store-selection.test.ts +92 -0
- package/src/__tests__/docker-deployment.test.ts +1211 -0
- package/src/__tests__/embedded-deployment.test.ts +342 -0
- package/src/__tests__/grant-store.test.ts +148 -0
- package/src/__tests__/http-proxy.test.ts +281 -0
- package/src/__tests__/instruction-service.test.ts +37 -0
- package/src/__tests__/link-buttons.test.ts +112 -0
- package/src/__tests__/lobu.test.ts +32 -0
- package/src/__tests__/mcp-config-service.test.ts +347 -0
- package/src/__tests__/mcp-proxy.test.ts +696 -0
- package/src/__tests__/message-handler-bridge.test.ts +17 -0
- package/src/__tests__/model-selection.test.ts +172 -0
- package/src/__tests__/oauth-templates.test.ts +39 -0
- package/src/__tests__/platform-adapter-slack-send.test.ts +114 -0
- package/src/__tests__/platform-helpers-model-resolution.test.ts +253 -0
- package/src/__tests__/provider-inheritance.test.ts +212 -0
- package/src/__tests__/routes/cli-auth.test.ts +337 -0
- package/src/__tests__/routes/interactions.test.ts +121 -0
- package/src/__tests__/secret-proxy.test.ts +85 -0
- package/src/__tests__/session-manager.test.ts +572 -0
- package/src/__tests__/setup.ts +133 -0
- package/src/__tests__/skill-and-mcp-registry.test.ts +203 -0
- package/src/__tests__/slack-routes.test.ts +161 -0
- package/src/__tests__/system-config-resolver.test.ts +75 -0
- package/src/__tests__/system-message-limiter.test.ts +89 -0
- package/src/__tests__/system-skills-service.test.ts +362 -0
- package/src/__tests__/transcription-service.test.ts +222 -0
- package/src/__tests__/utils/rate-limiter.test.ts +102 -0
- package/src/__tests__/worker-connection-manager.test.ts +497 -0
- package/src/__tests__/worker-job-router.test.ts +722 -0
- package/src/api/index.ts +1 -0
- package/src/api/platform.ts +292 -0
- package/src/api/response-renderer.ts +157 -0
- package/src/auth/agent-metadata-store.ts +168 -0
- package/src/auth/api-auth-middleware.ts +69 -0
- package/src/auth/api-key-provider-module.ts +213 -0
- package/src/auth/base-provider-module.ts +201 -0
- package/src/auth/chatgpt/chatgpt-oauth-module.ts +185 -0
- package/src/auth/chatgpt/device-code-client.ts +218 -0
- package/src/auth/chatgpt/index.ts +1 -0
- package/src/auth/claude/oauth-module.ts +280 -0
- package/src/auth/cli/token-service.ts +249 -0
- package/src/auth/external/client.ts +560 -0
- package/src/auth/external/device-code-client.ts +225 -0
- package/src/auth/mcp/config-service.ts +392 -0
- package/src/auth/mcp/proxy.ts +1088 -0
- package/src/auth/mcp/string-substitution.ts +17 -0
- package/src/auth/mcp/tool-cache.ts +90 -0
- package/src/auth/oauth/base-client.ts +267 -0
- package/src/auth/oauth/client.ts +153 -0
- package/src/auth/oauth/credentials.ts +7 -0
- package/src/auth/oauth/providers.ts +69 -0
- package/src/auth/oauth/state-store.ts +150 -0
- package/src/auth/oauth-templates.ts +179 -0
- package/src/auth/provider-catalog.ts +220 -0
- package/src/auth/provider-model-options.ts +41 -0
- package/src/auth/settings/agent-settings-store.ts +565 -0
- package/src/auth/settings/auth-profiles-manager.ts +216 -0
- package/src/auth/settings/index.ts +12 -0
- package/src/auth/settings/model-preference-store.ts +52 -0
- package/src/auth/settings/model-selection.ts +135 -0
- package/src/auth/settings/resolved-settings-view.ts +298 -0
- package/src/auth/settings/template-utils.ts +44 -0
- package/src/auth/settings/token-service.ts +88 -0
- package/src/auth/system-env-store.ts +98 -0
- package/src/auth/user-agents-store.ts +68 -0
- package/src/channels/binding-service.ts +214 -0
- package/src/channels/index.ts +4 -0
- package/src/cli/gateway.ts +1304 -0
- package/src/cli/index.ts +74 -0
- package/src/commands/built-in-commands.ts +80 -0
- package/src/commands/command-dispatcher.ts +94 -0
- package/src/commands/command-reply-adapters.ts +27 -0
- package/src/config/file-loader.ts +618 -0
- package/src/config/index.ts +588 -0
- package/src/config/network-allowlist.ts +71 -0
- package/src/connections/chat-instance-manager.ts +1284 -0
- package/src/connections/chat-response-bridge.ts +618 -0
- package/src/connections/index.ts +7 -0
- package/src/connections/interaction-bridge.ts +831 -0
- package/src/connections/message-handler-bridge.ts +415 -0
- package/src/connections/platform-auth-methods.ts +15 -0
- package/src/connections/types.ts +84 -0
- package/src/gateway/connection-manager.ts +291 -0
- package/src/gateway/index.ts +700 -0
- package/src/gateway/job-router.ts +201 -0
- package/src/gateway-main.ts +200 -0
- package/src/index.ts +41 -0
- package/src/infrastructure/queue/index.ts +12 -0
- package/src/infrastructure/queue/queue-producer.ts +148 -0
- package/src/infrastructure/queue/redis-queue.ts +361 -0
- package/src/infrastructure/queue/types.ts +133 -0
- package/src/infrastructure/redis/system-message-limiter.ts +94 -0
- package/src/interactions/config-request-store.ts +198 -0
- package/src/interactions.ts +363 -0
- package/src/lobu.ts +311 -0
- package/src/metrics/prometheus.ts +159 -0
- package/src/modules/module-system.ts +179 -0
- package/src/orchestration/base-deployment-manager.ts +900 -0
- package/src/orchestration/deployment-utils.ts +98 -0
- package/src/orchestration/impl/docker-deployment.ts +620 -0
- package/src/orchestration/impl/embedded-deployment.ts +268 -0
- package/src/orchestration/impl/index.ts +8 -0
- package/src/orchestration/impl/k8s/deployment.ts +1061 -0
- package/src/orchestration/impl/k8s/helpers.ts +610 -0
- package/src/orchestration/impl/k8s/index.ts +1 -0
- package/src/orchestration/index.ts +333 -0
- package/src/orchestration/message-consumer.ts +584 -0
- package/src/orchestration/scheduled-wakeup.ts +704 -0
- package/src/permissions/approval-policy.ts +36 -0
- package/src/permissions/grant-store.ts +219 -0
- package/src/platform/file-handler.ts +66 -0
- package/src/platform/link-buttons.ts +57 -0
- package/src/platform/renderer-utils.ts +44 -0
- package/src/platform/response-renderer.ts +84 -0
- package/src/platform/unified-thread-consumer.ts +187 -0
- package/src/platform.ts +318 -0
- package/src/proxy/http-proxy.ts +752 -0
- package/src/proxy/proxy-manager.ts +81 -0
- package/src/proxy/secret-proxy.ts +402 -0
- package/src/proxy/token-refresh-job.ts +143 -0
- package/src/routes/internal/audio.ts +141 -0
- package/src/routes/internal/device-auth.ts +566 -0
- package/src/routes/internal/files.ts +226 -0
- package/src/routes/internal/history.ts +69 -0
- package/src/routes/internal/images.ts +127 -0
- package/src/routes/internal/interactions.ts +84 -0
- package/src/routes/internal/middleware.ts +23 -0
- package/src/routes/internal/schedule.ts +226 -0
- package/src/routes/internal/types.ts +22 -0
- package/src/routes/openapi-auto.ts +239 -0
- package/src/routes/public/agent-access.ts +23 -0
- package/src/routes/public/agent-config.ts +675 -0
- package/src/routes/public/agent-history.ts +422 -0
- package/src/routes/public/agent-schedules.ts +296 -0
- package/src/routes/public/agent.ts +1086 -0
- package/src/routes/public/agents.ts +373 -0
- package/src/routes/public/channels.ts +191 -0
- package/src/routes/public/cli-auth.ts +883 -0
- package/src/routes/public/connections.ts +574 -0
- package/src/routes/public/landing.ts +16 -0
- package/src/routes/public/oauth.ts +147 -0
- package/src/routes/public/settings-auth.ts +104 -0
- package/src/routes/public/slack.ts +173 -0
- package/src/routes/shared/agent-ownership.ts +101 -0
- package/src/routes/shared/token-verifier.ts +34 -0
- package/src/services/core-services.ts +1053 -0
- package/src/services/image-generation-service.ts +257 -0
- package/src/services/instruction-service.ts +318 -0
- package/src/services/mcp-registry.ts +94 -0
- package/src/services/platform-helpers.ts +287 -0
- package/src/services/session-manager.ts +262 -0
- package/src/services/settings-resolver.ts +74 -0
- package/src/services/system-config-resolver.ts +90 -0
- package/src/services/system-skills-service.ts +229 -0
- package/src/services/transcription-service.ts +684 -0
- package/src/session.ts +110 -0
- package/src/spaces/index.ts +1 -0
- package/src/spaces/space-resolver.ts +17 -0
- package/src/stores/in-memory-agent-store.ts +403 -0
- package/src/stores/redis-agent-store.ts +279 -0
- package/src/utils/public-url.ts +44 -0
- package/src/utils/rate-limiter.ts +94 -0
- package/tsconfig.json +33 -0
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import type { ConfigProviderMeta } from "@lobu/core";
|
|
2
|
+
import type { ModelOption } from "../modules/module-system";
|
|
3
|
+
import { BaseProviderModule } from "./base-provider-module";
|
|
4
|
+
import type { AgentSettingsStore } from "./settings/agent-settings-store";
|
|
5
|
+
import { AuthProfilesManager } from "./settings/auth-profiles-manager";
|
|
6
|
+
|
|
7
|
+
export interface ApiKeyProviderConfig {
|
|
8
|
+
providerId: string;
|
|
9
|
+
providerDisplayName: string;
|
|
10
|
+
providerIconUrl: string;
|
|
11
|
+
envVarName: string;
|
|
12
|
+
apiKeyInstructions: string;
|
|
13
|
+
apiKeyPlaceholder: string;
|
|
14
|
+
systemEnvVarName?: string;
|
|
15
|
+
/** Provider slug for proxy path routing (e.g. "gemini") */
|
|
16
|
+
slug?: string;
|
|
17
|
+
/** Upstream base URL for proxy forwarding (e.g. "https://generativelanguage.googleapis.com") */
|
|
18
|
+
upstreamBaseUrl?: string;
|
|
19
|
+
/** Explicit base URL env var name (defaults to envVarName with _KEY replaced by _BASE_URL) */
|
|
20
|
+
baseUrlEnvVarName?: string;
|
|
21
|
+
/** Relative path to fetch model list (e.g. "/v1/models"). Enables generic model fetching. */
|
|
22
|
+
modelsEndpoint?: string;
|
|
23
|
+
/** SDK compatibility — "openai" means OpenAI-compatible format. Also maps OPENAI_BASE_URL in proxy. */
|
|
24
|
+
sdkCompat?: "openai";
|
|
25
|
+
/** Default model ID when none is configured */
|
|
26
|
+
defaultModel?: string;
|
|
27
|
+
/** Override provider name for model registry lookup */
|
|
28
|
+
registryAlias?: string;
|
|
29
|
+
/** Whether to show in "Add Provider" catalog (default: true) */
|
|
30
|
+
catalogVisible?: boolean;
|
|
31
|
+
agentSettingsStore: AgentSettingsStore;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Generic API-key provider module.
|
|
36
|
+
* Any model provider that only needs a "paste your API key" flow
|
|
37
|
+
* can be instantiated from this class without writing a full module.
|
|
38
|
+
*
|
|
39
|
+
* Config-driven providers (from system-skills.json) set sdkCompat,
|
|
40
|
+
* defaultModel, and registryAlias to enable dynamic worker model resolution.
|
|
41
|
+
*/
|
|
42
|
+
export class ApiKeyProviderModule extends BaseProviderModule {
|
|
43
|
+
protected readonly apiKeyConfig: ApiKeyProviderConfig;
|
|
44
|
+
|
|
45
|
+
constructor(config: ApiKeyProviderConfig) {
|
|
46
|
+
const authProfilesManager = new AuthProfilesManager(
|
|
47
|
+
config.agentSettingsStore
|
|
48
|
+
);
|
|
49
|
+
super(
|
|
50
|
+
{
|
|
51
|
+
providerId: config.providerId,
|
|
52
|
+
providerDisplayName: config.providerDisplayName,
|
|
53
|
+
providerIconUrl: config.providerIconUrl,
|
|
54
|
+
credentialEnvVarName: config.envVarName,
|
|
55
|
+
secretEnvVarNames: [config.envVarName],
|
|
56
|
+
systemEnvVarName: config.systemEnvVarName,
|
|
57
|
+
slug: config.slug || config.providerId,
|
|
58
|
+
upstreamBaseUrl: config.upstreamBaseUrl,
|
|
59
|
+
baseUrlEnvVarName:
|
|
60
|
+
config.baseUrlEnvVarName ||
|
|
61
|
+
config.envVarName.replace("_KEY", "_BASE_URL"),
|
|
62
|
+
authType: "api-key",
|
|
63
|
+
apiKeyInstructions: config.apiKeyInstructions,
|
|
64
|
+
apiKeyPlaceholder: config.apiKeyPlaceholder,
|
|
65
|
+
catalogVisible: config.catalogVisible,
|
|
66
|
+
},
|
|
67
|
+
authProfilesManager
|
|
68
|
+
);
|
|
69
|
+
this.apiKeyConfig = config;
|
|
70
|
+
this.name = `${config.providerId}-api-key`;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* For openai-compatible providers, also map OPENAI_BASE_URL so the
|
|
75
|
+
* OpenAI SDK resolves through our proxy.
|
|
76
|
+
*/
|
|
77
|
+
override getProxyBaseUrlMappings(
|
|
78
|
+
proxyUrl: string,
|
|
79
|
+
agentId?: string
|
|
80
|
+
): Record<string, string> {
|
|
81
|
+
const mappings = super.getProxyBaseUrlMappings(proxyUrl, agentId);
|
|
82
|
+
if (this.apiKeyConfig.sdkCompat === "openai") {
|
|
83
|
+
const slug = this.providerConfig.slug || this.providerId;
|
|
84
|
+
const base = `${proxyUrl}/${slug}`;
|
|
85
|
+
mappings.OPENAI_BASE_URL = agentId ? `${base}/a/${agentId}` : base;
|
|
86
|
+
}
|
|
87
|
+
return mappings;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Returns metadata for config-driven providers (sdkCompat, defaultModel, etc.)
|
|
92
|
+
* so the worker can register them dynamically. Returns null for hardcoded providers.
|
|
93
|
+
*/
|
|
94
|
+
getProviderMetadata(): ConfigProviderMeta | null {
|
|
95
|
+
if (
|
|
96
|
+
!this.apiKeyConfig.sdkCompat &&
|
|
97
|
+
!this.apiKeyConfig.defaultModel &&
|
|
98
|
+
!this.apiKeyConfig.registryAlias
|
|
99
|
+
) {
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
sdkCompat: this.apiKeyConfig.sdkCompat,
|
|
104
|
+
defaultModel: this.apiKeyConfig.defaultModel,
|
|
105
|
+
registryAlias: this.apiKeyConfig.registryAlias,
|
|
106
|
+
baseUrlEnvVar:
|
|
107
|
+
this.providerConfig.baseUrlEnvVarName ||
|
|
108
|
+
this.apiKeyConfig.envVarName.replace("_KEY", "_BASE_URL"),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async getModelOptions(
|
|
113
|
+
agentId: string,
|
|
114
|
+
_userId: string
|
|
115
|
+
): Promise<ModelOption[]> {
|
|
116
|
+
const key = await this.getCredential(agentId);
|
|
117
|
+
if (!key) return [];
|
|
118
|
+
|
|
119
|
+
// Gemini uses a non-standard models endpoint with key-in-query auth
|
|
120
|
+
if (this.providerId === "gemini") {
|
|
121
|
+
return this.fetchGeminiModels(key);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Generic modelsEndpoint: supports OpenAI format ({data:[{id}]}) and Ollama format ({models:[{name}]})
|
|
125
|
+
const modelsEndpoint = this.apiKeyConfig.modelsEndpoint;
|
|
126
|
+
if (modelsEndpoint && this.apiKeyConfig.upstreamBaseUrl) {
|
|
127
|
+
return this.fetchModelsGeneric(
|
|
128
|
+
key,
|
|
129
|
+
this.apiKeyConfig.upstreamBaseUrl,
|
|
130
|
+
modelsEndpoint
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return [];
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Generic model fetcher using Bearer auth. Works with OpenAI-compatible
|
|
139
|
+
* endpoints ({data:[{id}]}) and Ollama ({models:[{name}]}).
|
|
140
|
+
*/
|
|
141
|
+
private async fetchModelsGeneric(
|
|
142
|
+
apiKey: string,
|
|
143
|
+
baseUrl: string,
|
|
144
|
+
endpoint: string
|
|
145
|
+
): Promise<ModelOption[]> {
|
|
146
|
+
const url = `${baseUrl.replace(/\/$/, "")}${endpoint}`;
|
|
147
|
+
const response = await fetch(url, {
|
|
148
|
+
headers: {
|
|
149
|
+
Accept: "application/json",
|
|
150
|
+
Authorization: `Bearer ${apiKey}`,
|
|
151
|
+
},
|
|
152
|
+
}).catch(() => null);
|
|
153
|
+
if (!response || !response.ok) return [];
|
|
154
|
+
|
|
155
|
+
const payload = (await response.json().catch(() => ({}))) as {
|
|
156
|
+
data?: Array<{ id?: string }>;
|
|
157
|
+
models?: Array<{ name?: string; model?: string }>;
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
const prefix = this.providerId;
|
|
161
|
+
|
|
162
|
+
// OpenAI format: { data: [{ id: "model-name" }] }
|
|
163
|
+
if (payload.data && Array.isArray(payload.data)) {
|
|
164
|
+
return payload.data
|
|
165
|
+
.map((model) => {
|
|
166
|
+
const id = model.id?.trim();
|
|
167
|
+
if (!id) return null;
|
|
168
|
+
return { value: `${prefix}/${id}`, label: id } satisfies ModelOption;
|
|
169
|
+
})
|
|
170
|
+
.filter((item): item is ModelOption => Boolean(item));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Ollama format: { models: [{ name: "model-name", model: "model-name" }] }
|
|
174
|
+
if (payload.models && Array.isArray(payload.models)) {
|
|
175
|
+
return payload.models
|
|
176
|
+
.map((model) => {
|
|
177
|
+
const id = (model.model || model.name)?.trim();
|
|
178
|
+
if (!id) return null;
|
|
179
|
+
return { value: `${prefix}/${id}`, label: id } satisfies ModelOption;
|
|
180
|
+
})
|
|
181
|
+
.filter((item): item is ModelOption => Boolean(item));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return [];
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
private async fetchGeminiModels(apiKey: string): Promise<ModelOption[]> {
|
|
188
|
+
const url = new URL(
|
|
189
|
+
"https://generativelanguage.googleapis.com/v1beta/models"
|
|
190
|
+
);
|
|
191
|
+
url.searchParams.set("key", apiKey);
|
|
192
|
+
|
|
193
|
+
const response = await fetch(url.toString(), {
|
|
194
|
+
headers: { Accept: "application/json" },
|
|
195
|
+
}).catch(() => null);
|
|
196
|
+
if (!response || !response.ok) return [];
|
|
197
|
+
|
|
198
|
+
const payload = (await response.json().catch(() => ({}))) as {
|
|
199
|
+
models?: Array<{ name?: string; displayName?: string }>;
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
return (payload.models || [])
|
|
203
|
+
.map((model) => {
|
|
204
|
+
const raw = model.name?.replace(/^models\//, "").trim();
|
|
205
|
+
if (!raw) return null;
|
|
206
|
+
return {
|
|
207
|
+
value: `gemini/${raw}`,
|
|
208
|
+
label: model.displayName || raw,
|
|
209
|
+
} satisfies ModelOption;
|
|
210
|
+
})
|
|
211
|
+
.filter((item): item is ModelOption => Boolean(item));
|
|
212
|
+
}
|
|
213
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { createLogger } from "@lobu/core";
|
|
2
|
+
import { Hono } from "hono";
|
|
3
|
+
import {
|
|
4
|
+
BaseModule,
|
|
5
|
+
type ModelProviderModule,
|
|
6
|
+
type ProviderUpstreamConfig,
|
|
7
|
+
} from "../modules/module-system";
|
|
8
|
+
import { resolveEnv } from "./mcp/string-substitution";
|
|
9
|
+
import type { AuthProfilesManager } from "./settings/auth-profiles-manager";
|
|
10
|
+
|
|
11
|
+
const logger = createLogger("base-provider-module");
|
|
12
|
+
|
|
13
|
+
export interface BaseProviderConfig {
|
|
14
|
+
providerId: string;
|
|
15
|
+
providerDisplayName: string;
|
|
16
|
+
providerIconUrl: string;
|
|
17
|
+
/** Env var name the SDK expects for the API credential (e.g. "ANTHROPIC_API_KEY") */
|
|
18
|
+
credentialEnvVarName: string;
|
|
19
|
+
/** All env vars this provider considers secrets */
|
|
20
|
+
secretEnvVarNames: string[];
|
|
21
|
+
/** Env var to check for system key (defaults to credentialEnvVarName) */
|
|
22
|
+
systemEnvVarName?: string;
|
|
23
|
+
/** Provider slug for proxy path routing (e.g. "anthropic") */
|
|
24
|
+
slug?: string;
|
|
25
|
+
/** Upstream base URL for proxy forwarding (e.g. "https://api.anthropic.com") */
|
|
26
|
+
upstreamBaseUrl?: string;
|
|
27
|
+
/** Explicit base URL env var name (defaults to slug-derived name) */
|
|
28
|
+
baseUrlEnvVarName?: string;
|
|
29
|
+
authType: "oauth" | "device-code" | "api-key";
|
|
30
|
+
supportedAuthTypes?: ("oauth" | "device-code" | "api-key")[];
|
|
31
|
+
apiKeyInstructions?: string;
|
|
32
|
+
apiKeyPlaceholder?: string;
|
|
33
|
+
catalogDescription?: string;
|
|
34
|
+
catalogVisible?: boolean;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Base class for model provider modules.
|
|
39
|
+
* Implements shared logic: credential lookup, proxy mappings, env var injection,
|
|
40
|
+
* and Hono app management. Save-key and logout routes are handled by the
|
|
41
|
+
* parameterized auth router in gateway.ts.
|
|
42
|
+
*
|
|
43
|
+
* Subclasses provide a config object and optionally override:
|
|
44
|
+
* - `setupRoutes(app)` to add provider-specific routes
|
|
45
|
+
* - `getModelOptions()` for model listing
|
|
46
|
+
* - `buildEnvVars()` for custom env var injection
|
|
47
|
+
* - `hasSystemKey()` / `injectSystemKeyFallback()` for multi-env-var logic
|
|
48
|
+
*/
|
|
49
|
+
export abstract class BaseProviderModule
|
|
50
|
+
extends BaseModule
|
|
51
|
+
implements ModelProviderModule
|
|
52
|
+
{
|
|
53
|
+
name: string;
|
|
54
|
+
providerId: string;
|
|
55
|
+
providerDisplayName: string;
|
|
56
|
+
providerIconUrl: string;
|
|
57
|
+
authType: "oauth" | "device-code" | "api-key";
|
|
58
|
+
supportedAuthTypes?: ("oauth" | "device-code" | "api-key")[];
|
|
59
|
+
apiKeyInstructions?: string;
|
|
60
|
+
apiKeyPlaceholder?: string;
|
|
61
|
+
catalogDescription?: string;
|
|
62
|
+
catalogVisible?: boolean;
|
|
63
|
+
|
|
64
|
+
protected readonly providerConfig: BaseProviderConfig;
|
|
65
|
+
protected readonly authProfilesManager: AuthProfilesManager;
|
|
66
|
+
protected readonly app: Hono;
|
|
67
|
+
|
|
68
|
+
constructor(
|
|
69
|
+
config: BaseProviderConfig,
|
|
70
|
+
authProfilesManager: AuthProfilesManager
|
|
71
|
+
) {
|
|
72
|
+
super();
|
|
73
|
+
this.providerConfig = config;
|
|
74
|
+
this.authProfilesManager = authProfilesManager;
|
|
75
|
+
|
|
76
|
+
this.providerId = config.providerId;
|
|
77
|
+
this.name = `${config.providerId}-provider`;
|
|
78
|
+
this.providerDisplayName = config.providerDisplayName;
|
|
79
|
+
this.providerIconUrl = config.providerIconUrl;
|
|
80
|
+
this.authType = config.authType;
|
|
81
|
+
this.supportedAuthTypes = config.supportedAuthTypes;
|
|
82
|
+
this.apiKeyInstructions = config.apiKeyInstructions;
|
|
83
|
+
this.apiKeyPlaceholder = config.apiKeyPlaceholder;
|
|
84
|
+
this.catalogDescription = config.catalogDescription;
|
|
85
|
+
this.catalogVisible = config.catalogVisible;
|
|
86
|
+
|
|
87
|
+
this.app = new Hono();
|
|
88
|
+
this.setupRoutes();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
isEnabled(): boolean {
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
getSecretEnvVarNames(): string[] {
|
|
96
|
+
return this.providerConfig.secretEnvVarNames;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
getCredentialEnvVarName(): string {
|
|
100
|
+
return this.providerConfig.credentialEnvVarName;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
getUpstreamConfig(): ProviderUpstreamConfig | null {
|
|
104
|
+
const { slug, upstreamBaseUrl, baseUrlEnvVarName } = this.providerConfig;
|
|
105
|
+
if (!slug || !upstreamBaseUrl) return null;
|
|
106
|
+
// Check env for base URL override (e.g., ANTHROPIC_BASE_URL=https://api.z.ai)
|
|
107
|
+
const envOverride = baseUrlEnvVarName
|
|
108
|
+
? resolveEnv(baseUrlEnvVarName)
|
|
109
|
+
: undefined;
|
|
110
|
+
return { slug, upstreamBaseUrl: envOverride || upstreamBaseUrl };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async hasCredentials(agentId: string): Promise<boolean> {
|
|
114
|
+
return this.authProfilesManager.hasProviderProfiles(
|
|
115
|
+
agentId,
|
|
116
|
+
this.providerId
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
hasSystemKey(): boolean {
|
|
121
|
+
const envVar =
|
|
122
|
+
this.providerConfig.systemEnvVarName ||
|
|
123
|
+
this.providerConfig.credentialEnvVarName;
|
|
124
|
+
return !!resolveEnv(envVar);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
getProxyBaseUrlMappings(
|
|
128
|
+
proxyUrl: string,
|
|
129
|
+
agentId?: string
|
|
130
|
+
): Record<string, string> {
|
|
131
|
+
const { slug, baseUrlEnvVarName, credentialEnvVarName } =
|
|
132
|
+
this.providerConfig;
|
|
133
|
+
if (!slug) return {};
|
|
134
|
+
const envVar =
|
|
135
|
+
baseUrlEnvVarName || credentialEnvVarName.replace("_KEY", "_BASE_URL");
|
|
136
|
+
const base = `${proxyUrl}/${slug}`;
|
|
137
|
+
return { [envVar]: agentId ? `${base}/a/${agentId}` : base };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
injectSystemKeyFallback(
|
|
141
|
+
envVars: Record<string, string>
|
|
142
|
+
): Record<string, string> {
|
|
143
|
+
const credVar = this.providerConfig.credentialEnvVarName;
|
|
144
|
+
if (!envVars[credVar]) {
|
|
145
|
+
const sysVar = this.providerConfig.systemEnvVarName || credVar;
|
|
146
|
+
const systemKey = resolveEnv(sysVar);
|
|
147
|
+
if (systemKey) {
|
|
148
|
+
envVars[credVar] = systemKey;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return envVars;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async buildEnvVars(
|
|
155
|
+
agentId: string,
|
|
156
|
+
envVars: Record<string, string>
|
|
157
|
+
): Promise<Record<string, string>> {
|
|
158
|
+
const credVar = this.providerConfig.credentialEnvVarName;
|
|
159
|
+
if (!envVars[credVar]) {
|
|
160
|
+
const profile = await this.authProfilesManager.getBestProfile(
|
|
161
|
+
agentId,
|
|
162
|
+
this.providerId
|
|
163
|
+
);
|
|
164
|
+
if (profile?.credential) {
|
|
165
|
+
logger.info(
|
|
166
|
+
`Injecting ${credVar} for agent ${agentId} (${this.providerId})`
|
|
167
|
+
);
|
|
168
|
+
envVars[credVar] = profile.credential;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return envVars;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
getApp(): Hono {
|
|
175
|
+
return this.app;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
protected async getCredential(agentId: string): Promise<string | null> {
|
|
179
|
+
const profile = await this.authProfilesManager.getBestProfile(
|
|
180
|
+
agentId,
|
|
181
|
+
this.providerId
|
|
182
|
+
);
|
|
183
|
+
if (profile?.credential) {
|
|
184
|
+
return profile.credential;
|
|
185
|
+
}
|
|
186
|
+
const sysVar =
|
|
187
|
+
this.providerConfig.systemEnvVarName ||
|
|
188
|
+
this.providerConfig.credentialEnvVarName;
|
|
189
|
+
return process.env[sysVar] || null;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Build a structured placeholder for proxy mode (default: "lobu-proxy"). */
|
|
193
|
+
buildCredentialPlaceholder(_agentId: string): Promise<string> | string {
|
|
194
|
+
return "lobu-proxy";
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Override in subclasses to add provider-specific routes. */
|
|
198
|
+
protected setupRoutes(): void {
|
|
199
|
+
// Default: no extra routes
|
|
200
|
+
}
|
|
201
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { createLogger } from "@lobu/core";
|
|
2
|
+
import type { ModelOption } from "../../modules/module-system";
|
|
3
|
+
import { BaseProviderModule } from "../base-provider-module";
|
|
4
|
+
import type { AgentSettingsStore } from "../settings/agent-settings-store";
|
|
5
|
+
import {
|
|
6
|
+
AuthProfilesManager,
|
|
7
|
+
createAuthProfileLabel,
|
|
8
|
+
} from "../settings/auth-profiles-manager";
|
|
9
|
+
import { ChatGPTDeviceCodeClient } from "./device-code-client";
|
|
10
|
+
|
|
11
|
+
const logger = createLogger("chatgpt-oauth-module");
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* ChatGPT OAuth Module - Handles device code authentication for ChatGPT.
|
|
15
|
+
* Stores the access token in auth profiles.
|
|
16
|
+
*/
|
|
17
|
+
export class ChatGPTOAuthModule extends BaseProviderModule {
|
|
18
|
+
private deviceCodeClient: ChatGPTDeviceCodeClient;
|
|
19
|
+
|
|
20
|
+
constructor(agentSettingsStore: AgentSettingsStore) {
|
|
21
|
+
const authProfilesManager = new AuthProfilesManager(agentSettingsStore);
|
|
22
|
+
super(
|
|
23
|
+
{
|
|
24
|
+
providerId: "chatgpt",
|
|
25
|
+
providerDisplayName: "ChatGPT",
|
|
26
|
+
providerIconUrl:
|
|
27
|
+
"https://www.google.com/s2/favicons?domain=chatgpt.com&sz=128",
|
|
28
|
+
credentialEnvVarName: "OPENAI_API_KEY",
|
|
29
|
+
secretEnvVarNames: ["OPENAI_API_KEY"],
|
|
30
|
+
slug: "openai-codex",
|
|
31
|
+
upstreamBaseUrl: "https://chatgpt.com/backend-api",
|
|
32
|
+
baseUrlEnvVarName: "OPENAI_BASE_URL",
|
|
33
|
+
authType: "device-code",
|
|
34
|
+
supportedAuthTypes: ["device-code", "api-key"],
|
|
35
|
+
apiKeyInstructions:
|
|
36
|
+
'Enter your <a href="https://platform.openai.com/api-keys" target="_blank" class="text-blue-600 underline">OpenAI API key</a>:',
|
|
37
|
+
apiKeyPlaceholder: "sk-...",
|
|
38
|
+
catalogDescription: "OpenAI's ChatGPT with device code authentication",
|
|
39
|
+
},
|
|
40
|
+
authProfilesManager
|
|
41
|
+
);
|
|
42
|
+
// Preserve existing module name
|
|
43
|
+
this.name = "chatgpt-oauth";
|
|
44
|
+
this.deviceCodeClient = new ChatGPTDeviceCodeClient();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async buildCredentialPlaceholder(agentId: string): Promise<string> {
|
|
48
|
+
const profile = await this.authProfilesManager.getBestProfile(
|
|
49
|
+
agentId,
|
|
50
|
+
this.providerId
|
|
51
|
+
);
|
|
52
|
+
// Try metadata first, then extract from the stored credential JWT
|
|
53
|
+
let accountId = profile?.metadata?.accountId as string | undefined;
|
|
54
|
+
if (!accountId && profile?.credential) {
|
|
55
|
+
accountId = this.deviceCodeClient.extractAccountId(profile.credential);
|
|
56
|
+
}
|
|
57
|
+
if (!accountId) return "lobu-proxy";
|
|
58
|
+
|
|
59
|
+
// Minimal JWT with the chatgpt_account_id claim.
|
|
60
|
+
// Not a valid credential — only used by the codex backend to extract accountId.
|
|
61
|
+
const header = Buffer.from(
|
|
62
|
+
JSON.stringify({ alg: "none", typ: "JWT" })
|
|
63
|
+
).toString("base64url");
|
|
64
|
+
const payload = Buffer.from(
|
|
65
|
+
JSON.stringify({
|
|
66
|
+
"https://api.openai.com/auth": { chatgpt_account_id: accountId },
|
|
67
|
+
})
|
|
68
|
+
).toString("base64url");
|
|
69
|
+
return `${header}.${payload}.placeholder`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
getCliBackendConfig() {
|
|
73
|
+
return {
|
|
74
|
+
name: "codex",
|
|
75
|
+
command: "npx",
|
|
76
|
+
args: ["-y", "acpx@latest", "codex", "--quiet"],
|
|
77
|
+
modelArg: "--model",
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async getModelOptions(
|
|
82
|
+
agentId: string,
|
|
83
|
+
_userId: string
|
|
84
|
+
): Promise<ModelOption[]> {
|
|
85
|
+
const token = await this.getCredential(agentId);
|
|
86
|
+
if (!token) return [];
|
|
87
|
+
|
|
88
|
+
const response = await fetch("https://chatgpt.com/backend-api/models", {
|
|
89
|
+
headers: {
|
|
90
|
+
Accept: "application/json",
|
|
91
|
+
Authorization: `Bearer ${token}`,
|
|
92
|
+
},
|
|
93
|
+
}).catch(() => null);
|
|
94
|
+
|
|
95
|
+
if (!response || !response.ok) {
|
|
96
|
+
return [];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const payload = (await response.json().catch(() => ({}))) as {
|
|
100
|
+
models?: Array<{
|
|
101
|
+
slug?: string;
|
|
102
|
+
title?: string;
|
|
103
|
+
}>;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
return (payload.models || [])
|
|
107
|
+
.map((model) => {
|
|
108
|
+
const slug = model.slug?.trim();
|
|
109
|
+
if (!slug) return null;
|
|
110
|
+
return {
|
|
111
|
+
value: `openai-codex/${slug}`,
|
|
112
|
+
label: model.title?.trim() || slug,
|
|
113
|
+
} satisfies ModelOption;
|
|
114
|
+
})
|
|
115
|
+
.filter((item): item is ModelOption => Boolean(item));
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async startDeviceCode(agentId: string): Promise<{
|
|
119
|
+
userCode: string;
|
|
120
|
+
deviceAuthId: string;
|
|
121
|
+
interval: number;
|
|
122
|
+
verificationUrl: string;
|
|
123
|
+
}> {
|
|
124
|
+
try {
|
|
125
|
+
logger.info("Starting ChatGPT device code flow", { agentId });
|
|
126
|
+
const result = await this.deviceCodeClient.requestDeviceCode();
|
|
127
|
+
return {
|
|
128
|
+
userCode: result.userCode,
|
|
129
|
+
deviceAuthId: result.deviceAuthId,
|
|
130
|
+
interval: result.interval,
|
|
131
|
+
verificationUrl: "https://auth.openai.com/codex/device",
|
|
132
|
+
};
|
|
133
|
+
} catch (error) {
|
|
134
|
+
logger.error("Failed to start device code flow", { error });
|
|
135
|
+
throw new Error("Failed to start device code flow");
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async pollDeviceCode(
|
|
140
|
+
agentId: string,
|
|
141
|
+
payload: { deviceAuthId: string; userCode: string }
|
|
142
|
+
): Promise<{
|
|
143
|
+
status: "pending" | "success";
|
|
144
|
+
error?: string;
|
|
145
|
+
accountId?: string;
|
|
146
|
+
}> {
|
|
147
|
+
try {
|
|
148
|
+
const result = await this.deviceCodeClient.pollForToken(
|
|
149
|
+
payload.deviceAuthId,
|
|
150
|
+
payload.userCode
|
|
151
|
+
);
|
|
152
|
+
|
|
153
|
+
if (!result) {
|
|
154
|
+
return { status: "pending" };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
await this.authProfilesManager.upsertProfile({
|
|
158
|
+
agentId,
|
|
159
|
+
provider: this.providerId,
|
|
160
|
+
credential: result.accessToken,
|
|
161
|
+
authType: "device-code",
|
|
162
|
+
label: createAuthProfileLabel(
|
|
163
|
+
this.providerDisplayName,
|
|
164
|
+
result.accessToken,
|
|
165
|
+
result.accountId
|
|
166
|
+
),
|
|
167
|
+
metadata: {
|
|
168
|
+
accountId: result.accountId,
|
|
169
|
+
refreshToken: result.refreshToken,
|
|
170
|
+
expiresAt: Date.now() + result.expiresIn * 1000,
|
|
171
|
+
},
|
|
172
|
+
makePrimary: true,
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
logger.info(`ChatGPT token saved for agent ${agentId}`);
|
|
176
|
+
return {
|
|
177
|
+
status: "success",
|
|
178
|
+
accountId: result.accountId,
|
|
179
|
+
};
|
|
180
|
+
} catch (error) {
|
|
181
|
+
logger.error("Failed to poll for token", { error });
|
|
182
|
+
throw new Error("Failed to poll for token");
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|