@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,7 +1,9 @@
|
|
|
1
1
|
import { spawn, spawnSync } from "child_process";
|
|
2
|
+
import { randomBytes } from "crypto";
|
|
2
3
|
import { existsSync, statSync } from "fs";
|
|
3
4
|
import path from "path";
|
|
4
|
-
import { buildSpawnSpec
|
|
5
|
+
import { buildSpawnSpec } from "./spawn";
|
|
6
|
+
import { descendantsOf, LAUNCH_CLEANUP_TOKEN_ENV, probeLaunchCleanupToken, probePosixProcesses, probeWindowsProcesses, probeWslProcesses, sameProcess, signalPosixProcesses, signalOwnedPosixProcessGroup, signalLaunchCleanupToken, signalWindowsProcesses, signalWslProcesses, startedNoLaterThan, } from "./process-identity";
|
|
5
7
|
const SENSITIVE_ENV_KEY = /(PASSWORD|TOKEN|SECRET)/i;
|
|
6
8
|
const WSL_PID_MARKER = "__CODENOMAD_WSL_PID__:";
|
|
7
9
|
function redactEnvironment(env) {
|
|
@@ -15,17 +17,54 @@ function redactEnvironment(env) {
|
|
|
15
17
|
}
|
|
16
18
|
return redacted;
|
|
17
19
|
}
|
|
20
|
+
export class WorkspaceStopTimeoutError extends Error {
|
|
21
|
+
constructor(workspaceId, pid, timeoutMs, liveness, failures) {
|
|
22
|
+
const failureDetails = failures.length > 0 ? ` Stop failures: ${failures.join("; ")}.` : "";
|
|
23
|
+
super(`Workspace ${workspaceId} process ${pid ?? "with unknown PID"} did not stop within ${timeoutMs}ms; ${liveness}.` +
|
|
24
|
+
`${failureDetails} The stop can be retried.`);
|
|
25
|
+
this.code = "WORKSPACE_STOP_TIMEOUT";
|
|
26
|
+
this.retryable = true;
|
|
27
|
+
this.name = "WorkspaceStopTimeoutError";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export class WorkspaceWindowsTreeCleanupIncompleteError extends Error {
|
|
31
|
+
constructor(workspaceId, pid, failures) {
|
|
32
|
+
const failureDetails = failures.length > 0 ? ` Stop failures: ${failures.join("; ")}.` : "";
|
|
33
|
+
super(`Workspace ${workspaceId} Windows wrapper ${pid ?? "with unknown PID"} exited before taskkill confirmed process-tree cleanup.` +
|
|
34
|
+
`${failureDetails} The workspace record was retained because cleanup is incomplete.`);
|
|
35
|
+
this.code = "WORKSPACE_WINDOWS_TREE_CLEANUP_INCOMPLETE";
|
|
36
|
+
this.retryable = true;
|
|
37
|
+
this.name = "WorkspaceWindowsTreeCleanupIncompleteError";
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
export class WorkspaceRuntimeIdentityCaptureError extends Error {
|
|
41
|
+
constructor(workspaceId, detail) {
|
|
42
|
+
super(`Workspace ${workspaceId} process identity capture failed: ${detail}`);
|
|
43
|
+
this.code = "WORKSPACE_RUNTIME_IDENTITY_CAPTURE_FAILED";
|
|
44
|
+
this.name = "WorkspaceRuntimeIdentityCaptureError";
|
|
45
|
+
}
|
|
46
|
+
}
|
|
18
47
|
export class WorkspaceRuntime {
|
|
19
|
-
constructor(eventBus, logger) {
|
|
48
|
+
constructor(eventBus, logger, options = {}) {
|
|
20
49
|
this.eventBus = eventBus;
|
|
21
50
|
this.logger = logger;
|
|
22
51
|
this.processes = new Map();
|
|
52
|
+
this.platform = options.platform ?? process.platform;
|
|
53
|
+
this.spawnProcess = options.spawn ?? spawn;
|
|
54
|
+
this.spawnCommand = options.spawnSync ?? spawnSync;
|
|
55
|
+
this.scheduleTimeout = options.setTimeout ?? setTimeout;
|
|
56
|
+
this.cancelTimeout = options.clearTimeout ?? clearTimeout;
|
|
57
|
+
this.gracefulStopTimeoutMs = Math.max(0, options.gracefulStopTimeoutMs ?? 2000);
|
|
58
|
+
this.forcedStopTimeoutMs = Math.max(0, options.forcedStopTimeoutMs ?? 2000);
|
|
59
|
+
this.stopCommandTimeoutMs = Math.max(1, options.stopCommandTimeoutMs ?? 1000);
|
|
23
60
|
}
|
|
24
61
|
async launch(options) {
|
|
62
|
+
options.signal?.throwIfAborted();
|
|
25
63
|
this.validateFolder(options.folder);
|
|
26
64
|
const logLevel = typeof options.logLevel === "string" ? options.logLevel.toUpperCase() : "DEBUG";
|
|
27
65
|
const args = ["serve", "--port", "0", "--print-logs", "--log-level", logLevel];
|
|
28
|
-
const
|
|
66
|
+
const cleanupToken = randomBytes(32).toString("hex");
|
|
67
|
+
const env = { ...process.env, ...(options.environment ?? {}), [LAUNCH_CLEANUP_TOKEN_ENV]: cleanupToken };
|
|
29
68
|
let exitResolve = null;
|
|
30
69
|
const exitPromise = new Promise((resolveExit) => {
|
|
31
70
|
exitResolve = resolveExit;
|
|
@@ -47,12 +86,13 @@ export class WorkspaceRuntime {
|
|
|
47
86
|
return combined.join("\n");
|
|
48
87
|
};
|
|
49
88
|
return new Promise((resolve, reject) => {
|
|
50
|
-
const propagatedEnvKeys = Object.keys(options.environment ?? {});
|
|
89
|
+
const propagatedEnvKeys = [...Object.keys(options.environment ?? {}), LAUNCH_CLEANUP_TOKEN_ENV];
|
|
51
90
|
const spec = buildSpawnSpec(options.binaryPath, args, {
|
|
52
91
|
cwd: options.folder,
|
|
53
92
|
env,
|
|
54
93
|
propagateEnvKeys: propagatedEnvKeys,
|
|
55
94
|
wslPidMarker: WSL_PID_MARKER,
|
|
95
|
+
platform: this.platform,
|
|
56
96
|
});
|
|
57
97
|
const commandLine = [spec.command, ...spec.args].join(" ");
|
|
58
98
|
this.logger.info({
|
|
@@ -70,23 +110,75 @@ export class WorkspaceRuntime {
|
|
|
70
110
|
workspaceId: options.workspaceId,
|
|
71
111
|
env: redactEnvironment(env),
|
|
72
112
|
}, "OpenCode spawn environment");
|
|
73
|
-
const detached =
|
|
74
|
-
const child =
|
|
113
|
+
const detached = this.platform !== "win32";
|
|
114
|
+
const child = this.spawnProcess(spec.command, spec.args, {
|
|
75
115
|
cwd: spec.cwd,
|
|
76
116
|
env: spec.env,
|
|
77
117
|
stdio: ["ignore", "pipe", "pipe"],
|
|
78
118
|
detached,
|
|
79
119
|
...spec.options,
|
|
80
120
|
});
|
|
121
|
+
const handleEarlyError = (error) => {
|
|
122
|
+
this.logger.error({ workspaceId: options.workspaceId, err: error }, "Workspace runtime failed before launch handlers were ready");
|
|
123
|
+
};
|
|
124
|
+
child.on("error", handleEarlyError);
|
|
81
125
|
const managed = {
|
|
82
126
|
child,
|
|
127
|
+
cleanupToken,
|
|
128
|
+
processKind: spec.processKind,
|
|
83
129
|
requestedStop: false,
|
|
84
|
-
|
|
130
|
+
targets: { members: new Map() },
|
|
131
|
+
...(spec.wsl
|
|
132
|
+
? {
|
|
133
|
+
wsl: {
|
|
134
|
+
distro: spec.wsl.distro,
|
|
135
|
+
linuxPid: null,
|
|
136
|
+
linuxPgid: null,
|
|
137
|
+
leaderStartTime: null,
|
|
138
|
+
bootId: null,
|
|
139
|
+
members: new Map(),
|
|
140
|
+
},
|
|
141
|
+
}
|
|
142
|
+
: {}),
|
|
85
143
|
};
|
|
86
144
|
this.processes.set(options.workspaceId, managed);
|
|
145
|
+
if (spec.processKind === "posix" || spec.processKind === "wsl" || spec.processKind === "windows-direct") {
|
|
146
|
+
const launchSnapshot = child.pid
|
|
147
|
+
? this.platform === "win32"
|
|
148
|
+
? probeWindowsProcesses(this.spawnCommand, this.stopCommandTimeoutMs)
|
|
149
|
+
: probePosixProcesses(this.spawnCommand, this.stopCommandTimeoutMs, this.platform, { pids: [child.pid], groupId: child.pid })
|
|
150
|
+
: { ok: false, error: "spawned child did not expose a PID" };
|
|
151
|
+
const launchLeader = launchSnapshot.ok && child.pid ? launchSnapshot.processes.get(child.pid) : undefined;
|
|
152
|
+
if (!launchLeader) {
|
|
153
|
+
const detail = launchSnapshot.ok
|
|
154
|
+
? `spawned PID ${child.pid ?? "unknown"} was absent from the identity snapshot`
|
|
155
|
+
: launchSnapshot.error;
|
|
156
|
+
this.beginFailedLaunchCleanup(options.workspaceId, managed);
|
|
157
|
+
reject(new WorkspaceRuntimeIdentityCaptureError(options.workspaceId, detail));
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
managed.targets.leader = launchLeader;
|
|
161
|
+
managed.targets.groupId = launchLeader.groupId;
|
|
162
|
+
managed.targets.groupOwnershipRetained = this.platform !== "linux" && this.platform !== "win32" &&
|
|
163
|
+
launchLeader.groupId === launchLeader.pid;
|
|
164
|
+
for (const identity of launchSnapshot.ok ? launchSnapshot.processes.values() : [launchLeader]) {
|
|
165
|
+
if (identity.groupId === launchLeader.groupId)
|
|
166
|
+
managed.targets.members.set(identity.pid, identity);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
87
169
|
let stdoutBuffer = "";
|
|
88
170
|
let stderrBuffer = "";
|
|
89
171
|
let portFound = false;
|
|
172
|
+
let pendingPort = null;
|
|
173
|
+
let launchSettled = false;
|
|
174
|
+
const cancelLaunch = () => {
|
|
175
|
+
if (launchSettled)
|
|
176
|
+
return;
|
|
177
|
+
launchSettled = true;
|
|
178
|
+
stopWarningTimer();
|
|
179
|
+
reject(options.signal?.reason ?? new Error(`Workspace ${options.workspaceId} runtime launch was cancelled`));
|
|
180
|
+
};
|
|
181
|
+
managed.cancelLaunch = cancelLaunch;
|
|
90
182
|
let warningTimer = null;
|
|
91
183
|
const startWarningTimer = () => {
|
|
92
184
|
warningTimer = setInterval(() => {
|
|
@@ -100,15 +192,24 @@ export class WorkspaceRuntime {
|
|
|
100
192
|
}
|
|
101
193
|
};
|
|
102
194
|
startWarningTimer();
|
|
195
|
+
options.signal?.addEventListener("abort", cancelLaunch, { once: true });
|
|
196
|
+
if (options.signal?.aborted)
|
|
197
|
+
cancelLaunch();
|
|
103
198
|
const cleanupStreams = () => {
|
|
104
199
|
stopWarningTimer();
|
|
105
200
|
child.stdout?.removeAllListeners();
|
|
106
201
|
child.stderr?.removeAllListeners();
|
|
107
202
|
};
|
|
203
|
+
let finalized = false;
|
|
108
204
|
const handleExit = (code, signal) => {
|
|
205
|
+
if (finalized)
|
|
206
|
+
return;
|
|
207
|
+
finalized = true;
|
|
208
|
+
const cleanupRequired = !managed.requestedStop;
|
|
109
209
|
this.logger.info({ workspaceId: options.workspaceId, code, signal }, "OpenCode process exited");
|
|
110
|
-
this.processes.delete(options.workspaceId);
|
|
111
210
|
cleanupStreams();
|
|
211
|
+
options.signal?.removeEventListener("abort", cancelLaunch);
|
|
212
|
+
managed.cancelLaunch = undefined;
|
|
112
213
|
child.removeListener("error", handleError);
|
|
113
214
|
child.removeListener("exit", handleExit);
|
|
114
215
|
const exitInfo = {
|
|
@@ -124,25 +225,69 @@ export class WorkspaceRuntime {
|
|
|
124
225
|
if (!portFound) {
|
|
125
226
|
const recentOutput = getLastOutput().trim();
|
|
126
227
|
const reason = recentOutput || stderrBuffer || `Process exited with code ${code}`;
|
|
127
|
-
|
|
228
|
+
if (!launchSettled) {
|
|
229
|
+
launchSettled = true;
|
|
230
|
+
reject(new Error(reason));
|
|
231
|
+
}
|
|
128
232
|
}
|
|
129
233
|
else {
|
|
130
234
|
options.onExit?.(exitInfo);
|
|
131
235
|
}
|
|
236
|
+
if (cleanupRequired && this.processes.get(options.workspaceId) === managed) {
|
|
237
|
+
void this.stop(options.workspaceId).catch((error) => {
|
|
238
|
+
this.logger.warn({ workspaceId: options.workspaceId, err: error }, "Unexpected workspace exit cleanup remains pending");
|
|
239
|
+
});
|
|
240
|
+
}
|
|
132
241
|
};
|
|
242
|
+
managed.finalizeExit = handleExit;
|
|
133
243
|
const handleError = (error) => {
|
|
244
|
+
const cleanupRequired = !managed.requestedStop;
|
|
134
245
|
cleanupStreams();
|
|
246
|
+
options.signal?.removeEventListener("abort", cancelLaunch);
|
|
247
|
+
managed.cancelLaunch = undefined;
|
|
135
248
|
child.removeListener("exit", handleExit);
|
|
136
|
-
this.processes.delete(options.workspaceId);
|
|
137
249
|
this.logger.error({ workspaceId: options.workspaceId, err: error }, "Workspace runtime error");
|
|
138
250
|
if (exitResolve) {
|
|
139
251
|
exitResolve({ workspaceId: options.workspaceId, code: null, signal: null, requested: managed.requestedStop });
|
|
140
252
|
exitResolve = null;
|
|
141
253
|
}
|
|
142
|
-
|
|
254
|
+
if (!launchSettled) {
|
|
255
|
+
launchSettled = true;
|
|
256
|
+
reject(error);
|
|
257
|
+
}
|
|
258
|
+
if (cleanupRequired && this.processes.get(options.workspaceId) === managed) {
|
|
259
|
+
void this.stop(options.workspaceId).catch((stopError) => {
|
|
260
|
+
this.logger.warn({ workspaceId: options.workspaceId, err: stopError }, "Workspace error cleanup remains pending");
|
|
261
|
+
});
|
|
262
|
+
}
|
|
143
263
|
};
|
|
264
|
+
child.removeListener("error", handleEarlyError);
|
|
144
265
|
child.on("error", handleError);
|
|
145
266
|
child.on("exit", handleExit);
|
|
267
|
+
const resolveLaunchIfIdentified = () => {
|
|
268
|
+
if (launchSettled || pendingPort === null)
|
|
269
|
+
return;
|
|
270
|
+
if (managed.wsl && (!managed.wsl.linuxPid || !managed.wsl.linuxPgid || !managed.wsl.leaderStartTime || !managed.wsl.bootId)) {
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
portFound = true;
|
|
274
|
+
launchSettled = true;
|
|
275
|
+
stopWarningTimer();
|
|
276
|
+
options.signal?.removeEventListener("abort", cancelLaunch);
|
|
277
|
+
managed.cancelLaunch = undefined;
|
|
278
|
+
child.removeListener("error", handleError);
|
|
279
|
+
this.logger.info({ workspaceId: options.workspaceId, port: pendingPort }, "Workspace runtime allocated port");
|
|
280
|
+
resolve({ pid: child.pid, port: pendingPort, exitPromise, getLastOutput });
|
|
281
|
+
};
|
|
282
|
+
const failWslIdentityCapture = (detail) => {
|
|
283
|
+
if (launchSettled)
|
|
284
|
+
return;
|
|
285
|
+
launchSettled = true;
|
|
286
|
+
managed.requestedStop = true;
|
|
287
|
+
cleanupStreams();
|
|
288
|
+
this.beginFailedLaunchCleanup(options.workspaceId, managed);
|
|
289
|
+
reject(new WorkspaceRuntimeIdentityCaptureError(options.workspaceId, detail));
|
|
290
|
+
};
|
|
146
291
|
child.stdout?.on("data", (data) => {
|
|
147
292
|
const text = data.toString();
|
|
148
293
|
stdoutBuffer += text;
|
|
@@ -153,10 +298,32 @@ export class WorkspaceRuntime {
|
|
|
153
298
|
if (!trimmed)
|
|
154
299
|
continue;
|
|
155
300
|
if (managed.wsl && trimmed.startsWith(WSL_PID_MARKER)) {
|
|
156
|
-
const
|
|
157
|
-
|
|
301
|
+
const [linuxPidText, linuxPgidText, linuxStartTime = "", bootId = ""] = trimmed.slice(WSL_PID_MARKER.length).split(":", 4);
|
|
302
|
+
const linuxPid = Number.parseInt(linuxPidText ?? "", 10);
|
|
303
|
+
const linuxPgid = Number.parseInt(linuxPgidText ?? "", 10);
|
|
304
|
+
if (Number.isInteger(linuxPid) && linuxPid > 0 && Number.isInteger(linuxPgid) && linuxPgid > 0 && /^\d+$/.test(linuxStartTime) && bootId) {
|
|
158
305
|
managed.wsl.linuxPid = linuxPid;
|
|
159
|
-
|
|
306
|
+
managed.wsl.linuxPgid = linuxPgid;
|
|
307
|
+
managed.wsl.leaderStartTime = linuxStartTime;
|
|
308
|
+
managed.wsl.bootId = bootId;
|
|
309
|
+
managed.wsl.members.set(linuxPid, {
|
|
310
|
+
pid: linuxPid,
|
|
311
|
+
parentPid: 0,
|
|
312
|
+
groupId: linuxPgid,
|
|
313
|
+
startTime: linuxStartTime,
|
|
314
|
+
bootId,
|
|
315
|
+
startOrder: linuxStartTime,
|
|
316
|
+
});
|
|
317
|
+
this.logger.debug({
|
|
318
|
+
workspaceId: options.workspaceId,
|
|
319
|
+
linuxPid,
|
|
320
|
+
linuxPgid: managed.wsl.linuxPgid,
|
|
321
|
+
linuxStartTime: managed.wsl.leaderStartTime,
|
|
322
|
+
}, "Captured WSL OpenCode process identity");
|
|
323
|
+
resolveLaunchIfIdentified();
|
|
324
|
+
}
|
|
325
|
+
else {
|
|
326
|
+
failWslIdentityCapture("WSL launcher returned an incomplete Linux PID identity");
|
|
160
327
|
}
|
|
161
328
|
continue;
|
|
162
329
|
}
|
|
@@ -167,13 +334,14 @@ export class WorkspaceRuntime {
|
|
|
167
334
|
this.emitLog(options.workspaceId, "info", line);
|
|
168
335
|
if (!portFound) {
|
|
169
336
|
const portMatch = line.match(/opencode server listening on http:\/\/.+:(\d+)/i);
|
|
170
|
-
if (portMatch) {
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
337
|
+
if (portMatch && !launchSettled) {
|
|
338
|
+
pendingPort = parseInt(portMatch[1], 10);
|
|
339
|
+
if (managed.wsl && (!managed.wsl.leaderStartTime || !managed.wsl.bootId)) {
|
|
340
|
+
failWslIdentityCapture("WSL process reported a port before its Linux identity");
|
|
341
|
+
}
|
|
342
|
+
else {
|
|
343
|
+
resolveLaunchIfIdentified();
|
|
344
|
+
}
|
|
177
345
|
}
|
|
178
346
|
}
|
|
179
347
|
}
|
|
@@ -196,152 +364,317 @@ export class WorkspaceRuntime {
|
|
|
196
364
|
});
|
|
197
365
|
});
|
|
198
366
|
}
|
|
199
|
-
|
|
367
|
+
beginFailedLaunchCleanup(workspaceId, managed) {
|
|
368
|
+
managed.identityCaptureFailed = true;
|
|
369
|
+
void this.stop(workspaceId).catch((error) => {
|
|
370
|
+
this.logger.warn({ workspaceId, err: error }, "Unpublished workspace cleanup remains pending");
|
|
371
|
+
});
|
|
372
|
+
if (managed.child.exitCode === null && managed.child.signalCode === null) {
|
|
373
|
+
try {
|
|
374
|
+
managed.child.kill("SIGTERM");
|
|
375
|
+
}
|
|
376
|
+
catch (error) {
|
|
377
|
+
this.logger.debug({ workspaceId, err: error }, "Failed initial live-child cleanup signal");
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
stop(workspaceId) {
|
|
200
382
|
const managed = this.processes.get(workspaceId);
|
|
201
383
|
if (!managed)
|
|
202
|
-
return;
|
|
384
|
+
return Promise.resolve();
|
|
385
|
+
if (managed.stopPromise) {
|
|
386
|
+
return managed.stopPromise;
|
|
387
|
+
}
|
|
388
|
+
const stopPromise = this.stopManagedProcess(workspaceId, managed);
|
|
389
|
+
managed.stopPromise = stopPromise;
|
|
390
|
+
void stopPromise.finally(() => {
|
|
391
|
+
if (managed.stopPromise === stopPromise)
|
|
392
|
+
managed.stopPromise = undefined;
|
|
393
|
+
}).catch(() => undefined);
|
|
394
|
+
return stopPromise;
|
|
395
|
+
}
|
|
396
|
+
stopManagedProcess(workspaceId, managed) {
|
|
203
397
|
managed.requestedStop = true;
|
|
204
|
-
|
|
398
|
+
managed.cancelLaunch?.();
|
|
399
|
+
managed.cancelLaunch = undefined;
|
|
205
400
|
this.logger.info({ workspaceId }, "Stopping OpenCode process");
|
|
401
|
+
if (managed.processKind === "windows-wrapper")
|
|
402
|
+
return this.stopOwnedWindowsProcess(workspaceId, managed);
|
|
403
|
+
const { child } = managed;
|
|
206
404
|
const pid = child.pid;
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
const
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
405
|
+
const failures = [];
|
|
406
|
+
const wrapperExited = () => child.exitCode !== null || child.signalCode !== null;
|
|
407
|
+
const hasWslIdentity = () => Boolean(managed.wsl?.linuxPid && managed.wsl.linuxPgid && managed.wsl.leaderStartTime && managed.wsl.bootId);
|
|
408
|
+
const trackedTarget = () => managed.wsl && hasWslIdentity() ? managed.wsl : managed.targets;
|
|
409
|
+
const trackedLeader = () => {
|
|
410
|
+
if (!managed.wsl || !hasWslIdentity())
|
|
411
|
+
return managed.targets?.leader;
|
|
412
|
+
return {
|
|
413
|
+
pid: managed.wsl.linuxPid,
|
|
414
|
+
parentPid: 0,
|
|
415
|
+
groupId: managed.wsl.linuxPgid,
|
|
416
|
+
startTime: managed.wsl.leaderStartTime,
|
|
417
|
+
bootId: managed.wsl.bootId,
|
|
418
|
+
startOrder: managed.wsl.leaderStartTime,
|
|
419
|
+
};
|
|
420
|
+
};
|
|
421
|
+
const refreshTargets = () => {
|
|
422
|
+
const target = trackedTarget();
|
|
423
|
+
const leader = trackedLeader();
|
|
424
|
+
const groupId = managed.wsl && hasWslIdentity() ? managed.wsl.linuxPgid : target.groupId;
|
|
425
|
+
const portableGroupId = this.platform !== "linux" && this.platform !== "win32" &&
|
|
426
|
+
target.groupOwnershipRetained && !target.groupGoneConfirmed ? groupId : undefined;
|
|
427
|
+
const snapshot = managed.wsl && hasWslIdentity()
|
|
428
|
+
? probeWslProcesses(this.spawnCommand, managed.wsl.distro, this.stopCommandTimeoutMs)
|
|
429
|
+
: this.platform === "win32"
|
|
430
|
+
? probeWindowsProcesses(this.spawnCommand, this.stopCommandTimeoutMs)
|
|
431
|
+
: probePosixProcesses(this.spawnCommand, this.stopCommandTimeoutMs, this.platform, this.platform === "linux"
|
|
432
|
+
? undefined
|
|
433
|
+
: { pids: [leader?.pid, ...target.members.keys()].filter((value) => Boolean(value)), groupId: portableGroupId });
|
|
434
|
+
if (!snapshot.ok) {
|
|
435
|
+
const platformName = managed.wsl && hasWslIdentity() ? "WSL" : this.platform === "win32" ? "Windows" : "POSIX";
|
|
436
|
+
failures.push(`${platformName} identity discovery failed: ${snapshot.error}`);
|
|
437
|
+
return { snapshot, aliveMembers: [] };
|
|
217
438
|
}
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
439
|
+
const leaderMatches = sameProcess(leader, leader ? snapshot.processes.get(leader.pid) : undefined);
|
|
440
|
+
const groupLeader = groupId ? snapshot.processes.get(groupId) : undefined;
|
|
441
|
+
const groupWasReused = Boolean(groupLeader && !sameProcess(leader, groupLeader));
|
|
442
|
+
const retainedAnchorMatches = Boolean(portableGroupId && Array.from(target.members.values()).some((identity) => sameProcess(identity, snapshot.processes.get(identity.pid))));
|
|
443
|
+
if (portableGroupId && groupWasReused) {
|
|
444
|
+
target.groupGoneConfirmed = true;
|
|
445
|
+
target.groupOwnershipUncertain = false;
|
|
446
|
+
}
|
|
447
|
+
for (const process of snapshot.processes.values()) {
|
|
448
|
+
const sameBoot = !leader?.bootId || process.bootId === leader.bootId;
|
|
449
|
+
const withinDispatch = (this.platform === "linux" || Boolean(managed.wsl)) && Boolean(target.dispatchCutoff && sameBoot && startedNoLaterThan(process, target.dispatchCutoff));
|
|
450
|
+
const withinRetainedPortableGroup = Boolean(portableGroupId && !groupWasReused && retainedAnchorMatches);
|
|
451
|
+
if (groupId && process.groupId === groupId && (leaderMatches || withinRetainedPortableGroup || (!groupWasReused && withinDispatch))) {
|
|
452
|
+
target.members.set(process.pid, process);
|
|
222
453
|
}
|
|
223
|
-
this.logger.debug({ workspaceId, pid, err }, "Failed to signal POSIX process group");
|
|
224
|
-
return false;
|
|
225
454
|
}
|
|
455
|
+
if (portableGroupId && !groupWasReused) {
|
|
456
|
+
const groupPresent = Array.from(snapshot.processes.values()).some((process) => process.groupId === portableGroupId);
|
|
457
|
+
if (!groupPresent) {
|
|
458
|
+
target.groupGoneConfirmed = true;
|
|
459
|
+
target.groupOwnershipUncertain = false;
|
|
460
|
+
}
|
|
461
|
+
else if (!leaderMatches && !retainedAnchorMatches) {
|
|
462
|
+
target.groupOwnershipUncertain = true;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
if (this.platform === "win32" && !managed.wsl && leaderMatches && leader) {
|
|
466
|
+
for (const descendant of descendantsOf(snapshot.processes, leader.pid))
|
|
467
|
+
target.members.set(descendant.pid, descendant);
|
|
468
|
+
}
|
|
469
|
+
const aliveMembers = Array.from(target.members.values()).filter((identity) => sameProcess(identity, snapshot.processes.get(identity.pid)));
|
|
470
|
+
return { snapshot, aliveMembers };
|
|
226
471
|
};
|
|
227
|
-
const
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
return
|
|
472
|
+
const usesTokenCleanup = () => this.platform === "linux" || Boolean(managed.wsl);
|
|
473
|
+
const refreshTokenTargets = () => {
|
|
474
|
+
if (!usesTokenCleanup())
|
|
475
|
+
return;
|
|
476
|
+
const snapshot = probeLaunchCleanupToken(this.spawnCommand, managed.cleanupToken, this.stopCommandTimeoutMs, managed.wsl?.distro);
|
|
477
|
+
if (!snapshot.ok)
|
|
478
|
+
failures.push(`${managed.wsl ? "WSL" : "Linux"} launch-token discovery failed: ${snapshot.error}`);
|
|
479
|
+
else
|
|
480
|
+
for (const identity of snapshot.processes.values())
|
|
481
|
+
trackedTarget().members.set(identity.pid, identity);
|
|
482
|
+
return snapshot;
|
|
483
|
+
};
|
|
484
|
+
const recordSignalResult = (result, target, name, signal) => {
|
|
485
|
+
const identities = result.ok ? result.signaled : (result.observed ?? []);
|
|
486
|
+
for (const identity of identities)
|
|
487
|
+
target.members.set(identity.pid, identity);
|
|
488
|
+
if (!result.ok)
|
|
489
|
+
failures.push(`${name} guarded ${signal} failed: ${result.error}`);
|
|
490
|
+
else {
|
|
491
|
+
if (result.matched && !result.signalSent)
|
|
492
|
+
failures.push(`${name} guarded ${signal} matched but sent no signal`);
|
|
493
|
+
if (result.cutoff)
|
|
494
|
+
target.dispatchCutoff = result.cutoff;
|
|
231
495
|
}
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
496
|
+
};
|
|
497
|
+
const sendStopSignal = (signal) => {
|
|
498
|
+
if (!pid)
|
|
499
|
+
failures.push(`${signal} was not sent because the process PID is unavailable`);
|
|
500
|
+
if (pid && wrapperExited() && this.platform !== "linux" && this.platform !== "win32")
|
|
501
|
+
refreshTargets();
|
|
502
|
+
let signaledOwnedGroup = false;
|
|
503
|
+
if (pid && managed.identityCaptureFailed && this.platform !== "linux" && this.platform !== "win32" && !wrapperExited()) {
|
|
504
|
+
const result = signalOwnedPosixProcessGroup(this.spawnCommand, pid, signal, this.stopCommandTimeoutMs);
|
|
505
|
+
recordSignalResult(result, managed.targets, "owned POSIX group", signal);
|
|
506
|
+
const leader = result.ok && result.matched ? result.signaled.find((identity) => identity.pid === pid) : undefined;
|
|
507
|
+
if (leader)
|
|
508
|
+
Object.assign(managed.targets, { leader, groupId: pid });
|
|
509
|
+
refreshTargets();
|
|
510
|
+
signaledOwnedGroup = true;
|
|
511
|
+
}
|
|
512
|
+
if (pid && !signaledOwnedGroup) {
|
|
513
|
+
const target = trackedTarget();
|
|
514
|
+
const groupId = managed.wsl && hasWslIdentity() ? managed.wsl.linuxPgid : target.groupId;
|
|
515
|
+
const request = {
|
|
516
|
+
leader: trackedLeader(), groupId, members: [...target.members.values()], signal,
|
|
517
|
+
allowLeaderlessGroup: this.platform !== "linux" && this.platform !== "win32" &&
|
|
518
|
+
Boolean(target.groupOwnershipRetained && !target.groupGoneConfirmed && wrapperExited()),
|
|
519
|
+
cleanupToken: this.platform !== "linux" && this.platform !== "win32" ? managed.cleanupToken : undefined,
|
|
520
|
+
};
|
|
521
|
+
const result = managed.wsl && hasWslIdentity()
|
|
522
|
+
? signalWslProcesses(this.spawnCommand, managed.wsl.distro, request, this.stopCommandTimeoutMs)
|
|
523
|
+
: this.platform === "win32"
|
|
524
|
+
? signalWindowsProcesses(this.spawnCommand, request, this.stopCommandTimeoutMs)
|
|
525
|
+
: signalPosixProcesses(this.spawnCommand, request, this.stopCommandTimeoutMs, this.platform);
|
|
526
|
+
recordSignalResult(result, target, managed.wsl && hasWslIdentity() ? "WSL" : this.platform === "win32" ? "Windows" : "POSIX", signal);
|
|
527
|
+
refreshTargets();
|
|
528
|
+
}
|
|
529
|
+
if (usesTokenCleanup()) {
|
|
530
|
+
const result = signalLaunchCleanupToken(this.spawnCommand, managed.cleanupToken, signal, this.stopCommandTimeoutMs, managed.wsl?.distro);
|
|
531
|
+
const name = managed.wsl ? "WSL" : "Linux";
|
|
532
|
+
if (!result.ok)
|
|
533
|
+
failures.push(`${name} launch-token ${signal} failed: ${result.error}`);
|
|
534
|
+
else {
|
|
535
|
+
if (result.targets.length > 0 && !result.signalSent)
|
|
536
|
+
failures.push(`${name} launch-token ${signal} matched but sent no signal`);
|
|
537
|
+
for (const identity of result.targets)
|
|
538
|
+
trackedTarget().members.set(identity.pid, identity);
|
|
236
539
|
}
|
|
237
|
-
|
|
238
|
-
return false;
|
|
540
|
+
refreshTokenTargets();
|
|
239
541
|
}
|
|
240
542
|
};
|
|
241
|
-
const
|
|
242
|
-
const
|
|
243
|
-
|
|
244
|
-
|
|
543
|
+
const probeLiveness = () => {
|
|
544
|
+
const refreshed = pid ? refreshTargets() : undefined;
|
|
545
|
+
const tokenSnapshot = refreshTokenTargets();
|
|
546
|
+
if (tokenSnapshot && !tokenSnapshot.ok) {
|
|
547
|
+
return { state: "unknown", detail: `${managed.wsl ? "WSL Linux" : "Linux"} launch-token cleanup could not be confirmed` };
|
|
245
548
|
}
|
|
246
|
-
|
|
247
|
-
const
|
|
248
|
-
|
|
249
|
-
if (exitCode === 0) {
|
|
250
|
-
return true;
|
|
251
|
-
}
|
|
252
|
-
// If the PID is already gone, treat it as success.
|
|
253
|
-
const stderr = (result.stderr ?? "").toString().toLowerCase();
|
|
254
|
-
const stdout = (result.stdout ?? "").toString().toLowerCase();
|
|
255
|
-
const combined = `${stdout}\n${stderr}`;
|
|
256
|
-
if (combined.includes("not found") || combined.includes("no running instance") || combined.includes("process") && combined.includes("not")) {
|
|
257
|
-
return true;
|
|
258
|
-
}
|
|
259
|
-
this.logger.debug({ workspaceId, pid, exitCode, stderr: result.stderr, stdout: result.stdout }, "taskkill failed");
|
|
260
|
-
return false;
|
|
549
|
+
if (refreshed && !refreshed.snapshot.ok && (managed.targets?.leader || !tokenSnapshot?.ok)) {
|
|
550
|
+
const name = managed.wsl ? "WSL Linux" : this.platform === "win32" ? "Windows" : "POSIX";
|
|
551
|
+
return { state: "unknown", detail: `${name} target identity could not be confirmed` };
|
|
261
552
|
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
return false;
|
|
553
|
+
if (managed.identityCaptureFailed && this.platform === "win32" && !managed.wsl) {
|
|
554
|
+
return { state: "unknown", detail: "Windows cleanup cannot prove exact launch ownership without a Job Object" };
|
|
265
555
|
}
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
if (process.platform !== "win32" || !managed.wsl?.linuxPid) {
|
|
269
|
-
return false;
|
|
556
|
+
if (managed.identityCaptureFailed && managed.wsl && !managed.targets?.leader && !wrapperExited()) {
|
|
557
|
+
return { state: "unknown", detail: "the unidentified Windows WSL wrapper is still alive" };
|
|
270
558
|
}
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
const result = spawnSync(spec.command, spec.args, { encoding: "utf8" });
|
|
274
|
-
const exitCode = result.status;
|
|
275
|
-
if (exitCode === 0) {
|
|
276
|
-
return true;
|
|
277
|
-
}
|
|
278
|
-
const stderr = (result.stderr ?? "").toString().toLowerCase();
|
|
279
|
-
const stdout = (result.stdout ?? "").toString().toLowerCase();
|
|
280
|
-
const combined = `${stdout}\n${stderr}`;
|
|
281
|
-
if (combined.includes("no such process") || combined.includes("not found")) {
|
|
282
|
-
return true;
|
|
283
|
-
}
|
|
284
|
-
this.logger.debug({ workspaceId, pid, linuxPid: managed.wsl.linuxPid, distro: managed.wsl.distro, exitCode, stderr: result.stderr, stdout: result.stdout }, "WSL kill failed");
|
|
285
|
-
return false;
|
|
559
|
+
if (trackedTarget().groupOwnershipUncertain) {
|
|
560
|
+
return { state: "unknown", detail: "the retained POSIX process group no longer has a verified identity anchor" };
|
|
286
561
|
}
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
562
|
+
if (trackedTarget().members.size === 0) {
|
|
563
|
+
if (tokenSnapshot?.ok && tokenSnapshot.processes.size === 0)
|
|
564
|
+
return { state: "gone", detail: "no process carries the unpublished launch token" };
|
|
565
|
+
return { state: "unknown", detail: pid ? "the original process identity was not captured" : "the target PID is unavailable" };
|
|
566
|
+
}
|
|
567
|
+
if ((refreshed?.aliveMembers.length ?? 0) === 0 && (!tokenSnapshot?.ok || tokenSnapshot.processes.size === 0)) {
|
|
568
|
+
return { state: "gone", detail: "all tracked original process identities are gone" };
|
|
290
569
|
}
|
|
570
|
+
const name = managed.wsl && hasWslIdentity() ? "WSL Linux process group" : this.platform === "win32" ? "Windows process tree" : "POSIX process group";
|
|
571
|
+
return { state: "alive", detail: `the tracked original ${name} is still alive` };
|
|
291
572
|
};
|
|
292
|
-
const
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
573
|
+
const stopped = () => probeLiveness().state === "gone" ? true : undefined;
|
|
574
|
+
const totalTimeoutMs = this.gracefulStopTimeoutMs + this.forcedStopTimeoutMs;
|
|
575
|
+
return this.runBoundedStop(workspaceId, managed, {
|
|
576
|
+
start: () => {
|
|
577
|
+
this.logger.debug({ workspaceId, pid, detached: this.platform !== "win32" }, "Sending SIGTERM to workspace process (tree/group)");
|
|
578
|
+
sendStopSignal("SIGTERM");
|
|
579
|
+
return stopped();
|
|
580
|
+
},
|
|
581
|
+
exit: stopped,
|
|
582
|
+
error: (error) => { failures.push(`child process error while stopping: ${error.message}`); },
|
|
583
|
+
escalate: () => {
|
|
584
|
+
const liveness = probeLiveness();
|
|
585
|
+
if (liveness.state === "gone")
|
|
586
|
+
return true;
|
|
587
|
+
this.logger.warn({ workspaceId, pid }, "Process did not stop after SIGTERM, escalating");
|
|
588
|
+
sendStopSignal("SIGKILL");
|
|
589
|
+
},
|
|
590
|
+
deadline: () => {
|
|
591
|
+
const liveness = probeLiveness();
|
|
592
|
+
if (liveness.state === "gone")
|
|
593
|
+
return true;
|
|
594
|
+
const prefix = wrapperExited() ? "the wrapper exited but " : "";
|
|
595
|
+
return new WorkspaceStopTimeoutError(workspaceId, pid, totalTimeoutMs, `${prefix}${liveness.detail}`, failures);
|
|
596
|
+
},
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
stopOwnedWindowsProcess(workspaceId, managed) {
|
|
600
|
+
const { child } = managed;
|
|
601
|
+
const pid = child.pid;
|
|
602
|
+
const failures = (managed.windowsTreeCleanupFailures ??= []);
|
|
603
|
+
const outcome = () => managed.windowsTreeCleanupConfirmed
|
|
604
|
+
? true
|
|
605
|
+
: new WorkspaceWindowsTreeCleanupIncompleteError(workspaceId, pid, failures);
|
|
606
|
+
const stopChild = (force) => {
|
|
607
|
+
if (child.exitCode !== null || child.signalCode !== null)
|
|
608
|
+
return;
|
|
609
|
+
if (!pid) {
|
|
610
|
+
failures.push(`${force ? "forced" : "graceful"} stop was not sent because the process PID is unavailable`);
|
|
299
611
|
return;
|
|
300
612
|
}
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
613
|
+
const args = ["/PID", String(pid), "/T", ...(force ? ["/F"] : [])];
|
|
614
|
+
try {
|
|
615
|
+
const result = this.spawnCommand("taskkill.exe", args, { encoding: "utf8", timeout: this.stopCommandTimeoutMs });
|
|
616
|
+
if (result.status === 0)
|
|
617
|
+
managed.windowsTreeCleanupConfirmed = true;
|
|
618
|
+
else {
|
|
619
|
+
const detail = result.error?.message || String(result.stderr ?? result.stdout ?? "").trim() || `exit code ${result.status}`;
|
|
620
|
+
failures.push(`taskkill ${force ? "/T /F" : "/T"} failed: ${detail}`);
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
catch (error) {
|
|
624
|
+
failures.push(`taskkill ${force ? "/T /F" : "/T"} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
306
625
|
}
|
|
307
626
|
};
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
627
|
+
const totalTimeoutMs = this.gracefulStopTimeoutMs + this.forcedStopTimeoutMs;
|
|
628
|
+
return this.runBoundedStop(workspaceId, managed, {
|
|
629
|
+
start: () => {
|
|
630
|
+
if (child.exitCode !== null || child.signalCode !== null)
|
|
631
|
+
return outcome();
|
|
632
|
+
this.logger.debug({ workspaceId, pid }, "Stopping owned Windows workspace wrapper tree");
|
|
633
|
+
stopChild(false);
|
|
634
|
+
},
|
|
635
|
+
exit: outcome,
|
|
636
|
+
error: (error) => {
|
|
637
|
+
failures.push(`child process error while stopping: ${error.message}`);
|
|
638
|
+
return error;
|
|
639
|
+
},
|
|
640
|
+
escalate: () => {
|
|
641
|
+
this.logger.warn({ workspaceId, pid }, "Owned Windows process did not stop after the graceful attempt, escalating");
|
|
642
|
+
stopChild(true);
|
|
643
|
+
},
|
|
644
|
+
deadline: () => new WorkspaceStopTimeoutError(workspaceId, pid, totalTimeoutMs, child.exitCode !== null || child.signalCode !== null
|
|
645
|
+
? "taskkill did not confirm tree cleanup before the owned Windows wrapper exited"
|
|
646
|
+
: "the owned Windows wrapper did not emit exit or error after tree termination", failures),
|
|
647
|
+
});
|
|
648
|
+
}
|
|
649
|
+
runBoundedStop(workspaceId, managed, actions) {
|
|
650
|
+
const { child } = managed;
|
|
651
|
+
return new Promise((resolve, reject) => {
|
|
652
|
+
let settled = false;
|
|
653
|
+
const timers = [];
|
|
654
|
+
const finish = (outcome) => {
|
|
655
|
+
if (settled || !outcome)
|
|
656
|
+
return;
|
|
657
|
+
settled = true;
|
|
311
658
|
child.removeListener("exit", onExit);
|
|
312
659
|
child.removeListener("error", onError);
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
660
|
+
for (const timer of timers)
|
|
661
|
+
this.cancelTimeout(timer);
|
|
662
|
+
if (outcome instanceof Error)
|
|
663
|
+
reject(outcome);
|
|
664
|
+
else {
|
|
665
|
+
if (this.processes.get(workspaceId) === managed)
|
|
666
|
+
this.processes.delete(workspaceId);
|
|
667
|
+
managed.finalizeExit?.(child.exitCode, child.signalCode);
|
|
668
|
+
resolve();
|
|
316
669
|
}
|
|
317
670
|
};
|
|
318
|
-
const onExit = () =>
|
|
319
|
-
|
|
320
|
-
resolve();
|
|
321
|
-
};
|
|
322
|
-
const onError = (error) => {
|
|
323
|
-
cleanup();
|
|
324
|
-
reject(error);
|
|
325
|
-
};
|
|
326
|
-
if (isAlreadyExited()) {
|
|
327
|
-
this.logger.debug({ workspaceId, exitCode: child.exitCode, signal: child.signalCode }, "Process already exited");
|
|
328
|
-
cleanup();
|
|
329
|
-
resolve();
|
|
330
|
-
return;
|
|
331
|
-
}
|
|
671
|
+
const onExit = () => finish(actions.exit());
|
|
672
|
+
const onError = (error) => finish(actions.error(error));
|
|
332
673
|
child.once("exit", onExit);
|
|
333
|
-
child.
|
|
334
|
-
this.
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
escalationTimer = null;
|
|
338
|
-
if (isAlreadyExited()) {
|
|
339
|
-
this.logger.debug({ workspaceId, pid }, "Workspace exited before SIGKILL escalation");
|
|
340
|
-
return;
|
|
341
|
-
}
|
|
342
|
-
this.logger.warn({ workspaceId, pid }, "Process did not stop after SIGTERM, escalating");
|
|
343
|
-
sendStopSignal("SIGKILL");
|
|
344
|
-
}, 2000);
|
|
674
|
+
child.on("error", onError);
|
|
675
|
+
timers.push(this.scheduleTimeout(() => finish(actions.escalate()), this.gracefulStopTimeoutMs));
|
|
676
|
+
timers.push(this.scheduleTimeout(() => finish(actions.deadline()), this.gracefulStopTimeoutMs + this.forcedStopTimeoutMs));
|
|
677
|
+
finish(actions.start());
|
|
345
678
|
});
|
|
346
679
|
}
|
|
347
680
|
emitLog(workspaceId, level, message) {
|