@lark-codem/codem-cli 0.1.281-dev.100104639844.0.ga23aea5 → 0.1.281-dev.100104658625.0.g0f105de

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.
@@ -3,11 +3,11 @@
3
3
  import os from "node:os";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { fileURLToPath } from "node:url";
6
- import path from "node:path";
7
- import { sendSlardarPcBatch } from "./slardar-pc-transport.js";
6
+ import fs from "node:fs";
7
+ import { sendSlardarPcBatch, captureRuntimeLogArguments, formatRuntimeLogText, runtimeLogSecrets } from "./slardar-pc-transport.js";
8
8
 
9
9
  const id = value => typeof value === "string" && /^[a-z\d._:-]{1,128}$/iu.test(value) ? value : undefined;
10
- const FIELDS = ["resource_id", "resource_env", "operation_id", "stage", "outcome", "startup_id", "controller_id", "logical_sandbox_id", "sandbox_id", "dispatch_id", "request_id", "tenant_id", "tenant_key"];
10
+ const FIELDS = ["stage", "outcome", "startup_id", "controller_id", "logical_sandbox_id", "sandbox_id", "dispatch_id", "request_id", "tenant_id", "tenant_key"];
11
11
  const NUMBERS = ["exit_code", "errno", "http_status", "duration_ms"];
12
12
 
