@phnx-labs/agents-cli 1.23.0 → 1.23.2

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 (59) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +2 -0
  3. package/dist/commands/cloud-transcripts.js +1 -2
  4. package/dist/commands/daemon.js +70 -11
  5. package/dist/commands/exec.js +1 -1
  6. package/dist/commands/feed.js +1 -2
  7. package/dist/commands/focus.js +4 -1
  8. package/dist/commands/go.js +3 -2
  9. package/dist/commands/logs.js +1 -1
  10. package/dist/commands/menubar.js +28 -3
  11. package/dist/commands/ps-roster.d.ts +0 -11
  12. package/dist/commands/ps-roster.js +3 -116
  13. package/dist/commands/ps.d.ts +10 -0
  14. package/dist/commands/ps.js +182 -1
  15. package/dist/commands/resume.js +1 -1
  16. package/dist/commands/sessions-browser.d.ts +0 -1
  17. package/dist/commands/sessions-browser.js +6 -23
  18. package/dist/commands/sessions-export.js +1 -1
  19. package/dist/commands/sessions-migrate.js +1 -1
  20. package/dist/commands/sessions-picker.d.ts +6 -32
  21. package/dist/commands/sessions-picker.js +81 -8
  22. package/dist/commands/sessions-render.js +1 -1
  23. package/dist/commands/sessions-resume.js +2 -2
  24. package/dist/commands/sessions-share.js +1 -1
  25. package/dist/commands/sessions-trace.js +1 -1
  26. package/dist/commands/sessions.d.ts +2 -165
  27. package/dist/commands/sessions.js +16 -1216
  28. package/dist/lib/daemon/account-state-daemon-service.d.ts +2 -2
  29. package/dist/lib/daemon/account-state-daemon-service.js +2 -2
  30. package/dist/lib/daemon/attention-notify-service.js +8 -4
  31. package/dist/lib/daemon/daemon.d.ts +5 -1
  32. package/dist/lib/daemon/daemon.js +53 -6
  33. package/dist/lib/daemon/diagnostics.d.ts +70 -0
  34. package/dist/lib/daemon/diagnostics.js +185 -0
  35. package/dist/lib/daemon/service.d.ts +1 -1
  36. package/dist/lib/daemon/session-state-service.d.ts +1 -1
  37. package/dist/lib/daemon/session-state-service.js +2 -2
  38. package/dist/lib/daemon/supervisor.d.ts +8 -0
  39. package/dist/lib/daemon/supervisor.js +47 -6
  40. package/dist/lib/daemon-services.d.ts +3 -0
  41. package/dist/lib/daemon-services.js +36 -0
  42. package/dist/lib/daemon-ticks.d.ts +3 -1
  43. package/dist/lib/daemon-ticks.js +18 -12
  44. package/dist/lib/feed/tool-activity.js +10 -3
  45. package/dist/lib/feed/watch.js +8 -5
  46. package/dist/lib/helper-versions.js +1 -1
  47. package/dist/lib/menubar/install-menubar.d.ts +19 -1
  48. package/dist/lib/menubar/install-menubar.js +81 -12
  49. package/dist/lib/session/active.js +18 -14
  50. package/dist/lib/session/pid-registry.js +9 -6
  51. package/dist/lib/session/presentation.d.ts +107 -1
  52. package/dist/lib/session/presentation.js +543 -4
  53. package/dist/lib/session/remote/remote-list.d.ts +3 -0
  54. package/dist/lib/session/remote/remote-list.js +13 -0
  55. package/dist/lib/session/resume-command.d.ts +9 -0
  56. package/dist/lib/session/resume-command.js +107 -0
  57. package/dist/lib/session/selection.d.ts +102 -0
  58. package/dist/lib/session/selection.js +443 -0
  59. package/package.json +1 -1
@@ -3,6 +3,7 @@ import * as path from 'path';
3
3
  import * as yaml from 'yaml';
4
4
  import { getDaemonConfigDir } from './state.js';
5
5
  import { atomicWriteFileSync } from './fs-atomic.js';
