@lark-codem/codem-cli 0.1.274-test.202611170849.0.gc5a50ef → 0.1.274
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/LICENSE +6 -6
- package/bin/codem-service.js +132 -132
- package/bin/codem.js +250 -250
- package/bin/linco-paths.js +45 -45
- package/bin/platform-child-process.js +178 -178
- package/bin/process-tree.js +217 -0
- package/bin/tt-env.js +171 -171
- package/bin/worker-runtime-telemetry.js +75 -75
- package/bin/worker-runtime.js +345 -294
- package/package.json +9 -9
- package/profile/config-lock.js +512 -512
- package/profile/credential-errors.js +37 -37
- package/profile/credential-metadata.js +29 -29
- package/profile/debug.js +104 -104
- package/profile/device-identity.js +95 -95
- package/profile/diagnostic-id.js +47 -47
- package/profile/index.d.ts +61 -61
- package/profile/index.js +17 -17
- package/profile/profile-io.js +70 -70
- package/profile/profile-migration.js +1022 -1022
- package/profile/profile-snapshot.js +120 -120
- package/profile/profile-writers.js +296 -296
- package/profile/runtime-logs.js +660 -660
- package/profile/slardar-pc-transport.js +42 -42
- package/profile/worker-runtime-observation.js +10 -10
package/bin/worker-runtime.js
CHANGED
|
@@ -1,294 +1,345 @@
|
|
|
1
|
-
// Startup-only routing. Keep this module independent of Bridge business imports:
|
|
2
|
-
// it is also executed by container entrypoints before either Bridge is loaded.
|
|
3
|
-
import { spawn } from 'node:child_process';
|
|
4
|
-
import {
|
|
5
|
-
import
|
|
6
|
-
import
|
|
7
|
-
import
|
|
8
|
-
import
|
|
9
|
-
import
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
if (
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
if (
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
runtimeRoot = path.join(familyRoot, '
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
if (
|
|
58
|
-
const
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
const
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
const
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
throw new Error('
|
|
187
|
-
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
const
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
const
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
const
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
|
|
1
|
+
// Startup-only routing. Keep this module independent of Bridge business imports:
|
|
2
|
+
// it is also executed by container entrypoints before either Bridge is loaded.
|
|
3
|
+
import { execFile, spawn } from 'node:child_process';
|
|
4
|
+
import { promisify } from 'node:util';
|
|
5
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
6
|
+
import fs from 'node:fs/promises';
|
|
7
|
+
import { constants as fsConstants } from 'node:fs';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { pathToFileURL } from 'node:url';
|
|
11
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
12
|
+
import { applyHostedWindowsChildOptions } from './platform-child-process.js';
|
|
13
|
+
import { resolveEffectiveLincoHome, resolveLincoSessionsRoot, sameRecoveryPath } from './linco-paths.js';
|
|
14
|
+
import { observeWorkerRuntime } from './worker-runtime-telemetry.js';
|
|
15
|
+
import { snapshotDescendantPids, terminateProcessTree } from './process-tree.js';
|
|
16
|
+
|
|
17
|
+
const execFileAsync = promisify(execFile);
|
|
18
|
+
|
|
19
|
+
export const WORKER_HOST_HOME = process.env.CODEM_WORKER_HOST_HOME || path.join(os.homedir(), '.codem');
|
|
20
|
+
export const WORKER_RUNTIME_ROOT = path.join(WORKER_HOST_HOME, 'worker-runtimes');
|
|
21
|
+
export const EXACT_RUNTIME_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
|
|
22
|
+
const families = ['stable', 'current'];
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
async function readJSON(file) { return JSON.parse(await fs.readFile(file, 'utf8')); }
|
|
26
|
+
async function confinedFile(root, relative) {
|
|
27
|
+
if (typeof relative !== 'string' || !relative || path.isAbsolute(relative)) throw new Error('invalid runtime path');
|
|
28
|
+
const realRoot = await fs.realpath(root);
|
|
29
|
+
const resolved = await fs.realpath(path.resolve(realRoot, relative));
|
|
30
|
+
const inside = path.relative(realRoot, resolved);
|
|
31
|
+
if (!inside || inside === '..' || inside.startsWith(`..${path.sep}`) || path.isAbsolute(inside)) throw new Error('runtime path escapes pair');
|
|
32
|
+
if (!(await fs.stat(resolved)).isFile()) throw new Error('runtime entry is not a file');
|
|
33
|
+
return resolved;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Only installers write these immutable pair manifests. No npm resolution or
|
|
37
|
+
// floating global/current Core lookup happens in the execution process.
|
|
38
|
+
export async function readWorkerRuntime(root, family, { version = null, generation = null } = {}) {
|
|
39
|
+
if (!families.includes(family)) throw new Error('invalid worker runtime');
|
|
40
|
+
const familyRoot = path.join(root, family);
|
|
41
|
+
let pointerChannel = null;
|
|
42
|
+
let runtimeRoot = version ? path.join(familyRoot, 'versions', version) : familyRoot;
|
|
43
|
+
if (version && !EXACT_RUNTIME_VERSION.test(version)) throw new Error('invalid runtime version');
|
|
44
|
+
if (!version) try {
|
|
45
|
+
const pointer = await readJSON(path.join(familyRoot, 'current.json'));
|
|
46
|
+
if (!EXACT_RUNTIME_VERSION.test(pointer.version)) throw new Error('invalid runtime pointer');
|
|
47
|
+
pointerChannel = pointer.channel;
|
|
48
|
+
version = pointer.version;
|
|
49
|
+
generation = pointer.generation ?? null;
|
|
50
|
+
runtimeRoot = path.join(familyRoot, 'versions', version);
|
|
51
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
52
|
+
if (generation !== null) {
|
|
53
|
+
if (typeof generation !== 'string' || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(generation) || !version) throw new Error('invalid runtime generation');
|
|
54
|
+
runtimeRoot = path.join(familyRoot, 'generations', generation, 'versions', version);
|
|
55
|
+
}
|
|
56
|
+
const relative = path.relative(await fs.realpath(familyRoot), await fs.realpath(runtimeRoot));
|
|
57
|
+
if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) throw new Error('runtime generation escapes family');
|
|
58
|
+
const manifest = await readJSON(path.join(runtimeRoot, 'runtime-manifest.json'));
|
|
59
|
+
if (manifest.schema !== 1 || manifest.family !== family || !EXACT_RUNTIME_VERSION.test(manifest.cliVersion) || !EXACT_RUNTIME_VERSION.test(manifest.coreVersion)) throw new Error('invalid runtime manifest');
|
|
60
|
+
if (manifest.workflowPrebound !== (family === 'current')) throw new Error('runtime architecture does not match family');
|
|
61
|
+
if (version && manifest.cliVersion !== version) throw new Error('runtime pointer version does not match pair');
|
|
62
|
+
const cliEntry = await confinedFile(runtimeRoot, manifest.cliEntry);
|
|
63
|
+
const corePath = await confinedFile(runtimeRoot, manifest.coreBinaryPath);
|
|
64
|
+
return { ...manifest, ...(pointerChannel ? { channel: pointerChannel } : {}), generation, root: runtimeRoot, cliEntry, corePath };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function routeIdentity(env) {
|
|
68
|
+
const values = [env.CODEM_SANDBOX_TENANT_KEY, env.CODEM_SANDBOX_PROJECT_KEY, env.CODEM_SANDBOX_SESSION_ID];
|
|
69
|
+
if (values.some(value => typeof value !== 'string' || !value.trim() || value.length > 1024 || /[\0\r\n]/.test(value))) throw new Error('worker runtime requires trusted tenant/project/session');
|
|
70
|
+
const scope = createHash('sha256').update(JSON.stringify(values)).digest('hex');
|
|
71
|
+
const lincoHome = resolveEffectiveLincoHome({ env });
|
|
72
|
+
const sessions = resolveLincoSessionsRoot({ env, effectiveLincoHome: lincoHome });
|
|
73
|
+
const directory = path.join(path.dirname(sessions), 'worker-runtime-routes');
|
|
74
|
+
const dispatch = env.CODEM_SANDBOX_DISPATCH_ID;
|
|
75
|
+
if (typeof dispatch !== 'string' || !dispatch.trim() || dispatch.length > 1024 || /[\0\r\n]/.test(dispatch)) throw new Error('worker runtime requires trusted dispatch');
|
|
76
|
+
const executionScope = createHash('sha256').update(JSON.stringify([scope, dispatch])).digest('hex');
|
|
77
|
+
return { scope, lincoHome, sessions, markerPath: path.join(directory, `${scope}.json`), executionScope,
|
|
78
|
+
executionPath: path.join(directory, `${scope}-${executionScope}.json`) };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// This is only architecture routing, not a second checkpoint validator. Source
|
|
82
|
+
// adoption is committed to the original Root before the new main Agent starts
|
|
83
|
+
// (Core resume_prebound / SourceTaskAttached). Core still owns full replay,
|
|
84
|
+
// identity, compatibility and the existing recovery locks.
|
|
85
|
+
async function retainedRootMatches(lincoHome, metadata, file, tos) {
|
|
86
|
+
const runId = metadata?.run_id;
|
|
87
|
+
if (typeof runId !== 'string' || !runId) return true;
|
|
88
|
+
const bindingPath = path.join(lincoHome, 'workflow-runs', 'locks', `${createHash('sha256').update(runId).digest('hex')}.lock`);
|
|
89
|
+
let handle;
|
|
90
|
+
try { handle = await fs.open(bindingPath, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0) | (fsConstants.O_NONBLOCK ?? 0)); }
|
|
91
|
+
catch (error) { if (error.code === 'ENOENT') return true; throw error; }
|
|
92
|
+
let retained;
|
|
93
|
+
try {
|
|
94
|
+
const limit = 4 * 1024 * 1024;
|
|
95
|
+
const stat = await handle.stat();
|
|
96
|
+
if (!stat.isFile()) throw new Error('workflow recovery binding is not a regular file');
|
|
97
|
+
if (stat.size > limit) throw new Error('workflow recovery binding exceeds replay limit');
|
|
98
|
+
const chunks = [], buffer = Buffer.allocUnsafe(64 * 1024);
|
|
99
|
+
let size = 0;
|
|
100
|
+
for (;;) {
|
|
101
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
|
|
102
|
+
if (!bytesRead) break;
|
|
103
|
+
size += bytesRead;
|
|
104
|
+
if (size > limit) throw new Error('workflow recovery binding exceeds replay limit');
|
|
105
|
+
chunks.push(Buffer.from(buffer.subarray(0, bytesRead)));
|
|
106
|
+
}
|
|
107
|
+
try { retained = JSON.parse(Buffer.concat(chunks).toString('utf8')); }
|
|
108
|
+
catch { throw new Error('invalid retained workflow binding'); }
|
|
109
|
+
} finally { await handle.close(); }
|
|
110
|
+
// The retained binding, not today's sandbox type, froze the Root layout.
|
|
111
|
+
// Core still validates its complete contents and canonical workspace later.
|
|
112
|
+
const retainedTos = retained.storage_profile === 'tos_v1';
|
|
113
|
+
if (!retainedTos && retained.storage_profile !== undefined) throw new Error('unsupported retained workflow storage profile');
|
|
114
|
+
if (retainedTos !== tos || retained.initial_state?.metadata?.run_id !== runId ||
|
|
115
|
+
retained.initial_state?.metadata?.root_session_id !== metadata.root_session_id) return false;
|
|
116
|
+
if (typeof retained.root_session_path !== 'string' || !path.isAbsolute(retained.root_session_path)) throw new Error('invalid retained workflow root path');
|
|
117
|
+
return sameRecoveryPath(retained.root_session_path, await fs.realpath(file));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function historicalFamily(sessions, session, lincoHome) {
|
|
121
|
+
if (!session || /[/\\\0]/.test(session) || session === '.' || session === '..') throw new Error('invalid recovery session');
|
|
122
|
+
let directories;
|
|
123
|
+
try { directories = await fs.readdir(sessions, { withFileTypes: true }); }
|
|
124
|
+
catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
125
|
+
let found = false;
|
|
126
|
+
for (const entry of directories) {
|
|
127
|
+
if (!entry.isDirectory()) continue;
|
|
128
|
+
for (const layout of ['', 'workflow-tos-v1']) {
|
|
129
|
+
const file = path.join(sessions, entry.name, layout, `${session}.jsonl`);
|
|
130
|
+
let handle;
|
|
131
|
+
try { handle = await fs.open(file, 'r'); }
|
|
132
|
+
catch (error) { if (error.code === 'ENOENT') continue; throw error; }
|
|
133
|
+
try {
|
|
134
|
+
// Same replay/record bounds as WorkflowStoreLimits; never load all Sessions.
|
|
135
|
+
if ((await handle.stat()).size > 64 * 1024 * 1024) throw new Error('workflow recovery history exceeds replay limit');
|
|
136
|
+
let pending = Buffer.alloc(0), root = null;
|
|
137
|
+
for await (const chunk of handle.createReadStream()) {
|
|
138
|
+
pending = Buffer.concat([pending, chunk]);
|
|
139
|
+
let newline;
|
|
140
|
+
while ((newline = pending.indexOf(10)) !== -1) {
|
|
141
|
+
if (newline > 4 * 1024 * 1024) throw new Error('workflow recovery record exceeds replay limit');
|
|
142
|
+
let value;
|
|
143
|
+
try { value = JSON.parse(pending.subarray(0, newline).toString('utf8')); }
|
|
144
|
+
catch { throw new Error('invalid workflow recovery history'); }
|
|
145
|
+
pending = pending.subarray(newline + 1);
|
|
146
|
+
if (root === null) {
|
|
147
|
+
if (value.type !== 'workflow_metadata' || value.record?.initial_state?.metadata?.root_session_id !== session) { root = false; break; }
|
|
148
|
+
if (!await retainedRootMatches(lincoHome, value.record.initial_state.metadata, file, layout === 'workflow-tos-v1')) { root = false; break; }
|
|
149
|
+
root = found = true;
|
|
150
|
+
if (value.record.local_execution || value.record.initialization?.local_execution) return 'current';
|
|
151
|
+
}
|
|
152
|
+
if (root && value.type === 'workflow_local' && value.record?.event?.kind === 'source_task_attached') return 'current';
|
|
153
|
+
}
|
|
154
|
+
if (root === false) break;
|
|
155
|
+
if (pending.length > 4 * 1024 * 1024) throw new Error('workflow recovery record exceeds replay limit');
|
|
156
|
+
}
|
|
157
|
+
} finally { await handle.close(); }
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return found ? 'stable' : null;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function promoteRoute(markerPath, scope) {
|
|
164
|
+
// Join any first publisher before promotion, so a delayed stable reservation
|
|
165
|
+
// cannot replace a current record published from durable recovery evidence.
|
|
166
|
+
if (await recordRoute(markerPath, scope, 'current') === 'current') return;
|
|
167
|
+
const temporary = `${markerPath}.${randomUUID()}.tmp`;
|
|
168
|
+
try {
|
|
169
|
+
await fs.mkdir(path.dirname(markerPath), { recursive: true, mode: 0o700 });
|
|
170
|
+
await fs.writeFile(temporary, `${JSON.stringify({ schema: 1, scope, family: 'current' })}\n`, { mode: 0o600, flag: 'wx' });
|
|
171
|
+
await fs.rename(temporary, markerPath);
|
|
172
|
+
} finally { await fs.rm(temporary, { force: true }); }
|
|
173
|
+
}
|
|
174
|
+
async function readRoute(markerPath, scope) {
|
|
175
|
+
try {
|
|
176
|
+
let contents = await fs.readFile(markerPath, 'utf8');
|
|
177
|
+
// Exclusive creation reserves the name before complete-log rename on TOS.
|
|
178
|
+
// Only the empty reservation is transient; corrupt records fail immediately.
|
|
179
|
+
// A killed publisher leaves refusal evidence, never a reusable empty slot.
|
|
180
|
+
for (let attempt = 0; contents === '' && attempt < 100; attempt++) {
|
|
181
|
+
await delay(50);
|
|
182
|
+
contents = await fs.readFile(markerPath, 'utf8');
|
|
183
|
+
}
|
|
184
|
+
if (contents === '') throw new Error('runtime route publication incomplete');
|
|
185
|
+
const marker = JSON.parse(contents);
|
|
186
|
+
if (marker.schema !== 1 || marker.scope !== scope || !families.includes(marker.family)) throw new Error('identity or schema mismatch');
|
|
187
|
+
return marker.family;
|
|
188
|
+
} catch (error) {
|
|
189
|
+
if (error.code === 'ENOENT') return null;
|
|
190
|
+
throw new Error('invalid runtime route', { cause: error });
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
async function recordRoute(markerPath, scope, family) {
|
|
194
|
+
await fs.mkdir(path.dirname(markerPath), { recursive: true, mode: 0o700 });
|
|
195
|
+
const temporary = `${markerPath}.${randomUUID()}.tmp`;
|
|
196
|
+
try {
|
|
197
|
+
await fs.writeFile(temporary, `${JSON.stringify({ schema: 1, scope, family })}\n`, { mode: 0o600, flag: 'wx' });
|
|
198
|
+
// TOS rejects hard links and no-replace rename. Only the exclusive creator
|
|
199
|
+
// may replace its empty reservation with the complete record. Losers read it.
|
|
200
|
+
let reservation;
|
|
201
|
+
try { reservation = await fs.open(markerPath, 'wx', 0o600); }
|
|
202
|
+
catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
203
|
+
if (reservation) {
|
|
204
|
+
await reservation.close();
|
|
205
|
+
await fs.rename(temporary, markerPath);
|
|
206
|
+
}
|
|
207
|
+
} finally { await fs.rm(temporary, { force: true }); }
|
|
208
|
+
return readRoute(markerPath, scope);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export async function selectWorkerRuntime({ env = process.env, root = env.CODEM_WORKER_RUNTIME_ROOT || WORKER_RUNTIME_ROOT, loadRuntime = readWorkerRuntime, currentChannel = null } = {}) {
|
|
212
|
+
const requested = env.CODEM_WORKER_RUNTIME;
|
|
213
|
+
if (!families.includes(requested)) throw new Error('invalid worker runtime');
|
|
214
|
+
const { scope, lincoHome, sessions, markerPath, executionScope, executionPath } = routeIdentity(env);
|
|
215
|
+
let actual = await readRoute(markerPath, scope);
|
|
216
|
+
const restoring = env.CODEM_TASK_MODE === 'resume';
|
|
217
|
+
const upgradeFrom = env.CODEM_WORKER_RUNTIME_UPGRADE_FROM;
|
|
218
|
+
if (upgradeFrom !== undefined && (upgradeFrom !== 'stable' || !restoring || requested !== 'current')) throw new Error('invalid worker runtime upgrade');
|
|
219
|
+
if (restoring && actual !== 'current') {
|
|
220
|
+
const historical = await historicalFamily(sessions, env.CODEM_SANDBOX_SESSION_ID, lincoHome);
|
|
221
|
+
if (historical === 'current') {
|
|
222
|
+
await promoteRoute(markerPath, scope);
|
|
223
|
+
actual = 'current';
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
const frozen = await readRoute(executionPath, executionScope);
|
|
227
|
+
if (frozen === 'stable' && actual === 'current') throw new Error('execution runtime conflicts with retained current state');
|
|
228
|
+
const upgrading = restoring && actual === 'stable' && requested === 'current' && !frozen;
|
|
229
|
+
const reasons = [];
|
|
230
|
+
const load = async family => {
|
|
231
|
+
try {
|
|
232
|
+
const runtime = await loadRuntime(root, family);
|
|
233
|
+
// A retained alpha pair can recover its own Session, but cannot serve a new
|
|
234
|
+
// latest-channel Session after a failed channel switch.
|
|
235
|
+
if ((!actual || upgrading) && !frozen && family === 'current' && currentChannel !== null) {
|
|
236
|
+
const channel = typeof currentChannel === 'function' ? await currentChannel() : currentChannel;
|
|
237
|
+
if (runtime.channel !== channel) throw new Error('worker runtime channel unavailable');
|
|
238
|
+
}
|
|
239
|
+
return runtime;
|
|
240
|
+
} catch { reasons.push(`${family}_unavailable`); return null; }
|
|
241
|
+
};
|
|
242
|
+
let runtime = await load(frozen || (actual === 'current' ? 'current' : restoring ? requested : actual || requested));
|
|
243
|
+
if (!frozen && actual !== 'current' && !runtime && requested === 'current') runtime = await load('stable');
|
|
244
|
+
if (!runtime) throw new Error(`${actual ? 'required ' : ''}runtime unavailable: ${reasons.join(',')}`);
|
|
245
|
+
if (!actual) {
|
|
246
|
+
actual = await recordRoute(markerPath, scope, runtime.family);
|
|
247
|
+
if (actual !== runtime.family) {
|
|
248
|
+
runtime = await load(actual);
|
|
249
|
+
if (!runtime) throw new Error('required runtime unavailable after concurrent selection');
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
// Freeze fallback per Dispatch, independently of the monotonic Session family.
|
|
253
|
+
// A later user recovery has a new Dispatch; command retries keep this choice.
|
|
254
|
+
const executionFamily = await recordRoute(executionPath, executionScope, runtime.family);
|
|
255
|
+
if (executionFamily !== runtime.family) {
|
|
256
|
+
if (executionFamily === 'stable' && await readRoute(markerPath, scope) === 'current') throw new Error('execution runtime conflicts with retained current state');
|
|
257
|
+
runtime = await load(executionFamily);
|
|
258
|
+
if (!runtime) throw new Error('required runtime unavailable after concurrent execution selection');
|
|
259
|
+
}
|
|
260
|
+
if (restoring && actual === 'stable' && runtime.family === 'current') await promoteRoute(markerPath, scope);
|
|
261
|
+
return { ...runtime, runtimeRoot: root, lincoHome, sessionsRoot: sessions, requested, markerPath, fallbackReason: requested !== runtime.family ? reasons.join(',') || 'session_family' : null };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
export function launchWorkerRuntime(runtime, { args = process.argv.slice(2), env = process.env, nodePath = process.execPath, invocation = null, log = console.error } = {}) {
|
|
265
|
+
log(JSON.stringify({ event: 'worker_runtime_selected', requested_family: runtime.requested, actual_family: runtime.family, fallback_reason: runtime.fallbackReason,
|
|
266
|
+
bridge_version: runtime.cliVersion, core_version: runtime.coreVersion, pair: `${runtime.cliVersion}/${runtime.coreVersion}`, dispatch_id: env.CODEM_SANDBOX_DISPATCH_ID, session_id: env.CODEM_SANDBOX_SESSION_ID }));
|
|
267
|
+
return new Promise((resolve, reject) => {
|
|
268
|
+
const launch = invocation || { command: nodePath, args: [runtime.cliEntry, ...args] };
|
|
269
|
+
const child = spawn(launch.command, launch.args, applyHostedWindowsChildOptions({ ...launch.options, stdio: 'inherit', env: { ...env,
|
|
270
|
+
// Keep relative/empty overrides frozen even if business startup changes cwd.
|
|
271
|
+
...(runtime.lincoHome ? { LINCO_HOME: runtime.lincoHome } : {}),
|
|
272
|
+
...(runtime.sessionsRoot ? { LINCO_SESSIONS_ROOT: runtime.sessionsRoot } : {}),
|
|
273
|
+
CODEM_LINCO_PATH: runtime.corePath, CODEM_WORKER_RUNTIME_ROOT: runtime.runtimeRoot, CODEM_WORKER_RUNTIME_READY: '1', CODEM_WORKER_RUNTIME_ACTUAL: runtime.family, CODEM_WORKER_CLI_VERSION: runtime.cliVersion, CODEM_WORKER_CORE_VERSION: runtime.coreVersion,
|
|
274
|
+
CODEM_PLUGIN_NODE: env.CODEM_PLUGIN_NODE || nodePath,
|
|
275
|
+
CODEM_SKIP_UPDATE_CHECK: '1', CODEM_DISABLE_DAEMON_AUTO_UPDATE: '1' } }));
|
|
276
|
+
const stopObservation=observeWorkerRuntime(runtime,{env,args});
|
|
277
|
+
const signals = ['SIGTERM', 'SIGINT', 'SIGHUP'];
|
|
278
|
+
let shutdownTimer = null, descendants = null, shutdownCleanup = null;
|
|
279
|
+
const cleanup = () => {clearTimeout(shutdownTimer);stopObservation();signals.forEach((signal, index) => process.off(signal, handlers[index]));};
|
|
280
|
+
// Both the deadline and an early daemon exit own the same bounded tree cleanup.
|
|
281
|
+
// In particular, exit must not discard descendants orphaned by graceful shutdown.
|
|
282
|
+
const finishShutdown = () => {
|
|
283
|
+
if (shutdownCleanup === null) shutdownCleanup = (async () => {
|
|
284
|
+
clearTimeout(shutdownTimer);
|
|
285
|
+
let killTimer;
|
|
286
|
+
const controller = new AbortController();
|
|
287
|
+
const execFileImpl = (file, args, options) => execFileAsync(file, args, { ...options, signal: controller.signal });
|
|
288
|
+
try {
|
|
289
|
+
await Promise.race([
|
|
290
|
+
(async () => {
|
|
291
|
+
const current = child.exitCode === null && child.signalCode === null
|
|
292
|
+
? await snapshotDescendantPids(child.pid, { timeoutMs: 1000, execFileImpl }) : [];
|
|
293
|
+
await terminateProcessTree({ pid: child.pid,
|
|
294
|
+
descendants: [...new Set([...current, ...await descendants])], timeoutMs: 1000, execFileImpl });
|
|
295
|
+
})(),
|
|
296
|
+
new Promise(resolve => { killTimer = setTimeout(resolve, 2000); })
|
|
297
|
+
]);
|
|
298
|
+
} finally {
|
|
299
|
+
controller.abort();
|
|
300
|
+
clearTimeout(killTimer);
|
|
301
|
+
if (child.exitCode === null && child.signalCode === null) { try { child.kill('SIGKILL'); } catch {} }
|
|
302
|
+
cleanup();
|
|
303
|
+
}
|
|
304
|
+
})();
|
|
305
|
+
return shutdownCleanup;
|
|
306
|
+
};
|
|
307
|
+
const handlers = signals.map(signal => () => {
|
|
308
|
+
if (child.exitCode !== null || child.signalCode !== null || shutdownTimer !== null) return;
|
|
309
|
+
// Snapshot before forwarding: graceful shutdown may orphan descendants.
|
|
310
|
+
descendants = snapshotDescendantPids(child.pid, { timeoutMs: 1000 });
|
|
311
|
+
const exitCode = 128 + (os.constants.signals[signal] || 1);
|
|
312
|
+
// Sandbox shutdown owns up to 15s plus finalization. Leave that budget intact;
|
|
313
|
+
// repeated signals cannot renew this independent launcher backstop.
|
|
314
|
+
shutdownTimer = setTimeout(async () => {
|
|
315
|
+
await finishShutdown();
|
|
316
|
+
process.exit(exitCode);
|
|
317
|
+
}, 20_000);
|
|
318
|
+
void descendants.then(() => {
|
|
319
|
+
if (child.exitCode === null && child.signalCode === null) { try { child.kill(signal); } catch {} }
|
|
320
|
+
});
|
|
321
|
+
});
|
|
322
|
+
signals.forEach((signal, index) => process.on(signal, handlers[index]));
|
|
323
|
+
child.once('error', error => { cleanup(); reject(error); });
|
|
324
|
+
child.once('exit', async (code, signal) => {
|
|
325
|
+
const exitCode = code ?? (signal ? 128 + (os.constants.signals[signal] || 1) : 1);
|
|
326
|
+
if (shutdownTimer !== null) await finishShutdown();
|
|
327
|
+
else cleanup();
|
|
328
|
+
resolve(exitCode);
|
|
329
|
+
});
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
export function isWorkerRuntimeStartup(args = process.argv.slice(2), env = process.env) {
|
|
334
|
+
return env.CODEM_WORKER_RUNTIME !== undefined && env.CODEM_WORKER_RUNTIME_READY !== '1' && args[0] === 'daemon' && args.some(arg => arg === '--sandbox' || arg.startsWith('--sandbox='));
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// Container entrypoints invoke this directly, with a baked immutable root.
|
|
338
|
+
async function runStandalone() {
|
|
339
|
+
try {
|
|
340
|
+
const runtime = await selectWorkerRuntime();
|
|
341
|
+
process.exitCode = await launchWorkerRuntime(runtime, { nodePath: process.execPath });
|
|
342
|
+
} catch (error) { console.error(`worker runtime startup failed: ${error.message}`); process.exitCode = 1; }
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
if (typeof Bun === 'undefined' && process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) void runStandalone();
|