@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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,47 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.23.2
4
+
5
+ - **AGI Menu 1.15.21: Restart AGI Menu, and Quit no longer turns it off (PHNX-4325).** Settings → AGI Menu has a Restart button and the right-click menu has Restart AGI Menu (⌘R); both run `agents menubar restart`. Quit AGI Menu only quits, and the app returns at the next login. The new Turn off AGI Menu… asks first, then runs `agents menubar disable` as Quit used to. Settings → Tabs names the agents-cli version an unavailable tab needs. Several failing CLI calls finishing at once no longer crash the app. Source: `cli/src/lib/helper-versions.ts`.
6
+
7
+ - **Re-registering AGI Menu's login item no longer leaves the menu stopped.** `launchctl bootout` returns before launchd finishes removing the job, so the immediate `bootstrap` failed with `5: Input/output error` and the menu stayed down until the next login. Every setup, enable and startup repair that rewrites the plist took this path, including the one-time `KeepAlive` rewrite in 1.23.1. The CLI now waits for the old job to leave (up to 5 seconds), retries a refused bootstrap twice, and prints an error naming `agents menubar setup` if registration still fails. Source: `cli/src/lib/menubar/install-menubar.ts`.
8
+
9
+ ## 1.23.1
10
+
11
+ - **`agents ps preview <id>` shows the rich session card (PHNX-4227).** It is the
12
+ same command as `agents sessions preview` with the same flags, JSON envelope,
13
+ durable remote-preview cache and exit codes; `sessions preview` and
14
+ `sessions --preview` keep working unchanged, and peers are still asked with the
15
+ old `sessions preview` argv so a not-yet-upgraded device answers. Source:
16
+ `cli/src/commands/ps.ts`, `cli/src/lib/session/presentation.ts`.
17
+
18
+ - **AGI Menu 1.15.20: the GitHub tab gets a Mine chip and a folded Other repos (PHNX-4269).** Mine lists only the pull requests you opened. Other repos (repositories no project links) folds under its header while Needs me or a project group leads. Titles no longer stay slid sideways after the pointer leaves a row. Source: `cli/src/lib/helper-versions.ts`.
19
+
20
+ - **`agents menubar restart [--json]` restarts the running AGI Menu (PHNX-4325).** It runs
21
+ `launchctl kickstart -k` on the AGI Menu login item in its own session, so the restart
22
+ finishes even when AGI Menu itself asked for it, then waits up to 15 seconds for exactly
23
+ one new process. JSON reports `outcome` (`restarted` or `failed`), `previousPids`, `pids`
24
+ and `detail`; a turned-off AGI Menu, a failed kickstart, or no new process exits 1 with
25
+ the reason. AGI Menu's Settings and right-click menu call it. Source:
26
+ `cli/src/lib/menubar/install-menubar.ts`, `cli/src/commands/menubar.ts`.
27
+ - **Quitting AGI Menu now lasts until the next login (PHNX-4325).** The login item's
28
+ `KeepAlive` is `{SuccessfulExit: false}`: launchd relaunches AGI Menu after a crash but
29
+ not after a clean Quit, which previously came back within 30 seconds. The startup repair
30
+ rewrites an older plist once. Source: `cli/src/lib/menubar/install-menubar.ts`.
31
+
32
+ - **The daemon log says why it restarted (PHNX-4225).** `agents daemon logs` now
33
+ carries levels (`debug`, `info`, `warn`, `error`) and structured `data` on each
34
+ line. Every supervised tick is timed: a tick over half its deadline logs
35
+ `tick.slow`, and a deadline breach logs `tick.breach` with every in-flight tick,
36
+ the synchronous sections that ran during it, and the daemon's CPU, memory,
37
+ event-loop delay and load. A once-a-minute `vitals` line and `loop.stall` /
38
+ `span.slow` warnings attribute event-loop blocking to named sections, including
39
+ the feed hub and active-session discovery, which run outside the supervisor.
40
+ `agents daemon logs level debug` traces every tick and section and applies live;
41
+ `agents daemon logs level info` turns it back off. The usage-refresh and
42
+ active-sessions summaries are now structured log lines instead of raw stdout.
43
+ Source: `cli/src/lib/daemon/diagnostics.ts`, `cli/src/lib/daemon/supervisor.ts`.
44
+
3
45
  ## 1.23.0
