ring-cli 0.17.2__tar.gz → 0.17.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. {ring_cli-0.17.2 → ring_cli-0.17.3}/PKG-INFO +1 -1
  2. {ring_cli-0.17.2 → ring_cli-0.17.3}/pyproject.toml +2 -2
  3. {ring_cli-0.17.2 → ring_cli-0.17.3}/pyproject.toml.orig +2 -2
  4. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/hook.py +84 -19
  5. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/registry.py +71 -21
  6. {ring_cli-0.17.2 → ring_cli-0.17.3}/LICENSE +0 -0
  7. {ring_cli-0.17.2 → ring_cli-0.17.3}/README.en.md +0 -0
  8. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/__init__.py +0 -0
  9. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/__main__.py +0 -0
  10. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/agent_notify.py +0 -0
  11. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/cli.py +0 -0
  12. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/commands/__init__.py +0 -0
  13. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/commands/_args.py +0 -0
  14. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/commands/completion.py +0 -0
  15. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/commands/digest.py +0 -0
  16. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/commands/doctor.py +0 -0
  17. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/commands/focus.py +0 -0
  18. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/commands/gc.py +0 -0
  19. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/commands/hook.py +0 -0
  20. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/commands/quiet.py +0 -0
  21. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/commands/stats.py +0 -0
  22. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/config.py +0 -0
  23. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/focus/__init__.py +0 -0
  24. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/focus/applescript.py +0 -0
  25. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/focus/base.py +0 -0
  26. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/focus/iterm2.py +0 -0
  27. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/focus/kitty.py +0 -0
  28. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/focus/linux_wm.py +0 -0
  29. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/focus/neovim.py +0 -0
  30. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/focus/terminal.py +0 -0
  31. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/focus/tmux.py +0 -0
  32. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/focus/trace.py +0 -0
  33. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/gc.py +0 -0
  34. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/hook_protocol.py +0 -0
  35. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/i18n.py +0 -0
  36. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/ipc.py +0 -0
  37. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/labels.py +0 -0
  38. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/locale/en/LC_MESSAGES/ring.mo +0 -0
  39. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/locale/en/LC_MESSAGES/ring.po +0 -0
  40. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/locale/ring.pot +0 -0
  41. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/notify/__init__.py +0 -0
  42. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/notify/base.py +0 -0
  43. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/notify/command.py +0 -0
  44. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/notify/notify_send.py +0 -0
  45. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/notify/ntfy.py +0 -0
  46. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/notify/osascript_notifier.py +0 -0
  47. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/notify/terminal_notifier.py +0 -0
  48. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/notify/webhook.py +0 -0
  49. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/notify_queue.py +0 -0
  50. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/osascript.py +0 -0
  51. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/pathutil.py +0 -0
  52. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/payload_log.py +0 -0
  53. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/permission.py +0 -0
  54. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/plugins.py +0 -0
  55. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/ps_parse.py +0 -0
  56. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/question_detect.py +0 -0
  57. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/sources/__init__.py +0 -0
  58. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/sources/base.py +0 -0
  59. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/sources/claude_code.py +0 -0
  60. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/sources/codex.py +0 -0
  61. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/sources/hook_registry.py +0 -0
  62. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/sources/local_llm.py +0 -0
  63. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/stats.py +0 -0
  64. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/subproc.py +0 -0
  65. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/tmux_scan.py +0 -0
  66. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/transcript.py +0 -0
  67. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/tui.py +0 -0
  68. {ring_cli-0.17.2 → ring_cli-0.17.3}/src/ring/watcher.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ring-cli
3
- Version: 0.17.2
3
+ Version: 0.17.3
4
4
  Summary: RiNG — Realtime Instance Notification Grid for active agent CLI sessions.
5
5
  Keywords: claude-code,codex,ollama,llama-cpp,tui,dashboard,session,monitor,rich
6
6
  Author: Wei Lee
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "ring-cli"
3
- version = "0.17.2"
3
+ version = "0.17.3"
4
4
  description = "RiNG — Realtime Instance Notification Grid for active agent CLI sessions."
5
5
  readme = "README.en.md"
6
6
  requires-python = ">=3.13"
@@ -77,7 +77,7 @@ include-group = "test"
77
77
  include-group = "linters"
78
78
 
79
79
  [build-system]