6
+ import { LOG_LEVELS, parseLogLevel } from './daemon/diagnostics.js';
6
7
  export const DAEMON_SERVICES = [
7
8
  {
8
9
  id: 'scheduler',
@@ -163,6 +164,41 @@ export function writeDaemonServicesConfig(cfg) {
163
164
  const out = yaml.stringify({ ...preserved, services }, { sortMapEntries: false });
164
165
  atomicWriteFileSync(filePath, out, 'utf-8');
165
166
  }
167
+ function readServicesConfigText() {
168
+ try {
169
+ return fs.readFileSync(getDaemonServicesConfigPath(), 'utf-8');
170
+ }
171
+ catch (err) {
172
+ if (err.code === 'ENOENT')
173
+ return undefined;
174
+ throw err;
175
+ }
176
+ }
177
+ export function readDaemonLogLevel() {
178
+ const raw = readServicesConfigText();
179
+ if (raw === undefined)
180
+ return 'INFO';
181
+ const parsed = yaml.parse(raw);
182
+ if (!parsed || parsed.logLevel === undefined)
183
+ return 'INFO';
184
+ const level = parseLogLevel(parsed.logLevel);
185
+ if (!level)
186
+ throw new Error(`${getDaemonServicesConfigPath()}: logLevel '${String(parsed.logLevel)}' is not one of ${LOG_LEVELS.join(', ').toLowerCase()}`);
187
+ return level;
188
+ }
189
+ export function writeDaemonLogLevel(level) {
190
+ const dir = getDaemonConfigDir();
191
+ fs.mkdirSync(dir, { recursive: true });
192
+ const filePath = getDaemonServicesConfigPath();
193
+ const raw = readServicesConfigText();
194
+ const parsed = raw === undefined ? null : yaml.parse(raw);
195
+ if (parsed !== null && (typeof parsed !== 'object' || Array.isArray(parsed))) {
196
+ throw new Error(`${filePath} is not a YAML mapping; fix it before setting the log level`);
197
+ }
198
+ const doc = { ...parsed };
199
+ doc.logLevel = level.toLowerCase();
200
+ atomicWriteFileSync(filePath, yaml.stringify(doc, { sortMapEntries: false }), 'utf-8');
201
+ }
166
202
  export function isDaemonServiceEnabled(id) {
167
203
  return readDaemonServicesConfig().services[id] !== false;
168
204
  }
@@ -1,3 +1,4 @@
1
+ import { type DiagnosticLog } from './daemon/diagnostics.js';
1
2
  import type { FleetStatusRow } from './fleet-status.js';
2
3
  import { type AuthProbeRow } from './auth-health.js';
3
4
  export { AUTH_PROBE_MAX_AGE_MS } from './auth-health.js';
@@ -16,10 +17,11 @@ export declare function refreshLocalFleetAuthState(opts?: {
16
17
  authRows: import('./auth-health.js').AuthProbeRow[];
17
18
  }>;
18
19
  export declare function runFleetCacheWarmTick(signal?: AbortSignal): Promise<void>;
19
- export declare function runUsageRefreshTick(signal?: AbortSignal): Promise<void>;
20
+ export declare function runUsageRefreshTick(signal?: AbortSignal, log?: DiagnosticLog): Promise<void>;
20
21
  export declare function runActiveSessionsWarmTick(opts?: {
21
22
  gather?: () => Promise<import('./session/active.js').ActiveSession[]>;
22
23
  nowMs?: number;
24
+ log?: DiagnosticLog;
23
25
  }): Promise<{
24
26
  sessions: number;
25
27
  }>;
@@ -1,3 +1,4 @@
1
+ import { span, spanSync } from './daemon/diagnostics.js';
1
2
  import { AUTH_PROBE_MAX_AGE_MS, authTargetKey } from './auth-health.js';
2
3
  export { AUTH_PROBE_MAX_AGE_MS } from './auth-health.js';
3
4
  export function isFreshFleetAuthSnapshot(value, minimumCapturedAt) {
@@ -55,12 +56,13 @@ export async function runFleetCacheWarmTick(signal) {
55
56
  const authCount = result.authRows.length;
56
57
  console.log(`fleet cache warm: ${authCount} auth row(s) refreshed, ${row.agents.running} running agent(s) on ${row.host}`);
57
58
  }
58
- export async function runUsageRefreshTick(signal) {
59
+ const noLog = () => { };
60
+ export async function runUsageRefreshTick(signal, log = noLog) {
59
61
  const { runUsageRefresh, buildLocalUsageAccounts } = await import('./usage-refresh.js');
60
62
  const { writeClaudeUsageCache, readClaudeUsageCache } = await import('./accounting/usage.js');
61
63
  const { usageRateLimitedUntil } = await import('./usage-backoff.js');
62
64
  const { machineId } = await import('./machine-id.js');
63
- const r = await runUsageRefresh({
65
+ const r = await span('usage.refresh', () => runUsageRefresh({
64
66
  listAccounts: buildLocalUsageAccounts,
65
67
  writeUsageCache: writeClaudeUsageCache,
66
68
  backoffUntil: (agentId, usageKey) => usageRateLimitedUntil(agentId, Date.now(), usageKey),
@@ -71,35 +73,39 @@ export async function runUsageRefreshTick(signal) {
71
73
  const { publishUsageSnapshotToSharedStore } = await import('./accounting/usage-sync.js');
72
74
  await publishUsageSnapshotToSharedStore();
73
75
  },
74
- });
76
+ }));
75
77
  const { listProfiles } = await import('./profiles.js');
76
78
  const { refreshDueByokUsage } = await import('./byok-usage.js');
77
- const byok = await refreshDueByokUsage(listProfiles());
78
- console.log(`usage refresh: ${r.refreshed} refreshed, ${r.failed} failed, ${r.skippedNotDue} not-due, ${r.skippedBackoff} backed-off, ${r.skippedCap} capped, ${r.skippedBudget} over-budget, ${r.skippedFresh} statusline-fresh; BYOK ${byok.refreshed} refreshed, ${byok.skipped} not-due`);
79
+ const byok = await span('usage.refresh-byok', () => refreshDueByokUsage(listProfiles()));
80
+ log(r.failed > 0 ? 'WARN' : 'INFO', `usage refresh: ${r.refreshed} refreshed, ${r.failed} failed, ${r.skippedNotDue} not-due, ${r.skippedBackoff} backed-off, ${r.skippedCap} capped, ${r.skippedBudget} over-budget, ${r.skippedFresh} statusline-fresh; BYOK ${byok.refreshed} refreshed, ${byok.skipped} not-due`, {
81
+ event: 'usage.refresh', refreshed: r.refreshed, failed: r.failed, notDue: r.skippedNotDue, backedOff: r.skippedBackoff,
82
+ capped: r.skippedCap, overBudget: r.skippedBudget, statuslineFresh: r.skippedFresh, byokRefreshed: byok.refreshed, byokNotDue: byok.skipped,
83
+ });
79
84
  }
80
85
  export async function runActiveSessionsWarmTick(opts = {}) {
86
+ const log = opts.log ?? noLog;
81
87
  const { publishLocalActiveSessions, isActiveSessionsJournalReaderRecent } = await import('./session/session-cache.js');
82
88
  const nowMs = opts.nowMs ?? Date.now();
83
89
  if (!isActiveSessionsJournalReaderRecent(nowMs)) {
84
- console.log('active-sessions warm: idle (no recent reader), skipping gather');
90
+ log('DEBUG', 'active-sessions warm: idle (no recent reader), skipping gather', { event: 'sessions.warm', skipped: 'no-reader' });
85
91
  return { sessions: 0 };
86
92
  }
87
93
  const gather = opts.gather ?? (async () => {
88
94
  const { getActiveSessions } = await import('./session/active.js');
89
95
  return getActiveSessions({ localOnly: true });
90
96
  });
91
- const gathered = await gather();
97
+ const gathered = await span('sessions.warm.gather', gather, () => ({}));
92
98
  const { runTimelinePassSync } = await import('./session/timeline-pass.js');
93
99
  let timeline = { computed: 0, reused: 0, skipped: 0 };
94
100
  try {
95
- timeline = runTimelinePassSync({ sessions: gathered, nowMs });
101
+ timeline = spanSync('sessions.timeline-pass', () => runTimelinePassSync({ sessions: gathered, nowMs }), () => ({ sessions: gathered.length }));
96
102
  }
97
103
  catch (err) {
98
- console.log(`active-sessions warm: timeline pass failed: ${err.message}`);
104
+ log('WARN', `active-sessions warm: timeline pass failed: ${err.message}`, { event: 'sessions.timeline-pass.failed', error: err.message });
99
105
  }
100
- const r = await publishLocalActiveSessions({ gather: async () => gathered, nowMs });
101
- console.log(`active-sessions warm: ${r.sessions.length} session(s) published; `
102
- + `timeline ${timeline.computed} folded, ${timeline.reused} current, ${timeline.skipped} skipped`);
106
+ const r = await span('sessions.warm.publish', () => publishLocalActiveSessions({ gather: async () => gathered, nowMs }));
107
+ log('DEBUG', `active-sessions warm: ${r.sessions.length} session(s) published; `
108
+ + `timeline ${timeline.computed} folded, ${timeline.reused} current, ${timeline.skipped} skipped`, { event: 'sessions.warm', sessions: r.sessions.length, ...timeline });
103
109
  return { sessions: r.sessions.length };
104
110
  }
105
111
  export async function runSessionIndexWarmTick() {
@@ -4,6 +4,7 @@ import * as path from 'node:path';
4
4
  import { getBrowserRuntimeDir, getCacheDir } from '../state.js';
5
5
  import { getEventsDir } from './events.js';
6
6
  import { readRecentActivity } from './activity.js';
7
+ import { span, spanSync } from '../daemon/diagnostics.js';
7
8
  import { invocation as browserInvocation, resolveBrowserBin } from '../browser-client.js';
8
9
  import { invocation as computerInvocation, resolveComputerBin } from '../computer-client.js';
9
10
  import { getSessionById } from '../session/db.js';
@@ -89,6 +90,9 @@ export async function readStandaloneComputerRows() {
89
90
  });
90
91
  }
91
92
  function buildLaunchSessionIndex() {
93
+ return spanSync('feed.tools.launch-index', buildLaunchSessionIndexNow);
94
+ }
95
+ function buildLaunchSessionIndexNow() {
92
96
  const byLaunchId = new Map();
93
97
  for (const event of readRecentActivity({ maxBytesPerSession: 64 * 1024 })) {
94
98
  if (event.launchId && event.sessionId)
@@ -106,6 +110,9 @@ function buildLaunchSessionIndex() {
106
110
  }
107
111
  /** The tools record a session or launch id; only agents-cli's index can say which agent session that was. */
108
112
  export function linkToolSessions(rows) {
113
+ return spanSync('feed.tools.link-sessions', () => linkToolSessionsNow(rows), () => ({ rows: rows.length }));
114
+ }
115
+ function linkToolSessionsNow(rows) {
109
116
  let byLaunchId;
110
117
  return rows.map((row) => {
111
118
  let linked = row.sessionId ? getSessionById(row.sessionId) : null;
@@ -133,7 +140,7 @@ export async function collectToolRows(scope, sources = {}) {
133
140
  };
134
141
  const [bindingList, liveTaskList, browserRows, computerRows] = await Promise.all([
135
142
  read('browser', sources.bindings ?? (() => []), []),
136
- read('browser', sources.liveTasks ?? (() => readLiveBrowserTasks()), []),
143
+ read('browser', sources.liveTasks ?? (() => spanSync('feed.tools.live-tasks', () => readLiveBrowserTasks())), []),
137
144
  read('browser', sources.browserRows ?? (async () => linkToolSessions(await readStandaloneBrowserRows())), []),
138
145
  read('computer', sources.computerRows ?? (async () => linkToolSessions(await readStandaloneComputerRows())), []),
139
146
  ]);
@@ -295,12 +302,12 @@ export function watchToolActivity(options) {
295
302
  const reproject = async () => {
296
303
  projecting = true;
297
304
  try {
298
- const snapshot = await collectToolRows(options.scope, options.sources);
305
+ const snapshot = await span('feed.tools.collect', () => collectToolRows(options.scope, options.sources));
299
306
  if (stopped)
300
307
  return;
301
308
  if (snapshot.retry)
302
309
  dirty = true;
303
- const diff = set.diff(snapshot.rows, snapshot.incomplete);
310
+ const diff = spanSync('feed.tools.diff', () => set.diff(snapshot.rows, snapshot.incomplete), () => ({ rows: snapshot.rows.length }));
304
311
  if (diff.upserts.length > 0 || diff.removes.length > 0)
305
312
  options.onDiff(diff);
306
313
  }
@@ -1,4 +1,5 @@
1
1
  import { SessionProjection } from '../session/projection.js';
2
+ import { span, spanSync } from '../daemon/diagnostics.js';
2
3
  import * as fs from 'node:fs';
3
4
  import * as path from 'node:path';
4
5
  import { loadDevices, isDialableDevice } from '../devices/registry.js';
@@ -222,7 +223,7 @@ export async function watchLocalFeed(options) {
222
223
  const activityTimer = setInterval(() => {
223
224
  pending = pending.then(async () => {
224
225
  const nowMs = Date.now();
225
- const events = activity.read(activityCursor + 1, nowMs).reverse();
226
+ const events = spanSync('feed.activity.read', () => activity.read(activityCursor + 1, nowMs).reverse());
226
227
  for (const event of events) {
227
228
  activityCursor = Math.max(activityCursor, Date.parse(event.ts));
228
229
  options.emit(state.emit({ type: 'activity.append', scope: options.scope, event }));
@@ -231,7 +232,7 @@ export async function watchLocalFeed(options) {
231
232
  return;
232
233
  attentionDirty = false;
233
234
  lastReconcileMs = nowMs;
234
- await reconcileRows();
235
+ await span('feed.attention.reconcile', reconcileRows, () => ({ rows: agents.size }));
235
236
  });
236
237
  }, options.activityPollMs ?? 500);
237
238
  const toolWatch = watchToolActivity({
@@ -270,7 +271,7 @@ export async function watchLocalFeed(options) {
270
271
  attention.delete(event.rowKey);
271
272
  prStatus.delete(event.rowKey);
272
273
  }
273
- pending = pending.then(() => projectSessionEnvelope(event, state, options.gh, toolRows, setupRows)).then((events) => {
274
+ pending = pending.then(() => span('feed.sessions.project', () => projectSessionEnvelope(event, state, options.gh, toolRows, setupRows), () => ({ type: event.type }))).then((events) => {
274
275
  for (const projected of events) {
275
276
  if (projected.type === 'reset') {
276
277
  attention.clear();
@@ -345,8 +346,10 @@ export async function watchFleetFeed(options) {
345
346
  const coordinator = new FeedWatchState();
346
347
  const projection = new FeedSessionProjection(coordinator);
347
348
  const forward = (event) => {
348
- for (const projected of projection.apply(event))
349
- options.emit(projected);
349
+ spanSync('feed.fleet.apply', () => {
350
+ for (const projected of projection.apply(event))
351
+ options.emit(projected);
352
+ }, () => ({ type: event.type, scope: 'scope' in event ? event.scope : undefined }));
350
353
  };
351
354
  const local = subscribeSharedLocalFeed({ signal: options.signal, emit: forward });
352
355
  let devices;
@@ -1,5 +1,5 @@
1
1
  export const HELPER_RELEASES = {
2
- menubar: { tagPrefix: 'menubar', floor: '1.15.19' },
2
+ menubar: { tagPrefix: 'menubar', floor: '1.15.21' },
3
3
  };
4
4
  export function helperTag(helper, version) {
5
5
  const release = HELPER_RELEASES[helper];
@@ -25,10 +25,27 @@ export declare function ensureMenubarAppInstalled(opts?: {
25
25
  export declare function generateServicePlist(execPath: string): string;
26
26
  export declare function restartMenubarLaunchAgent(uid: number, plist: string, exec?: (cmd: string, args: readonly string[], opts: {
27
27
  stdio: ['ignore', 'ignore', 'ignore'];
28
- }) => Buffer): void;
28
+ }) => Buffer, sleep?: (ms: number) => void): void;
29
29
  export declare function restartMenubarHelperAfterSwap(uid: number, ownProcesses: readonly MenubarProcess[], exec?: (cmd: string, args: readonly string[], opts: {
30
30
  stdio: ['ignore', 'ignore', 'ignore'];
31
31
  }) => Buffer, kill?: (pid: number) => void): void;
32
+ export interface MenubarRestartResult {
33
+ outcome: 'restarted' | 'failed';
34
+ previousPids: number[];
35
+ pids: number[];
36
+ detail: string;
37
+ }
38
+ export declare const MENUBAR_RESTART_DEADLINE_MS = 15000;
39
+ export interface MenubarRestartDeps {
40
+ ownPids: () => number[];
41
+ kickstart: (target: string) => Promise<{
42
+ code: number | null;
43
+ stderr: string;
44
+ }>;
45
+ sleep: (ms: number) => Promise<void>;
46
+ deadlineMs: number;
47
+ }
48
+ export declare function restartMenubarHelper(deps?: MenubarRestartDeps): Promise<MenubarRestartResult>;
32
49
  export declare function enableMenubarService(opts?: {
33
50
  clearOptOut?: boolean;
34
51
  }): Promise<boolean>;
@@ -58,6 +75,7 @@ export declare function menubarPlistNeedsRepoint(opts: {
58
75
  plistNodeExists: boolean;
59
76
  activeEntry: string | null;
60
77
  activeNode: string | null;
78
+ plistRelaunchesCleanExit: boolean;
61
79
  }): boolean;
62
80
  export declare function disableMenubarService(): void;
63
81
  export declare function mayInstallMenubarHelper(opts: {
@@ -22,6 +22,7 @@ export function serviceLabel() {
22
22
  return namespacedServiceLabel(SERVICE_LABEL_BASE);
23
23
  }
24
24
  const MENUBAR_THROTTLE_SECONDS = 30;
25
+ const MENUBAR_BOOTOUT_WAIT_TRIES = 50;
25
26
  function onDarwin() {
26
27
  return process.platform === 'darwin';
27
28
  }
@@ -213,7 +214,10 @@ export function generateServicePlist(execPath) {
213
214
  <key>RunAtLoad</key>
214
215
  <true/>
215
216
  <key>KeepAlive</key>
216
- <true/>
217
+ <dict>
218
+ <key>SuccessfulExit</key>
219
+ <false/>
220
+ </dict>
217
221
  <key>ThrottleInterval</key>
218
222
  <integer>${MENUBAR_THROTTLE_SECONDS}</integer>
219
223
  <key>ProcessType</key>
@@ -229,7 +233,7 @@ ${envXml}
229
233
  </dict>
230
234
  </plist>`;
231
235
  }
232
- export function restartMenubarLaunchAgent(uid, plist, exec = execFileSync) {
236
+ export function restartMenubarLaunchAgent(uid, plist, exec = execFileSync, sleep = sleepSync) {
233
237
  const reg = serviceManagerRegistrationAllowed();
234
238
  if (!reg.allowed) {
235
239
  process.stderr.write(`[agents] ${reg.reason}\n`);
@@ -237,18 +241,28 @@ export function restartMenubarLaunchAgent(uid, plist, exec = execFileSync) {
237
241
  }
238
242
  const serviceTarget = `gui/${uid}/${serviceLabel()}`;
239
243
  const opts = { stdio: ['ignore', 'ignore', 'ignore'] };
240
- try {
241
- exec('launchctl', ['bootout', serviceTarget], opts);
242
- }
243
- catch { }
244
- try {
245
- exec('launchctl', ['bootstrap', `gui/${uid}`, plist], opts);
244
+ const succeeds = (args) => {
245
+ try {
246
+ exec('launchctl', args, opts);
247
+ return true;
248
+ }
249
+ catch {
250
+ return false;
251
+ }
252
+ };
253
+ succeeds(['bootout', serviceTarget]);
254
+ for (let i = 0; i < MENUBAR_BOOTOUT_WAIT_TRIES && succeeds(['print', serviceTarget]); i++)
255
+ sleep(100);
256
+ let bootstrapped = false;
257
+ for (let attempt = 0; attempt < 3 && !bootstrapped; attempt++) {
258
+ if (attempt > 0)
259
+ sleep(500);
260
+ bootstrapped = succeeds(['bootstrap', `gui/${uid}`, plist]);
246
261
  }
247
- catch { }
248
- try {
249
- exec('launchctl', ['kickstart', serviceTarget], opts);
262
+ if (!bootstrapped) {
263
+ process.stderr.write(`[agents] AGI Menu login item could not be registered (launchctl bootstrap gui/${uid} ${plist} failed 3 times); run \`agents menubar setup\`\n`);
250
264
  }
251
- catch { }
265
+ succeeds(['kickstart', serviceTarget]);
252
266
  }
253
267
  export function restartMenubarHelperAfterSwap(uid, ownProcesses, exec = execFileSync, kill = endProcess) {
254
268
  const reg = serviceManagerRegistrationAllowed();
@@ -265,6 +279,50 @@ export function restartMenubarHelperAfterSwap(uid, ownProcesses, exec = execFile
265
279
  kill(p.pid);
266
280
  }
267
281
  }
282
+ export const MENUBAR_RESTART_DEADLINE_MS = 15_000;
283
+ function kickstartDetached(target) {
284
+ return new Promise((resolve) => {
285
+ const child = spawn('launchctl', ['kickstart', '-k', target], { detached: true, stdio: ['ignore', 'ignore', 'pipe'] });
286
+ let stderr = '';
287
+ child.stderr?.on('data', (chunk) => { stderr += chunk.toString(); });
288
+ const timer = setTimeout(() => { stderr = `${stderr}timed out after 10 s`; child.kill('SIGKILL'); }, 10_000);
289
+ child.on('error', (error) => { clearTimeout(timer); resolve({ code: null, stderr: error.message }); });
290
+ child.on('close', (code) => { clearTimeout(timer); resolve({ code, stderr: stderr.trim() }); });
291
+ });
292
+ }
293
+ const defaultRestartDeps = {
294
+ ownPids: () => liveMenubarProcesses().own.map((p) => p.pid),
295
+ kickstart: kickstartDetached,
296
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
297
+ deadlineMs: MENUBAR_RESTART_DEADLINE_MS,
298
+ };
299
+ export async function restartMenubarHelper(deps = defaultRestartDeps) {
300
+ const failed = (detail, previousPids = [], pids = []) => ({ outcome: 'failed', previousPids, pids, detail });
301
+ if (!onDarwin())
302
+ return failed('AGI Menu is macOS only');
303
+ if (menubarDisabledByUser() || !menubarServiceInstalled()) {
304
+ return failed('AGI Menu is turned off; `agents menubar setup` turns it on');
305
+ }
306
+ const registration = serviceManagerRegistrationAllowed();
307
+ if (!registration.allowed)
308
+ return failed(registration.reason);
309
+ const previousPids = deps.ownPids();
310
+ const target = `gui/${process.getuid?.() ?? 0}/${serviceLabel()}`;
311
+ const kick = await deps.kickstart(target);
312
+ if (kick.code !== 0) {
313
+ return failed(`launchctl kickstart -k ${target} failed${kick.stderr ? `: ${kick.stderr}` : ''}`, previousPids, deps.ownPids());
314
+ }
315
+ const deadline = Date.now() + deps.deadlineMs;
316
+ let pids = deps.ownPids();
317
+ while (!(pids.length === 1 && !previousPids.includes(pids[0]))) {
318
+ if (Date.now() >= deadline) {
319
+ return failed(`AGI Menu did not come back as one new process within ${Math.round(deps.deadlineMs / 1000)} s; \`agents menubar setup\` repairs it`, previousPids, pids);
320
+ }
321
+ await deps.sleep(200);
322
+ pids = deps.ownPids();
323
+ }
324
+ return { outcome: 'restarted', previousPids, pids, detail: `AGI Menu restarted (pid ${pids[0]})` };
325
+ }
268
326
  function startMenubarServiceFromSource(opts = {}) {
269
327
  if (!onDarwin())
270
328
  return false;
@@ -400,6 +458,8 @@ export function menubarPlistNeedsRepoint(opts) {
400
458
  return false;
401
459
  if (opts.plistEntry !== opts.activeEntry)
402
460
  return true;
461
+ if (opts.plistRelaunchesCleanExit)
462
+ return true;
403
463
  if (opts.activeNode && (!opts.plistNode || !opts.plistNodeExists))
404
464
  return true;
405
465
  return false;
@@ -422,8 +482,17 @@ function menubarSetupNeedsRepoint() {
422
482
  plistNodeExists: Boolean(plistNode) && fs.existsSync(plistNode),
423
483
  activeEntry: resolveCliEntry(),
424
484
  activeNode: process.execPath,
485
+ plistRelaunchesCleanExit: plistRelaunchesCleanExit(),
425
486
  });
426
487
  }
488
+ function plistRelaunchesCleanExit() {
489
+ try {
490
+ return /<key>KeepAlive<\/key>\s*<true\/>/.test(fs.readFileSync(servicePlistPath(), 'utf-8'));
491
+ }
492
+ catch {
493
+ return false;
494
+ }
495
+ }
427
496
  export function disableMenubarService() {
428
497
  if (!onDarwin())
429
498
  return;
@@ -1,4 +1,5 @@
1
1
  import { writerProcessView } from './process-view.js';
2
+ import { span, spanSync } from '../daemon/diagnostics.js';
2
3
  import * as fs from 'fs';
3
4
  import * as path from 'path';
4
5
  import * as os from 'os';
@@ -1249,11 +1250,12 @@ export async function getActiveSessions(opts = {}) {
1249
1250
  const { loadLocalActiveSessions } = await import('./session-cache.js');
1250
1251
  return (await loadLocalActiveSessions()).sessions;
1251
1252
  }
1253
+ const count = (rows) => () => ({ rows: rows.length });
1252
1254
  const [tmuxAgents, teams, terminals, cloud] = await Promise.all([
1253
- listTmuxAgentSessions().catch(() => []),
1254
- listTeamsActive({ localOnly: opts.localOnly }).catch(() => []),
1255
- listTerminalsActive().catch(() => []),
1256
- Promise.resolve(listCloudActive()),
1255
+ span('active.tmux', () => listTmuxAgentSessions().catch(() => [])),
1256
+ span('active.teams', () => listTeamsActive({ localOnly: opts.localOnly }).catch(() => [])),
1257
+ span('active.terminals', () => listTerminalsActive().catch(() => [])),
1258
+ Promise.resolve(spanSync('active.cloud', () => listCloudActive())),
1257
1259
  ]);
1258
1260
  const knownPids = new Set();
1259
1261
  for (const s of tmuxAgents)
@@ -1265,17 +1267,19 @@ export async function getActiveSessions(opts = {}) {
1265
1267
  for (const s of terminals)
1266
1268
  if (s.pid)
1267
1269
  knownPids.add(s.pid);
1268
- const unattributed = opts.skipHeadless ? [] : await listUnattributedActive(knownPids);
1270
+ const unattributed = opts.skipHeadless ? [] : await span('active.unattributed', () => listUnattributedActive(knownPids));
1269
1271
  const merged = dedupeBySession([...tmuxAgents, ...teams, ...terminals, ...cloud, ...unattributed]);
1270
- await enrichProvenance(merged);
1271
- await resolveOrigins(merged);
1272
- foldPresence(merged);
1273
- await foldTmuxClients(merged);
1274
- foldHostLink(merged);
1275
- foldExecutionMachine(merged, recordedMachineLookup(merged), machineId());
1276
- annotateOrchestratorLabels(merged);
1277
- foldRecap(merged);
1278
- foldPhase(merged);
1272
+ await span('active.provenance', () => enrichProvenance(merged), count(merged));
1273
+ await span('active.origins', () => resolveOrigins(merged), count(merged));
1274
+ spanSync('active.fold-presence', () => foldPresence(merged), count(merged));
1275
+ await span('active.tmux-clients', () => foldTmuxClients(merged));
1276
+ spanSync('active.fold', () => {
1277
+ foldHostLink(merged);
1278
+ foldExecutionMachine(merged, recordedMachineLookup(merged), machineId());
1279
+ annotateOrchestratorLabels(merged);
1280
+ foldRecap(merged);
1281
+ foldPhase(merged);
1282
+ }, count(merged));
1279
1283
  return merged;
1280
1284
  }
1281
1285
  export async function describeActiveDiscoveryHealth() {
@@ -1,4 +1,5 @@
1
1
  import fs from 'fs';
2
+ import { spanSync } from '../daemon/diagnostics.js';
2
3
  import path from 'path';
3
4
  import { execFileSync } from 'child_process';
4
5
  import { hostProcessView, writerProcessView } from './process-view.js';
@@ -29,12 +30,14 @@ function pidExists(pid) {
29
30
  }
30
31
  }
31
32
  function darwinStartTime(pid) {
32
- try {
33
- return execFileSync('ps', ['-p', String(pid), '-o', 'lstart='], { encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'] }).trim() || undefined;
34
- }
35
- catch {
36
- return undefined;
37
- }
33
+ return spanSync('proc.ps-start-time', () => {
34
+ try {
35
+ return execFileSync('ps', ['-p', String(pid), '-o', 'lstart='], { encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'] }).trim() || undefined;
36
+ }
37
+ catch {
38
+ return undefined;
39
+ }
40
+ });
38
41
  }
39
42
  function processStartTimeMs(value) {
40
43
  return typeof value === 'string' ? Date.parse(value.trim().replace(/\s+/g, ' ')) : NaN;
@@ -1,5 +1,7 @@
1
- import { type FilterOptions, type SessionMeta, type ViewMode } from '@phnx-labs/sessions-cli/reader';
1
+ import { type FileChange, type FilterOptions, type SessionEvent, type SessionMeta, type TodoProgress, type ViewMode } from '@phnx-labs/sessions-cli/reader';
2
+ import type { changeCounts, detectTestResult, extractArtifacts, extractHooks, extractLinks, extractSkills, toolHistogram } from '@phnx-labs/sessions-cli/reader';
2
3
  import type { ActiveSession } from './active.js';
4
+ import { type SessionAgeParts } from './relative-time.js';
3
5
  export declare function signalBadges(s: Pick<ActiveSession, 'awaitingReason' | 'pr' | 'worktree' | 'ticket'>): string;
4
6
  export interface TranscriptRenderOptions {
5
7
  json?: boolean;
@@ -19,3 +21,107 @@ export declare function renderSessionLogJson(session: SessionMeta): Promise<void
19
21
  export declare function renderSession(session: SessionMeta, mode: ViewMode, filters: FilterOptions, options?: {
20
22
  redact?: boolean;
21
23
  }): Promise<void>;
24
+ export declare function formatTodoCompact(todos?: Pick<TodoProgress, 'done' | 'total' | 'activeForm'> | null): string;
25
+ export declare function statusColor(status: ActiveSession['status']): (s: string) => string;
26
+ export declare function cleanPreview(text: string): string;
27
+ export declare function buildSessionDescription(s: ActiveSession): string;
28
+ export declare function liveGlyphAndPreview(a: ActiveSession | undefined): {
29
+ glyph: string;
30
+ preview: string;
31
+ };
32
+ export declare function liveStatusWord(a: ActiveSession | undefined): string;
33
+ export declare function isAwaitingUser(s: ActiveSession): boolean;
34
+ export declare function shortCwd(cwd?: string): string;
35
+ export declare const LIVE_STATUS_W = 8;
36
+ export declare function liveStatusCell(live: ActiveSession | undefined): {
37
+ cell: string;
38
+ width: number;
39
+ };
40
+ export declare function linkTicketCell(s: Pick<SessionMeta, 'ticketId' | 'prNumber' | 'prUrl'>, label: string): string;
41
+ export declare function linkCwdCell(s: Pick<SessionMeta, 'cwd' | '_remote'>, label: string): string;
42
+ export declare function formatLiveStatusHeadline(live: ActiveSession | undefined, bookmarked?: boolean): string;
43
+ export declare function teamTag(session: SessionMeta): string;
44
+ export declare function teamBadge(session: SessionMeta): {
45
+ plain: string;
46
+ width: number;
47
+ };
48
+ export declare function originTag(session: SessionMeta): string;
49
+ export declare function timeCell(age: SessionAgeParts, topicSlack: number): {
50
+ plain: string;
51
+ text: string;
52
+ extraW: number;
53
+ };
54
+ export declare function flatSessionRow(session: SessionMeta, live?: ActiveSession, showTicket?: boolean, cols?: PickerColumns, bookmarked?: boolean): string;
55
+ export declare function treeSessionRow(session: SessionMeta, live?: ActiveSession): string;
56
+ export declare function printSessionTable(sessions: SessionMeta[], hiddenCount?: number, tree?: boolean, liveIndex?: Map<string, ActiveSession>): void;
57
+ export declare function renderTopicCell(label: string | undefined | null, topic: string | undefined | null, query: string, visibleWidth: number, paddedWidth: number): string;
58
+ export interface SshOriginTag {
59
+ device?: string;
60
+ }
61
+ export interface PickerColumns {
62
+ showMachine?: boolean;
63
+ machineLabel?: (m: string) => string;
64
+ machineWidth?: number;
65
+ showModel?: boolean;
66
+ modelWidth?: number;
67
+ showTicket?: boolean;
68
+ showHost?: boolean;
69
+ showBookmark?: boolean;
70
+ showStatus?: boolean;
71
+ gutter?: number;
72
+ }
73
+ export declare function machineLabeler(machines: string[]): (m: string) => string;
74
+ export declare function pickerColumnsFor(sessions: SessionMeta[]): PickerColumns;
75
+ export declare function liveHostLabel(a: ActiveSession | undefined): string;
76
+ export declare function formatPickerLabel(s: SessionMeta, query: string, cols?: PickerColumns, ssh?: SshOriginTag, host?: string, bookmarked?: boolean, live?: ActiveSession): string;
77
+ export declare function formatPickerTip(sessions: SessionMeta[]): string;
78
+ export declare function formatTeamHiddenFooter(hiddenCount: number): string;
79
+ export declare function notFoundByIdMessage(query: string): string[];
80
+ export interface SessionPreviewDigest {
81
+ schemaVersion: 1;
82
+ firstUser: string;
83
+ lastAssistant: string;
84
+ filesRead: number;
85
+ toolCalls: number;
86
+ planFile: string;
87
+ todos?: TodoProgress;
88
+ subAgentCount: number;
89
+ backgroundShellCount?: number;
90
+ toolTags: string[];
91
+ changes: ReturnType<typeof changeCounts>;
92
+ changedFiles: FileChange[];
93
+ dirs: string[];
94
+ repos: string[];
95
+ artifacts: ReturnType<typeof extractArtifacts>;
96
+ skills: ReturnType<typeof extractSkills>;
97
+ plugins: string[];
98
+ hooks: ReturnType<typeof extractHooks>;
99
+ links: ReturnType<typeof extractLinks>;
100
+ errorCount: number;
101
+ firstError?: string;
102
+ toolHistogram: ReturnType<typeof toolHistogram>;
103
+ test: ReturnType<typeof detectTestResult>;
104
+ partial?: boolean;
105
+ partialReason?: string;
106
+ }
107
+ export interface SessionDetailMessage {
108
+ role: 'user' | 'assistant';
109
+ text: string;
110
+ at: string | null;
111
+ }
112
+ export declare function sessionTranscriptStamp(session: SessionMeta): {
113
+ fileMtimeMs: number;
114
+ fileSize: number;
115
+ } | undefined;
116
+ export declare function buildSessionDetailBlock(session: SessionMeta, digest: SessionPreviewDigest | undefined, events: SessionEvent[], sourceStamp?: {
117
+ fileMtimeMs: number;
118
+ fileSize: number;
119
+ }): {
120
+ request: unknown;
121
+ timeline: unknown;
122
+ files: unknown;
123
+ messages: SessionDetailMessage[];
124
+ sourceRevision: string | null;
125
+ partial: boolean;
126
+ reason: string | null;
127
+ };