@phnx-labs/agents-cli 1.23.24 → 1.23.26

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 CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.23.26
4
+
5
+ - **`agents ps` says how long a working Claude turn has been quiet (PHNX-4387).** The list row shows `quiet Nm` where it showed `idle Nm` for a turn Claude reports busy, including one whose transcript tail holds only request records (Claude 2.1.261 appends 100+ KB of them after a step), where no quiet time was shown. `agents ps --json` carries `quietSinceMs`, when the turn went silent, in place of `quietMs`: a timestamp is stable across polls, so a quiet row no longer rewrites the active-sessions journal on every poll, and the age is computed when it is shown. Source: `cli/src/lib/session/active.ts`, `cli/src/commands/ps-roster.ts`, `cli/src/lib/session/presentation.ts`.
6
+
7
+ ## 1.23.25
8
+
9
+ - **A Claude turn quiet for over two minutes stays `running` in `agents ps`.** Claude writes nothing to its transcript while it thinks or streams one long tool call, so a live turn turned idle after two minutes. agents-cli now passes the turn state Claude Code records in `<config>/sessions/<pid>.json` (`busy` / `idle`) to the state engine (`@phnx-labs/sessions-cli` 0.8.6): `busy` is `running`, `idle` is `idle`, and other harnesses keep the two-minute window. `agents ps --json` rows carry `quietMs` once a running turn has been silent past two minutes, and `agents ps <id>` shows `quiet Nm` beside `working`. Source: `cli/src/lib/session/active.ts`, `cli/src/lib/session/presentation.ts`.
10
+
11
+ - **One session name everywhere; `--name` reaches Claude (PHNX-4387).** A session's name now resolves once, in the CLI, through `resolveSessionName`: a user rename, then Claude's own current name for the running process, then the label already in the index, then the `agents run --name` launch name, then Claude's generated title. The index and the live roster both use it, so `agents ps`, the extension's tab, sidebar card and status bar agree. Claude's per-process `sessions/<pid>.json` is now read from every config home (version and account homes on fleet workers, not only `~/.claude`), a running session's transcript is re-indexed every tick so a rename reaches the index without waiting for its directory to change, and the extension's echoed tab title is no longer an input. `agents run claude --name <x>` now launches `claude --name <x>` (not on `--resume`); the unused `AGENT_SESSION_NAME` env var is gone. `agents ps --json` rows add `startedAs`, the first prompt the session was started with, with `/goal` and harness-injected turns stripped. Source: `cli/src/lib/session/title.ts`, `cli/src/lib/session/active.ts`, `cli/src/lib/session/discover.ts`, `cli/src/lib/exec.ts`.
12
+
3
13
  ## 1.23.24
4
14
 
5
15
  - **`agents fork <id> --device <box>` works again, and so does every other command that declares its own `--device`.** The fleet router rejected `--device` on any top-level name missing from its hand-kept list, so `agents fork`, `agents cloud run`, `agents projects status` and `agents projects pull` all failed with "does not support --device". The router now steps aside when the resolved command declares `--device` itself (the `--device` that `addHostOption` adds stays the router's, and `--devices`/`--hosts` route exactly as before), and a test walks the whole command tree so a moved or new command cannot lose `--device` silently. `agents config list --device <name>` now runs its own handler (that device's config read here) instead of being forwarded to the device. The fork sibling starts in the source session's folder (`--cwd`) when it lands on the machine that holds the source session, and `agents ps preview` exits 1 when the hop to the owning device fails, so `agents fork` reports the peer's error instead of "could not read the source". Source: `cli/src/lib/hosts/routing-flag.ts`, `cli/src/lib/hosts/passthrough.ts`, `cli/src/commands/fork.ts`, `cli/src/commands/ps.ts`.
