@phnx-labs/agents-cli 1.23.29 → 1.23.31

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.31
4
+
5
+ - **A session row's `title` is the one name to show, and a fork says it is one.** `title` on `agents ps --json`, `agents ps watch --json` and `agents feed watch --json` (live and history rows) is never Claude's `<folder>-<n>` placeholder such as "agents-92" or "agents-1f", never the `[host/<device>]` fallback, and never an injected note, sub-agent hand-back or bare slash command; it falls through to the next usable name instead of going empty. A session started by `agents fork` carries `forkOf` (the source session id) and, until it has a name of its own, the source's name as its `title` instead of "fork of …". `agents fork` no longer launches an unnamed fork with `--name "fork of …"`, so the harness's own title takes over once it writes one; `--name` still names it. Source: `cli/src/lib/session/title.ts`, `cli/src/lib/session/fork.ts`, `cli/src/lib/session/active.ts`, `cli/src/lib/session/remote/watch.ts`, `cli/src/commands/fork.ts`.
6
+
7
+ ## 1.23.30
8
+
9
+ - **Session rows tell the truth about questions, replies, PRs and limits (#3989).** A permission prompt no longer replaces the open question a Claude session is asking, and an `AskUserQuestion` permission request opens nothing of its own, so the question's choices stay answerable. A question the user rejects clears (`PostToolUseFailure`), so the next permission prompt shows. `agents feed answer` types into the terminal the watchdog resolves (a VSCodium tab, or a tmux pane) when the session has no reply rail; VSCodium cannot confirm delivery, so that answer reports `unknown` and resolves when the session moves on. Live rows carry `prs` when a session opened more than one PR (rows of ended sessions keep the newest `pr`). With `@phnx-labs/sessions-cli` 0.8.7, a session reads as rate-limited only when it is stopped on a limit (not when its tool output mentions 429), a transcript ending in a large compaction line still reads, and pages rewritten under `.agents/artifacts/`, `plans/` or `reports/` count as artifacts. Source: cli/src/lib/feed/feed.ts, cli/src/lib/answer-router.ts, cli/src/lib/session/active.ts
10
+
11
+ - **A live Claude session row carries Claude's own recap.** Claude Code periodically writes a recap of the session into its transcript (`away_summary`). The newest one now rides the session row as `recap: { text, at }`, without the "(disable recaps in /config)" hint, on `agents ps --json`, `agents ps watch --json` and `agents feed watch --json`, so AGI EXT can show where a session stands without reading the transcript. It comes from the existing index scan; a session indexed before this version gets it with its next recap. Source: `cli/src/lib/session/discover.ts`, `cli/src/lib/session/db.ts`, `cli/src/lib/session/active.ts`, `cli/src/lib/session/title.ts`.
12
+
3
13
  ## 1.23.29
4
14
 
5
15
  - **Removed: routines (`agents routines`, the scheduler and catch-up services, routine sync).** Routines never worked reliably, so they are deprecated and gone as of this version. `agents routines` and its old `agents jobs`/`agents cron` aliases are now unknown commands. Also removed with them: the daemon's `scheduler` and `catchup` services, the `scheduler.enabled` device config key, project routine sync and routine device activation, `agents cloud run --on` event triggers, `agents prune cleanup runs`, the `routines:` list in the `fleet:` manifest, the `--routine` filters on `agents ps` and `agents ps focus`, the `agents inspect --routines` drill-down, the `fleet` placement kind (`--where fleet`), session lookup by routine run id, the `routine.start`/`routine.end` events, and the routine fields in JSON output (`jobCount` in `agents daemon status`, `detachedChildren` in `agents daemon stop`, `routines` in `agents menubar snapshot`, `recentRuns` in the factory snapshot, `origin`/`routineName` on `agents ps --json` rows). For scheduled agent work, use OS cron, a systemd timer or launchd and call `agents run` from it, for example `0 9 * * 1-5 agents run claude "triage the open PRs"`. Existing `~/.agents/routines/*.yml` files and leftover `scheduler`/`catchup`/`schedulerEnabled`/`routines:` config keys are ignored rather than rejected, so nothing breaks on upgrade. Source: cli/src/lib/daemon/daemon.ts, cli/src/lib/daemon-services.ts, cli/src/lib/state.ts
@@ -40,6 +40,8 @@ const FORK_HELP = {
40
40
  - The recap carries the source id — the sibling can run '/continue <id>' for the
41
41
  full history if it needs more than the recap.
42
42
  - Resolve the source the same way as resume: an exact or prefix id fragment.
43
+ - Without --name the fork's row carries forkOf (the source id) and the source's
44
+ name as its title until the harness gives the fork a name of its own.
43
45
  `,
44
46
  };
45
47
  export async function runFork(sessionArg, options, deps = defaultDeps()) {
@@ -81,7 +83,9 @@ export async function runFork(sessionArg, options, deps = defaultDeps()) {
81
83
  lastAssistant: digest?.lastAssistant,
82
84
  changes: digest?.changes,
83
85
  });
84
- const runArgs = ['run', source.agent, recap, '-i', '--strategy', 'balanced', '--name', options.name || `fork of ${label}`];
86
+ const runArgs = ['run', source.agent, recap, '-i', '--strategy', 'balanced'];
87
+ if (options.name)
88
+ runArgs.push('--name', options.name);
85
89
  const sourceIsHere = !source.machine || isSelfHost(source.machine);
86
90
  const landsOnSource = !options.device
87
91
  ? sourceIsHere
@@ -106,7 +110,7 @@ export function registerForkCommand(program) {
106
110
  const cmd = program
107
111
  .command('fork <session>')
108
112
  .description('Branch a session into a new same-harness sibling, seeded with a recap so it continues the work. The original is untouched.')
109
- .option('--name <label>', 'Session label for the fork (default: "fork of <original>")')
113
+ .option('--name <label>', 'Session label for the fork (default: the source\'s name until the fork names itself)')
110
114
  .option('--device <host>', 'Place the sibling on a fleet device (name or "auto"); defaults to here')
111
115
  .option('--terminal [backend]', 'Open the sibling in a real terminal tab (iterm | ghostty | terminal | tmux | vscodium-agent) instead of in-place');
112
116
  setHelpSections(cmd, FORK_HELP);
@@ -1,7 +1,7 @@
1
1
  import { type OpenBlock, type BlockOption } from './feed/feed.js';
2
2
  import type { ActiveSession } from './session/active.js';
3
3
  import type { InjectTarget } from './terminal/index.js';
4
- export type AnswerRouteKind = 'mailbox' | 'tmux' | 'iterm' | 'resume' | 'refuse';
4
+ export type AnswerRouteKind = 'mailbox' | 'tmux' | 'iterm' | 'vscodium' | 'resume' | 'refuse';
5
5
  export interface AnswerRoute {
6
6
  kind: AnswerRouteKind;
7
7
  reason: string;
@@ -1,5 +1,5 @@
1
1
  import { deriveBlockState } from './feed/feed.js';
2
- import { addressabilityRecoveryHint } from './terminal/resolve.js';
2
+ import { addressabilityRecoveryHint, resolveInjectTargetForSession } from './terminal/resolve.js';
3
3
  import { injectTargetFromReplyRail } from './session/inject.js';
4
4
  const ESCAPE_KEY = '\u001b';
5
5
  export function matchOptionIndex(answer, options) {
@@ -56,12 +56,11 @@ export function isOpenQuestionBlock(block) {
56
56
  return (block.questions?.length ?? 0) > 0;
57
57
  }
58
58
  function injectTargetForSession(session) {
59
- if (session.provenance?.reply) {
60
- const fromRail = injectTargetFromReplyRail(session.provenance.reply);
61
- if (fromRail)
62
- return fromRail;
63
- }
64
- return null;
59
+ const fromRail = session.provenance?.reply ? injectTargetFromReplyRail(session.provenance.reply) : null;
60
+ if (fromRail)
61
+ return fromRail;
62
+ const resolved = resolveInjectTargetForSession(session);
63
+ return resolved.addressable ? resolved.target : null;
65
64
  }
66
65
  export function resolveAnswerRoute(input) {
67
66
  const { answer, block, session } = input;
@@ -73,8 +72,8 @@ export function resolveAnswerRoute(input) {
73
72
  const inject = injectTargetForSession(session);
74
73
  const { payload, matched, enter } = keystrokesForAnswer(answer, options);
75
74
  if (inject) {
76
- const kind = inject.backend === 'tmux' ? 'tmux'
77
- : inject.backend === 'iterm' ? 'iterm'
75
+ const kind = inject.backend === 'iterm' ? 'iterm'
76
+ : inject.backend === 'vscodium' ? 'vscodium'
78
77
  : 'tmux';
79
78
  return {
80
79
  kind,
@@ -101,7 +100,7 @@ export function resolveAnswerRoute(input) {
101
100
  }
102
101
  return {
103
102
  kind: 'refuse',
104
- reason: 'Agent is parked on a question but has no addressable terminal (no tmux/iterm rail). ' +
103
+ reason: 'Agent is parked on a question but has no addressable terminal (no tmux, iTerm or IDE rail). ' +
105
104
  addressabilityRecoveryHint(session),
106
105
  };
107
106
  }
@@ -161,7 +161,7 @@ export declare function publishBlock(block: OpenBlock, root?: string): void;
161
161
  export declare function listBlocks(root?: string): OpenBlock[];
162
162
  export declare function listAskStats(root?: string): FeedAskStats[];
163
163
  export declare function removeBlock(blockId: string, root?: string): boolean;
164
- export declare const FEED_PUBLISH_HOOK_SCRIPT = "#!/usr/bin/env python3\n\"\"\"Publish and clear open-block records for `agents feed`.\n\nThe manifest invokes this script for top-level AskUserQuestion calls, waiting\nnotifications, question answers, and session lifecycle events. One atomic file\nper session means a new block replaces the previous block. Answer/resume/stop\nevents remove it so `agents feed` only lists decisions that are still open.\n\nSub-agent gate: when the PreToolUse payload carries `agent_type`, this is a\nTask/Agent subagent -- skip. Only the top-level agent publishes. Verified on\nClaude Code 2.1.170 (2026-07).\n\nFail-open: ANY error is swallowed so a feed hiccup never blocks a tool call.\n\"\"\"\nimport os\nimport sys\nimport json\nimport re\nimport socket\nimport tempfile\nfrom datetime import datetime, timezone\n\nWAITING_NOTIFICATION_TYPES = {\n \"permission_prompt\",\n \"elicitation_dialog\",\n}\nCLEAR_EVENTS = {\n \"PostToolUse\",\n \"Stop\",\n \"SessionEnd\",\n}\n\n\ndef read_json(path):\n try:\n with open(path) as f:\n return json.load(f)\n except Exception:\n return None\n\n\ndef write_json(path, value):\n dir_name = os.path.dirname(path)\n os.makedirs(dir_name, exist_ok=True)\n fd, tmp = tempfile.mkstemp(dir=dir_name, suffix=\".tmp\")\n try:\n with os.fdopen(fd, \"w\") as f:\n json.dump(value, f, indent=2)\n os.replace(tmp, path)\n except Exception:\n try:\n os.unlink(tmp)\n except Exception:\n pass\n\n\ndef project_from_cwd(cwd):\n \"\"\"Basename of cwd, with worktree paths resolved to their repo name.\"\"\"\n if not cwd:\n return None\n norm = cwd.replace(\"\\\\\", \"/\").rstrip(\"/\")\n if not norm:\n return None\n marker = \"/.agents/worktrees/\"\n idx = norm.find(marker)\n if idx > 0:\n repo_path = norm[:idx]\n base = repo_path[repo_path.rfind(\"/\") + 1:]\n if base:\n return base\n base = norm[norm.rfind(\"/\") + 1:]\n return base or None\n\n\ndef main():\n raw = sys.stdin.read()\n try:\n payload = json.loads(raw) if raw.strip() else {}\n except Exception:\n return\n\n if payload.get(\"agent_type\"):\n return\n\n session_id = payload.get(\"session_id\", \"\")\n if not session_id:\n return\n\n safe_session_id = re.sub(r\"[^A-Za-z0-9._-]\", \"-\", session_id)\n block_id = f\"block-{safe_session_id}\"\n home = os.environ.get(\"HOME\") or os.path.expanduser(\"~\")\n feed_dir = os.path.join(home, \".agents\", \".history\", \"feed\")\n answered_dir = os.path.join(feed_dir, \"answered\")\n asks_dir = os.path.join(feed_dir, \"asks\")\n target = os.path.join(feed_dir, f\"{block_id}.json\")\n hook_event = payload.get(\"hook_event_name\", \"PreToolUse\")\n\n if hook_event in CLEAR_EVENTS:\n try:\n with open(target) as existing_file:\n existing = json.load(existing_file)\n answered = os.path.exists(os.path.join(answered_dir, f\"{block_id}.json\"))\n\n # Ordinary lifecycle hooks cannot clear a declared block before it is answered.\n if existing.get(\"kind\") == \"declared\" and not answered:\n return\n except Exception:\n pass\n if hook_event == \"PostToolUse\":\n try:\n with open(target) as existing_file:\n existing = json.load(existing_file)\n if existing.get(\"kind\") == \"question\" and payload.get(\"tool_name\") != \"AskUserQuestion\":\n return\n except Exception:\n pass\n try:\n os.unlink(target)\n except FileNotFoundError:\n pass\n except Exception:\n pass\n try:\n os.unlink(os.path.join(answered_dir, f\"{block_id}.json\"))\n except FileNotFoundError:\n pass\n except Exception:\n pass\n return\n\n if hook_event == \"UserPromptSubmit\":\n os.makedirs(answered_dir, exist_ok=True)\n marker = os.path.join(answered_dir, f\"{block_id}.json\")\n now_iso = datetime.now(timezone.utc).isoformat()\n try:\n fd = os.open(marker, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)\n record = {\n \"answeredAt\": now_iso,\n \"answeredFrom\": \"terminal\",\n }\n with os.fdopen(fd, \"w\") as f:\n json.dump(record, f, indent=2)\n except FileExistsError:\n pass\n except Exception:\n pass\n existing = read_json(target)\n if isinstance(existing, dict):\n generation = existing.get(\"generation\") or existing.get(\"ts\")\n if generation:\n tombstone = {\n \"blockId\": block_id,\n \"generation\": generation,\n \"resolvedAt\": now_iso,\n \"reason\": \"answered\",\n }\n source_cursor = existing.get(\"sourceCursor\")\n if source_cursor:\n tombstone[\"sourceCursor\"] = source_cursor\n write_json(\n os.path.join(feed_dir, \"resolutions\", f\"{block_id}.json\"),\n tombstone,\n )\n try:\n os.unlink(target)\n except FileNotFoundError:\n pass\n except Exception:\n pass\n return\n\n notification_type = None\n codex_approval = False\n if hook_event == \"Notification\":\n notification_type = payload.get(\"notification_type\", \"\")\n if notification_type not in WAITING_NOTIFICATION_TYPES:\n return\n try:\n with open(target) as existing_file:\n existing = json.load(existing_file)\n if existing.get(\"kind\") == \"question\":\n return\n if (\n notification_type == \"permission_prompt\"\n and existing.get(\"notificationType\") == \"permission_prompt\"\n and (existing.get(\"questions\") or [{}])[0].get(\"header\") == \"Approval needed\"\n ):\n return\n except Exception:\n pass\n message = payload.get(\"message\", \"\")\n if not message:\n return\n normalized_questions = [{\n \"text\": message,\n \"header\": payload.get(\"title\") or notification_type.replace(\"_\", \" \").title(),\n \"multiSelect\": False,\n }]\n kind = \"notification\"\n elif hook_event == \"PermissionRequest\":\n tool_name = payload.get(\"tool_name\") or \"a tool\"\n tool_input = payload.get(\"tool_input\", {})\n transcript_path = str(payload.get(\"transcript_path\") or \"\")\n is_claude = \"permission_suggestions\" in payload or \"/.claude/\" in transcript_path.replace(os.sep, \"/\")\n command = \"\"\n if isinstance(tool_input, dict):\n command = (\n tool_input.get(\"command\")\n or tool_input.get(\"cmd\")\n or tool_input.get(\"path\")\n or (tool_input.get(\"file_path\") or tool_input.get(\"url\") or tool_input.get(\"pattern\") if is_claude else \"\")\n or \"\"\n )\n if isinstance(command, list):\n command = \" \".join(str(c) for c in command)\n detail = f\": {command}\" if command else \"\"\n who = \"Claude\" if is_claude else \"Codex\"\n normalized_questions = [{\n \"text\": f\"{who} needs approval to run {tool_name}{detail}\",\n \"header\": \"Approval needed\",\n \"multiSelect\": False,\n }]\n kind = \"notification\"\n notification_type = \"permission_prompt\"\n codex_approval = not is_claude\n else:\n tool_input = payload.get(\"tool_input\", {})\n questions = tool_input.get(\"questions\", [])\n if not questions:\n return\n normalized_questions = []\n for q in questions:\n if not isinstance(q, dict):\n continue\n question = {\n \"text\": q.get(\"question\", q.get(\"header\", \"\")),\n \"header\": q.get(\"header\"),\n \"multiSelect\": q.get(\"multiSelect\", False),\n }\n raw_opts = q.get(\"options\", [])\n if raw_opts:\n question[\"options\"] = [\n {\"label\": o.get(\"label\", \"\"), \"description\": o.get(\"description\")}\n for o in raw_opts\n if isinstance(o, dict)\n ]\n normalized_questions.append(question)\n if not normalized_questions:\n return\n kind = \"question\"\n\n mailbox_id = os.path.basename(\n os.environ.get(\"AGENTS_MAILBOX_DIR\", \"\").rstrip(\"/\")\n ) or session_id\n\n now = datetime.now(timezone.utc)\n now_iso = now.isoformat()\n now_ms = int(now.timestamp() * 1000)\n stats_path = os.path.join(asks_dir, f\"{safe_session_id}.json\")\n stats = read_json(stats_path) or {}\n recent = stats.get(\"recentAskTimestamps\") if isinstance(stats, dict) else []\n if not isinstance(recent, list):\n recent = []\n recent.append(now_iso)\n recent = recent[-200:]\n write_json(stats_path, {\n \"sessionId\": session_id,\n \"mailboxId\": mailbox_id,\n \"firstAskAt\": stats.get(\"firstAskAt\") or now_iso,\n \"lastAskAt\": now_iso,\n \"totalAskCount\": int(stats.get(\"totalAskCount\") or 0) + 1,\n \"recentAskTimestamps\": recent,\n })\n\n hostname = os.environ.get(\"AGENTS_SYNC_MACHINE_ID\") or socket.gethostname()\n host = hostname.split(\".\")[0].strip().lower()\n host = re.sub(r\"[^a-z0-9_-]\", \"-\", host) or \"unknown\"\n\n runtime = os.environ.get(\"AGENTS_RUNTIME\", \"headless\")\n cwd = payload.get(\"cwd\") or os.environ.get(\"AGENTS_CWD\")\n project = project_from_cwd(cwd)\n\n block = {\n \"blockId\": block_id,\n \"sessionId\": session_id,\n \"mailboxId\": mailbox_id,\n \"host\": host,\n \"runtime\": runtime,\n \"ts\": now_iso,\n \"sourceCursor\": {\"lastActivityMs\": now_ms},\n \"questions\": normalized_questions,\n \"kind\": kind,\n }\n if project:\n block[\"project\"] = project\n if notification_type:\n block[\"notificationType\"] = notification_type\n\n if codex_approval:\n block[\"blockClass\"] = \"approval\"\n block[\"costOfDelay\"] = \"high\"\n block[\"safeDefault\"] = \"deny\"\n\n controls = payload.get(\"tool_input\", {}) if hook_event not in (\"Notification\", \"PermissionRequest\") else {}\n block_class = controls.get(\"blockClass\") if isinstance(controls, dict) else None\n if block_class in (\"approval\", \"decision\"):\n block[\"blockClass\"] = block_class\n consequence = controls.get(\"consequence\") if isinstance(controls, dict) else None\n if consequence:\n block[\"consequence\"] = consequence\n allowed = controls.get(\"allowedOperators\") if isinstance(controls, dict) else None\n if isinstance(allowed, list):\n block[\"allowedOperators\"] = [str(a) for a in allowed]\n timeout = controls.get(\"timeoutMinutes\") if isinstance(controls, dict) else None\n if isinstance(timeout, (int, float)) and timeout > 0:\n block[\"timeoutMinutes\"] = int(timeout)\n safe_default = controls.get(\"safeDefault\") if isinstance(controls, dict) else None\n if isinstance(safe_default, str):\n block[\"safeDefault\"] = safe_default\n cost = controls.get(\"costOfDelay\") if isinstance(controls, dict) else None\n if cost in (\"low\", \"medium\", \"high\"):\n block[\"costOfDelay\"] = cost\n\n try:\n os.unlink(os.path.join(answered_dir, f\"{block_id}.json\"))\n except FileNotFoundError:\n pass\n except Exception:\n pass\n\n os.makedirs(feed_dir, exist_ok=True)\n\n fd, tmp = tempfile.mkstemp(dir=feed_dir, suffix=\".tmp\")\n try:\n with os.fdopen(fd, \"w\") as f:\n json.dump(block, f, indent=2)\n os.replace(tmp, target)\n except Exception:\n try:\n os.unlink(tmp)\n except Exception:\n pass\n\n\nif __name__ == \"__main__\":\n try:\n main()\n except Exception:\n pass\n";
164
+ export declare const FEED_PUBLISH_HOOK_SCRIPT = "#!/usr/bin/env python3\n\"\"\"Publish and clear open-block records for `agents feed`.\n\nThe manifest invokes this script for top-level AskUserQuestion calls, waiting\nnotifications, question answers, and session lifecycle events. One atomic file\nper session means a new block replaces the previous block. Answer/resume/stop\nevents remove it so `agents feed` only lists decisions that are still open.\n\nSub-agent gate: when the PreToolUse payload carries `agent_type`, this is a\nTask/Agent subagent -- skip. Only the top-level agent publishes. Verified on\nClaude Code 2.1.170 (2026-07).\n\nFail-open: ANY error is swallowed so a feed hiccup never blocks a tool call.\n\"\"\"\nimport os\nimport sys\nimport json\nimport re\nimport socket\nimport tempfile\nfrom datetime import datetime, timezone\n\nWAITING_NOTIFICATION_TYPES = {\n \"permission_prompt\",\n \"elicitation_dialog\",\n}\nCLEAR_EVENTS = {\n \"PostToolUse\",\n \"PostToolUseFailure\",\n \"Stop\",\n \"SessionEnd\",\n}\n\n\ndef read_json(path):\n try:\n with open(path) as f:\n return json.load(f)\n except Exception:\n return None\n\n\ndef write_json(path, value):\n dir_name = os.path.dirname(path)\n os.makedirs(dir_name, exist_ok=True)\n fd, tmp = tempfile.mkstemp(dir=dir_name, suffix=\".tmp\")\n try:\n with os.fdopen(fd, \"w\") as f:\n json.dump(value, f, indent=2)\n os.replace(tmp, path)\n except Exception:\n try:\n os.unlink(tmp)\n except Exception:\n pass\n\n\ndef project_from_cwd(cwd):\n \"\"\"Basename of cwd, with worktree paths resolved to their repo name.\"\"\"\n if not cwd:\n return None\n norm = cwd.replace(\"\\\\\", \"/\").rstrip(\"/\")\n if not norm:\n return None\n marker = \"/.agents/worktrees/\"\n idx = norm.find(marker)\n if idx > 0:\n repo_path = norm[:idx]\n base = repo_path[repo_path.rfind(\"/\") + 1:]\n if base:\n return base\n base = norm[norm.rfind(\"/\") + 1:]\n return base or None\n\n\ndef main():\n raw = sys.stdin.read()\n try:\n payload = json.loads(raw) if raw.strip() else {}\n except Exception:\n return\n\n if payload.get(\"agent_type\"):\n return\n\n session_id = payload.get(\"session_id\", \"\")\n if not session_id:\n return\n\n safe_session_id = re.sub(r\"[^A-Za-z0-9._-]\", \"-\", session_id)\n block_id = f\"block-{safe_session_id}\"\n home = os.environ.get(\"HOME\") or os.path.expanduser(\"~\")\n feed_dir = os.path.join(home, \".agents\", \".history\", \"feed\")\n answered_dir = os.path.join(feed_dir, \"answered\")\n asks_dir = os.path.join(feed_dir, \"asks\")\n target = os.path.join(feed_dir, f\"{block_id}.json\")\n hook_event = payload.get(\"hook_event_name\", \"PreToolUse\")\n\n if hook_event in CLEAR_EVENTS:\n try:\n with open(target) as existing_file:\n existing = json.load(existing_file)\n answered = os.path.exists(os.path.join(answered_dir, f\"{block_id}.json\"))\n\n # Ordinary lifecycle hooks cannot clear a declared block before it is answered.\n if existing.get(\"kind\") == \"declared\" and not answered:\n return\n except Exception:\n pass\n if hook_event in (\"PostToolUse\", \"PostToolUseFailure\"):\n try:\n with open(target) as existing_file:\n existing = json.load(existing_file)\n if existing.get(\"kind\") == \"question\" and payload.get(\"tool_name\") != \"AskUserQuestion\":\n return\n except Exception:\n pass\n try:\n os.unlink(target)\n except FileNotFoundError:\n pass\n except Exception:\n pass\n try:\n os.unlink(os.path.join(answered_dir, f\"{block_id}.json\"))\n except FileNotFoundError:\n pass\n except Exception:\n pass\n return\n\n if hook_event == \"UserPromptSubmit\":\n os.makedirs(answered_dir, exist_ok=True)\n marker = os.path.join(answered_dir, f\"{block_id}.json\")\n now_iso = datetime.now(timezone.utc).isoformat()\n try:\n fd = os.open(marker, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)\n record = {\n \"answeredAt\": now_iso,\n \"answeredFrom\": \"terminal\",\n }\n with os.fdopen(fd, \"w\") as f:\n json.dump(record, f, indent=2)\n except FileExistsError:\n pass\n except Exception:\n pass\n existing = read_json(target)\n if isinstance(existing, dict):\n generation = existing.get(\"generation\") or existing.get(\"ts\")\n if generation:\n tombstone = {\n \"blockId\": block_id,\n \"generation\": generation,\n \"resolvedAt\": now_iso,\n \"reason\": \"answered\",\n }\n source_cursor = existing.get(\"sourceCursor\")\n if source_cursor:\n tombstone[\"sourceCursor\"] = source_cursor\n write_json(\n os.path.join(feed_dir, \"resolutions\", f\"{block_id}.json\"),\n tombstone,\n )\n try:\n os.unlink(target)\n except FileNotFoundError:\n pass\n except Exception:\n pass\n return\n\n notification_type = None\n codex_approval = False\n if hook_event == \"Notification\":\n notification_type = payload.get(\"notification_type\", \"\")\n if notification_type not in WAITING_NOTIFICATION_TYPES:\n return\n try:\n with open(target) as existing_file:\n existing = json.load(existing_file)\n if existing.get(\"kind\") == \"question\":\n return\n if (\n notification_type == \"permission_prompt\"\n and existing.get(\"notificationType\") == \"permission_prompt\"\n and (existing.get(\"questions\") or [{}])[0].get(\"header\") == \"Approval needed\"\n ):\n return\n except Exception:\n pass\n message = payload.get(\"message\", \"\")\n if not message:\n return\n normalized_questions = [{\n \"text\": message,\n \"header\": payload.get(\"title\") or notification_type.replace(\"_\", \" \").title(),\n \"multiSelect\": False,\n }]\n kind = \"notification\"\n elif hook_event == \"PermissionRequest\":\n tool_name = payload.get(\"tool_name\") or \"a tool\"\n if tool_name == \"AskUserQuestion\":\n return\n try:\n with open(target) as existing_file:\n existing = json.load(existing_file)\n if existing.get(\"kind\") == \"question\":\n return\n except Exception:\n pass\n tool_input = payload.get(\"tool_input\", {})\n transcript_path = str(payload.get(\"transcript_path\") or \"\")\n is_claude = \"permission_suggestions\" in payload or \"/.claude/\" in transcript_path.replace(os.sep, \"/\")\n command = \"\"\n if isinstance(tool_input, dict):\n command = (\n tool_input.get(\"command\")\n or tool_input.get(\"cmd\")\n or tool_input.get(\"path\")\n or (tool_input.get(\"file_path\") or tool_input.get(\"url\") or tool_input.get(\"pattern\") if is_claude else \"\")\n or \"\"\n )\n if isinstance(command, list):\n command = \" \".join(str(c) for c in command)\n detail = f\": {command}\" if command else \"\"\n who = \"Claude\" if is_claude else \"Codex\"\n normalized_questions = [{\n \"text\": f\"{who} needs approval to run {tool_name}{detail}\",\n \"header\": \"Approval needed\",\n \"multiSelect\": False,\n }]\n kind = \"notification\"\n notification_type = \"permission_prompt\"\n codex_approval = not is_claude\n else:\n tool_input = payload.get(\"tool_input\", {})\n questions = tool_input.get(\"questions\", [])\n if not questions:\n return\n normalized_questions = []\n for q in questions:\n if not isinstance(q, dict):\n continue\n question = {\n \"text\": q.get(\"question\", q.get(\"header\", \"\")),\n \"header\": q.get(\"header\"),\n \"multiSelect\": q.get(\"multiSelect\", False),\n }\n raw_opts = q.get(\"options\", [])\n if raw_opts:\n question[\"options\"] = [\n {\"label\": o.get(\"label\", \"\"), \"description\": o.get(\"description\")}\n for o in raw_opts\n if isinstance(o, dict)\n ]\n normalized_questions.append(question)\n if not normalized_questions:\n return\n kind = \"question\"\n\n mailbox_id = os.path.basename(\n os.environ.get(\"AGENTS_MAILBOX_DIR\", \"\").rstrip(\"/\")\n ) or session_id\n\n now = datetime.now(timezone.utc)\n now_iso = now.isoformat()\n now_ms = int(now.timestamp() * 1000)\n stats_path = os.path.join(asks_dir, f\"{safe_session_id}.json\")\n stats = read_json(stats_path) or {}\n recent = stats.get(\"recentAskTimestamps\") if isinstance(stats, dict) else []\n if not isinstance(recent, list):\n recent = []\n recent.append(now_iso)\n recent = recent[-200:]\n write_json(stats_path, {\n \"sessionId\": session_id,\n \"mailboxId\": mailbox_id,\n \"firstAskAt\": stats.get(\"firstAskAt\") or now_iso,\n \"lastAskAt\": now_iso,\n \"totalAskCount\": int(stats.get(\"totalAskCount\") or 0) + 1,\n \"recentAskTimestamps\": recent,\n })\n\n hostname = os.environ.get(\"AGENTS_SYNC_MACHINE_ID\") or socket.gethostname()\n host = hostname.split(\".\")[0].strip().lower()\n host = re.sub(r\"[^a-z0-9_-]\", \"-\", host) or \"unknown\"\n\n runtime = os.environ.get(\"AGENTS_RUNTIME\", \"headless\")\n cwd = payload.get(\"cwd\") or os.environ.get(\"AGENTS_CWD\")\n project = project_from_cwd(cwd)\n\n block = {\n \"blockId\": block_id,\n \"sessionId\": session_id,\n \"mailboxId\": mailbox_id,\n \"host\": host,\n \"runtime\": runtime,\n \"ts\": now_iso,\n \"sourceCursor\": {\"lastActivityMs\": now_ms},\n \"questions\": normalized_questions,\n \"kind\": kind,\n }\n if project:\n block[\"project\"] = project\n if notification_type:\n block[\"notificationType\"] = notification_type\n\n if codex_approval:\n block[\"blockClass\"] = \"approval\"\n block[\"costOfDelay\"] = \"high\"\n block[\"safeDefault\"] = \"deny\"\n\n controls = payload.get(\"tool_input\", {}) if hook_event not in (\"Notification\", \"PermissionRequest\") else {}\n block_class = controls.get(\"blockClass\") if isinstance(controls, dict) else None\n if block_class in (\"approval\", \"decision\"):\n block[\"blockClass\"] = block_class\n consequence = controls.get(\"consequence\") if isinstance(controls, dict) else None\n if consequence:\n block[\"consequence\"] = consequence\n allowed = controls.get(\"allowedOperators\") if isinstance(controls, dict) else None\n if isinstance(allowed, list):\n block[\"allowedOperators\"] = [str(a) for a in allowed]\n timeout = controls.get(\"timeoutMinutes\") if isinstance(controls, dict) else None\n if isinstance(timeout, (int, float)) and timeout > 0:\n block[\"timeoutMinutes\"] = int(timeout)\n safe_default = controls.get(\"safeDefault\") if isinstance(controls, dict) else None\n if isinstance(safe_default, str):\n block[\"safeDefault\"] = safe_default\n cost = controls.get(\"costOfDelay\") if isinstance(controls, dict) else None\n if cost in (\"low\", \"medium\", \"high\"):\n block[\"costOfDelay\"] = cost\n\n try:\n os.unlink(os.path.join(answered_dir, f\"{block_id}.json\"))\n except FileNotFoundError:\n pass\n except Exception:\n pass\n\n os.makedirs(feed_dir, exist_ok=True)\n\n fd, tmp = tempfile.mkstemp(dir=feed_dir, suffix=\".tmp\")\n try:\n with os.fdopen(fd, \"w\") as f:\n json.dump(block, f, indent=2)\n os.replace(tmp, target)\n except Exception:\n try:\n os.unlink(tmp)\n except Exception:\n pass\n\n\nif __name__ == \"__main__\":\n try:\n main()\n except Exception:\n pass\n";
165
165
  export declare function ensureFeedPublishHook(userAgentsDir?: string): {
166
166
  installed: boolean;
167
167
  error?: string;
@@ -510,6 +510,7 @@ WAITING_NOTIFICATION_TYPES = {
510
510
  }
511
511
  CLEAR_EVENTS = {
512
512
  "PostToolUse",
513
+ "PostToolUseFailure",
513
514
  "Stop",
514
515
  "SessionEnd",
515
516
  }
@@ -590,7 +591,7 @@ def main():
590
591
  return
591
592
  except Exception:
592
593
  pass
593
- if hook_event == "PostToolUse":
594
+ if hook_event in ("PostToolUse", "PostToolUseFailure"):
594
595
  try:
595
596
  with open(target) as existing_file:
596
597
  existing = json.load(existing_file)
@@ -683,6 +684,15 @@ def main():
683
684
  kind = "notification"
684
685
  elif hook_event == "PermissionRequest":
685
686
  tool_name = payload.get("tool_name") or "a tool"
687
+ if tool_name == "AskUserQuestion":
688
+ return
689
+ try:
690
+ with open(target) as existing_file:
691
+ existing = json.load(existing_file)
692
+ if existing.get("kind") == "question":
693
+ return
694
+ except Exception:
695
+ pass
686
696
  tool_input = payload.get("tool_input", {})
687
697
  transcript_path = str(payload.get("transcript_path") or "")
688
698
  is_claude = "permission_suggestions" in payload or "/.claude/" in transcript_path.replace(os.sep, "/")
@@ -879,6 +889,13 @@ export function ensureFeedPublishHook(userAgentsDir = getUserAgentsDir()) {
879
889
  script: '10-feed-publish.py',
880
890
  timeout: 5,
881
891
  },
892
+ 'feed-clear-answered-failure': {
893
+ agents: ['claude'],
894
+ events: ['PostToolUseFailure'],
895
+ matcher: 'AskUserQuestion',
896
+ script: '10-feed-publish.py',
897
+ timeout: 5,
898
+ },
882
899
  'feed-clear-permission': {
883
900
  agents: ['codex'],
884
901
  events: ['PostToolUse'],
@@ -1,6 +1,7 @@
1
1
  import type { CloudTaskStatus } from '../cloud/types.js';
2
2
  import { type PidSessionEntry } from './pid-registry.js';
3
3
  import { type HookSessionIndex } from './hook-sessions.js';
4
+ import { type SessionRecap } from './title.js';
4
5
  import { type UserPromptKind } from '@phnx-labs/sessions-cli/reader';
5
6
  import { type SessionState, type SessionActivity, type AwaitingReason, type StructuredQuestion, type TodoProgress, type DetectedPr, type DetectedWorktree, type DetectedTicket } from '@phnx-labs/sessions-cli/reader';
6
7
  import { type SessionAgentId, type SessionAttachment, type SessionFiles, type SessionMeta, type SessionRequest, type SessionTimeline } from '@phnx-labs/sessions-cli/reader';
@@ -42,7 +43,7 @@ export declare function serializeActiveSessionsForJson(sessions: ActiveSession[]
42
43
  export declare function serializeSessionsJson(sessions: SessionMeta[]): string;
43
44
  export type ActiveStatus = 'running' | 'idle' | 'queued' | 'input_required' | 'closed' | 'abandoned' | 'orphaned' | 'crashed' | 'unknown';
44
45
  export type SessionPhase = 'running' | 'waiting' | 'failed' | 'done' | 'idle';
45
- export type RecapSource = 'label' | 'generated' | 'prompt';
46
+ export type RecapSource = 'label' | 'generated' | 'fork' | 'prompt';
46
47
  export type ImportantMessageKind = 'question' | 'needs_you' | 'activity';
47
48
  export interface SessionImportantMessage {
48
49
  text: string;
@@ -79,7 +80,9 @@ export interface ActiveSession {
79
80
  lastUserMessage?: string;
80
81
  generatedTitle?: string;
81
82
  title?: string;
83
+ forkOf?: string;
82
84
  startedAs?: string;
85
+ recap?: SessionRecap;
83
86
  recapSource?: RecapSource;
84
87
  userPromptClean?: string;
85
88
  userPromptKind?: UserPromptKind;
@@ -99,6 +102,7 @@ export interface ActiveSession {
99
102
  todos?: TodoProgress;
100
103
  tail?: string[];
101
104
  pr?: SessionPr;
105
+ prs?: DetectedPr[];
102
106
  worktree?: DetectedWorktree;
103
107
  ticket?: DetectedTicket;
104
108
  rateLimited?: boolean;
@@ -262,8 +266,9 @@ export declare function foldExecutionMachine(rows: ActiveSession[], machineOf: (
262
266
  export declare function sessionProcessIsLocal(s: Pick<ActiveSession, 'machine' | 'offloadedFrom'>, self: string): boolean;
263
267
  export declare function sessionProcessHost(s: Pick<ActiveSession, 'machine' | 'offloadedFrom'>, self: string): string | undefined;
264
268
  export declare function foldHostLink(rows: ActiveSession[]): void;
265
- export declare function deriveSessionRecap(row: Pick<ActiveSession, 'label' | 'generatedTitle' | 'topic' | 'tail' | 'firstUserMessage' | 'lastUserMessage' | 'attachments' | 'request'>): {
269
+ export declare function deriveSessionRecap(row: Pick<ActiveSession, 'label' | 'generatedTitle' | 'topic' | 'tail' | 'firstUserMessage' | 'lastUserMessage' | 'attachments' | 'request' | 'cwd' | 'startedAs'>): {
266
270
  title?: string;
271
+ forkOf?: string;
267
272
  recapSource?: RecapSource;
268
273
  userPromptClean?: string;
269
274
  userPromptKind?: UserPromptKind;
@@ -16,7 +16,8 @@ import { readSessionActorRecord, writeSessionAliasRecord } from './actor-sidecar
16
16
  import { loadHookSessionIndex, resolveHookSessionRecord, readStateSessionRecord } from './hook-sessions.js';
17
17
  import { extractClaudeUserText, getAgentSessionDirs, readClaudeLiveNames } from './discover.js';
18
18
  import { buildRunNameMap } from './run-names.js';
19
- import { resolveSessionName, startedAsFromUserTurn } from './title.js';
19
+ import { cleanDisplayTitle, isPlaceholderSessionName, resolveSessionName, startedAsFromUserTurn } from './title.js';
20
+ import { forkSourceOf } from './fork.js';
20
21
  import { getIndexedSessionNames, latestSessionFileForCwd, indexedSessionIdForFile, findSessionsByShortIds, findSessionMachinesByIds, getSessionById } from './db.js';
21
22
  import { extractSessionTopic, classifyUserPrompt, tidyRequest } from '@phnx-labs/sessions-cli/reader';
22
23
  import { readSessionTailWithRaw } from '@phnx-labs/sessions-cli/reader';
@@ -150,6 +151,8 @@ export function applySessionNames(sessions) {
150
151
  indexed: stored?.label,
151
152
  launchName: s.name,
152
153
  }) ?? s.label;
154
+ if (stored?.recap)
155
+ s.recap = stored.recap;
153
156
  }
154
157
  }
155
158
  export function sessionAccountLabel(kind, session, accounts = listNativeAccounts(readMeta())) {
@@ -620,6 +623,7 @@ function applyState(base, state, fallbackFile, pidAlive) {
620
623
  tail: state.tail,
621
624
  preview: state.preview ?? base.preview,
622
625
  pr: state.pr,
626
+ prs: state.prs,
623
627
  worktree: state.worktree,
624
628
  ticket: state.ticket,
625
629
  createdTickets: state.createdTickets,
@@ -1442,25 +1446,29 @@ export function deriveSessionRecap(row) {
1442
1446
  });
1443
1447
  const userPromptClean = tidied?.headline ?? fallback?.clean;
1444
1448
  const userPromptKind = tidied?.kind ?? fallback?.kind;
1445
- const label = recapLine(row.label);
1446
- const generated = recapLine(row.generatedTitle);
1447
- const prompt = recapLine(userPromptClean || row.topic);
1449
+ const fork = forkSourceOf(row.firstUserMessage ?? row.topic);
1450
+ const ownLabel = row.label && !(fork && row.label.trim() === `fork of ${fork.label}`) ? row.label : undefined;
1451
+ const rungs = [
1452
+ ['label', ownLabel],
1453
+ ['fork', fork?.label],
1454
+ ['generated', row.generatedTitle],
1455
+ ['prompt', userPromptClean],
1456
+ ['prompt', row.topic],
1457
+ ['prompt', row.startedAs],
1458
+ ];
1448
1459
  let title;
1449
1460
  let recapSource;
1450
- if (label) {
1451
- title = label;
1452
- recapSource = 'label';
1453
- }
1454
- else if (generated) {
1455
- title = generated;
1456
- recapSource = 'generated';
1457
- }
1458
- else if (prompt) {
1459
- title = prompt;
1460
- recapSource = 'prompt';
1461
+ for (const [source, candidate] of rungs) {
1462
+ const clean = isPlaceholderSessionName(candidate, row.cwd) ? undefined : recapLine(cleanDisplayTitle(candidate));
1463
+ if (clean) {
1464
+ title = clean;
1465
+ recapSource = source;
1466
+ break;
1467
+ }
1461
1468
  }
1462
1469
  return {
1463
1470
  title,
1471
+ ...(fork?.id ? { forkOf: fork.id } : {}),
1464
1472
  recapSource,
1465
1473
  userPromptClean: recapLine(userPromptClean),
1466
1474
  userPromptKind,
@@ -1492,9 +1500,10 @@ export function deriveImportantMessage(row) {
1492
1500
  return undefined;
1493
1501
  }
1494
1502
  function applyRecap(s) {
1503
+ s.startedAs ??= s.firstUserMessage ? startedAsFromUserTurn(s.firstUserMessage) : undefined;
1495
1504
  const recap = deriveSessionRecap(s);
1496
1505
  s.title = recap.title;
1497
- s.startedAs ??= s.firstUserMessage ? startedAsFromUserTurn(s.firstUserMessage) : undefined;
1506
+ s.forkOf = recap.forkOf;
1498
1507
  s.recapSource = recap.recapSource;
1499
1508
  s.userPromptClean = recap.userPromptClean;
1500
1509
  s.userPromptKind = recap.userPromptKind;
@@ -1,5 +1,6 @@
1
1
  import Database from '../sqlite.js';
2
2
  import type { SessionAgentId, SessionCheckpoint, SessionChecklistItem, SessionEvent, SessionFiles, SessionGlance, SessionMeta, SessionRequest, SessionSubagent, SessionTimeline, SummaryState } from '@phnx-labs/sessions-cli/reader';
3
+ import type { SessionRecap } from './title.js';
3
4
  import { type IndexedToolCall } from '@phnx-labs/sessions-cli/reader';
4
5
  import { type ToolScanResumePoint } from './tool-store.js';
5
6
  import { type TimelineState } from '@phnx-labs/sessions-cli/reader';
@@ -89,13 +90,15 @@ export declare function upsertSessionsBatch(entries: Array<{
89
90
  toolIndexMode?: 'replace' | 'append';
90
91
  toolResume?: ToolScanResumePoint | null;
91
92
  }>): void;
93
+ export interface IndexedSessionNames {
94
+ label?: string;
95
+ customTitle?: string;
96
+ recap?: SessionRecap;
97
+ }
92
98
  export declare function getIndexedSessionNames(rows: Array<{
93
99
  id: string;
94
100
  filePath?: string;
95
- }>): Map<string, {
96
- label?: string;
97
- customTitle?: string;
98
- }>;
101
+ }>): Map<string, IndexedSessionNames>;
99
102
  export declare function seedLabelsFromNames(nameMap: Map<string, string | null>): number;
100
103
  export declare function syncTopics(topicMap: Map<string, string>): number;
101
104
  export declare function isSessionActivityFresh(row: {
@@ -1996,14 +1996,15 @@ export function getIndexedSessionNames(rows) {
1996
1996
  const keys = [...idByLedgerKey.keys()];
1997
1997
  for (let i = 0; i < keys.length; i += CHUNK) {
1998
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)`)
1999
+ const fromState = db
2000
+ .prepare(`SELECT file_path, json_extract(parser_state, '$.customTitle') AS custom_title, json_extract(parser_state, '$.recap') AS recap FROM scan_ledger WHERE file_path IN (${chunk.map(() => '?').join(',')}) AND json_valid(parser_state)`)
2001
2001
  .all(...chunk);
2002
- for (const row of titled) {
2003
- if (typeof row.custom_title !== 'string' || !row.custom_title)
2004
- continue;
2002
+ for (const row of fromState) {
2005
2003
  const id = idByLedgerKey.get(row.file_path);
2006
- out.set(id, { ...out.get(id), customTitle: row.custom_title });
2004
+ const customTitle = typeof row.custom_title === 'string' && row.custom_title ? row.custom_title : undefined;
2005
+ const recap = row.recap ? JSON.parse(row.recap) : undefined;
2006
+ if (customTitle || recap)
2007
+ out.set(id, { ...out.get(id), customTitle, recap });
2007
2008
  }
2008
2009
  }
2009
2010
  return out;
@@ -1,7 +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
+ import { type LiveSessionName, type SessionRecap } from './title.js';
5
5
  import { ToolCallCollector, type IndexedToolCall, type ToolCallCollectorSnapshot } from '@phnx-labs/sessions-cli/reader';
6
6
  interface DiscoverOptions {
7
7
  agent?: SessionAgentId;
@@ -183,6 +183,7 @@ interface ClaudeParseState {
183
183
  firstUserMessage?: string;
184
184
  customTitle?: string;
185
185
  aiTitle?: string;
186
+ recap?: SessionRecap;
186
187
  entrypoint?: string;
187
188
  messageCount: number;
188
189
  toolCallCount: number;
@@ -236,6 +237,7 @@ export interface ClaudeParserState {
236
237
  firstUserMessage?: string;
237
238
  customTitle?: string;
238
239
  aiTitle?: string;
240
+ recap?: SessionRecap;
239
241
  plan?: string;
240
242
  lastTsMs?: number;
241
243
  messageCount: number;
@@ -30,7 +30,7 @@ export { machineForSessionFile } from './origin-machine.js';
30
30
  import { mapBounded } from '../concurrency.js';
31
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
+ import { claudeRecapFromLine, resolveSessionName } from './title.js';
34
34
  import { resolveLinearApiKey } from '../linear-cache.js';
35
35
  import { ToolCallCollector, collectClaudeToolCalls, collectCodexToolCalls, } from '@phnx-labs/sessions-cli/reader';
36
36
  import { purgeMissingToolCallsInDirectory } from './tool-store.js';
@@ -2128,6 +2128,7 @@ export function initClaudeParseState() {
2128
2128
  firstUserMessage: undefined,
2129
2129
  customTitle: undefined,
2130
2130
  aiTitle: undefined,
2131
+ recap: undefined,
2131
2132
  entrypoint: undefined,
2132
2133
  messageCount: 0,
2133
2134
  toolCallCount: 0,
@@ -2283,6 +2284,11 @@ export function applyClaudeLine(state, parsed) {
2283
2284
  state.aiTitle = t;
2284
2285
  return;
2285
2286
  }
2287
+ const recap = claudeRecapFromLine(parsed);
2288
+ if (recap) {
2289
+ state.recap = recap;
2290
+ return;
2291
+ }
2286
2292
  if (parsed.type === 'user') {
2287
2293
  const text = extractClaudeUserText(parsed);
2288
2294
  if (text) {
@@ -2444,6 +2450,7 @@ export function serializeClaudeParserState(state, offset, jsonlDroppingOversized
2444
2450
  firstUserMessage: state.firstUserMessage,
2445
2451
  customTitle: state.customTitle,
2446
2452
  aiTitle: state.aiTitle,
2453
+ recap: state.recap,
2447
2454
  plan: state.plan,
2448
2455
  lastTsMs: state.lastTsMs,
2449
2456
  messageCount: state.messageCount,
@@ -2493,6 +2500,7 @@ export function hydrateClaudeParseState(prior) {
2493
2500
  firstUserMessage: prior.firstUserMessage,
2494
2501
  customTitle: prior.customTitle,
2495
2502
  aiTitle: prior.aiTitle,
2503
+ recap: prior.recap,
2496
2504
  entrypoint: prior.entrypoint,
2497
2505
  messageCount: prior.messageCount,
2498
2506
  toolCallCount: prior.toolCallCount ?? 0,
@@ -15,6 +15,11 @@ interface ForkRecapInput {
15
15
  lastAssistant?: string;
16
16
  changes?: ForkRecapChanges;
17
17
  }
18
- export declare function forkLabelFor(session: Pick<SessionMeta, 'label' | 'generatedTitle' | 'topic' | 'shortId'>): string;
18
+ export declare function forkLabelFor(session: Pick<SessionMeta, 'label' | 'generatedTitle' | 'topic' | 'shortId' | 'cwd'>): string;
19
+ export interface ForkSource {
20
+ label: string;
21
+ id?: string;
22
+ }
23
+ export declare function forkSourceOf(firstUserMessage: string | null | undefined): ForkSource | undefined;
19
24
  export declare function buildForkRecap(input: ForkRecapInput): string;
20
25
  export {};
@@ -9,6 +9,15 @@ function trimLastLine(text) {
9
9
  export function forkLabelFor(session) {
10
10
  return sessionHeadline(session) || session.shortId;
11
11
  }
12
+ const FORK_OPENING_RE = /^Continue a prior \S+ session \("(.+)"\)\. Pick up where it left off/;
13
+ const FORK_SOURCE_RE = /run `\/continue ([^`\s]+)` if you need the full transcript\.$/m;
14
+ export function forkSourceOf(firstUserMessage) {
15
+ const label = firstUserMessage ? FORK_OPENING_RE.exec(firstUserMessage)?.[1] : undefined;
16
+ if (!label)
17
+ return undefined;
18
+ const id = FORK_SOURCE_RE.exec(firstUserMessage)?.[1];
19
+ return id ? { label, id } : { label };
20
+ }
12
21
  export function buildForkRecap(input) {
13
22
  const lines = [];
14
23
  lines.push(`Continue a prior ${input.agent} session ("${input.label}"). Pick up where it left off — do not restart it.`);
@@ -73,9 +73,6 @@ function epochMs(value) {
73
73
  function previousSessionWatchRowKey(scope, sessionId) {
74
74
  return createHash('sha256').update(`${scope}\0previous\0${sessionId}`).digest('base64url').slice(0, 22);
75
75
  }
76
- function previousRowTitle(session, foldedHeadline) {
77
- return session.label || session.generatedTitle || foldedHeadline || session.topic || undefined;
78
- }
79
76
  function previousRowCard(session, request, attachments) {
80
77
  const digest = readCachedPreviewDigest(session);
81
78
  const recap = deriveSessionRecap({
@@ -89,6 +86,8 @@ function previousRowCard(session, request, attachments) {
89
86
  const todos = digest?.todos ?? session.todos;
90
87
  const importantMessage = deriveImportantMessage({ status: 'closed', lastAgentLine: recap.lastAgentLine });
91
88
  return {
89
+ ...(recap.title ? { title: recap.title } : {}),
90
+ ...(recap.forkOf ? { forkOf: recap.forkOf } : {}),
92
91
  ...(recap.lastAgentLine ? { lastAgentLine: recap.lastAgentLine } : {}),
93
92
  ...(recap.request ? { request: recap.request } : {}),
94
93
  ...(recap.userPromptClean ? { userPromptClean: recap.userPromptClean } : {}),
@@ -116,7 +115,6 @@ export function toPreviousSessionWatchRow(scope, session, accounts = listNativeA
116
115
  : readSessionSummaryAny(session.id);
117
116
  const folded = readSessionTimelineAny(session.id);
118
117
  const model = folded?.model ?? session.model;
119
- const title = previousRowTitle(session, folded?.request?.headline);
120
118
  const card = previousRowCard(session, folded?.request, folded?.attachments);
121
119
  return {
122
120
  context: 'recent',
@@ -129,7 +127,6 @@ export function toPreviousSessionWatchRow(scope, session, accounts = listNativeA
129
127
  confirmedProject: confirmedProjectForCwd(session.cwd) ?? null,
130
128
  ...(session.label ? { label: session.label } : {}),
131
129
  ...(session.generatedTitle ? { generatedTitle: session.generatedTitle } : {}),
132
- ...(title ? { title } : {}),
133
130
  ...(session.topic ? { topic: session.topic } : {}),
134
131
  ...(session.firstUserMessage ? { firstUserMessage: session.firstUserMessage } : {}),
135
132
  ...(session.version ? { version: session.version } : {}),
@@ -27,6 +27,7 @@ interface ImmutableSessionFields {
27
27
  startedAtMs?: number;
28
28
  version?: string;
29
29
  pr?: ActiveSession['pr'];
30
+ prs?: ActiveSession['prs'];
30
31
  worktree?: ActiveSession['worktree'];
31
32
  ticket?: ActiveSession['ticket'];
32
33
  createdTickets?: string[];
@@ -37,7 +38,7 @@ interface ImmutableSessionFields {
37
38
  kind?: string;
38
39
  context?: ActiveSession['context'];
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 IMMUTABLE_FIELD_KEYS: readonly ["topic", "firstUserMessage", "label", "name", "cwd", "project", "attachments", "startedAtMs", "version", "pr", "prs", "worktree", "ticket", "createdTickets", "spawnedTeam", "sessionFile", "owner", "assignedTask", "kind", "context"];
41
42
  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
43
  export declare const ACTIVE_SESSIONS_READER_IDLE_WINDOW_MS = 45000;
43
44
  export declare function setActiveSessionsSnapshotPathForTest(p: string | null): string | null;
@@ -31,6 +31,7 @@ export const IMMUTABLE_FIELD_KEYS = [
31
31
  'startedAtMs',
32
32
  'version',
33
33
  'pr',
34
+ 'prs',
34
35
  'worktree',
35
36
  'ticket',
36
37
  'createdTickets',
@@ -25,7 +25,20 @@ export declare function sessionHeadline<T extends {
25
25
  label?: string | null;
26
26
  generatedTitle?: string | null;
27
27
  topic?: string | null;
28
+ cwd?: string | null;
28
29
  }>(row: CarriesTitleRung<T>): string | undefined;
30
+ export declare function isPlaceholderSessionName(name: string | null | undefined, cwd?: string | null): boolean;
31
+ export declare function cleanDisplayTitle(raw: string | null | undefined): string | undefined;
32
+ export interface SessionRecap {
33
+ text: string;
34
+ at: string;
35
+ }
36
+ export declare function claudeRecapFromLine(parsed: {
37
+ type?: unknown;
38
+ subtype?: unknown;
39
+ content?: unknown;
40
+ timestamp?: unknown;
41
+ }): SessionRecap | undefined;
29
42
  export interface LiveSessionName {
30
43
  name: string;
31
44
  source?: string;
@@ -69,7 +69,47 @@ export function sanitizeGeneratedTitle(raw) {
69
69
  return title || undefined;
70
70
  }
71
71
  export function sessionHeadline(row) {
72
- return row.label || row.generatedTitle || row.topic || undefined;
72
+ const label = isPlaceholderSessionName(row.label, row.cwd) ? undefined : row.label;
73
+ return label || row.generatedTitle || row.topic || undefined;
74
+ }
75
+ const HOST_FALLBACK_LABEL_RE = /^\[host\/[^\]]+\]$/;
76
+ const PLACEHOLDER_SUFFIX_RE = /^(?:\d+|(?=[0-9a-f]*\d)[0-9a-f]{1,4})$/i;
77
+ export function isPlaceholderSessionName(name, cwd) {
78
+ const n = name?.trim();
79
+ if (!n)
80
+ return false;
81
+ if (HOST_FALLBACK_LABEL_RE.test(n))
82
+ return true;
83
+ const dir = cwd?.replace(/[/\\]+$/, '').split(/[/\\]/).pop();
84
+ if (!dir || n.length <= dir.length + 1)
85
+ return false;
86
+ return n.slice(0, dir.length + 1).toLowerCase() === `${dir.toLowerCase()}-` && PLACEHOLDER_SUFFIX_RE.test(n.slice(dir.length + 1));
87
+ }
88
+ const INJECTED_NOTE_RE = /^another \w+ session sent a message:?\s*/i;
89
+ export function cleanDisplayTitle(raw) {
90
+ if (!raw || /^\s*<(?:task-notification|system-reminder)/i.test(raw))
91
+ return undefined;
92
+ const t = raw
93
+ .replace(/<\/?agent-message[^>]*>/gi, ' ')
94
+ .replace(INJECTED_NOTE_RE, '')
95
+ .replace(/\[([^\]]+)\]\([^)]*(?:\)|$)/g, '$1')
96
+ .replace(/[`*]+/g, '')
97
+ .replace(/^[#>\s]+/, '')
98
+ .replace(/\s+/g, ' ')
99
+ .trim()
100
+ .replace(/^[…. ]+$/, '');
101
+ if (!t || /^\[subagent hand-back\]/i.test(t) || /^\/[\w:-]+(?:\s|$)/.test(t))
102
+ return undefined;
103
+ return t;
104
+ }
105
+ const CLAUDE_RECAP_HINT_RE = /\s*\(disable recaps in \/config\)\s*$/i;
106
+ export function claudeRecapFromLine(parsed) {
107
+ if (parsed.type !== 'system' || parsed.subtype !== 'away_summary')
108
+ return undefined;
109
+ if (typeof parsed.content !== 'string' || typeof parsed.timestamp !== 'string')
110
+ return undefined;
111
+ const text = parsed.content.replace(CLAUDE_RECAP_HINT_RE, '').trim();
112
+ return text ? { text, at: parsed.timestamp } : undefined;
73
113
  }
74
114
  function nonEmpty(s) {
75
115
  return s?.trim() || undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phnx-labs/agents-cli",
3
- "version": "1.23.29",
3
+ "version": "1.23.31",
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.6",
92
+ "@phnx-labs/sessions-cli": "0.8.7",
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",