80
- requires = ["uv_build >= 0.10.3, <0.12.0"]
80
+ requires = ["uv_build>=0.10.3,<0.13.0"]
81
81
  build-backend = "uv_build"
82
82
 
83
83
  [tool.uv.build-backend]
@@ -2,7 +2,7 @@
2
2
  # import 的 module(見 [tool.uv.build-backend] module-name)與 CLI 指令仍是 `ring`。
3
3
  [project]
4
4
  name = "ring-cli"
5
- version = "0.17.2"
5
+ version = "0.17.3"
6
6
  description = "RiNG — Realtime Instance Notification Grid for active agent CLI sessions."
7
7
  readme = "README.en.md"
8
8
  requires-python = ">=3.13"
@@ -62,7 +62,7 @@ linters = ["ruff>=0.15.1", "mypy>=1.19.1", "prek>=0.3.3", "commitizen>=4.13.9"]
62
62
  docs = ["mkdocs-material>=9,<10", "mkdocs-static-i18n>=1.3,<2"]
63
63
 
64
64
  [build-system]
65
- requires = ["uv_build >= 0.10.3, <0.12.0"]
65
+ requires = ["uv_build>=0.10.3,<0.13.0"]
66
66
  build-backend = "uv_build"
67
67
 
68
68
  [tool.uv.build-backend]
@@ -26,12 +26,15 @@ Agent CLI 在各事件把一段 JSON 從 stdin 餵進來。我們據此 upsert
26
26
 
27
27
  from __future__ import annotations
28
28
 
29
+ import fcntl
29
30
  import json
30
31
  import os
31
32
  import shutil
32
33
  import subprocess
33
34
  import sys
34
35
  import time
36
+ from collections.abc import Iterator
37
+ from contextlib import contextmanager
35
38
  from dataclasses import dataclass, replace
36
39
  from pathlib import Path
37
40
  from typing import Any
@@ -120,25 +123,22 @@ def _ps_row(pid: int) -> tuple[int, str] | None:
120
123
  return None
121
124
 
122
125
 
123
- def _session_tty(process_names: tuple[str, ...]) -> str:
124
- """hook 是 agent CLI 的後代——往上找到 provider process,回它的控制終端 tty。
125
-
126
- 這是「session → 哪個終端」最精準的對應(不必靠 cwd 猜),給非-tmux 終端 focuser(iTerm2 等)跳轉用。
127
- """
126
+ def _session_pid(process_names: tuple[str, ...]) -> int | None:
127
+ """hook 是 agent CLI 的後代——往上找到真正的 provider process PID。"""
128
128
  if not process_names:
129
- return ""
129
+ return None
130
130
  pid = os.getppid()
131
131
  for _attempt in range(12):
132
132
  row = _ps_row(pid)
133
133
  if row is None:
134
- return ""
134
+ return None
135
135
  ppid, comm = row
136
136
  if Path(comm.strip()).name in process_names:
137
- return _pid_tty(pid)
137
+ return pid
138
138
  if ppid <= 1:
139
- return ""
139
+ return None
140
140
  pid = ppid
141
- return ""
141
+ return None
142
142
 
143
143
 
144
144
  def _controlling_tty() -> str:
@@ -188,18 +188,64 @@ def run_hook(provider: str = "claude-code") -> int:
188
188
  return _delegate_to_agent_hooks(raw, selected_provider)
189
189
 
190
190
 
191
+ @contextmanager
192
+ def _session_state_lock(path: Path) -> Iterator[None]:
193
+ """同 session 的 hook 序列化整段 read-modify-write,包含 SessionEnd。
194
+
195
+ lock 檔不隨 row 刪除,避免仍在排隊的 writer 鎖住舊 inode、另一個 writer 卻鎖住新 inode。
196
+ """
197
+ path.parent.mkdir(parents=True, exist_ok=True)
198
+ with path.with_suffix(".json.lock").open("a", encoding="utf-8") as handle:
199
+ fcntl.flock(handle, fcntl.LOCK_EX)
200
+ try:
201
+ yield
202
+ finally:
203
+ fcntl.flock(handle, fcntl.LOCK_UN)
204
+
205
+
191
206
  def _record_session_state(data: dict[str, Any], selected_provider: str) -> None:
