@lark-codem/codem-cli 0.1.281-dev.100104585886.0.ga915b98 → 0.1.281-dev.100104602537.0.gd02b8a3

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,3 +1,5 @@
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";
@@ -63,7 +65,6 @@ const OBSERVATION_DIMENSIONS = {
63
65
  timing_origin: ["observed", "restored_unknown"]
64
66
  };
65
67
  const OBSERVATION_METRICS = {
66
- history_recall: ["duration_ms", "hit_count", "message_count", "output_tokens_upper_bound"],
67
68
  host_identity_collection: ["duration_ms", "field_error_count"],
68
69
  host_identity_command: ["duration_ms", "timeout_ms"],
69
70
  host_session_attempt: ["elapsed_ms", "next_retry_ms", "consecutive_failures", "session_remaining_ms", ...TRUSTED_DEVICE_PHASES.map(phase => `${phase}_duration_ms`)],
@@ -79,27 +80,46 @@ const OBSERVATION_METRICS = {
79
80
  };
80
81
  const EXTRA_FIELDS = ["observation_id", "runtime_client_instance_id", "command_id", "delivery_id", "probe_id", "sync_id", "transport_request_id", "attempt_id"];
81
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
+ ]);
82
92
  const STRING_FIELDS = new Set([
83
- ...EXTRA_FIELDS, "command_type", "ack_status", "ack_outcome", "readback_scope", "timing_origin", "required_capability",
84
- "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",
85
96
  "process_instance_id", "run_id", "stage", "phase", "status", "outcome", "reason", "action",
86
97
  "error_class", "error_code", "error_kind", "error_type", "code", "signal", "stop_reason",
87
98
  "first_error", "retry_source", "cleanup_result",
88
99
  "terminal_event", "event_type", "actor_type", "source", "trigger", "hook_id", "hook_event",
89
100
  "target_version", "cli_version", "core_version", "version", "previous_state", "state",
90
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",
91
- "operation_id", "entrypoint", "workflow_launch_id"
102
+ "operation_id", "entrypoint", "workflow_launch_id", "runtime_client_instance_id", "connection_instance_id", "lease_epoch",
103
+ "load_id", "refresh_id", "registry_snapshot_id", "capability_key", "capability_type",
104
+ "component_type", "publisher_type", "capability_source", "installation_mode",
105
+ "capability_version", "project_key", "business_scene", "invocation_id", "result",
106
+ "error_category", "runtime_scope", "refresh_trigger", "load_trigger", "stage_name",
107
+ "operation_name", "invocation_source", "binding_state", "load_result"
92
108
  ]);
93
109
  const VALUE_FIELDS = new Set([
94
- "truncated",
95
110
  "session_retained", "lease_valid_until_ms", "requested_valid_until_ms", "lease_remaining_ms", "wall_remaining_ms",
111
+ "local_rpc_id", "batch_index", "rpc_error_code", "has_subscribers", "window_active",
96
112
  ...new Set(Object.values(OBSERVATION_METRICS).flat()),
97
113
  "pid", "exit_code", "duration_ms", "elapsed_ms", "wait_ms", "run_ms", "total_ms", "took_ms",
98
114
  "attempt", "attempts", "attempt_count", "retryable", "http_status", "errno", "active_task_count",
99
115
  "pending_event_count", "pending_command_ack_count", "next_retry_ms", "consecutive_failures",
116
+ ...Array.from(UPLINK_DIAGNOSTIC_METRICS.values()).flat(), "transport_open",
100
117
  "outage_duration_ms", "startup_duration_ms", "failed_attempts", "active_runs", "completed",
101
118
  "delivered", "result_delivered", "queued_behind_existing", "expected", "timed_out",
102
119
  "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",
120
+ "expected_count", "loaded_count", "loaded_capability_count", "failed_count", "skipped_count", "ready_count", "downloaded_count", "turn_id", "turn_index",
121
+ "late_rpc_error_code", "lifecycle_wait_ms", "prepare_ms", "router_cred_ms", "meegle_init_ms", "spawn_init_ms", "budget_ms",
122
+ "oauth_ms", "project_list_ms", "config_total_ms", "write_total_ms",
103
123
  ...LIFECYCLE_METRICS
104
124
  ]);
