@lark-codem/codem-cli 0.1.282-dev.100104684703.0.g9b92fbb → 0.1.282-dev.100104694445.0.g18c5dac

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.
@@ -1,37 +1,34 @@
1
+ import { realtimeLogID } from "./realtime-log-id.js";
2
+ import { sandboxObservationContext, sandboxLogUploadAllowed } from "./sandbox-observability.js";
1
3
  import { workerRuntimeAttributes } from "./worker-runtime-observation.js";
2
4
  import { createHash, randomUUID } from "node:crypto";
3
5
  import os from "node:os";
4
6
  import fs from "node:fs";
5
7
  import path from "node:path";
6
- import { setImmediate as yieldToEventLoop } from "node:timers/promises";
7
8
  import { diagnosticId } from "./diagnostic-id.js";
8
- import { safeServerLogId } from "./http-read-diagnostics.js";
9
- import { redactDiagnosticText } from "./diagnostic-text.js";
10
9
  import { readDeviceId } from "./device-identity.js";
11
- import { sendSlardarPcBatch, SLARDAR_PC_AID, SLARDAR_PC_REPORTER_VERSION,
12
- captureRuntimeLogArguments, formatRuntimeLogText, runtimeLogSecrets, isRuntimeOutputError } from "./slardar-pc-transport.js";
10
+ import { sendSlardarPcBatch, SLARDAR_PC_AID, SLARDAR_PC_REPORTER_VERSION } from "./slardar-pc-transport.js";
13
11
 
14
12
  const CAPACITY = 256;
15
13
  const BATCH_SIZE = 32;
16
14
  const INTERVAL_MS = 10_000;
17
15
  const REQUEST_TIMEOUT_MS = 3_000;
18
16
  const MAX_BATCH_BYTES = 256 * 1024;
19
- const TEXT_FORMAT_BUDGET_MS = 16;
20
17
  const LIFECYCLE_EVENT_NAME = "codem_bridge_lifecycle";
21
18
  const LIFECYCLE_COMPONENTS = {
22
- daemon_process_startup: "daemon", daemon_first_heartbeat: "daemon",
23
- runtime_sync: "runtime-post", command_handoff: "bridge",
19
+ daemon_startup: "daemon", runtime_sync: "runtime-post", command_handoff: "bridge",
24
20
  runner_operation: "bridge", delivery_settled: "runtime-post", runtime_state: "bridge",
25
21
  event_discarded: "runtime-post", process_lifecycle: "linco"
26
22
  };
27
23
  const LIFECYCLE_METRICS = [
28
- "duration_ms", "ack_settle_duration_ms", "operation_age_ms", "deferred_age_ms", "pending_command_ack_count",
24
+ "duration_ms", "ack_settle_duration_ms", "startup_wait_ms", "operation_age_ms",
25
+ "outage_duration_ms", "consecutive_failures", "deferred_age_ms", "pending_command_ack_count",
29
26
  "pending_ack_age_ms", "pending_event_count", "oldest_event_age_ms", "lifetime_ms"
30
27
  ];
