@sakanano-moe/agenthelm 6.8.0 → 6.11.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +1 -1
  2. package/README.zh-CN.md +2 -0
  3. package/package.json +1 -1
  4. package/runtime/index.json +6 -6
  5. package/runtime/plugins/agent-pack/.codex-plugin/plugin.json +1 -1
  6. package/runtime/plugins/agent-pack/hooks/hooks.json +32 -0
  7. package/runtime/plugins/agent-pack/plugin.json +1 -1
  8. package/runtime/plugins/agent-pack/references/local-only.md +126 -0
  9. package/runtime/plugins/agent-pack/references/nudge.en.md +58 -0
  10. package/runtime/plugins/agent-pack/references/nudge.md +58 -0
  11. package/runtime/plugins/agent-pack/runtime/agent_pack_nudge.py +613 -0
  12. package/runtime/plugins/agent-pack/runtime/agenthelm.py +1271 -221
  13. package/runtime/plugins/agent-pack/runtime/agenthelm_runtime.py +114 -65
  14. package/runtime/plugins/agent-pack/runtime/i18n_agent_pack.py +78 -0
  15. package/runtime/plugins/agent-pack/runtime/local_only.py +1132 -0
  16. package/runtime/plugins/agent-pack/runtime/locale/en.json +569 -0
  17. package/runtime/plugins/agent-pack/runtime/mcp_server.py +25 -0
  18. package/runtime/plugins/agent-pack/runtime/nudge_text.py +127 -0
  19. package/runtime/plugins/agent-pack/runtime/user_settings.py +275 -0
  20. package/runtime/plugins/agent-pack/skills/agent-pack/SKILL.md +11 -1
  21. package/runtime/plugins/agents-init/.codex-plugin/plugin.json +1 -1
  22. package/runtime/plugins/agents-init/content.json +4 -4
  23. package/runtime/plugins/agents-init/plugin.json +1 -1
  24. package/runtime/plugins/agents-init/skills/agents-init/AGENT.template.md +141 -5
  25. package/runtime/plugins/agents-init/skills/agents-init/SKILL.md +41 -8
  26. package/runtime/plugins/agents-init/skills/agents-init/project.schema.json +408 -80
  27. package/runtime/plugins/agents-init/skills/agents-init/scripts/adopt.py +615 -0
  28. package/runtime/plugins/agents-init/skills/agents-init/scripts/baseline.py +221 -0
  29. package/runtime/plugins/agents-init/skills/agents-init/scripts/i18n_init.py +78 -0
  30. package/runtime/plugins/agents-init/skills/agents-init/scripts/init_project.py +748 -159
  31. package/runtime/plugins/agents-init/skills/agents-init/scripts/locale/en.json +289 -0
  32. package/runtime/plugins/agents-init/skills/agents-init/scripts/merge3.py +149 -0
  33. package/runtime/plugins/agents-init/skills/agents-init/scripts/regions.py +99 -0
  34. package/runtime/plugins/agents-init/skills/agents-init/scripts/scaffold.py +594 -90
  35. package/runtime/plugins/agents-init/skills/agents-init/skeleton.json +2 -0
  36. package/runtime/plugins/agents-init/skills/agents-init/skill.json +1 -1
  37. package/runtime/plugins/opinion-manager/.codex-plugin/plugin.json +1 -1
  38. package/runtime/plugins/opinion-manager/plugin.json +1 -1
  39. package/runtime/plugins/opinion-manager/references/inbox.en.md +48 -0
  40. package/runtime/plugins/opinion-manager/references/inbox.md +48 -0
  41. package/runtime/plugins/opinion-manager/runtime/context.py +31 -26
  42. package/runtime/plugins/opinion-manager/runtime/i18n_opinion.py +78 -0
  43. package/runtime/plugins/opinion-manager/runtime/inbox.py +398 -0
  44. package/runtime/plugins/opinion-manager/runtime/inbox_text.py +114 -0
  45. package/runtime/plugins/opinion-manager/runtime/lifecycle.py +45 -44
  46. package/runtime/plugins/opinion-manager/runtime/locale/en.json +193 -0
  47. package/runtime/plugins/opinion-manager/runtime/opinion_manager.py +55 -50
  48. package/runtime/plugins/opinion-manager/runtime/versioned.py +90 -85
  49. package/runtime/plugins/opinion-manager/skills/opinion-manager/SKILL.md +15 -2
  50. package/runtime/plugins/project-orchestrator/.codex-plugin/plugin.json +1 -1
  51. package/runtime/plugins/project-orchestrator/content.json +30 -3
  52. package/runtime/plugins/project-orchestrator/plugin.json +1 -1
  53. package/runtime/plugins/project-orchestrator/references/case-workspaces.md +9 -1
  54. package/runtime/plugins/project-orchestrator/references/case.schema.json +1 -0
  55. package/runtime/plugins/project-orchestrator/references/sop-interview.md +83 -0
  56. package/runtime/plugins/project-orchestrator/references/sop.md +156 -0
  57. package/runtime/plugins/project-orchestrator/runtime/assets.py +52 -57
  58. package/runtime/plugins/project-orchestrator/runtime/case.py +139 -80
  59. package/runtime/plugins/project-orchestrator/runtime/case_structure.py +71 -0
  60. package/runtime/plugins/project-orchestrator/runtime/case_workspace.py +47 -46
  61. package/runtime/plugins/project-orchestrator/runtime/i18n_orchestrator.py +78 -0
  62. package/runtime/plugins/project-orchestrator/runtime/locale/en.json +1450 -0
  63. package/runtime/plugins/project-orchestrator/runtime/memory.py +45 -45
  64. package/runtime/plugins/project-orchestrator/runtime/private_paths.py +119 -0
  65. package/runtime/plugins/project-orchestrator/runtime/project_base.py +37 -19
  66. package/runtime/plugins/project-orchestrator/runtime/project_cli.py +307 -195
  67. package/runtime/plugins/project-orchestrator/runtime/project_demo.py +130 -48
  68. package/runtime/plugins/project-orchestrator/runtime/project_maintain.py +328 -221
  69. package/runtime/plugins/project-orchestrator/runtime/project_menu.py +167 -89
  70. package/runtime/plugins/project-orchestrator/runtime/project_real.py +187 -105
  71. package/runtime/plugins/project-orchestrator/runtime/project_write.py +58 -55
  72. package/runtime/plugins/project-orchestrator/runtime/sop.py +1670 -0
  73. package/runtime/plugins/project-orchestrator/runtime/sop_structure.py +226 -0
  74. package/runtime/plugins/project-orchestrator/runtime/wf.py +74 -70
  75. package/runtime/plugins/project-orchestrator/skills/project-orchestrator/SKILL.md +22 -0
  76. package/runtime/plugins/project-orchestrator/sop-templates/blank/SOP.en.md +57 -0
  77. package/runtime/plugins/project-orchestrator/sop-templates/blank/SOP.md +57 -0
  78. package/runtime/plugins/project-orchestrator/sop-templates/knowledge-digest/SOP.en.md +77 -0
  79. package/runtime/plugins/project-orchestrator/sop-templates/knowledge-digest/SOP.md +77 -0
  80. package/runtime/plugins/project-orchestrator/sop-templates/knowledge-digest/templates/digest.en.md +11 -0
  81. package/runtime/plugins/project-orchestrator/sop-templates/knowledge-digest/templates/digest.md +11 -0
  82. package/runtime/plugins/project-orchestrator/sop-templates/video-to-transcript/SOP.en.md +87 -0
  83. package/runtime/plugins/project-orchestrator/sop-templates/video-to-transcript/SOP.md +87 -0
  84. package/runtime/plugins/project-orchestrator/sop-templates/weekly-review/SOP.en.md +75 -0
  85. package/runtime/plugins/project-orchestrator/sop-templates/weekly-review/SOP.md +75 -0
  86. package/runtime/plugins/project-orchestrator/sop-templates/weekly-review/templates/review.en.md +11 -0
  87. package/runtime/plugins/project-orchestrator/sop-templates/weekly-review/templates/review.md +12 -0
  88. package/runtime/plugins/project-orchestrator/templates/CASE.en.md +39 -0
  89. package/runtime/plugins/agents-init/skills/agents-init/scripts/test_init_project.py +0 -678
  90. package/runtime/plugins/agents-init/skills/agents-init/scripts/test_scaffold.py +0 -551
