@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.
Files changed (84) hide show
  1. package/CHANGELOG.md +14 -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/session/active.d.ts +2 -1
  42. package/dist/lib/session/active.js +10 -6
  43. package/dist/lib/session/hook-sessions.d.ts +10 -0
  44. package/dist/lib/session/hook-sessions.js +22 -10
  45. package/dist/lib/session/inject-target.d.ts +1 -0
  46. package/dist/lib/session/inject-target.js +2 -1
  47. package/dist/lib/session/pid-registry.d.ts +1 -0
  48. package/dist/lib/session/remote/watch.d.ts +1 -0
  49. package/dist/lib/startup/command-registry.js +2 -1
  50. package/dist/lib/state.js +0 -1
  51. package/dist/lib/terminal/index.d.ts +1 -1
  52. package/dist/lib/terminal/index.js +1 -1
  53. package/dist/lib/terminal/inject.d.ts +0 -15
  54. package/dist/lib/terminal/inject.js +2 -16
  55. package/dist/lib/terminal/resolve.d.ts +2 -1
  56. package/dist/lib/terminal/resolve.js +13 -18
  57. package/dist/lib/types.d.ts +0 -3
  58. package/package.json +1 -1
  59. package/dist/commands/setup-watchdog.d.ts +0 -3
  60. package/dist/commands/setup-watchdog.js +0 -49
  61. package/dist/commands/watchdog.d.ts +0 -4
  62. package/dist/commands/watchdog.js +0 -361
  63. package/dist/lib/daemon/watchdog-service.d.ts +0 -10
  64. package/dist/lib/daemon/watchdog-service.js +0 -27
  65. package/dist/lib/session/presence.d.ts +0 -47
  66. package/dist/lib/session/presence.js +0 -100
  67. package/dist/lib/watchdog/history.d.ts +0 -20
  68. package/dist/lib/watchdog/history.js +0 -43
  69. package/dist/lib/watchdog/log.d.ts +0 -33
  70. package/dist/lib/watchdog/log.js +0 -117
  71. package/dist/lib/watchdog/read.d.ts +0 -8
  72. package/dist/lib/watchdog/read.js +0 -93
  73. package/dist/lib/watchdog/rotate.d.ts +0 -55
  74. package/dist/lib/watchdog/rotate.js +0 -220
  75. package/dist/lib/watchdog/runner.d.ts +0 -100
  76. package/dist/lib/watchdog/runner.js +0 -727
  77. package/dist/lib/watchdog/service.d.ts +0 -15
  78. package/dist/lib/watchdog/service.js +0 -36
  79. package/dist/lib/watchdog/watchdog-agent.d.ts +0 -8
  80. package/dist/lib/watchdog/watchdog-agent.js +0 -32
  81. package/dist/lib/watchdog/watchdog.d.ts +0 -43
  82. package/dist/lib/watchdog/watchdog.js +0 -116
  83. package/dist/lib/watchdog/watchdogTail.d.ts +0 -6
  84. package/dist/lib/watchdog/watchdogTail.js +0 -116
