@phnx-labs/agents-cli 1.23.38 → 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.
Files changed (102) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +7 -20
  3. package/dist/cli/command-registry.js +0 -2
  4. package/dist/commands/config.js +0 -4
  5. package/dist/commands/daemon.js +5 -5
  6. package/dist/commands/events.js +1 -1
  7. package/dist/commands/exec.d.ts +4 -0
  8. package/dist/commands/exec.js +14 -1
  9. package/dist/commands/lead.js +4 -3
  10. package/dist/commands/setup.d.ts +1 -1
  11. package/dist/commands/setup.js +1 -9
  12. package/dist/commands/ssh.js +4 -5
  13. package/dist/lib/accounting/account-pool-collect.d.ts +1 -0
  14. package/dist/lib/accounting/account-pool-collect.js +13 -7
  15. package/dist/lib/accounting/account-pool.d.ts +1 -0
  16. package/dist/lib/accounting/account-pool.js +4 -3
  17. package/dist/lib/accounting/usage.d.ts +1 -1
  18. package/dist/lib/answer-router.d.ts +1 -1
  19. package/dist/lib/answer-router.js +16 -6
  20. package/dist/lib/channels/providers/session.js +13 -0
  21. package/dist/lib/channels/registry.d.ts +1 -1
  22. package/dist/lib/config-keys.d.ts +1 -1
  23. package/dist/lib/config-keys.js +1 -4
  24. package/dist/lib/daemon/daemon.js +1 -6
  25. package/dist/lib/daemon/device-probe-service.js +8 -0
  26. package/dist/lib/daemon-services.d.ts +1 -1
  27. package/dist/lib/daemon-services.js +1 -6
  28. package/dist/lib/device-config.js +2 -11
  29. package/dist/lib/devices/stats-cache.d.ts +24 -1
  30. package/dist/lib/devices/stats-cache.js +52 -18
  31. package/dist/lib/devices/worker-pick.d.ts +1 -1
  32. package/dist/lib/devices/worker-pick.js +8 -1
  33. package/dist/lib/feed/answer.js +25 -1
  34. package/dist/lib/feed/attention.d.ts +8 -0
  35. package/dist/lib/feed/attention.js +39 -0
  36. package/dist/lib/feed/tab-delivery.d.ts +27 -0
  37. package/dist/lib/feed/tab-delivery.js +102 -0
  38. package/dist/lib/feed/watch.d.ts +3 -0
  39. package/dist/lib/feed/watch.js +63 -13
  40. package/dist/lib/hosts/passthrough.js +0 -1
  41. package/dist/lib/hosts/ready.d.ts +3 -0
  42. package/dist/lib/hosts/ready.js +41 -1
  43. package/dist/lib/installations/migrate.d.ts +0 -1
  44. package/dist/lib/installations/migrate.js +0 -17
  45. package/dist/lib/lead/drafts.d.ts +11 -0
  46. package/dist/lib/lead/drafts.js +34 -0
  47. package/dist/lib/lead/host.d.ts +5 -0
  48. package/dist/lib/lead/host.js +52 -1
  49. package/dist/lib/lead/paths.js +1 -1
  50. package/dist/lib/lead/tools.d.ts +1 -0
  51. package/dist/lib/lead/tools.js +22 -0
  52. package/dist/lib/menubar/snapshot.d.ts +0 -6
  53. package/dist/lib/menubar/snapshot.js +0 -18
  54. package/dist/lib/session/active.d.ts +2 -1
  55. package/dist/lib/session/active.js +21 -9
  56. package/dist/lib/session/hook-sessions.d.ts +10 -0
  57. package/dist/lib/session/hook-sessions.js +22 -10
  58. package/dist/lib/session/inject-target.d.ts +1 -0
  59. package/dist/lib/session/inject-target.js +2 -1
  60. package/dist/lib/session/pid-registry.d.ts +1 -0
  61. package/dist/lib/session/remote/watch.d.ts +1 -0
  62. package/dist/lib/smart-launch.d.ts +5 -1
  63. package/dist/lib/smart-launch.js +41 -20
  64. package/dist/lib/startup/command-registry.js +2 -1
  65. package/dist/lib/state.js +0 -1
  66. package/dist/lib/teams/placement-probe.d.ts +5 -2
  67. package/dist/lib/teams/placement-probe.js +119 -57
  68. package/dist/lib/teams/scheduler.d.ts +1 -0
  69. package/dist/lib/terminal/index.d.ts +1 -1
  70. package/dist/lib/terminal/index.js +1 -1
  71. package/dist/lib/terminal/inject.d.ts +0 -15
  72. package/dist/lib/terminal/inject.js +2 -16
  73. package/dist/lib/terminal/resolve.d.ts +2 -1
  74. package/dist/lib/terminal/resolve.js +13 -18
  75. package/dist/lib/types.d.ts +0 -3
  76. package/package.json +1 -1
  77. package/dist/commands/setup-watchdog.d.ts +0 -3
  78. package/dist/commands/setup-watchdog.js +0 -49
  79. package/dist/commands/watchdog.d.ts +0 -4
  80. package/dist/commands/watchdog.js +0 -361
  81. package/dist/lib/daemon/watchdog-service.d.ts +0 -10
  82. package/dist/lib/daemon/watchdog-service.js +0 -27
  83. package/dist/lib/session/presence.d.ts +0 -47
  84. package/dist/lib/session/presence.js +0 -100
  85. package/dist/lib/watchdog/history.d.ts +0 -20
  86. package/dist/lib/watchdog/history.js +0 -43
  87. package/dist/lib/watchdog/log.d.ts +0 -33
  88. package/dist/lib/watchdog/log.js +0 -117
  89. package/dist/lib/watchdog/read.d.ts +0 -8
  90. package/dist/lib/watchdog/read.js +0 -93
  91. package/dist/lib/watchdog/rotate.d.ts +0 -55
  92. package/dist/lib/watchdog/rotate.js +0 -220
  93. package/dist/lib/watchdog/runner.d.ts +0 -100
  94. package/dist/lib/watchdog/runner.js +0 -727
  95. package/dist/lib/watchdog/service.d.ts +0 -15
  96. package/dist/lib/watchdog/service.js +0 -36
  97. package/dist/lib/watchdog/watchdog-agent.d.ts +0 -8
  98. package/dist/lib/watchdog/watchdog-agent.js +0 -32
  99. package/dist/lib/watchdog/watchdog.d.ts +0 -43
  100. package/dist/lib/watchdog/watchdog.js +0 -116
  101. package/dist/lib/watchdog/watchdogTail.d.ts +0 -6
  102. package/dist/lib/watchdog/watchdogTail.js +0 -116
