@neuralnomads/codenomad-dev 0.18.0-dev-20260715-07e8ce68 → 0.18.0-dev-20260716-40cee071
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/events/bus.js +13 -0
- package/dist/events/bus.test.js +37 -0
- package/dist/index.js +33 -56
- package/dist/index.test.js +32 -0
- package/dist/server/__tests__/remote-proxy.test.js +102 -6
- package/dist/server/http-server.js +2 -0
- package/dist/server/remote-proxy.js +96 -9
- package/dist/server/routes/usage.js +18 -0
- package/dist/server/routes/usage.test.js +26 -0
- package/dist/server/routes/workspaces.js +32 -1
- package/dist/server/routes/workspaces.test.js +75 -0
- package/dist/settings/binaries.js +4 -1
- package/dist/settings/binaries.test.js +24 -0
- package/dist/shutdown.js +75 -0
- package/dist/shutdown.test.js +111 -0
- 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 +111 -0
- package/dist/usage/providers/special.js +148 -0
- package/dist/usage/service.js +83 -0
- package/dist/usage/service.test.js +59 -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 +177 -25
- package/dist/workspaces/launch-cleanup.js +132 -0
- package/dist/workspaces/launch-cleanup.test.js +33 -0
- package/dist/workspaces/manager.js +393 -135
- package/dist/workspaces/manager.test.js +318 -0
- package/dist/workspaces/process-identity.js +408 -0
- package/dist/workspaces/process-identity.test.js +165 -0
- package/dist/workspaces/runtime.js +567 -122
- package/dist/workspaces/runtime.test.js +603 -0
- package/dist/workspaces/spawn.js +86 -15
- package/package.json +1 -1
- package/public/assets/{FilesTab-EPvldvn1.js → FilesTab-BjztpSdj.js} +2 -2
- package/public/assets/{GitChangesTab-ofjovmv2.js → GitChangesTab-B9XraSoR.js} +2 -2
- package/public/assets/{SplitFilePanel-CyoPkcLd.js → SplitFilePanel-Cu_5-Z-E.js} +1 -1
- package/public/assets/StatusTab-D_IE79r-.js +1 -0
- package/public/assets/{align-justify-Bcf1-ZOl.js → align-justify-BKS9gyRk.js} +1 -1
- package/public/assets/{bundle-full-D5dzvToA.js → bundle-full-CXGXXlzR.js} +1 -1
- package/public/assets/{diff-viewer-DViXCI-4.js → diff-viewer-CSNOYoEB.js} +1 -1
- package/public/assets/{git-diff-vendor-CSgooKT_.js → git-diff-vendor-CYS3ApzA.js} +1 -1
- package/public/assets/index-B3YjNCh4.js +1 -0
- package/public/assets/index-B3ZD2_SU.js +1 -0
- package/public/assets/index-Bh2ofaQo.js +1 -0
- package/public/assets/index-CM0c9xRZ.js +1 -0
- package/public/assets/index-CdDxouJl.js +2 -0
- package/public/assets/index-D06Y2cFq.js +1 -0
- package/public/assets/{index-lf4nUOU1.js → index-DVc4ls8c.js} +1 -1
- package/public/assets/index-PmE51vPh.js +1 -0
- package/public/assets/{index-BMvFMsuy.css → index-Qj63IiSj.css} +1 -1
- package/public/assets/index-VY_zwmsG.js +1 -0
- package/public/assets/index-qiiH7egV.js +1 -0
- package/public/assets/{index-UbL8tz_V.js → index-sLe9hEfQ.js} +1 -1
- package/public/assets/{loading-CZ_tt3h0.js → loading-CDmt9OJU.js} +1 -1
- package/public/assets/main-CTN6Wwz1.js +68 -0
- package/public/assets/{markdown-G11aN6hz.js → markdown-1ZLSxCFT.js} +55 -44
- package/public/assets/monaco-viewer-D6JgH76W.js +26 -0
- package/public/assets/{tool-call-BsSXWErm.js → tool-call-CyXb63LH.js} +32 -32
- package/public/assets/{unified-picker-BRNI3UvE.js → unified-picker-DCCdSVwI.js} +1 -1
- package/public/assets/{wrap-text-B7up-uv7.js → wrap-text-pNMdTIq3.js} +1 -1
- package/public/index.html +5 -5
- package/public/loading.html +5 -5
- package/public/sw.js +1 -1
- package/public/assets/StatusTab-Bgu1Fh24.js +0 -1
- package/public/assets/index-3KsjbWGP.js +0 -1
- package/public/assets/index-B0WK8-cF.js +0 -1
- package/public/assets/index-BDv_iVtj.js +0 -1
- package/public/assets/index-BjxZvyb9.js +0 -2
- package/public/assets/index-BleKf9Nj.js +0 -1
- package/public/assets/index-CiIQ43NW.js +0 -1
- package/public/assets/index-DBquqL6Q.js +0 -1
- package/public/assets/index-yf9zolv4.js +0 -1
- package/public/assets/index-ypaL7i_s.js +0 -1
- package/public/assets/main-CAkg_fp_.js +0 -68
- package/public/assets/monaco-viewer-CZefBfct.js +0 -26
|
@@ -1,7 +1,10 @@
|
|
|
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, probePosixProcesses, probeWindowsProcesses, probeWslProcesses, sameProcess, signalPosixProcesses, signalOwnedPosixProcessGroup, signalWindowsProcesses, signalWslProcesses, startedNoLaterThan, } from "./process-identity";
|
|
7
|
+
import { LAUNCH_CLEANUP_TOKEN_ENV, probeLaunchCleanupToken, signalLaunchCleanupToken, } from "./launch-cleanup";
|
|
5
8
|
const SENSITIVE_ENV_KEY = /(PASSWORD|TOKEN|SECRET)/i;
|
|
6
9
|
const WSL_PID_MARKER = "__CODENOMAD_WSL_PID__:";
|
|
7
10
|
function redactEnvironment(env) {
|
|
@@ -15,21 +18,68 @@ function redactEnvironment(env) {
|
|
|
15
18
|
}
|
|
16
19
|
return redacted;
|
|
17
20
|
}
|
|
21
|
+
export class WorkspaceStopTimeoutError extends Error {
|
|
22
|
+
constructor(workspaceId, pid, timeoutMs, liveness, failures) {
|
|
23
|
+
const failureDetails = failures.length > 0 ? ` Stop failures: ${failures.join("; ")}.` : "";
|
|
24
|
+
super(`Workspace ${workspaceId} process ${pid ?? "with unknown PID"} did not stop within ${timeoutMs}ms; ${liveness}.` +
|
|
25
|
+
`${failureDetails} The stop can be retried.`);
|
|
26
|
+
this.code = "WORKSPACE_STOP_TIMEOUT";
|
|
27
|
+
this.retryable = true;
|
|
28
|
+
this.name = "WorkspaceStopTimeoutError";
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export class WorkspaceWindowsTreeCleanupIncompleteError extends Error {
|
|
32
|
+
constructor(workspaceId, pid, failures) {
|
|
33
|
+
const failureDetails = failures.length > 0 ? ` Stop failures: ${failures.join("; ")}.` : "";
|
|
34
|
+
super(`Workspace ${workspaceId} Windows wrapper ${pid ?? "with unknown PID"} exited before taskkill confirmed process-tree cleanup.` +
|
|
35
|
+
`${failureDetails} The workspace record was retained because cleanup is incomplete.`);
|
|
36
|
+
this.code = "WORKSPACE_WINDOWS_TREE_CLEANUP_INCOMPLETE";
|
|
37
|
+
this.retryable = true;
|
|
38
|
+
this.name = "WorkspaceWindowsTreeCleanupIncompleteError";
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export class WorkspaceRuntimeLaunchCancelledError extends Error {
|
|
42
|
+
constructor(workspaceId) {
|
|
43
|
+
super(`Workspace ${workspaceId} runtime launch was cancelled`);
|
|
44
|
+
this.code = "WORKSPACE_RUNTIME_LAUNCH_CANCELLED";
|
|
45
|
+
this.name = "WorkspaceRuntimeLaunchCancelledError";
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export class WorkspaceRuntimeIdentityCaptureError extends Error {
|
|
49
|
+
constructor(workspaceId, detail) {
|
|
50
|
+
super(`Workspace ${workspaceId} process identity capture failed: ${detail}`);
|
|
51
|
+
this.code = "WORKSPACE_RUNTIME_IDENTITY_CAPTURE_FAILED";
|
|
52
|
+
this.name = "WorkspaceRuntimeIdentityCaptureError";
|
|
53
|
+
}
|
|
54
|
+
}
|
|
18
55
|
export class WorkspaceRuntime {
|
|
19
|
-
constructor(eventBus, logger) {
|
|
56
|
+
constructor(eventBus, logger, options = {}) {
|
|
20
57
|
this.eventBus = eventBus;
|
|
21
58
|
this.logger = logger;
|
|
22
59
|
this.processes = new Map();
|
|
60
|
+
this.platform = options.platform ?? process.platform;
|
|
61
|
+
this.spawnProcess = options.spawn ?? spawn;
|
|
62
|
+
this.spawnCommand = options.spawnSync ?? spawnSync;
|
|
63
|
+
this.scheduleTimeout = options.setTimeout ?? setTimeout;
|
|
64
|
+
this.cancelTimeout = options.clearTimeout ?? clearTimeout;
|
|
65
|
+
this.gracefulStopTimeoutMs = Math.max(0, options.gracefulStopTimeoutMs ?? 2000);
|
|
66
|
+
this.forcedStopTimeoutMs = Math.max(0, options.forcedStopTimeoutMs ?? 2000);
|
|
67
|
+
this.stopCommandTimeoutMs = Math.max(1, options.stopCommandTimeoutMs ?? 1000);
|
|
23
68
|
}
|
|
24
69
|
async launch(options) {
|
|
25
70
|
this.validateFolder(options.folder);
|
|
26
71
|
const logLevel = typeof options.logLevel === "string" ? options.logLevel.toUpperCase() : "DEBUG";
|
|
27
72
|
const args = ["serve", "--port", "0", "--print-logs", "--log-level", logLevel];
|
|
28
|
-
const
|
|
73
|
+
const cleanupToken = randomBytes(32).toString("hex");
|
|
74
|
+
const env = { ...process.env, ...(options.environment ?? {}), [LAUNCH_CLEANUP_TOKEN_ENV]: cleanupToken };
|
|
29
75
|
let exitResolve = null;
|
|
30
76
|
const exitPromise = new Promise((resolveExit) => {
|
|
31
77
|
exitResolve = resolveExit;
|
|
32
78
|
});
|
|
79
|
+
let cancellationResolve = null;
|
|
80
|
+
const cancellationPromise = new Promise((resolveCancellation) => {
|
|
81
|
+
cancellationResolve = resolveCancellation;
|
|
82
|
+
});
|
|
33
83
|
// Store recent output for debugging - keep last 50 lines from each stream
|
|
34
84
|
const MAX_OUTPUT_LINES = 50;
|
|
35
85
|
const recentStdout = [];
|
|
@@ -47,12 +97,13 @@ export class WorkspaceRuntime {
|
|
|
47
97
|
return combined.join("\n");
|
|
48
98
|
};
|
|
49
99
|
return new Promise((resolve, reject) => {
|
|
50
|
-
const propagatedEnvKeys = Object.keys(options.environment ?? {});
|
|
100
|
+
const propagatedEnvKeys = [...Object.keys(options.environment ?? {}), LAUNCH_CLEANUP_TOKEN_ENV];
|
|
51
101
|
const spec = buildSpawnSpec(options.binaryPath, args, {
|
|
52
102
|
cwd: options.folder,
|
|
53
103
|
env,
|
|
54
104
|
propagateEnvKeys: propagatedEnvKeys,
|
|
55
105
|
wslPidMarker: WSL_PID_MARKER,
|
|
106
|
+
platform: this.platform,
|
|
56
107
|
});
|
|
57
108
|
const commandLine = [spec.command, ...spec.args].join(" ");
|
|
58
109
|
this.logger.info({
|
|
@@ -70,23 +121,62 @@ export class WorkspaceRuntime {
|
|
|
70
121
|
workspaceId: options.workspaceId,
|
|
71
122
|
env: redactEnvironment(env),
|
|
72
123
|
}, "OpenCode spawn environment");
|
|
73
|
-
const detached =
|
|
74
|
-
const child =
|
|
124
|
+
const detached = this.platform !== "win32";
|
|
125
|
+
const child = this.spawnProcess(spec.command, spec.args, {
|
|
75
126
|
cwd: spec.cwd,
|
|
76
127
|
env: spec.env,
|
|
77
128
|
stdio: ["ignore", "pipe", "pipe"],
|
|
78
129
|
detached,
|
|
79
130
|
...spec.options,
|
|
80
131
|
});
|
|
132
|
+
const handleEarlyError = (error) => {
|
|
133
|
+
this.logger.error({ workspaceId: options.workspaceId, err: error }, "Workspace runtime failed before launch handlers were ready");
|
|
134
|
+
};
|
|
135
|
+
child.on("error", handleEarlyError);
|
|
81
136
|
const managed = {
|
|
82
137
|
child,
|
|
138
|
+
cleanupToken,
|
|
139
|
+
processKind: spec.processKind,
|
|
83
140
|
requestedStop: false,
|
|
84
|
-
|
|
141
|
+
targets: { members: new Map() },
|
|
142
|
+
...(spec.wsl
|
|
143
|
+
? {
|
|
144
|
+
wsl: {
|
|
145
|
+
distro: spec.wsl.distro,
|
|
146
|
+
linuxPid: null,
|
|
147
|
+
linuxPgid: null,
|
|
148
|
+
leaderStartTime: null,
|
|
149
|
+
bootId: null,
|
|
150
|
+
members: new Map(),
|
|
151
|
+
},
|
|
152
|
+
}
|
|
153
|
+
: {}),
|
|
85
154
|
};
|
|
86
155
|
this.processes.set(options.workspaceId, managed);
|
|
156
|
+
if (spec.processKind === "posix" || spec.processKind === "wsl" || spec.processKind === "windows-direct") {
|
|
157
|
+
const launchSnapshot = child.pid
|
|
158
|
+
? this.platform === "win32"
|
|
159
|
+
? probeWindowsProcesses(this.spawnCommand, this.stopCommandTimeoutMs)
|
|
160
|
+
: probePosixProcesses(this.spawnCommand, this.stopCommandTimeoutMs, this.platform)
|
|
161
|
+
: { ok: false, error: "spawned child did not expose a PID" };
|
|
162
|
+
const launchLeader = launchSnapshot.ok && child.pid ? launchSnapshot.processes.get(child.pid) : undefined;
|
|
163
|
+
if (!launchLeader) {
|
|
164
|
+
const detail = launchSnapshot.ok
|
|
165
|
+
? `spawned PID ${child.pid ?? "unknown"} was absent from the identity snapshot`
|
|
166
|
+
: launchSnapshot.error;
|
|
167
|
+
this.beginFailedLaunchCleanup(options.workspaceId, managed);
|
|
168
|
+
reject(new WorkspaceRuntimeIdentityCaptureError(options.workspaceId, detail));
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
managed.targets.leader = launchLeader;
|
|
172
|
+
managed.targets.groupId = launchLeader.groupId;
|
|
173
|
+
managed.targets.members.set(launchLeader.pid, launchLeader);
|
|
174
|
+
}
|
|
87
175
|
let stdoutBuffer = "";
|
|
88
176
|
let stderrBuffer = "";
|
|
89
177
|
let portFound = false;
|
|
178
|
+
let pendingPort = null;
|
|
179
|
+
let launchSettled = false;
|
|
90
180
|
let warningTimer = null;
|
|
91
181
|
const startWarningTimer = () => {
|
|
92
182
|
warningTimer = setInterval(() => {
|
|
@@ -100,14 +190,32 @@ export class WorkspaceRuntime {
|
|
|
100
190
|
}
|
|
101
191
|
};
|
|
102
192
|
startWarningTimer();
|
|
193
|
+
managed.cancelWaits = () => {
|
|
194
|
+
const error = new WorkspaceRuntimeLaunchCancelledError(options.workspaceId);
|
|
195
|
+
if (!launchSettled) {
|
|
196
|
+
launchSettled = true;
|
|
197
|
+
stopWarningTimer();
|
|
198
|
+
reject(error);
|
|
199
|
+
}
|
|
200
|
+
if (cancellationResolve) {
|
|
201
|
+
cancellationResolve(error);
|
|
202
|
+
cancellationResolve = null;
|
|
203
|
+
}
|
|
204
|
+
};
|
|
103
205
|
const cleanupStreams = () => {
|
|
104
206
|
stopWarningTimer();
|
|
105
207
|
child.stdout?.removeAllListeners();
|
|
106
208
|
child.stderr?.removeAllListeners();
|
|
107
209
|
};
|
|
210
|
+
let finalized = false;
|
|
108
211
|
const handleExit = (code, signal) => {
|
|
212
|
+
if (finalized)
|
|
213
|
+
return;
|
|
214
|
+
finalized = true;
|
|
109
215
|
this.logger.info({ workspaceId: options.workspaceId, code, signal }, "OpenCode process exited");
|
|
110
|
-
this.processes.
|
|
216
|
+
if (!managed.requestedStop && this.processes.get(options.workspaceId) === managed) {
|
|
217
|
+
this.processes.delete(options.workspaceId);
|
|
218
|
+
}
|
|
111
219
|
cleanupStreams();
|
|
112
220
|
child.removeListener("error", handleError);
|
|
113
221
|
child.removeListener("exit", handleExit);
|
|
@@ -124,25 +232,57 @@ export class WorkspaceRuntime {
|
|
|
124
232
|
if (!portFound) {
|
|
125
233
|
const recentOutput = getLastOutput().trim();
|
|
126
234
|
const reason = recentOutput || stderrBuffer || `Process exited with code ${code}`;
|
|
127
|
-
|
|
235
|
+
if (!launchSettled) {
|
|
236
|
+
launchSettled = true;
|
|
237
|
+
reject(new Error(reason));
|
|
238
|
+
}
|
|
128
239
|
}
|
|
129
240
|
else {
|
|
130
241
|
options.onExit?.(exitInfo);
|
|
131
242
|
}
|
|
132
243
|
};
|
|
244
|
+
managed.finalizeExit = handleExit;
|
|
133
245
|
const handleError = (error) => {
|
|
134
246
|
cleanupStreams();
|
|
135
247
|
child.removeListener("exit", handleExit);
|
|
136
|
-
this.processes.
|
|
248
|
+
if (!managed.requestedStop && this.processes.get(options.workspaceId) === managed) {
|
|
249
|
+
this.processes.delete(options.workspaceId);
|
|
250
|
+
}
|
|
137
251
|
this.logger.error({ workspaceId: options.workspaceId, err: error }, "Workspace runtime error");
|
|
138
252
|
if (exitResolve) {
|
|
139
253
|
exitResolve({ workspaceId: options.workspaceId, code: null, signal: null, requested: managed.requestedStop });
|
|
140
254
|
exitResolve = null;
|
|
141
255
|
}
|
|
142
|
-
|
|
256
|
+
if (!launchSettled) {
|
|
257
|
+
launchSettled = true;
|
|
258
|
+
reject(error);
|
|
259
|
+
}
|
|
143
260
|
};
|
|
261
|
+
child.removeListener("error", handleEarlyError);
|
|
144
262
|
child.on("error", handleError);
|
|
145
263
|
child.on("exit", handleExit);
|
|
264
|
+
const resolveLaunchIfIdentified = () => {
|
|
265
|
+
if (launchSettled || pendingPort === null)
|
|
266
|
+
return;
|
|
267
|
+
if (managed.wsl && (!managed.wsl.linuxPid || !managed.wsl.linuxPgid || !managed.wsl.leaderStartTime || !managed.wsl.bootId)) {
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
portFound = true;
|
|
271
|
+
launchSettled = true;
|
|
272
|
+
stopWarningTimer();
|
|
273
|
+
child.removeListener("error", handleError);
|
|
274
|
+
this.logger.info({ workspaceId: options.workspaceId, port: pendingPort }, "Workspace runtime allocated port");
|
|
275
|
+
resolve({ pid: child.pid, port: pendingPort, exitPromise, cancellationPromise, getLastOutput });
|
|
276
|
+
};
|
|
277
|
+
const failWslIdentityCapture = (detail) => {
|
|
278
|
+
if (launchSettled)
|
|
279
|
+
return;
|
|
280
|
+
launchSettled = true;
|
|
281
|
+
managed.requestedStop = true;
|
|
282
|
+
cleanupStreams();
|
|
283
|
+
this.beginFailedLaunchCleanup(options.workspaceId, managed);
|
|
284
|
+
reject(new WorkspaceRuntimeIdentityCaptureError(options.workspaceId, detail));
|
|
285
|
+
};
|
|
146
286
|
child.stdout?.on("data", (data) => {
|
|
147
287
|
const text = data.toString();
|
|
148
288
|
stdoutBuffer += text;
|
|
@@ -153,10 +293,32 @@ export class WorkspaceRuntime {
|
|
|
153
293
|
if (!trimmed)
|
|
154
294
|
continue;
|
|
155
295
|
if (managed.wsl && trimmed.startsWith(WSL_PID_MARKER)) {
|
|
156
|
-
const
|
|
157
|
-
|
|
296
|
+
const [linuxPidText, linuxPgidText, linuxStartTime = "", bootId = ""] = trimmed.slice(WSL_PID_MARKER.length).split(":", 4);
|
|
297
|
+
const linuxPid = Number.parseInt(linuxPidText ?? "", 10);
|
|
298
|
+
const linuxPgid = Number.parseInt(linuxPgidText ?? "", 10);
|
|
299
|
+
if (Number.isInteger(linuxPid) && linuxPid > 0 && Number.isInteger(linuxPgid) && linuxPgid > 0 && /^\d+$/.test(linuxStartTime) && bootId) {
|
|
158
300
|
managed.wsl.linuxPid = linuxPid;
|
|
159
|
-
|
|
301
|
+
managed.wsl.linuxPgid = linuxPgid;
|
|
302
|
+
managed.wsl.leaderStartTime = linuxStartTime;
|
|
303
|
+
managed.wsl.bootId = bootId;
|
|
304
|
+
managed.wsl.members.set(linuxPid, {
|
|
305
|
+
pid: linuxPid,
|
|
306
|
+
parentPid: 0,
|
|
307
|
+
groupId: linuxPgid,
|
|
308
|
+
startTime: linuxStartTime,
|
|
309
|
+
bootId,
|
|
310
|
+
startOrder: linuxStartTime,
|
|
311
|
+
});
|
|
312
|
+
this.logger.debug({
|
|
313
|
+
workspaceId: options.workspaceId,
|
|
314
|
+
linuxPid,
|
|
315
|
+
linuxPgid: managed.wsl.linuxPgid,
|
|
316
|
+
linuxStartTime: managed.wsl.leaderStartTime,
|
|
317
|
+
}, "Captured WSL OpenCode process identity");
|
|
318
|
+
resolveLaunchIfIdentified();
|
|
319
|
+
}
|
|
320
|
+
else {
|
|
321
|
+
failWslIdentityCapture("WSL launcher returned an incomplete Linux PID identity");
|
|
160
322
|
}
|
|
161
323
|
continue;
|
|
162
324
|
}
|
|
@@ -167,13 +329,14 @@ export class WorkspaceRuntime {
|
|
|
167
329
|
this.emitLog(options.workspaceId, "info", line);
|
|
168
330
|
if (!portFound) {
|
|
169
331
|
const portMatch = line.match(/opencode server listening on http:\/\/.+:(\d+)/i);
|
|
170
|
-
if (portMatch) {
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
332
|
+
if (portMatch && !launchSettled) {
|
|
333
|
+
pendingPort = parseInt(portMatch[1], 10);
|
|
334
|
+
if (managed.wsl && (!managed.wsl.leaderStartTime || !managed.wsl.bootId)) {
|
|
335
|
+
failWslIdentityCapture("WSL process reported a port before its Linux identity");
|
|
336
|
+
}
|
|
337
|
+
else {
|
|
338
|
+
resolveLaunchIfIdentified();
|
|
339
|
+
}
|
|
177
340
|
}
|
|
178
341
|
}
|
|
179
342
|
}
|
|
@@ -196,152 +359,434 @@ export class WorkspaceRuntime {
|
|
|
196
359
|
});
|
|
197
360
|
});
|
|
198
361
|
}
|
|
199
|
-
|
|
362
|
+
beginFailedLaunchCleanup(workspaceId, managed) {
|
|
363
|
+
const child = managed.child;
|
|
364
|
+
managed.identityCaptureFailed = true;
|
|
365
|
+
void this.stop(workspaceId).catch((error) => {
|
|
366
|
+
this.logger.warn({ workspaceId, err: error }, "Unpublished workspace cleanup remains pending");
|
|
367
|
+
});
|
|
368
|
+
try {
|
|
369
|
+
child.kill("SIGTERM");
|
|
370
|
+
}
|
|
371
|
+
catch (error) {
|
|
372
|
+
this.logger.debug({ workspaceId, err: error }, "Failed initial live-child cleanup signal");
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
stop(workspaceId) {
|
|
200
376
|
const managed = this.processes.get(workspaceId);
|
|
201
377
|
if (!managed)
|
|
202
|
-
return;
|
|
378
|
+
return Promise.resolve();
|
|
379
|
+
if (managed.stopPromise) {
|
|
380
|
+
return managed.stopPromise;
|
|
381
|
+
}
|
|
382
|
+
const stopPromise = this.stopManagedProcess(workspaceId, managed);
|
|
383
|
+
managed.stopPromise = stopPromise;
|
|
384
|
+
void stopPromise.then(() => {
|
|
385
|
+
if (managed.stopPromise === stopPromise)
|
|
386
|
+
managed.stopPromise = undefined;
|
|
387
|
+
}, () => {
|
|
388
|
+
if (managed.stopPromise === stopPromise)
|
|
389
|
+
managed.stopPromise = undefined;
|
|
390
|
+
});
|
|
391
|
+
return stopPromise;
|
|
392
|
+
}
|
|
393
|
+
stopManagedProcess(workspaceId, managed) {
|
|
203
394
|
managed.requestedStop = true;
|
|
395
|
+
managed.cancelWaits?.();
|
|
396
|
+
managed.cancelWaits = undefined;
|
|
204
397
|
const child = managed.child;
|
|
205
398
|
this.logger.info({ workspaceId }, "Stopping OpenCode process");
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
this.logger.warn({ workspaceId }, "Workspace process missing PID; cannot stop");
|
|
209
|
-
return;
|
|
399
|
+
if (managed.processKind === "windows-wrapper") {
|
|
400
|
+
return this.stopOwnedWindowsProcess(workspaceId, managed);
|
|
210
401
|
}
|
|
211
|
-
const
|
|
212
|
-
const
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
return
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
402
|
+
const pid = child.pid;
|
|
403
|
+
const failures = [];
|
|
404
|
+
const wrapperExited = () => child.exitCode !== null || child.signalCode !== null;
|
|
405
|
+
const rememberGroupMembers = (snapshot, targets) => {
|
|
406
|
+
if (!snapshot.ok || !pid)
|
|
407
|
+
return { snapshot, leaderMatches: false, aliveMembers: [] };
|
|
408
|
+
const currentLeader = snapshot.processes.get(pid);
|
|
409
|
+
const leaderMatches = sameProcess(targets.leader, currentLeader);
|
|
410
|
+
const currentGroupLeader = targets.groupId ? snapshot.processes.get(targets.groupId) : undefined;
|
|
411
|
+
const groupWasReused = Boolean(currentGroupLeader && !sameProcess(targets.leader, currentGroupLeader));
|
|
412
|
+
if (targets.groupId) {
|
|
413
|
+
for (const process of snapshot.processes.values()) {
|
|
414
|
+
const launchBootMatches = !targets.leader?.bootId || process.bootId === targets.leader.bootId;
|
|
415
|
+
const withinProvenLinuxDispatch = this.platform === "linux" && Boolean(targets.dispatchCutoff && launchBootMatches && startedNoLaterThan(process, targets.dispatchCutoff));
|
|
416
|
+
if (process.groupId === targets.groupId && (leaderMatches || (!groupWasReused && withinProvenLinuxDispatch))) {
|
|
417
|
+
targets.members.set(process.pid, process);
|
|
418
|
+
}
|
|
222
419
|
}
|
|
223
|
-
this.logger.debug({ workspaceId, pid, err }, "Failed to signal POSIX process group");
|
|
224
|
-
return false;
|
|
225
420
|
}
|
|
421
|
+
return {
|
|
422
|
+
snapshot,
|
|
423
|
+
leaderMatches,
|
|
424
|
+
aliveMembers: Array.from(targets.members.values()).filter((identity) => sameProcess(identity, snapshot.processes.get(identity.pid))),
|
|
425
|
+
};
|
|
226
426
|
};
|
|
227
|
-
const
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
427
|
+
const refreshHostTargets = () => {
|
|
428
|
+
const targets = managed.targets ?? { members: new Map() };
|
|
429
|
+
managed.targets = targets;
|
|
430
|
+
const snapshot = this.platform === "win32"
|
|
431
|
+
? probeWindowsProcesses(this.spawnCommand, this.stopCommandTimeoutMs)
|
|
432
|
+
: probePosixProcesses(this.spawnCommand, this.stopCommandTimeoutMs, this.platform);
|
|
433
|
+
if (!snapshot.ok) {
|
|
434
|
+
failures.push(`${this.platform === "win32" ? "Windows" : "POSIX"} identity discovery failed: ${snapshot.error}`);
|
|
435
|
+
return { snapshot, leaderMatches: false, aliveMembers: [] };
|
|
231
436
|
}
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
437
|
+
const refreshed = rememberGroupMembers(snapshot, targets);
|
|
438
|
+
if (this.platform === "win32" && refreshed.leaderMatches && targets.leader) {
|
|
439
|
+
for (const descendant of descendantsOf(snapshot.processes, targets.leader.pid)) {
|
|
440
|
+
targets.members.set(descendant.pid, descendant);
|
|
236
441
|
}
|
|
237
|
-
|
|
238
|
-
return false;
|
|
442
|
+
refreshed.aliveMembers = Array.from(targets.members.values()).filter((identity) => sameProcess(identity, snapshot.processes.get(identity.pid)));
|
|
239
443
|
}
|
|
444
|
+
return refreshed;
|
|
240
445
|
};
|
|
241
|
-
const
|
|
242
|
-
const
|
|
243
|
-
|
|
244
|
-
|
|
446
|
+
const refreshWslTargets = () => {
|
|
447
|
+
const wsl = managed.wsl;
|
|
448
|
+
const snapshot = probeWslProcesses(this.spawnCommand, wsl.distro, this.stopCommandTimeoutMs);
|
|
449
|
+
if (!snapshot.ok) {
|
|
450
|
+
failures.push(`WSL identity discovery failed: ${snapshot.error}`);
|
|
451
|
+
return { snapshot, leaderMatches: false, aliveMembers: [] };
|
|
245
452
|
}
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
const exitCode = result.status;
|
|
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;
|
|
453
|
+
if (!wsl.linuxPid || !wsl.leaderStartTime) {
|
|
454
|
+
return { snapshot, leaderMatches: false, aliveMembers: [] };
|
|
261
455
|
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
456
|
+
const leaderIdentity = {
|
|
457
|
+
pid: wsl.linuxPid,
|
|
458
|
+
parentPid: 0,
|
|
459
|
+
groupId: wsl.linuxPgid ?? wsl.linuxPid,
|
|
460
|
+
startTime: wsl.leaderStartTime,
|
|
461
|
+
...(wsl.bootId ? { bootId: wsl.bootId } : {}),
|
|
462
|
+
startOrder: wsl.leaderStartTime,
|
|
463
|
+
};
|
|
464
|
+
const currentLeader = snapshot.processes.get(wsl.linuxPid);
|
|
465
|
+
const leaderMatches = sameProcess(leaderIdentity, currentLeader);
|
|
466
|
+
const currentGroupLeader = wsl.linuxPgid ? snapshot.processes.get(wsl.linuxPgid) : undefined;
|
|
467
|
+
const groupWasReused = Boolean(currentGroupLeader && !sameProcess(leaderIdentity, currentGroupLeader));
|
|
468
|
+
if (wsl.linuxPgid) {
|
|
469
|
+
for (const process of snapshot.processes.values()) {
|
|
470
|
+
const withinProvenDispatch = Boolean(wsl.dispatchCutoff && process.bootId === wsl.bootId && startedNoLaterThan(process, wsl.dispatchCutoff));
|
|
471
|
+
if (process.groupId === wsl.linuxPgid && (leaderMatches || (!groupWasReused && withinProvenDispatch))) {
|
|
472
|
+
wsl.members.set(process.pid, process);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
265
475
|
}
|
|
476
|
+
return {
|
|
477
|
+
snapshot,
|
|
478
|
+
leaderMatches,
|
|
479
|
+
aliveMembers: Array.from(wsl.members.values()).filter((identity) => sameProcess(identity, snapshot.processes.get(identity.pid))),
|
|
480
|
+
};
|
|
266
481
|
};
|
|
267
|
-
const
|
|
268
|
-
|
|
269
|
-
|
|
482
|
+
const hasWslIdentity = () => Boolean(managed.wsl?.linuxPid && managed.wsl.linuxPgid && managed.wsl.leaderStartTime && managed.wsl.bootId);
|
|
483
|
+
const canUseTokenCleanup = () => this.platform === "linux" || Boolean(managed.wsl);
|
|
484
|
+
const tokenTarget = () => managed.wsl ?? managed.targets;
|
|
485
|
+
const refreshTokenTargets = () => {
|
|
486
|
+
if (!canUseTokenCleanup())
|
|
487
|
+
return undefined;
|
|
488
|
+
const snapshot = probeLaunchCleanupToken(this.spawnCommand, managed.cleanupToken, this.stopCommandTimeoutMs, managed.wsl?.distro);
|
|
489
|
+
if (!snapshot.ok) {
|
|
490
|
+
failures.push(`${managed.wsl ? "WSL" : "Linux"} launch-token discovery failed: ${snapshot.error}`);
|
|
491
|
+
return snapshot;
|
|
270
492
|
}
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
const
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
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;
|
|
286
|
-
}
|
|
287
|
-
catch (error) {
|
|
288
|
-
this.logger.debug({ workspaceId, pid, linuxPid: managed.wsl.linuxPid, distro: managed.wsl.distro, err: error }, "WSL kill failed to execute");
|
|
289
|
-
return false;
|
|
493
|
+
const target = tokenTarget();
|
|
494
|
+
for (const identity of snapshot.processes.values())
|
|
495
|
+
target.members.set(identity.pid, identity);
|
|
496
|
+
return snapshot;
|
|
497
|
+
};
|
|
498
|
+
const recordSignalResult = (result, target, platformName, signal) => {
|
|
499
|
+
if (!result.ok) {
|
|
500
|
+
for (const identity of result.observed ?? [])
|
|
501
|
+
target.members.set(identity.pid, identity);
|
|
502
|
+
failures.push(`${platformName} guarded ${signal} failed: ${result.error}`);
|
|
503
|
+
return;
|
|
290
504
|
}
|
|
505
|
+
if (result.matched && !result.signalSent)
|
|
506
|
+
failures.push(`${platformName} guarded ${signal} matched but sent no signal`);
|
|
507
|
+
for (const identity of result.signaled)
|
|
508
|
+
target.members.set(identity.pid, identity);
|
|
509
|
+
if (result.cutoff)
|
|
510
|
+
target.dispatchCutoff = result.cutoff;
|
|
291
511
|
};
|
|
292
512
|
const sendStopSignal = (signal) => {
|
|
293
|
-
if (
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
513
|
+
if (!pid) {
|
|
514
|
+
failures.push(`${signal} was not sent because the process PID is unavailable`);
|
|
515
|
+
}
|
|
516
|
+
let ownedPosixHandled = false;
|
|
517
|
+
if (pid && managed.identityCaptureFailed && this.platform !== "linux" && this.platform !== "win32" && !wrapperExited()) {
|
|
518
|
+
const cleanup = signalOwnedPosixProcessGroup(this.spawnCommand, pid, signal, this.stopCommandTimeoutMs);
|
|
519
|
+
recordSignalResult(cleanup, managed.targets, "owned POSIX group", signal);
|
|
520
|
+
if (cleanup.ok && cleanup.matched) {
|
|
521
|
+
const leader = cleanup.signaled.find((identity) => identity.pid === pid);
|
|
522
|
+
if (leader) {
|
|
523
|
+
managed.targets.leader = leader;
|
|
524
|
+
managed.targets.groupId = pid;
|
|
525
|
+
}
|
|
298
526
|
}
|
|
299
|
-
|
|
527
|
+
refreshHostTargets();
|
|
528
|
+
ownedPosixHandled = true;
|
|
529
|
+
}
|
|
530
|
+
if (pid && managed.wsl && hasWslIdentity()) {
|
|
531
|
+
const wsl = managed.wsl;
|
|
532
|
+
const leader = {
|
|
533
|
+
pid: wsl.linuxPid,
|
|
534
|
+
parentPid: 0,
|
|
535
|
+
groupId: wsl.linuxPgid,
|
|
536
|
+
startTime: wsl.leaderStartTime,
|
|
537
|
+
bootId: wsl.bootId,
|
|
538
|
+
startOrder: wsl.leaderStartTime,
|
|
539
|
+
};
|
|
540
|
+
const result = signalWslProcesses(this.spawnCommand, wsl.distro, {
|
|
541
|
+
leader,
|
|
542
|
+
groupId: wsl.linuxPgid,
|
|
543
|
+
members: Array.from(wsl.members.values()),
|
|
544
|
+
signal,
|
|
545
|
+
}, this.stopCommandTimeoutMs);
|
|
546
|
+
recordSignalResult(result, wsl, "WSL", signal);
|
|
547
|
+
refreshWslTargets();
|
|
548
|
+
}
|
|
549
|
+
else if (pid && !ownedPosixHandled) {
|
|
550
|
+
const targets = managed.targets;
|
|
551
|
+
const request = {
|
|
552
|
+
leader: targets.leader,
|
|
553
|
+
groupId: targets.groupId,
|
|
554
|
+
members: Array.from(targets.members.values()),
|
|
555
|
+
signal,
|
|
556
|
+
};
|
|
557
|
+
if (this.platform === "win32") {
|
|
558
|
+
recordSignalResult(signalWindowsProcesses(this.spawnCommand, request, this.stopCommandTimeoutMs), targets, "Windows", signal);
|
|
559
|
+
}
|
|
560
|
+
else {
|
|
561
|
+
recordSignalResult(signalPosixProcesses(this.spawnCommand, request, this.stopCommandTimeoutMs, this.platform), targets, "POSIX", signal);
|
|
562
|
+
}
|
|
563
|
+
refreshHostTargets();
|
|
300
564
|
}
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
565
|
+
if (canUseTokenCleanup()) {
|
|
566
|
+
const tokenResult = signalLaunchCleanupToken(this.spawnCommand, managed.cleanupToken, signal, this.stopCommandTimeoutMs, managed.wsl?.distro);
|
|
567
|
+
if (!tokenResult.ok) {
|
|
568
|
+
failures.push(`${managed.wsl ? "WSL" : "Linux"} launch-token ${signal} failed: ${tokenResult.error}`);
|
|
569
|
+
}
|
|
570
|
+
else {
|
|
571
|
+
if (tokenResult.targets.length > 0 && !tokenResult.signalSent) {
|
|
572
|
+
failures.push(`${managed.wsl ? "WSL" : "Linux"} launch-token ${signal} matched but sent no signal`);
|
|
573
|
+
}
|
|
574
|
+
const target = tokenTarget();
|
|
575
|
+
for (const identity of tokenResult.targets)
|
|
576
|
+
target.members.set(identity.pid, identity);
|
|
577
|
+
}
|
|
578
|
+
refreshTokenTargets();
|
|
306
579
|
}
|
|
307
580
|
};
|
|
308
|
-
|
|
581
|
+
const probeTargetLiveness = () => {
|
|
582
|
+
const refreshed = pid
|
|
583
|
+
? managed.wsl && hasWslIdentity() ? refreshWslTargets() : refreshHostTargets()
|
|
584
|
+
: undefined;
|
|
585
|
+
const tokenSnapshot = refreshTokenTargets();
|
|
586
|
+
if (tokenSnapshot && !tokenSnapshot.ok) {
|
|
587
|
+
return { state: "unknown", detail: `${managed.wsl ? "WSL Linux" : "Linux"} launch-token cleanup could not be confirmed` };
|
|
588
|
+
}
|
|
589
|
+
if (refreshed && !refreshed.snapshot.ok && (managed.targets?.leader || !tokenSnapshot?.ok)) {
|
|
590
|
+
const platformName = managed.wsl ? "WSL Linux" : this.platform === "win32" ? "Windows" : "POSIX";
|
|
591
|
+
return { state: "unknown", detail: `${platformName} target identity could not be confirmed` };
|
|
592
|
+
}
|
|
593
|
+
const trackedCount = managed.wsl ? managed.wsl.members.size : (managed.targets?.members.size ?? 0);
|
|
594
|
+
if (managed.identityCaptureFailed && this.platform === "win32" && !managed.wsl) {
|
|
595
|
+
return { state: "unknown", detail: "Windows cleanup cannot prove exact launch ownership without a Job Object" };
|
|
596
|
+
}
|
|
597
|
+
if (managed.identityCaptureFailed && managed.wsl && !managed.targets?.leader && !wrapperExited()) {
|
|
598
|
+
return { state: "unknown", detail: "the unidentified Windows WSL wrapper is still alive" };
|
|
599
|
+
}
|
|
600
|
+
if (trackedCount === 0) {
|
|
601
|
+
if (tokenSnapshot?.ok && tokenSnapshot.processes.size === 0) {
|
|
602
|
+
return { state: "gone", detail: "no process carries the unpublished launch token" };
|
|
603
|
+
}
|
|
604
|
+
return { state: "unknown", detail: pid ? "the original process identity was not captured" : "the target PID is unavailable" };
|
|
605
|
+
}
|
|
606
|
+
if ((refreshed?.aliveMembers.length ?? 0) === 0 && (!tokenSnapshot?.ok || tokenSnapshot.processes.size === 0)) {
|
|
607
|
+
return { state: "gone", detail: "all tracked original process identities are gone" };
|
|
608
|
+
}
|
|
609
|
+
const targetName = managed.wsl && hasWslIdentity() ? "WSL Linux process group" : this.platform === "win32" ? "Windows process tree" : "POSIX process group";
|
|
610
|
+
return { state: "alive", detail: `the tracked original ${targetName} is still alive` };
|
|
611
|
+
};
|
|
612
|
+
return new Promise((resolve, reject) => {
|
|
309
613
|
let escalationTimer = null;
|
|
614
|
+
let deadlineTimer = null;
|
|
615
|
+
let settled = false;
|
|
310
616
|
const cleanup = () => {
|
|
311
617
|
child.removeListener("exit", onExit);
|
|
312
618
|
child.removeListener("error", onError);
|
|
313
619
|
if (escalationTimer) {
|
|
314
|
-
|
|
620
|
+
this.cancelTimeout(escalationTimer);
|
|
315
621
|
escalationTimer = null;
|
|
316
622
|
}
|
|
623
|
+
if (deadlineTimer) {
|
|
624
|
+
this.cancelTimeout(deadlineTimer);
|
|
625
|
+
deadlineTimer = null;
|
|
626
|
+
}
|
|
317
627
|
};
|
|
318
|
-
const
|
|
628
|
+
const confirmTargetGone = () => {
|
|
629
|
+
if (settled)
|
|
630
|
+
return;
|
|
631
|
+
settled = true;
|
|
319
632
|
cleanup();
|
|
633
|
+
if (this.processes.get(workspaceId) === managed) {
|
|
634
|
+
this.processes.delete(workspaceId);
|
|
635
|
+
}
|
|
636
|
+
managed.finalizeExit?.(child.exitCode, child.signalCode);
|
|
320
637
|
resolve();
|
|
321
638
|
};
|
|
639
|
+
const checkForConfirmedStop = () => {
|
|
640
|
+
const liveness = probeTargetLiveness();
|
|
641
|
+
if (liveness.state === "gone") {
|
|
642
|
+
confirmTargetGone();
|
|
643
|
+
}
|
|
644
|
+
return liveness;
|
|
645
|
+
};
|
|
646
|
+
const onExit = () => {
|
|
647
|
+
checkForConfirmedStop();
|
|
648
|
+
};
|
|
322
649
|
const onError = (error) => {
|
|
650
|
+
failures.push(`child process error while stopping: ${error.message}`);
|
|
651
|
+
};
|
|
652
|
+
child.once("exit", onExit);
|
|
653
|
+
child.on("error", onError);
|
|
654
|
+
escalationTimer = this.scheduleTimeout(() => {
|
|
655
|
+
escalationTimer = null;
|
|
656
|
+
if (settled)
|
|
657
|
+
return;
|
|
658
|
+
const liveness = checkForConfirmedStop();
|
|
659
|
+
if (settled)
|
|
660
|
+
return;
|
|
661
|
+
this.logger.warn({ workspaceId, pid }, "Process did not stop after SIGTERM, escalating");
|
|
662
|
+
sendStopSignal("SIGKILL");
|
|
663
|
+
if (liveness.state === "unknown") {
|
|
664
|
+
this.logger.debug({ workspaceId, pid }, "Escalating because target liveness could not be confirmed");
|
|
665
|
+
}
|
|
666
|
+
}, this.gracefulStopTimeoutMs);
|
|
667
|
+
const totalTimeoutMs = this.gracefulStopTimeoutMs + this.forcedStopTimeoutMs;
|
|
668
|
+
deadlineTimer = this.scheduleTimeout(() => {
|
|
669
|
+
deadlineTimer = null;
|
|
670
|
+
if (settled)
|
|
671
|
+
return;
|
|
672
|
+
const liveness = checkForConfirmedStop();
|
|
673
|
+
if (settled)
|
|
674
|
+
return;
|
|
675
|
+
settled = true;
|
|
323
676
|
cleanup();
|
|
324
|
-
|
|
677
|
+
const wrapperDetail = wrapperExited() ? "the wrapper exited but " : "";
|
|
678
|
+
reject(new WorkspaceStopTimeoutError(workspaceId, pid, totalTimeoutMs, `${wrapperDetail}${liveness.detail}`, failures));
|
|
679
|
+
}, totalTimeoutMs);
|
|
680
|
+
this.logger.debug({ workspaceId, pid, detached: this.platform !== "win32" }, "Sending SIGTERM to workspace process (tree/group)");
|
|
681
|
+
sendStopSignal("SIGTERM");
|
|
682
|
+
checkForConfirmedStop();
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
stopOwnedWindowsProcess(workspaceId, managed) {
|
|
686
|
+
const child = managed.child;
|
|
687
|
+
const pid = child.pid;
|
|
688
|
+
const failures = (managed.windowsTreeCleanupFailures ?? (managed.windowsTreeCleanupFailures = []));
|
|
689
|
+
return new Promise((resolve, reject) => {
|
|
690
|
+
let escalationTimer = null;
|
|
691
|
+
let deadlineTimer = null;
|
|
692
|
+
let settled = false;
|
|
693
|
+
const cleanup = () => {
|
|
694
|
+
child.removeListener("exit", onExit);
|
|
695
|
+
child.removeListener("error", onError);
|
|
696
|
+
if (escalationTimer)
|
|
697
|
+
this.cancelTimeout(escalationTimer);
|
|
698
|
+
if (deadlineTimer)
|
|
699
|
+
this.cancelTimeout(deadlineTimer);
|
|
325
700
|
};
|
|
326
|
-
|
|
327
|
-
|
|
701
|
+
const finish = () => {
|
|
702
|
+
if (settled)
|
|
703
|
+
return;
|
|
704
|
+
settled = true;
|
|
328
705
|
cleanup();
|
|
706
|
+
if (this.processes.get(workspaceId) === managed)
|
|
707
|
+
this.processes.delete(workspaceId);
|
|
708
|
+
managed.finalizeExit?.(child.exitCode, child.signalCode);
|
|
329
709
|
resolve();
|
|
330
|
-
|
|
331
|
-
|
|
710
|
+
};
|
|
711
|
+
const rejectIncompleteCleanup = () => {
|
|
712
|
+
if (settled)
|
|
713
|
+
return;
|
|
714
|
+
settled = true;
|
|
715
|
+
cleanup();
|
|
716
|
+
reject(new WorkspaceWindowsTreeCleanupIncompleteError(workspaceId, pid, failures));
|
|
717
|
+
};
|
|
718
|
+
const onExit = () => {
|
|
719
|
+
if (managed.windowsTreeCleanupConfirmed) {
|
|
720
|
+
finish();
|
|
721
|
+
}
|
|
722
|
+
else {
|
|
723
|
+
rejectIncompleteCleanup();
|
|
724
|
+
}
|
|
725
|
+
};
|
|
726
|
+
const onError = (error) => {
|
|
727
|
+
if (settled)
|
|
728
|
+
return;
|
|
729
|
+
settled = true;
|
|
730
|
+
cleanup();
|
|
731
|
+
failures.push(`child process error while stopping: ${error.message}`);
|
|
732
|
+
reject(error);
|
|
733
|
+
};
|
|
734
|
+
const stopChild = (force) => {
|
|
735
|
+
if (child.exitCode !== null || child.signalCode !== null)
|
|
736
|
+
return;
|
|
737
|
+
if (!pid) {
|
|
738
|
+
failures.push(`${force ? "forced" : "graceful"} stop was not sent because the process PID is unavailable`);
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
const args = ["/PID", String(pid), "/T", ...(force ? ["/F"] : [])];
|
|
742
|
+
try {
|
|
743
|
+
const result = this.spawnCommand("taskkill.exe", args, {
|
|
744
|
+
encoding: "utf8",
|
|
745
|
+
timeout: this.stopCommandTimeoutMs,
|
|
746
|
+
});
|
|
747
|
+
if (result.status === 0) {
|
|
748
|
+
managed.windowsTreeCleanupConfirmed = true;
|
|
749
|
+
}
|
|
750
|
+
else {
|
|
751
|
+
const detail = result.error?.message || String(result.stderr ?? result.stdout ?? "").trim() || `exit code ${result.status}`;
|
|
752
|
+
failures.push(`taskkill ${force ? "/T /F" : "/T"} failed: ${detail}`);
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
catch (error) {
|
|
756
|
+
failures.push(`taskkill ${force ? "/T /F" : "/T"} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
757
|
+
}
|
|
758
|
+
};
|
|
332
759
|
child.once("exit", onExit);
|
|
333
760
|
child.once("error", onError);
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
761
|
+
if (child.exitCode !== null || child.signalCode !== null) {
|
|
762
|
+
if (managed.windowsTreeCleanupConfirmed) {
|
|
763
|
+
finish();
|
|
764
|
+
}
|
|
765
|
+
else {
|
|
766
|
+
rejectIncompleteCleanup();
|
|
767
|
+
}
|
|
768
|
+
return;
|
|
769
|
+
}
|
|
770
|
+
escalationTimer = this.scheduleTimeout(() => {
|
|
337
771
|
escalationTimer = null;
|
|
338
|
-
if (
|
|
339
|
-
this.logger.debug({ workspaceId, pid }, "Workspace exited before SIGKILL escalation");
|
|
772
|
+
if (settled)
|
|
340
773
|
return;
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
774
|
+
this.logger.warn({ workspaceId, pid }, "Owned Windows process did not stop after the graceful attempt, escalating");
|
|
775
|
+
stopChild(true);
|
|
776
|
+
}, this.gracefulStopTimeoutMs);
|
|
777
|
+
const totalTimeoutMs = this.gracefulStopTimeoutMs + this.forcedStopTimeoutMs;
|
|
778
|
+
deadlineTimer = this.scheduleTimeout(() => {
|
|
779
|
+
deadlineTimer = null;
|
|
780
|
+
if (settled)
|
|
781
|
+
return;
|
|
782
|
+
settled = true;
|
|
783
|
+
cleanup();
|
|
784
|
+
reject(new WorkspaceStopTimeoutError(workspaceId, pid, totalTimeoutMs, child.exitCode !== null || child.signalCode !== null
|
|
785
|
+
? "taskkill did not confirm tree cleanup before the owned Windows wrapper exited"
|
|
786
|
+
: "the owned Windows wrapper did not emit exit or error after tree termination", failures));
|
|
787
|
+
}, totalTimeoutMs);
|
|
788
|
+
this.logger.debug({ workspaceId, pid }, "Stopping owned Windows workspace wrapper tree");
|
|
789
|
+
stopChild(false);
|
|
345
790
|
});
|
|
346
791
|
}
|
|
347
792
|
emitLog(workspaceId, level, message) {
|