@lark-codem/codem-cli 0.1.280 → 0.1.281-daemon-startup-observability.100104504092.0.g24d481d
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 +7 -7
- package/profile/credential-errors.js +2 -2
- package/profile/credential-metadata.js +2 -2
- package/profile/debug.js +12 -12
- package/profile/diagnostic-text.js +49 -0
- package/profile/http-read-diagnostics.js +17 -0
- package/profile/profile-snapshot.js +1 -1
- package/profile/runtime-logs.js +207 -33
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lark-codem/codem-cli",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.281-daemon-startup-observability.100104504092.0.g24d481d",
|
|
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.
|
|
38
|
-
"@lark-codem/codem-cli-darwin-x64": "0.1.
|
|
39
|
-
"@lark-codem/codem-cli-linux-arm64": "0.1.
|
|
40
|
-
"@lark-codem/codem-cli-linux-x64": "0.1.
|
|
41
|
-
"@lark-codem/codem-cli-win32-arm64": "0.1.
|
|
42
|
-
"@lark-codem/codem-cli-win32-x64": "0.1.
|
|
37
|
+
"@lark-codem/codem-cli-darwin-arm64": "0.1.281-daemon-startup-observability.100104504092.0.g24d481d",
|
|
38
|
+
"@lark-codem/codem-cli-darwin-x64": "0.1.281-daemon-startup-observability.100104504092.0.g24d481d",
|
|
39
|
+
"@lark-codem/codem-cli-linux-arm64": "0.1.281-daemon-startup-observability.100104504092.0.g24d481d",
|
|
40
|
+
"@lark-codem/codem-cli-linux-x64": "0.1.281-daemon-startup-observability.100104504092.0.g24d481d",
|
|
41
|
+
"@lark-codem/codem-cli-win32-arm64": "0.1.281-daemon-startup-observability.100104504092.0.g24d481d",
|
|
42
|
+
"@lark-codem/codem-cli-win32-x64": "0.1.281-daemon-startup-observability.100104504092.0.g24d481d"
|
|
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 =
|
|
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(/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?\b/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);
|
package/profile/runtime-logs.js
CHANGED
|
@@ -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
|
-
|
|
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", "
|
|
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: ["
|
|
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", "
|
|
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", "
|
|
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", "
|
|
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,140 @@ 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
|
+
// Preserve CodeM/Linco relative paths while stripping intermediate directories.
|
|
295
|
+
.replace(/(?:~(?=[\\/])|\\\\\?\\|file:\/\/\/+|[a-z]:(?=[\\/])|\\\\|(?<![:\w~])(?=\/(?!\/)))[^\r\n'"()(),。]*?[\\/](\.(?:codem|linco)(?:[\\/][^\s'"()(),。,:;\u4e00-\u9fff\u3000-\u303f\uff00-\uffef]+)?)/giu, (_, sub) => `~/${sub.replaceAll("\\", "/")}`)
|
|
296
|
+
.replace(/(['"])((?:~[\\/](?!\.(?:codem|linco)(?:[\\/]|['"]))|\\\\\?\\|file:\/\/\/+|[a-z]:[\\/]|\\\\|\/(?!\/))[^'"\r\n]+)\1/giu, (_, quote, candidate) => `${quote}${sanitizeDiagnosticPath(candidate)}${quote}`)
|
|
297
|
+
.replace(/~[\\/](?!\.(?:codem|linco)(?:[\\/]|$))(?:[^\r\n'"()(),。,:;\u4e00-\u9fff\u3000-\u303f\uff00-\uffef]*[\\/])?[^\s'"()(),。,:;\u4e00-\u9fff\u3000-\u303f\uff00-\uffef]+[,:;)\]}]*/giu, (candidate) => sanitizeDiagnosticPath(candidate))
|
|
298
|
+
.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)}`)
|
|
299
|
+
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/gu, "�");
|
|
300
|
+
return toWellFormedString(redacted.length <= limit ? redacted : redacted.slice(0, limit - 1) + "…");
|
|
301
|
+
};
|
|
302
|
+
const textLimit = depth === 0 ? 2048 : 1024;
|
|
303
|
+
return {
|
|
304
|
+
name, code,
|
|
305
|
+
...(kind ? { kind } : {}),
|
|
306
|
+
...(syscall ? { syscall } : {}),
|
|
307
|
+
...(errno !== undefined ? { errno } : {}),
|
|
308
|
+
...(signal ? { signal } : {}),
|
|
309
|
+
...(safePath && safePath !== "[REDACTED_PATH]" ? { path: safePath } : {}),
|
|
310
|
+
message: clean(typeof error === "string" ? error : optional(() => error.message), textLimit),
|
|
311
|
+
stack: clean(optional(() => error.stack), textLimit),
|
|
312
|
+
cause: diagnosticErrorDetail(optional(() => error.cause), depth + 1)
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
|
|
184
316
|
function keepLegacyMetric(event, fields, role, severity) {
|
|
185
317
|
if (/^startup\.(?:main|update_check|daemon_service_reconcile|login_gate|login_handoff_to_linco)$/u.test(event) && severity === "info") return false;
|
|
186
318
|
if (/(?:^|\.)drain_(?:started|completed)$/u.test(event) && severity === "info") return false;
|
|
@@ -251,10 +383,11 @@ export class RuntimeLogReporter {
|
|
|
251
383
|
// Never await network IO in uncaughtExceptionMonitor. Replay is at-least-once.
|
|
252
384
|
// deliverNow also queues the record for this process's next flush. A
|
|
253
385
|
// successful send deletes its file; otherwise the next process replays it.
|
|
254
|
-
persistCrash(component, event, fields = {}, { deliverNow = false } = {}) {
|
|
386
|
+
persistCrash(component, event, fields = {}, { deliverNow = false, captureError = false } = {}) {
|
|
255
387
|
try {
|
|
256
388
|
if (this.#closed || (!this.#crashDirectory && !deliverNow)) return;
|
|
257
|
-
const entry = this.#logEntry("fatal", component, event, fields);
|
|
389
|
+
const entry = this.#logEntry("fatal", component, event, fields, captureError);
|
|
390
|
+
entry.record.category.replay = "0";
|
|
258
391
|
this.#saveCrash(entry);
|
|
259
392
|
if (deliverNow) this.#replay.queue.push(entry);
|
|
260
393
|
} catch { /* Crash diagnostics must preserve the original exit behavior. */ }
|
|
@@ -283,12 +416,27 @@ export class RuntimeLogReporter {
|
|
|
283
416
|
const file = path.join(this.#crashDirectory, name);
|
|
284
417
|
try {
|
|
285
418
|
const stat = await fs.promises.lstat(file);
|
|
286
|
-
if (!stat.isFile()
|
|
287
|
-
const
|
|
288
|
-
if (
|
|
419
|
+
if (!stat.isFile()) continue;
|
|
420
|
+
const stale = Date.now() - stat.mtimeMs > 5_000;
|
|
421
|
+
if (stat.size > 65536) {
|
|
422
|
+
if (stale) await fs.promises.unlink(file).catch(() => {});
|
|
423
|
+
continue;
|
|
424
|
+
}
|
|
425
|
+
const rawEntry = await fs.promises.readFile(file, "utf8");
|
|
426
|
+
let entry;
|
|
427
|
+
try { entry = JSON.parse(rawEntry); } catch {
|
|
428
|
+
if (stale) await fs.promises.unlink(file).catch(() => {});
|
|
429
|
+
continue;
|
|
430
|
+
}
|
|
431
|
+
if (entry?.record?.category?.reporter !== "codem_js" || entry?.record?.log_type !== "log" || !entry.header) {
|
|
432
|
+
if (stale) await fs.promises.unlink(file).catch(() => {});
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
289
435
|
if (this.#closed) return;
|
|
290
|
-
if (entry.metricName === LIFECYCLE_EVENT_NAME) {
|
|
436
|
+
if (entry.metricName === LIFECYCLE_EVENT_NAME || entry.record.category.replay === "0") {
|
|
291
437
|
entry.record.category.replay = "1";
|
|
438
|
+
}
|
|
439
|
+
if (entry.metricName === LIFECYCLE_EVENT_NAME) {
|
|
292
440
|
this.#replay.queue.push({ ...entry, attempts: 0, crashFile: file });
|
|
293
441
|
} else {
|
|
294
442
|
this.#replay.queue.push({ header: entry.header, record: entry.record, metricName: entry.metricName,
|
|
@@ -320,16 +468,25 @@ export class RuntimeLogReporter {
|
|
|
320
468
|
get droppedCount() { return this.#dropped; }
|
|
321
469
|
get identityKey() { return JSON.stringify([this.#instanceId, this.#role, this.#identity.deviceId, this.#identity.userId, this.#identity.tenantId]); }
|
|
322
470
|
|
|
323
|
-
record(level, component, event, fields = {}) {
|
|
471
|
+
record(level, component, event, fields = {}, { captureError = false, persist = false } = {}) {
|
|
324
472
|
try {
|
|
325
473
|
if (this.#closed) return false;
|
|
326
|
-
|
|
474
|
+
const entry = this.#logEntry(level, component, event, fields, captureError);
|
|
475
|
+
if (persist) {
|
|
476
|
+
entry.record.category.replay = "0";
|
|
477
|
+
this.#saveCrash(entry);
|
|
478
|
+
}
|
|
479
|
+
return this.#enqueue(entry);
|
|
327
480
|
} catch { return false; }
|
|
328
481
|
}
|
|
329
482
|
|
|
330
|
-
#logEntry(level, component, event, fields) {
|
|
483
|
+
#logEntry(level, component, event, fields, captureError) {
|
|
331
484
|
let safeFields;
|
|
332
485
|
try { safeFields = projectFields(fields); } catch { safeFields = {}; }
|
|
486
|
+
if (captureError) {
|
|
487
|
+
const error = optional(() => diagnosticErrorDetail(fields.error));
|
|
488
|
+
if (error) safeFields.error = error;
|
|
489
|
+
}
|
|
333
490
|
if (OBSERVATION_EVENTS.has(event)) safeFields.observation_id = randomUUID();
|
|
334
491
|
const severity = ["info", "warn", "error", "fatal"].includes(level) ? level : "info";
|
|
335
492
|
// Keep arbitrary upstream error codes out of trusted-device metric dimensions.
|
|
@@ -348,7 +505,7 @@ export class RuntimeLogReporter {
|
|
|
348
505
|
};
|
|
349
506
|
}
|
|
350
507
|
|
|
351
|
-
recordLifecycle(event, fields = {}, { persist = false } = {}) {
|
|
508
|
+
recordLifecycle(event, fields = {}, { persist = false, captureError = false } = {}) {
|
|
352
509
|
try {
|
|
353
510
|
if (this.#closed || !Object.hasOwn(LIFECYCLE_COMPONENTS, event)) return false;
|
|
354
511
|
const unstable = fields.stability === "unstable" || fields.outcome === "failed" || fields.outcome === "conflicting";
|
|
@@ -377,11 +534,15 @@ export class RuntimeLogReporter {
|
|
|
377
534
|
const { replay: _replay, ...logDimensions } = dimensions;
|
|
378
535
|
const summary = hasDetail ? lifecycleErrorSummary(dimensions, fields) : "";
|
|
379
536
|
const { reason: _reason, error_code: _errorCode, ...projected } = projectFields(fields, false);
|
|
537
|
+
const isStartup = event === "daemon_process_startup" || event === "daemon_first_heartbeat";
|
|
538
|
+
const errorDetail = hasDetail && (captureError || (isStartup && ["failed", "rejected"].includes(fields.outcome)))
|
|
539
|
+
? optional(() => diagnosticErrorDetail(fields.error)) : undefined;
|
|
380
540
|
const safeFields = {
|
|
381
541
|
...projected, ...logDimensions, ...metrics,
|
|
382
542
|
process_instance_id: this.#instanceId,
|
|
383
|
-
...(
|
|
543
|
+
...(isStartup ? { startup_id: this.#instanceId } : {}),
|
|
384
544
|
observation_id: randomUUID(),
|
|
545
|
+
...(errorDetail ? { error: errorDetail } : {}),
|
|
385
546
|
...(summary ? { error_summary: summary } : {})
|
|
386
547
|
};
|
|
387
548
|
const extra = Object.fromEntries(LIFECYCLE_EXTRA_FIELDS
|
|
@@ -581,8 +742,8 @@ export function observeRuntimeLogSandboxConfig(config) {
|
|
|
581
742
|
try { active?.observeSandboxConfig(config); } catch { /* best effort */ }
|
|
582
743
|
}
|
|
583
744
|
|
|
584
|
-
export function recordRuntimeLog(level, component, event, fields = {}) {
|
|
585
|
-
try { return active?.record(level, component, event, fields) ?? false; } catch { return false; }
|
|
745
|
+
export function recordRuntimeLog(level, component, event, fields = {}, options = {}) {
|
|
746
|
+
try { return active?.record(level, component, event, fields, options) ?? false; } catch { return false; }
|
|
586
747
|
}
|
|
587
748
|
|
|
588
749
|
// An explicit result or state observation. This never waits for the collector;
|
|
@@ -592,27 +753,33 @@ export function recordBridgeLifecycle(event, fields, options = {}) {
|
|
|
592
753
|
}
|
|
593
754
|
|
|
594
755
|
export function flushRuntimeLogsInBackground() {
|
|
595
|
-
|
|
756
|
+
try {
|
|
757
|
+
if (active) setImmediate(() => { void active?.flush().catch(() => {}); }).unref?.();
|
|
758
|
+
} catch { /* best effort */ }
|
|
596
759
|
}
|
|
597
760
|
|
|
598
|
-
export function persistRuntimeCrash(component, event, fields) {
|
|
599
|
-
try { active?.persistCrash(component, event, fields); } catch { /* best effort */ }
|
|
761
|
+
export function persistRuntimeCrash(component, event, fields, options = {}) {
|
|
762
|
+
try { active?.persistCrash(component, event, fields, options); } catch { /* best effort */ }
|
|
600
763
|
}
|
|
601
764
|
|
|
602
765
|
// A failure that ends a short-lived process: persist first, then try to deliver
|
|
603
766
|
// 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 */ }
|
|
767
|
+
export function reportRuntimeFailure(component, event, fields = {}, options = {}) {
|
|
768
|
+
try { active?.persistCrash(component, event, fields, { captureError: Boolean(fields?.error), ...options, deliverNow: true }); } catch { /* best effort */ }
|
|
606
769
|
flushRuntimeLogsInBackground();
|
|
607
770
|
}
|
|
608
771
|
|
|
772
|
+
export function closeRuntimeLogs() {
|
|
773
|
+
try { active?.close(); active = undefined; } catch { /* best effort */ }
|
|
774
|
+
}
|
|
775
|
+
|
|
609
776
|
export async function flushRuntimeLogs(budgetMs = 200) {
|
|
610
777
|
if (!active) return;
|
|
611
778
|
let timeout;
|
|
612
779
|
try {
|
|
613
780
|
await Promise.race([
|
|
614
781
|
active.flush({ timeoutMs: budgetMs }),
|
|
615
|
-
new Promise((resolve) => { timeout = setTimeout(resolve, budgetMs); })
|
|
782
|
+
new Promise((resolve) => { timeout = setTimeout(resolve, budgetMs); timeout.unref?.(); })
|
|
616
783
|
]);
|
|
617
784
|
} catch { /* best effort, including a broken uploader */ } finally { clearTimeout(timeout); }
|
|
618
785
|
}
|
|
@@ -651,12 +818,19 @@ export function recordInteractiveProcessExit({ exitCode, signal }) {
|
|
|
651
818
|
}
|
|
652
819
|
|
|
653
820
|
// Select events explicitly, then project fields again at the remote boundary.
|
|
654
|
-
export function recordSelectedRuntimeLog(component, event, fields = {}) {
|
|
821
|
+
export function recordSelectedRuntimeLog(component, event, fields = {}, { capturedError = undefined } = {}) {
|
|
655
822
|
try {
|
|
656
823
|
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;
|
|
824
|
+
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
825
|
const expected = optional(() => fields?.errorKind === "user_stop" || fields?.terminalError?.kind === "user_stop" || fields?.exitCode === 130 || fields?.signal === "SIGINT");
|
|
659
|
-
const level = expected ? "info"
|
|
660
|
-
|
|
826
|
+
const level = expected ? "info"
|
|
827
|
+
: (fields?.status === "failed" || (selectedEvent === "authentication_snapshot.router_unavailable" && fields?.reason === "storage") || /(?:failed|error|exhausted|timeout)$/u.test(event)) ? "error"
|
|
828
|
+
: /(?:suspect|dropped|missing|oversize|unavailable)$/u.test(event) ? "warn"
|
|
829
|
+
: "info";
|
|
830
|
+
const captureError = capturedError !== undefined;
|
|
831
|
+
const persist = selectedEvent === "router.credentials.refresh_failed"
|
|
832
|
+
|| (selectedEvent === "authentication_snapshot.router_unavailable" && fields?.reason === "storage");
|
|
833
|
+
recordRuntimeLog(level, component, event, captureError ? { ...fields, error: capturedError } : fields, { captureError, persist });
|
|
834
|
+
if (persist) flushRuntimeLogsInBackground();
|
|
661
835
|
} catch { /* best effort */ }
|
|
662
836
|
}
|