@phnx-labs/agents-cli 1.23.29 → 1.23.30

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,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.23.30
4
+
5
+ - **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
6
+
7
+ - **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`.
8
+
3
9
  ## 1.23.29
4
10
 
5
11
  - **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
@@ -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';
@@ -80,6 +81,7 @@ export interface ActiveSession {
80
81
  generatedTitle?: string;
81
82
  title?: string;
82
83
  startedAs?: string;
84
+ recap?: SessionRecap;
83
85
  recapSource?: RecapSource;
84
86
  userPromptClean?: string;
85
87
  userPromptKind?: UserPromptKind;
@@ -99,6 +101,7 @@ export interface ActiveSession {
99
101
  todos?: TodoProgress;
100
102
  tail?: string[];
101
103
  pr?: SessionPr;
104
+ prs?: DetectedPr[];
102
105
  worktree?: DetectedWorktree;
103
106
  ticket?: DetectedTicket;
104
107
  rateLimited?: boolean;
@@ -150,6 +150,8 @@ export function applySessionNames(sessions) {
150
150
  indexed: stored?.label,
151
151
  launchName: s.name,
152
152
  }) ?? s.label;
153
+ if (stored?.recap)
154
+ s.recap = stored.recap;
153
155
  }
154
156
  }
155
157
  export function sessionAccountLabel(kind, session, accounts = listNativeAccounts(readMeta())) {
@@ -620,6 +622,7 @@ function applyState(base, state, fallbackFile, pidAlive) {
620
622
  tail: state.tail,
621
623
  preview: state.preview ?? base.preview,
622
624
  pr: state.pr,
625
+ prs: state.prs,
623
626
  worktree: state.worktree,
624
627
  ticket: state.ticket,
625
628
  createdTickets: state.createdTickets,
@@ -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,
@@ -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',
@@ -26,6 +26,16 @@ 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 SessionRecap {
30
+ text: string;
31
+ at: string;
32
+ }
33
+ export declare function claudeRecapFromLine(parsed: {
34
+ type?: unknown;
35
+ subtype?: unknown;
36
+ content?: unknown;
37
+ timestamp?: unknown;
38
+ }): SessionRecap | undefined;
29
39
  export interface LiveSessionName {
30
40
  name: string;
31
41
  source?: string;
@@ -71,6 +71,15 @@ export function sanitizeGeneratedTitle(raw) {
71
71
  export function sessionHeadline(row) {
72
72
  return row.label || row.generatedTitle || row.topic || undefined;
73
73
  }
74
+ const CLAUDE_RECAP_HINT_RE = /\s*\(disable recaps in \/config\)\s*$/i;
75
+ export function claudeRecapFromLine(parsed) {
76
+ if (parsed.type !== 'system' || parsed.subtype !== 'away_summary')
77
+ return undefined;
78
+ if (typeof parsed.content !== 'string' || typeof parsed.timestamp !== 'string')
79
+ return undefined;
80
+ const text = parsed.content.replace(CLAUDE_RECAP_HINT_RE, '').trim();
81
+ return text ? { text, at: parsed.timestamp } : undefined;
82
+ }
74
83
  function nonEmpty(s) {
75
84
  return s?.trim() || undefined;
76
85
  }
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.30",
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",