@botcord/daemon 0.2.61 → 0.2.63

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.
@@ -11,16 +11,22 @@ describe("diagnostics bundle", () => {
11
11
  const logFile = path.join(tmp, "daemon.log");
12
12
  const configFile = path.join(tmp, "config.json");
13
13
  const snapshotFile = path.join(tmp, "snapshot.json");
14
+ const sessionsFile = path.join(tmp, "sessions.json");
14
15
  const diagnosticsDir = path.join(tmp, "diagnostics");
15
16
  writeFileSync(logFile, 'Authorization: Bearer secret-token\n{"refreshToken":"drt_secret"}\n');
16
17
  writeFileSync(configFile, '{"token":"agent-secret","ok":true}\n');
17
18
  writeFileSync(snapshotFile, '{"version":1}\n');
19
+ writeFileSync(
20
+ sessionsFile,
21
+ '{"version":1,"entries":{"k":{"runtimeSessionId":"sess_1","token":"session-secret"}}}\n',
22
+ );
18
23
 
19
24
  const bundle = await createDiagnosticBundle({
20
25
  diagnosticsDir,
21
26
  logFile,
22
27
  configFile,
23
28
  snapshotFile,
29
+ sessionsFile,
24
30
  doctor: { text: "doctor ok", json: { ok: true } },
25
31
  });
26
32
  expect(bundle.filename).toMatch(/^botcord-daemon-diagnostics-.*\.zip$/);
@@ -42,12 +48,29 @@ describe("diagnostics bundle", () => {
42
48
  expect(listing).toContain("doctor.json");
43
49
  expect(listing).toContain("status.json");
44
50
  expect(listing).toContain("config.json.redacted");
51
+ expect(listing).toContain("sessions.json.redacted");
45
52
 
46
53
  const log = execFileSync("unzip", ["-p", bundle.path, "daemon.log"], {
47
54
  encoding: "utf8",
48
55
  });
49
56
  expect(log).toContain("Authorization: Bearer [REDACTED]");
50
57
  expect(log).toContain('"refreshToken":"[REDACTED]"');
58
+
59
+ const status = JSON.parse(execFileSync("unzip", ["-p", bundle.path, "status.json"], {
60
+ encoding: "utf8",
61
+ }));
62
+ expect(status.daemon.packageName).toBe("@botcord/daemon");
63
+ expect(status.daemon.version).toMatch(/^\d+\.\d+\.\d+/);
64
+ expect(status.daemon.entrypoint).toBeTruthy();
65
+ expect(status.daemon.packages["@botcord/daemon"]).toBe(status.daemon.version);
66
+ expect(status.environment.PATH).toBeTruthy();
67
+ expect(status.sessionsPath).toBe(sessionsFile);
68
+
69
+ const sessions = execFileSync("unzip", ["-p", bundle.path, "sessions.json.redacted"], {
70
+ encoding: "utf8",
71
+ });
72
+ expect(sessions).toContain('"runtimeSessionId":"sess_1"');
73
+ expect(sessions).toContain('"token":"[REDACTED]"');
51
74
  }, 20_000);
52
75
 
53
76
  it("bundles active log plus latest 5 rotated logs by default, or all with includeAllLogs", async () => {
@@ -202,6 +202,45 @@ describe("OpenclawAcpAdapter.run", () => {
202
202
  expect(res.error).toContain("Missing env var FOO_API_KEY");
203
203
  });
204
204
 
205
+ it("treats end_turn with warning-only stdout as an empty reply, not an error", async () => {
206
+ const child = new FakeChild();
207
+ const adapter = new OpenclawAcpAdapter({ spawnFn: makeSpawn(child) });
208
+ const gateway: ResolvedOpenclawGateway = {
209
+ name: "local",
210
+ url: "ws://127.0.0.1:1",
211
+ openclawAgent: "main",
212
+ };
213
+
214
+ child.stdin.on("data", (chunk: Buffer) => {
215
+ for (const line of chunk.toString("utf8").split("\n").filter(Boolean)) {
216
+ const frame = JSON.parse(line);
217
+ if (frame.method === "initialize") {
218
+ child.stdout.write("◇ Config warnings ─────────────────────╮\n");
219
+ child.stdout.write("│ - plugins.allow: plugin not installed: brave │\n");
220
+ child.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: frame.id, result: { protocolVersion: 1 } }) + "\n");
221
+ } else if (frame.method === "session/new") {
222
+ child.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: frame.id, result: { sessionId: "sid-warn-end" } }) + "\n");
223
+ } else if (frame.method === "session/prompt") {
224
+ child.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: frame.id, result: { stopReason: "end_turn" } }) + "\n");
225
+ }
226
+ }
227
+ });
228
+
229
+ const res = await adapter.run({
230
+ text: "hi",
231
+ sessionId: null,
232
+ cwd: "/tmp",
233
+ accountId: "ag_alice",
234
+ signal: new AbortController().signal,
235
+ trustLevel: "owner",
236
+ gateway,
237
+ });
238
+
239
+ expect(res.text).toBe("");
240
+ expect(res.newSessionId).toBe("sid-warn-end");
241
+ expect(res.error).toBeUndefined();
242
+ });
243
+
205
244
  it("streams only final text when OpenClaw sends reasoning before a final block", async () => {
206
245
  const child = new FakeChild();
207
246
  const adapter = new OpenclawAcpAdapter({ spawnFn: makeSpawn(child) });
@@ -156,6 +156,7 @@ describe("discoverLocalOpenclawGateways", () => {
156
156
 
157
157
  expect(found).toEqual([
158
158
  expect.objectContaining({
159
+ name: "qclaw-127-0-0-1-28789",
159
160
  url: "ws://127.0.0.1:28789",
160
161
  token: "qclaw-token",
161
162
  source: "config-file",
@@ -0,0 +1,382 @@
1
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, renameSync, statSync, unlinkSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import path from "node:path";
4
+ import type { LogFileEntry } from "./log.js";
5
+
6
+ const ACP_LOG_DIR = path.join(homedir(), ".botcord", "logs", "acp");
7
+ const ACP_LOG_MAX_BYTES = 2 * 1024 * 1024;
8
+ const ACP_LOG_KEEP = 20;
9
+ const ACP_LOG_DIAGNOSTICS_DEFAULT = 10;
10
+ const ACP_LOG_DIAGNOSTICS_ALL = 50;
11
+ const RUNTIME_LOG_DEFAULT_PER_ROOT = 5;
12
+ const RUNTIME_LOG_ALL_PER_ROOT = 25;
13
+ const RUNTIME_LOG_MAX_FILE_BYTES = 2 * 1024 * 1024;
14
+
15
+ const SECRET_KEY_RE = /token|secret|private.?key|api.?key|authorization|password/i;
16
+
17
+ export type AcpTraceStream =
18
+ | "child_start"
19
+ | "child_exit"
20
+ | "child_error"
21
+ | "stderr"
22
+ | "stdout_non_json"
23
+ | "rpc_in"
24
+ | "rpc_out";
25
+
26
+ export interface AcpTraceMeta {
27
+ runtime: string;
28
+ accountId?: string;
29
+ turnId?: string;
30
+ roomId?: string;
31
+ topicId?: string | null;
32
+ gatewayName?: string;
33
+ gatewayUrl?: string;
34
+ hermesProfile?: string;
35
+ sessionId?: string | null;
36
+ }
37
+
38
+ export interface AcpTraceEvent {
39
+ stream: AcpTraceStream;
40
+ direction?: "in" | "out";
41
+ pid?: number;
42
+ id?: number | string;
43
+ method?: string;
44
+ status?: "request" | "notification" | "response" | "error";
45
+ code?: number | null;
46
+ signal?: NodeJS.Signals | null;
47
+ error?: string;
48
+ chunk?: string;
49
+ params?: unknown;
50
+ result?: unknown;
51
+ }
52
+
53
+ export interface AcpTraceLogger {
54
+ path: string;
55
+ verbose: boolean;
56
+ write(event: AcpTraceEvent): void;
57
+ }
58
+
59
+ interface RuntimeLogRoot {
60
+ label: string;
61
+ dir: string;
62
+ }
63
+
64
+ interface RuntimeLogFile extends LogFileEntry {
65
+ bundleName: string;
66
+ }
67
+
68
+ export function createAcpTraceLogger(meta: AcpTraceMeta): AcpTraceLogger | null {
69
+ if (process.env.BOTCORD_ACP_LOGS === "0") return null;
70
+ const runtime = safePathSegment(meta.runtime || "acp");
71
+ const key = safePathSegment(
72
+ [
73
+ meta.accountId,
74
+ meta.gatewayName,
75
+ meta.hermesProfile,
76
+ meta.roomId,
77
+ ].filter(Boolean).join("_") || "default",
78
+ );
79
+ const dir = path.join(ACP_LOG_DIR, runtime);
80
+ const file = path.join(dir, `${key}.jsonl`);
81
+ const verbose = process.env.BOTCORD_ACP_TRACE === "verbose";
82
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
83
+ return {
84
+ path: file,
85
+ verbose,
86
+ write(event) {
87
+ writeAcpTrace(file, meta, event, verbose);
88
+ },
89
+ };
90
+ }
91
+
92
+ export function listAcpTraceLogFiles(includeAll = false): LogFileEntry[] {
93
+ const limit = includeAll ? ACP_LOG_DIAGNOSTICS_ALL : ACP_LOG_DIAGNOSTICS_DEFAULT;
94
+ const out: LogFileEntry[] = [];
95
+ collectFiles(ACP_LOG_DIR, out, (name) => name.endsWith(".jsonl") || name.includes(".jsonl."));
96
+ return out
97
+ .sort((a, b) => b.mtimeMs - a.mtimeMs || b.name.localeCompare(a.name))
98
+ .slice(0, limit);
99
+ }
100
+
101
+ export function listRuntimeLogFiles(includeAll = false): RuntimeLogFile[] {
102
+ const limit = includeAll ? RUNTIME_LOG_ALL_PER_ROOT : RUNTIME_LOG_DEFAULT_PER_ROOT;
103
+ const out: RuntimeLogFile[] = [];
104
+ for (const root of runtimeLogRoots()) {
105
+ const files: LogFileEntry[] = [];
106
+ collectFiles(root.dir, files, looksLikeLogFile, 4);
107
+ for (const entry of files
108
+ .sort((a, b) => b.mtimeMs - a.mtimeMs || b.name.localeCompare(a.name))
109
+ .slice(0, limit)) {
110
+ out.push({
111
+ ...entry,
112
+ bundleName: path.posix.join(
113
+ "runtime-logs",
114
+ root.label,
115
+ relativeBundlePath(root.dir, entry.path),
116
+ ),
117
+ });
118
+ }
119
+ }
120
+ return out;
121
+ }
122
+
123
+ function writeAcpTrace(
124
+ file: string,
125
+ meta: AcpTraceMeta,
126
+ event: AcpTraceEvent,
127
+ verbose: boolean,
128
+ ): void {
129
+ try {
130
+ rotateIfNeeded(file);
131
+ const record = {
132
+ ts: new Date().toISOString(),
133
+ runtime: meta.runtime,
134
+ accountId: meta.accountId,
135
+ turnId: meta.turnId,
136
+ roomId: meta.roomId,
137
+ topicId: meta.topicId ?? undefined,
138
+ gatewayName: meta.gatewayName,
139
+ gatewayUrl: meta.gatewayUrl,
140
+ hermesProfile: meta.hermesProfile,
141
+ sessionId: event.params && typeof event.params === "object"
142
+ ? pickString(event.params as Record<string, unknown>, "sessionId") ?? meta.sessionId ?? undefined
143
+ : meta.sessionId ?? undefined,
144
+ ...summarizeEvent(event, verbose),
145
+ };
146
+ appendFileSync(file, JSON.stringify(record) + "\n", { mode: 0o600 });
147
+ } catch {
148
+ // ACP trace logging must never affect runtime execution.
149
+ }
150
+ }
151
+
152
+ function summarizeEvent(event: AcpTraceEvent, verbose: boolean): Record<string, unknown> {
153
+ const out: Record<string, unknown> = {
154
+ stream: event.stream,
155
+ };
156
+ if (event.direction) out.direction = event.direction;
157
+ if (event.pid !== undefined) out.pid = event.pid;
158
+ if (event.id !== undefined) out.id = event.id;
159
+ if (event.method) out.method = event.method;
160
+ if (event.status) out.status = event.status;
161
+ if (event.code !== undefined) out.code = event.code;
162
+ if (event.signal !== undefined) out.signal = event.signal;
163
+ if (event.error) out.error = truncate(event.error, 1000);
164
+ if (event.chunk) out.chunk = truncate(redactSecretString(event.chunk), 2000);
165
+ if (event.params !== undefined) out.params = summarizePayload(event.params, verbose);
166
+ if (event.result !== undefined) out.result = summarizePayload(event.result, verbose);
167
+ return out;
168
+ }
169
+
170
+ function summarizePayload(value: unknown, verbose: boolean): unknown {
171
+ const redacted = redactSecrets(value);
172
+ if (verbose) return capPayload(redacted);
173
+ if (Array.isArray(redacted)) return { type: "array", length: redacted.length };
174
+ if (!redacted || typeof redacted !== "object") return redacted;
175
+ const obj = redacted as Record<string, unknown>;
176
+ const out: Record<string, unknown> = {};
177
+ for (const [key, v] of Object.entries(obj)) {
178
+ if (key === "prompt") {
179
+ out.prompt = summarizePrompt(v);
180
+ } else if (key === "cwd" || key === "sessionId") {
181
+ out[key] = v;
182
+ } else if (key === "_meta") {
183
+ out[key] = summarizePayload(v, false);
184
+ } else if (key === "update") {
185
+ out.update = summarizeUpdate(v);
186
+ } else if (key === "toolCall") {
187
+ out.toolCall = summarizeToolCall(v);
188
+ } else if (typeof v === "string") {
189
+ out[key] = stringSummary(v);
190
+ } else if (Array.isArray(v)) {
191
+ out[key] = { type: "array", length: v.length };
192
+ } else if (v && typeof v === "object") {
193
+ out[key] = { type: "object", keys: Object.keys(v as Record<string, unknown>).slice(0, 20) };
194
+ } else {
195
+ out[key] = v;
196
+ }
197
+ }
198
+ return out;
199
+ }
200
+
201
+ function summarizePrompt(value: unknown): unknown {
202
+ if (!Array.isArray(value)) return summarizePayload(value, false);
203
+ return value.map((item) => {
204
+ if (!item || typeof item !== "object") return summarizePayload(item, false);
205
+ const obj = item as Record<string, unknown>;
206
+ const text = typeof obj.text === "string" ? obj.text : "";
207
+ return {
208
+ type: obj.type,
209
+ textBytes: text ? Buffer.byteLength(text, "utf8") : undefined,
210
+ textPreview: text ? truncate(text.replace(/\s+/g, " "), 120) : undefined,
211
+ };
212
+ });
213
+ }
214
+
215
+ function summarizeUpdate(value: unknown): unknown {
216
+ if (!value || typeof value !== "object") return summarizePayload(value, false);
217
+ const obj = value as Record<string, unknown>;
218
+ const out: Record<string, unknown> = {};
219
+ if (typeof obj.sessionUpdate === "string") out.sessionUpdate = obj.sessionUpdate;
220
+ if (typeof obj.title === "string") out.title = stringSummary(obj.title);
221
+ if (obj.content !== undefined) out.content = summarizePayload(obj.content, false);
222
+ return Object.keys(out).length > 0 ? out : { type: "object", keys: Object.keys(obj).slice(0, 20) };
223
+ }
224
+
225
+ function summarizeToolCall(value: unknown): unknown {
226
+ if (!value || typeof value !== "object") return summarizePayload(value, false);
227
+ const obj = value as Record<string, unknown>;
228
+ return {
229
+ name: typeof obj.name === "string" ? obj.name : undefined,
230
+ rawInput: obj.rawInput === undefined ? undefined : summarizePayload(obj.rawInput, false),
231
+ };
232
+ }
233
+
234
+ function redactSecrets(value: unknown): unknown {
235
+ if (Array.isArray(value)) return value.map(redactSecrets);
236
+ if (!value || typeof value !== "object") {
237
+ return typeof value === "string" ? redactSecretString(value) : value;
238
+ }
239
+ const out: Record<string, unknown> = {};
240
+ for (const [key, v] of Object.entries(value as Record<string, unknown>)) {
241
+ out[key] = SECRET_KEY_RE.test(key) ? "[REDACTED]" : redactSecrets(v);
242
+ }
243
+ return out;
244
+ }
245
+
246
+ function redactSecretString(value: string): string {
247
+ return value
248
+ .replace(/(Authorization:\s*Bearer\s+)[^\s"']+/gi, "$1[REDACTED]")
249
+ .replace(/\b(token=)[^\s"']+/gi, "$1[REDACTED]")
250
+ .replace(/\b(drt_|dit_|gho_)[A-Za-z0-9_-]+/g, "$1[REDACTED]");
251
+ }
252
+
253
+ function capPayload(value: unknown): unknown {
254
+ if (typeof value === "string") return truncate(value, 2000);
255
+ if (Array.isArray(value)) return value.slice(0, 50).map(capPayload);
256
+ if (!value || typeof value !== "object") return value;
257
+ const out: Record<string, unknown> = {};
258
+ for (const [key, v] of Object.entries(value as Record<string, unknown>).slice(0, 50)) {
259
+ out[key] = capPayload(v);
260
+ }
261
+ return out;
262
+ }
263
+
264
+ function stringSummary(value: string): Record<string, unknown> {
265
+ return {
266
+ bytes: Buffer.byteLength(value, "utf8"),
267
+ preview: truncate(value.replace(/\s+/g, " "), 160),
268
+ };
269
+ }
270
+
271
+ function truncate(value: string, max: number): string {
272
+ return value.length > max ? `${value.slice(0, max)}…` : value;
273
+ }
274
+
275
+ function pickString(obj: Record<string, unknown>, key: string): string | undefined {
276
+ const value = obj[key];
277
+ return typeof value === "string" && value.length > 0 ? value : undefined;
278
+ }
279
+
280
+ function rotateIfNeeded(file: string): void {
281
+ try {
282
+ const st = statSync(file);
283
+ if (!st.isFile() || st.size <= ACP_LOG_MAX_BYTES) return;
284
+ renameSync(file, `${file}.${new Date().toISOString().replace(/[:.]/g, "-")}.${process.pid}`);
285
+ const dir = path.dirname(file);
286
+ const base = path.basename(file);
287
+ const rotated = readdirSync(dir)
288
+ .filter((name) => name.startsWith(`${base}.`))
289
+ .map((name) => {
290
+ const p = path.join(dir, name);
291
+ const st = statSync(p);
292
+ return { p, mtimeMs: st.mtimeMs };
293
+ })
294
+ .sort((a, b) => b.mtimeMs - a.mtimeMs);
295
+ for (const entry of rotated.slice(ACP_LOG_KEEP)) unlinkSync(entry.p);
296
+ } catch {
297
+ // best-effort
298
+ }
299
+ }
300
+
301
+ function collectFiles(
302
+ dir: string,
303
+ out: LogFileEntry[],
304
+ accept: (name: string, file: string) => boolean,
305
+ maxDepth = 3,
306
+ ): void {
307
+ if (maxDepth < 0) return;
308
+ let names: string[];
309
+ try {
310
+ names = readdirSync(dir);
311
+ } catch {
312
+ return;
313
+ }
314
+ for (const name of names) {
315
+ const file = path.join(dir, name);
316
+ try {
317
+ const st = statSync(file);
318
+ if (st.isDirectory()) {
319
+ collectFiles(file, out, accept, maxDepth - 1);
320
+ } else if (st.isFile() && st.size <= RUNTIME_LOG_MAX_FILE_BYTES && accept(name, file)) {
321
+ out.push({
322
+ path: file,
323
+ name: path.relative(ACP_LOG_DIR, file) || name,
324
+ sizeBytes: st.size,
325
+ mtimeMs: st.mtimeMs,
326
+ active: true,
327
+ });
328
+ }
329
+ } catch {
330
+ // ignore disappearing files
331
+ }
332
+ }
333
+ }
334
+
335
+ function runtimeLogRoots(): RuntimeLogRoot[] {
336
+ const roots: RuntimeLogRoot[] = [
337
+ { label: "openclaw", dir: path.join(homedir(), ".openclaw", "logs") },
338
+ { label: "qclaw", dir: path.join(homedir(), ".qclaw", "logs") },
339
+ { label: "hermes", dir: path.join(homedir(), ".hermes", "logs") },
340
+ ];
341
+ const hermesProfiles = path.join(homedir(), ".hermes", "profiles");
342
+ try {
343
+ for (const name of readdirSync(hermesProfiles)) {
344
+ roots.push({
345
+ label: path.posix.join("hermes-profiles", safePathSegment(name)),
346
+ dir: path.join(hermesProfiles, name, "logs"),
347
+ });
348
+ }
349
+ } catch {
350
+ // no profiles
351
+ }
352
+ const botcordAgents = path.join(homedir(), ".botcord", "agents");
353
+ try {
354
+ for (const agent of readdirSync(botcordAgents)) {
355
+ roots.push({
356
+ label: path.posix.join("botcord-hermes", safePathSegment(agent)),
357
+ dir: path.join(botcordAgents, agent, "hermes-home", "logs"),
358
+ });
359
+ }
360
+ } catch {
361
+ // no botcord agent homes
362
+ }
363
+ return roots.filter((root) => existsSync(root.dir));
364
+ }
365
+
366
+ function looksLikeLogFile(name: string): boolean {
367
+ const lower = name.toLowerCase();
368
+ return (
369
+ lower.endsWith(".log") ||
370
+ lower.endsWith(".jsonl") ||
371
+ lower.endsWith(".txt") ||
372
+ lower.includes("log")
373
+ );
374
+ }
375
+
376
+ function relativeBundlePath(root: string, file: string): string {
377
+ return path.relative(root, file).split(path.sep).map(safePathSegment).join("/");
378
+ }
379
+
380
+ function safePathSegment(raw: string): string {
381
+ return raw.replace(/[^A-Za-z0-9._-]+/g, "_").slice(0, 120) || "unknown";
382
+ }