@lark-codem/codem-cli 0.1.280 → 0.1.281-daemon-startup-observability.100104504395.0.g271d7c3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-codem/codem-cli",
3
- "version": "0.1.280",
3
+ "version": "0.1.281-daemon-startup-observability.100104504395.0.g271d7c3",
4
4
  "codemServiceManagementProtocol": 3,
5
5
  "codemProfileProtocol": 1,
6
6
  "type": "module",
@@ -34,12 +34,12 @@
34
34
  "@lark-codem/lark-cli": "0.1.5"
35
35
  },
36
36
  "optionalDependencies": {
37
- "@lark-codem/codem-cli-darwin-arm64": "0.1.280",
38
- "@lark-codem/codem-cli-darwin-x64": "0.1.280",
39
- "@lark-codem/codem-cli-linux-arm64": "0.1.280",
40
- "@lark-codem/codem-cli-linux-x64": "0.1.280",
41
- "@lark-codem/codem-cli-win32-arm64": "0.1.280",
42
- "@lark-codem/codem-cli-win32-x64": "0.1.280"
37
+ "@lark-codem/codem-cli-darwin-arm64": "0.1.281-daemon-startup-observability.100104504395.0.g271d7c3",
38
+ "@lark-codem/codem-cli-darwin-x64": "0.1.281-daemon-startup-observability.100104504395.0.g271d7c3",
39
+ "@lark-codem/codem-cli-linux-arm64": "0.1.281-daemon-startup-observability.100104504395.0.g271d7c3",
40
+ "@lark-codem/codem-cli-linux-x64": "0.1.281-daemon-startup-observability.100104504395.0.g271d7c3",
41
+ "@lark-codem/codem-cli-win32-arm64": "0.1.281-daemon-startup-observability.100104504395.0.g271d7c3",
42
+ "@lark-codem/codem-cli-win32-x64": "0.1.281-daemon-startup-observability.100104504395.0.g271d7c3"
43
43
  },
44
44
  "engines": {
45
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;
@@ -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
+ }
@@ -53,7 +53,7 @@ async function readLockedProfileSnapshot(home) {
53
53
  } catch (error) {
54
54
  if (!(error instanceof CredentialStorageError)) throw error;
55
55
  const kind = ["oauth", "router-ak"].includes(error.kind) ? error.kind : null;
56
- throw new CredentialStorageError(error.code.replace(/^credential_storage_/, ""), kind);
56
+ throw new CredentialStorageError(error.code.replace(/^credential_storage_/, ""), kind, error.cause !== undefined ? { cause: error.cause } : undefined);
57
57
  }
58
58
  if (!config && metadata && !metadata.loggedOut) throw new CredentialStorageError("config_missing", "oauth");
59
59
  const device = record(config?.device);
@@ -4,6 +4,8 @@ import os from "node:os";
4
4
  import fs from "node:fs";
5
5
  import path from "node:path";
6
6
  import { diagnosticId } from "./diagnostic-id.js";
7
+ import { safeServerLogId } from "./http-read-diagnostics.js";
8
+ import { redactDiagnosticText } from "./diagnostic-text.js";
7
9
  import { readDeviceId } from "./device-identity.js";
8
10
  import { sendSlardarPcBatch, SLARDAR_PC_AID, SLARDAR_PC_REPORTER_VERSION } from "./slardar-pc-transport.js";
9
11
 
@@ -14,19 +16,19 @@ const REQUEST_TIMEOUT_MS = 3_000;
14
16
  const MAX_BATCH_BYTES = 256 * 1024;
15
17
  const LIFECYCLE_EVENT_NAME = "codem_bridge_lifecycle";
16
18
  const LIFECYCLE_COMPONENTS = {
17
- daemon_startup: "daemon", runtime_sync: "runtime-post", command_handoff: "bridge",
19
+ daemon_process_startup: "daemon", daemon_first_heartbeat: "daemon",
20
+ runtime_sync: "runtime-post", command_handoff: "bridge",
18
21
  runner_operation: "bridge", delivery_settled: "runtime-post", runtime_state: "bridge",
19
22
  event_discarded: "runtime-post", process_lifecycle: "linco"
20
23
  };