31
28
  const LIFECYCLE_DIMENSIONS = {
32
29
  outcome: ["success", "failed", "rejected", "canceled", "unknown", "accepted", "duplicate", "conflicting", "observed", "recovered"],
33
30
  operation: ["prepare", "spawn", "ready", "cancel", "shutdown"],
34
- scope: ["runner", "command", "queue"],
31
+ scope: ["startup", "runner", "sync", "command", "queue"],
35
32
  kind: ["command_ack", "runtime_event", "control", "events", "relay", "offline"],
36
33
  phase: ["startup_marker", "prelude", "healthcheck", "config_load", "update_check", "service_reconcile", "login_gate", "launch", "authentication", "singleton", "initialize", "start_client", "first_sync", "trusted_device",
37
34
  "build_request", "request", "validate_response", "apply_response", "persist_state",
@@ -41,8 +38,7 @@ const LIFECYCLE_DIMENSIONS = {
41
38
  "shutting_down_handoff", "handoff_target_not_active", "handler_inflight", "duplicate_inflight",
42
39
  "runtime_unavailable", "runtime_environment_failed", "capability_probe_failed", "runtime_binary_changed",
43
40
  "strict_resume_unsupported", "turn_context_unsupported", "active_run_protocol_mismatch", "trusted_device_blocked",
44
- "invalid_runtime_event", "event_rejected", "device_replaced", "device_unbound",
45
- "task_terminated:canceled", "task_terminated:failed", "task_terminated:succeeded"],
41
+ "invalid_runtime_event", "event_rejected", "task_terminated:canceled", "task_terminated:failed", "task_terminated:succeeded"],
46
42
  error_source: ["bridge", "base", "linco", "transport"],
47
43
  stability: ["stable", "unstable", "unknown"],
48
44
  action: ["exit", "restart"],
@@ -69,10 +65,6 @@ const OBSERVATION_DIMENSIONS = {
69
65
  timing_origin: ["observed", "restored_unknown"]
70
66
  };
71
67
  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"],
76
68
  host_identity_collection: ["duration_ms", "field_error_count"],
77
69
  host_identity_command: ["duration_ms", "timeout_ms"],
78
70
  host_session_attempt: ["elapsed_ms", "next_retry_ms", "consecutive_failures", "session_remaining_ms", ...TRUSTED_DEVICE_PHASES.map(phase => `${phase}_duration_ms`)],
@@ -86,30 +78,49 @@ const OBSERVATION_METRICS = {
86
78
  command_observation_closed: ["omitted_detail_count", "pending_command_ack_count", "deferred_count"],
87
79
  diagnostic_reporter_health: ["dropped_delta", "upload_failure_delta", "pending_event_count"]
88
80
  };
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"];
81
+ const EXTRA_FIELDS = ["observation_id", "runtime_client_instance_id", "command_id", "delivery_id", "probe_id", "sync_id", "transport_request_id", "attempt_id"];
90
82
  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
+ ]);
91
92
  const STRING_FIELDS = new Set([
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",
93
+ "resource_id", "resource_env", "request_id", "command_id", "session_id", "task_id", "dispatch_id", "event_id", "sync_id", "attempt_id",
94
+ "failure_stage", "first_route_id", "first_method", "first_reason", "late_outcome", "ipc_request_id",
95
+ "lane", "target_kind", "frontier_did", "packet_kind", "packet_traceparent",
94
96
  "process_instance_id", "run_id", "stage", "phase", "status", "outcome", "reason", "action",
95
97
  "error_class", "error_code", "error_kind", "error_type", "code", "signal", "stop_reason",
96
98
  "first_error", "retry_source", "cleanup_result",
97
99
  "terminal_event", "event_type", "actor_type", "source", "trigger", "hook_id", "hook_event",
98
100
  "target_version", "cli_version", "core_version", "version", "previous_state", "state",
99
101
  "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",
100
- "operation_id", "entrypoint", "native_operation", "workflow_launch_id"
102
+ "syscall",
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"
101
109
  ]);
102
110
  const VALUE_FIELDS = new Set([
103
- "truncated",
104
- "session_retained", "unreadable", "win32_error",
105
- "lease_valid_until_ms", "requested_valid_until_ms", "lease_remaining_ms", "wall_remaining_ms",
111
+ "session_retained", "lease_valid_until_ms", "requested_valid_until_ms", "lease_remaining_ms", "wall_remaining_ms",
112
+ "local_rpc_id", "batch_index", "rpc_error_code", "has_subscribers", "window_active",
106
113
  ...new Set(Object.values(OBSERVATION_METRICS).flat()),
107
114
  "pid", "exit_code", "duration_ms", "elapsed_ms", "wait_ms", "run_ms", "total_ms", "took_ms",
108
115
  "attempt", "attempts", "attempt_count", "retryable", "http_status", "errno", "active_task_count",
109
116
  "pending_event_count", "pending_command_ack_count", "next_retry_ms", "consecutive_failures",
110
- "outage_duration_ms", "failed_attempts", "active_runs", "completed",
117
+ ...Array.from(UPLINK_DIAGNOSTIC_METRICS.values()).flat(), "transport_open",
118
+ "outage_duration_ms", "startup_duration_ms", "failed_attempts", "active_runs", "completed",
111
119
  "delivered", "result_delivered", "queued_behind_existing", "expected", "timed_out",
112
120
  "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",
113
124
  ...LIFECYCLE_METRICS
114
125
  ]);
115
126
 
@@ -127,7 +138,7 @@ function optional(read) {
127
138
  }
128
139
 