192
- """把事件正規化後 upsert / 刪除 RiNG registry 檔(看板狀態)。失敗安靜吞,不回傳。"""
207
+ """正規化後序列化 registry 更新;I/O 失敗不影響 hook 後續委派。"""
193
208
  adapter = adapter_for(selected_provider)
194
209
  event = adapter.normalize(data)
195
210
  if event is None:
196
211
  return
197
212
  event = _maybe_flag_trailing_question(event, data)
198
213
 
199
- unhide_session(event.session_id)
200
214
  path = RING_REGISTRY / f"{quote(event.session_id, safe=':')}.json"
215
+ try:
216
+ with _session_state_lock(path):
217
+ notification = _update_session_state(path, event, data, adapter.process_names)
218
+ except OSError:
219
+ return
220
+ # 系統通知可能等待外部程序,不可持鎖阻擋後續解除等待的 hook。
221
+ if notification is not None:
222
+ _ring_waiting_now(*notification)
223
+
224
+
225
+ def _update_session_state(
226
+ path: Path, event: NormalizedHookEvent, data: dict[str, Any], process_names: tuple[str, ...]
227
+ ) -> tuple[NormalizedHookEvent, dict[str, Any], str] | None:
228
+ """持有 session lock 時合併並寫入;回傳需在鎖外發送的通知。"""
201
229
  prev_row = _previous_row(path)
202
230
  prev_status = str(prev_row["status"]) if "status" in prev_row else None
231
+ agent_id = next((value for key in ("agent_id", "agentId") if isinstance(value := data.get(key), str) and value), "")
232
+ is_subagent_event = bool(agent_id) or any(
233
+ isinstance(data.get(key), str) and data[key] for key in ("agent_type", "agentType")
234
+ )
235
+ if is_subagent_event:
236
+ # 共用 host session_id 不代表能解除前景或另一個 agent 的等待。
237
+ # 舊 row 沒有等待來源時視為前景;僅知道 agent_type 也不能證明是同一個等待者。
238
+ if event.status is Status.ENDED or (
239
+ prev_status == Status.WAITING.value and (not agent_id or prev_row.get("waiting_agent_id") != agent_id)
240
+ ):
241
+ return None
242
+ if prev_row:
243
+ event = replace(
244
+ event,
245
+ cwd=str(prev_row.get("cwd", event.cwd)),
246
+ transcript_path=str(prev_row.get("source_path", "")),
247
+ )
248
+ unhide_session(event.session_id)
203
249
  # 一般 Notification 只能升 🔴、不能降 🟡——閒置提醒不是「使用者回應了」的證據。
204
250
  keep_waiting = _notification_keeps_waiting(event, prev_row)
205
251
  if keep_waiting:
@@ -214,7 +260,16 @@ def _record_session_state(data: dict[str, Any], selected_provider: str) -> None:
214
260
  path.unlink(missing_ok=True) # 乾淨離場:直接消失
215
261
  if prev_status is not None and prev_status != Status.ENDED.value:
216
262
  log_transition(event.session_id, event.provider, event.cwd, Status.ENDED.value)
217
- return
263
+ return None
264
+
265
+ previous_pid = int(prev_row["agent_pid"]) if str(prev_row.get("agent_pid", "")).isdigit() else None
266
+ agent_pid = None if is_subagent_event else _session_pid(process_names)
267
+ same_binding = is_subagent_event or (
268
+ event.event != "SessionStart" and (agent_pid is None or agent_pid == previous_pid)
269
+ )
270
+ if same_binding and agent_pid is None:
271
+ # 查詢未知不是 session 換人;保留已取得的前景身分,成功的新 lookup 仍可重新綁定。
272
+ agent_pid = previous_pid
218
273
 
219
274
  last_action, todo = event.last_action or "—", None
220
275
  tp = event.transcript_path
@@ -229,7 +284,7 @@ def _record_session_state(data: dict[str, Any], selected_provider: str) -> None:
229
284
  "session_id": event.session_id,
230
285
  "provider": event.provider,
231
286
  "cwd": event.cwd,
232
- "origin_cwd": event.cwd,
287
+ "origin_cwd": prev_row.get("origin_cwd", event.cwd) if is_subagent_event else event.cwd,
233
288
  "status": event.status.value,
234
289
  # 最後一個 hook 事件名:讀取側據此做 codex 的核可等待判定(最後事件是
235
290
  # PermissionRequest 且靜默逾時 → 🔴),任何後續事件覆寫它就自然清紅。
