@neuralnomads/codenomad 0.18.0 → 0.19.0
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/README.md +12 -0
- package/THIRD_PARTY_NOTICES.md +26 -0
- package/dist/auth/manager.js +1 -1
- package/dist/background-processes/manager.js +15 -30
- package/dist/background-processes/manager.test.js +123 -0
- package/dist/config/schema.js +2 -1
- package/dist/config/schema.test.js +13 -0
- package/dist/events/bus.js +17 -0
- package/dist/events/bus.test.js +37 -0
- package/dist/filesystem/__tests__/search-cache.test.js +20 -8
- package/dist/filesystem/__tests__/search.test.js +53 -0
- package/dist/filesystem/search-cache.js +6 -10
- package/dist/filesystem/search.js +22 -9
- package/dist/index.js +77 -58
- package/dist/index.test.js +62 -0
- package/dist/opencode-plugin/codenomad-opencode-plugin.tgz +0 -0
- package/dist/opencode-update/service.js +150 -0
- package/dist/opencode-update/service.test.js +107 -0
- package/dist/permissions/auto-accept-manager.js +380 -0
- package/dist/permissions/auto-accept-manager.test.js +736 -0
- package/dist/permissions/auto-accept-store.js +118 -0
- package/dist/permissions/auto-accept-store.test.js +157 -0
- package/dist/permissions/opencode-replier.js +31 -0
- package/dist/permissions/opencode-yolo-metadata.js +81 -0
- package/dist/permissions/opencode-yolo-metadata.test.js +54 -0
- package/dist/server/__tests__/listener-retry.test.js +15 -0
- package/dist/server/__tests__/remote-proxy.test.js +151 -47
- package/dist/server/http-server.js +22 -9
- package/dist/server/remote-proxy.js +91 -34
- package/dist/server/routes/auth-pages/login.html +3 -3
- package/dist/server/routes/auth.js +1 -1
- package/dist/server/routes/auth.test.js +21 -0
- package/dist/server/routes/opencode-update.js +37 -0
- package/dist/server/routes/opencode-update.test.js +34 -0
- package/dist/server/routes/remote-servers.js +1 -1
- package/dist/server/routes/settings.js +48 -2
- package/dist/server/routes/settings.test.js +58 -0
- package/dist/server/routes/usage.js +18 -0
- package/dist/server/routes/usage.test.js +26 -0
- package/dist/server/routes/workspaces.js +34 -2
- package/dist/server/routes/workspaces.test.js +113 -0
- package/dist/server/routes/worktrees.js +19 -0
- package/dist/server/routes/yolo.js +13 -0
- package/dist/server/tls.js +2 -2
- package/dist/settings/binaries.js +4 -1
- package/dist/settings/binaries.test.js +19 -0
- package/dist/settings/public-config.js +14 -0
- package/dist/settings/public-config.test.js +56 -0
- package/dist/settings/service.js +17 -5
- package/dist/settings/service.test.js +51 -0
- package/dist/settings/yaml-doc-store.js +55 -4
- package/dist/settings/yaml-doc-store.test.js +78 -0
- package/dist/shutdown.js +83 -0
- package/dist/shutdown.test.js +148 -0
- package/dist/sidecars/manager.js +26 -3
- package/dist/sidecars/manager.test.js +42 -0
- package/dist/speech/service.js +121 -10
- package/dist/speech/service.test.js +247 -0
- package/dist/ui/remote-ui.js +2 -2
- package/dist/usage/providers/api-key.js +171 -0
- package/dist/usage/providers/google.js +171 -0
- package/dist/usage/providers/minimax.js +109 -0
- package/dist/usage/providers/oauth.js +76 -0
- package/dist/usage/providers/special.js +148 -0
- package/dist/usage/service.js +83 -0
- package/dist/usage/service.test.js +61 -0
- package/dist/usage/shared.js +130 -0
- package/dist/usage/shared.test.js +33 -0
- package/dist/usage/types.js +1 -0
- package/dist/workspaces/__tests__/spawn.test.js +64 -7
- package/dist/workspaces/__tests__/workspace-identity.test.js +163 -0
- package/dist/workspaces/binary-path.test.js +10 -0
- package/dist/workspaces/instance-client.js +42 -0
- package/dist/workspaces/instance-client.test.js +149 -0
- package/dist/workspaces/instance-events.js +2 -2
- package/dist/workspaces/launch-cleanup.test.js +29 -0
- package/dist/workspaces/loopback.js +8 -0
- package/dist/workspaces/manager.js +473 -128
- package/dist/workspaces/manager.test.js +335 -0
- package/dist/workspaces/process-identity.darwin.test.js +88 -0
- package/dist/workspaces/process-identity.js +449 -0
- package/dist/workspaces/process-identity.test.js +140 -0
- package/dist/workspaces/runtime.js +471 -138
- package/dist/workspaces/runtime.test.js +286 -0
- package/dist/workspaces/spawn.js +86 -15
- package/dist/workspaces/workspace-identity.js +27 -0
- package/package.json +2 -1
- package/public/assets/FilesTab-Cbs7b7y9.js +2 -0
- package/public/assets/{GitChangesTab-DyRStL3G.js → GitChangesTab-D3H4cqJJ.js} +2 -2
- package/public/assets/{SplitFilePanel-C4FztlTR.js → SplitFilePanel-C_Bcle0r.js} +1 -1
- package/public/assets/StatusTab-D1-tfkgN.js +1 -0
- package/public/assets/{align-justify-GNs_d9nT.js → align-justify-B5HUL_LR.js} +1 -1
- package/public/assets/{bundle-full-B0vc8NGv.js → bundle-full-CEFzES5w.js} +1 -1
- package/public/assets/{diff-viewer-BmSzmlPC.js → diff-viewer-BBC2_yI1.js} +1 -1
- package/public/assets/{git-diff-vendor-CSgooKT_.js → git-diff-vendor-CYS3ApzA.js} +1 -1
- package/public/assets/{index-ChDVvMF4.js → index-B81f0aWL.js} +1 -1
- package/public/assets/index-BHlYVddm.js +1 -0
- package/public/assets/index-Best16ZB.js +2 -0
- package/public/assets/index-Boq37ErX.js +1 -0
- package/public/assets/index-By9pgzQk.css +1 -0
- package/public/assets/index-C0caoeJg.js +1 -0
- package/public/assets/index-Dqg2UVvS.js +1 -0
- package/public/assets/index-it6EGJV6.js +1 -0
- package/public/assets/{index-Bv867yIC.js → index-lORR8OnW.js} +1 -1
- package/public/assets/index-ppe6yWaU.js +1 -0
- package/public/assets/index-wEqeBwqT.js +1 -0
- package/public/assets/index-yEcajWX_.js +1 -0
- package/public/assets/{loading-DRzViX8M.js → loading-CbUWFqQ_.js} +1 -1
- package/public/assets/main-DfSREDgt.js +69 -0
- package/public/assets/{markdown-BlxzERp2.js → markdown-CEtfpKK-.js} +60 -47
- package/public/assets/monaco-viewer-NKl8kwH2.js +26 -0
- package/public/assets/terminal-square-q-by1uT7.js +1 -0
- package/public/assets/tool-call-CZL2uqIM.js +59 -0
- package/public/assets/unified-picker-CvJXD-j8.js +1 -0
- package/public/assets/{wrap-text-CMFBVbBi.js → wrap-text-Bo7xr74P.js} +1 -1
- package/public/index.html +5 -5
- package/public/loading.html +5 -5
- package/public/sw.js +1 -1
- package/public/ui-version.json +1 -1
- package/public/assets/FilesTab-CFF9uJuc.js +0 -2
- package/public/assets/StatusTab-CcoPFya8.js +0 -1
- package/public/assets/index--bYE3fA1.js +0 -1
- package/public/assets/index-B-9c-wPM.css +0 -1
- package/public/assets/index-BDJqHo1E.js +0 -1
- package/public/assets/index-BEXDNmDA.js +0 -1
- package/public/assets/index-BWX6Cyx3.js +0 -2
- package/public/assets/index-CUB1cngT.js +0 -1
- package/public/assets/index-CyGPk9Qx.js +0 -1
- package/public/assets/index-D9T8sYiH.js +0 -1
- package/public/assets/index-DQ8RfkwK.js +0 -1
- package/public/assets/index-udaOwtFG.js +0 -1
- package/public/assets/main-DUP17Bqi.js +0 -68
- package/public/assets/monaco-viewer-BbohfXZk.js +0 -26
- package/public/assets/tool-call-B0Ri40qI.js +0 -59
- package/public/assets/unified-picker-CGg8mlSo.js +0 -1
|
@@ -1,32 +1,106 @@
|
|
|
1
1
|
import path from "path";
|
|
2
2
|
import { spawnSync } from "child_process";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
3
4
|
import { connect } from "net";
|
|
5
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
4
6
|
import { FileSystemBrowser } from "../filesystem/browser";
|
|
5
7
|
import { searchWorkspaceFiles } from "../filesystem/search";
|
|
6
8
|
import { clearWorkspaceSearchCache } from "../filesystem/search-cache";
|
|
7
9
|
import { WorkspaceRuntime } from "./runtime";
|
|
8
10
|
import { buildOpencodeConfigContent, getCodeNomadPluginUrl, resolveExistingOpencodeConfigContent, } from "../opencode-plugin.js";
|
|
9
11
|
import { OPENCODE_SERVER_BASE_URL_ENV, buildOpencodeBasicAuthHeader, OPENCODE_SERVER_PASSWORD_ENV, OPENCODE_SERVER_USERNAME_ENV, resolveOpencodeServerAuth, } from "./opencode-auth";
|
|
12
|
+
import { resolveWorkspaceIdentity } from "./workspace-identity";
|
|
13
|
+
import { parseWslUncPath } from "./spawn";
|
|
14
|
+
import { LOOPBACK_HOST } from "./loopback";
|
|
10
15
|
const STARTUP_STABILITY_DELAY_MS = 1500;
|
|
16
|
+
const DEFAULT_LAUNCH_TIMEOUT_MS = 30_000;
|
|
17
|
+
const ORDINARY_CREATION_OWNER = "";
|
|
18
|
+
const WORKSPACE_STATE = Symbol("workspaceState");
|
|
19
|
+
export function binaryPathsEqual(left, right, platform = process.platform) {
|
|
20
|
+
const leftWsl = parseWslUncPath(left);
|
|
21
|
+
const rightWsl = parseWslUncPath(right);
|
|
22
|
+
if (leftWsl || rightWsl) {
|
|
23
|
+
return Boolean(leftWsl
|
|
24
|
+
&& rightWsl
|
|
25
|
+
&& leftWsl.distro.toLowerCase() === rightWsl.distro.toLowerCase()
|
|
26
|
+
&& leftWsl.linuxPath === rightWsl.linuxPath);
|
|
27
|
+
}
|
|
28
|
+
return platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right;
|
|
29
|
+
}
|
|
30
|
+
export class WorkspaceLaunchCancelledError extends Error {
|
|
31
|
+
constructor(workspaceId) {
|
|
32
|
+
super(`Workspace ${workspaceId} launch was cancelled`);
|
|
33
|
+
this.name = "WorkspaceLaunchCancelledError";
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export class WorkspaceLaunchTimeoutError extends Error {
|
|
37
|
+
constructor(workspaceId, timeoutMs) {
|
|
38
|
+
super(`${workspaceId ? `Workspace ${workspaceId}` : "Workspace"} did not finish launching within ${timeoutMs}ms`);
|
|
39
|
+
this.code = "WORKSPACE_LAUNCH_TIMEOUT";
|
|
40
|
+
this.retryable = true;
|
|
41
|
+
this.name = "WorkspaceLaunchTimeoutError";
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export class WorkspaceCleanupTimeoutError extends Error {
|
|
45
|
+
constructor(operation, timeoutMs) {
|
|
46
|
+
super(`Workspace ${operation} did not finish within ${timeoutMs}ms; cleanup can be retried`);
|
|
47
|
+
this.code = "WORKSPACE_CLEANUP_TIMEOUT";
|
|
48
|
+
this.retryable = true;
|
|
49
|
+
this.name = "WorkspaceCleanupTimeoutError";
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export class WorkspaceShutdownError extends AggregateError {
|
|
53
|
+
constructor(errors) {
|
|
54
|
+
super(errors, `Failed to stop ${errors.length} workspace${errors.length === 1 ? "" : "s"} during shutdown; cleanup can be retried`);
|
|
55
|
+
this.code = "WORKSPACE_SHUTDOWN_FAILED";
|
|
56
|
+
this.retryable = true;
|
|
57
|
+
this.name = "WorkspaceShutdownError";
|
|
58
|
+
}
|
|
59
|
+
}
|
|
11
60
|
export class WorkspaceManager {
|
|
12
61
|
constructor(options) {
|
|
13
62
|
this.options = options;
|
|
14
63
|
this.workspaces = new Map();
|
|
64
|
+
this.pendingWorkspaceCreations = new Map();
|
|
65
|
+
this.cancelledCreationRequests = new Set();
|
|
66
|
+
this.shuttingDown = false;
|
|
15
67
|
this.opencodeAuth = new Map();
|
|
16
|
-
this.runtime = new WorkspaceRuntime(this.options.eventBus, this.options.logger);
|
|
68
|
+
this.runtime = options.runtime ?? new WorkspaceRuntime(this.options.eventBus, this.options.logger);
|
|
17
69
|
this.codeNomadPluginUrl = getCodeNomadPluginUrl();
|
|
18
70
|
}
|
|
19
71
|
list() {
|
|
20
|
-
return Array.from(this.workspaces.values())
|
|
72
|
+
return Array.from(this.workspaces.values())
|
|
73
|
+
.filter((record) => record[WORKSPACE_STATE].published);
|
|
21
74
|
}
|
|
22
75
|
get(id) {
|
|
23
|
-
|
|
76
|
+
const record = this.workspaces.get(id);
|
|
77
|
+
return record?.[WORKSPACE_STATE].published ? record : undefined;
|
|
24
78
|
}
|
|
25
79
|
getInstancePort(id) {
|
|
26
|
-
|
|
80
|
+
const record = this.workspaces.get(id);
|
|
81
|
+
return record?.[WORKSPACE_STATE].published ? record.port : undefined;
|
|
27
82
|
}
|
|
28
83
|
getInstanceAuthorizationHeader(id) {
|
|
29
|
-
return this.opencodeAuth.get(id)?.authorization;
|
|
84
|
+
return this.workspaces.get(id)?.[WORKSPACE_STATE].published ? this.opencodeAuth.get(id)?.authorization : undefined;
|
|
85
|
+
}
|
|
86
|
+
findReadyInstanceIdByBinary(binaryPath) {
|
|
87
|
+
const resolvedPath = this.resolveBinaryPath(binaryPath);
|
|
88
|
+
return this.list().find((workspace) => {
|
|
89
|
+
return workspace.status === "ready" && binaryPathsEqual(workspace.binaryId, resolvedPath);
|
|
90
|
+
})?.id;
|
|
91
|
+
}
|
|
92
|
+
findReadyWorkspaceByIdentity(identityKey, includeRestoreOwned) {
|
|
93
|
+
for (const record of this.workspaces.values()) {
|
|
94
|
+
const state = record[WORKSPACE_STATE];
|
|
95
|
+
if (state.published
|
|
96
|
+
&& !state.abortController.signal.aborted
|
|
97
|
+
&& (includeRestoreOwned || !record.requestId)
|
|
98
|
+
&& record.status === "ready"
|
|
99
|
+
&& record.identityKey === identityKey) {
|
|
100
|
+
return record;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return undefined;
|
|
30
104
|
}
|
|
31
105
|
listFiles(workspaceId, relativePath = ".") {
|
|
32
106
|
const workspace = this.requireWorkspace(workspaceId);
|
|
@@ -71,16 +145,73 @@ export class WorkspaceManager {
|
|
|
71
145
|
const browser = new FileSystemBrowser({ rootDir: directory });
|
|
72
146
|
browser.writeFile(relativePath, contents);
|
|
73
147
|
}
|
|
74
|
-
async create(folder, name) {
|
|
75
|
-
const
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
|
|
148
|
+
async create(folder, name, options = {}) {
|
|
149
|
+
const launchTimeoutMs = Math.max(1, this.options.launchTimeoutMs ?? DEFAULT_LAUNCH_TIMEOUT_MS);
|
|
150
|
+
const launchDeadlineAt = Date.now() + launchTimeoutMs;
|
|
151
|
+
try {
|
|
152
|
+
const { workspacePath, identityKey } = await this.withLaunchDeadline(resolveWorkspaceIdentity(folder, this.options.rootDir), undefined, launchDeadlineAt, launchTimeoutMs);
|
|
153
|
+
if (options.requestId && this.cancelledCreationRequests.has(options.requestId)) {
|
|
154
|
+
throw new Error(`Workspace creation request ${options.requestId} was cancelled`);
|
|
155
|
+
}
|
|
156
|
+
if (this.shuttingDown) {
|
|
157
|
+
throw new Error("Workspace manager is shutting down");
|
|
158
|
+
}
|
|
159
|
+
if (options.forceNew) {
|
|
160
|
+
const ownership = this.createOwnership(options.requestId);
|
|
161
|
+
const record = this.reserveWorkspace(workspacePath, identityKey, name, options, ownership, launchDeadlineAt);
|
|
162
|
+
const result = await this.startCreation(record, options, launchDeadlineAt, launchTimeoutMs);
|
|
163
|
+
return this.finishCreation(result, options.requestId, ownership);
|
|
164
|
+
}
|
|
165
|
+
const existing = this.findReadyWorkspaceByIdentity(identityKey, Boolean(options.requestId));
|
|
166
|
+
if (existing) {
|
|
167
|
+
this.options.logger.info({ workspaceId: existing.id, folder: workspacePath }, "Reusing existing workspace");
|
|
168
|
+
const record = this.workspaces.get(existing.id);
|
|
169
|
+
if (options.requestId && record) {
|
|
170
|
+
if (!record.ownership.has(options.requestId))
|
|
171
|
+
record.ownership.set(options.requestId, "active");
|
|
172
|
+
this.syncOwnership(record);
|
|
173
|
+
return this.finishCreation({ workspace: existing, created: false }, options.requestId, record.ownership);
|
|
174
|
+
}
|
|
175
|
+
return { workspace: existing, created: false };
|
|
176
|
+
}
|
|
177
|
+
const pending = this.pendingWorkspaceCreations.get(identityKey);
|
|
178
|
+
if (pending) {
|
|
179
|
+
const state = pending[WORKSPACE_STATE];
|
|
180
|
+
const owner = options.requestId ?? ORDINARY_CREATION_OWNER;
|
|
181
|
+
if (!pending.ownership.has(owner))
|
|
182
|
+
pending.ownership.set(owner, "active");
|
|
183
|
+
this.syncOwnership(pending);
|
|
184
|
+
const result = await state.creation;
|
|
185
|
+
return this.finishCreation({ workspace: result.workspace, created: false }, options.requestId, pending.ownership);
|
|
186
|
+
}
|
|
187
|
+
const ownership = this.createOwnership(options.requestId);
|
|
188
|
+
const record = this.reserveWorkspace(workspacePath, identityKey, name, options, ownership, launchDeadlineAt);
|
|
189
|
+
const creation = this.startCreation(record, options, launchDeadlineAt, launchTimeoutMs);
|
|
190
|
+
this.pendingWorkspaceCreations.set(identityKey, record);
|
|
191
|
+
try {
|
|
192
|
+
return this.finishCreation(await creation, options.requestId, ownership);
|
|
193
|
+
}
|
|
194
|
+
finally {
|
|
195
|
+
if (this.pendingWorkspaceCreations.get(identityKey) === record) {
|
|
196
|
+
this.pendingWorkspaceCreations.delete(identityKey);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
finally {
|
|
201
|
+
if (options.requestId)
|
|
202
|
+
this.cancelledCreationRequests.delete(options.requestId);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
reserveWorkspace(workspacePath, identityKey, name, options, ownership, launchDeadlineAt) {
|
|
206
|
+
const id = randomUUID();
|
|
207
|
+
const binary = this.options.binaryResolver.resolve(options.binaryPath);
|
|
208
|
+
const resolvedBinaryPath = this.resolveBinaryPath(binary.path, Math.max(1, launchDeadlineAt - Date.now()));
|
|
79
209
|
clearWorkspaceSearchCache(workspacePath);
|
|
80
210
|
this.options.logger.info({ workspaceId: id, folder: workspacePath, binary: resolvedBinaryPath }, "Creating workspace");
|
|
81
211
|
const proxyPath = `/workspaces/${id}/instance`;
|
|
82
|
-
const
|
|
212
|
+
const record = {
|
|
83
213
|
id,
|
|
214
|
+
requestId: options.requestId,
|
|
84
215
|
path: workspacePath,
|
|
85
216
|
name,
|
|
86
217
|
status: "starting",
|
|
@@ -91,112 +222,314 @@ export class WorkspaceManager {
|
|
|
91
222
|
createdAt: new Date().toISOString(),
|
|
92
223
|
updatedAt: new Date().toISOString(),
|
|
93
224
|
};
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
const userEnvironment = envVars && typeof envVars === "object" && !Array.isArray(envVars) ? envVars : {};
|
|
99
|
-
const opencodeConfigContent = buildOpencodeConfigContent(resolveExistingOpencodeConfigContent(userEnvironment), this.codeNomadPluginUrl);
|
|
100
|
-
const serverBaseUrl = this.options.getServerBaseUrl();
|
|
101
|
-
const normalizedServerBaseUrl = serverBaseUrl.replace(/\/+$/, "");
|
|
102
|
-
const { username: opencodeUsername, password: opencodePassword } = resolveOpencodeServerAuth({
|
|
103
|
-
userEnvironment,
|
|
104
|
-
processEnv: process.env,
|
|
225
|
+
Object.defineProperties(record, {
|
|
226
|
+
identityKey: { value: identityKey },
|
|
227
|
+
ownership: { value: ownership },
|
|
228
|
+
[WORKSPACE_STATE]: { value: { abortController: new AbortController(), published: false, stoppedPublished: false } },
|
|
105
229
|
});
|
|
106
|
-
|
|
107
|
-
if (
|
|
108
|
-
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
230
|
+
this.workspaces.set(id, record);
|
|
231
|
+
if (options.requestId && this.cancelledCreationRequests.has(options.requestId)) {
|
|
232
|
+
record[WORKSPACE_STATE].abortController.abort(new WorkspaceLaunchCancelledError(id));
|
|
233
|
+
}
|
|
234
|
+
return record;
|
|
235
|
+
}
|
|
236
|
+
startCreation(record, options, launchDeadlineAt, launchTimeoutMs) {
|
|
237
|
+
const creation = this.createWithDeadline(record, options, launchDeadlineAt, launchTimeoutMs);
|
|
238
|
+
record[WORKSPACE_STATE].creation = creation;
|
|
239
|
+
record[WORKSPACE_STATE].settlement = creation.then(() => undefined, () => undefined);
|
|
240
|
+
return creation;
|
|
241
|
+
}
|
|
242
|
+
async createWithDeadline(record, options, launchDeadlineAt, launchTimeoutMs) {
|
|
243
|
+
const timeoutMs = Math.max(1, launchDeadlineAt - Date.now());
|
|
244
|
+
const state = record[WORKSPACE_STATE];
|
|
245
|
+
let timeout = (this.options.setTimeout ?? setTimeout)(() => {
|
|
246
|
+
timeout = null;
|
|
247
|
+
if (!state.abortController.signal.aborted) {
|
|
248
|
+
state.abortController.abort(new WorkspaceLaunchTimeoutError(record.id, launchTimeoutMs));
|
|
249
|
+
}
|
|
250
|
+
}, timeoutMs);
|
|
251
|
+
try {
|
|
252
|
+
return await this.createResolvedWorkspace(record, options);
|
|
253
|
+
}
|
|
254
|
+
finally {
|
|
255
|
+
if (timeout)
|
|
256
|
+
(this.options.clearTimeout ?? clearTimeout)(timeout);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
async withLaunchDeadline(operation, workspaceId, deadlineAt, launchTimeoutMs) {
|
|
260
|
+
const timeoutMs = Math.max(1, deadlineAt - Date.now());
|
|
261
|
+
let timeout = null;
|
|
262
|
+
const deadline = new Promise((_resolve, reject) => {
|
|
263
|
+
timeout = (this.options.setTimeout ?? setTimeout)(() => {
|
|
264
|
+
timeout = null;
|
|
265
|
+
reject(new WorkspaceLaunchTimeoutError(workspaceId, launchTimeoutMs));
|
|
266
|
+
}, timeoutMs);
|
|
267
|
+
});
|
|
268
|
+
try {
|
|
269
|
+
return await Promise.race([operation, deadline]);
|
|
270
|
+
}
|
|
271
|
+
finally {
|
|
272
|
+
if (timeout)
|
|
273
|
+
(this.options.clearTimeout ?? clearTimeout)(timeout);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
async createResolvedWorkspace(record, options) {
|
|
277
|
+
const state = record[WORKSPACE_STATE];
|
|
278
|
+
const { id, path: workspacePath, binaryId: resolvedBinaryPath, proxyPath } = record;
|
|
123
279
|
try {
|
|
280
|
+
this.throwIfCancelled(record);
|
|
281
|
+
const serverConfig = this.options.settings.getOwner("config", "server");
|
|
282
|
+
const envVars = serverConfig?.environmentVariables;
|
|
283
|
+
const userEnvironment = envVars && typeof envVars === "object" && !Array.isArray(envVars) ? envVars : {};
|
|
284
|
+
const opencodeConfigContent = buildOpencodeConfigContent(resolveExistingOpencodeConfigContent(userEnvironment), this.codeNomadPluginUrl);
|
|
285
|
+
const serverBaseUrl = this.options.getServerBaseUrl();
|
|
286
|
+
const normalizedServerBaseUrl = serverBaseUrl.replace(/\/+$/, "");
|
|
287
|
+
const { username: opencodeUsername, password: opencodePassword } = resolveOpencodeServerAuth({
|
|
288
|
+
userEnvironment,
|
|
289
|
+
processEnv: process.env,
|
|
290
|
+
});
|
|
291
|
+
const authorization = buildOpencodeBasicAuthHeader({ username: opencodeUsername, password: opencodePassword });
|
|
292
|
+
if (!authorization) {
|
|
293
|
+
throw new Error("Failed to build OpenCode auth header");
|
|
294
|
+
}
|
|
295
|
+
this.opencodeAuth.set(id, { username: opencodeUsername, password: opencodePassword, authorization });
|
|
296
|
+
const environment = {
|
|
297
|
+
...userEnvironment,
|
|
298
|
+
OPENCODE_CONFIG_CONTENT: opencodeConfigContent,
|
|
299
|
+
OPENCODE_EXPERIMENTAL_WORKSPACES: "true",
|
|
300
|
+
CODENOMAD_INSTANCE_ID: id,
|
|
301
|
+
CODENOMAD_BASE_URL: serverBaseUrl,
|
|
302
|
+
...(this.options.nodeExtraCaCertsPath ? { NODE_EXTRA_CA_CERTS: this.options.nodeExtraCaCertsPath } : {}),
|
|
303
|
+
[OPENCODE_SERVER_BASE_URL_ENV]: `${normalizedServerBaseUrl}${proxyPath}`,
|
|
304
|
+
[OPENCODE_SERVER_USERNAME_ENV]: opencodeUsername,
|
|
305
|
+
[OPENCODE_SERVER_PASSWORD_ENV]: opencodePassword,
|
|
306
|
+
};
|
|
307
|
+
const logLevel = serverConfig?.logLevel;
|
|
124
308
|
const { pid, port, exitPromise, getLastOutput } = await this.runtime.launch({
|
|
125
309
|
workspaceId: id,
|
|
126
310
|
folder: workspacePath,
|
|
127
311
|
binaryPath: resolvedBinaryPath,
|
|
128
312
|
environment,
|
|
129
313
|
logLevel,
|
|
314
|
+
signal: state.abortController.signal,
|
|
130
315
|
onExit: (info) => this.handleProcessExit(info.workspaceId, info),
|
|
131
316
|
});
|
|
132
|
-
|
|
317
|
+
record.pid = pid;
|
|
318
|
+
record.port = port;
|
|
319
|
+
this.throwIfCancelled(record);
|
|
320
|
+
state.published = true;
|
|
321
|
+
this.options.eventBus.publish({ type: "workspace.created", workspace: record });
|
|
322
|
+
this.throwIfCancelled(record);
|
|
323
|
+
const runtimeVersion = await this.waitForWorkspaceReadiness({
|
|
324
|
+
workspaceId: id,
|
|
325
|
+
port,
|
|
326
|
+
exitPromise,
|
|
327
|
+
getLastOutput,
|
|
328
|
+
signal: state.abortController.signal,
|
|
329
|
+
});
|
|
330
|
+
this.throwIfCancelled(record);
|
|
133
331
|
if (runtimeVersion) {
|
|
134
|
-
|
|
332
|
+
record.binaryVersion = runtimeVersion;
|
|
135
333
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
descriptor.updatedAt = new Date().toISOString();
|
|
140
|
-
this.options.eventBus.publish({ type: "workspace.started", workspace: descriptor });
|
|
334
|
+
record.status = "ready";
|
|
335
|
+
record.updatedAt = new Date().toISOString();
|
|
336
|
+
this.options.eventBus.publish({ type: "workspace.started", workspace: record });
|
|
141
337
|
this.options.logger.info({ workspaceId: id, port }, "Workspace ready");
|
|
142
|
-
return
|
|
338
|
+
return { workspace: record, created: true };
|
|
143
339
|
}
|
|
144
340
|
catch (error) {
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
this.options.logger.error({ workspaceId: id, err: error }, "Workspace failed to start");
|
|
150
|
-
throw error;
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
async delete(id) {
|
|
154
|
-
const workspace = this.workspaces.get(id);
|
|
155
|
-
if (!workspace)
|
|
156
|
-
return undefined;
|
|
157
|
-
this.options.logger.info({ workspaceId: id }, "Stopping workspace");
|
|
158
|
-
const wasRunning = Boolean(workspace.pid);
|
|
159
|
-
if (wasRunning) {
|
|
160
|
-
await this.runtime.stop(id).catch((error) => {
|
|
161
|
-
this.options.logger.warn({ workspaceId: id, err: error }, "Failed to stop workspace process cleanly");
|
|
341
|
+
const launchFailure = state.abortController.signal.aborted ? state.abortController.signal.reason : error;
|
|
342
|
+
let stopFailure;
|
|
343
|
+
await this.runtime.stop(id).catch((stopError) => {
|
|
344
|
+
stopFailure = stopError;
|
|
162
345
|
});
|
|
346
|
+
if (!stopFailure) {
|
|
347
|
+
this.removeRecord(id, record, state.published);
|
|
348
|
+
throw launchFailure;
|
|
349
|
+
}
|
|
350
|
+
if (!state.published) {
|
|
351
|
+
throw stopFailure;
|
|
352
|
+
}
|
|
353
|
+
record.status = "error";
|
|
354
|
+
record.error = stopFailure instanceof Error
|
|
355
|
+
? `Workspace startup failed and its process could not be stopped: ${stopFailure.message}`
|
|
356
|
+
: launchFailure instanceof Error ? launchFailure.message : String(launchFailure);
|
|
357
|
+
record.updatedAt = new Date().toISOString();
|
|
358
|
+
if (this.workspaces.get(id) === record && state.published) {
|
|
359
|
+
this.options.eventBus.publish({ type: "workspace.error", workspace: record });
|
|
360
|
+
}
|
|
361
|
+
this.options.logger.error({ workspaceId: id, err: launchFailure }, "Workspace failed to start");
|
|
362
|
+
throw launchFailure;
|
|
163
363
|
}
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
if (!
|
|
168
|
-
|
|
364
|
+
}
|
|
365
|
+
delete(id) {
|
|
366
|
+
const record = this.workspaces.get(id);
|
|
367
|
+
if (!record)
|
|
368
|
+
return Promise.resolve(undefined);
|
|
369
|
+
const state = record[WORKSPACE_STATE];
|
|
370
|
+
if (!state.abortController.signal.aborted) {
|
|
371
|
+
state.abortController.abort(new WorkspaceLaunchCancelledError(id));
|
|
169
372
|
}
|
|
170
|
-
|
|
373
|
+
const pending = this.pendingWorkspaceCreations.get(record.identityKey);
|
|
374
|
+
if (pending === record) {
|
|
375
|
+
this.pendingWorkspaceCreations.delete(record.identityKey);
|
|
376
|
+
}
|
|
377
|
+
if (!state.deletePromise) {
|
|
378
|
+
let deletePromise;
|
|
379
|
+
deletePromise = this.cleanupDeletedWorkspace(id, record).catch((error) => {
|
|
380
|
+
if (state.deletePromise === deletePromise)
|
|
381
|
+
state.deletePromise = undefined;
|
|
382
|
+
throw error;
|
|
383
|
+
});
|
|
384
|
+
state.deletePromise = deletePromise;
|
|
385
|
+
}
|
|
386
|
+
return state.deletePromise;
|
|
171
387
|
}
|
|
172
|
-
|
|
173
|
-
this.
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
388
|
+
releaseCreationRequest(id, requestId) {
|
|
389
|
+
const record = this.workspaces.get(id);
|
|
390
|
+
if (!record?.[WORKSPACE_STATE].published)
|
|
391
|
+
return false;
|
|
392
|
+
const ownership = record.ownership;
|
|
393
|
+
const state = ownership.get(requestId);
|
|
394
|
+
if (state === "released")
|
|
395
|
+
return true;
|
|
396
|
+
if (state === "cancelled")
|
|
397
|
+
return false;
|
|
398
|
+
if (state !== "active")
|
|
399
|
+
return false;
|
|
400
|
+
ownership.set(requestId, "released");
|
|
401
|
+
this.syncOwnership(record);
|
|
402
|
+
return true;
|
|
403
|
+
}
|
|
404
|
+
async cancelCreationRequest(requestId) {
|
|
405
|
+
let matched = false;
|
|
406
|
+
for (const [workspaceId, record] of this.workspaces) {
|
|
407
|
+
const ownership = record.ownership;
|
|
408
|
+
const state = ownership.get(requestId);
|
|
409
|
+
if (state === "released") {
|
|
410
|
+
matched = true;
|
|
178
411
|
continue;
|
|
179
412
|
}
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
this.
|
|
183
|
-
|
|
413
|
+
if (state === "cancelled") {
|
|
414
|
+
matched = true;
|
|
415
|
+
if (this.hasActiveRequest(ownership) || this.isRetained(ownership))
|
|
416
|
+
continue;
|
|
417
|
+
await this.delete(workspaceId);
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
if (state !== "active")
|
|
421
|
+
continue;
|
|
422
|
+
matched = true;
|
|
423
|
+
ownership.set(requestId, "cancelled");
|
|
424
|
+
this.syncOwnership(record);
|
|
425
|
+
if (this.hasActiveRequest(ownership) || this.isRetained(ownership))
|
|
426
|
+
return;
|
|
427
|
+
await this.delete(workspaceId);
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
if (!matched)
|
|
431
|
+
this.cancelledCreationRequests.add(requestId);
|
|
432
|
+
}
|
|
433
|
+
createOwnership(requestId) {
|
|
434
|
+
return new Map([[requestId ?? ORDINARY_CREATION_OWNER, "active"]]);
|
|
435
|
+
}
|
|
436
|
+
finishCreation(result, requestId, ownership) {
|
|
437
|
+
if (requestId && ownership.get(requestId) === "cancelled") {
|
|
438
|
+
throw new Error(`Workspace creation request ${requestId} was cancelled`);
|
|
439
|
+
}
|
|
440
|
+
const retained = this.isRetained(ownership);
|
|
441
|
+
return {
|
|
442
|
+
workspace: requestId ? { ...result.workspace, requestId } : result.workspace,
|
|
443
|
+
created: result.created && !(requestId && retained),
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
syncOwnership(record) {
|
|
447
|
+
if (!record)
|
|
448
|
+
return;
|
|
449
|
+
const ownership = record.ownership;
|
|
450
|
+
record.requestId = this.isRetained(ownership)
|
|
451
|
+
? undefined
|
|
452
|
+
: Array.from(ownership).find(([, state]) => state === "active")?.[0];
|
|
453
|
+
}
|
|
454
|
+
isRetained(ownership) {
|
|
455
|
+
return ownership.has(ORDINARY_CREATION_OWNER) || Array.from(ownership.values()).includes("released");
|
|
456
|
+
}
|
|
457
|
+
hasActiveRequest(ownership) {
|
|
458
|
+
return Array.from(ownership).some(([requestId, state]) => Boolean(requestId) && state === "active");
|
|
459
|
+
}
|
|
460
|
+
async shutdown() {
|
|
461
|
+
this.shuttingDown = true;
|
|
462
|
+
this.options.logger.info("Shutting down all workspaces");
|
|
463
|
+
const stopTasks = Array.from(this.workspaces.keys(), (id) => this.delete(id));
|
|
464
|
+
const results = stopTasks.length
|
|
465
|
+
? await this.withTimeout(Promise.allSettled(stopTasks), this.options.shutdownTimeoutMs ?? 10000, "shutdown")
|
|
466
|
+
: [];
|
|
467
|
+
const stopFailures = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
|
|
468
|
+
if (this.workspaces.size === 0) {
|
|
469
|
+
this.pendingWorkspaceCreations.clear();
|
|
470
|
+
this.cancelledCreationRequests.clear();
|
|
471
|
+
}
|
|
472
|
+
else if (!stopFailures.length)
|
|
473
|
+
stopFailures.push(new Error(`Workspace cleanup remains incomplete for: ${Array.from(this.workspaces.keys()).join(", ")}`));
|
|
474
|
+
if (stopFailures.length)
|
|
475
|
+
throw new WorkspaceShutdownError(stopFailures);
|
|
476
|
+
}
|
|
477
|
+
async withTimeout(operation, timeoutMs, label) {
|
|
478
|
+
let timeout = null;
|
|
479
|
+
const deadline = new Promise((_resolve, reject) => {
|
|
480
|
+
timeout = (this.options.setTimeout ?? setTimeout)(() => {
|
|
481
|
+
timeout = null;
|
|
482
|
+
reject(new WorkspaceCleanupTimeoutError(label, timeoutMs));
|
|
483
|
+
}, timeoutMs);
|
|
484
|
+
});
|
|
485
|
+
try {
|
|
486
|
+
return await Promise.race([operation, deadline]);
|
|
184
487
|
}
|
|
185
|
-
|
|
186
|
-
|
|
488
|
+
finally {
|
|
489
|
+
if (timeout)
|
|
490
|
+
(this.options.clearTimeout ?? clearTimeout)(timeout);
|
|
187
491
|
}
|
|
188
|
-
this.workspaces.clear();
|
|
189
|
-
this.opencodeAuth.clear();
|
|
190
|
-
this.options.logger.info("All workspaces cleared");
|
|
191
492
|
}
|
|
192
493
|
requireWorkspace(id) {
|
|
193
|
-
const
|
|
194
|
-
if (!
|
|
494
|
+
const record = this.workspaces.get(id);
|
|
495
|
+
if (!record?.[WORKSPACE_STATE].published)
|
|
195
496
|
throw new Error("Workspace not found");
|
|
196
|
-
|
|
197
|
-
|
|
497
|
+
return record;
|
|
498
|
+
}
|
|
499
|
+
throwIfCancelled(record) {
|
|
500
|
+
record[WORKSPACE_STATE].abortController.signal.throwIfAborted();
|
|
501
|
+
}
|
|
502
|
+
async cleanupDeletedWorkspace(id, record) {
|
|
503
|
+
// Stop once immediately, then again after launch settlement to cover a child
|
|
504
|
+
// that became available while cancellation was propagating.
|
|
505
|
+
const immediateStop = this.runtime.stop(id).catch((error) => {
|
|
506
|
+
this.options.logger.warn({ workspaceId: id, err: error }, "Initial workspace process cleanup failed; retrying after launch settles");
|
|
507
|
+
});
|
|
508
|
+
await this.withTimeout(record[WORKSPACE_STATE].settlement, this.options.launchSettlementTimeoutMs ?? 5000, `${id} launch cancellation`);
|
|
509
|
+
await immediateStop;
|
|
510
|
+
await this.runtime.stop(id);
|
|
511
|
+
this.removeRecord(id, record, true);
|
|
512
|
+
return record;
|
|
198
513
|
}
|
|
199
|
-
|
|
514
|
+
removeRecord(id, record, publishStopped) {
|
|
515
|
+
if (this.workspaces.get(id) !== record)
|
|
516
|
+
return;
|
|
517
|
+
this.workspaces.delete(id);
|
|
518
|
+
this.opencodeAuth.delete(id);
|
|
519
|
+
clearWorkspaceSearchCache(record.path);
|
|
520
|
+
if (publishStopped)
|
|
521
|
+
this.publishStopped(record, "deleted");
|
|
522
|
+
}
|
|
523
|
+
publishStopped(record, reason = "stopped") {
|
|
524
|
+
const state = record[WORKSPACE_STATE];
|
|
525
|
+
if (!state.published || state.stoppedPublished)
|
|
526
|
+
return;
|
|
527
|
+
state.stoppedPublished = true;
|
|
528
|
+
record.status = "stopped";
|
|
529
|
+
record.error = undefined;
|
|
530
|
+
this.options.eventBus.publish({ type: "workspace.stopped", workspaceId: record.id, reason });
|
|
531
|
+
}
|
|
532
|
+
resolveBinaryPath(identifier, timeoutMs = DEFAULT_LAUNCH_TIMEOUT_MS) {
|
|
200
533
|
if (!identifier) {
|
|
201
534
|
return identifier;
|
|
202
535
|
}
|
|
@@ -206,7 +539,7 @@ export class WorkspaceManager {
|
|
|
206
539
|
}
|
|
207
540
|
const locator = process.platform === "win32" ? "where" : "which";
|
|
208
541
|
try {
|
|
209
|
-
const result = spawnSync(locator, [identifier], { encoding: "utf8" });
|
|
542
|
+
const result = spawnSync(locator, [identifier], { encoding: "utf8", timeout: Math.max(1, timeoutMs) });
|
|
210
543
|
if (result.status === 0 && result.stdout) {
|
|
211
544
|
const candidates = result.stdout
|
|
212
545
|
.split(/\r?\n/)
|
|
@@ -243,26 +576,24 @@ export class WorkspaceManager {
|
|
|
243
576
|
}
|
|
244
577
|
async waitForWorkspaceReadiness(params) {
|
|
245
578
|
await Promise.race([
|
|
246
|
-
this.waitForPortAvailability(params.port),
|
|
247
|
-
|
|
248
|
-
throw this.buildStartupError(params.workspaceId, "exited before becoming ready", info, params.getLastOutput());
|
|
249
|
-
}),
|
|
579
|
+
this.waitForPortAvailability(params.port, 5000, params.signal),
|
|
580
|
+
this.exitDuringStartup(params, "exited before becoming ready"),
|
|
250
581
|
]);
|
|
251
582
|
const version = await this.waitForInstanceHealth(params);
|
|
252
583
|
await Promise.race([
|
|
253
|
-
this.
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
584
|
+
this.validateInstanceConfiguration(params),
|
|
585
|
+
this.exitDuringStartup(params, "exited during configuration validation"),
|
|
586
|
+
]);
|
|
587
|
+
await Promise.race([
|
|
588
|
+
delay(STARTUP_STABILITY_DELAY_MS, undefined, { signal: params.signal }),
|
|
589
|
+
this.exitDuringStartup(params, "exited shortly after start"),
|
|
257
590
|
]);
|
|
258
591
|
return version;
|
|
259
592
|
}
|
|
260
593
|
async waitForInstanceHealth(params) {
|
|
261
594
|
const probeResult = await Promise.race([
|
|
262
|
-
this.probeInstance(params.workspaceId, params.port),
|
|
263
|
-
|
|
264
|
-
throw this.buildStartupError(params.workspaceId, "exited during health checks", info, params.getLastOutput());
|
|
265
|
-
}),
|
|
595
|
+
this.probeInstance(params.workspaceId, params.port, params.signal),
|
|
596
|
+
this.exitDuringStartup(params, "exited during health checks"),
|
|
266
597
|
]);
|
|
267
598
|
if (probeResult.ok) {
|
|
268
599
|
return probeResult.version;
|
|
@@ -274,15 +605,15 @@ export class WorkspaceManager {
|
|
|
274
605
|
const reason = probeResult.reason ?? "Health check failed";
|
|
275
606
|
throw new Error(`Workspace ${params.workspaceId} failed health check: ${reason}.`);
|
|
276
607
|
}
|
|
277
|
-
|
|
278
|
-
|
|
608
|
+
exitDuringStartup(params, phase) {
|
|
609
|
+
return params.exitPromise.then((info) => {
|
|
610
|
+
throw this.buildStartupError(params.workspaceId, phase, info, params.getLastOutput());
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
async probeInstance(workspaceId, port, signal) {
|
|
614
|
+
const url = `http://${LOOPBACK_HOST}:${port}/global/health`;
|
|
279
615
|
try {
|
|
280
|
-
const
|
|
281
|
-
const authHeader = this.opencodeAuth.get(workspaceId)?.authorization;
|
|
282
|
-
if (authHeader) {
|
|
283
|
-
headers["Authorization"] = authHeader;
|
|
284
|
-
}
|
|
285
|
-
const response = await fetch(url, { headers });
|
|
616
|
+
const response = await fetch(url, { headers: this.getInstanceRequestHeaders(workspaceId), signal });
|
|
286
617
|
if (!response.ok) {
|
|
287
618
|
const reason = `/global/health returned HTTP ${response.status}`;
|
|
288
619
|
this.options.logger.debug({ workspaceId, status: response.status }, "Health probe returned server error");
|
|
@@ -304,13 +635,29 @@ export class WorkspaceManager {
|
|
|
304
635
|
return { ok: false, reason };
|
|
305
636
|
}
|
|
306
637
|
}
|
|
638
|
+
async validateInstanceConfiguration(params) {
|
|
639
|
+
const response = await fetch(`http://${LOOPBACK_HOST}:${params.port}/config`, {
|
|
640
|
+
headers: this.getInstanceRequestHeaders(params.workspaceId),
|
|
641
|
+
signal: params.signal,
|
|
642
|
+
});
|
|
643
|
+
if (response.ok) {
|
|
644
|
+
await response.body?.cancel();
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
const body = (await response.text()).trim();
|
|
648
|
+
throw new Error(body || `OpenCode /config returned HTTP ${response.status}`);
|
|
649
|
+
}
|
|
650
|
+
getInstanceRequestHeaders(workspaceId) {
|
|
651
|
+
const authorization = this.opencodeAuth.get(workspaceId)?.authorization;
|
|
652
|
+
return authorization ? { Authorization: authorization } : {};
|
|
653
|
+
}
|
|
307
654
|
buildStartupError(workspaceId, phase, exitInfo, lastOutput) {
|
|
308
655
|
const exitDetails = this.describeExit(exitInfo);
|
|
309
656
|
const trimmedOutput = lastOutput.trim();
|
|
310
657
|
const outputDetails = trimmedOutput ? ` Last output: ${trimmedOutput}` : "";
|
|
311
658
|
return new Error(`Workspace ${workspaceId} ${phase} (${exitDetails}).${outputDetails}`);
|
|
312
659
|
}
|
|
313
|
-
waitForPortAvailability(port, timeoutMs = 5000) {
|
|
660
|
+
waitForPortAvailability(port, timeoutMs = 5000, signal) {
|
|
314
661
|
return new Promise((resolve, reject) => {
|
|
315
662
|
const deadline = Date.now() + timeoutMs;
|
|
316
663
|
let settled = false;
|
|
@@ -323,17 +670,20 @@ export class WorkspaceManager {
|
|
|
323
670
|
}
|
|
324
671
|
};
|
|
325
672
|
const tryConnect = () => {
|
|
326
|
-
if (settled)
|
|
673
|
+
if (settled)
|
|
327
674
|
return;
|
|
328
|
-
}
|
|
329
|
-
const socket = connect({ port, host: "127.0.0.1" }, () => {
|
|
675
|
+
const socket = connect({ port, host: LOOPBACK_HOST, signal }, () => {
|
|
330
676
|
cleanup();
|
|
331
677
|
socket.end();
|
|
332
678
|
resolve();
|
|
333
679
|
});
|
|
334
680
|
socket.once("error", () => {
|
|
335
681
|
socket.destroy();
|
|
336
|
-
if (settled)
|
|
682
|
+
if (settled)
|
|
683
|
+
return;
|
|
684
|
+
if (signal?.aborted) {
|
|
685
|
+
cleanup();
|
|
686
|
+
reject(signal.reason);
|
|
337
687
|
return;
|
|
338
688
|
}
|
|
339
689
|
if (Date.now() >= deadline) {
|
|
@@ -348,15 +698,11 @@ export class WorkspaceManager {
|
|
|
348
698
|
}
|
|
349
699
|
});
|
|
350
700
|
};
|
|
701
|
+
if (signal?.aborted)
|
|
702
|
+
return reject(signal.reason);
|
|
351
703
|
tryConnect();
|
|
352
704
|
});
|
|
353
705
|
}
|
|
354
|
-
delay(durationMs) {
|
|
355
|
-
if (durationMs <= 0) {
|
|
356
|
-
return Promise.resolve();
|
|
357
|
-
}
|
|
358
|
-
return new Promise((resolve) => setTimeout(resolve, durationMs));
|
|
359
|
-
}
|
|
360
706
|
describeExit(info) {
|
|
361
707
|
if (info.signal) {
|
|
362
708
|
return `signal ${info.signal}`;
|
|
@@ -367,18 +713,17 @@ export class WorkspaceManager {
|
|
|
367
713
|
return "unknown reason";
|
|
368
714
|
}
|
|
369
715
|
handleProcessExit(workspaceId, info) {
|
|
370
|
-
const
|
|
371
|
-
if (!
|
|
716
|
+
const record = this.workspaces.get(workspaceId);
|
|
717
|
+
if (!record)
|
|
372
718
|
return;
|
|
719
|
+
const workspace = record;
|
|
373
720
|
this.opencodeAuth.delete(workspaceId);
|
|
374
721
|
this.options.logger.info({ workspaceId, ...info }, "Workspace process exited");
|
|
375
722
|
workspace.pid = undefined;
|
|
376
723
|
workspace.port = undefined;
|
|
377
724
|
workspace.updatedAt = new Date().toISOString();
|
|
378
|
-
if (info.requested || info.code === 0) {
|
|
379
|
-
|
|
380
|
-
workspace.error = undefined;
|
|
381
|
-
this.options.eventBus.publish({ type: "workspace.stopped", workspaceId });
|
|
725
|
+
if (record[WORKSPACE_STATE].abortController.signal.aborted || info.requested || info.code === 0) {
|
|
726
|
+
this.publishStopped(record);
|
|
382
727
|
}
|
|
383
728
|
else {
|
|
384
729
|
workspace.status = "error";
|