129
140
  function metricProjection(event, fields = {}) {
130
- return { count: 1, ...Object.fromEntries((OBSERVATION_METRICS[event] ?? [])
141
+ return { count: 1, ...Object.fromEntries((OBSERVATION_METRICS[event] ?? UPLINK_DIAGNOSTIC_METRICS.get(event) ?? [])
131
142
  .filter(key => typeof fields?.[key] === "number" && Number.isFinite(fields[key]) && fields[key] >= 0)
132
143
  .map(key => [key, fields[key]])) };
133
144
  }
@@ -136,11 +147,18 @@ function extraProjection(fields = {}) {
136
147
  return Object.fromEntries(EXTRA_FIELDS.filter(key => token(fields?.[key])).map(key => [key, token(fields[key])]));
137
148
  }
138
149
 
139
- function projectFields(input, fingerprintErrors = true) {
150
+ const REALTIME_IDS = new Set(["route_id", "question_id", "thread_id", "turn_id", "session_id", "event_id"]);
151
+
152
+ function projectFields(input, fingerprintErrors = true, component) {
140
153
  const result = {};
141
154
  for (const [key, value] of Object.entries(input ?? {}).slice(0, 100)) {
142
155
  const name = fieldName(key);
143
- if (STRING_FIELDS.has(name)) {
156
+ if (name === "method" && typeof value === "string" && /^[a-z][a-z\d_.]*(?:\/[a-z][a-z\d_.]*){0,7}$/iu.test(value) && value.length <= 80) {
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)) {
144
162
  const safe = token(value);
145
163
  if (safe) result[name] = safe;
146
164
  } else if (VALUE_FIELDS.has(name) && (typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value)))) {
@@ -165,9 +183,7 @@ function projectFields(input, fingerprintErrors = true) {
165
183
  // Errors can contain prompts, paths and raw upstream response bodies.
166
184
  // Retain classification + a fingerprint, never their arbitrary text.
167
185
  const message = typeof error === "string" ? error : error.message;
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);
186
+ if (typeof message === "string") result.error_fingerprint = createHash("sha256").update(message.slice(0, 4096)).digest("hex").slice(0, 24);
171
187
  }
172
188
  return result;
173
189
  }
@@ -187,201 +203,98 @@ function lifecycleErrorSummary(dimensions, fields) {
187
203
 
188
204
  function lifecycleErrorCode(fields) {
189
205
  const code = token(fields.error_code ?? fields.error?.code ?? fields.error?.cause?.code)?.toLowerCase();
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;
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;
191
207
  const status = Number(fields.http_status);
192
208
  if (Number.isInteger(status) && status >= 100 && status <= 599) return `http_${status}`;
193
209
  return fields.outcome === "failed" || fields.outcome === "rejected" || fields.outcome === "conflicting" ? "unknown" : undefined;
194
210
  }
195
211
 
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
- }
201
-
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
- }
212
+ const REALTIME_LOG_ONLY = new Set([
213
+ "app_server_rpc", "app_server_rpc_unmatched", "app_server_rpc_late_reply", "app_server_host_attached",
214
+ "app_server_host_failed", "app_server_host_reused_failed", "app_server_host_prepare", "artifact_operation_failed",
215
+ "app_server_resume_binding_failed", "app_server_question", "hitl_answer",
216
+ "downlink_admission", "rpc_reply", "uplink_commit", "uplink_transport", "subscription_query", "runtime_lease"
217
+ ]);
220
218
 
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"));
219
+ const LOCAL_SENSITIVE_KEY = /^(?:oauth|authorization|token|secret|password|apikey|api_key|ak|access_key|secret_key|refresh_token|access_token|user_access_token|uat|rt|device_secret|device_secret_plaintext)$/iu;
220
+
221
+ const defaultRealtimeSink = {
222
+ info(line) {
223
+ const out = console;
224
+ out.info(line);
225
+ },
226
+ warn(line) {
227
+ const out = console;
228
+ out.warn(line);
229
+ },
230
+ error(line) {
231
+ const out = console;
232
+ out.error(line);
226
233
  }
227
- return undefined;
228
- }
229
-
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
- }
234
+ };
271
235
 
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;
236
+ function serializeLocalValue(value, depth = 0) {
237
+ if (value === null || value === undefined) return undefined;
238
+ if (typeof value === "string") return value.length > 1024 ? `${value.slice(0, 1021)}...` : value;
239
+ if (typeof value === "number") return Number.isFinite(value) ? value : undefined;
240
+ if (typeof value === "boolean") return value;
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;
282
261
  }