@@ -1,117 +0,0 @@
1
- import * as fs from 'fs';
2
- import * as path from 'path';
3
- import { withFileLock, atomicWriteFileSync, ensureLockTarget } from '../fs-atomic.js';
4
- import { getLogsDir } from '../state.js';
5
- export function watchdogLogPath() {
6
- return path.join(getLogsDir(), 'watchdog.log');
7
- }
8
- const WATCHDOG_EVENT_KINDS = new Set(['tick', 'decision', 'nudge', 'undelivered', 'rotate', 'error']);
9
- export function parseWatchdogEvents(text) {
10
- const events = [];
11
- for (const line of text.split('\n')) {
12
- if (!line.trim())
13
- continue;
14
- try {
15
- const value = JSON.parse(line);
16
- if (typeof value.ts !== 'number' ||
17
- !Number.isFinite(value.ts) ||
18
- typeof value.kind !== 'string' ||
19
- !WATCHDOG_EVENT_KINDS.has(value.kind) ||
20
- typeof value.message !== 'string')
21
- continue;
22
- const inspections = Array.isArray(value.inspections)
23
- ? value.inspections.flatMap((item) => {
24
- if (item === null || typeof item !== 'object')
25
- return [];
26
- const row = item;
27
- if (typeof row.agentType !== 'string' || typeof row.message !== 'string' || typeof row.reason !== 'string')
28
- return [];
29
- return [{
30
- terminalId: typeof row.terminalId === 'string' ? row.terminalId : undefined,
31
- agentType: row.agentType,
32
- message: row.message,
33
- reason: row.reason,
34
- stalledForMs: typeof row.stalledForMs === 'number' ? row.stalledForMs : undefined,
35
- }];
36
- })
37
- : undefined;
38
- events.push({
39
- ts: value.ts,
40
- kind: value.kind,
41
- message: value.message,
42
- terminalId: typeof value.terminalId === 'string' ? value.terminalId : undefined,
43
- agentType: typeof value.agentType === 'string' ? value.agentType : undefined,
44
- reason: typeof value.reason === 'string' ? value.reason : undefined,
45
- tailLines: Array.isArray(value.tailLines)
46
- ? value.tailLines.filter((item) => typeof item === 'string')
47
- : undefined,
48
- stalledForMs: typeof value.stalledForMs === 'number' ? value.stalledForMs : undefined,
49
- lastUserMessage: typeof value.lastUserMessage === 'string' ? value.lastUserMessage : undefined,
50
- lastAssistantMessage: typeof value.lastAssistantMessage === 'string' ? value.lastAssistantMessage : undefined,
51
- nudgeText: typeof value.nudgeText === 'string' ? value.nudgeText : undefined,
52
- inspections,
53
- });
54
- }
55
- catch {
56
- }
57
- }
58
- return events;
59
- }
60
- export function readWatchdogEvents(logPath = watchdogLogPath()) {
61
- if (!fs.existsSync(logPath))
62
- return [];
63
- return parseWatchdogEvents(fs.readFileSync(logPath, 'utf8'));
64
- }
65
- export function formatEvent(ev) {
66
- return JSON.stringify(ev);
67
- }
68
- const WATCHDOG_LOG_MAX_LINES = 5000;
69
- export const WATCHDOG_TAIL_MAX_CHARS = 4096;
70
- export function boundTailLines(lines, maxChars = WATCHDOG_TAIL_MAX_CHARS) {
71
- const kept = [];
72
- let remaining = maxChars;
73
- for (let i = lines.length - 1; i >= 0 && remaining > 0; i--) {
74
- const line = lines[i];
75
- if (line.length <= remaining) {
76
- kept.unshift(line);
77
- remaining -= line.length;
78
- }
79
- else {
80
- kept.unshift(line.slice(-remaining));
81
- remaining = 0;
82
- }
83
- }
84
- return kept;
85
- }
86
- export function trimToLast(text, maxLines) {
87
- const lines = text.split('\n').filter((l) => l.trim().length > 0);
88
- if (lines.length <= maxLines)
89
- return lines.join('\n') + (lines.length ? '\n' : '');
90
- return lines.slice(lines.length - maxLines).join('\n') + '\n';
91
- }
92
- export function appendWatchdogEvents(events, opts = {}) {
93
- if (events.length === 0)
94
- return;
95
- const logPath = opts.logPath ?? watchdogLogPath();
96
- const maxLines = opts.maxLines ?? WATCHDOG_LOG_MAX_LINES;
97
- const lockPath = path.join(path.dirname(logPath), '.watchdog.log.lock');
98
- try {
99
- ensureLockTarget(lockPath);
100
- withFileLock(lockPath, () => {
101
- let existing = '';
102
- try {
103
- existing = fs.readFileSync(logPath, 'utf8');
104
- }
105
- catch {
106
- }
107
- const boundedEvents = events.map((event) => event.tailLines === undefined
108
- ? event
109
- : { ...event, tailLines: boundTailLines(event.tailLines) });
110
- const appended = boundedEvents.map(formatEvent).join('\n') + '\n';
111
- const body = trimToLast(existing + appended, maxLines);
112
- atomicWriteFileSync(logPath, body);
113
- });
114
- }
115
- catch {
116
- }
117
- }
@@ -1,8 +0,0 @@
1
- export declare const WATCHDOG_TAIL_LINES = 20;
2
- export declare const WATCHDOG_STALL_MS = 300000;
3
- export declare const WATCHDOG_COOLDOWN_MS = 1200000;
4
- export declare const WATCHDOG_DORMANT_MS = 3600000;
5
- export declare function readTailLines(filePath: string, maxLines: number): string[];
6
- export declare function findSessionJsonlIn(dirs: string[], sessionId: string, ext?: string): string | undefined;
7
- export declare function resolveWatchdogSessionPath(sessionId: string, agent: string): string | undefined;
8
- export declare function readWatchdogTail(sessionId: string, agent: string, maxLines?: number): string[];
@@ -1,93 +0,0 @@
1
- import * as fs from 'fs';
2
- import * as path from 'path';
3
- import { getAgentSessionDirs } from '../session/discover.js';
4
- import { walkForFiles } from '../fs-walk.js';
5
- export const WATCHDOG_TAIL_LINES = 20;
6
- export const WATCHDOG_STALL_MS = 300_000;
7
- export const WATCHDOG_COOLDOWN_MS = 1_200_000;
8
- export const WATCHDOG_DORMANT_MS = 3_600_000;
9
- const CHUNK_SIZE = 64 * 1024;
10
- const UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
11
- const WATCHDOG_WALK_CAP = 100_000;
12
- const WATCHDOG_SESSION_LAYOUT = {
13
- claude: { subdir: 'projects', ext: '.jsonl' },
14
- codex: { subdir: 'sessions', ext: '.jsonl' },
15
- droid: { subdir: 'sessions', ext: '.jsonl' },
16
- };
17
- const WATCHDOG_SESSION_LAYOUT_DEFAULT = { subdir: 'projects', ext: '.jsonl' };
18
- export function readTailLines(filePath, maxLines) {
19
- let fd;
20
- try {
21
- fd = fs.openSync(filePath, 'r');
22
- }
23
- catch {
24
- return [];
25
- }
26
- try {
27
- const fileSize = fs.fstatSync(fd).size;
28
- if (fileSize === 0)
29
- return [];
30
- let position = fileSize;
31
- let buffer = '';
32
- let collected = [];
33
- while (position > 0 && collected.length <= maxLines) {
34
- const readSize = Math.min(CHUNK_SIZE, position);
35
- position -= readSize;
36
- const chunk = Buffer.alloc(readSize);
37
- fs.readSync(fd, chunk, 0, readSize, position);
38
- buffer = chunk.toString('utf-8') + buffer;
39
- collected = buffer.split(/\r?\n/).filter((l) => l.trim());
40
- }
41
- return collected.slice(-maxLines);
42
- }
43
- catch {
44
- return [];
45
- }
46
- finally {
47
- try {
48
- fs.closeSync(fd);
49
- }
50
- catch {
51
- }
52
- }
53
- }
54
- export function findSessionJsonlIn(dirs, sessionId, ext = '.jsonl') {
55
- if (!sessionId)
56
- return undefined;
57
- const matches = (name) => {
58
- if (!name.endsWith(ext))
59
- return false;
60
- const stem = name.slice(0, -ext.length);
61
- if (stem === sessionId)
62
- return true;
63
- return name.includes(sessionId) || (UUID_RE.test(sessionId) && stem.includes(sessionId));
64
- };
65
- let best;
66
- for (const dir of dirs) {
67
- for (const file of walkForFiles(dir, ext, WATCHDOG_WALK_CAP)) {
68
- if (!matches(path.basename(file)))
69
- continue;
70
- let mtime;
71
- try {
72
- mtime = fs.statSync(file).mtimeMs;
73
- }
74
- catch {
75
- continue;
76
- }
77
- if (!best || mtime > best.mtime)
78
- best = { file, mtime };
79
- }
80
- }
81
- return best?.file;
82
- }
83
- export function resolveWatchdogSessionPath(sessionId, agent) {
84
- const layout = WATCHDOG_SESSION_LAYOUT[agent] ?? WATCHDOG_SESSION_LAYOUT_DEFAULT;
85
- const dirs = getAgentSessionDirs(agent, layout.subdir);
86
- return findSessionJsonlIn(dirs, sessionId, layout.ext);
87
- }
88
- export function readWatchdogTail(sessionId, agent, maxLines = WATCHDOG_TAIL_LINES) {
89
- const filePath = resolveWatchdogSessionPath(sessionId, agent);
90
- if (!filePath)
91
- return [];
92
- return readTailLines(filePath, maxLines);
93
- }
@@ -1,55 +0,0 @@
1
- import type { InjectTarget } from '../terminal/index.js';
2
- import type { ActiveSession } from '../session/active.js';
3
- type RotateTailVerdict = {
4
- kind: 'none';
5
- } | {
6
- kind: 'rate_limited';
7
- resetsAtMs?: number;
8
- };
9
- export declare function classifyTailForRotate(tailLines: string[], nowMs: number): RotateTailVerdict;
10
- export declare function parseRotateResetMs(text: string, nowMs: number): number | undefined;
11
- export declare const ROTATE_EXIT_SEQUENCES: Record<string, string[]>;
12
- export declare const DEFAULT_ROTATE_EXIT_SEQUENCE: string[];
13
- export declare function exitSequenceFor(agent: string): string[];
14
- export declare function buildRotateLaunchCommand(opts: {
15
- host?: string;
16
- sessionId: string;
17
- }): string;
18
- export declare function buildRotateReplayText(oldSessionId: string): string;
19
- export type RotatePhase = 'exiting' | 'launching' | 'awaiting-tui' | 'replaying' | 'done' | 'failed';
20
- export interface RotateState {
21
- sessionId: string;
22
- newSessionId: string;
23
- agent: string;
24
- phase: RotatePhase;
25
- target: InjectTarget;
26
- host?: string;
27
- cwd?: string;
28
- machineHost?: string;
29
- startedAtMs: number;
30
- updatedAtMs: number;
31
- deadlineMs: number;
32
- error?: string;
33
- suppressUntilMs?: number;
34
- }
35
- export declare const DEFAULT_ROTATE_READINESS_MS = 60000;
36
- export declare const DEFAULT_ROTATE_SKIP_COOLDOWN_MS: number;
37
- export declare const DEFAULT_ROTATE_FAILED_COOLDOWN_MS: number;
38
- export declare function readRotateState(dir: string, sessionId: string): RotateState | null;
39
- export declare function writeRotateState(dir: string, state: RotateState): void;
40
- export declare function isInflightPhase(phase: RotatePhase): boolean;
41
- export declare function listRotateStates(dir: string): RotateState[];
42
- export declare function listInflightRotates(dir: string): RotateState[];
43
- export declare function shouldLogRotateSkip(dir: string, sessionId: string, nowMs: number): boolean;
44
- export declare function recordRotateSkip(dir: string, sessionId: string, suppressUntilMs: number): void;
45
- export declare function isWatchdogRotateEnabled(): boolean;
46
- export declare function setWatchdogRotateEnabled(on: boolean): void;
47
- export interface RotateGateResult {
48
- healthy: boolean;
49
- resetsAtMs?: number;
50
- detail: string;
51
- }
52
- export declare function defaultRotateGate(): Promise<RotateGateResult>;
53
- export declare function isCorrelatedRelaunch(state: RotateState, s: ActiveSession): boolean;
54
- export declare function defaultTuiLiveFor(state: RotateState, sessions: ActiveSession[]): boolean;
55
- export {};
@@ -1,220 +0,0 @@
1
- import * as fs from 'fs';
2
- import * as path from 'path';
3
- import { readMeta, writeMeta } from '../state.js';
4
- import { collectHarnessCandidates, classifyHarnessCandidates, pickHarnessWeighted, earliestResetAcross, formatNoHealthyHarnessError, } from '../accounting/rotate.js';
5
- import { resolveWatchdogSessionPath } from './read.js';
6
- const ROTATE_LIMIT_PATTERNS = [
7
- /you'?ve hit your [\w-]*\s?limit/i,
8
- /hit your (weekly|daily|usage|session) limit/i,
9
- /usage limit (has been )?(reached|exceeded)/i,
10
- /rate limit (reached|exceeded)/i,
11
- /out of (credits|extra usage)/i,
12
- ];
13
- export function classifyTailForRotate(tailLines, nowMs) {
14
- if (tailLines.length === 0)
15
- return { kind: 'none' };
16
- const tail = tailLines.join('\n');
17
- if (ROTATE_LIMIT_PATTERNS.some((p) => p.test(tail))) {
18
- return { kind: 'rate_limited', resetsAtMs: parseRotateResetMs(tail, nowMs) };
19
- }
20
- return { kind: 'none' };
21
- }
22
- export function parseRotateResetMs(text, nowMs) {
23
- const iso = /resets\s+(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z)\b/i.exec(text);
24
- if (iso) {
25
- const parsedIso = Date.parse(iso[1]);
26
- return Number.isNaN(parsedIso) || parsedIso <= nowMs ? undefined : parsedIso;
27
- }
28
- const m = /resets\s+([^.;!\n]+)/i.exec(text);
29
- if (!m)
30
- return undefined;
31
- const segment = m[1].trim();
32
- const timeZone = /\(([A-Za-z_]+\/[A-Za-z_]+)\)/.exec(segment)?.[1];
33
- const timePart = segment.replace(/\([A-Za-z_]+\/[A-Za-z_]+\)/, '').trim();
34
- const parsed = Date.parse(timePart);
35
- if (!Number.isNaN(parsed)) {
36
- return parsed > nowMs ? parsed : undefined;
37
- }
38
- const t = /(\d{1,2})(?::(\d{2}))?\s*(am|pm)/i.exec(timePart);
39
- if (!t)
40
- return undefined;
41
- let hour = parseInt(t[1], 10) % 12;
42
- if (t[3].toLowerCase() === 'pm')
43
- hour += 12;
44
- const minute = t[2] ? parseInt(t[2], 10) : 0;
45
- return nextOccurrenceMs(hour, minute, timeZone, nowMs);
46
- }
47
- function nextOccurrenceMs(hour, minute, timeZone, nowMs) {
48
- try {
49
- if (!timeZone) {
50
- const d = new Date(nowMs);
51
- d.setHours(hour, minute, 0, 0);
52
- if (d.getTime() <= nowMs)
53
- d.setDate(d.getDate() + 1);
54
- return d.getTime();
55
- }
56
- const parts = new Intl.DateTimeFormat('en-US', {
57
- timeZone,
58
- hour12: false,
59
- year: 'numeric',
60
- month: '2-digit',
61
- day: '2-digit',
62
- hour: '2-digit',
63
- minute: '2-digit',
64
- }).formatToParts(new Date(nowMs));
65
- const get = (type) => parseInt(parts.find((p) => p.type === type)?.value ?? '0', 10);
66
- const year = get('year');
67
- const month = get('month') - 1;
68
- const day = get('day');
69
- const wallNowMs = Date.UTC(year, month, day, get('hour') % 24, get('minute'));
70
- const offsetMs = wallNowMs - nowMs;
71
- let candidate = Date.UTC(year, month, day, hour, minute) - offsetMs;
72
- if (candidate <= nowMs)
73
- candidate += 24 * 60 * 60 * 1000;
74
- return candidate;
75
- }
76
- catch {
77
- return undefined;
78
- }
79
- }
80
- export const ROTATE_EXIT_SEQUENCES = {
81
- claude: ['\x1b', '\x03', '\x03'],
82
- codex: ['\x03', '\x03'],
83
- cursor: ['\x03', '\x03'],
84
- opencode: ['\x03', '\x03'],
85
- };
86
- export const DEFAULT_ROTATE_EXIT_SEQUENCE = ['\x03', '\x03'];
87
- export function exitSequenceFor(agent) {
88
- return ROTATE_EXIT_SEQUENCES[agent] ?? DEFAULT_ROTATE_EXIT_SEQUENCE;
89
- }
90
- export function buildRotateLaunchCommand(opts) {
91
- let cmd = 'agents run auto --interactive';
92
- if (opts.host) {
93
- cmd += ` --device ${shellQuoteHost(opts.host)}`;
94
- }
95
- cmd += ` --session-id ${opts.sessionId}`;
96
- return cmd;
97
- }
98
- function shellQuoteHost(value) {
99
- return `'${value.replace(/'/g, `'\\''`)}'`;
100
- }
101
- export function buildRotateReplayText(oldSessionId) {
102
- return (`Resume previous work by loading session ${oldSessionId}. ` +
103
- `Run \`sessions ${oldSessionId}\` to load the transcript, assess current state, then continue working.`);
104
- }
105
- export const DEFAULT_ROTATE_READINESS_MS = 60_000;
106
- export const DEFAULT_ROTATE_SKIP_COOLDOWN_MS = 30 * 60_000;
107
- export const DEFAULT_ROTATE_FAILED_COOLDOWN_MS = 15 * 60_000;
108
- function rotateDir(dir) {
109
- return path.join(dir, 'rotate');
110
- }
111
- function rotateStatePath(dir, sessionId) {
112
- return path.join(rotateDir(dir), `${sessionId}.json`);
113
- }
114
- export function readRotateState(dir, sessionId) {
115
- try {
116
- const parsed = JSON.parse(fs.readFileSync(rotateStatePath(dir, sessionId), 'utf8'));
117
- return parsed && typeof parsed.sessionId === 'string' && typeof parsed.phase === 'string' ? parsed : null;
118
- }
119
- catch {
120
- return null;
121
- }
122
- }
123
- export function writeRotateState(dir, state) {
124
- try {
125
- fs.mkdirSync(rotateDir(dir), { recursive: true });
126
- fs.writeFileSync(rotateStatePath(dir, state.sessionId), JSON.stringify(state, null, 2));
127
- }
128
- catch {
129
- }
130
- }
131
- export function isInflightPhase(phase) {
132
- return phase !== 'done' && phase !== 'failed';
133
- }
134
- export function listRotateStates(dir) {
135
- let files;
136
- try {
137
- files = fs.readdirSync(rotateDir(dir)).filter((f) => f.endsWith('.json'));
138
- }
139
- catch {
140
- return [];
141
- }
142
- const out = [];
143
- for (const f of files) {
144
- const s = readRotateState(dir, f.slice(0, -'.json'.length));
145
- if (s)
146
- out.push(s);
147
- }
148
- return out;
149
- }
150
- export function listInflightRotates(dir) {
151
- return listRotateStates(dir).filter((s) => isInflightPhase(s.phase));
152
- }
153
- function readRotateSkipLedger(dir) {
154
- try {
155
- return JSON.parse(fs.readFileSync(path.join(dir, 'rotate-skips.json'), 'utf8'));
156
- }
157
- catch {
158
- return {};
159
- }
160
- }
161
- export function shouldLogRotateSkip(dir, sessionId, nowMs) {
162
- return (readRotateSkipLedger(dir)[sessionId] ?? 0) <= nowMs;
163
- }
164
- export function recordRotateSkip(dir, sessionId, suppressUntilMs) {
165
- try {
166
- const ledger = readRotateSkipLedger(dir);
167
- ledger[sessionId] = suppressUntilMs;
168
- fs.writeFileSync(path.join(dir, 'rotate-skips.json'), JSON.stringify(ledger, null, 2));
169
- }
170
- catch {
171
- }
172
- }
173
- export function isWatchdogRotateEnabled() {
174
- return readMeta().watchdog?.rotate !== 'off';
175
- }
176
- export function setWatchdogRotateEnabled(on) {
177
- const meta = readMeta();
178
- meta.watchdog = { ...(meta.watchdog ?? {}), rotate: on ? 'on' : 'off' };
179
- writeMeta(meta);
180
- }
181
- export async function defaultRotateGate() {
182
- const byHarness = await collectHarnessCandidates();
183
- const pick = pickHarnessWeighted(byHarness);
184
- if (pick) {
185
- return { healthy: true, detail: `picked ${pick.picked.agent}` };
186
- }
187
- const all = [...byHarness.values()].flat();
188
- const reset = earliestResetAcross(all);
189
- return {
190
- healthy: false,
191
- resetsAtMs: reset?.getTime(),
192
- detail: formatNoHealthyHarnessError(classifyHarnessCandidates(byHarness)),
193
- };
194
- }
195
- const ROTATE_TRANSCRIPT_AGENTS = ['claude', 'codex', 'droid'];
196
- function defaultRotateTranscriptLive(newSessionId) {
197
- return ROTATE_TRANSCRIPT_AGENTS.some((agent) => resolveWatchdogSessionPath(newSessionId, agent) !== undefined);
198
- }
199
- function normalizeCwd(cwd) {
200
- if (!cwd)
201
- return undefined;
202
- const n = cwd.replace(/\/+$/, '');
203
- return n === '' ? '/' : n;
204
- }
205
- export function isCorrelatedRelaunch(state, s) {
206
- if (!s.sessionId || s.sessionId === state.sessionId)
207
- return false;
208
- if ((s.startedAtMs ?? 0) < state.startedAtMs)
209
- return false;
210
- const cwd = normalizeCwd(state.cwd);
211
- const host = state.machineHost;
212
- if (!cwd || !host)
213
- return false;
214
- return normalizeCwd(s.cwd) === cwd && s.provenance?.host === host;
215
- }
216
- export function defaultTuiLiveFor(state, sessions) {
217
- if (defaultRotateTranscriptLive(state.newSessionId))
218
- return true;
219
- return sessions.some((s) => isCorrelatedRelaunch(state, s));
220
- }
@@ -1,100 +0,0 @@
1
- import type { ActiveSession } from '../session/active.js';
2
- import { type PresenceTransition } from '../session/presence.js';
3
- import { type InjectRail, type InjectResult, type InjectTarget } from '../terminal/index.js';
4
- import { type StallStatus, type WatchdogCandidate } from './watchdog.js';
5
- import { type WatchdogAgentDecider } from './watchdog-agent.js';
6
- import { type OpenBlock } from '../feed/feed.js';
7
- import { type RotateGateResult, type RotatePhase, type RotateState } from './rotate.js';
8
- export type WatchdogPolicy = 'off' | 'keep' | 'handsoff';
9
- export interface WatchdogThresholds {
10
- stallMs: number;
11
- cooldownMs: number;
12
- dormantMs: number;
13
- }
14
- export declare const DEFAULT_THRESHOLDS: WatchdogThresholds;
15
- export interface WatchdogTickOptions {
16
- nudge?: boolean;
17
- nudgeText?: string;
18
- smartAgent?: string;
19
- thresholds?: Partial<WatchdogThresholds>;
20
- allowGhosttyFocus?: boolean;
21
- injectDryRun?: boolean;
22
- sessions?: ActiveSession[];
23
- nowMs?: number;
24
- stateDir?: string;
25
- lastActivityFor?: (s: ActiveSession) => number | undefined;
26
- tailFor?: (s: ActiveSession) => string[];
27
- policyFor?: (s: ActiveSession) => WatchdogPolicy;
28
- smartDecider?: SmartDecider;
29
- agentDecider?: WatchdogAgentDecider;
30
- openBlockFor?: (s: ActiveSession) => OpenBlock | null;
31
- injectFn?: (target: InjectTarget, text: string, opts: {
32
- dryRun?: boolean;
33
- enter?: boolean;
34
- }) => Promise<InjectResult>;
35
- publishBlockFn?: (block: OpenBlock) => void;
36
- logPath?: string;
37
- rotate?: boolean;
38
- rotateReadinessMs?: number;
39
- rotateGate?: () => Promise<RotateGateResult>;
40
- newSessionIdFor?: () => string;
41
- tuiLiveFor?: (state: RotateState, sessions: ActiveSession[]) => boolean;
42
- rotateKeyDelayMs?: number;
43
- }
44
- export type SmartDecider = (session: ActiveSession, candidate: WatchdogCandidate) => Promise<NudgeDecision>;
45
- export interface SessionOutcome {
46
- sessionId?: string;
47
- kind: string;
48
- host?: string;
49
- cwd?: string;
50
- project?: string | null;
51
- label?: string;
52
- name?: string;
53
- generatedTitle?: string;
54
- topic?: string;
55
- preview?: string;
56
- activity?: ActiveSession['activity'];
57
- status?: ActiveSession['status'];
58
- startedAtMs?: number;
59
- lastActivityMs?: number;
60
- machine?: string;
61
- owner?: string;
62
- stall: StallStatus['kind'];
63
- stalledForMs?: number;
64
- policy: WatchdogPolicy;
65
- decision: 'nudge' | 'skip' | 'rotate';
66
- reason: string;
67
- rotatePhase?: RotatePhase;
68
- rail?: InjectRail;
69
- via?: NudgeVia;
70
- addressable?: boolean;
71
- injected?: boolean;
72
- nudgeText?: string;
73
- }
74
- export type NudgeVia = 'inject' | 'mailbox' | 'resume';
75
- export interface WatchdogTickResult {
76
- atMs: number;
77
- didNudge: boolean;
78
- outcomes: SessionOutcome[];
79
- counts: {
80
- total: number;
81
- stalled: number;
82
- nudged: number;
83
- unaddressable: number;
84
- skipped: number;
85
- rotating: number;
86
- };
87
- presence: {
88
- connected: number;
89
- disconnected: number;
90
- transitions: PresenceTransition[];
91
- };
92
- }
93
- export declare function writePolicySentinel(dir: string, sessionId: string, policy: WatchdogPolicy): void;
94
- export interface NudgeDecision {
95
- nudge: boolean;
96
- reason: string;
97
- text?: string;
98
- needsHuman?: boolean;
99
- }
100
- export declare function runWatchdogTick(opts?: WatchdogTickOptions): Promise<WatchdogTickResult>;