@lark-codem/codem-cli 0.1.276-dev.100104078381.0.g42bb861 → 0.1.276-dev.100104081633.0.ga52f9f6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/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
  }
@@ -3,7 +3,7 @@
3
3
  import { execFile, spawn } from 'node:child_process';
4
4
  import { promisify } from 'node:util';
5
5
  import { createHash, randomUUID } from 'node:crypto';
6
- import fs from 'node:fs/promises';
6
+ import fs from '../src/compatible-fs.js';
7
7
  import { constants as fsConstants } from 'node:fs';
8
8
  import os from 'node:os';
9
9
  import path from 'node:path';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-codem/codem-cli",
3
- "version": "0.1.276-dev.100104078381.0.g42bb861",
3
+ "version": "0.1.276-dev.100104081633.0.ga52f9f6",
4
4
  "codemServiceManagementProtocol": 3,
5
5
  "codemWorkerRuntimeProtocol": 1,
6
6
  "codemProfileProtocol": 1,
@@ -30,17 +30,17 @@
30
30
  "access": "public"
31
31
  },
32
32
  "dependencies": {
33
- "@lark-codem/codem-core": "0.8.93-dev.100104078381.0.g67c5ea6",
33
+ "@lark-codem/codem-core": "0.8.93-dev.100104081633.0.g1b3cd4e",
34
34
  "zod": "3.25.76",
35
- "@lark-codem/lark-cli": "0.1.2"
35
+ "@lark-codem/lark-cli": "0.1.1-test.20261110.1"
36
36
  },
37
37
  "optionalDependencies": {
38
- "@lark-codem/codem-cli-darwin-arm64": "0.1.276-dev.100104078381.0.g42bb861",
39
- "@lark-codem/codem-cli-darwin-x64": "0.1.276-dev.100104078381.0.g42bb861",
40
- "@lark-codem/codem-cli-linux-arm64": "0.1.276-dev.100104078381.0.g42bb861",
41
- "@lark-codem/codem-cli-linux-x64": "0.1.276-dev.100104078381.0.g42bb861",
42
- "@lark-codem/codem-cli-win32-arm64": "0.1.276-dev.100104078381.0.g42bb861",
43
- "@lark-codem/codem-cli-win32-x64": "0.1.276-dev.100104078381.0.g42bb861"
38
+ "@lark-codem/codem-cli-darwin-arm64": "0.1.276-dev.100104081633.0.ga52f9f6",
39
+ "@lark-codem/codem-cli-darwin-x64": "0.1.276-dev.100104081633.0.ga52f9f6",
40
+ "@lark-codem/codem-cli-linux-arm64": "0.1.276-dev.100104081633.0.ga52f9f6",
41
+ "@lark-codem/codem-cli-linux-x64": "0.1.276-dev.100104081633.0.ga52f9f6",
42
+ "@lark-codem/codem-cli-win32-arm64": "0.1.276-dev.100104081633.0.ga52f9f6",
43
+ "@lark-codem/codem-cli-win32-x64": "0.1.276-dev.100104081633.0.ga52f9f6"
44
44
  },