@@ -425,7 +425,7 @@ export function registerRunCommand(program) {
425
425
  .option('--since <time>', 'With a bare --resume: only sessions newer than this (default 30d; e.g. 2h, 7d, 4w, or ISO date)')
426
426
  .option('-n, --limit <n>', 'With a bare --resume: maximum sessions loaded into the picker (default 200)')
427
427
  .option('--session-id <id>', 'Force a NEW conversation to use this exact session UUID (Claude only). This CREATES a session — to resume an existing one, use --resume.', parseExplicitSessionId)
428
- .option('--name <slug>', 'Name the run — seeds the session label so it shows up as `<name>` in `sessions` and `agents ps` and resolves by it (and `agents events logs <name>` for --device runs) instead of an opaque id. An agent-generated title later refines the label; your name shows until then. Optional.')
428
+ .option('--name <slug>', 'Name the run. Claude receives it as its own session name (`claude --name`); for every harness it becomes the session label shown in `sessions` and `agents ps` and resolves by it (and `agents events logs <name>` for --device runs) instead of an opaque id. A rename inside the session replaces it. Ignored on --resume. Optional.')
429
429
  .option('--notify', 'Post a desktop notification when a headless run finishes. Fired by this process on exit, so it survives whatever launched the run (the menu bar dispatching it, a terminal you closed).')
430
430
  .option('--terminal [backend]', "Open this run in a real terminal tab instead of here. Without a value the terminal is detected from your live sessions (`agents ps` host), so it lands where you already work — Ghostty for a Ghostty user, iTerm for an iTerm user. Name one to force it: iterm | ghostty | terminal | tmux | vscodium-agent. This is how the menu bar's New Session opens.")
431
431
  .option('--verbose', 'Show detailed execution logs')
@@ -2,7 +2,7 @@ import chalk from 'chalk';
2
2
  import path from 'path';
3
3
  import { execFile } from 'child_process';
4
4
  import { promisify } from 'util';
5
- import { dedupeByMachineSession, getActiveSessions, findSessionFileForKind, listTerminalsActive, sessionProcessIsLocal, sessionProcessHost } from '../lib/session/active.js';
5
+ import { applySessionNames, dedupeByMachineSession, getActiveSessions, findSessionFileForKind, listTerminalsActive, sessionProcessIsLocal, sessionProcessHost } from '../lib/session/active.js';
6
6
  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';
@@ -241,6 +241,7 @@ export function editorTabsForSelector(selector, tabs, nowMs = Date.now()) {
241
241
  return tabs.filter((t) => isFocusableEditorTab(t, nowMs) && t.sessionId?.startsWith(selector));
242
242
  }
243
243
  async function focusEditorTab(tab) {
244
+ applySessionNames([tab]);
244
245
  const variant = editorVariantForHost(tab.host);
245
246
  for (const spec of focusTabSpecs(variant, tab.workspaceDir, tab.terminalId)) {
246
247
  const result = await runLocal(spec, 10_000);
@@ -96,7 +96,9 @@ function activeTimeCell(s) {
96
96
  const parts = [];
97
97
  if (s.startedAtMs)
98
98
  parts.push(`created ${formatCompactAge(new Date(s.startedAtMs).toISOString())}`);
99
- if (s.lastActivityMs)
99
+ if (s.activity === 'working' && s.quietSinceMs != null)
100
+ parts.push(`quiet ${formatCompactAge(new Date(s.quietSinceMs).toISOString())}`);
101
+ else if (s.lastActivityMs)
100
102
  parts.push(`idle ${formatCompactAge(new Date(s.lastActivityMs).toISOString())}`);
101
103
  return parts.join(' · ');
102
104
  }
@@ -113,6 +113,7 @@ interface AgentCommandTemplate {
113
113
  modelFlag?: string;
114
114
  printFlags?: string[];
115
115
  verboseFlag?: string;
116
+ nameFlag?: string;
116
117
  resume?: ({
117
118
  flag: string;
118
119
  interactiveFlag?: string;
package/dist/lib/exec.js CHANGED
@@ -292,9 +292,6 @@ export function buildExecEnv(options) {
292
292
  else {
293
293
  delete result.AGENTS_RUN_ACCOUNT_ID;
294
294
  }
295
- if (options.name) {
296
- result.AGENT_SESSION_NAME = options.name;
297
- }
298
295
  Object.assign(result, actorEnv(resolveActor()));
299
296
  return {
300
297
  ...result,
@@ -335,6 +332,7 @@ export const AGENT_COMMANDS = {
335
332
  modelFlag: '--model',
336
333
  printFlags: ['--print'],
337
334
  verboseFlag: '--verbose',
335
+ nameFlag: '--name',
338
336
  resume: { flag: '--resume' },
339
337
  },
340
338
  codex: {
@@ -621,6 +619,9 @@ export function buildExecCommand(options) {
621
619
  else if (options.sessionId && options.agent === 'claude') {
622
620
  cmd.push('--session-id', options.sessionId);
623
621
  }
622
+ if (options.name && template.nameFlag && !options.resume) {
623
+ cmd.push(template.nameFlag, options.name);
624
+ }
624
625
  if (effectiveModel && template.modelFlag) {
625
626
  if (tierResolved) {
626
627
  if (tierResolved.model) {
@@ -22,6 +22,7 @@ export declare function filterCachedUnattributed(sessions: ActiveSession[], attr
22
22
  export type ActiveContext = 'terminal' | 'teams' | 'cloud' | 'headless';
23
23
  type BackfillMeta = Pick<SessionMeta, 'version' | 'account' | 'accountId' | 'accountKey' | 'timestamp' | 'label' | 'firstUserMessage' | 'lastUserMessage' | 'generatedTitle' | 'ticketId' | 'prUrl' | 'prNumber' | 'origin' | 'routineName' | 'harness' | 'tokenCount' | 'durationMs' | 'subAgentCount' | 'lastActivity'>;
24
24
  export declare function backfillActiveRowsFromMeta(sessions: ActiveSession[], metaById: Map<string, BackfillMeta>): void;
25
+ export declare function applySessionNames(sessions: ActiveSession[]): void;
25
26
  export declare function sessionAccountLabel(kind: string, session: Pick<SessionMeta, 'accountId' | 'accountKey' | 'account'>, accounts?: import("../account-registry.js").NativeAccount[]): string | undefined;
26
27
  export declare function backfillActiveRowsFromIndex(sessions: ActiveSession[]): void;
27
28
  export declare function isRunningLiveSession(s: ActiveSession): boolean;
@@ -78,6 +79,7 @@ export interface ActiveSession {
78
79
  lastUserMessage?: string;
79
80
  generatedTitle?: string;
80
81
  title?: string;
82
+ startedAs?: string;
81
83
  recapSource?: RecapSource;
82
84
  userPromptClean?: string;
83
85
  userPromptKind?: UserPromptKind;
@@ -122,6 +124,7 @@ export interface ActiveSession {
122
124
  accountLabel?: string;
123
125
  lastActivityMs?: number;
124
126
  lastEventMs?: number;
127
+ quietSinceMs?: number;
125
128
  status: ActiveStatus;
126
129
  phase?: SessionPhase;
127
130
  origin?: 'cli' | 'routine';
@@ -195,12 +198,19 @@ export declare function lifecycleStatus(pidAlive: boolean, mtimeMs: number | und
195
198
  export declare function resolveFallbackStatus(sessionFile: string | undefined, pidAlive: boolean, nowMs?: number): ActiveStatus;
196
199
  export declare function findSessionFileForKind(kind: string, cwd?: string, sessionId?: string): string | undefined;
197
200
  export declare function sessionIdFromFile(kind: string, file?: string): string | undefined;
201
+ type LiveState = SessionState & {
202
+ quietSinceMs?: number;
203
+ };
198
204
  interface LiveSignals {
199
- state?: SessionState;
205
+ state?: LiveState;
200
206
  tokPerSec?: number;
201
207
  }
202
208
  export declare function clearLiveSignalsCacheForTest(): void;
203
209
  export declare function computeLiveSignals(kind: string, sessionFile: string | undefined, cwd: string | undefined, pidAlive: boolean, nowMs?: number): LiveSignals;
210
+ export declare function readTranscriptHead(sessionFile: string): {
211
+ topic?: string;
212
+ startedAs?: string;
213
+ };
204
214
  export declare function summarizeMission(prompt: string | null | undefined): string | undefined;
205
215
  export declare function listTeamsActive(opts?: {
206
216
  localOnly?: boolean;
@@ -14,14 +14,15 @@ import { parseNativeIdentityKey } from '../native-accounts.js';
14
14
  import { readLivePidSessionEntry as readPidSessionEntry, listPidSessionEntries, prunePidSessionRegistry, sessionIdFromLivePid, } from './pid-registry.js';
15
15
  import { readSessionActorRecord, writeSessionAliasRecord } from './actor-sidecar.js';
16
16
  import { loadHookSessionIndex, resolveHookSessionRecord, readStateSessionRecord } from './hook-sessions.js';
17
- import { buildClaudeLabelMap, getAgentSessionDirs } from './discover.js';
17
+ import { extractClaudeUserText, getAgentSessionDirs, readClaudeLiveNames } from './discover.js';
18
18
  import { buildRunNameMap } from './run-names.js';
19
- import { latestSessionFileForCwd, indexedSessionIdForFile, findSessionsByShortIds, findSessionMachinesByIds, getSessionById } from './db.js';
19
+ import { resolveSessionName, startedAsFromUserTurn } from './title.js';
20
+ import { getIndexedSessionNames, latestSessionFileForCwd, indexedSessionIdForFile, findSessionsByShortIds, findSessionMachinesByIds, getSessionById } from './db.js';
20
21
  import { extractSessionTopic, classifyUserPrompt, tidyRequest } from '@phnx-labs/sessions-cli/reader';
21
22
  import { readSessionTailWithRaw } from '@phnx-labs/sessions-cli/reader';
22
23
  import { parseSession } from '@phnx-labs/sessions-cli/reader';
23
24
  import { computeTokPerSec } from './throughput.js';
24
- import { inferSessionState } from '@phnx-labs/sessions-cli/reader';
25
+ import { inferSessionState, readHarnessStatus } from '@phnx-labs/sessions-cli/reader';
25
26
  import { isSessionTrackedAgent, SESSION_AGENTS, AG_TMUX_NAME_RE } from '@phnx-labs/sessions-cli/reader';
26
27
  import { AGENTS } from '../agents.js';
27
28
  import { canonicalProjectName, confirmedProjectForCwd, listProjectDefsCached } from '../projects.js';
@@ -133,6 +134,28 @@ export function backfillActiveRowsFromMeta(sessions, metaById) {
133
134
  applyRecap(s);
134
135
  }
135
136
  }
137
+ export function applySessionNames(sessions) {
138
+ const self = machineId();
139
+ const owned = sessions.filter((s) => !s.machine || s.machine === self || s.offloadedFrom === self);
140
+ if (owned.length === 0)
141
+ return;
142
+ const live = readClaudeLiveNames();
143
+ const launch = buildRunNameMap();
144
+ const indexed = getIndexedSessionNames(owned.flatMap((s) => s.sessionId ? [{ id: s.sessionId, filePath: s.sessionFile }] : []));
145
+ for (const s of owned) {
146
+ const id = s.sessionId;
147
+ if (id)
148
+ s.name ??= launch.get(id) ?? undefined;
149
+ const runsHere = !s.machine || s.machine === self;
150
+ const stored = id ? indexed.get(id) : undefined;
151
+ s.label = resolveSessionName({
152
+ customTitle: stored?.customTitle,
153
+ live: id && runsHere ? live.get(id) : undefined,
154
+ indexed: stored?.label,
155
+ launchName: s.name,
156
+ }) ?? s.label;
157
+ }
158
+ }
136
159
  export function sessionAccountLabel(kind, session, accounts = listNativeAccounts(readMeta())) {
137
160
  const matches = accounts.filter(account => {
138
161
  if (account.agent !== kind)
@@ -564,9 +587,15 @@ export function computeLiveSignals(kind, sessionFile, cwd, pidAlive, nowMs = Dat
564
587
  liveTailCache.clear();
565
588
  liveTailCache.set(cacheKey, tail);
566
589
  }
567
- if (tail.events.length === 0)
590
+ const harnessStatus = kind === 'claude' && pidAlive ? readHarnessStatus(sessionFile)?.status : undefined;
591
+ if (tail.events.length === 0 && harnessStatus !== 'busy')
568
592
  return {};
569
- const state = inferSessionState(tail.events, { cwd, pidAlive, mtimeMs, activeWindowMs: ACTIVE_MTIME_WINDOW_MS, nowMs });
593
+ const state = inferSessionState(tail.events, { cwd, pidAlive, mtimeMs, harnessStatus, activeWindowMs: ACTIVE_MTIME_WINDOW_MS, nowMs });
594
+ if (harnessStatus === 'busy' && state.activity === 'working') {
595
+ const quietSinceMs = state.quietMs != null ? nowMs - state.quietMs : tail.events.length === 0 ? mtimeMs : undefined;
596
+ if (quietSinceMs != null && nowMs - quietSinceMs >= ACTIVE_MTIME_WINDOW_MS)
597
+ state.quietSinceMs = quietSinceMs;
598
+ }
570
599
  return { state, tokPerSec: tail.tokPerSec };
571
600
  }
572
601
  function statusFromActivity(activity) {
@@ -587,6 +616,7 @@ function applyState(base, state, fallbackFile, pidAlive) {
587
616
  awaitingReason: state.awaitingReason,
588
617
  question: state.question,
589
618
  lastEventMs: state.lastEventMs,
619
+ quietSinceMs: state.quietSinceMs,
590
620
  plan: state.plan,
591
621
  todos: state.todos,
592
622
  tail: state.tail,
@@ -602,28 +632,15 @@ function applyState(base, state, fallbackFile, pidAlive) {
602
632
  rateLimited: state.rateLimited,
603
633
  };
604
634
  }
605
- function extractClaudeUserText(parsed) {
606
- const msg = parsed.message;
607
- if (!msg?.content)
608
- return undefined;
609
- const content = Array.isArray(msg.content) ? msg.content : [msg.content];
610
- const texts = [];
611
- for (const block of content) {
612
- if (typeof block === 'string')
613
- texts.push(block);
614
- else if (block?.type === 'text' && typeof block.text === 'string')
615
- texts.push(block.text);
616
- }
617
- return texts.join('\n').trim() || undefined;
618
- }
619
- function quickExtractTopic(sessionFile) {
635
+ export function readTranscriptHead(sessionFile) {
620
636
  let fd;
621
637
  try {
622
638
  fd = fs.openSync(sessionFile, 'r');
623
639
  }
624
640
  catch {
625
- return undefined;
641
+ return {};
626
642
  }
643
+ const head = {};
627
644
  try {
628
645
  const chunkSize = 256 * 1024;
629
646
  const maxBytes = 2 * 1024 * 1024;
@@ -656,9 +673,10 @@ function quickExtractTopic(sessionFile) {
656
673
  if (parsed.type === 'user') {
657
674
  const text = extractClaudeUserText(parsed);
658
675
  if (text) {
659
- const topic = extractSessionTopic(text);
660
- if (topic)
661
- return topic;
676
+ head.startedAs ??= startedAsFromUserTurn(text);
677
+ head.topic ??= extractSessionTopic(text);
678
+ if (head.topic && head.startedAs)
679
+ return head;
662
680
  }
663
681
  }
664
682
  }
@@ -668,7 +686,7 @@ function quickExtractTopic(sessionFile) {
668
686
  finally {
669
687
  fs.closeSync(fd);
670
688
  }
671
- return undefined;
689
+ return head;
672
690
  }
673
691
  export function summarizeMission(prompt) {
674
692
  if (!prompt)
@@ -688,7 +706,7 @@ export async function listTeamsActive(opts = {}) {
688
706
  return running.map((a) => {
689
707
  const ownSessionId = a.remoteSessionId ?? undefined;
690
708
  const sessionFile = findSessionFileForKind(a.agentType, a.cwd ?? undefined, ownSessionId);
691
- const topic = sessionFile ? quickExtractTopic(sessionFile) : undefined;
709
+ const { topic, startedAs } = sessionFile ? readTranscriptHead(sessionFile) : {};
692
710
  const pidAlive = a.pid ? isPidAlive(a.pid) : true;
693
711
  const { state, tokPerSec } = computeLiveSignals(a.agentType, sessionFile, a.cwd ?? undefined, pidAlive);
694
712
  const resolvedId = ownSessionId ?? sessionIdFromFile(a.agentType, sessionFile);
@@ -704,8 +722,9 @@ export async function listTeamsActive(opts = {}) {
704
722
  offloadedFrom: offloaded ? self : undefined,
705
723
  orchestratorSessionId: a.parentSessionId ?? undefined,
706
724
  cwd: a.cwd ?? undefined,
707
- label: a.name ?? undefined,
725
+ name: a.name ?? undefined,
708
726
  topic,
727
+ startedAs,
709
728
  tokPerSec,
710
729
  sessionFile,
711
730
  startedAtMs: a.startedAt.getTime(),
@@ -725,8 +744,6 @@ export async function listTerminalsActive() {
725
744
  for (const r of await readProcessTable())
726
745
  procByPid.set(r.pid, r);
727
746
  const children = childrenByParent(new Map([...procByPid.values()].map(r => [r.pid, r.ppid])));
728
- const labelMap = buildClaudeLabelMap();
729
- const runNameMap = buildRunNameMap();
730
747
  const self = machineId();
731
748
  return entries.flatMap((t) => {
732
749
  const directEntry = readPidSessionEntry(t.pid, procByPid.get(t.pid)?.startTime);
@@ -739,9 +756,7 @@ export async function listTerminalsActive() {
739
756
  if (!resolvedId && !isSessionTrackedAgent(sessionKind))
740
757
  return [];
741
758
  const sessionFile = resolvedId ? findSessionFileForKind(sessionKind, cwd, resolvedId) : undefined;
742
- const label = t.label ?? (resolvedId ? labelMap.get(resolvedId) : undefined) ?? undefined;
743
- const name = resolvedId ? runNameMap.get(resolvedId) ?? undefined : undefined;
744
- const topic = sessionFile ? quickExtractTopic(sessionFile) : undefined;
759
+ const { topic, startedAs } = sessionFile ? readTranscriptHead(sessionFile) : {};
745
760
  const pidAlive = isPidAlive(t.pid, t.startedAtMs);
746
761
  const { state, tokPerSec } = computeLiveSignals(sessionKind, sessionFile, cwd, pidAlive);
747
762
  return [applyState({
@@ -757,9 +772,8 @@ export async function listTerminalsActive() {
757
772
  originTerminal: pidEntry?.originTerminal,
758
773
  tabIndex: t.tabIndex,
759
774
  cwd,
760
- label,
761
- name,
762
775
  topic,
776
+ startedAs,
763
777
  tokPerSec,
764
778
  sessionFile,
765
779
  startedAtMs: pidEntry?.startedAtMs ?? t.startedAtMs,
@@ -1087,7 +1101,6 @@ async function listUnattributedActiveLive(attributed) {
1087
1101
  const cwds = await resolveCwds(kept.map(c => c.pid));
1088
1102
  let hookIndex;
1089
1103
  let children;
1090
- const runNameMap = buildRunNameMap();
1091
1104
  const ensureChildren = () => children ??= childrenByParent(ppidMap);
1092
1105
  const out = [];
1093
1106
  for (let i = 0; i < kept.length; i++) {
@@ -1116,15 +1129,13 @@ async function listUnattributedActiveLive(attributed) {
1116
1129
  continue;
1117
1130
  const cwd = cwds[i] ?? entry?.cwd ?? undefined;
1118
1131
  const sessionFile = findSessionFileForKind(kind, cwd, exactId);
1119
- const topic = sessionFile ? quickExtractTopic(sessionFile) : undefined;
1132
+ const { topic, startedAs } = sessionFile ? readTranscriptHead(sessionFile) : {};
1120
1133
  const host = detectHost(pid, procByPid);
1121
1134
  const tty = procByPid.get(pid)?.tty;
1122
1135
  const context = unattributedContext(host, tty);
1123
1136
  const { state, tokPerSec } = computeLiveSignals(kind, sessionFile, cwd, true);
1124
1137
  const { birthtimeMs, mtimeMs } = sessionFileTimes(sessionFile);
1125
1138
  const resolvedId = exactId ?? sessionIdFromFile(kind, sessionFile);
1126
- const name = resolvedId ? runNameMap.get(resolvedId) ?? undefined : undefined;
1127
- const label = name;
1128
1139
  out.push(applyState({
1129
1140
  context,
1130
1141
  kind,
@@ -1134,9 +1145,8 @@ async function listUnattributedActiveLive(attributed) {
1134
1145
  pid,
1135
1146
  cwd,
1136
1147
  sessionId: resolvedId,
1137
- label,
1138
- name,
1139
1148
  topic,
1149
+ startedAs,
1140
1150
  tokPerSec,
1141
1151
  sessionFile,
1142
1152
  startedAtMs: hookRec?.ts ?? birthtimeMs,
@@ -1242,7 +1252,7 @@ export async function listTmuxAgentSessions() {
1242
1252
  const pid = id.pid ?? (parseInt(pidRaw, 10) || undefined);
1243
1253
  const cwd = liveEntry?.cwd ?? meta?.cwd ?? (curPath || undefined);
1244
1254
  const sessionFile = id.sessionId ? findSessionFileForKind(id.agent, cwd, id.sessionId) : undefined;
1245
- const topic = sessionFile ? quickExtractTopic(sessionFile) : undefined;
1255
+ const { topic, startedAs } = sessionFile ? readTranscriptHead(sessionFile) : {};
1246
1256
  const paneDead = paneDeadRaw === '1';
1247
1257
  const pidAlive = !paneDead && (pid ? isPidAlive(pid, liveEntry?.startedAtMs) : true);
1248
1258
  const { state, tokPerSec } = computeLiveSignals(id.agent, sessionFile, cwd, pidAlive);
@@ -1262,6 +1272,7 @@ export async function listTmuxAgentSessions() {
1262
1272
  sessionId: id.sessionId ?? sessionIdFromFile(id.agent, sessionFile),
1263
1273
  cwd,
1264
1274
  topic,
1275
+ startedAs,
1265
1276
  tokPerSec,
1266
1277
  sessionFile,
1267
1278
  startedAtMs: liveEntry?.startedAtMs ?? birthtimeMs,
@@ -1308,6 +1319,7 @@ export async function getActiveSessions(opts = {}) {
1308
1319
  spanSync('active.fold', () => {
1309
1320
  foldHostLink(merged);
1310
1321
  foldExecutionMachine(merged, recordedMachineLookup(merged), machineId());
1322
+ applySessionNames(merged);
1311
1323
  annotateOrchestratorLabels(merged);
1312
1324
  foldRecap(merged);
1313
1325
  foldPhase(merged);
@@ -1484,6 +1496,7 @@ export function deriveImportantMessage(row) {
1484
1496
  function applyRecap(s) {
1485
1497
  const recap = deriveSessionRecap(s);
1486
1498
  s.title = recap.title;
1499
+ s.startedAs ??= s.firstUserMessage ? startedAsFromUserTurn(s.firstUserMessage) : undefined;
1487
1500
  s.recapSource = recap.recapSource;
1488
1501
  s.userPromptClean = recap.userPromptClean;
1489
1502
  s.userPromptKind = recap.userPromptKind;
@@ -4,7 +4,7 @@ import { type IndexedToolCall } from '@phnx-labs/sessions-cli/reader';
4
4
  import { type ToolScanResumePoint } from './tool-store.js';
5
5
  import { type TimelineState } from '@phnx-labs/sessions-cli/reader';
6
6
  export declare const SCHEMA_VERSION = 52;
7
- export declare const CONTENT_INDEX_VERSION = 7;
7
+ export declare const CONTENT_INDEX_VERSION = 8;
8
8
  export declare const INSIGHTS_EXTRACTOR_VERSION = 7;
9
9
  export declare const SESSION_SUMMARY_EXTRACTOR_VERSION = 1;
10
10
  export interface ScanStamp {
@@ -90,7 +90,13 @@ export declare function upsertSessionsBatch(entries: Array<{
90
90
  toolIndexMode?: 'replace' | 'append';
91
91
  toolResume?: ToolScanResumePoint | null;
92
92
  }>): void;
93
- export declare function syncLabels(labelMap: Map<string, string | null>): number;
93
+ export declare function getIndexedSessionNames(rows: Array<{
94
+ id: string;
95
+ filePath?: string;
96
+ }>): Map<string, {
97
+ label?: string;
98
+ customTitle?: string;
99
+ }>;
94
100
  export declare function seedLabelsFromNames(nameMap: Map<string, string | null>): number;
95
101
  export declare function syncTopics(topicMap: Map<string, string>): number;
96
102
  export declare function isSessionActivityFresh(row: {
@@ -19,7 +19,7 @@ import { emptyTimelineState, TIMELINE_EXTRACTOR_VERSION } from '@phnx-labs/sessi
19
19
  const SESSIONS_DIR = getSessionsDir();
20
20
  const DB_PATH = getSessionsDbPath();
21
21
  export const SCHEMA_VERSION = 52;
22
- export const CONTENT_INDEX_VERSION = 7;
22
+ export const CONTENT_INDEX_VERSION = 8;
23
23
  const RESOURCE_INDEX_VERSION = 2;
24
24
  function canonicalLedgerKey(filePath) {
25
25
  if (!filePath)
@@ -1492,8 +1492,8 @@ const upsertSessionStmt = (db) => db.prepare(`
1492
1492
  last_user_message = COALESCE(excluded.last_user_message, sessions.last_user_message),
1493
1493
  -- Never let an empty/placeholder incoming label clobber a good stored one.
1494
1494
  -- A real incoming label (non-empty after trim) still wins; a blank one keeps
1495
- -- the label seeded by --name (seedLabelsFromNames) or refined by an agent
1496
- -- title / rename (syncLabels). A bare rescan carries no label, so it must
1495
+ -- the label seeded by --name (seedLabelsFromNames) or resolved at an earlier
1496
+ -- scan (resolveSessionName). A bare rescan carries no label, so it must
1497
1497
  -- preserve, not erase, the good one already stored.
1498
1498
  label = CASE
1499
1499
  WHEN excluded.label IS NULL OR trim(excluded.label) = '' THEN sessions.label
@@ -1971,38 +1971,42 @@ export function upsertSessionsBatch(entries) {
1971
1971
  }
1972
1972
  maintainSessionSearchIndex(db);
1973
1973
  }
1974
- export function syncLabels(labelMap) {
1975
- if (labelMap.size === 0)
1976
- return 0;
1974
+ export function getIndexedSessionNames(rows) {
1975
+ const out = new Map();
1976
+ if (rows.length === 0)
1977
+ return out;
1977
1978
  const db = getDB();
1978
- const ids = [...labelMap.keys()];
1979
1979
  const CHUNK = 500;
1980
- const updates = [];
1980
+ const filePathById = new Map(rows.map((r) => [r.id, r.filePath]));
1981
+ const ids = [...filePathById.keys()];
1981
1982
  for (let i = 0; i < ids.length; i += CHUNK) {
1982
1983
  const chunk = ids.slice(i, i + CHUNK);
1983
- const placeholders = chunk.map(() => '?').join(',');
1984
- const rows = db
1985
- .prepare(`SELECT id, label FROM sessions WHERE id IN (${placeholders})`)
1984
+ const indexed = db
1985
+ .prepare(`SELECT id, label, file_path FROM sessions WHERE id IN (${chunk.map(() => '?').join(',')})`)
1986
1986
  .all(...chunk);
1987
- for (const row of rows) {
1988
- const live = labelMap.get(row.id)?.trim() || null;
1989
- if (live && live !== (row.label ?? '')) {
1990
- updates.push({ id: row.id, label: live });
1991
- }
1987
+ for (const row of indexed) {
1988
+ out.set(row.id, { label: row.label ?? undefined });
1989
+ filePathById.set(row.id, filePathById.get(row.id) ?? row.file_path ?? undefined);
1990
+ }
1991
+ }
1992
+ const idByLedgerKey = new Map();
1993
+ for (const [id, fp] of filePathById)
1994
+ if (fp)
1995
+ idByLedgerKey.set(canonicalLedgerKey(fp), id);
1996
+ const keys = [...idByLedgerKey.keys()];
1997
+ for (let i = 0; i < keys.length; i += CHUNK) {
1998
+ const chunk = keys.slice(i, i + CHUNK);
1999
+ const titled = db
2000
+ .prepare(`SELECT file_path, json_extract(parser_state, '$.customTitle') AS custom_title FROM scan_ledger WHERE file_path IN (${chunk.map(() => '?').join(',')}) AND json_valid(parser_state)`)
2001
+ .all(...chunk);
2002
+ for (const row of titled) {
2003
+ if (typeof row.custom_title !== 'string' || !row.custom_title)
2004
+ continue;
2005
+ const id = idByLedgerKey.get(row.file_path);
2006
+ out.set(id, { ...out.get(id), customTitle: row.custom_title });
1992
2007
  }
1993
2008
  }
1994
- if (updates.length === 0)
1995
- return 0;
1996
- const updSessions = db.prepare(`UPDATE sessions SET label = ? WHERE id = ?`);
1997
- const updFts = db.prepare(`UPDATE session_text SET label = ? WHERE rowid = ${SESSION_TEXT_ROWID}`);
1998
- const txn = db.transaction((items) => {
1999
- for (const { id, label } of items) {
2000
- updSessions.run(label, id);
2001
- updFts.run(label ?? '', id);
2002
- }
2003
- });
2004
- txn(updates);
2005
- return updates.length;
2009
+ return out;
2006
2010
  }
2007
2011
  export function seedLabelsFromNames(nameMap) {
2008
2012
  if (nameMap.size === 0)
@@ -1,6 +1,7 @@
1
1
  import type { SessionAgentId, SessionEvent, SessionMeta, TodoProgress } from '@phnx-labs/sessions-cli/reader';
2
2
  export { machineForSessionFile } from './origin-machine.js';
3
3
  import { type ScanStamp } from './db.js';
4
+ import { type LiveSessionName } from './title.js';
4
5
  import { ToolCallCollector, type IndexedToolCall, type ToolCallCollectorSnapshot } from '@phnx-labs/sessions-cli/reader';
5
6
  interface DiscoverOptions {
6
7
  agent?: SessionAgentId;
@@ -40,7 +41,8 @@ interface ClaudeSessionScan {
40
41
  model?: string;
41
42
  topic?: string;
42
43
  firstUserMessage?: string;
43
- label?: string;
44
+ customTitle?: string;
45
+ aiTitle?: string;
44
46
  messageCount: number;
45
47
  tokenCount?: number;
46
48
  outputTokens?: number;
@@ -152,7 +154,9 @@ interface SessionRoots {
152
154
  dirs: string[];
153
155
  }
154
156
  export declare function getSessionRoots(): SessionRoots[];
155
- export declare function buildClaudeLabelMap(): Map<string, string | null>;
157
+ export declare function readClaudeLiveNames(): Map<string, LiveSessionName & {
158
+ sessionId: string;
159
+ }>;
156
160
  export declare function decodeJwtEmail(idToken: string): string | undefined;
157
161
  export declare function __codexAccountResolveCountForTest(): number;
158
162
  export declare function __resetCodexAccountCacheForTest(): void;
@@ -361,6 +365,7 @@ export declare function __codexScanBranchCountsForTest(): {
361
365
  full: number;
362
366
  };
363
367
  export declare function __resetCodexScanBranchCountsForTest(): void;
368
+ export declare function extractClaudeUserText(parsed: any): string | undefined;
364
369
  export declare function extractVersionFromManagedPath(agent: SessionAgentId, sourcePath?: string): string | undefined;
365
370
  export declare function readCursorMeta(filePath: string, currentVersion?: string): {
366
371
  meta: SessionMeta;
@@ -28,8 +28,9 @@ import { readSessionActorRecord } from './actor-sidecar.js';
28
28
  import { machineForSessionFile } from './origin-machine.js';
29
29
  export { machineForSessionFile } from './origin-machine.js';
30
30
  import { mapBounded } from '../concurrency.js';
31
- import { getDB, getScanStampByPath, getScanStampsForPaths, getParserStatesForPaths, getDirLedgerForPaths, recordDirScans, recordScans, syncLabels, seedLabelsFromNames, syncTopics, upsertSessionsBatch, querySessions, countSessions, ftsSearch, getSessionById, tryClaimScan, releaseScan, scanInProgressByLivePid, cacheLinearProject, CONTENT_INDEX_VERSION, } from './db.js';
31
+ import { getDB, getScanStampByPath, getScanStampsForPaths, getParserStatesForPaths, getDirLedgerForPaths, recordDirScans, recordScans, seedLabelsFromNames, syncTopics, upsertSessionsBatch, querySessions, countSessions, ftsSearch, getSessionById, tryClaimScan, releaseScan, scanInProgressByLivePid, cacheLinearProject, CONTENT_INDEX_VERSION, } from './db.js';
32
32
  import { buildRunNameMap } from './run-names.js';
33
+ import { resolveSessionName } from './title.js';
33
34
  import { resolveLinearApiKey } from '../linear-cache.js';
34
35
  import { ToolCallCollector, collectClaudeToolCalls, collectCodexToolCalls, } from '@phnx-labs/sessions-cli/reader';
35
36
  import { purgeMissingToolCallsInDirectory } from './tool-store.js';
@@ -496,7 +497,7 @@ export function shouldDeferRecentAppend(prev, current, nowMs, debounceMs = ACTIV
496
497
  return false;
497
498
  return nowMs - prev.scannedAt < debounceMs;
498
499
  }
499
- function collectChangedFilesInLeafDirs(leafDirs, ext) {
500
+ function collectChangedFilesInLeafDirs(leafDirs, ext, isHotFile) {
500
501
  const disabled = dirLedgerDisabled();
501
502
  const dirStamps = disabled ? new Map() : getDirLedgerForPaths(leafDirs.map(d => d.dirPath));
502
503
  const now = Date.now();
@@ -524,7 +525,7 @@ function collectChangedFilesInLeafDirs(leafDirs, ext) {
524
525
  if (dirUnchanged) {
525
526
  const stamps = isLiveRoot ? null : getScanStampsForPaths(files);
526
527
  for (const filePath of files) {
527
- let hot = isLiveRoot;
528
+ let hot = isLiveRoot || isHotFile?.(filePath) === true;
528
529
  if (!hot && stamps) {
529
530
  const s = stamps.get(filePath);
530
531
  hot = s?.extractorVersion !== CONTENT_INDEX_VERSION
@@ -755,40 +756,59 @@ function claudeAccountIndex(refresh = false) {
755
756
  cachedClaudeAccountIndex = buildClaudeAccountIndex();
756
757
  return cachedClaudeAccountIndex;
757
758
  }
758
- export function buildClaudeLabelMap() {
759
- const map = new Map();
760
- const dir = path.join(HOME, '.claude', 'sessions');
761
- if (!fs.existsSync(dir))
762
- return new Map();
763
- let files;
764
- try {
765
- files = fs.readdirSync(dir).filter(f => f.endsWith('.json'));
766
- }
767
- catch {
768
- return new Map();
759
+ const lastSeenLiveMs = new Map();
760
+ function recentlyLive(sessionIds, now) {
761
+ for (const id of sessionIds)
762
+ lastSeenLiveMs.set(id, now);
763
+ const hot = new Set();
764
+ for (const [id, at] of lastSeenLiveMs) {
765
+ if (now - at <= HOT_FILE_WINDOW_MS)
766
+ hot.add(id);
767
+ else
768
+ lastSeenLiveMs.delete(id);
769
769
  }
770
- for (const f of files) {
770
+ return hot;
771
+ }
772
+ export function readClaudeLiveNames() {
773
+ const newest = new Map();
774
+ for (const dir of getAgentSessionDirs('claude', 'sessions')) {
775
+ let files;
771
776
  try {
772
- const data = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf-8'));
773
- if (typeof data.sessionId !== 'string')
777
+ files = fs.readdirSync(dir).filter(f => f.endsWith('.json'));
778
+ }
779
+ catch {
780
+ continue;
781
+ }
782
+ for (const f of files) {
783
+ let data;
784
+ try {
785
+ data = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf-8'));
786
+ }
787
+ catch {
774
788
  continue;
775
- const name = typeof data.name === 'string' && data.name.trim() ? data.name.trim() : null;
776
- const startedAt = typeof data.startedAt === 'number' ? data.startedAt : 0;
777
- const existing = map.get(data.sessionId);
778
- if (!existing || startedAt > existing.startedAt) {
779
- map.set(data.sessionId, { label: name, startedAt });
780
789
  }
790
+ if (typeof data?.sessionId !== 'string')
791
+ continue;
792
+ const at = typeof data.updatedAt === 'number' ? data.updatedAt : typeof data.startedAt === 'number' ? data.startedAt : 0;
793
+ const prev = newest.get(data.sessionId);
794
+ if (prev && prev.at >= at)
795
+ continue;
796
+ newest.set(data.sessionId, {
797
+ entry: {
798
+ sessionId: data.sessionId,
799
+ name: typeof data.name === 'string' ? data.name.trim() : '',
800
+ source: typeof data.nameSource === 'string' ? data.nameSource : undefined,
801
+ },
802
+ at,
803
+ });
781
804
  }
782
- catch { }
783
805
  }
784
- const out = new Map();
785
- for (const [sid, { label }] of map)
786
- out.set(sid, label);
787
- return out;
806
+ return new Map([...newest].map(([id, { entry }]) => [id, entry]));
788
807
  }
789
808
  async function scanClaudeIncremental(onProgress) {
790
809
  claudeAccountIndex(true);
791
- const labelMap = buildClaudeLabelMap();
810
+ const liveNames = readClaudeLiveNames();
811
+ const launchNames = buildRunNameMap();
792
812
  const roots = getAgentSessionDirs('claude', 'projects');
793
813
  const leafDirs = [];
794
814
  const seenLeaf = new Set();
@@ -810,8 +830,9 @@ async function scanClaudeIncremental(onProgress) {
810
830
  leafDirs.push({ dirPath, isLiveRoot });
811
831
  }
812
832
  });
813
- const { changed: changedAll, allFiles } = collectChangedFilesInLeafDirs(leafDirs, '.jsonl');
814
833
  const sessionIdOf = (fp) => path.basename(fp).replace('.jsonl', '');
834
+ const hot = recentlyLive(liveNames.keys(), Date.now());
835
+ const { changed: changedAll, allFiles } = collectChangedFilesInLeafDirs(leafDirs, '.jsonl', fp => hot.has(sessionIdOf(fp)));
815
836
  const winnerBySession = new Map();
816
837
  for (const { filePath } of allFiles) {
817
838
  const id = sessionIdOf(filePath);
@@ -828,9 +849,11 @@ async function scanClaudeIncremental(onProgress) {
828
849
  for (const { filePath, scan } of changed) {
829
850
  try {
830
851
  const sessionId = path.basename(filePath).replace('.jsonl', '');
831
- const label = labelMap.get(sessionId) ?? undefined;
832
852
  const priorRow = priorStates.get(filePath);
833
- const result = await readClaudeMeta(filePath, sessionId, scan, priorRow, label);
853
+ const result = await readClaudeMeta(filePath, sessionId, scan, priorRow, {
854
+ live: liveNames.get(sessionId),
855
+ launchName: launchNames.get(sessionId),
856
+ });
834
857
  if (result) {
835
858
  entries.push({
836
859
  meta: result.meta,
@@ -856,10 +879,8 @@ async function scanClaudeIncremental(onProgress) {
856
879
  upsertSessionsBatch(entries);
857
880
  recordScans(touched);
858
881
  }
859
- if (labelMap.size > 0)
860
- syncLabels(labelMap);
861
882
  }
862
- async function readClaudeMeta(filePath, sessionId, scanStamp, priorRow, label) {
883
+ async function readClaudeMeta(filePath, sessionId, scanStamp, priorRow, names = {}) {
863
884
  const prior = priorRow?.extractorVersion === CONTENT_INDEX_VERSION ? parsePriorClaudeState(priorRow) : null;
864
885
  const { scan, newState, toolCalls, mode } = await scanClaudeSessionResumable(filePath, prior, scanStamp.fileMtimeMs, scanStamp.fileSize, priorRow?.fileMtimeMs);
865
886
  if (mode === 'incremental')
@@ -867,6 +888,7 @@ async function readClaudeMeta(filePath, sessionId, scanStamp, priorRow, label) {
867
888
  else
868
889
  claudeFullScanCount++;
869
890
  const isTeamOrigin = scan.entrypoint === 'sdk-cli';
891
+ const label = resolveSessionName({ customTitle: scan.customTitle, aiTitle: scan.aiTitle, ...names });
870
892
  const acct = resolveClaudeAccount(claudeAccountIndex(), filePath, scan.version, readSessionActorRecord(sessionId)?.accountId);
871
893
  let meta;
872
894
  if (scan.timestamp) {
@@ -888,7 +910,7 @@ async function readClaudeMeta(filePath, sessionId, scanStamp, priorRow, label) {
888
910
  accountOrg: acct.orgName ?? undefined,
889
911
  topic: scan.topic,
890
912
  firstUserMessage: scan.firstUserMessage,
891
- label: label || scan.label,
913
+ label,
892
914
  messageCount: scan.messageCount,
893
915
  toolCallCount: scan.toolCallCount,
894
916
  tokenCount: scan.tokenCount,
@@ -928,7 +950,7 @@ async function readClaudeMeta(filePath, sessionId, scanStamp, priorRow, label) {
928
950
  accountKey: acct.key,
929
951
  accountOrg: acct.orgName ?? undefined,
930
952
  model: scan.model,
931
- label: label || scan.label,
953
+ label,
932
954
  messageCount: scan.messageCount,
933
955
  toolCallCount: scan.toolCallCount,
934
956
  tokenCount: scan.tokenCount,
@@ -2458,7 +2480,6 @@ export function finalizeClaudeScan(state, sessionFile) {
2458
2480
  const durationMs = state.firstTsMs !== undefined && state.lastTsMs !== undefined && state.lastTsMs > state.firstTsMs
2459
2481
  ? state.lastTsMs - state.firstTsMs
2460
2482
  : undefined;
2461
- const label = state.customTitle || cleanGeneratedSessionLabel(state.aiTitle);
2462
2483
  const worktree = detectWorktree(state.cwd, state.gitBranch);
2463
2484
  const ticket = detectTicket(state.userTexts.join('\n') || undefined, state.gitBranch);
2464
2485
  return {
@@ -2469,7 +2490,8 @@ export function finalizeClaudeScan(state, sessionFile) {
2469
2490
  model: state.model,
2470
2491
  topic: state.topic,
2471
2492
  firstUserMessage: state.firstUserMessage,
2472
- label,
2493
+ customTitle: state.customTitle,
2494
+ aiTitle: state.aiTitle,
2473
2495
  entrypoint: state.entrypoint,
2474
2496
  messageCount: state.messageCount,
2475
2497
  toolCallCount: state.toolCallCount,
@@ -3127,7 +3149,7 @@ function safeRealpathSync(p) {
3127
3149
  return null;
3128
3150
  }
3129
3151
  }
3130
- function extractClaudeUserText(parsed) {
3152
+ export function extractClaudeUserText(parsed) {
3131
3153
  if (parsed.isMeta === true)
3132
3154
  return undefined;
3133
3155
  const content = parsed.message?.content;
@@ -9,7 +9,7 @@ import { homeDir, toComparablePath } from '../platform/index.js';
9
9
  import { redactSecrets, sanitizeForTerminal } from '../redact.js';
10
10
  import { listBookmarks } from './bookmarks.js';
11
11
  import { readArchivedSessionPreview, readSessionContent, readSessionTimelineAny } from './db.js';
12
- import { formatRelativeTime, sessionAgeParts } from './relative-time.js';
12
+ import { formatCompactAge, formatRelativeTime, sessionAgeParts } from './relative-time.js';
13
13
  import { ticketLabel } from './selection.js';
14
14
  import { sessionHeadline } from './title.js';
15
15
  import { padToWidth, stringWidth, terminalWidth, truncateToWidth } from './width.js';
@@ -340,6 +340,8 @@ export function formatLiveStatusHeadline(live, bookmarked = false) {
340
340
  const needsYou = isAwaitingUser(live);
341
341
  const reason = live.awaitingReason ? ` (${live.awaitingReason.replace('_', ' ')})` : '';
342
342
  let suffix = needsYou ? chalk.yellow(` ← needs you${reason}`) : '';
343
+ if (word === 'working' && live.quietSinceMs != null)
344
+ suffix = chalk.dim(` quiet ${formatCompactAge(new Date(live.quietSinceMs).toISOString())}`);
343
345
  if (live.status === 'crashed') {
344
346
  suffix = chalk.redBright(' ← the host app or connection went away and took the agent with it');
345
347
  }
@@ -38,7 +38,7 @@ interface ImmutableSessionFields {
38
38
  context?: ActiveSession['context'];
39
39
  }
40
40
  export declare const IMMUTABLE_FIELD_KEYS: readonly ["topic", "firstUserMessage", "label", "name", "cwd", "project", "attachments", "startedAtMs", "version", "pr", "worktree", "ticket", "createdTickets", "spawnedTeam", "sessionFile", "owner", "assignedTask", "kind", "context"];
41
- export declare const LIVE_STATUS_KEYS: readonly ["status", "activity", "model", "failures", "activityHistogram", "userTurns", "subagents", "pending", "effort", "fast", "preview", "tokPerSec", "awaitingReason", "question", "todos", "tail", "lastActivityMs", "lastEventMs", "hostLink", "presence", "pidAlive", "tmuxClients", "windowHeartbeatMs", "provenance", "rateLimited", "plan"];
41
+ export declare const LIVE_STATUS_KEYS: readonly ["status", "activity", "model", "failures", "activityHistogram", "userTurns", "subagents", "pending", "effort", "fast", "preview", "tokPerSec", "awaitingReason", "question", "todos", "tail", "lastActivityMs", "lastEventMs", "quietSinceMs", "hostLink", "presence", "pidAlive", "tmuxClients", "windowHeartbeatMs", "provenance", "rateLimited", "plan"];
42
42
  export declare const ACTIVE_SESSIONS_READER_IDLE_WINDOW_MS = 45000;
43
43
  export declare function setActiveSessionsSnapshotPathForTest(p: string | null): string | null;
44
44
  export declare function clearActiveSnapshotMemoryForTest(): void;
@@ -61,6 +61,7 @@ export const LIVE_STATUS_KEYS = [
61
61
  'tail',
62
62
  'lastActivityMs',
63
63
  'lastEventMs',
64
+ 'quietSinceMs',
64
65
  'hostLink',
65
66
  'presence',
66
67
  'pidAlive',
@@ -26,6 +26,20 @@ export declare function sessionHeadline<T extends {
26
26
  generatedTitle?: string | null;
27
27
  topic?: string | null;
28
28
  }>(row: CarriesTitleRung<T>): string | undefined;
29
+ export interface LiveSessionName {
30
+ name: string;
31
+ source?: string;
32
+ }
33
+ export interface SessionNameSources {
34
+ customTitle?: string | null;
35
+ live?: LiveSessionName | null;
36
+ indexed?: string | null;
37
+ launchName?: string | null;
38
+ aiTitle?: string | null;
39
+ }
40
+ export declare function resolveSessionName(n: SessionNameSources): string | undefined;
41
+ export declare const STARTED_AS_MAX_CHARS = 280;
42
+ export declare function startedAsFromUserTurn(text: string): string | undefined;
29
43
  export type SessionTitleRunner = (prompt: string, signal?: AbortSignal) => Promise<string>;
30
44
  export declare function resolveSessionTitleAgent(): Promise<string | null>;
31
45
  export declare function defaultSessionTitleRunner(prompt: string, signal?: AbortSignal): Promise<string>;
@@ -1,4 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
+ import { cleanFirstUserMessage, cleanGeneratedSessionLabel } from '@phnx-labs/sessions-cli/reader';
2
3
  export const SESSION_TITLE_PROMPT_MARKER = 'Generate a concise session headline';
3
4
  export const SESSION_TITLE_MAX_CHARS = 60;
4
5
  export const SESSION_TITLE_MAX_WORDS = 8;
@@ -70,6 +71,37 @@ export function sanitizeGeneratedTitle(raw) {
70
71
  export function sessionHeadline(row) {
71
72
  return row.label || row.generatedTitle || row.topic || undefined;
72
73
  }
74
+ function nonEmpty(s) {
75
+ return s?.trim() || undefined;
76
+ }
77
+ export function resolveSessionName(n) {
78
+ const liveName = n.live && n.live.source !== 'derived' ? nonEmpty(n.live.name) : undefined;
79
+ return (n.live?.source === 'user' ? liveName : undefined)
80
+ ?? nonEmpty(n.customTitle)
81
+ ?? liveName
82
+ ?? nonEmpty(n.indexed)
83
+ ?? nonEmpty(n.launchName)
84
+ ?? cleanGeneratedSessionLabel(n.aiTitle ?? undefined);
85
+ }
86
+ export const STARTED_AS_MAX_CHARS = 280;
87
+ const COMMAND_RE = /<command-name>\s*(\/[^<\s]+)\s*<\/command-name>[\s\S]*?(?:<command-args>([\s\S]*?)<\/command-args>|$)/;
88
+ export function startedAsFromUserTurn(text) {
89
+ const command = COMMAND_RE.exec(text);
90
+ let prompt;
91
+ if (command) {
92
+ const args = command[2]?.trim();
93
+ if (!args)
94
+ return undefined;
95
+ prompt = command[1] === '/goal' ? args : `${command[1]} ${args}`;
96
+ }
97
+ else {
98
+ prompt = cleanFirstUserMessage(text);
99
+ }
100
+ const flat = prompt?.replace(/\s+/g, ' ').trim();
101
+ if (!flat)
102
+ return undefined;
103
+ return flat.length > STARTED_AS_MAX_CHARS ? `${flat.slice(0, STARTED_AS_MAX_CHARS - 1).trimEnd()}…` : flat;
104
+ }
73
105
  export async function resolveSessionTitleAgent() {
74
106
  const { listInstalledVersions } = await import('../installations/store.js');
75
107
  for (const agent of SESSION_TITLE_AGENTS) {
@@ -1,7 +1,8 @@
1
1
  import { AgentStatus, resolveMode } from './agents.js';
2
2
  import { getDelta } from './summarizer.js';
3
3
  import { debug } from './debug.js';
4
- import { buildClaudeLabelMap } from '../session/discover.js';
4
+ import { readClaudeLiveNames } from '../session/discover.js';
5
+ import { resolveSessionName } from '../session/title.js';
5
6
  import { resolveTeammateDelivery } from './delivery.js';
6
7
  import { hasUncommittedChanges } from './worktree.js';
7
8
  function truncateBashCommand(cmd, maxLen = 120) {
@@ -205,8 +206,8 @@ export async function handleStatus(manager, taskName, filter, since, parentSessi
205
206
  }
206
207
  }
207
208
  let maxTimestamp = since || new Date(0).toISOString();
208
- const claudeLabels = allAgents.some((agent) => agent.agentType === 'claude')
209
- ? buildClaudeLabelMap()
209
+ const claudeLiveNames = allAgents.some((agent) => agent.agentType === 'claude')
210
+ ? readClaudeLiveNames()
210
211
  : new Map();
211
212
  for (const agent of agents) {
212
213
  await agent.readNewEvents();
@@ -234,7 +235,7 @@ export async function handleStatus(manager, taskName, filter, since, parentSessi
234
235
  version: agent.version,
235
236
  remote_session_id: agent.remoteSessionId,
236
237
  session_label: agent.remoteSessionId
237
- ? claudeLabels.get(agent.remoteSessionId) ?? null
238
+ ? resolveSessionName({ live: claudeLiveNames.get(agent.remoteSessionId) }) ?? null
238
239
  : null,
239
240
  name: agent.name,
240
241
  after: agent.after,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phnx-labs/agents-cli",
3
- "version": "1.23.24",
3
+ "version": "1.23.26",
4
4
  "description": "One CLI for all your AI coding agents - versions, config, cloud dispatch, sessions, and teams (now with first-class Grok Build CLI support)",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -89,7 +89,7 @@
89
89
  "@fontsource/jetbrains-mono": "^5.3.0",
90
90
  "@inquirer/prompts": "8.5.2",
91
91
  "@phnx-labs/secrets-cli": "0.4.0",
92
- "@phnx-labs/sessions-cli": "0.8.4",
92
+ "@phnx-labs/sessions-cli": "0.8.6",
93
93
  "@resvg/resvg-wasm": "^2.6.2",
94
94
  "@types/proper-lockfile": "4.1.4",
95
95
  "@zed-industries/agent-client-protocol": "0.4.5",