@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.
@@ -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
+ }
package/bin/codem.js CHANGED
@@ -12,6 +12,7 @@
12
12
  // 开发态兜底:repo checkout 里没有平台包,若 ../dist/src/index.js 存在
13
13
  // (npm run build 产物),直接 import 执行——`node bin/codem.js` 在仓内可用。
14
14
 
15
+ import { randomUUID } from "node:crypto";
15
16
  import { spawn } from "node:child_process";
16
17
  import fs from "node:fs";
17
18
  import { createRequire } from "node:module";
@@ -53,6 +54,72 @@ function resolvePlatformBinary() {
53
54
  return candidates.find((candidate) => fs.existsSync(candidate)) ?? null;
54
55
  }
55
56
 
57
+ function isGlobalNpmEntrypoint(args) {
58
+ // Official npm –g installs link from <prefix>/bin on POSIX and create
59
+ // shims beside <prefix>/node_modules on Windows. A local/npx/managed/App
60
+ // package merely located under node_modules must not prepare shared state.
61
+ const nodeModules = path.dirname(path.dirname(PACKAGE_ROOT));
62
+ if (PACKAGE_SCOPE !== "@lark-codem" || path.basename(nodeModules) !== "node_modules") return false;
63
+ const windows = process.platform === "win32";
64
+ if (!windows && path.basename(path.dirname(nodeModules)) !== "lib") return false;
65
+ const shimDirectory = windows ? path.dirname(nodeModules) : path.resolve(nodeModules, "../../bin");
66
+ const expected = fs.realpathSync(fileURLToPath(import.meta.url));
67
+ const hasGlobalShim = ["codem", "codem-cli"].some(name => {
68
+ try {
69
+ const shim = path.join(shimDirectory, name + (windows ? ".cmd" : ""));
70
+ return windows
71
+ ? fs.readFileSync(shim, "utf8").toLowerCase().includes("\\node_modules\\@lark-codem\\codem-cli\\bin\\codem.js")
72
+ : fs.realpathSync(shim) === expected;
73
+ } catch { return false; }
74
+ });
75
+ return hasGlobalShim && !args[0]?.startsWith("__") && !args.includes("--healthcheck") &&
76
+ !args.includes("--windows-migration-launcher-pid");
77
+ }
78
+
79
+ function forwardChildSignals(child) {
80
+ const handlers = new Map();
81
+ for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) {
82
+ const handler = () => {
83
+ if (child.exitCode !== null || child.signalCode !== null) return;
84
+ try { child.kill(signal); }
85
+ catch { /* child already gone */ }
86
+ };
87
+ handlers.set(signal, handler);
88
+ process.on(signal, handler);
89
+ }
90
+ return () => {
91
+ for (const [signal, handler] of handlers) process.removeListener(signal, handler);
92
+ };
93
+ }
94
+
95
+ async function prepareSharedLaunch(binaryPath, args, env) {
96
+ return new Promise((resolve, reject) => {
97
+ const child = spawn(binaryPath, ["__npm-runtime-launch", ...args], applyHostedWindowsChildOptions({
98
+ env: { ...env,
99
+ CODEM_NPM_RUNTIME_TTY: process.stdin.isTTY && process.stdout.isTTY && process.stderr.isTTY ? "1" : "0" },
100
+ stdio: ["inherit", "pipe", "inherit"],
101
+ windowsHide: true
102
+ }));
103
+ const removeSignalHandlers = forwardChildSignals(child);
104
+ let output = "";
105
+ child.stdout.setEncoding("utf8");
106
+ child.stdout.on("data", chunk => { output += chunk; });
107
+ child.once("error", error => {
108
+ removeSignalHandlers();
109
+ reject(error);
110
+ });
111
+ child.once("close", (code, signal) => {
112
+ removeSignalHandlers();
113
+ if (signal) process.kill(process.pid, signal);
114
+ if (code !== 0) reject(new Error("shared runtime bootstrap failed"));
115
+ else {
116
+ try { resolve(JSON.parse(output)); }
117
+ catch (error) { reject(error); }
118
+ }
119
+ });
120
+ });
121
+ }
122
+
56
123
  // spawn 的失败有两条互斥出口:只有 EACCES / EAGAIN / EMFILE / ENFILE / ENOENT
57
124
  // 会被 Node 降级成异步 `error` 事件,其余 errno(ENOEXEC / ENOTDIR / EPERM,以及
