dsh-hive-runner 0.6.4 → 0.7.0

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/notify.js ADDED
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Deliver a queen-facing message through the live DSH Agent.
3
+ *
4
+ * A host plugin may inject user-role messages into a live Session through the
5
+ * public `Agent` API (`followup`, `steer`, `inject`). The message is an ordinary
6
+ * identified UserMessage: `{ id, role: 'user', content, source }`. Its source
7
+ * kind is this plugin's name — the session log only requires a non-empty string
8
+ * kind and consumers fall through unknown producers, so no DSH change is needed.
9
+ *
10
+ * Delivery policy:
11
+ * - `followup` — queue an ordinary next-turn prompt and wake the driver. This
12
+ * is what an anomaly digest wants: the queen should act even when idle;
13
+ * - `steer` — only if a future Agent lacks `followup`; consumed at the next
14
+ * step boundary of the running turn;
15
+ * - `inject` — last resort; context without waking (the next patrol retries).
16
+ *
17
+ * No live Session (panel closed, agent disposed, DSH headless): delivery reports
18
+ * `no-live-queen-session` and the caller keeps the digest in the pending list.
19
+ *
20
+ * @module dsh-hive-runner/notify
21
+ */
22
+ import { randomUUID } from 'node:crypto';
23
+
24
+ /** Message source kind recorded in the Session log. */
25
+ export const QUEEN_NOTICE_SOURCE = 'hive-runner';
26
+
27
+ /**
28
+ * One identified user-role message. Mirrors `createUserMessage` from
29
+ * `@deepseek-ai/dsh-llm` without importing the package (the runner must stay a
30
+ * one-peer-dependency plugin): identity is a fresh UUID, content is one text
31
+ * block, and the source kind marks the producer.
32
+ * @param {string} body
33
+ * @param {string} [source]
34
+ * @returns {{ id: string, role: 'user', content: Array<{ type: 'text', text: string }>, source: { kind: string } }}
35
+ */
36
+ export function createQueenMessage(body, source = QUEEN_NOTICE_SOURCE) {
37
+ return {
38
+ id: randomUUID(),
39
+ role: 'user',
40
+ content: [{ type: 'text', text: String(body) }],
41
+ source: { kind: typeof source === 'string' && source !== '' ? source : QUEEN_NOTICE_SOURCE },
42
+ };
43
+ }
44
+
45
+ /** Resolve the live Agent for the registered queen Session, if any. */
46
+ export function resolveQueenAgent(ctx, queenSession) {
47
+ const sessionId = queenSession?.sessionId;
48
+ if (typeof sessionId !== 'string' || sessionId === '') return undefined;
49
+ try {
50
+ const agents = typeof ctx?.get === 'function' ? ctx.get('agents') : undefined;
51
+ const agent = typeof agents?.get === 'function' ? agents.get(sessionId) : undefined;
52
+ return agent === null ? undefined : agent;
53
+ } catch {
54
+ return undefined;
55
+ }
56
+ }
57
+
58
+ /** Resolve one live Agent by Session id (worker guidance uses this too). */
59
+ export function resolveAgent(ctx, sessionId) {
60
+ if (typeof sessionId !== 'string' || sessionId === '') return undefined;
61
+ try {
62
+ const agents = typeof ctx?.get === 'function' ? ctx.get('agents') : undefined;
63
+ const agent = typeof agents?.get === 'function' ? agents.get(sessionId) : undefined;
64
+ return agent === null ? undefined : agent;
65
+ } catch {
66
+ return undefined;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Deliver one user-role message to an arbitrary live Session (worker guidance).
72
+ * A running agent gets `steer` (next step boundary); an idle agent gets
73
+ * `followup` (starts a turn). Falls back through the available inbox methods.
74
+ * @param {{ ctx: object }} options
75
+ * @param {string} sessionId
76
+ * @param {string} body
77
+ * @param {{ prefer?: 'steer' | 'followup' | 'inject' }} [delivery]
78
+ * @returns {{ delivered: boolean, via?: string, reason?: string, error?: string }}
79
+ */
80
+ export function deliverToSession({ ctx } = {}, sessionId, body, delivery = {}) {
81
+ if (typeof body !== 'string' || body.trim() === '') return { delivered: false, reason: 'empty-message' };
82
+ const agent = resolveAgent(ctx, sessionId);
83
+ if (agent === undefined) return { delivered: false, reason: 'no-live-session' };
84
+ const message = createQueenMessage(body);
85
+ const prefer = delivery.prefer;
86
+ const order = prefer === 'followup'
87
+ ? ['followup', 'steer', 'inject']
88
+ : prefer === 'inject'
89
+ ? ['inject', 'followup', 'steer']
90
+ : ['steer', 'followup', 'inject'];
91
+ for (const method of order) {
92
+ if (typeof agent[method] !== 'function') continue;
93
+ try {
94
+ agent[method](message);
95
+ return { delivered: true, via: method };
96
+ } catch (error) {
97
+ return { delivered: false, reason: 'delivery-failed', error: error instanceof Error ? error.message : String(error) };
98
+ }
99
+ }
100
+ return { delivered: false, reason: 'no-inbox-api' };
101
+ }
102
+
103
+ /**
104
+ * Create the delivery facade.
105
+ * @param {{ ctx: object, queenSession: { sessionId: string|null }, log?: (level: string, ...args: unknown[]) => void }} options
106
+ * @returns {{ deliver: (body: string) => { delivered: boolean, via?: string, reason?: string }, hasLiveQueen: () => boolean }}
107
+ */
108
+ export function createQueenNotifier({ ctx, queenSession, log = () => {} } = {}) {
109
+ const target = () => resolveQueenAgent(ctx, queenSession);
110
+
111
+ function deliver(body) {
112
+ if (typeof body !== 'string' || body.trim() === '') {
113
+ return { delivered: false, reason: 'empty-digest' };
114
+ }
115
+ const agent = target();
116
+ if (agent === undefined) return { delivered: false, reason: 'no-live-queen-session' };
117
+ const message = createQueenMessage(body);
118
+ try {
119
+ if (typeof agent.followup === 'function') {
120
+ agent.followup(message);
121
+ return { delivered: true, via: 'followup' };
122
+ }
123
+ if (typeof agent.steer === 'function') {
124
+ agent.steer(message);
125
+ return { delivered: true, via: 'steer' };
126
+ }
127
+ if (typeof agent.inject === 'function') {
128
+ agent.inject(message);
129
+ return { delivered: true, via: 'inject' };
130
+ }
131
+ return { delivered: false, reason: 'no-inbox-api' };
132
+ } catch (error) {
133
+ const reason = error instanceof Error ? error.message : String(error);
134
+ log('warn', 'queen message delivery failed: ' + reason);
135
+ return { delivered: false, reason: 'delivery-failed', error: reason };
136
+ }
137
+ }
138
+
139
+ return {
140
+ deliver,
141
+ hasLiveQueen: () => target() !== undefined,
142
+ };
143
+ }
144
+
145
+ export default createQueenNotifier;
package/lib/patrol.js ADDED
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Queen patrol: the periodic supervision tick.
3
+ *
4
+ * Every `intervalMs` (default 5 minutes) it re-reads the supervisor status and
5
+ * turns anything that needs a decision into anomaly entries — auto-paused
6
+ * repositories, deferred environment errors, a worker whose heartbeat stalled,
7
+ * a worker past its timeout. Then it delivers ONE digest to the queen.
8
+ *
9
+ * It is deliberately quiet: with nothing to report it delivers nothing, so a
10
+ * healthy swarm costs no model tokens. Immediate card events use
11
+ * `scheduleFlush` and are debounced into a single digest.
12
+ *
13
+ * @module dsh-hive-runner/patrol
14
+ */
15
+ import { renderDigest } from './anomalies.js';
16
+
17
+ /**
18
+ * @param {{
19
+ * supervisor?: { status: () => object },
20
+ * feed: { push: Function, pending: Function, markDelivered: Function },
21
+ * notifier?: { deliver: (body: string) => { delivered: boolean, via?: string, reason?: string } },
22
+ * inspect?: () => Promise<void> | void,
23
+ * intervalMs?: number,
24
+ * debounceMs?: number,
25
+ * now?: () => number,
26
+ * setTimer?: typeof setTimeout,
27
+ * clearTimer?: typeof clearTimeout,
28
+ * setIntervalFn?: typeof setInterval,
29
+ * clearIntervalFn?: typeof clearInterval,
30
+ * log?: (level: string, ...args: unknown[]) => void,
31
+ * }} options
32
+ */
33
+ export function createPatrol(options = {}) {
34
+ const feed = options.feed;
35
+ if (feed === undefined || typeof feed.push !== 'function' || typeof feed.pending !== 'function') {
36
+ throw new TypeError('createPatrol: an anomaly feed is required');
37
+ }
38
+ const supervisor = options.supervisor;
39
+ const notifier = options.notifier;
40
+ // Optional audit hook (arch review completeness) run on every patrol tick.
41
+ const inspect = typeof options.inspect === 'function' ? options.inspect : undefined;
42
+ const intervalMs = Number.isFinite(options.intervalMs) && options.intervalMs > 0 ? options.intervalMs : 5 * 60_000;
43
+ const debounceMs = Number.isFinite(options.debounceMs) && options.debounceMs >= 0 ? options.debounceMs : 3_000;
44
+ const now = typeof options.now === 'function' ? options.now : () => Date.now();
45
+ const setTimer = typeof options.setTimer === 'function' ? options.setTimer : setTimeout;
46
+ const clearTimer = typeof options.clearTimer === 'function' ? options.clearTimer : clearTimeout;
47
+ const setIntervalFn = typeof options.setIntervalFn === 'function' ? options.setIntervalFn : setInterval;
48
+ const clearIntervalFn = typeof options.clearIntervalFn === 'function' ? options.clearIntervalFn : clearInterval;
49
+ const log = typeof options.log === 'function' ? options.log : () => {};
50
+
51
+ let patrolTimer = null;
52
+ let flushTimer = null;
53
+ let started = false;
54
+
55
+ function push(event) {
56
+ try {
57
+ return feed.push(event);
58
+ } catch (error) {
59
+ log('warn', 'anomaly push failed', error);
60
+ return null;
61
+ }
62
+ }
63
+
64
+ /** Deliver every pending entry as one digest; keep them when nobody listens. */
65
+ function flushPending() {
66
+ let pending;
67
+ try {
68
+ pending = feed.pending();
69
+ } catch (error) {
70
+ log('warn', 'reading pending anomalies failed', error);
71
+ return { delivered: false, count: 0, reason: 'read-failed' };
72
+ }
73
+ if (!Array.isArray(pending) || pending.length === 0) {
74
+ return { delivered: false, count: 0, reason: 'nothing-pending' };
75
+ }
76
+ if (notifier === undefined || typeof notifier.deliver !== 'function') {
77
+ return { delivered: false, count: pending.length, reason: 'no-notifier' };
78
+ }
79
+ let result;
80
+ try {
81
+ result = notifier.deliver(renderDigest(pending));
82
+ } catch (error) {
83
+ log('warn', 'queen digest delivery failed', error);
84
+ return { delivered: false, count: pending.length, reason: 'delivery-threw' };
85
+ }
86
+ if (result !== undefined && result.delivered === true) {
87
+ try {
88
+ feed.markDelivered(pending.map((entry) => entry.id));
89
+ } catch (error) {
90
+ log('warn', 'marking anomalies delivered failed', error);
91
+ }
92
+ return { delivered: true, count: pending.length, via: result.via ?? null, reason: null };
93
+ }
94
+ return {
95
+ delivered: false,
96
+ count: pending.length,
97
+ via: null,
98
+ reason: result?.reason ?? 'not-delivered',
99
+ };
100
+ }
101
+
102
+ /** Debounce card-level events into one digest. */
103
+ function scheduleFlush() {
104
+ if (debounceMs <= 0) return flushPending();
105
+ if (flushTimer !== null) return { delivered: false, count: 0, reason: 'scheduled' };
106
+ flushTimer = setTimer(() => {
107
+ flushTimer = null;
108
+ flushPending();
109
+ }, debounceMs);
110
+ flushTimer?.unref?.();
111
+ return { delivered: false, count: 0, reason: 'scheduled' };
112
+ }
113
+
114
+ /** Scan the supervisor status for conditions that need the queen. */
115
+ function inspectStatus() {
116
+ if (supervisor === undefined || typeof supervisor.status !== 'function') return;
117
+ let status;
118
+ try {
119
+ status = supervisor.status();
120
+ } catch (error) {
121
+ log('warn', 'patrol could not read supervisor status', error);
122
+ return;
123
+ }
124
+ if (status === null || typeof status !== 'object' || !Array.isArray(status.repos)) return;
125
+ const at = now();
126
+ for (const repo of status.repos) {
127
+ if (repo === null || typeof repo !== 'object') continue;
128
+ const name = typeof repo.repo === 'string' ? repo.repo : '';
129
+ if (repo.paused === true && repo.pausedBy === 'auto') {
130
+ push({
131
+ kind: 'auto-paused',
132
+ repo: name,
133
+ summary: 'repository auto-paused',
134
+ detail: String(repo.pausedReason ?? 'auto-paused after repeated round failures'),
135
+ });
136
+ }
137
+ if (typeof repo.environmentError === 'string' && repo.environmentError !== '') {
138
+ push({ kind: 'environment-error', repo: name, summary: 'environment error', detail: repo.environmentError });
139
+ }
140
+ if (!Array.isArray(repo.workers)) continue;
141
+ for (const worker of repo.workers) {
142
+ if (worker === null || typeof worker !== 'object') continue;
143
+ const cardId = typeof worker.cardId === 'string' ? worker.cardId : null;
144
+ const role = typeof worker.role === 'string' ? worker.role : null;
145
+ if (worker.heartbeat === 'warn') {
146
+ push({
147
+ kind: 'heartbeat-warn',
148
+ repo: name,
149
+ cardId,
150
+ role,
151
+ summary: 'worker heartbeat stalled',
152
+ detail: 'no commit observed since ' + String(worker.lastOutputAt ?? 'unknown'),
153
+ });
154
+ }
155
+ const timeoutAt = typeof worker.timeoutAt === 'string' ? Date.parse(worker.timeoutAt) : Number.NaN;
156
+ if (Number.isFinite(timeoutAt) && timeoutAt <= at) {
157
+ push({
158
+ kind: 'card-timeout',
159
+ repo: name,
160
+ cardId,
161
+ role,
162
+ summary: 'worker past its card deadline',
163
+ detail: 'timeoutAt ' + String(worker.timeoutAt),
164
+ });
165
+ }
166
+ }
167
+ }
168
+ }
169
+
170
+ /**
171
+ * One patrol tick: run the optional audit, scan the supervisor status, then
172
+ * deliver whatever is pending. Async because the audit reads the board.
173
+ */
174
+ async function patrol() {
175
+ if (inspect !== undefined) {
176
+ try {
177
+ await inspect();
178
+ } catch (error) {
179
+ log('warn', 'patrol inspect hook failed', error);
180
+ }
181
+ }
182
+ inspectStatus();
183
+ return flushPending();
184
+ }
185
+
186
+ return {
187
+ scheduleFlush,
188
+ flushPending,
189
+ patrol,
190
+ /** Whether the patrol timer is armed. */
191
+ isRunning() {
192
+ return started;
193
+ },
194
+ start() {
195
+ if (started) return;
196
+ started = true;
197
+ patrolTimer = setIntervalFn(() => {
198
+ void Promise.resolve()
199
+ .then(() => patrol())
200
+ .catch((error) => log('warn', 'patrol tick failed', error));
201
+ }, intervalMs);
202
+ patrolTimer?.unref?.();
203
+ },
204
+ stop() {
205
+ started = false;
206
+ if (patrolTimer !== null) {
207
+ clearIntervalFn(patrolTimer);
208
+ patrolTimer = null;
209
+ }
210
+ if (flushTimer !== null) {
211
+ clearTimer(flushTimer);
212
+ flushTimer = null;
213
+ }
214
+ },
215
+ };
216
+ }
217
+
218
+ export default createPatrol;