@lobu/gateway 3.0.9 → 3.0.12
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/dist/api/platform.d.ts.map +1 -1
- package/dist/api/platform.js +7 -26
- package/dist/api/platform.js.map +1 -1
- package/dist/auth/mcp/proxy.d.ts +14 -0
- package/dist/auth/mcp/proxy.d.ts.map +1 -1
- package/dist/auth/mcp/proxy.js +149 -13
- package/dist/auth/mcp/proxy.js.map +1 -1
- package/dist/cli/gateway.d.ts.map +1 -1
- package/dist/cli/gateway.js +29 -0
- package/dist/cli/gateway.js.map +1 -1
- package/dist/connections/chat-instance-manager.d.ts.map +1 -1
- package/dist/connections/chat-instance-manager.js +2 -1
- package/dist/connections/chat-instance-manager.js.map +1 -1
- package/dist/connections/interaction-bridge.d.ts +9 -2
- package/dist/connections/interaction-bridge.d.ts.map +1 -1
- package/dist/connections/interaction-bridge.js +121 -261
- package/dist/connections/interaction-bridge.js.map +1 -1
- package/dist/interactions.d.ts +9 -43
- package/dist/interactions.d.ts.map +1 -1
- package/dist/interactions.js +10 -52
- package/dist/interactions.js.map +1 -1
- package/dist/routes/public/agent.d.ts +4 -0
- package/dist/routes/public/agent.d.ts.map +1 -1
- package/dist/routes/public/agent.js +21 -0
- package/dist/routes/public/agent.js.map +1 -1
- package/dist/services/core-services.d.ts.map +1 -1
- package/dist/services/core-services.js +4 -0
- package/dist/services/core-services.js.map +1 -1
- package/package.json +9 -9
- package/src/__tests__/agent-config-routes.test.ts +0 -254
- package/src/__tests__/agent-history-routes.test.ts +0 -72
- package/src/__tests__/agent-routes.test.ts +0 -68
- package/src/__tests__/agent-schedules-routes.test.ts +0 -59
- package/src/__tests__/agent-settings-store.test.ts +0 -323
- package/src/__tests__/bedrock-model-catalog.test.ts +0 -40
- package/src/__tests__/bedrock-openai-service.test.ts +0 -157
- package/src/__tests__/bedrock-provider-module.test.ts +0 -56
- package/src/__tests__/chat-instance-manager-slack.test.ts +0 -204
- package/src/__tests__/chat-response-bridge.test.ts +0 -131
- package/src/__tests__/config-memory-plugins.test.ts +0 -92
- package/src/__tests__/config-request-store.test.ts +0 -127
- package/src/__tests__/connection-routes.test.ts +0 -144
- package/src/__tests__/core-services-store-selection.test.ts +0 -92
- package/src/__tests__/docker-deployment.test.ts +0 -1211
- package/src/__tests__/embedded-deployment.test.ts +0 -342
- package/src/__tests__/grant-store.test.ts +0 -148
- package/src/__tests__/http-proxy.test.ts +0 -281
- package/src/__tests__/instruction-service.test.ts +0 -37
- package/src/__tests__/link-buttons.test.ts +0 -112
- package/src/__tests__/lobu.test.ts +0 -32
- package/src/__tests__/mcp-config-service.test.ts +0 -347
- package/src/__tests__/mcp-proxy.test.ts +0 -694
- package/src/__tests__/message-handler-bridge.test.ts +0 -17
- package/src/__tests__/model-selection.test.ts +0 -172
- package/src/__tests__/oauth-templates.test.ts +0 -39
- package/src/__tests__/platform-adapter-slack-send.test.ts +0 -114
- package/src/__tests__/platform-helpers-model-resolution.test.ts +0 -253
- package/src/__tests__/provider-inheritance.test.ts +0 -212
- package/src/__tests__/routes/cli-auth.test.ts +0 -337
- package/src/__tests__/routes/interactions.test.ts +0 -121
- package/src/__tests__/secret-proxy.test.ts +0 -85
- package/src/__tests__/session-manager.test.ts +0 -572
- package/src/__tests__/setup.ts +0 -133
- package/src/__tests__/skill-and-mcp-registry.test.ts +0 -203
- package/src/__tests__/slack-routes.test.ts +0 -161
- package/src/__tests__/system-config-resolver.test.ts +0 -75
- package/src/__tests__/system-message-limiter.test.ts +0 -89
- package/src/__tests__/system-skills-service.test.ts +0 -362
- package/src/__tests__/transcription-service.test.ts +0 -222
- package/src/__tests__/utils/rate-limiter.test.ts +0 -102
- package/src/__tests__/worker-connection-manager.test.ts +0 -497
- package/src/__tests__/worker-job-router.test.ts +0 -722
- package/src/api/index.ts +0 -1
- package/src/api/platform.ts +0 -292
- package/src/api/response-renderer.ts +0 -157
- package/src/auth/agent-metadata-store.ts +0 -168
- package/src/auth/api-auth-middleware.ts +0 -69
- package/src/auth/api-key-provider-module.ts +0 -213
- package/src/auth/base-provider-module.ts +0 -201
- package/src/auth/bedrock/provider-module.ts +0 -110
- package/src/auth/chatgpt/chatgpt-oauth-module.ts +0 -185
- package/src/auth/chatgpt/device-code-client.ts +0 -218
- package/src/auth/chatgpt/index.ts +0 -1
- package/src/auth/claude/oauth-module.ts +0 -280
- package/src/auth/cli/token-service.ts +0 -249
- package/src/auth/external/client.ts +0 -560
- package/src/auth/external/device-code-client.ts +0 -235
- package/src/auth/mcp/config-service.ts +0 -420
- package/src/auth/mcp/proxy.ts +0 -1086
- package/src/auth/mcp/string-substitution.ts +0 -17
- package/src/auth/mcp/tool-cache.ts +0 -90
- package/src/auth/oauth/base-client.ts +0 -267
- package/src/auth/oauth/client.ts +0 -153
- package/src/auth/oauth/credentials.ts +0 -7
- package/src/auth/oauth/providers.ts +0 -69
- package/src/auth/oauth/state-store.ts +0 -150
- package/src/auth/oauth-templates.ts +0 -179
- package/src/auth/provider-catalog.ts +0 -220
- package/src/auth/provider-model-options.ts +0 -41
- package/src/auth/settings/agent-settings-store.ts +0 -565
- package/src/auth/settings/auth-profiles-manager.ts +0 -216
- package/src/auth/settings/index.ts +0 -12
- package/src/auth/settings/model-preference-store.ts +0 -52
- package/src/auth/settings/model-selection.ts +0 -135
- package/src/auth/settings/resolved-settings-view.ts +0 -298
- package/src/auth/settings/template-utils.ts +0 -44
- package/src/auth/settings/token-service.ts +0 -88
- package/src/auth/system-env-store.ts +0 -98
- package/src/auth/user-agents-store.ts +0 -68
- package/src/channels/binding-service.ts +0 -214
- package/src/channels/index.ts +0 -4
- package/src/cli/gateway.ts +0 -1312
- package/src/cli/index.ts +0 -74
- package/src/commands/built-in-commands.ts +0 -80
- package/src/commands/command-dispatcher.ts +0 -94
- package/src/commands/command-reply-adapters.ts +0 -27
- package/src/config/file-loader.ts +0 -618
- package/src/config/index.ts +0 -588
- package/src/config/network-allowlist.ts +0 -71
- package/src/connections/chat-instance-manager.ts +0 -1284
- package/src/connections/chat-response-bridge.ts +0 -618
- package/src/connections/index.ts +0 -7
- package/src/connections/interaction-bridge.ts +0 -831
- package/src/connections/message-handler-bridge.ts +0 -440
- package/src/connections/platform-auth-methods.ts +0 -15
- package/src/connections/types.ts +0 -84
- package/src/gateway/connection-manager.ts +0 -291
- package/src/gateway/index.ts +0 -698
- package/src/gateway/job-router.ts +0 -201
- package/src/gateway-main.ts +0 -200
- package/src/index.ts +0 -41
- package/src/infrastructure/queue/index.ts +0 -12
- package/src/infrastructure/queue/queue-producer.ts +0 -148
- package/src/infrastructure/queue/redis-queue.ts +0 -361
- package/src/infrastructure/queue/types.ts +0 -133
- package/src/infrastructure/redis/system-message-limiter.ts +0 -94
- package/src/interactions/config-request-store.ts +0 -198
- package/src/interactions.ts +0 -363
- package/src/lobu.ts +0 -311
- package/src/metrics/prometheus.ts +0 -159
- package/src/modules/module-system.ts +0 -179
- package/src/orchestration/base-deployment-manager.ts +0 -900
- package/src/orchestration/deployment-utils.ts +0 -98
- package/src/orchestration/impl/docker-deployment.ts +0 -620
- package/src/orchestration/impl/embedded-deployment.ts +0 -268
- package/src/orchestration/impl/index.ts +0 -8
- package/src/orchestration/impl/k8s/deployment.ts +0 -1061
- package/src/orchestration/impl/k8s/helpers.ts +0 -610
- package/src/orchestration/impl/k8s/index.ts +0 -1
- package/src/orchestration/index.ts +0 -333
- package/src/orchestration/message-consumer.ts +0 -584
- package/src/orchestration/scheduled-wakeup.ts +0 -704
- package/src/permissions/approval-policy.ts +0 -36
- package/src/permissions/grant-store.ts +0 -219
- package/src/platform/file-handler.ts +0 -66
- package/src/platform/link-buttons.ts +0 -57
- package/src/platform/renderer-utils.ts +0 -44
- package/src/platform/response-renderer.ts +0 -84
- package/src/platform/unified-thread-consumer.ts +0 -194
- package/src/platform.ts +0 -318
- package/src/proxy/http-proxy.ts +0 -752
- package/src/proxy/proxy-manager.ts +0 -81
- package/src/proxy/secret-proxy.ts +0 -402
- package/src/proxy/token-refresh-job.ts +0 -143
- package/src/routes/internal/audio.ts +0 -141
- package/src/routes/internal/device-auth.ts +0 -652
- package/src/routes/internal/files.ts +0 -226
- package/src/routes/internal/history.ts +0 -69
- package/src/routes/internal/images.ts +0 -127
- package/src/routes/internal/interactions.ts +0 -84
- package/src/routes/internal/middleware.ts +0 -23
- package/src/routes/internal/schedule.ts +0 -226
- package/src/routes/internal/types.ts +0 -22
- package/src/routes/openapi-auto.ts +0 -239
- package/src/routes/public/agent-access.ts +0 -23
- package/src/routes/public/agent-config.ts +0 -675
- package/src/routes/public/agent-history.ts +0 -422
- package/src/routes/public/agent-schedules.ts +0 -296
- package/src/routes/public/agent.ts +0 -1086
- package/src/routes/public/agents.ts +0 -373
- package/src/routes/public/channels.ts +0 -191
- package/src/routes/public/cli-auth.ts +0 -896
- package/src/routes/public/connections.ts +0 -574
- package/src/routes/public/landing.ts +0 -16
- package/src/routes/public/oauth.ts +0 -147
- package/src/routes/public/settings-auth.ts +0 -104
- package/src/routes/public/slack.ts +0 -173
- package/src/routes/shared/agent-ownership.ts +0 -101
- package/src/routes/shared/token-verifier.ts +0 -34
- package/src/services/bedrock-model-catalog.ts +0 -217
- package/src/services/bedrock-openai-service.ts +0 -658
- package/src/services/core-services.ts +0 -1072
- package/src/services/image-generation-service.ts +0 -257
- package/src/services/instruction-service.ts +0 -318
- package/src/services/mcp-registry.ts +0 -94
- package/src/services/platform-helpers.ts +0 -287
- package/src/services/session-manager.ts +0 -262
- package/src/services/settings-resolver.ts +0 -74
- package/src/services/system-config-resolver.ts +0 -89
- package/src/services/system-skills-service.ts +0 -229
- package/src/services/transcription-service.ts +0 -684
- package/src/session.ts +0 -110
- package/src/spaces/index.ts +0 -1
- package/src/spaces/space-resolver.ts +0 -17
- package/src/stores/in-memory-agent-store.ts +0 -403
- package/src/stores/redis-agent-store.ts +0 -279
- package/src/utils/public-url.ts +0 -44
- package/src/utils/rate-limiter.ts +0 -94
- package/tsconfig.json +0 -33
- package/tsconfig.tsbuildinfo +0 -1
|
@@ -1,620 +0,0 @@
|
|
|
1
|
-
import fs from "node:fs";
|
|
2
|
-
import path from "node:path";
|
|
3
|
-
import { createLogger, ErrorCode, OrchestratorError } from "@lobu/core";
|
|
4
|
-
import Docker from "dockerode";
|
|
5
|
-
import type { ModelProviderModule } from "../../modules/module-system";
|
|
6
|
-
import {
|
|
7
|
-
BaseDeploymentManager,
|
|
8
|
-
type DeploymentInfo,
|
|
9
|
-
type MessagePayload,
|
|
10
|
-
type ModuleEnvVarsBuilder,
|
|
11
|
-
type OrchestratorConfig,
|
|
12
|
-
} from "../base-deployment-manager";
|
|
13
|
-
import {
|
|
14
|
-
BASE_WORKER_LABELS,
|
|
15
|
-
buildDeploymentInfoSummary,
|
|
16
|
-
getVeryOldThresholdDays,
|
|
17
|
-
resolvePlatformDeploymentMetadata,
|
|
18
|
-
} from "../deployment-utils";
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* Resource parsing utilities for memory and CPU limits
|
|
22
|
-
*/
|
|
23
|
-
class ResourceParser {
|
|
24
|
-
static parseMemory(memoryStr: string): number {
|
|
25
|
-
const units: Record<string, number> = {
|
|
26
|
-
Ki: 1024,
|
|
27
|
-
Mi: 1024 * 1024,
|
|
28
|
-
Gi: 1024 * 1024 * 1024,
|
|
29
|
-
k: 1000,
|
|
30
|
-
M: 1000 * 1000,
|
|
31
|
-
G: 1000 * 1000 * 1000,
|
|
32
|
-
};
|
|
33
|
-
for (const [unit, multiplier] of Object.entries(units)) {
|
|
34
|
-
if (memoryStr.endsWith(unit)) {
|
|
35
|
-
const value = parseFloat(memoryStr.replace(unit, ""));
|
|
36
|
-
return value * multiplier;
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
return parseInt(memoryStr, 10);
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
static parseCpu(cpuStr: string): number {
|
|
43
|
-
if (cpuStr.endsWith("m")) {
|
|
44
|
-
const millicores = parseInt(cpuStr.replace("m", ""), 10);
|
|
45
|
-
return (millicores / 1000) * 1e9;
|
|
46
|
-
}
|
|
47
|
-
const cores = parseFloat(cpuStr);
|
|
48
|
-
return cores * 1e9;
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
const logger = createLogger("orchestrator");
|
|
53
|
-
|
|
54
|
-
export class DockerDeploymentManager extends BaseDeploymentManager {
|
|
55
|
-
private docker: Docker;
|
|
56
|
-
private gvisorAvailable = false;
|
|
57
|
-
private activityTimestamps: Map<string, Date> = new Map();
|
|
58
|
-
|
|
59
|
-
constructor(
|
|
60
|
-
config: OrchestratorConfig,
|
|
61
|
-
moduleEnvVarsBuilder?: ModuleEnvVarsBuilder,
|
|
62
|
-
providerModules: ModelProviderModule[] = []
|
|
63
|
-
) {
|
|
64
|
-
super(config, moduleEnvVarsBuilder, providerModules);
|
|
65
|
-
|
|
66
|
-
// Explicitly use the Unix socket for Docker connection
|
|
67
|
-
this.docker = new Docker({ socketPath: "/var/run/docker.sock" });
|
|
68
|
-
|
|
69
|
-
// Check for gvisor availability on initialization
|
|
70
|
-
this.checkGvisorAvailability();
|
|
71
|
-
|
|
72
|
-
// Ensure the internal network exists for worker isolation
|
|
73
|
-
this.ensureInternalNetwork();
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
private async checkGvisorAvailability(): Promise<void> {
|
|
77
|
-
try {
|
|
78
|
-
const info = await this.docker.info();
|
|
79
|
-
const runtimes = info.Runtimes || {};
|
|
80
|
-
|
|
81
|
-
if (runtimes.runsc || runtimes.gvisor) {
|
|
82
|
-
this.gvisorAvailable = true;
|
|
83
|
-
logger.info(
|
|
84
|
-
"✅ gVisor runtime detected and will be used for worker isolation"
|
|
85
|
-
);
|
|
86
|
-
} else {
|
|
87
|
-
logger.info(
|
|
88
|
-
"ℹ️ gVisor runtime not available, using default runc runtime"
|
|
89
|
-
);
|
|
90
|
-
}
|
|
91
|
-
} catch (error) {
|
|
92
|
-
logger.warn(
|
|
93
|
-
`⚠️ Failed to check Docker runtime availability: ${error instanceof Error ? error.message : String(error)}`
|
|
94
|
-
);
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
/**
|
|
99
|
-
* Ensure the internal Docker network exists with `internal: true` for worker isolation.
|
|
100
|
-
* Skipped when WORKER_NETWORK is explicitly set (e.g. local dev using bridge).
|
|
101
|
-
* Creates the network if it doesn't exist (e.g. production without docker-compose).
|
|
102
|
-
*/
|
|
103
|
-
private async ensureInternalNetwork(): Promise<void> {
|
|
104
|
-
// If explicitly overridden (e.g. WORKER_NETWORK=bridge for local dev), skip
|
|
105
|
-
if (process.env.WORKER_NETWORK) {
|
|
106
|
-
return;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
const composeProjectName = process.env.COMPOSE_PROJECT_NAME || "lobu";
|
|
110
|
-
const networkName = `${composeProjectName}_lobu-internal`;
|
|
111
|
-
|
|
112
|
-
try {
|
|
113
|
-
const network = this.docker.getNetwork(networkName);
|
|
114
|
-
const info = await network.inspect();
|
|
115
|
-
if (!info.Internal) {
|
|
116
|
-
logger.warn(
|
|
117
|
-
`⚠️ Network ${networkName} exists but is NOT internal — workers may have direct internet access`
|
|
118
|
-
);
|
|
119
|
-
}
|
|
120
|
-
} catch {
|
|
121
|
-
// Network doesn't exist — create it with internal: true
|
|
122
|
-
try {
|
|
123
|
-
await this.docker.createNetwork({
|
|
124
|
-
Name: networkName,
|
|
125
|
-
Internal: true,
|
|
126
|
-
Driver: "bridge",
|
|
127
|
-
Labels: {
|
|
128
|
-
"lobu.io/managed": "true",
|
|
129
|
-
"lobu.io/purpose": "worker-isolation",
|
|
130
|
-
},
|
|
131
|
-
});
|
|
132
|
-
logger.info(
|
|
133
|
-
`✅ Created internal network ${networkName} for worker isolation`
|
|
134
|
-
);
|
|
135
|
-
} catch (createError) {
|
|
136
|
-
logger.error(
|
|
137
|
-
`Failed to create internal network ${networkName}: ${createError instanceof Error ? createError.message : String(createError)}`
|
|
138
|
-
);
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
/**
|
|
144
|
-
* Check if gateway is running inside a Docker container
|
|
145
|
-
*/
|
|
146
|
-
private isRunningInContainer(): boolean {
|
|
147
|
-
return fs.existsSync("/.dockerenv") || process.env.CONTAINER === "true";
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
/**
|
|
151
|
-
* Get the host address that workers should use to reach the gateway
|
|
152
|
-
* When gateway runs on host, workers use host.docker.internal
|
|
153
|
-
* When gateway runs in container (docker-compose mode), workers use service name
|
|
154
|
-
*/
|
|
155
|
-
private getHostAddress(): string {
|
|
156
|
-
if (this.isRunningInContainer()) {
|
|
157
|
-
return "gateway";
|
|
158
|
-
}
|
|
159
|
-
// For host-mode development, workers reach gateway via host.docker.internal
|
|
160
|
-
return "host.docker.internal";
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
/**
|
|
164
|
-
* Validate that the worker image exists locally, or pull it if missing.
|
|
165
|
-
* Called on gateway startup to ensure workers can be created.
|
|
166
|
-
*/
|
|
167
|
-
async validateWorkerImage(): Promise<void> {
|
|
168
|
-
const imageName = this.getWorkerImageReference();
|
|
169
|
-
|
|
170
|
-
try {
|
|
171
|
-
await this.docker.getImage(imageName).inspect();
|
|
172
|
-
logger.info(`✅ Worker image verified: ${imageName}`);
|
|
173
|
-
} catch (error) {
|
|
174
|
-
const errorMessage =
|
|
175
|
-
error instanceof Error ? error.message : String(error);
|
|
176
|
-
|
|
177
|
-
// If image not found, try to pull it
|
|
178
|
-
if (
|
|
179
|
-
errorMessage.includes("No such image") ||
|
|
180
|
-
errorMessage.includes("404")
|
|
181
|
-
) {
|
|
182
|
-
logger.info(
|
|
183
|
-
`📥 Worker image ${imageName} not found locally, pulling...`
|
|
184
|
-
);
|
|
185
|
-
try {
|
|
186
|
-
await new Promise<void>((resolve, reject) => {
|
|
187
|
-
this.docker.pull(imageName, (err: any, stream: any) => {
|
|
188
|
-
if (err) return reject(err);
|
|
189
|
-
this.docker.modem.followProgress(stream, (err: any) => {
|
|
190
|
-
if (err) reject(err);
|
|
191
|
-
else resolve();
|
|
192
|
-
});
|
|
193
|
-
});
|
|
194
|
-
});
|
|
195
|
-
logger.info(`✅ Worker image ${imageName} pulled successfully`);
|
|
196
|
-
} catch (pullError) {
|
|
197
|
-
logger.error(
|
|
198
|
-
`❌ Failed to pull worker image ${imageName}:`,
|
|
199
|
-
pullError
|
|
200
|
-
);
|
|
201
|
-
throw new OrchestratorError(
|
|
202
|
-
ErrorCode.DEPLOYMENT_CREATE_FAILED,
|
|
203
|
-
`Worker image ${imageName} does not exist locally and pull failed. Please check your internet connection or registry permissions.`
|
|
204
|
-
);
|
|
205
|
-
}
|
|
206
|
-
} else {
|
|
207
|
-
// Other error - re-throw
|
|
208
|
-
throw new OrchestratorError(
|
|
209
|
-
ErrorCode.DEPLOYMENT_CREATE_FAILED,
|
|
210
|
-
`Failed to validate worker image ${imageName}: ${errorMessage}`
|
|
211
|
-
);
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
async listDeployments(): Promise<DeploymentInfo[]> {
|
|
217
|
-
try {
|
|
218
|
-
const containers = await this.docker.listContainers({
|
|
219
|
-
all: true,
|
|
220
|
-
filters: {
|
|
221
|
-
label: ["app.kubernetes.io/component=worker"],
|
|
222
|
-
},
|
|
223
|
-
});
|
|
224
|
-
|
|
225
|
-
const now = Date.now();
|
|
226
|
-
const idleThresholdMinutes = this.config.worker.idleCleanupMinutes;
|
|
227
|
-
const veryOldDays = getVeryOldThresholdDays(this.config);
|
|
228
|
-
|
|
229
|
-
return containers.map((containerInfo: Docker.ContainerInfo) => {
|
|
230
|
-
const deploymentName = containerInfo.Names[0]?.substring(1) || ""; // Remove leading '/'
|
|
231
|
-
|
|
232
|
-
// Get last activity from in-memory tracking, labels, or creation time
|
|
233
|
-
const trackedActivity = this.activityTimestamps.get(deploymentName);
|
|
234
|
-
const lastActivityStr =
|
|
235
|
-
containerInfo.Labels?.["lobu.io/last-activity"] ||
|
|
236
|
-
containerInfo.Labels?.["lobu.io/created"];
|
|
237
|
-
|
|
238
|
-
const labelActivity = lastActivityStr
|
|
239
|
-
? new Date(lastActivityStr)
|
|
240
|
-
: new Date(containerInfo.Created * 1000);
|
|
241
|
-
|
|
242
|
-
// Use the most recent timestamp from any source
|
|
243
|
-
const lastActivity =
|
|
244
|
-
trackedActivity && trackedActivity > labelActivity
|
|
245
|
-
? trackedActivity
|
|
246
|
-
: labelActivity;
|
|
247
|
-
const replicas = containerInfo.State === "running" ? 1 : 0;
|
|
248
|
-
return buildDeploymentInfoSummary({
|
|
249
|
-
deploymentName,
|
|
250
|
-
lastActivity,
|
|
251
|
-
now,
|
|
252
|
-
idleThresholdMinutes,
|
|
253
|
-
veryOldDays,
|
|
254
|
-
replicas,
|
|
255
|
-
});
|
|
256
|
-
});
|
|
257
|
-
} catch (error) {
|
|
258
|
-
throw new OrchestratorError(
|
|
259
|
-
ErrorCode.DEPLOYMENT_CREATE_FAILED,
|
|
260
|
-
`Failed to list Docker containers: ${error instanceof Error ? error.message : String(error)}`,
|
|
261
|
-
{ error },
|
|
262
|
-
true
|
|
263
|
-
);
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
/**
|
|
268
|
-
* Ensures a Docker volume exists for the given space ID.
|
|
269
|
-
* Uses named volumes for better isolation and security.
|
|
270
|
-
* Multiple threads in the same space share the same volume.
|
|
271
|
-
*/
|
|
272
|
-
private async ensureVolume(agentId: string): Promise<string> {
|
|
273
|
-
const volumeName = `lobu-workspace-${agentId}`;
|
|
274
|
-
let volumeCreated = false;
|
|
275
|
-
|
|
276
|
-
try {
|
|
277
|
-
// Check if volume already exists (idempotent for concurrent creation)
|
|
278
|
-
await this.docker.getVolume(volumeName).inspect();
|
|
279
|
-
logger.info(`✅ Volume ${volumeName} already exists`);
|
|
280
|
-
} catch (_error) {
|
|
281
|
-
// Volume doesn't exist, create it
|
|
282
|
-
try {
|
|
283
|
-
await this.docker.createVolume({
|
|
284
|
-
Name: volumeName,
|
|
285
|
-
Labels: {
|
|
286
|
-
"lobu.io/agent-id": agentId,
|
|
287
|
-
"lobu.io/created": new Date().toISOString(),
|
|
288
|
-
},
|
|
289
|
-
});
|
|
290
|
-
logger.info(`✅ Created volume: ${volumeName}`);
|
|
291
|
-
volumeCreated = true;
|
|
292
|
-
} catch (createError: any) {
|
|
293
|
-
// Handle race condition: volume created by another thread
|
|
294
|
-
if (
|
|
295
|
-
createError.statusCode === 409 ||
|
|
296
|
-
createError.message?.includes("already exists")
|
|
297
|
-
) {
|
|
298
|
-
logger.info(`Volume ${volumeName} was created by another thread`);
|
|
299
|
-
} else {
|
|
300
|
-
throw createError;
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
// Fix volume permissions for new volumes
|
|
306
|
-
// The claude user in the worker container has UID 1001
|
|
307
|
-
if (volumeCreated) {
|
|
308
|
-
try {
|
|
309
|
-
const initContainer = await this.docker.createContainer({
|
|
310
|
-
Image: "alpine:latest",
|
|
311
|
-
Cmd: ["chown", "-R", "1001:1001", "/workspace"],
|
|
312
|
-
HostConfig: {
|
|
313
|
-
AutoRemove: true,
|
|
314
|
-
Mounts: [
|
|
315
|
-
{
|
|
316
|
-
Type: "volume",
|
|
317
|
-
Source: volumeName,
|
|
318
|
-
Target: "/workspace",
|
|
319
|
-
},
|
|
320
|
-
],
|
|
321
|
-
},
|
|
322
|
-
});
|
|
323
|
-
await initContainer.start();
|
|
324
|
-
await initContainer.wait();
|
|
325
|
-
logger.info(`✅ Fixed volume permissions for ${volumeName}`);
|
|
326
|
-
} catch (permError) {
|
|
327
|
-
logger.warn(
|
|
328
|
-
`⚠️ Could not fix volume permissions: ${permError instanceof Error ? permError.message : String(permError)}`
|
|
329
|
-
);
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
return volumeName;
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
async createDeployment(
|
|
337
|
-
...args: Parameters<BaseDeploymentManager["createDeployment"]>
|
|
338
|
-
): Promise<void> {
|
|
339
|
-
const [deploymentName, username, userId, messageDataRaw] = args;
|
|
340
|
-
const messageData = messageDataRaw as MessagePayload | undefined;
|
|
341
|
-
|
|
342
|
-
try {
|
|
343
|
-
// Use agentId for volume naming (shared across threads in same space)
|
|
344
|
-
const agentId = messageData?.agentId;
|
|
345
|
-
if (!agentId) {
|
|
346
|
-
throw new OrchestratorError(
|
|
347
|
-
ErrorCode.DEPLOYMENT_CREATE_FAILED,
|
|
348
|
-
"Missing agentId in message payload"
|
|
349
|
-
);
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
// Determine if running in Docker and resolve project paths
|
|
353
|
-
const isRunningInDocker = process.env.DEPLOYMENT_MODE === "docker";
|
|
354
|
-
const projectRoot = isRunningInDocker
|
|
355
|
-
? process.env.LOBU_DEV_PROJECT_PATH || "/app"
|
|
356
|
-
: path.join(process.cwd(), "..", "..");
|
|
357
|
-
|
|
358
|
-
const workspaceDir = `${projectRoot}/workspaces/${agentId}`;
|
|
359
|
-
|
|
360
|
-
// Ensure volume exists for production mode (space-scoped)
|
|
361
|
-
const volumeName = await this.ensureVolume(agentId);
|
|
362
|
-
|
|
363
|
-
// Get common environment variables from base class
|
|
364
|
-
const commonEnvVars = await this.generateEnvironmentVariables(
|
|
365
|
-
username,
|
|
366
|
-
userId,
|
|
367
|
-
deploymentName,
|
|
368
|
-
messageData,
|
|
369
|
-
true
|
|
370
|
-
);
|
|
371
|
-
|
|
372
|
-
// On macOS/Windows, Docker containers need to use host.docker.internal instead of localhost
|
|
373
|
-
if (process.platform === "darwin" || process.platform === "win32") {
|
|
374
|
-
if (
|
|
375
|
-
commonEnvVars.LOBU_DATABASE_HOST === "localhost" ||
|
|
376
|
-
commonEnvVars.LOBU_DATABASE_HOST === "127.0.0.1"
|
|
377
|
-
) {
|
|
378
|
-
commonEnvVars.LOBU_DATABASE_HOST = "host.docker.internal";
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
// Environment variables from base class already include:
|
|
383
|
-
// HTTP_PROXY, HTTPS_PROXY, NO_PROXY, NODE_ENV, DEBUG
|
|
384
|
-
// Provider credentials are injected via provider modules in generateEnvironmentVariables()
|
|
385
|
-
const envVars = Object.entries(commonEnvVars).map(
|
|
386
|
-
([key, value]) => `${key}=${value}`
|
|
387
|
-
);
|
|
388
|
-
|
|
389
|
-
// Check if Nix packages are configured (need writable rootfs for symlinks)
|
|
390
|
-
const hasNixConfig =
|
|
391
|
-
(messageData?.nixConfig?.packages?.length ?? 0) > 0 ||
|
|
392
|
-
!!messageData?.nixConfig?.flakeUrl;
|
|
393
|
-
|
|
394
|
-
// Get the Docker Compose project name from environment or use default
|
|
395
|
-
const composeProjectName = process.env.COMPOSE_PROJECT_NAME || "lobu";
|
|
396
|
-
|
|
397
|
-
const createOptions: Docker.ContainerCreateOptions = {
|
|
398
|
-
name: deploymentName,
|
|
399
|
-
Image: this.getWorkerImageReference(),
|
|
400
|
-
Env: envVars,
|
|
401
|
-
Labels: {
|
|
402
|
-
...BASE_WORKER_LABELS,
|
|
403
|
-
"lobu.io/created": new Date().toISOString(),
|
|
404
|
-
"lobu.io/agent-id": agentId,
|
|
405
|
-
// Docker Compose labels to associate with the project
|
|
406
|
-
"com.docker.compose.project": composeProjectName,
|
|
407
|
-
"com.docker.compose.service": deploymentName, // Use unique service name
|
|
408
|
-
"com.docker.compose.oneoff": "False",
|
|
409
|
-
// Add platform-specific metadata
|
|
410
|
-
...resolvePlatformDeploymentMetadata(messageData),
|
|
411
|
-
},
|
|
412
|
-
HostConfig: {
|
|
413
|
-
// Use named volumes in production for better isolation
|
|
414
|
-
// Use bind mounts in development for hot reload
|
|
415
|
-
...(process.env.NODE_ENV === "development" && isRunningInDocker
|
|
416
|
-
? {
|
|
417
|
-
Binds: [
|
|
418
|
-
`${workspaceDir}:/workspace`,
|
|
419
|
-
// Mount packages and scripts for hot reload
|
|
420
|
-
`${projectRoot}/packages:/app/packages`,
|
|
421
|
-
`${projectRoot}/scripts:/app/scripts`,
|
|
422
|
-
// Additional custom mounts (optional)
|
|
423
|
-
...(process.env.WORKER_VOLUME_MOUNTS
|
|
424
|
-
? process.env.WORKER_VOLUME_MOUNTS.split(";")
|
|
425
|
-
.filter((mount) => mount.trim())
|
|
426
|
-
.map((mount) =>
|
|
427
|
-
mount
|
|
428
|
-
.replace("${PWD}", projectRoot)
|
|
429
|
-
.replace("${WORKSPACE_DIR}", workspaceDir)
|
|
430
|
-
)
|
|
431
|
-
: []),
|
|
432
|
-
],
|
|
433
|
-
}
|
|
434
|
-
: {
|
|
435
|
-
// Production: use named volumes for better isolation
|
|
436
|
-
Mounts: [
|
|
437
|
-
{
|
|
438
|
-
Type: "volume",
|
|
439
|
-
Source: volumeName,
|
|
440
|
-
Target: "/workspace",
|
|
441
|
-
ReadOnly: false,
|
|
442
|
-
},
|
|
443
|
-
],
|
|
444
|
-
}),
|
|
445
|
-
RestartPolicy: {
|
|
446
|
-
Name: "unless-stopped",
|
|
447
|
-
},
|
|
448
|
-
// Resource limits similar to K8s
|
|
449
|
-
Memory: ResourceParser.parseMemory(
|
|
450
|
-
this.config.worker.resources.limits.memory
|
|
451
|
-
),
|
|
452
|
-
NanoCpus: ResourceParser.parseCpu(
|
|
453
|
-
this.config.worker.resources.limits.cpu
|
|
454
|
-
),
|
|
455
|
-
// Always connect to internal network (network isolation always enabled)
|
|
456
|
-
// In docker-compose mode: uses compose project prefix
|
|
457
|
-
// In host mode: uses plain network name (WORKER_NETWORK env var)
|
|
458
|
-
NetworkMode:
|
|
459
|
-
process.env.WORKER_NETWORK || `${composeProjectName}_lobu-internal`,
|
|
460
|
-
// Add host.docker.internal mapping when gateway runs on host
|
|
461
|
-
// Required on Linux, and needed on macOS/Windows when using internal networks
|
|
462
|
-
...(!this.isRunningInContainer() && {
|
|
463
|
-
ExtraHosts: ["host.docker.internal:host-gateway"],
|
|
464
|
-
}),
|
|
465
|
-
// Security: Drop all capabilities and only add what's needed
|
|
466
|
-
CapDrop: ["ALL"],
|
|
467
|
-
CapAdd: process.env.WORKER_CAPABILITIES
|
|
468
|
-
? process.env.WORKER_CAPABILITIES.split(",")
|
|
469
|
-
: [],
|
|
470
|
-
// Security: Prevent privilege escalation
|
|
471
|
-
SecurityOpt: [
|
|
472
|
-
"no-new-privileges:true",
|
|
473
|
-
// Custom seccomp profile (default Docker seccomp is applied automatically)
|
|
474
|
-
...(process.env.WORKER_SECCOMP_PROFILE
|
|
475
|
-
? [`seccomp=${process.env.WORKER_SECCOMP_PROFILE}`]
|
|
476
|
-
: []),
|
|
477
|
-
// AppArmor profile if specified
|
|
478
|
-
...(process.env.WORKER_APPARMOR_PROFILE
|
|
479
|
-
? [`apparmor=${process.env.WORKER_APPARMOR_PROFILE}`]
|
|
480
|
-
: []),
|
|
481
|
-
],
|
|
482
|
-
// User namespace remapping (if Docker daemon is configured for it)
|
|
483
|
-
// This makes the root user inside container map to non-root on host
|
|
484
|
-
UsernsMode: process.env.WORKER_USERNS_MODE || "",
|
|
485
|
-
// Read-only root filesystem (worker can write to /workspace and /tmp)
|
|
486
|
-
// Disabled when Nix packages configured (entrypoint needs to symlink /nix/store)
|
|
487
|
-
// Enabled by default for security, set WORKER_READONLY_ROOTFS=false to disable
|
|
488
|
-
ReadonlyRootfs:
|
|
489
|
-
!hasNixConfig && process.env.WORKER_READONLY_ROOTFS !== "false",
|
|
490
|
-
// Temporary filesystem for /tmp (writable, in-memory)
|
|
491
|
-
...(!hasNixConfig &&
|
|
492
|
-
process.env.WORKER_READONLY_ROOTFS !== "false" && {
|
|
493
|
-
Tmpfs: {
|
|
494
|
-
"/tmp": "rw,noexec,nosuid,size=100m",
|
|
495
|
-
},
|
|
496
|
-
}),
|
|
497
|
-
// Shared memory for Chromium and other apps requiring /dev/shm
|
|
498
|
-
ShmSize: 268435456, // 256MB
|
|
499
|
-
// Use gVisor runtime if available for enhanced isolation
|
|
500
|
-
...(this.gvisorAvailable && {
|
|
501
|
-
Runtime: "runsc",
|
|
502
|
-
}),
|
|
503
|
-
},
|
|
504
|
-
WorkingDir: "/workspace",
|
|
505
|
-
};
|
|
506
|
-
|
|
507
|
-
const container = await this.docker.createContainer(createOptions);
|
|
508
|
-
try {
|
|
509
|
-
await container.start();
|
|
510
|
-
} catch (startError) {
|
|
511
|
-
// Clean up orphaned container if start fails
|
|
512
|
-
logger.error(
|
|
513
|
-
`Failed to start container ${deploymentName}, removing orphaned container`,
|
|
514
|
-
startError
|
|
515
|
-
);
|
|
516
|
-
try {
|
|
517
|
-
await container.remove({ force: true });
|
|
518
|
-
} catch (removeError) {
|
|
519
|
-
logger.error(
|
|
520
|
-
`Failed to remove orphaned container ${deploymentName}:`,
|
|
521
|
-
removeError
|
|
522
|
-
);
|
|
523
|
-
}
|
|
524
|
-
throw startError;
|
|
525
|
-
}
|
|
526
|
-
|
|
527
|
-
// In host mode, also connect the worker to the public network so it can
|
|
528
|
-
// reach the host gateway via host.docker.internal (internal network blocks host access)
|
|
529
|
-
if (!this.isRunningInContainer()) {
|
|
530
|
-
try {
|
|
531
|
-
const publicNetwork = this.docker.getNetwork(
|
|
532
|
-
`${composeProjectName}_lobu-public`
|
|
533
|
-
);
|
|
534
|
-
await publicNetwork.connect({ Container: container.id });
|
|
535
|
-
} catch (netErr) {
|
|
536
|
-
logger.warn(
|
|
537
|
-
`Could not connect ${deploymentName} to public network: ${netErr instanceof Error ? netErr.message : String(netErr)}`
|
|
538
|
-
);
|
|
539
|
-
}
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
logger.info(`✅ Created and started Docker container: ${deploymentName}`);
|
|
543
|
-
} catch (error) {
|
|
544
|
-
throw new OrchestratorError(
|
|
545
|
-
ErrorCode.DEPLOYMENT_CREATE_FAILED,
|
|
546
|
-
`Failed to create Docker container: ${error instanceof Error ? error.message : String(error)}`,
|
|
547
|
-
{ deploymentName, error },
|
|
548
|
-
true
|
|
549
|
-
);
|
|
550
|
-
}
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
async scaleDeployment(
|
|
554
|
-
deploymentName: string,
|
|
555
|
-
replicas: number
|
|
556
|
-
): Promise<void> {
|
|
557
|
-
try {
|
|
558
|
-
const container = this.docker.getContainer(deploymentName);
|
|
559
|
-
const containerInfo = await container.inspect();
|
|
560
|
-
|
|
561
|
-
if (replicas === 0 && containerInfo.State.Running) {
|
|
562
|
-
await container.stop();
|
|
563
|
-
logger.info(`Stopped container ${deploymentName}`);
|
|
564
|
-
} else if (replicas === 1 && !containerInfo.State.Running) {
|
|
565
|
-
await container.start();
|
|
566
|
-
logger.info(`Started container ${deploymentName}`);
|
|
567
|
-
}
|
|
568
|
-
} catch (error) {
|
|
569
|
-
throw new OrchestratorError(
|
|
570
|
-
ErrorCode.DEPLOYMENT_SCALE_FAILED,
|
|
571
|
-
`Failed to scale Docker container ${deploymentName}: ${error instanceof Error ? error.message : String(error)}`,
|
|
572
|
-
{ deploymentName, replicas, error },
|
|
573
|
-
true
|
|
574
|
-
);
|
|
575
|
-
}
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
async deleteDeployment(deploymentName: string): Promise<void> {
|
|
579
|
-
try {
|
|
580
|
-
const container = this.docker.getContainer(deploymentName);
|
|
581
|
-
|
|
582
|
-
// Stop container if running
|
|
583
|
-
try {
|
|
584
|
-
await container.stop();
|
|
585
|
-
logger.info(`✅ Stopped container: ${deploymentName}`);
|
|
586
|
-
} catch (_error) {
|
|
587
|
-
// Container might already be stopped
|
|
588
|
-
logger.warn(`⚠️ Container ${deploymentName} was not running`);
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
// Remove container
|
|
592
|
-
await container.remove();
|
|
593
|
-
this.activityTimestamps.delete(deploymentName);
|
|
594
|
-
logger.info(`✅ Removed container: ${deploymentName}`);
|
|
595
|
-
} catch (error) {
|
|
596
|
-
const dockerError = error as { statusCode?: number };
|
|
597
|
-
if (dockerError.statusCode === 404) {
|
|
598
|
-
logger.warn(
|
|
599
|
-
`⚠️ Container ${deploymentName} not found (already deleted)`
|
|
600
|
-
);
|
|
601
|
-
} else {
|
|
602
|
-
throw error;
|
|
603
|
-
}
|
|
604
|
-
}
|
|
605
|
-
|
|
606
|
-
// NOTE: Space volumes are NOT deleted on deployment deletion
|
|
607
|
-
// They are shared across threads in the same space and persist
|
|
608
|
-
// for future conversations. Cleanup is done manually or via separate process.
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
async updateDeploymentActivity(deploymentName: string): Promise<void> {
|
|
612
|
-
// Docker doesn't support runtime label updates like K8s annotations
|
|
613
|
-
// Track activity in-memory for idle cleanup calculations
|
|
614
|
-
this.activityTimestamps.set(deploymentName, new Date());
|
|
615
|
-
}
|
|
616
|
-
|
|
617
|
-
protected getDispatcherHost(): string {
|
|
618
|
-
return this.getHostAddress();
|
|
619
|
-
}
|
|
620
|
-
}
|