@lark-codem/codem-cli 0.1.272-web-trusted-device-access.100103781761.0.gc527772 → 0.1.272

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/bin/codem.js CHANGED
@@ -145,6 +145,19 @@ function explainWindowsFatalStatus(code) {
145
145
  ].join("\n");
146
146
  }
147
147
 
148
+ // Source/development and npm entrypoints select before invoking business code.
149
+ // The compiled entry has the same guard for managed/direct binary installations.
150
+ if (process.env.CODEM_WORKER_RUNTIME !== undefined) {
151
+ const { isWorkerRuntimeStartup } = await import("./worker-runtime.js");
152
+ if (isWorkerRuntimeStartup()) {
153
+ const bootstrap = await import("../dist/src/worker-runtime-bootstrap.js").catch(() => null);
154
+ if (bootstrap) {
155
+ try { process.exitCode = await bootstrap.runWorkerRuntimeBootstrap(); }
156
+ catch (error) { writeStderrSync(`worker runtime startup failed: ${error.message}`); process.exitCode = 1; }
157
+ process.exit(process.exitCode ?? 0);
158
+ }
159
+ }
160
+ }
148
161
  const binaryPath = resolvePlatformBinary();
149
162
 
150
163
  if (binaryPath) {
@@ -0,0 +1,45 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+
4
+ export function resolveEffectiveLincoHome({
5
+ env = process.env, homeDir = os.homedir(), workingDirectory = process.cwd(), platform = process.platform
6
+ } = {}) {
7
+ const pathApi = platform === "win32" ? path.win32 : path;
8
+ const configured = Object.hasOwn(env ?? {}, "LINCO_HOME")
9
+ ? String(env.LINCO_HOME ?? "") : pathApi.join(String(homeDir), ".codem");
10
+ return pathApi.resolve(String(workingDirectory), configured);
11
+ }
12
+
13
+ // Mirror Core sessions_root_for, including present-but-empty path overrides.
14
+ // Sidecars are siblings of the session root, never sandbox CODEM_STATE_HOME.
15
+ export function resolveLincoSessionsRoot(options = {}) {
16
+ const { env = process.env, workingDirectory = process.cwd(), platform = process.platform } = options;
17
+ const pathApi = platform === "win32" ? path.win32 : path;
18
+ return Object.hasOwn(env ?? {}, "LINCO_SESSIONS_ROOT")
19
+ ? pathApi.resolve(String(workingDirectory), String(env.LINCO_SESSIONS_ROOT ?? ""))
20
+ : pathApi.join(options.effectiveLincoHome ?? resolveEffectiveLincoHome(options), "sessions");
21
+ }
22
+
23
+ export function resolveLincoHostContextRoot(options = {}) {
24
+ const pathApi = options.platform === "win32" ? path.win32 : path;
25
+ return pathApi.join(pathApi.dirname(resolveLincoSessionsRoot(options)), "host-context");
26
+ }
27
+
28
+ export function sameRecoveryPath(retained, current, platform = process.platform) {
29
+ if (typeof retained !== "string" || typeof current !== "string") return false;
30
+ if (platform !== "win32" || retained === current) return retained === current;
31
+ // Rust canonicalize retains the extended-length drive/UNC prefix; Node
32
+ // realpath removes it. Strip only that representation difference, preserving
33
+ // case and literal segments rather than resolving untrusted binding paths.
34
+ const identity = value => {
35
+ if (value.toLowerCase().startsWith("\\\\?\\unc\\")) value = `\\\\${value.slice(8)}`;
36
+ else if (value.startsWith("\\\\?\\")) value = value.slice(4);
37
+ const root = path.win32.parse(value).root;
38
+ if (!path.win32.isAbsolute(value) || root.length <= 1) return null;
39
+ // Namespaced UNC roots may omit the trailing separator. Do not normalize
40
+ // non-root segments: verbatim paths must not acquire lexical aliases.
41
+ return value === root && !value.endsWith("\\") ? `${value}\\` : value;
42
+ };
43
+ const retainedIdentity = identity(retained);
44
+ return retainedIdentity !== null && retainedIdentity === identity(current);
45
+ }
@@ -0,0 +1,217 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+
4
+ import { applyHostedWindowsChildOptions } from "./platform-child-process.js";
5
+
6
+ const execFileAsync = promisify(execFile);
7
+
8
+ /**
9
+ * 进程树终止。
10
+ *
11
+ * 为什么不能只 `child.kill()`:我们 spawn 的是 linco 一个进程,但 linco 干活时
12
+ * 会自己再起子进程(内联的 `npm run dev`、`cargo build`、git…)。只杀直接子进程
13
+ * 会把整棵子树留成孤儿——它们继续占端口、占锁,而且**继承了我们的 stdio 管道**,
14
+ * 于是 `child` 的 `close` 永远不触发(见 linco-runner.js 的
15
+ * LINCO_EXIT_DRAIN_GRACE_MS)。
16
+ *
17
+ * 为什么必须"先快照后代、再杀":`ps` 反查 ppid(unix)和 `taskkill /T`
18
+ * (Windows)**都依赖父进程还活着**。父进程一死,后代立刻被 reparent 到 PID 1
19
+ * (Windows 上 ppid 指向一个已消失的 pid),血缘信息就永久丢了,再也认不出哪些
20
+ * 进程曾属于这次 run。而"父死子活"恰恰就是我们要处理的那个场景。所以血缘必须
21
+ * 在**树还完整的时刻**取样,强杀阶段只按快照执行。
22
+ */
23
+
24
+ // `ps -A -o pid=,ppid=` 是 POSIX 通用形态,macOS / Linux 输出一致(两列数字,
25
+ // 前导空格对齐)。用 `=` 后缀去掉表头,省一次解析分支。
26
+ const UNIX_PS_ARGS = ["-A", "-o", "pid=,ppid="];
27
+
28
+ // Win32 没有 POSIX ps。PowerShell 的 CIM 查询比已废弃的 wmic 稳(wmic 在
29
+ // Windows 11 / Server 2025 上默认不再安装)。输出两列数字,与 unix 分支同构。
30
+ const WINDOWS_PS_ARGS = [
31
+ "-NoProfile",
32
+ "-NonInteractive",
33
+ "-Command",
34
+ "Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId) $($_.ParentProcessId)\" }"
35
+ ];
36
+
37
+ function parsePidPairs(stdout) {
38
+ const pairs = [];
39
+ for (const line of String(stdout ?? "").split("\n")) {
40
+ const match = line.trim().match(/^(\d+)\s+(\d+)$/);
41
+ if (!match) {
42
+ continue;
43
+ }
44
+ pairs.push([Number.parseInt(match[1], 10), Number.parseInt(match[2], 10)]);
45
+ }
46
+ return pairs;
47
+ }
48
+
49
+ /**
50
+ * 广度优先收集 rootPid 的全部后代(不含 rootPid 自己),返回**由深到浅**的顺序。
51
+ *
52
+ * 由深到浅是为了终止时先杀叶子:先杀中间节点会让它的孩子提前变孤儿,剩下的
53
+ * kill 就打空了。
54
+ *
55
+ * 任何失败都返回空数组——快照是尽力而为的增强,绝不能让它把调用方的终止路径
56
+ * 拖崩。拿不到血缘时调用方仍会杀直接子进程,等于退回改动前的行为。
57
+ */
58
+ export async function snapshotDescendantPids(
59
+ rootPid,
60
+ { platform = process.platform, execFileImpl = execFileAsync, timeoutMs = null, onError = null } = {}
61
+ ) {
62
+ if (!Number.isInteger(rootPid) || rootPid <= 0) {
63
+ return [];
64
+ }
65
+
66
+ const startedAt = performance.now();
67
+ let pairs = [];
68
+ try {
69
+ const { stdout } =
70
+ platform === "win32"
71
+ ? await execFileImpl(
72
+ "powershell.exe",
73
+ WINDOWS_PS_ARGS,
74
+ applyHostedWindowsChildOptions(
75
+ Number.isFinite(timeoutMs) && timeoutMs > 0 ? { timeout: timeoutMs } : {},
76
+ { platform }
77
+ )
78
+ )
79
+ : await execFileImpl(
80
+ "ps",
81
+ UNIX_PS_ARGS,
82
+ applyHostedWindowsChildOptions(
83
+ Number.isFinite(timeoutMs) && timeoutMs > 0 ? { timeout: timeoutMs } : {},
84
+ { platform }
85
+ )
86
+ );
87
+ pairs = parsePidPairs(stdout);
88
+ } catch (error) {
89
+ onError?.(error, {
90
+ durationMs: Math.round(performance.now() - startedAt),
91
+ timeoutMs,
92
+ code: error?.code ?? null,
93
+ killed: error?.killed === true,
94
+ signal: error?.signal ?? null
95
+ });
96
+ return [];
97
+ }
98
+
99
+ const childrenByParent = new Map();
100
+ for (const [pid, ppid] of pairs) {
101
+ if (pid === ppid) {
102
+ // 自指(部分系统上 pid 1 会这么报)。放任会让下面的 BFS 死循环。
103
+ continue;
104
+ }
105
+ const bucket = childrenByParent.get(ppid);
106
+ if (bucket) {
107
+ bucket.push(pid);
108
+ } else {
109
+ childrenByParent.set(ppid, [pid]);
110
+ }
111
+ }
112
+
113
+ const levels = [];
114
+ const seen = new Set([rootPid]);
115
+ let frontier = [rootPid];
116
+ // 深度上限:纯防御。真实进程树不会有 64 层,但快照来自外部命令的文本输出,
117
+ // 一旦解析出环就会在这里无限打转。
118
+ for (let depth = 0; depth < 64 && frontier.length > 0; depth += 1) {
119
+ const next = [];
120
+ for (const pid of frontier) {
121
+ for (const childPid of childrenByParent.get(pid) ?? []) {
122
+ if (seen.has(childPid)) {
123
+ continue;
124
+ }
125
+ seen.add(childPid);
126
+ next.push(childPid);
127
+ }
128
+ }
129
+ if (next.length > 0) {
130
+ levels.push(next);
131
+ }
132
+ frontier = next;
133
+ }
134
+
135
+ return levels.reverse().flat();
136
+ }
137
+
138
+ /**
139
+ * 杀掉 rootPid 及其后代。
140
+ *
141
+ * `descendants` 由调用方在树还完整时用 snapshotDescendantPids 取样后传入;
142
+ * 不传就现取(只在父进程仍活着时才有意义)。
143
+ *
144
+ * 返回实际发出信号的 pid 数——调用方用它做日志,不做控制流:kill 失败绝大多数
145
+ * 是"进程已经没了",那正是我们要的结果。
146
+ */
147
+ export async function terminateProcessTree({
148
+ pid,
149
+ descendants = null,
150
+ signal = "SIGKILL",
151
+ platform = process.platform,
152
+ execFileImpl = execFileAsync,
153
+ killImpl = (targetPid, targetSignal) => process.kill(targetPid, targetSignal),
154
+ timeoutMs = null,
155
+ onError = null
156
+ } = {}) {
157
+ if (!Number.isInteger(pid) || pid <= 0) {
158
+ return { signaled: 0 };
159
+ }
160
+
161
+ const targets =
162
+ descendants ??
163
+ (await snapshotDescendantPids(pid, { platform, execFileImpl, timeoutMs, onError }));
164
+ let signaled = 0;
165
+
166
+ if (platform === "win32") {
167
+ // /T 覆盖此刻仍挂在 pid 下的活树,一次调用比逐个 taskkill 更少竞态。
168
+ try {
169
+ await execFileImpl(
170
+ "taskkill.exe",
171
+ ["/F", "/T", "/PID", String(pid)],
172
+ applyHostedWindowsChildOptions(
173
+ Number.isFinite(timeoutMs) && timeoutMs > 0 ? { timeout: timeoutMs } : {},
174
+ { platform }
175
+ )
176
+ );
177
+ signaled += 1;
178
+ } catch (error) {
179
+ // pid 已消失时 taskkill 返回非 0,属预期。
180
+ onError?.(error);
181
+ }
182
+ // 快照里那些已经和 pid 断了血缘的(父先死的孤儿),/T 够不着,逐个补刀。
183
+ for (const targetPid of targets) {
184
+ try {
185
+ await execFileImpl(
186
+ "taskkill.exe",
187
+ ["/F", "/PID", String(targetPid)],
188
+ applyHostedWindowsChildOptions(
189
+ Number.isFinite(timeoutMs) && timeoutMs > 0 ? { timeout: timeoutMs } : {},
190
+ { platform }
191
+ )
192
+ );
193
+ signaled += 1;
194
+ } catch {
195
+ // 已退出。
196
+ }
197
+ }
198
+ return { signaled };
199
+ }
200
+
201
+ // unix:叶子优先,最后才是 root。
202
+ for (const targetPid of targets) {
203
+ try {
204
+ killImpl(targetPid, signal);
205
+ signaled += 1;
206
+ } catch {
207
+ // 已退出。
208
+ }
209
+ }
210
+ try {
211
+ killImpl(pid, signal);
212
+ signaled += 1;
213
+ } catch {
214
+ // 已退出。
215
+ }
216
+ return { signaled };
217
+ }
package/bin/tt-env.js ADDED
@@ -0,0 +1,171 @@
1
+ // CODEM_X_TT_ENV 泳道支持:按环境变量把 codem 请求打入 BOE 环境 / PPE·BOE 泳道。
2
+ // 与 linco 侧(linco-code crates/linco-core/src/tt_env.rs)同一契约、同一矩阵:
3
+ //
4
+ // | 值 | 域名 | x-tt-env | x-use-ppe |
5
+ // |---------|---------------------------------------|----------|-----------|
6
+ // | boe | codem.feishu.cn → codem.feishu-boe.cn | — | — |
7
+ // | boe_* | codem.feishu.cn → codem.feishu-boe.cn | 原值 | — |
8
+ // | ppe | 不变(PPE 与线上同域名) | — | 1 |
9
+ // | ppe_* | 不变 | 原值 | 1 |
10
+ // | 其他 | 完全惰性 | — | — |
11
+ //
12
+ // daemon spawn linco 时 env 全量继承(linco-runner buildLincoProcessEnv),
13
+ // 该变量无需任何桥接代码即透传给 linco 进程。
14
+ //
15
+ // 头注入统一走 ttEnvHeadersFor(url):只对官方 codem host(prod/BOE)产出头,
16
+ // 任何可被 env 覆写到第三方 host 的出口(agent-config / project 端点)天然
17
+ // 拿不到泳道头——泄露风险在构造上排除,而非靠调用点纪律。
18
+ //
19
+ // 个人和 native sandbox 的 serverUrl 经 resolveServerUrl 派生;cloud/custom
20
+ // sandbox 保留自己的配置优先级,再用 rewriteUrlForTtEnv 改写选中的官方域名。
21
+ // Runtime POST 使用已解析的 serverUrl 拼接路径,与 managed-config 保持同一环境;
22
+ // 自定义服务地址不受影响。BOE 身份态通过 resolveStateHome 隔离到 .boe 子树。
23
+
24
+ import path from "node:path";
25
+
26
+ export const CODEM_X_TT_ENV = "CODEM_X_TT_ENV";
27
+
28
+ const PROD_ROUTER_HOST = "codem.feishu.cn";
29
+ const BOE_ROUTER_HOST = "codem.feishu-boe.cn";
30
+
31
+
32
+ // 合法形状:boe / ppe 裸值,或 boe_ / ppe_ 前缀 + [A-Za-z0-9_-] 泳道名。其余
33
+ // 一律 null(惰性)。显式剥 BOM(U+FEFF,Windows env 文件复制常见混入);泳道
34
+ // 名限定字符集,控制字符等坏值直接判惰性而不是变成非法 header value。两条都
35
+ // 是与 linco 侧(tt_env.rs)钉死的契约——同一变量被两个进程各自解析,任何
36
+ // 语义分叉都会造成"bridge 进泳道、linco 留 prod"的半程泳道。
37
+ export function parseTtEnvLane(raw) {
38
+ if (typeof raw !== "string") {
39
+ return null;
40
+ }
41
+ // 字符类显式含 U+0085(NEL):JS \s 不含它而 Rust char::is_whitespace 含,
42
+ // 不补齐会在这一个字符上出现两侧判定分叉。
43
+ const value = raw.replace(/^[\s…]+|[\s…]+$/gu, "");
44
+ const bare = value === "boe" || value === "ppe";
45
+ const named = /^(?:boe|ppe)_[A-Za-z0-9_-]+$/u.test(value);
46
+ if (!bare && !named) {
47
+ return null;
48
+ }
49
+ return {
50
+ value,
51
+ isBoe: value === "boe" || value.startsWith("boe_"),
52
+ xTtEnv: named ? value : null,
53
+ usePpe: value === "ppe" || value.startsWith("ppe_")
54
+ };
55
+ }
56
+
57
+ export function resolveTtEnvLane(env = process.env) {
58
+ return parseTtEnvLane(env?.[CODEM_X_TT_ENV]);
59
+ }
60
+
61
+ function isOfficialCodemHost(hostname) {
62
+ const host = hostname.toLowerCase();
63
+ return host === PROD_ROUTER_HOST || host === BOE_ROUTER_HOST;
64
+ }
65
+
66
+ // BOE 泳道下把官方 prod host 重写为 BOE host;显式自定义 server(localhost /
67
+ // 私有化)与非法 URL 原样返回,保证 --server 显式指向永远赢过泳道。
68
+ export function rewriteUrlForTtEnv(url, env = process.env) {
69
+ const lane = resolveTtEnvLane(env);
70
+ if (!lane?.isBoe) {
71
+ return url;
72
+ }
73
+ let parsed;
74
+ try {
75
+ parsed = new URL(url);
76
+ } catch {
77
+ return url;
78
+ }
79
+ if (parsed.hostname.toLowerCase() !== PROD_ROUTER_HOST) {
80
+ return url;
81
+ }
82
+ parsed.hostname = BOE_ROUTER_HOST;
83
+ let rewritten = parsed.toString();
84
+ // URL 序列化会给裸域名补尾部 "/",与既有 serverUrl 约定(仅存域名)不符:
85
+ // 输入没带尾斜杠时保持原样。
86
+ if (!url.endsWith("/") && parsed.pathname === "/" && rewritten.endsWith("/")) {
87
+ rewritten = rewritten.slice(0, -1);
88
+ }
89
+ return rewritten;
90
+ }
91
+
92
+ // 目标是官方 codem host(prod/BOE)时产出泳道头,否则 {}——第三方 host 永远拿不到。
93
+ export function ttEnvHeadersFor(url, env = process.env) {
94
+ const lane = resolveTtEnvLane(env);
95
+ if (!lane || (!lane.xTtEnv && !lane.usePpe)) {
96
+ return {};
97
+ }
98
+ let hostname;
99
+ try {
100
+ hostname = (url instanceof URL ? url : new URL(String(url))).hostname;
101
+ } catch {
102
+ return {};
103
+ }
104
+ if (!isOfficialCodemHost(hostname)) {
105
+ return {};
106
+ }
107
+ const headers = {};
108
+ if (lane.xTtEnv) {
109
+ headers["x-tt-env"] = lane.xTtEnv;
110
+ }
111
+ if (lane.usePpe) {
112
+ headers["x-use-ppe"] = "1";
113
+ }
114
+ return headers;
115
+ }
116
+
117
+ // 环境状态根:身份/环境态(config/credentials/sessions/daemon 锁等)的落盘
118
+ // 基目录。boe 与 prod(ppe) 账号体系独立,各存一份互不打爆:boe* 泳道落
119
+ // `$CODEM_HOME/.boe`,其余共用 `$CODEM_HOME`。程序安装态(runtime/ 二进制、
120
+ // 更新状态、bin)**不走本函数**、始终留在 CODEM_HOME——否则首次 boe 启动
121
+ // launcher 在空的 .boe/runtime 找不到版本会触发重装。spawn linco 时子进程
122
+ // CODEM_HOME 指到本函数产物,linco(含 LINCO_HOME 派生的全部状态)自动跟随。
123
+ export function resolveStateHome(codemHome, env = process.env) {
124
+ const lane = resolveTtEnvLane(env);
125
+ if (!lane?.isBoe) {
126
+ return codemHome;
127
+ }
128
+ // 幂等:daemon 把 linco 子进程 CODEM_HOME 设为已派生的状态根并透传泳道变量,
129
+ // linco 回调 bridge CLI 的嵌套进程会再走一次派生——basename 已是 .boe 时
130
+ // 原样返回,否则出现 .boe/.boe 双目录(首次 BOE 登录 / AK 刷新读写错位)。
131
+ if (path.basename(codemHome) === ".boe") {
132
+ return codemHome;
133
+ }
134
+ return path.join(codemHome, ".boe");
135
+ }
136
+
137
+ // 泳道作用域文件名:/v1/models 这类**按泳道头返回不同内容**的缓存,必须以
138
+ // 完整泳道值分文件——boe_a 与 boe_b、裸 ppe 与 prod 的 catalog 都可能不同,
139
+ // 只分 boe/非 boe 两档会让跨泳道切换在 TTL 内复用错误 endpoint(与 linco
140
+ // model_discovery::cache_file_name 同契约)。泳道名字符集由 parseTtEnvLane
141
+ // 限定 [A-Za-z0-9_-],可安全嵌入文件名。
142
+ export function laneScopedFileName(baseName, env = process.env) {
143
+ const lane = resolveTtEnvLane(env);
144
+ if (!lane) {
145
+ return baseName;
146
+ }
147
+ const dot = baseName.lastIndexOf(".");
148
+ return dot > 0
149
+ ? `${baseName.slice(0, dot)}.${lane.value}${baseName.slice(dot)}`
150
+ : `${baseName}.${lane.value}`;
151
+ }
152
+
153
+ // 启动日志一行(无泳道时 null):泳道头漏注入的故障模式是"静默打到线上",
154
+ // 这行日志是运行现场唯一的可观测抓手。
155
+ export function describeTtEnvLane(env = process.env) {
156
+ const lane = resolveTtEnvLane(env);
157
+ if (!lane) {
158
+ return null;
159
+ }
160
+ const parts = [`CODEM_X_TT_ENV=${lane.value}`];
161
+ if (lane.isBoe) {
162
+ parts.push(`host→${BOE_ROUTER_HOST}`);
163
+ }
164
+ if (lane.xTtEnv) {
165
+ parts.push(`x-tt-env:${lane.xTtEnv}`);
166
+ }
167
+ if (lane.usePpe) {
168
+ parts.push("x-use-ppe:1");
169
+ }
170
+ return parts.join(" ");
171
+ }
@@ -0,0 +1,75 @@
1
+ // Observation only. This module runs before either business Bridge (including
2
+ // an unmodified stable CLI), and imports only stdlib and shared lane rules.
3
+ import http from 'node:http';
4
+ import https from 'node:https';
5
+ import { rewriteUrlForTtEnv, ttEnvHeadersFor } from './tt-env.js';
6
+
7
+ export function workerRuntimeTelemetryTarget({env=process.env,args=process.argv.slice(2)}={}) {
8
+ if (/^(1|true|yes|on)$/i.test(env.CODEM_TELEMETRY_DISABLED || '') || !env.CODEM_TOKEN || !env.CODEM_SANDBOX_DISPATCH_ID) return null;
9
+ // Mirror daemon's Commander options without importing business Bridge code:
10
+ // optional --sandbox [mode], required --server <url>, last occurrence wins.
11
+ let sandbox,serverFlag;
12
+ for(let index=0;index<args.length;index++) {
13
+ const arg=args[index];
14
+ if(arg==='--')break;
15
+ if(arg==='--sandbox') {
16
+ sandbox=args[index+1] && !args[index+1].startsWith('-') ? args[++index] : true;
17
+ } else if(arg.startsWith('--sandbox=')) {
18
+ sandbox=arg.slice('--sandbox='.length);
19
+ } else if(arg==='--server') {
20
+ if(!args[index+1] || args[index+1].startsWith('-'))return null;
21
+ serverFlag=args[++index];
22
+ } else if(arg.startsWith('--server=')) {
23
+ serverFlag=arg.slice('--server='.length);
24
+ }
25
+ }
26
+ if(sandbox!==undefined && sandbox!==true && sandbox!=='native')return null;
27
+ const native=sandbox==='native';
28
+ // Native rejects --server and ignores legacy sandbox URL aliases. Cloud's
29
+ // --server default is CODEM_SERVER_URL, before the sandbox-config fallbacks.
30
+ if(native && serverFlag!==undefined)return null;
31
+ const candidates=native ? [env.CODEM_SERVER_URL,'https://codem.feishu.cn'] : [serverFlag===undefined ? env.CODEM_SERVER_URL : serverFlag,env.CODEM_SANDBOX_SERVER_URL,env.SANDBOX_SERVER_URL,env.SERVER_URL,'http://localhost:3000'];
32
+ const server=candidates.find(value=>typeof value==='string' && value.trim()).trim();
33
+ const url=new URL(rewriteUrlForTtEnv(server,env));
34
+ if (!['http:','https:'].includes(url.protocol) || url.username || url.password) return null;
35
+ url.pathname=`${url.pathname.replace(/\/+$/,'') || '/goapi/codem'}/sandbox/telemetry/workflow_metrics`;
36
+ url.search='';url.hash='';
37
+ return {url,headers:{'Content-Type':'application/json',Authorization:`Bearer sandbox_${env.CODEM_TOKEN}`,...ttEnvHeadersFor(url,env)}};
38
+ }
39
+
40
+ export async function reportWorkerRuntime(runtime,{env=process.env,args=process.argv.slice(2),signal,timeoutMS=750}={}) {
41
+ try {
42
+ const target=workerRuntimeTelemetryTarget({env,args});
43
+ if (!target || signal?.aborted) return false;
44
+ const body=JSON.stringify({worker_runtime:{dispatch_id:env.CODEM_SANDBOX_DISPATCH_ID,family:runtime.family,cli_version:runtime.cliVersion,core_version:runtime.coreVersion}});
45
+ return await new Promise(resolve=>{
46
+ let timer,finished=false;
47
+ const done=value=>{if(finished)return;finished=true;clearTimeout(timer);resolve(value);};
48
+ const request=(target.url.protocol==='https:'?https:http).request(target.url,{method:'POST',headers:{...target.headers,'Content-Length':Buffer.byteLength(body)},signal},response=>{
49
+ let payload='';
50
+ response.on('data',chunk=>{payload+=chunk;if(payload.length>4096){done(false);request.destroy();}});
51
+ response.once('error',()=>done(false));
52
+ response.once('end',()=>{try{done(response.statusCode===200 && JSON.parse(payload).accepted===true);}catch{done(false);}});
53
+ });
54
+ request.once('error',()=>done(false));
55
+ timer=setTimeout(()=>{done(false);request.destroy();},timeoutMS);
56
+ timer.unref();
57
+ request.end(body);
58
+ });
59
+ } catch { return false; }
60
+ }
61
+
62
+ export function observeWorkerRuntime(runtime,options={}) {
63
+ const controller=new AbortController();
64
+ let timer;
65
+ // Native's dispatch token may only be materialized by the child's first
66
+ // normal Sync. Bounded retries do not acquire a lease or replay a task.
67
+ const delays=[1000,5000,30000];
68
+ const attempt=async index=>{
69
+ const accepted=await reportWorkerRuntime(runtime,{...options,signal:controller.signal});
70
+ if(accepted || controller.signal.aborted || index===delays.length)return;
71
+ timer=setTimeout(()=>void attempt(index+1),delays[index]);timer.unref();
72
+ };
73
+ void attempt(0);
74
+ return ()=>{clearTimeout(timer);controller.abort();};
75
+ }