jaxon-agents 0.1.0 → 0.3.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.
Files changed (64) hide show
  1. package/README.agent.md +203 -168
  2. package/README.md +51 -34
  3. package/README.zh-CN.md +55 -38
  4. package/dist/BUILD_INFO.json +3 -3
  5. package/dist/PACKAGE_MANIFEST.json +63 -42
  6. package/dist/RELEASE_META.json +8 -2
  7. package/dist/agents/directory-store.js +66 -11
  8. package/dist/agents/jaxon-admin.entry.js +5 -3
  9. package/dist/agents/session-switch.js +6 -0
  10. package/dist/api/mcp-tools.js +76 -45
  11. package/dist/connections/health.js +4 -1
  12. package/dist/console/activity-client.js +644 -0
  13. package/dist/console/activity-page.js +24 -0
  14. package/dist/console/activity-topics.js +698 -0
  15. package/dist/console/activity.js +379 -0
  16. package/dist/console/assets.js +394 -241
  17. package/dist/console/chat-library.js +685 -0
  18. package/dist/console/console-info.js +30 -0
  19. package/dist/console/icons.js +14 -0
  20. package/dist/console/pages.js +94 -31
  21. package/dist/console/server.js +58 -8
  22. package/dist/console/station-pages.js +83 -25
  23. package/dist/daemon/client.js +1 -1
  24. package/dist/daemon/host.js +16 -3
  25. package/dist/environment/pi-launch-spec.js +1 -1
  26. package/dist/index.js +87 -8
  27. package/dist/launcher.js +17 -26
  28. package/dist/ops/catalog.js +18 -14
  29. package/dist/ops/core.js +157 -77
  30. package/dist/pi-host/history-reader.js +20 -0
  31. package/dist/pi-host/mcp-bridge.entry.js +55 -7
  32. package/dist/platform/index.js +22 -0
  33. package/dist/platform/linux.js +64 -0
  34. package/dist/release/handoff.js +6 -8
  35. package/dist/release/store.js +3 -13
  36. package/dist/sessions/dashboard-usage.js +5 -3
  37. package/dist/sessions/supervisor.js +449 -60
  38. package/dist/stations/activity.js +24 -28
  39. package/dist/stations/boards.js +10 -5
  40. package/dist/stations/cues.js +71 -48
  41. package/dist/stations/interactions.js +75 -0
  42. package/dist/stations/member-instructions.js +23 -0
  43. package/dist/stations/station-member.entry.js +31 -14
  44. package/examples/README.md +23 -8
  45. package/examples/agents/README.md +93 -35
  46. package/examples/agents/coder/README.md +37 -0
  47. package/examples/agents/custom-gateway/README.md +42 -0
  48. package/examples/agents/local-qwen/README.md +46 -0
  49. package/examples/agents/planner/README.md +39 -0
  50. package/examples/agents/reviewer/README.md +42 -0
  51. package/examples/mcp-clients/README.md +35 -16
  52. package/examples/stations/README.md +98 -21
  53. package/examples/stations/dev-loop/README.md +40 -0
  54. package/examples/stations/parallel-coders/README.md +40 -0
  55. package/examples/stations/parallel-coders/STATION.md +2 -2
  56. package/examples/stations/research-writer/README.md +39 -0
  57. package/examples/stations/research-writer/STATION.md +1 -1
  58. package/examples/workflows/01-dev-loop-e2e.md +27 -5
  59. package/examples/workflows/02-human-auth-and-roster-switch.md +25 -3
  60. package/examples/workflows/README.md +17 -0
  61. package/package.json +8 -2
  62. package/runtime/provenance.json +3 -3
  63. package/runtime/runtime-lock.json +2 -2
  64. package/runtime/runtime-package.json +1 -1