13
13
  export function createStartupLogger({ component, startupId, identity = {}, env = process.env, version = "unknown", send = sendSlardarPcBatch } = {}) {
@@ -16,11 +16,10 @@ export function createStartupLogger({ component, startupId, identity = {}, env =
16
16
  const source = id(component ?? env.CODEM_LOG_COMPONENT) ?? "sandbox-bootstrap";
17
17
  const fields = {
18
18
  startup_id: startup,
19
- ...(env.CODEM_SANDBOX_VERSION === "resource" ? { resource_id: id(env.CODEM_RESOURCE_ID), resource_env: id(env.CODEM_RESOURCE_ENV), operation_id: id(env.CODEM_RESOURCE_OPERATION_ID) } : {}),
20
19
  controller_id: id(identity.controllerId ?? env.CODEM_SANDBOX_CONTROLLER_ID),
21
20
  logical_sandbox_id: id(identity.logicalSandboxId ?? env.CODEM_SANDBOX_LOGICAL_SANDBOX_ID),
22
- sandbox_id: id(identity.sandboxId ?? env.CODEM_SANDBOX_DEVICE_ID),
23
- dispatch_id: id(identity.dispatchId ?? env.CODEM_SANDBOX_DISPATCH_ID),
21
+ sandbox_id: id(identity.sandboxId ?? env.CODEM_SANDBOX_ID ?? env.CODEM_SANDBOX_DEVICE_ID),
22
+ dispatch_id: id(identity.dispatchId ?? env.CODEM_DISPATCH_ID ?? env.CODEM_SANDBOX_DISPATCH_ID ?? env.DISPATCH_ID),
24
23
  tenant_id: id(identity.tenantId ?? env.CODEM_SANDBOX_TENANT_ID),
25
24
  tenant_key: id(identity.tenantKey ?? env.CODEM_SANDBOX_TENANT_KEY)
26
25
  };
@@ -28,8 +27,9 @@ export function createStartupLogger({ component, startupId, identity = {}, env =
28
27
  aid: "1880", device_id: id(identity.deviceId ?? env.CODEM_SANDBOX_DEVICE_ID) ?? processId, user_id: "0",
29
28
  parfait_version: "1.0.0.0", channel: "unknown", os: process.platform === "win32" ? "Windows" : process.platform === "darwin" ? "Mac OS X" : process.platform, os_version: os.release()
30
29
  };
30
+ const secrets = runtimeLogSecrets(env);
31
31
  const queue = [];
32
- let closed = env.CODEM_SANDBOX_LOG_UPLOAD_ENABLED !== "1" || /^(1|true|yes)$/iu.test(env.CODEM_TELEMETRY_DISABLED ?? "");
32
+ let closed = /^(1|true|yes)$/iu.test(env.CODEM_TELEMETRY_DISABLED ?? "");
33
33
  let inflight;
34
34
  let dropped = 0;
35
35
  let uploadFailures = 0;
@@ -43,9 +43,7 @@ export function createStartupLogger({ component, startupId, identity = {}, env =
43
43
  const safe = { ...fields };
44
44
  for (const key of FIELDS) if (id(context[key])) safe[key] = context[key];
45
45
  for (const key of NUMBERS) if (Number.isFinite(context[key])) safe[key] = context[key];
46
- const event = message === "sandbox bootstrap" ? "sandbox.bootstrap" : undefined;
47
- if (!event) return false;
48
- const entry = { level, event, fields: safe,
46
+ const entry = { level, args: captureRuntimeLogArguments([message]), fields: safe,
49
47
  timestamp: Number.isSafeInteger(timestamp) && timestamp >= 0 ? timestamp : Date.now(), observationId: randomUUID() };
50
48
  if (queue.length >= 256) { queue.shift(); dropped++; }
51
49
  queue.push(entry);
@@ -77,10 +75,10 @@ export function createStartupLogger({ component, startupId, identity = {}, env =
77
75
  app_version: version, app_minor_version: "", build_id: "", process_type: "codem-sandbox-bootstrap", session_id: "",
78
76
  timestamp: entry.timestamp, log_type: "log", log_level: entry.level === "fatal" ? "error" : entry.level,
79
77
  category: { reporter: "codem_bootstrap", runtime_role: "sandbox", component: source, event: "application.log", severity: entry.level,
80
- ...(fields.resource_env ? { resource_env: fields.resource_env } : {}),
78
+ ...(id(env.CODEM_RESOURCE_ENV) ? { resource_env: env.CODEM_RESOURCE_ENV } : {}),
81
79
  ...(id(env.CODEM_SANDBOX_TYPE) ? { sandbox_type: env.CODEM_SANDBOX_TYPE } : {}),
82
80
  ...(fields.tenant_id ? { tenant_id: fields.tenant_id } : {}) },
83
- log_content: `${entry.event}\n${JSON.stringify({ schema_version: 1, timestamp: entry.timestamp,
81
+ log_content: `${formatRuntimeLogText(entry.args, secrets)}\n${JSON.stringify({ schema_version: 1, timestamp: entry.timestamp,
84
82
  process_instance_id: processId, fields: { ...entry.fields, observation_id: entry.observationId } })}`
85
83
  }));
86
84
  try { await Promise.race([send({ header, data }, { signal: controller.signal }), expired]); }
@@ -122,6 +120,9 @@ export async function runStartupLogInput({ input = process.stdin, ...options } =
122
120
  logger.close();
123
121
  }
124
122
 
125
- if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
123
+ let isMain = false;
124
+ try { isMain = Boolean(process.argv[1]) && fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url)); }
125
+ catch { /* Importing the helper must not depend on the host entrypoint path. */ }
126
+ if (isMain) {
126
127
  runStartupLogInput().catch(() => {});
127
128
  }
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
- command,
268
- childArgs,
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
- if (command === binaryPath) stopWindowsHostMigrationWatch = watchWindowsDaemonHostMigration({
181
+ stopWindowsHostMigrationWatch = watchWindowsDaemonHostMigration({
275
182
  binaryPath,
276
183
  daemonPid: child.pid,
277
184
  launcherPid: process.pid
278
185
  });
279
186
  } catch (error) {
280
- reportSpawnFailure(command, error);
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 removeSignalHandlers = forwardChildSignals(child);
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(command, error);
211
+ reportSpawnFailure(binaryPath, error);
291
212
  });
292
213
 
293
214
  child.on("exit", (code, signal) => {
294
215
  stopWindowsHostMigrationWatch();
295
- removeSignalHandlers();
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);
@@ -1,6 +1,140 @@
1
1
  import https from "node:https";
2
2
  import { gzip } from "node:zlib";
3
3
  import { promisify } from "node:util";
4
+ import { formatWithOptions } from "node:util";
5
+ import { createHash } from "node:crypto";
6
+
7
+ export const MAX_LOG_TEXT_BYTES = 16 * 1024;
8
+ const MAX_ARGUMENT_CHARS = 8192;
9
+ const SECRET_KEY = /token|secret|password|passwd|cookie|authorization|credential|api[_-]?key|access[_-]?key|(?:^|_)(?:ak|uat|rt)(?:_|$)/iu;
10
+ const NON_CREDENTIAL_SETTING = /^(?:enable|disable|max|min|num)_|_(?:enabled|disabled|enable|disable|import|max_tokens|dir|path|file)$/iu;
11
+ const runtimeOutputErrors = new WeakSet();
12
+ const nativeErrorStackGetter = Object.getOwnPropertyDescriptor(new Error(), "stack")?.get;
13
+
14
+ // Explicit provenance at the child/SSE boundary. Never infer it from text or
15
+ // trust an upstream terminal_error.source field to authorize uploading content.
16
+ export function markRuntimeOutputError(error) {
17
+ runtimeOutputErrors.add(error);
18
+ return error;
19
+ }
20
+
21
+ export function isRuntimeOutputError(error) { return runtimeOutputErrors.has(error); }
22
+
23
+ // Called once at the configuration boundary. Keep old values while their logs
24
+ // are queued, including credentials rotated after a log was recorded.
25
+ export function runtimeLogSecrets(source = {}) {
26
+ return Object.entries(source).filter(([key, value]) => SECRET_KEY.test(key) && !NON_CREDENTIAL_SETTING.test(key) &&
27
+ typeof value === "string" && value.length >= 8 && !/^(?:\d+|true|false|none|null|enabled|disabled)$/iu.test(value))
28
+ .slice(0, 64).map(([, value]) => Buffer.from(value.slice(0, 8192), "utf16le").toString("utf16le"));
29
+ }
30
+
31
+ // The application call only retains a bounded argument list. Formatting and
32
+ // redaction happen later in the uploader, never in the logging call.
33
+ export function captureRuntimeLogArguments(args) {
34
+ let remaining = 32 * 1024;
35
+ const seen = new Set();
36
+ const text = value => {
37
+ // Even a short slice can flatten an entire V8 rope. Omit the remote copy
38
+ // before slicing or converting an oversized value; local args stay intact.
39
+ if (value.length > Math.min(MAX_ARGUMENT_CHARS, remaining)) value = "[oversized log argument omitted]";
40
+ // A sliced V8 string can retain its entire upstream allocation. Copy only
41
+ // the bounded UTF-16 code units, including any unmatched surrogate.
42
+ const result = Buffer.from(value.slice(0, Math.min(MAX_ARGUMENT_CHARS, remaining)), "utf16le").toString("utf16le");
43
+ remaining -= result.length;
44
+ return result;
45
+ };
46
+ function snapshot(value, depth = 0, framesOnly = false) {
47
+ if (typeof value === "string") return framesOnly ? { log_error: true, framesOnly: true, message: text(value), stack: "" } : text(value);
48
+ if (value === null || ["number", "boolean", "undefined"].includes(typeof value)) return value;
49
+ if (!(value instanceof Error)) return "[object omitted]";
50
+ if (seen.has(value) || depth >= 8 || remaining === 0) return "[error cause omitted]";
51
+ seen.add(value);
52
+ // Never invoke getters/custom inspection or retain arbitrary object graphs.
53
+ const own = key => Object.getOwnPropertyDescriptor(value, key)?.value;
54
+ function inheritedDescriptor(key) {
55
+ let holder = value;
56
+ for (let i = 0; holder && i < 8; i++, holder = Object.getPrototypeOf(holder)) {
57
+ const descriptor = Object.getOwnPropertyDescriptor(holder, key);
58
+ if (descriptor) return descriptor;
59
+ }
60
+ }
61
+ const messageDescriptor = inheritedDescriptor("message");
62
+ const nameDescriptor = inheritedDescriptor("name");
63
+ const message = messageDescriptor?.value;
64
+ const name = nameDescriptor?.value;
65
+ const capturedMessage = typeof message === "string" ? text(message) : "Error";
66
+ // Some V8 versions materialize lazy stack even when reading its descriptor.
67
+ // Check message/name first, without invoking accessors or coercing objects.
68
+ // Oversized errors omit their remote body and retain the original Error
69
+ // locally; never expand their complete body on this thread.
70
+ const safeLazyStack = typeof message === "string" && typeof name === "string" &&
71
+ message.length + name.length <= MAX_ARGUMENT_CHARS && remaining > 0;
72
+ const stackDescriptor = safeLazyStack ? Object.getOwnPropertyDescriptor(value, "stack") : undefined;
73
+ // Node 22/V8 exposes the genuine lazy stack as a native accessor. Do not
74
+ // execute application-defined getters masquerading as Error properties.
75
+ const rawStack = stackDescriptor?.value ?? (stackDescriptor?.get &&
76
+ stackDescriptor.get === nativeErrorStackGetter
77
+ ? stackDescriptor.get.call(value) : undefined);
78
+ // A preformatted stack can also be arbitrarily large. Reject it before
79
+ // searching for the message or splitting/filtering its lines.
80
+ const stack = typeof rawStack === "string" && rawStack.length <= MAX_ARGUMENT_CHARS ? rawStack : undefined;
81
+ const cause = own("cause");
82
+ framesOnly ||= runtimeOutputErrors.has(value);
83
+ // A provider message can itself contain lines beginning with "at". Remove
84
+ // the complete original message before selecting V8's actual trailing frames.
85
+ const header = framesOnly && typeof stack === "string" ? (!name ? message : !message ? name : `${name}: ${message}`) : undefined;
86
+ const frameStart = typeof stack === "string" && typeof header === "string" && stack.startsWith(header + "\n")
87
+ ? header.length + 1 : -1;
88
+ const frames = framesOnly
89
+ ? frameStart < 0 ? undefined : stack.slice(frameStart).split("\n").filter(line => /^\s+at\s/u.test(line)).join("\n")
90
+ : stack;
91
+ return { log_error: true, framesOnly, stack: typeof frames === "string" ? text(frames) : undefined,
92
+ message: capturedMessage,
93
+ ...(cause === undefined ? {} : { cause: snapshot(cause, depth + 1, framesOnly) }) };
94
+ }
95
+ return args.slice(0, 8).map(value => snapshot(value));
96
+ }
97
+
98
+ export function redactRuntimeLogText(input, secrets = []) {
99
+ let text = input;
100
+ for (const secret of secrets) text = text.split(secret).join("[REDACTED]");
101
+ return text
102
+ .replace(/((?:proxy-authorization|authorization|set-cookie|cookie)["']?\s*:\s*)[^\r\n]*/giu, "$1[REDACTED]")
103
+ .replace(/((?:prompt|tool[_ -]?(?:output|result)|stdout|stderr|response[_ -]?body|request[_ -]?body|payload)["']?\s*[:=]\s*)[^\n]*/giu, "$1[content omitted]")
104
+ .replace(/((?:Bearer|Basic)\s+)[a-z\d._~+/=-]+/giu, "$1[REDACTED]")
105
+ .replace(/(--(?:token|secret|password|passwd|api[_-]?key|access[_-]?key|ak|uat|rt|authorization|credential)\s+)(?:"(?:\\(?:[^\n]|(?=\n|$))|[^"\\\n])*"?|'(?:\\(?:[^\n]|(?=\n|$))|[^'\\\n])*'?|[^\s]+)/giu, "$1[REDACTED]")
106
+ // Scan each complete assignment key once. Matching sensitive substrings
107
+ // between greedy key fragments causes catastrophic backtracking on log text.
108
+ .replace(/\b([a-z_][a-z\d_-]*)(["']?\s*[:=]\s*)("(?:\\(?:[^\n]|(?=\n|$))|[^"\\\n])*"?|'(?:\\(?:[^\n]|(?=\n|$))|[^'\\\n])*'?|[^\s,;"'{}]+)/giu,
109
+ (match, key, separator, value) => {
110
+ if (!SECRET_KEY.test(key) && key.toLowerCase() !== "key") return match;
111
+ const quote = value[0] === '"' || value[0] === "'" ? value[0] : "";
112
+ return `${key}${separator}${quote}[REDACTED]${quote}`;
113
+ })
114
+ .replace(/\b(?:sk-[a-z\d_-]{8,}|(?:ghp|gho|ghu|ghs|ghr)_[a-z\d]{8,}|glpat-[a-z\d_-]{8,}|[ut]-[a-z\d_.-]{16,})\b/giu, "[REDACTED]")
115
+ .replace(/(?:(?<![A-Za-z0-9])(?:codem_at|uat|rt|cat|ak|llm_api_ak)|(?<=sandbox_)(?:codem_at|uat|rt|cat|ak))_[A-Za-z0-9._~+/=-]+/gu, "[REDACTED]")
116
+ .replace(/(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?(?![A-Za-z0-9_-])/gu, "[REDACTED]")
117
+ // Consume the whole token once. Anchored replacements cannot restart at
118
+ // every nested https:// prefix when a query/fragment delimiter is absent.
119
+ .replace(/https?:\/\/[^\s]+/giu, url => url
120
+ .replace(/^(https?:\/\/)[^\s/@:]+:[^\s/@]+@/iu, "$1[REDACTED]@")
121
+ .replace(/^(https?:\/\/[^\s?#]+)[?#][^\s]*/iu, "$1?[REDACTED]")
122
+ .replace(/^(https?:\/\/[^/\s?#]+)\/[^\s?#]*/iu, "$1/[path]"))
123
+ .replace(/(?<![\w:/])(?:file:\/+)?(?:[a-z]:[\\/]|\/)(?:[^\s\\/:()"']+[\\/])+([^\s\\/()"']+)/giu, "<path>/$1");
124
+ }
125
+
126
+ export function formatRuntimeLogText(args, secrets = []) {
127
+ function errorText(value) {
128
+ if (!value?.log_error) return value;
129
+ const ownText = value.framesOnly ? `Runtime output error (fingerprint=${createHash("sha256").update(value.message).digest("hex").slice(0, 24)})\n${value.stack ?? ""}` : (value.stack ?? value.message);
130
+ return ownText + (value.cause === undefined ? "" : `\nCaused by: ${errorText(value.cause)}`);
131
+ }
132
+ const formatted = formatWithOptions({ depth: 3, maxArrayLength: 20, maxStringLength: 8192, customInspect: false, getters: false },
133
+ ...args.map(errorText)).slice(0, 64 * 1024);
134
+ const safe = redactRuntimeLogText(formatted, secrets);
135
+ const bytes = Buffer.from(safe);
136
+ return bytes.length <= MAX_LOG_TEXT_BYTES ? safe : `${bytes.subarray(0, MAX_LOG_TEXT_BYTES - 32).toString("utf8")}\n[log truncated]`;
137
+ }
4
138
 
5
139
  // PC Custom Log / Custom Event wire format, verified against Parfait 1.7.0.0's
6
140
  // public IUploader callback. This is not the Slardar Web/BID protocol. Keep the
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
- export function isOfficialCodemHost(hostname) {
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
- const bearer=env.CODEM_TOKEN.startsWith('codem_resource.')?env.CODEM_TOKEN:`sandbox_${env.CODEM_TOKEN}`;
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.100104639844.0.ga23aea5",
3
+ "version": "0.1.281-dev.100104658625.0.g0f105de",
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.100104639844.0.g9589128",
32
+ "@lark-codem/codem-core": "0.8.98-dev.100104658625.0.gd2cb43d",
36
33
  "zod": "3.25.76",
37
- "@lark-codem/lark-cli": "0.1.6-test.20261129.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.100104639844.0.ga23aea5",
41
- "@lark-codem/codem-cli-darwin-x64": "0.1.281-dev.100104639844.0.ga23aea5",
42
- "@lark-codem/codem-cli-linux-arm64": "0.1.281-dev.100104639844.0.ga23aea5",
43
- "@lark-codem/codem-cli-linux-x64": "0.1.281-dev.100104639844.0.ga23aea5",
44
- "@lark-codem/codem-cli-win32-arm64": "0.1.281-dev.100104639844.0.ga23aea5",
45
- "@lark-codem/codem-cli-win32-x64": "0.1.281-dev.100104639844.0.ga23aea5"
37
+ "@lark-codem/codem-cli-darwin-arm64": "0.1.281-dev.100104658625.0.g0f105de",
38
+ "@lark-codem/codem-cli-darwin-x64": "0.1.281-dev.100104658625.0.g0f105de",
39
+ "@lark-codem/codem-cli-linux-arm64": "0.1.281-dev.100104658625.0.g0f105de",
40
+ "@lark-codem/codem-cli-linux-x64": "0.1.281-dev.100104658625.0.g0f105de",
41
+ "@lark-codem/codem-cli-win32-arm64": "0.1.281-dev.100104658625.0.g0f105de",
42
+ "@lark-codem/codem-cli-win32-x64": "0.1.281-dev.100104658625.0.g0f105de"
46
43
  },
47
44
  "engines": {
48
45
  "node": ">=18"
@@ -17,11 +17,11 @@ export const OAUTH_REAUTHORIZATION_HINT =
17
17
  "上次 OAuth 刷新尚未确认,将在下次连接时重试恢复;也可运行 codem login 重新登录(设备身份会保留)";
18
18
 
19
19
  export class CredentialStorageError extends Error {
20
- constructor(code, kind = null) {
20
+ constructor(code, kind = null, options = undefined) {
21
21
  const recovery = credentialStorageRecovery(code);
22
22
  const rotation = kind === "oauth" && (code === "rotation_pending" || code === "rotation_unknown");
23
23
  const suffix = recovery ? `。${recovery.message}。${recovery.hint}` : rotation ? `。${OAUTH_REAUTHORIZATION_HINT}。` : "";
24
- super(`Credential storage ${code}${kind ? ` (${kind})` : ""}${suffix}`);
24
+ super(`Credential storage ${code}${kind ? ` (${kind})` : ""}${suffix}`, options);
25
25
  this.name = "CredentialStorageError";
26
26
  this.code = `credential_storage_${code}`;
27
27
  this.kind = kind;
@@ -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
- // Missing OAuth can reauthorize the existing device, never another kind.
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
  }
@@ -5,7 +5,7 @@ export const CREDENTIAL_SCHEMA = 1;
5
5
  const KINDS = new Set(["oauth", "router-ak"]);
6
6
  const STATES = new Set(["legacy", "preparing", "secure"]);
7
7
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
8
- function fail(code, kind) { throw new CredentialStorageError(code, kind); }
8
+ function fail(code, kind, options) { throw new CredentialStorageError(code, kind, options); }
9
9
 
10
10
  export async function readCredentialMetadata(metadataPath, marker = null, expectedKind = null) {
11
11
  if (expectedKind && marker && marker.kind !== expectedKind) fail("scope_mismatch", expectedKind);
@@ -14,7 +14,7 @@ export async function readCredentialMetadata(metadataPath, marker = null, expect
14
14
  metadata = JSON.parse(await fs.readFile(metadataPath, "utf8"));
15
15
  } catch (error) {
16
16
  if (error.code === "ENOENT" && !marker) return null;
17
- fail(error.code === "ENOENT" ? "metadata_missing" : "metadata_unreadable");
17
+ fail(error.code === "ENOENT" ? "metadata_missing" : "metadata_unreadable", null, { cause: error });
18
18
  }
19
19
  if (metadata?.schemaVersion !== CREDENTIAL_SCHEMA) fail("incompatible");
20
20
  if (!UUID.test(metadata.scopeId) || !UUID.test(metadata.loginEpoch)
package/profile/debug.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { recordSelectedRuntimeLog } from "./runtime-logs.js";
2
+ import { redactDebugString } from "./diagnostic-text.js";
2
3
 
3
4
  const DEBUG_ENV_KEYS = ["CODEM_DEBUG", "CODEM_BRIDGE_DEBUG"];
4
5
  const SENSITIVE_KEY_PATTERN = /^(?:authorization|token|secret|password|apikey|api_key|apiKey|ak|access_key|accessKey|secret_key|secretKey|appsecret|app_secret|login_secret|refresh_token|access_token|user_access_token|userAccessToken|refreshToken|accessToken|uat|rt|deviceSecret|device_secret|deviceSecretPlaintext|device_secret_plaintext)$/iu;
@@ -12,19 +13,12 @@ export function isDebugEnabled(env = process.env) {
12
13
  return DEBUG_ENV_KEYS.some((key) => enabledValue(env?.[key]));
13
14
  }
14
15
 
15
- function redactString(value) {
16
- return String(value ?? "")
17
- .replace(/((?:Authorization|Codem-Login-Secret)\s*:\s*(?:Bearer\s+)?)[^&\s,"'}]+/giu, "$1[REDACTED]")
18
- .replace(/("(?:authorization|token|secret|apikey|api_key|apiKey|ak|access_key|accessKey|secret_key|secretKey|refresh_token|access_token|user_access_token|userAccessToken|refreshToken|accessToken)"\s*:\s*")[^"]*(")/giu, "$1[REDACTED]$2")
19
- .replace(/((?:refresh_token|access_token|user_access_token|refreshToken|accessToken|userAccessToken|apikey|api_key|apiKey|access_key|accessKey|secret_key|secretKey|uat|rt|token|secret|ak)\s*[=:]\s*)[^&\s,"'}]+/giu, "$1[REDACTED]");
20
- }
21
-
22
16
  export function sanitizeDebugPayload(value, { maxStringLength = 500, depth = 0 } = {}) {
23
17
  if (value === null || value === undefined) {
24
18
  return value;
25
19
  }
26
20
  if (typeof value === "string") {
27
- const redacted = redactString(value);
21
+ const redacted = redactDebugString(value);
28
22
  return redacted.length > maxStringLength ? `${redacted.slice(0, maxStringLength - 1)}...` : redacted;
29
23
  }
30
24
  if (typeof value === "number" || typeof value === "boolean") {
@@ -65,8 +59,8 @@ export function formatDebugLine(event, payload = {}) {
65
59
  // reports have already hit that wall: a daemon rebound itself once a minute for
66
60
  // ten minutes and the structured record of *why* was gated behind a flag nobody
67
61
  // had set. High-frequency loops (per-poll sync, command lists) stay on debugLog.
68
- export function debugLogAlways(event, payload = {}, { logger = console } = {}) {
69
- recordSelectedRuntimeLog("bridge", event, payload);
62
+ export function debugLogAlways(event, payload = {}, { logger = console, remoteFields = undefined } = {}) {
63
+ recordSelectedRuntimeLog("bridge", event, remoteFields ? { ...payload, ...remoteFields } : payload);
70
64
  const line = formatDebugLine(event, payload);
71
65
  if (logger && typeof logger.info === "function") {
72
66
  logger.info(line);
@@ -78,9 +72,15 @@ export function debugLogAlways(event, payload = {}, { logger = console } = {}) {
78
72
 
79
73
  export function debugLog(event, payload = {}, {
80
74
  env = process.env,
81
- logger = console
75
+ logger = console,
76
+ capturedError = undefined,
77
+ remoteFields = undefined
82
78
  } = {}) {
83
- recordSelectedRuntimeLog("bridge", event, payload);
79
+ recordSelectedRuntimeLog("bridge", event, remoteFields ? { ...payload, ...remoteFields } : payload, { capturedError });
80
+ return writeDebugLog(event, payload, { env, logger });
81
+ }
82
+
83
+ export function writeDebugLog(event, payload, { env, logger }) {
84
84
  if (!isDebugEnabled(env)) {
85
85
  return false;
86
86
  }
@@ -0,0 +1,49 @@
1
+ const MAX_DIAGNOSTIC_SCAN_CHARS = 32_768;
2
+ const MAX_DIAGNOSTIC_TEXT_CHARS = 4096;
3
+
4
+ function safeString(value) {
5
+ if (value === null || value === undefined) return "";
6
+ if (typeof value === "string") return value;
7
+ try { return String(value); } catch { return "[UNSTRINGIFIABLE_VALUE]"; }
8
+ }
9
+
10
+ export function redactDebugString(value) {
11
+ return safeString(value)
12
+ .replace(/((?:Authorization|Codem-Login-Secret)\s*:\s*(?:(?:Bearer|Basic)\s+)?)[^&\s,"'}]+/giu, "$1[REDACTED]")
13
+ .replace(/("(?:authorization|password|uat|rt|ak|api[_-]?key|access[_-]?key|host[_-]?session|[A-Za-z0-9_.-]{0,64}secret[A-Za-z0-9_.-]{0,64}|[A-Za-z0-9_.-]{0,64}token)"\s*:\s*")[^"]*("|$)/giu, "$1[REDACTED]$2")
14
+ .replace(/(?<![A-Za-z0-9_.-])((?:password|uat|rt|ak|api[_-]?key|access[_-]?key|host[_-]?session|[A-Za-z0-9_.-]{0,64}secret[A-Za-z0-9_.-]{0,64}|[A-Za-z0-9_.-]{0,64}token)\s*[=:]\s*)(?:(["'])([^\r\n]*?)(?:\2|$)|[^&\s,"'}]+)/giu, (_, prefix, quote) => quote ? `${prefix}${quote}[REDACTED]${quote}` : `${prefix}[REDACTED]`);
15
+ }
16
+
17
+ /** @param {unknown} value */
18
+ export function safeDiagnosticEndpoint(value) {
19
+ try {
20
+ const url = new URL(safeString(value));
21
+ url.username = "";
22
+ url.password = "";
23
+ url.search = "";
24
+ url.hash = "";
25
+ return url.toString();
26
+ } catch {
27
+ return "";
28
+ }
29
+ }
30
+
31
+ /** @param {unknown} value */
32
+ export function redactDiagnosticText(value, { redactURLPath = false, preserveURLPunctuation = true } = {}) {
33
+ const input = safeString(value);
34
+ const bounded = input.length > MAX_DIAGNOSTIC_SCAN_CHARS ? input.slice(0, MAX_DIAGNOSTIC_SCAN_CHARS) : input;
35
+ const withSafeURLs = bounded.replace(/https?:\/\/[^\s"'<>]+/giu, (rawURL) => {
36
+ let end = rawURL.length;
37
+ while (end > 0 && "),.;".includes(rawURL[end - 1])) end -= 1;
38
+ const url = rawURL.slice(0, end);
39
+ const safe = safeDiagnosticEndpoint(url);
40
+ const display = safe && redactURLPath ? new URL(safe).origin : safe;
41
+ return (display || "[REDACTED_URL]") + (preserveURLPunctuation ? rawURL.slice(end) : "");
42
+ });
43
+ const redacted = redactDebugString(withSafeURLs)
44
+ .replace(/\bBearer\s+[^&\s,"'}]+/giu, "Bearer [REDACTED]")
45
+ .replace(/\b((?:Set-)?Cookie:[ \t]*)[^\r\n]+/giu, "$1[REDACTED]")
46
+ .replace(/(?:(?<![A-Za-z0-9])(?:codem_at|uat|rt|cat|ak|llm_api_ak)|(?<=sandbox_)(?:codem_at|uat|rt|cat|ak))_[A-Za-z0-9._~+/=-]+/gu, "[REDACTED]")
47
+ .replace(/(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?(?![A-Za-z0-9_-])/gu, "[REDACTED_JWT]");
48
+ return redacted.length > MAX_DIAGNOSTIC_TEXT_CHARS ? redacted.slice(0, MAX_DIAGNOSTIC_TEXT_CHARS) : redacted;
49
+ }
@@ -0,0 +1,17 @@
1
+ /** @param {unknown} value */
2
+ export function safeServerLogId(value) {
3
+ return typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/u.test(value) ? value : undefined;
4
+ }
5
+
6
+ export function httpReadDiagnostics(response, reason) {
7
+ let logId = null;
8
+ try {
9
+ logId = safeServerLogId(response?.headers?.get?.("x-tt-logid")) ?? null;
10
+ } catch {}
11
+ return {
12
+ httpStatus: Number.isInteger(response?.status) && response.status >= 100 && response.status <= 599
13
+ ? response.status : null,
14
+ logId,
15
+ reason
16
+ };
17
+ }