4
46
 
5
47
  ### Removed
package/README.md CHANGED
@@ -1416,6 +1416,8 @@ agents daemon services disable browser-ipc # stop hosting browser IPC without s
1416
1416
  agents browser stop --service # browser-scoped alias; next browser action requiring IPC re-enables it
1417
1417
  agents routines stop # disable/reload only the scheduler service
1418
1418
  agents daemon logs -f --level warn --since 1h
1419
+ agents daemon logs --level error --since 1h # each restart, with what was running when it happened
1420
+ agents daemon logs level debug # trace every tick and slow section, live; `level info` turns it off
1419
1421
  agents daemon doctor # one-shot health check; non-zero exit on problems
1420
1422
 
1421
1423
  agents daemon index roots # transcript directories the indexer scans (JSON)
@@ -4,8 +4,7 @@ import { interruptibleSpinner } from '../lib/spinner.js';
4
4
  const DEFAULT_LIMIT = '50';
5
5
  export async function runCloudTranscripts(query, options) {
6
6
  const { discoverCloudSessions, ensureCloudSessionCached } = await import('../lib/session/cloud.js');
7
- const { buildFilterOptions, resolveViewMode, renderSession } = await import('../lib/session/presentation.js');
8
- const { printSessionTable } = await import('./sessions.js');
7
+ const { buildFilterOptions, printSessionTable, resolveViewMode, renderSession } = await import('../lib/session/presentation.js');
9
8
  let filterOpts;
10
9
  try {
11
10
  filterOpts = buildFilterOptions(options);
@@ -7,7 +7,8 @@ import { getDaemonStatus, isDaemonRunning, readDaemonLog, startDaemon, stopDaemo
7
7
  import { listDaemonRunProcesses } from '../lib/daemon/leaked-daemons.js';
8
8
  import { getConfigValue, setConfigValue, isDaemonEnabled } from '../lib/device-config.js';
9
9
  import { readSubsystemHealth, readAllSubsystemHealth, SUBSYSTEM_DAEMON_START, } from '../lib/daemon-health.js';
10
- import { DAEMON_SERVICE_IDS, listDaemonServiceStates, setDaemonServiceEnabled, getDaemonServicesConfigPath, queueDaemonServiceRestart, } from '../lib/daemon-services.js';
10
+ import { DAEMON_SERVICE_IDS, listDaemonServiceStates, setDaemonServiceEnabled, getDaemonServicesConfigPath, queueDaemonServiceRestart, readDaemonLogLevel, writeDaemonLogLevel, } from '../lib/daemon-services.js';
11
+ import { LOG_LEVELS, levelRank, parseLogLevel } from '../lib/daemon/diagnostics.js';
11
12
  import { listJobs, getLatestRun } from '../lib/scheduling/routines.js';
12
13
  import { JobScheduler } from '../lib/scheduler.js';
13
14
  import { followFile } from '../lib/log-follow.js';
@@ -376,14 +377,9 @@ function parseLogLines(raw) {
376
377
  }
377
378
  return out;
378
379
  }
379
- const LEVEL_RANK = { INFO: 0, WARN: 1, ERROR: 2 };
380
380
  function passesFilters(entry, minLevel, sinceMs) {
381
- if (minLevel) {
382
- const min = LEVEL_RANK[minLevel.toUpperCase()] ?? 0;
383
- const level = LEVEL_RANK[entry.level.toUpperCase()] ?? 0;
384
- if (level < min)
385
- return false;
386
- }
381
+ if (minLevel && levelRank(entry.level) < levelRank(minLevel))
382
+ return false;
387
383
  if (sinceMs !== undefined && Date.parse(entry.ts) < sinceMs)
388
384
  return false;
389
385
  return true;
@@ -391,8 +387,38 @@ function passesFilters(entry, minLevel, sinceMs) {
391
387
  function printLogEntry(entry) {
392
388
  const color = entry.level === 'ERROR' ? chalk.red : entry.level === 'WARN' ? chalk.yellow : chalk.gray;
393
389
  console.log(`${chalk.gray(entry.ts)} ${color(entry.level.padEnd(5))} ${entry.message}`);
390
+ if (entry.data && (entry.level === 'ERROR' || entry.level === 'WARN'))
391
+ console.log(chalk.gray(` ${JSON.stringify(entry.data)}`));
392
+ }
393
+ function assertLogLevelOption(level) {
394
+ if (level !== undefined && !parseLogLevel(level)) {
395
+ throw new Error(`--level must be one of ${LOG_LEVELS.join(', ').toLowerCase()} (got '${level}')`);
396
+ }
397
+ }
398
+ function runLogLevel(level, opts) {
399
+ if (level === undefined) {
400
+ const current = readDaemonLogLevel().toLowerCase();
401
+ if (opts.json)
402
+ console.log(JSON.stringify({ level: current }));
403
+ else
404
+ console.log(current);
405
+ return;
406
+ }
407
+ const parsed = parseLogLevel(level);
408
+ if (!parsed)
409
+ throw new Error(`log level must be one of ${LOG_LEVELS.join(', ').toLowerCase()} (got '${level}')`);
410
+ writeDaemonLogLevel(parsed);
411
+ const applied = signalDaemonReload();
412
+ if (opts.json) {
413
+ console.log(JSON.stringify({ level: parsed.toLowerCase(), applied }));
414
+ return;
415
+ }
416
+ console.log(applied
417
+ ? chalk.green(`Daemon log level set to ${parsed.toLowerCase()}.`) + chalk.gray(' Applied live. Follow it: agents daemon logs -f')
418
+ : chalk.yellow(`Daemon log level set to ${parsed.toLowerCase()} in ${getDaemonServicesConfigPath()}, but the reload signal was not delivered; it applies on the next daemon start.`));
394
419
  }
395
420
  async function runLogs(opts) {
421
+ assertLogLevelOption(opts.level);
396
422
  const sinceMs = opts.since ? Date.now() - (parseDuration(opts.since) ?? 0) * 1000 : undefined;
397
423
  const lineCount = opts.lines ? parseInt(opts.lines, 10) : 50;
398
424
  if (opts.follow) {
@@ -655,6 +681,9 @@ export function registerDaemonCommand(program) {
655
681
  # Tail the daemon's own log, warnings and up, from the last hour
656
682
  agents daemon logs -f --level warn --since 1h
657
683
 
684
+ # Trace every service tick and slow section while diagnosing (applies live)
685
+ agents daemon logs level debug
686
+
658
687
  # One-shot health check for scripts (non-zero exit on problems)
659
688
  agents daemon doctor
660
689
 
@@ -892,17 +921,47 @@ export function registerDaemonCommand(program) {
892
921
  registerWebhooksSubcommand(cmd);
893
922
  registerFunnelCommand(cmd);
894
923
  registerDaemonIndexCommand(cmd);
895
- cmd.command('logs')
896
- .description('Read the daemon\'s own log (lifecycle + subsystem errors — not routine run output).')
924
+ const logsCmd = cmd.command('logs')
925
+ .description('Read the daemon\'s own log: lifecycle, every service tick, slow sections, event-loop stalls, and per-minute vitals (not routine run output).')
897
926
  .option('-n, --lines <number>', 'Show this many recent lines', '50')
898
927
  .option('-f, --follow', 'Stream new lines as they are written (like tail -f)')
899
- .option('--level <level>', 'Minimum level to show: info | warn | error')
928
+ .option('--level <level>', 'Minimum level to show: debug | info | warn | error')
900
929
  .option('--since <dur>', 'Only lines newer than this (e.g. 1h, 30m)')
901
930
  .option('--json', 'Emit each line as JSON')
902
931
  .action(async (opts, command) => {
903
932
  const merged = command.optsWithGlobals();
904
933
  await runLogs({ lines: opts.lines, follow: opts.follow, level: opts.level, since: opts.since, json: merged.json === true || opts.json === true });
905
934
  });
935
+ logsCmd.command('level [level]')
936
+ .description('Show or set what the daemon writes: debug (every tick and span) | info (default) | warn | error. Applies live.')
937
+ .option('--json', 'Emit as JSON')
938
+ .action((level, opts, command) => {
939
+ runLogLevel(level, { json: command.optsWithGlobals().json === true || opts.json === true });
940
+ });
941
+ setHelpSections(logsCmd, {
942
+ examples: `
943
+ # Why did it restart? Errors carry a snapshot: in-flight ticks, slow sections, vitals
944
+ agents daemon logs --level error --since 1h
945
+
946
+ # Event-loop stalls and slow synchronous sections, as they happen
947
+ agents daemon logs -f --level warn
948
+
949
+ # Turn on per-tick and per-span tracing while you diagnose, then turn it back off
950
+ agents daemon logs level debug
951
+ agents daemon logs -f --level debug
952
+ agents daemon logs level info
953
+
954
+ # Machine-readable, with each line's structured data
955
+ agents daemon logs --since 10m --json
956
+ `,
957
+ notes: `
958
+ Every line is JSON in the daemon log file (agents daemon status shows the path), with
959
+ an optional data object. Event names: tick.slow, tick.failed, tick.breach, loop.stall,
960
+ span.slow, vitals (once a minute), and at debug tick.start, tick.ok, span.
961
+ The level is stored as logLevel in the daemon's services.yaml. Debug writes a line per
962
+ tick and per section synchronously, so leave it on only while diagnosing.
963
+ `,
964
+ });
906
965
  cmd.command('doctor')
907
966
  .description('One-shot health check: identity, duplicates, hosted services, scheduler. Non-zero exit on problems.')
908
967
  .option('--json', 'Emit as JSON')
@@ -846,7 +846,7 @@ ${formatModeSupportTable().split('\n').map((line) => ` ${line}`).join('\n
846
846
  delete process.env.AGENTS_RESUME_SOURCE_JSON;
847
847
  const outcome = injectedSource
848
848
  ? { kind: 'resolved', session: injectedSource }
849
- : await (await import('./sessions.js')).resolveSessionMetadataValue(selector, { agent: runBaseAgentId ?? undefined });
849
+ : await (await import('../lib/session/selection.js')).resolveSessionMetadataValue(selector, { agent: runBaseAgentId ?? undefined });
850
850
  if (outcome.kind === 'partial') {
851
851
  const offline = outcome.failedPeers;
852
852
  console.error(chalk.yellow(`Warning: ${offline.length} device(s) unreachable, not checked: ${offline.join(', ')}`));
@@ -19,8 +19,7 @@ import { registerFeedWatchCommand } from './feed-watch.js';
19
19
  import { AnswerError, answerOwnerIsLocal, checkAnswerDelivery, claimAndRouteAttentionAnswer, forwardFeedAnswer, parseAttentionKey, } from '../lib/feed/answer.js';
20
20
  import { gcMailbox } from '../lib/mailbox-gc.js';
21
21
  import { isValidMailboxId } from '../lib/mailbox.js';
22
- import { getActiveSessions } from '../lib/session/active.js';
23
- import { backfillActiveRowsFromMeta } from './sessions.js';
22
+ import { backfillActiveRowsFromMeta, getActiveSessions } from '../lib/session/active.js';
24
23
  import { mailboxIdForActiveSession } from '../lib/mailbox-target.js';
25
24
  import { GLYPH, masthead } from '../lib/comms-render.js';
26
25
  import { discoverSessions } from '../lib/session/discover.js';
@@ -6,7 +6,10 @@ import { sessionProcessIsLocal, sessionProcessHost, shortIdFromName } from '../l
6
6
  import { isAgentTmuxAlias } from '@phnx-labs/sessions-cli/reader';
7
7
  import { attachLocalLiveSelector } from '../lib/session/local-tmux-attach.js';
8
8
  export { looksLikeTmuxAlias, resolveTmuxAliasState, shouldAttachLocalTmuxAliasBeforeFleet } from '../lib/session/local-tmux-attach.js';
9
- import { buildSessionRecoveryCommand, filterSessionsByQuery, formatLiveStatusHeadline, formatPickerLabel, isRunningLiveSession, pickerColumnsFor, resumeSessionInPlace, resolveSessionMetadataValue, resolveSessionAgentName } from './sessions.js';
9
+ import { isRunningLiveSession } from '../lib/session/active.js';
10
+ import { formatLiveStatusHeadline, formatPickerLabel, pickerColumnsFor } from '../lib/session/presentation.js';
11
+ import { buildSessionRecoveryCommand, resumeSessionInPlace } from '../lib/session/resume-command.js';
12
+ import { filterSessionsByQuery, resolveSessionMetadataValue, resolveSessionAgentName } from '../lib/session/selection.js';
10
13
  import { requestedLiveStatuses } from './ps-roster.js';
11
14
  import { resolveBackend, CONFIRM_THRESHOLD } from './sessions-resume.js';
12
15
  import { runOnPeer } from '../lib/session/remote-list.js';
@@ -7,9 +7,10 @@ import { isSessionIdShape } from '../lib/session/pid-registry.js';
7
7
  import { gatherRemoteActive } from '../lib/session/remote-active.js';
8
8
  import { discoverSessions } from '../lib/session/discover.js';
9
9
  import { deriveShortId } from '../lib/session/short-id.js';
10
- import { mergeLocalFirst, pickSessionInteractive, filterSessionsByQuery, formatPickerLabel, pickerColumnsFor, isUniqueEnoughSelector } from './sessions.js';
10
+ import { formatPickerLabel, pickerColumnsFor } from '../lib/session/presentation.js';
11
+ import { mergeLocalFirst, filterSessionsByQuery, isUniqueEnoughSelector } from '../lib/session/selection.js';
11
12
  import { dedupeByMachineSession, matchesLiveStatus } from './ps-roster.js';
12
- import { buildPreview } from './sessions-picker.js';
13
+ import { buildPreview, pickSessionInteractive } from './sessions-picker.js';
13
14
  import { multiItemPicker } from '../lib/picker.js';
14
15
  import { isPromptCancelled } from './utils.js';
15
16
  import { machineId } from '../lib/session/sync/config.js';
@@ -1,6 +1,6 @@
1
1
  import chalk from 'chalk';
2
2
  import { discoverSessions, resolveSessionById } from '../lib/session/discover.js';
3
- import { parseAgentFilter } from './sessions.js';
3
+ import { parseAgentFilter } from '../lib/session/selection.js';
4
4
  import { renderSessionLog, renderSessionLogJson } from '../lib/session/presentation.js';
5
5
  import { runSessions } from '../lib/sessions-client.js';
6
6
  import { showHostTaskLog, hostTaskLogJson } from '../lib/hosts/logs.js';
@@ -1,6 +1,6 @@
1
1
  import chalk from 'chalk';
2
2
  import { setHelpSections } from '../lib/help.js';
3
- import { updateMenubarHelperIfNewer, enableMenubarService, disableMenubarService, getMenubarStatus, runMenubarSetup, buildMenubarDoctorReport, } from '../lib/menubar/install-menubar.js';
3
+ import { updateMenubarHelperIfNewer, enableMenubarService, disableMenubarService, getMenubarStatus, restartMenubarHelper, runMenubarSetup, buildMenubarDoctorReport, } from '../lib/menubar/install-menubar.js';
4
4
  function notMac() {
5
5
  if (process.platform !== 'darwin') {
6
6
  console.log(chalk.yellow('AGI Menu is macOS only.'));
@@ -14,7 +14,7 @@ function printStatus(s, opts = {}) {
14
14
  console.log(` running ${yn(s.running)}`);
15
15
  console.log(` service installed ${yn(s.serviceInstalled)}`);
16
16
  if (opts.brief) {
17
- console.log(chalk.gray('\n setup | enable | disable | status'));
17
+ console.log(chalk.gray('\n setup | restart | enable | disable | status'));
18
18
  return;
19
19
  }
20
20
  console.log(` app installed ${s.installedApp ? chalk.gray(s.installedApp) : chalk.gray('no')}`);
@@ -119,6 +119,30 @@ export function registerMenubarCommands(program) {
119
119
  after this command exits. Check-only never installs or restarts the app.
120
120
  `,
121
121
  });
122
+ const restart = menubar.command('restart')
123
+ .description('Restart the running AGI Menu through its login item')
124
+ .option('--json', 'Emit machine-readable restart result')
125
+ .action(async (options) => {
126
+ const result = await restartMenubarHelper();
127
+ if (options.json)
128
+ process.stdout.write(`${JSON.stringify(result)}\n`);
129
+ else
130
+ console.log(result.outcome === 'failed' ? chalk.red(result.detail) : chalk.green(result.detail));
131
+ if (result.outcome === 'failed')
132
+ process.exitCode = 1;
133
+ });
134
+ setHelpSections(restart, {
135
+ examples: `
136
+ agents menubar restart
137
+ agents menubar restart --json
138
+ `,
139
+ notes: `
140
+ Restarts AGI Menu with launchctl kickstart -k and waits up to 15 seconds
141
+ for exactly one new process. The kickstart runs in its own session, so
142
+ the restart completes even when AGI Menu itself requested it. A turned-off
143
+ AGI Menu is refused rather than started; \`agents menubar setup\` turns it on.
144
+ `,
145
+ });
122
146
  const setup = menubar
123
147
  .command('setup')
124
148
  .description('Configure AGI Menu end-to-end: one instance, started at login')
@@ -163,7 +187,8 @@ export function registerMenubarCommands(program) {
163
187
  Configures, in order: every running helper ended, AGI Menu at
164
188
  ~/Library/Application Support/agents-cli/MenubarHelper.app, its code
165
189
  signature, the launchd login item (com.phnx-labs.agents-menubar —
166
- RunAtLoad + KeepAlive), then verifies exactly one helper came back up.
190
+ RunAtLoad, relaunched after a crash but not after Quit), then verifies
191
+ exactly one helper came back up.
167
192
 
168
193
  Every running helper is ended and launchd restarts one, so the survivor is
169
194
  always the login-managed copy. Exits nonzero if it cannot reach that state.
@@ -11,17 +11,8 @@ export interface LiveStatusFlags {
11
11
  queued?: boolean;
12
12
  unknown?: boolean;
13
13
  }
14
- export declare function statusColor(status: ActiveSession['status']): (s: string) => string;
15
- export declare function cleanPreview(text: string): string;
16
- export declare function buildSessionDescription(s: ActiveSession): string;
17
14
  export declare function formatActiveRowDescription(s: ActiveSession): string;
18
15
  export declare function indexActiveBySessionId(active: ActiveSession[]): Map<string, ActiveSession>;
19
- export declare function liveGlyphAndPreview(a: ActiveSession | undefined): {
20
- glyph: string;
21
- preview: string;
22
- };
23
- export declare function liveStatusWord(a: ActiveSession | undefined): string;
24
- export declare function isAwaitingUser(s: ActiveSession): boolean;
25
16
  export declare function renderActiveRowLines(s: ActiveSession, indent: string, termW: number): string[];
26
17
  export declare function ownerLabel(s: ActiveSession): string;
27
18
  interface ActiveSessionsLayout {
@@ -48,8 +39,6 @@ interface MachineGroupedLayout {
48
39
  export declare function groupSessionsByMachine(sessions: ActiveSession[], localMachine: string): MachineGroupedLayout;
49
40
  export declare function dedupeByMachineSession(sessions: ActiveSession[]): ActiveSession[];
50
41
  export declare function filterActiveSessionsByHostScope(sessions: ActiveSession[], hosts: string[] | undefined, self: string): ActiveSession[];
51
- export declare function shouldIncludeLocal(hosts: string[] | undefined, self: string): boolean;
52
- export declare function remoteHostsToDial(hosts: string[] | undefined, self: string): string[] | undefined;
53
42
  export declare function gatherActiveSessions(opts?: {
54
43
  local?: boolean;
55
44
  hosts?: string[];
@@ -1,76 +1,22 @@
1
1
  import * as path from 'path';
2
2
  import chalk from 'chalk';
3
3
  import { sessionDisplayAgent, linkUrl } from '@phnx-labs/sessions-cli/reader';
4
- import { toComparablePath, homeDir } from '../lib/platform/index.js';
5
4
  import { getActiveSessions, describeActiveDiscoveryHealth, sessionProcessIsLocal, backfillActiveRowsFromIndex, isRunningLiveSession, serializeActiveSessionsForJson, } from '../lib/session/active.js';
6
5
  import { enumerateGhosttyTabs, assignGhosttyTabs } from '../lib/session/ghostty-tabs.js';
7
6
  import { mapPanesToTargets, listClients } from '../lib/tmux/session.js';
8
7
  import { resolveViewingIn, viewingInLabel } from '../lib/session/viewing-in.js';
9
8
  import { machineId, normalizeHost } from '../lib/session/sync/config.js';
10
9
  import { gatherRemoteActive } from '../lib/session/remote-active.js';
10
+ import { hostToken, remoteHostsToDial, shouldIncludeLocal } from '../lib/session/remote-list.js';
11
11
  import { loadFleetActiveSessions, loadLocalActiveSessions } from '../lib/session/session-cache.js';
12
12
  import { stringWidth, truncateToWidth, padToWidth, terminalWidth } from '../lib/session/width.js';
13
13
  import { formatCompactAge } from '../lib/session/relative-time.js';
14
14
  import { colorAgent } from '../lib/agents.js';
15
15
  import { fuzzyMatch, FUZZY_PRESETS } from '../lib/fuzzy.js';
16
16
  import { listBookmarks } from '../lib/session/bookmarks.js';
17
- import { signalBadges } from '../lib/session/presentation.js';
18
- import { formatTodoCompact, githubRepoUrlFromCwd } from './sessions-picker.js';
17
+ import { cleanPreview, formatTodoCompact, isAwaitingUser, shortCwd, signalBadges, statusColor } from '../lib/session/presentation.js';
18
+ import { githubRepoUrlFromCwd } from './sessions-picker.js';
19
19
  import { isInteractiveTerminal } from './utils.js';
20
- function shortCwd(cwd) {
21
- if (!cwd)
22
- return '-';
23
- const home = homeDir();
24
- return toComparablePath(cwd).startsWith(toComparablePath(home))
25
- ? '~' + cwd.slice(home.length)
26
- : cwd;
27
- }
28
- export function statusColor(status) {
29
- switch (status) {
30
- case 'running': return chalk.green;
31
- case 'idle': return chalk.gray;
32
- case 'queued': return chalk.blue;
33
- case 'input_required': return chalk.yellow;
34
- case 'closed': return chalk.dim;
35
- case 'abandoned': return chalk.red;
36
- case 'crashed': return chalk.redBright;
37
- case 'orphaned': return chalk.yellow;
38
- case 'unknown': return chalk.magenta;
39
- }
40
- }
41
- export function cleanPreview(text) {
42
- // eslint-disable-next-line no-control-regex
43
- return text
44
- .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, '')
45
- .replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '')
46
- .replace(/<\/?(?:local-command-stdout|command-name|command-message|command-args|task-notification|system-reminder)>/g, '')
47
- .replace(/\s+/g, ' ')
48
- .trim();
49
- }
50
- export function buildSessionDescription(s) {
51
- const todo = formatTodoCompact(s.todos);
52
- if (s.context === 'cloud') {
53
- const base = s.preview || `${s.cloudProvider ?? ''}${s.cloudTaskId ? ` · ${s.cloudTaskId.slice(0, 12)}` : ''}`;
54
- return cleanPreview([todo, base].filter(Boolean).join(' · '));
55
- }
56
- if (s.context === 'teams') {
57
- const parts = [s.teamName];
58
- if (s.label && s.label !== s.teamName)
59
- parts.push(s.label);
60
- const orch = s.orchestratorLabel || (s.orchestratorSessionId ? s.orchestratorSessionId.slice(0, 8) : '');
61
- if (orch)
62
- parts.push(`by ${orch}`);
63
- if (todo)
64
- parts.push(todo);
65
- const target = s.preview || s.assignedTask || s.topic;
66
- if (target)
67
- parts.push(target);
68
- return cleanPreview(parts.filter(Boolean).join(' · '));
69
- }
70
- // ladder-exempt: compact live preview base, not the row's headline.
71
- const base = s.preview || s.label || s.topic || '';
72
- return cleanPreview([todo, base].filter(Boolean).join(' · '));
73
- }
74
20
  export function formatActiveRowDescription(s) {
75
21
  const parts = [];
76
22
  const pushText = (t) => {
@@ -122,52 +68,6 @@ export function indexActiveBySessionId(active) {
122
68
  }
123
69
  return byId;
124
70
  }
125
- export function liveGlyphAndPreview(a) {
126
- if (!a)
127
- return { glyph: '', preview: '' };
128
- if (a.status === 'abandoned')
129
- return { glyph: statusColor(a.status)('⊘'), preview: buildSessionDescription(a) };
130
- if (a.status === 'closed')
131
- return { glyph: statusColor(a.status)('×'), preview: buildSessionDescription(a) };
132
- if (a.status === 'crashed')
133
- return { glyph: statusColor(a.status)('✗'), preview: buildSessionDescription(a) };
134
- if (a.status === 'orphaned')
135
- return { glyph: statusColor(a.status)('◍'), preview: buildSessionDescription(a) };
136
- const waiting = a.status === 'input_required' || a.activity === 'waiting_input';
137
- const running = a.status === 'running' || a.activity === 'working';
138
- const unknown = a.status === 'unknown';
139
- const shape = waiting ? '◐'
140
- : running ? '●'
141
- : unknown ? '◌'
142
- : '○';
143
- return { glyph: statusColor(a.status)(shape), preview: buildSessionDescription(a) };
144
- }
145
- export function liveStatusWord(a) {
146
- if (!a)
147
- return '';
148
- if (a.status === 'closed' || a.status === 'abandoned')
149
- return a.status;
150
- if (a.status === 'crashed')
151
- return 'crashed';
152
- if (a.status === 'orphaned')
153
- return 'orphan';
154
- if (a.status === 'input_required' || a.activity === 'waiting_input')
155
- return 'waiting';
156
- if (a.status === 'running' || a.activity === 'working')
157
- return 'working';
158
- if (a.status === 'idle' || a.activity === 'idle')
159
- return 'idle';
160
- if (a.status === 'queued')
161
- return 'queued';
162
- return '';
163
- }
164
- export function isAwaitingUser(s) {
165
- if (s.status === 'crashed' || s.status === 'closed')
166
- return false;
167
- if (s.status === 'abandoned' && s.pidAlive !== true)
168
- return false;
169
- return s.status === 'input_required' || s.activity === 'waiting_input';
170
- }
171
71
  function locatorBadge(s) {
172
72
  const p = s.provenance;
173
73
  const parts = [];
@@ -498,19 +398,6 @@ async function enrichTmuxLocators(local, surfaces = []) {
498
398
  }
499
399
  catch { }
500
400
  }
501
- function hostToken(h) {
502
- return normalizeHost(h.split('@').pop() || h);
503
- }
504
- export function shouldIncludeLocal(hosts, self) {
505
- if (!hosts || hosts.length === 0)
506
- return true;
507
- return hosts.some(h => hostToken(h) === self);
508
- }
509
- export function remoteHostsToDial(hosts, self) {
510
- if (!hosts || hosts.length === 0)
511
- return undefined;
512
- return hosts.filter(h => hostToken(h) !== self);
513
- }
514
401
  export async function gatherActiveSessions(opts = {}) {
515
402
  const forceRefresh = opts.forceRefresh === true
516
403
  || process.env.AGENTS_SESSIONS_FORCE_REFRESH === '1';
@@ -4,3 +4,13 @@ export declare const PS_STATUSES: readonly LiveStatusFilter[];
4
4
  export declare function statusFlags(values: string[] | undefined): LiveStatusFlags;
5
5
  export declare function deviceScope(devices: string[] | undefined): string[] | undefined;
6
6
  export declare function registerPsCommand(program: Command): void;
7
+ export declare function registerSessionPreviewCommand(parent: Command, group: 'ps' | 'sessions'): void;
8
+ export declare function renderSessionPreview(query: string, scope: {
9
+ agent?: string;
10
+ project?: string;
11
+ local?: boolean;
12
+ hosts?: string[];
13
+ json?: boolean;
14
+ refresh?: boolean;
15
+ revision?: string;
16
+ }): Promise<void>;