105
125
 
@@ -117,7 +137,7 @@ function optional(read) {
117
137
  }
118
138
 
119
139
  function metricProjection(event, fields = {}) {
120
- return { count: 1, ...Object.fromEntries((OBSERVATION_METRICS[event] ?? [])
140
+ return { count: 1, ...Object.fromEntries((OBSERVATION_METRICS[event] ?? UPLINK_DIAGNOSTIC_METRICS.get(event) ?? [])
121
141
  .filter(key => typeof fields?.[key] === "number" && Number.isFinite(fields[key]) && fields[key] >= 0)
122
142
  .map(key => [key, fields[key]])) };
123
143
  }
@@ -126,11 +146,18 @@ function extraProjection(fields = {}) {
126
146
  return Object.fromEntries(EXTRA_FIELDS.filter(key => token(fields?.[key])).map(key => [key, token(fields[key])]));
127
147
  }
128
148
 
129
- function projectFields(input, fingerprintErrors = true) {
149
+ const REALTIME_IDS = new Set(["route_id", "question_id", "thread_id", "turn_id", "session_id", "event_id"]);
150
+
151
+ function projectFields(input, fingerprintErrors = true, component) {
130
152
  const result = {};
131
153
  for (const [key, value] of Object.entries(input ?? {}).slice(0, 100)) {
132
154
  const name = fieldName(key);
133
- if (STRING_FIELDS.has(name)) {
155
+ if (name === "method" && typeof value === "string" && /^[a-z][a-z\d_.]*(?:\/[a-z][a-z\d_.]*){0,7}$/iu.test(value) && value.length <= 80) {
156
+ result[name] = value;
157
+ } else if (component === "realtime" && REALTIME_IDS.has(name)) {
158
+ const id = realtimeLogID(value);
159
+ if (id !== undefined) result[name] = id;
160
+ } else if (STRING_FIELDS.has(name)) {
134
161
  const safe = token(value);
135
162
  if (safe) result[name] = safe;
136
163
  } else if (VALUE_FIELDS.has(name) && (typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value)))) {
@@ -181,7 +208,92 @@ function lifecycleErrorCode(fields) {
181
208
  return fields.outcome === "failed" || fields.outcome === "rejected" || fields.outcome === "conflicting" ? "unknown" : undefined;
182
209
  }
183
210
 
211
+ const REALTIME_LOG_ONLY = new Set([
212
+ "app_server_rpc", "app_server_rpc_unmatched", "app_server_rpc_late_reply", "app_server_host_attached",
213
+ "app_server_host_failed", "app_server_host_reused_failed", "app_server_host_prepare", "artifact_operation_failed",
214
+ "app_server_resume_binding_failed", "app_server_question", "hitl_answer",
215
+ "downlink_admission", "rpc_reply", "uplink_commit", "uplink_transport", "subscription_query", "runtime_lease"
216
+ ]);
217
+
218
+ 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;
219
+
220
+ const defaultRealtimeSink = {
221
+ info(line) {
222
+ const out = console;
223
+ out.info(line);
224
+ },
225
+ warn(line) {
226
+ const out = console;
227
+ out.warn(line);
228
+ },
229
+ error(line) {
230
+ const out = console;
231
+ out.error(line);
232
+ }
233
+ };
234
+
235
+ function serializeLocalValue(value, depth = 0) {
236
+ if (value === null || value === undefined) return undefined;
237
+ if (typeof value === "string") return value.length > 1024 ? `${value.slice(0, 1021)}...` : value;
238
+ if (typeof value === "number") return Number.isFinite(value) ? value : undefined;
239
+ if (typeof value === "boolean") return value;
240
+ if (value instanceof Error) {
241
+ const summary = {
242
+ error_type: value.name || "Error",
243
+ error_message: typeof value.message === "string" ? value.message.slice(0, 1024) : ""
244
+ };
245
+ if (value.code !== undefined) summary.error_code = String(value.code).slice(0, 128);
246
+ if (value.errno !== undefined) summary.errno = value.errno;
247
+ if (value.rpcError?.code !== undefined) summary.rpc_error_code = value.rpcError.code;
248
+ return summary;
249
+ }
250
+ if (depth >= 3) return undefined;
251
+ if (Array.isArray(value)) {
252
+ return value.slice(0, 32).map(entry => serializeLocalValue(entry, depth + 1)).filter(entry => entry !== undefined);
253
+ }
254
+ if (typeof value === "object") {
255
+ const out = {};
256
+ for (const [key, entry] of Object.entries(value)) {
257
+ if (entry === undefined || LOCAL_SENSITIVE_KEY.test(key)) continue;
258
+ const serialized = serializeLocalValue(entry, depth + 1);
259
+ if (serialized !== undefined) out[key] = serialized;
260
+ }
261
+ return out;
262
+ }
263
+ return undefined;
264
+ }
265
+
266
+ export function writeLocalRealtimeLog(level, event, fields = {}, { logger } = {}) {
267
+ try {
268
+ if (logger === null) return;
269
+ if (!logger && process.env.NODE_TEST_CONTEXT && process.env.CODEM_REALTIME_LOCAL_LOG !== "1") return;
270
+ const sink = logger ?? defaultRealtimeSink;
271
+ const payload = serializeLocalValue(fields) ?? {};
272
+ const line = `[codem][realtime][${event}] ${JSON.stringify(payload)}`;
273
+ if (level === "info") {
274
+ sink.info?.(line);
275
+ } else if (level === "error" || level === "fatal") {
276
+ (sink.error ?? sink.warn)?.call(sink, line);
277
+ } else {
278
+ sink.warn?.(line);
279
+ }
280
+ } catch { /* Local diagnostics must never affect business execution. */ }
281
+ }
282
+
283
+ export function writeLocalCoreStderr(pid, rawLine, { logger } = {}) {
284
+ try {
285
+ if (logger === null) return;
286
+ if (!logger && process.env.NODE_TEST_CONTEXT && process.env.CODEM_REALTIME_LOCAL_LOG !== "1") return;
287
+ const trimmed = String(rawLine ?? "").trim();
288
+ if (!trimmed) return;
289
+ const safe = trimmed.length > 2048 ? `${trimmed.slice(0, 2045)}...` : trimmed;
290
+ const sink = logger ?? defaultRealtimeSink;
291
+ sink.warn?.(`[codem][core-stderr][pid=${pid ?? "unknown"}] ${safe}`);
292
+ } catch { /* Forwarding child stderr must never fail the host. */ }
293
+ }
294
+
184
295
  function keepLegacyMetric(event, fields, role, severity) {
296
+ if (REALTIME_LOG_ONLY.has(event)) return false;
185
297
  if (/^startup\.(?:main|update_check|daemon_service_reconcile|login_gate|login_handoff_to_linco)$/u.test(event) && severity === "info") return false;
186
298
  if (/(?:^|\.)drain_(?:started|completed)$/u.test(event) && severity === "info") return false;
187
299
  if (role === "daemon" && event === "runtime_capability_probe" && severity === "info") return false;
@@ -215,6 +327,7 @@ export class RuntimeLogReporter {
215
327
  #live = { queue: [], inflight: undefined, abort: undefined };
216
328
  #replay = { queue: [], inflight: undefined, abort: undefined };
217
329
  #identity = {};
330
+ #resourceContext = {};
218
331
  #timer;
219
332
  #closed = false;
220
333
  #dropped = 0;
@@ -233,10 +346,11 @@ export class RuntimeLogReporter {
233
346
  #restoring;
234
347
  #savedDuringRestore = new Set();
235
348
 
236
- constructor({ role = "cli", version = "unknown", send = sendSlardarPcBatch, instanceId = randomUUID(), diagnosticId: supportId = diagnosticId(), platform = process.platform, osVersion = os.release(), crashDirectory } = {}) {
349
+ constructor({ role = "cli", version = "unknown", env = process.env, send = sendSlardarPcBatch, instanceId = randomUUID(), diagnosticId: supportId = diagnosticId(), platform = process.platform, osVersion = os.release(), crashDirectory } = {}) {
237
350
  this.#send = send;
238
351
  this.#crashDirectory = crashDirectory;
239
352
  this.#role = token(role) ?? "cli";
353
+ this.#resourceContext = sandboxObservationContext(env, role);
240
354
  this.#version = token(version) ?? "unknown";
241
355
  this.#instanceId = instanceId;
242
356
  this.#diagnosticId = supportId;
@@ -264,9 +378,12 @@ export class RuntimeLogReporter {
264
378
  if (!this.#crashDirectory) return;
265
379
  try {
266
380
  fs.mkdirSync(this.#crashDirectory, { recursive: true, mode: 0o700 });
267
- const names = fs.readdirSync(this.#crashDirectory).filter(name => /^js-[a-f0-9-]+\.json$/u.test(name));
268
- if (names.length >= 32) return;
269
- const name = `js-${randomUUID()}.json`;
381
+ const migration = entry.record.log_type === "flexible";
382
+ const prefix = migration ? "js-migration-" : "js-";
383
+ const pattern = migration ? /^js-migration-[a-f0-9-]+\.json$/u : /^js-[a-f0-9-]+\.json$/u;
384
+ const names = fs.readdirSync(this.#crashDirectory).filter(name => pattern.test(name));
385
+ if (names.length >= (migration ? 64 : 32)) return;
386
+ const name = `${prefix}${randomUUID()}.json`;
270
387
  const file = path.join(this.#crashDirectory, name);
271
388
  fs.writeFileSync(file, JSON.stringify(entry), { flag: "wx", mode: 0o600 });
272
389
  this.#savedDuringRestore?.add(name);
@@ -277,7 +394,10 @@ export class RuntimeLogReporter {
277
394
  async #restoreCrashes() {
278
395
  if (!this.#crashDirectory) return;
279
396
  try {
280
- for (const name of (await fs.promises.readdir(this.#crashDirectory)).filter(name => /^js-[a-f0-9-]+\.json$/u.test(name)).slice(0, 32)) {
397
+ const names = await fs.promises.readdir(this.#crashDirectory);
398
+ const crashes = names.filter(name => /^js-[a-f0-9-]+\.json$/u.test(name)).slice(0, 32);
399
+ const migrations = names.filter(name => /^js-migration-[a-f0-9-]+\.json$/u.test(name)).slice(0, 64);
400
+ for (const name of [...crashes, ...migrations]) {
281
401
  if (this.#closed) return;
282
402
  if (this.#savedDuringRestore?.has(name)) continue;
283
403
  const file = path.join(this.#crashDirectory, name);
@@ -285,8 +405,13 @@ export class RuntimeLogReporter {
285
405
  const stat = await fs.promises.lstat(file);
286
406
  if (!stat.isFile() || stat.size > 65536) continue;
287
407
  const entry = JSON.parse(await fs.promises.readFile(file, "utf8"));
288
- if (entry?.record?.category?.reporter !== "codem_js" || entry?.record?.log_type !== "log" || !entry.header) continue;
408
+ if (entry?.record?.category?.reporter !== "codem_js" || !entry.header) continue;
289
409
  if (this.#closed) return;
410
+ if (entry.record.log_type === "flexible" && entry.record.event_name?.startsWith("runtime.shared_migration.")) {
411
+ this.#replay.queue.push({ header: entry.header, record: entry.record, metricName: null, attempts: 0, crashFile: file });
412
+ continue;
413
+ }
414
+ if (entry.record.log_type !== "log") continue;
290
415
  if (entry.metricName === LIFECYCLE_EVENT_NAME) {
291
416
  entry.record.category.replay = "1";
292
417
  this.#replay.queue.push({ ...entry, attempts: 0, crashFile: file });
@@ -318,7 +443,37 @@ export class RuntimeLogReporter {
318
443
 
319
444
  get pendingCount() { return this.#live.queue.length + this.#replay.queue.length; }
320
445
  get droppedCount() { return this.#dropped; }
321
- get identityKey() { return JSON.stringify([this.#instanceId, this.#role, this.#identity.deviceId, this.#identity.userId, this.#identity.tenantId]); }
446
+
447
+ #header() {
448
+ const identity = this.#identity;
449
+ return { aid: SLARDAR_PC_AID, device_id: identity.deviceId ?? this.#instanceId,
450
+ user_id: identity.userId ?? "0", parfait_version: SLARDAR_PC_REPORTER_VERSION,
451
+ channel: identity.channel ?? "unknown", os: this.#platform, os_version: this.#osVersion };
452
+ }
453
+
454
+ recordMetric(name, category, metrics, { persist = false } = {}) {
455
+ if (this.#closed) return false;
456
+ if (this.#live.queue.length >= CAPACITY) {
457
+ this.#dropped += 1;
458
+ return false;
459
+ }
460
+ const identity = this.#identity;
461
+ const record = {
462
+ app_version: this.#version, app_minor_version: "", build_id: "",
463
+ process_type: `codem-${this.#role}`, session_id: "", timestamp: Date.now(),
464
+ log_type: "flexible", event_name: name,
465
+ category: { reporter: "codem_js", runtime_role: this.#role,
466
+ ...(identity.tenantId ? { tenant_id: identity.tenantId } : {}), ...category },
467
+ metrics
468
+ };
469
+ const entry = { header: this.#header(), record, metricName: null, attempts: 0 };
470
+ if (persist) this.#saveCrash(entry);
471
+ this.#live.queue.push(entry);
472
+ // Bursts need not wait for the periodic timer, and a slow collector still
473
+ // has only one bounded in-flight upload.
474
+ if (this.#live.queue.length >= BATCH_SIZE) void this.#flushLane(this.#live, REQUEST_TIMEOUT_MS);
475
+ return true;
476
+ }
322
477
 
323
478
  record(level, component, event, fields = {}) {
324
479
  try {
@@ -329,13 +484,17 @@ export class RuntimeLogReporter {
329
484
 
330
485
  #logEntry(level, component, event, fields) {
331
486
  let safeFields;
332
- try { safeFields = projectFields(fields); } catch { safeFields = {}; }
487
+ try { safeFields = projectFields(fields, true, component); } catch { safeFields = {}; }
333
488
  if (OBSERVATION_EVENTS.has(event)) safeFields.observation_id = randomUUID();
334
489
  const severity = ["info", "warn", "error", "fatal"].includes(level) ? level : "info";
335
490
  // Keep arbitrary upstream error codes out of trusted-device metric dimensions.
336
491
  const trustedDevice = TRUSTED_DEVICE_EVENTS.has(event);
337
492
  const dimensions = trustedDevice ? {} : Object.fromEntries(["stage", "error_class", "error_code", "error_kind", "outcome"]
338
493
  .filter(key => safeFields[key]).map(key => [key, safeFields[key]]));
494
+ if (UPLINK_DIAGNOSTIC_METRICS.has(event)) {
495
+ if (safeFields.lane) dimensions.lane = safeFields.lane;
496
+ if (safeFields.target_kind) dimensions.target_kind = safeFields.target_kind;
497
+ }
339
498
  if (OBSERVATION_EVENTS.has(event)) {
340
499
  for (const [key, values] of Object.entries(trustedDevice ? TRUSTED_DEVICE_DIMENSIONS : OBSERVATION_DIMENSIONS)) {
341
500
  if (safeFields[key]) dimensions[key] = values.includes(safeFields[key]) ? safeFields[key] : "unknown";
@@ -397,6 +556,7 @@ export class RuntimeLogReporter {
397
556
  }
398
557
 
399
558
  #entry(severity, component, event, safeFields, identity, dimensions, includeLog) {
559
+ safeFields = { ...this.#resourceContext, ...safeFields, ...(this.#resourceContext.resource_id ? { resource_id: this.#resourceContext.resource_id } : {}) };
400
560
  const category = {
401
561
  ...workerRuntimeAttributes(),
402
562
  client_kind: "cli", runtime_role: this.#role, reporter: "codem_js", log_schema: "1",
@@ -567,9 +727,9 @@ export function runtimeLogIdentityKey() { return active?.identityKey; }
567
727
 
568
728
  export function startRuntimeLogs({ role, version, env = process.env, send } = {}) {
569
729
  try {
570
- if (active || /^(1|true|yes)$/iu.test(env.CODEM_TELEMETRY_DISABLED ?? "") || env.NODE_TEST_CONTEXT) return;
730
+ if (active || !sandboxLogUploadAllowed(env, role) || /^(1|true|yes)$/iu.test(env.CODEM_TELEMETRY_DISABLED ?? "") || env.NODE_TEST_CONTEXT) return;
571
731
  const root = env.CODEM_HOME || env.LINCO_HOME || path.join(os.homedir(), ".codem");
572
- active = new RuntimeLogReporter({ role, version, send, crashDirectory: path.join(root, "runtime-crashes") });
732
+ active = new RuntimeLogReporter({ role, version, env, send, crashDirectory: path.join(root, "runtime-crashes") });
573
733
  } catch { /* Monitoring initialization never prevents a command from running. */ }
574
734
  }
575
735
 
@@ -595,6 +755,10 @@ export function flushRuntimeLogsInBackground() {
595
755
  if (active) setImmediate(() => { void active?.flush().catch(() => {}); }).unref?.();
596
756
  }
597
757
 
758
+ export function recordRuntimeMetric(name, category, metrics, options) {
759
+ try { return active?.recordMetric(name, category, metrics, options) ?? false; } catch { return false; }
760
+ }
761
+
598
762
  export function persistRuntimeCrash(component, event, fields) {
599
763
  try { active?.persistCrash(component, event, fields); } catch { /* best effort */ }
600
764
  }
@@ -654,9 +818,9 @@ export function recordInteractiveProcessExit({ exitCode, signal }) {
654
818
  export function recordSelectedRuntimeLog(component, event, fields = {}) {
655
819
  try {
656
820
  const selectedEvent = event.replace(/^linco\./u, "");
657
- if (!/^(?:startup\.(?:main|update_check|daemon_service_reconcile|login_gate|login_handoff_to_linco)|oauth\.refresh\.(?:relogin_suspect|persist_failed|persisted)|managed_config\.(?:member_refresh_failed|sandbox_refresh_failed|sandbox_fetch_recovered|sandbox_fetch_exhausted|refreshed|resource_failed)|(?:agent|command)\.(?:start|interactive_start|success|error|spawn_error|resolve_error|exit_drain_timeout|cancelled_before_spawn|artifact_oversize|artifact_missing|artifact_dropped|artifact_route_selected|artifact_image_upload|artifact_file_upload|artifact_local_register)|router\.credentials\.(?:ensured|refresh_failed)|config-lock\.release_failed|binary\.heal_chmod_failed|project\.(?:inject_error|state)|(?:permission_ask|user_question|plan)\.report_failed|process_tree\.(?:force_kill|force_kill_failed)|artifact\.(?:oversize|missing|dropped)|runtime_post\.daemon\.device_rebind_[a-z_]+)$/u.test(selectedEvent)) return;
821
+ 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;
658
822
  const expected = optional(() => fields?.errorKind === "user_stop" || fields?.terminalError?.kind === "user_stop" || fields?.exitCode === 130 || fields?.signal === "SIGINT");
659
- const level = expected ? "info" : (fields?.status === "failed" || /(?:failed|error|exhausted|timeout)$/u.test(event)) ? "error" : /(?:suspect|dropped|missing|oversize)$/u.test(event) ? "warn" : "info";
823
+ 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";
660
824
  recordRuntimeLog(level, component, event, fields);
661
825
  } catch { /* best effort */ }
662
826
  }
@@ -0,0 +1,17 @@
1
+ // Server-resolved sandbox policy and correlation. These values never select an
2
+ // upload destination, authenticate a caller, or alter personal-device logging.
3
+ export function sandboxObservationContext(env = process.env, role) {
4
+ if (env.CODEM_SANDBOX_VERSION !== "resource") return {};
5
+ const fields = {};
6
+ for (const [name, key] of [["CODEM_RESOURCE_ID", "resource_id"], ["CODEM_RESOURCE_ENV", "resource_env"], ["CODEM_RESOURCE_OPERATION_ID", "operation_id"]]) {
7
+ const value = env[name];
8
+ if (typeof value === "string" && /^[A-Za-z0-9_.:-]{1,160}$/u.test(value)) fields[key] = value;
9
+ }
10
+ return fields;
11
+ }
12
+
13
+ export function sandboxLogUploadAllowed(env = process.env, role) {
14
+ const sandbox = role === "sandbox" || env.CODEM_SANDBOX_VERSION === "resource" || env.CODEM_SESSION_SOURCE === "sandbox";
15
+ const policy = env.CODEM_SANDBOX_LOG_UPLOAD_ENABLED;
16
+ return !sandbox || policy === undefined || policy === "1";
17
+ }