@lark-codem/codem-cli 0.1.281-dev.100104531322.0.g35e0932 → 0.1.281-dev.100104534209.0.gf5d08a3
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 +5896 -0
- package/bin/codem-startup-logs.js +127 -0
- 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 +11 -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 +166 -13
- package/profile/sandbox-observability.js +17 -0
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Image bootstrap's dedicated input. Never pipe business stdout/stderr here.
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { sendSlardarPcBatch } from "./slardar-pc-transport.js";
|
|
8
|
+
|
|
9
|
+
const id = value => typeof value === "string" && /^[a-z\d._:-]{1,128}$/iu.test(value) ? value : undefined;
|
|
10
|
+
const FIELDS = ["resource_id", "resource_env", "operation_id", "stage", "outcome", "startup_id", "controller_id", "logical_sandbox_id", "sandbox_id", "dispatch_id", "request_id", "tenant_id", "tenant_key"];
|
|
11
|
+
const NUMBERS = ["exit_code", "errno", "http_status", "duration_ms"];
|
|
12
|
+
|
|
13
|
+
export function createStartupLogger({ component, startupId, identity = {}, env = process.env, version = "unknown", send = sendSlardarPcBatch } = {}) {
|
|
14
|
+
const processId = randomUUID();
|
|
15
|
+
const startup = id(startupId ?? env.CODEM_STARTUP_ID) ?? processId;
|
|
16
|
+
const source = id(component ?? env.CODEM_LOG_COMPONENT) ?? "sandbox-bootstrap";
|
|
17
|
+
const fields = {
|
|
18
|
+
startup_id: startup,
|
|
19
|
+
...(env.CODEM_SANDBOX_VERSION === "resource" ? { resource_id: id(env.CODEM_RESOURCE_ID), resource_env: id(env.CODEM_RESOURCE_ENV), operation_id: id(env.CODEM_RESOURCE_OPERATION_ID) } : {}),
|
|
20
|
+
controller_id: id(identity.controllerId ?? env.CODEM_SANDBOX_CONTROLLER_ID),
|
|
21
|
+
logical_sandbox_id: id(identity.logicalSandboxId ?? env.CODEM_SANDBOX_LOGICAL_SANDBOX_ID),
|
|
22
|
+
sandbox_id: id(identity.sandboxId ?? env.CODEM_SANDBOX_DEVICE_ID),
|
|
23
|
+
dispatch_id: id(identity.dispatchId ?? env.CODEM_SANDBOX_DISPATCH_ID),
|
|
24
|
+
tenant_id: id(identity.tenantId ?? env.CODEM_SANDBOX_TENANT_ID),
|
|
25
|
+
tenant_key: id(identity.tenantKey ?? env.CODEM_SANDBOX_TENANT_KEY)
|
|
26
|
+
};
|
|
27
|
+
const header = {
|
|
28
|
+
aid: "1880", device_id: id(identity.deviceId ?? env.CODEM_SANDBOX_DEVICE_ID) ?? processId, user_id: "0",
|
|
29
|
+
parfait_version: "1.0.0.0", channel: "unknown", os: process.platform === "win32" ? "Windows" : process.platform === "darwin" ? "Mac OS X" : process.platform, os_version: os.release()
|
|
30
|
+
};
|
|
31
|
+
const queue = [];
|
|
32
|
+
let closed = env.CODEM_SANDBOX_LOG_UPLOAD_ENABLED !== "1" || /^(1|true|yes)$/iu.test(env.CODEM_TELEMETRY_DISABLED ?? "");
|
|
33
|
+
let inflight;
|
|
34
|
+
let dropped = 0;
|
|
35
|
+
let uploadFailures = 0;
|
|
36
|
+
let activeController;
|
|
37
|
+
const timer = setInterval(() => { void flush(); }, 10_000);
|
|
38
|
+
timer.unref();
|
|
39
|
+
|
|
40
|
+
function log(level, message, context = {}, timestamp = Date.now()) {
|
|
41
|
+
try {
|
|
42
|
+
if (closed || !["info", "warn", "error", "fatal"].includes(level)) return false;
|
|
43
|
+
const safe = { ...fields };
|
|
44
|
+
for (const key of FIELDS) if (id(context[key])) safe[key] = context[key];
|
|
45
|
+
for (const key of NUMBERS) if (Number.isFinite(context[key])) safe[key] = context[key];
|
|
46
|
+
const event = message === "sandbox bootstrap" ? "sandbox.bootstrap" : undefined;
|
|
47
|
+
if (!event) return false;
|
|
48
|
+
const entry = { level, event, fields: safe,
|
|
49
|
+
timestamp: Number.isSafeInteger(timestamp) && timestamp >= 0 ? timestamp : Date.now(), observationId: randomUUID() };
|
|
50
|
+
if (queue.length >= 256) { queue.shift(); dropped++; }
|
|
51
|
+
queue.push(entry);
|
|
52
|
+
return true;
|
|
53
|
+
} catch { dropped++; return false; }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function flush({ timeoutMs = 3000 } = {}) {
|
|
57
|
+
if (inflight) return inflight;
|
|
58
|
+
if (closed || queue.length === 0) return Promise.resolve();
|
|
59
|
+
inflight = drain(timeoutMs).finally(() => { inflight = undefined; });
|
|
60
|
+
return inflight;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function drain(timeoutMs) {
|
|
64
|
+
const controller = new AbortController();
|
|
65
|
+
activeController = controller;
|
|
66
|
+
let timeout;
|
|
67
|
+
const expired = new Promise((_, reject) => {
|
|
68
|
+
// stdin (or the one EOF deadline below) owns this helper's lifetime.
|
|
69
|
+
// A previous background upload must not extend the short EOF budget.
|
|
70
|
+
timeout = setTimeout(() => { controller.abort(); reject(new Error("upload timeout")); }, timeoutMs);
|
|
71
|
+
timeout.unref();
|
|
72
|
+
});
|
|
73
|
+
try {
|
|
74
|
+
while (!closed && queue.length && !controller.signal.aborted) {
|
|
75
|
+
const batch = queue.splice(0, 8);
|
|
76
|
+
const data = batch.map(entry => ({
|
|
77
|
+
app_version: version, app_minor_version: "", build_id: "", process_type: "codem-sandbox-bootstrap", session_id: "",
|
|
78
|
+
timestamp: entry.timestamp, log_type: "log", log_level: entry.level === "fatal" ? "error" : entry.level,
|
|
79
|
+
category: { reporter: "codem_bootstrap", runtime_role: "sandbox", component: source, event: "application.log", severity: entry.level,
|
|
80
|
+
...(fields.resource_env ? { resource_env: fields.resource_env } : {}),
|
|
81
|
+
...(id(env.CODEM_SANDBOX_TYPE) ? { sandbox_type: env.CODEM_SANDBOX_TYPE } : {}),
|
|
82
|
+
...(fields.tenant_id ? { tenant_id: fields.tenant_id } : {}) },
|
|
83
|
+
log_content: `${entry.event}\n${JSON.stringify({ schema_version: 1, timestamp: entry.timestamp,
|
|
84
|
+
process_instance_id: processId, fields: { ...entry.fields, observation_id: entry.observationId } })}`
|
|
85
|
+
}));
|
|
86
|
+
try { await Promise.race([send({ header, data }, { signal: controller.signal }), expired]); }
|
|
87
|
+
catch { uploadFailures++; dropped += batch.length; break; }
|
|
88
|
+
}
|
|
89
|
+
} catch { uploadFailures++; }
|
|
90
|
+
finally { clearTimeout(timeout); activeController = undefined; }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return { log, flush, get pendingCount() { return queue.length; }, get droppedCount() { return dropped; },
|
|
94
|
+
get uploadFailureCount() { return uploadFailures; },
|
|
95
|
+
close() { closed = true; clearInterval(timer); activeController?.abort(); dropped += queue.length; queue.length = 0; } };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export async function runStartupLogInput({ input = process.stdin, ...options } = {}) {
|
|
99
|
+
const logger = createStartupLogger(options);
|
|
100
|
+
let pending = "";
|
|
101
|
+
// A dedicated pipe with bounded records. Oversized/malformed input is dropped;
|
|
102
|
+
// it cannot cause an unbounded readline allocation or affect the caller.
|
|
103
|
+
input.setEncoding("utf8");
|
|
104
|
+
input.on("data", chunk => {
|
|
105
|
+
pending += chunk;
|
|
106
|
+
let end;
|
|
107
|
+
while ((end = pending.indexOf("\n")) >= 0) {
|
|
108
|
+
const line = pending.slice(0, end);
|
|
109
|
+
pending = pending.slice(end + 1);
|
|
110
|
+
if (line.length > 8192) continue;
|
|
111
|
+
try {
|
|
112
|
+
const row = JSON.parse(line);
|
|
113
|
+
if (row && typeof row.message === "string") logger.log(row.level, row.message, row.fields, row.timestamp);
|
|
114
|
+
} catch { /* The pipe is optional diagnostic input. */ }
|
|
115
|
+
}
|
|
116
|
+
if (pending.length > 8192) pending = "";
|
|
117
|
+
});
|
|
118
|
+
await new Promise(resolve => { input.once("end", resolve); input.once("error", resolve); });
|
|
119
|
+
let deadline;
|
|
120
|
+
await Promise.race([logger.flush({ timeoutMs: 200 }), new Promise(resolve => { deadline = setTimeout(resolve, 200); })]);
|
|
121
|
+
clearTimeout(deadline);
|
|
122
|
+
logger.close();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
126
|
+
runStartupLogInput().catch(() => {});
|
|
127
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import https from "node:https";
|
|
2
|
+
import { gzip } from "node:zlib";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
|
|
5
|
+
// PC Custom Log / Custom Event wire format, verified against Parfait 1.7.0.0's
|
|
6
|
+
// public IUploader callback. This is not the Slardar Web/BID protocol. Keep the
|
|
7
|
+
// SDK capture fixture and the platform readback procedure with this adapter.
|
|
8
|
+
export const SLARDAR_PC_AID = "1880";
|
|
9
|
+
// Use the native envelope's four-part version convention in this legacy field.
|
|
10
|
+
// This is our JS adapter version; reporter=codem_js distinguishes it
|
|
11
|
+
// from the native Parfait SDK. Do not advertise a native SDK we do not run.
|
|
12
|
+
export const SLARDAR_PC_REPORTER_VERSION = "1.0.0.0";
|
|
13
|
+
const ENDPOINT = `https://pc-mon.zijieapi.com/monitor_pc/collect/api/pc_log?aid=${SLARDAR_PC_AID}`;
|
|
14
|
+
const compress = promisify(gzip);
|
|
15
|
+
|
|
16
|
+
export async function sendSlardarPcBatch(payload, { signal, request = https.request } = {}) {
|
|
17
|
+
signal?.throwIfAborted();
|
|
18
|
+
const body = await compress(Buffer.from(JSON.stringify(payload)));
|
|
19
|
+
signal?.throwIfAborted();
|
|
20
|
+
return new Promise((resolve, reject) => {
|
|
21
|
+
const req = request(ENDPOINT, {
|
|
22
|
+
method: "POST",
|
|
23
|
+
signal,
|
|
24
|
+
headers: {
|
|
25
|
+
"content-type": "application/json",
|
|
26
|
+
"content-encoding": "gzip",
|
|
27
|
+
"content-length": body.length
|
|
28
|
+
}
|
|
29
|
+
}, (res) => {
|
|
30
|
+
// The collector returns an empty 204. Never buffer arbitrary responses.
|
|
31
|
+
res.resume();
|
|
32
|
+
res.once("error", reject);
|
|
33
|
+
res.once("end", () => {
|
|
34
|
+
if (res.statusCode >= 200 && res.statusCode < 300) resolve();
|
|
35
|
+
else reject(new Error(`Slardar PC HTTP ${res.statusCode}`));
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
req.on("socket", (socket) => socket.unref?.());
|
|
39
|
+
req.once("error", reject);
|
|
40
|
+
req.end(body);
|
|
41
|
+
});
|
|
42
|
+
}
|
package/bin/tt-env.js
CHANGED
|
@@ -58,7 +58,7 @@ export function resolveTtEnvLane(env = process.env) {
|
|
|
58
58
|
return parseTtEnvLane(env?.[CODEM_X_TT_ENV]);
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
-
function isOfficialCodemHost(hostname) {
|
|
61
|
+
export function isOfficialCodemHost(hostname) {
|
|
62
62
|
const host = hostname.toLowerCase();
|
|
63
63
|
return host === PROD_ROUTER_HOST || host === BOE_ROUTER_HOST;
|
|
64
64
|
}
|
|
@@ -34,7 +34,8 @@ export function workerRuntimeTelemetryTarget({env=process.env,args=process.argv.
|
|
|
34
34
|
if (!['http:','https:'].includes(url.protocol) || url.username || url.password) return null;
|
|
35
35
|
url.pathname=`${url.pathname.replace(/\/+$/,'') || '/goapi/codem'}/sandbox/telemetry/workflow_metrics`;
|
|
36
36
|
url.search='';url.hash='';
|
|
37
|
-
|
|
37
|
+
const bearer=env.CODEM_TOKEN.startsWith('codem_resource.')?env.CODEM_TOKEN:`sandbox_${env.CODEM_TOKEN}`;
|
|
38
|
+
return {url,headers:{'Content-Type':'application/json',Authorization:`Bearer ${bearer}`,...ttEnvHeadersFor(url,env)}};
|
|
38
39
|
}
|
|
39
40
|
|
|
40
41
|
export async function reportWorkerRuntime(runtime,{env=process.env,args=process.argv.slice(2),signal,timeoutMS=750}={}) {
|
package/package.json
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lark-codem/codem-cli",
|
|
3
|
-
"version": "0.1.281-dev.
|
|
3
|
+
"version": "0.1.281-dev.100104534209.0.gf5d08a3",
|
|
4
4
|
"codemServiceManagementProtocol": 3,
|
|
5
5
|
"codemProfileProtocol": 1,
|
|
6
|
+
"codemAuthProtocol": 1,
|
|
6
7
|
"type": "module",
|
|
7
8
|
"description": "CodeM local CLI for Feishu-driven coding sessions",
|
|
8
9
|
"license": "SEE LICENSE IN LICENSE",
|
|
9
10
|
"files": [
|
|
10
11
|
"bin",
|
|
11
12
|
"profile",
|
|
13
|
+
"auth",
|
|
12
14
|
"LICENSE"
|
|
13
15
|
],
|
|
14
16
|
"os": [
|
|
@@ -29,17 +31,17 @@
|
|
|
29
31
|
"access": "public"
|
|
30
32
|
},
|
|
31
33
|
"dependencies": {
|
|
32
|
-
"@lark-codem/codem-core": "0.8.98-dev.
|
|
34
|
+
"@lark-codem/codem-core": "0.8.98-dev.100104534209.0.g58a8322",
|
|
33
35
|
"zod": "3.25.76",
|
|
34
|
-
"@lark-codem/lark-cli": "0.1.
|
|
36
|
+
"@lark-codem/lark-cli": "0.1.3"
|
|
35
37
|
},
|
|
36
38
|
"optionalDependencies": {
|
|
37
|
-
"@lark-codem/codem-cli-darwin-arm64": "0.1.281-dev.
|
|
38
|
-
"@lark-codem/codem-cli-darwin-x64": "0.1.281-dev.
|
|
39
|
-
"@lark-codem/codem-cli-linux-arm64": "0.1.281-dev.
|
|
40
|
-
"@lark-codem/codem-cli-linux-x64": "0.1.281-dev.
|
|
41
|
-
"@lark-codem/codem-cli-win32-arm64": "0.1.281-dev.
|
|
42
|
-
"@lark-codem/codem-cli-win32-x64": "0.1.281-dev.
|
|
39
|
+
"@lark-codem/codem-cli-darwin-arm64": "0.1.281-dev.100104534209.0.gf5d08a3",
|
|
40
|
+
"@lark-codem/codem-cli-darwin-x64": "0.1.281-dev.100104534209.0.gf5d08a3",
|
|
41
|
+
"@lark-codem/codem-cli-linux-arm64": "0.1.281-dev.100104534209.0.gf5d08a3",
|
|
42
|
+
"@lark-codem/codem-cli-linux-x64": "0.1.281-dev.100104534209.0.gf5d08a3",
|
|
43
|
+
"@lark-codem/codem-cli-win32-arm64": "0.1.281-dev.100104534209.0.gf5d08a3",
|
|
44
|
+
"@lark-codem/codem-cli-win32-x64": "0.1.281-dev.100104534209.0.gf5d08a3"
|
|
43
45
|
},
|
|
44
46
|
"engines": {
|
|
45
47
|
"node": ">=18"
|
|
@@ -31,7 +31,6 @@ export class CredentialStorageError extends Error {
|
|
|
31
31
|
export function isRecoverableCredentialState(error) {
|
|
32
32
|
return error?.code === "credential_storage_rotation_pending"
|
|
33
33
|
|| error?.code === "credential_storage_rotation_unknown"
|
|
34
|
-
//
|
|
35
|
-
// never use of its stale plaintext mirror or another credential kind.
|
|
34
|
+
// Missing OAuth can reauthorize the existing device, never another kind.
|
|
36
35
|
|| (error?.code === "credential_storage_missing" && error.kind === "oauth");
|
|
37
36
|
}
|
|
@@ -44,7 +44,8 @@ export async function readProfileSnapshot(home) {
|
|
|
44
44
|
return withCodeMConfigLock(join(home, "config.json"), () => readLockedProfileSnapshot(home));
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
-
|
|
47
|
+
// Internal callers must already hold the canonical profile config lock.
|
|
48
|
+
export async function readLockedProfileSnapshot(home) {
|
|
48
49
|
const configPath = join(home, "config.json");
|
|
49
50
|
const config = await readProfileObject(configPath);
|
|
50
51
|
let metadata;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Base bounds the JSON encoding of RPC IDs at 1024 bytes. Printable route
|
|
2
|
+
// keys include Go QueryEscape's percent escapes and plus sign. Only record
|
|
3
|
+
// identifier characters; never truncate two different IDs to the same value.
|
|
4
|
+
export function realtimeLogID(value) {
|
|
5
|
+
if (Number.isSafeInteger(value)) return value;
|
|
6
|
+
if (typeof value === "string" && value.length <= 1022 &&
|
|
7
|
+
/^[\p{L}\p{N}_.:%~+-]+$/u.test(value) && Buffer.byteLength(value) <= 1022) return value;
|
|
8
|
+
return undefined;
|
|
9
|
+
}
|
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;
|
|
@@ -316,7 +432,35 @@ export class RuntimeLogReporter {
|
|
|
316
432
|
|
|
317
433
|
get pendingCount() { return this.#live.queue.length + this.#replay.queue.length; }
|
|
318
434
|
get droppedCount() { return this.#dropped; }
|
|
319
|
-
|
|
435
|
+
|
|
436
|
+
#header() {
|
|
437
|
+
const identity = this.#identity;
|
|
438
|
+
return { aid: SLARDAR_PC_AID, device_id: identity.deviceId ?? this.#instanceId,
|
|
439
|
+
user_id: identity.userId ?? "0", parfait_version: SLARDAR_PC_REPORTER_VERSION,
|
|
440
|
+
channel: identity.channel ?? "unknown", os: this.#platform, os_version: this.#osVersion };
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
recordMetric(name, category, metrics) {
|
|
444
|
+
if (this.#closed) return false;
|
|
445
|
+
if (this.#live.queue.length >= CAPACITY) {
|
|
446
|
+
this.#dropped += 1;
|
|
447
|
+
return false;
|
|
448
|
+
}
|
|
449
|
+
const identity = this.#identity;
|
|
450
|
+
const record = {
|
|
451
|
+
app_version: this.#version, app_minor_version: "", build_id: "",
|
|
452
|
+
process_type: `codem-${this.#role}`, session_id: "", timestamp: Date.now(),
|
|
453
|
+
log_type: "flexible", event_name: name,
|
|
454
|
+
category: { reporter: "codem_js", runtime_role: this.#role,
|
|
455
|
+
...(identity.tenantId ? { tenant_id: identity.tenantId } : {}), ...category },
|
|
456
|
+
metrics
|
|
457
|
+
};
|
|
458
|
+
this.#live.queue.push({ header: this.#header(), record, metricName: null, attempts: 0 });
|
|
459
|
+
// Bursts need not wait for the periodic timer, and a slow collector still
|
|
460
|
+
// has only one bounded in-flight upload.
|
|
461
|
+
if (this.#live.queue.length >= BATCH_SIZE) void this.#flushLane(this.#live, REQUEST_TIMEOUT_MS);
|
|
462
|
+
return true;
|
|
463
|
+
}
|
|
320
464
|
|
|
321
465
|
record(level, component, event, fields = {}) {
|
|
322
466
|
try {
|
|
@@ -327,13 +471,17 @@ export class RuntimeLogReporter {
|
|
|
327
471
|
|
|
328
472
|
#logEntry(level, component, event, fields) {
|
|
329
473
|
let safeFields;
|
|
330
|
-
try { safeFields = projectFields(fields); } catch { safeFields = {}; }
|
|
474
|
+
try { safeFields = projectFields(fields, true, component); } catch { safeFields = {}; }
|
|
331
475
|
if (OBSERVATION_EVENTS.has(event)) safeFields.observation_id = randomUUID();
|
|
332
476
|
const severity = ["info", "warn", "error", "fatal"].includes(level) ? level : "info";
|
|
333
477
|
// Keep arbitrary upstream error codes out of trusted-device metric dimensions.
|
|
334
478
|
const trustedDevice = TRUSTED_DEVICE_EVENTS.has(event);
|
|
335
479
|
const dimensions = trustedDevice ? {} : Object.fromEntries(["stage", "error_class", "error_code", "error_kind", "outcome"]
|
|
336
480
|
.filter(key => safeFields[key]).map(key => [key, safeFields[key]]));
|
|
481
|
+
if (UPLINK_DIAGNOSTIC_METRICS.has(event)) {
|
|
482
|
+
if (safeFields.lane) dimensions.lane = safeFields.lane;
|
|
483
|
+
if (safeFields.target_kind) dimensions.target_kind = safeFields.target_kind;
|
|
484
|
+
}
|
|
337
485
|
if (OBSERVATION_EVENTS.has(event)) {
|
|
338
486
|
for (const [key, values] of Object.entries(trustedDevice ? TRUSTED_DEVICE_DIMENSIONS : OBSERVATION_DIMENSIONS)) {
|
|
339
487
|
if (safeFields[key]) dimensions[key] = values.includes(safeFields[key]) ? safeFields[key] : "unknown";
|
|
@@ -395,6 +543,7 @@ export class RuntimeLogReporter {
|
|
|
395
543
|
}
|
|
396
544
|
|
|
397
545
|
#entry(severity, component, event, safeFields, identity, dimensions, includeLog) {
|
|
546
|
+
safeFields = { ...this.#resourceContext, ...safeFields, ...(this.#resourceContext.resource_id ? { resource_id: this.#resourceContext.resource_id } : {}) };
|
|
398
547
|
const category = {
|
|
399
548
|
...workerRuntimeAttributes(),
|
|
400
549
|
client_kind: "cli", runtime_role: this.#role, reporter: "codem_js", log_schema: "1",
|
|
@@ -565,9 +714,9 @@ export function runtimeLogIdentityKey() { return active?.identityKey; }
|
|
|
565
714
|
|
|
566
715
|
export function startRuntimeLogs({ role, version, env = process.env, send } = {}) {
|
|
567
716
|
try {
|
|
568
|
-
if (active || /^(1|true|yes)$/iu.test(env.CODEM_TELEMETRY_DISABLED ?? "") || env.NODE_TEST_CONTEXT) return;
|
|
717
|
+
if (active || !sandboxLogUploadAllowed(env, role) || /^(1|true|yes)$/iu.test(env.CODEM_TELEMETRY_DISABLED ?? "") || env.NODE_TEST_CONTEXT) return;
|
|
569
718
|
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") });
|
|
719
|
+
active = new RuntimeLogReporter({ role, version, env, send, crashDirectory: path.join(root, "runtime-crashes") });
|
|
571
720
|
} catch { /* Monitoring initialization never prevents a command from running. */ }
|
|
572
721
|
}
|
|
573
722
|
|
|
@@ -593,6 +742,10 @@ export function flushRuntimeLogsInBackground() {
|
|
|
593
742
|
if (active) setImmediate(() => { void active?.flush().catch(() => {}); }).unref?.();
|
|
594
743
|
}
|
|
595
744
|
|
|
745
|
+
export function recordRuntimeMetric(name, category, metrics) {
|
|
746
|
+
try { return active?.recordMetric(name, category, metrics) ?? false; } catch { return false; }
|
|
747
|
+
}
|
|
748
|
+
|
|
596
749
|
export function persistRuntimeCrash(component, event, fields) {
|
|
597
750
|
try { active?.persistCrash(component, event, fields); } catch { /* best effort */ }
|
|
598
751
|
}
|
|
@@ -652,9 +805,9 @@ export function recordInteractiveProcessExit({ exitCode, signal }) {
|
|
|
652
805
|
export function recordSelectedRuntimeLog(component, event, fields = {}) {
|
|
653
806
|
try {
|
|
654
807
|
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;
|
|
808
|
+
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
809
|
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";
|
|
810
|
+
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
811
|
recordRuntimeLog(level, component, event, fields);
|
|
659
812
|
} catch { /* best effort */ }
|
|
660
813
|
}
|
|
@@ -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
|
+
}
|