@phnx-labs/agents-cli 1.23.39 → 1.23.40
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/CHANGELOG.md +14 -0
- package/README.md +7 -20
- package/dist/cli/command-registry.js +0 -2
- package/dist/commands/config.js +0 -4
- package/dist/commands/daemon.js +5 -5
- package/dist/commands/events.js +1 -1
- package/dist/commands/lead.js +4 -3
- package/dist/commands/setup.d.ts +1 -1
- package/dist/commands/setup.js +1 -9
- package/dist/commands/ssh.js +4 -5
- package/dist/lib/accounting/usage.d.ts +1 -1
- package/dist/lib/answer-router.d.ts +1 -1
- package/dist/lib/answer-router.js +16 -6
- package/dist/lib/channels/providers/session.js +13 -0
- package/dist/lib/channels/registry.d.ts +1 -1
- package/dist/lib/config-keys.d.ts +1 -1
- package/dist/lib/config-keys.js +1 -4
- package/dist/lib/daemon/daemon.js +1 -6
- package/dist/lib/daemon-services.d.ts +1 -1
- package/dist/lib/daemon-services.js +0 -5
- package/dist/lib/device-config.js +2 -11
- package/dist/lib/feed/answer.js +25 -1
- package/dist/lib/feed/attention.d.ts +8 -0
- package/dist/lib/feed/attention.js +39 -0
- package/dist/lib/feed/tab-delivery.d.ts +27 -0
- package/dist/lib/feed/tab-delivery.js +102 -0
- package/dist/lib/feed/watch.d.ts +3 -0
- package/dist/lib/feed/watch.js +63 -13
- package/dist/lib/hosts/passthrough.js +0 -1
- package/dist/lib/installations/migrate.d.ts +0 -1
- package/dist/lib/installations/migrate.js +0 -17
- package/dist/lib/lead/drafts.d.ts +11 -0
- package/dist/lib/lead/drafts.js +34 -0
- package/dist/lib/lead/host.d.ts +5 -0
- package/dist/lib/lead/host.js +52 -1
- package/dist/lib/lead/paths.js +1 -1
- package/dist/lib/lead/tools.d.ts +1 -0
- package/dist/lib/lead/tools.js +22 -0
- package/dist/lib/menubar/snapshot.d.ts +0 -6
- package/dist/lib/menubar/snapshot.js +0 -18
- package/dist/lib/session/active.d.ts +2 -1
- package/dist/lib/session/active.js +10 -6
- package/dist/lib/session/hook-sessions.d.ts +10 -0
- package/dist/lib/session/hook-sessions.js +22 -10
- package/dist/lib/session/inject-target.d.ts +1 -0
- package/dist/lib/session/inject-target.js +2 -1
- package/dist/lib/session/pid-registry.d.ts +1 -0
- package/dist/lib/session/remote/watch.d.ts +1 -0
- package/dist/lib/startup/command-registry.js +2 -1
- package/dist/lib/state.js +0 -1
- package/dist/lib/terminal/index.d.ts +1 -1
- package/dist/lib/terminal/index.js +1 -1
- package/dist/lib/terminal/inject.d.ts +0 -15
- package/dist/lib/terminal/inject.js +2 -16
- package/dist/lib/terminal/resolve.d.ts +2 -1
- package/dist/lib/terminal/resolve.js +13 -18
- package/dist/lib/types.d.ts +0 -3
- package/package.json +1 -1
- package/dist/commands/setup-watchdog.d.ts +0 -3
- package/dist/commands/setup-watchdog.js +0 -49
- package/dist/commands/watchdog.d.ts +0 -4
- package/dist/commands/watchdog.js +0 -361
- package/dist/lib/daemon/watchdog-service.d.ts +0 -10
- package/dist/lib/daemon/watchdog-service.js +0 -27
- package/dist/lib/session/presence.d.ts +0 -47
- package/dist/lib/session/presence.js +0 -100
- package/dist/lib/watchdog/history.d.ts +0 -20
- package/dist/lib/watchdog/history.js +0 -43
- package/dist/lib/watchdog/log.d.ts +0 -33
- package/dist/lib/watchdog/log.js +0 -117
- package/dist/lib/watchdog/read.d.ts +0 -8
- package/dist/lib/watchdog/read.js +0 -93
- package/dist/lib/watchdog/rotate.d.ts +0 -55
- package/dist/lib/watchdog/rotate.js +0 -220
- package/dist/lib/watchdog/runner.d.ts +0 -100
- package/dist/lib/watchdog/runner.js +0 -727
- package/dist/lib/watchdog/service.d.ts +0 -15
- package/dist/lib/watchdog/service.js +0 -36
- package/dist/lib/watchdog/watchdog-agent.d.ts +0 -8
- package/dist/lib/watchdog/watchdog-agent.js +0 -32
- package/dist/lib/watchdog/watchdog.d.ts +0 -43
- package/dist/lib/watchdog/watchdog.js +0 -116
- package/dist/lib/watchdog/watchdogTail.d.ts +0 -6
- package/dist/lib/watchdog/watchdogTail.js +0 -116
|
@@ -1,361 +0,0 @@
|
|
|
1
|
-
import chalk from 'chalk';
|
|
2
|
-
import * as path from 'path';
|
|
3
|
-
import { setHelpSections } from '../lib/help.js';
|
|
4
|
-
import { parseDuration } from '../lib/hooks/cache.js';
|
|
5
|
-
import { getRuntimeStateDir } from '../lib/state.js';
|
|
6
|
-
import { getConfigValue, setConfigValue } from '../lib/device-config.js';
|
|
7
|
-
import { writePolicySentinel, DEFAULT_THRESHOLDS, } from '../lib/watchdog/runner.js';
|
|
8
|
-
import { isWatchdogRotateEnabled, listRotateStates, setWatchdogRotateEnabled } from '../lib/watchdog/rotate.js';
|
|
9
|
-
import { loadWatchdogSessions, runWatchdogPass } from '../lib/watchdog/service.js';
|
|
10
|
-
import { readWatchdogEvents, watchdogLogPath } from '../lib/watchdog/log.js';
|
|
11
|
-
import { selectWatchdogHistory } from '../lib/watchdog/history.js';
|
|
12
|
-
import { sessionHeadline } from '../lib/session/title.js';
|
|
13
|
-
function stateDir() {
|
|
14
|
-
return path.join(getRuntimeStateDir(), 'watchdog');
|
|
15
|
-
}
|
|
16
|
-
async function reloadDaemonForWatchdog(startIfStopped) {
|
|
17
|
-
// Keep daemon dependencies off startup. If running, reload it; enable additionally starts it when stopped.
|
|
18
|
-
const { isDaemonRunning, ensureDaemonStarted, signalDaemonReload } = await import('../lib/daemon/daemon.js');
|
|
19
|
-
if (isDaemonRunning()) {
|
|
20
|
-
signalDaemonReload();
|
|
21
|
-
return;
|
|
22
|
-
}
|
|
23
|
-
if (startIfStopped)
|
|
24
|
-
ensureDaemonStarted();
|
|
25
|
-
}
|
|
26
|
-
function durationMsOr(raw, fallbackMs) {
|
|
27
|
-
if (raw === undefined)
|
|
28
|
-
return fallbackMs;
|
|
29
|
-
const secs = parseDuration(raw);
|
|
30
|
-
return secs === null ? fallbackMs : secs * 1000;
|
|
31
|
-
}
|
|
32
|
-
function humanMs(ms) {
|
|
33
|
-
if (ms >= 3600_000)
|
|
34
|
-
return `${Math.round(ms / 3600_000)}h`;
|
|
35
|
-
if (ms >= 60_000)
|
|
36
|
-
return `${Math.round(ms / 60_000)}m`;
|
|
37
|
-
return `${Math.round(ms / 1000)}s`;
|
|
38
|
-
}
|
|
39
|
-
function elapsedLabel(atMs, eventMs) {
|
|
40
|
-
const seconds = Math.max(0, Math.round((atMs - eventMs) / 1000));
|
|
41
|
-
if (seconds < 60)
|
|
42
|
-
return `${seconds} second${seconds === 1 ? '' : 's'} ago`;
|
|
43
|
-
const minutes = Math.round(seconds / 60);
|
|
44
|
-
if (minutes < 60)
|
|
45
|
-
return `${minutes} minute${minutes === 1 ? '' : 's'} ago`;
|
|
46
|
-
const hours = Math.round(minutes / 60);
|
|
47
|
-
if (hours < 48)
|
|
48
|
-
return `${hours} hour${hours === 1 ? '' : 's'} ago`;
|
|
49
|
-
const days = Math.round(hours / 24);
|
|
50
|
-
return `${days} day${days === 1 ? '' : 's'} ago`;
|
|
51
|
-
}
|
|
52
|
-
function isAttentionOutcome(outcome) {
|
|
53
|
-
return !outcome.sessionId
|
|
54
|
-
|| outcome.lastActivityMs === undefined
|
|
55
|
-
|| outcome.stall === 'stalled'
|
|
56
|
-
|| outcome.decision !== 'skip'
|
|
57
|
-
|| outcome.injected === true
|
|
58
|
-
|| outcome.addressable === false
|
|
59
|
-
|| outcome.rotatePhase === 'failed';
|
|
60
|
-
}
|
|
61
|
-
export function formatWatchdogTickLines(result, willInject, verbose = false) {
|
|
62
|
-
const { counts } = result;
|
|
63
|
-
const mode = willInject ? 'nudge' : 'dry';
|
|
64
|
-
const lines = [
|
|
65
|
-
`watchdog ${mode} · checked ${new Date(result.atMs).toLocaleString()} · ` +
|
|
66
|
-
`${counts.total} live · ${counts.stalled} stalled · ` +
|
|
67
|
-
`${counts.nudged} nudged · ${counts.unaddressable} un-addressable` +
|
|
68
|
-
(counts.rotating > 0 ? ` · ${counts.rotating} rotating` : ''),
|
|
69
|
-
];
|
|
70
|
-
const visible = verbose ? result.outcomes : result.outcomes.filter(isAttentionOutcome);
|
|
71
|
-
for (const o of visible) {
|
|
72
|
-
const tag = o.injected ? 'NUDGED'
|
|
73
|
-
: o.decision === 'rotate' ? (o.rotatePhase === 'failed' ? 'ROTATE-FAIL' : 'ROTATE')
|
|
74
|
-
: o.addressable === false ? 'FLAGGED'
|
|
75
|
-
: o.decision === 'nudge' ? 'WOULD-NUDGE'
|
|
76
|
-
: 'skip';
|
|
77
|
-
const id = o.sessionId?.slice(0, 8) ?? 'no-session-id';
|
|
78
|
-
const title = o.label || o.name || sessionHeadline(o);
|
|
79
|
-
lines.push(` ${tag.padEnd(11)} ${id}${title ? ` · ${title}` : ''}`);
|
|
80
|
-
const metadata = [
|
|
81
|
-
o.kind,
|
|
82
|
-
o.host,
|
|
83
|
-
o.machine ?? 'local',
|
|
84
|
-
o.project ?? (o.cwd ? path.basename(o.cwd) : undefined),
|
|
85
|
-
o.activity ?? o.status,
|
|
86
|
-
o.owner ? `owner ${o.owner}` : undefined,
|
|
87
|
-
o.startedAtMs ? `started ${elapsedLabel(result.atMs, o.startedAtMs)}` : undefined,
|
|
88
|
-
o.lastActivityMs ? `activity ${elapsedLabel(result.atMs, o.lastActivityMs)}` : undefined,
|
|
89
|
-
o.rail ? `rail ${o.rail}` : undefined,
|
|
90
|
-
].filter((value) => Boolean(value));
|
|
91
|
-
lines.push(` ${metadata.join(' · ')}`);
|
|
92
|
-
if (o.cwd)
|
|
93
|
-
lines.push(` cwd ${o.cwd}`);
|
|
94
|
-
if (o.preview)
|
|
95
|
-
lines.push(` latest ${o.preview.replace(/\s+/g, ' ').slice(0, 140)}`);
|
|
96
|
-
lines.push(` reason ${o.reason}`);
|
|
97
|
-
}
|
|
98
|
-
const omitted = result.outcomes.length - visible.length;
|
|
99
|
-
if (omitted > 0)
|
|
100
|
-
lines.push(` ${omitted} healthy/non-actionable session${omitted === 1 ? '' : 's'} omitted · use --verbose or --json to inspect all`);
|
|
101
|
-
return lines;
|
|
102
|
-
}
|
|
103
|
-
function printTick(result, willInject, verbose) {
|
|
104
|
-
for (const line of formatWatchdogTickLines(result, willInject, verbose))
|
|
105
|
-
console.log(line);
|
|
106
|
-
}
|
|
107
|
-
async function sleep(ms) {
|
|
108
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
109
|
-
}
|
|
110
|
-
export function registerWatchdogCommand(program) {
|
|
111
|
-
// The daemon alone schedules automatic passes; manual runs inject only with explicit --nudge.
|
|
112
|
-
const cmd = program
|
|
113
|
-
.command('watchdog')
|
|
114
|
-
.description('Auto-nudge stalled agent terminals: detect stalls, resolve the exact split, inject "Continue." — no menu-bar needed.')
|
|
115
|
-
.option('--nudge', 'Actually inject (default is a dry run that only reports what it would do)')
|
|
116
|
-
.option('--watch', 'Manual poll loop: run a tick every --interval (dry unless --nudge; the always-on path is `watchdog enable`)')
|
|
117
|
-
.option('--interval <dur>', 'Poll interval in --watch mode (e.g. 30s, 1m)', '30s')
|
|
118
|
-
.option('--stall <dur>', 'Idle time before a session counts as stalled', humanMs(DEFAULT_THRESHOLDS.stallMs))
|
|
119
|
-
.option('--cooldown <dur>', 'Minimum time between nudges to the same session', humanMs(DEFAULT_THRESHOLDS.cooldownMs))
|
|
120
|
-
.option('--dormant <dur>', 'Idle time after which a session is left alone (dormant)', humanMs(DEFAULT_THRESHOLDS.dormantMs))
|
|
121
|
-
.option('--text <text>', 'Nudge text delivered into the terminal', 'Continue.')
|
|
122
|
-
.option('--smart-agent <agent>', 'Agent the watchdog decider runs as', 'claude')
|
|
123
|
-
.option('--allow-ghostty-focus', 'Permit the coarse, focus-stealing Ghostty path (off by default)')
|
|
124
|
-
.option('--verbose', 'Show healthy and non-actionable session inspections too')
|
|
125
|
-
.option('--json', 'Emit the tick result as JSON (for the menu-bar / scripts)')
|
|
126
|
-
.action(async (opts) => {
|
|
127
|
-
const thresholds = {
|
|
128
|
-
stallMs: durationMsOr(opts.stall, DEFAULT_THRESHOLDS.stallMs),
|
|
129
|
-
cooldownMs: durationMsOr(opts.cooldown, DEFAULT_THRESHOLDS.cooldownMs),
|
|
130
|
-
dormantMs: durationMsOr(opts.dormant, DEFAULT_THRESHOLDS.dormantMs),
|
|
131
|
-
};
|
|
132
|
-
const computeWillInject = () => opts.nudge === true;
|
|
133
|
-
const tickOnce = async (willInject, sessions) => runWatchdogPass({
|
|
134
|
-
nudge: willInject,
|
|
135
|
-
nudgeText: opts.text,
|
|
136
|
-
smartAgent: opts.smartAgent,
|
|
137
|
-
thresholds,
|
|
138
|
-
allowGhosttyFocus: opts.allowGhosttyFocus === true,
|
|
139
|
-
sessions,
|
|
140
|
-
});
|
|
141
|
-
if (!opts.watch) {
|
|
142
|
-
const willInject = computeWillInject();
|
|
143
|
-
// Reuse the daemon-warmed active snapshot rather than gathering the fleet again.
|
|
144
|
-
const sessions = await loadWatchdogSessions();
|
|
145
|
-
const result = await tickOnce(willInject, sessions);
|
|
146
|
-
if (opts.json)
|
|
147
|
-
console.log(JSON.stringify(result, null, 2));
|
|
148
|
-
else
|
|
149
|
-
printTick(result, willInject, opts.verbose === true);
|
|
150
|
-
return;
|
|
151
|
-
}
|
|
152
|
-
const intervalMs = durationMsOr(opts.interval, 30_000);
|
|
153
|
-
if (!computeWillInject() && !opts.json) {
|
|
154
|
-
console.log(chalk.yellow(`watchdog --watch is DETECT-ONLY. Pass --nudge to inject, ` +
|
|
155
|
-
`or run 'agents watchdog enable' for the daemon-owned pass.`));
|
|
156
|
-
}
|
|
157
|
-
// eslint-disable-next-line no-constant-condition
|
|
158
|
-
while (true) {
|
|
159
|
-
const willInject = computeWillInject();
|
|
160
|
-
const sessions = await loadWatchdogSessions();
|
|
161
|
-
const result = await tickOnce(willInject, sessions);
|
|
162
|
-
if (opts.json)
|
|
163
|
-
console.log(JSON.stringify(result));
|
|
164
|
-
else
|
|
165
|
-
printTick(result, willInject, opts.verbose === true);
|
|
166
|
-
await sleep(intervalMs);
|
|
167
|
-
}
|
|
168
|
-
});
|
|
169
|
-
setHelpSections(cmd, {
|
|
170
|
-
examples: `
|
|
171
|
-
# One tick, dry — see what it WOULD nudge and why (safe, no injection)
|
|
172
|
-
agents watchdog
|
|
173
|
-
|
|
174
|
-
# One tick, actually inject "Continue." into stalled+addressable splits
|
|
175
|
-
agents watchdog --nudge
|
|
176
|
-
|
|
177
|
-
# Manual watch loop every 30s, tighter stall threshold (ad-hoc; dry unless --nudge)
|
|
178
|
-
agents watchdog --watch --nudge --interval 30s --stall 60s --cooldown 5m
|
|
179
|
-
|
|
180
|
-
# Machine-readable for the menu-bar
|
|
181
|
-
agents watchdog --json
|
|
182
|
-
|
|
183
|
-
# Turn on the daemon-owned watchdog pass (every three minutes)
|
|
184
|
-
agents watchdog enable
|
|
185
|
-
|
|
186
|
-
# Show device enablement, rotate config, and in-flight rotates
|
|
187
|
-
agents watchdog status
|
|
188
|
-
|
|
189
|
-
# Show what Watchdog decided and acted on during the last day
|
|
190
|
-
agents watchdog history --since 24h
|
|
191
|
-
|
|
192
|
-
# Follow one session's Watchdog decisions
|
|
193
|
-
agents watchdog history <sessionId>
|
|
194
|
-
|
|
195
|
-
# Leave one session detected-but-untouched
|
|
196
|
-
agents watchdog policy <sessionId> handsoff
|
|
197
|
-
|
|
198
|
-
# Opt out of in-place rotate only (nudging stays on)
|
|
199
|
-
agents watchdog rotate off
|
|
200
|
-
`,
|
|
201
|
-
notes: `
|
|
202
|
-
Decision path: the watchdog is an AGENT, not a heuristic script. Every idle
|
|
203
|
-
session on this machine (its task + transcript tail) is handed to ONE
|
|
204
|
-
'agents run --mode plan' call per tick, which judges each: idle-but-unfinished
|
|
205
|
-
(was given a task, went quiet, not finished/handed off) -> NUDGE that drives
|
|
206
|
-
it to finish; idle-and-done or genuinely-needs-human -> SKIP. The agent is a
|
|
207
|
-
customizable 'watchdog' workflow (drop a WORKFLOW.md in project/user
|
|
208
|
-
workflows/ to override the prompt + model); absent one, the built-in prompt
|
|
209
|
-
runs. Nothing is nudged when nothing is idle (no agent is spawned).
|
|
210
|
-
|
|
211
|
-
Delivery (answer-router): a running agent is steered via its mailbox; a
|
|
212
|
-
parked-on-question agent is answered into its EXACT split -- tmux / iTerm /
|
|
213
|
-
an IDE integrated terminal (VS Codium / Cursor / VS Code) -- or re-entered
|
|
214
|
-
via resume when headless. A parked agent with no addressable rail (e.g.
|
|
215
|
-
Ghostty with no tmux) is flagged for the menu-bar and SKIPPED -- never a
|
|
216
|
-
guessed or frontmost target.
|
|
217
|
-
|
|
218
|
-
Rotate: a stalled session whose tail shows a HARD account limit ("You've
|
|
219
|
-
hit your weekly limit - resets ...") is ROTATED IN PLACE instead of nudged:
|
|
220
|
-
the tick gates on the same healthy-account selection 'agents run auto'
|
|
221
|
-
makes (zero healthy -> one skip event per cooldown window, terminal
|
|
222
|
-
untouched), injects the harness's exit sequence, relaunches
|
|
223
|
-
'agents run auto --interactive --session-id <uuid>' in the SAME tab, waits
|
|
224
|
-
(bounded, 60s) for the new TUI, then injects the resume replay for the old
|
|
225
|
-
session. On timeout the session is flagged and never blind-typed into; the
|
|
226
|
-
flag says the terminal may sit at a bare shell and needs a manual
|
|
227
|
-
'agents run auto'. A failed rotate is suppressed for 15m before retry.
|
|
228
|
-
Default ON; disable with 'agents watchdog rotate off' (writes
|
|
229
|
-
'watchdog.rotate: off' to ~/.agents/agents.yaml; nudging stays on).
|
|
230
|
-
State machine: ~/.agents/.cache/state/watchdog/rotate/<sessionId>.json.
|
|
231
|
-
|
|
232
|
-
Always-on: 'agents watchdog enable' enables one daemon-owned pass every three
|
|
233
|
-
minutes on this device and reloads the daemon; 'off' disables it here.
|
|
234
|
-
Defaults OFF. Per-session policy: off (ignore), keep (default), handsoff
|
|
235
|
-
(detect + flag).
|
|
236
|
-
|
|
237
|
-
State (tray-readable): ${path.join('~/.agents/.cache/state/watchdog', '{nudges,flags,last-tick}.json')}
|
|
238
|
-
`,
|
|
239
|
-
});
|
|
240
|
-
const turnOn = async () => {
|
|
241
|
-
setConfigValue('watchdog.enabled', true);
|
|
242
|
-
await reloadDaemonForWatchdog(true);
|
|
243
|
-
console.log(chalk.green('watchdog: ON on this device (every 3 minutes)'));
|
|
244
|
-
};
|
|
245
|
-
const turnOff = async () => {
|
|
246
|
-
setConfigValue('watchdog.enabled', false);
|
|
247
|
-
await reloadDaemonForWatchdog(false);
|
|
248
|
-
console.log(chalk.yellow('watchdog: OFF on this device'));
|
|
249
|
-
};
|
|
250
|
-
cmd.command('enable')
|
|
251
|
-
.alias('on')
|
|
252
|
-
.description('Enable the daemon watchdog pass on this device.')
|
|
253
|
-
.action(async () => {
|
|
254
|
-
await turnOn();
|
|
255
|
-
});
|
|
256
|
-
cmd.command('disable')
|
|
257
|
-
.alias('off')
|
|
258
|
-
.description('Disable the daemon watchdog pass on this device.')
|
|
259
|
-
.action(async () => {
|
|
260
|
-
await turnOff();
|
|
261
|
-
});
|
|
262
|
-
cmd.command('rotate <state>')
|
|
263
|
-
.description('Turn in-place rotate of rate-limited sessions on|off (watchdog.rotate in agents.yaml). ' +
|
|
264
|
-
'Rotate-only: nudging stays on — unlike `watchdog disable`, which disables the whole watchdog on this device.')
|
|
265
|
-
.action((state) => {
|
|
266
|
-
const s = state.toLowerCase();
|
|
267
|
-
if (s !== 'on' && s !== 'off') {
|
|
268
|
-
console.error(chalk.red(`invalid state '${state}'. Use: on | off`));
|
|
269
|
-
process.exitCode = 1;
|
|
270
|
-
return;
|
|
271
|
-
}
|
|
272
|
-
setWatchdogRotateEnabled(s === 'on');
|
|
273
|
-
console.log(`watchdog: rotate ${s === 'on' ? chalk.green('ON') : chalk.yellow('OFF')} ` +
|
|
274
|
-
chalk.dim(`(watchdog.rotate: ${s} in agents.yaml)`));
|
|
275
|
-
});
|
|
276
|
-
cmd.command('status')
|
|
277
|
-
.description('Show whether the daemon watchdog pass is enabled and where state is written.')
|
|
278
|
-
.option('--json', 'Emit status as JSON (for the menu-bar / scripts)')
|
|
279
|
-
.action((_opts, command) => {
|
|
280
|
-
const json = command.optsWithGlobals().json === true;
|
|
281
|
-
const on = getConfigValue('watchdog.enabled').value === true;
|
|
282
|
-
const rotate = isWatchdogRotateEnabled() ? 'on' : 'off';
|
|
283
|
-
const rotates = listRotateStates(stateDir());
|
|
284
|
-
const inflight = rotates.filter((r) => r.phase !== 'done' && r.phase !== 'failed');
|
|
285
|
-
if (json) {
|
|
286
|
-
console.log(JSON.stringify({
|
|
287
|
-
enabled: on,
|
|
288
|
-
cadenceMs: 180_000,
|
|
289
|
-
stateDir: stateDir(),
|
|
290
|
-
rotate,
|
|
291
|
-
rotates: rotates.map((r) => ({
|
|
292
|
-
sessionId: r.sessionId,
|
|
293
|
-
newSessionId: r.newSessionId,
|
|
294
|
-
agent: r.agent,
|
|
295
|
-
phase: r.phase,
|
|
296
|
-
updatedAtMs: r.updatedAtMs,
|
|
297
|
-
error: r.error,
|
|
298
|
-
})),
|
|
299
|
-
}));
|
|
300
|
-
return;
|
|
301
|
-
}
|
|
302
|
-
console.log(`always-on watchdog: ${on ? chalk.green('ON') : chalk.dim('off')} (every 3 minutes on this device)`);
|
|
303
|
-
console.log(`rotate: ${rotate === 'on' ? chalk.green('on') : chalk.yellow('off')} (watchdog.rotate in agents.yaml) · ${inflight.length} in-flight`);
|
|
304
|
-
for (const r of inflight) {
|
|
305
|
-
console.log(` ${chalk.magenta(r.phase.padEnd(12))} ${chalk.bold(r.sessionId.slice(0, 8))} → ${r.newSessionId.slice(0, 8)}${r.error ? chalk.red(` ${r.error}`) : ''}`);
|
|
306
|
-
}
|
|
307
|
-
console.log(`state dir: ${chalk.dim(stateDir())}`);
|
|
308
|
-
console.log(`history: ${chalk.dim('agents watchdog history')}`);
|
|
309
|
-
});
|
|
310
|
-
cmd.command('history [sessionId]')
|
|
311
|
-
.description('Show persisted Watchdog decisions and actions, newest first.')
|
|
312
|
-
.option('--limit <count>', 'Maximum events to show', '50')
|
|
313
|
-
.option('--since <duration>', 'Only events within a duration such as 2h or 7d')
|
|
314
|
-
.option('--all', 'Include heartbeat tick events')
|
|
315
|
-
.option('--json', 'Emit safe structured history (transcript content is excluded)')
|
|
316
|
-
.action((sessionId, opts, command) => {
|
|
317
|
-
const globals = command.optsWithGlobals();
|
|
318
|
-
const limit = Number.parseInt(opts.limit, 10);
|
|
319
|
-
if (!Number.isInteger(limit) || limit < 1) {
|
|
320
|
-
throw new Error('--limit must be a positive integer');
|
|
321
|
-
}
|
|
322
|
-
const sinceSeconds = opts.since === undefined ? undefined : parseDuration(opts.since);
|
|
323
|
-
if (sinceSeconds !== undefined && (sinceSeconds === null || sinceSeconds <= 0)) {
|
|
324
|
-
throw new Error('--since must be a positive duration such as 2h or 7d');
|
|
325
|
-
}
|
|
326
|
-
const sinceMs = sinceSeconds == null ? undefined : sinceSeconds * 1000;
|
|
327
|
-
const entries = selectWatchdogHistory(readWatchdogEvents(), {
|
|
328
|
-
limit,
|
|
329
|
-
sinceMs,
|
|
330
|
-
sessionId,
|
|
331
|
-
includeTicks: opts.all === true,
|
|
332
|
-
});
|
|
333
|
-
if (globals.json === true) {
|
|
334
|
-
console.log(JSON.stringify({ logPath: watchdogLogPath(), events: entries }, null, 2));
|
|
335
|
-
return;
|
|
336
|
-
}
|
|
337
|
-
if (entries.length === 0) {
|
|
338
|
-
console.log(chalk.dim(`No Watchdog events found in ${watchdogLogPath()}`));
|
|
339
|
-
return;
|
|
340
|
-
}
|
|
341
|
-
for (const entry of entries) {
|
|
342
|
-
const when = new Date(entry.ts).toLocaleString();
|
|
343
|
-
const session = entry.sessionId ? entry.sessionId.slice(0, 8) : '-';
|
|
344
|
-
const reason = entry.reason ? ` · ${entry.reason}` : '';
|
|
345
|
-
console.log(`${chalk.dim(when)} ${entry.kind.padEnd(8)} ${chalk.bold(session)} ${entry.agent ?? '-'} ${entry.message}${reason}`);
|
|
346
|
-
}
|
|
347
|
-
console.log(chalk.dim(`${entries.length} event${entries.length === 1 ? '' : 's'} · ${watchdogLogPath()}`));
|
|
348
|
-
});
|
|
349
|
-
cmd.command('policy <sessionId> <policy>')
|
|
350
|
-
.description('Set per-session policy: off (ignore) | keep (default) | handsoff (detect + flag, never inject).')
|
|
351
|
-
.action((sessionId, policy) => {
|
|
352
|
-
const p = policy.toLowerCase();
|
|
353
|
-
if (p !== 'off' && p !== 'keep' && p !== 'handsoff') {
|
|
354
|
-
console.error(chalk.red(`invalid policy '${policy}'. Use: off | keep | handsoff`));
|
|
355
|
-
process.exitCode = 1;
|
|
356
|
-
return;
|
|
357
|
-
}
|
|
358
|
-
writePolicySentinel(stateDir(), sessionId, p);
|
|
359
|
-
console.log(`watchdog: session ${chalk.bold(sessionId.slice(0, 8))} policy = ${chalk.cyan(p)}`);
|
|
360
|
-
});
|
|
361
|
-
}
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import { BasePeriodicService, type DaemonContext } from './service.js';
|
|
2
|
-
import type { DaemonServiceId } from '../daemon-services.js';
|
|
3
|
-
export declare class WatchdogService extends BasePeriodicService {
|
|
4
|
-
readonly id: DaemonServiceId;
|
|
5
|
-
readonly intervalMs: number;
|
|
6
|
-
readonly deadlineMs = 120000;
|
|
7
|
-
protected onStart(_ctx: DaemonContext): Promise<void>;
|
|
8
|
-
protected onStop(): Promise<void>;
|
|
9
|
-
protected onTick(ctx: DaemonContext): Promise<void>;
|
|
10
|
-
}
|
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import { BasePeriodicService } from './service.js';
|
|
2
|
-
import { getConfigValueAsync } from '../device-config.js';
|
|
3
|
-
import { emitAsync } from '../feed/events.js';
|
|
4
|
-
const WATCHDOG_TICK_MS = 3 * 60_000;
|
|
5
|
-
const WATCHDOG_DEADLINE_MS = 120_000;
|
|
6
|
-
export class WatchdogService extends BasePeriodicService {
|
|
7
|
-
id = 'watchdog';
|
|
8
|
-
intervalMs = WATCHDOG_TICK_MS;
|
|
9
|
-
deadlineMs = WATCHDOG_DEADLINE_MS;
|
|
10
|
-
async onStart(_ctx) {
|
|
11
|
-
}
|
|
12
|
-
async onStop() {
|
|
13
|
-
}
|
|
14
|
-
async onTick(ctx) {
|
|
15
|
-
if ((await getConfigValueAsync('watchdog.enabled')).value !== true)
|
|
16
|
-
return;
|
|
17
|
-
const { runWatchdogPass } = await import('../watchdog/service.js');
|
|
18
|
-
const result = await runWatchdogPass({ nudge: true });
|
|
19
|
-
ctx.log('INFO', `watchdog: ${result.counts.total} live, ${result.counts.stalled} stalled, ${result.counts.nudged} nudged`);
|
|
20
|
-
await emitAsync('watchdog.action', {
|
|
21
|
-
module: 'watchdog',
|
|
22
|
-
total: result.counts.total,
|
|
23
|
-
stalled: result.counts.stalled,
|
|
24
|
-
nudged: result.counts.nudged,
|
|
25
|
-
});
|
|
26
|
-
}
|
|
27
|
-
}
|
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
export type PresenceStatus = 'connected' | 'disconnected';
|
|
2
|
-
export type PresenceLocation = 'local' | 'ssh';
|
|
3
|
-
export interface ObservedSession {
|
|
4
|
-
sessionId: string;
|
|
5
|
-
agent: string;
|
|
6
|
-
location: PresenceLocation;
|
|
7
|
-
device: string;
|
|
8
|
-
transport: string;
|
|
9
|
-
interactive: boolean;
|
|
10
|
-
}
|
|
11
|
-
export interface PresenceRecord {
|
|
12
|
-
sessionId: string;
|
|
13
|
-
agent: string;
|
|
14
|
-
location: PresenceLocation;
|
|
15
|
-
device: string;
|
|
16
|
-
transport: string;
|
|
17
|
-
interactive: boolean;
|
|
18
|
-
lastSeenMs: number;
|
|
19
|
-
status: PresenceStatus;
|
|
20
|
-
}
|
|
21
|
-
export type PresenceAction = 'reconnect-nudge' | 'keep-alive' | 'none';
|
|
22
|
-
export interface PresenceTransition {
|
|
23
|
-
record: PresenceRecord;
|
|
24
|
-
from: PresenceStatus;
|
|
25
|
-
to: PresenceStatus;
|
|
26
|
-
action: PresenceAction;
|
|
27
|
-
}
|
|
28
|
-
export declare const PRESENCE_TTL_MS: number;
|
|
29
|
-
export declare function presenceFilePath(dir?: string): string;
|
|
30
|
-
export declare function loadPresence(dir?: string): Record<string, PresenceRecord>;
|
|
31
|
-
export declare function savePresence(map: Record<string, PresenceRecord>, dir?: string): void;
|
|
32
|
-
interface ActiveSessionLike {
|
|
33
|
-
sessionId?: string;
|
|
34
|
-
kind: string;
|
|
35
|
-
context: string;
|
|
36
|
-
machine?: string;
|
|
37
|
-
provenance?: {
|
|
38
|
-
transport?: string;
|
|
39
|
-
};
|
|
40
|
-
}
|
|
41
|
-
export declare function observedFromActive(sessions: ActiveSessionLike[], selfHost?: string): ObservedSession[];
|
|
42
|
-
export declare function actionFor(record: PresenceRecord): PresenceAction;
|
|
43
|
-
export declare function reconcilePresence(prev: Record<string, PresenceRecord>, observed: ObservedSession[], nowMs: number): {
|
|
44
|
-
next: Record<string, PresenceRecord>;
|
|
45
|
-
transitions: PresenceTransition[];
|
|
46
|
-
};
|
|
47
|
-
export {};
|
|
@@ -1,100 +0,0 @@
|
|
|
1
|
-
import fs from 'node:fs';
|
|
2
|
-
import os from 'node:os';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import { getRuntimeStateDir } from '../state.js';
|
|
5
|
-
export const PRESENCE_TTL_MS = 30 * 60_000;
|
|
6
|
-
export function presenceFilePath(dir) {
|
|
7
|
-
return path.join(dir ?? path.join(getRuntimeStateDir(), 'watchdog'), 'presence.json');
|
|
8
|
-
}
|
|
9
|
-
export function loadPresence(dir) {
|
|
10
|
-
let raw;
|
|
11
|
-
try {
|
|
12
|
-
raw = fs.readFileSync(presenceFilePath(dir), 'utf8');
|
|
13
|
-
}
|
|
14
|
-
catch {
|
|
15
|
-
return {};
|
|
16
|
-
}
|
|
17
|
-
try {
|
|
18
|
-
const parsed = JSON.parse(raw);
|
|
19
|
-
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
20
|
-
return parsed;
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
catch {
|
|
24
|
-
}
|
|
25
|
-
return {};
|
|
26
|
-
}
|
|
27
|
-
export function savePresence(map, dir) {
|
|
28
|
-
try {
|
|
29
|
-
const file = presenceFilePath(dir);
|
|
30
|
-
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
31
|
-
fs.writeFileSync(file, JSON.stringify(map), 'utf8');
|
|
32
|
-
}
|
|
33
|
-
catch {
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
export function observedFromActive(sessions, selfHost = os.hostname()) {
|
|
37
|
-
const out = [];
|
|
38
|
-
for (const s of sessions) {
|
|
39
|
-
if (!s.sessionId)
|
|
40
|
-
continue;
|
|
41
|
-
const location = s.machine ? 'ssh' : 'local';
|
|
42
|
-
out.push({
|
|
43
|
-
sessionId: s.sessionId,
|
|
44
|
-
agent: s.kind,
|
|
45
|
-
location,
|
|
46
|
-
device: s.machine ?? selfHost,
|
|
47
|
-
transport: s.provenance?.transport ?? location,
|
|
48
|
-
interactive: s.context === 'terminal',
|
|
49
|
-
});
|
|
50
|
-
}
|
|
51
|
-
return out;
|
|
52
|
-
}
|
|
53
|
-
export function actionFor(record) {
|
|
54
|
-
if (record.status !== 'disconnected')
|
|
55
|
-
return 'none';
|
|
56
|
-
if (record.interactive)
|
|
57
|
-
return 'reconnect-nudge';
|
|
58
|
-
if (record.location === 'ssh')
|
|
59
|
-
return 'keep-alive';
|
|
60
|
-
return 'none';
|
|
61
|
-
}
|
|
62
|
-
export function reconcilePresence(prev, observed, nowMs) {
|
|
63
|
-
const next = {};
|
|
64
|
-
const transitions = [];
|
|
65
|
-
const observedIds = new Set(observed.map((o) => o.sessionId));
|
|
66
|
-
for (const o of observed) {
|
|
67
|
-
const before = prev[o.sessionId];
|
|
68
|
-
const record = {
|
|
69
|
-
sessionId: o.sessionId,
|
|
70
|
-
agent: o.agent,
|
|
71
|
-
location: o.location,
|
|
72
|
-
device: o.device,
|
|
73
|
-
transport: o.transport,
|
|
74
|
-
interactive: o.interactive,
|
|
75
|
-
lastSeenMs: nowMs,
|
|
76
|
-
status: 'connected',
|
|
77
|
-
};
|
|
78
|
-
next[o.sessionId] = record;
|
|
79
|
-
if (before && before.status === 'disconnected') {
|
|
80
|
-
transitions.push({ record, from: 'disconnected', to: 'connected', action: 'none' });
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
for (const [id, before] of Object.entries(prev)) {
|
|
84
|
-
if (observedIds.has(id))
|
|
85
|
-
continue;
|
|
86
|
-
if (nowMs - before.lastSeenMs > PRESENCE_TTL_MS)
|
|
87
|
-
continue;
|
|
88
|
-
const record = { ...before, status: 'disconnected' };
|
|
89
|
-
next[id] = record;
|
|
90
|
-
if (before.status === 'connected') {
|
|
91
|
-
transitions.push({
|
|
92
|
-
record,
|
|
93
|
-
from: 'connected',
|
|
94
|
-
to: 'disconnected',
|
|
95
|
-
action: actionFor(record),
|
|
96
|
-
});
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
return { next, transitions };
|
|
100
|
-
}
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import type { WatchdogEvent, WatchdogEventKind } from './log.js';
|
|
2
|
-
interface WatchdogHistoryEntry {
|
|
3
|
-
ts: number;
|
|
4
|
-
kind: WatchdogEventKind | 'inspection';
|
|
5
|
-
sessionId?: string;
|
|
6
|
-
agent?: string;
|
|
7
|
-
message: string;
|
|
8
|
-
reason?: string;
|
|
9
|
-
stalledForMs?: number;
|
|
10
|
-
nudgeText?: string;
|
|
11
|
-
}
|
|
12
|
-
interface WatchdogHistoryOptions {
|
|
13
|
-
limit?: number;
|
|
14
|
-
sinceMs?: number;
|
|
15
|
-
sessionId?: string;
|
|
16
|
-
includeTicks?: boolean;
|
|
17
|
-
nowMs?: number;
|
|
18
|
-
}
|
|
19
|
-
export declare function selectWatchdogHistory(events: WatchdogEvent[], options?: WatchdogHistoryOptions): WatchdogHistoryEntry[];
|
|
20
|
-
export {};
|
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
export function selectWatchdogHistory(events, options = {}) {
|
|
2
|
-
const limit = options.limit ?? 50;
|
|
3
|
-
const cutoff = options.sinceMs === undefined
|
|
4
|
-
? Number.NEGATIVE_INFINITY
|
|
5
|
-
: (options.nowMs ?? Date.now()) - options.sinceMs;
|
|
6
|
-
const session = options.sessionId?.toLowerCase();
|
|
7
|
-
const expanded = events.flatMap((event) => {
|
|
8
|
-
const inspections = event.inspections?.map((inspection) => ({
|
|
9
|
-
ts: event.ts,
|
|
10
|
-
kind: 'inspection',
|
|
11
|
-
sessionId: inspection.terminalId,
|
|
12
|
-
agent: inspection.agentType,
|
|
13
|
-
message: inspection.message,
|
|
14
|
-
reason: inspection.reason,
|
|
15
|
-
stalledForMs: inspection.stalledForMs,
|
|
16
|
-
})) ?? [];
|
|
17
|
-
if (event.kind === 'tick' && !options.includeTicks)
|
|
18
|
-
return inspections;
|
|
19
|
-
return [...inspections, {
|
|
20
|
-
ts: event.ts,
|
|
21
|
-
kind: event.kind,
|
|
22
|
-
sessionId: event.terminalId,
|
|
23
|
-
agent: event.agentType,
|
|
24
|
-
message: event.message,
|
|
25
|
-
reason: event.reason,
|
|
26
|
-
stalledForMs: event.stalledForMs,
|
|
27
|
-
nudgeText: event.nudgeText,
|
|
28
|
-
}];
|
|
29
|
-
});
|
|
30
|
-
const matching = expanded
|
|
31
|
-
.filter((entry) => entry.ts >= cutoff)
|
|
32
|
-
.filter((entry) => !session || entry.sessionId?.toLowerCase().startsWith(session))
|
|
33
|
-
.sort((a, b) => b.ts - a.ts);
|
|
34
|
-
if (matching.length <= limit)
|
|
35
|
-
return matching;
|
|
36
|
-
const newest = matching.slice(0, limit);
|
|
37
|
-
if (newest.some((entry) => entry.kind !== 'inspection'))
|
|
38
|
-
return newest;
|
|
39
|
-
const newestAction = matching.find((entry) => entry.kind !== 'inspection');
|
|
40
|
-
if (!newestAction)
|
|
41
|
-
return newest;
|
|
42
|
-
return [...newest.slice(0, limit - 1), newestAction].sort((a, b) => b.ts - a.ts);
|
|
43
|
-
}
|
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
export declare function watchdogLogPath(): string;
|
|
2
|
-
export type WatchdogEventKind = 'tick' | 'decision' | 'nudge' | 'undelivered' | 'rotate' | 'error';
|
|
3
|
-
export interface WatchdogEvent {
|
|
4
|
-
ts: number;
|
|
5
|
-
kind: WatchdogEventKind;
|
|
6
|
-
terminalId?: string;
|
|
7
|
-
agentType?: string;
|
|
8
|
-
message: string;
|
|
9
|
-
reason?: string;
|
|
10
|
-
tailLines?: string[];
|
|
11
|
-
stalledForMs?: number;
|
|
12
|
-
lastUserMessage?: string;
|
|
13
|
-
lastAssistantMessage?: string;
|
|
14
|
-
nudgeText?: string;
|
|
15
|
-
inspections?: WatchdogInspection[];
|
|
16
|
-
}
|
|
17
|
-
export interface WatchdogInspection {
|
|
18
|
-
terminalId?: string;
|
|
19
|
-
agentType: string;
|
|
20
|
-
message: string;
|
|
21
|
-
reason: string;
|
|
22
|
-
stalledForMs?: number;
|
|
23
|
-
}
|
|
24
|
-
export declare function parseWatchdogEvents(text: string): WatchdogEvent[];
|
|
25
|
-
export declare function readWatchdogEvents(logPath?: string): WatchdogEvent[];
|
|
26
|
-
export declare function formatEvent(ev: WatchdogEvent): string;
|
|
27
|
-
export declare const WATCHDOG_TAIL_MAX_CHARS = 4096;
|
|
28
|
-
export declare function boundTailLines(lines: string[], maxChars?: number): string[];
|
|
29
|
-
export declare function trimToLast(text: string, maxLines: number): string;
|
|
30
|
-
export declare function appendWatchdogEvents(events: WatchdogEvent[], opts?: {
|
|
31
|
-
logPath?: string;
|
|
32
|
-
maxLines?: number;
|
|
33
|
-
}): void;
|