@lark-codem/codem-cli 0.1.279-dev.100104376703.0.g07159f3 → 0.1.279-dev.100104423302.0.g324b5ae

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.
@@ -140,6 +140,7 @@ export async function snapshotDescendantPids(
140
140
  *
141
141
  * `descendants` 由调用方在树还完整时用 snapshotDescendantPids 取样后传入;
142
142
  * 不传就现取(只在父进程仍活着时才有意义)。
143
+ * 父进程已退出时传 pid: null 和已记录的 descendants,只清理后代,避免向复用的父 PID 发信号。
143
144
  *
144
145
  * 返回实际发出信号的 pid 数——调用方用它做日志,不做控制流:kill 失败绝大多数
145
146
  * 是"进程已经没了",那正是我们要的结果。
@@ -154,7 +155,8 @@ export async function terminateProcessTree({
154
155
  timeoutMs = null,
155
156
  onError = null
156
157
  } = {}) {
157
- if (!Number.isInteger(pid) || pid <= 0) {
158
+ const hasRoot = Number.isInteger(pid) && pid > 0;
159
+ if (!hasRoot && !Array.isArray(descendants)) {
158
160
  return { signaled: 0 };
159
161
  }
160
162
 
@@ -165,19 +167,21 @@ export async function terminateProcessTree({
165
167
 
166
168
  if (platform === "win32") {
167
169
  // /T 覆盖此刻仍挂在 pid 下的活树,一次调用比逐个 taskkill 更少竞态。
168
- try {
169
- await execFileImpl(
170
- "taskkill.exe",
171
- ["/F", "/T", "/PID", String(pid)],
172
- applyHostedWindowsChildOptions(
173
- Number.isFinite(timeoutMs) && timeoutMs > 0 ? { timeout: timeoutMs } : {},
174
- { platform }
175
- )
176
- );
177
- signaled += 1;
178
- } catch (error) {
179
- // pid 已消失时 taskkill 返回非 0,属预期。
180
- onError?.(error);
170
+ if (hasRoot) {
171
+ try {
172
+ await execFileImpl(
173
+ "taskkill.exe",
174
+ ["/F", "/T", "/PID", String(pid)],
175
+ applyHostedWindowsChildOptions(
176
+ Number.isFinite(timeoutMs) && timeoutMs > 0 ? { timeout: timeoutMs } : {},
177
+ { platform }
178
+ )
179
+ );
180
+ signaled += 1;
181
+ } catch (error) {
182
+ // pid 已消失时 taskkill 返回非 0,属预期。
183
+ onError?.(error);
184
+ }
181
185
  }
182
186
  // 快照里那些已经和 pid 断了血缘的(父先死的孤儿),/T 够不着,逐个补刀。
183
187
  for (const targetPid of targets) {
@@ -207,11 +211,13 @@ export async function terminateProcessTree({
207
211
  // 已退出。
208
212
  }
209
213
  }
210
- try {
211
- killImpl(pid, signal);
212
- signaled += 1;
213
- } catch {
214
- // 已退出。
214
+ if (hasRoot) {
215
+ try {
216
+ killImpl(pid, signal);
217
+ signaled += 1;
218
+ } catch {
219
+ // 已退出。
220
+ }
215
221
  }
216
222
  return { signaled };
217
223
  }
@@ -229,10 +229,10 @@ export async function selectWorkerRuntime({ env = process.env, root = env.CODEM_
229
229
  const reasons = [];
230
230
  const load = async family => {
231
231
  try {
232
- const runtime = await loadRuntime(root, family);
232
+ const runtime = await loadRuntime(root, family, { retained: Boolean(actual || frozen), restoring });
233
233
  // A retained alpha pair can recover its own Session, but cannot serve a new
234
234
  // latest-channel Session after a failed channel switch.
235
- if ((!actual || upgrading) && !frozen && family === 'current' && currentChannel !== null) {
235
+ if ((!actual || upgrading) && !frozen && runtime.family === 'current' && currentChannel !== null) {
236
236
  const channel = typeof currentChannel === 'function' ? await currentChannel() : currentChannel;
237
237
  if (runtime.channel !== channel) throw new Error('worker runtime channel unavailable');
238
238
  }
package/package.json CHANGED
@@ -1,15 +1,16 @@
1
1
  {
2
2
  "name": "@lark-codem/codem-cli",
3
- "version": "0.1.279-dev.100104376703.0.g07159f3",
3
+ "version": "0.1.279-dev.100104423302.0.g324b5ae",
4
4
  "codemServiceManagementProtocol": 3,
5
- "codemWorkerRuntimeProtocol": 1,
6
5
  "codemProfileProtocol": 1,
6
+ "codemAuthProtocol": 1,
7
7
  "type": "module",
8
8
  "description": "CodeM local CLI for Feishu-driven coding sessions",
9
9
  "license": "SEE LICENSE IN LICENSE",
10
10
  "files": [
11
11
  "bin",
12
12
  "profile",
13
+ "auth",
13
14
  "LICENSE"
14
15
  ],
15
16
  "os": [
@@ -30,17 +31,17 @@
30
31
  "access": "public"
31
32
  },
32
33
  "dependencies": {
33
- "@lark-codem/codem-core": "0.8.96-dev.100104376703.0.g275f2a5",
34
+ "@lark-codem/codem-core": "0.8.96-dev.100104423302.0.g3ddbf0b",
34
35
  "zod": "3.25.76",
35
- "@lark-codem/lark-cli": "0.1.1-test.20261110.1"
36
+ "@lark-codem/lark-cli": "0.1.3"
36
37
  },
37
38
  "optionalDependencies": {
38
- "@lark-codem/codem-cli-darwin-arm64": "0.1.279-dev.100104376703.0.g07159f3",
39
- "@lark-codem/codem-cli-darwin-x64": "0.1.279-dev.100104376703.0.g07159f3",
40
- "@lark-codem/codem-cli-linux-arm64": "0.1.279-dev.100104376703.0.g07159f3",
41
- "@lark-codem/codem-cli-linux-x64": "0.1.279-dev.100104376703.0.g07159f3",
42
- "@lark-codem/codem-cli-win32-arm64": "0.1.279-dev.100104376703.0.g07159f3",
43
- "@lark-codem/codem-cli-win32-x64": "0.1.279-dev.100104376703.0.g07159f3"
39
+ "@lark-codem/codem-cli-darwin-arm64": "0.1.279-dev.100104423302.0.g324b5ae",
40
+ "@lark-codem/codem-cli-darwin-x64": "0.1.279-dev.100104423302.0.g324b5ae",
41
+ "@lark-codem/codem-cli-linux-arm64": "0.1.279-dev.100104423302.0.g324b5ae",
42
+ "@lark-codem/codem-cli-linux-x64": "0.1.279-dev.100104423302.0.g324b5ae",
43
+ "@lark-codem/codem-cli-win32-arm64": "0.1.279-dev.100104423302.0.g324b5ae",
44
+ "@lark-codem/codem-cli-win32-x64": "0.1.279-dev.100104423302.0.g324b5ae"
44
45
  },
45
46
  "engines": {
46
47
  "node": ">=18"
@@ -73,6 +73,7 @@ import { debugLog } from "./debug.js";
73
73
  const DEFAULT_STALE_MS = 10_000;
74
74
  const DEFAULT_TIMEOUT_MS = 15_000;
75
75
  const DEFAULT_RETRY_MS = 75;
76
+ const RELEASE_EMPTY_READ_DELAYS_MS = [50, 100, 200, 400, 500, 500];
76
77
  const REAPER_CHOOSING_PREFIX = "choosing-";
77
78
  const REAPER_TICKET_PREFIX = "ticket-";
78
79
  const REAPER_TICKET_WIDTH = 16;
@@ -160,6 +161,48 @@ async function readOwner(filePath) {
160
161
  }
161
162
  }
162
163
 
164
+ async function releaseOwnedLock(lockFile, token, sleep) {
165
+ let stage = "read";
166
+ let attempts = 0;
167
+ try {
168
+ // s3fs can return an empty body after the lock was written and closed.
169
+ let raw;
170
+ do {
171
+ attempts++;
172
+ raw = await fs.readFile(lockFile, "utf8");
173
+ if (raw.length !== 0) break;
174
+ if (attempts > RELEASE_EMPTY_READ_DELAYS_MS.length) {
175
+ debugLog("config-lock.release_failed", { lockFile, stage, attempts, outcome: "empty_read_exhausted" });
176
+ return;
177
+ }
178
+ await sleep(RELEASE_EMPTY_READ_DELAYS_MS[attempts - 1]);
179
+ } while (true);
180
+
181
+ stage = "parse";
182
+ const owner = JSON.parse(raw);
183
+ if (typeof owner?.token !== "string") {
184
+ debugLog("config-lock.release_failed", { lockFile, stage, attempts, outcome: "invalid_record" });
185
+ return;
186
+ }
187
+ if (owner.token !== token) {
188
+ debugLog("config-lock.release_failed", { lockFile, stage: "ownership", attempts, outcome: "owner_changed" });
189
+ return;
190
+ }
191
+
192
+ // A live holder is the only participant that can remove its lock under this protocol.
193
+ stage = "remove";
194
+ await fs.unlink(lockFile);
195
+ } catch (error) {
196
+ if (error?.code === "ENOENT") return;
197
+ debugLog("config-lock.release_failed", {
198
+ lockFile, stage, attempts, outcome: stage === "parse" ? "invalid_record" : "io_error",
199
+ errorCode: error?.code, errorClass: error?.name,
200
+ // JSON.parse errors can echo file contents. Keep only stack frames.
201
+ stack: error?.stack?.split("\n").filter((line) => line.startsWith(" at ")).join("\n")
202
+ });
203
+ }
204
+ }
205
+
163
206
  // 机会性清扫残留 tmp(Bug 7384601509):tmp 的生命周期原本只挂在「获取进程走完所有
164
207
  // 出口」上——等待窗口内被 SIGINT/SIGTERM/SIGKILL/崩溃/断电终止的进程,其 tmp 因文件名
165
208
  // 内嵌 randomUUID 永不复用而永久残留。这里在每次获取时顺带回收同目录的 `<lock>.tmp-*`
@@ -298,13 +341,7 @@ export async function acquireConfigLock(targetPath, {
298
341
  return;
299
342
  }
300
343
  released = true;
301
- // Ownership-checked release:token 匹配才删;不匹配/读不到 → no-op,
302
- // 绝不移动或删除别人的锁。存活 holder 的锁只有自己会删(见头注不变量),
303
- // 所以这里的 read→unlink 无竞态。
304
- const owner = await readOwner(lockFile);
305
- if (owner?.token === token) {
306
- await fs.rm(lockFile, { force: true }).catch(() => {});
307
- }
344
+ await releaseOwnedLock(lockFile, token, sleep);
308
345
  };
309
346
  }
310
347
  } finally {
@@ -44,7 +44,8 @@ export async function readProfileSnapshot(home) {
44
44
  return withCodeMConfigLock(join(home, "config.json"), () => readLockedProfileSnapshot(home));
45
45
  }
46
46
 
47
- async function readLockedProfileSnapshot(home) {
47
+ // Internal callers must already hold the canonical profile config lock.
48
+ export async function readLockedProfileSnapshot(home) {
48
49
  const configPath = join(home, "config.json");
49
50
  const config = await readProfileObject(configPath);
50
51
  let metadata;
@@ -90,6 +90,7 @@ const UPLINK_DIAGNOSTIC_METRICS = new Map([
90
90
  ]);
91
91
  const STRING_FIELDS = new Set([
92
92
  "request_id", "command_id", "session_id", "task_id", "dispatch_id", "event_id", "sync_id", "attempt_id",
93
+ "failure_stage", "first_route_id", "first_method", "first_reason", "late_outcome", "ipc_request_id",
93
94
  "lane", "target_kind", "frontier_did", "packet_kind", "packet_traceparent",
94
95
  "process_instance_id", "run_id", "stage", "phase", "status", "outcome", "reason", "action",
95
96
  "error_class", "error_code", "error_kind", "error_type", "code", "signal", "stop_reason",
@@ -116,6 +117,8 @@ const VALUE_FIELDS = new Set([
116
117
  "delivered", "result_delivered", "queued_behind_existing", "expected", "timed_out",
117
118
  "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",
118
119
  "expected_count", "loaded_count", "loaded_capability_count", "failed_count", "skipped_count", "ready_count", "downloaded_count", "turn_id", "turn_index",
120
+ "late_rpc_error_code", "lifecycle_wait_ms", "prepare_ms", "router_cred_ms", "meegle_init_ms", "spawn_init_ms", "budget_ms",
121
+ "oauth_ms", "project_list_ms", "config_total_ms", "write_total_ms",
119
122
  ...LIFECYCLE_METRICS
120
123
  ]);
121
124
 
@@ -205,10 +208,89 @@ function lifecycleErrorCode(fields) {
205
208
  }
206
209
 
207
210
  const REALTIME_LOG_ONLY = new Set([
208
- "app_server_rpc", "app_server_rpc_unmatched", "app_server_host_attached", "app_server_host_failed", "app_server_question", "hitl_answer",
211
+ "app_server_rpc", "app_server_rpc_unmatched", "app_server_rpc_late_reply", "app_server_host_attached",
212
+ "app_server_host_failed", "app_server_host_reused_failed", "app_server_host_prepare", "artifact_operation_failed",
213
+ "app_server_resume_binding_failed", "app_server_question", "hitl_answer",
209
214
  "downlink_admission", "rpc_reply", "uplink_commit", "uplink_transport", "subscription_query", "runtime_lease"
210
215
  ]);
211
216
 
217
+ 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;
218
+
219
+ const defaultRealtimeSink = {
220
+ info(line) {
221
+ const out = console;
222
+ out.info(line);
223
+ },
224
+ warn(line) {
225
+ const out = console;
226
+ out.warn(line);
227
+ },
228
+ error(line) {
229
+ const out = console;
230
+ out.error(line);
231
+ }
232
+ };
233
+
234
+ function serializeLocalValue(value, depth = 0) {
235
+ if (value === null || value === undefined) return undefined;
236
+ if (typeof value === "string") return value.length > 1024 ? `${value.slice(0, 1021)}...` : value;
237
+ if (typeof value === "number") return Number.isFinite(value) ? value : undefined;
238
+ if (typeof value === "boolean") return value;
239
+ if (value instanceof Error) {
240
+ const summary = {
241
+ error_type: value.name || "Error",
242
+ error_message: typeof value.message === "string" ? value.message.slice(0, 1024) : ""
243
+ };
244
+ if (value.code !== undefined) summary.error_code = String(value.code).slice(0, 128);
245
+ if (value.errno !== undefined) summary.errno = value.errno;
246
+ if (value.rpcError?.code !== undefined) summary.rpc_error_code = value.rpcError.code;
247
+ return summary;
248
+ }
249
+ if (depth >= 3) return undefined;
250
+ if (Array.isArray(value)) {
251
+ return value.slice(0, 32).map(entry => serializeLocalValue(entry, depth + 1)).filter(entry => entry !== undefined);
252
+ }
253
+ if (typeof value === "object") {
254
+ const out = {};
255
+ for (const [key, entry] of Object.entries(value)) {
256
+ if (entry === undefined || LOCAL_SENSITIVE_KEY.test(key)) continue;
257
+ const serialized = serializeLocalValue(entry, depth + 1);
258
+ if (serialized !== undefined) out[key] = serialized;
259
+ }
260
+ return out;
261
+ }
262
+ return undefined;
263
+ }
264
+
265
+ export function writeLocalRealtimeLog(level, event, fields = {}, { logger } = {}) {
266
+ try {
267
+ if (logger === null) return;
268
+ if (!logger && process.env.NODE_TEST_CONTEXT && process.env.CODEM_REALTIME_LOCAL_LOG !== "1") return;
269
+ const sink = logger ?? defaultRealtimeSink;
270
+ const payload = serializeLocalValue(fields) ?? {};
271
+ const line = `[codem][realtime][${event}] ${JSON.stringify(payload)}`;
272
+ if (level === "info") {
273
+ sink.info?.(line);
274
+ } else if (level === "error" || level === "fatal") {
275
+ (sink.error ?? sink.warn)?.call(sink, line);
276
+ } else {
277
+ sink.warn?.(line);
278
+ }
279
+ } catch { /* Local diagnostics must never affect business execution. */ }
280
+ }
281
+
282
+ export function writeLocalCoreStderr(pid, rawLine, { logger } = {}) {
283
+ try {
284
+ if (logger === null) return;
285
+ if (!logger && process.env.NODE_TEST_CONTEXT && process.env.CODEM_REALTIME_LOCAL_LOG !== "1") return;
286
+ const trimmed = String(rawLine ?? "").trim();
287
+ if (!trimmed) return;
288
+ const safe = trimmed.length > 2048 ? `${trimmed.slice(0, 2045)}...` : trimmed;
289
+ const sink = logger ?? defaultRealtimeSink;
290
+ sink.warn?.(`[codem][core-stderr][pid=${pid ?? "unknown"}] ${safe}`);
291
+ } catch { /* Forwarding child stderr must never fail the host. */ }
292
+ }
293
+
212
294
  function keepLegacyMetric(event, fields, role, severity) {
213
295
  if (REALTIME_LOG_ONLY.has(event)) return false;
214
296
  if (/^startup\.(?:main|update_check|daemon_service_reconcile|login_gate|login_handoff_to_linco)$/u.test(event) && severity === "info") return false;
@@ -719,7 +801,7 @@ export function recordInteractiveProcessExit({ exitCode, signal }) {
719
801
  export function recordSelectedRuntimeLog(component, event, fields = {}) {
720
802
  try {
721
803
  const selectedEvent = event.replace(/^linco\./u, "");
722
- 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)|capability\.(?:load\.lifecycle|operation|resource\.lifecycle|runtime\.timing|registry\.(?:snapshot|binding)|invocation|skill\.activation)|(?: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)|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;
804
+ 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)|capability\.(?:load\.lifecycle|operation|resource\.lifecycle|runtime\.timing|registry\.(?:snapshot|binding)|invocation|skill\.activation)|(?: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;
723
805
  const expected = optional(() => fields?.errorKind === "user_stop" || fields?.terminalError?.kind === "user_stop" || fields?.exitCode === 130 || fields?.signal === "SIGINT");
724
806
  const level = expected ? "info" : (fields?.status === "failed" || ["failed", "timeout"].includes(fields?.result) || /(?:failed|error|exhausted|timeout)$/u.test(event)) ? "error" : /(?:suspect|dropped|missing|oversize)$/u.test(event) ? "warn" : "info";
725
807
  recordRuntimeLog(level, component, event, fields);