@lark-codem/codem-cli 0.1.281-dev.100104639844.0.ga23aea5 → 0.1.281-dev.100104658625.0.g0f105de
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/codem-startup-logs.js +14 -13
- package/bin/codem.js +30 -107
- package/bin/slardar-pc-transport.js +134 -0
- package/bin/tt-env.js +1 -1
- package/bin/worker-runtime-telemetry.js +1 -2
- package/package.json +9 -12
- package/profile/credential-errors.js +4 -3
- 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 +2 -3
- package/profile/runtime-logs.js +389 -208
- package/profile/slardar-pc-transport.js +134 -0
- package/auth/index.d.ts +0 -19
- package/auth/index.js +0 -5936
- package/profile/realtime-log-id.js +0 -9
- package/profile/sandbox-observability.js +0 -17
package/profile/runtime-logs.js
CHANGED
|
@@ -1,34 +1,37 @@
|
|
|
1
|
-
import { realtimeLogID } from "./realtime-log-id.js";
|
|
2
|
-
import { sandboxObservationContext, sandboxLogUploadAllowed } from "./sandbox-observability.js";
|
|
3
1
|
import { workerRuntimeAttributes } from "./worker-runtime-observation.js";
|
|
4
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
5
3
|
import os from "node:os";
|
|
6
4
|
import fs from "node:fs";
|
|
7
5
|
import path from "node:path";
|
|
6
|
+
import { setImmediate as yieldToEventLoop } from "node:timers/promises";
|
|
8
7
|
import { diagnosticId } from "./diagnostic-id.js";
|
|
8
|
+
import { safeServerLogId } from "./http-read-diagnostics.js";
|
|
9
|
+
import { redactDiagnosticText } from "./diagnostic-text.js";
|
|
9
10
|
import { readDeviceId } from "./device-identity.js";
|
|
10
|
-
import { sendSlardarPcBatch, SLARDAR_PC_AID, SLARDAR_PC_REPORTER_VERSION
|
|
11
|
+
import { sendSlardarPcBatch, SLARDAR_PC_AID, SLARDAR_PC_REPORTER_VERSION,
|
|
12
|
+
captureRuntimeLogArguments, formatRuntimeLogText, runtimeLogSecrets, isRuntimeOutputError } from "./slardar-pc-transport.js";
|
|
11
13
|
|
|
12
14
|
const CAPACITY = 256;
|
|
13
15
|
const BATCH_SIZE = 32;
|
|
14
16
|
const INTERVAL_MS = 10_000;
|
|
15
17
|
const REQUEST_TIMEOUT_MS = 3_000;
|
|
16
18
|
const MAX_BATCH_BYTES = 256 * 1024;
|
|
19
|
+
const TEXT_FORMAT_BUDGET_MS = 16;
|
|
17
20
|
const LIFECYCLE_EVENT_NAME = "codem_bridge_lifecycle";
|
|
18
21
|
const LIFECYCLE_COMPONENTS = {
|
|
19
|
-
|
|
22
|
+
daemon_process_startup: "daemon", daemon_first_heartbeat: "daemon",
|
|
23
|
+
runtime_sync: "runtime-post", command_handoff: "bridge",
|
|
20
24
|
runner_operation: "bridge", delivery_settled: "runtime-post", runtime_state: "bridge",
|
|
21
25
|
event_discarded: "runtime-post", process_lifecycle: "linco"
|
|
22
26
|
};
|
|
23
27
|
const LIFECYCLE_METRICS = [
|
|
24
|
-
"duration_ms", "ack_settle_duration_ms", "
|
|
25
|
-
"outage_duration_ms", "consecutive_failures", "deferred_age_ms", "pending_command_ack_count",
|
|
28
|
+
"duration_ms", "ack_settle_duration_ms", "operation_age_ms", "deferred_age_ms", "pending_command_ack_count",
|
|
26
29
|
"pending_ack_age_ms", "pending_event_count", "oldest_event_age_ms", "lifetime_ms"
|
|
27
30
|
];
|
|
28
31
|
const LIFECYCLE_DIMENSIONS = {
|
|
29
32
|
outcome: ["success", "failed", "rejected", "canceled", "unknown", "accepted", "duplicate", "conflicting", "observed", "recovered"],
|
|
30
33
|
operation: ["prepare", "spawn", "ready", "cancel", "shutdown"],
|
|
31
|
-
scope: ["
|
|
34
|
+
scope: ["runner", "command", "queue"],
|
|
32
35
|
kind: ["command_ack", "runtime_event", "control", "events", "relay", "offline"],
|
|
33
36
|
phase: ["startup_marker", "prelude", "healthcheck", "config_load", "update_check", "service_reconcile", "login_gate", "launch", "authentication", "singleton", "initialize", "start_client", "first_sync", "trusted_device",
|
|
34
37
|
"build_request", "request", "validate_response", "apply_response", "persist_state",
|
|
@@ -38,7 +41,8 @@ const LIFECYCLE_DIMENSIONS = {
|
|
|
38
41
|
"shutting_down_handoff", "handoff_target_not_active", "handler_inflight", "duplicate_inflight",
|
|
39
42
|
"runtime_unavailable", "runtime_environment_failed", "capability_probe_failed", "runtime_binary_changed",
|
|
40
43
|
"strict_resume_unsupported", "turn_context_unsupported", "active_run_protocol_mismatch", "trusted_device_blocked",
|
|
41
|
-
"invalid_runtime_event", "event_rejected", "
|
|
44
|
+
"invalid_runtime_event", "event_rejected", "device_replaced", "device_unbound",
|
|
45
|
+
"task_terminated:canceled", "task_terminated:failed", "task_terminated:succeeded"],
|
|
42
46
|
error_source: ["bridge", "base", "linco", "transport"],
|
|
43
47
|
stability: ["stable", "unstable", "unknown"],
|
|
44
48
|
action: ["exit", "restart"],
|
|
@@ -65,6 +69,10 @@ const OBSERVATION_DIMENSIONS = {
|
|
|
65
69
|
timing_origin: ["observed", "restored_unknown"]
|
|
66
70
|
};
|
|
67
71
|
const OBSERVATION_METRICS = {
|
|
72
|
+
"startup.started": [],
|
|
73
|
+
"startup.registered": ["duration_ms"],
|
|
74
|
+
"startup.failed": ["duration_ms"],
|
|
75
|
+
history_recall: ["duration_ms", "hit_count", "message_count", "output_tokens_upper_bound"],
|
|
68
76
|
host_identity_collection: ["duration_ms", "field_error_count"],
|
|
69
77
|
host_identity_command: ["duration_ms", "timeout_ms"],
|
|
70
78
|
host_session_attempt: ["elapsed_ms", "next_retry_ms", "consecutive_failures", "session_remaining_ms", ...TRUSTED_DEVICE_PHASES.map(phase => `${phase}_duration_ms`)],
|
|
@@ -78,49 +86,30 @@ const OBSERVATION_METRICS = {
|
|
|
78
86
|
command_observation_closed: ["omitted_detail_count", "pending_command_ack_count", "deferred_count"],
|
|
79
87
|
diagnostic_reporter_health: ["dropped_delta", "upload_failure_delta", "pending_event_count"]
|
|
80
88
|
};
|
|
81
|
-
const EXTRA_FIELDS = ["observation_id", "runtime_client_instance_id", "command_id", "delivery_id", "probe_id", "sync_id", "transport_request_id", "attempt_id"];
|
|
89
|
+
const EXTRA_FIELDS = ["startup_id", "controller_id", "logical_sandbox_id", "sandbox_id", "dispatch_id", "observation_id", "runtime_client_instance_id", "command_id", "delivery_id", "probe_id", "sync_id", "transport_request_id", "attempt_id", "server_log_id"];
|
|
82
90
|
const LIFECYCLE_EXTRA_FIELDS = [...EXTRA_FIELDS, "process_instance_id", "startup_id", "request_id", "event_id"];
|
|
83
|
-
const UPLINK_BATCH_METRICS = [
|
|
84
|
-
"message_count", "packet_bytes", "queue_wait_ms", "encode_ms", "ack_wait_ms",
|
|
85
|
-
"batch_sequence", "pending_count", "pending_bytes"
|
|
86
|
-
];
|
|
87
|
-
const UPLINK_DIAGNOSTIC_METRICS = new Map([
|
|
88
|
-
["uplink_queue_pressure", ["pending_count", "pending_bytes", "oldest_age_ms", "full_count", "batch_sequence", "ack_wait_ms"]],
|
|
89
|
-
["event_handoff_failed", UPLINK_BATCH_METRICS],
|
|
90
|
-
["uplink_batch_slow", UPLINK_BATCH_METRICS]
|
|
91
|
-
]);
|
|
92
91
|
const STRING_FIELDS = new Set([
|
|
93
|
-
|
|
94
|
-
"
|
|
95
|
-
"lane", "target_kind", "frontier_did", "packet_kind", "packet_traceparent",
|
|
92
|
+
...EXTRA_FIELDS, "command_type", "ack_status", "ack_outcome", "readback_scope", "timing_origin", "required_capability",
|
|
93
|
+
"request_id", "command_id", "session_id", "task_id", "dispatch_id", "event_id", "sync_id",
|
|
96
94
|
"process_instance_id", "run_id", "stage", "phase", "status", "outcome", "reason", "action",
|
|
97
95
|
"error_class", "error_code", "error_kind", "error_type", "code", "signal", "stop_reason",
|
|
98
96
|
"first_error", "retry_source", "cleanup_result",
|
|
99
97
|
"terminal_event", "event_type", "actor_type", "source", "trigger", "hook_id", "hook_event",
|
|
100
98
|
"target_version", "cli_version", "core_version", "version", "previous_state", "state",
|
|
101
99
|
"failure_kind", "failure_impact", "failure_type", "failure_subtype", "failure_code", "failure_status", "delay_source", "mode", "provider", "name", "termination", "interaction_id", "interaction_kind", "owner_state", "artifact_id", "resource_type", "delivery_mode", "host", "scheme", "tool_call_id", "tool_name", "background_task_id", "model", "artifact_kind", "codem_user_id", "device_id", "operation", "foreground_error_code",
|
|
102
|
-
"
|
|
103
|
-
"operation_id", "entrypoint", "workflow_launch_id", "runtime_client_instance_id", "connection_instance_id", "lease_epoch",
|
|
104
|
-
"load_id", "refresh_id", "registry_snapshot_id", "capability_key", "capability_type",
|
|
105
|
-
"component_type", "publisher_type", "capability_source", "installation_mode",
|
|
106
|
-
"capability_version", "project_key", "business_scene", "invocation_id", "result",
|
|
107
|
-
"error_category", "runtime_scope", "refresh_trigger", "load_trigger", "stage_name",
|
|
108
|
-
"operation_name", "invocation_source", "binding_state", "load_result"
|
|
100
|
+
"operation_id", "entrypoint", "native_operation", "workflow_launch_id"
|
|
109
101
|
]);
|
|
110
102
|
const VALUE_FIELDS = new Set([
|
|
111
|
-
"
|
|
112
|
-
"
|
|
103
|
+
"truncated",
|
|
104
|
+
"session_retained", "unreadable", "win32_error",
|
|
105
|
+
"lease_valid_until_ms", "requested_valid_until_ms", "lease_remaining_ms", "wall_remaining_ms",
|
|
113
106
|
...new Set(Object.values(OBSERVATION_METRICS).flat()),
|
|
114
107
|
"pid", "exit_code", "duration_ms", "elapsed_ms", "wait_ms", "run_ms", "total_ms", "took_ms",
|
|
115
108
|
"attempt", "attempts", "attempt_count", "retryable", "http_status", "errno", "active_task_count",
|
|
116
109
|
"pending_event_count", "pending_command_ack_count", "next_retry_ms", "consecutive_failures",
|
|
117
|
-
|
|
118
|
-
"outage_duration_ms", "startup_duration_ms", "failed_attempts", "active_runs", "completed",
|
|
110
|
+
"outage_duration_ms", "failed_attempts", "active_runs", "completed",
|
|
119
111
|
"delivered", "result_delivered", "queued_behind_existing", "expected", "timed_out",
|
|
120
112
|
"force_exit_ms", "teardown_ceiling_ms", "recovered", "count", "ms_since_process_start", "owner_pid", "consumed", "delivery_attempt", "ack_deadline_ms", "command_to_bridge_ms", "size_bytes", "source_size_bytes", "processed_bytes", "before", "after", "omitted_detail_count", "opened", "selected", "foreground",
|
|
121
|
-
"expected_count", "loaded_count", "loaded_capability_count", "failed_count", "skipped_count", "ready_count", "downloaded_count", "turn_id", "turn_index",
|
|
122
|
-
"late_rpc_error_code", "lifecycle_wait_ms", "prepare_ms", "router_cred_ms", "meegle_init_ms", "spawn_init_ms", "budget_ms",
|
|
123
|
-
"oauth_ms", "project_list_ms", "config_total_ms", "write_total_ms",
|
|
124
113
|
...LIFECYCLE_METRICS
|
|
125
114
|
]);
|
|
126
115
|
|
|
@@ -138,7 +127,7 @@ function optional(read) {
|
|
|
138
127
|
}
|
|
139
128
|
|
|
140
129
|
function metricProjection(event, fields = {}) {
|
|
141
|
-
return { count: 1, ...Object.fromEntries((OBSERVATION_METRICS[event] ??
|
|
130
|
+
return { count: 1, ...Object.fromEntries((OBSERVATION_METRICS[event] ?? [])
|
|
142
131
|
.filter(key => typeof fields?.[key] === "number" && Number.isFinite(fields[key]) && fields[key] >= 0)
|
|
143
132
|
.map(key => [key, fields[key]])) };
|
|
144
133
|
}
|
|
@@ -147,18 +136,11 @@ function extraProjection(fields = {}) {
|
|
|
147
136
|
return Object.fromEntries(EXTRA_FIELDS.filter(key => token(fields?.[key])).map(key => [key, token(fields[key])]));
|
|
148
137
|
}
|
|
149
138
|
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
function projectFields(input, fingerprintErrors = true, component) {
|
|
139
|
+
function projectFields(input, fingerprintErrors = true) {
|
|
153
140
|
const result = {};
|
|
154
141
|
for (const [key, value] of Object.entries(input ?? {}).slice(0, 100)) {
|
|
155
142
|
const name = fieldName(key);
|
|
156
|
-
if (
|
|
157
|
-
result[name] = value;
|
|
158
|
-
} else if (component === "realtime" && REALTIME_IDS.has(name)) {
|
|
159
|
-
const id = realtimeLogID(value);
|
|
160
|
-
if (id !== undefined) result[name] = id;
|
|
161
|
-
} else if (STRING_FIELDS.has(name)) {
|
|
143
|
+
if (STRING_FIELDS.has(name)) {
|
|
162
144
|
const safe = token(value);
|
|
163
145
|
if (safe) result[name] = safe;
|
|
164
146
|
} else if (VALUE_FIELDS.has(name) && (typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value)))) {
|
|
@@ -183,7 +165,9 @@ function projectFields(input, fingerprintErrors = true, component) {
|
|
|
183
165
|
// Errors can contain prompts, paths and raw upstream response bodies.
|
|
184
166
|
// Retain classification + a fingerprint, never their arbitrary text.
|
|
185
167
|
const message = typeof error === "string" ? error : error.message;
|
|
186
|
-
|
|
168
|
+
// Slicing a rope can flatten its full body before hashing the prefix.
|
|
169
|
+
// Oversized remote messages are omitted, so skip their synchronous hash too.
|
|
170
|
+
if (typeof message === "string" && message.length <= 8192) result.error_fingerprint = createHash("sha256").update(message.slice(0, 4096)).digest("hex").slice(0, 24);
|
|
187
171
|
}
|
|
188
172
|
return result;
|
|
189
173
|
}
|
|
@@ -203,98 +187,201 @@ function lifecycleErrorSummary(dimensions, fields) {
|
|
|
203
187
|
|
|
204
188
|
function lifecycleErrorCode(fields) {
|
|
205
189
|
const code = token(fields.error_code ?? fields.error?.code ?? fields.error?.cause?.code)?.toLowerCase();
|
|
206
|
-
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;
|
|
190
|
+
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;
|
|
207
191
|
const status = Number(fields.http_status);
|
|
208
192
|
if (Number.isInteger(status) && status >= 100 && status <= 599) return `http_${status}`;
|
|
209
193
|
return fields.outcome === "failed" || fields.outcome === "rejected" || fields.outcome === "conflicting" ? "unknown" : undefined;
|
|
210
194
|
}
|
|
211
195
|
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
]);
|
|
196
|
+
function toWellFormedString(value) {
|
|
197
|
+
if (typeof value.toWellFormed === "function") return value.toWellFormed();
|
|
198
|
+
// Node 18 compatibility: replace unpaired UTF-16 surrogates with U+FFFD.
|
|
199
|
+
return value.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "\uFFFD");
|
|
200
|
+
}
|
|
218
201
|
|
|
219
|
-
const
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
}
|
|
202
|
+
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;
|
|
203
|
+
|
|
204
|
+
function sanitizeDiagnosticPath(rawPath) {
|
|
205
|
+
if (typeof rawPath !== "string") return "[REDACTED_PATH]";
|
|
206
|
+
const bounded = rawPath.length > 1024 ? rawPath.slice(0, 1024) : rawPath;
|
|
207
|
+
const trimmed = bounded.trim();
|
|
208
|
+
let end = trimmed.length;
|
|
209
|
+
while (end > 0 && ",:;)]}".includes(trimmed[end - 1])) end -= 1;
|
|
210
|
+
const suffix = trimmed.slice(end);
|
|
211
|
+
const core = trimmed.slice(0, end).replace(/^(?:\\\\\?\\|file:\/\/\/+)/iu, "").replaceAll("\\", "/");
|
|
212
|
+
const homeMatch = core.match(/(?:^|\/)(\.(?:codem|linco)(?:\/[^\s'"()(),。,:;\u4e00-\u9fff\u3000-\u303f\uff00-\uffef]+)?)$/iu);
|
|
213
|
+
if (homeMatch) return `~/${homeMatch[1]}${suffix}`;
|
|
214
|
+
const moduleMatch = core.match(/(?:^|\/)(node_modules\/[^\s'"()(),。,:;\u4e00-\u9fff\u3000-\u303f\uff00-\uffef]+)$/iu);
|
|
215
|
+
if (moduleMatch) return `${moduleMatch[1]}${suffix}`;
|
|
216
|
+
const base = core.split("/").filter(Boolean).pop();
|
|
217
|
+
if (base && SAFE_DIAGNOSTIC_BASENAME.test(base)) return `.../${base}${suffix}`;
|
|
218
|
+
return `[REDACTED_PATH]${suffix}`;
|
|
219
|
+
}
|
|
235
220
|
|
|
236
|
-
function
|
|
237
|
-
|
|
238
|
-
if (typeof value === "string") return value
|
|
239
|
-
if (
|
|
240
|
-
|
|
241
|
-
if (value instanceof Error) {
|
|
242
|
-
const summary = {
|
|
243
|
-
error_type: value.name || "Error",
|
|
244
|
-
error_message: typeof value.message === "string" ? value.message.slice(0, 1024) : ""
|
|
245
|
-
};
|
|
246
|
-
if (value.code !== undefined) summary.error_code = String(value.code).slice(0, 128);
|
|
247
|
-
if (value.errno !== undefined) summary.errno = value.errno;
|
|
248
|
-
if (value.rpcError?.code !== undefined) summary.rpc_error_code = value.rpcError.code;
|
|
249
|
-
return summary;
|
|
250
|
-
}
|
|
251
|
-
if (depth >= 3) return undefined;
|
|
252
|
-
if (Array.isArray(value)) {
|
|
253
|
-
return value.slice(0, 32).map(entry => serializeLocalValue(entry, depth + 1)).filter(entry => entry !== undefined);
|
|
254
|
-
}
|
|
255
|
-
if (typeof value === "object") {
|
|
256
|
-
const out = {};
|
|
257
|
-
for (const [key, entry] of Object.entries(value)) {
|
|
258
|
-
if (entry === undefined || LOCAL_SENSITIVE_KEY.test(key)) continue;
|
|
259
|
-
const serialized = serializeLocalValue(entry, depth + 1);
|
|
260
|
-
if (serialized !== undefined) out[key] = serialized;
|
|
261
|
-
}
|
|
262
|
-
return out;
|
|
221
|
+
function textOrBuffer(read) {
|
|
222
|
+
const value = optional(read);
|
|
223
|
+
if (typeof value === "string") return value;
|
|
224
|
+
if (Buffer.isBuffer(value) || value instanceof Uint8Array) {
|
|
225
|
+
return optional(() => Buffer.from(value).subarray(0, 32_768).toString("utf8"));
|
|
263
226
|
}
|
|
264
227
|
return undefined;
|
|
265
228
|
}
|
|
266
229
|
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
230
|
+
function boundedSlice(value, maxChars = 32_768) {
|
|
231
|
+
return typeof value === "string" ? (value.length > maxChars ? value.slice(0, maxChars) : value) : undefined;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function escapeRegExp(value) {
|
|
235
|
+
return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function privateErrorText(error) {
|
|
239
|
+
const rawResponse = optional(() => error.response?.raw);
|
|
240
|
+
const logId = optional(() => error.logid);
|
|
241
|
+
const output = optional(() => error.runtimeDiagnosticOutput);
|
|
242
|
+
const rawPath = optional(() => error.path);
|
|
243
|
+
const rawDest = optional(() => error.dest);
|
|
244
|
+
return [
|
|
245
|
+
// A wrapper can interpolate its cause's raw output into its own message.
|
|
246
|
+
[error instanceof SyntaxError ? boundedSlice(optional(() => error.message)) : undefined, "[REDACTED_PARSE_INPUT]"],
|
|
247
|
+
[boundedSlice(output === true ? optional(() => error.message) : output), "[REDACTED_OUTPUT]"],
|
|
248
|
+
[typeof rawResponse === "string" ? boundedSlice(rawResponse.trim()) : undefined, "[REDACTED_RESPONSE]"],
|
|
249
|
+
[boundedSlice(optional(() => error.runtimeDiagnosticResponseExcerpt)), "[REDACTED_RESPONSE]"],
|
|
250
|
+
[typeof logId === "string" && !safeServerLogId(logId) ? `(logid: ${logId})` : undefined, "(logid: [REDACTED_LOG_ID])"],
|
|
251
|
+
[boundedSlice(optional(() => error.cmd), 4096), "[REDACTED_COMMAND]"],
|
|
252
|
+
[textOrBuffer(() => error.stderr), "[REDACTED_OUTPUT]"],
|
|
253
|
+
[textOrBuffer(() => error.stdout), "[REDACTED_OUTPUT]"],
|
|
254
|
+
[textOrBuffer(() => error.processIdentityDiagnostic?.stderr), "[REDACTED_OUTPUT]"],
|
|
255
|
+
[textOrBuffer(() => error.processIdentityDiagnostic?.stdout), "[REDACTED_OUTPUT]"],
|
|
256
|
+
[rawPath, sanitizeDiagnosticPath(rawPath)],
|
|
257
|
+
[rawDest, sanitizeDiagnosticPath(rawDest)]
|
|
258
|
+
].filter(([raw]) => typeof raw === "string" && raw.trim().length >= 2 && !/^[./\\]+$/u.test(raw.trim()) && !/^\[REDACTED/u.test(raw.trim()))
|
|
259
|
+
.flatMap(([raw, replacement]) => raw.trim() !== raw
|
|
260
|
+
? [[raw, replacement], [raw.trim(), replacement]]
|
|
261
|
+
: [[raw, replacement]]);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function userInputErrorPatterns(error) {
|
|
265
|
+
const raw = optional(() => error.runtimeDiagnosticUserInput);
|
|
266
|
+
const items = Array.isArray(raw) ? raw : typeof raw === "string" ? [raw] : [];
|
|
267
|
+
return items
|
|
268
|
+
.filter(item => typeof item === "string" && item.trim().length >= 1 && !/^\[REDACTED/u.test(item.trim()))
|
|
269
|
+
.map(item => boundedSlice(item.trim(), 32_768));
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function replaceTruncatedPrefix(text, raw, replacement) {
|
|
273
|
+
if (raw.length < 64) return text;
|
|
274
|
+
const probe = raw.slice(0, 64);
|
|
275
|
+
let cursor = 0;
|
|
276
|
+
while (cursor < text.length) {
|
|
277
|
+
const pos = text.indexOf(probe, cursor);
|
|
278
|
+
if (pos === -1) break;
|
|
279
|
+
let matchLen = probe.length;
|
|
280
|
+
while (pos + matchLen < text.length && matchLen < raw.length && text[pos + matchLen] === raw[matchLen]) {
|
|
281
|
+
matchLen += 1;
|
|
280
282
|
}
|
|
281
|
-
|
|
283
|
+
text = text.slice(0, pos) + replacement + text.slice(pos + matchLen);
|
|
284
|
+
cursor = pos + replacement.length;
|
|
285
|
+
}
|
|
286
|
+
return text;
|
|
282
287
|
}
|
|
283
288
|
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
289
|
+
function isErrorLikeObject(value) {
|
|
290
|
+
if (!value || typeof value !== "object") return false;
|
|
291
|
+
if (value instanceof Error) return true;
|
|
292
|
+
return typeof optional(() => value.message) === "string"
|
|
293
|
+
|| typeof optional(() => value.code) === "string"
|
|
294
|
+
|| Number.isSafeInteger(optional(() => value.code));
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// Keep captured exceptions small enough for crash replay, including the
|
|
298
|
+
// second JSON encoding of log_content.
|
|
299
|
+
function diagnosticErrorDetail(error, depth = 0, inheritedUserInputs = []) {
|
|
300
|
+
if (depth === 4 || (typeof error !== "string" && !isErrorLikeObject(error))) return undefined;
|
|
301
|
+
const name = token(optional(() => error.name));
|
|
302
|
+
const rawCode = optional(() => error.code);
|
|
303
|
+
const code = Number.isSafeInteger(rawCode) ? rawCode : token(rawCode);
|
|
304
|
+
const syscall = token(optional(() => error.syscall));
|
|
305
|
+
const rawErrno = optional(() => error.errno);
|
|
306
|
+
const errno = Number.isSafeInteger(rawErrno) ? rawErrno : token(rawErrno);
|
|
307
|
+
const signal = token(optional(() => error.signal));
|
|
308
|
+
const kind = token(optional(() => error.kind ?? error.errorKind ?? error.terminalError?.kind));
|
|
309
|
+
const rawPath = optional(() => error.path);
|
|
310
|
+
const safePath = typeof rawPath === "string" && rawPath.trim().length >= 2 && !/^[./\\]+$/u.test(rawPath.trim())
|
|
311
|
+
? sanitizeDiagnosticPath(rawPath)
|
|
312
|
+
: undefined;
|
|
313
|
+
// JSON.parse can quote the credential file's contents in the SyntaxError.
|
|
314
|
+
if (error instanceof SyntaxError || isRuntimeOutputError(error) || optional(() => error.runtimeDiagnosticOutput) === true) {
|
|
315
|
+
return { name, code, ...(kind ? { kind } : {}), ...(syscall ? { syscall } : {}), ...(errno !== undefined ? { errno } : {}), ...(signal ? { signal } : {}) };
|
|
316
|
+
}
|
|
317
|
+
const privateText = [];
|
|
318
|
+
const userInputs = [...inheritedUserInputs];
|
|
319
|
+
let cause = error;
|
|
320
|
+
for (let i = depth; cause && i < 4; i++) {
|
|
321
|
+
privateText.push(...privateErrorText(cause));
|
|
322
|
+
userInputs.push(...userInputErrorPatterns(cause));
|
|
323
|
+
cause = optional(() => cause.cause);
|
|
324
|
+
}
|
|
325
|
+
privateText.sort(([a], [b]) => b.length - a.length);
|
|
326
|
+
const uniqueUserInputs = [...new Set(userInputs)].slice(0, 64).sort((a, b) => b.length - a.length);
|
|
327
|
+
const clean = (text, limit) => {
|
|
328
|
+
if (typeof text !== "string") return undefined;
|
|
329
|
+
if (text.length > 32_768) text = text.slice(0, 32_768);
|
|
330
|
+
for (const [raw, replacement] of privateText) {
|
|
331
|
+
text = text.replaceAll(raw, replacement);
|
|
332
|
+
if (replacement === "[REDACTED_RESPONSE]" || replacement === "[REDACTED_OUTPUT]") {
|
|
333
|
+
text = replaceTruncatedPrefix(text, raw, replacement);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
if (uniqueUserInputs.length > 0) {
|
|
337
|
+
const frameMatch = /\r?\n(?=[ \t]+at )/u.exec(text);
|
|
338
|
+
const headerEnd = frameMatch ? frameMatch.index : text.length;
|
|
339
|
+
let header = text.slice(0, headerEnd);
|
|
340
|
+
for (const inputArg of uniqueUserInputs) {
|
|
341
|
+
const flags = inputArg.length >= 2 ? "giu" : "gu";
|
|
342
|
+
const pattern = new RegExp(
|
|
343
|
+
`(?<=^|[\\s'"\`“”‘’「」『』【】{}()(),。、,;!??!;::=\\[<])${escapeRegExp(inputArg)}(?=$|[\\s'"\`“”‘’「」『』【】{}()(),。、,;!??!;::=\\]>]|\\.(?=$|\\s))`,
|
|
344
|
+
flags
|
|
345
|
+
);
|
|
346
|
+
header = header.replace(pattern, "[REDACTED_ARG]");
|
|
347
|
+
if (inputArg.length >= 64) {
|
|
348
|
+
header = replaceTruncatedPrefix(header, inputArg, "[REDACTED_ARG]");
|
|
349
|
+
const lowerArg = inputArg.toLowerCase();
|
|
350
|
+
if (lowerArg !== inputArg) header = replaceTruncatedPrefix(header, lowerArg, "[REDACTED_ARG]");
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
text = header + text.slice(headerEnd);
|
|
354
|
+
}
|
|
355
|
+
text = text.replace(/(?:<!doctype\s+html\b|<html\b)[\s\S]*/iu, "[REDACTED_RESPONSE]");
|
|
356
|
+
const redacted = redactDiagnosticText(text, { redactURLPath: true })
|
|
357
|
+
// Keep stack locations as file:line:column (including `at async C:\Users\Alice Smith\...`).
|
|
358
|
+
.replace(/^([ \t]+at (?:async )?(?:[^\r\n(]*? \()?)(?:\\\\\?\\|file:\/\/\/+|[a-z]:[\\/]|\\\\|\/)[^\r\n]*[\\/]([^\\/()\r\n]+:\d+:\d+\)?)(?=\r?$)/gimu, "$1$2")
|
|
359
|
+
// Strip OS user home directory names (including spaces and CJK) before further path normalization.
|
|
360
|
+
.replace(/(?:\\\\\?\\|file:\/\/\/(?=[a-z]:)|file:\/\/(?=\/))?(?:[a-z]:[\\/]Users|\/(?:Users|home))[\\/][^\\/\r\n'"<>|()(),。,:;]{1,128}(?=[\\/])/giu, "~")
|
|
361
|
+
.replace(/(?:\\\\\?\\|file:\/\/\/(?=[a-z]:)|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]|$)|[^\s\\/\r\n'"<>|()(),。,:;]{1,64}(?=[\s'"<>|()(),。,:;]|$))/giu, "[REDACTED_PATH]")
|
|
362
|
+
// Sanitize quoted paths first (preserving ~/.codem, ~/.linco, node_modules, and safe basenames).
|
|
363
|
+
.replace(/(['"])((?:~[\\/]|\\\\\?\\|file:\/\/\/+|[a-z]:[\\/]|\\\\|\/(?!\/))[^'"\r\n]+)\1/giu, (_, quote, candidate) => `${quote}${sanitizeDiagnosticPath(candidate)}${quote}`)
|
|
364
|
+
// Sanitize unquoted ~-normalized home paths and other filesystem paths token-by-token (no cross-space clobbering).
|
|
365
|
+
.replace(/(?<!['"\w])(~[\\/][^\s'"()(),。;\]]+)/giu, (_, candidate) => sanitizeDiagnosticPath(candidate))
|
|
366
|
+
.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)}`)
|
|
367
|
+
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/gu, "�");
|
|
368
|
+
return toWellFormedString(redacted.length <= limit ? redacted : redacted.slice(0, limit - 1) + "…");
|
|
369
|
+
};
|
|
370
|
+
const textLimit = depth === 0 ? 2048 : 1024;
|
|
371
|
+
return {
|
|
372
|
+
name, code,
|
|
373
|
+
...(kind ? { kind } : {}),
|
|
374
|
+
...(syscall ? { syscall } : {}),
|
|
375
|
+
...(errno !== undefined ? { errno } : {}),
|
|
376
|
+
...(signal ? { signal } : {}),
|
|
377
|
+
...(safePath && safePath !== "[REDACTED_PATH]" ? { path: safePath } : {}),
|
|
378
|
+
message: clean(typeof error === "string" ? error : optional(() => error.message), textLimit),
|
|
379
|
+
stack: clean(optional(() => error.stack), textLimit),
|
|
380
|
+
cause: diagnosticErrorDetail(optional(() => error.cause), depth + 1, uniqueUserInputs)
|
|
381
|
+
};
|
|
294
382
|
}
|
|
295
383
|
|
|
296
384
|
function keepLegacyMetric(event, fields, role, severity) {
|
|
297
|
-
if (REALTIME_LOG_ONLY.has(event)) return false;
|
|
298
385
|
if (/^startup\.(?:main|update_check|daemon_service_reconcile|login_gate|login_handoff_to_linco)$/u.test(event) && severity === "info") return false;
|
|
299
386
|
if (/(?:^|\.)drain_(?:started|completed)$/u.test(event) && severity === "info") return false;
|
|
300
387
|
if (role === "daemon" && event === "runtime_capability_probe" && severity === "info") return false;
|
|
@@ -328,7 +415,6 @@ export class RuntimeLogReporter {
|
|
|
328
415
|
#live = { queue: [], inflight: undefined, abort: undefined };
|
|
329
416
|
#replay = { queue: [], inflight: undefined, abort: undefined };
|
|
330
417
|
#identity = {};
|
|
331
|
-
#resourceContext = {};
|
|
332
418
|
#timer;
|
|
333
419
|
#closed = false;
|
|
334
420
|
#dropped = 0;
|
|
@@ -346,17 +432,26 @@ export class RuntimeLogReporter {
|
|
|
346
432
|
#crashDirectory;
|
|
347
433
|
#restoring;
|
|
348
434
|
#savedDuringRestore = new Set();
|
|
435
|
+
#secrets;
|
|
436
|
+
#startupId;
|
|
437
|
+
#context;
|
|
438
|
+
#sandboxIdFromEnv;
|
|
349
439
|
|
|
350
|
-
constructor({ role = "cli", version = "unknown",
|
|
440
|
+
constructor({ role = "cli", version = "unknown", send = sendSlardarPcBatch, instanceId = randomUUID(), diagnosticId: supportId = diagnosticId(), platform = process.platform, osVersion = os.release(), crashDirectory, env = process.env } = {}) {
|
|
351
441
|
this.#send = send;
|
|
352
442
|
this.#crashDirectory = crashDirectory;
|
|
353
443
|
this.#role = token(role) ?? "cli";
|
|
354
|
-
this.#resourceContext = sandboxObservationContext(env, role);
|
|
355
444
|
this.#version = token(version) ?? "unknown";
|
|
356
445
|
this.#instanceId = instanceId;
|
|
357
446
|
this.#diagnosticId = supportId;
|
|
358
447
|
this.#platform = platform === "win32" ? "Windows" : platform === "darwin" ? "Mac OS X" : platform;
|
|
359
448
|
this.#osVersion = osVersion;
|
|
449
|
+
this.#secrets = runtimeLogSecrets(env);
|
|
450
|
+
this.#startupId = token(env.CODEM_STARTUP_ID) ?? randomUUID();
|
|
451
|
+
this.#sandboxIdFromEnv = token(env.CODEM_SANDBOX_ID) ?? token(env.CODEM_SANDBOX_DEVICE_ID);
|
|
452
|
+
this.#context = projectFields({ startup_id: this.#startupId, controller_id: env.CODEM_SANDBOX_CONTROLLER_ID ?? env.CONTROLLER_ID,
|
|
453
|
+
logical_sandbox_id: env.CODEM_SANDBOX_LOGICAL_SANDBOX_ID ?? env.LOGICAL_SANDBOX_ID, sandbox_id: this.#sandboxIdFromEnv,
|
|
454
|
+
dispatch_id: env.CODEM_DISPATCH_ID ?? env.CODEM_SANDBOX_DISPATCH_ID ?? env.DISPATCH_ID });
|
|
360
455
|
this.#timer = setInterval(() => { void this.flush(); }, INTERVAL_MS);
|
|
361
456
|
this.#timer.unref?.();
|
|
362
457
|
this.#restoring = this.#restoreCrashes().finally(() => { this.#savedDuringRestore = undefined; });
|
|
@@ -366,10 +461,18 @@ export class RuntimeLogReporter {
|
|
|
366
461
|
// Never await network IO in uncaughtExceptionMonitor. Replay is at-least-once.
|
|
367
462
|
// deliverNow also queues the record for this process's next flush. A
|
|
368
463
|
// successful send deletes its file; otherwise the next process replays it.
|
|
369
|
-
persistCrash(component, event, fields = {}, { deliverNow = false } = {}) {
|
|
464
|
+
persistCrash(component, event, fields = {}, { deliverNow = false, captureError = false } = {}) {
|
|
370
465
|
try {
|
|
371
466
|
if (this.#closed || (!this.#crashDirectory && !deliverNow)) return;
|
|
372
|
-
const entry = this.#logEntry("fatal", component, event, fields);
|
|
467
|
+
const entry = this.#logEntry("fatal", component, event, fields, captureError);
|
|
468
|
+
if (!captureError && this.acceptsApplicationLogs && fields.error instanceof Error) {
|
|
469
|
+
// Fatal monitor cannot wait for background work. Reuse its one existing
|
|
470
|
+
// crash write with a bounded, already-redacted text snapshot, no second
|
|
471
|
+
// file or network wait. Keep the original structured metric contract;
|
|
472
|
+
// attaching text must not add a second observation or counter.
|
|
473
|
+
entry.record.log_content = `${formatRuntimeLogText(captureRuntimeLogArguments([fields.error]), this.#secrets)}\n${entry.record.log_content}`;
|
|
474
|
+
}
|
|
475
|
+
entry.record.category.replay = "0";
|
|
373
476
|
this.#saveCrash(entry);
|
|
374
477
|
if (deliverNow) this.#replay.queue.push(entry);
|
|
375
478
|
} catch { /* Crash diagnostics must preserve the original exit behavior. */ }
|
|
@@ -379,12 +482,9 @@ export class RuntimeLogReporter {
|
|
|
379
482
|
if (!this.#crashDirectory) return;
|
|
380
483
|
try {
|
|
381
484
|
fs.mkdirSync(this.#crashDirectory, { recursive: true, mode: 0o700 });
|
|
382
|
-
const
|
|
383
|
-
|
|
384
|
-
const
|
|
385
|
-
const names = fs.readdirSync(this.#crashDirectory).filter(name => pattern.test(name));
|
|
386
|
-
if (names.length >= (migration ? 64 : 32)) return;
|
|
387
|
-
const name = `${prefix}${randomUUID()}.json`;
|
|
485
|
+
const names = fs.readdirSync(this.#crashDirectory).filter(name => /^js-[a-f0-9-]+\.json$/u.test(name));
|
|
486
|
+
if (names.length >= 32) return;
|
|
487
|
+
const name = `js-${randomUUID()}.json`;
|
|
388
488
|
const file = path.join(this.#crashDirectory, name);
|
|
389
489
|
fs.writeFileSync(file, JSON.stringify(entry), { flag: "wx", mode: 0o600 });
|
|
390
490
|
this.#savedDuringRestore?.add(name);
|
|
@@ -395,26 +495,34 @@ export class RuntimeLogReporter {
|
|
|
395
495
|
async #restoreCrashes() {
|
|
396
496
|
if (!this.#crashDirectory) return;
|
|
397
497
|
try {
|
|
398
|
-
const
|
|
399
|
-
const crashes = names.filter(name => /^js-[a-f0-9-]+\.json$/u.test(name)).slice(0, 32);
|
|
400
|
-
const migrations = names.filter(name => /^js-migration-[a-f0-9-]+\.json$/u.test(name)).slice(0, 64);
|
|
401
|
-
for (const name of [...crashes, ...migrations]) {
|
|
498
|
+
for (const name of (await fs.promises.readdir(this.#crashDirectory)).filter(name => /^js-[a-f0-9-]+\.json$/u.test(name)).slice(0, 32)) {
|
|
402
499
|
if (this.#closed) return;
|
|
403
500
|
if (this.#savedDuringRestore?.has(name)) continue;
|
|
404
501
|
const file = path.join(this.#crashDirectory, name);
|
|
405
502
|
try {
|
|
406
503
|
const stat = await fs.promises.lstat(file);
|
|
407
|
-
if (!stat.isFile()
|
|
408
|
-
const
|
|
409
|
-
if (
|
|
410
|
-
|
|
411
|
-
if (entry.record.log_type === "flexible" && entry.record.event_name?.startsWith("runtime.shared_migration.")) {
|
|
412
|
-
this.#replay.queue.push({ header: entry.header, record: entry.record, metricName: null, attempts: 0, crashFile: file });
|
|
504
|
+
if (!stat.isFile()) continue;
|
|
505
|
+
const stale = Date.now() - stat.mtimeMs > 5_000;
|
|
506
|
+
if (stat.size > 65536) {
|
|
507
|
+
if (stale) await fs.promises.unlink(file).catch(() => {});
|
|
413
508
|
continue;
|
|
414
509
|
}
|
|
415
|
-
|
|
416
|
-
|
|
510
|
+
const rawEntry = await fs.promises.readFile(file, "utf8");
|
|
511
|
+
let entry;
|
|
512
|
+
try { entry = JSON.parse(rawEntry); } catch {
|
|
513
|
+
if (stale) await fs.promises.unlink(file).catch(() => {});
|
|
514
|
+
continue;
|
|
515
|
+
}
|
|
516
|
+
if (entry?.record?.category?.reporter !== "codem_js" || entry?.record?.log_type !== "log" || !entry.header) {
|
|
517
|
+
if (stale) await fs.promises.unlink(file).catch(() => {});
|
|
518
|
+
continue;
|
|
519
|
+
}
|
|
520
|
+
if (entry.record.category.event?.startsWith("startup.")) entry.record.category.replay = "1";
|
|
521
|
+
if (this.#closed) return;
|
|
522
|
+
if (entry.metricName === LIFECYCLE_EVENT_NAME || entry.record.category.replay === "0") {
|
|
417
523
|
entry.record.category.replay = "1";
|
|
524
|
+
}
|
|
525
|
+
if (entry.metricName === LIFECYCLE_EVENT_NAME) {
|
|
418
526
|
this.#replay.queue.push({ ...entry, attempts: 0, crashFile: file });
|
|
419
527
|
} else {
|
|
420
528
|
this.#replay.queue.push({ header: entry.header, record: entry.record, metricName: entry.metricName,
|
|
@@ -429,7 +537,10 @@ export class RuntimeLogReporter {
|
|
|
429
537
|
// A sandbox may read the launcher profile for credentials. That profile is
|
|
430
538
|
// not the tenant/device owning the sandbox's runtime diagnostics.
|
|
431
539
|
if (this.#role === "sandbox") return;
|
|
432
|
-
try {
|
|
540
|
+
try {
|
|
541
|
+
this.#identity = runtimeLogIdentity(config);
|
|
542
|
+
this.#secrets = [...new Set([...this.#secrets, ...runtimeLogSecrets(optional(() => config?.auth?.oauth)), ...runtimeLogSecrets(optional(() => config?.device))])].slice(-128);
|
|
543
|
+
} catch { this.#identity = {}; }
|
|
433
544
|
}
|
|
434
545
|
|
|
435
546
|
observeSandboxConfig(config) {
|
|
@@ -439,63 +550,59 @@ export class RuntimeLogReporter {
|
|
|
439
550
|
tenantId: optional(() => token(config?.tenantId ?? config?.tenantKey)),
|
|
440
551
|
serverEnvironment: runtimeLogIdentity(config).serverEnvironment
|
|
441
552
|
};
|
|
553
|
+
this.#context = { ...this.#context, ...projectFields({ controller_id: config?.controllerId,
|
|
554
|
+
logical_sandbox_id: config?.logicalSandboxId, sandbox_id: config?.sandboxId ?? this.#sandboxIdFromEnv ?? optional(() => config?.deviceId), dispatch_id: config?.dispatchId }) };
|
|
555
|
+
this.#secrets = [...new Set([...this.#secrets, ...runtimeLogSecrets(config), ...runtimeLogSecrets(config?.auth?.oauth)])].slice(-128);
|
|
442
556
|
// ownerUserKey is not a Slardar UID. Keep user_id anonymous in this scope.
|
|
443
557
|
}
|
|
444
558
|
|
|
445
559
|
get pendingCount() { return this.#live.queue.length + this.#replay.queue.length; }
|
|
446
560
|
get droppedCount() { return this.#dropped; }
|
|
561
|
+
get identityKey() { return JSON.stringify([this.#instanceId, this.#role, this.#identity.deviceId, this.#identity.userId, this.#identity.tenantId]); }
|
|
562
|
+
get acceptsApplicationLogs() { return this.#role === "sandbox" || this.#role === "daemon"; }
|
|
447
563
|
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
return false;
|
|
460
|
-
}
|
|
461
|
-
const identity = this.#identity;
|
|
462
|
-
const record = {
|
|
463
|
-
app_version: this.#version, app_minor_version: "", build_id: "",
|
|
464
|
-
process_type: `codem-${this.#role}`, session_id: "", timestamp: Date.now(),
|
|
465
|
-
log_type: "flexible", event_name: name,
|
|
466
|
-
category: { reporter: "codem_js", runtime_role: this.#role,
|
|
467
|
-
...(identity.tenantId ? { tenant_id: identity.tenantId } : {}), ...category },
|
|
468
|
-
metrics
|
|
469
|
-
};
|
|
470
|
-
const entry = { header: this.#header(), record, metricName: null, attempts: 0 };
|
|
471
|
-
if (persist) this.#saveCrash(entry);
|
|
472
|
-
this.#live.queue.push(entry);
|
|
473
|
-
// Bursts need not wait for the periodic timer, and a slow collector still
|
|
474
|
-
// has only one bounded in-flight upload.
|
|
475
|
-
if (this.#live.queue.length >= BATCH_SIZE) void this.#flushLane(this.#live, REQUEST_TIMEOUT_MS);
|
|
476
|
-
return true;
|
|
564
|
+
recordPlainLog(level, component, args, fields = {}) {
|
|
565
|
+
try {
|
|
566
|
+
if (this.#closed || !this.acceptsApplicationLogs || !["log", "info", "warn", "error", "fatal"].includes(level)) return false;
|
|
567
|
+
const entry = this.#entry(level === "log" ? "info" : level, component, "application.log",
|
|
568
|
+
{ ...this.#context, observation_id: randomUUID(), ...projectFields(fields) }, this.#identity, {}, true);
|
|
569
|
+
// Format only when draining. Capture values without getters/object graphs.
|
|
570
|
+
entry.textArgs = captureRuntimeLogArguments(args);
|
|
571
|
+
entry.textSecrets = this.#secrets;
|
|
572
|
+
entry.metricName = null;
|
|
573
|
+
return this.#enqueue(entry);
|
|
574
|
+
} catch { this.#dropped += 1; return false; }
|
|
477
575
|
}
|
|
478
576
|
|
|
479
|
-
record(level, component, event, fields = {}) {
|
|
577
|
+
record(level, component, event, fields = {}, { captureError = false, persist = false } = {}) {
|
|
480
578
|
try {
|
|
481
579
|
if (this.#closed) return false;
|
|
482
|
-
|
|
580
|
+
const entry = this.#logEntry(level, component, event, fields, captureError);
|
|
581
|
+
if (persist) {
|
|
582
|
+
entry.record.category.replay = "0";
|
|
583
|
+
this.#saveCrash(entry);
|
|
584
|
+
}
|
|
585
|
+
return this.#enqueue(entry);
|
|
483
586
|
} catch { return false; }
|
|
484
587
|
}
|
|
485
588
|
|
|
486
|
-
#logEntry(level, component, event, fields) {
|
|
589
|
+
#logEntry(level, component, event, fields, captureError) {
|
|
590
|
+
const context = this.acceptsApplicationLogs ? this.#context : {};
|
|
487
591
|
let safeFields;
|
|
488
|
-
try { safeFields = projectFields(fields
|
|
489
|
-
if (
|
|
592
|
+
try { safeFields = { ...context, ...projectFields(fields) }; } catch { safeFields = { ...context }; }
|
|
593
|
+
if (captureError) {
|
|
594
|
+
const error = optional(() => diagnosticErrorDetail(fields.error));
|
|
595
|
+
if (error) safeFields.error = error;
|
|
596
|
+
}
|
|
597
|
+
const startup = event.startsWith("startup.");
|
|
598
|
+
if (OBSERVATION_EVENTS.has(event) || startup) safeFields.observation_id = randomUUID();
|
|
599
|
+
if (startup) safeFields.startup_id = this.#startupId;
|
|
490
600
|
const severity = ["info", "warn", "error", "fatal"].includes(level) ? level : "info";
|
|
491
601
|
// Keep arbitrary upstream error codes out of trusted-device metric dimensions.
|
|
492
602
|
const trustedDevice = TRUSTED_DEVICE_EVENTS.has(event);
|
|
493
603
|
const dimensions = trustedDevice ? {} : Object.fromEntries(["stage", "error_class", "error_code", "error_kind", "outcome"]
|
|
494
604
|
.filter(key => safeFields[key]).map(key => [key, safeFields[key]]));
|
|
495
|
-
if (
|
|
496
|
-
if (safeFields.lane) dimensions.lane = safeFields.lane;
|
|
497
|
-
if (safeFields.target_kind) dimensions.target_kind = safeFields.target_kind;
|
|
498
|
-
}
|
|
605
|
+
if (startup) dimensions.replay = "0";
|
|
499
606
|
if (OBSERVATION_EVENTS.has(event)) {
|
|
500
607
|
for (const [key, values] of Object.entries(trustedDevice ? TRUSTED_DEVICE_DIMENSIONS : OBSERVATION_DIMENSIONS)) {
|
|
501
608
|
if (safeFields[key]) dimensions[key] = values.includes(safeFields[key]) ? safeFields[key] : "unknown";
|
|
@@ -508,7 +615,7 @@ export class RuntimeLogReporter {
|
|
|
508
615
|
};
|
|
509
616
|
}
|
|
510
617
|
|
|
511
|
-
recordLifecycle(event, fields = {}, { persist = false } = {}) {
|
|
618
|
+
recordLifecycle(event, fields = {}, { persist = false, captureError = false } = {}) {
|
|
512
619
|
try {
|
|
513
620
|
if (this.#closed || !Object.hasOwn(LIFECYCLE_COMPONENTS, event)) return false;
|
|
514
621
|
const unstable = fields.stability === "unstable" || fields.outcome === "failed" || fields.outcome === "conflicting";
|
|
@@ -537,11 +644,15 @@ export class RuntimeLogReporter {
|
|
|
537
644
|
const { replay: _replay, ...logDimensions } = dimensions;
|
|
538
645
|
const summary = hasDetail ? lifecycleErrorSummary(dimensions, fields) : "";
|
|
539
646
|
const { reason: _reason, error_code: _errorCode, ...projected } = projectFields(fields, false);
|
|
647
|
+
const isStartup = event === "daemon_process_startup" || event === "daemon_first_heartbeat";
|
|
648
|
+
const errorDetail = hasDetail && (captureError || (isStartup && ["failed", "rejected"].includes(fields.outcome)))
|
|
649
|
+
? optional(() => diagnosticErrorDetail(fields.error)) : undefined;
|
|
540
650
|
const safeFields = {
|
|
541
|
-
...projected, ...logDimensions, ...metrics,
|
|
651
|
+
...(this.acceptsApplicationLogs ? this.#context : {}), ...projected, ...logDimensions, ...metrics,
|
|
542
652
|
process_instance_id: this.#instanceId,
|
|
543
|
-
...(
|
|
653
|
+
...(isStartup ? { startup_id: this.#instanceId } : {}),
|
|
544
654
|
observation_id: randomUUID(),
|
|
655
|
+
...(errorDetail ? { error: errorDetail } : {}),
|
|
545
656
|
...(summary ? { error_summary: summary } : {})
|
|
546
657
|
};
|
|
547
658
|
const extra = Object.fromEntries(LIFECYCLE_EXTRA_FIELDS
|
|
@@ -557,7 +668,6 @@ export class RuntimeLogReporter {
|
|
|
557
668
|
}
|
|
558
669
|
|
|
559
670
|
#entry(severity, component, event, safeFields, identity, dimensions, includeLog) {
|
|
560
|
-
safeFields = { ...this.#resourceContext, ...safeFields, ...(this.#resourceContext.resource_id ? { resource_id: this.#resourceContext.resource_id } : {}) };
|
|
561
671
|
const category = {
|
|
562
672
|
...workerRuntimeAttributes(),
|
|
563
673
|
client_kind: "cli", runtime_role: this.#role, reporter: "codem_js", log_schema: "1",
|
|
@@ -660,18 +770,43 @@ export class RuntimeLogReporter {
|
|
|
660
770
|
const controller = new AbortController();
|
|
661
771
|
lane.abort = controller;
|
|
662
772
|
let expire;
|
|
663
|
-
const
|
|
664
|
-
|
|
773
|
+
const expiresAt = performance.now() + timeoutMs;
|
|
774
|
+
let formattingMs = 0;
|
|
775
|
+
const deadline = new Promise(resolve => {
|
|
776
|
+
expire = setTimeout(() => { controller.abort(); resolve(); }, timeoutMs);
|
|
665
777
|
expire.unref?.();
|
|
666
778
|
});
|
|
667
779
|
try {
|
|
668
|
-
|
|
780
|
+
// Let flush install its deadline and give task callbacks a turn before
|
|
781
|
+
// processing text. Also yield after every bounded text record below.
|
|
782
|
+
await yieldToEventLoop();
|
|
783
|
+
while (lane.queue.length && !this.#closed && !controller.signal.aborted) {
|
|
669
784
|
const first = lane.queue[0];
|
|
670
785
|
const key = JSON.stringify(first.header);
|
|
671
786
|
const batch = [];
|
|
672
787
|
const data = [];
|
|
673
788
|
let bytes = 0;
|
|
674
|
-
while (batch.length < BATCH_SIZE && lane.queue.length && JSON.stringify(lane.queue[0].header) === key && Boolean(lane.queue[0].crashFile) === Boolean(first.crashFile)) {
|
|
789
|
+
while (batch.length < BATCH_SIZE && lane.queue.length && !this.#closed && !controller.signal.aborted && JSON.stringify(lane.queue[0].header) === key && Boolean(lane.queue[0].crashFile) === Boolean(first.crashFile)) {
|
|
790
|
+
const entry = lane.queue[0];
|
|
791
|
+
const hasText = Boolean(entry.textArgs);
|
|
792
|
+
if (entry.textArgs) {
|
|
793
|
+
if (formattingMs >= TEXT_FORMAT_BUDGET_MS || performance.now() >= expiresAt) {
|
|
794
|
+
lane.queue.shift();
|
|
795
|
+
this.#dropped += 1;
|
|
796
|
+
continue;
|
|
797
|
+
}
|
|
798
|
+
const started = performance.now();
|
|
799
|
+
const text = formatRuntimeLogText(entry.textArgs, entry.textSecrets);
|
|
800
|
+
formattingMs += performance.now() - started;
|
|
801
|
+
if (formattingMs >= TEXT_FORMAT_BUDGET_MS || performance.now() >= expiresAt) {
|
|
802
|
+
lane.queue.shift();
|
|
803
|
+
this.#dropped += 1;
|
|
804
|
+
continue;
|
|
805
|
+
}
|
|
806
|
+
entry.record.log_content = `${text}\n${entry.record.log_content}`;
|
|
807
|
+
delete entry.textArgs;
|
|
808
|
+
delete entry.textSecrets;
|
|
809
|
+
}
|
|
675
810
|
const { record, metrics, extra, metricName = "codem_runtime_diagnostic", includeLog = true } = lane.queue[0];
|
|
676
811
|
const records = includeLog ? [record] : [];
|
|
677
812
|
if (metricName) records.push({
|
|
@@ -685,9 +820,13 @@ export class RuntimeLogReporter {
|
|
|
685
820
|
bytes += entryBytes;
|
|
686
821
|
batch.push(lane.queue.shift());
|
|
687
822
|
data.push(...records);
|
|
823
|
+
if (hasText) await yieldToEventLoop();
|
|
688
824
|
}
|
|
825
|
+
if (this.#closed) return;
|
|
826
|
+
if (!batch.length) continue;
|
|
689
827
|
try {
|
|
690
828
|
await Promise.race([Promise.resolve().then(() => this.#send({ header: first.header, data }, { signal: controller.signal })), deadline]);
|
|
829
|
+
controller.signal.throwIfAborted();
|
|
691
830
|
for (const entry of batch) {
|
|
692
831
|
if (entry.crashFile) await fs.promises.unlink(entry.crashFile).catch(() => {});
|
|
693
832
|
}
|
|
@@ -726,11 +865,12 @@ let active;
|
|
|
726
865
|
export function runtimeLogsEnabled() { return Boolean(active); }
|
|
727
866
|
export function runtimeLogIdentityKey() { return active?.identityKey; }
|
|
728
867
|
|
|
868
|
+
/** @param {{role?: string, version?: string, env?: NodeJS.ProcessEnv, send?: Function}} options */
|
|
729
869
|
export function startRuntimeLogs({ role, version, env = process.env, send } = {}) {
|
|
730
870
|
try {
|
|
731
|
-
if (active ||
|
|
871
|
+
if (active || /^(1|true|yes)$/iu.test(env.CODEM_TELEMETRY_DISABLED ?? "") || env.NODE_TEST_CONTEXT || (process.env.NODE_TEST_CONTEXT && !send)) return;
|
|
732
872
|
const root = env.CODEM_HOME || env.LINCO_HOME || path.join(os.homedir(), ".codem");
|
|
733
|
-
active = new RuntimeLogReporter({ role, version,
|
|
873
|
+
active = new RuntimeLogReporter({ role, version, send, env, crashDirectory: path.join(root, "runtime-crashes") });
|
|
734
874
|
} catch { /* Monitoring initialization never prevents a command from running. */ }
|
|
735
875
|
}
|
|
736
876
|
|
|
@@ -742,8 +882,36 @@ export function observeRuntimeLogSandboxConfig(config) {
|
|
|
742
882
|
try { active?.observeSandboxConfig(config); } catch { /* best effort */ }
|
|
743
883
|
}
|
|
744
884
|
|
|
745
|
-
export function recordRuntimeLog(level, component, event, fields = {}) {
|
|
746
|
-
try { return active?.record(level, component, event, fields) ?? false; } catch { return false; }
|
|
885
|
+
export function recordRuntimeLog(level, component, event, fields = {}, options = {}) {
|
|
886
|
+
try { return active?.record(level, component, event, fields, options) ?? false; } catch { return false; }
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
export function recordRuntimeText(level, component, args, fields = {}) {
|
|
890
|
+
try { return active?.recordPlainLog(level, component, args, fields) ?? false; } catch { return false; }
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
// A process-local logger destination, never a mutation of global console or fds.
|
|
894
|
+
// Only application log calls enter it; debug and raw business protocols stay local.
|
|
895
|
+
export function createRuntimeLogger(base, component, context = {}) {
|
|
896
|
+
const logger = Object.create(base);
|
|
897
|
+
// Each task owns its context. Bind directly to the original local sink so
|
|
898
|
+
// concurrent task loggers neither share state nor upload the same call twice.
|
|
899
|
+
logger.withRuntimeLogContext = fields => createRuntimeLogger(base, component, { ...context, ...fields });
|
|
900
|
+
for (const level of ["log", "info", "warn", "error", "fatal", "debug"]) {
|
|
901
|
+
if (typeof base[level] !== "function") continue;
|
|
902
|
+
logger[level] = (...args) => {
|
|
903
|
+
const localOnly = typeof args[0] === "string" && (args[0].startsWith("sandbox error:") || args[0].startsWith("[codem][debug]"));
|
|
904
|
+
if (level !== "debug" && !localOnly) {
|
|
905
|
+
const outputError = args.find(isRuntimeOutputError);
|
|
906
|
+
// The local formatted prefix may already contain the child error text.
|
|
907
|
+
// Provenance, rather than text matching, decides to omit that copy too.
|
|
908
|
+
recordRuntimeText(level, component, outputError ? ["Runtime execution failed", outputError] : args,
|
|
909
|
+
{ ...context, ...(outputError ? { error: outputError } : {}) });
|
|
910
|
+
}
|
|
911
|
+
return base[level].call(base, ...args);
|
|
912
|
+
};
|
|
913
|
+
}
|
|
914
|
+
return logger;
|
|
747
915
|
}
|
|
748
916
|
|
|
749
917
|
// An explicit result or state observation. This never waits for the collector;
|
|
@@ -753,28 +921,34 @@ export function recordBridgeLifecycle(event, fields, options = {}) {
|
|
|
753
921
|
}
|
|
754
922
|
|
|
755
923
|
export function flushRuntimeLogsInBackground() {
|
|
756
|
-
|
|
757
|
-
}
|
|
758
|
-
|
|
759
|
-
export function recordRuntimeMetric(name, category, metrics, options) {
|
|
760
|
-
try { return active?.recordMetric(name, category, metrics, options) ?? false; } catch { return false; }
|
|
924
|
+
try {
|
|
925
|
+
if (active) setImmediate(() => { void active?.flush().catch(() => {}); }).unref?.();
|
|
926
|
+
} catch { /* best effort */ }
|
|
761
927
|
}
|
|
762
928
|
|
|
763
|
-
export function persistRuntimeCrash(component, event, fields) {
|
|
764
|
-
try { active?.persistCrash(component, event, fields); } catch { /* best effort */ }
|
|
929
|
+
export function persistRuntimeCrash(component, event, fields, options = {}) {
|
|
930
|
+
try { active?.persistCrash(component, event, fields, options); } catch { /* best effort */ }
|
|
765
931
|
}
|
|
766
932
|
|
|
767
933
|
// A failure that ends a short-lived process: persist first, then try to deliver
|
|
768
934
|
// within one upload budget, so an immediate exit cannot lose the count.
|
|
769
|
-
export function reportRuntimeFailure(component, event, fields = {}) {
|
|
770
|
-
try { active?.persistCrash(component, event, fields, { deliverNow: true }); } catch { /* best effort */ }
|
|
935
|
+
export function reportRuntimeFailure(component, event, fields = {}, options = {}) {
|
|
936
|
+
try { active?.persistCrash(component, event, fields, { captureError: Boolean(fields?.error), ...options, deliverNow: true }); } catch { /* best effort */ }
|
|
771
937
|
flushRuntimeLogsInBackground();
|
|
772
938
|
}
|
|
773
939
|
|
|
940
|
+
export function closeRuntimeLogs() {
|
|
941
|
+
try { active?.close(); active = undefined; } catch { /* best effort */ }
|
|
942
|
+
}
|
|
943
|
+
|
|
774
944
|
export async function flushRuntimeLogs(budgetMs = 200) {
|
|
775
945
|
if (!active) return;
|
|
776
946
|
let timeout;
|
|
777
947
|
try {
|
|
948
|
+
// Keep this explicit exit budget timer referenced: the upload socket and
|
|
949
|
+
// internal drain timers are unref'd, so unref'ing `timeout` too would let
|
|
950
|
+
// the process exit 0 while `main()` is still paused in `finally` before
|
|
951
|
+
// rethrowing a command/startup error.
|
|
778
952
|
await Promise.race([
|
|
779
953
|
active.flush({ timeoutMs: budgetMs }),
|
|
780
954
|
new Promise((resolve) => { timeout = setTimeout(resolve, budgetMs); })
|
|
@@ -816,12 +990,19 @@ export function recordInteractiveProcessExit({ exitCode, signal }) {
|
|
|
816
990
|
}
|
|
817
991
|
|
|
818
992
|
// Select events explicitly, then project fields again at the remote boundary.
|
|
819
|
-
export function recordSelectedRuntimeLog(component, event, fields = {}) {
|
|
993
|
+
export function recordSelectedRuntimeLog(component, event, fields = {}, { capturedError = undefined } = {}) {
|
|
820
994
|
try {
|
|
821
995
|
const selectedEvent = event.replace(/^linco\./u, "");
|
|
822
|
-
if (!/^(?:startup\.(?:main|update_check|daemon_service_reconcile|login_gate|login_handoff_to_linco)|oauth\.refresh\.(?:relogin_suspect|persist_failed|persisted)|managed_config\.(?:member_refresh_failed|sandbox_refresh_failed|sandbox_fetch_recovered|sandbox_fetch_exhausted|refreshed|resource_failed)|
|
|
996
|
+
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;
|
|
823
997
|
const expected = optional(() => fields?.errorKind === "user_stop" || fields?.terminalError?.kind === "user_stop" || fields?.exitCode === 130 || fields?.signal === "SIGINT");
|
|
824
|
-
const level = expected ? "info"
|
|
825
|
-
|
|
998
|
+
const level = expected ? "info"
|
|
999
|
+
: (fields?.status === "failed" || (selectedEvent === "authentication_snapshot.router_unavailable" && fields?.reason === "storage") || /(?:failed|error|exhausted|timeout)$/u.test(event)) ? "error"
|
|
1000
|
+
: /(?:suspect|dropped|missing|oversize|unavailable)$/u.test(event) ? "warn"
|
|
1001
|
+
: "info";
|
|
1002
|
+
const captureError = capturedError !== undefined;
|
|
1003
|
+
const persist = selectedEvent === "router.credentials.refresh_failed"
|
|
1004
|
+
|| (selectedEvent === "authentication_snapshot.router_unavailable" && fields?.reason === "storage");
|
|
1005
|
+
recordRuntimeLog(level, component, event, captureError ? { ...fields, error: capturedError } : fields, { captureError, persist });
|
|
1006
|
+
if (persist) flushRuntimeLogsInBackground();
|
|
826
1007
|
} catch { /* best effort */ }
|
|
827
1008
|
}
|