283
- text = text.slice(0, pos) + replacement + text.slice(pos + matchLen);
284
- cursor = pos + replacement.length;
262
+ return out;
285
263
  }
286
- return text;
264
+ return undefined;
287
265
  }
288
266
 
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));
267
+ export function writeLocalRealtimeLog(level, event, fields = {}, { logger } = {}) {
268
+ try {
269
+ if (logger === null) return;
270
+ if (!logger && process.env.NODE_TEST_CONTEXT && process.env.CODEM_REALTIME_LOCAL_LOG !== "1") return;
271
+ const sink = logger ?? defaultRealtimeSink;
272
+ const payload = serializeLocalValue(fields) ?? {};
273
+ const line = `[codem][realtime][${event}] ${JSON.stringify(payload)}`;
274
+ if (level === "info") {
275
+ sink.info?.(line);
276
+ } else if (level === "error" || level === "fatal") {
277
+ (sink.error ?? sink.warn)?.call(sink, line);
278
+ } else {
279
+ sink.warn?.(line);
280
+ }
281
+ } catch { /* Local diagnostics must never affect business execution. */ }
295
282
  }
296
283
 
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
- };
284
+ export function writeLocalCoreStderr(pid, rawLine, { logger } = {}) {
285
+ try {
286
+ if (logger === null) return;
287
+ if (!logger && process.env.NODE_TEST_CONTEXT && process.env.CODEM_REALTIME_LOCAL_LOG !== "1") return;
288
+ const trimmed = String(rawLine ?? "").trim();
289
+ if (!trimmed) return;
290
+ const safe = trimmed.length > 2048 ? `${trimmed.slice(0, 2045)}...` : trimmed;
291
+ const sink = logger ?? defaultRealtimeSink;
292
+ sink.warn?.(`[codem][core-stderr][pid=${pid ?? "unknown"}] ${safe}`);
293
+ } catch { /* Forwarding child stderr must never fail the host. */ }
382
294
  }
383
295
 
