@phnx-labs/agents-cli 1.22.121 → 1.22.122

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 (70) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +6 -45
  3. package/dist/cli/command-registry.js +0 -2
  4. package/dist/commands/daemon.js +7 -8
  5. package/dist/commands/mailboxes.js +1 -1
  6. package/dist/commands/projects.js +3 -3
  7. package/dist/commands/setup-mine.js +0 -1
  8. package/dist/commands/sync.js +101 -1
  9. package/dist/lib/daemon/daemon.js +1 -16
  10. package/dist/lib/daemon-services.d.ts +1 -1
  11. package/dist/lib/daemon-services.js +0 -5
  12. package/dist/lib/daemon-webhooks.d.ts +1 -1
  13. package/dist/lib/daemon-webhooks.js +1 -1
  14. package/dist/lib/device-config.js +1 -1
  15. package/dist/lib/github/project-prs.js +2 -2
  16. package/dist/lib/hosts/passthrough.js +0 -1
  17. package/dist/lib/plugins/plugins.d.ts +7 -1
  18. package/dist/lib/plugins/plugins.js +26 -5
  19. package/dist/lib/pr-land-detach.js +2 -2
  20. package/dist/lib/refresh.js +4 -1
  21. package/dist/lib/scheduling/routines.d.ts +1 -1
  22. package/dist/lib/scheduling/routines.js +1 -1
  23. package/dist/lib/session/db.d.ts +1 -1
  24. package/dist/lib/session/db.js +51 -28
  25. package/dist/lib/staleness/index.js +12 -0
  26. package/dist/lib/staleness/types.d.ts +5 -0
  27. package/dist/lib/startup/command-registry.js +1 -1
  28. package/dist/lib/state.d.ts +0 -3
  29. package/dist/lib/state.js +0 -6
  30. package/dist/lib/sync-delete.d.ts +21 -0
  31. package/dist/lib/sync-delete.js +113 -0
  32. package/package.json +1 -3
  33. package/dist/commands/monitors.d.ts +0 -2
  34. package/dist/commands/monitors.js +0 -1070
  35. package/dist/lib/daemon/monitor-engine-service.d.ts +0 -13
  36. package/dist/lib/daemon/monitor-engine-service.js +0 -25
  37. package/dist/lib/monitors/config.d.ts +0 -77
  38. package/dist/lib/monitors/config.js +0 -405
  39. package/dist/lib/monitors/dispatch.d.ts +0 -10
  40. package/dist/lib/monitors/dispatch.js +0 -72
  41. package/dist/lib/monitors/engine.d.ts +0 -45
  42. package/dist/lib/monitors/engine.js +0 -243
  43. package/dist/lib/monitors/fingerprint.d.ts +0 -3
  44. package/dist/lib/monitors/fingerprint.js +0 -43
  45. package/dist/lib/monitors/pid-watch.d.ts +0 -4
  46. package/dist/lib/monitors/pid-watch.js +0 -14
  47. package/dist/lib/monitors/remote.d.ts +0 -31
  48. package/dist/lib/monitors/remote.js +0 -63
  49. package/dist/lib/monitors/sources/command.d.ts +0 -4
  50. package/dist/lib/monitors/sources/command.js +0 -20
  51. package/dist/lib/monitors/sources/device.d.ts +0 -3
  52. package/dist/lib/monitors/sources/device.js +0 -31
  53. package/dist/lib/monitors/sources/failure.d.ts +0 -5
  54. package/dist/lib/monitors/sources/failure.js +0 -25
  55. package/dist/lib/monitors/sources/file.d.ts +0 -4
  56. package/dist/lib/monitors/sources/file.js +0 -46
  57. package/dist/lib/monitors/sources/http.d.ts +0 -3
  58. package/dist/lib/monitors/sources/http.js +0 -25
  59. package/dist/lib/monitors/sources/index.d.ts +0 -5
  60. package/dist/lib/monitors/sources/index.js +0 -22
  61. package/dist/lib/monitors/sources/poll.d.ts +0 -1
  62. package/dist/lib/monitors/sources/poll.js +0 -1
  63. package/dist/lib/monitors/sources/types.d.ts +0 -9
  64. package/dist/lib/monitors/sources/types.js +0 -1
  65. package/dist/lib/monitors/sources/webhook.d.ts +0 -3
  66. package/dist/lib/monitors/sources/webhook.js +0 -3
  67. package/dist/lib/monitors/sources/ws.d.ts +0 -4
  68. package/dist/lib/monitors/sources/ws.js +0 -35
  69. package/dist/lib/monitors/state.d.ts +0 -51
  70. package/dist/lib/monitors/state.js +0 -221
@@ -1,243 +0,0 @@
1
- import { listMonitors, monitorRunsOnThisDevice, parseInterval, setMonitorEnabled, } from './config.js';
2
- import { evaluateSource } from './sources/index.js';
3
- import { hasChanged, readState, writeState, recordFireTime, writeFireRecord, recordCheck, markDroughtNotified, } from './state.js';
4
- import { dispatchAction, injectEvent } from './dispatch.js';
5
- import { sendToOwner } from '../notify.js';
6
- import { readRunMeta } from '../scheduling/routines.js';
7
- export const MONITOR_ENGINE_TICK_MS = 5_000;
8
- const DEFAULT_INTERVAL_MS = 60_000;
9
- const MAX_CONCURRENT_POLLS = 4;
10
- const DROUGHT_THRESHOLD = 5;
11
- export const POLL_SOURCE_TYPES = new Set(['command', 'poll', 'poll-http', 'file', 'device']);
12
- export function shouldEscalateDrought(liveness) {
13
- return liveness.consecutiveErrors >= DROUGHT_THRESHOLD && !liveness.droughtNotifiedAt;
14
- }
15
- function truncateSummary(text) {
16
- const oneLine = text.replace(/\s+/g, ' ').trim();
17
- return oneLine.length > 240 ? oneLine.slice(0, 240) + '…' : oneLine;
18
- }
19
- function buildEvent(monitor, summary, payload) {
20
- return { monitorName: monitor.name, firedAt: new Date().toISOString(), summary, payload };
21
- }
22
- // Failed observations never move state; every-mode ignores blank output, while the first valid on-change value, even empty, becomes a silent baseline.
23
- export function decideFire(monitor, observation) {
24
- const cond = monitor.condition;
25
- const raw = observation.raw;
26
- const payload = observation.meta ?? {};
27
- const dedupeKey = cond.dedupeKey;
28
- if (observation.failed) {
29
- return { fire: false, value: raw, dedupeKey, persist: false, event: null };
30
- }
31
- if (cond.mode === 'every') {
32
- if (raw.trim() === '') {
33
- return { fire: false, value: raw, dedupeKey, persist: false, event: null };
34
- }
35
- return {
36
- fire: true,
37
- value: raw,
38
- dedupeKey,
39
- persist: false,
40
- event: buildEvent(monitor, truncateSummary(raw), payload),
41
- };
42
- }
43
- if (cond.mode === 'match') {
44
- let matched = null;
45
- try {
46
- matched = new RegExp(cond.match ?? '').exec(raw);
47
- }
48
- catch {
49
- matched = null;
50
- }
51
- if (!matched) {
52
- return { fire: false, value: raw, dedupeKey, persist: false, event: null };
53
- }
54
- const matchedValue = matched[0];
55
- const changed = hasChanged(monitor.name, matchedValue, dedupeKey);
56
- return {
57
- fire: changed,
58
- value: matchedValue,
59
- dedupeKey,
60
- persist: changed,
61
- event: changed ? buildEvent(monitor, truncateSummary(matchedValue), payload) : null,
62
- };
63
- }
64
- const prior = readState(monitor.name);
65
- if (!prior) {
66
- return { fire: false, value: raw, dedupeKey, persist: true, event: null };
67
- }
68
- const changed = hasChanged(monitor.name, raw, dedupeKey);
69
- return {
70
- fire: changed,
71
- value: raw,
72
- dedupeKey,
73
- persist: changed,
74
- event: changed ? buildEvent(monitor, truncateSummary(raw), payload) : null,
75
- };
76
- }
77
- export async function evaluateMonitorOnce(monitor) {
78
- const observation = await evaluateSource(monitor.source);
79
- if (!observation)
80
- return { observation: null, decision: null };
81
- return { observation, decision: decideFire(monitor, observation) };
82
- }
83
- export class MonitorEngine {
84
- logFn;
85
- timer = null;
86
- monitors = [];
87
- lastEval = new Map();
88
- ticking = false;
89
- running = false;
90
- constructor(logFn = () => { }) {
91
- this.logFn = logFn;
92
- }
93
- start(options = {}) {
94
- this.running = true;
95
- this.loadAll();
96
- this.logFn('INFO', `Monitor engine started (${this.monitors.length} monitor(s) on this device)`);
97
- if (!options.externalScheduler) {
98
- this.timer = setInterval(() => void this.tick(), MONITOR_ENGINE_TICK_MS);
99
- }
100
- }
101
- reload() {
102
- this.loadAll();
103
- this.logFn('INFO', `Monitor engine reloaded (${this.monitors.length} monitor(s) on this device)`);
104
- }
105
- stop() {
106
- this.running = false;
107
- if (this.timer) {
108
- clearInterval(this.timer);
109
- this.timer = null;
110
- }
111
- }
112
- loadAll() {
113
- this.monitors = listMonitors().filter((m) => m.enabled && monitorRunsOnThisDevice(m));
114
- }
115
- intervalMs(monitor) {
116
- if (monitor.source.interval)
117
- return parseInterval(monitor.source.interval) ?? DEFAULT_INTERVAL_MS;
118
- return DEFAULT_INTERVAL_MS;
119
- }
120
- isDue(monitor, now) {
121
- const last = this.lastEval.get(monitor.name) ?? 0;
122
- return now - last >= this.intervalMs(monitor);
123
- }
124
- async tick(launchWindowMs = Infinity) {
125
- if (!this.running || this.ticking)
126
- return;
127
- this.ticking = true;
128
- try {
129
- const startedAt = Date.now();
130
- const due = this.monitors
131
- .filter((monitor) => this.isDue(monitor, startedAt))
132
- .sort((a, b) => (this.lastEval.get(a.name) ?? 0) - (this.lastEval.get(b.name) ?? 0));
133
- const worker = async () => {
134
- while (this.running && due.length > 0 && Date.now() - startedAt < launchWindowMs) {
135
- const monitor = due.shift();
136
- this.lastEval.set(monitor.name, Date.now());
137
- await this.runMonitor(monitor);
138
- }
139
- };
140
- await Promise.all(Array.from({ length: MAX_CONCURRENT_POLLS }, worker));
141
- }
142
- finally {
143
- this.ticking = false;
144
- }
145
- }
146
- async runMonitor(monitor) {
147
- const isPollSource = POLL_SOURCE_TYPES.has(monitor.source.type);
148
- if (!isPollSource)
149
- return;
150
- const checkedAt = new Date().toISOString();
151
- let checkError;
152
- try {
153
- const observation = await evaluateSource(monitor.source);
154
- if (!observation) {
155
- checkError = 'source produced no observation';
156
- }
157
- else if (observation.failed) {
158
- checkError = `poll failed: ${observation.failureReason ?? 'observation failure'}`;
159
- this.logFn('WARN', `monitor '${monitor.name}' poll failed (${observation.failureReason ?? 'observation failure'}) — not treated as a value change`);
160
- }
161
- else {
162
- const decision = decideFire(monitor, observation);
163
- if (decision.fire && decision.event) {
164
- const result = await this.fire(monitor, decision, decision.event);
165
- if (!result.ok)
166
- checkError = `action ${result.kind} failed: ${result.error ?? 'unknown'}`;
167
- }
168
- else if (decision.persist) {
169
- writeState(monitor.name, decision.value, decision.dedupeKey);
170
- }
171
- }
172
- }
173
- catch (err) {
174
- checkError = err.message;
175
- this.logFn('ERROR', `monitor '${monitor.name}' evaluation failed: ${checkError}`);
176
- }
177
- this.afterCheck(monitor, checkedAt, checkError);
178
- }
179
- // Liveness is independent of change state: every poll updates it and recovery resets the drought.
180
- afterCheck(monitor, checkedAt, error) {
181
- const liveness = recordCheck(monitor.name, checkedAt, error);
182
- if (error && shouldEscalateDrought(liveness)) {
183
- void this.escalateDrought(monitor, liveness.consecutiveErrors, error);
184
- }
185
- }
186
- async escalateDrought(monitor, consecutiveErrors, error) {
187
- const at = new Date().toISOString();
188
- markDroughtNotified(monitor.name, at);
189
- const text = `Monitor '${monitor.name}' has failed ${consecutiveErrors} checks in a row and accomplished nothing. ` +
190
- `Last error: ${error}`;
191
- try {
192
- const result = await sendToOwner(text);
193
- this.logFn(result.ok ? 'WARN' : 'ERROR', `monitor '${monitor.name}' drought (${consecutiveErrors} failed checks) → notify owner` +
194
- (result.ok ? '' : ` FAILED: ${result.error}`));
195
- }
196
- catch (err) {
197
- this.logFn('ERROR', `monitor '${monitor.name}' drought notify threw: ${err.message}`);
198
- }
199
- }
200
- async fire(monitor, decision, event) {
201
- const now = Date.now();
202
- let fireTimes;
203
- if (monitor.rateLimit) {
204
- const windowMs = parseInterval(monitor.rateLimit.per) ?? 60_000;
205
- fireTimes = recordFireTime(monitor.name, now, windowMs);
206
- if (fireTimes.length > monitor.rateLimit.max) {
207
- writeFireRecord(event, { action: monitor.action.type, ok: false, error: 'rate limited — auto-paused' });
208
- writeState(monitor.name, decision.value, decision.dedupeKey, { lastFiredAt: event.firedAt, fireTimes });
209
- try {
210
- setMonitorEnabled(monitor.name, false);
211
- }
212
- catch { }
213
- this.logFn('WARN', `monitor '${monitor.name}' exceeded rate limit (${monitor.rateLimit.max}/${monitor.rateLimit.per}) — auto-paused`);
214
- this.loadAll();
215
- return { kind: monitor.action.type, ok: true };
216
- }
217
- }
218
- let result;
219
- try {
220
- result = await dispatchAction(monitor, event);
221
- }
222
- catch (err) {
223
- result = { kind: monitor.action.type, ok: false, error: err.message };
224
- }
225
- const runStatusAtFire = result.runId ? readRunMeta(monitor.name, result.runId)?.status : undefined;
226
- const postcondition = (result.kind === 'run' || result.kind === 'routine') && monitor.action.postcondition
227
- ? injectEvent(monitor.action.postcondition, event)
228
- : undefined;
229
- writeFireRecord(event, {
230
- ...(result.runId ? { runId: result.runId } : {}),
231
- action: result.kind,
232
- ok: result.ok,
233
- ...(result.error ? { error: result.error } : {}),
234
- ...(runStatusAtFire ? { runStatusAtFire } : {}),
235
- ...(postcondition ? { postcondition } : {}),
236
- });
237
- writeState(monitor.name, decision.value, decision.dedupeKey, { lastFiredAt: event.firedAt, fireTimes });
238
- this.logFn(result.ok ? 'INFO' : 'ERROR', `monitor '${monitor.name}' fired → ${result.kind}` +
239
- (result.runId ? ` (run: ${result.runId})` : '') +
240
- (result.ok ? '' : ` FAILED: ${result.error}`));
241
- return result;
242
- }
243
- }
@@ -1,3 +0,0 @@
1
- import type { MonitorConfig } from './config.js';
2
- export declare function monitorFingerprint(config: Pick<MonitorConfig, 'source' | 'condition' | 'action'>): string;
3
- export declare function findDuplicateMonitor(config: Pick<MonitorConfig, 'name' | 'source' | 'condition' | 'action'>, existing: Array<Pick<MonitorConfig, 'name' | 'source' | 'condition' | 'action'>>): string | null;
@@ -1,43 +0,0 @@
1
- import { createHash } from 'crypto';
2
- function stable(value, seen = new WeakSet()) {
3
- if (value instanceof Date)
4
- return value.toISOString();
5
- if (Array.isArray(value)) {
6
- if (seen.has(value))
7
- return '[circular]';
8
- seen.add(value);
9
- return value.map((v) => stable(v, seen));
10
- }
11
- if (value && typeof value === 'object') {
12
- if (seen.has(value))
13
- return '[circular]';
14
- seen.add(value);
15
- const out = {};
16
- for (const key of Object.keys(value).sort()) {
17
- const v = value[key];
18
- if (v === undefined)
19
- continue;
20
- out[key] = stable(v, seen);
21
- }
22
- return out;
23
- }
24
- return value;
25
- }
26
- export function monitorFingerprint(config) {
27
- const identity = stable({
28
- source: config.source,
29
- condition: config.condition,
30
- action: config.action,
31
- });
32
- return createHash('sha256').update(JSON.stringify(identity)).digest('hex').slice(0, 16);
33
- }
34
- export function findDuplicateMonitor(config, existing) {
35
- const fp = monitorFingerprint(config);
36
- for (const other of existing) {
37
- if (other.name === config.name)
38
- continue;
39
- if (monitorFingerprint(other) === fp)
40
- return other.name;
41
- }
42
- return null;
43
- }
@@ -1,4 +0,0 @@
1
- export declare const PID_WATCH_EXITED_TOKEN = "exited";
2
- export declare const PID_WATCH_RUNNING_TOKEN = "running";
3
- export declare const PID_WATCH_NOT_YET_SPAWNED_TOKEN = "notyetspawned";
4
- export declare function pidLivenessCommand(pid: number, seenRunningMarkerPath: string): string;
@@ -1,14 +0,0 @@
1
- import { IS_WINDOWS } from '../platform/index.js';
2
- export const PID_WATCH_EXITED_TOKEN = 'exited';
3
- export const PID_WATCH_RUNNING_TOKEN = 'running';
4
- export const PID_WATCH_NOT_YET_SPAWNED_TOKEN = 'notyetspawned';
5
- export function pidLivenessCommand(pid, seenRunningMarkerPath) {
6
- if (IS_WINDOWS) {
7
- return (`tasklist /FI "PID eq ${pid}" 2>NUL | findstr /I "${pid}" >NUL ` +
8
- `&& (type nul > "${seenRunningMarkerPath}" & echo ${PID_WATCH_RUNNING_TOKEN}) ` +
9
- `|| (if exist "${seenRunningMarkerPath}" (echo ${PID_WATCH_EXITED_TOKEN}) else (echo ${PID_WATCH_NOT_YET_SPAWNED_TOKEN}))`);
10
- }
11
- return (`kill -0 ${pid} 2>/dev/null ` +
12
- `&& { mkdir -p "$(dirname "${seenRunningMarkerPath}")" 2>/dev/null; : > "${seenRunningMarkerPath}"; echo ${PID_WATCH_RUNNING_TOKEN}; } ` +
13
- `|| { [ -e "${seenRunningMarkerPath}" ] && echo ${PID_WATCH_EXITED_TOKEN} || echo ${PID_WATCH_NOT_YET_SPAWNED_TOKEN}; }`);
14
- }
@@ -1,31 +0,0 @@
1
- import { type GatherRemoteAgentsJsonDeps } from '../remote-agents-json.js';
2
- import type { MonitorConfig } from './config.js';
3
- export declare const NO_MONITOR_FANOUT_ENV = "AGENTS_MONITORS_LOCAL";
4
- export interface RemoteMonitorDisplay {
5
- enabled?: boolean;
6
- owner?: string;
7
- scope?: 'user' | 'system';
8
- stalled?: boolean;
9
- checkCount?: number;
10
- lastCheckedAt?: string | null;
11
- lastFiredAt?: string | null;
12
- lastActionFailed?: boolean;
13
- }
14
- export interface RemoteMonitor {
15
- machine: string;
16
- monitor: Pick<MonitorConfig, 'name' | 'source' | 'condition' | 'action'>;
17
- display?: RemoteMonitorDisplay;
18
- }
19
- export declare function parseRemoteMonitors(stdout: string, machine: string): RemoteMonitor[];
20
- interface FleetMonitorsResult {
21
- monitors: RemoteMonitor[];
22
- discoveryFailed: boolean;
23
- skipped: string[];
24
- }
25
- interface GatherFleetMonitorsOptions {
26
- againstFingerprint?: string;
27
- deps?: GatherRemoteAgentsJsonDeps;
28
- hosts?: string[];
29
- }
30
- export declare function gatherFleetMonitors(options?: GatherFleetMonitorsOptions): Promise<FleetMonitorsResult>;
31
- export {};
@@ -1,63 +0,0 @@
1
- import { gatherRemoteAgentsJson } from '../remote-agents-json.js';
2
- import { monitorFingerprint } from './fingerprint.js';
3
- export const NO_MONITOR_FANOUT_ENV = 'AGENTS_MONITORS_LOCAL';
4
- export function parseRemoteMonitors(stdout, machine) {
5
- let parsed;
6
- try {
7
- parsed = JSON.parse(stdout);
8
- }
9
- catch {
10
- return [];
11
- }
12
- if (!Array.isArray(parsed))
13
- return [];
14
- const rows = parsed;
15
- const out = [];
16
- for (const row of rows) {
17
- if (!row || typeof row !== 'object' || Array.isArray(row))
18
- continue;
19
- const m = row;
20
- if (!m.name || !m.source || !m.condition || !m.action)
21
- continue;
22
- const display = {
23
- enabled: typeof m.enabled === 'boolean' ? m.enabled : undefined,
24
- owner: typeof m.owner === 'string' ? m.owner : undefined,
25
- scope: m.scope === 'system' || m.scope === 'user' ? m.scope : undefined,
26
- stalled: typeof m.stalled === 'boolean' ? m.stalled : undefined,
27
- checkCount: typeof m.checkCount === 'number' ? m.checkCount : undefined,
28
- lastCheckedAt: typeof m.lastCheckedAt === 'string' ? m.lastCheckedAt : undefined,
29
- lastFiredAt: typeof m.lastFiredAt === 'string' ? m.lastFiredAt : undefined,
30
- lastActionFailed: typeof m.lastActionFailed === 'boolean' ? m.lastActionFailed : undefined,
31
- };
32
- out.push({
33
- machine,
34
- monitor: { name: m.name, source: m.source, condition: m.condition, action: m.action },
35
- display,
36
- });
37
- }
38
- return out;
39
- }
40
- export async function gatherFleetMonitors(options = {}) {
41
- try {
42
- const result = await gatherRemoteAgentsJson({
43
- args: ['monitors', 'list', '--json'],
44
- noFanoutEnv: NO_MONITOR_FANOUT_ENV,
45
- hosts: options.hosts,
46
- parse: parseRemoteMonitors,
47
- quiet: true,
48
- earlyExit: options.againstFingerprint
49
- ? {
50
- isDefinitive: (item) => monitorFingerprint(item.monitor) === options.againstFingerprint,
51
- }
52
- : undefined,
53
- }, options.deps);
54
- return {
55
- monitors: result.items,
56
- skipped: [...result.skipped, ...result.parseFailed],
57
- discoveryFailed: result.discoveryFailed,
58
- };
59
- }
60
- catch {
61
- return { monitors: [], skipped: [], discoveryFailed: true };
62
- }
63
- }
@@ -1,4 +0,0 @@
1
- import type { MonitorSource } from '../config.js';
2
- import type { Observation } from './types.js';
3
- export declare const POLL_TIMEOUT_MS = 60000;
4
- export declare function evaluate(source: MonitorSource, timeoutMs?: number): Promise<Observation | null>;
@@ -1,20 +0,0 @@
1
- import { execFileBounded } from '../../exec-bounded.js';
2
- import { classifyPollFailure } from './failure.js';
3
- export const POLL_TIMEOUT_MS = 60_000;
4
- export async function evaluate(source, timeoutMs = POLL_TIMEOUT_MS) {
5
- const command = source.command;
6
- if (!command)
7
- return null;
8
- const [bin, args] = process.platform === 'win32'
9
- ? ['cmd', ['/c', command]]
10
- : ['/bin/sh', ['-c', command]];
11
- const { stdout, stderr, code, timedOut } = await execFileBounded(bin, args, { timeoutMs, maxBuffer: 8 * 1024 * 1024 });
12
- const exitCode = code ?? 1;
13
- const raw = (stdout.length > 0 ? stdout : stderr).replace(/\s+$/, '');
14
- const failureReason = timedOut ? `timed out after ${timeoutMs / 1000}s` : classifyPollFailure({ exitCode, text: raw });
15
- return {
16
- raw,
17
- meta: { exitCode },
18
- ...(failureReason ? { failed: true, failureReason } : {}),
19
- };
20
- }
@@ -1,3 +0,0 @@
1
- import type { MonitorSource } from '../config.js';
2
- import type { Observation } from './types.js';
3
- export declare function evaluate(source: MonitorSource): Promise<Observation | null>;
@@ -1,31 +0,0 @@
1
- import { loadDevices } from '../../devices/registry.js';
2
- import { probeDeviceStats, probeLocalStats, headroom } from '../../devices/health.js';
3
- import { machineId, normalizeHost } from '../../machine-id.js';
4
- export async function evaluate(source) {
5
- const name = source.device;
6
- if (!name)
7
- return null;
8
- const registry = await loadDevices();
9
- const wanted = normalizeHost(name);
10
- const entry = Object.entries(registry).find(([k]) => normalizeHost(k) === wanted);
11
- if (!entry) {
12
- return {
13
- raw: `error\tdevice not registered: ${name}`,
14
- meta: { error: true, reachable: false, device: name },
15
- };
16
- }
17
- const stats = normalizeHost(entry[0]) === machineId()
18
- ? await probeLocalStats(name)
19
- : await probeDeviceStats(entry[1]);
20
- const bucket = headroom(stats);
21
- return {
22
- raw: `${stats.reachable ? 'reachable' : 'unreachable'}\t${bucket}`,
23
- meta: {
24
- reachable: stats.reachable,
25
- headroom: bucket,
26
- loadPercent: stats.loadPercent,
27
- memPercent: stats.memPercent,
28
- ncpu: stats.ncpu,
29
- },
30
- };
31
- }
@@ -1,5 +0,0 @@
1
- export declare function matchFailureText(text: string): string | null;
2
- export declare function classifyPollFailure(input: {
3
- exitCode?: number;
4
- text: string;
5
- }): string | null;
@@ -1,25 +0,0 @@
1
- const FAILURE_TEXT_PATTERNS = [
2
- { re: /\bAPI rate limit (?:already )?exceeded\b/i, reason: 'API rate limit exceeded' },
3
- { re: /\bsecondary rate limit\b/i, reason: 'secondary rate limit' },
4
- { re: /^\s*GraphQL:\s/im, reason: 'GraphQL error' },
5
- { re: /\bbad credentials\b/i, reason: 'bad credentials' },
6
- { re: /\b(?:401 Unauthorized|403 Forbidden)\b/i, reason: 'auth error' },
7
- { re: /\bcould not resolve host\b/i, reason: 'transport error (DNS)' },
8
- { re: /\bconnection (?:refused|reset|timed out)\b/i, reason: 'connection error' },
9
- { re: /\bnetwork is unreachable\b/i, reason: 'network unreachable' },
10
- ];
11
- export function matchFailureText(text) {
12
- for (const { re, reason } of FAILURE_TEXT_PATTERNS) {
13
- if (re.test(text))
14
- return reason;
15
- }
16
- return null;
17
- }
18
- export function classifyPollFailure(input) {
19
- const textReason = matchFailureText(input.text);
20
- const badExit = typeof input.exitCode === 'number' && input.exitCode !== 0;
21
- if (badExit) {
22
- return textReason ? `${textReason} (exit ${input.exitCode})` : `command exited ${input.exitCode}`;
23
- }
24
- return textReason;
25
- }
@@ -1,4 +0,0 @@
1
- import type { MonitorSource } from '../config.js';
2
- import type { Observation } from './types.js';
3
- export declare function evaluate(source: MonitorSource): Promise<Observation | null>;
4
- export declare function subscribe(source: MonitorSource, onObs: (obs: Observation) => void): () => void;
@@ -1,46 +0,0 @@
1
- import * as fs from 'fs';
2
- import * as path from 'path';
3
- import { followFile } from '../../log-follow.js';
4
- const MAX_CONTENT = 256 * 1024;
5
- export function evaluate(source) {
6
- const filePath = source.path;
7
- if (!filePath)
8
- return Promise.resolve(null);
9
- try {
10
- const stat = fs.statSync(filePath);
11
- if (stat.isDirectory()) {
12
- const entries = fs
13
- .readdirSync(filePath, { withFileTypes: true })
14
- .map((e) => {
15
- try {
16
- const s = fs.statSync(path.join(filePath, e.name));
17
- return `${e.name}\t${s.size}\t${Math.round(s.mtimeMs)}`;
18
- }
19
- catch {
20
- return `${e.name}\t?`;
21
- }
22
- })
23
- .sort();
24
- return Promise.resolve({
25
- raw: entries.join('\n'),
26
- meta: { kind: 'directory', count: entries.length },
27
- });
28
- }
29
- let content = fs.readFileSync(filePath, 'utf-8');
30
- if (content.length > MAX_CONTENT)
31
- content = content.slice(content.length - MAX_CONTENT);
32
- return Promise.resolve({
33
- raw: content,
34
- meta: { kind: 'file', size: stat.size, mtimeMs: Math.round(stat.mtimeMs) },
35
- });
36
- }
37
- catch (err) {
38
- return Promise.resolve({ raw: `missing: ${err.message}`, meta: { kind: 'missing' } });
39
- }
40
- }
41
- export function subscribe(source, onObs) {
42
- const filePath = source.path;
43
- if (!filePath)
44
- return () => { };
45
- return followFile(filePath, (text) => onObs({ raw: text, meta: { kind: 'append' } }), { fromEnd: true });
46
- }
@@ -1,3 +0,0 @@
1
- import type { MonitorSource } from '../config.js';
2
- import type { Observation } from './types.js';
3
- export declare function evaluate(source: MonitorSource): Promise<Observation | null>;
@@ -1,25 +0,0 @@
1
- const DEFAULT_TIMEOUT_MS = 30_000;
2
- const MAX_BODY = 1024 * 1024;
3
- export async function evaluate(source) {
4
- const url = source.url;
5
- if (!url)
6
- return null;
7
- const controller = new AbortController();
8
- const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
9
- try {
10
- const res = await fetch(url, { signal: controller.signal, redirect: 'follow' });
11
- let body = await res.text();
12
- if (body.length > MAX_BODY)
13
- body = body.slice(0, MAX_BODY);
14
- return {
15
- raw: `${res.status}\n${body}`,
16
- meta: { status: res.status, ok: res.ok },
17
- };
18
- }
19
- catch (err) {
20
- return { raw: `error: ${err.message}`, meta: { status: 0, ok: false } };
21
- }
22
- finally {
23
- clearTimeout(timer);
24
- }
25
- }
@@ -1,5 +0,0 @@
1
- import type { MonitorSourceType, MonitorSource } from '../config.js';
2
- import type { Observation, SourceEvaluator } from './types.js';
3
- export type { Observation, SourceEvaluator, SourceSubscriber } from './types.js';
4
- export declare const SOURCE_EVALUATORS: Record<MonitorSourceType, SourceEvaluator>;
5
- export declare function evaluateSource(source: MonitorSource): Promise<Observation | null>;
@@ -1,22 +0,0 @@
1
- import * as command from './command.js';
2
- import * as poll from './poll.js';
3
- import * as http from './http.js';
4
- import * as file from './file.js';
5
- import * as device from './device.js';
6
- import * as ws from './ws.js';
7
- import * as webhook from './webhook.js';
8
- export const SOURCE_EVALUATORS = {
9
- command: command.evaluate,
10
- poll: poll.evaluate,
11
- 'poll-http': http.evaluate,
12
- file: file.evaluate,
13
- device: device.evaluate,
14
- ws: ws.evaluate,
15
- webhook: webhook.evaluate,
16
- };
17
- export function evaluateSource(source) {
18
- const evaluator = SOURCE_EVALUATORS[source.type];
19
- if (!evaluator)
20
- return Promise.resolve(null);
21
- return evaluator(source);
22
- }
@@ -1 +0,0 @@
1
- export { evaluate } from './command.js';
@@ -1 +0,0 @@
1
- export { evaluate } from './command.js';
@@ -1,9 +0,0 @@
1
- import type { MonitorSource } from '../config.js';
2
- export interface Observation {
3
- raw: string;
4
- meta?: Record<string, unknown>;
5
- failed?: boolean;
6
- failureReason?: string;
7
- }
8
- export type SourceEvaluator = (source: MonitorSource) => Promise<Observation | null>;
9
- export type SourceSubscriber = (source: MonitorSource, onObs: (obs: Observation) => void) => () => void;
@@ -1 +0,0 @@
1
- export {};
@@ -1,3 +0,0 @@
1
- import type { MonitorSource } from '../config.js';
2
- import type { Observation } from './types.js';
3
- export declare function evaluate(_source: MonitorSource): Promise<Observation | null>;
@@ -1,3 +0,0 @@
1
- export function evaluate(_source) {
2
- return Promise.resolve(null);
3
- }
@@ -1,4 +0,0 @@
1
- import type { MonitorSource } from '../config.js';
2
- import type { Observation } from './types.js';
3
- export declare function evaluate(_source: MonitorSource): Promise<Observation | null>;
4
- export declare function subscribe(source: MonitorSource, onObs: (obs: Observation) => void): () => void;