@adhdev/daemon-core 0.9.82-rc.311 → 0.9.82-rc.313

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,220 @@
1
+ /**
2
+ * Daemon log tail reader — read the last N bytes of a daemon log file, newest
3
+ * bytes first, bounded so the result is safe to ship over a mesh P2P channel.
4
+ *
5
+ * Used by the mesh `get_mesh_node_logs` command: the coordinator asks a (possibly
6
+ * remote) daemon for its recent log tail instead of having to open a session and
7
+ * grep the file by hand. Because the mesh RPC envelope is sent as a single
8
+ * datachannel message (~256KB SCTP ceiling, no chunking), the returned tail is
9
+ * HARD-bounded by `tailBytes` (default 64KB, capped at MAX_TAIL_BYTES=128KB) and
10
+ * flags `truncated:true` when the file was larger.
11
+ *
12
+ * Boundary-safe: lines are cut on the newline byte (0x0A) only, which never
13
+ * appears inside a multibyte UTF-8 sequence, so decoding each complete byte
14
+ * segment never splits a multibyte char.
15
+ */
16
+
17
+ import * as fs from 'fs';
18
+ import { getCurrentDaemonLogPath, getDaemonLogDir } from './logger.js';
19
+
20
+ export const DEFAULT_TAIL_BYTES = 64 * 1024;
21
+ export const MAX_TAIL_BYTES = 128 * 1024;
22
+ const READ_CHUNK_BYTES = 64 * 1024;
23
+
24
+ export interface ReadDaemonLogTailArgs {
25
+ /** Date of the log file to read (defaults to today). YYYY-MM-DD string or Date. */
26
+ date?: string | Date;
27
+ /** Max bytes of tail to return. Clamped to (0, MAX_TAIL_BYTES]. Default 64KB. */
28
+ tailBytes?: number;
29
+ /** Optional regex source string; only lines matching (case-insensitive) are kept. */
30
+ grep?: string;
31
+ /** Optional epoch-ms floor; only lines whose leading [HH:MM:SS...] / ISO ts >= this are kept. */
32
+ sinceMs?: number;
33
+ }
34
+
35
+ export interface DaemonLogTailResult {
36
+ success: boolean;
37
+ error?: string;
38
+ lines: string[];
39
+ truncated: boolean;
40
+ logPath: string;
41
+ platform: NodeJS.Platform;
42
+ bytesReturned: number;
43
+ /** True when a grep/since filter dropped lines from the raw tail window. */
44
+ filtered: boolean;
45
+ /** The grep source actually applied (echoed back for clarity). */
46
+ grep?: string;
47
+ }
48
+
49
+ function resolveLogPath(date?: string | Date): string {
50
+ if (date instanceof Date) return getCurrentDaemonLogPath(date);
51
+ if (typeof date === 'string' && date.trim()) {
52
+ const parsed = new Date(`${date.trim()}T00:00:00.000Z`);
53
+ if (!Number.isNaN(parsed.getTime())) return getCurrentDaemonLogPath(parsed);
54
+ }
55
+ return getCurrentDaemonLogPath();
56
+ }
57
+
58
+ function clampTailBytes(tailBytes?: number): number {
59
+ if (!Number.isFinite(tailBytes) || (tailBytes as number) <= 0) return DEFAULT_TAIL_BYTES;
60
+ return Math.min(Math.floor(tailBytes as number), MAX_TAIL_BYTES);
61
+ }
62
+
63
+ /**
64
+ * Read up to `limitBytes` from the end of `filePath`, on a UTF-8 line boundary.
65
+ * Returns the decoded text, whether the read was truncated (file bigger than the
66
+ * window), and the number of bytes actually decoded.
67
+ */
68
+ function readByteBoundedTail(filePath: string, limitBytes: number): { text: string; truncated: boolean; bytesReturned: number } {
69
+ const fd = fs.openSync(filePath, 'r');
70
+ try {
71
+ const stat = fs.fstatSync(fd);
72
+ const size = stat.size;
73
+ if (size === 0) return { text: '', truncated: false, bytesReturned: 0 };
74
+
75
+ const want = Math.min(limitBytes, size);
76
+ let start = size - want;
77
+ const truncated = start > 0;
78
+
79
+ // Collect chunks newest-last into a buffer covering [start, size).
80
+ const buffers: Buffer[] = [];
81
+ let position = start;
82
+ while (position < size) {
83
+ const chunkSize = Math.min(READ_CHUNK_BYTES, size - position);
84
+ const chunk = Buffer.alloc(chunkSize);
85
+ fs.readSync(fd, chunk, 0, chunkSize, position);
86
+ buffers.push(chunk);
87
+ position += chunkSize;
88
+ }
89
+ let buf = Buffer.concat(buffers);
90
+
91
+ // If we truncated mid-line, drop the leading partial line so we never emit
92
+ // a half-decoded line (and never split a multibyte char at the window edge).
93
+ if (truncated) {
94
+ const firstNewline = buf.indexOf(0x0a);
95
+ if (firstNewline >= 0) {
96
+ buf = buf.subarray(firstNewline + 1);
97
+ }
98
+ }
99
+ return { text: buf.toString('utf-8'), truncated, bytesReturned: buf.length };
100
+ } finally {
101
+ fs.closeSync(fd);
102
+ }
103
+ }
104
+
105
+ // Parse a leading timestamp from a log line into epoch ms. The unified logger
106
+ // writes `[HH:MM:SS.mmm]` (local time, today's date) and the startup banner uses
107
+ // a full timestamp; we best-effort parse `[HH:MM:SS...]` against the file's date.
108
+ // Returns null when no timestamp can be extracted (line is then kept by sinceMs).
109
+ function parseLineEpochMs(line: string, fileDate: Date): number | null {
110
+ const m = line.match(/^\[(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?\]/);
111
+ if (!m) {
112
+ // Try an embedded ISO timestamp as a fallback.
113
+ const iso = line.match(/\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?/);
114
+ if (iso) {
115
+ const t = Date.parse(iso[0].replace(' ', 'T'));
116
+ return Number.isNaN(t) ? null : t;
117
+ }
118
+ return null;
119
+ }
120
+ const d = new Date(fileDate);
121
+ d.setHours(Number(m[1]), Number(m[2]), Number(m[3]), m[4] ? Number(m[4].padEnd(3, '0')) : 0);
122
+ return d.getTime();
123
+ }
124
+
125
+ /**
126
+ * Read the daemon log tail for `date` (default today), bounded to `tailBytes`,
127
+ * with optional grep (regex source) and sinceMs filters. Falls back to the
128
+ * size-rotation backup (`*.1.log`) when the primary file does not exist.
129
+ */
130
+ export function readDaemonLogTail(args: ReadDaemonLogTailArgs = {}): DaemonLogTailResult {
131
+ const platform = process.platform;
132
+ const limitBytes = clampTailBytes(args.tailBytes);
133
+ let logPath = resolveLogPath(args.date);
134
+
135
+ // Fall back to the size-rotation backup if the active file is absent.
136
+ if (!fs.existsSync(logPath)) {
137
+ const backup = logPath.replace(/\.log$/, '.1.log');
138
+ if (fs.existsSync(backup)) {
139
+ logPath = backup;
140
+ } else {
141
+ return {
142
+ success: false,
143
+ error: `No daemon log file at ${logPath} (dir: ${getDaemonLogDir()})`,
144
+ lines: [],
145
+ truncated: false,
146
+ logPath,
147
+ platform,
148
+ bytesReturned: 0,
149
+ filtered: false,
150
+ };
151
+ }
152
+ }
153
+
154
+ let raw: { text: string; truncated: boolean; bytesReturned: number };
155
+ try {
156
+ raw = readByteBoundedTail(logPath, limitBytes);
157
+ } catch (e: any) {
158
+ return {
159
+ success: false,
160
+ error: `Failed to read ${logPath}: ${e?.message ?? String(e)}`,
161
+ lines: [],
162
+ truncated: false,
163
+ logPath,
164
+ platform,
165
+ bytesReturned: 0,
166
+ filtered: false,
167
+ };
168
+ }
169
+
170
+ let lines = raw.text.split('\n');
171
+ // A trailing newline yields a final empty element — drop it.
172
+ if (lines.length && lines[lines.length - 1] === '') lines.pop();
173
+ const rawCount = lines.length;
174
+
175
+ // since filter
176
+ if (Number.isFinite(args.sinceMs)) {
177
+ const fileDate = args.date instanceof Date
178
+ ? args.date
179
+ : typeof args.date === 'string' && args.date.trim()
180
+ ? new Date(`${args.date.trim()}T00:00:00.000Z`)
181
+ : new Date();
182
+ const floor = args.sinceMs as number;
183
+ lines = lines.filter((line) => {
184
+ const ts = parseLineEpochMs(line, fileDate);
185
+ // Keep lines with no parseable timestamp (continuation/stack lines).
186
+ return ts === null || ts >= floor;
187
+ });
188
+ }
189
+
190
+ // grep filter
191
+ let appliedGrep: string | undefined;
192
+ if (typeof args.grep === 'string' && args.grep.trim()) {
193
+ appliedGrep = args.grep.trim();
194
+ let re: RegExp | null = null;
195
+ try {
196
+ re = new RegExp(appliedGrep, 'i');
197
+ } catch {
198
+ re = null;
199
+ }
200
+ if (re) {
201
+ const compiled = re;
202
+ lines = lines.filter((line) => compiled.test(line));
203
+ } else {
204
+ // Invalid regex → fall back to a literal substring match.
205
+ const needle = appliedGrep.toLowerCase();
206
+ lines = lines.filter((line) => line.toLowerCase().includes(needle));
207
+ }
208
+ }
209
+
210
+ return {
211
+ success: true,
212
+ lines,
213
+ truncated: raw.truncated,
214
+ logPath,
215
+ platform,
216
+ bytesReturned: raw.bytesReturned,
217
+ filtered: lines.length !== rawCount,
218
+ ...(appliedGrep ? { grep: appliedGrep } : {}),
219
+ };
220
+ }
@@ -342,6 +342,7 @@ const TOOLS_SECTION = `## Available Tools
342
342
  | \`mesh_read_debug\` | Collect a daemon-side chat/parser debug bundle for a session |
343
343
  | \`mesh_task_history\` | Read the task ledger — dispatches, completions, failures. Use to understand what has been done before deciding next steps |
344
344
  | \`mesh_git_status\` | Check git status on a specific node |
345
+ | \`mesh_read_node_logs\` | Fetch a remote node's daemon log tail directly over P2P (grep/since/byte-bounded, secrets redacted) — no session/PowerShell needed to debug a node's daemon |
345
346
  | \`mesh_fast_forward_node\` | Safely dry-run or explicitly execute an obvious clean fast-forward without launching an agent session |
346
347
  | \`mesh_checkpoint\` | Create a git checkpoint on a node |
347
348
  | \`mesh_approve\` | Approve/reject a pending agent action |
@@ -22,6 +22,7 @@ import { LOG } from '../logging/logger.js';
22
22
  import { VersionArchive } from './version-archive.js';
23
23
  import type {
24
24
  ProviderCompatibilityEntry,
25
+ ProviderControlDef,
25
26
  ProviderModule,
26
27
  ProviderCategory,
27
28
  ProviderScripts,
@@ -87,6 +88,70 @@ export interface MachineProviderConfig {
87
88
  lastVerification?: MachineProviderCheckResult;
88
89
  }
89
90
 
91
+ /**
92
+ * Translate a spec `control_bar` array into the web-facing
93
+ * `ProviderControlDef[]` shape the dashboard renders.
94
+ *
95
+ * The two shapes are distinct: `control_bar` entries are daemon-side
96
+ * `{ id, label, visible_when_state, action }` records driving
97
+ * SpecCliAdapter.invokeScript, while the dashboard's chat bar reads
98
+ * `ProviderControlDef` (`{ id, type, label, placement, ... }`). Spec
99
+ * providers (claude-cli / codex-cli) historically declared *only*
100
+ * `control_bar`, so the dashboard saw no controls at all — the Model / Mode
101
+ * pickers never rendered. This bridges that gap without changing how the
102
+ * controls actually dispatch.
103
+ *
104
+ * Script-name contract: the dashboard sends the control's
105
+ * `listScript` / `setScript` / `invokeScript` name through
106
+ * `invoke_provider_script`, which gates on `provider.scripts[<name>]` and then
107
+ * routes to `SpecCliAdapter.invokeScript(<name>)` — which matches the name
108
+ * against `control_bar[].id`. So every synthesized script name MUST equal the
109
+ * control id (the loader stubs `provider.scripts[id]` from the same source).
110
+ *
111
+ * Mapping:
112
+ * open_picker → select (dynamic): list + set both keyed on the control id;
113
+ * the adapter distinguishes LIST vs SELECT by the presence of
114
+ * a choice arg, so one id serves both roles.
115
+ * send_keys → action: one-shot keystroke (stop, cycle_mode).
116
+ * attach_image → skipped: it needs an image blob from a file picker, not a
117
+ * bare bar button; surfacing it as an `action` would only
118
+ * produce a button that errors with "requires args.blob".
119
+ */
120
+ function synthesizeControlsFromControlBar(specControls: any[]): ProviderControlDef[] {
121
+ const out: ProviderControlDef[] = [];
122
+ specControls.forEach((ctl, index) => {
123
+ const id = typeof ctl?.id === 'string' ? ctl.id.trim() : '';
124
+ const actionType = ctl?.action?.type;
125
+ if (!id || !actionType) return;
126
+ const label = typeof ctl?.label === 'string' && ctl.label.trim() ? ctl.label : id;
127
+ if (actionType === 'open_picker') {
128
+ out.push({
129
+ id,
130
+ type: 'select',
131
+ label,
132
+ placement: 'bar',
133
+ dynamic: true,
134
+ listScript: id,
135
+ setScript: id,
136
+ readFrom: id,
137
+ order: index,
138
+ });
139
+ } else if (actionType === 'send_keys') {
140
+ out.push({
141
+ id,
142
+ type: 'action',
143
+ label,
144
+ placement: 'bar',
145
+ invokeScript: id,
146
+ resultDisplay: 'none',
147
+ order: index,
148
+ });
149
+ }
150
+ // attach_image intentionally skipped — see fn doc.
151
+ });
152
+ return out;
153
+ }
154
+
90
155
  type CliDetectionEntry = {
91
156
  id: string;
92
157
  displayName: string;
@@ -1271,6 +1336,19 @@ export class ProviderLoader {
1271
1336
  });
1272
1337
  }
1273
1338
  }
1339
+ // Bridge the spec control_bar into the web-facing controls schema so
1340
+ // the dashboard chat bar actually renders Model/Mode pickers. Only
1341
+ // synthesize when the provider hasn't already declared its own
1342
+ // `controls` in provider.v1.json (e.g. hermes-cli) — an explicit
1343
+ // declaration wins and must not be clobbered.
1344
+ const hasDeclaredControls = Array.isArray((resolved as any).controls)
1345
+ && (resolved as any).controls.length > 0;
1346
+ if (!hasDeclaredControls) {
1347
+ const synthesized = synthesizeControlsFromControlBar(specControls);
1348
+ if (synthesized.length > 0) {
1349
+ resolved.controls = synthesized;
1350
+ }
1351
+ }
1274
1352
  }
1275
1353
  if (nh) {
1276
1354
  let reader: ((input: any) => any) | null = null;
@@ -355,8 +355,14 @@ export class SpecCliAdapter implements CliAdapter {
355
355
  const choiceIndex = typeof flat.choiceIndex === 'number' ? flat.choiceIndex
356
356
  : typeof flat.choiceIndex === 'string' && flat.choiceIndex.trim() ? Number(flat.choiceIndex)
357
357
  : undefined;
358
+ // `value` is the arg the dashboard's generic value-control set path
359
+ // sends ({ value: <chosen option> }). control_bar pickers are
360
+ // surfaced to the dashboard as dynamic `select` controls whose
361
+ // option values are the screen-parsed labels, so a bare `value`
362
+ // is just a label to match against the live choices.
358
363
  const choiceLabel = typeof flat.choiceLabel === 'string' ? flat.choiceLabel
359
364
  : typeof flat.choice === 'string' ? flat.choice
365
+ : typeof flat.value === 'string' ? flat.value
360
366
  : undefined;
361
367
  if ((typeof choiceIndex === 'number' && Number.isFinite(choiceIndex)) || (choiceLabel && choiceLabel.trim())) {
362
368
  return this.selectPickerChoice(ctl, action, choiceIndex, choiceLabel);
@@ -631,6 +631,12 @@ export interface RepoMeshPeerConnectionStatus {
631
631
  transport: RepoMeshPeerConnectionTransport;
632
632
  reported: boolean;
633
633
  reason?: string;
634
+ /**
635
+ * Round-trip time in ms for the selected candidate pair, as sampled by the
636
+ * coordinator daemon when connected. Optional — older daemons and not_reported
637
+ * fallbacks omit it; the dashboard must treat it as best-effort telemetry.
638
+ */
639
+ rttMs?: number;
634
640
  lastStateChangeAt?: string;
635
641
  lastConnectedAt?: string;
636
642
  lastCommandAt?: string;