@phnx-labs/agents-cli 1.23.0 → 1.23.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/README.md +2 -0
- package/dist/commands/cloud-transcripts.js +1 -2
- package/dist/commands/daemon.js +70 -11
- package/dist/commands/exec.js +1 -1
- package/dist/commands/feed.js +1 -2
- package/dist/commands/focus.js +4 -1
- package/dist/commands/go.js +3 -2
- package/dist/commands/logs.js +1 -1
- package/dist/commands/menubar.js +28 -3
- package/dist/commands/ps-roster.d.ts +0 -11
- package/dist/commands/ps-roster.js +3 -116
- package/dist/commands/ps.d.ts +10 -0
- package/dist/commands/ps.js +182 -1
- package/dist/commands/resume.js +1 -1
- package/dist/commands/sessions-browser.d.ts +0 -1
- package/dist/commands/sessions-browser.js +6 -23
- package/dist/commands/sessions-export.js +1 -1
- package/dist/commands/sessions-migrate.js +1 -1
- package/dist/commands/sessions-picker.d.ts +6 -32
- package/dist/commands/sessions-picker.js +81 -8
- package/dist/commands/sessions-render.js +1 -1
- package/dist/commands/sessions-resume.js +2 -2
- package/dist/commands/sessions-share.js +1 -1
- package/dist/commands/sessions-trace.js +1 -1
- package/dist/commands/sessions.d.ts +2 -165
- package/dist/commands/sessions.js +16 -1216
- package/dist/lib/daemon/account-state-daemon-service.d.ts +2 -2
- package/dist/lib/daemon/account-state-daemon-service.js +2 -2
- package/dist/lib/daemon/attention-notify-service.js +8 -4
- package/dist/lib/daemon/daemon.d.ts +5 -1
- package/dist/lib/daemon/daemon.js +53 -6
- package/dist/lib/daemon/diagnostics.d.ts +70 -0
- package/dist/lib/daemon/diagnostics.js +185 -0
- package/dist/lib/daemon/service.d.ts +1 -1
- package/dist/lib/daemon/session-state-service.d.ts +1 -1
- package/dist/lib/daemon/session-state-service.js +2 -2
- package/dist/lib/daemon/supervisor.d.ts +8 -0
- package/dist/lib/daemon/supervisor.js +47 -6
- package/dist/lib/daemon-services.d.ts +3 -0
- package/dist/lib/daemon-services.js +36 -0
- package/dist/lib/daemon-ticks.d.ts +3 -1
- package/dist/lib/daemon-ticks.js +18 -12
- package/dist/lib/feed/tool-activity.js +10 -3
- package/dist/lib/feed/watch.js +8 -5
- package/dist/lib/helper-versions.js +1 -1
- package/dist/lib/menubar/install-menubar.d.ts +18 -0
- package/dist/lib/menubar/install-menubar.js +59 -1
- package/dist/lib/session/active.js +18 -14
- package/dist/lib/session/pid-registry.js +9 -6
- package/dist/lib/session/presentation.d.ts +107 -1
- package/dist/lib/session/presentation.js +543 -4
- package/dist/lib/session/remote/remote-list.d.ts +3 -0
- package/dist/lib/session/remote/remote-list.js +13 -0
- package/dist/lib/session/resume-command.d.ts +9 -0
- package/dist/lib/session/resume-command.js +107 -0
- package/dist/lib/session/selection.d.ts +102 -0
- package/dist/lib/session/selection.js +443 -0
- package/package.json +1 -1
|
@@ -19,10 +19,10 @@ export declare class AccountUsageService extends BasePeriodicService {
|
|
|
19
19
|
readonly intervalMs = 60000;
|
|
20
20
|
readonly deadlineMs: number;
|
|
21
21
|
private readonly refresh;
|
|
22
|
-
constructor(refresh?: (signal: AbortSignal) => Promise<void>);
|
|
22
|
+
constructor(refresh?: (signal: AbortSignal, log: DaemonContext['log']) => Promise<void>);
|
|
23
23
|
protected onStart(): Promise<void>;
|
|
24
24
|
protected onStop(): Promise<void>;
|
|
25
|
-
protected onTick(
|
|
25
|
+
protected onTick(ctx: DaemonContext, signal: AbortSignal): Promise<void>;
|
|
26
26
|
}
|
|
27
27
|
export declare class AccountAuthService extends BasePeriodicService {
|
|
28
28
|
readonly id: DaemonServiceId;
|
|
@@ -36,9 +36,9 @@ export class AccountUsageService extends BasePeriodicService {
|
|
|
36
36
|
}
|
|
37
37
|
async onStart() { }
|
|
38
38
|
async onStop() { }
|
|
39
|
-
async onTick(
|
|
39
|
+
async onTick(ctx, signal) {
|
|
40
40
|
await Promise.race([
|
|
41
|
-
this.refresh(signal),
|
|
41
|
+
this.refresh(signal, ctx.log),
|
|
42
42
|
abortRejection(signal, 'usage refresh aborted at deadline'),
|
|
43
43
|
]);
|
|
44
44
|
}
|
|
@@ -33,6 +33,7 @@ import { blockIdForSession, readBlock, readResolution } from '../feed/feed.js';
|
|
|
33
33
|
import { reconcileAttention, harnessOf } from '../feed/attention.js';
|
|
34
34
|
import { notifyDesktop } from '../menubar/notify-desktop.js';
|
|
35
35
|
import { BasePeriodicService } from './service.js';
|
|
36
|
+
import { span, spanSync } from './diagnostics.js';
|
|
36
37
|
const ATTENTION_NOTIFY_TICK_MS = 5_000;
|
|
37
38
|
const ATTENTION_NOTIFY_DEADLINE_MS = 10_000;
|
|
38
39
|
const LEDGER_RETENTION_MS = 14 * 24 * 60 * 60 * 1000;
|
|
@@ -101,19 +102,20 @@ export class AttentionNotifyService extends BasePeriodicService {
|
|
|
101
102
|
async onStop() {
|
|
102
103
|
}
|
|
103
104
|
async onTick(ctx) {
|
|
104
|
-
const sessions = await this.getSessions();
|
|
105
|
+
const sessions = await span('attention.sessions', () => this.getSessions(), () => ({}));
|
|
105
106
|
const host = machineId();
|
|
107
|
+
let posted = 0;
|
|
106
108
|
for (const session of sessions) {
|
|
107
109
|
if (!session.sessionId)
|
|
108
110
|
continue;
|
|
109
111
|
const projected = { ...session, host };
|
|
110
112
|
const blockId = blockIdForSession(session.sessionId);
|
|
111
|
-
const item = reconcileAttention({
|
|
113
|
+
const item = spanSync('attention.reconcile', () => reconcileAttention({
|
|
112
114
|
block: readBlock(blockId, this.feedRoot),
|
|
113
115
|
session: projected,
|
|
114
116
|
resolution: readResolution(blockId, this.feedRoot),
|
|
115
117
|
nowMs: this.now(),
|
|
116
|
-
});
|
|
118
|
+
}));
|
|
117
119
|
if (!item || !BANNER_KINDS[item.kind])
|
|
118
120
|
continue;
|
|
119
121
|
if (await this.hasNotified(item.key))
|
|
@@ -123,9 +125,11 @@ export class AttentionNotifyService extends BasePeriodicService {
|
|
|
123
125
|
continue;
|
|
124
126
|
this.notify(notification);
|
|
125
127
|
await this.markNotified(item.key);
|
|
126
|
-
|
|
128
|
+
posted += 1;
|
|
129
|
+
ctx.log('INFO', `attention-notify: posted ${item.kind} banner for ${item.key}`, { event: 'attention.posted', kind: item.kind, key: item.key });
|
|
127
130
|
}
|
|
128
131
|
await this.pruneLedger();
|
|
132
|
+
ctx.log('DEBUG', `attention-notify: ${sessions.length} session(s) reconciled, ${posted} banner(s) posted`, { event: 'attention.tick', sessions: sessions.length, posted });
|
|
129
133
|
}
|
|
130
134
|
ledgerPath(key) {
|
|
131
135
|
return path.join(this.ledgerDir, encodeURIComponent(key));
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { isolatedHomeSuffix } from '../service-manifest.js';
|
|
2
2
|
import { getAgentsBinPath } from '../cli-entry.js';
|
|
3
3
|
import type { ServiceHealth } from './service.js';
|
|
4
|
+
import { type LogFields, type LogLevel } from './diagnostics.js';
|
|
4
5
|
export declare function getServiceSupervisorHealth(): Record<string, ServiceHealth> | null;
|
|
5
6
|
export declare function productionDaemonServiceNames(): {
|
|
6
7
|
systemdUnit: string;
|
|
@@ -33,7 +34,10 @@ export declare function reapStrayDaemons(keepPid?: number): {
|
|
|
33
34
|
details: string[];
|
|
34
35
|
};
|
|
35
36
|
export declare function isLiveDaemon(pid: number): boolean;
|
|
36
|
-
export declare function
|
|
37
|
+
export declare function setDaemonLogLevel(level: LogLevel): void;
|
|
38
|
+
export declare function getDaemonLogLevel(): LogLevel;
|
|
39
|
+
export declare function applyConfiguredLogLevel(): void;
|
|
40
|
+
export declare function log(level: string, message: string, fields?: LogFields): void;
|
|
37
41
|
export declare function guardSignalHandler(handler: () => void, onError: (err: unknown) => void): () => void;
|
|
38
42
|
export declare function anchorDaemonCwd(): string | null;
|
|
39
43
|
export declare function warnEphemeralDaemonRoot(resolveBin?: () => string): string | null;
|
|
@@ -22,8 +22,9 @@ import { isSchedulerEnabled, assertSchedulerEnabled, isDaemonEnabled } from '../
|
|
|
22
22
|
import { recordSubsystemOk, recordSubsystemError, recordSubsystemErrorReason, readSubsystemHealth, readRecentDaemonRestarts, SUBSYSTEM_DAEMON_START } from '../daemon-health.js';
|
|
23
23
|
import { ServiceSupervisor } from './supervisor.js';
|
|
24
24
|
import { emit, emitAsync, emitRoutineEnd } from '../feed/events.js';
|
|
25
|
-
import { readDaemonServicesConfig, drainDaemonServiceRestartQueue } from '../daemon-services.js';
|
|
25
|
+
import { readDaemonServicesConfig, readDaemonLogLevel, drainDaemonServiceRestartQueue } from '../daemon-services.js';
|
|
26
26
|
import { sleepSync } from '../fs-atomic.js';
|
|
27
|
+
import { DaemonVitals, installSpanLog, levelEnabled, topSpansSinceReport } from './diagnostics.js';
|
|
27
28
|
let activeServiceSupervisor = null;
|
|
28
29
|
export function getServiceSupervisorHealth() {
|
|
29
30
|
return activeServiceSupervisor?.health() ?? null;
|
|
@@ -428,17 +429,52 @@ function rotateLogsIfNeeded(logPath) {
|
|
|
428
429
|
}
|
|
429
430
|
catch { }
|
|
430
431
|
}
|
|
431
|
-
|
|
432
|
+
let logThreshold = 'INFO';
|
|
433
|
+
export function setDaemonLogLevel(level) {
|
|
434
|
+
logThreshold = level;
|
|
435
|
+
}
|
|
436
|
+
export function getDaemonLogLevel() {
|
|
437
|
+
return logThreshold;
|
|
438
|
+
}
|
|
439
|
+
function redactFields(value) {
|
|
440
|
+
if (typeof value === 'string')
|
|
441
|
+
return redactSecrets(value);
|
|
442
|
+
if (Array.isArray(value))
|
|
443
|
+
return value.map(redactFields);
|
|
444
|
+
if (value && typeof value === 'object') {
|
|
445
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, redactFields(v)]));
|
|
446
|
+
}
|
|
447
|
+
return value;
|
|
448
|
+
}
|
|
449
|
+
export function applyConfiguredLogLevel() {
|
|
450
|
+
const before = logThreshold;
|
|
451
|
+
try {
|
|
452
|
+
logThreshold = readDaemonLogLevel();
|
|
453
|
+
}
|
|
454
|
+
catch (err) {
|
|
455
|
+
log('WARN', `daemon log level unchanged (${before.toLowerCase()}): ${err.message}`);
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
if (logThreshold !== before)
|
|
459
|
+
log('INFO', `daemon log level ${before.toLowerCase()} -> ${logThreshold.toLowerCase()}`, { event: 'log.level', from: before, to: logThreshold });
|
|
460
|
+
}
|
|
461
|
+
export function log(level, message, fields) {
|
|
462
|
+
if (!levelEnabled(level, logThreshold))
|
|
463
|
+
return;
|
|
432
464
|
const logPath = getDaemonLogPath();
|
|
433
465
|
rotateLogsIfNeeded(logPath);
|
|
434
|
-
const
|
|
466
|
+
const lvl = level.toUpperCase();
|
|
467
|
+
const entry = { ts: new Date().toISOString(), level: lvl, message: redactSecrets(message) };
|
|
468
|
+
if (fields && Object.keys(fields).length > 0)
|
|
469
|
+
entry.data = redactFields(fields);
|
|
435
470
|
fs.appendFileSync(logPath, JSON.stringify(entry) + '\n', 'utf-8');
|
|
436
471
|
try {
|
|
437
472
|
fs.chmodSync(logPath, 0o600);
|
|
438
473
|
}
|
|
439
474
|
catch { }
|
|
475
|
+
if (lvl === 'DEBUG')
|
|
476
|
+
return;
|
|
440
477
|
try {
|
|
441
|
-
const lvl = level.toUpperCase();
|
|
442
478
|
const event = lvl === 'ERROR' || lvl === 'FATAL' ? 'daemon.error'
|
|
443
479
|
: lvl === 'START' || /starting|started/i.test(message) ? 'daemon.start'
|
|
444
480
|
: lvl === 'STOP' || /stopping|stopped|shutting down/i.test(message) ? 'daemon.stop'
|
|
@@ -553,7 +589,10 @@ export async function runDaemon() {
|
|
|
553
589
|
const lifetimePath = path.join(getDaemonDir(), LIFETIME_FILE);
|
|
554
590
|
const lifetimeToken = `${process.pid}:${Date.now()}`;
|
|
555
591
|
fs.writeFileSync(lifetimePath, lifetimeToken, 'utf-8');
|
|
556
|
-
|
|
592
|
+
applyConfiguredLogLevel();
|
|
593
|
+
log('INFO', `Daemon started (PID: ${process.pid})`, {
|
|
594
|
+
event: 'daemon.start', pid: process.pid, node: process.version, logLevel: getDaemonLogLevel().toLowerCase(),
|
|
595
|
+
});
|
|
557
596
|
anchorDaemonCwd();
|
|
558
597
|
warnEphemeralDaemonRoot();
|
|
559
598
|
try {
|
|
@@ -589,7 +628,12 @@ export async function runDaemon() {
|
|
|
589
628
|
catch (err) {
|
|
590
629
|
log('ERROR', `Stray daemon reaper failed: ${err.message}`);
|
|
591
630
|
}
|
|
592
|
-
|
|
631
|
+
let supervisorRef = null;
|
|
632
|
+
const vitals = new DaemonVitals({ log, extra: () => ({ inFlight: supervisorRef?.inFlightTicks() ?? [] }) });
|
|
633
|
+
installSpanLog(log);
|
|
634
|
+
vitals.start();
|
|
635
|
+
const supervisor = new ServiceSupervisor({ diagnostics: () => ({ vitals: vitals.snapshot(), topSpansSinceReport: topSpansSinceReport(8) }) });
|
|
636
|
+
supervisorRef = supervisor;
|
|
593
637
|
if (isEnabled('session-state')) {
|
|
594
638
|
supervisor.register(new SessionStateService(() => supervisor.runNow('session-state')));
|
|
595
639
|
}
|
|
@@ -813,6 +857,7 @@ export async function runDaemon() {
|
|
|
813
857
|
recordSubsystemOk(SUBSYSTEM_DAEMON_START);
|
|
814
858
|
const handleReload = () => {
|
|
815
859
|
log('INFO', 'Reloading jobs (SIGHUP)');
|
|
860
|
+
applyConfiguredLogLevel();
|
|
816
861
|
const reloadedConfig = readDaemonServicesConfig();
|
|
817
862
|
const reloadedEnabled = (id) => reloadedConfig.services[id] !== false;
|
|
818
863
|
for (const id of Object.keys(servicesConfig.services)) {
|
|
@@ -873,6 +918,8 @@ export async function runDaemon() {
|
|
|
873
918
|
// Cleanup removes lifetime, pid, heartbeat, and registry state only when each still belongs to this instance.
|
|
874
919
|
const handleShutdown = singleShot(async () => {
|
|
875
920
|
log('INFO', 'Daemon shutting down');
|
|
921
|
+
vitals.report();
|
|
922
|
+
vitals.stop();
|
|
876
923
|
await supervisor.stopAll();
|
|
877
924
|
activeServiceSupervisor = null;
|
|
878
925
|
stopScheduler();
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
export declare const LOG_LEVELS: readonly ["DEBUG", "INFO", "WARN", "ERROR"];
|
|
2
|
+
export type LogLevel = (typeof LOG_LEVELS)[number];
|
|
3
|
+
export type LogFields = Record<string, unknown>;
|
|
4
|
+
export type DiagnosticLog = (level: LogLevel, message: string, fields?: LogFields) => void;
|
|
5
|
+
export declare function parseLogLevel(raw: unknown): LogLevel | undefined;
|
|
6
|
+
export declare function levelRank(level: string): number;
|
|
7
|
+
export declare function levelEnabled(level: string, threshold: LogLevel): boolean;
|
|
8
|
+
export interface SpanRecord {
|
|
9
|
+
name: string;
|
|
10
|
+
kind: 'sync' | 'async';
|
|
11
|
+
startMs: number;
|
|
12
|
+
durMs: number;
|
|
13
|
+
fields?: LogFields;
|
|
14
|
+
}
|
|
15
|
+
export interface SpanAggregate {
|
|
16
|
+
name: string;
|
|
17
|
+
kind: 'sync' | 'async';
|
|
18
|
+
count: number;
|
|
19
|
+
totalMs: number;
|
|
20
|
+
maxMs: number;
|
|
21
|
+
}
|
|
22
|
+
export declare function installSpanLog(log: DiagnosticLog | null, opts?: {
|
|
23
|
+
slowSyncMs?: number;
|
|
24
|
+
}): void;
|
|
25
|
+
export declare function spanSync<T>(name: string, fn: () => T, fields?: () => LogFields | undefined): T;
|
|
26
|
+
export declare function span<T>(name: string, fn: () => Promise<T>, fields?: () => LogFields | undefined): Promise<T>;
|
|
27
|
+
export declare function syncSpansBetween(fromMs: number, toMs: number): SpanRecord[];
|
|
28
|
+
export declare function topSpansSinceReport(limit: number): SpanAggregate[];
|
|
29
|
+
export interface VitalsSnapshot {
|
|
30
|
+
uptimeS: number;
|
|
31
|
+
loop: {
|
|
32
|
+
p50Ms: number;
|
|
33
|
+
p99Ms: number;
|
|
34
|
+
maxMs: number;
|
|
35
|
+
};
|
|
36
|
+
cpuPct: number;
|
|
37
|
+
rssMb: number;
|
|
38
|
+
heapUsedMb: number;
|
|
39
|
+
load1: number;
|
|
40
|
+
cores: number;
|
|
41
|
+
}
|
|
42
|
+
interface VitalsOptions {
|
|
43
|
+
log: DiagnosticLog;
|
|
44
|
+
reportMs?: number;
|
|
45
|
+
probeMs?: number;
|
|
46
|
+
stallMs?: number;
|
|
47
|
+
extra?: () => LogFields;
|
|
48
|
+
}
|
|
49
|
+
export declare class DaemonVitals {
|
|
50
|
+
private readonly log;
|
|
51
|
+
private readonly reportMs;
|
|
52
|
+
private readonly probeMs;
|
|
53
|
+
private readonly stallMs;
|
|
54
|
+
private readonly extra?;
|
|
55
|
+
private histogram;
|
|
56
|
+
private probeTimer?;
|
|
57
|
+
private reportTimer?;
|
|
58
|
+
private lastProbe;
|
|
59
|
+
private lastCpu;
|
|
60
|
+
private lastCpuAt;
|
|
61
|
+
private readonly startedAt;
|
|
62
|
+
constructor(opts: VitalsOptions);
|
|
63
|
+
start(): void;
|
|
64
|
+
stop(): void;
|
|
65
|
+
snapshot(): VitalsSnapshot;
|
|
66
|
+
private safe;
|
|
67
|
+
private probe;
|
|
68
|
+
report(): void;
|
|
69
|
+
}
|
|
70
|
+
export {};
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import * as os from 'os';
|
|
2
|
+
import { monitorEventLoopDelay, performance } from 'perf_hooks';
|
|
3
|
+
export const LOG_LEVELS = ['DEBUG', 'INFO', 'WARN', 'ERROR'];
|
|
4
|
+
const LEVEL_RANK = { DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3 };
|
|
5
|
+
export function parseLogLevel(raw) {
|
|
6
|
+
if (typeof raw !== 'string')
|
|
7
|
+
return undefined;
|
|
8
|
+
const upper = raw.trim().toUpperCase();
|
|
9
|
+
return LOG_LEVELS.includes(upper) ? upper : undefined;
|
|
10
|
+
}
|
|
11
|
+
export function levelRank(level) {
|
|
12
|
+
if (level.toUpperCase() === 'FATAL')
|
|
13
|
+
return LEVEL_RANK.ERROR;
|
|
14
|
+
return LEVEL_RANK[parseLogLevel(level) ?? 'INFO'];
|
|
15
|
+
}
|
|
16
|
+
export function levelEnabled(level, threshold) {
|
|
17
|
+
return levelRank(level) >= LEVEL_RANK[threshold];
|
|
18
|
+
}
|
|
19
|
+
const SPAN_RING_SIZE = 256;
|
|
20
|
+
const SYNC_RING_FLOOR_MS = 5;
|
|
21
|
+
const SLOW_SYNC_SPAN_MS = 250;
|
|
22
|
+
const spans = { syncRing: [], window: new Map(), log: null, slowSyncMs: SLOW_SYNC_SPAN_MS };
|
|
23
|
+
export function installSpanLog(log, opts = {}) {
|
|
24
|
+
spans.log = log;
|
|
25
|
+
spans.slowSyncMs = opts.slowSyncMs ?? SLOW_SYNC_SPAN_MS;
|
|
26
|
+
spans.syncRing = [];
|
|
27
|
+
spans.window = new Map();
|
|
28
|
+
}
|
|
29
|
+
function safeLog(level, message, fields) {
|
|
30
|
+
try {
|
|
31
|
+
spans.log?.(level, message, fields);
|
|
32
|
+
}
|
|
33
|
+
catch { }
|
|
34
|
+
}
|
|
35
|
+
function record(rec) {
|
|
36
|
+
if (!spans.log)
|
|
37
|
+
return;
|
|
38
|
+
if (rec.kind === 'sync' && rec.durMs >= SYNC_RING_FLOOR_MS) {
|
|
39
|
+
spans.syncRing.push(rec);
|
|
40
|
+
if (spans.syncRing.length > SPAN_RING_SIZE)
|
|
41
|
+
spans.syncRing.splice(0, spans.syncRing.length - SPAN_RING_SIZE);
|
|
42
|
+
}
|
|
43
|
+
const key = `${rec.kind}:${rec.name}`;
|
|
44
|
+
const agg = spans.window.get(key) ?? { name: rec.name, kind: rec.kind, count: 0, totalMs: 0, maxMs: 0 };
|
|
45
|
+
agg.count += 1;
|
|
46
|
+
agg.totalMs += rec.durMs;
|
|
47
|
+
agg.maxMs = Math.max(agg.maxMs, rec.durMs);
|
|
48
|
+
spans.window.set(key, agg);
|
|
49
|
+
const fields = { span: rec.name, kind: rec.kind, durMs: Math.round(rec.durMs), ...rec.fields };
|
|
50
|
+
if (rec.kind === 'sync' && rec.durMs >= spans.slowSyncMs) {
|
|
51
|
+
safeLog('WARN', `slow synchronous section '${rec.name}' blocked the event loop for ${Math.round(rec.durMs)}ms`, { event: 'span.slow', ...fields });
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
safeLog('DEBUG', `span '${rec.name}' ${Math.round(rec.durMs)}ms`, { event: 'span', ...fields });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
export function spanSync(name, fn, fields) {
|
|
58
|
+
if (!spans.log)
|
|
59
|
+
return fn();
|
|
60
|
+
const startMs = performance.now();
|
|
61
|
+
try {
|
|
62
|
+
return fn();
|
|
63
|
+
}
|
|
64
|
+
finally {
|
|
65
|
+
record({ name, kind: 'sync', startMs, durMs: performance.now() - startMs, fields: fields?.() });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export async function span(name, fn, fields) {
|
|
69
|
+
if (!spans.log)
|
|
70
|
+
return fn();
|
|
71
|
+
const startMs = performance.now();
|
|
72
|
+
try {
|
|
73
|
+
return await fn();
|
|
74
|
+
}
|
|
75
|
+
finally {
|
|
76
|
+
record({ name, kind: 'async', startMs, durMs: performance.now() - startMs, fields: fields?.() });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
export function syncSpansBetween(fromMs, toMs) {
|
|
80
|
+
return spans.syncRing.filter((r) => r.startMs + r.durMs >= fromMs && r.startMs <= toMs);
|
|
81
|
+
}
|
|
82
|
+
export function topSpansSinceReport(limit) {
|
|
83
|
+
return [...spans.window.values()]
|
|
84
|
+
.sort((a, b) => b.totalMs - a.totalMs)
|
|
85
|
+
.slice(0, limit)
|
|
86
|
+
.map((a) => ({ ...a, totalMs: Math.round(a.totalMs), maxMs: Math.round(a.maxMs) }));
|
|
87
|
+
}
|
|
88
|
+
function drainSpanWindow(limit) {
|
|
89
|
+
const out = topSpansSinceReport(limit);
|
|
90
|
+
spans.window = new Map();
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
function summarizeSpan(r) {
|
|
94
|
+
return { span: r.name, durMs: Math.round(r.durMs), ...r.fields };
|
|
95
|
+
}
|
|
96
|
+
const toMs = (ns) => Math.round(ns / 1e6);
|
|
97
|
+
export class DaemonVitals {
|
|
98
|
+
log;
|
|
99
|
+
reportMs;
|
|
100
|
+
probeMs;
|
|
101
|
+
stallMs;
|
|
102
|
+
extra;
|
|
103
|
+
histogram = null;
|
|
104
|
+
probeTimer;
|
|
105
|
+
reportTimer;
|
|
106
|
+
lastProbe = 0;
|
|
107
|
+
lastCpu = process.cpuUsage();
|
|
108
|
+
lastCpuAt = performance.now();
|
|
109
|
+
startedAt = performance.now();
|
|
110
|
+
constructor(opts) {
|
|
111
|
+
this.log = opts.log;
|
|
112
|
+
this.reportMs = opts.reportMs ?? 60_000;
|
|
113
|
+
this.probeMs = opts.probeMs ?? 250;
|
|
114
|
+
this.stallMs = opts.stallMs ?? 1_000;
|
|
115
|
+
this.extra = opts.extra;
|
|
116
|
+
}
|
|
117
|
+
start() {
|
|
118
|
+
this.histogram = monitorEventLoopDelay({ resolution: 20 });
|
|
119
|
+
this.histogram.enable();
|
|
120
|
+
this.lastProbe = performance.now();
|
|
121
|
+
this.probeTimer = setInterval(() => this.probe(), this.probeMs);
|
|
122
|
+
this.reportTimer = setInterval(() => this.report(), this.reportMs);
|
|
123
|
+
this.probeTimer.unref?.();
|
|
124
|
+
this.reportTimer.unref?.();
|
|
125
|
+
}
|
|
126
|
+
stop() {
|
|
127
|
+
if (this.probeTimer)
|
|
128
|
+
clearInterval(this.probeTimer);
|
|
129
|
+
if (this.reportTimer)
|
|
130
|
+
clearInterval(this.reportTimer);
|
|
131
|
+
this.histogram?.disable();
|
|
132
|
+
this.histogram = null;
|
|
133
|
+
}
|
|
134
|
+
snapshot() {
|
|
135
|
+
const now = performance.now();
|
|
136
|
+
const cpu = process.cpuUsage(this.lastCpu);
|
|
137
|
+
const wallUs = Math.max(1, (now - this.lastCpuAt) * 1000);
|
|
138
|
+
const mem = process.memoryUsage();
|
|
139
|
+
const h = this.histogram;
|
|
140
|
+
return {
|
|
141
|
+
uptimeS: Math.round((now - this.startedAt) / 1000),
|
|
142
|
+
loop: h ? { p50Ms: toMs(h.percentile(50)), p99Ms: toMs(h.percentile(99)), maxMs: toMs(h.max) } : { p50Ms: 0, p99Ms: 0, maxMs: 0 },
|
|
143
|
+
cpuPct: Math.round(((cpu.user + cpu.system) / wallUs) * 100),
|
|
144
|
+
rssMb: Math.round(mem.rss / 1048576),
|
|
145
|
+
heapUsedMb: Math.round(mem.heapUsed / 1048576),
|
|
146
|
+
load1: Math.round(os.loadavg()[0] * 10) / 10,
|
|
147
|
+
cores: os.availableParallelism?.() ?? os.cpus().length,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
safe(level, message, fields) {
|
|
151
|
+
try {
|
|
152
|
+
this.log(level, message, fields);
|
|
153
|
+
}
|
|
154
|
+
catch { }
|
|
155
|
+
}
|
|
156
|
+
probe() {
|
|
157
|
+
const now = performance.now();
|
|
158
|
+
const stalledMs = now - this.lastProbe - this.probeMs;
|
|
159
|
+
const from = this.lastProbe;
|
|
160
|
+
this.lastProbe = now;
|
|
161
|
+
if (stalledMs < this.stallMs)
|
|
162
|
+
return;
|
|
163
|
+
const blockers = syncSpansBetween(from, now).sort((a, b) => b.durMs - a.durMs).slice(0, 5);
|
|
164
|
+
const named = blockers.length ? blockers.map((b) => `${b.name} ${Math.round(b.durMs)}ms`).join(', ') : 'no instrumented section (uninstrumented code or the process was descheduled)';
|
|
165
|
+
this.safe('WARN', `event loop stalled ${Math.round(stalledMs)}ms; ran: ${named}`, {
|
|
166
|
+
event: 'loop.stall',
|
|
167
|
+
stalledMs: Math.round(stalledMs),
|
|
168
|
+
blockers: blockers.map(summarizeSpan),
|
|
169
|
+
load1: Math.round(os.loadavg()[0] * 10) / 10,
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
report() {
|
|
173
|
+
const snap = this.snapshot();
|
|
174
|
+
const top = drainSpanWindow(8);
|
|
175
|
+
this.histogram?.reset();
|
|
176
|
+
this.lastCpu = process.cpuUsage();
|
|
177
|
+
this.lastCpuAt = performance.now();
|
|
178
|
+
this.safe('INFO', `vitals: loop p99 ${snap.loop.p99Ms}ms max ${snap.loop.maxMs}ms, cpu ${snap.cpuPct}%, rss ${snap.rssMb}MB, load ${snap.load1}/${snap.cores}`, {
|
|
179
|
+
event: 'vitals',
|
|
180
|
+
...snap,
|
|
181
|
+
topSpans: top,
|
|
182
|
+
...this.extra?.(),
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
}
|
|
@@ -7,7 +7,7 @@ export interface ServiceHealth {
|
|
|
7
7
|
consecutiveFailures: number;
|
|
8
8
|
}
|
|
9
9
|
export interface DaemonContext {
|
|
10
|
-
log: (level: string, message: string) => void;
|
|
10
|
+
log: (level: string, message: string, fields?: Record<string, unknown>) => void;
|
|
11
11
|
}
|
|
12
12
|
export interface DaemonService {
|
|
13
13
|
readonly id: DaemonServiceId;
|
|
@@ -9,5 +9,5 @@ export declare class SessionStateService extends BasePeriodicService {
|
|
|
9
9
|
constructor(wake: () => void);
|
|
10
10
|
protected onStart(_ctx: DaemonContext): Promise<void>;
|
|
11
11
|
protected onStop(): Promise<void>;
|
|
12
|
-
protected onTick(
|
|
12
|
+
protected onTick(ctx: DaemonContext): Promise<void>;
|
|
13
13
|
}
|
|
@@ -20,7 +20,7 @@ export class SessionStateService extends BasePeriodicService {
|
|
|
20
20
|
this.stopReaderWatch?.();
|
|
21
21
|
this.stopReaderWatch = null;
|
|
22
22
|
}
|
|
23
|
-
async onTick(
|
|
24
|
-
await runActiveSessionsWarmTick();
|
|
23
|
+
async onTick(ctx) {
|
|
24
|
+
await runActiveSessionsWarmTick({ log: ctx.log });
|
|
25
25
|
}
|
|
26
26
|
}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import type { DaemonServiceId } from '../daemon-services.js';
|
|
2
2
|
import type { DaemonContext, DaemonService, ServiceHealth } from './service.js';
|
|
3
|
+
import { type LogFields } from './diagnostics.js';
|
|
3
4
|
interface ServiceSupervisorOptions {
|
|
4
5
|
lifecycleDeadlineMs?: number;
|
|
5
6
|
exit?: (code: number) => never;
|
|
7
|
+
diagnostics?: () => LogFields;
|
|
6
8
|
}
|
|
7
9
|
interface RegisterServiceOptions {
|
|
8
10
|
enabled?: boolean;
|
|
@@ -12,7 +14,12 @@ export declare class ServiceSupervisor {
|
|
|
12
14
|
private ctx;
|
|
13
15
|
private readonly lifecycleDeadlineMs;
|
|
14
16
|
private readonly exit;
|
|
17
|
+
private readonly diagnostics?;
|
|
15
18
|
constructor(opts?: ServiceSupervisorOptions);
|
|
19
|
+
inFlightTicks(now?: number): Array<{
|
|
20
|
+
service: DaemonServiceId;
|
|
21
|
+
elapsedMs: number;
|
|
22
|
+
}>;
|
|
16
23
|
private withDeadline;
|
|
17
24
|
register(service: DaemonService, options?: RegisterServiceOptions): void;
|
|
18
25
|
private clearInFlight;
|
|
@@ -31,6 +38,7 @@ export declare class ServiceSupervisor {
|
|
|
31
38
|
private scheduleTimer;
|
|
32
39
|
private runTick;
|
|
33
40
|
private recordFailure;
|
|
41
|
+
private breachSnapshot;
|
|
34
42
|
private exitForRestart;
|
|
35
43
|
private freezeTimers;
|
|
36
44
|
}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { recordSubsystemOk, recordSubsystemError, recordSubsystemState, recordDaemonRestart } from '../daemon-health.js';
|
|
2
2
|
import { isPeriodicService } from './service.js';
|
|
3
|
+
import { syncSpansBetween } from './diagnostics.js';
|
|
4
|
+
import { performance } from 'perf_hooks';
|
|
3
5
|
const DEADLINE_EXIT_CODE = 70;
|
|
4
6
|
const DEFAULT_LIFECYCLE_DEADLINE_MS = 30_000;
|
|
5
7
|
export class ServiceSupervisor {
|
|
@@ -7,9 +9,19 @@ export class ServiceSupervisor {
|
|
|
7
9
|
ctx = null;
|
|
8
10
|
lifecycleDeadlineMs;
|
|
9
11
|
exit;
|
|
12
|
+
diagnostics;
|
|
10
13
|
constructor(opts = {}) {
|
|
11
14
|
this.lifecycleDeadlineMs = opts.lifecycleDeadlineMs ?? DEFAULT_LIFECYCLE_DEADLINE_MS;
|
|
12
15
|
this.exit = opts.exit ?? ((code) => process.exit(code));
|
|
16
|
+
this.diagnostics = opts.diagnostics;
|
|
17
|
+
}
|
|
18
|
+
inFlightTicks(now = performance.now()) {
|
|
19
|
+
const out = [];
|
|
20
|
+
for (const [id, entry] of this.registry) {
|
|
21
|
+
if (entry.inFlight && entry.tickStartedAt !== undefined)
|
|
22
|
+
out.push({ service: id, elapsedMs: Math.round(now - entry.tickStartedAt) });
|
|
23
|
+
}
|
|
24
|
+
return out.sort((a, b) => b.elapsedMs - a.elapsedMs);
|
|
13
25
|
}
|
|
14
26
|
async withDeadline(op, ms, label) {
|
|
15
27
|
let timer;
|
|
@@ -206,9 +218,12 @@ export class ServiceSupervisor {
|
|
|
206
218
|
return;
|
|
207
219
|
const periodicService = entry.service;
|
|
208
220
|
entry.inFlight = true;
|
|
221
|
+
const startedAt = performance.now();
|
|
222
|
+
entry.tickStartedAt = startedAt;
|
|
209
223
|
const controller = new AbortController();
|
|
210
224
|
entry.activeController = controller;
|
|
211
225
|
let timedOut = false;
|
|
226
|
+
ctx.log('DEBUG', `service '${id}' tick start`, { event: 'tick.start', service: id });
|
|
212
227
|
const tickPromise = periodicService.tick(ctx, controller.signal);
|
|
213
228
|
entry.activeTick = tickPromise;
|
|
214
229
|
try {
|
|
@@ -219,6 +234,14 @@ export class ServiceSupervisor {
|
|
|
219
234
|
}, periodicService.deadlineMs);
|
|
220
235
|
});
|
|
221
236
|
await Promise.race([tickPromise, deadline]);
|
|
237
|
+
const durMs = Math.round(performance.now() - startedAt);
|
|
238
|
+
const tickFields = { service: id, durMs, deadlineMs: periodicService.deadlineMs };
|
|
239
|
+
if (durMs * 2 > periodicService.deadlineMs) {
|
|
240
|
+
ctx.log('WARN', `service '${id}' tick took ${durMs}ms, over half its ${periodicService.deadlineMs}ms deadline`, { event: 'tick.slow', ...tickFields, inFlight: this.inFlightTicks() });
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
ctx.log('DEBUG', `service '${id}' tick ok in ${durMs}ms`, { event: 'tick.ok', ...tickFields });
|
|
244
|
+
}
|
|
222
245
|
entry.consecutiveFailures = 0;
|
|
223
246
|
entry.lastError = undefined;
|
|
224
247
|
entry.lastRunMs = Date.now();
|
|
@@ -228,11 +251,11 @@ export class ServiceSupervisor {
|
|
|
228
251
|
const stoppedDuringTick = this.registry.get(id)?.state === 'stopped';
|
|
229
252
|
if (timedOut && !stoppedDuringTick) {
|
|
230
253
|
controller.abort();
|
|
231
|
-
this.exitForRestart(id, err);
|
|
254
|
+
this.exitForRestart(id, err, startedAt);
|
|
232
255
|
return;
|
|
233
256
|
}
|
|
234
257
|
if (!timedOut)
|
|
235
|
-
this.recordFailure(entry, id, err);
|
|
258
|
+
this.recordFailure(entry, id, err, Math.round(performance.now() - startedAt));
|
|
236
259
|
}
|
|
237
260
|
finally {
|
|
238
261
|
if (entry.deadlineTimer) {
|
|
@@ -241,17 +264,35 @@ export class ServiceSupervisor {
|
|
|
241
264
|
}
|
|
242
265
|
entry.activeTick = undefined;
|
|
243
266
|
entry.activeController = undefined;
|
|
267
|
+
entry.tickStartedAt = undefined;
|
|
244
268
|
this.clearInFlight(entry);
|
|
245
269
|
}
|
|
246
270
|
}
|
|
247
|
-
recordFailure(entry, id, err) {
|
|
271
|
+
recordFailure(entry, id, err, durMs) {
|
|
248
272
|
const message = err instanceof Error ? err.message : String(err);
|
|
249
273
|
entry.consecutiveFailures += 1;
|
|
250
274
|
entry.lastError = message;
|
|
251
275
|
recordSubsystemError(id, message);
|
|
252
|
-
this.ctx?.log('WARN', `service '${id}' failed: ${message}
|
|
276
|
+
this.ctx?.log('WARN', `service '${id}' failed: ${message}`, {
|
|
277
|
+
event: 'tick.failed', service: id, durMs, consecutiveFailures: entry.consecutiveFailures, error: message,
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
breachSnapshot(id, startedAt) {
|
|
281
|
+
const now = performance.now();
|
|
282
|
+
const blockers = startedAt === undefined ? [] : syncSpansBetween(startedAt, now)
|
|
283
|
+
.sort((a, b) => b.durMs - a.durMs)
|
|
284
|
+
.slice(0, 8)
|
|
285
|
+
.map((r) => ({ span: r.name, durMs: Math.round(r.durMs), ...r.fields }));
|
|
286
|
+
return {
|
|
287
|
+
event: 'tick.breach',
|
|
288
|
+
service: id,
|
|
289
|
+
elapsedMs: startedAt === undefined ? undefined : Math.round(now - startedAt),
|
|
290
|
+
inFlight: this.inFlightTicks(now),
|
|
291
|
+
syncSpansDuringTick: blockers,
|
|
292
|
+
...this.diagnostics?.(),
|
|
293
|
+
};
|
|
253
294
|
}
|
|
254
|
-
exitForRestart(id, err) {
|
|
295
|
+
exitForRestart(id, err, startedAt) {
|
|
255
296
|
const cause = err instanceof Error ? err.message : String(err);
|
|
256
297
|
const entry = this.registry.get(id);
|
|
257
298
|
if (entry) {
|
|
@@ -260,7 +301,7 @@ export class ServiceSupervisor {
|
|
|
260
301
|
}
|
|
261
302
|
recordSubsystemError(id, cause);
|
|
262
303
|
recordDaemonRestart(id, cause);
|
|
263
|
-
this.ctx?.log('ERROR', `service '${id}' breached its deadline (${cause}); exiting (code ${DEADLINE_EXIT_CODE}) for a supervised restart
|
|
304
|
+
this.ctx?.log('ERROR', `service '${id}' breached its deadline (${cause}); exiting (code ${DEADLINE_EXIT_CODE}) for a supervised restart`, this.breachSnapshot(id, startedAt));
|
|
264
305
|
this.freezeTimers();
|
|
265
306
|
this.exit(DEADLINE_EXIT_CODE);
|
|
266
307
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type LogLevel } from './daemon/diagnostics.js';
|
|
1
2
|
export type DaemonServiceId = 'scheduler' | 'catchup' | 'webhook-receiver' | 'self-heal' | 'self-update' | 'account-state' | 'account-auth' | 'watchdog' | 'device-probe' | 'state-dir-check' | 'session-index' | 'session-title' | 'auth-sync' | 'usage-sync' | 'daemon-heartbeat' | 'tmux-reap' | 'session-state' | 'feed-stream' | 'session-summarizer' | 'attention-notify' | 'recordings' | 'harness-update';
|
|
2
3
|
interface DaemonServiceDef {
|
|
3
4
|
id: DaemonServiceId;
|
|
@@ -13,6 +14,8 @@ export interface DaemonServicesConfig {
|
|
|
13
14
|
export declare function getDaemonServicesConfigPath(): string;
|
|
14
15
|
export declare function readDaemonServicesConfig(): DaemonServicesConfig;
|
|
15
16
|
export declare function writeDaemonServicesConfig(cfg: DaemonServicesConfig): void;
|
|
17
|
+
export declare function readDaemonLogLevel(): LogLevel;
|
|
18
|
+
export declare function writeDaemonLogLevel(level: LogLevel): void;
|
|
16
19
|
export declare function isDaemonServiceEnabled(id: DaemonServiceId): boolean;
|
|
17
20
|
export declare function setDaemonServiceEnabled(id: DaemonServiceId, enabled: boolean): DaemonServicesConfig;
|
|
18
21
|
export declare function listDaemonServiceStates(): Array<DaemonServiceDef & {
|