@lark-codem/codem-cli 0.1.272-web-trusted-device-access.100103781761.0.gc527772 → 0.1.272
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.js +13 -0
- package/bin/linco-paths.js +45 -0
- package/bin/process-tree.js +217 -0
- package/bin/tt-env.js +171 -0
- package/bin/worker-runtime-telemetry.js +75 -0
- package/bin/worker-runtime.js +345 -0
- package/package.json +11 -6
- package/profile/credential-errors.js +4 -1
- package/profile/runtime-logs.js +319 -95
- package/profile/slardar-pc-transport.js +7 -3
- package/profile/worker-runtime-observation.js +10 -0
package/profile/runtime-logs.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { workerRuntimeAttributes } from "./worker-runtime-observation.js";
|
|
1
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
3
|
import os from "node:os";
|
|
3
4
|
import fs from "node:fs";
|
|
@@ -10,32 +11,94 @@ const CAPACITY = 256;
|
|
|
10
11
|
const BATCH_SIZE = 32;
|
|
11
12
|
const INTERVAL_MS = 10_000;
|
|
12
13
|
const REQUEST_TIMEOUT_MS = 3_000;
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
const MAX_BATCH_BYTES = 256 * 1024;
|
|
15
|
+
const LIFECYCLE_EVENT_NAME = "codem_bridge_lifecycle";
|
|
16
|
+
const LIFECYCLE_COMPONENTS = {
|
|
17
|
+
daemon_startup: "daemon", runtime_sync: "runtime-post", command_handoff: "bridge",
|
|
18
|
+
runner_operation: "bridge", delivery_settled: "runtime-post", runtime_state: "bridge",
|
|
19
|
+
event_discarded: "runtime-post", process_lifecycle: "linco"
|
|
20
|
+
};
|
|
21
|
+
const LIFECYCLE_METRICS = [
|
|
22
|
+
"duration_ms", "ack_settle_duration_ms", "startup_wait_ms", "operation_age_ms",
|
|
23
|
+
"outage_duration_ms", "consecutive_failures", "deferred_age_ms", "pending_command_ack_count",
|
|
24
|
+
"pending_ack_age_ms", "pending_event_count", "oldest_event_age_ms", "lifetime_ms"
|
|
16
25
|
];
|
|
17
|
-
const
|
|
18
|
-
["
|
|
19
|
-
["
|
|
20
|
-
["
|
|
21
|
-
]
|
|
26
|
+
const LIFECYCLE_DIMENSIONS = {
|
|
27
|
+
outcome: ["success", "failed", "rejected", "canceled", "unknown", "accepted", "duplicate", "conflicting", "observed", "recovered"],
|
|
28
|
+
operation: ["prepare", "spawn", "ready", "cancel", "shutdown"],
|
|
29
|
+
scope: ["startup", "runner", "sync", "command", "queue"],
|
|
30
|
+
kind: ["command_ack", "runtime_event", "control", "events", "relay", "offline"],
|
|
31
|
+
phase: ["startup_marker", "prelude", "healthcheck", "config_load", "update_check", "service_reconcile", "login_gate", "launch", "authentication", "singleton", "initialize", "start_client", "first_sync", "trusted_device",
|
|
32
|
+
"build_request", "request", "validate_response", "apply_response", "persist_state",
|
|
33
|
+
"admission", "handler", "resolve_binary", "build_env", "host_capabilities", "parse_capabilities",
|
|
34
|
+
"strict_resume", "verify_binding", "prepare", "spawn", "ready", "cancel", "teardown"],
|
|
35
|
+
reason: ["overflow", "oversized", "timeout", "cleanup_failed", "unsupported_command", "invalid_payload",
|
|
36
|
+
"shutting_down_handoff", "handoff_target_not_active", "handler_inflight", "duplicate_inflight",
|
|
37
|
+
"runtime_unavailable", "runtime_environment_failed", "capability_probe_failed", "runtime_binary_changed",
|
|
38
|
+
"strict_resume_unsupported", "turn_context_unsupported", "active_run_protocol_mismatch", "trusted_device_blocked",
|
|
39
|
+
"invalid_runtime_event", "event_rejected", "task_terminated:canceled", "task_terminated:failed", "task_terminated:succeeded"],
|
|
40
|
+
error_source: ["bridge", "base", "linco", "transport"],
|
|
41
|
+
stability: ["stable", "unstable", "unknown"],
|
|
42
|
+
action: ["exit", "restart"],
|
|
43
|
+
expected: ["true", "false", "unknown"],
|
|
44
|
+
critical: ["true", "false"]
|
|
45
|
+
};
|
|
46
|
+
const TRUSTED_DEVICE_EVENTS = new Set(["host_identity_collection", "host_identity_command", "host_session_attempt", "host_session_expired", "trusted_device_admission_blocked", "trusted_device_admission_recovered"]);
|
|
47
|
+
const TRUSTED_DEVICE_PHASES = ["auth", "identity", "provider", "host_key", "activation_state", "activation_apply", "activation_sign", "activation_complete", "credential_resolve", "session_apply", "session_sign", "session_complete", "trusted_device"];
|
|
48
|
+
const TRUSTED_DEVICE_DIMENSIONS = {
|
|
49
|
+
phase: TRUSTED_DEVICE_PHASES,
|
|
50
|
+
operation: ["create", "renew", "recovery", "platform_identity", "network_interfaces", "network_ports", "serial_number", "platform_uuid", "network_adapters"],
|
|
51
|
+
outcome: ["success", "partial", "failed", "ready", "not_registered", "no_auth", "reset", "blocked", "invalid", "verified", "not_required", "absent", "expired"],
|
|
52
|
+
failure_kind: ["none", "timeout", "exec_failed", "invalid_json", "empty_identity", "read_failed", "authorization", "unknown"]
|
|
53
|
+
};
|
|
54
|
+
const OBSERVATION_EVENTS = new Set(["command_delivery_observed", "command_admission", "runtime_capability_probe", "command_ack", "command_observation_closed", "diagnostic_reporter_health", ...TRUSTED_DEVICE_EVENTS]);
|
|
55
|
+
const OBSERVATION_DIMENSIONS = {
|
|
56
|
+
phase: ["resolve_binary", "build_env", "host_capabilities", "parse_capabilities", "strict_resume", "verify_binding", "prepare", "persist_state", "trusted_device", "request", "validate_response", "apply_response"],
|
|
57
|
+
reason: ["runtime_unavailable", "runtime_environment_failed", "capability_probe_failed", "runtime_binary_changed", "strict_resume_unsupported", "turn_context_unsupported", "active_run_protocol_mismatch", "trusted_device_blocked", "shutting_down_handoff", "handoff_target_not_active", "duplicate_inflight", "handler_inflight", "prepare_exception_unknown", "capacity", "stopped", "replaced", "scope_changed", "queue_removed", "local_rejected"],
|
|
58
|
+
command_type: ["agent.run", "agent.steer", "agent.stop", "task.assign", "task.stop", "artifact.relay.read", "artifact.convert_to_lark_resource", "artifact.download", "directory.list", "git.preview", "workflow.preview"],
|
|
59
|
+
actor_type: ["device", "sandbox"],
|
|
60
|
+
ack_status: ["accepted", "ignored_duplicate", "rejected"],
|
|
61
|
+
ack_outcome: ["accepted", "duplicate", "rejected", "conflicting"],
|
|
62
|
+
readback_scope: ["command", "delivery", "unmatched"],
|
|
63
|
+
timing_origin: ["observed", "restored_unknown"]
|
|
64
|
+
};
|
|
65
|
+
const OBSERVATION_METRICS = {
|
|
66
|
+
host_identity_collection: ["duration_ms", "field_error_count"],
|
|
67
|
+
host_identity_command: ["duration_ms", "timeout_ms"],
|
|
68
|
+
host_session_attempt: ["elapsed_ms", "next_retry_ms", "consecutive_failures", "session_remaining_ms", ...TRUSTED_DEVICE_PHASES.map(phase => `${phase}_duration_ms`)],
|
|
69
|
+
host_session_expired: ["expired_for_ms", "consecutive_failures", "next_retry_ms"],
|
|
70
|
+
trusted_device_admission_blocked: ["elapsed_ms", "blocked_response_count"],
|
|
71
|
+
trusted_device_admission_recovered: ["elapsed_ms", "blocked_response_count"],
|
|
72
|
+
command_delivery_observed: ["attempt_delta", "suppressed_count"],
|
|
73
|
+
command_admission: ["attempt_delta", "suppressed_count", "deferred_age_ms", "deferred_duration_ms"],
|
|
74
|
+
runtime_capability_probe: ["probe_duration_ms"],
|
|
75
|
+
command_ack: ["attempt_delta", "suppressed_count", "ack_queue_wait_ms", "ack_settle_duration_ms", "pending_ack_age_ms", "pending_command_ack_count", "pending_ack_unknown_age_count"],
|
|
76
|
+
command_observation_closed: ["omitted_detail_count", "pending_command_ack_count", "deferred_count"],
|
|
77
|
+
diagnostic_reporter_health: ["dropped_delta", "upload_failure_delta", "pending_event_count"]
|
|
78
|
+
};
|
|
79
|
+
const EXTRA_FIELDS = ["observation_id", "runtime_client_instance_id", "command_id", "delivery_id", "probe_id", "sync_id", "transport_request_id", "attempt_id"];
|
|
80
|
+
const LIFECYCLE_EXTRA_FIELDS = [...EXTRA_FIELDS, "process_instance_id", "startup_id", "request_id", "event_id"];
|
|
22
81
|
const STRING_FIELDS = new Set([
|
|
82
|
+
...EXTRA_FIELDS, "command_type", "ack_status", "ack_outcome", "readback_scope", "timing_origin", "required_capability",
|
|
23
83
|
"request_id", "command_id", "session_id", "task_id", "dispatch_id", "event_id", "sync_id",
|
|
24
|
-
"lane", "target_kind", "frontier_did", "packet_kind", "packet_traceparent",
|
|
25
84
|
"process_instance_id", "run_id", "stage", "phase", "status", "outcome", "reason", "action",
|
|
26
85
|
"error_class", "error_code", "error_kind", "error_type", "code", "signal", "stop_reason",
|
|
86
|
+
"first_error", "retry_source", "cleanup_result",
|
|
27
87
|
"terminal_event", "event_type", "actor_type", "source", "trigger", "hook_id", "hook_event",
|
|
28
88
|
"target_version", "cli_version", "core_version", "version", "previous_state", "state",
|
|
29
|
-
"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"
|
|
89
|
+
"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",
|
|
90
|
+
"operation_id", "entrypoint"
|
|
30
91
|
]);
|
|
31
92
|
const VALUE_FIELDS = new Set([
|
|
93
|
+
"session_retained",
|
|
94
|
+
...new Set(Object.values(OBSERVATION_METRICS).flat()),
|
|
32
95
|
"pid", "exit_code", "duration_ms", "elapsed_ms", "wait_ms", "run_ms", "total_ms", "took_ms",
|
|
33
|
-
"attempt", "attempts", "attempt_count", "retryable", "http_status", "active_task_count",
|
|
96
|
+
"attempt", "attempts", "attempt_count", "retryable", "http_status", "errno", "active_task_count",
|
|
34
97
|
"pending_event_count", "pending_command_ack_count", "next_retry_ms", "consecutive_failures",
|
|
35
|
-
...Array.from(UPLINK_DIAGNOSTIC_METRICS.values()).flat(), "transport_open",
|
|
36
98
|
"outage_duration_ms", "startup_duration_ms", "failed_attempts", "active_runs", "completed",
|
|
37
99
|
"delivered", "result_delivered", "queued_behind_existing", "expected", "timed_out",
|
|
38
|
-
"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", "before", "after", "omitted_detail_count", "opened", "selected", "foreground"
|
|
100
|
+
"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",
|
|
101
|
+
...LIFECYCLE_METRICS
|
|
39
102
|
]);
|
|
40
103
|
|
|
41
104
|
function token(value) {
|
|
@@ -51,20 +114,31 @@ function optional(read) {
|
|
|
51
114
|
try { return read(); } catch { return undefined; }
|
|
52
115
|
}
|
|
53
116
|
|
|
54
|
-
function
|
|
117
|
+
function metricProjection(event, fields = {}) {
|
|
118
|
+
return { count: 1, ...Object.fromEntries((OBSERVATION_METRICS[event] ?? [])
|
|
119
|
+
.filter(key => typeof fields?.[key] === "number" && Number.isFinite(fields[key]) && fields[key] >= 0)
|
|
120
|
+
.map(key => [key, fields[key]])) };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function extraProjection(fields = {}) {
|
|
124
|
+
return Object.fromEntries(EXTRA_FIELDS.filter(key => token(fields?.[key])).map(key => [key, token(fields[key])]));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function projectFields(input, fingerprintErrors = true) {
|
|
55
128
|
const result = {};
|
|
56
129
|
for (const [key, value] of Object.entries(input ?? {}).slice(0, 100)) {
|
|
57
130
|
const name = fieldName(key);
|
|
58
|
-
if (
|
|
59
|
-
result[name] = value;
|
|
60
|
-
} else if (STRING_FIELDS.has(name)) {
|
|
131
|
+
if (STRING_FIELDS.has(name)) {
|
|
61
132
|
const safe = token(value);
|
|
62
133
|
if (safe) result[name] = safe;
|
|
63
134
|
} else if (VALUE_FIELDS.has(name) && (typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value)))) {
|
|
64
135
|
result[name] = value;
|
|
65
136
|
}
|
|
66
137
|
}
|
|
138
|
+
if (!fingerprintErrors) return result;
|
|
67
139
|
const error = input?.error ?? input?.terminalError;
|
|
140
|
+
const fingerprint = input?.error_fingerprint ?? input?.errorFingerprint;
|
|
141
|
+
if (typeof fingerprint === "string" && /^[a-f0-9]{24}$/u.test(fingerprint)) result.error_fingerprint = fingerprint;
|
|
68
142
|
const terminal = input?.terminalError ?? error?.terminalError;
|
|
69
143
|
if (terminal && typeof terminal === "object") {
|
|
70
144
|
if (token(terminal.code)) result.error_code = token(terminal.code);
|
|
@@ -84,6 +158,36 @@ function projectFields(input) {
|
|
|
84
158
|
return result;
|
|
85
159
|
}
|
|
86
160
|
|
|
161
|
+
// Build the display summary from classified fields. Keep free-form text at
|
|
162
|
+
// its source so collecting telemetry never scans upstream or local messages.
|
|
163
|
+
function lifecycleErrorSummary(dimensions, fields) {
|
|
164
|
+
return [
|
|
165
|
+
dimensions.phase ?? dimensions.operation ?? dimensions.scope,
|
|
166
|
+
dimensions.error_source,
|
|
167
|
+
dimensions.error_code,
|
|
168
|
+
dimensions.reason !== dimensions.error_code ? dimensions.reason : undefined,
|
|
169
|
+
Number.isSafeInteger(fields.errno) && fields.errno !== 0 ? `errno=${fields.errno}` : undefined,
|
|
170
|
+
Number.isSafeInteger(fields.exit_code) ? `exit_code=${fields.exit_code}` : undefined
|
|
171
|
+
].filter(Boolean).join(" · ");
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function lifecycleErrorCode(fields) {
|
|
175
|
+
const code = token(fields.error_code ?? fields.error?.code ?? fields.error?.cause?.code)?.toLowerCase();
|
|
176
|
+
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;
|
|
177
|
+
const status = Number(fields.http_status);
|
|
178
|
+
if (Number.isInteger(status) && status >= 100 && status <= 599) return `http_${status}`;
|
|
179
|
+
return fields.outcome === "failed" || fields.outcome === "rejected" || fields.outcome === "conflicting" ? "unknown" : undefined;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function keepLegacyMetric(event, fields, role, severity) {
|
|
183
|
+
if (/^startup\.(?:main|update_check|daemon_service_reconcile|login_gate|login_handoff_to_linco)$/u.test(event) && severity === "info") return false;
|
|
184
|
+
if (/(?:^|\.)drain_(?:started|completed)$/u.test(event) && severity === "info") return false;
|
|
185
|
+
if (role === "daemon" && event === "runtime_capability_probe" && severity === "info") return false;
|
|
186
|
+
if (role === "daemon" && ["sync_ready", "sync_failed", "sync_recovered", "shutdown_completed"].includes(event)) return false;
|
|
187
|
+
if (event === "command_ack" && ["settled", "pending"].includes(fields.stage)) return false;
|
|
188
|
+
return true;
|
|
189
|
+
}
|
|
190
|
+
|
|
87
191
|
export function runtimeLogIdentity(config) {
|
|
88
192
|
const oauth = optional(() => config?.auth?.oauth);
|
|
89
193
|
return {
|
|
@@ -96,6 +200,15 @@ export function runtimeLogIdentity(config) {
|
|
|
96
200
|
};
|
|
97
201
|
}
|
|
98
202
|
|
|
203
|
+
// Prefer an operation's attribution over the identity of its eventual sender.
|
|
204
|
+
export function runtimeObservationTenant(value) {
|
|
205
|
+
return optional(() => {
|
|
206
|
+
const payload = value?.payload ?? value;
|
|
207
|
+
const context = payload?.telemetryContext ?? payload?.telemetry_context;
|
|
208
|
+
return token(context?.tenantId ?? context?.tenant_id ?? payload?.tenantId ?? payload?.tenant_id ?? value?.tenantId ?? value?.tenant_id);
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
99
212
|
export class RuntimeLogReporter {
|
|
100
213
|
#live = { queue: [], inflight: undefined, abort: undefined };
|
|
101
214
|
#replay = { queue: [], inflight: undefined, abort: undefined };
|
|
@@ -103,6 +216,10 @@ export class RuntimeLogReporter {
|
|
|
103
216
|
#timer;
|
|
104
217
|
#closed = false;
|
|
105
218
|
#dropped = 0;
|
|
219
|
+
#uploadFailures = 0;
|
|
220
|
+
#reportedDrops = 0;
|
|
221
|
+
#reportedFailures = 0;
|
|
222
|
+
#lastHealthAt = Date.now();
|
|
106
223
|
#send;
|
|
107
224
|
#role;
|
|
108
225
|
#version;
|
|
@@ -111,6 +228,8 @@ export class RuntimeLogReporter {
|
|
|
111
228
|
#platform;
|
|
112
229
|
#osVersion;
|
|
113
230
|
#crashDirectory;
|
|
231
|
+
#restoring;
|
|
232
|
+
#savedDuringRestore = new Set();
|
|
114
233
|
|
|
115
234
|
constructor({ role = "cli", version = "unknown", send = sendSlardarPcBatch, instanceId = randomUUID(), diagnosticId: supportId = diagnosticId(), platform = process.platform, osVersion = os.release(), crashDirectory } = {}) {
|
|
116
235
|
this.#send = send;
|
|
@@ -123,7 +242,7 @@ export class RuntimeLogReporter {
|
|
|
123
242
|
this.#osVersion = osVersion;
|
|
124
243
|
this.#timer = setInterval(() => { void this.flush(); }, INTERVAL_MS);
|
|
125
244
|
this.#timer.unref?.();
|
|
126
|
-
this.#restoreCrashes();
|
|
245
|
+
this.#restoring = this.#restoreCrashes().finally(() => { this.#savedDuringRestore = undefined; });
|
|
127
246
|
}
|
|
128
247
|
|
|
129
248
|
// Crash files hold already-projected records and the identity at failure time.
|
|
@@ -131,33 +250,48 @@ export class RuntimeLogReporter {
|
|
|
131
250
|
// deliverNow also queues the record for this process's next flush. A
|
|
132
251
|
// successful send deletes its file; otherwise the next process replays it.
|
|
133
252
|
persistCrash(component, event, fields = {}, { deliverNow = false } = {}) {
|
|
134
|
-
let entry;
|
|
135
|
-
let crashFile;
|
|
136
253
|
try {
|
|
137
254
|
if (this.#closed || (!this.#crashDirectory && !deliverNow)) return;
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
if (
|
|
255
|
+
const entry = this.#logEntry("fatal", component, event, fields);
|
|
256
|
+
this.#saveCrash(entry);
|
|
257
|
+
if (deliverNow) this.#replay.queue.push(entry);
|
|
258
|
+
} catch { /* Crash diagnostics must preserve the original exit behavior. */ }
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
#saveCrash(entry) {
|
|
262
|
+
if (!this.#crashDirectory) return;
|
|
263
|
+
try {
|
|
141
264
|
fs.mkdirSync(this.#crashDirectory, { recursive: true, mode: 0o700 });
|
|
142
265
|
const names = fs.readdirSync(this.#crashDirectory).filter(name => /^js-[a-f0-9-]+\.json$/u.test(name));
|
|
143
266
|
if (names.length >= 32) return;
|
|
144
|
-
const
|
|
267
|
+
const name = `js-${randomUUID()}.json`;
|
|
268
|
+
const file = path.join(this.#crashDirectory, name);
|
|
145
269
|
fs.writeFileSync(file, JSON.stringify(entry), { flag: "wx", mode: 0o600 });
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
}
|
|
270
|
+
this.#savedDuringRestore?.add(name);
|
|
271
|
+
entry.crashFile = file;
|
|
272
|
+
} catch { /* Local storage can be full or unavailable. */ }
|
|
150
273
|
}
|
|
151
274
|
|
|
152
|
-
#restoreCrashes() {
|
|
275
|
+
async #restoreCrashes() {
|
|
276
|
+
if (!this.#crashDirectory) return;
|
|
153
277
|
try {
|
|
154
|
-
for (const name of fs.
|
|
278
|
+
for (const name of (await fs.promises.readdir(this.#crashDirectory)).filter(name => /^js-[a-f0-9-]+\.json$/u.test(name)).slice(0, 32)) {
|
|
279
|
+
if (this.#closed) return;
|
|
280
|
+
if (this.#savedDuringRestore?.has(name)) continue;
|
|
155
281
|
const file = path.join(this.#crashDirectory, name);
|
|
156
282
|
try {
|
|
157
|
-
|
|
158
|
-
|
|
283
|
+
const stat = await fs.promises.lstat(file);
|
|
284
|
+
if (!stat.isFile() || stat.size > 65536) continue;
|
|
285
|
+
const entry = JSON.parse(await fs.promises.readFile(file, "utf8"));
|
|
159
286
|
if (entry?.record?.category?.reporter !== "codem_js" || entry?.record?.log_type !== "log" || !entry.header) continue;
|
|
160
|
-
this.#
|
|
287
|
+
if (this.#closed) return;
|
|
288
|
+
if (entry.metricName === LIFECYCLE_EVENT_NAME) {
|
|
289
|
+
entry.record.category.replay = "1";
|
|
290
|
+
this.#replay.queue.push({ ...entry, attempts: 0, crashFile: file });
|
|
291
|
+
} else {
|
|
292
|
+
this.#replay.queue.push({ header: entry.header, record: entry.record, metricName: entry.metricName,
|
|
293
|
+
metrics: metricProjection(entry.record.category.event, entry.metrics), extra: extraProjection(entry.extra), attempts: 0, crashFile: file });
|
|
294
|
+
}
|
|
161
295
|
} catch { /* A partial crash write cannot prevent startup. */ }
|
|
162
296
|
}
|
|
163
297
|
} catch { /* First startup or unavailable storage. */ }
|
|
@@ -182,84 +316,153 @@ export class RuntimeLogReporter {
|
|
|
182
316
|
|
|
183
317
|
get pendingCount() { return this.#live.queue.length + this.#replay.queue.length; }
|
|
184
318
|
get droppedCount() { return this.#dropped; }
|
|
319
|
+
get identityKey() { return JSON.stringify([this.#instanceId, this.#role, this.#identity.deviceId, this.#identity.userId, this.#identity.tenantId]); }
|
|
185
320
|
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
321
|
+
record(level, component, event, fields = {}) {
|
|
322
|
+
try {
|
|
323
|
+
if (this.#closed) return false;
|
|
324
|
+
return this.#enqueue(this.#logEntry(level, component, event, fields));
|
|
325
|
+
} catch { return false; }
|
|
191
326
|
}
|
|
192
327
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
328
|
+
#logEntry(level, component, event, fields) {
|
|
329
|
+
let safeFields;
|
|
330
|
+
try { safeFields = projectFields(fields); } catch { safeFields = {}; }
|
|
331
|
+
if (OBSERVATION_EVENTS.has(event)) safeFields.observation_id = randomUUID();
|
|
332
|
+
const severity = ["info", "warn", "error", "fatal"].includes(level) ? level : "info";
|
|
333
|
+
// Keep arbitrary upstream error codes out of trusted-device metric dimensions.
|
|
334
|
+
const trustedDevice = TRUSTED_DEVICE_EVENTS.has(event);
|
|
335
|
+
const dimensions = trustedDevice ? {} : Object.fromEntries(["stage", "error_class", "error_code", "error_kind", "outcome"]
|
|
336
|
+
.filter(key => safeFields[key]).map(key => [key, safeFields[key]]));
|
|
337
|
+
if (OBSERVATION_EVENTS.has(event)) {
|
|
338
|
+
for (const [key, values] of Object.entries(trustedDevice ? TRUSTED_DEVICE_DIMENSIONS : OBSERVATION_DIMENSIONS)) {
|
|
339
|
+
if (safeFields[key]) dimensions[key] = values.includes(safeFields[key]) ? safeFields[key] : "unknown";
|
|
340
|
+
}
|
|
198
341
|
}
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
log_type: "flexible", event_name: name,
|
|
204
|
-
category: { reporter: "codem_js", runtime_role: this.#role,
|
|
205
|
-
...(identity.tenantId ? { tenant_id: identity.tenantId } : {}), ...category },
|
|
206
|
-
metrics
|
|
342
|
+
return {
|
|
343
|
+
...this.#entry(severity, component, event, safeFields, this.#identity, dimensions, true),
|
|
344
|
+
metricName: keepLegacyMetric(event, safeFields, this.#role, severity) ? "codem_runtime_diagnostic" : null,
|
|
345
|
+
metrics: metricProjection(event, safeFields), extra: extraProjection(safeFields)
|
|
207
346
|
};
|
|
208
|
-
this.#live.queue.push({ header: this.#header(), record, attempts: 0 });
|
|
209
|
-
// Bursts need not wait for the periodic timer, and a slow collector still
|
|
210
|
-
// has only one bounded in-flight upload.
|
|
211
|
-
if (this.#live.queue.length >= BATCH_SIZE) void this.#flushLane(this.#live, REQUEST_TIMEOUT_MS);
|
|
212
|
-
return true;
|
|
213
347
|
}
|
|
214
348
|
|
|
215
|
-
|
|
349
|
+
recordLifecycle(event, fields = {}, { persist = false } = {}) {
|
|
216
350
|
try {
|
|
217
|
-
if (this.#closed) return false;
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
const severity =
|
|
221
|
-
const
|
|
222
|
-
|
|
351
|
+
if (this.#closed || !Object.hasOwn(LIFECYCLE_COMPONENTS, event)) return false;
|
|
352
|
+
const unstable = fields.stability === "unstable" || fields.outcome === "failed" || fields.outcome === "conflicting";
|
|
353
|
+
const hasDetail = fields.detail ?? (persist || unstable || fields.outcome === "rejected" || fields.outcome === "unknown");
|
|
354
|
+
const severity = persist ? "fatal" : unstable ? "error" : "info";
|
|
355
|
+
const dimensions = {
|
|
356
|
+
stability: unstable ? "unstable" : fields.outcome === "unknown" ? "unknown" : "stable",
|
|
357
|
+
has_detail: hasDetail ? "1" : "0", replay: "0"
|
|
358
|
+
};
|
|
359
|
+
for (const [key, values] of Object.entries(LIFECYCLE_DIMENSIONS)) {
|
|
360
|
+
if (fields[key] != null && values.includes(String(fields[key]))) dimensions[key] = String(fields[key]);
|
|
361
|
+
}
|
|
362
|
+
const errorCode = lifecycleErrorCode(fields);
|
|
363
|
+
if (errorCode) dimensions.error_code = errorCode;
|
|
364
|
+
if (fields.command_type) dimensions.command_type = OBSERVATION_DIMENSIONS.command_type.includes(fields.command_type) ? fields.command_type : "other";
|
|
365
|
+
const metrics = Object.fromEntries(LIFECYCLE_METRICS
|
|
366
|
+
.filter(key => typeof fields[key] === "number" && Number.isFinite(fields[key]) && fields[key] >= 0)
|
|
367
|
+
.map(key => [key, Math.round(fields[key])]));
|
|
368
|
+
if (event !== "runtime_state") {
|
|
369
|
+
metrics.count = event === "delivery_settled" && Number.isSafeInteger(fields.count) && fields.count > 0 ? fields.count : 1;
|
|
370
|
+
}
|
|
371
|
+
const identity = {
|
|
372
|
+
...this.#identity,
|
|
373
|
+
...(Object.hasOwn(fields, "tenantId") ? { tenantId: token(fields.tenantId) } : {})
|
|
374
|
+
};
|
|
375
|
+
const { replay: _replay, ...logDimensions } = dimensions;
|
|
376
|
+
const summary = hasDetail ? lifecycleErrorSummary(dimensions, fields) : "";
|
|
377
|
+
const { reason: _reason, error_code: _errorCode, ...projected } = projectFields(fields, false);
|
|
378
|
+
const safeFields = {
|
|
379
|
+
...projected, ...logDimensions, ...metrics,
|
|
380
|
+
process_instance_id: this.#instanceId,
|
|
381
|
+
...(event === "daemon_startup" ? { startup_id: this.#instanceId } : {}),
|
|
382
|
+
observation_id: randomUUID(),
|
|
383
|
+
...(summary ? { error_summary: summary } : {})
|
|
384
|
+
};
|
|
385
|
+
const extra = Object.fromEntries(LIFECYCLE_EXTRA_FIELDS
|
|
386
|
+
.filter(key => token(safeFields[key])).map(key => [key, safeFields[key]]));
|
|
387
|
+
if (summary) extra.error_summary = summary;
|
|
388
|
+
const entry = {
|
|
389
|
+
...this.#entry(severity, LIFECYCLE_COMPONENTS[event], event, safeFields, identity, dimensions, hasDetail),
|
|
390
|
+
metricName: LIFECYCLE_EVENT_NAME, metrics, extra
|
|
391
|
+
};
|
|
392
|
+
if (persist && hasDetail) this.#saveCrash(entry);
|
|
393
|
+
return this.#enqueue(entry);
|
|
394
|
+
} catch { return false; }
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
#entry(severity, component, event, safeFields, identity, dimensions, includeLog) {
|
|
398
|
+
const category = {
|
|
399
|
+
...workerRuntimeAttributes(),
|
|
223
400
|
client_kind: "cli", runtime_role: this.#role, reporter: "codem_js", log_schema: "1",
|
|
224
401
|
component: token(component) ?? "unknown", event: token(event) ?? "unknown", severity,
|
|
225
402
|
identity_source: identity.deviceId ? "codem" : "process",
|
|
226
403
|
diagnostic_id: this.#diagnosticId,
|
|
227
404
|
...(identity.tenantId ? { tenant_id: identity.tenantId } : {}),
|
|
228
405
|
...(identity.serverEnvironment ? { server_environment: identity.serverEnvironment } : {}),
|
|
229
|
-
...
|
|
406
|
+
...dimensions
|
|
407
|
+
};
|
|
408
|
+
const header = {
|
|
409
|
+
aid: SLARDAR_PC_AID,
|
|
410
|
+
device_id: identity.deviceId ?? this.#instanceId,
|
|
411
|
+
user_id: identity.userId ?? "0",
|
|
412
|
+
parfait_version: SLARDAR_PC_REPORTER_VERSION,
|
|
413
|
+
channel: identity.channel ?? "unknown",
|
|
414
|
+
os: this.#platform, os_version: this.#osVersion
|
|
230
415
|
};
|
|
231
|
-
if (safeFields.lane) category.lane = safeFields.lane;
|
|
232
|
-
if (safeFields.target_kind) category.target_kind = safeFields.target_kind;
|
|
233
|
-
const metrics = { count: 1 };
|
|
234
|
-
for (const field of UPLINK_DIAGNOSTIC_METRICS.get(category.event) ?? []) {
|
|
235
|
-
const value = safeFields[field];
|
|
236
|
-
if (Number.isFinite(value) && value >= 0) metrics[field] = value;
|
|
237
|
-
}
|
|
238
|
-
const header = this.#header();
|
|
239
416
|
const timestamp = Date.now();
|
|
240
|
-
const payload = {
|
|
417
|
+
const payload = includeLog ? {
|
|
241
418
|
schema_version: 1, timestamp, component: category.component, event: category.event, level: severity,
|
|
242
419
|
process_instance_id: this.#instanceId, diagnostic_id: this.#diagnosticId, pid: process.pid,
|
|
243
420
|
...(identity.tenantId ? { tenant_id: identity.tenantId } : {}),
|
|
244
421
|
fields: safeFields
|
|
245
|
-
};
|
|
422
|
+
} : undefined;
|
|
246
423
|
const record = {
|
|
247
424
|
app_version: this.#version, app_minor_version: "", build_id: "",
|
|
248
425
|
process_type: `codem-${this.#role}`, session_id: "", timestamp, category,
|
|
249
426
|
log_type: "log", log_level: severity === "fatal" ? "error" : severity,
|
|
250
|
-
log_content: `CodeM diagnostic ${severity} ${category.component}/${category.event}\n${JSON.stringify(payload)}`
|
|
427
|
+
...(payload ? { log_content: `CodeM diagnostic ${severity} ${category.component}/${category.event}\n${JSON.stringify(payload)}` } : {})
|
|
251
428
|
};
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
429
|
+
const criticalSettlement = event === "delivery_settled" && dimensions.critical === "true";
|
|
430
|
+
const priority = severity === "fatal" ? 3 :
|
|
431
|
+
["resumed", "settled"].includes(safeFields.stage) || (severity === "error" && !safeFields.suppressed_count) ? 2 :
|
|
432
|
+
severity === "info" && !criticalSettlement ? 0 : 1;
|
|
433
|
+
return { header, record, includeLog, priority, attempts: 0, crashFile: undefined };
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
#enqueue(entry) {
|
|
437
|
+
const queue = this.#live.queue;
|
|
438
|
+
if (queue.length >= CAPACITY) {
|
|
439
|
+
const minimum = Math.min(...queue.map(item => item.priority));
|
|
440
|
+
if (minimum > entry.priority) { this.#dropped += 1; return false; }
|
|
441
|
+
queue.splice(queue.findIndex(item => item.priority === minimum), 1);
|
|
442
|
+
this.#dropped += 1;
|
|
443
|
+
}
|
|
444
|
+
queue.push(entry);
|
|
445
|
+
return true;
|
|
260
446
|
}
|
|
261
447
|
|
|
262
448
|
async flush({ timeoutMs = REQUEST_TIMEOUT_MS } = {}) {
|
|
449
|
+
// Counters only in the failure path: never recursively log an upload error.
|
|
450
|
+
if (Date.now() - this.#lastHealthAt >= 60_000 && (this.#dropped !== this.#reportedDrops || this.#uploadFailures !== this.#reportedFailures)) {
|
|
451
|
+
this.#lastHealthAt = Date.now();
|
|
452
|
+
const dropped = this.#dropped;
|
|
453
|
+
const failures = this.#uploadFailures;
|
|
454
|
+
const queued = this.record("warn", "runtime-post", "diagnostic_reporter_health", {
|
|
455
|
+
dropped_delta: dropped - this.#reportedDrops,
|
|
456
|
+
upload_failure_delta: failures - this.#reportedFailures,
|
|
457
|
+
pending_event_count: this.pendingCount
|
|
458
|
+
});
|
|
459
|
+
// The health record can itself evict an entry or be refused by a full
|
|
460
|
+
// higher-priority queue. Neither loss has been included in this snapshot.
|
|
461
|
+
if (queued) {
|
|
462
|
+
this.#reportedDrops = dropped;
|
|
463
|
+
this.#reportedFailures = failures;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
263
466
|
const deadline = Date.now() + timeoutMs;
|
|
264
467
|
const live = this.#flushLane(this.#live, timeoutMs).then(() => {
|
|
265
468
|
// Cover records added after drain's last queue check but before its
|
|
@@ -272,7 +475,7 @@ export class RuntimeLogReporter {
|
|
|
272
475
|
// Run both lanes concurrently: old replay cannot delay live sends. Waiting
|
|
273
476
|
// for both within one budget also gives short-lived invocations a chance
|
|
274
477
|
// to finish replay; a timeout leaves its original crash file for next time.
|
|
275
|
-
const replay = this.#flushLane(this.#replay, REQUEST_TIMEOUT_MS);
|
|
478
|
+
const replay = this.#restoring.then(() => this.#flushLane(this.#replay, REQUEST_TIMEOUT_MS));
|
|
276
479
|
let timer;
|
|
277
480
|
try {
|
|
278
481
|
await Promise.race([
|
|
@@ -303,18 +506,30 @@ export class RuntimeLogReporter {
|
|
|
303
506
|
const first = lane.queue[0];
|
|
304
507
|
const key = JSON.stringify(first.header);
|
|
305
508
|
const batch = [];
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
509
|
+
const data = [];
|
|
510
|
+
let bytes = 0;
|
|
511
|
+
while (batch.length < BATCH_SIZE && lane.queue.length && JSON.stringify(lane.queue[0].header) === key && Boolean(lane.queue[0].crashFile) === Boolean(first.crashFile)) {
|
|
512
|
+
const { record, metrics, extra, metricName = "codem_runtime_diagnostic", includeLog = true } = lane.queue[0];
|
|
513
|
+
const records = includeLog ? [record] : [];
|
|
514
|
+
if (metricName) records.push({
|
|
515
|
+
app_version: record.app_version, app_minor_version: "", build_id: "",
|
|
516
|
+
process_type: record.process_type, session_id: "", timestamp: record.timestamp,
|
|
517
|
+
log_type: "flexible", event_name: metricName, category: record.category,
|
|
518
|
+
metrics: metrics ?? { count: 1 }, ...(extra ? { extra } : {})
|
|
519
|
+
});
|
|
520
|
+
const entryBytes = Buffer.byteLength(JSON.stringify(records));
|
|
521
|
+
if (batch.length && bytes + entryBytes > MAX_BATCH_BYTES) break;
|
|
522
|
+
bytes += entryBytes;
|
|
523
|
+
batch.push(lane.queue.shift());
|
|
524
|
+
data.push(...records);
|
|
525
|
+
}
|
|
312
526
|
try {
|
|
313
527
|
await Promise.race([Promise.resolve().then(() => this.#send({ header: first.header, data }, { signal: controller.signal })), deadline]);
|
|
314
528
|
for (const entry of batch) {
|
|
315
|
-
if (entry.crashFile)
|
|
529
|
+
if (entry.crashFile) await fs.promises.unlink(entry.crashFile).catch(() => {});
|
|
316
530
|
}
|
|
317
531
|
} catch {
|
|
532
|
+
this.#uploadFailures += 1;
|
|
318
533
|
// One later retry, on the regular interval. Bound both memory and work;
|
|
319
534
|
// an unavailable collector must not create a retry loop or block exit.
|
|
320
535
|
for (const entry of batch) {
|
|
@@ -345,6 +560,9 @@ export class RuntimeLogReporter {
|
|
|
345
560
|
|
|
346
561
|
let active;
|
|
347
562
|
|
|
563
|
+
export function runtimeLogsEnabled() { return Boolean(active); }
|
|
564
|
+
export function runtimeLogIdentityKey() { return active?.identityKey; }
|
|
565
|
+
|
|
348
566
|
export function startRuntimeLogs({ role, version, env = process.env, send } = {}) {
|
|
349
567
|
try {
|
|
350
568
|
if (active || /^(1|true|yes)$/iu.test(env.CODEM_TELEMETRY_DISABLED ?? "") || env.NODE_TEST_CONTEXT) return;
|
|
@@ -365,8 +583,14 @@ export function recordRuntimeLog(level, component, event, fields = {}) {
|
|
|
365
583
|
try { return active?.record(level, component, event, fields) ?? false; } catch { return false; }
|
|
366
584
|
}
|
|
367
585
|
|
|
368
|
-
|
|
369
|
-
|
|
586
|
+
// An explicit result or state observation. This never waits for the collector;
|
|
587
|
+
// persist is reserved for rare terminal failures that can outlive this process.
|
|
588
|
+
export function recordBridgeLifecycle(event, fields, options = {}) {
|
|
589
|
+
try { return active?.recordLifecycle(event, fields, options) ?? false; } catch { return false; }
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
export function flushRuntimeLogsInBackground() {
|
|
593
|
+
if (active) setImmediate(() => { void active?.flush().catch(() => {}); }).unref?.();
|
|
370
594
|
}
|
|
371
595
|
|
|
372
596
|
export function persistRuntimeCrash(component, event, fields) {
|
|
@@ -375,9 +599,9 @@ export function persistRuntimeCrash(component, event, fields) {
|
|
|
375
599
|
|
|
376
600
|
// A failure that ends a short-lived process: persist first, then try to deliver
|
|
377
601
|
// within one upload budget, so an immediate exit cannot lose the count.
|
|
378
|
-
export
|
|
602
|
+
export function reportRuntimeFailure(component, event, fields = {}) {
|
|
379
603
|
try { active?.persistCrash(component, event, fields, { deliverNow: true }); } catch { /* best effort */ }
|
|
380
|
-
|
|
604
|
+
flushRuntimeLogsInBackground();
|
|
381
605
|
}
|
|
382
606
|
|
|
383
607
|
export async function flushRuntimeLogs(budgetMs = 200) {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import https from "node:https";
|
|
2
|
-
import {
|
|
2
|
+
import { gzip } from "node:zlib";
|
|
3
|
+
import { promisify } from "node:util";
|
|
3
4
|
|
|
4
5
|
// PC Custom Log / Custom Event wire format, verified against Parfait 1.7.0.0's
|
|
5
6
|
// public IUploader callback. This is not the Slardar Web/BID protocol. Keep the
|
|
@@ -10,10 +11,13 @@ export const SLARDAR_PC_AID = "1880";
|
|
|
10
11
|
// from the native Parfait SDK. Do not advertise a native SDK we do not run.
|
|
11
12
|
export const SLARDAR_PC_REPORTER_VERSION = "1.0.0.0";
|
|
12
13
|
const ENDPOINT = `https://pc-mon.zijieapi.com/monitor_pc/collect/api/pc_log?aid=${SLARDAR_PC_AID}`;
|
|
14
|
+
const compress = promisify(gzip);
|
|
13
15
|
|
|
14
|
-
export function sendSlardarPcBatch(payload, { signal, request = https.request } = {}) {
|
|
16
|
+
export async function sendSlardarPcBatch(payload, { signal, request = https.request } = {}) {
|
|
17
|
+
signal?.throwIfAborted();
|
|
18
|
+
const body = await compress(Buffer.from(JSON.stringify(payload)));
|
|
19
|
+
signal?.throwIfAborted();
|
|
15
20
|
return new Promise((resolve, reject) => {
|
|
16
|
-
const body = gzipSync(Buffer.from(JSON.stringify(payload)));
|
|
17
21
|
const req = request(ENDPOINT, {
|
|
18
22
|
method: "POST",
|
|
19
23
|
signal,
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
const exactVersion = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
|
|
2
|
+
|
|
3
|
+
// Low-cardinality process context shared by existing logs, metric categories,
|
|
4
|
+
// and tracing. Ordinary personal-Bot processes have no worker attribution.
|
|
5
|
+
export function workerRuntimeAttributes(env = process.env) {
|
|
6
|
+
if (env.CODEM_WORKER_RUNTIME_READY !== '1' || !['stable', 'current'].includes(env.CODEM_WORKER_RUNTIME_ACTUAL)) return {};
|
|
7
|
+
return { worker_runtime_family: env.CODEM_WORKER_RUNTIME_ACTUAL,
|
|
8
|
+
...(exactVersion.test(env.CODEM_WORKER_CLI_VERSION || '') ? { worker_cli_version: env.CODEM_WORKER_CLI_VERSION } : {}),
|
|
9
|
+
...(exactVersion.test(env.CODEM_WORKER_CORE_VERSION || '') ? { worker_core_version: env.CODEM_WORKER_CORE_VERSION } : {}) };
|
|
10
|
+
}
|