@lark-codem/codem-cli 0.1.281-dev.100104624968.0.g09ca961 → 0.1.281-dev.100104631660.0.gd9b8134
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 +30 -107
- package/bin/tt-env.js +1 -1
- package/bin/worker-runtime-telemetry.js +1 -2
- package/package.json +9 -12
- package/profile/credential-errors.js +2 -1
- package/profile/profile-snapshot.js +1 -2
- package/profile/runtime-logs.js +18 -185
- package/auth/index.d.ts +0 -19
- package/auth/index.js +0 -5936
- package/bin/codem-startup-logs.js +0 -127
- package/bin/slardar-pc-transport.js +0 -42
- package/profile/realtime-log-id.js +0 -9
- package/profile/sandbox-observability.js +0 -17
package/bin/codem.js
CHANGED
|
@@ -12,7 +12,6 @@
|
|
|
12
12
|
// 开发态兜底:repo checkout 里没有平台包,若 ../dist/src/index.js 存在
|
|
13
13
|
// (npm run build 产物),直接 import 执行——`node bin/codem.js` 在仓内可用。
|
|
14
14
|
|
|
15
|
-
import { randomUUID } from "node:crypto";
|
|
16
15
|
import { spawn } from "node:child_process";
|
|
17
16
|
import fs from "node:fs";
|
|
18
17
|
import { createRequire } from "node:module";
|
|
@@ -54,72 +53,6 @@ function resolvePlatformBinary() {
|
|
|
54
53
|
return candidates.find((candidate) => fs.existsSync(candidate)) ?? null;
|
|
55
54
|
}
|
|
56
55
|
|
|
57
|
-
function isGlobalNpmEntrypoint(args) {
|
|
58
|
-
// Official npm –g installs link from <prefix>/bin on POSIX and create
|
|
59
|
-
// shims beside <prefix>/node_modules on Windows. A local/npx/managed/App
|
|
60
|
-
// package merely located under node_modules must not prepare shared state.
|
|
61
|
-
const nodeModules = path.dirname(path.dirname(PACKAGE_ROOT));
|
|
62
|
-
if (PACKAGE_SCOPE !== "@lark-codem" || path.basename(nodeModules) !== "node_modules") return false;
|
|
63
|
-
const windows = process.platform === "win32";
|
|
64
|
-
if (!windows && path.basename(path.dirname(nodeModules)) !== "lib") return false;
|
|
65
|
-
const shimDirectory = windows ? path.dirname(nodeModules) : path.resolve(nodeModules, "../../bin");
|
|
66
|
-
const expected = fs.realpathSync(fileURLToPath(import.meta.url));
|
|
67
|
-
const hasGlobalShim = ["codem", "codem-cli"].some(name => {
|
|
68
|
-
try {
|
|
69
|
-
const shim = path.join(shimDirectory, name + (windows ? ".cmd" : ""));
|
|
70
|
-
return windows
|
|
71
|
-
? fs.readFileSync(shim, "utf8").toLowerCase().includes("\\node_modules\\@lark-codem\\codem-cli\\bin\\codem.js")
|
|
72
|
-
: fs.realpathSync(shim) === expected;
|
|
73
|
-
} catch { return false; }
|
|
74
|
-
});
|
|
75
|
-
return hasGlobalShim && !args[0]?.startsWith("__") && !args.includes("--healthcheck") &&
|
|
76
|
-
!args.includes("--windows-migration-launcher-pid");
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
function forwardChildSignals(child) {
|
|
80
|
-
const handlers = new Map();
|
|
81
|
-
for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) {
|
|
82
|
-
const handler = () => {
|
|
83
|
-
if (child.exitCode !== null || child.signalCode !== null) return;
|
|
84
|
-
try { child.kill(signal); }
|
|
85
|
-
catch { /* child already gone */ }
|
|
86
|
-
};
|
|
87
|
-
handlers.set(signal, handler);
|
|
88
|
-
process.on(signal, handler);
|
|
89
|
-
}
|
|
90
|
-
return () => {
|
|
91
|
-
for (const [signal, handler] of handlers) process.removeListener(signal, handler);
|
|
92
|
-
};
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
async function prepareSharedLaunch(binaryPath, args, env) {
|
|
96
|
-
return new Promise((resolve, reject) => {
|
|
97
|
-
const child = spawn(binaryPath, ["__npm-runtime-launch", ...args], applyHostedWindowsChildOptions({
|
|
98
|
-
env: { ...env,
|
|
99
|
-
CODEM_NPM_RUNTIME_TTY: process.stdin.isTTY && process.stdout.isTTY && process.stderr.isTTY ? "1" : "0" },
|
|
100
|
-
stdio: ["inherit", "pipe", "inherit"],
|
|
101
|
-
windowsHide: true
|
|
102
|
-
}));
|
|
103
|
-
const removeSignalHandlers = forwardChildSignals(child);
|
|
104
|
-
let output = "";
|
|
105
|
-
child.stdout.setEncoding("utf8");
|
|
106
|
-
child.stdout.on("data", chunk => { output += chunk; });
|
|
107
|
-
child.once("error", error => {
|
|
108
|
-
removeSignalHandlers();
|
|
109
|
-
reject(error);
|
|
110
|
-
});
|
|
111
|
-
child.once("close", (code, signal) => {
|
|
112
|
-
removeSignalHandlers();
|
|
113
|
-
if (signal) process.kill(process.pid, signal);
|
|
114
|
-
if (code !== 0) reject(new Error("shared runtime bootstrap failed"));
|
|
115
|
-
else {
|
|
116
|
-
try { resolve(JSON.parse(output)); }
|
|
117
|
-
catch (error) { reject(error); }
|
|
118
|
-
}
|
|
119
|
-
});
|
|
120
|
-
});
|
|
121
|
-
}
|
|
122
|
-
|
|
123
56
|
// spawn 的失败有两条互斥出口:只有 EACCES / EAGAIN / EMFILE / ENFILE / ENOENT
|
|
124
57
|
// 会被 Node 降级成异步 `error` 事件,其余 errno(ENOEXEC / ENOTDIR / EPERM,以及
|
|
125
58
|
// Windows 上杀软 / EDR 拦截 CreateProcessW 时 libuv 报的 UNKNOWN=-4094)在
|
|
@@ -228,71 +161,61 @@ if (process.env.CODEM_WORKER_RUNTIME !== undefined) {
|
|
|
228
161
|
const binaryPath = resolvePlatformBinary();
|
|
229
162
|
|
|
230
163
|
if (binaryPath) {
|
|
231
|
-
const args = process.argv.slice(2);
|
|
232
|
-
let command = binaryPath;
|
|
233
|
-
let childArgs = args;
|
|
234
|
-
const env = { ...process.env, CODEM_PLUGIN_NODE: process.execPath };
|
|
235
|
-
if (isGlobalNpmEntrypoint(args)) {
|
|
236
|
-
env.CODEM_SHARED_RUNTIME_ATTEMPT = randomUUID();
|
|
237
|
-
env.CODEM_SHARED_RUNTIME_SOURCE = "npm_global";
|
|
238
|
-
const plan = await prepareSharedLaunch(binaryPath, args, env).catch(error => ({ error: error.code || "io_error" }));
|
|
239
|
-
if (plan.handled || plan.cancelled) process.exit(0);
|
|
240
|
-
if (plan.reason || plan.error) writeStderrSync(`codem: ${plan.error ?? plan.reason}`);
|
|
241
|
-
if (plan.error) {
|
|
242
|
-
if (plan.error === "legacy_service") writeStderrSync(" codem service start");
|
|
243
|
-
process.exit(1);
|
|
244
|
-
}
|
|
245
|
-
if (plan.launcher) {
|
|
246
|
-
command = plan.node;
|
|
247
|
-
childArgs = [plan.launcher, ...args];
|
|
248
|
-
env.CODEM_PLUGIN_NODE = plan.node;
|
|
249
|
-
env.CODEM_LARK_CLI_PATH = plan.lark;
|
|
250
|
-
const previousPath = process.env.PATH || "";
|
|
251
|
-
for (const key of Object.keys(env)) {
|
|
252
|
-
if (process.platform === "win32" && key.toUpperCase() === "PATH") delete env[key];
|
|
253
|
-
}
|
|
254
|
-
env.PATH = [plan.bin, previousPath].join(path.delimiter);
|
|
255
|
-
const explicitBash = process.env.LINCO_GIT_BASH_PATH;
|
|
256
|
-
if (process.platform === "win32" && plan.bash && path.isAbsolute(plan.bash)
|
|
257
|
-
&& fs.statSync(plan.bash, { throwIfNoEntry: false })?.isFile()
|
|
258
|
-
&& !(explicitBash && path.isAbsolute(explicitBash) && fs.statSync(explicitBash, { throwIfNoEntry: false })?.isFile())) {
|
|
259
|
-
env.LINCO_GIT_BASH_PATH = plan.bash;
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
164
|
let child;
|
|
264
165
|
let stopWindowsHostMigrationWatch = () => {};
|
|
265
166
|
try {
|
|
266
167
|
child = spawn(
|
|
267
|
-
|
|
268
|
-
|
|
168
|
+
binaryPath,
|
|
169
|
+
process.argv.slice(2),
|
|
269
170
|
applyHostedWindowsChildOptions({
|
|
270
171
|
stdio: "inherit",
|
|
271
|
-
env
|
|
172
|
+
env: {
|
|
173
|
+
...process.env,
|
|
174
|
+
// The compiled binary cannot infer a Node executable from its own
|
|
175
|
+
// process image. The npm launcher is the authority for this install
|
|
176
|
+
// form and hands off its exact interpreter as the canonical launcher.
|
|
177
|
+
CODEM_PLUGIN_NODE: process.execPath
|
|
178
|
+
}
|
|
272
179
|
})
|
|
273
180
|
);
|
|
274
|
-
|
|
181
|
+
stopWindowsHostMigrationWatch = watchWindowsDaemonHostMigration({
|
|
275
182
|
binaryPath,
|
|
276
183
|
daemonPid: child.pid,
|
|
277
184
|
launcherPid: process.pid
|
|
278
185
|
});
|
|
279
186
|
} catch (error) {
|
|
280
|
-
reportSpawnFailure(
|
|
187
|
+
reportSpawnFailure(binaryPath, error);
|
|
281
188
|
}
|
|
282
189
|
|
|
283
190
|
// 终端会把 SIGINT/SIGHUP 广播给整个前台进程组,但 execFile timeout、
|
|
284
191
|
// child.kill()、launchd/systemd 等调用方也会只命中 launcher PID。三类终止
|
|
285
192
|
// 信号都显式转发,保证后一种场景不会留下 Bun 子进程;child.kill 只命中
|
|
286
193
|
// 直接子进程,不会把同一信号再次广播给它下面的 linco 进程组。
|
|
287
|
-
const
|
|
194
|
+
const signalHandlers = new Map();
|
|
195
|
+
for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) {
|
|
196
|
+
const handler = () => {
|
|
197
|
+
if (child.exitCode !== null || child.signalCode !== null) {
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
try {
|
|
201
|
+
child.kill(signal);
|
|
202
|
+
} catch {
|
|
203
|
+
// child already gone
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
signalHandlers.set(signal, handler);
|
|
207
|
+
process.on(signal, handler);
|
|
208
|
+
}
|
|
288
209
|
|
|
289
210
|
child.on("error", (error) => {
|
|
290
|
-
reportSpawnFailure(
|
|
211
|
+
reportSpawnFailure(binaryPath, error);
|
|
291
212
|
});
|
|
292
213
|
|
|
293
214
|
child.on("exit", (code, signal) => {
|
|
294
215
|
stopWindowsHostMigrationWatch();
|
|
295
|
-
|
|
216
|
+
for (const [registeredSignal, handler] of signalHandlers) {
|
|
217
|
+
process.removeListener(registeredSignal, handler);
|
|
218
|
+
}
|
|
296
219
|
if (signal) {
|
|
297
220
|
// 让退出信号对上游可见:自己的 handler 已摘掉,可以安全补发同名信号。
|
|
298
221
|
process.kill(process.pid, signal);
|
package/bin/tt-env.js
CHANGED
|
@@ -58,7 +58,7 @@ export function resolveTtEnvLane(env = process.env) {
|
|
|
58
58
|
return parseTtEnvLane(env?.[CODEM_X_TT_ENV]);
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
-
|
|
61
|
+
function isOfficialCodemHost(hostname) {
|
|
62
62
|
const host = hostname.toLowerCase();
|
|
63
63
|
return host === PROD_ROUTER_HOST || host === BOE_ROUTER_HOST;
|
|
64
64
|
}
|
|
@@ -34,8 +34,7 @@ export function workerRuntimeTelemetryTarget({env=process.env,args=process.argv.
|
|
|
34
34
|
if (!['http:','https:'].includes(url.protocol) || url.username || url.password) return null;
|
|
35
35
|
url.pathname=`${url.pathname.replace(/\/+$/,'') || '/goapi/codem'}/sandbox/telemetry/workflow_metrics`;
|
|
36
36
|
url.search='';url.hash='';
|
|
37
|
-
|
|
38
|
-
return {url,headers:{'Content-Type':'application/json',Authorization:`Bearer ${bearer}`,...ttEnvHeadersFor(url,env)}};
|
|
37
|
+
return {url,headers:{'Content-Type':'application/json',Authorization:`Bearer sandbox_${env.CODEM_TOKEN}`,...ttEnvHeadersFor(url,env)}};
|
|
39
38
|
}
|
|
40
39
|
|
|
41
40
|
export async function reportWorkerRuntime(runtime,{env=process.env,args=process.argv.slice(2),signal,timeoutMS=750}={}) {
|
package/package.json
CHANGED
|
@@ -1,17 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lark-codem/codem-cli",
|
|
3
|
-
"version": "0.1.281-dev.
|
|
3
|
+
"version": "0.1.281-dev.100104631660.0.gd9b8134",
|
|
4
4
|
"codemServiceManagementProtocol": 3,
|
|
5
|
-
"codemSharedRuntime": 2,
|
|
6
5
|
"codemProfileProtocol": 1,
|
|
7
|
-
"codemAuthProtocol": 1,
|
|
8
6
|
"type": "module",
|
|
9
7
|
"description": "CodeM local CLI for Feishu-driven coding sessions",
|
|
10
8
|
"license": "SEE LICENSE IN LICENSE",
|
|
11
9
|
"files": [
|
|
12
10
|
"bin",
|
|
13
11
|
"profile",
|
|
14
|
-
"auth",
|
|
15
12
|
"LICENSE"
|
|
16
13
|
],
|
|
17
14
|
"os": [
|
|
@@ -32,17 +29,17 @@
|
|
|
32
29
|
"access": "public"
|
|
33
30
|
},
|
|
34
31
|
"dependencies": {
|
|
35
|
-
"@lark-codem/codem-core": "0.8.98-dev.
|
|
32
|
+
"@lark-codem/codem-core": "0.8.98-dev.100104631660.0.g5923e0f",
|
|
36
33
|
"zod": "3.25.76",
|
|
37
|
-
"@lark-codem/lark-cli": "0.1.
|
|
34
|
+
"@lark-codem/lark-cli": "0.1.5"
|
|
38
35
|
},
|
|
39
36
|
"optionalDependencies": {
|
|
40
|
-
"@lark-codem/codem-cli-darwin-arm64": "0.1.281-dev.
|
|
41
|
-
"@lark-codem/codem-cli-darwin-x64": "0.1.281-dev.
|
|
42
|
-
"@lark-codem/codem-cli-linux-arm64": "0.1.281-dev.
|
|
43
|
-
"@lark-codem/codem-cli-linux-x64": "0.1.281-dev.
|
|
44
|
-
"@lark-codem/codem-cli-win32-arm64": "0.1.281-dev.
|
|
45
|
-
"@lark-codem/codem-cli-win32-x64": "0.1.281-dev.
|
|
37
|
+
"@lark-codem/codem-cli-darwin-arm64": "0.1.281-dev.100104631660.0.gd9b8134",
|
|
38
|
+
"@lark-codem/codem-cli-darwin-x64": "0.1.281-dev.100104631660.0.gd9b8134",
|
|
39
|
+
"@lark-codem/codem-cli-linux-arm64": "0.1.281-dev.100104631660.0.gd9b8134",
|
|
40
|
+
"@lark-codem/codem-cli-linux-x64": "0.1.281-dev.100104631660.0.gd9b8134",
|
|
41
|
+
"@lark-codem/codem-cli-win32-arm64": "0.1.281-dev.100104631660.0.gd9b8134",
|
|
42
|
+
"@lark-codem/codem-cli-win32-x64": "0.1.281-dev.100104631660.0.gd9b8134"
|
|
46
43
|
},
|
|
47
44
|
"engines": {
|
|
48
45
|
"node": ">=18"
|
|
@@ -31,6 +31,7 @@ export class CredentialStorageError extends Error {
|
|
|
31
31
|
export function isRecoverableCredentialState(error) {
|
|
32
32
|
return error?.code === "credential_storage_rotation_pending"
|
|
33
33
|
|| error?.code === "credential_storage_rotation_unknown"
|
|
34
|
-
//
|
|
34
|
+
// A missing OAuth record permits reauthorization with the existing device,
|
|
35
|
+
// never use of its stale plaintext mirror or another credential kind.
|
|
35
36
|
|| (error?.code === "credential_storage_missing" && error.kind === "oauth");
|
|
36
37
|
}
|
|
@@ -44,8 +44,7 @@ export async function readProfileSnapshot(home) {
|
|
|
44
44
|
return withCodeMConfigLock(join(home, "config.json"), () => readLockedProfileSnapshot(home));
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
-
|
|
48
|
-
export async function readLockedProfileSnapshot(home) {
|
|
47
|
+
async function readLockedProfileSnapshot(home) {
|
|
49
48
|
const configPath = join(home, "config.json");
|
|
50
49
|
const config = await readProfileObject(configPath);
|
|
51
50
|
let metadata;
|
package/profile/runtime-logs.js
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import { realtimeLogID } from "./realtime-log-id.js";
|
|
2
|
-
import { sandboxObservationContext, sandboxLogUploadAllowed } from "./sandbox-observability.js";
|
|
3
1
|
import { workerRuntimeAttributes } from "./worker-runtime-observation.js";
|
|
4
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
5
3
|
import os from "node:os";
|
|
@@ -80,47 +78,26 @@ const OBSERVATION_METRICS = {
|
|
|
80
78
|
};
|
|
81
79
|
const EXTRA_FIELDS = ["observation_id", "runtime_client_instance_id", "command_id", "delivery_id", "probe_id", "sync_id", "transport_request_id", "attempt_id"];
|
|
82
80
|
const LIFECYCLE_EXTRA_FIELDS = [...EXTRA_FIELDS, "process_instance_id", "startup_id", "request_id", "event_id"];
|
|
83
|
-
const UPLINK_BATCH_METRICS = [
|
|
84
|
-
"message_count", "packet_bytes", "queue_wait_ms", "encode_ms", "ack_wait_ms",
|
|
85
|
-
"batch_sequence", "pending_count", "pending_bytes"
|
|
86
|
-
];
|
|
87
|
-
const UPLINK_DIAGNOSTIC_METRICS = new Map([
|
|
88
|
-
["uplink_queue_pressure", ["pending_count", "pending_bytes", "oldest_age_ms", "full_count", "batch_sequence", "ack_wait_ms"]],
|
|
89
|
-
["event_handoff_failed", UPLINK_BATCH_METRICS],
|
|
90
|
-
["uplink_batch_slow", UPLINK_BATCH_METRICS]
|
|
91
|
-
]);
|
|
92
81
|
const STRING_FIELDS = new Set([
|
|
93
|
-
|
|
94
|
-
"
|
|
95
|
-
"lane", "target_kind", "frontier_did", "packet_kind", "packet_traceparent",
|
|
82
|
+
...EXTRA_FIELDS, "command_type", "ack_status", "ack_outcome", "readback_scope", "timing_origin", "required_capability",
|
|
83
|
+
"request_id", "command_id", "session_id", "task_id", "dispatch_id", "event_id", "sync_id",
|
|
96
84
|
"process_instance_id", "run_id", "stage", "phase", "status", "outcome", "reason", "action",
|
|
97
85
|
"error_class", "error_code", "error_kind", "error_type", "code", "signal", "stop_reason",
|
|
98
86
|
"first_error", "retry_source", "cleanup_result",
|
|
99
87
|
"terminal_event", "event_type", "actor_type", "source", "trigger", "hook_id", "hook_event",
|
|
100
88
|
"target_version", "cli_version", "core_version", "version", "previous_state", "state",
|
|
101
89
|
"failure_kind", "failure_impact", "failure_type", "failure_subtype", "failure_code", "failure_status", "delay_source", "mode", "provider", "name", "termination", "interaction_id", "interaction_kind", "owner_state", "artifact_id", "resource_type", "delivery_mode", "host", "scheme", "tool_call_id", "tool_name", "background_task_id", "model", "artifact_kind", "codem_user_id", "device_id", "operation", "foreground_error_code",
|
|
102
|
-
"
|
|
103
|
-
"operation_id", "entrypoint", "workflow_launch_id", "runtime_client_instance_id", "connection_instance_id", "lease_epoch",
|
|
104
|
-
"load_id", "refresh_id", "registry_snapshot_id", "capability_key", "capability_type",
|
|
105
|
-
"component_type", "publisher_type", "capability_source", "installation_mode",
|
|
106
|
-
"capability_version", "project_key", "business_scene", "invocation_id", "result",
|
|
107
|
-
"error_category", "runtime_scope", "refresh_trigger", "load_trigger", "stage_name",
|
|
108
|
-
"operation_name", "invocation_source", "binding_state", "load_result"
|
|
90
|
+
"operation_id", "entrypoint", "workflow_launch_id"
|
|
109
91
|
]);
|
|
110
92
|
const VALUE_FIELDS = new Set([
|
|
111
93
|
"session_retained", "lease_valid_until_ms", "requested_valid_until_ms", "lease_remaining_ms", "wall_remaining_ms",
|
|
112
|
-
"local_rpc_id", "batch_index", "rpc_error_code", "has_subscribers", "window_active",
|
|
113
94
|
...new Set(Object.values(OBSERVATION_METRICS).flat()),
|
|
114
95
|
"pid", "exit_code", "duration_ms", "elapsed_ms", "wait_ms", "run_ms", "total_ms", "took_ms",
|
|
115
96
|
"attempt", "attempts", "attempt_count", "retryable", "http_status", "errno", "active_task_count",
|
|
116
97
|
"pending_event_count", "pending_command_ack_count", "next_retry_ms", "consecutive_failures",
|
|
117
|
-
...Array.from(UPLINK_DIAGNOSTIC_METRICS.values()).flat(), "transport_open",
|
|
118
98
|
"outage_duration_ms", "startup_duration_ms", "failed_attempts", "active_runs", "completed",
|
|
119
99
|
"delivered", "result_delivered", "queued_behind_existing", "expected", "timed_out",
|
|
120
100
|
"force_exit_ms", "teardown_ceiling_ms", "recovered", "count", "ms_since_process_start", "owner_pid", "consumed", "delivery_attempt", "ack_deadline_ms", "command_to_bridge_ms", "size_bytes", "source_size_bytes", "processed_bytes", "before", "after", "omitted_detail_count", "opened", "selected", "foreground",
|
|
121
|
-
"expected_count", "loaded_count", "loaded_capability_count", "failed_count", "skipped_count", "ready_count", "downloaded_count", "turn_id", "turn_index",
|
|
122
|
-
"late_rpc_error_code", "lifecycle_wait_ms", "prepare_ms", "router_cred_ms", "meegle_init_ms", "spawn_init_ms", "budget_ms",
|
|
123
|
-
"oauth_ms", "project_list_ms", "config_total_ms", "write_total_ms",
|
|
124
101
|
...LIFECYCLE_METRICS
|
|
125
102
|
]);
|
|
126
103
|
|
|
@@ -138,7 +115,7 @@ function optional(read) {
|
|
|
138
115
|
}
|
|
139
116
|
|
|
140
117
|
function metricProjection(event, fields = {}) {
|
|
141
|
-
return { count: 1, ...Object.fromEntries((OBSERVATION_METRICS[event] ??
|
|
118
|
+
return { count: 1, ...Object.fromEntries((OBSERVATION_METRICS[event] ?? [])
|
|
142
119
|
.filter(key => typeof fields?.[key] === "number" && Number.isFinite(fields[key]) && fields[key] >= 0)
|
|
143
120
|
.map(key => [key, fields[key]])) };
|
|
144
121
|
}
|
|
@@ -147,18 +124,11 @@ function extraProjection(fields = {}) {
|
|
|
147
124
|
return Object.fromEntries(EXTRA_FIELDS.filter(key => token(fields?.[key])).map(key => [key, token(fields[key])]));
|
|
148
125
|
}
|
|
149
126
|
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
function projectFields(input, fingerprintErrors = true, component) {
|
|
127
|
+
function projectFields(input, fingerprintErrors = true) {
|
|
153
128
|
const result = {};
|
|
154
129
|
for (const [key, value] of Object.entries(input ?? {}).slice(0, 100)) {
|
|
155
130
|
const name = fieldName(key);
|
|
156
|
-
if (
|
|
157
|
-
result[name] = value;
|
|
158
|
-
} else if (component === "realtime" && REALTIME_IDS.has(name)) {
|
|
159
|
-
const id = realtimeLogID(value);
|
|
160
|
-
if (id !== undefined) result[name] = id;
|
|
161
|
-
} else if (STRING_FIELDS.has(name)) {
|
|
131
|
+
if (STRING_FIELDS.has(name)) {
|
|
162
132
|
const safe = token(value);
|
|
163
133
|
if (safe) result[name] = safe;
|
|
164
134
|
} else if (VALUE_FIELDS.has(name) && (typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value)))) {
|
|
@@ -209,92 +179,7 @@ function lifecycleErrorCode(fields) {
|
|
|
209
179
|
return fields.outcome === "failed" || fields.outcome === "rejected" || fields.outcome === "conflicting" ? "unknown" : undefined;
|
|
210
180
|
}
|
|
211
181
|
|
|
212
|
-
const REALTIME_LOG_ONLY = new Set([
|
|
213
|
-
"app_server_rpc", "app_server_rpc_unmatched", "app_server_rpc_late_reply", "app_server_host_attached",
|
|
214
|
-
"app_server_host_failed", "app_server_host_reused_failed", "app_server_host_prepare", "artifact_operation_failed",
|
|
215
|
-
"app_server_resume_binding_failed", "app_server_question", "hitl_answer",
|
|
216
|
-
"downlink_admission", "rpc_reply", "uplink_commit", "uplink_transport", "subscription_query", "runtime_lease"
|
|
217
|
-
]);
|
|
218
|
-
|
|
219
|
-
const LOCAL_SENSITIVE_KEY = /^(?:oauth|authorization|token|secret|password|apikey|api_key|ak|access_key|secret_key|refresh_token|access_token|user_access_token|uat|rt|device_secret|device_secret_plaintext)$/iu;
|
|
220
|
-
|
|
221
|
-
const defaultRealtimeSink = {
|
|
222
|
-
info(line) {
|
|
223
|
-
const out = console;
|
|
224
|
-
out.info(line);
|
|
225
|
-
},
|
|
226
|
-
warn(line) {
|
|
227
|
-
const out = console;
|
|
228
|
-
out.warn(line);
|
|
229
|
-
},
|
|
230
|
-
error(line) {
|
|
231
|
-
const out = console;
|
|
232
|
-
out.error(line);
|
|
233
|
-
}
|
|
234
|
-
};
|
|
235
|
-
|
|
236
|
-
function serializeLocalValue(value, depth = 0) {
|
|
237
|
-
if (value === null || value === undefined) return undefined;
|
|
238
|
-
if (typeof value === "string") return value.length > 1024 ? `${value.slice(0, 1021)}...` : value;
|
|
239
|
-
if (typeof value === "number") return Number.isFinite(value) ? value : undefined;
|
|
240
|
-
if (typeof value === "boolean") return value;
|
|
241
|
-
if (value instanceof Error) {
|
|
242
|
-
const summary = {
|
|
243
|
-
error_type: value.name || "Error",
|
|
244
|
-
error_message: typeof value.message === "string" ? value.message.slice(0, 1024) : ""
|
|
245
|
-
};
|
|
246
|
-
if (value.code !== undefined) summary.error_code = String(value.code).slice(0, 128);
|
|
247
|
-
if (value.errno !== undefined) summary.errno = value.errno;
|
|
248
|
-
if (value.rpcError?.code !== undefined) summary.rpc_error_code = value.rpcError.code;
|
|
249
|
-
return summary;
|
|
250
|
-
}
|
|
251
|
-
if (depth >= 3) return undefined;
|
|
252
|
-
if (Array.isArray(value)) {
|
|
253
|
-
return value.slice(0, 32).map(entry => serializeLocalValue(entry, depth + 1)).filter(entry => entry !== undefined);
|
|
254
|
-
}
|
|
255
|
-
if (typeof value === "object") {
|
|
256
|
-
const out = {};
|
|
257
|
-
for (const [key, entry] of Object.entries(value)) {
|
|
258
|
-
if (entry === undefined || LOCAL_SENSITIVE_KEY.test(key)) continue;
|
|
259
|
-
const serialized = serializeLocalValue(entry, depth + 1);
|
|
260
|
-
if (serialized !== undefined) out[key] = serialized;
|
|
261
|
-
}
|
|
262
|
-
return out;
|
|
263
|
-
}
|
|
264
|
-
return undefined;
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
export function writeLocalRealtimeLog(level, event, fields = {}, { logger } = {}) {
|
|
268
|
-
try {
|
|
269
|
-
if (logger === null) return;
|
|
270
|
-
if (!logger && process.env.NODE_TEST_CONTEXT && process.env.CODEM_REALTIME_LOCAL_LOG !== "1") return;
|
|
271
|
-
const sink = logger ?? defaultRealtimeSink;
|
|
272
|
-
const payload = serializeLocalValue(fields) ?? {};
|
|
273
|
-
const line = `[codem][realtime][${event}] ${JSON.stringify(payload)}`;
|
|
274
|
-
if (level === "info") {
|
|
275
|
-
sink.info?.(line);
|
|
276
|
-
} else if (level === "error" || level === "fatal") {
|
|
277
|
-
(sink.error ?? sink.warn)?.call(sink, line);
|
|
278
|
-
} else {
|
|
279
|
-
sink.warn?.(line);
|
|
280
|
-
}
|
|
281
|
-
} catch { /* Local diagnostics must never affect business execution. */ }
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
export function writeLocalCoreStderr(pid, rawLine, { logger } = {}) {
|
|
285
|
-
try {
|
|
286
|
-
if (logger === null) return;
|
|
287
|
-
if (!logger && process.env.NODE_TEST_CONTEXT && process.env.CODEM_REALTIME_LOCAL_LOG !== "1") return;
|
|
288
|
-
const trimmed = String(rawLine ?? "").trim();
|
|
289
|
-
if (!trimmed) return;
|
|
290
|
-
const safe = trimmed.length > 2048 ? `${trimmed.slice(0, 2045)}...` : trimmed;
|
|
291
|
-
const sink = logger ?? defaultRealtimeSink;
|
|
292
|
-
sink.warn?.(`[codem][core-stderr][pid=${pid ?? "unknown"}] ${safe}`);
|
|
293
|
-
} catch { /* Forwarding child stderr must never fail the host. */ }
|
|
294
|
-
}
|
|
295
|
-
|
|
296
182
|
function keepLegacyMetric(event, fields, role, severity) {
|
|
297
|
-
if (REALTIME_LOG_ONLY.has(event)) return false;
|
|
298
183
|
if (/^startup\.(?:main|update_check|daemon_service_reconcile|login_gate|login_handoff_to_linco)$/u.test(event) && severity === "info") return false;
|
|
299
184
|
if (/(?:^|\.)drain_(?:started|completed)$/u.test(event) && severity === "info") return false;
|
|
300
185
|
if (role === "daemon" && event === "runtime_capability_probe" && severity === "info") return false;
|
|
@@ -328,7 +213,6 @@ export class RuntimeLogReporter {
|
|
|
328
213
|
#live = { queue: [], inflight: undefined, abort: undefined };
|
|
329
214
|
#replay = { queue: [], inflight: undefined, abort: undefined };
|
|
330
215
|
#identity = {};
|
|
331
|
-
#resourceContext = {};
|
|
332
216
|
#timer;
|
|
333
217
|
#closed = false;
|
|
334
218
|
#dropped = 0;
|
|
@@ -347,11 +231,10 @@ export class RuntimeLogReporter {
|
|
|
347
231
|
#restoring;
|
|
348
232
|
#savedDuringRestore = new Set();
|
|
349
233
|
|
|
350
|
-
constructor({ role = "cli", version = "unknown",
|
|
234
|
+
constructor({ role = "cli", version = "unknown", send = sendSlardarPcBatch, instanceId = randomUUID(), diagnosticId: supportId = diagnosticId(), platform = process.platform, osVersion = os.release(), crashDirectory } = {}) {
|
|
351
235
|
this.#send = send;
|
|
352
236
|
this.#crashDirectory = crashDirectory;
|
|
353
237
|
this.#role = token(role) ?? "cli";
|
|
354
|
-
this.#resourceContext = sandboxObservationContext(env, role);
|
|
355
238
|
this.#version = token(version) ?? "unknown";
|
|
356
239
|
this.#instanceId = instanceId;
|
|
357
240
|
this.#diagnosticId = supportId;
|
|
@@ -379,12 +262,9 @@ export class RuntimeLogReporter {
|
|
|
379
262
|
if (!this.#crashDirectory) return;
|
|
380
263
|
try {
|
|
381
264
|
fs.mkdirSync(this.#crashDirectory, { recursive: true, mode: 0o700 });
|
|
382
|
-
const
|
|
383
|
-
|
|
384
|
-
const
|
|
385
|
-
const names = fs.readdirSync(this.#crashDirectory).filter(name => pattern.test(name));
|
|
386
|
-
if (names.length >= (migration ? 64 : 32)) return;
|
|
387
|
-
const name = `${prefix}${randomUUID()}.json`;
|
|
265
|
+
const names = fs.readdirSync(this.#crashDirectory).filter(name => /^js-[a-f0-9-]+\.json$/u.test(name));
|
|
266
|
+
if (names.length >= 32) return;
|
|
267
|
+
const name = `js-${randomUUID()}.json`;
|
|
388
268
|
const file = path.join(this.#crashDirectory, name);
|
|
389
269
|
fs.writeFileSync(file, JSON.stringify(entry), { flag: "wx", mode: 0o600 });
|
|
390
270
|
this.#savedDuringRestore?.add(name);
|
|
@@ -395,10 +275,7 @@ export class RuntimeLogReporter {
|
|
|
395
275
|
async #restoreCrashes() {
|
|
396
276
|
if (!this.#crashDirectory) return;
|
|
397
277
|
try {
|
|
398
|
-
const
|
|
399
|
-
const crashes = names.filter(name => /^js-[a-f0-9-]+\.json$/u.test(name)).slice(0, 32);
|
|
400
|
-
const migrations = names.filter(name => /^js-migration-[a-f0-9-]+\.json$/u.test(name)).slice(0, 64);
|
|
401
|
-
for (const name of [...crashes, ...migrations]) {
|
|
278
|
+
for (const name of (await fs.promises.readdir(this.#crashDirectory)).filter(name => /^js-[a-f0-9-]+\.json$/u.test(name)).slice(0, 32)) {
|
|
402
279
|
if (this.#closed) return;
|
|
403
280
|
if (this.#savedDuringRestore?.has(name)) continue;
|
|
404
281
|
const file = path.join(this.#crashDirectory, name);
|
|
@@ -406,13 +283,8 @@ export class RuntimeLogReporter {
|
|
|
406
283
|
const stat = await fs.promises.lstat(file);
|
|
407
284
|
if (!stat.isFile() || stat.size > 65536) continue;
|
|
408
285
|
const entry = JSON.parse(await fs.promises.readFile(file, "utf8"));
|
|
409
|
-
if (entry?.record?.category?.reporter !== "codem_js" || !entry.header) continue;
|
|
286
|
+
if (entry?.record?.category?.reporter !== "codem_js" || entry?.record?.log_type !== "log" || !entry.header) continue;
|
|
410
287
|
if (this.#closed) return;
|
|
411
|
-
if (entry.record.log_type === "flexible" && entry.record.event_name?.startsWith("runtime.shared_migration.")) {
|
|
412
|
-
this.#replay.queue.push({ header: entry.header, record: entry.record, metricName: null, attempts: 0, crashFile: file });
|
|
413
|
-
continue;
|
|
414
|
-
}
|
|
415
|
-
if (entry.record.log_type !== "log") continue;
|
|
416
288
|
if (entry.metricName === LIFECYCLE_EVENT_NAME) {
|
|
417
289
|
entry.record.category.replay = "1";
|
|
418
290
|
this.#replay.queue.push({ ...entry, attempts: 0, crashFile: file });
|
|
@@ -444,37 +316,7 @@ export class RuntimeLogReporter {
|
|
|
444
316
|
|
|
445
317
|
get pendingCount() { return this.#live.queue.length + this.#replay.queue.length; }
|
|
446
318
|
get droppedCount() { return this.#dropped; }
|
|
447
|
-
|
|
448
|
-
#header() {
|
|
449
|
-
const identity = this.#identity;
|
|
450
|
-
return { aid: SLARDAR_PC_AID, device_id: identity.deviceId ?? this.#instanceId,
|
|
451
|
-
user_id: identity.userId ?? "0", parfait_version: SLARDAR_PC_REPORTER_VERSION,
|
|
452
|
-
channel: identity.channel ?? "unknown", os: this.#platform, os_version: this.#osVersion };
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
recordMetric(name, category, metrics, { persist = false } = {}) {
|
|
456
|
-
if (this.#closed) return false;
|
|
457
|
-
if (this.#live.queue.length >= CAPACITY) {
|
|
458
|
-
this.#dropped += 1;
|
|
459
|
-
return false;
|
|
460
|
-
}
|
|
461
|
-
const identity = this.#identity;
|
|
462
|
-
const record = {
|
|
463
|
-
app_version: this.#version, app_minor_version: "", build_id: "",
|
|
464
|
-
process_type: `codem-${this.#role}`, session_id: "", timestamp: Date.now(),
|
|
465
|
-
log_type: "flexible", event_name: name,
|
|
466
|
-
category: { reporter: "codem_js", runtime_role: this.#role,
|
|
467
|
-
...(identity.tenantId ? { tenant_id: identity.tenantId } : {}), ...category },
|
|
468
|
-
metrics
|
|
469
|
-
};
|
|
470
|
-
const entry = { header: this.#header(), record, metricName: null, attempts: 0 };
|
|
471
|
-
if (persist) this.#saveCrash(entry);
|
|
472
|
-
this.#live.queue.push(entry);
|
|
473
|
-
// Bursts need not wait for the periodic timer, and a slow collector still
|
|
474
|
-
// has only one bounded in-flight upload.
|
|
475
|
-
if (this.#live.queue.length >= BATCH_SIZE) void this.#flushLane(this.#live, REQUEST_TIMEOUT_MS);
|
|
476
|
-
return true;
|
|
477
|
-
}
|
|
319
|
+
get identityKey() { return JSON.stringify([this.#instanceId, this.#role, this.#identity.deviceId, this.#identity.userId, this.#identity.tenantId]); }
|
|
478
320
|
|
|
479
321
|
record(level, component, event, fields = {}) {
|
|
480
322
|
try {
|
|
@@ -485,17 +327,13 @@ export class RuntimeLogReporter {
|
|
|
485
327
|
|
|
486
328
|
#logEntry(level, component, event, fields) {
|
|
487
329
|
let safeFields;
|
|
488
|
-
try { safeFields = projectFields(fields
|
|
330
|
+
try { safeFields = projectFields(fields); } catch { safeFields = {}; }
|
|
489
331
|
if (OBSERVATION_EVENTS.has(event)) safeFields.observation_id = randomUUID();
|
|
490
332
|
const severity = ["info", "warn", "error", "fatal"].includes(level) ? level : "info";
|
|
491
333
|
// Keep arbitrary upstream error codes out of trusted-device metric dimensions.
|
|
492
334
|
const trustedDevice = TRUSTED_DEVICE_EVENTS.has(event);
|
|
493
335
|
const dimensions = trustedDevice ? {} : Object.fromEntries(["stage", "error_class", "error_code", "error_kind", "outcome"]
|
|
494
336
|
.filter(key => safeFields[key]).map(key => [key, safeFields[key]]));
|
|
495
|
-
if (UPLINK_DIAGNOSTIC_METRICS.has(event)) {
|
|
496
|
-
if (safeFields.lane) dimensions.lane = safeFields.lane;
|
|
497
|
-
if (safeFields.target_kind) dimensions.target_kind = safeFields.target_kind;
|
|
498
|
-
}
|
|
499
337
|
if (OBSERVATION_EVENTS.has(event)) {
|
|
500
338
|
for (const [key, values] of Object.entries(trustedDevice ? TRUSTED_DEVICE_DIMENSIONS : OBSERVATION_DIMENSIONS)) {
|
|
501
339
|
if (safeFields[key]) dimensions[key] = values.includes(safeFields[key]) ? safeFields[key] : "unknown";
|
|
@@ -557,7 +395,6 @@ export class RuntimeLogReporter {
|
|
|
557
395
|
}
|
|
558
396
|
|
|
559
397
|
#entry(severity, component, event, safeFields, identity, dimensions, includeLog) {
|
|
560
|
-
safeFields = { ...this.#resourceContext, ...safeFields, ...(this.#resourceContext.resource_id ? { resource_id: this.#resourceContext.resource_id } : {}) };
|
|
561
398
|
const category = {
|
|
562
399
|
...workerRuntimeAttributes(),
|
|
563
400
|
client_kind: "cli", runtime_role: this.#role, reporter: "codem_js", log_schema: "1",
|
|
@@ -728,9 +565,9 @@ export function runtimeLogIdentityKey() { return active?.identityKey; }
|
|
|
728
565
|
|
|
729
566
|
export function startRuntimeLogs({ role, version, env = process.env, send } = {}) {
|
|
730
567
|
try {
|
|
731
|
-
if (active ||
|
|
568
|
+
if (active || /^(1|true|yes)$/iu.test(env.CODEM_TELEMETRY_DISABLED ?? "") || env.NODE_TEST_CONTEXT) return;
|
|
732
569
|
const root = env.CODEM_HOME || env.LINCO_HOME || path.join(os.homedir(), ".codem");
|
|
733
|
-
active = new RuntimeLogReporter({ role, version,
|
|
570
|
+
active = new RuntimeLogReporter({ role, version, send, crashDirectory: path.join(root, "runtime-crashes") });
|
|
734
571
|
} catch { /* Monitoring initialization never prevents a command from running. */ }
|
|
735
572
|
}
|
|
736
573
|
|
|
@@ -756,10 +593,6 @@ export function flushRuntimeLogsInBackground() {
|
|
|
756
593
|
if (active) setImmediate(() => { void active?.flush().catch(() => {}); }).unref?.();
|
|
757
594
|
}
|
|
758
595
|
|
|
759
|
-
export function recordRuntimeMetric(name, category, metrics, options) {
|
|
760
|
-
try { return active?.recordMetric(name, category, metrics, options) ?? false; } catch { return false; }
|
|
761
|
-
}
|
|
762
|
-
|
|
763
596
|
export function persistRuntimeCrash(component, event, fields) {
|
|
764
597
|
try { active?.persistCrash(component, event, fields); } catch { /* best effort */ }
|
|
765
598
|
}
|
|
@@ -819,9 +652,9 @@ export function recordInteractiveProcessExit({ exitCode, signal }) {
|
|
|
819
652
|
export function recordSelectedRuntimeLog(component, event, fields = {}) {
|
|
820
653
|
try {
|
|
821
654
|
const selectedEvent = event.replace(/^linco\./u, "");
|
|
822
|
-
if (!/^(?:startup\.(?:main|update_check|daemon_service_reconcile|login_gate|login_handoff_to_linco)|oauth\.refresh\.(?:relogin_suspect|persist_failed|persisted)|managed_config\.(?:member_refresh_failed|sandbox_refresh_failed|sandbox_fetch_recovered|sandbox_fetch_exhausted|refreshed|resource_failed)|
|
|
655
|
+
if (!/^(?:startup\.(?:main|update_check|daemon_service_reconcile|login_gate|login_handoff_to_linco)|oauth\.refresh\.(?:relogin_suspect|persist_failed|persisted)|managed_config\.(?:member_refresh_failed|sandbox_refresh_failed|sandbox_fetch_recovered|sandbox_fetch_exhausted|refreshed|resource_failed)|(?:agent|command)\.(?:start|interactive_start|success|error|spawn_error|resolve_error|exit_drain_timeout|cancelled_before_spawn|artifact_oversize|artifact_missing|artifact_dropped|artifact_route_selected|artifact_image_upload|artifact_file_upload|artifact_local_register)|router\.credentials\.(?:ensured|refresh_failed)|config-lock\.release_failed|binary\.heal_chmod_failed|project\.(?:inject_error|state)|(?:permission_ask|user_question|plan)\.report_failed|process_tree\.(?:force_kill|force_kill_failed)|artifact\.(?:oversize|missing|dropped)|runtime_post\.daemon\.device_rebind_[a-z_]+)$/u.test(selectedEvent)) return;
|
|
823
656
|
const expected = optional(() => fields?.errorKind === "user_stop" || fields?.terminalError?.kind === "user_stop" || fields?.exitCode === 130 || fields?.signal === "SIGINT");
|
|
824
|
-
const level = expected ? "info" : (fields?.status === "failed" ||
|
|
657
|
+
const level = expected ? "info" : (fields?.status === "failed" || /(?:failed|error|exhausted|timeout)$/u.test(event)) ? "error" : /(?:suspect|dropped|missing|oversize)$/u.test(event) ? "warn" : "info";
|
|
825
658
|
recordRuntimeLog(level, component, event, fields);
|
|
826
659
|
} catch { /* best effort */ }
|
|
827
660
|
}
|
package/auth/index.d.ts
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
export interface UserAccessTokenIdentity {
|
|
2
|
-
readonly userId: string
|
|
3
|
-
readonly tenantId: string
|
|
4
|
-
readonly serverOrigin: 'https://codem.feishu.cn' | 'https://codem.feishu-boe.cn'
|
|
5
|
-
readonly revision: string
|
|
6
|
-
}
|
|
7
|
-
export interface UserAccessTokenProvider {
|
|
8
|
-
getValidUserAccessToken(): Promise<{ readonly userAccessToken: string; readonly expiresAt: string }>
|
|
9
|
-
dispose(): void
|
|
10
|
-
}
|
|
11
|
-
export class CodeMUserAccessTokenError extends Error {
|
|
12
|
-
readonly code: string
|
|
13
|
-
}
|
|
14
|
-
export function createUserAccessTokenProvider(options: {
|
|
15
|
-
readonly home: string
|
|
16
|
-
readonly identity: UserAccessTokenIdentity
|
|
17
|
-
readonly ttEnv: string | null
|
|
18
|
-
readonly fetchImpl?: typeof fetch
|
|
19
|
-
}): UserAccessTokenProvider
|