@neuralnomads/codenomad-dev 0.18.0-dev-20260715-07e8ce68 → 0.18.0-dev-20260718-8f6aa44b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +12 -0
  2. package/THIRD_PARTY_NOTICES.md +26 -0
  3. package/dist/auth/manager.js +1 -1
  4. package/dist/events/bus.js +13 -0
  5. package/dist/events/bus.test.js +37 -0
  6. package/dist/filesystem/__tests__/search-cache.test.js +5 -5
  7. package/dist/filesystem/search-cache.js +1 -1
  8. package/dist/index.js +58 -56
  9. package/dist/index.test.js +62 -0
  10. package/dist/opencode-update/service.js +150 -0
  11. package/dist/opencode-update/service.test.js +107 -0
  12. package/dist/server/__tests__/remote-proxy.test.js +151 -47
  13. package/dist/server/http-server.js +9 -1
  14. package/dist/server/remote-proxy.js +91 -34
  15. package/dist/server/routes/opencode-update.js +37 -0
  16. package/dist/server/routes/opencode-update.test.js +34 -0
  17. package/dist/server/routes/remote-servers.js +1 -1
  18. package/dist/server/routes/usage.js +18 -0
  19. package/dist/server/routes/usage.test.js +26 -0
  20. package/dist/server/routes/workspaces.js +32 -1
  21. package/dist/server/routes/workspaces.test.js +113 -0
  22. package/dist/server/tls.js +2 -2
  23. package/dist/settings/binaries.js +4 -1
  24. package/dist/settings/binaries.test.js +19 -0
  25. package/dist/shutdown.js +83 -0
  26. package/dist/shutdown.test.js +148 -0
  27. package/dist/ui/remote-ui.js +2 -2
  28. package/dist/usage/providers/api-key.js +171 -0
  29. package/dist/usage/providers/google.js +171 -0
  30. package/dist/usage/providers/minimax.js +109 -0
  31. package/dist/usage/providers/oauth.js +111 -0
  32. package/dist/usage/providers/special.js +148 -0
  33. package/dist/usage/service.js +83 -0
  34. package/dist/usage/service.test.js +59 -0
  35. package/dist/usage/shared.js +130 -0
  36. package/dist/usage/shared.test.js +33 -0
  37. package/dist/usage/types.js +1 -0
  38. package/dist/workspaces/__tests__/spawn.test.js +64 -7
  39. package/dist/workspaces/__tests__/workspace-identity.test.js +99 -139
  40. package/dist/workspaces/binary-path.test.js +10 -0
  41. package/dist/workspaces/instance-client.js +4 -3
  42. package/dist/workspaces/launch-cleanup.test.js +29 -0
  43. package/dist/workspaces/manager.js +399 -192
  44. package/dist/workspaces/manager.test.js +290 -0
  45. package/dist/workspaces/process-identity.darwin.test.js +88 -0
  46. package/dist/workspaces/process-identity.js +431 -0
  47. package/dist/workspaces/process-identity.test.js +111 -0
  48. package/dist/workspaces/runtime.js +471 -138
  49. package/dist/workspaces/runtime.test.js +278 -0
  50. package/dist/workspaces/spawn.js +86 -15
  51. package/package.json +1 -1
  52. package/public/assets/{FilesTab-EPvldvn1.js → FilesTab-B0-DlSCT.js} +2 -2
  53. package/public/assets/{GitChangesTab-ofjovmv2.js → GitChangesTab-CxjbNBVr.js} +2 -2
  54. package/public/assets/{SplitFilePanel-CyoPkcLd.js → SplitFilePanel-CLQb-6uX.js} +1 -1
  55. package/public/assets/StatusTab-CBGAuhmp.js +1 -0
  56. package/public/assets/{align-justify-Bcf1-ZOl.js → align-justify-s5mnjsP0.js} +1 -1
  57. package/public/assets/{bundle-full-D5dzvToA.js → bundle-full-lwIMY5om.js} +1 -1
  58. package/public/assets/{diff-viewer-DViXCI-4.js → diff-viewer-CDtmFe6e.js} +1 -1
  59. package/public/assets/{git-diff-vendor-CSgooKT_.js → git-diff-vendor-CYS3ApzA.js} +1 -1
  60. package/public/assets/index-6ABz_Izb.js +1 -0
  61. package/public/assets/index-BPdjM9ZI.css +1 -0
  62. package/public/assets/index-BQK8um1r.js +1 -0
  63. package/public/assets/index-BkUAI4ZY.js +1 -0
  64. package/public/assets/index-D8bkUvEd.js +2 -0
  65. package/public/assets/index-DY_sbCt9.js +1 -0
  66. package/public/assets/index-DhmUOdAI.js +1 -0
  67. package/public/assets/{index-UbL8tz_V.js → index-DupnEKCQ.js} +1 -1
  68. package/public/assets/index-HhZzWWha.js +1 -0
  69. package/public/assets/{index-lf4nUOU1.js → index-lBAEWdAF.js} +1 -1
  70. package/public/assets/index-nVII4VJz.js +1 -0
  71. package/public/assets/index-p1Sble5V.js +1 -0
  72. package/public/assets/{loading-CZ_tt3h0.js → loading-h8DvUqqc.js} +1 -1
  73. package/public/assets/main-BxUSjoWA.js +68 -0
  74. package/public/assets/{markdown-G11aN6hz.js → markdown-Djug_spc.js} +55 -44
  75. package/public/assets/monaco-viewer-lkUcsK65.js +26 -0
  76. package/public/assets/{tool-call-BsSXWErm.js → tool-call-C4YH896w.js} +32 -32
  77. package/public/assets/{unified-picker-BRNI3UvE.js → unified-picker-DwNZOVlY.js} +1 -1
  78. package/public/assets/{wrap-text-B7up-uv7.js → wrap-text-BLVYxvcj.js} +1 -1
  79. package/public/index.html +5 -5
  80. package/public/loading.html +5 -5
  81. package/public/sw.js +1 -1
  82. package/public/assets/StatusTab-Bgu1Fh24.js +0 -1
  83. package/public/assets/index-3KsjbWGP.js +0 -1
  84. package/public/assets/index-B0WK8-cF.js +0 -1
  85. package/public/assets/index-BDv_iVtj.js +0 -1
  86. package/public/assets/index-BMvFMsuy.css +0 -1
  87. package/public/assets/index-BjxZvyb9.js +0 -2
  88. package/public/assets/index-BleKf9Nj.js +0 -1
  89. package/public/assets/index-CiIQ43NW.js +0 -1
  90. package/public/assets/index-DBquqL6Q.js +0 -1
  91. package/public/assets/index-yf9zolv4.js +0 -1
  92. package/public/assets/index-ypaL7i_s.js +0 -1
  93. package/public/assets/main-CAkg_fp_.js +0 -68
  94. package/public/assets/monaco-viewer-CZefBfct.js +0 -26