58
125
  // Windows 上杀软 / EDR 拦截 CreateProcessW 时 libuv 报的 UNKNOWN=-4094)在
@@ -161,61 +228,71 @@ if (process.env.CODEM_WORKER_RUNTIME !== undefined) {
161
228
  const binaryPath = resolvePlatformBinary();
162
229
 
163
230
  if (binaryPath) {
231
+ const args = process.argv.slice(2);
232
+ let command = binaryPath;
233
+ let childArgs = args;
234
+ const env = { ...process.env, CODEM_PLUGIN_NODE: process.execPath };
235
+ if (isGlobalNpmEntrypoint(args)) {
236
+ env.CODEM_SHARED_RUNTIME_ATTEMPT = randomUUID();
237
+ env.CODEM_SHARED_RUNTIME_SOURCE = "npm_global";
238
+ const plan = await prepareSharedLaunch(binaryPath, args, env).catch(error => ({ error: error.code || "io_error" }));
239
+ if (plan.handled || plan.cancelled) process.exit(0);
240
+ if (plan.reason || plan.error) writeStderrSync(`codem: ${plan.error ?? plan.reason}`);
241
+ if (plan.error) {
242
+ if (plan.error === "legacy_service") writeStderrSync(" codem service start");
243
+ process.exit(1);
244
+ }
245
+ if (plan.launcher) {
246
+ command = plan.node;
247
+ childArgs = [plan.launcher, ...args];
248
+ env.CODEM_PLUGIN_NODE = plan.node;
249
+ env.CODEM_LARK_CLI_PATH = plan.lark;
250
+ const previousPath = process.env.PATH || "";
251
+ for (const key of Object.keys(env)) {
252
+ if (process.platform === "win32" && key.toUpperCase() === "PATH") delete env[key];
253
+ }
254
+ env.PATH = [plan.bin, previousPath].join(path.delimiter);
255
+ const explicitBash = process.env.LINCO_GIT_BASH_PATH;
256
+ if (process.platform === "win32" && plan.bash && path.isAbsolute(plan.bash)
257
+ && fs.statSync(plan.bash, { throwIfNoEntry: false })?.isFile()
258
+ && !(explicitBash && path.isAbsolute(explicitBash) && fs.statSync(explicitBash, { throwIfNoEntry: false })?.isFile())) {
259
+ env.LINCO_GIT_BASH_PATH = plan.bash;
260
+ }
261
+ }
262
+ }
164
263
  let child;
165
264
  let stopWindowsHostMigrationWatch = () => {};
166
265
  try {
167
266
  child = spawn(
168
- binaryPath,
169
- process.argv.slice(2),
267
+ command,
268
+ childArgs,
170
269
  applyHostedWindowsChildOptions({
171
270
  stdio: "inherit",
172
- env: {
173
- ...process.env,
174
- // The compiled binary cannot infer a Node executable from its own
175
- // process image. The npm launcher is the authority for this install
176
- // form and hands off its exact interpreter as the canonical launcher.
177
- CODEM_PLUGIN_NODE: process.execPath
178
- }
271
+ env
179
272
  })
180
273
  );
181
- stopWindowsHostMigrationWatch = watchWindowsDaemonHostMigration({
274
+ if (command === binaryPath) stopWindowsHostMigrationWatch = watchWindowsDaemonHostMigration({
182
275
  binaryPath,
183
276
  daemonPid: child.pid,
184
277
  launcherPid: process.pid
185
278
  });
186
279
  } catch (error) {
187
- reportSpawnFailure(binaryPath, error);
280
+ reportSpawnFailure(command, error);
188
281
  }
189
282
 
190
283
  // 终端会把 SIGINT/SIGHUP 广播给整个前台进程组,但 execFile timeout、
191
284
  // child.kill()、launchd/systemd 等调用方也会只命中 launcher PID。三类终止
192
285
  // 信号都显式转发,保证后一种场景不会留下 Bun 子进程;child.kill 只命中
193
286
  // 直接子进程,不会把同一信号再次广播给它下面的 linco 进程组。
194
- const signalHandlers = new Map();
195
- for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) {
196
- const handler = () => {
197
- if (child.exitCode !== null || child.signalCode !== null) {
198
- return;
199
- }
200
- try {
201
- child.kill(signal);
202
- } catch {
203
- // child already gone
204
- }
205
- };
206
- signalHandlers.set(signal, handler);
207
- process.on(signal, handler);
208
- }
287
+ const removeSignalHandlers = forwardChildSignals(child);
209
288
 
210
289
  child.on("error", (error) => {
211
- reportSpawnFailure(binaryPath, error);
290
+ reportSpawnFailure(command, error);
212
291
  });
213
292
 
214
293
  child.on("exit", (code, signal) => {
215
294
  stopWindowsHostMigrationWatch();
216
- for (const [registeredSignal, handler] of signalHandlers) {
217
- process.removeListener(registeredSignal, handler);
218
- }
295
+ removeSignalHandlers();
219
296
  if (signal) {
220
297
  // 让退出信号对上游可见:自己的 handler 已摘掉,可以安全补发同名信号。
221
298
  process.kill(process.pid, signal);
@@ -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
- return {url,headers:{'Content-Type':'application/json',Authorization:`Bearer sandbox_${env.CODEM_TOKEN}`,...ttEnvHeadersFor(url,env)}};
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,17 @@
1
1
  {
2
2
  "name": "@lark-codem/codem-cli",
3
- "version": "0.1.281-dev.100104585886.0.ga915b98",
3
+ "version": "0.1.281-dev.100104602537.0.gd02b8a3",
4
4
  "codemServiceManagementProtocol": 3,
5
+ "codemSharedRuntime": 2,
5
6
  "codemProfileProtocol": 1,
7
+ "codemAuthProtocol": 1,
6
8
  "type": "module",
7
9
  "description": "CodeM local CLI for Feishu-driven coding sessions",
8
10
  "license": "SEE LICENSE IN LICENSE",
9
11
  "files": [
10
12
  "bin",
11
13
  "profile",
14
+ "auth",
12
15
  "LICENSE"
13
16
  ],
14
17
  "os": [
@@ -29,17 +32,17 @@
29
32
  "access": "public"
30
33
  },
31
34
  "dependencies": {
32
- "@lark-codem/codem-core": "0.8.98-dev.100104585886.0.g6a6c97f",
35
+ "@lark-codem/codem-core": "0.8.98-dev.100104602537.0.gddf7610",
33
36
  "zod": "3.25.76",
34
- "@lark-codem/lark-cli": "0.1.5"
37
+ "@lark-codem/lark-cli": "0.1.6-test.20261129.1"
35
38
  },
36
39
  "optionalDependencies": {
37
- "@lark-codem/codem-cli-darwin-arm64": "0.1.281-dev.100104585886.0.ga915b98",
38
- "@lark-codem/codem-cli-darwin-x64": "0.1.281-dev.100104585886.0.ga915b98",
39
- "@lark-codem/codem-cli-linux-arm64": "0.1.281-dev.100104585886.0.ga915b98",
40
- "@lark-codem/codem-cli-linux-x64": "0.1.281-dev.100104585886.0.ga915b98",
41
- "@lark-codem/codem-cli-win32-arm64": "0.1.281-dev.100104585886.0.ga915b98",
42
- "@lark-codem/codem-cli-win32-x64": "0.1.281-dev.100104585886.0.ga915b98"
40
+ "@lark-codem/codem-cli-darwin-arm64": "0.1.281-dev.100104602537.0.gd02b8a3",
41
+ "@lark-codem/codem-cli-darwin-x64": "0.1.281-dev.100104602537.0.gd02b8a3",
42
+ "@lark-codem/codem-cli-linux-arm64": "0.1.281-dev.100104602537.0.gd02b8a3",
43
+ "@lark-codem/codem-cli-linux-x64": "0.1.281-dev.100104602537.0.gd02b8a3",
44
+ "@lark-codem/codem-cli-win32-arm64": "0.1.281-dev.100104602537.0.gd02b8a3",
45
+ "@lark-codem/codem-cli-win32-x64": "0.1.281-dev.100104602537.0.gd02b8a3"
43
46
  },
44
47
  "engines": {
45
48
  "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
- // 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
  }
@@ -44,7 +44,8 @@ export async function readProfileSnapshot(home) {
44
44
  return withCodeMConfigLock(join(home, "config.json"), () => readLockedProfileSnapshot(home));
45
45
  }
46
46
 
47
- async function readLockedProfileSnapshot(home) {
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
+ }