384
296
  function keepLegacyMetric(event, fields, role, severity) {
297
+ if (REALTIME_LOG_ONLY.has(event)) return false;
385
298
  if (/^startup\.(?:main|update_check|daemon_service_reconcile|login_gate|login_handoff_to_linco)$/u.test(event) && severity === "info") return false;
386
299
  if (/(?:^|\.)drain_(?:started|completed)$/u.test(event) && severity === "info") return false;
387
300
  if (role === "daemon" && event === "runtime_capability_probe" && severity === "info") return false;
@@ -415,6 +328,7 @@ export class RuntimeLogReporter {
415
328
  #live = { queue: [], inflight: undefined, abort: undefined };
416
329
  #replay = { queue: [], inflight: undefined, abort: undefined };
417
330
  #identity = {};
331
+ #resourceContext = {};
418
332
  #timer;
419
333
  #closed = false;
420
334
  #dropped = 0;
@@ -432,26 +346,17 @@ export class RuntimeLogReporter {
432
346
  #crashDirectory;
433
347
  #restoring;
434
348
  #savedDuringRestore = new Set();
435
- #secrets;
436
- #startupId;
437
- #context;
438
- #sandboxIdFromEnv;
439
349
 
440
- constructor({ role = "cli", version = "unknown", send = sendSlardarPcBatch, instanceId = randomUUID(), diagnosticId: supportId = diagnosticId(), platform = process.platform, osVersion = os.release(), crashDirectory, env = process.env } = {}) {
350
+ constructor({ role = "cli", version = "unknown", env = process.env, send = sendSlardarPcBatch, instanceId = randomUUID(), diagnosticId: supportId = diagnosticId(), platform = process.platform, osVersion = os.release(), crashDirectory } = {}) {
441
351
  this.#send = send;
442
352
  this.#crashDirectory = crashDirectory;
443
353
  this.#role = token(role) ?? "cli";
354
+ this.#resourceContext = sandboxObservationContext(env, role);
444
355
  this.#version = token(version) ?? "unknown";
445
356
  this.#instanceId = instanceId;
446
357
  this.#diagnosticId = supportId;
447
358
  this.#platform = platform === "win32" ? "Windows" : platform === "darwin" ? "Mac OS X" : platform;
448
359
  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 });
455
360
  this.#timer = setInterval(() => { void this.flush(); }, INTERVAL_MS);
456
361
  this.#timer.unref?.();
457
362
  this.#restoring = this.#restoreCrashes().finally(() => { this.#savedDuringRestore = undefined; });
@@ -461,18 +366,10 @@ export class RuntimeLogReporter {
461
366
  // Never await network IO in uncaughtExceptionMonitor. Replay is at-least-once.
462
367
  // deliverNow also queues the record for this process's next flush. A
463
368
  // successful send deletes its file; otherwise the next process replays it.
464
- persistCrash(component, event, fields = {}, { deliverNow = false, captureError = false } = {}) {
369
+ persistCrash(component, event, fields = {}, { deliverNow = false } = {}) {
465
370
  try {
466
371
  if (this.#closed || (!this.#crashDirectory && !deliverNow)) return;
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";
372
+ const entry = this.#logEntry("fatal", component, event, fields);
476
373
  this.#saveCrash(entry);
477
374
  if (deliverNow) this.#replay.queue.push(entry);
478
375
  } catch { /* Crash diagnostics must preserve the original exit behavior. */ }
@@ -482,9 +379,12 @@ export class RuntimeLogReporter {
482
379
  if (!this.#crashDirectory) return;
483
380
  try {
484
381
  fs.mkdirSync(this.#crashDirectory, { recursive: true, mode: 0o700 });
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`;
382
+ const migration = entry.record.log_type === "flexible";
383
+ const prefix = migration ? "js-migration-" : "js-";
384
+ const pattern = migration ? /^js-migration-[a-f0-9-]+\.json$/u : /^js-[a-f0-9-]+\.json$/u;
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`;
488
388
  const file = path.join(this.#crashDirectory, name);
489
389
  fs.writeFileSync(file, JSON.stringify(entry), { flag: "wx", mode: 0o600 });
490
390
  this.#savedDuringRestore?.add(name);
@@ -495,34 +395,26 @@ export class RuntimeLogReporter {
495
395
  async #restoreCrashes() {
496
396
  if (!this.#crashDirectory) return;
497
397
  try {
498
- for (const name of (await fs.promises.readdir(this.#crashDirectory)).filter(name => /^js-[a-f0-9-]+\.json$/u.test(name)).slice(0, 32)) {
398
+ const names = await fs.promises.readdir(this.#crashDirectory);
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]) {
499
402
  if (this.#closed) return;
500
403
  if (this.#savedDuringRestore?.has(name)) continue;
501
404
  const file = path.join(this.#crashDirectory, name);
502
405
  try {
503
406
  const stat = await fs.promises.lstat(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(() => {});
508
- continue;
509
- }
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";
407
+ if (!stat.isFile() || stat.size > 65536) continue;
408
+ const entry = JSON.parse(await fs.promises.readFile(file, "utf8"));
409
+ if (entry?.record?.category?.reporter !== "codem_js" || !entry.header) continue;
521
410
  if (this.#closed) return;
522
- if (entry.metricName === LIFECYCLE_EVENT_NAME || entry.record.category.replay === "0") {
523
- entry.record.category.replay = "1";
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 });
413
+ continue;
524
414
  }
415
+ if (entry.record.log_type !== "log") continue;
525
416
  if (entry.metricName === LIFECYCLE_EVENT_NAME) {
417
+ entry.record.category.replay = "1";
526
418
  this.#replay.queue.push({ ...entry, attempts: 0, crashFile: file });
527
419
  } else {
528
420
  this.#replay.queue.push({ header: entry.header, record: entry.record, metricName: entry.metricName,
@@ -537,10 +429,7 @@ export class RuntimeLogReporter {
537
429
  // A sandbox may read the launcher profile for credentials. That profile is
538
430
  // not the tenant/device owning the sandbox's runtime diagnostics.
539
431
  if (this.#role === "sandbox") return;
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 = {}; }
432
+ try { this.#identity = runtimeLogIdentity(config); } catch { this.#identity = {}; }
544
433
  }
545
434
 
546
435
  observeSandboxConfig(config) {
@@ -550,59 +439,63 @@ export class RuntimeLogReporter {
550
439
  tenantId: optional(() => token(config?.tenantId ?? config?.tenantKey)),
551
440
  serverEnvironment: runtimeLogIdentity(config).serverEnvironment
552
441
  };
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);
556
442
  // ownerUserKey is not a Slardar UID. Keep user_id anonymous in this scope.
557
443
  }
558
444
 
559
445
  get pendingCount() { return this.#live.queue.length + this.#replay.queue.length; }
560
446
  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"; }
563
447
 
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; }
448
+ #header() {
449
+ const identity = this.#identity;
450
+ return { aid: SLARDAR_PC_AID, device_id: identity.deviceId ?? this.#instanceId,
451
+ user_id: identity.userId ?? "0", parfait_version: SLARDAR_PC_REPORTER_VERSION,
452
+ channel: identity.channel ?? "unknown", os: this.#platform, os_version: this.#osVersion };
575
453
  }
576
454
 
577
- record(level, component, event, fields = {}, { captureError = false, persist = false } = {}) {
455
+ recordMetric(name, category, metrics, { persist = false } = {}) {
456
+ if (this.#closed) return false;
457
+ if (this.#live.queue.length >= CAPACITY) {
458
+ this.#dropped += 1;
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;
477
+ }
478
+
479
+ record(level, component, event, fields = {}) {
578
480
  try {
579
481
  if (this.#closed) return false;
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);
482
+ return this.#enqueue(this.#logEntry(level, component, event, fields));
586
483
  } catch { return false; }
587
484
  }
588
485
 
589
- #logEntry(level, component, event, fields, captureError) {
590
- const context = this.acceptsApplicationLogs ? this.#context : {};
486
+ #logEntry(level, component, event, fields) {
591
487
  let safeFields;
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;
488
+ try { safeFields = projectFields(fields, true, component); } catch { safeFields = {}; }
489
+ if (OBSERVATION_EVENTS.has(event)) safeFields.observation_id = randomUUID();
600
490
  const severity = ["info", "warn", "error", "fatal"].includes(level) ? level : "info";
601
491
  // Keep arbitrary upstream error codes out of trusted-device metric dimensions.
602
492
  const trustedDevice = TRUSTED_DEVICE_EVENTS.has(event);
603
493
  const dimensions = trustedDevice ? {} : Object.fromEntries(["stage", "error_class", "error_code", "error_kind", "outcome"]
604
494
  .filter(key => safeFields[key]).map(key => [key, safeFields[key]]));
605
- if (startup) dimensions.replay = "0";
495
+ if (UPLINK_DIAGNOSTIC_METRICS.has(event)) {
496
+ if (safeFields.lane) dimensions.lane = safeFields.lane;
497
+ if (safeFields.target_kind) dimensions.target_kind = safeFields.target_kind;
498
+ }
606
499
  if (OBSERVATION_EVENTS.has(event)) {
607
500
  for (const [key, values] of Object.entries(trustedDevice ? TRUSTED_DEVICE_DIMENSIONS : OBSERVATION_DIMENSIONS)) {
608
501
  if (safeFields[key]) dimensions[key] = values.includes(safeFields[key]) ? safeFields[key] : "unknown";
@@ -615,7 +508,7 @@ export class RuntimeLogReporter {
615
508
  };
616
509
  }
617
510
 
618
- recordLifecycle(event, fields = {}, { persist = false, captureError = false } = {}) {
511
+ recordLifecycle(event, fields = {}, { persist = false } = {}) {
619
512
  try {
620
513
  if (this.#closed || !Object.hasOwn(LIFECYCLE_COMPONENTS, event)) return false;
621
514
  const unstable = fields.stability === "unstable" || fields.outcome === "failed" || fields.outcome === "conflicting";
@@ -644,15 +537,11 @@ export class RuntimeLogReporter {
644
537
  const { replay: _replay, ...logDimensions } = dimensions;
645
538
  const summary = hasDetail ? lifecycleErrorSummary(dimensions, fields) : "";
646
539
  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;
650
540
  const safeFields = {
651
- ...(this.acceptsApplicationLogs ? this.#context : {}), ...projected, ...logDimensions, ...metrics,
541
+ ...projected, ...logDimensions, ...metrics,
652
542
  process_instance_id: this.#instanceId,
653
- ...(isStartup ? { startup_id: this.#instanceId } : {}),
543
+ ...(event === "daemon_startup" ? { startup_id: this.#instanceId } : {}),
654
544
  observation_id: randomUUID(),
655
- ...(errorDetail ? { error: errorDetail } : {}),
656
545
  ...(summary ? { error_summary: summary } : {})
657
546
  };
658
547
  const extra = Object.fromEntries(LIFECYCLE_EXTRA_FIELDS
@@ -668,6 +557,7 @@ export class RuntimeLogReporter {
668
557
  }
669
558
 
670
559
  #entry(severity, component, event, safeFields, identity, dimensions, includeLog) {
560
+ safeFields = { ...this.#resourceContext, ...safeFields, ...(this.#resourceContext.resource_id ? { resource_id: this.#resourceContext.resource_id } : {}) };
671
561
  const category = {
672
562
  ...workerRuntimeAttributes(),
673
563
  client_kind: "cli", runtime_role: this.#role, reporter: "codem_js", log_schema: "1",
@@ -770,43 +660,18 @@ export class RuntimeLogReporter {
770
660
  const controller = new AbortController();
771
661
  lane.abort = controller;
772
662
  let expire;
773
- const expiresAt = performance.now() + timeoutMs;
774
- let formattingMs = 0;
775
- const deadline = new Promise(resolve => {
776
- expire = setTimeout(() => { controller.abort(); resolve(); }, timeoutMs);
663
+ const deadline = new Promise((_, reject) => {
664
+ expire = setTimeout(() => { controller.abort(); reject(new Error("Slardar upload timed out")); }, timeoutMs);
777
665
  expire.unref?.();
778
666
  });
779
667
  try {
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) {
668
+ while (lane.queue.length && !this.#closed) {
784
669
  const first = lane.queue[0];
785
670
  const key = JSON.stringify(first.header);
786
671
  const batch = [];
787
672
  const data = [];
788
673
  let bytes = 0;
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
- }
674
+ while (batch.length < BATCH_SIZE && lane.queue.length && JSON.stringify(lane.queue[0].header) === key && Boolean(lane.queue[0].crashFile) === Boolean(first.crashFile)) {
810
675
  const { record, metrics, extra, metricName = "codem_runtime_diagnostic", includeLog = true } = lane.queue[0];
811
676
  const records = includeLog ? [record] : [];
812
677
  if (metricName) records.push({
@@ -820,13 +685,9 @@ export class RuntimeLogReporter {
820
685
  bytes += entryBytes;
821
686
  batch.push(lane.queue.shift());
822
687
  data.push(...records);
823
- if (hasText) await yieldToEventLoop();
824
688
  }
825
- if (this.#closed) return;
826
- if (!batch.length) continue;
827
689
  try {
828
690
  await Promise.race([Promise.resolve().then(() => this.#send({ header: first.header, data }, { signal: controller.signal })), deadline]);
829
- controller.signal.throwIfAborted();
830
691
  for (const entry of batch) {
831
692
  if (entry.crashFile) await fs.promises.unlink(entry.crashFile).catch(() => {});
832
693
  }
@@ -865,12 +726,11 @@ let active;
865
726
  export function runtimeLogsEnabled() { return Boolean(active); }
866
727
  export function runtimeLogIdentityKey() { return active?.identityKey; }
867
728
 
868
- /** @param {{role?: string, version?: string, env?: NodeJS.ProcessEnv, send?: Function}} options */
869
729
  export function startRuntimeLogs({ role, version, env = process.env, send } = {}) {
870
730
  try {
871
- if (active || /^(1|true|yes)$/iu.test(env.CODEM_TELEMETRY_DISABLED ?? "") || env.NODE_TEST_CONTEXT || (process.env.NODE_TEST_CONTEXT && !send)) return;
731
+ if (active || !sandboxLogUploadAllowed(env, role) || /^(1|true|yes)$/iu.test(env.CODEM_TELEMETRY_DISABLED ?? "") || env.NODE_TEST_CONTEXT) return;
872
732
  const root = env.CODEM_HOME || env.LINCO_HOME || path.join(os.homedir(), ".codem");
873
- active = new RuntimeLogReporter({ role, version, send, env, crashDirectory: path.join(root, "runtime-crashes") });
733
+ active = new RuntimeLogReporter({ role, version, env, send, crashDirectory: path.join(root, "runtime-crashes") });
874
734
  } catch { /* Monitoring initialization never prevents a command from running. */ }
875
735
  }
876
736
 
@@ -882,36 +742,8 @@ export function observeRuntimeLogSandboxConfig(config) {
882
742
  try { active?.observeSandboxConfig(config); } catch { /* best effort */ }
883
743
  }
884
744
 
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;
745
+ export function recordRuntimeLog(level, component, event, fields = {}) {
746
+ try { return active?.record(level, component, event, fields) ?? false; } catch { return false; }
915
747
  }
916
748
 
917
749
  // An explicit result or state observation. This never waits for the collector;
@@ -921,34 +753,28 @@ export function recordBridgeLifecycle(event, fields, options = {}) {
921
753
  }
922
754
 
923
755
  export function flushRuntimeLogsInBackground() {
924
- try {
925
- if (active) setImmediate(() => { void active?.flush().catch(() => {}); }).unref?.();
926
- } catch { /* best effort */ }
756
+ if (active) setImmediate(() => { void active?.flush().catch(() => {}); }).unref?.();
927
757
  }
928
758
 
929
- export function persistRuntimeCrash(component, event, fields, options = {}) {
930
- try { active?.persistCrash(component, event, fields, options); } catch { /* best effort */ }
759
+ export function recordRuntimeMetric(name, category, metrics, options) {
760
+ try { return active?.recordMetric(name, category, metrics, options) ?? false; } catch { return false; }
761
+ }
762
+
763
+ export function persistRuntimeCrash(component, event, fields) {
764
+ try { active?.persistCrash(component, event, fields); } catch { /* best effort */ }
931
765
  }
932
766
 
933
767
  // A failure that ends a short-lived process: persist first, then try to deliver
934
768
  // within one upload budget, so an immediate exit cannot lose the count.
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 */ }
769
+ export function reportRuntimeFailure(component, event, fields = {}) {
770
+ try { active?.persistCrash(component, event, fields, { deliverNow: true }); } catch { /* best effort */ }
937
771
  flushRuntimeLogsInBackground();
938
772
  }
939
773
 
940
- export function closeRuntimeLogs() {
941
- try { active?.close(); active = undefined; } catch { /* best effort */ }
942
- }
943
-
944
774
  export async function flushRuntimeLogs(budgetMs = 200) {
945
775
  if (!active) return;
946
776
  let timeout;
947
777
  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.
952
778
  await Promise.race([
953
779
  active.flush({ timeoutMs: budgetMs }),
954
780
  new Promise((resolve) => { timeout = setTimeout(resolve, budgetMs); })
@@ -990,19 +816,12 @@ export function recordInteractiveProcessExit({ exitCode, signal }) {
990
816
  }
991
817
 
992
818
  // Select events explicitly, then project fields again at the remote boundary.
993
- export function recordSelectedRuntimeLog(component, event, fields = {}, { capturedError = undefined } = {}) {
819
+ export function recordSelectedRuntimeLog(component, event, fields = {}) {
994
820
  try {
995
821
  const selectedEvent = event.replace(/^linco\./u, "");
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;
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)|capability\.(?:load\.lifecycle|operation|resource\.lifecycle|runtime\.timing|registry\.(?:snapshot|binding)|invocation|skill\.activation)|(?:agent|command)\.(?:start|interactive_start|success|error|spawn_error|resolve_error|exit_drain_timeout|cancelled_before_spawn|artifact_oversize|artifact_missing|artifact_dropped|artifact_route_selected|artifact_image_upload|artifact_file_upload|artifact_local_register)|router\.credentials\.(?:ensured|refresh_failed)|config-lock\.release_failed|binary\.heal_chmod_failed|project\.(?:inject_error|state)|(?:permission_ask|user_question|plan)\.report_failed|process_tree\.(?:force_kill|force_kill_failed)|artifact\.(?:oversize|missing|dropped)|runtime_post\.daemon\.device_rebind_[a-z_]+)$/u.test(selectedEvent)) return;
997
823
  const expected = optional(() => fields?.errorKind === "user_stop" || fields?.terminalError?.kind === "user_stop" || fields?.exitCode === 130 || fields?.signal === "SIGINT");
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();
824
+ const level = expected ? "info" : (fields?.status === "failed" || ["failed", "timeout"].includes(fields?.result) || /(?:failed|error|exhausted|timeout)$/u.test(event)) ? "error" : /(?:suspect|dropped|missing|oversize)$/u.test(event) ? "warn" : "info";
825
+ recordRuntimeLog(level, component, event, fields);
1007
826
  } catch { /* best effort */ }
1008
827
  }