@phnx-labs/agents-cli 1.23.39 → 1.23.41

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 (87) hide show
  1. package/CHANGELOG.md +20 -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/lead.js +4 -3
  8. package/dist/commands/setup.d.ts +1 -1
  9. package/dist/commands/setup.js +1 -9
  10. package/dist/commands/ssh.js +4 -5
  11. package/dist/lib/accounting/usage.d.ts +1 -1
  12. package/dist/lib/answer-router.d.ts +1 -1
  13. package/dist/lib/answer-router.js +16 -6
  14. package/dist/lib/channels/providers/session.js +13 -0
  15. package/dist/lib/channels/registry.d.ts +1 -1
  16. package/dist/lib/config-keys.d.ts +1 -1
  17. package/dist/lib/config-keys.js +1 -4
  18. package/dist/lib/daemon/daemon.js +1 -6
  19. package/dist/lib/daemon-services.d.ts +1 -1
  20. package/dist/lib/daemon-services.js +0 -5
  21. package/dist/lib/device-config.js +2 -11
  22. package/dist/lib/feed/answer.js +25 -1
  23. package/dist/lib/feed/attention.d.ts +8 -0
  24. package/dist/lib/feed/attention.js +39 -0
  25. package/dist/lib/feed/tab-delivery.d.ts +27 -0
  26. package/dist/lib/feed/tab-delivery.js +102 -0
  27. package/dist/lib/feed/watch.d.ts +3 -0
  28. package/dist/lib/feed/watch.js +63 -13
  29. package/dist/lib/hosts/passthrough.js +0 -1
  30. package/dist/lib/installations/migrate.d.ts +0 -1
  31. package/dist/lib/installations/migrate.js +0 -17
  32. package/dist/lib/lead/drafts.d.ts +11 -0
  33. package/dist/lib/lead/drafts.js +34 -0
  34. package/dist/lib/lead/host.d.ts +5 -0
  35. package/dist/lib/lead/host.js +52 -1
  36. package/dist/lib/lead/paths.js +1 -1
  37. package/dist/lib/lead/tools.d.ts +1 -0
  38. package/dist/lib/lead/tools.js +22 -0
  39. package/dist/lib/menubar/snapshot.d.ts +0 -6
  40. package/dist/lib/menubar/snapshot.js +0 -18
  41. package/dist/lib/recordings/settle.d.ts +5 -2
  42. package/dist/lib/recordings/settle.js +8 -6
  43. package/dist/lib/session/active.d.ts +2 -1
  44. package/dist/lib/session/active.js +10 -6
  45. package/dist/lib/session/db.js +24 -6
  46. package/dist/lib/session/hook-sessions.d.ts +10 -0
  47. package/dist/lib/session/hook-sessions.js +22 -10
  48. package/dist/lib/session/inject-target.d.ts +1 -0
  49. package/dist/lib/session/inject-target.js +2 -1
  50. package/dist/lib/session/pid-registry.d.ts +1 -0
  51. package/dist/lib/session/remote/watch.d.ts +1 -0
  52. package/dist/lib/startup/command-registry.js +2 -1
  53. package/dist/lib/state.js +0 -1
  54. package/dist/lib/terminal/index.d.ts +1 -1
  55. package/dist/lib/terminal/index.js +1 -1
  56. package/dist/lib/terminal/inject.d.ts +0 -15
  57. package/dist/lib/terminal/inject.js +2 -16
  58. package/dist/lib/terminal/resolve.d.ts +2 -1
  59. package/dist/lib/terminal/resolve.js +13 -18
  60. package/dist/lib/types.d.ts +0 -3
  61. package/package.json +1 -1
  62. package/dist/commands/setup-watchdog.d.ts +0 -3
  63. package/dist/commands/setup-watchdog.js +0 -49
  64. package/dist/commands/watchdog.d.ts +0 -4
  65. package/dist/commands/watchdog.js +0 -361
  66. package/dist/lib/daemon/watchdog-service.d.ts +0 -10
  67. package/dist/lib/daemon/watchdog-service.js +0 -27
  68. package/dist/lib/session/presence.d.ts +0 -47
  69. package/dist/lib/session/presence.js +0 -100
  70. package/dist/lib/watchdog/history.d.ts +0 -20
  71. package/dist/lib/watchdog/history.js +0 -43
  72. package/dist/lib/watchdog/log.d.ts +0 -33
  73. package/dist/lib/watchdog/log.js +0 -117
  74. package/dist/lib/watchdog/read.d.ts +0 -8
  75. package/dist/lib/watchdog/read.js +0 -93
  76. package/dist/lib/watchdog/rotate.d.ts +0 -55
  77. package/dist/lib/watchdog/rotate.js +0 -220
  78. package/dist/lib/watchdog/runner.d.ts +0 -100
  79. package/dist/lib/watchdog/runner.js +0 -727
  80. package/dist/lib/watchdog/service.d.ts +0 -15
  81. package/dist/lib/watchdog/service.js +0 -36
  82. package/dist/lib/watchdog/watchdog-agent.d.ts +0 -8
  83. package/dist/lib/watchdog/watchdog-agent.js +0 -32
  84. package/dist/lib/watchdog/watchdog.d.ts +0 -43
  85. package/dist/lib/watchdog/watchdog.js +0 -116
  86. package/dist/lib/watchdog/watchdogTail.d.ts +0 -6
  87. package/dist/lib/watchdog/watchdogTail.js +0 -116
