dsh-hive-runner 0.6.1 → 0.6.7

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/lib/runs.js ADDED
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Last-run records for Hive cards: `<repo>/.hive/runs/<cardId>.json`.
3
+ *
4
+ * One file per card, overwritten by every attempt, so the panel can show what
5
+ * the worker produced the last time the card ran without parsing a log.
6
+ *
7
+ * The record is observability only: a failed write must never fail the card,
8
+ * so `writeRunRecord` swallows every filesystem error and returns a boolean.
9
+ * A record produced by a worker activation also carries the child Session id
10
+ * (`sessionId`) and the model-facing child name (`agentName`), so the panel can
11
+ * open that worker's conversation; both keys are omitted when the attempt never
12
+ * reached an activation (for example an activation that threw before returning
13
+ * a child). An attempt whose `hive guard` announcement found another agent on
14
+ * the same or a related path carries an `overlaps` array (see
15
+ * `normalizeOverlaps`) on the opening `running` write and on the terminal write.
16
+ * The path is derived from the card id after `ID_RE` validation, which rejects
17
+ * path separators, so a card id can never escape `.hive/runs`.
18
+ *
19
+ * `output` is the worker's final result message, not its process: the text blocks
20
+ * of the last assistant message only (lib/round.js strips reasoning/thinking, tool
21
+ * calls and narration; a provider without a typed text block falls back to the last
22
+ * non-empty text). It keeps the *smaller* of the last 200 lines and the last 32 KiB
23
+ * of UTF-8, which bounds the file on disk no matter how chatty the worker is.
24
+ */
25
+ import fs from 'node:fs';
26
+ import path from 'node:path';
27
+
28
+ import { ID_RE } from './commands.js';
29
+
30
+ /** Directory (relative to the repository root) holding one file per card. */
31
+ export const RUNS_DIR = path.join('.hive', 'runs');
32
+ /** Hard cap on the stored `output` bytes. */
33
+ export const RUN_OUTPUT_MAX_BYTES = 32 * 1024;
34
+ /** Hard cap on the stored `output` lines. */
35
+ export const RUN_OUTPUT_MAX_LINES = 200;
36
+ /** Hard cap on the stored `overlaps` entries. */
37
+ export const RUN_OVERLAPS_MAX = 100;
38
+
39
+ /** Valid record statuses. */
40
+ export const RUN_STATUSES = Object.freeze(['done', 'failed', 'running']);
41
+
42
+ /** Last `maxBytes` bytes of `text`, advanced to a UTF-8 code point boundary. */
43
+ function tailBytes(text, maxBytes) {
44
+ const buffer = Buffer.from(text, 'utf8');
45
+ if (buffer.length <= maxBytes) return text;
46
+ let start = buffer.length - maxBytes;
47
+ while (start < buffer.length && (buffer[start] & 0xc0) === 0x80) start += 1;
48
+ return buffer.subarray(start).toString('utf8');
49
+ }
50
+
51
+ /**
52
+ * Keep the smaller of the last `maxLines` lines and the last `maxBytes` bytes.
53
+ * @param {string} text - worker output (stdout + stderr tail).
54
+ * @param {{ maxBytes?: number, maxLines?: number }} [limits]
55
+ * @returns {string}
56
+ */
57
+ export function truncateRunOutput(text, { maxBytes = RUN_OUTPUT_MAX_BYTES, maxLines = RUN_OUTPUT_MAX_LINES } = {}) {
58
+ const value = typeof text === 'string' ? text : String(text ?? '');
59
+ const lines = value.split('\n');
60
+ const byLines = lines.length > maxLines ? lines.slice(-maxLines).join('\n') : value;
61
+ const byBytes = tailBytes(value, maxBytes);
62
+ return Buffer.byteLength(byBytes) < Buffer.byteLength(byLines) ? byBytes : byLines;
63
+ }
64
+
65
+ /**
66
+ * Normalize the optional announcement overlaps of one attempt.
67
+ *
68
+ * The consensus board reports `{ key, agent, task, expiresAt }` entries. Only
69
+ * entries with a non-empty string `agent` survive; `key`, `task` and
70
+ * `expiresAt` are copied when they are non-empty strings, and everything else
71
+ * is dropped. The list is capped at `RUN_OVERLAPS_MAX` entries.
72
+ * @param {unknown} value
73
+ * @returns {Array<{ agent: string, key?: string, task?: string, expiresAt?: string }>}
74
+ */
75
+ export function normalizeOverlaps(value) {
76
+ if (!Array.isArray(value)) return [];
77
+ const overlaps = [];
78
+ for (const entry of value) {
79
+ if (overlaps.length >= RUN_OVERLAPS_MAX) break;
80
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) continue;
81
+ if (typeof entry.agent !== 'string' || entry.agent.trim() === '') continue;
82
+ const overlap = { agent: entry.agent };
83
+ for (const key of ['key', 'task', 'expiresAt']) {
84
+ if (typeof entry[key] === 'string' && entry[key].trim() !== '') overlap[key] = entry[key];
85
+ }
86
+ overlaps.push(overlap);
87
+ }
88
+ return overlaps;
89
+ }
90
+
91
+ /** Hard cap on the stored `lessons.scopes` entries. */
92
+ export const RUN_LESSON_SCOPES_MAX = 100;
93
+
94
+ /**
95
+ * Normalize the optional recall summary of one attempt.
96
+ *
97
+ * The runner always writes it after recall finishes: `{ count, scopes }` on a
98
+ * successful recall, `{ count: 0, scopes, error }` when recall failed. The
99
+ * panel reads `lessons.count` to show "recalled N lessons / no lesson matched",
100
+ * so the three keys are fixed.
101
+ * @param {unknown} value
102
+ * @returns {{ count: number, scopes: string[], error?: string } | null}
103
+ */
104
+ export function normalizeLessons(value) {
105
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return null;
106
+ const count = Number.isInteger(value.count) && value.count >= 0 ? value.count : 0;
107
+ const scopes = Array.isArray(value.scopes)
108
+ ? value.scopes
109
+ .filter((scope) => typeof scope === 'string' && scope.trim() !== '')
110
+ .slice(0, RUN_LESSON_SCOPES_MAX)
111
+ : [];
112
+ const lessons = { count, scopes };
113
+ if (typeof value.error === 'string' && value.error.trim() !== '') lessons.error = value.error;
114
+ return lessons;
115
+ }
116
+
117
+ /**
118
+ * Resolve the record file for one card, validating the id and containment.
119
+ * @param {string} repo - repository root.
120
+ * @param {string} cardId - Hive card id (`ID_RE`).
121
+ * @returns {{ dir: string, file: string }}
122
+ */
123
+ export function runRecordPath(repo, cardId) {
124
+ if (typeof repo !== 'string' || repo === '') throw new TypeError('runRecordPath: repo is required');
125
+ if (typeof cardId !== 'string' || !ID_RE.test(cardId)) {
126
+ throw new TypeError('runRecordPath: cardId must match ' + String(ID_RE));
127
+ }
128
+ const dir = path.resolve(repo, RUNS_DIR);
129
+ const file = path.resolve(dir, cardId + '.json');
130
+ if (!file.startsWith(dir + path.sep)) throw new TypeError('runRecordPath: cardId escapes ' + RUNS_DIR);
131
+ return { dir, file };
132
+ }
133
+
134
+ /** Normalize one record to the documented shape. */
135
+ function normalizeRecord(record) {
136
+ const status = RUN_STATUSES.includes(record?.status) ? record.status : 'running';
137
+ const normalized = {
138
+ cardId: record.cardId,
139
+ agent: typeof record.agent === 'string' ? record.agent : '',
140
+ startedAt: typeof record.startedAt === 'string' ? record.startedAt : new Date().toISOString(),
141
+ endedAt: typeof record.endedAt === 'string' ? record.endedAt : null,
142
+ status,
143
+ output: truncateRunOutput(record.output),
144
+ };
145
+ if (Number.isInteger(record.exitCode)) normalized.exitCode = record.exitCode;
146
+ if (typeof record.commit === 'string' && record.commit !== '') normalized.commit = record.commit;
147
+ // Durable child identity: present exactly when a worker activation started.
148
+ if (typeof record.sessionId === 'string' && record.sessionId !== '') normalized.sessionId = record.sessionId;
149
+ if (typeof record.agentName === 'string' && record.agentName !== '') normalized.agentName = record.agentName;
150
+ // Announcement overlaps: advisory information from `hive guard --json`, kept
151
+ // on both the running and the terminal write. Omitted when empty.
152
+ const overlaps = normalizeOverlaps(record.overlaps);
153
+ if (overlaps.length > 0) normalized.overlaps = overlaps;
154
+ // Recall summary: fixed keys consumed by the panel (lessons.count/.scopes/.error).
155
+ const lessons = normalizeLessons(record.lessons);
156
+ if (lessons !== null) normalized.lessons = lessons;
157
+ // Liveness telemetry: heartbeat turns to warn when the worker produced no new
158
+ // output for heartbeatWarnMs while still running.
159
+ if (record.heartbeat === 'ok' || record.heartbeat === 'warn') normalized.heartbeat = record.heartbeat;
160
+ if (typeof record.lastOutputAt === 'string' && record.lastOutputAt !== '') normalized.lastOutputAt = record.lastOutputAt;
161
+ // Which Agent was used as the worker's parent (the registered queen Session).
162
+ if (record.parentSource === 'queen') normalized.parentSource = record.parentSource;
163
+ return normalized;
164
+ }
165
+
166
+ /**
167
+ * Write (overwrite) the last-run record for one card. Best effort.
168
+ * @param {string} repo - repository root.
169
+ * @param {object} record - `{ cardId, agent, startedAt, endedAt, status, exitCode?, commit?, sessionId?, agentName?, overlaps?, lessons?, output }`.
170
+ * @returns {boolean} true when the file was written.
171
+ */
172
+ export function writeRunRecord(repo, record) {
173
+ try {
174
+ if (record === null || typeof record !== 'object') return false;
175
+ const { dir, file } = runRecordPath(repo, record.cardId);
176
+ const payload = normalizeRecord(record);
177
+ fs.mkdirSync(dir, { recursive: true });
178
+ fs.writeFileSync(file, JSON.stringify(payload, null, 2) + '\n');
179
+ return true;
180
+ } catch {
181
+ // Observability must never break a card run.
182
+ return false;
183
+ }
184
+ }
package/lib/shell.js CHANGED
@@ -37,7 +37,7 @@ export function createShellRunner({ ctx, config = {} }) {
37
37
  /**
38
38
  * Run one already-allowlisted command through the shell seam.
39
39
  * @param {string} command shell command string (the seam executes it with bash -c)
40
- * @param {{ workdir?: string, session?: object, signal?: AbortSignal, timeoutMs?: number, stdoutMaxBytes?: number }} [options]
40
+ * @param {{ workdir?: string, session?: object, signal?: AbortSignal, timeoutMs?: number, stdoutMaxBytes?: number, env?: Record<string, string> }} [options]
41
41
  * @returns {Promise<{ command: string, exitCode: number | null, signal: string | null, timedOut: boolean, aborted: boolean, stdout: string, stderr: string, sandbox?: object }>}
42
42
  */
43
43
  return async function run(command, options = {}) {
@@ -49,6 +49,8 @@ export function createShellRunner({ ctx, config = {} }) {
49
49
  };
50
50
  if (workdir !== undefined) request.workdir = workdir;
51
51
  if (signal !== undefined) request.signal = signal;
52
+ // Ordinary env entries are merged after credential scrubbing by the executor.
53
+ if (options.env !== undefined) request.env = options.env;
52
54
  if (sandboxPolicy !== undefined && sandboxPolicy !== null) {
53
55
  const base = sandboxPolicy.resolve(session === undefined ? {} : { session });
54
56
  request.sandboxPolicy = session === undefined && workdir !== undefined
package/lib/supervisor.js CHANGED
@@ -104,6 +104,8 @@ export class HiveSupervisor {
104
104
  * @param {(repo: string, options: object) => Promise<object[]>} [options.listReady]
105
105
  * @param {(request: object) => Promise<object>} [options.runCard]
106
106
  * @param {(repo: string) => void} [options.preflight] round-start environment check (merge-on-commit hook)
107
+ * @param {(repo: string) => object[]} [options.activeRuns] live worker descriptors for status
108
+ * @param {{ sessionId: string | null }} [options.queenSession] shared queen-session registration
107
109
  * @param {(repo: string) => Promise<string|{mode: string}>} [options.readMode] Hive mode reader (free/freeze)
108
110
  * @param {() => Promise<string[]>} [options.discover]
109
111
  * @param {Console} [options.logger]
@@ -131,6 +133,10 @@ export class HiveSupervisor {
131
133
  this.listReady = options.listReady;
132
134
  this.runCard = options.runCard;
133
135
  this.preflight = typeof options.preflight === 'function' ? options.preflight : undefined;
136
+ this.activeRuns = typeof options.activeRuns === 'function' ? options.activeRuns : undefined;
137
+ // Shared with the round runner: the Session registered by the panel when the
138
+ // queen takes over. Nothing is dispatched until this is set.
139
+ this.queenSession = options.queenSession ?? { sessionId: null };
134
140
  this.readMode = typeof options.readMode === 'function' ? options.readMode : undefined;
135
141
  this.discover = options.discover;
136
142
  this.logger = options.logger === undefined ? console : options.logger;
@@ -283,6 +289,25 @@ export class HiveSupervisor {
283
289
  return this.#snapshot(entry);
284
290
  }
285
291
 
292
+ /**
293
+ * Register the queen Session that owns every worker. The panel calls this when
294
+ * its init/queen activation succeeds; until then no card is dispatched.
295
+ * @param {string} sessionId live DSH Session id of the queen conversation
296
+ * @returns {object} supervisor status
297
+ */
298
+ setQueenSession(sessionId) {
299
+ if (typeof sessionId !== 'string' || sessionId.trim() === '') {
300
+ throw new TypeError('setQueenSession: sessionId must be a non-empty string');
301
+ }
302
+ this.queenSession.sessionId = sessionId.trim();
303
+ for (const entry of this.repos.values()) {
304
+ entry.waiting = null;
305
+ entry.nextAttemptAt = this.now();
306
+ }
307
+ this.#log('info', 'registered queen session', this.queenSession.sessionId);
308
+ return this.status();
309
+ }
310
+
286
311
  /** Arm the timer; the first tick runs immediately (asynchronously). */
287
312
  start() {
288
313
  if (this.started) return;
@@ -340,8 +365,15 @@ export class HiveSupervisor {
340
365
 
341
366
  /** Serializable supervisor + per-repository status. */
342
367
  status() {
368
+ const waiting = this.queenSession.sessionId === null || this.queenSession.sessionId === undefined
369
+ ? 'no-queen-session'
370
+ : null;
343
371
  return {
344
372
  started: this.started,
373
+ // The queen Session registered by the panel; every card worker is parented
374
+ // to it. Until it is registered nothing is dispatched.
375
+ queenSessionId: this.queenSession.sessionId ?? null,
376
+ waiting,
345
377
  intervalMs: this.intervalMs,
346
378
  idleBackoffMs: this.idleBackoffMs,
347
379
  maxConcurrentRepos: this.maxConcurrentRepos,
@@ -384,6 +416,15 @@ export class HiveSupervisor {
384
416
  const signal = this.abortController?.signal;
385
417
  try {
386
418
  if (entry.paused) return { repo: entry.repo, state: entry.state };
419
+ // One parent only: the queen Session registered by the panel. Before that
420
+ // registration the supervisor waits; it never picks another Session.
421
+ if (this.queenSession.sessionId === null || this.queenSession.sessionId === undefined) {
422
+ entry.state = STATES.IDLE;
423
+ entry.lastError = null;
424
+ entry.lastCheckAt = this.now();
425
+ entry.nextAttemptAt = this.now() + this.intervalMs;
426
+ return { repo: entry.repo, state: entry.state, waiting: 'no-queen-session' };
427
+ }
387
428
  if (typeof this.listReady !== 'function') throw new Error('supervisor has no listReady implementation');
388
429
  if (typeof this.runCard !== 'function') throw new Error('supervisor has no runCard implementation');
389
430
 
@@ -556,6 +597,12 @@ export class HiveSupervisor {
556
597
  lastResults: entry.lastResults,
557
598
  backlog: { ...entry.backlog },
558
599
  roles: copyRoles(entry.roles),
600
+ // Live workers currently running in this repository: sessionId/start time
601
+ // let the panel jump to the conversation or diagnose a stuck card.
602
+ workers: this.#workers(entry.repo),
603
+ waiting: this.queenSession.sessionId === null || this.queenSession.sessionId === undefined
604
+ ? 'no-queen-session'
605
+ : null,
559
606
  limitsError: entry.limitsError ?? null,
560
607
  environmentError: entry.environmentError ?? null,
561
608
  mode: entry.mode ?? null,
@@ -564,6 +611,15 @@ export class HiveSupervisor {
564
611
  };
565
612
  }
566
613
 
614
+ /** Best-effort live worker list for status; observability never throws. */
615
+ #workers(repo) {
616
+ try {
617
+ return typeof this.activeRuns === 'function' ? this.activeRuns(repo) : [];
618
+ } catch {
619
+ return [];
620
+ }
621
+ }
622
+
567
623
  #log(level, ...args) {
568
624
  if (this.logger === false || this.logger === null) return;
569
625
  const write = this.logger?.[level];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-hive-runner",
3
- "version": "0.6.1",
3
+ "version": "0.6.7",
4
4
  "description": "DSH host plugin for Hive: a resident supervisor that runs one DSH subagent per ready task card, with per-role worker limits, pause/resume and Hive tools.",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -20,7 +20,7 @@
20
20
  "LICENSE"
21
21
  ],
22
22
  "engines": {
23
- "node": ">=22"
23
+ "node": ">=22.19"
24
24
  },
25
25
  "scripts": {
26
26
  "test": "node --test test/*.test.js",