@@ -1,10 +1,11 @@
1
1
  import { getActiveSessions } from '../session/active.js';
2
2
  import { machineId } from '../machine-id.js';
3
- const IDE_INJECT_VARIANTS = {
4
- codium: { cli: 'codium', scheme: 'vscodium' },
5
- cursor: { cli: 'cursor', scheme: 'cursor' },
6
- code: { cli: 'code', scheme: 'vscode' },
7
- };
3
+ const IDE_HOSTS = new Set(['codium', 'cursor', 'code']);
4
+ export function typedByEditorTab(session) {
5
+ if (!session.sessionId || session.context === 'headless' || session.context === 'teams')
6
+ return false;
7
+ return !session.host || IDE_HOSTS.has(session.host);
8
+ }
8
9
  export function addressabilityRecoveryHint(session, fallbackId) {
9
10
  const sid = session.sessionId;
10
11
  const resumeId = sid ?? fallbackId;
@@ -16,7 +17,7 @@ export function addressabilityRecoveryHint(session, fallbackId) {
16
17
  if (session.host === 'ghostty') {
17
18
  return `Ghostty has no per-split addressing. ${interactive ? `Enable tmux wrapping with \`${tmuxCmd}\` and re-launch, or ` : ''}use \`${resumeCmd}\` to continue this session.`;
18
19
  }
19
- if (session.host && session.host in IDE_INJECT_VARIANTS && !sid) {
20
+ if (session.host && IDE_HOSTS.has(session.host) && !sid) {
20
21
  return `This IDE terminal has not registered a session id yet. Wait a moment and retry, or use \`${resumeCmd}\` to continue.`;
21
22
  }
22
23
  if (session.host) {
@@ -40,19 +41,13 @@ export function resolveInjectTargetForSession(session, opts = {}) {
40
41
  target: { backend: 'iterm', session: prov.reply.session },
41
42
  };
42
43
  }
43
- const variant = session.host ? IDE_INJECT_VARIANTS[session.host] : undefined;
44
- if (variant) {
45
- if (!session.sessionId) {
46
- return {
47
- addressable: false,
48
- reason: `IDE terminal (${session.host}) has no session id to address`,
49
- hint: addressabilityRecoveryHint(session),
50
- };
51
- }
44
+ if (session.host && IDE_HOSTS.has(session.host)) {
52
45
  return {
53
- addressable: true,
54
- rail: 'vscodium',
55
- target: { backend: 'vscodium', terminalId: session.sessionId, cli: variant.cli, scheme: variant.scheme },
46
+ addressable: false,
47
+ reason: session.sessionId
48
+ ? `IDE terminal (${session.host}): the AGI EXT window that binds the session types into it`
49
+ : `IDE terminal (${session.host}) has no session id to address`,
50
+ hint: addressabilityRecoveryHint(session),
56
51
  };
57
52
  }
58
53
  if (session.host === 'ghostty') {
@@ -439,9 +439,6 @@ export interface Meta {
439
439
  model?: {
440
440
  tiers?: Record<string, Partial<Record<'cheap' | 'default' | 'best' | 'ultra', string>>>;
441
441
  };
442
- watchdog?: {
443
- rotate?: 'on' | 'off';
444
- };
445
442
  lease?: {
446
443
  secretsBundle?: string;
447
444
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phnx-labs/agents-cli",
3
- "version": "1.23.38",
3
+ "version": "1.23.40",
4
4
  "description": "One CLI for all your AI coding agents - versions, config, cloud dispatch, sessions, and teams (now with first-class Grok Build CLI support)",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -1,3 +0,0 @@
1
- import type { Command } from 'commander';
2
- export declare function runWatchdogSetupWizard(): Promise<void>;
3
- export declare function registerSetupWatchdogCommand(setup: Command): void;
@@ -1,49 +0,0 @@
1
- import chalk from 'chalk';
2
- import { spawnSync } from 'node:child_process';
3
- import { getCliLaunch } from '../lib/cli-entry.js';
4
- import { loadDevices } from '../lib/devices/registry.js';
5
- import { machineId, normalizeHost } from '../lib/machine-id.js';
6
- import { getConfigValue, setConfigValue } from '../lib/device-config.js';
7
- import { isPromptCancelled, requireInteractiveSelection } from './utils.js';
8
- export async function runWatchdogSetupWizard() {
9
- const registry = await loadDevices();
10
- const devices = [...new Set([...Object.keys(registry), machineId()].map(normalizeHost))].sort();
11
- const enabled = new Set(devices.filter((device) => getConfigValue('watchdog.enabled', { device }).value === true));
12
- if (!process.stdin.isTTY || !process.stdout.isTTY) {
13
- requireInteractiveSelection('watchdog devices', ['agents watchdog enable', 'agents watchdog enable --device <device>']);
14
- }
15
- try {
16
- const { checkbox } = await import('@inquirer/prompts');
17
- const selected = await checkbox({
18
- message: 'Devices where the watchdog should run:',
19
- choices: devices.map((device) => ({ name: device, value: device, checked: enabled.has(device) })),
20
- });
21
- const selectedSet = new Set(selected);
22
- for (const device of devices) {
23
- const on = selectedSet.has(device);
24
- if (device === normalizeHost(machineId())) {
25
- setConfigValue('watchdog.enabled', on);
26
- continue;
27
- }
28
- const launch = getCliLaunch(['watchdog', on ? 'enable' : 'disable', '--device', device]);
29
- const result = spawnSync(launch.command, launch.args, { stdio: 'inherit', env: process.env });
30
- if ((result.status ?? 1) !== 0)
31
- throw new Error(`Could not configure watchdog on ${device}`);
32
- }
33
- console.log(chalk.green(selected.length === 0
34
- ? 'Watchdog disabled on every registered device'
35
- : `Watchdog enabled on: ${selected.join(', ')}`));
36
- }
37
- catch (error) {
38
- if (isPromptCancelled(error)) {
39
- console.log(chalk.gray('Cancelled'));
40
- return;
41
- }
42
- throw error;
43
- }
44
- }
45
- export function registerSetupWatchdogCommand(setup) {
46
- setup.command('watchdog')
47
- .description('Choose the devices where the daemon watchdog pass runs.')
48
- .action(runWatchdogSetupWizard);
49
- }
@@ -1,4 +0,0 @@
1
- import type { Command } from 'commander';
2
- import { type WatchdogTickResult } from '../lib/watchdog/runner.js';
3
- export declare function formatWatchdogTickLines(result: WatchdogTickResult, willInject: boolean, verbose?: boolean): string[];
4
- export declare function registerWatchdogCommand(program: Command): void;
@@ -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 {};