21
24
  const LIFECYCLE_METRICS = [
22
- "duration_ms", "ack_settle_duration_ms", "startup_wait_ms", "operation_age_ms",
23
- "outage_duration_ms", "consecutive_failures", "deferred_age_ms", "pending_command_ack_count",
25
+ "duration_ms", "ack_settle_duration_ms", "operation_age_ms", "deferred_age_ms", "pending_command_ack_count",
24
26
  "pending_ack_age_ms", "pending_event_count", "oldest_event_age_ms", "lifetime_ms"
25
27
  ];
26
28
  const LIFECYCLE_DIMENSIONS = {
27
29
  outcome: ["success", "failed", "rejected", "canceled", "unknown", "accepted", "duplicate", "conflicting", "observed", "recovered"],
28
30
  operation: ["prepare", "spawn", "ready", "cancel", "shutdown"],
29
- scope: ["startup", "runner", "sync", "command", "queue"],
31
+ scope: ["runner", "command", "queue"],
30
32
  kind: ["command_ack", "runtime_event", "control", "events", "relay", "offline"],
31
33
  phase: ["startup_marker", "prelude", "healthcheck", "config_load", "update_check", "service_reconcile", "login_gate", "launch", "authentication", "singleton", "initialize", "start_client", "first_sync", "trusted_device",
32
34
  "build_request", "request", "validate_response", "apply_response", "persist_state",
@@ -36,7 +38,8 @@ const LIFECYCLE_DIMENSIONS = {
36
38
  "shutting_down_handoff", "handoff_target_not_active", "handler_inflight", "duplicate_inflight",
37
39
  "runtime_unavailable", "runtime_environment_failed", "capability_probe_failed", "runtime_binary_changed",
38
40
  "strict_resume_unsupported", "turn_context_unsupported", "active_run_protocol_mismatch", "trusted_device_blocked",
39
- "invalid_runtime_event", "event_rejected", "task_terminated:canceled", "task_terminated:failed", "task_terminated:succeeded"],
41
+ "invalid_runtime_event", "event_rejected", "device_replaced", "device_unbound",
42
+ "task_terminated:canceled", "task_terminated:failed", "task_terminated:succeeded"],
40
43
  error_source: ["bridge", "base", "linco", "transport"],
41
44
  stability: ["stable", "unstable", "unknown"],
42
45
  action: ["exit", "restart"],
@@ -77,7 +80,7 @@ const OBSERVATION_METRICS = {
77
80
  command_observation_closed: ["omitted_detail_count", "pending_command_ack_count", "deferred_count"],
78
81
  diagnostic_reporter_health: ["dropped_delta", "upload_failure_delta", "pending_event_count"]
79
82
  };
80
- const EXTRA_FIELDS = ["observation_id", "runtime_client_instance_id", "command_id", "delivery_id", "probe_id", "sync_id", "transport_request_id", "attempt_id"];
83
+ const EXTRA_FIELDS = ["observation_id", "runtime_client_instance_id", "command_id", "delivery_id", "probe_id", "sync_id", "transport_request_id", "attempt_id", "server_log_id"];
81
84
  const LIFECYCLE_EXTRA_FIELDS = [...EXTRA_FIELDS, "process_instance_id", "startup_id", "request_id", "event_id"];
82
85
  const STRING_FIELDS = new Set([
83
86
  ...EXTRA_FIELDS, "command_type", "ack_status", "ack_outcome", "readback_scope", "timing_origin", "required_capability",
@@ -88,16 +91,17 @@ const STRING_FIELDS = new Set([
88
91
  "terminal_event", "event_type", "actor_type", "source", "trigger", "hook_id", "hook_event",
89
92
  "target_version", "cli_version", "core_version", "version", "previous_state", "state",
90
93
  "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",
91
- "operation_id", "entrypoint", "workflow_launch_id"
94
+ "operation_id", "entrypoint", "native_operation", "workflow_launch_id"
92
95
  ]);
93
96
  const VALUE_FIELDS = new Set([
94
97
  "truncated",
95
- "session_retained", "lease_valid_until_ms", "requested_valid_until_ms", "lease_remaining_ms", "wall_remaining_ms",
98
+ "session_retained", "unreadable", "win32_error",
99
+ "lease_valid_until_ms", "requested_valid_until_ms", "lease_remaining_ms", "wall_remaining_ms",
96
100
  ...new Set(Object.values(OBSERVATION_METRICS).flat()),
97
101
  "pid", "exit_code", "duration_ms", "elapsed_ms", "wait_ms", "run_ms", "total_ms", "took_ms",
98
102
  "attempt", "attempts", "attempt_count", "retryable", "http_status", "errno", "active_task_count",
99
103
  "pending_event_count", "pending_command_ack_count", "next_retry_ms", "consecutive_failures",
100
- "outage_duration_ms", "startup_duration_ms", "failed_attempts", "active_runs", "completed",
104
+ "outage_duration_ms", "failed_attempts", "active_runs", "completed",
101
105
  "delivered", "result_delivered", "queued_behind_existing", "expected", "timed_out",
102
106
  "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",
103
107
  ...LIFECYCLE_METRICS
@@ -175,12 +179,141 @@ function lifecycleErrorSummary(dimensions, fields) {
175
179
 
176
180
  function lifecycleErrorCode(fields) {
177
181
  const code = token(fields.error_code ?? fields.error?.code ?? fields.error?.cause?.code)?.toLowerCase();
178
- if (code && /^(?:e(?:connreset|connrefused|pipe|timedout|netunreach|hostunreach|notfound|ai_again|acces|perm|noent|exist|nospace|nospc|io)|runtime_post_[a-z_]{1,48}|http_[1-5]\d\d|(?:[a-z_]{1,35}_)?timeout|not_logged_in|unsupported_command|invalid_payload|invalid_response|relogin_required|rotation_pending|cleanup_failed|oversized|overflow|unexpected_exit|spawn_failed|ready_missing|prepare_failed|ack_rejected|ack_conflicting)$/u.test(code)) return code;
182
+ if (code && /^(?:e(?:connreset|connrefused|pipe|timedout|netunreach|hostunreach|notfound|ai_again|acces|perm|noent|exist|nospace|nospc|io|isdir|notdir|busy|mfile|nfile|rofs)|credential_storage_[a-z_]{1,32}|runtime_post_[a-z_]{1,48}|http_[1-5]\d\d|(?:[a-z_]{1,35}_)?timeout|config_lock_timeout|module_not_found|err_dlopen_failed|not_logged_in|unsupported_command|invalid_payload|invalid_response|relogin_required|rotation_pending|cleanup_failed|oversized|overflow|unexpected_exit|spawn_failed|ready_missing|prepare_failed|ack_rejected|ack_conflicting)$/u.test(code)) return code;
179
183
  const status = Number(fields.http_status);
180
184
  if (Number.isInteger(status) && status >= 100 && status <= 599) return `http_${status}`;
181
185
  return fields.outcome === "failed" || fields.outcome === "rejected" || fields.outcome === "conflicting" ? "unknown" : undefined;
182
186
  }
183
187
 
188
+ function toWellFormedString(value) {
189
+ if (typeof value.toWellFormed === "function") return value.toWellFormed();
190
+ // Node 18 compatibility: replace unpaired UTF-16 surrogates with U+FFFD.
191
+ return value.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "\uFFFD");
192
+ }
193
+
194
+ const SAFE_DIAGNOSTIC_BASENAME = /^(?:linco(?:\.exe)?|codem(?:\.exe)?|codem-daemon-host(?:\.exe|\.json)?|node(?:\.exe)?|npm(?:\.cmd)?|security|launchctl|systemctl|sc(?:\.exe)?|schtasks(?:\.exe)?|powershell(?:\.exe)?|config\.json|\.credentials\.json|credential-storage\.json|master\.key(?:\.file)?|current\.json|previous\.json|package\.json|config\.toml|daemon\.pid|[a-z\d._-]{1,96}\.(?:node|dll|dylib|so|enc|lock))$/iu;
195
+
196
+ function sanitizeDiagnosticPath(rawPath) {
197
+ if (typeof rawPath !== "string") return "[REDACTED_PATH]";
198
+ const bounded = rawPath.length > 1024 ? rawPath.slice(0, 1024) : rawPath;
199
+ const trimmed = bounded.trim();
200
+ let end = trimmed.length;
201
+ while (end > 0 && ",:;)]}".includes(trimmed[end - 1])) end -= 1;
202
+ const suffix = trimmed.slice(end);
203
+ const core = trimmed.slice(0, end).replace(/^(?:\\\\\?\\|file:\/\/\/+)/iu, "").replaceAll("\\", "/");
204
+ const homeMatch = core.match(/(?:^|\/)(\.(?:codem|linco)(?:\/[^\s'"()(),。,:;\u4e00-\u9fff\u3000-\u303f\uff00-\uffef]+)?)$/iu);
205
+ if (homeMatch) return `~/${homeMatch[1]}${suffix}`;
206
+ const moduleMatch = core.match(/(?:^|\/)(node_modules\/[^\s'"()(),。,:;\u4e00-\u9fff\u3000-\u303f\uff00-\uffef]+)$/iu);
207
+ if (moduleMatch) return `${moduleMatch[1]}${suffix}`;
208
+ const base = core.split("/").filter(Boolean).pop();
209
+ if (base && SAFE_DIAGNOSTIC_BASENAME.test(base)) return `.../${base}${suffix}`;
210
+ return `[REDACTED_PATH]${suffix}`;
211
+ }
212
+
213
+ function textOrBuffer(read) {
214
+ const value = optional(read);
215
+ if (typeof value === "string") return value;
216
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array) {
217
+ return optional(() => Buffer.from(value).subarray(0, 32_768).toString("utf8"));
218
+ }
219
+ return undefined;
220
+ }
221
+
222
+ function privateErrorText(error) {
223
+ const rawResponse = optional(() => error.response?.raw);
224
+ const logId = optional(() => error.logid);
225
+ const output = optional(() => error.runtimeDiagnosticOutput);
226
+ const rawPath = optional(() => error.path);
227
+ const rawDest = optional(() => error.dest);
228
+ return [
229
+ // A wrapper can interpolate its cause's raw output into its own message.
230
+ [error instanceof SyntaxError ? optional(() => error.message) : undefined, "[REDACTED_PARSE_INPUT]"],
231
+ [output === true ? optional(() => error.message) : output, "[REDACTED_OUTPUT]"],
232
+ [typeof rawResponse === "string" ? rawResponse.trim() : undefined, "[REDACTED_RESPONSE]"],
233
+ [optional(() => error.runtimeDiagnosticResponseExcerpt), "[REDACTED_RESPONSE]"],
234
+ [typeof logId === "string" && !safeServerLogId(logId) ? `(logid: ${logId})` : undefined, "(logid: [REDACTED_LOG_ID])"],
235
+ [optional(() => error.cmd), "[REDACTED_COMMAND]"],
236
+ [textOrBuffer(() => error.stderr), "[REDACTED_OUTPUT]"],
237
+ [textOrBuffer(() => error.stdout), "[REDACTED_OUTPUT]"],
238
+ [textOrBuffer(() => error.processIdentityDiagnostic?.stderr), "[REDACTED_OUTPUT]"],
239
+ [textOrBuffer(() => error.processIdentityDiagnostic?.stdout), "[REDACTED_OUTPUT]"],
240
+ [rawPath, sanitizeDiagnosticPath(rawPath)],
241
+ [rawDest, sanitizeDiagnosticPath(rawDest)]
242
+ ].filter(([raw]) => typeof raw === "string" && raw.trim().length >= 2 && !/^[./\\]+$/u.test(raw.trim()) && !/^\[REDACTED/u.test(raw.trim()))
243
+ .flatMap(([raw, replacement]) => raw.trim() !== raw
244
+ ? [[raw, replacement], [raw.trim(), replacement]]
245
+ : [[raw, replacement]]);
246
+ }
247
+
248
+ function isErrorLikeObject(value) {
249
+ if (!value || typeof value !== "object") return false;
250
+ if (value instanceof Error) return true;
251
+ return typeof optional(() => value.message) === "string"
252
+ || typeof optional(() => value.code) === "string"
253
+ || Number.isSafeInteger(optional(() => value.code));
254
+ }
255
+
256
+ // Keep captured exceptions small enough for crash replay, including the
257
+ // second JSON encoding of log_content.
258
+ function diagnosticErrorDetail(error, depth = 0) {
259
+ if (depth === 4 || (typeof error !== "string" && !isErrorLikeObject(error))) return undefined;
260
+ const name = token(optional(() => error.name));
261
+ const rawCode = optional(() => error.code);
262
+ const code = Number.isSafeInteger(rawCode) ? rawCode : token(rawCode);
263
+ const syscall = token(optional(() => error.syscall));
264
+ const rawErrno = optional(() => error.errno);
265
+ const errno = Number.isSafeInteger(rawErrno) ? rawErrno : token(rawErrno);
266
+ const signal = token(optional(() => error.signal));
267
+ const kind = token(optional(() => error.kind ?? error.errorKind ?? error.terminalError?.kind));
268
+ const rawPath = optional(() => error.path);
269
+ const safePath = typeof rawPath === "string" && rawPath.trim().length >= 2 && !/^[./\\]+$/u.test(rawPath.trim())
270
+ ? sanitizeDiagnosticPath(rawPath)
271
+ : undefined;
272
+ // JSON.parse can quote the credential file's contents in the SyntaxError.
273
+ if (error instanceof SyntaxError || optional(() => error.runtimeDiagnosticOutput) === true) {
274
+ return { name, code, ...(kind ? { kind } : {}), ...(syscall ? { syscall } : {}), ...(errno !== undefined ? { errno } : {}), ...(signal ? { signal } : {}) };
275
+ }
276
+ const privateText = [];
277
+ let cause = error;
278
+ for (let i = depth; cause && i < 4; i++) {
279
+ privateText.push(...privateErrorText(cause));
280
+ cause = optional(() => cause.cause);
281
+ }
282
+ privateText.sort(([a], [b]) => b.length - a.length);
283
+ const clean = (text, limit) => {
284
+ if (typeof text !== "string") return undefined;
285
+ if (text.length > 32_768) text = text.slice(0, 32_768);
286
+ for (const [raw, replacement] of privateText) {
287
+ text = text.replaceAll(raw, replacement);
288
+ }
289
+ const redacted = redactDiagnosticText(text, { redactURLPath: true })
290
+ // Keep stack locations as file:line:column (including `at async C:\Users\Alice Smith\...`).
291
+ .replace(/^([ \t]+at (?:async )?(?:[^\r\n(]*? \()?)(?:\\\\\?\\|file:\/\/\/+|[a-z]:[\\/]|\\\\|\/)[^\r\n]*[\\/]([^\\/()\r\n]+:\d+:\d+\)?)(?=\r?$)/gimu, "$1$2")
292
+ // Strip OS user home directory names (including spaces) before further path normalization.
293
+ .replace(/(?:\\\\\?\\|file:\/\/\/+)?(?:[a-z]:[\\/]Users|\/(?:Users|home))[\\/][^\\/\r\n'"<>|()(),。,:;]{1,128}(?=[\\/])/giu, "~")
294
+ .replace(/(?:\\\\\?\\|file:\/\/\/+)?(?:[a-z]:[\\/]Users|\/(?:Users|home))[\\/][^\\/\r\n'"<>|()(),。,:;\u4e00-\u9fff]{1,64}?(?=\s+(?:failed|error|cannot|could|is|was|does|not|to|at|in|on|with|from)\b|\s*[\r\n'"<>|()(),。,:;\u4e00-\u9fff]|$)/giu, "[REDACTED_PATH]")
295
+ // Sanitize quoted paths first (preserving ~/.codem, ~/.linco, node_modules, and safe basenames).
296
+ .replace(/(['"])((?:~[\\/]|\\\\\?\\|file:\/\/\/+|[a-z]:[\\/]|\\\\|\/(?!\/))[^'"\r\n]+)\1/giu, (_, quote, candidate) => `${quote}${sanitizeDiagnosticPath(candidate)}${quote}`)
297
+ // Sanitize unquoted ~-normalized home paths and other filesystem paths token-by-token (no cross-space clobbering).
298
+ .replace(/(^|[\s((=])(~[\\/][^\s'"()(),。;]+)/giu, (_, prefix, candidate) => `${prefix}${sanitizeDiagnosticPath(candidate)}`)
299
+ .replace(/(^|[\s((=])(?<!\b(?:GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)\s)((?:\\\\\?\\|file:\/\/\/+|[a-z]:[\\/]|\\\\|\/(?:(?:Users|home|private|var|tmp|opt|etc|usr|Volumes|mnt|root|proc|sys|dev|Library|Applications|System|nix|snap|run|srv|data\d*)(?:\/|$)|[^\s'"()(),。,:;/]+\/))[^\s'"()(),。;\u4e00-\u9fff\u3000-\u303f\uff00-\uffef]*)/gimu, (_, prefix, candidate) => `${prefix}${sanitizeDiagnosticPath(candidate)}`)
300
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/gu, "�");
301
+ return toWellFormedString(redacted.length <= limit ? redacted : redacted.slice(0, limit - 1) + "…");
302
+ };
303
+ const textLimit = depth === 0 ? 2048 : 1024;
304
+ return {
305
+ name, code,
306
+ ...(kind ? { kind } : {}),
307
+ ...(syscall ? { syscall } : {}),
308
+ ...(errno !== undefined ? { errno } : {}),
309
+ ...(signal ? { signal } : {}),
310
+ ...(safePath && safePath !== "[REDACTED_PATH]" ? { path: safePath } : {}),
311
+ message: clean(typeof error === "string" ? error : optional(() => error.message), textLimit),
312
+ stack: clean(optional(() => error.stack), textLimit),
313
+ cause: diagnosticErrorDetail(optional(() => error.cause), depth + 1)
314
+ };
315
+ }
316
+
184
317
  function keepLegacyMetric(event, fields, role, severity) {
185
318
  if (/^startup\.(?:main|update_check|daemon_service_reconcile|login_gate|login_handoff_to_linco)$/u.test(event) && severity === "info") return false;
186
319
  if (/(?:^|\.)drain_(?:started|completed)$/u.test(event) && severity === "info") return false;
@@ -251,10 +384,11 @@ export class RuntimeLogReporter {
251
384
  // Never await network IO in uncaughtExceptionMonitor. Replay is at-least-once.
252
385
  // deliverNow also queues the record for this process's next flush. A
253
386
  // successful send deletes its file; otherwise the next process replays it.
254
- persistCrash(component, event, fields = {}, { deliverNow = false } = {}) {
387
+ persistCrash(component, event, fields = {}, { deliverNow = false, captureError = false } = {}) {
255
388
  try {
256
389
  if (this.#closed || (!this.#crashDirectory && !deliverNow)) return;
257
- const entry = this.#logEntry("fatal", component, event, fields);
390
+ const entry = this.#logEntry("fatal", component, event, fields, captureError);
391
+ entry.record.category.replay = "0";
258
392
  this.#saveCrash(entry);
259
393
  if (deliverNow) this.#replay.queue.push(entry);
260
394
  } catch { /* Crash diagnostics must preserve the original exit behavior. */ }
@@ -283,12 +417,27 @@ export class RuntimeLogReporter {
283
417
  const file = path.join(this.#crashDirectory, name);
284
418
  try {
285
419
  const stat = await fs.promises.lstat(file);
286
- if (!stat.isFile() || stat.size > 65536) continue;
287
- const entry = JSON.parse(await fs.promises.readFile(file, "utf8"));
288
- if (entry?.record?.category?.reporter !== "codem_js" || entry?.record?.log_type !== "log" || !entry.header) continue;
420
+ if (!stat.isFile()) continue;
421
+ const stale = Date.now() - stat.mtimeMs > 5_000;
422
+ if (stat.size > 65536) {
423
+ if (stale) await fs.promises.unlink(file).catch(() => {});
424
+ continue;
425
+ }
426
+ const rawEntry = await fs.promises.readFile(file, "utf8");
427
+ let entry;
428
+ try { entry = JSON.parse(rawEntry); } catch {
429
+ if (stale) await fs.promises.unlink(file).catch(() => {});
430
+ continue;
431
+ }
432
+ if (entry?.record?.category?.reporter !== "codem_js" || entry?.record?.log_type !== "log" || !entry.header) {
433
+ if (stale) await fs.promises.unlink(file).catch(() => {});
434
+ continue;
435
+ }
289
436
  if (this.#closed) return;
290
- if (entry.metricName === LIFECYCLE_EVENT_NAME) {
437
+ if (entry.metricName === LIFECYCLE_EVENT_NAME || entry.record.category.replay === "0") {
291
438
  entry.record.category.replay = "1";
439
+ }
440
+ if (entry.metricName === LIFECYCLE_EVENT_NAME) {
292
441
  this.#replay.queue.push({ ...entry, attempts: 0, crashFile: file });
293
442
  } else {
294
443
  this.#replay.queue.push({ header: entry.header, record: entry.record, metricName: entry.metricName,
@@ -320,16 +469,25 @@ export class RuntimeLogReporter {
320
469
  get droppedCount() { return this.#dropped; }
321
470
  get identityKey() { return JSON.stringify([this.#instanceId, this.#role, this.#identity.deviceId, this.#identity.userId, this.#identity.tenantId]); }
322
471
 
323
- record(level, component, event, fields = {}) {
472
+ record(level, component, event, fields = {}, { captureError = false, persist = false } = {}) {
324
473
  try {
325
474
  if (this.#closed) return false;
326
- return this.#enqueue(this.#logEntry(level, component, event, fields));
475
+ const entry = this.#logEntry(level, component, event, fields, captureError);
476
+ if (persist) {
477
+ entry.record.category.replay = "0";
478
+ this.#saveCrash(entry);
479
+ }
480
+ return this.#enqueue(entry);
327
481
  } catch { return false; }
328
482
  }
329
483
 
330
- #logEntry(level, component, event, fields) {
484
+ #logEntry(level, component, event, fields, captureError) {
331
485
  let safeFields;
332
486
  try { safeFields = projectFields(fields); } catch { safeFields = {}; }
487
+ if (captureError) {
488
+ const error = optional(() => diagnosticErrorDetail(fields.error));
489
+ if (error) safeFields.error = error;
490
+ }
333
491
  if (OBSERVATION_EVENTS.has(event)) safeFields.observation_id = randomUUID();
334
492
  const severity = ["info", "warn", "error", "fatal"].includes(level) ? level : "info";
335
493
  // Keep arbitrary upstream error codes out of trusted-device metric dimensions.
@@ -348,7 +506,7 @@ export class RuntimeLogReporter {
348
506
  };
349
507
  }
350
508
 
351
- recordLifecycle(event, fields = {}, { persist = false } = {}) {
509
+ recordLifecycle(event, fields = {}, { persist = false, captureError = false } = {}) {
352
510
  try {
353
511
  if (this.#closed || !Object.hasOwn(LIFECYCLE_COMPONENTS, event)) return false;
354
512
  const unstable = fields.stability === "unstable" || fields.outcome === "failed" || fields.outcome === "conflicting";
@@ -377,11 +535,15 @@ export class RuntimeLogReporter {
377
535
  const { replay: _replay, ...logDimensions } = dimensions;
378
536
  const summary = hasDetail ? lifecycleErrorSummary(dimensions, fields) : "";
379
537
  const { reason: _reason, error_code: _errorCode, ...projected } = projectFields(fields, false);
538
+ const isStartup = event === "daemon_process_startup" || event === "daemon_first_heartbeat";
539
+ const errorDetail = hasDetail && (captureError || (isStartup && ["failed", "rejected"].includes(fields.outcome)))
540
+ ? optional(() => diagnosticErrorDetail(fields.error)) : undefined;
380
541
  const safeFields = {
381
542
  ...projected, ...logDimensions, ...metrics,
382
543
  process_instance_id: this.#instanceId,
383
- ...(event === "daemon_startup" ? { startup_id: this.#instanceId } : {}),
544
+ ...(isStartup ? { startup_id: this.#instanceId } : {}),
384
545
  observation_id: randomUUID(),
546
+ ...(errorDetail ? { error: errorDetail } : {}),
385
547
  ...(summary ? { error_summary: summary } : {})
386
548
  };
387
549
  const extra = Object.fromEntries(LIFECYCLE_EXTRA_FIELDS
@@ -581,8 +743,8 @@ export function observeRuntimeLogSandboxConfig(config) {
581
743
  try { active?.observeSandboxConfig(config); } catch { /* best effort */ }
582
744
  }
583
745
 
584
- export function recordRuntimeLog(level, component, event, fields = {}) {
585
- try { return active?.record(level, component, event, fields) ?? false; } catch { return false; }
746
+ export function recordRuntimeLog(level, component, event, fields = {}, options = {}) {
747
+ try { return active?.record(level, component, event, fields, options) ?? false; } catch { return false; }
586
748
  }
587
749
 
588
750
  // An explicit result or state observation. This never waits for the collector;
@@ -592,27 +754,33 @@ export function recordBridgeLifecycle(event, fields, options = {}) {
592
754
  }
593
755
 
594
756
  export function flushRuntimeLogsInBackground() {
595
- if (active) setImmediate(() => { void active?.flush().catch(() => {}); }).unref?.();
757
+ try {
758
+ if (active) setImmediate(() => { void active?.flush().catch(() => {}); }).unref?.();
759
+ } catch { /* best effort */ }
596
760
  }
597
761
 
598
- export function persistRuntimeCrash(component, event, fields) {
599
- try { active?.persistCrash(component, event, fields); } catch { /* best effort */ }
762
+ export function persistRuntimeCrash(component, event, fields, options = {}) {
763
+ try { active?.persistCrash(component, event, fields, options); } catch { /* best effort */ }
600
764
  }
601
765
 
602
766
  // A failure that ends a short-lived process: persist first, then try to deliver
603
767
  // within one upload budget, so an immediate exit cannot lose the count.
604
- export function reportRuntimeFailure(component, event, fields = {}) {
605
- try { active?.persistCrash(component, event, fields, { deliverNow: true }); } catch { /* best effort */ }
768
+ export function reportRuntimeFailure(component, event, fields = {}, options = {}) {
769
+ try { active?.persistCrash(component, event, fields, { captureError: Boolean(fields?.error), ...options, deliverNow: true }); } catch { /* best effort */ }
606
770
  flushRuntimeLogsInBackground();
607
771
  }
608
772
 
773
+ export function closeRuntimeLogs() {
774
+ try { active?.close(); active = undefined; } catch { /* best effort */ }
775
+ }
776
+
609
777
  export async function flushRuntimeLogs(budgetMs = 200) {
610
778
  if (!active) return;
611
779
  let timeout;
612
780
  try {
613
781
  await Promise.race([
614
782
  active.flush({ timeoutMs: budgetMs }),
615
- new Promise((resolve) => { timeout = setTimeout(resolve, budgetMs); })
783
+ new Promise((resolve) => { timeout = setTimeout(resolve, budgetMs); timeout.unref?.(); })
616
784
  ]);
617
785
  } catch { /* best effort, including a broken uploader */ } finally { clearTimeout(timeout); }
618
786
  }
@@ -651,12 +819,19 @@ export function recordInteractiveProcessExit({ exitCode, signal }) {
651
819
  }
652
820
 
653
821
  // Select events explicitly, then project fields again at the remote boundary.
654
- export function recordSelectedRuntimeLog(component, event, fields = {}) {
822
+ export function recordSelectedRuntimeLog(component, event, fields = {}, { capturedError = undefined } = {}) {
655
823
  try {
656
824
  const selectedEvent = event.replace(/^linco\./u, "");
657
- 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;
825
+ 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)|authentication_snapshot\.router_unavailable|capabilities\.probe_failed|runtime_post\.(?:trusted_device_startup_probe_failed|daemon\.capabilities_probe_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;
658
826
  const expected = optional(() => fields?.errorKind === "user_stop" || fields?.terminalError?.kind === "user_stop" || fields?.exitCode === 130 || fields?.signal === "SIGINT");
659
- const level = expected ? "info" : (fields?.status === "failed" || /(?:failed|error|exhausted|timeout)$/u.test(event)) ? "error" : /(?:suspect|dropped|missing|oversize)$/u.test(event) ? "warn" : "info";
660
- recordRuntimeLog(level, component, event, fields);
827
+ const level = expected ? "info"
828
+ : (fields?.status === "failed" || (selectedEvent === "authentication_snapshot.router_unavailable" && fields?.reason === "storage") || /(?:failed|error|exhausted|timeout)$/u.test(event)) ? "error"
829
+ : /(?:suspect|dropped|missing|oversize|unavailable)$/u.test(event) ? "warn"
830
+ : "info";
831
+ const captureError = capturedError !== undefined;
832
+ const persist = selectedEvent === "router.credentials.refresh_failed"
833
+ || (selectedEvent === "authentication_snapshot.router_unavailable" && fields?.reason === "storage");
834
+ recordRuntimeLog(level, component, event, captureError ? { ...fields, error: capturedError } : fields, { captureError, persist });
835
+ if (persist) flushRuntimeLogsInBackground();
661
836
  } catch { /* best effort */ }
662
837
  }