@@ -239,9 +294,12 @@ def _record_session_state(data: dict[str, Any], selected_provider: str) -> None:
239
294
  "last_action": last_action,
240
295
  "hook_pid": os.getpid(),
241
296
  }
297
+ if agent_pid is not None:
298
+ payload["agent_pid"] = agent_pid
242
299
  if tp:
243
300
  payload["source_path"] = tp
244
- tmux_pane = os.environ.get("TMUX_PANE", "").strip()
301
+ previous_pane = str(prev_row.get("tmux_pane", "")) if same_binding else ""
302
+ tmux_pane = previous_pane if is_subagent_event else os.environ.get("TMUX_PANE", "").strip() or previous_pane
245
303
  if tmux_pane:
246
304
  payload["tmux_pane"] = tmux_pane
247
305
  if todo:
@@ -263,19 +321,26 @@ def _record_session_state(data: dict[str, Any], selected_provider: str) -> None:
263
321
  if event.status is Status.WAITING and event.waiting_kind:
264
322
  payload["waiting_kind"] = event.waiting_kind
265
323
  if event.status is Status.WAITING:
324
+ waiting_agent_id = prev_row.get("waiting_agent_id", "") if keep_waiting else agent_id
325
+ if waiting_agent_id:
326
+ payload["waiting_agent_id"] = waiting_agent_id
266
327
  waiting_detail = event.detail
267
328
  if event.event == "Notification" and event.waiting_kind == "permission" and pending_detail:
268
329
  waiting_detail = pending_detail
269
330
  if waiting_detail:
270
331
  payload["waiting_detail"] = waiting_detail
271
- tty = event.tty or _controlling_tty() or _session_tty(adapter.process_names)
332
+ previous_tty = str(prev_row.get("tty", "")) if same_binding else ""
333
+ if is_subagent_event:
334
+ tty = previous_tty or (_pid_tty(agent_pid) if agent_pid is not None else "")
335
+ else:
336
+ tty = event.tty or _controlling_tty() or (_pid_tty(agent_pid) if agent_pid is not None else "") or previous_tty
272
337
  if tty:
273
338
  payload["tty"] = tty
274
339
 
275
340
  # waiting 通知冷卻(防翻轉轟炸):hook 是短命 process,冷卻狀態持久化在 registry row
276
341
  # 的 waiting_notified_at(上次 waiting 通知的 epoch 時間戳)。離開 WAITING 也要把時間戳
277
342
  # 帶進新 row(payload 每次重建,不帶會遺失),快速翻回 WAITING 時才判得出「還在冷卻期」。
278
- # 舊 row 沒這欄位 = 從未通知過 → 照發。並發寫沿用既有 tmp+replace 的 last-write-wins。
343
+ # 舊 row 沒這欄位 = 從未通知過 → 照發。讀取與預約通知時間同樣受 session lock 保護。
279
344
  last_notified = _as_epoch(prev_row.get("waiting_notified_at"))
280
345
  if last_notified is not None:
281
346
  payload["waiting_notified_at"] = last_notified
@@ -287,7 +352,6 @@ def _record_session_state(data: dict[str, Any], selected_provider: str) -> None:
287
352
  if should_ring:
288
353
  payload["waiting_notified_at"] = now
289
354
 
290
- RING_REGISTRY.mkdir(parents=True, exist_ok=True)
291
355
  tmp = path.with_suffix(".json.tmp")
292
356
  tmp.write_text(json.dumps(payload))
293
357
  tmp.replace(path) # atomic
@@ -296,7 +360,8 @@ def _record_session_state(data: dict[str, Any], selected_provider: str) -> None:
296
360
  log_transition(event.session_id, event.provider, event.cwd, event.status.value)
297
361
 
298
362
  if should_ring:
299
- _ring_waiting_now(event, payload, last_action)
363
+ return event, payload, last_action
364
+ return None
300
365
 
301
366
 
302
367
  def _notification_keeps_waiting(event: NormalizedHookEvent, prev_row: dict[str, Any]) -> bool:
@@ -86,6 +86,7 @@ BARE_SESSION_START_GRACE_SECONDS = 120.0
86
86
  # 同義 provider 名先正規化(例如 "claude" → "claude-code")。
87
87
  _PROVIDER_ALIASES: dict[str, str] = {"claude": "claude-code"}