@@ -0,0 +1,613 @@
1
+ """agenthelm nudge:在 Claude Code、Codex、Cursor 的 hook 里自动采集观点候选、注入试行规则并提示未决事项。
2
+
3
+ ``nudge hook`` 由客户端的 hook 调用(stdin 为 hook 的 JSON),永远退出 0、只在有话要说时输出一段 JSON:
4
+
5
+ * ``session-start``:向模型注入候选采集协议与项目内试行的候选;未决候选超过阈值或久未处理时附一行用户可见提示。
6
+ * ``prompt-submit``(Claude Code、Codex):用户消息命中长期偏好关键词时,提醒模型把它暂存为候选。
7
+ * ``stop``:任务看起来已完成且本次会话暂存了还没展示过的候选时,让模型一次性请用户裁决。
8
+
9
+ 候选保存在项目的 ``.opinion/inbox.json``(由 opinion-manager 的 ``inbox`` 维护);本模块只读取汇总,
10
+ 按「待确认项提供者」契约聚合各来源,不写规则。阈值写在 Project Profile 的 ``opinion.nudge`` 或用户配置
11
+ ``~/.config/agenthelm/config.json`` 的 ``nudge``(用户配置优先)。``nudge status`` 显示生效配置与当前汇总,
12
+ ``nudge install-hooks --client cursor`` 预览或写入 Cursor 的 hooks.json。
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import os
19
+ import re
20
+ import shlex
21
+ import subprocess
22
+ import sys
23
+ import time
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ from nudge_text import LANGUAGES, resolve_language, session_flag, text as say
28
+
29
+ ENV_DISABLE = "AGENTHELM_NO_NUDGE"
30
+ ENV_DEBUG = "AGENTHELM_NUDGE_DEBUG"
31
+ CLIENTS = ("claude", "codex", "cursor")
32
+ EVENTS = ("session-start", "prompt-submit", "stop")
33
+ STOP_MODES = ("off", "on-completion", "always")
34
+ OURS = re.compile(r"agenthelm\.py['\"]?\s+nudge\s+hook")
35
+ SUBPROCESS_TIMEOUT = 5
36
+ MAX_PROMPT_CHARS = 1500
37
+ SESSION_RETENTION_SECONDS = 14 * 24 * 3600
38
+ SESSION_LIMIT = 200
39
+
40
+ DEFAULT_KEYWORDS = [
41
+ "以后都", "以后要", "以后不要", "以后别", "今后", "从现在起", "从现在开始", "每次都", "总是", "永远", "别再", "不要再",
42
+ "不要总是", "必须", "一定要", "务必", "记住", "记一下", "下次", "我希望你", "我不喜欢", "我喜欢你",
43
+ "always", "never", "from now on", "going forward", "remember to", "don't ever", "stop doing", "next time",
44
+ ]
45
+ DEFAULT_COMPLETION = [
46
+ "完成", "搞定", "已提交", "已推送", "已创建", "已实现", "已修复", "已合并", "总结",
47
+ "done", "completed", "finished", "all set", "merged", "pushed", "implemented", "fixed",
48
+ ]
49
+ DEFAULTS: dict[str, Any] = {
50
+ "enabled": True,
51
+ "language": "auto",
52
+ "pending_threshold": 5,
53
+ "stale_days": 7,
54
+ "max_prompts_per_session": 1,
55
+ "capture_hints_per_session": 3,
56
+ "trial_expire_days": 30,
57
+ "reminder_repeat_hours": 24,
58
+ "stop_prompt": {"claude": "on-completion", "codex": "on-completion", "cursor": "off"},
59
+ "keywords": DEFAULT_KEYWORDS,
60
+ "completion_keywords": DEFAULT_COMPLETION,
61
+ }
62
+
63
+
64
+ # ---------------------------------------------------------------- configuration
65
+
66
+ def _positive_int(value: Any, fallback: int) -> int:
67
+ return value if isinstance(value, int) and not isinstance(value, bool) and value >= 1 else fallback
68
+
69
+
70
+ def _words(value: Any, fallback: list[str]) -> list[str]:
71
+ if isinstance(value, list) and value and all(isinstance(item, str) and item.strip() for item in value):
72
+ return [item.strip().lower() for item in value]
73
+ return [item.lower() for item in fallback]
74
+
75
+
76
+ def merge_config(*layers: Any) -> tuple[dict[str, Any], list[str]]:
77
+ """内置默认 ← 项目 Profile ← 用户配置;非法值忽略并报告,不让会话失败。"""
78
+ config = {key: (dict(value) if isinstance(value, dict) else value) for key, value in DEFAULTS.items()}
79
+ problems: list[tuple[str, dict]] = []
80
+ for index, layer in enumerate(layers):
81
+ label = ("label_profile", "label_user")[index]
82
+ if layer is None:
83
+ continue
84
+ if not isinstance(layer, dict):
85
+ problems.append(("warn_object", {"label": label}))
86
+ continue
87
+ for key, value in layer.items():
88
+ if key not in DEFAULTS:
89
+ problems.append(("warn_unknown", {"label": label, "key": key}))
90
+ elif key == "enabled":
91
+ if isinstance(value, bool):
92
+ config[key] = value
93
+ else:
94
+ problems.append(("warn_bool", {"label": label, "key": key}))
95
+ elif key == "language":
96
+ if value in ("auto", *LANGUAGES):
97
+ config[key] = value
98
+ else:
99
+ problems.append(("warn_language", {"label": label}))
100
+ elif key == "stop_prompt":
101
+ modes = {client: value for client in CLIENTS} if isinstance(value, str) else value
102
+ if isinstance(modes, dict) and all(client in CLIENTS and mode in STOP_MODES for client, mode in modes.items()):
103
+ config[key] = {**config[key], **modes}
104
+ else:
105
+ problems.append(("warn_stop", {"label": label, "modes": "/".join(STOP_MODES)}))
106
+ elif key in ("keywords", "completion_keywords"):
107
+ parsed = _words(value, [])
108
+ if parsed:
109
+ config[key] = parsed
110
+ else:
111
+ problems.append(("warn_words", {"label": label, "key": key}))
112
+ elif isinstance(value, int) and not isinstance(value, bool) and value >= 1:
113
+ config[key] = value
114
+ else:
115
+ problems.append(("warn_int", {"label": label, "key": key}))
116
+ config["keywords"] = _words(config["keywords"], DEFAULT_KEYWORDS)
117
+ config["completion_keywords"] = _words(config["completion_keywords"], DEFAULT_COMPLETION)
118
+ config["lang"] = resolve_language(config["language"])
119
+ warnings = [say(key, config["lang"], **{**fields, **({"label": say(fields["label"], config["lang"])} if "label" in fields else {})})
120
+ for key, fields in problems]
121
+ return config, warnings
122
+
123
+
124
+ def project_profile(host: Any, root: Path) -> dict:
125
+ try:
126
+ data = host.read_json(root / host.PROFILE_FILE)
127
+ except (OSError, ValueError):
128
+ return {}
129
+ return data if isinstance(data, dict) else {}
130
+
131
+
132
+ def load_config(host: Any, env: Any, root: Path | None) -> tuple[dict[str, Any], list[str]]:
133
+ profile_layer = None
134
+ if root is not None:
135
+ opinion = project_profile(host, root).get("opinion")
136
+ profile_layer = opinion.get("nudge") if isinstance(opinion, dict) else None
137
+ try:
138
+ user = host.read_json(env.config_file)
139
+ user_layer = user.get("nudge") if isinstance(user, dict) else None
140
+ except (OSError, ValueError):
141
+ user_layer = None
142
+ return merge_config(profile_layer, user_layer)
143
+
144
+
145
+ # ---------------------------------------------------------------- project and manager discovery
146
+
147
+ def find_project(host: Any, start: Path | None) -> Path | None:
148
+ """从 start 向上找启用了 opinion-manager 的项目根;与 Opinion 无关的目录不产生任何输出。"""
149
+ if start is None:
150
+ return None
151
+ base = start.expanduser().resolve()
152
+ for path in [base, *base.parents]:
153
+ if (path / host.PROFILE_FILE).is_file():
154
+ opinion = project_profile(host, path).get("opinion")
155
+ provider = opinion.get("provider") if isinstance(opinion, dict) else None
156
+ enabled = provider == "opinion-manager" or (path / ".opinion").is_dir() or (path / "opinion.lock.json").is_file()
157
+ return path if enabled else None
158
+ if (path / ".opinion").is_dir() or (path / "opinion.lock.json").is_file():
159
+ return path
160
+ return None
161
+
162
+
163
+ def payload_directory(payload: dict, client: str, environment: dict) -> Path | None:
164
+ roots = payload.get("workspace_roots")
165
+ candidate = (roots[0] if isinstance(roots, list) and roots else None) or payload.get("cwd") \
166
+ or environment.get("CURSOR_PROJECT_DIR") or environment.get("CLAUDE_PROJECT_DIR")
167
+ return Path(candidate) if isinstance(candidate, str) and candidate else None
168
+
169
+
170
+ def detect_client(requested: str, payload: dict, environment: dict) -> str:
171
+ if requested != "auto":
172
+ return requested
173
+ if "workspace_roots" in payload or "conversation_id" in payload:
174
+ return "cursor"
175
+ if "turn_id" in payload or environment.get("PLUGIN_ROOT"):
176
+ return "codex"
177
+ return "claude"
178
+
179
+
180
+ def find_manager(host: Any, env: Any) -> Path | None:
181
+ installed = host.installed_plugins(env, {"opinion-manager"})
182
+ found = host.locate_companion("opinion-manager", installed)
183
+ return found / "runtime" / "opinion_manager.py" if found is not None else None
184
+
185
+
186
+ MANAGER_FAILURES: list[str] = [] # opinion-manager calls that failed during this hook run (summaries, no user text)
187
+
188
+
189
+ def _manager_failed(arguments: tuple[str, ...], reason: str) -> None:
190
+ words = [word for word in arguments[:2] if re.fullmatch(r"[a-z][a-z-]*", word)]
191
+ MANAGER_FAILURES.append(f"opinion-manager {' '.join(words)}: {reason}")
192
+
193
+
194
+ def run_manager(manager: Path, *arguments: str, lang: str | None = None) -> Any:
195
+ command = [*arguments, "--lang", lang] if lang else list(arguments)
196
+ try:
197
+ completed = subprocess.run([sys.executable, str(manager), *command], capture_output=True, text=True,
198
+ check=False, timeout=SUBPROCESS_TIMEOUT)
199
+ except (OSError, subprocess.SubprocessError) as exc:
200
+ _manager_failed(arguments, type(exc).__name__)
201
+ return None
202
+ if completed.returncode != 0:
203
+ _manager_failed(arguments, f"exit {completed.returncode}")
204
+ return None
205
+ if "markdown" in arguments:
206
+ return completed.stdout
207
+ try:
208
+ result = json.loads(completed.stdout)
209
+ except ValueError:
210
+ _manager_failed(arguments, "invalid JSON output")
211
+ return None
212
+ return result if isinstance(result, dict) and result.get("ok") else None
213
+
214
+
215
+ # ---------------------------------------------------------------- pending-item providers
216
+
217
+ def opinion_provider(manager: Path | None, root: Path, session: str, lang: str) -> dict | None:
218
+ """待确认项提供者契约:返回 {source, items[{id, source, title, status, age_days, hint_command…}],
219
+ counts, oldest_pending_days, last_action_at, session_unpresented}。其他来源(如 SOP 待办)按同一结构接入。"""
220
+ if manager is None or not (root / ".opinion" / "inbox.json").is_file():
221
+ return None
222
+ arguments = ["inbox", "pending", "--project", str(root)] + (["--session", session] if session else [])
223
+ return run_manager(manager, *arguments, lang=lang)
224
+
225
+
226
+ PROVIDERS = (opinion_provider,)
227
+
228
+
229
+ def collect(manager: Path | None, root: Path, session: str, lang: str) -> dict:
230
+ summaries = [result for provider in PROVIDERS if (result := provider(manager, root, session, lang))]
231
+ waiting = [item for summary in summaries for item in summary["items"] if item["status"] == "pending"]
232
+ return {"summaries": summaries, "pending": len(waiting),
233
+ "trial": sum(1 for summary in summaries for item in summary["items"] if item["status"] == "trial"),
234
+ "oldest_days": max((item["age_days"] for item in waiting), default=0.0),
235
+ "hint": next((item["hint_command"] for item in waiting), None),
236
+ "session_unpresented": [identity for summary in summaries for identity in summary.get("session_unpresented", [])]}
237
+
238
+
239
+ def reminder_text(summary: dict, config: dict) -> str | None:
240
+ count, oldest, lang = summary["pending"], summary["oldest_days"], config["lang"]
241
+ if not count or not (count >= config["pending_threshold"] or oldest >= config["stale_days"]):
242
+ return None
243
+ return say("reminder", lang, count=count,
244
+ age=say("reminder_age", lang, days=int(oldest)) if oldest >= 1 else "",
245
+ trial=say("reminder_trial", lang, trial=summary["trial"]) if summary["trial"] else "")
246
+
247
+
248
+ # ---------------------------------------------------------------- machine-local state
249
+
250
+ def state_file(env: Any) -> Path:
251
+ return env.state_dir / "agenthelm" / "nudge.json"
252
+
253
+
254
+ def load_state(host: Any, env: Any) -> dict:
255
+ try:
256
+ data = host.read_json(state_file(env))
257
+ if isinstance(data, dict) and isinstance(data.get("sessions"), dict):
258
+ data.setdefault("reminders", {})
259
+ data.setdefault("exposure_noted", {})
260
+ return data
261
+ except (OSError, ValueError):
262
+ pass
263
+ return {"sessions": {}, "reminders": {}, "exposure_noted": {}}
264
+
265
+
266
+ def save_state(host: Any, env: Any, state: dict) -> None:
267
+ moment = time.time()
268
+ sessions = {key: value for key, value in state["sessions"].items() if moment - value.get("at", 0) < SESSION_RETENTION_SECONDS}
269
+ if len(sessions) > SESSION_LIMIT:
270
+ sessions = dict(sorted(sessions.items(), key=lambda item: item[1].get("at", 0))[-SESSION_LIMIT:])
271
+ state["sessions"] = sessions
272
+ try:
273
+ host.write_json_atomic(state_file(env), state)
274
+ except OSError:
275
+ pass
276
+
277
+
278
+ def session_record(state: dict, session: str) -> dict:
279
+ record = state["sessions"].setdefault(session or "unknown", {"capture_hints": 0, "stop_prompts": 0})
280
+ record["at"] = time.time()
281
+ return record
282
+
283
+
284
+ # ---------------------------------------------------------------- output per client
285
+
286
+ def render(client: str, event: str, *, context: str | None = None, system: str | None = None,
287
+ follow_up: bool = False) -> dict | None:
288
+ """各客户端的 hook 输出格式。context 为给模型的文字,system 为给用户看的一行。"""
289
+ if not context and not system:
290
+ return None
291
+ if client == "cursor":
292
+ if event == "session-start":
293
+ return {"additional_context": context} if context else None
294
+ return {"followup_message": context} if context and event == "stop" else None
295
+ if event == "stop" and client == "codex":
296
+ return {"decision": "block", "reason": context} if context else None
297
+ name = {"session-start": "SessionStart", "prompt-submit": "UserPromptSubmit", "stop": "Stop"}[event]
298
+ output: dict[str, Any] = {}
299
+ if system:
300
+ output["systemMessage"] = system
301
+ if context:
302
+ output["hookSpecificOutput"] = {"hookEventName": name, "additionalContext": context}
303
+ return output
304
+
305
+
306
+ # ---------------------------------------------------------------- events
307
+
308
+ def session_start(host: Any, env: Any, payload: dict, client: str, root: Path, config: dict) -> dict | None:
309
+ manager = find_manager(host, env)
310
+ if manager is None:
311
+ return None
312
+ session = str(payload.get("session_id") or payload.get("conversation_id") or "")
313
+ source = str(payload.get("source") or "startup")
314
+ if (root / ".opinion" / "inbox.json").is_file():
315
+ run_manager(manager, "inbox", "expire", "--project", str(root), "--days", str(config["trial_expire_days"]), lang=config["lang"])
316
+ brief = run_manager(manager, "inbox", "brief", "--project", str(root), *(["--session", session] if session else []), lang=config["lang"])
317
+ context = brief["text"] if brief else None
318
+ if source == "compact":
319
+ return render(client, "session-start", context=context)
320
+ summary = collect(manager, root, session, config["lang"])
321
+ text = reminder_text(summary, config)
322
+ state = load_state(host, env)
323
+ shown: list[str] = []
324
+ if text:
325
+ previous = state["reminders"].get(str(root), {})
326
+ if time.time() - previous.get("at", 0) >= config["reminder_repeat_hours"] * 3600:
327
+ state["reminders"][str(root)] = {"at": time.time()}
328
+ shown.append(text)
329
+ context = (context or "") + say("reminder_hint", config["lang"], text=text)
330
+ notice = exposure_notice(manager, root, state, config["lang"])
331
+ if notice:
332
+ shown.append(notice)
333
+ if client != "claude":
334
+ context = (context or "") + say("relay", config["lang"], notice=notice)
335
+ if shown:
336
+ save_state(host, env, state)
337
+ return render(client, "session-start", context=context, system="\n".join(shown) or None)
338
+
339
+
340
+ def exposure_notice(manager: Path, root: Path, state: dict, lang: str) -> str | None:
341
+ """收件箱含用户原话:每个项目只在第一次提醒一次是否会随仓库或同步盘被他人看到。只告知,不替用户决定,不改任何文件。"""
342
+ if not (root / ".opinion" / "inbox.json").is_file() or str(root) in state["exposure_noted"]:
343
+ return None
344
+ result = run_manager(manager, "inbox", "exposure", "--project", str(root), lang=lang)
345
+ if not result or not result.get("needs_notice"):
346
+ return None
347
+ state["exposure_noted"][str(root)] = {"at": time.time(), "git": result["git"]}
348
+ return "[Opinion] " + result["message"]
349
+
350
+
351
+ def prompt_submit(host: Any, env: Any, payload: dict, client: str, root: Path, config: dict) -> dict | None:
352
+ prompt = payload.get("prompt")
353
+ if client == "cursor" or not isinstance(prompt, str) or not prompt.strip() or len(prompt) > MAX_PROMPT_CHARS:
354
+ return None
355
+ lowered = prompt.lower()
356
+ hits = [word for word in config["keywords"] if word in lowered]
357
+ if not hits:
358
+ return None
359
+ session = str(payload.get("session_id") or "")
360
+ state = load_state(host, env)
361
+ record = session_record(state, session)
362
+ if record["capture_hints"] >= config["capture_hints_per_session"]:
363
+ return None
364
+ record["capture_hints"] += 1
365
+ save_state(host, env, state)
366
+ manager = find_manager(host, env)
367
+ lang = config["lang"]
368
+ command = say("add_command", lang, manager=manager, root=root, lang=lang,
369
+ session=session_flag(session)) if manager else say("add_command_fallback", lang)
370
+ context = say("prompt_hint", lang, hits=say("sep", lang).join(hits[:3]), command=command)
371
+ return render(client, "prompt-submit", context=context)
372
+
373
+
374
+ def stop(host: Any, env: Any, payload: dict, client: str, root: Path, config: dict) -> dict | None:
375
+ mode = config["stop_prompt"].get(client, "off")
376
+ if mode == "off" or payload.get("stop_hook_active") or payload.get("loop_count"):
377
+ return None
378
+ if client == "cursor" and payload.get("status") not in (None, "completed"):
379
+ return None
380
+ session = str(payload.get("session_id") or payload.get("conversation_id") or "")
381
+ inbox = root / ".opinion" / "inbox.json"
382
+ if not session or not inbox.is_file() or session not in inbox.read_text(encoding="utf-8", errors="replace"):
383
+ return None
384
+ state = load_state(host, env)
385
+ record = session_record(state, session)
386
+ if record["stop_prompts"] >= config["max_prompts_per_session"]:
387
+ return None
388
+ message = str(payload.get("last_assistant_message") or "").lower()
389
+ if mode == "on-completion" and client != "cursor" and not any(word in message for word in config["completion_keywords"]):
390
+ return None
391
+ manager = find_manager(host, env)
392
+ if manager is None:
393
+ return None
394
+ summary = collect(manager, root, session, config["lang"])
395
+ identifiers = summary["session_unpresented"]
396
+ if not identifiers:
397
+ return None
398
+ listing = run_manager(manager, "inbox", "list", "--project", str(root), "--session", session, "--unpresented",
399
+ "--status", "pending", "--output", "markdown", lang=config["lang"])
400
+ if not listing:
401
+ return None
402
+ run_manager(manager, "inbox", "present", *identifiers, "--project", str(root), lang=config["lang"])
403
+ record["stop_prompts"] += 1
404
+ save_state(host, env, state)
405
+ context = say("stop_request", config["lang"], count=len(identifiers), manager=manager, root=root, lang=config["lang"], listing=listing)
406
+ return render(client, "stop", context=context)
407
+
408
+
409
+ HANDLERS = {"session-start": session_start, "prompt-submit": prompt_submit, "stop": stop}
410
+
411
+
412
+ def read_payload() -> dict:
413
+ if sys.stdin is None or sys.stdin.isatty():
414
+ return {}
415
+ try:
416
+ data = json.loads(sys.stdin.read() or "{}")
417
+ except ValueError:
418
+ return {}
419
+ return data if isinstance(data, dict) else {}
420
+
421
+
422
+ def run_hook(args: argparse.Namespace, host: Any, payload: dict | None = None) -> dict | None:
423
+ """hook 入口:任何异常都吞掉,保证不影响客户端会话;最近一次错误的摘要(不含用户原话)记到用户状态目录,供 nudge status / doctor 查看。"""
424
+ del MANAGER_FAILURES[:]
425
+ env = None
426
+ try:
427
+ env = host.current_env(args.home)
428
+ if env.get(ENV_DISABLE) not in (None, "0", "false"):
429
+ return None
430
+ payload = read_payload() if payload is None else payload
431
+ client = detect_client(args.client, payload, dict(os.environ))
432
+ root = find_project(host, payload_directory(payload, client, dict(os.environ)))
433
+ if root is None:
434
+ return None
435
+ config, _ = load_config(host, env, root)
436
+ if not config["enabled"]:
437
+ return None
438
+ output = HANDLERS[args.event](host, env, payload, client, root, config)
439
+ if MANAGER_FAILURES:
440
+ _record(host, env, args.event, MANAGER_FAILURES[0])
441
+ return output
442
+ except Exception as exc: # noqa: BLE001 - a nudge must never break a session
443
+ _record(host, env, args.event, exc, home=args.home)
444
+ if os.environ.get(ENV_DEBUG):
445
+ import traceback
446
+ traceback.print_exc(file=sys.stderr)
447
+ return None
448
+
449
+
450
+ def _record(host: Any, env: Any, event: str, error: Any, home: Path | None = None) -> None:
451
+ try:
452
+ if env is None:
453
+ env = host.current_env(home)
454
+ host.record_hook_error(env, f"nudge {event}", error)
455
+ except Exception: # noqa: BLE001 - recording is best effort and silent
456
+ pass
457
+
458
+
459
+ # ---------------------------------------------------------------- status and hook installation
460
+
461
+ def status(args: argparse.Namespace, host: Any) -> dict:
462
+ env = host.current_env(args.home)
463
+ root = find_project(host, args.project or Path.cwd())
464
+ config, warnings = load_config(host, env, root)
465
+ cleared = host.clear_hook_errors(env) if getattr(args, "clear_errors", False) else False
466
+ result: dict[str, Any] = {"ok": True, "project": str(root) if root else None, "config": config, "warnings": warnings,
467
+ "disabled_by_environment": env.get(ENV_DISABLE) not in (None, "0", "false"),
468
+ "last_hook_error": host.last_hook_error(env), "hook_errors_cleared": cleared}
469
+ if root is None:
470
+ result["note"] = say("note_no_project", config["lang"])
471
+ return result
472
+ manager = find_manager(host, env)
473
+ result["opinion_manager"] = str(manager) if manager else None
474
+ summary = collect(manager, root, "", config["lang"])
475
+ result["summary"] = {key: summary[key] for key in ("pending", "trial", "oldest_days")}
476
+ if manager is not None and (root / ".opinion" / "inbox.json").is_file():
477
+ result["exposure"] = run_manager(manager, "inbox", "exposure", "--project", str(root), lang=config["lang"])
478
+ result["reminder"] = reminder_text(summary, config)
479
+ return result
480
+
481
+
482
+ def cursor_commands(runtime: Path) -> dict[str, dict]:
483
+ # POSIX 用 shlex.quote(路径含 $、反引号、双引号时双引号不够);Windows 的 cmd 不认单引号,保留双引号
484
+ quoted = shlex.quote(str(runtime)) if os.name == "posix" else f'"{runtime}"'
485
+ base = f"python3 {quoted} nudge hook --client cursor --event"
486
+ return {"sessionStart": {"command": f"{base} session-start", "timeout": 10},
487
+ "stop": {"command": f"{base} stop", "timeout": 10}}
488
+
489
+
490
+ def merged_cursor_hooks(existing: dict, runtime: Path, remove: bool) -> dict:
491
+ data = json.loads(json.dumps(existing)) if existing else {}
492
+ data.setdefault("version", 1)
493
+ hooks = data.setdefault("hooks", {})
494
+ wanted = cursor_commands(runtime)
495
+ for event in list(hooks):
496
+ kept = [entry for entry in hooks[event] if not (isinstance(entry, dict) and OURS.search(str(entry.get("command", ""))))]
497
+ if kept:
498
+ hooks[event] = kept
499
+ else:
500
+ del hooks[event]
501
+ if not remove:
502
+ for event, entry in wanted.items():
503
+ hooks.setdefault(event, []).append(entry)
504
+ return data
505
+
506
+
507
+ def install_hooks(args: argparse.Namespace, host: Any) -> dict:
508
+ env = host.current_env(args.home)
509
+ lang = load_config(host, env, None)[0]["lang"]
510
+ if args.scope == "project":
511
+ project = (args.project or Path.cwd()).expanduser().resolve()
512
+ target = project / ".cursor" / "hooks.json"
513
+ else:
514
+ target = env.home / ".cursor" / "hooks.json"
515
+ try:
516
+ existing = host.read_json(target) if target.is_file() else {}
517
+ except ValueError as exc:
518
+ raise host.CheckError(say("err_hooks_json", lang, target=target, error=exc)) from exc
519
+ if not isinstance(existing, dict):
520
+ raise host.CheckError(say("err_hooks_root", lang, target=target))
521
+ runtime = Path(__file__).resolve().with_name("agenthelm.py")
522
+ merged = merged_cursor_hooks(existing, runtime, args.remove)
523
+ changed = merged != existing
524
+ result = {"ok": True, "applied": False, "target": str(target), "changed": changed, "remove": args.remove,
525
+ "hooks": merged.get("hooks", {})}
526
+ if args.apply and changed:
527
+ if target.is_file():
528
+ backup = target.with_name(target.name + ".agenthelm-bak")
529
+ if not backup.exists(): # the first original only: it is never refreshed
530
+ try:
531
+ backup.write_text(target.read_text(encoding="utf-8"), encoding="utf-8")
532
+ except (OSError, ValueError) as exc:
533
+ raise host.CheckError(say("err_backup", lang, target=target, backup=backup, error=exc)) from exc
534
+ result["backup"] = str(backup)
535
+ host.write_json_atomic(target, merged)
536
+ result["applied"] = True
537
+ result["note"] = say("note_cursor", lang)
538
+ result["lang"] = lang
539
+ return result
540
+
541
+
542
+ def parser() -> argparse.ArgumentParser:
543
+ result = argparse.ArgumentParser(prog="agenthelm nudge", description="agenthelm nudge: collect opinion candidates from client hooks and remind about unconfirmed items")
544
+ sub = result.add_subparsers(dest="action", required=True)
545
+ hook = sub.add_parser("hook", help="called by a client hook: the hook JSON arrives on stdin, always exits 0")
546
+ hook.add_argument("--event", choices=EVENTS, required=True)
547
+ hook.add_argument("--client", choices=("auto", *CLIENTS), default="auto")
548
+ hook.add_argument("--home", type=Path, help=argparse.SUPPRESS)
549
+ state = sub.add_parser("status", help="show the effective config, the current pending summary and whether a new session would remind")
550
+ state.add_argument("--project", type=Path)
551
+ state.add_argument("--clear-errors", action="store_true", help="clear the recorded last hook error")
552
+ state.add_argument("--output", choices=("text", "json"), default="text")
553
+ state.add_argument("--home", type=Path, help=argparse.SUPPRESS)
554
+ install = sub.add_parser("install-hooks", help="write the nudge hooks into Cursor's hooks.json (preview by default)")
555
+ install.add_argument("--client", choices=("cursor",), default="cursor")
556
+ install.add_argument("--scope", choices=("user", "project"), default="user")
557
+ install.add_argument("--project", type=Path)
558
+ install.add_argument("--remove", action="store_true", help="remove the entries agenthelm wrote")
559
+ install.add_argument("--apply", action="store_true")
560
+ install.add_argument("--output", choices=("text", "json"), default="text")
561
+ install.add_argument("--home", type=Path, help=argparse.SUPPRESS)
562
+ return result
563
+
564
+
565
+ def main(argv: list[str], host: Any) -> int:
566
+ args = parser().parse_args(argv)
567
+ if args.action == "hook":
568
+ output = run_hook(args, host)
569
+ if output is not None:
570
+ print(json.dumps(output, ensure_ascii=False))
571
+ return 0
572
+ try:
573
+ result = status(args, host) if args.action == "status" else install_hooks(args, host)
574
+ except host.CheckError as exc:
575
+ print(f"error: {exc}", file=sys.stderr)
576
+ return 2
577
+ if args.output == "json":
578
+ print(json.dumps(result, ensure_ascii=False, indent=2))
579
+ return 0
580
+ if args.action == "status":
581
+ config = result["config"]
582
+ lang = config["lang"]
583
+ if result["disabled_by_environment"]:
584
+ state = say("status_env_off", lang)
585
+ else:
586
+ state = say("status_on", lang) if config["enabled"] else say("status_off", lang)
587
+ lines = [say("status_project", lang, project=result["project"] or say("status_no_project", lang)),
588
+ say("status_switch", lang, state=state),
589
+ say("status_thresholds", lang, pending=config["pending_threshold"], stale=config["stale_days"],
590
+ prompts=config["max_prompts_per_session"], expire=config["trial_expire_days"],
591
+ stop=config["stop_prompt"], language=f"{config['language']} ({lang})")]
592
+ if result.get("summary"):
593
+ summary = result["summary"]
594
+ lines.append(say("status_current", lang, pending=summary["pending"], trial=summary["trial"], days=int(summary["oldest_days"])))
595
+ lines.append(result["reminder"] or say("status_quiet", lang))
596
+ if result.get("exposure"):
597
+ lines.append(say("status_exposure", lang, message=result["exposure"]["message"]))
598
+ lines += [say("status_warning", lang, item=item) for item in result["warnings"]]
599
+ if result["hook_errors_cleared"]:
600
+ lines.append(say("status_errors_cleared", lang))
601
+ failure = result["last_hook_error"]
602
+ if failure:
603
+ lines.append(say("status_hook_error", lang, line=host.hook_error_line(failure), count=failure["count"]))
604
+ if result.get("note"):
605
+ lines.append(result["note"])
606
+ print("\n".join(lines))
607
+ else:
608
+ lang = result["lang"]
609
+ verb = say("install_written" if result["applied"] else ("install_unchanged" if not result["changed"] else "install_preview"), lang)
610
+ print(say("install_line", lang, verb=verb, target=result["target"]))
611
+ print(json.dumps(result["hooks"], ensure_ascii=False, indent=2))
612
+ print(result["note"])
613
+ return 0