@lark-codem/codem-cli 0.1.281-dev.100104590539.0.gd9b8134 → 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.
- package/auth/index.d.ts +19 -0
- package/auth/index.js +5911 -0
- package/bin/codem-startup-logs.js +127 -0
- package/bin/codem.js +107 -30
- package/bin/slardar-pc-transport.js +42 -0
- package/bin/tt-env.js +1 -1
- package/bin/worker-runtime-telemetry.js +2 -1
- package/package.json +12 -9
- package/profile/credential-errors.js +1 -2
- package/profile/profile-snapshot.js +2 -1
- package/profile/realtime-log-id.js +9 -0
- package/profile/runtime-logs.js +184 -18
- package/profile/sandbox-observability.js +17 -0
package/profile/runtime-logs.js
CHANGED
|
@@ -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";
|
|
@@ -78,26 +80,46 @@ const OBSERVATION_METRICS = {
|
|
|
78
80
|
};
|
|
79
81
|
const EXTRA_FIELDS = ["observation_id", "runtime_client_instance_id", "command_id", "delivery_id", "probe_id", "sync_id", "transport_request_id", "attempt_id"];
|
|
80
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
|
+
]);
|
|
81
92
|
const STRING_FIELDS = new Set([
|
|
82
|
-
|
|
83
|
-
"
|
|
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",
|
|
84
96
|
"process_instance_id", "run_id", "stage", "phase", "status", "outcome", "reason", "action",
|
|
85
97
|
"error_class", "error_code", "error_kind", "error_type", "code", "signal", "stop_reason",
|
|
86
98
|
"first_error", "retry_source", "cleanup_result",
|
|
87
99
|
"terminal_event", "event_type", "actor_type", "source", "trigger", "hook_id", "hook_event",
|
|
88
100
|
"target_version", "cli_version", "core_version", "version", "previous_state", "state",
|
|
89
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",
|
|
90
|
-
"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"
|
|
91
108
|
]);
|
|
92
109
|
const VALUE_FIELDS = new Set([
|
|
93
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",
|
|
94
112
|
...new Set(Object.values(OBSERVATION_METRICS).flat()),
|
|
95
113
|
"pid", "exit_code", "duration_ms", "elapsed_ms", "wait_ms", "run_ms", "total_ms", "took_ms",
|
|
96
114
|
"attempt", "attempts", "attempt_count", "retryable", "http_status", "errno", "active_task_count",
|
|
97
115
|
"pending_event_count", "pending_command_ack_count", "next_retry_ms", "consecutive_failures",
|
|
116
|
+
...Array.from(UPLINK_DIAGNOSTIC_METRICS.values()).flat(), "transport_open",
|
|
98
117
|
"outage_duration_ms", "startup_duration_ms", "failed_attempts", "active_runs", "completed",
|
|
99
118
|
"delivered", "result_delivered", "queued_behind_existing", "expected", "timed_out",
|
|
100
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",
|
|
101
123
|
...LIFECYCLE_METRICS
|
|
102
124
|
]);
|
|
103
125
|
|
|
@@ -115,7 +137,7 @@ function optional(read) {
|
|
|
115
137
|
}
|
|
116
138
|
|
|
117
139
|
function metricProjection(event, fields = {}) {
|
|
118
|
-
return { count: 1, ...Object.fromEntries((OBSERVATION_METRICS[event] ?? [])
|
|
140
|
+
return { count: 1, ...Object.fromEntries((OBSERVATION_METRICS[event] ?? UPLINK_DIAGNOSTIC_METRICS.get(event) ?? [])
|
|
119
141
|
.filter(key => typeof fields?.[key] === "number" && Number.isFinite(fields[key]) && fields[key] >= 0)
|
|
120
142
|
.map(key => [key, fields[key]])) };
|
|
121
143
|
}
|
|
@@ -124,11 +146,18 @@ function extraProjection(fields = {}) {
|
|
|
124
146
|
return Object.fromEntries(EXTRA_FIELDS.filter(key => token(fields?.[key])).map(key => [key, token(fields[key])]));
|
|
125
147
|
}
|
|
126
148
|
|
|
127
|
-
|
|
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) {
|
|
128
152
|
const result = {};
|
|
129
153
|
for (const [key, value] of Object.entries(input ?? {}).slice(0, 100)) {
|
|
130
154
|
const name = fieldName(key);
|
|
131
|
-
if (
|
|
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)) {
|
|
132
161
|
const safe = token(value);
|
|
133
162
|
if (safe) result[name] = safe;
|
|
134
163
|
} else if (VALUE_FIELDS.has(name) && (typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value)))) {
|
|
@@ -179,7 +208,92 @@ function lifecycleErrorCode(fields) {
|
|
|
179
208
|
return fields.outcome === "failed" || fields.outcome === "rejected" || fields.outcome === "conflicting" ? "unknown" : undefined;
|
|
180
209
|
}
|
|
181
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
|
+
|
|
182
295
|
function keepLegacyMetric(event, fields, role, severity) {
|
|
296
|
+
if (REALTIME_LOG_ONLY.has(event)) return false;
|
|
183
297
|
if (/^startup\.(?:main|update_check|daemon_service_reconcile|login_gate|login_handoff_to_linco)$/u.test(event) && severity === "info") return false;
|
|
184
298
|
if (/(?:^|\.)drain_(?:started|completed)$/u.test(event) && severity === "info") return false;
|
|
185
299
|
if (role === "daemon" && event === "runtime_capability_probe" && severity === "info") return false;
|
|
@@ -213,6 +327,7 @@ export class RuntimeLogReporter {
|
|
|
213
327
|
#live = { queue: [], inflight: undefined, abort: undefined };
|
|
214
328
|
#replay = { queue: [], inflight: undefined, abort: undefined };
|
|
215
329
|
#identity = {};
|
|
330
|
+
#resourceContext = {};
|
|
216
331
|
#timer;
|
|
217
332
|
#closed = false;
|
|
218
333
|
#dropped = 0;
|
|
@@ -231,10 +346,11 @@ export class RuntimeLogReporter {
|
|
|
231
346
|
#restoring;
|
|
232
347
|
#savedDuringRestore = new Set();
|
|
233
348
|
|
|
234
|
-
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 } = {}) {
|
|
235
350
|
this.#send = send;
|
|
236
351
|
this.#crashDirectory = crashDirectory;
|
|
237
352
|
this.#role = token(role) ?? "cli";
|
|
353
|
+
this.#resourceContext = sandboxObservationContext(env, role);
|
|
238
354
|
this.#version = token(version) ?? "unknown";
|
|
239
355
|
this.#instanceId = instanceId;
|
|
240
356
|
this.#diagnosticId = supportId;
|
|
@@ -262,9 +378,12 @@ export class RuntimeLogReporter {
|
|
|
262
378
|
if (!this.#crashDirectory) return;
|
|
263
379
|
try {
|
|
264
380
|
fs.mkdirSync(this.#crashDirectory, { recursive: true, mode: 0o700 });
|
|
265
|
-
const
|
|
266
|
-
|
|
267
|
-
const
|
|
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`;
|
|
268
387
|
const file = path.join(this.#crashDirectory, name);
|
|
269
388
|
fs.writeFileSync(file, JSON.stringify(entry), { flag: "wx", mode: 0o600 });
|
|
270
389
|
this.#savedDuringRestore?.add(name);
|
|
@@ -275,7 +394,10 @@ export class RuntimeLogReporter {
|
|
|
275
394
|
async #restoreCrashes() {
|
|
276
395
|
if (!this.#crashDirectory) return;
|
|
277
396
|
try {
|
|
278
|
-
|
|
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]) {
|
|
279
401
|
if (this.#closed) return;
|
|
280
402
|
if (this.#savedDuringRestore?.has(name)) continue;
|
|
281
403
|
const file = path.join(this.#crashDirectory, name);
|
|
@@ -283,8 +405,13 @@ export class RuntimeLogReporter {
|
|
|
283
405
|
const stat = await fs.promises.lstat(file);
|
|
284
406
|
if (!stat.isFile() || stat.size > 65536) continue;
|
|
285
407
|
const entry = JSON.parse(await fs.promises.readFile(file, "utf8"));
|
|
286
|
-
if (entry?.record?.category?.reporter !== "codem_js" ||
|
|
408
|
+
if (entry?.record?.category?.reporter !== "codem_js" || !entry.header) continue;
|
|
287
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;
|
|
288
415
|
if (entry.metricName === LIFECYCLE_EVENT_NAME) {
|
|
289
416
|
entry.record.category.replay = "1";
|
|
290
417
|
this.#replay.queue.push({ ...entry, attempts: 0, crashFile: file });
|
|
@@ -316,7 +443,37 @@ export class RuntimeLogReporter {
|
|
|
316
443
|
|
|
317
444
|
get pendingCount() { return this.#live.queue.length + this.#replay.queue.length; }
|
|
318
445
|
get droppedCount() { return this.#dropped; }
|
|
319
|
-
|
|
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
|
+
}
|
|
320
477
|
|
|
321
478
|
record(level, component, event, fields = {}) {
|
|
322
479
|
try {
|
|
@@ -327,13 +484,17 @@ export class RuntimeLogReporter {
|
|
|
327
484
|
|
|
328
485
|
#logEntry(level, component, event, fields) {
|
|
329
486
|
let safeFields;
|
|
330
|
-
try { safeFields = projectFields(fields); } catch { safeFields = {}; }
|
|
487
|
+
try { safeFields = projectFields(fields, true, component); } catch { safeFields = {}; }
|
|
331
488
|
if (OBSERVATION_EVENTS.has(event)) safeFields.observation_id = randomUUID();
|
|
332
489
|
const severity = ["info", "warn", "error", "fatal"].includes(level) ? level : "info";
|
|
333
490
|
// Keep arbitrary upstream error codes out of trusted-device metric dimensions.
|
|
334
491
|
const trustedDevice = TRUSTED_DEVICE_EVENTS.has(event);
|
|
335
492
|
const dimensions = trustedDevice ? {} : Object.fromEntries(["stage", "error_class", "error_code", "error_kind", "outcome"]
|
|
336
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
|
+
}
|
|
337
498
|
if (OBSERVATION_EVENTS.has(event)) {
|
|
338
499
|
for (const [key, values] of Object.entries(trustedDevice ? TRUSTED_DEVICE_DIMENSIONS : OBSERVATION_DIMENSIONS)) {
|
|
339
500
|
if (safeFields[key]) dimensions[key] = values.includes(safeFields[key]) ? safeFields[key] : "unknown";
|
|
@@ -395,6 +556,7 @@ export class RuntimeLogReporter {
|
|
|
395
556
|
}
|
|
396
557
|
|
|
397
558
|
#entry(severity, component, event, safeFields, identity, dimensions, includeLog) {
|
|
559
|
+
safeFields = { ...this.#resourceContext, ...safeFields, ...(this.#resourceContext.resource_id ? { resource_id: this.#resourceContext.resource_id } : {}) };
|
|
398
560
|
const category = {
|
|
399
561
|
...workerRuntimeAttributes(),
|
|
400
562
|
client_kind: "cli", runtime_role: this.#role, reporter: "codem_js", log_schema: "1",
|
|
@@ -565,9 +727,9 @@ export function runtimeLogIdentityKey() { return active?.identityKey; }
|
|
|
565
727
|
|
|
566
728
|
export function startRuntimeLogs({ role, version, env = process.env, send } = {}) {
|
|
567
729
|
try {
|
|
568
|
-
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;
|
|
569
731
|
const root = env.CODEM_HOME || env.LINCO_HOME || path.join(os.homedir(), ".codem");
|
|
570
|
-
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") });
|
|
571
733
|
} catch { /* Monitoring initialization never prevents a command from running. */ }
|
|
572
734
|
}
|
|
573
735
|
|
|
@@ -593,6 +755,10 @@ export function flushRuntimeLogsInBackground() {
|
|
|
593
755
|
if (active) setImmediate(() => { void active?.flush().catch(() => {}); }).unref?.();
|
|
594
756
|
}
|
|
595
757
|
|
|
758
|
+
export function recordRuntimeMetric(name, category, metrics, options) {
|
|
759
|
+
try { return active?.recordMetric(name, category, metrics, options) ?? false; } catch { return false; }
|
|
760
|
+
}
|
|
761
|
+
|
|
596
762
|
export function persistRuntimeCrash(component, event, fields) {
|
|
597
763
|
try { active?.persistCrash(component, event, fields); } catch { /* best effort */ }
|
|
598
764
|
}
|
|
@@ -652,9 +818,9 @@ export function recordInteractiveProcessExit({ exitCode, signal }) {
|
|
|
652
818
|
export function recordSelectedRuntimeLog(component, event, fields = {}) {
|
|
653
819
|
try {
|
|
654
820
|
const selectedEvent = event.replace(/^linco\./u, "");
|
|
655
|
-
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;
|
|
656
822
|
const expected = optional(() => fields?.errorKind === "user_stop" || fields?.terminalError?.kind === "user_stop" || fields?.exitCode === 130 || fields?.signal === "SIGINT");
|
|
657
|
-
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";
|
|
658
824
|
recordRuntimeLog(level, component, event, fields);
|
|
659
825
|
} catch { /* best effort */ }
|
|
660
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
|
+
}
|