88
88
  _PROVIDER_PROCS: dict[str, Callable[[], list[tuple[str, str]] | None]] = {}
89
+ _PROVIDER_PIDS: dict[str, Callable[[], list[int] | None]] = {}
89
90
 
90
91
 
91
92
  def _canonical_provider(provider: str) -> str:
@@ -269,13 +270,25 @@ def prune_hidden_sessions(
269
270
  return stale
270
271
 
271
272
 
272
- def register_provider_procs(provider: str, detector: Callable[[], list[tuple[str, str]] | None]) -> None:
273
+ def register_provider_procs(
274
+ provider: str,
275
+ detector: Callable[[], list[tuple[str, str]] | None],
276
+ *,
277
+ pid_detector: Callable[[], list[int] | None] | None = None,
278
+ ) -> None:
273
279
  """註冊某 provider 的 live-process 偵測器(回傳 ``[(cwd, tty), …]``)。
274
280
 
275
281
  有偵測器的 provider 才會在 ``_hook_sessions`` 走 process-based 存活清理;沒註冊的
276
282
  provider 一律 fail-open(不靠 process 判離場,交給該工具自己的 SessionEnd hook)。
283
+ 有提供 ``pid_detector`` 時,新格式 hook row 會優先用精準 PID 驗活;未提供或舊格式
284
+ row 則繼續使用 cwd / tty 判定。
277
285
  """
278
- _PROVIDER_PROCS[_canonical_provider(provider)] = detector
286
+ canonical = _canonical_provider(provider)
287
+ _PROVIDER_PROCS[canonical] = detector
288
+ if pid_detector is None:
289
+ _PROVIDER_PIDS.pop(canonical, None)
290
+ else:
291
+ _PROVIDER_PIDS[canonical] = pid_detector
279
292
 
280
293
 
281
294
  def collect_provider_procs() -> dict[str, list[tuple[str, str]] | None]:
@@ -287,6 +300,20 @@ def collect_provider_procs() -> dict[str, list[tuple[str, str]] | None]:
287
300
  return {provider: detector() for provider, detector in _PROVIDER_PROCS.items()}
288
301
 
289
302
 
303
+ def collect_provider_pids(providers: set[str] | None = None) -> dict[str, list[int] | None]:
304
+ """取得 provider 的 live PID,供新格式 hook row 做精準存活比對。
305
+
306
+ ``providers`` 只限制要呼叫哪些偵測器;沒有 PID 偵測器的 provider 不會出現在
307
+ 結果中,讀取側會沿用 cwd / tty fallback。``None`` 仍代表這輪偵測失敗。
308
+ """
309
+ wanted = None if providers is None else {_canonical_provider(provider) for provider in providers}
310
+ result: dict[str, list[int] | None] = {}
311
+ for provider, detector in _PROVIDER_PIDS.items():
312
+ if wanted is None or provider in wanted:
313
+ result[provider] = detector()
314
+ return result
315
+
316
+
290
317
  class Status(StrEnum):
291
318
  """場館裡一個 session 的狀態。等你的排最上面。"""
292
319
 
@@ -316,6 +343,7 @@ class Session:
316
343
  tmux_pane: str | None = None # stable tmux pane id from hook, e.g. "%12"
317
344
  tty: str | None = None # e.g. "/dev/ttys003",給非-tmux 終端(iTerm2 等)聚焦用
318
345
  hook_pid: int | None = None
346
+ agent_pid: int | None = None # provider CLI 的長命 process;精準排除同 cwd 的舊 hook row
319
347
  heartbeat_at: float = 0.0
320
348
  source_path: str = ""
321
349
  hook_stale: bool = False
@@ -786,8 +814,8 @@ def _codex_procs() -> list[tuple[str, str]] | None:
786
814
 
787
815
 
788
816
  # 內建 provider 的 live-process 偵測器。外部工具用 register_provider_procs() 加自己的。
789
- register_provider_procs("claude-code", _claude_procs)
790
- register_provider_procs("codex", _codex_procs)
817
+ register_provider_procs("claude-code", _claude_procs, pid_detector=running_foreground_claude_pids)
818
+ register_provider_procs("codex", _codex_procs, pid_detector=running_codex_pids)
791
819
 
792
820
 
793
821
  def _codex_tail_kind(records: list[dict[str, Any]]) -> str:
@@ -1069,6 +1097,7 @@ def _hook_sessions(
1069
1097
  procs: list[tuple[str, str]] | None = None,
1070
1098
  *,
1071
1099
  procs_by_provider: dict[str, list[tuple[str, str]] | None] | None = None,
1100
+ pids_by_provider: dict[str, list[int] | None] | None = None,
1072
1101
  purge_session_start_phantoms: bool = True,
1073
1102
  ) -> list[Session]:
1074
1103
  if not RING_REGISTRY.is_dir():
@@ -1098,6 +1127,7 @@ def _hook_sessions(
1098
1127
  tmux_pane=str(data.get("tmux_pane", "")) or None,
1099
1128
  tty=str(data.get("tty", "")) or None,
1100
1129
  hook_pid=int(data["hook_pid"]) if str(data.get("hook_pid", "")).isdigit() else None,
1130
+ agent_pid=int(data["agent_pid"]) if str(data.get("agent_pid", "")).isdigit() else None,
1101
1131
  heartbeat_at=float(data.get("heartbeat_at", data.get("last_active", 0.0))),
1102
1132
  source_path=str(data.get("source_path", "")),
1103
1133
  todo=tuple(todo) if isinstance(todo, list) and len(todo) == 2 else None,
@@ -1135,16 +1165,25 @@ def _hook_sessions(
1135
1165
  for s in out:
1136
1166
  if s.source == "hook":
1137
1167
  s.hook_stale = _hook_heartbeat_stale(s.source_path, s.heartbeat_at, s.status)
1168
+ pid_providers = {
1169
+ _canonical_provider(s.provider)
1170
+ for s in out
1171
+ if s.agent_pid is not None and _canonical_provider(s.provider) in _PROVIDER_PIDS
1172
+ }
1173
+ if pids_by_provider is None and pid_providers:
1174
+ pids_by_provider = collect_provider_pids(pid_providers)
1138
1175
  # SessionEnd 沒觸發(crash)會留下幽靈檔。判定離場:
1139
- # 1. 該 cwd 完全沒有 live proc → 一定離場。
1140
- # 2. 該 cwd 的 hook row 數「多於一筆」時,用 tty 挑出 tty 對不上的那幾筆標離場——
1176
+ # 1. 新格式 row 有 provider CLI PID 時,直接用 PID 判斷,不讓同 cwd 的另一個新
1177
+ # session 替已離場的舊 WAITING row 證明存活。
1178
+ # 2. 舊格式 row 的 cwd 完全沒有 live proc → 一定離場。
1179
+ # 3. 該 cwd 的 hook row 數「多於一筆」時,用 tty 挑出 tty 對不上的那幾筆標離場——
1141
1180
  # 不論這筆數是否 <= live proc 數:計數只是巧合對上(例如同 cwd 剛好有跟 RiNG
1142
1181
  # hook 無關的 live process 佔掉名額),不代表每筆 row 都真的還活著;row 數 > 1
1143
1182
  # 時 tty 交叉比對才有意義去挑出誰是 stale 的。
1144
- # 3. 該 cwd 只有「單一」hook row 時,無論 tty 是否對得上都不靠 tty 殺——hook 寫進來
1183
+ # 4. 該 cwd 只有「單一」舊格式 hook row 時,無論 tty 是否對得上都不靠 tty 殺——hook 寫進來
1145
1184
  # 的 tty 不一定可靠(終端 tty 會被作業系統重配,甚至跨 session 錯置),拿它隱藏
1146
1185
  # 唯一活著的 session 會讓整列憑空消失。
1147
- # 4. 「這個 provider 這輪 ps/lsof 掃描失敗」(值為 ``None``)是「未知」,不是
1186
+ # 5. 「這個 provider 這輪 ps/lsof 掃描失敗」(值為 ``None``)是「未知」,不是
1148
1187
  # 「真的偵測到零個 live process」——未知時完全不動這個 provider 底下任何一筆
1149
1188
  # row 的狀態,保留既有狀態,避免單次系統瞬間卡頓(ps timeout)把整版 session
1150
1189
  # 誤判 ENDED(見 ring-vanishing-sessions 診斷)。
@@ -1181,18 +1220,33 @@ def _hook_sessions(
1181
1220
  # 這裡的 fallback 只是避免拿 None 做 in 運算炸掉。
1182
1221
  background_ids = background_agent_session_ids() or set()
1183
1222
  rows_by_key: dict[tuple[str, str], list[Session]] = {}
1223
+ pid_resolved: set[str] = set()
1224
+ claimed_pids: dict[tuple[str, str], set[int]] = {}
1184
1225
  for s in out:
1185
1226
  pk = _canonical_provider(s.provider)
1186
1227
  if pk not in _PROVIDER_PROCS:
1187
1228
  continue # 沒有 proc 偵測器 → 無法驗活性 → fail-open,交給 SessionEnd
1188
1229
  if pk == "claude-code" and s.session_id in background_ids:
1189
1230
  continue
1190
- rows_by_key.setdefault((pk, _real(s.cwd)), []).append(s)
1231
+ key = (pk, _real(s.cwd))
1232
+ rows_by_key.setdefault(key, []).append(s)
1233
+ if s.agent_pid is not None and pids_by_provider is not None and pk in pids_by_provider:
1234
+ live_pids = pids_by_provider[pk]
1235
+ if live_pids is not None:
1236
+ if s.agent_pid not in live_pids:
1237
+ s.status = Status.ENDED
1238
+ else:
1239
+ claimed_pids.setdefault(key, set()).add(s.agent_pid)
1240
+ # 保留完整分組基數與已認領的名額,但 fallback 不得覆寫精準 PID 結果。
1241
+ pid_resolved.add(s.session_id)
1191
1242
 
1192
1243
  for key, rows in rows_by_key.items():
1193
1244
  pk, row_cwd = key
1194
1245
  if pk in unknown_providers:
1195
1246
  continue # 這輪掃描失敗,未知不等於離場,保留既有狀態
1247
+ fallback_rows = [s for s in rows if s.session_id not in pid_resolved]
1248
+ if not fallback_rows:
1249
+ continue
1196
1250
  live_n = proc_counts.get(key, 0)
1197
1251
  if live_n == 0:
1198
1252
  if _has_ancestor_live_process(row_cwd, proc_cwds_by_provider.get(pk, [])):
@@ -1202,30 +1256,26 @@ def _hook_sessions(
1202
1256
  # cd 進子目錄的 session 誤判 ENDED(見
1203
1257
  # test_hook_sessions_keeps_live_session_when_cwd_moved_to_subdir)。
1204
1258
  continue
1205
- for s in rows:
1259
+ for s in fallback_rows:
1206
1260
  s.status = Status.ENDED
1207
1261
  continue
1208
1262
 
1209
- # 單筆 row:不靠 tty 殺,理由見上方註解 3——避免唯一活著的 session 因 tty
1263
+ # 單筆舊格式 row:不靠 tty 殺,理由見上方註解 4——避免唯一活著的 session 因 tty
1210
1264
  # 重配而憑空消失(test_hook_sessions_keeps_lone_live_session_with_wrong_tty)。
1211
1265
  if len(rows) == 1:
1212
1266
  continue
1213
1267
 
1214
1268
  live_ttys = proc_ttys.get(key, set())
1215
1269
  if live_ttys:
1216
- for s in rows:
1270
+ for s in fallback_rows:
1217
1271
  if s.tty and s.tty not in live_ttys:
1218
1272
  s.status = Status.ENDED
1219
1273
 
1220
- if len(rows) <= live_n:
1221
- # 沒有多餘列要修剪,但上面的 tty 交叉比對仍然有效——即使計數巧合對上,
1222
- # tty 對不上的那幾筆(例如已 crash 的舊 row)還是會被標離場,不會永遠
1223
- # 靠計數巧合躲過清理。
1224
- continue
1225
-
1226
- remaining = [s for s in rows if s.status is not Status.ENDED]
1227
- if len(remaining) > live_n:
1274
+ # 新舊格式不能共用同一個 process 名額;只修剪未經 PID 確認的列。
1275
+ available = max(0, live_n - len(claimed_pids.get(key, set())))
1276
+ remaining = [s for s in fallback_rows if s.status is not Status.ENDED]
1277
+ if len(remaining) > available:
1228
1278
  remaining.sort(key=lambda s: s.last_active, reverse=True)
1229
- for s in remaining[live_n:]:
1279
+ for s in remaining[available:]:
1230
1280
  s.status = Status.ENDED
1231
1281
  return out
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes