@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,13 +0,0 @@
1
- import { BasePeriodicService, type DaemonContext } from './service.js';
2
- import type { DaemonServiceId } from '../daemon-services.js';
3
- import { MonitorEngine } from '../monitors/engine.js';
4
- export declare class MonitorEngineService extends BasePeriodicService {
5
- readonly id: DaemonServiceId;
6
- readonly intervalMs = 5000;
7
- readonly deadlineMs: number;
8
- private engine;
9
- getEngine(): MonitorEngine | null;
10
- protected onStart(ctx: DaemonContext): Promise<void>;
11
- protected onStop(): Promise<void>;
12
- protected onTick(_ctx: DaemonContext): Promise<void>;
13
- }
@@ -1,25 +0,0 @@
1
- import { BasePeriodicService } from './service.js';
2
- import { MONITOR_ENGINE_TICK_MS, MonitorEngine } from '../monitors/engine.js';
3
- import { POLL_TIMEOUT_MS } from '../monitors/sources/command.js';
4
- export class MonitorEngineService extends BasePeriodicService {
5
- id = 'monitors';
6
- intervalMs = MONITOR_ENGINE_TICK_MS;
7
- deadlineMs = 3 * POLL_TIMEOUT_MS;
8
- engine = null;
9
- getEngine() {
10
- return this.engine;
11
- }
12
- async onStart(ctx) {
13
- this.engine = new MonitorEngine((level, message) => ctx.log(level, message));
14
- this.engine.start({ externalScheduler: true });
15
- }
16
- async onStop() {
17
- this.engine?.stop();
18
- this.engine = null;
19
- }
20
- async onTick(_ctx) {
21
- if (!this.engine)
22
- throw new Error('monitor engine tick requested before start');
23
- await this.engine.tick(POLL_TIMEOUT_MS);
24
- }
25
- }
@@ -1,77 +0,0 @@
1
- import type { AgentId } from '../types.js';
2
- export type MonitorSourceType = 'command' | 'poll' | 'poll-http' | 'webhook' | 'ws' | 'file' | 'device';
3
- export interface MonitorWebhookSource {
4
- source: 'github' | 'linear';
5
- event: string;
6
- repo?: string;
7
- branch?: string;
8
- action?: string;
9
- teamKey?: string;
10
- label?: string;
11
- }
12
- export interface MonitorSource {
13
- type: MonitorSourceType;
14
- command?: string;
15
- interval?: string;
16
- url?: string;
17
- wsUrl?: string;
18
- path?: string;
19
- device?: string;
20
- webhook?: MonitorWebhookSource;
21
- }
22
- export type MonitorConditionMode = 'on-change' | 'match' | 'every';
23
- export interface MonitorCondition {
24
- mode: MonitorConditionMode;
25
- match?: string;
26
- dedupeKey?: string;
27
- }
28
- export type MonitorActionType = 'run' | 'routine' | 'notify' | 'webhook-out';
29
- export interface ActionConfig {
30
- type: MonitorActionType;
31
- agent?: AgentId | (string & {});
32
- prompt?: string;
33
- mode?: 'plan' | 'edit' | 'auto' | 'skip' | 'full';
34
- effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'auto';
35
- timeout?: string;
36
- routine?: string;
37
- notifyChannel?: string;
38
- url?: string;
39
- postcondition?: string;
40
- }
41
- export interface MonitorConfig {
42
- name: string;
43
- enabled: boolean;
44
- source: MonitorSource;
45
- condition: MonitorCondition;
46
- action: ActionConfig;
47
- device?: string;
48
- devices?: string[];
49
- sharedInput?: boolean;
50
- runOn?: string;
51
- cwd?: string;
52
- rateLimit?: {
53
- max: number;
54
- per: string;
55
- };
56
- variables?: Record<string, string>;
57
- version?: string;
58
- scope?: 'user' | 'system';
59
- }
60
- export interface MonitorEvent {
61
- monitorName: string;
62
- firedAt: string;
63
- summary: string;
64
- payload: Record<string, unknown>;
65
- }
66
- export declare function parseInterval(interval: string): number | null;
67
- export declare function requiresSingleOwner(config: Pick<MonitorConfig, 'device' | 'devices' | 'scope' | 'sharedInput'>): boolean;
68
- export declare function resolveSharedInputOwner(interactiveHost: string | undefined, deviceNames: string[], self: string): string | undefined;
69
- export declare function monitorSharedInputOwner(): string | undefined;
70
- export declare function monitorRunsOnThisDevice(config: Pick<MonitorConfig, 'device' | 'devices' | 'scope' | 'sharedInput'>, ownerHost?: string): boolean;
71
- export declare function validateMonitor(config: Partial<MonitorConfig>): string[];
72
- export declare function listMonitors(): MonitorConfig[];
73
- export declare function readMonitor(name: string): MonitorConfig | null;
74
- export declare function getMonitorPath(name: string): string | null;
75
- export declare function writeMonitor(config: MonitorConfig): void;
76
- export declare function deleteMonitor(name: string): boolean;
77
- export declare function setMonitorEnabled(name: string, enabled: boolean): void;
@@ -1,405 +0,0 @@
1
- import * as fs from 'fs';
2
- import * as path from 'path';
3
- import * as yaml from 'yaml';
4
- import { getMonitorsDir, getSystemMonitorsDir, ensureAgentsDir, readMeta } from '../state.js';
5
- import { safeJoin, isSafeSegmentName } from '../paths.js';
6
- import { atomicWriteFileSync } from '../fs-atomic.js';
7
- import { machineId, normalizeHost } from '../machine-id.js';
8
- import { loadDevicesSync } from '../devices/registry.js';
9
- import { ALL_AGENT_IDS } from '../agents.js';
10
- import { isCustomHarnessName } from '../profiles.js';
11
- const MONITOR_DEFAULTS = {
12
- enabled: true,
13
- };
14
- const SOURCE_TYPES = [
15
- 'command',
16
- 'poll',
17
- 'poll-http',
18
- 'webhook',
19
- 'ws',
20
- 'file',
21
- 'device',
22
- ];
23
- const CONDITION_MODES = ['on-change', 'match', 'every'];
24
- const ACTION_TYPES = ['run', 'routine', 'notify', 'webhook-out'];
25
- export function parseInterval(interval) {
26
- const match = interval.trim().match(/^(?:(\d+)w)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/);
27
- if (!match)
28
- return null;
29
- const weeks = parseInt(match[1] || '0', 10);
30
- const days = parseInt(match[2] || '0', 10);
31
- const hours = parseInt(match[3] || '0', 10);
32
- const minutes = parseInt(match[4] || '0', 10);
33
- const seconds = parseInt(match[5] || '0', 10);
34
- const ms = ((((weeks * 7 + days) * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000;
35
- return ms > 0 ? ms : null;
36
- }
37
- // Unpinned system/shared-input monitors require one resolved owner; no owner means fire nowhere.
38
- export function requiresSingleOwner(config) {
39
- if (config.device || (config.devices && config.devices.length > 0))
40
- return false;
41
- if (config.scope === 'system')
42
- return config.sharedInput !== false;
43
- return config.sharedInput === true;
44
- }
45
- export function resolveSharedInputOwner(interactiveHost, deviceNames, self) {
46
- if (typeof interactiveHost === 'string' && interactiveHost.trim()) {
47
- return normalizeHost(interactiveHost);
48
- }
49
- const others = deviceNames.map((d) => normalizeHost(d)).filter((d) => d && d !== self);
50
- if (others.length === 0)
51
- return self;
52
- return undefined;
53
- }
54
- export function monitorSharedInputOwner() {
55
- const self = machineId();
56
- const interactiveHost = readMeta().config?.interactiveHost;
57
- let deviceNames = [];
58
- try {
59
- deviceNames = Object.keys(loadDevicesSync());
60
- }
61
- catch {
62
- deviceNames = [];
63
- }
64
- return resolveSharedInputOwner(typeof interactiveHost === 'string' ? interactiveHost : undefined, deviceNames, self);
65
- }
66
- // Explicit device/device lists remain the executor choice and bypass shared-input owner inference.
67
- export function monitorRunsOnThisDevice(config, ownerHost) {
68
- const self = machineId();
69
- if (config.device)
70
- return normalizeHost(config.device) === self;
71
- if (config.devices && config.devices.length > 0) {
72
- return config.devices.some((d) => normalizeHost(d) === self);
73
- }
74
- if (requiresSingleOwner(config)) {
75
- const resolved = ownerHost !== undefined ? ownerHost : monitorSharedInputOwner();
76
- const owner = resolved && resolved.trim() ? normalizeHost(resolved) : undefined;
77
- return owner !== undefined && owner === self;
78
- }
79
- return true;
80
- }
81
- function populatedSourceFields(source) {
82
- const fields = [
83
- ['command', source.command],
84
- ['url', source.url],
85
- ['wsUrl', source.wsUrl],
86
- ['path', source.path],
87
- ['device', source.device],
88
- ['webhook', source.webhook],
89
- ];
90
- return fields.filter(([, v]) => v !== undefined && v !== null && v !== '').map(([k]) => k);
91
- }
92
- const SOURCE_TYPE_FIELD = {
93
- command: 'command',
94
- poll: 'command',
95
- 'poll-http': 'url',
96
- webhook: 'webhook',
97
- ws: 'wsUrl',
98
- file: 'path',
99
- device: 'device',
100
- };
101
- function populatedActionFields(action) {
102
- const fields = [
103
- ['agent', action.agent],
104
- ['routine', action.routine],
105
- ['url', action.url],
106
- ];
107
- return fields.filter(([, v]) => v !== undefined && v !== null && v !== '').map(([k]) => k);
108
- }
109
- export function validateMonitor(config) {
110
- const errors = [];
111
- if (!config.name || typeof config.name !== 'string') {
112
- errors.push('name is required');
113
- }
114
- else if (!isSafeSegmentName(config.name)) {
115
- errors.push(`invalid name ${JSON.stringify(config.name)}: must be a single path segment ` +
116
- `(no '/', '\\\\', or null bytes, and not '.' or '..')`);
117
- }
118
- const source = config.source;
119
- if (!source || typeof source !== 'object') {
120
- errors.push('a source is required (source: { type, ... })');
121
- }
122
- else {
123
- if (!source.type || !SOURCE_TYPES.includes(source.type)) {
124
- errors.push(`source.type must be one of: ${SOURCE_TYPES.join(', ')}`);
125
- }
126
- const populated = populatedSourceFields(source);
127
- if (source.type && SOURCE_TYPES.includes(source.type)) {
128
- const required = SOURCE_TYPE_FIELD[source.type];
129
- const stray = populated.filter((f) => f !== required);
130
- if (stray.length > 0) {
131
- errors.push(`source has conflicting fields (${[required, ...stray].join(', ')}); specify exactly one source`);
132
- }
133
- if (!populated.includes(required)) {
134
- errors.push(`source.type '${source.type}' requires source.${required}`);
135
- }
136
- }
137
- else if (populated.length > 1) {
138
- errors.push(`source has conflicting fields (${populated.join(', ')}); specify exactly one source`);
139
- }
140
- if ((source.type === 'poll' || source.type === 'poll-http') && source.interval === undefined) {
141
- errors.push(`source.type '${source.type}' requires source.interval (e.g. 30s, 15m, 8h)`);
142
- }
143
- if (source.interval !== undefined && parseInterval(source.interval) === null) {
144
- errors.push(`source.interval must be like 30s, 15m, 8h, 1d (got ${JSON.stringify(source.interval)})`);
145
- }
146
- if (source.webhook !== undefined) {
147
- const w = source.webhook;
148
- if (!w || typeof w !== 'object') {
149
- errors.push('source.webhook must be an object');
150
- }
151
- else if (w.source !== 'github' && w.source !== 'linear') {
152
- errors.push("source.webhook.source must be 'github' or 'linear'");
153
- }
154
- else if (!w.event || typeof w.event !== 'string') {
155
- errors.push('source.webhook.event is required');
156
- }
157
- }
158
- }
159
- const condition = config.condition;
160
- if (!condition || typeof condition !== 'object') {
161
- errors.push('a condition is required (condition: { mode, ... })');
162
- }
163
- else {
164
- if (!condition.mode || !CONDITION_MODES.includes(condition.mode)) {
165
- errors.push(`condition.mode must be one of: ${CONDITION_MODES.join(', ')}`);
166
- }
167
- if (condition.mode === 'match') {
168
- if (!condition.match || typeof condition.match !== 'string') {
169
- errors.push("condition.mode 'match' requires condition.match (a regex)");
170
- }
171
- }
172
- for (const key of ['match', 'dedupeKey']) {
173
- const val = condition[key];
174
- if (val !== undefined) {
175
- if (typeof val !== 'string') {
176
- errors.push(`condition.${key} must be a regex string`);
177
- }
178
- else {
179
- try {
180
- new RegExp(val);
181
- }
182
- catch {
183
- errors.push(`condition.${key} is not a valid regular expression: ${JSON.stringify(val)}`);
184
- }
185
- }
186
- }
187
- }
188
- }
189
- const action = config.action;
190
- if (!action || typeof action !== 'object') {
191
- errors.push('an action is required (action: { type, ... })');
192
- }
193
- else {
194
- if (!action.type || !ACTION_TYPES.includes(action.type)) {
195
- errors.push(`action.type must be one of: ${ACTION_TYPES.join(', ')}`);
196
- }
197
- const populatedAct = populatedActionFields(action);
198
- const requiredByType = {
199
- run: 'agent',
200
- routine: 'routine',
201
- 'webhook-out': 'url',
202
- };
203
- if (action.type && ACTION_TYPES.includes(action.type)) {
204
- const required = requiredByType[action.type];
205
- const stray = populatedAct.filter((f) => f !== required);
206
- if (stray.length > 0) {
207
- errors.push(`action has conflicting fields (${[...(required ? [required] : []), ...stray].join(', ')}); specify exactly one action`);
208
- }
209
- if (required && !populatedAct.includes(required)) {
210
- errors.push(`action.type '${action.type}' requires action.${required}`);
211
- }
212
- }
213
- else if (populatedAct.length > 1) {
214
- errors.push(`action has conflicting fields (${populatedAct.join(', ')}); specify exactly one action`);
215
- }
216
- if (action.type === 'run') {
217
- if (action.agent && !ALL_AGENT_IDS.includes(action.agent) && !isCustomHarnessName(action.agent)) {
218
- errors.push(`action.agent must be one of: ${ALL_AGENT_IDS.join(', ')}, or a custom harness (agents harness list)`);
219
- }
220
- if (!action.prompt || typeof action.prompt !== 'string') {
221
- errors.push("action.type 'run' requires action.prompt");
222
- }
223
- if (action.mode && !['plan', 'edit', 'auto', 'skip', 'full'].includes(action.mode)) {
224
- errors.push("action.mode must be plan, edit, auto, or skip ('full' accepted as alias for skip)");
225
- }
226
- if (action.effort && !['low', 'medium', 'high', 'xhigh', 'max', 'auto'].includes(action.effort)) {
227
- errors.push('action.effort must be low, medium, high, xhigh, max, or auto');
228
- }
229
- }
230
- if (action.type === 'webhook-out' && action.url) {
231
- try {
232
- // eslint-disable-next-line no-new
233
- new URL(action.url);
234
- }
235
- catch {
236
- errors.push(`action.url must be an absolute URL (got ${JSON.stringify(action.url)})`);
237
- }
238
- }
239
- if (action.postcondition !== undefined) {
240
- if (action.type !== 'run' && action.type !== 'routine') {
241
- errors.push("action.postcondition only applies to run or routine actions");
242
- }
243
- else if (typeof action.postcondition !== 'string' || action.postcondition.trim() === '') {
244
- errors.push('action.postcondition must be a non-empty shell command');
245
- }
246
- }
247
- }
248
- if (config.device !== undefined && config.devices !== undefined) {
249
- errors.push("device (single owner) and devices (allowlist) are mutually exclusive — pick one");
250
- }
251
- if (config.device !== undefined && (typeof config.device !== 'string' || config.device.trim() === '')) {
252
- errors.push('device must be a non-empty device name');
253
- }
254
- if (config.devices !== undefined) {
255
- if (!Array.isArray(config.devices)) {
256
- errors.push('devices must be an array of device names');
257
- }
258
- else {
259
- for (const d of config.devices) {
260
- if (typeof d !== 'string' || d.trim() === '') {
261
- errors.push('each entry in devices must be a non-empty device name');
262
- break;
263
- }
264
- }
265
- }
266
- }
267
- if (config.sharedInput !== undefined && typeof config.sharedInput !== 'boolean') {
268
- errors.push('sharedInput must be a boolean (true = source polls a fleet-shared queue)');
269
- }
270
- if (config.runOn !== undefined && (typeof config.runOn !== 'string' || config.runOn.trim() === '')) {
271
- errors.push('runOn must be a non-empty machine name (a registered host, device, capability tag, or user@host)');
272
- }
273
- if (config.cwd !== undefined && (typeof config.cwd !== 'string' || config.cwd.trim() === '')) {
274
- errors.push('cwd must be a non-empty path (home-relative or ~/…)');
275
- }
276
- if (config.rateLimit !== undefined) {
277
- const rl = config.rateLimit;
278
- if (!rl || typeof rl !== 'object' || typeof rl.max !== 'number' || rl.max <= 0) {
279
- errors.push('rateLimit.max must be a positive number');
280
- }
281
- if (!rl || typeof rl.per !== 'string' || parseInterval(rl.per) === null) {
282
- errors.push('rateLimit.per must be an interval like 1m, 1h, 1d');
283
- }
284
- }
285
- return errors;
286
- }
287
- /**
288
- * Read and normalize a monitor file. A built-in defaults to enabled exactly like
289
- * every other system-layer resource (rules, hooks, commands, skills): a monitor
290
- * shipped in the system mirror is on for every install unless the user shadows it
291
- * with an explicit `enabled: false` (via `agents monitors pause`, which writes a
292
- * user copy — the system mirror is pull-only). There is deliberately no
293
- * system-scope special-case: monitors used to be the lone outlier that shipped
294
- * disabled+invisible (PHNX-2506). `scope` no longer changes the enabled default;
295
- * it is retained on the config so `list`/`view` can tag a built-in.
296
- *
297
- * Enabled-by-default is NOT, on its own, permission to fire on every daemon. A
298
- * shared-input built-in (one whose source polls a fleet-shared queue such as `gh
299
- * pr list --author @me`) is placed on a single owner by `monitorRunsOnThisDevice`
300
- * / `requiresSingleOwner` even when the shipped YAML carries no `device:` pin: a
301
- * system built-in is treated as shared-input unless it sets `sharedInput: false`,
302
- * so it can never fan out across the fleet and double-fire on a shared queue
303
- * (SING-9). A device-local built-in opts back into fleet-wide firing with
304
- * `sharedInput: false`; a genuinely-shared one should still ship a `device:` pin
305
- * (or `sharedInput: true`) to document the intent.
306
- */
307
- function readMonitorFile(filePath, scope = 'user') {
308
- try {
309
- const content = fs.readFileSync(filePath, 'utf-8');
310
- const parsed = yaml.parse(content);
311
- if (!parsed || typeof parsed !== 'object')
312
- return null;
313
- const hasEnabled = Object.prototype.hasOwnProperty.call(parsed, 'enabled');
314
- return {
315
- ...MONITOR_DEFAULTS,
316
- ...parsed,
317
- name: parsed.name || path.basename(filePath).replace(/\.ya?ml$/, ''),
318
- enabled: hasEnabled ? parsed.enabled !== false : (MONITOR_DEFAULTS.enabled ?? true),
319
- scope,
320
- };
321
- }
322
- catch {
323
- return null;
324
- }
325
- }
326
- function monitorLayers() {
327
- return [
328
- { scope: 'user', path: getMonitorsDir() },
329
- { scope: 'system', path: getSystemMonitorsDir() },
330
- ];
331
- }
332
- export function listMonitors() {
333
- ensureAgentsDir();
334
- const monitors = [];
335
- const seen = new Set();
336
- for (const { scope, path: dir } of monitorLayers()) {
337
- if (!fs.existsSync(dir))
338
- continue;
339
- for (const file of fs.readdirSync(dir).filter((f) => f.endsWith('.yml') || f.endsWith('.yaml'))) {
340
- const monitor = readMonitorFile(path.join(dir, file), scope);
341
- if (!monitor || seen.has(monitor.name))
342
- continue;
343
- seen.add(monitor.name);
344
- monitors.push(monitor);
345
- }
346
- }
347
- return monitors;
348
- }
349
- export function readMonitor(name) {
350
- ensureAgentsDir();
351
- for (const { scope, path: dir } of monitorLayers()) {
352
- for (const ext of ['.yml', '.yaml']) {
353
- const filePath = safeJoin(dir, name + ext);
354
- if (fs.existsSync(filePath))
355
- return readMonitorFile(filePath, scope);
356
- }
357
- }
358
- return null;
359
- }
360
- export function getMonitorPath(name) {
361
- const dir = getMonitorsDir();
362
- for (const ext of ['.yml', '.yaml']) {
363
- const filePath = safeJoin(dir, name + ext);
364
- if (fs.existsSync(filePath))
365
- return filePath;
366
- }
367
- return null;
368
- }
369
- export function writeMonitor(config) {
370
- ensureAgentsDir();
371
- const dir = getMonitorsDir();
372
- fs.mkdirSync(dir, { recursive: true });
373
- const ymlPath = safeJoin(dir, config.name + '.yml');
374
- const yamlPath = safeJoin(dir, config.name + '.yaml');
375
- if (fs.existsSync(ymlPath) && fs.existsSync(yamlPath)) {
376
- throw new Error(`Monitor '${config.name}' has both .yml and .yaml files; resolve the ambiguity before editing.`);
377
- }
378
- const filePath = fs.existsSync(yamlPath) ? yamlPath : ymlPath;
379
- const output = { ...config };
380
- if (output.enabled === true)
381
- delete output.enabled;
382
- delete output.scope;
383
- const devArr = output.devices;
384
- if (!devArr || devArr.length === 0)
385
- delete output.devices;
386
- atomicWriteFileSync(filePath, yaml.stringify(output));
387
- }
388
- export function deleteMonitor(name) {
389
- const dir = getMonitorsDir();
390
- for (const ext of ['.yml', '.yaml']) {
391
- const filePath = safeJoin(dir, name + ext);
392
- if (fs.existsSync(filePath)) {
393
- fs.unlinkSync(filePath);
394
- return true;
395
- }
396
- }
397
- return false;
398
- }
399
- export function setMonitorEnabled(name, enabled) {
400
- const monitor = readMonitor(name);
401
- if (!monitor)
402
- throw new Error(`Monitor '${name}' not found`);
403
- monitor.enabled = enabled;
404
- writeMonitor(monitor);
405
- }
@@ -1,10 +0,0 @@
1
- import type { Meta } from '../types.js';
2
- import type { ActionConfig, MonitorConfig, MonitorEvent } from './config.js';
3
- export interface DispatchResult {
4
- kind: ActionConfig['type'];
5
- ok: boolean;
6
- runId?: string;
7
- error?: string;
8
- }
9
- export declare function injectEvent(prompt: string, event: MonitorEvent): string;
10
- export declare function dispatchAction(monitor: MonitorConfig, event: MonitorEvent, meta?: Meta): Promise<DispatchResult>;
@@ -1,72 +0,0 @@
1
- import { executeJobDetached } from '../daemon/runner.js';
2
- import { readJob } from '../scheduling/routines.js';
3
- import { sendToOwner } from '../notify.js';
4
- export function injectEvent(prompt, event) {
5
- return prompt.replace(/\{event\}/g, event.summary);
6
- }
7
- export async function dispatchAction(monitor, event, meta) {
8
- const action = monitor.action;
9
- if (action.type === 'run') {
10
- const job = {
11
- name: monitor.name,
12
- dispatchedBy: 'monitor',
13
- agent: action.agent,
14
- mode: action.mode ?? 'auto',
15
- effort: action.effort ?? 'auto',
16
- timeout: action.timeout ?? '10m',
17
- enabled: true,
18
- prompt: injectEvent(action.prompt ?? '', event),
19
- cwd: monitor.cwd ?? '~',
20
- ...(monitor.variables ? { variables: monitor.variables } : {}),
21
- ...(monitor.version ? { version: monitor.version } : {}),
22
- ...(monitor.runOn ? { host: monitor.runOn } : {}),
23
- };
24
- try {
25
- const runMeta = await executeJobDetached(job);
26
- if (runMeta.status === 'skipped' || runMeta.status === 'blocked' || runMeta.status === 'failed') {
27
- return { kind: 'run', ok: false, runId: runMeta.runId, error: runMeta.errorMessage ?? runMeta.status };
28
- }
29
- return { kind: 'run', ok: true, runId: runMeta.runId };
30
- }
31
- catch (err) {
32
- return { kind: 'run', ok: false, error: err.message };
33
- }
34
- }
35
- if (action.type === 'routine') {
36
- const routine = action.routine ? readJob(action.routine) : null;
37
- if (!routine) {
38
- return { kind: 'routine', ok: false, error: `routine '${action.routine}' not found` };
39
- }
40
- const fired = { ...routine, prompt: injectEvent(routine.prompt ?? '', event) };
41
- try {
42
- const runMeta = await executeJobDetached(fired);
43
- if (runMeta.status === 'skipped' || runMeta.status === 'blocked' || runMeta.status === 'failed') {
44
- return { kind: 'routine', ok: false, runId: runMeta.runId, error: runMeta.errorMessage ?? runMeta.status };
45
- }
46
- return { kind: 'routine', ok: true, runId: runMeta.runId };
47
- }
48
- catch (err) {
49
- return { kind: 'routine', ok: false, error: err.message };
50
- }
51
- }
52
- if (action.type === 'notify') {
53
- const result = await sendToOwner(event.summary, {
54
- ...(meta ? { meta } : {}),
55
- ...(action.notifyChannel ? { channel: action.notifyChannel } : {}),
56
- });
57
- return { kind: 'notify', ok: result.ok, ...(result.ok ? {} : { error: result.error }) };
58
- }
59
- if (!action.url)
60
- return { kind: 'webhook-out', ok: false, error: 'action.url is required' };
61
- try {
62
- const res = await fetch(action.url, {
63
- method: 'POST',
64
- headers: { 'content-type': 'application/json' },
65
- body: JSON.stringify(event),
66
- });
67
- return { kind: 'webhook-out', ok: res.ok, ...(res.ok ? {} : { error: `HTTP ${res.status}` }) };
68
- }
69
- catch (err) {
70
- return { kind: 'webhook-out', ok: false, error: err.message };
71
- }
72
- }
@@ -1,45 +0,0 @@
1
- import { type MonitorConfig, type MonitorEvent } from './config.js';
2
- import { type Observation } from './sources/index.js';
3
- export declare const MONITOR_ENGINE_TICK_MS = 5000;
4
- export declare const POLL_SOURCE_TYPES: Set<string>;
5
- export declare function shouldEscalateDrought(liveness: MonitorLivenessLike): boolean;
6
- interface MonitorLivenessLike {
7
- consecutiveErrors: number;
8
- droughtNotifiedAt?: string;
9
- }
10
- interface FireDecision {
11
- fire: boolean;
12
- value: string;
13
- dedupeKey?: string;
14
- persist: boolean;
15
- event: MonitorEvent | null;
16
- }
17
- export declare function decideFire(monitor: MonitorConfig, observation: Observation): FireDecision;
18
- export declare function evaluateMonitorOnce(monitor: MonitorConfig): Promise<{
19
- observation: Observation | null;
20
- decision: FireDecision | null;
21
- }>;
22
- type LogFn = (level: string, message: string) => void;
23
- export declare class MonitorEngine {
24
- private logFn;
25
- private timer;
26
- private monitors;
27
- private lastEval;
28
- private ticking;
29
- private running;
30
- constructor(logFn?: LogFn);
31
- start(options?: {
32
- externalScheduler?: boolean;
33
- }): void;
34
- reload(): void;
35
- stop(): void;
36
- private loadAll;
37
- private intervalMs;
38
- private isDue;
39
- tick(launchWindowMs?: number): Promise<void>;
40
- runMonitor(monitor: MonitorConfig): Promise<void>;
41
- private afterCheck;
42
- private escalateDrought;
43
- private fire;
44
- }
45
- export {};