@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/bin/tt-env.js CHANGED
@@ -1,171 +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
- }
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
+ }
@@ -1,75 +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
- }
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
+ }