@@ -1,727 +0,0 @@
1
- import * as fs from 'fs';
2
- import * as path from 'path';
3
- import * as crypto from 'crypto';
4
- import { getActiveSessions } from '../session/active.js';
5
- import { reconcilePresence, loadPresence, savePresence, observedFromActive, } from '../session/presence.js';
6
- import { resolveInjectTargetForSession, injectIntoTerminal, } from '../terminal/index.js';
7
- import { classifyTerminal, } from './watchdog.js';
8
- import { makeWatchdogAgentDecider } from './watchdog-agent.js';
9
- import { readWatchdogTail, WATCHDOG_STALL_MS, WATCHDOG_COOLDOWN_MS, WATCHDOG_DORMANT_MS, WATCHDOG_TAIL_LINES, } from './read.js';
10
- import { getRuntimeStateDir } from '../state.js';
11
- import { withFileLock, atomicWriteFileSync, ensureLockTarget } from '../fs-atomic.js';
12
- import { resolveAnswerRoute, isOpenQuestionBlock } from '../answer-router.js';
13
- import { enqueue, mailboxDir } from '../mailbox.js';
14
- import { mailboxIdForActiveSession } from '../mailbox-target.js';
15
- import { readBlock, blockIdForSession, buildDeclaredBlock, publishBlock } from '../feed/feed.js';
16
- import { summarizeWatchdogTail } from './watchdogTail.js';
17
- import { appendWatchdogEvents } from './log.js';
18
- import { buildRotateLaunchCommand, buildRotateReplayText, classifyTailForRotate, defaultRotateGate, defaultTuiLiveFor, exitSequenceFor, isInflightPhase, isWatchdogRotateEnabled, listInflightRotates, readRotateState, recordRotateSkip, shouldLogRotateSkip, writeRotateState, DEFAULT_ROTATE_READINESS_MS, DEFAULT_ROTATE_SKIP_COOLDOWN_MS, DEFAULT_ROTATE_FAILED_COOLDOWN_MS, } from './rotate.js';
19
- export const DEFAULT_THRESHOLDS = {
20
- stallMs: WATCHDOG_STALL_MS,
21
- cooldownMs: WATCHDOG_COOLDOWN_MS,
22
- dormantMs: WATCHDOG_DORMANT_MS,
23
- };
24
- const DEFAULT_NUDGE_TEXT = 'Continue.';
25
- function watchdogStateDir(opts) {
26
- return opts.stateDir ?? path.join(getRuntimeStateDir(), 'watchdog');
27
- }
28
- function readJsonFile(file, fallback) {
29
- try {
30
- return JSON.parse(fs.readFileSync(file, 'utf8'));
31
- }
32
- catch {
33
- return fallback;
34
- }
35
- }
36
- function writeJsonFile(file, value) {
37
- try {
38
- fs.mkdirSync(path.dirname(file), { recursive: true });
39
- fs.writeFileSync(file, JSON.stringify(value, null, 2));
40
- }
41
- catch {
42
- }
43
- }
44
- function readNudgeLedger(dir) {
45
- return readJsonFile(path.join(dir, 'nudges.json'), {});
46
- }
47
- function readPolicySentinel(dir, sessionId) {
48
- if (!sessionId)
49
- return 'keep';
50
- let raw;
51
- try {
52
- raw = fs.readFileSync(path.join(dir, 'policy', sessionId), 'utf8').trim().toLowerCase();
53
- }
54
- catch {
55
- return 'keep';
56
- }
57
- return raw === 'off' || raw === 'handsoff' ? raw : 'keep';
58
- }
59
- export function writePolicySentinel(dir, sessionId, policy) {
60
- const file = path.join(dir, 'policy', sessionId);
61
- fs.mkdirSync(path.dirname(file), { recursive: true });
62
- fs.writeFileSync(file, policy + '\n');
63
- }
64
- function defaultLastActivity(s) {
65
- if (s.sessionFile) {
66
- try {
67
- return fs.statSync(s.sessionFile).mtimeMs;
68
- }
69
- catch {
70
- }
71
- }
72
- return s.startedAtMs;
73
- }
74
- function planDelivery(session, chosenText, block, allowGhosttyFocus) {
75
- const sessionId = session.sessionId ?? '';
76
- const mailboxId = mailboxIdForActiveSession(session) ?? sessionId;
77
- const resolution = resolveInjectTargetForSession(session, { allowGhosttyFocus });
78
- const route = resolveAnswerRoute({ mailboxId, answer: chosenText, session, block });
79
- if (resolution.addressable) {
80
- return { via: 'inject', rail: resolution.rail, target: resolution.target };
81
- }
82
- if (route.kind === 'resume')
83
- return { via: 'resume' };
84
- if (route.kind === 'mailbox' && isOpenQuestionBlock(block))
85
- return { via: 'mailbox', mailboxId };
86
- return {
87
- via: 'refuse',
88
- reason: route.kind === 'refuse' ? route.reason : resolution.reason,
89
- hint: route.kind === 'refuse' ? undefined : resolution.hint,
90
- };
91
- }
92
- function defaultOpenBlockFor(session) {
93
- const id = mailboxIdForActiveSession(session) ?? session.sessionId;
94
- if (!id)
95
- return null;
96
- const direct = readBlock(blockIdForSession(id));
97
- if (direct && direct.mailboxId === id)
98
- return direct;
99
- return null;
100
- }
101
- function deliverViaMailbox(mailboxId, text, block) {
102
- enqueue(mailboxDir(mailboxId), { to: mailboxId, text, from: 'watchdog', blockId: block?.blockId });
103
- }
104
- async function deliverViaResume(session, text) {
105
- const sid = session.sessionId;
106
- if (!sid)
107
- return { ok: false, error: 'no session id to resume' };
108
- try {
109
- const [{ getAgentsInvocation }, { spawn }] = await Promise.all([
110
- import('../daemon/daemon.js'),
111
- import('child_process'),
112
- ]);
113
- const inv = getAgentsInvocation(['run', session.kind, '--resume', sid, '--', text]);
114
- const code = await new Promise((resolve) => {
115
- const child = spawn(inv.command, inv.args, { stdio: 'ignore', env: process.env, detached: false });
116
- child.on('exit', (c) => resolve(c ?? 1));
117
- child.on('error', () => resolve(1));
118
- });
119
- return code === 0 ? { ok: true } : { ok: false, error: `resume exited ${code}` };
120
- }
121
- catch (err) {
122
- return { ok: false, error: err instanceof Error ? err.message : String(err) };
123
- }
124
- }
125
- function rotateOutcomeReason(s) {
126
- switch (s.phase) {
127
- case 'awaiting-tui':
128
- return `rotate in flight — awaiting new session ${s.newSessionId} TUI (deadline ${new Date(s.deadlineMs).toISOString()})`;
129
- case 'done':
130
- return `rotated → ${s.newSessionId}; replayed resume`;
131
- case 'failed':
132
- return `rotate failed: ${s.error ?? 'unknown'}`;
133
- default:
134
- return `rotate in flight (${s.phase})`;
135
- }
136
- }
137
- async function advanceRotate(state, deps) {
138
- let s = state;
139
- const fail = (error) => {
140
- s = {
141
- ...s, phase: 'failed', error, updatedAtMs: deps.nowMs,
142
- suppressUntilMs: deps.nowMs + DEFAULT_ROTATE_FAILED_COOLDOWN_MS,
143
- };
144
- writeRotateState(deps.dir, s);
145
- deps.flags[s.sessionId] = { reason: `rotate failed: ${error}`, host: s.host, atMs: deps.nowMs };
146
- deps.logEvents.push({
147
- ts: deps.nowMs, kind: 'rotate', terminalId: s.sessionId, agentType: s.agent,
148
- message: `rotate failed: ${s.sessionId} — ${error}`,
149
- });
150
- return s;
151
- };
152
- if (s.phase === 'exiting' || s.phase === 'launching') {
153
- s = { ...s, phase: 'awaiting-tui', updatedAtMs: deps.nowMs };
154
- writeRotateState(deps.dir, s);
155
- }
156
- if (s.phase === 'awaiting-tui') {
157
- if (!deps.tuiLiveFor(s, deps.sessions)) {
158
- if (deps.nowMs > s.deadlineMs) {
159
- return fail(`new session ${s.newSessionId} TUI not live within the readiness budget — nothing was typed ` +
160
- `into a possibly-dead shell; the terminal may sit at a BARE SHELL now: relaunch manually with ` +
161
- `\`agents run auto\` (there is no automatic recovery)`);
162
- }
163
- return s;
164
- }
165
- s = { ...s, phase: 'replaying', updatedAtMs: deps.nowMs };
166
- writeRotateState(deps.dir, s);
167
- }
168
- if (s.phase === 'replaying') {
169
- if (!deps.mayInject)
170
- return s;
171
- let ok = true;
172
- let error;
173
- try {
174
- const r = await deps.injectFn(s.target, buildRotateReplayText(s.sessionId), { dryRun: deps.injectDryRun });
175
- ok = r.ok;
176
- error = r.error;
177
- }
178
- catch (err) {
179
- ok = false;
180
- error = err instanceof Error ? err.message : String(err);
181
- }
182
- if (!ok)
183
- return fail(`replay inject failed: ${error ?? 'unknown error'}`);
184
- s = { ...s, phase: 'done', updatedAtMs: deps.nowMs };
185
- writeRotateState(deps.dir, s);
186
- deps.logEvents.push({
187
- ts: deps.nowMs, kind: 'rotate', terminalId: s.sessionId, agentType: s.agent,
188
- message: `rotated ${s.sessionId} → ${s.newSessionId}; replayed resume`,
189
- });
190
- }
191
- return s;
192
- }
193
- export async function runWatchdogTick(opts = {}) {
194
- const nowMs = opts.nowMs ?? Date.now();
195
- const nudgeText = opts.nudgeText ?? DEFAULT_NUDGE_TEXT;
196
- const thresholds = { ...DEFAULT_THRESHOLDS, ...opts.thresholds };
197
- const dir = watchdogStateDir(opts);
198
- const lastActivityFor = opts.lastActivityFor ?? defaultLastActivity;
199
- const tailFor = opts.tailFor ?? ((s) => (s.sessionId ? readWatchdogTail(s.sessionId, s.kind, WATCHDOG_TAIL_LINES) : []));
200
- const policyFor = opts.policyFor ?? ((s) => (s.sessionId ? readPolicySentinel(dir, s.sessionId) : 'keep'));
201
- const openBlockFor = opts.openBlockFor ?? defaultOpenBlockFor;
202
- const injectFn = opts.injectFn ?? injectIntoTerminal;
203
- const publishBlockFn = opts.publishBlockFn ?? publishBlock;
204
- const rotateEnabled = opts.rotate ?? isWatchdogRotateEnabled();
205
- const rotateGate = opts.rotateGate ?? defaultRotateGate;
206
- const newSessionIdFor = opts.newSessionIdFor ?? (() => crypto.randomUUID());
207
- const rotateReadinessMs = opts.rotateReadinessMs ?? DEFAULT_ROTATE_READINESS_MS;
208
- const rotateKeyDelayMs = opts.rotateKeyDelayMs ?? 300;
209
- const tuiLiveFor = opts.tuiLiveFor ?? defaultTuiLiveFor;
210
- const sessions = opts.sessions ?? (await getActiveSessions());
211
- const presenceResult = reconcilePresence(loadPresence(dir), observedFromActive(sessions), nowMs);
212
- savePresence(presenceResult.next, dir);
213
- const presence = {
214
- connected: Object.values(presenceResult.next).filter((r) => r.status === 'connected').length,
215
- disconnected: Object.values(presenceResult.next).filter((r) => r.status === 'disconnected').length,
216
- transitions: presenceResult.transitions,
217
- };
218
- const ledger = readNudgeLedger(dir);
219
- const ledgerUpdates = {};
220
- const flags = {};
221
- const outcomes = [];
222
- const logEvents = [];
223
- const viaLabel = (plan) => plan.via === 'inject' ? `inject (${plan.rail})` : plan.via;
224
- const advancedRotates = new Set();
225
- const rotateDeps = {
226
- dir, nowMs, sessions,
227
- mayInject: opts.nudge === true,
228
- injectFn, tuiLiveFor,
229
- injectDryRun: opts.injectDryRun,
230
- logEvents, flags,
231
- };
232
- const tailCache = new Map();
233
- const idleCandidates = [];
234
- for (const session of sessions) {
235
- const sid = session.sessionId;
236
- if (!sid)
237
- continue;
238
- if (policyFor(session) === 'off')
239
- continue;
240
- const la = lastActivityFor(session);
241
- if (la === undefined)
242
- continue;
243
- const st = classifyTerminal({
244
- lastActivityMs: la, nowMs, lastNudgeMs: ledger[sid] ?? null, optedOut: false,
245
- stallMs: thresholds.stallMs, cooldownMs: thresholds.cooldownMs, dormantMs: thresholds.dormantMs,
246
- });
247
- if (st.kind !== 'stalled')
248
- continue;
249
- const tail = tailFor(session);
250
- tailCache.set(sid, tail);
251
- if (rotateEnabled) {
252
- const inflight = readRotateState(dir, sid);
253
- if (inflight && (isInflightPhase(inflight.phase) || (inflight.phase === 'failed' && (inflight.suppressUntilMs ?? 0) > nowMs)))
254
- continue;
255
- if (classifyTailForRotate(tail, nowMs).kind === 'rate_limited')
256
- continue;
257
- }
258
- idleCandidates.push({
259
- session,
260
- candidate: {
261
- terminalId: sid,
262
- agentType: session.kind === 'codex' ? 'codex' : 'claude',
263
- tailLines: tail,
264
- stalledForMs: st.stalledForMs,
265
- task: session.topic ?? session.label ?? session.name,
266
- cwd: session.cwd,
267
- },
268
- });
269
- }
270
- const decisionByTerminal = new Map();
271
- if (idleCandidates.length > 0) {
272
- if (opts.smartDecider) {
273
- for (const { session, candidate } of idleCandidates) {
274
- const raw = await opts.smartDecider(session, candidate);
275
- decisionByTerminal.set(candidate.terminalId, raw.nudge ? raw : { ...raw, needsHuman: raw.needsHuman ?? true });
276
- }
277
- }
278
- else {
279
- const decide = opts.agentDecider ?? makeWatchdogAgentDecider(opts.smartAgent ?? 'claude');
280
- const verdicts = await decide(idleCandidates.map((e) => e.candidate));
281
- if (verdicts.size === 0) {
282
- logEvents.push({
283
- ts: nowMs, kind: 'error',
284
- message: `watchdog agent returned no verdicts for ${idleCandidates.length} idle session(s) — decider unavailable this tick`,
285
- });
286
- }
287
- for (const { candidate } of idleCandidates) {
288
- const d = verdicts.get(candidate.terminalId);
289
- decisionByTerminal.set(candidate.terminalId, d
290
- ? {
291
- nudge: d.action === 'nudge',
292
- reason: d.reason || `agent: ${d.action}`,
293
- text: d.text || undefined,
294
- needsHuman: d.action === 'skip' ? d.needsHuman ?? true : undefined,
295
- }
296
- : { nudge: false, reason: 'watchdog agent returned no verdict — retry next tick' });
297
- }
298
- }
299
- }
300
- for (const session of sessions) {
301
- const policy = policyFor(session);
302
- const base = {
303
- sessionId: session.sessionId,
304
- kind: session.kind,
305
- host: session.host,
306
- cwd: session.cwd,
307
- project: session.project,
308
- label: session.label,
309
- name: session.name,
310
- generatedTitle: session.generatedTitle,
311
- topic: session.topic,
312
- preview: session.preview,
313
- activity: session.activity,
314
- status: session.status,
315
- startedAtMs: session.startedAtMs,
316
- lastActivityMs: session.lastActivityMs,
317
- machine: session.machine ?? session.provenance?.host,
318
- owner: session.owner,
319
- policy,
320
- stall: 'active',
321
- decision: 'skip',
322
- reason: '',
323
- nudgeText,
324
- };
325
- if (!session.sessionId) {
326
- outcomes.push({ ...base, reason: 'no session id (cannot address or track)' });
327
- continue;
328
- }
329
- if (policy === 'off') {
330
- outcomes.push({ ...base, stall: 'opted_out', reason: 'policy: off (opted out)' });
331
- continue;
332
- }
333
- const lastActivityMs = lastActivityFor(session);
334
- base.lastActivityMs = session.lastActivityMs ?? lastActivityMs;
335
- if (lastActivityMs === undefined) {
336
- outcomes.push({ ...base, reason: 'no activity timestamp (no transcript / start time)' });
337
- continue;
338
- }
339
- const status = classifyTerminal({
340
- lastActivityMs,
341
- nowMs,
342
- lastNudgeMs: ledger[session.sessionId] ?? null,
343
- optedOut: false,
344
- stallMs: thresholds.stallMs,
345
- cooldownMs: thresholds.cooldownMs,
346
- dormantMs: thresholds.dormantMs,
347
- });
348
- base.stall = status.kind;
349
- if (status.kind !== 'stalled') {
350
- const reason = status.kind === 'active' ? `active (last activity ${Math.round((nowMs - lastActivityMs) / 1000)}s ago)`
351
- : status.kind === 'dormant' ? 'dormant (idle past the dormant window)'
352
- : status.kind === 'rate_limited' ? `cooling down (${Math.round(status.cooldownRemainingMs / 1000)}s left)`
353
- : 'opted out';
354
- outcomes.push({ ...base, reason });
355
- continue;
356
- }
357
- base.stalledForMs = status.stalledForMs;
358
- const tailLines = tailCache.get(session.sessionId) ?? tailFor(session);
359
- const candidate = {
360
- terminalId: session.sessionId,
361
- agentType: (session.kind === 'codex' ? 'codex' : 'claude'),
362
- tailLines,
363
- stalledForMs: status.stalledForMs,
364
- };
365
- if (rotateEnabled) {
366
- const sid = session.sessionId;
367
- const inflight = readRotateState(dir, sid);
368
- if (inflight && isInflightPhase(inflight.phase)) {
369
- const advanced = await advanceRotate(inflight, rotateDeps);
370
- advancedRotates.add(sid);
371
- outcomes.push({
372
- ...base, decision: 'rotate', rotatePhase: advanced.phase,
373
- reason: rotateOutcomeReason(advanced),
374
- });
375
- continue;
376
- }
377
- if (inflight && inflight.phase === 'failed' && (inflight.suppressUntilMs ?? 0) > nowMs) {
378
- outcomes.push({
379
- ...base, decision: 'skip', rotatePhase: 'failed',
380
- reason: `rotate suppressed until ${new Date(inflight.suppressUntilMs).toISOString()} (failed-rotate cooldown)`,
381
- });
382
- continue;
383
- }
384
- const verdict = classifyTailForRotate(tailLines, nowMs);
385
- if (verdict.kind === 'rate_limited') {
386
- if (policy === 'handsoff') {
387
- flags[sid] = {
388
- reason: 'handsoff: rate-limited, would rotate in place but policy is hands-off',
389
- host: session.host,
390
- atMs: nowMs,
391
- };
392
- outcomes.push({
393
- ...base, decision: 'skip',
394
- reason: 'handsoff: rate-limited — flagged, not rotated',
395
- });
396
- continue;
397
- }
398
- if (!opts.nudge) {
399
- outcomes.push({
400
- ...base, decision: 'rotate',
401
- reason: 'rate-limited — would rotate in place via `agents run auto` (dry — pass --nudge)',
402
- });
403
- continue;
404
- }
405
- let gate;
406
- try {
407
- gate = await rotateGate();
408
- }
409
- catch (err) {
410
- const msg = err instanceof Error ? err.message : String(err);
411
- logEvents.push({
412
- ts: nowMs, kind: 'error', terminalId: sid, agentType: candidate.agentType,
413
- message: `rotate gate failed: ${msg}`,
414
- });
415
- outcomes.push({
416
- ...base, decision: 'skip',
417
- reason: `rate-limited but the rotate health gate failed — skipped this tick: ${msg}`,
418
- });
419
- continue;
420
- }
421
- if (!gate.healthy) {
422
- const cooldownMs = gate.resetsAtMs !== undefined ? Math.max(60_000, gate.resetsAtMs - nowMs)
423
- : verdict.resetsAtMs !== undefined ? Math.max(60_000, verdict.resetsAtMs - nowMs)
424
- : DEFAULT_ROTATE_SKIP_COOLDOWN_MS;
425
- const suppressUntilMs = nowMs + cooldownMs;
426
- if (shouldLogRotateSkip(dir, sid, nowMs)) {
427
- recordRotateSkip(dir, sid, suppressUntilMs);
428
- logEvents.push({
429
- ts: nowMs, kind: 'rotate', terminalId: sid, agentType: candidate.agentType,
430
- message: `rotate skipped: no healthy harness — ${gate.detail}; suppressed until ${new Date(suppressUntilMs).toISOString()}`,
431
- reason: gate.detail,
432
- });
433
- }
434
- outcomes.push({
435
- ...base, decision: 'skip',
436
- reason: `rate-limited but no healthy account/harness to rotate into — terminal untouched (suppressed until ${new Date(suppressUntilMs).toISOString()})`,
437
- });
438
- continue;
439
- }
440
- const resolution = resolveInjectTargetForSession(session, { allowGhosttyFocus: opts.allowGhosttyFocus });
441
- if (!resolution.addressable) {
442
- flags[sid] = { reason: `rotate: ${resolution.reason}`, host: session.host, atMs: nowMs };
443
- outcomes.push({
444
- ...base, decision: 'skip', addressable: false,
445
- reason: resolution.hint
446
- ? `rate-limited but un-addressable — ${resolution.reason} — ${resolution.hint}`
447
- : `rate-limited but un-addressable — ${resolution.reason}`,
448
- });
449
- continue;
450
- }
451
- const newSessionId = newSessionIdFor();
452
- let state = {
453
- sessionId: sid,
454
- newSessionId,
455
- agent: session.kind,
456
- phase: 'exiting',
457
- target: resolution.target,
458
- host: session.provenance?.transport === 'ssh' ? session.provenance.host : undefined,
459
- cwd: session.cwd,
460
- machineHost: session.provenance?.host,
461
- startedAtMs: nowMs,
462
- updatedAtMs: nowMs,
463
- deadlineMs: nowMs + rotateReadinessMs,
464
- };
465
- writeRotateState(dir, state);
466
- advancedRotates.add(sid);
467
- let rotateFailed = null;
468
- for (const key of exitSequenceFor(session.kind)) {
469
- try {
470
- const r = await injectFn(state.target, key, { dryRun: opts.injectDryRun, enter: false });
471
- if (!r.ok) {
472
- rotateFailed = `exit sequence inject failed: ${r.error ?? 'unknown error'}`;
473
- break;
474
- }
475
- }
476
- catch (err) {
477
- rotateFailed = `exit sequence inject threw: ${err instanceof Error ? err.message : String(err)}`;
478
- break;
479
- }
480
- if (rotateKeyDelayMs > 0 && !opts.injectDryRun) {
481
- await new Promise((resolve) => setTimeout(resolve, rotateKeyDelayMs));
482
- }
483
- }
484
- if (!rotateFailed) {
485
- state = { ...state, phase: 'launching', updatedAtMs: nowMs };
486
- writeRotateState(dir, state);
487
- const launch = buildRotateLaunchCommand({ host: state.host, sessionId: newSessionId });
488
- try {
489
- const r = await injectFn(state.target, launch, { dryRun: opts.injectDryRun });
490
- if (!r.ok)
491
- rotateFailed = `launch inject failed: ${r.error ?? 'unknown error'}`;
492
- }
493
- catch (err) {
494
- rotateFailed = `launch inject threw: ${err instanceof Error ? err.message : String(err)}`;
495
- }
496
- }
497
- if (rotateFailed) {
498
- state = {
499
- ...state, phase: 'failed', error: rotateFailed, updatedAtMs: nowMs,
500
- suppressUntilMs: nowMs + DEFAULT_ROTATE_FAILED_COOLDOWN_MS,
501
- };
502
- writeRotateState(dir, state);
503
- flags[sid] = { reason: `rotate failed: ${rotateFailed}`, host: session.host, atMs: nowMs };
504
- logEvents.push({
505
- ts: nowMs, kind: 'rotate', terminalId: sid, agentType: candidate.agentType,
506
- message: `rotate failed: ${sid} — ${rotateFailed}`,
507
- });
508
- outcomes.push({
509
- ...base, decision: 'rotate', rotatePhase: 'failed', addressable: true, rail: resolution.rail,
510
- reason: `rotate failed: ${rotateFailed}`,
511
- });
512
- continue;
513
- }
514
- state = { ...state, phase: 'awaiting-tui', updatedAtMs: nowMs };
515
- writeRotateState(dir, state);
516
- logEvents.push({
517
- ts: nowMs, kind: 'rotate', terminalId: sid, agentType: candidate.agentType,
518
- message: `rotating ${sid} in place → agents run auto (new session ${newSessionId})`,
519
- });
520
- outcomes.push({
521
- ...base, decision: 'rotate', rotatePhase: 'awaiting-tui', addressable: true, rail: resolution.rail,
522
- reason: `rotating in place → agents run auto (new session ${newSessionId})`,
523
- });
524
- continue;
525
- }
526
- }
527
- const decision = decisionByTerminal.get(session.sessionId) ??
528
- { nudge: false, reason: 'not evaluated by the watchdog agent', needsHuman: false };
529
- const chosenText = decision.text ?? nudgeText;
530
- const summary = summarizeWatchdogTail(tailLines, candidate.agentType);
531
- logEvents.push({
532
- ts: nowMs,
533
- kind: 'decision',
534
- terminalId: session.sessionId,
535
- agentType: candidate.agentType,
536
- message: decision.reason,
537
- reason: decision.reason,
538
- stalledForMs: status.stalledForMs,
539
- tailLines,
540
- nudgeText: decision.nudge ? chosenText : undefined,
541
- lastUserMessage: summary.lastUserMessage,
542
- lastAssistantMessage: summary.lastAssistantMessage,
543
- });
544
- if (!decision.nudge) {
545
- if (decision.needsHuman) {
546
- const lastNudgeMs = ledger[session.sessionId ?? ''] ?? 0;
547
- const cooldownMs = thresholds.cooldownMs;
548
- const withinCooldown = nowMs - lastNudgeMs < cooldownMs;
549
- if (opts.nudge && session.sessionId && !withinCooldown) {
550
- const existingBlock = openBlockFor(session);
551
- if (existingBlock === null) {
552
- const resolution = resolveInjectTargetForSession(session, { allowGhosttyFocus: opts.allowGhosttyFocus });
553
- if (resolution.addressable) {
554
- const reminderText = 'You appear stuck. If you genuinely need Muqsit, file it: ' +
555
- 'agents feed post "<one-line ask>" --blocked --default "<safe default>". ' +
556
- 'Otherwise keep going.';
557
- try {
558
- await injectFn(resolution.target, reminderText, { dryRun: opts.injectDryRun });
559
- }
560
- catch {
561
- }
562
- ledgerUpdates[session.sessionId] = nowMs;
563
- }
564
- else {
565
- const mailboxId = mailboxIdForActiveSession(session) ?? session.sessionId;
566
- const machineHost = session.provenance?.host ?? 'unknown';
567
- const runtime = session.kind;
568
- try {
569
- const declaredBlock = buildDeclaredBlock({ sessionId: session.sessionId, mailboxId, host: machineHost, runtime, cwd: session.cwd }, {
570
- text: resolution.hint
571
- ? `Session genuinely needs Muqsit and is un-addressable — ${decision.reason}. Needs attention. ${resolution.hint}`
572
- : `Session genuinely needs Muqsit and is un-addressable — ${decision.reason}. Needs attention.`,
573
- });
574
- publishBlockFn(declaredBlock);
575
- ledgerUpdates[session.sessionId] = nowMs;
576
- }
577
- catch {
578
- }
579
- }
580
- }
581
- }
582
- }
583
- outcomes.push({ ...base, decision: 'skip', reason: decision.reason });
584
- continue;
585
- }
586
- const block = openBlockFor(session);
587
- const plan = planDelivery(session, chosenText, block, opts.allowGhosttyFocus);
588
- const rail = plan.via === 'inject' ? plan.rail : undefined;
589
- const addressable = plan.via === 'inject' ? true : undefined;
590
- if (plan.via === 'refuse') {
591
- flags[session.sessionId] = { reason: plan.reason, host: session.host, atMs: nowMs };
592
- outcomes.push({
593
- ...base, decision: 'skip', addressable: false,
594
- reason: plan.hint
595
- ? `nudge-worthy but un-addressable — ${plan.reason} — ${plan.hint}`
596
- : `nudge-worthy but un-addressable — ${plan.reason}`,
597
- nudgeText: chosenText,
598
- });
599
- continue;
600
- }
601
- if (policy === 'handsoff') {
602
- flags[session.sessionId] = {
603
- reason: `handsoff: would nudge via ${viaLabel(plan)} but policy is hands-off`,
604
- host: session.host,
605
- atMs: nowMs,
606
- };
607
- outcomes.push({
608
- ...base, decision: 'nudge', addressable, rail, via: plan.via, injected: false,
609
- reason: `handsoff: flagged, not delivered (would nudge via ${viaLabel(plan)})`,
610
- nudgeText: chosenText,
611
- });
612
- continue;
613
- }
614
- if (!opts.nudge) {
615
- outcomes.push({
616
- ...base, decision: 'nudge', addressable, rail, via: plan.via, injected: false,
617
- reason: `would nudge via ${viaLabel(plan)} (dry — pass --nudge)`,
618
- nudgeText: chosenText,
619
- });
620
- continue;
621
- }
622
- let delivered;
623
- if (plan.via === 'inject') {
624
- try {
625
- const r = await injectFn(plan.target, chosenText, { dryRun: opts.injectDryRun });
626
- delivered = { ok: r.ok, confirmed: r.confirmed, error: r.error };
627
- }
628
- catch (err) {
629
- delivered = { ok: false, confirmed: false, error: err instanceof Error ? err.message : String(err) };
630
- }
631
- }
632
- else if (plan.via === 'mailbox') {
633
- if (opts.injectDryRun) {
634
- delivered = { ok: true, confirmed: true };
635
- }
636
- else {
637
- try {
638
- deliverViaMailbox(plan.mailboxId, chosenText, block);
639
- delivered = { ok: true, confirmed: true };
640
- }
641
- catch (err) {
642
- delivered = { ok: false, confirmed: false, error: err instanceof Error ? err.message : String(err) };
643
- }
644
- }
645
- }
646
- else {
647
- delivered = opts.injectDryRun ? { ok: true, confirmed: true } : { ...(await deliverViaResume(session, chosenText)), confirmed: true };
648
- }
649
- if (delivered.ok && delivered.confirmed) {
650
- ledgerUpdates[session.sessionId] = nowMs;
651
- logEvents.push({
652
- ts: nowMs, kind: 'nudge', terminalId: session.sessionId, agentType: candidate.agentType,
653
- message: `nudged via ${viaLabel(plan)}`, reason: decision.reason, nudgeText: chosenText,
654
- });
655
- outcomes.push({
656
- ...base, decision: 'nudge', addressable, rail, via: plan.via, injected: true,
657
- reason: `nudged via ${viaLabel(plan)}`,
658
- nudgeText: chosenText,
659
- });
660
- }
661
- else if (delivered.ok && !delivered.confirmed) {
662
- ledgerUpdates[session.sessionId] = nowMs;
663
- logEvents.push({
664
- ts: nowMs, kind: 'undelivered', terminalId: session.sessionId, agentType: candidate.agentType,
665
- message: `dispatched via ${viaLabel(plan)} but UNCONFIRMED (needs swarm-ext ack)`,
666
- reason: decision.reason, nudgeText: chosenText,
667
- });
668
- outcomes.push({
669
- ...base, decision: 'skip', addressable, rail, via: plan.via, injected: false,
670
- reason: `nudge dispatched via ${viaLabel(plan)} but delivery is UNCONFIRMED (swarm-ext ack pending)`,
671
- nudgeText: chosenText,
672
- });
673
- }
674
- else {
675
- outcomes.push({
676
- ...base, decision: 'skip', addressable, rail, via: plan.via, injected: false,
677
- reason: `nudge via ${viaLabel(plan)} failed: ${delivered.error ?? 'unknown error'}`,
678
- nudgeText: chosenText,
679
- });
680
- }
681
- }
682
- for (const inflight of listInflightRotates(dir)) {
683
- if (advancedRotates.has(inflight.sessionId))
684
- continue;
685
- await advanceRotate(inflight, rotateDeps);
686
- }
687
- if (Object.keys(ledgerUpdates).length > 0) {
688
- const nudgesPath = path.join(dir, 'nudges.json');
689
- const ledgerLock = path.join(dir, '.ledger.lock');
690
- try {
691
- ensureLockTarget(ledgerLock);
692
- withFileLock(ledgerLock, () => {
693
- const current = readNudgeLedger(dir);
694
- for (const [sid, ts] of Object.entries(ledgerUpdates))
695
- current[sid] = ts;
696
- atomicWriteFileSync(nudgesPath, JSON.stringify(current, null, 2));
697
- });
698
- }
699
- catch {
700
- }
701
- }
702
- writeJsonFile(path.join(dir, 'flags.json'), flags);
703
- const counts = {
704
- total: outcomes.length,
705
- stalled: outcomes.filter((o) => o.stall === 'stalled').length,
706
- nudged: outcomes.filter((o) => o.injected).length,
707
- unaddressable: outcomes.filter((o) => o.addressable === false).length,
708
- skipped: outcomes.filter((o) => o.decision === 'skip').length,
709
- rotating: outcomes.filter((o) => o.decision === 'rotate').length,
710
- };
711
- const result = { atMs: nowMs, didNudge: opts.nudge === true, outcomes, counts, presence };
712
- writeJsonFile(path.join(dir, 'last-tick.json'), result);
713
- logEvents.push({
714
- ts: nowMs,
715
- kind: 'tick',
716
- message: `${counts.total} live · ${counts.stalled} stalled · ${counts.nudged} nudged · ${counts.unaddressable} un-addressable`,
717
- inspections: outcomes.map((outcome) => ({
718
- terminalId: outcome.sessionId,
719
- agentType: outcome.kind,
720
- message: outcome.decision,
721
- reason: outcome.reason,
722
- stalledForMs: outcome.stalledForMs,
723
- })),
724
- });
725
- appendWatchdogEvents(logEvents, { logPath: opts.logPath });
726
- return result;
727
- }