45
45
  "engines": {
46
46
  "node": ">=18"
@@ -0,0 +1,79 @@
1
+ import nativeFs from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ const FALLBACK_RENAME_CODES = new Set([
5
+ "EACCES", "EBUSY", "EEXIST", "EINVAL", "ENOTSUP", "EOPNOTSUPP", "EPERM", "EXDEV"
6
+ ]);
7
+
8
+ function fallbackError(source, destination, renameError, copyError) {
9
+ const error = new Error(
10
+ `Cannot move ${source} to ${destination}: native rename and copy-delete fallback both failed`,
11
+ { cause: new AggregateError([renameError, copyError]) }
12
+ );
13
+ error.code = copyError?.code ?? renameError?.code;
14
+ return error;
15
+ }
16
+
17
+ function fallbackWouldRecurse(source, destination, sourceStat) {
18
+ if (!sourceStat.isDirectory()) return false;
19
+ const relative = path.relative(path.resolve(source), path.resolve(destination));
20
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${path.sep}`);
21
+ }
22
+
23
+ async function existingDestination(lstatImpl, destination) {
24
+ try {
25
+ return await lstatImpl(destination);
26
+ } catch (error) {
27
+ if (error?.code === "ENOENT") return null;
28
+ throw error;
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Move a file-system entry, falling back to copy + source removal when the
34
+ * platform cannot perform a native rename. The fallback intentionally replaces
35
+ * the destination exactly instead of merging directories. Unlike rename it is
36
+ * not atomic, so callers must continue to prefer the successful native path.
37
+ */
38
+ export async function compatibleRename(source, destination, {
39
+ renameImpl = nativeFs.rename,
40
+ copyImpl = nativeFs.cp,
41
+ removeImpl = nativeFs.rm,
42
+ lstatImpl = nativeFs.lstat
43
+ } = {}) {
44
+ try {
45
+ return await renameImpl(source, destination);
46
+ } catch (renameError) {
47
+ if (!FALLBACK_RENAME_CODES.has(renameError?.code)) throw renameError;
48
+ try {
49
+ if (path.resolve(source) === path.resolve(destination)) throw renameError;
50
+ const sourceStat = await lstatImpl(source);
51
+ if (fallbackWouldRecurse(source, destination, sourceStat)) throw renameError;
52
+ const destinationStat = await existingDestination(lstatImpl, destination);
53
+ // Directory publication uses EEXIST/ENOTEMPTY as its compare-and-swap
54
+ // signal. Replacing a directory that appeared after rename failed would
55
+ // delete a peer's committed tree, so only an absent directory target may
56
+ // use the non-atomic compatibility path.
57
+ if (destinationStat && (sourceStat.isDirectory() || destinationStat.isDirectory())) {
58
+ throw renameError;
59
+ }
60
+ await copyImpl(source, destination, {
61
+ recursive: sourceStat.isDirectory(),
62
+ force: true,
63
+ errorOnExist: false,
64
+ preserveTimestamps: true,
65
+ verbatimSymlinks: true
66
+ });
67
+ await removeImpl(source, { recursive: sourceStat.isDirectory(), force: false });
68
+ } catch (copyError) {
69
+ if (copyError === renameError) throw renameError;
70
+ throw fallbackError(source, destination, renameError, copyError);
71
+ }
72
+ }
73
+ }
74
+
75
+ export default new Proxy(nativeFs, {
76
+ get(target, property, receiver) {
77
+ return property === "rename" ? compatibleRename : Reflect.get(target, property, receiver);
78
+ }
79
+ });
@@ -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
- // A missing OAuth record permits reauthorization with the existing device,
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
  }
@@ -1,6 +1,7 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { randomUUID } from "node:crypto";
3
- import { mkdir, open, rename, rm } from "node:fs/promises";
3
+ import { mkdir, open, rm } from "node:fs/promises";
4
+ import { compatibleRename as rename } from "./compatible-fs.js";
4
5
  import { basename, dirname, join, posix, win32 } from "node:path";
5
6
  import { acquireConfigLock } from "./config-lock.js";
6
7
 
@@ -1,5 +1,6 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
- import { lstat, mkdir, readFile, readdir, readlink, realpath, rename, rm, unlink } from 'node:fs/promises';
2
+ import { lstat, mkdir, readFile, readdir, readlink, realpath, rm, unlink } from 'node:fs/promises';
3
+ import { compatibleRename as rename } from './compatible-fs.js';
3
4
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
4
5
  import { z } from 'zod';
5
6
  import { writeFileAtomically, writeJsonFileAtomically } from './profile-io.js';
@@ -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
+ }
@@ -1,3 +1,4 @@
1
+ import { realtimeLogID } from "./realtime-log-id.js";
1
2
  import { workerRuntimeAttributes } from "./worker-runtime-observation.js";
2
3
  import { createHash, randomUUID } from "node:crypto";
3
4
  import os from "node:os";
@@ -78,23 +79,33 @@ const OBSERVATION_METRICS = {
78
79
  };
79
80
  const EXTRA_FIELDS = ["observation_id", "runtime_client_instance_id", "command_id", "delivery_id", "probe_id", "sync_id", "transport_request_id", "attempt_id"];
80
81
  const LIFECYCLE_EXTRA_FIELDS = [...EXTRA_FIELDS, "process_instance_id", "startup_id", "request_id", "event_id"];
82
+ const UPLINK_BATCH_METRICS = [
83
+ "message_count", "packet_bytes", "queue_wait_ms", "encode_ms", "ack_wait_ms",
84
+ "batch_sequence", "pending_count", "pending_bytes"
85
+ ];
86
+ const UPLINK_DIAGNOSTIC_METRICS = new Map([
87
+ ["uplink_queue_pressure", ["pending_count", "pending_bytes", "oldest_age_ms", "full_count", "batch_sequence", "ack_wait_ms"]],
88
+ ["event_handoff_failed", UPLINK_BATCH_METRICS],
89
+ ["uplink_batch_slow", UPLINK_BATCH_METRICS]
90
+ ]);
81
91
  const STRING_FIELDS = new Set([
82
- ...EXTRA_FIELDS, "command_type", "ack_status", "ack_outcome", "readback_scope", "timing_origin", "required_capability",
83
- "request_id", "command_id", "session_id", "task_id", "dispatch_id", "event_id", "sync_id",
92
+ "request_id", "command_id", "session_id", "task_id", "dispatch_id", "event_id", "sync_id", "attempt_id",
93
+ "lane", "target_kind", "frontier_did", "packet_kind", "packet_traceparent",
84
94
  "process_instance_id", "run_id", "stage", "phase", "status", "outcome", "reason", "action",
85
95
  "error_class", "error_code", "error_kind", "error_type", "code", "signal", "stop_reason",
86
96
  "first_error", "retry_source", "cleanup_result",
87
97
  "terminal_event", "event_type", "actor_type", "source", "trigger", "hook_id", "hook_event",
88
98
  "target_version", "cli_version", "core_version", "version", "previous_state", "state",
89
99
  "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"
100
+ "operation_id", "entrypoint", "runtime_client_instance_id", "connection_instance_id", "lease_epoch"
91
101
  ]);
92
102
  const VALUE_FIELDS = new Set([
93
- "session_retained",
103
+ "session_retained", "local_rpc_id", "batch_index", "rpc_error_code", "has_subscribers", "window_active",
94
104
  ...new Set(Object.values(OBSERVATION_METRICS).flat()),
95
105
  "pid", "exit_code", "duration_ms", "elapsed_ms", "wait_ms", "run_ms", "total_ms", "took_ms",
96
106
  "attempt", "attempts", "attempt_count", "retryable", "http_status", "errno", "active_task_count",
97
107
  "pending_event_count", "pending_command_ack_count", "next_retry_ms", "consecutive_failures",
108
+ ...Array.from(UPLINK_DIAGNOSTIC_METRICS.values()).flat(), "transport_open",
98
109
  "outage_duration_ms", "startup_duration_ms", "failed_attempts", "active_runs", "completed",
99
110
  "delivered", "result_delivered", "queued_behind_existing", "expected", "timed_out",
100
111
  "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",
@@ -115,7 +126,7 @@ function optional(read) {
115
126
  }
116
127
 
117
128
  function metricProjection(event, fields = {}) {
118
- return { count: 1, ...Object.fromEntries((OBSERVATION_METRICS[event] ?? [])
129
+ return { count: 1, ...Object.fromEntries((OBSERVATION_METRICS[event] ?? UPLINK_DIAGNOSTIC_METRICS.get(event) ?? [])
119
130
  .filter(key => typeof fields?.[key] === "number" && Number.isFinite(fields[key]) && fields[key] >= 0)
120
131
  .map(key => [key, fields[key]])) };
121
132
  }
@@ -124,11 +135,18 @@ function extraProjection(fields = {}) {
124
135
  return Object.fromEntries(EXTRA_FIELDS.filter(key => token(fields?.[key])).map(key => [key, token(fields[key])]));
125
136
  }
126
137
 
127
- function projectFields(input, fingerprintErrors = true) {
138
+ const REALTIME_IDS = new Set(["route_id", "question_id", "thread_id", "turn_id", "session_id", "event_id"]);
139
+
140
+ function projectFields(input, fingerprintErrors = true, component) {
128
141
  const result = {};
129
142
  for (const [key, value] of Object.entries(input ?? {}).slice(0, 100)) {
130
143
  const name = fieldName(key);
131
- if (STRING_FIELDS.has(name)) {
144
+ if (name === "method" && typeof value === "string" && /^[a-z][a-z\d_.]*(?:\/[a-z][a-z\d_.]*){0,7}$/iu.test(value) && value.length <= 80) {
145
+ result[name] = value;
146
+ } else if (component === "realtime" && REALTIME_IDS.has(name)) {
147
+ const id = realtimeLogID(value);
148
+ if (id !== undefined) result[name] = id;
149
+ } else if (STRING_FIELDS.has(name)) {
132
150
  const safe = token(value);
133
151
  if (safe) result[name] = safe;
134
152
  } else if (VALUE_FIELDS.has(name) && (typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value)))) {
@@ -179,7 +197,13 @@ function lifecycleErrorCode(fields) {
179
197
  return fields.outcome === "failed" || fields.outcome === "rejected" || fields.outcome === "conflicting" ? "unknown" : undefined;
180
198
  }
181
199
 
200
+ const REALTIME_LOG_ONLY = new Set([
201
+ "app_server_rpc", "app_server_rpc_unmatched", "app_server_host_attached", "app_server_host_failed", "app_server_question", "hitl_answer",
202
+ "downlink_admission", "rpc_reply", "uplink_commit", "uplink_transport", "subscription_query", "runtime_lease"
203
+ ]);
204
+
182
205
  function keepLegacyMetric(event, fields, role, severity) {
206
+ if (REALTIME_LOG_ONLY.has(event)) return false;
183
207
  if (/^startup\.(?:main|update_check|daemon_service_reconcile|login_gate|login_handoff_to_linco)$/u.test(event) && severity === "info") return false;
184
208
  if (/(?:^|\.)drain_(?:started|completed)$/u.test(event) && severity === "info") return false;
185
209
  if (role === "daemon" && event === "runtime_capability_probe" && severity === "info") return false;
@@ -316,7 +340,35 @@ export class RuntimeLogReporter {
316
340
 
317
341
  get pendingCount() { return this.#live.queue.length + this.#replay.queue.length; }
318
342
  get droppedCount() { return this.#dropped; }
319
- get identityKey() { return JSON.stringify([this.#instanceId, this.#role, this.#identity.deviceId, this.#identity.userId, this.#identity.tenantId]); }
343
+
344
+ #header() {
345
+ const identity = this.#identity;
346
+ return { aid: SLARDAR_PC_AID, device_id: identity.deviceId ?? this.#instanceId,
347
+ user_id: identity.userId ?? "0", parfait_version: SLARDAR_PC_REPORTER_VERSION,
348
+ channel: identity.channel ?? "unknown", os: this.#platform, os_version: this.#osVersion };
349
+ }
350
+
351
+ recordMetric(name, category, metrics) {
352
+ if (this.#closed) return false;
353
+ if (this.#live.queue.length >= CAPACITY) {
354
+ this.#dropped += 1;
355
+ return false;
356
+ }
357
+ const identity = this.#identity;
358
+ const record = {
359
+ app_version: this.#version, app_minor_version: "", build_id: "",
360
+ process_type: `codem-${this.#role}`, session_id: "", timestamp: Date.now(),
361
+ log_type: "flexible", event_name: name,
362
+ category: { reporter: "codem_js", runtime_role: this.#role,
363
+ ...(identity.tenantId ? { tenant_id: identity.tenantId } : {}), ...category },
364
+ metrics
365
+ };
366
+ this.#live.queue.push({ header: this.#header(), record, metricName: null, attempts: 0 });
367
+ // Bursts need not wait for the periodic timer, and a slow collector still
368
+ // has only one bounded in-flight upload.
369
+ if (this.#live.queue.length >= BATCH_SIZE) void this.#flushLane(this.#live, REQUEST_TIMEOUT_MS);
370
+ return true;
371
+ }
320
372
 
321
373
  record(level, component, event, fields = {}) {
322
374
  try {
@@ -327,13 +379,17 @@ export class RuntimeLogReporter {
327
379
 
328
380
  #logEntry(level, component, event, fields) {
329
381
  let safeFields;
330
- try { safeFields = projectFields(fields); } catch { safeFields = {}; }
382
+ try { safeFields = projectFields(fields, true, component); } catch { safeFields = {}; }
331
383
  if (OBSERVATION_EVENTS.has(event)) safeFields.observation_id = randomUUID();
332
384
  const severity = ["info", "warn", "error", "fatal"].includes(level) ? level : "info";
333
385
  // Keep arbitrary upstream error codes out of trusted-device metric dimensions.
334
386
  const trustedDevice = TRUSTED_DEVICE_EVENTS.has(event);
335
387
  const dimensions = trustedDevice ? {} : Object.fromEntries(["stage", "error_class", "error_code", "error_kind", "outcome"]
336
388
  .filter(key => safeFields[key]).map(key => [key, safeFields[key]]));
389
+ if (UPLINK_DIAGNOSTIC_METRICS.has(event)) {
390
+ if (safeFields.lane) dimensions.lane = safeFields.lane;
391
+ if (safeFields.target_kind) dimensions.target_kind = safeFields.target_kind;
392
+ }
337
393
  if (OBSERVATION_EVENTS.has(event)) {
338
394
  for (const [key, values] of Object.entries(trustedDevice ? TRUSTED_DEVICE_DIMENSIONS : OBSERVATION_DIMENSIONS)) {
339
395
  if (safeFields[key]) dimensions[key] = values.includes(safeFields[key]) ? safeFields[key] : "unknown";
@@ -593,6 +649,10 @@ export function flushRuntimeLogsInBackground() {
593
649
  if (active) setImmediate(() => { void active?.flush().catch(() => {}); }).unref?.();
594
650
  }
595
651
 
652
+ export function recordRuntimeMetric(name, category, metrics) {
653
+ try { return active?.recordMetric(name, category, metrics) ?? false; } catch { return false; }
654
+ }
655
+
596
656
  export function persistRuntimeCrash(component, event, fields) {
597
657
  try { active?.persistCrash(component, event, fields); } catch { /* best effort */ }
598
658
  }