@@ -2,6 +2,7 @@ import path from "path";
2
2
  import { spawnSync } from "child_process";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { connect } from "net";
5
+ import { setTimeout as delay } from "node:timers/promises";
5
6
  import { FileSystemBrowser } from "../filesystem/browser";
6
7
  import { searchWorkspaceFiles } from "../filesystem/search";
7
8
  import { clearWorkspaceSearchCache } from "../filesystem/search-cache";
@@ -9,37 +10,96 @@ import { WorkspaceRuntime } from "./runtime";
9
10
  import { buildOpencodeConfigContent, getCodeNomadPluginUrl, resolveExistingOpencodeConfigContent, } from "../opencode-plugin.js";
10
11
  import { OPENCODE_SERVER_BASE_URL_ENV, buildOpencodeBasicAuthHeader, OPENCODE_SERVER_PASSWORD_ENV, OPENCODE_SERVER_USERNAME_ENV, resolveOpencodeServerAuth, } from "./opencode-auth";
11
12
  import { resolveWorkspaceIdentity } from "./workspace-identity";
13
+ import { parseWslUncPath } from "./spawn";
12
14
  const STARTUP_STABILITY_DELAY_MS = 1500;
15
+ const DEFAULT_LAUNCH_TIMEOUT_MS = 30_000;
16
+ const ORDINARY_CREATION_OWNER = "";
17
+ const WORKSPACE_STATE = Symbol("workspaceState");
18
+ export function binaryPathsEqual(left, right, platform = process.platform) {
19
+ const leftWsl = parseWslUncPath(left);
20
+ const rightWsl = parseWslUncPath(right);
21
+ if (leftWsl || rightWsl) {
22
+ return Boolean(leftWsl
23
+ && rightWsl
24
+ && leftWsl.distro.toLowerCase() === rightWsl.distro.toLowerCase()
25
+ && leftWsl.linuxPath === rightWsl.linuxPath);
26
+ }
27
+ return platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right;
28
+ }
29
+ export class WorkspaceLaunchCancelledError extends Error {
30
+ constructor(workspaceId) {
31
+ super(`Workspace ${workspaceId} launch was cancelled`);
32
+ this.name = "WorkspaceLaunchCancelledError";
33
+ }
34
+ }
35
+ export class WorkspaceLaunchTimeoutError extends Error {
36
+ constructor(workspaceId, timeoutMs) {
37
+ super(`${workspaceId ? `Workspace ${workspaceId}` : "Workspace"} did not finish launching within ${timeoutMs}ms`);
38
+ this.code = "WORKSPACE_LAUNCH_TIMEOUT";
39
+ this.retryable = true;
40
+ this.name = "WorkspaceLaunchTimeoutError";
41
+ }
42
+ }
43
+ export class WorkspaceCleanupTimeoutError extends Error {
44
+ constructor(operation, timeoutMs) {
45
+ super(`Workspace ${operation} did not finish within ${timeoutMs}ms; cleanup can be retried`);
46
+ this.code = "WORKSPACE_CLEANUP_TIMEOUT";
47
+ this.retryable = true;
48
+ this.name = "WorkspaceCleanupTimeoutError";
49
+ }
50
+ }
51
+ export class WorkspaceShutdownError extends AggregateError {
52
+ constructor(errors) {
53
+ super(errors, `Failed to stop ${errors.length} workspace${errors.length === 1 ? "" : "s"} during shutdown; cleanup can be retried`);
54
+ this.code = "WORKSPACE_SHUTDOWN_FAILED";
55
+ this.retryable = true;
56
+ this.name = "WorkspaceShutdownError";
57
+ }
58
+ }
13
59
  export class WorkspaceManager {
14
60
  constructor(options) {
15
61
  this.options = options;
16
62
  this.workspaces = new Map();
17
- this.workspaceIdentities = new Map();
18
63
  this.pendingWorkspaceCreations = new Map();
19
- this.pendingWorkspaceOwners = new Map();
20
- this.activeWorkspaceCreations = new Set();
21
- this.cancelledWorkspaceCreations = new Set();
64
+ this.cancelledCreationRequests = new Set();
22
65
  this.shuttingDown = false;
23
66
  this.opencodeAuth = new Map();
24
- this.runtime = new WorkspaceRuntime(this.options.eventBus, this.options.logger);
67
+ this.runtime = options.runtime ?? new WorkspaceRuntime(this.options.eventBus, this.options.logger);
25
68
  this.codeNomadPluginUrl = getCodeNomadPluginUrl();
26
69
  }
27
70
  list() {
28
- return Array.from(this.workspaces.values());
71
+ return Array.from(this.workspaces.values())
72
+ .filter((record) => record[WORKSPACE_STATE].published);
29
73
  }
30
74
  get(id) {
31
- return this.workspaces.get(id);
75
+ const record = this.workspaces.get(id);
76
+ return record?.[WORKSPACE_STATE].published ? record : undefined;
32
77
  }
33
78
  getInstancePort(id) {
34
- return this.workspaces.get(id)?.port;
79
+ const record = this.workspaces.get(id);
80
+ return record?.[WORKSPACE_STATE].published ? record.port : undefined;
35
81
  }
36
82
  getInstanceAuthorizationHeader(id) {
37
- return this.opencodeAuth.get(id)?.authorization;
83
+ return this.workspaces.get(id)?.[WORKSPACE_STATE].published ? this.opencodeAuth.get(id)?.authorization : undefined;
38
84
  }
39
- findReadyWorkspaceByIdentity(identityKey) {
40
- return Array.from(this.workspaces.values()).find((workspace) => {
41
- return workspace.status === "ready" && this.workspaceIdentities.get(workspace.id) === identityKey;
42
- });
85
+ findReadyInstanceIdByBinary(binaryPath) {
86
+ const resolvedPath = this.resolveBinaryPath(binaryPath);
87
+ return this.list().find((workspace) => {
88
+ return workspace.status === "ready" && binaryPathsEqual(workspace.binaryId, resolvedPath);
89
+ })?.id;
90
+ }
91
+ findReadyWorkspaceByIdentity(identityKey, includeRestoreOwned) {
92
+ for (const record of this.workspaces.values()) {
93
+ const state = record[WORKSPACE_STATE];
94
+ if (state.published
95
+ && !state.abortController.signal.aborted
96
+ && (includeRestoreOwned || !record.requestId)
97
+ && record.status === "ready"
98
+ && record.identityKey === identityKey) {
99
+ return record;
100
+ }
101
+ }
102
+ return undefined;
43
103
  }
44
104
  listFiles(workspaceId, relativePath = ".") {
45
105
  const workspace = this.requireWorkspace(workspaceId);
@@ -84,60 +144,73 @@ export class WorkspaceManager {
84
144
  const browser = new FileSystemBrowser({ rootDir: directory });
85
145
  browser.writeFile(relativePath, contents);
86
146
  }
87
- async create(folder, name, options) {
88
- const { workspacePath, identityKey } = await resolveWorkspaceIdentity(folder, this.options.rootDir);
89
- if (this.shuttingDown) {
90
- throw new Error("Workspace manager is shutting down");
91
- }
92
- if (options?.forceNew) {
93
- return this.trackWorkspaceCreation(this.createResolvedWorkspace(workspacePath, identityKey, name));
94
- }
95
- const existing = this.findReadyWorkspaceByIdentity(identityKey);
96
- if (existing) {
97
- this.options.logger.info({ workspaceId: existing.id, folder: workspacePath }, "Reusing existing workspace");
98
- return { workspace: existing, created: false };
99
- }
100
- const pending = this.pendingWorkspaceCreations.get(identityKey);
101
- if (pending) {
102
- const result = await pending;
103
- return { workspace: result.workspace, created: false };
104
- }
105
- const creation = this.trackWorkspaceCreation(this.createResolvedWorkspace(workspacePath, identityKey, name, (workspaceId) => {
106
- this.pendingWorkspaceOwners.set(identityKey, workspaceId);
107
- }));
108
- this.pendingWorkspaceCreations.set(identityKey, creation);
147
+ async create(folder, name, options = {}) {
148
+ const launchTimeoutMs = Math.max(1, this.options.launchTimeoutMs ?? DEFAULT_LAUNCH_TIMEOUT_MS);
149
+ const launchDeadlineAt = Date.now() + launchTimeoutMs;
109
150
  try {
110
- return await creation;
111
- }
112
- finally {
113
- if (this.pendingWorkspaceCreations.get(identityKey) === creation) {
114
- this.pendingWorkspaceCreations.delete(identityKey);
115
- this.pendingWorkspaceOwners.delete(identityKey);
151
+ const { workspacePath, identityKey } = await this.withLaunchDeadline(resolveWorkspaceIdentity(folder, this.options.rootDir), undefined, launchDeadlineAt, launchTimeoutMs);
152
+ if (options.requestId && this.cancelledCreationRequests.has(options.requestId)) {
153
+ throw new Error(`Workspace creation request ${options.requestId} was cancelled`);
116
154
  }
117
- }
118
- }
119
- trackWorkspaceCreation(creation) {
120
- let tracked;
121
- tracked = (async () => {
155
+ if (this.shuttingDown) {
156
+ throw new Error("Workspace manager is shutting down");
157
+ }
158
+ if (options.forceNew) {
159
+ const ownership = this.createOwnership(options.requestId);
160
+ const record = this.reserveWorkspace(workspacePath, identityKey, name, options, ownership, launchDeadlineAt);
161
+ const result = await this.startCreation(record, options, launchDeadlineAt, launchTimeoutMs);
162
+ return this.finishCreation(result, options.requestId, ownership);
163
+ }
164
+ const existing = this.findReadyWorkspaceByIdentity(identityKey, Boolean(options.requestId));
165
+ if (existing) {
166
+ this.options.logger.info({ workspaceId: existing.id, folder: workspacePath }, "Reusing existing workspace");
167
+ const record = this.workspaces.get(existing.id);
168
+ if (options.requestId && record) {
169
+ if (!record.ownership.has(options.requestId))
170
+ record.ownership.set(options.requestId, "active");
171
+ this.syncOwnership(record);
172
+ return this.finishCreation({ workspace: existing, created: false }, options.requestId, record.ownership);
173
+ }
174
+ return { workspace: existing, created: false };
175
+ }
176
+ const pending = this.pendingWorkspaceCreations.get(identityKey);
177
+ if (pending) {
178
+ const state = pending[WORKSPACE_STATE];
179
+ const owner = options.requestId ?? ORDINARY_CREATION_OWNER;
180
+ if (!pending.ownership.has(owner))
181
+ pending.ownership.set(owner, "active");
182
+ this.syncOwnership(pending);
183
+ const result = await state.creation;
184
+ return this.finishCreation({ workspace: result.workspace, created: false }, options.requestId, pending.ownership);
185
+ }
186
+ const ownership = this.createOwnership(options.requestId);
187
+ const record = this.reserveWorkspace(workspacePath, identityKey, name, options, ownership, launchDeadlineAt);
188
+ const creation = this.startCreation(record, options, launchDeadlineAt, launchTimeoutMs);
189
+ this.pendingWorkspaceCreations.set(identityKey, record);
122
190
  try {
123
- return await creation;
191
+ return this.finishCreation(await creation, options.requestId, ownership);
124
192
  }
125
193
  finally {
126
- this.activeWorkspaceCreations.delete(tracked);
194
+ if (this.pendingWorkspaceCreations.get(identityKey) === record) {
195
+ this.pendingWorkspaceCreations.delete(identityKey);
196
+ }
127
197
  }
128
- })();
129
- this.activeWorkspaceCreations.add(tracked);
130
- return tracked;
198
+ }
199
+ finally {
200
+ if (options.requestId)
201
+ this.cancelledCreationRequests.delete(options.requestId);
202
+ }
131
203
  }
132
- async createResolvedWorkspace(workspacePath, identityKey, name, onReserved) {
204
+ reserveWorkspace(workspacePath, identityKey, name, options, ownership, launchDeadlineAt) {
133
205
  const id = randomUUID();
134
- const binary = this.options.binaryResolver.resolveDefault();
135
- const resolvedBinaryPath = this.resolveBinaryPath(binary.path);
206
+ const binary = this.options.binaryResolver.resolve(options.binaryPath);
207
+ const resolvedBinaryPath = this.resolveBinaryPath(binary.path, Math.max(1, launchDeadlineAt - Date.now()));
136
208
  clearWorkspaceSearchCache(workspacePath);
137
209
  this.options.logger.info({ workspaceId: id, folder: workspacePath, binary: resolvedBinaryPath }, "Creating workspace");
138
210
  const proxyPath = `/workspaces/${id}/instance`;
139
- const descriptor = {
211
+ const record = {
140
212
  id,
213
+ requestId: options.requestId,
141
214
  path: workspacePath,
142
215
  name,
143
216
  status: "starting",
@@ -148,11 +221,62 @@ export class WorkspaceManager {
148
221
  createdAt: new Date().toISOString(),
149
222
  updatedAt: new Date().toISOString(),
150
223
  };
151
- this.workspaces.set(id, descriptor);
152
- this.workspaceIdentities.set(id, identityKey);
153
- onReserved?.(id);
224
+ Object.defineProperties(record, {
225
+ identityKey: { value: identityKey },
226
+ ownership: { value: ownership },
227
+ [WORKSPACE_STATE]: { value: { abortController: new AbortController(), published: false, stoppedPublished: false } },
228
+ });
229
+ this.workspaces.set(id, record);
230
+ if (options.requestId && this.cancelledCreationRequests.has(options.requestId)) {
231
+ record[WORKSPACE_STATE].abortController.abort(new WorkspaceLaunchCancelledError(id));
232
+ }
233
+ return record;
234
+ }
235
+ startCreation(record, options, launchDeadlineAt, launchTimeoutMs) {
236
+ const creation = this.createWithDeadline(record, options, launchDeadlineAt, launchTimeoutMs);
237
+ record[WORKSPACE_STATE].creation = creation;
238
+ record[WORKSPACE_STATE].settlement = creation.then(() => undefined, () => undefined);
239
+ return creation;
240
+ }
241
+ async createWithDeadline(record, options, launchDeadlineAt, launchTimeoutMs) {
242
+ const timeoutMs = Math.max(1, launchDeadlineAt - Date.now());
243
+ const state = record[WORKSPACE_STATE];
244
+ let timeout = (this.options.setTimeout ?? setTimeout)(() => {
245
+ timeout = null;
246
+ if (!state.abortController.signal.aborted) {
247
+ state.abortController.abort(new WorkspaceLaunchTimeoutError(record.id, launchTimeoutMs));
248
+ }
249
+ }, timeoutMs);
154
250
  try {
155
- this.options.eventBus.publish({ type: "workspace.created", workspace: descriptor });
251
+ return await this.createResolvedWorkspace(record, options);
252
+ }
253
+ finally {
254
+ if (timeout)
255
+ (this.options.clearTimeout ?? clearTimeout)(timeout);
256
+ }
257
+ }
258
+ async withLaunchDeadline(operation, workspaceId, deadlineAt, launchTimeoutMs) {
259
+ const timeoutMs = Math.max(1, deadlineAt - Date.now());
260
+ let timeout = null;
261
+ const deadline = new Promise((_resolve, reject) => {
262
+ timeout = (this.options.setTimeout ?? setTimeout)(() => {
263
+ timeout = null;
264
+ reject(new WorkspaceLaunchTimeoutError(workspaceId, launchTimeoutMs));
265
+ }, timeoutMs);
266
+ });
267
+ try {
268
+ return await Promise.race([operation, deadline]);
269
+ }
270
+ finally {
271
+ if (timeout)
272
+ (this.options.clearTimeout ?? clearTimeout)(timeout);
273
+ }
274
+ }
275
+ async createResolvedWorkspace(record, options) {
276
+ const state = record[WORKSPACE_STATE];
277
+ const { id, path: workspacePath, binaryId: resolvedBinaryPath, proxyPath } = record;
278
+ try {
279
+ this.throwIfCancelled(record);
156
280
  const serverConfig = this.options.settings.getOwner("config", "server");
157
281
  const envVars = serverConfig?.environmentVariables;
158
282
  const userEnvironment = envVars && typeof envVars === "object" && !Array.isArray(envVars) ? envVars : {};
@@ -180,145 +304,231 @@ export class WorkspaceManager {
180
304
  [OPENCODE_SERVER_PASSWORD_ENV]: opencodePassword,
181
305
  };
182
306
  const logLevel = serverConfig?.logLevel;
183
- this.throwIfWorkspaceCreationCancelled(id);
184
307
  const { pid, port, exitPromise, getLastOutput } = await this.runtime.launch({
185
308
  workspaceId: id,
186
309
  folder: workspacePath,
187
310
  binaryPath: resolvedBinaryPath,
188
311
  environment,
189
312
  logLevel,
313
+ signal: state.abortController.signal,
190
314
  onExit: (info) => this.handleProcessExit(info.workspaceId, info),
191
315
  });
192
- descriptor.pid = pid;
193
- descriptor.port = port;
194
- this.throwIfWorkspaceCreationCancelled(id);
195
- const runtimeVersion = await this.waitForWorkspaceReadiness({ workspaceId: id, port, exitPromise, getLastOutput });
316
+ record.pid = pid;
317
+ record.port = port;
318
+ this.throwIfCancelled(record);
319
+ state.published = true;
320
+ this.options.eventBus.publish({ type: "workspace.created", workspace: record });
321
+ this.throwIfCancelled(record);
322
+ const runtimeVersion = await this.waitForWorkspaceReadiness({
323
+ workspaceId: id,
324
+ port,
325
+ exitPromise,
326
+ getLastOutput,
327
+ signal: state.abortController.signal,
328
+ });
329
+ this.throwIfCancelled(record);
196
330
  if (runtimeVersion) {
197
- descriptor.binaryVersion = runtimeVersion;
331
+ record.binaryVersion = runtimeVersion;
198
332
  }
199
- this.throwIfWorkspaceCreationCancelled(id);
200
- descriptor.status = "ready";
201
- descriptor.updatedAt = new Date().toISOString();
202
- this.options.eventBus.publish({ type: "workspace.started", workspace: descriptor });
333
+ record.status = "ready";
334
+ record.updatedAt = new Date().toISOString();
335
+ this.options.eventBus.publish({ type: "workspace.started", workspace: record });
203
336
  this.options.logger.info({ workspaceId: id, port }, "Workspace ready");
204
- return { workspace: descriptor, created: true };
337
+ return { workspace: record, created: true };
205
338
  }
206
339
  catch (error) {
340
+ const launchFailure = state.abortController.signal.aborted ? state.abortController.signal.reason : error;
207
341
  let stopFailure;
208
342
  await this.runtime.stop(id).catch((stopError) => {
209
343
  stopFailure = stopError;
210
- this.options.logger.warn({ workspaceId: id, err: stopError }, "Failed to stop workspace after startup error");
211
344
  });
212
- const cancelled = this.cancelledWorkspaceCreations.delete(id) || !this.workspaces.has(id);
213
- if (cancelled && !stopFailure) {
214
- throw new Error("Workspace creation cancelled");
345
+ if (!stopFailure) {
346
+ this.removeRecord(id, record, state.published);
347
+ throw launchFailure;
215
348
  }
216
- descriptor.status = "error";
217
- descriptor.error = stopFailure instanceof Error
218
- ? `Workspace startup failed and its process could not be stopped: ${stopFailure.message}`
219
- : error instanceof Error ? error.message : String(error);
220
- descriptor.updatedAt = new Date().toISOString();
221
- if (this.workspaces.has(id)) {
222
- this.options.eventBus.publish({ type: "workspace.error", workspace: descriptor });
349
+ if (!state.published) {
350
+ throw stopFailure;
223
351
  }
224
- this.options.logger.error({ workspaceId: id, err: error }, "Workspace failed to start");
225
- if (cancelled) {
226
- throw new Error(descriptor.error);
352
+ record.status = "error";
353
+ record.error = stopFailure instanceof Error
354
+ ? `Workspace startup failed and its process could not be stopped: ${stopFailure.message}`
355
+ : launchFailure instanceof Error ? launchFailure.message : String(launchFailure);
356
+ record.updatedAt = new Date().toISOString();
357
+ if (this.workspaces.get(id) === record && state.published) {
358
+ this.options.eventBus.publish({ type: "workspace.error", workspace: record });
227
359
  }
228
- throw error;
360
+ this.options.logger.error({ workspaceId: id, err: launchFailure }, "Workspace failed to start");
361
+ throw launchFailure;
229
362
  }
230
363
  }
231
- async delete(id) {
232
- const workspace = this.workspaces.get(id);
233
- if (!workspace)
234
- return undefined;
235
- this.options.logger.info({ workspaceId: id }, "Stopping workspace");
236
- const wasStarting = workspace.status === "starting";
237
- const wasRunning = Boolean(workspace.pid);
238
- if (wasStarting) {
239
- this.cancelledWorkspaceCreations.add(id);
364
+ delete(id) {
365
+ const record = this.workspaces.get(id);
366
+ if (!record)
367
+ return Promise.resolve(undefined);
368
+ const state = record[WORKSPACE_STATE];
369
+ if (!state.abortController.signal.aborted) {
370
+ state.abortController.abort(new WorkspaceLaunchCancelledError(id));
371
+ }
372
+ const pending = this.pendingWorkspaceCreations.get(record.identityKey);
373
+ if (pending === record) {
374
+ this.pendingWorkspaceCreations.delete(record.identityKey);
375
+ }
376
+ if (!state.deletePromise) {
377
+ let deletePromise;
378
+ deletePromise = this.cleanupDeletedWorkspace(id, record).catch((error) => {
379
+ if (state.deletePromise === deletePromise)
380
+ state.deletePromise = undefined;
381
+ throw error;
382
+ });
383
+ state.deletePromise = deletePromise;
240
384
  }
241
- if (wasStarting || wasRunning) {
242
- try {
243
- await this.runtime.stop(id);
385
+ return state.deletePromise;
386
+ }
387
+ releaseCreationRequest(id, requestId) {
388
+ const record = this.workspaces.get(id);
389
+ if (!record?.[WORKSPACE_STATE].published)
390
+ return false;
391
+ const ownership = record.ownership;
392
+ const state = ownership.get(requestId);
393
+ if (state === "released")
394
+ return true;
395
+ if (state === "cancelled")
396
+ return false;
397
+ if (state !== "active")
398
+ return false;
399
+ ownership.set(requestId, "released");
400
+ this.syncOwnership(record);
401
+ return true;
402
+ }
403
+ async cancelCreationRequest(requestId) {
404
+ let matched = false;
405
+ for (const [workspaceId, record] of this.workspaces) {
406
+ const ownership = record.ownership;
407
+ const state = ownership.get(requestId);
408
+ if (state === "released") {
409
+ matched = true;
410
+ continue;
244
411
  }
245
- catch (error) {
246
- this.options.logger.warn({ workspaceId: id, err: error }, "Failed to stop workspace process cleanly");
247
- workspace.status = "error";
248
- workspace.error = error instanceof Error ? error.message : String(error);
249
- workspace.updatedAt = new Date().toISOString();
250
- this.options.eventBus.publish({ type: "workspace.error", workspace });
251
- throw error;
412
+ if (state === "cancelled") {
413
+ matched = true;
414
+ if (this.hasActiveRequest(ownership) || this.isRetained(ownership))
415
+ continue;
416
+ await this.delete(workspaceId);
417
+ return;
252
418
  }
419
+ if (state !== "active")
420
+ continue;
421
+ matched = true;
422
+ ownership.set(requestId, "cancelled");
423
+ this.syncOwnership(record);
424
+ if (this.hasActiveRequest(ownership) || this.isRetained(ownership))
425
+ return;
426
+ await this.delete(workspaceId);
427
+ return;
253
428
  }
254
- const identityKey = this.workspaceIdentities.get(id);
255
- if (identityKey && this.pendingWorkspaceOwners.get(identityKey) === id) {
256
- this.pendingWorkspaceCreations.delete(identityKey);
257
- this.pendingWorkspaceOwners.delete(identityKey);
258
- }
259
- const stoppedEventPublished = workspace.status === "stopped";
260
- this.workspaces.delete(id);
261
- this.workspaceIdentities.delete(id);
262
- this.opencodeAuth.delete(id);
263
- if (!wasStarting) {
264
- this.cancelledWorkspaceCreations.delete(id);
265
- }
266
- clearWorkspaceSearchCache(workspace.path);
267
- if (!stoppedEventPublished) {
268
- this.options.eventBus.publish({ type: "workspace.stopped", workspaceId: id });
429
+ if (!matched)
430
+ this.cancelledCreationRequests.add(requestId);
431
+ }
432
+ createOwnership(requestId) {
433
+ return new Map([[requestId ?? ORDINARY_CREATION_OWNER, "active"]]);
434
+ }
435
+ finishCreation(result, requestId, ownership) {
436
+ if (requestId && ownership.get(requestId) === "cancelled") {
437
+ throw new Error(`Workspace creation request ${requestId} was cancelled`);
269
438
  }
270
- return workspace;
439
+ const retained = this.isRetained(ownership);
440
+ return {
441
+ workspace: requestId ? { ...result.workspace, requestId } : result.workspace,
442
+ created: result.created && !(requestId && retained),
443
+ };
444
+ }
445
+ syncOwnership(record) {
446
+ if (!record)
447
+ return;
448
+ const ownership = record.ownership;
449
+ record.requestId = this.isRetained(ownership)
450
+ ? undefined
451
+ : Array.from(ownership).find(([, state]) => state === "active")?.[0];
452
+ }
453
+ isRetained(ownership) {
454
+ return ownership.has(ORDINARY_CREATION_OWNER) || Array.from(ownership.values()).includes("released");
455
+ }
456
+ hasActiveRequest(ownership) {
457
+ return Array.from(ownership).some(([requestId, state]) => Boolean(requestId) && state === "active");
271
458
  }
272
459
  async shutdown() {
273
460
  this.shuttingDown = true;
274
461
  this.options.logger.info("Shutting down all workspaces");
275
- const stopTasks = [];
276
- for (const [id, workspace] of this.workspaces) {
277
- if (workspace.status === "starting") {
278
- this.cancelledWorkspaceCreations.add(id);
279
- }
280
- if (!workspace.pid && workspace.status !== "starting") {
281
- this.options.logger.debug({ workspaceId: id }, "Workspace already stopped");
282
- continue;
283
- }
284
- this.options.logger.info({ workspaceId: id }, "Stopping workspace during shutdown");
285
- stopTasks.push(this.runtime.stop(id).catch((error) => {
286
- this.options.logger.error({ workspaceId: id, err: error }, "Failed to stop workspace during shutdown");
287
- throw error;
288
- }));
289
- }
290
- if (stopTasks.length > 0) {
291
- const stopResults = await Promise.allSettled(stopTasks);
292
- const failedStop = stopResults.find((result) => result.status === "rejected");
293
- if (failedStop) {
294
- throw failedStop.reason;
295
- }
462
+ const stopTasks = Array.from(this.workspaces.keys(), (id) => this.delete(id));
463
+ const results = stopTasks.length
464
+ ? await this.withTimeout(Promise.allSettled(stopTasks), this.options.shutdownTimeoutMs ?? 10000, "shutdown")
465
+ : [];
466
+ const stopFailures = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
467
+ if (this.workspaces.size === 0) {
468
+ this.pendingWorkspaceCreations.clear();
469
+ this.cancelledCreationRequests.clear();
470
+ }
471
+ else if (!stopFailures.length)
472
+ stopFailures.push(new Error(`Workspace cleanup remains incomplete for: ${Array.from(this.workspaces.keys()).join(", ")}`));
473
+ if (stopFailures.length)
474
+ throw new WorkspaceShutdownError(stopFailures);
475
+ }
476
+ async withTimeout(operation, timeoutMs, label) {
477
+ let timeout = null;
478
+ const deadline = new Promise((_resolve, reject) => {
479
+ timeout = (this.options.setTimeout ?? setTimeout)(() => {
480
+ timeout = null;
481
+ reject(new WorkspaceCleanupTimeoutError(label, timeoutMs));
482
+ }, timeoutMs);
483
+ });
484
+ try {
485
+ return await Promise.race([operation, deadline]);
296
486
  }
297
- if (this.activeWorkspaceCreations.size > 0) {
298
- await Promise.allSettled(this.activeWorkspaceCreations);
487
+ finally {
488
+ if (timeout)
489
+ (this.options.clearTimeout ?? clearTimeout)(timeout);
299
490
  }
300
- this.workspaces.clear();
301
- this.workspaceIdentities.clear();
302
- this.pendingWorkspaceCreations.clear();
303
- this.pendingWorkspaceOwners.clear();
304
- this.activeWorkspaceCreations.clear();
305
- this.cancelledWorkspaceCreations.clear();
306
- this.opencodeAuth.clear();
307
- this.options.logger.info("All workspaces cleared");
308
491
  }
309
492
  requireWorkspace(id) {
310
- const workspace = this.workspaces.get(id);
311
- if (!workspace) {
493
+ const record = this.workspaces.get(id);
494
+ if (!record?.[WORKSPACE_STATE].published)
312
495
  throw new Error("Workspace not found");
313
- }
314
- return workspace;
496
+ return record;
315
497
  }
316
- throwIfWorkspaceCreationCancelled(id) {
317
- if (this.shuttingDown || this.cancelledWorkspaceCreations.has(id) || !this.workspaces.has(id)) {
318
- throw new Error("Workspace creation cancelled");
319
- }
498
+ throwIfCancelled(record) {
499
+ record[WORKSPACE_STATE].abortController.signal.throwIfAborted();
500
+ }
501
+ async cleanupDeletedWorkspace(id, record) {
502
+ // Stop once immediately, then again after launch settlement to cover a child
503
+ // that became available while cancellation was propagating.
504
+ const immediateStop = this.runtime.stop(id).catch((error) => {
505
+ this.options.logger.warn({ workspaceId: id, err: error }, "Initial workspace process cleanup failed; retrying after launch settles");
506
+ });
507
+ await this.withTimeout(record[WORKSPACE_STATE].settlement, this.options.launchSettlementTimeoutMs ?? 5000, `${id} launch cancellation`);
508
+ await immediateStop;
509
+ await this.runtime.stop(id);
510
+ this.removeRecord(id, record, true);
511
+ return record;
512
+ }
513
+ removeRecord(id, record, publishStopped) {
514
+ if (this.workspaces.get(id) !== record)
515
+ return;
516
+ this.workspaces.delete(id);
517
+ this.opencodeAuth.delete(id);
518
+ clearWorkspaceSearchCache(record.path);
519
+ if (publishStopped)
520
+ this.publishStopped(record, "deleted");
320
521
  }
321
- resolveBinaryPath(identifier) {
522
+ publishStopped(record, reason = "stopped") {
523
+ const state = record[WORKSPACE_STATE];
524
+ if (!state.published || state.stoppedPublished)
525
+ return;
526
+ state.stoppedPublished = true;
527
+ record.status = "stopped";
528
+ record.error = undefined;
529
+ this.options.eventBus.publish({ type: "workspace.stopped", workspaceId: record.id, reason });
530
+ }
531
+ resolveBinaryPath(identifier, timeoutMs = DEFAULT_LAUNCH_TIMEOUT_MS) {
322
532
  if (!identifier) {
323
533
  return identifier;
324
534
  }
@@ -328,7 +538,7 @@ export class WorkspaceManager {
328
538
  }
329
539
  const locator = process.platform === "win32" ? "where" : "which";
330
540
  try {
331
- const result = spawnSync(locator, [identifier], { encoding: "utf8" });
541
+ const result = spawnSync(locator, [identifier], { encoding: "utf8", timeout: Math.max(1, timeoutMs) });
332
542
  if (result.status === 0 && result.stdout) {
333
543
  const candidates = result.stdout
334
544
  .split(/\r?\n/)
@@ -365,26 +575,20 @@ export class WorkspaceManager {
365
575
  }
366
576
  async waitForWorkspaceReadiness(params) {
367
577
  await Promise.race([
368
- this.waitForPortAvailability(params.port),
369
- params.exitPromise.then((info) => {
370
- throw this.buildStartupError(params.workspaceId, "exited before becoming ready", info, params.getLastOutput());
371
- }),
578
+ this.waitForPortAvailability(params.port, 5000, params.signal),
579
+ this.exitDuringStartup(params, "exited before becoming ready"),
372
580
  ]);
373
581
  const version = await this.waitForInstanceHealth(params);
374
582
  await Promise.race([
375
- this.delay(STARTUP_STABILITY_DELAY_MS),
376
- params.exitPromise.then((info) => {
377
- throw this.buildStartupError(params.workspaceId, "exited shortly after start", info, params.getLastOutput());
378
- }),
583
+ delay(STARTUP_STABILITY_DELAY_MS, undefined, { signal: params.signal }),
584
+ this.exitDuringStartup(params, "exited shortly after start"),
379
585
  ]);
380
586
  return version;
381
587
  }
382
588
  async waitForInstanceHealth(params) {
383
589
  const probeResult = await Promise.race([
384
- this.probeInstance(params.workspaceId, params.port),
385
- params.exitPromise.then((info) => {
386
- throw this.buildStartupError(params.workspaceId, "exited during health checks", info, params.getLastOutput());
387
- }),
590
+ this.probeInstance(params.workspaceId, params.port, params.signal),
591
+ this.exitDuringStartup(params, "exited during health checks"),
388
592
  ]);
389
593
  if (probeResult.ok) {
390
594
  return probeResult.version;
@@ -396,7 +600,12 @@ export class WorkspaceManager {
396
600
  const reason = probeResult.reason ?? "Health check failed";
397
601
  throw new Error(`Workspace ${params.workspaceId} failed health check: ${reason}.`);
398
602
  }
399
- async probeInstance(workspaceId, port) {
603
+ exitDuringStartup(params, phase) {
604
+ return params.exitPromise.then((info) => {
605
+ throw this.buildStartupError(params.workspaceId, phase, info, params.getLastOutput());
606
+ });
607
+ }
608
+ async probeInstance(workspaceId, port, signal) {
400
609
  const url = `http://127.0.0.1:${port}/global/health`;
401
610
  try {
402
611
  const headers = {};
@@ -404,7 +613,7 @@ export class WorkspaceManager {
404
613
  if (authHeader) {
405
614
  headers["Authorization"] = authHeader;
406
615
  }
407
- const response = await fetch(url, { headers });
616
+ const response = await fetch(url, { headers, signal });
408
617
  if (!response.ok) {
409
618
  const reason = `/global/health returned HTTP ${response.status}`;
410
619
  this.options.logger.debug({ workspaceId, status: response.status }, "Health probe returned server error");
@@ -432,7 +641,7 @@ export class WorkspaceManager {
432
641
  const outputDetails = trimmedOutput ? ` Last output: ${trimmedOutput}` : "";
433
642
  return new Error(`Workspace ${workspaceId} ${phase} (${exitDetails}).${outputDetails}`);
434
643
  }
435
- waitForPortAvailability(port, timeoutMs = 5000) {
644
+ waitForPortAvailability(port, timeoutMs = 5000, signal) {
436
645
  return new Promise((resolve, reject) => {
437
646
  const deadline = Date.now() + timeoutMs;
438
647
  let settled = false;
@@ -445,17 +654,20 @@ export class WorkspaceManager {
445
654
  }
446
655
  };
447
656
  const tryConnect = () => {
448
- if (settled) {
657
+ if (settled)
449
658
  return;
450
- }
451
- const socket = connect({ port, host: "127.0.0.1" }, () => {
659
+ const socket = connect({ port, host: "127.0.0.1", signal }, () => {
452
660
  cleanup();
453
661
  socket.end();
454
662
  resolve();
455
663
  });
456
664
  socket.once("error", () => {
457
665
  socket.destroy();
458
- if (settled) {
666
+ if (settled)
667
+ return;
668
+ if (signal?.aborted) {
669
+ cleanup();
670
+ reject(signal.reason);
459
671
  return;
460
672
  }
461
673
  if (Date.now() >= deadline) {
@@ -470,15 +682,11 @@ export class WorkspaceManager {
470
682
  }
471
683
  });
472
684
  };
685
+ if (signal?.aborted)
686
+ return reject(signal.reason);
473
687
  tryConnect();
474
688
  });
475
689
  }
476
- delay(durationMs) {
477
- if (durationMs <= 0) {
478
- return Promise.resolve();
479
- }
480
- return new Promise((resolve) => setTimeout(resolve, durationMs));
481
- }
482
690
  describeExit(info) {
483
691
  if (info.signal) {
484
692
  return `signal ${info.signal}`;
@@ -489,18 +697,17 @@ export class WorkspaceManager {
489
697
  return "unknown reason";
490
698
  }
491
699
  handleProcessExit(workspaceId, info) {
492
- const workspace = this.workspaces.get(workspaceId);
493
- if (!workspace)
700
+ const record = this.workspaces.get(workspaceId);
701
+ if (!record)
494
702
  return;
703
+ const workspace = record;
495
704
  this.opencodeAuth.delete(workspaceId);
496
705
  this.options.logger.info({ workspaceId, ...info }, "Workspace process exited");
497
706
  workspace.pid = undefined;
498
707
  workspace.port = undefined;
499
708
  workspace.updatedAt = new Date().toISOString();
500
- if (info.requested || info.code === 0) {
501
- workspace.status = "stopped";
502
- workspace.error = undefined;
503
- this.options.eventBus.publish({ type: "workspace.stopped", workspaceId });
709
+ if (record[WORKSPACE_STATE].abortController.signal.aborted || info.requested || info.code === 0) {
710
+ this.publishStopped(record);
504
711
  }
505
712
  else {
506
713
  workspace.status = "error";