@@ -0,0 +1,379 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { branch } from "../pi-host/history-reader.js";
5
+ import { DATA_ROOT, STATE } from "../root.js";
6
+ import { fail } from "../ops/errors.js";
7
+ import { InteractionStore } from "../stations/interactions.js";
8
+ import { ActivityTopicGenerator, activityLanguage, topicInput } from "./activity-topics.js";
9
+ const WINDOWS = { '1m': 60_000, '10m': 600_000, '1h': 3_600_000, '1d': 86_400_000 };
10
+ const BUSY = new Set(['starting', 'running', 'stopping', 'waiting_input']);
11
+ const time = (value) => typeof value === 'number' ? value : typeof value === 'string' ? Date.parse(value) || 0 : 0;
12
+ const iso = (value) => value ? new Date(value).toISOString() : null;
13
+ const intervalFor = (window) => window === '1m' || window === '10m' ? 5_000 : 30_000;
14
+ const boundedWait = (ms) => Number.isFinite(ms) ? Math.max(0, Math.min(55_000, ms)) : 0;
15
+ function delay(ms, signal) {
16
+ if (ms <= 0 || signal?.aborted)
17
+ return Promise.resolve();
18
+ return new Promise(resolve => {
19
+ const done = () => { clearTimeout(timer); signal?.removeEventListener('abort', done); resolve(); };
20
+ const timer = setTimeout(done, ms);
21
+ timer.unref();
22
+ signal?.addEventListener('abort', done, { once: true });
23
+ });
24
+ }
25
+ function recentSessionEntries(sessionId) {
26
+ const file = path.join(STATE, 'sessions', sessionId, 'session.jsonl');
27
+ try {
28
+ const stat = fs.statSync(file);
29
+ const start = Math.max(0, stat.size - 512 * 1024);
30
+ const fd = fs.openSync(file, 'r');
31
+ try {
32
+ const buffer = Buffer.alloc(stat.size - start);
33
+ fs.readSync(fd, buffer, 0, buffer.length, start);
34
+ const text = buffer.toString('utf8');
35
+ const newline = text.indexOf('\n');
36
+ const usable = start > 0 && newline >= 0 ? text.slice(newline + 1) : text;
37
+ const entries = usable.split('\n').flatMap((line) => {
38
+ if (!line)
39
+ return [];
40
+ try {
41
+ const entry = JSON.parse(line);
42
+ return entry.id && entry.type !== 'session' ? [{ ...entry, _sid: sessionId }] : [];
43
+ }
44
+ catch {
45
+ return [];
46
+ }
47
+ });
48
+ return branch(entries, entries.at(-1)?.id ?? null);
49
+ }
50
+ finally {
51
+ fs.closeSync(fd);
52
+ }
53
+ }
54
+ catch {
55
+ return [];
56
+ }
57
+ }
58
+ /** Activity projections are read-only. Cursor changes never imply a visual change without a new content fingerprint. */
59
+ export class StationActivityGraph {
60
+ ops;
61
+ interactions;
62
+ topics;
63
+ revisions = new Map();
64
+ listeners = new Map();
65
+ overviewListeners = new Set();
66
+ instance = randomUUID();
67
+ backgroundStarted = false;
68
+ constructor(ops) {
69
+ this.ops = ops;
70
+ this.interactions = new InteractionStore(ops.activity.root);
71
+ this.interactions.onChange = (id) => this.notify(id);
72
+ this.topics = new ActivityTopicGenerator(ops, (id) => this.notify(id));
73
+ this.ops.onStationChange((id) => this.notify(id));
74
+ for (const station of this.ops.stations.all())
75
+ this.interactions.compact(station);
76
+ }
77
+ startBackground() {
78
+ if (this.backgroundStarted || process.env.JAXON_PREFLIGHT || process.env.JAXON_DAEMON_PREFLIGHT)
79
+ return;
80
+ this.backgroundStarted = true;
81
+ this.scheduleBackground(60_000 + Math.floor(Math.random() * 120_000));
82
+ }
83
+ scheduleBackground(after) {
84
+ const override = Number(process.env.JAXON_ACTIVITY_BACKGROUND_INTERVAL_MS);
85
+ const interval = Number.isFinite(override) && override > 0 ? Math.min(override, 3_600_000) : after;
86
+ const timer = setTimeout(() => {
87
+ void this.runBackground().catch(error => console.error('Background activity sweep', error))
88
+ .finally(() => this.scheduleBackground(3_600_000));
89
+ }, interval);
90
+ timer.unref();
91
+ }
92
+ async runBackground() {
93
+ if (!this.topics.backgroundEnabled() || process.env.JAXON_PREFLIGHT || process.env.JAXON_DAEMON_PREFLIGHT)
94
+ return;
95
+ const blocked = () => !this.topics.backgroundEnabled() ||
96
+ ['waiting_quiet', 'handing_off', 'maintenance'].includes(this.ops.serviceInfo?.()?.runtime?.update?.state);
97
+ if (blocked() || this.ops.admission.closed)
98
+ return;
99
+ const latest = new Map();
100
+ for (const meta of this.ops.supervisor.allMetadata()) {
101
+ if (meta.station)
102
+ latest.set(meta.station.station_id, Math.max(latest.get(meta.station.station_id) ?? 0, time(meta.updated_at)));
103
+ }
104
+ const stations = this.ops.stations.all().map(station => ({
105
+ station, last: Math.max(latest.get(station.station_id) ?? 0, time(this.interactions.list(station).at(-1)?.at), time(this.ops.cues.list(station, 1).at(-1)?.at)),
106
+ })).sort((a, b) => b.last - a.last || a.station.name.localeCompare(b.station.name));
107
+ for (const { station } of stations) {
108
+ if (blocked())
109
+ break;
110
+ const done = this.ops.admission.tryEnter('activity_topic_sweep');
111
+ if (!done)
112
+ break;
113
+ try {
114
+ this.build(station, '1d', Date.now(), 'background');
115
+ }
116
+ catch (error) {
117
+ console.error('Background activity topics', station.station_id, error);
118
+ }
119
+ finally {
120
+ done();
121
+ }
122
+ await this.topics.settled(station);
123
+ }
124
+ }
125
+ notify(stationId) {
126
+ this.revisions.set(stationId, (this.revisions.get(stationId) ?? 0) + 1);
127
+ for (const listener of this.listeners.get(stationId) ?? [])
128
+ listener();
129
+ for (const listener of this.overviewListeners)
130
+ listener();
131
+ }
132
+ recordDispatch(ref, event) {
133
+ this.interactions.append(ref, { ...event, kind: 'dispatch', at: new Date().toISOString() });
134
+ }
135
+ recordReports(ref, sessionId, read) {
136
+ const outcomes = Array.isArray(read.turn_outcomes) ? read.turn_outcomes : [];
137
+ const session = this.ops.supervisor.sessions.get(sessionId)?.meta;
138
+ if (!session?.station || session.station.station_id !== ref.station_id)
139
+ return;
140
+ for (const outcome of outcomes) {
141
+ if (!outcome.turn_id || !outcome.outcome || outcome.origin === 'cue')
142
+ continue;
143
+ this.interactions.append(ref, { at: new Date().toISOString(), kind: 'report', op: 'session_read', agent: session.agent,
144
+ session_id: sessionId, turn_id: outcome.turn_id, source: 'master' });
145
+ }
146
+ }
147
+ cursor(id, window, fp, issuedAt) {
148
+ return Buffer.from(JSON.stringify({ station: id, rev: this.revisions.get(id) ?? 0, fp, window,
149
+ issued_at: issuedAt, daemon: this.instance })).toString('base64url');
150
+ }
151
+ parseCursor(value) {
152
+ if (value.length > 1024)
153
+ return {};
154
+ try {
155
+ return JSON.parse(Buffer.from(value, 'base64url').toString()) ?? {};
156
+ }
157
+ catch {
158
+ return {};
159
+ }
160
+ }
161
+ async throttle(previous, window, started, signal) {
162
+ const issued = previous?.issued_at;
163
+ if (previous?.daemon !== this.instance || previous?.window !== window || !Number.isFinite(issued))
164
+ return;
165
+ const notBefore = Math.min(started, issued) + intervalFor(window);
166
+ // The wait budget bounds waiting for changes, not the earliest allowed response.
167
+ while (!signal?.aborted && Date.now() < notBefore)
168
+ await delay(notBefore - Date.now(), signal);
169
+ }
170
+ changed(built, previous, window) {
171
+ return previous.daemon !== this.instance || previous.window !== window || previous.station !== built.station_id || previous.fp !== built._fp;
172
+ }
173
+ async wait(id, ms, expiry, signal) {
174
+ const duration = Math.min(ms, expiry - Date.now());
175
+ if (duration <= 0 || signal?.aborted)
176
+ return;
177
+ const listeners = id === null ? this.overviewListeners : this.listeners.get(id) ?? new Set();
178
+ if (id !== null)
179
+ this.listeners.set(id, listeners);
180
+ await new Promise(resolve => {
181
+ const done = () => {
182
+ clearTimeout(timer);
183
+ signal?.removeEventListener('abort', done);
184
+ listeners.delete(done);
185
+ if (id !== null && !listeners.size)
186
+ this.listeners.delete(id);
187
+ resolve();
188
+ };
189
+ const timer = setTimeout(done, duration);
190
+ timer.unref();
191
+ listeners.add(done);
192
+ signal?.addEventListener('abort', done, { once: true });
193
+ });
194
+ }
195
+ async snapshot(station, window = '10m', since, waitMs = 0, signal) {
196
+ if (!Object.hasOwn(WINDOWS, window))
197
+ fail('INVALID_WINDOW', window, { window });
198
+ const ref = this.ops.stations.resolve(station);
199
+ const started = Date.now();
200
+ const previous = since ? this.parseCursor(since) : null;
201
+ const deadline = started + boundedWait(waitMs);
202
+ if (previous?.station === ref.station_id)
203
+ await this.throttle(previous, window, started, signal);
204
+ let built = this.build(ref, window, Date.now(), signal?.aborted ? undefined : 'on_demand', started);
205
+ while (previous && !signal?.aborted && !this.changed(built, previous, window) && Date.now() < deadline) {
206
+ await this.wait(ref.station_id, deadline - Date.now(), built._expiry, signal);
207
+ built = this.build(ref, window, Date.now(), undefined, started);
208
+ }
209
+ return this.publicSnapshot(built, previous ? this.changed(built, previous, window) : true);
210
+ }
211
+ publicSnapshot(built, changed) {
212
+ const { _fp, _expiry, ...snapshot } = built;
213
+ return { ...snapshot, changed };
214
+ }
215
+ build(ref, window, now, trigger, issuedAt = now) {
216
+ const windowMs = WINDOWS[window];
217
+ const interactions = this.interactions.list(ref);
218
+ const cues = this.ops.cues.list(ref, 20_000);
219
+ const latestSignals = new Map();
220
+ for (const row of interactions)
221
+ latestSignals.set(row.session_id, Math.max(latestSignals.get(row.session_id) ?? 0, time(row.at)));
222
+ for (const row of cues) {
223
+ if (row.delivery === 'undelivered' || row.to.target === 'master' || row.from.agent === 'master')
224
+ continue;
225
+ latestSignals.set(row.from.session_id, Math.max(latestSignals.get(row.from.session_id) ?? 0, time(row.at)));
226
+ if (row.to.session_id)
227
+ latestSignals.set(row.to.session_id, Math.max(latestSignals.get(row.to.session_id) ?? 0, time(row.at)));
228
+ }
229
+ const language = activityLanguage();
230
+ const boardCache = new Map();
231
+ const roster = new Set(this.ops.activity.roster(ref));
232
+ const rows = [];
233
+ const sessionsForStation = this.ops.supervisor.allMetadata().filter(meta => meta.station?.station_id === ref.station_id);
234
+ let expiry = now + windowMs;
235
+ for (const meta of sessionsForStation) {
236
+ const active = BUSY.has(meta.status) || (meta.queue?.length ?? 0) > 0;
237
+ const closedAt = meta.status === 'closed' ? time(meta.updated_at) : 0;
238
+ if (closedAt && now - closedAt >= windowMs)
239
+ continue;
240
+ const outcomes = Object.values(meta.turn_outcomes ?? {}).map((value) => time(value.at));
241
+ const startedAt = time(meta.turn_started_at) || time(meta.turn_progress?.started_at);
242
+ const lastAt = Math.max(time(meta.updated_at), startedAt, ...outcomes, latestSignals.get(meta.session_id) ?? 0);
243
+ if (!active && now - lastAt >= windowMs)
244
+ continue;
245
+ if (!active)
246
+ expiry = Math.min(expiry, (closedAt || lastAt) + windowMs);
247
+ const entries = recentSessionEntries(meta.session_id);
248
+ const tense = active ? 'progressive' : 'past';
249
+ if (!boardCache.has(meta.agent))
250
+ boardCache.set(meta.agent, this.ops.boards.own(ref, meta.agent));
251
+ const input = topicInput(meta, entries, language, tense, boardCache.get(meta.agent));
252
+ rows.push({ meta, active, closedAt, startedAt, lastAt, language, tense, ...input });
253
+ }
254
+ rows.sort((a, b) => Number(b.active) - Number(a.active) || b.lastAt - a.lastAt || a.meta.session_id.localeCompare(b.meta.session_id));
255
+ const candidates = rows.map((row) => ({ session_id: row.meta.session_id, input: row.input, fp: row.fp,
256
+ fallback: row.fallback, active: row.active, status: row.meta.status, language: row.language, tense: row.tense, last_activity_at: row.lastAt, empty: row.empty }));
257
+ const topics = this.topics.present(ref, candidates, trigger);
258
+ const agents = new Set([...roster, ...rows.map((row) => row.meta.agent)]);
259
+ const nodes = [{ id: 'master', kind: 'master', url: `/stations/${encodeURIComponent(ref.station_id)}` }];
260
+ for (const agent of [...agents].sort()) {
261
+ const sessions = rows.filter((row) => row.meta.agent === agent)
262
+ .map(row => ({ ...row, pendingCues: this.ops.supervisor.pendingCueSummary(row.meta) }));
263
+ nodes.push({ id: agent, kind: 'agent', in_roster: roster.has(agent), url: `/agents/${encodeURIComponent(agent)}`,
264
+ active_sessions: sessions.filter((row) => row.active).length, window_sessions: sessions.length, last_activity_at: iso(Math.max(0, ...sessions.map(row => row.lastAt))),
265
+ pending_cues: sessions.reduce((sum, row) => sum + row.pendingCues.count, 0),
266
+ sessions: sessions.slice(0, 12).map((row) => {
267
+ const meta = row.meta;
268
+ return { session_id: meta.session_id, status: meta.status, queued_turns: meta.queue?.length ?? 0,
269
+ turn_started_at: iso(row.startedAt), last_activity_at: iso(row.lastAt), closed_at: iso(row.closedAt),
270
+ pending_cues: row.pendingCues,
271
+ ...(row.active && BUSY.has(meta.status) && !meta.last_turn_outcome && meta.turn_origin === 'cue' ? { origin: 'cue' } : {}),
272
+ topic: topics[meta.session_id], url: `/sessions/${encodeURIComponent(meta.session_id)}` };
273
+ }) });
274
+ }
275
+ const sessionAgents = new Map(sessionsForStation.map(meta => [meta.session_id, meta.agent]));
276
+ const edgeMap = new Map();
277
+ const addEdge = (from, to, kind, at, last, unique) => {
278
+ if (!at || now - at >= windowMs)
279
+ return;
280
+ expiry = Math.min(expiry, at + windowMs);
281
+ const key = `${from}\0${to}\0${kind}`;
282
+ const edge = edgeMap.get(key) ?? { from, to, kind, last_at: 0, count: 0, _ids: new Set(), last: null };
283
+ if (!unique || !edge._ids.has(unique)) {
284
+ edge.count++;
285
+ if (unique)
286
+ edge._ids.add(unique);
287
+ }
288
+ if (at >= edge.last_at) {
289
+ edge.last_at = at;
290
+ edge.last = last;
291
+ }
292
+ edgeMap.set(key, edge);
293
+ };
294
+ for (const row of interactions) {
295
+ const at = time(row.at);
296
+ if (row.kind === 'dispatch' && row.source === 'master')
297
+ addEdge('master', row.agent, 'dispatch', at, { op: row.op, session_id: row.session_id, delivery: row.delivery ?? null });
298
+ else if (row.kind === 'report')
299
+ addEdge(row.agent, 'master', 'report', at, { op: row.op, session_id: row.session_id, turn_id: row.turn_id ?? null });
300
+ }
301
+ for (const row of cues) {
302
+ if (row.delivery === 'undelivered' || row.to.target === 'master' || row.from.agent === 'master')
303
+ continue;
304
+ const to = (row.to.session_id && sessionAgents.get(row.to.session_id)) || row.to.target;
305
+ addEdge(row.from.agent, to, 'cue', time(row.at), { cue_id: row.cue_id, from_session: row.from.session_id,
306
+ to_session: row.to.session_id, delivery: row.delivery ?? 'pending', wake: row.wake ?? null,
307
+ woken_turn_id: row.woken_turn_id ?? null, message: row.message ?? null, board: row.board }, row.cue_id ? `${row.cue_id}:${row.from.agent}:${to}:cue` : undefined);
308
+ }
309
+ const edges = [...edgeMap.values()].sort((a, b) => b.last_at - a.last_at).map(({ _ids, ...edge }) => ({ ...edge, last_at: iso(edge.last_at) }));
310
+ const topicsBatch = this.topics.batchStatus(ref);
311
+ const stationPending = this.ops.activity.pending(ref);
312
+ const fp = createHash('sha256').update(JSON.stringify({ name: ref.name, nodes, edges, stationPending, topics: { state: topicsBatch.state, pending: topicsBatch.pending }, language })).digest('hex');
313
+ return { station_id: ref.station_id, name: ref.name, now: new Date(now).toISOString(), window, window_ms: windowMs,
314
+ min_interval_ms: intervalFor(window), not_before: new Date(issuedAt + intervalFor(window)).toISOString(), topic_language: language,
315
+ cursor: this.cursor(ref.station_id, window, fp, issuedAt), station_pending: stationPending, topics_batch: topicsBatch, nodes, edges, _fp: fp, _expiry: expiry };
316
+ }
317
+ async overview(window = '10m', since, waitMs = 0, signal) {
318
+ if (!Object.hasOwn(WINDOWS, window))
319
+ fail('INVALID_WINDOW', window, { window });
320
+ const previous = since ? this.parseCursor(since) : null;
321
+ const started = Date.now();
322
+ const deadline = started + boundedWait(waitMs);
323
+ if (previous)
324
+ await this.throttle(previous, window, started, signal);
325
+ let result = this.buildOverview(window, started, previous?.station, true, signal);
326
+ while (previous && !signal?.aborted && !this.changed(result.projection, previous, window) && Date.now() < deadline) {
327
+ await this.wait(null, deadline - Date.now(), result.projection._expiry, signal);
328
+ result = this.buildOverview(window, started, result.selected?.station_id, !result.selected, signal);
329
+ }
330
+ const { projection, snapshot, ...overview } = result;
331
+ const changed = previous ? this.changed(projection, previous, window) : true;
332
+ return { ...overview, cursor: projection.cursor, changed, snapshot: snapshot ? this.publicSnapshot(projection, changed) : null };
333
+ }
334
+ buildOverview(window, issuedAt, holdStation, demand, signal) {
335
+ const stations = this.ops.stations.all();
336
+ const count = stations.length;
337
+ if (!count) {
338
+ const topic_language = activityLanguage();
339
+ const projection = { station_id: '', _fp: topic_language, _expiry: Number.POSITIVE_INFINITY, cursor: this.cursor('', window, topic_language, issuedAt) };
340
+ return { selected: null, stations_count: 0, list_url: '/stations', diagnostics: { pinned_missing: false }, snapshot: null, topic_language, projection };
341
+ }
342
+ let pinned = '';
343
+ try {
344
+ pinned = JSON.parse(fs.readFileSync(path.join(DATA_ROOT, 'config.json'), 'utf8'))?.activity?.overview_station ?? '';
345
+ }
346
+ catch { }
347
+ const pinnedRef = pinned ? stations.find((station) => station.station_id === pinned || station.name === pinned) : undefined;
348
+ const metrics = stations.map((station) => {
349
+ const sessions = this.ops.supervisor.allMetadata().filter((meta) => meta.station?.station_id === station.station_id);
350
+ const interactions = this.interactions.list(station);
351
+ const cues = this.ops.cues.list(station, 1);
352
+ const last = Math.max(0, ...sessions.map((meta) => Math.max(time(meta.updated_at), time(meta.turn_started_at), ...Object.values(meta.turn_outcomes ?? {}).map((outcome) => time(outcome.at)))), time(interactions.at(-1)?.at), time(cues.at(-1)?.at));
353
+ const active = sessions.some((meta) => BUSY.has(meta.status) || (meta.queue?.length ?? 0) > 0);
354
+ let updated = 0;
355
+ try {
356
+ updated = fs.statSync(path.join(this.ops.stations.root, station.name, 'CURRENT')).mtimeMs;
357
+ }
358
+ catch { }
359
+ return { station, last, active, updated };
360
+ });
361
+ const active = metrics.filter((metric) => metric.active).sort((a, b) => b.last - a.last || b.updated - a.updated || a.station.name.localeCompare(b.station.name));
362
+ const recent = metrics.slice().sort((a, b) => b.last - a.last || b.updated - a.updated || a.station.name.localeCompare(b.station.name));
363
+ const updated = metrics.slice().sort((a, b) => b.updated - a.updated || a.station.name.localeCompare(b.station.name));
364
+ let selected = pinnedRef ?? active[0]?.station ?? recent[0]?.station ?? updated[0].station;
365
+ const reason = pinnedRef ? 'pinned' : active.length ? 'active' : recent[0]?.last ? 'recent' : 'updated';
366
+ if (!pinnedRef && holdStation) {
367
+ const current = metrics.find((metric) => metric.station.station_id === holdStation);
368
+ if (current?.active) {
369
+ selected = current.station;
370
+ }
371
+ }
372
+ const snapshot = this.build(selected, window, Date.now(), !signal?.aborted && (demand || selected.station_id !== holdStation) ? 'on_demand' : undefined, issuedAt);
373
+ snapshot._fp = createHash('sha256').update(JSON.stringify([snapshot._fp, count, pinned, !!pinnedRef])).digest('hex');
374
+ snapshot.cursor = this.cursor(selected.station_id, window, snapshot._fp, issuedAt);
375
+ return { selected: { station_id: selected.station_id, name: selected.name, reason, url: `/stations/${encodeURIComponent(selected.station_id)}` },
376
+ stations_count: count, list_url: '/stations', diagnostics: { pinned_missing: Boolean(pinned && !pinnedRef) }, snapshot, projection: snapshot };
377
+ }
378
+ topicUsage() { return this.topics.usage(); }
379
+ }