@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,398 @@
1
+ """项目私有的候选收件箱:低摩擦暂存 Agent 在工作中发现的观点,从不写入 OPINION.md、Profile 或锁。
2
+
3
+ 收件箱记录的是“待用户裁决的候选”,不是规则。状态只有五种:pending(待确认)、trial(项目内试行)、
4
+ formal(用户已同意转正,正文仍须经 opinion-manager 的完整预览与确认写入)、held(暂缓)、rejected(丢弃)。
5
+ 暂存(add)无需确认;任何状态变化(decide)都必须带 ``--confirmed``,表示用户已看过候选全文并明确表态。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import fcntl
12
+ import hashlib
13
+ import json
14
+ import os
15
+ import re
16
+ import shlex
17
+ import subprocess
18
+ import tempfile
19
+ from datetime import UTC, datetime
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ import inbox_text as words
24
+ import versioned
25
+
26
+
27
+ STORE = Path(".opinion") / "inbox.json"
28
+ STATUSES = ("pending", "trial", "formal", "held", "rejected")
29
+ DECIDABLE = ("pending", "trial", "formal", "held", "rejected")
30
+ OPEN_STATUSES = ("pending", "trial")
31
+ EMPTY = {"schema_version": 1, "candidates": {}}
32
+ MAX_TITLE, MAX_TEXT, MAX_QUOTE = 120, 1200, 600
33
+ RUNTIME = Path(__file__).resolve().with_name("opinion_manager.py")
34
+
35
+ LANGUAGE = words.DEFAULT_LANGUAGE
36
+
37
+
38
+ class InboxError(ValueError):
39
+ pass
40
+
41
+
42
+ def say(key: str, **fields: Any) -> str:
43
+ return words.text(key, LANGUAGE, **fields)
44
+
45
+
46
+ def fail(key: str, **fields: Any) -> None:
47
+ raise InboxError(say(key, **fields))
48
+
49
+
50
+ def now() -> datetime:
51
+ return datetime.now(UTC)
52
+
53
+
54
+ def stamp(moment: datetime | None = None) -> str:
55
+ return (moment or now()).strftime("%Y-%m-%dT%H:%M:%SZ")
56
+
57
+
58
+ def parse_stamp(value: str) -> datetime:
59
+ return datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=UTC)
60
+
61
+
62
+ def days_since(value: str | None, moment: datetime | None = None) -> float:
63
+ if not value:
64
+ return 0.0
65
+ return max(0.0, ((moment or now()) - parse_stamp(value)).total_seconds() / 86400)
66
+
67
+
68
+ def store_path(root: Path) -> Path:
69
+ for item in (root / ".opinion", root / STORE):
70
+ if item.is_symlink():
71
+ fail("err_symlink", path=item)
72
+ return root / STORE
73
+
74
+
75
+ def git_status(root: Path) -> str:
76
+ """只读判断 .opinion/inbox.json 在 Git 里的状态;从不修改任何文件。"""
77
+ def git(*arguments: str) -> int | None:
78
+ try:
79
+ return subprocess.run(["git", "-C", str(root), *arguments], capture_output=True, check=False, timeout=5).returncode
80
+ except (OSError, subprocess.SubprocessError):
81
+ return None
82
+
83
+ target = STORE.as_posix()
84
+ inside = git("rev-parse", "--is-inside-work-tree")
85
+ if inside is None:
86
+ return "unknown"
87
+ if inside != 0:
88
+ return "no-git"
89
+ if git("ls-files", "--error-unmatch", "--", target) == 0:
90
+ return "tracked"
91
+ ignored = git("check-ignore", "-q", "--", target)
92
+ return "ignored" if ignored == 0 else ("not-ignored" if ignored == 1 else "unknown")
93
+
94
+
95
+ def exposure(root: Path) -> dict[str, Any]:
96
+ state = git_status(root)
97
+ return {"ok": True, "status": "read-only", "git": state, "needs_notice": state != "ignored",
98
+ "message": say("exposure_notice") + say("gap") + say(f"state_{state}")}
99
+
100
+
101
+ def normalized(title: str, text: str) -> str:
102
+ return hashlib.sha256(re.sub(r"\s+", "", f"{title}{text}").lower().encode("utf-8")).hexdigest()
103
+
104
+
105
+ def load(root: Path) -> dict[str, Any]:
106
+ path = store_path(root)
107
+ if not path.exists():
108
+ return json.loads(json.dumps(EMPTY))
109
+ data = json.loads(path.read_text(encoding="utf-8"))
110
+ if not isinstance(data, dict) or not isinstance(data.get("candidates"), dict):
111
+ fail("err_format", path=path)
112
+ return data
113
+
114
+
115
+ def save(root: Path, data: dict[str, Any]) -> None:
116
+ path = store_path(root)
117
+ path.parent.mkdir(parents=True, exist_ok=True)
118
+ descriptor, temporary = tempfile.mkstemp(prefix=".inbox-", dir=path.parent)
119
+ try:
120
+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
121
+ json.dump(data, handle, ensure_ascii=False, indent=2, sort_keys=True)
122
+ handle.write("\n")
123
+ handle.flush()
124
+ os.fsync(handle.fileno())
125
+ os.replace(temporary, path)
126
+ finally:
127
+ if Path(temporary).exists():
128
+ Path(temporary).unlink()
129
+
130
+
131
+ class Locked:
132
+ """读改写一致:同一项目的多个会话同时暂存时不丢失。"""
133
+
134
+ def __init__(self, root: Path) -> None:
135
+ self.root = root
136
+
137
+ def __enter__(self) -> dict[str, Any]:
138
+ directory = store_path(self.root).parent
139
+ directory.mkdir(parents=True, exist_ok=True)
140
+ self.guard = (directory / ".inbox.lock").open("a")
141
+ fcntl.flock(self.guard, fcntl.LOCK_EX)
142
+ self.data = load(self.root)
143
+ return self.data
144
+
145
+ def __exit__(self, *_: object) -> None:
146
+ fcntl.flock(self.guard, fcntl.LOCK_UN)
147
+ self.guard.close()
148
+
149
+
150
+ def clean(value: str | None, label: str, limit: int, *, required: bool = True) -> str:
151
+ text = (value or "").strip()
152
+ if required and not text:
153
+ fail("err_empty", label=say(label))
154
+ if len(text) > limit:
155
+ fail("err_too_long", label=say(label), limit=limit)
156
+ return text
157
+
158
+
159
+ def next_identity(data: dict[str, Any], moment: datetime) -> str:
160
+ prefix = f"cand-{moment:%Y%m%d}-"
161
+ used = [int(key[len(prefix):]) for key in data["candidates"] if key.startswith(prefix) and key[len(prefix):].isdigit()]
162
+ return f"{prefix}{max(used, default=0) + 1:03d}"
163
+
164
+
165
+ def add(root: Path, args: argparse.Namespace) -> dict[str, Any]:
166
+ title = clean(args.title, "label_title", MAX_TITLE)
167
+ text = clean(args.text, "label_text", MAX_TEXT)
168
+ quote = clean(args.quote, "label_quote", MAX_QUOTE, required=False)
169
+ scopes = [clean(item, "label_scope", MAX_TITLE) for item in args.scope]
170
+ if not scopes:
171
+ fail("err_scope")
172
+ moment = now()
173
+ first = not store_path(root).exists()
174
+ with Locked(root) as data:
175
+ digest = normalized(title, text)
176
+ for existing in data["candidates"].values():
177
+ if existing["digest"] == digest:
178
+ if args.quote and args.quote.strip() and args.quote.strip() not in existing["quotes"]:
179
+ existing["quotes"].append(args.quote.strip())
180
+ existing["updated_at"] = stamp(moment)
181
+ save(root, data)
182
+ return {"ok": True, "status": "duplicate", "id": existing["id"], "state": existing["status"]}
183
+ identity = next_identity(data, moment)
184
+ data["candidates"][identity] = {
185
+ "id": identity, "title": title, "text": text, "scopes": scopes, "quotes": [quote] if quote else [],
186
+ "status": "pending", "digest": digest, "client": args.client or "", "session": args.session or "",
187
+ "created_at": stamp(moment), "updated_at": stamp(moment), "last_action_at": stamp(moment),
188
+ "trial_since": None, "presented": 0, "presented_at": None,
189
+ "history": [{"at": stamp(moment), "to": "pending", "note": "captured"}],
190
+ }
191
+ save(root, data)
192
+ result = {"ok": True, "status": "added", "id": identity, "state": "pending", "writes_stable_rules": False}
193
+ if first:
194
+ notice = exposure(root)
195
+ if notice["needs_notice"]:
196
+ result["notice"] = notice["message"]
197
+ return result
198
+
199
+
200
+ def decide(root: Path, args: argparse.Namespace) -> dict[str, Any]:
201
+ if not args.confirmed:
202
+ fail("err_confirm")
203
+ if args.to not in DECIDABLE:
204
+ fail("err_to", choices=say("sep").join(DECIDABLE))
205
+ moment = now()
206
+ changed = []
207
+ with Locked(root) as data:
208
+ for identity in args.ids:
209
+ candidate = data["candidates"].get(identity)
210
+ if candidate is None:
211
+ fail("err_missing", id=identity)
212
+ for identity in args.ids:
213
+ candidate = data["candidates"][identity]
214
+ if candidate["status"] == args.to:
215
+ continue
216
+ candidate["status"] = args.to
217
+ candidate["updated_at"] = candidate["last_action_at"] = stamp(moment)
218
+ candidate["trial_since"] = stamp(moment) if args.to == "trial" else None
219
+ candidate["history"].append({"at": stamp(moment), "to": args.to, "note": (args.note or "").strip()})
220
+ changed.append(identity)
221
+ save(root, data)
222
+ reminder = say("formal_reminder") if args.to == "formal" else ""
223
+ return {"ok": True, "status": "written", "changed": changed, "to": args.to, "reminder": reminder,
224
+ "writes_stable_rules": False}
225
+
226
+
227
+ def present(root: Path, args: argparse.Namespace) -> dict[str, Any]:
228
+ moment = now()
229
+ marked = []
230
+ with Locked(root) as data:
231
+ for identity in args.ids:
232
+ candidate = data["candidates"].get(identity)
233
+ if candidate is not None:
234
+ candidate["presented"] += 1
235
+ candidate["presented_at"] = stamp(moment)
236
+ marked.append(identity)
237
+ save(root, data)
238
+ return {"ok": True, "status": "written", "marked": marked}
239
+
240
+
241
+ def expire(root: Path, args: argparse.Namespace) -> dict[str, Any]:
242
+ """试行超过天数未转正则回到待确认。回退只改状态,仍保留 last_action_at,因此计入“久未处理”。"""
243
+ if args.days < 1:
244
+ fail("err_days")
245
+ moment = now()
246
+ reverted = []
247
+ with Locked(root) as data:
248
+ for candidate in data["candidates"].values():
249
+ if candidate["status"] == "trial" and days_since(candidate["trial_since"], moment) >= args.days:
250
+ candidate["status"] = "pending"
251
+ candidate["trial_since"] = None
252
+ candidate["updated_at"] = stamp(moment)
253
+ candidate["history"].append({"at": stamp(moment), "to": "pending", "note": f"trial-expired:{args.days}d"})
254
+ reverted.append(candidate["id"])
255
+ if reverted:
256
+ save(root, data)
257
+ return {"ok": True, "status": "written" if reverted else "unchanged", "reverted": reverted}
258
+
259
+
260
+ def view(candidate: dict[str, Any]) -> dict[str, Any]:
261
+ keys = ("id", "title", "text", "scopes", "quotes", "status", "created_at", "updated_at", "last_action_at",
262
+ "trial_since", "presented", "presented_at", "session", "client")
263
+ return {key: candidate[key] for key in keys}
264
+
265
+
266
+ def select(data: dict[str, Any], statuses: list[str] | None, session: str | None = None,
267
+ unpresented: bool = False) -> list[dict[str, Any]]:
268
+ items = [item for item in data["candidates"].values() if not statuses or item["status"] in statuses]
269
+ if session:
270
+ items = [item for item in items if item["session"] == session]
271
+ if unpresented:
272
+ items = [item for item in items if not item["presented"]]
273
+ return sorted(items, key=lambda item: (item["created_at"], item["id"]))
274
+
275
+
276
+ def listing(root: Path, args: argparse.Namespace) -> dict[str, Any] | str:
277
+ statuses = args.status.split(",") if args.status else None
278
+ for item in statuses or []:
279
+ if item not in STATUSES:
280
+ fail("err_status", status=item)
281
+ items = select(load(root), statuses, args.session, args.unpresented)
282
+ if args.output == "markdown":
283
+ if not items:
284
+ return say("list_empty") + "\n"
285
+ lines = []
286
+ for number, item in enumerate(items, 1):
287
+ lines.append(f"{number}. **{item['title']}** ({item['id']} · {item['status']})")
288
+ lines.append(say("list_rule", text=item["text"]))
289
+ lines.append(say("list_scope", scopes=say("sep").join(item["scopes"])))
290
+ if item["quotes"]:
291
+ lines.append(say("list_quote", quote=item["quotes"][-1]))
292
+ return "\n".join(lines) + "\n"
293
+ return {"ok": True, "status": "read-only", "value": [view(item) for item in items]}
294
+
295
+
296
+ def pending(root: Path, args: argparse.Namespace) -> dict[str, Any]:
297
+ """待确认项提供者:agent-pack 的会话开始检测按此契约汇总各来源(opinion 候选、SOP 待办等)。"""
298
+ data = load(root)
299
+ moment = now()
300
+ open_items = select(data, list(OPEN_STATUSES))
301
+ counts = {status: len(select(data, [status])) for status in STATUSES}
302
+ waiting = [item for item in open_items if item["status"] == "pending"]
303
+ command = f"python3 {shlex.quote(str(RUNTIME))} inbox list --project {shlex.quote(str(root))} --status pending,trial --output markdown"
304
+ items = [{"id": item["id"], "source": "opinion", "kind": "candidate", "title": item["title"],
305
+ "status": item["status"], "created_at": item["created_at"], "last_action_at": item["last_action_at"],
306
+ "age_days": round(days_since(item["last_action_at"], moment), 1), "hint_command": command}
307
+ for item in open_items]
308
+ session_items = select(data, ["pending"], args.session, True) if args.session else []
309
+ last_actions = [item["last_action_at"] for item in data["candidates"].values()]
310
+ return {"ok": True, "status": "read-only", "source": "opinion", "items": items, "counts": counts,
311
+ "oldest_pending_days": round(max((days_since(item["last_action_at"], moment) for item in waiting), default=0.0), 1),
312
+ "last_action_at": max(last_actions) if last_actions else None,
313
+ "session_unpresented": [item["id"] for item in session_items]}
314
+
315
+
316
+ def brief(root: Path, args: argparse.Namespace) -> dict[str, Any]:
317
+ data = load(root)
318
+ trial = select(data, ["trial"])
319
+ protocol = say("protocol", runtime=RUNTIME, project=root, lang=LANGUAGE,
320
+ session=words.session_flag(args.session))
321
+ lines = [protocol]
322
+ used = len(protocol)
323
+ shown = []
324
+ if trial:
325
+ lines.append(say("brief_trial_header"))
326
+ for item in trial:
327
+ entry = say("brief_trial_entry", id=item["id"], title=item["title"], text=item["text"],
328
+ scopes=say("sep").join(item["scopes"]))
329
+ if used + len(entry) > args.max_chars:
330
+ lines.append(say("brief_trial_more", count=len(trial) - len(shown)))
331
+ break
332
+ lines.append(entry)
333
+ used += len(entry)
334
+ shown.append(item["id"])
335
+ waiting = len(select(data, ["pending"]))
336
+ if waiting:
337
+ lines.append(say("brief_pending", count=waiting))
338
+ return {"ok": True, "status": "read-only", "text": "\n".join(lines), "trial_shown": shown,
339
+ "pending": waiting, "trial": len(trial)}
340
+
341
+
342
+ def add_command(subparsers: Any) -> None:
343
+ parser = subparsers.add_parser("inbox", help="Project-private candidate inbox: stash, decide and summarize pending items; never writes rules")
344
+ parser.add_argument("action", choices=("add", "list", "decide", "present", "expire", "pending", "brief", "exposure"))
345
+ parser.add_argument("ids", nargs="*", help="candidate ids for decide / present")
346
+ parser.add_argument("--project", type=Path, required=True)
347
+ parser.add_argument("--title")
348
+ parser.add_argument("--text")
349
+ parser.add_argument("--scope", action="append", default=[])
350
+ parser.add_argument("--quote", help="the user's own words, kept as evidence for the candidate")
351
+ parser.add_argument("--client", help="source client: claude / codex / cursor")
352
+ parser.add_argument("--session", help="source session id; lets the end-of-task confirmation cover only this session's candidates")
353
+ parser.add_argument("--status", help="list: comma-separated status filter")
354
+ parser.add_argument("--unpresented", action="store_true", help="list: only candidates not yet shown to the user")
355
+ parser.add_argument("--to", choices=DECIDABLE)
356
+ parser.add_argument("--confirmed", action="store_true", help="the user has seen the full candidate and stated a decision explicitly")
357
+ parser.add_argument("--note")
358
+ parser.add_argument("--days", type=int, help="expire: revert trials older than this many days to pending")
359
+ parser.add_argument("--max-chars", type=int, default=6000, help="brief: size limit of the text")
360
+ parser.add_argument("--output", choices=("json", "markdown"), default="json")
361
+ parser.add_argument("--lang", choices=("auto", *words.LANGUAGES), help="message language: zh / en; by default AGENTHELM_LANG, then the system locale, then English")
362
+
363
+
364
+ def run(args: argparse.Namespace) -> dict[str, Any] | str:
365
+ global LANGUAGE
366
+ LANGUAGE = words.resolve_language(getattr(args, "lang", None))
367
+ root = Path(os.path.abspath(args.project.expanduser()))
368
+ if not root.is_dir():
369
+ fail("err_project", path=root)
370
+ if args.action == "add":
371
+ return add(root, args)
372
+ if args.action == "list":
373
+ return listing(root, args)
374
+ if args.action == "pending":
375
+ return pending(root, args)
376
+ if args.action == "brief":
377
+ return brief(root, args)
378
+ if args.action == "exposure":
379
+ return exposure(root)
380
+ if args.action in ("decide", "present") and not args.ids:
381
+ fail("err_ids")
382
+ if args.action == "decide":
383
+ if not args.to:
384
+ fail("err_need_to")
385
+ return decide(root, args)
386
+ if args.action == "present":
387
+ return present(root, args)
388
+ if args.days is None:
389
+ fail("err_need_days")
390
+ return expire(root, args)
391
+
392
+
393
+ def execute(args: argparse.Namespace) -> tuple[int, str]:
394
+ try:
395
+ result = run(args)
396
+ except (InboxError, versioned.OpinionVersionError, OSError, json.JSONDecodeError) as exc:
397
+ return 2, versioned.pretty({"ok": False, "error": str(exc)})
398
+ return 0, result if isinstance(result, str) else versioned.pretty(result)
@@ -0,0 +1,114 @@
1
+ """收件箱面向用户和模型的文案(中文、英文)与语言选择。
2
+
3
+ 语言按这个顺序决定:命令行 ``--lang`` → 环境变量 ``AGENTHELM_LANG`` → 系统 locale(``LC_ALL``、``LC_MESSAGES``、
4
+ ``LANG``)→ 英文。``auto``、空值和 C/POSIX 视为未指定;中文 locale 用中文,其他语言的 locale 暂用英文。
5
+ 候选内容本身(标题、规则、用户原话)是用户的话,从不翻译;文件里的字段名与历史记录使用与语言无关的编码。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import shlex
12
+ from typing import Any
13
+
14
+
15
+ LANGUAGES = ("zh", "en")
16
+
17
+
18
+ from i18n_opinion import DEFAULT_LANGUAGE, normalize, resolve_language # noqa: E402,F401
19
+
20
+
21
+ MESSAGES: dict[str, dict[str, str]] = {
22
+ "protocol": {
23
+ "zh": """[Opinion 协议 · agenthelm]
24
+ 1. 实施前读取项目 OPINION.md(如有)并按其要求工作;下列「试行」候选同样要遵循,交付时说明是否适用。
25
+ 2. 用户在对话里表达长期偏好、纠正或规则(如“以后都…”“不要再…”“必须…”“记住…”)时,先静默暂存为候选,不打断当前工作:
26
+ python3 {runtime} inbox add --project {project} --title "<标题>" --text "<完整规则>" --scope "<适用范围>" --quote "<用户原话>"{session} --lang {lang}
27
+ 一次性的任务要求、项目事实和命令不是候选。暂存不需要确认,也不会改变任何规则。
28
+ 3. 任务完成或即将完成时,若本次暂存了候选,用编号列表一次性请用户裁决:正式采纳 / 项目内试行 / 暂缓 / 丢弃。
29
+ 用户明确表态后记录:python3 {runtime} inbox decide <编号…> --project {project} --to trial|formal|held|rejected --confirmed --lang {lang}
30
+ 采纳为正式只改状态;写入 OPINION.md 须走 opinion-manager 的完整预览与确认。
31
+ 4. 未经用户确认,不得把候选写入 OPINION.md,也不得把一次出现当作确认。
32
+ 5. inbox add 的结果带 notice(首次暂存时出现)时,用一句话如实转告用户。收件箱保存用户原话,可能含敏感信息;
33
+ 是否公开仓库、是否排除 .opinion/ 由用户决定,不要自行修改 .gitignore、删除或改写内容。
34
+ 6. 向用户转告和确认时,使用用户正在使用的语言。""",
35
+ "en": """[Opinion protocol · agenthelm]
36
+ 1. Before working, read the project's OPINION.md (if any) and follow it. The "trial" candidates listed below apply too; say in your delivery whether they applied.
37
+ 2. When the user states a lasting preference, a correction of your behavior or a rule during the conversation (e.g. "from now on...", "never again...", "must...", "remember..."), stash it as a candidate silently, without interrupting the current work:
38
+ python3 {runtime} inbox add --project {project} --title "<title>" --text "<the full rule>" --scope "<where it applies>" --quote "<the user's own words>"{session} --lang {lang}
39
+ One-off task requirements, project facts and commands are not candidates. Stashing needs no confirmation and changes no rule.
40
+ 3. When the task is done or nearly done and you stashed candidates in this session, ask the user once, as a numbered list: adopt as formal / trial in this project / hold / discard.
41
+ After the user states a decision explicitly, record it: python3 {runtime} inbox decide <ids...> --project {project} --to trial|formal|held|rejected --confirmed --lang {lang}
42
+ Adopting as formal only records the decision; writing it into OPINION.md goes through opinion-manager's full preview and confirmation.
43
+ 4. Never write a candidate into OPINION.md without the user's confirmation, and never treat a single occurrence as confirmation.
44
+ 5. When the result of inbox add carries a notice (shown on the first stash), pass it on to the user in one sentence, as written. The inbox stores the user's own words, which may contain sensitive information; whether to make the repository public or to exclude .opinion/ is the user's decision. Do not edit .gitignore, delete or rewrite anything yourself.
45
+ 6. Relay and confirm in the language the user is using.""",
46
+ },
47
+ "exposure_notice": {
48
+ "zh": "收件箱会把你的原话保存在 .opinion/inbox.json,其中可能含敏感信息。启用本功能的项目建议保持私有;"
49
+ "若要公开仓库或让他人看到,是否排除 .opinion/ 及其中内容由你决定。本工具不会替你决定,也不会修改 .gitignore。",
50
+ "en": "The inbox stores your own words in .opinion/inbox.json, which may contain sensitive information. "
51
+ "Projects that use this feature should stay private; if you want to make the repository public or visible to others, "
52
+ "whether to exclude .opinion/ and its contents is your decision. This tool will not decide for you and never edits .gitignore.",
53
+ },
54
+ "gap": {"zh": "", "en": " "},
55
+ "state_ignored": {"zh": "当前已被 Git 忽略。", "en": "It is currently ignored by Git."},
56
+ "state_tracked": {"zh": "当前已被 Git 跟踪,提交和推送会包含它。", "en": "It is currently tracked by Git, so commits and pushes include it."},
57
+ "state_not-ignored": {"zh": "当前未被 Git 忽略,提交时会被包含。", "en": "It is currently not ignored by Git, so commits will include it."},
58
+ "state_no-git": {"zh": "当前目录不是 Git 仓库;放在同步盘或共享目录里同样会被他人看到。",
59
+ "en": "This directory is not a Git repository; in a synced or shared folder it is just as visible to others."},
60
+ "state_unknown": {"zh": "无法判断 Git 状态。", "en": "The Git state could not be determined."},
61
+ "sep": {"zh": "、", "en": ", "},
62
+ "label_title": {"zh": "标题", "en": "Title"},
63
+ "label_text": {"zh": "规则正文", "en": "Rule text"},
64
+ "label_quote": {"zh": "用户原话", "en": "User's words"},
65
+ "label_scope": {"zh": "适用范围", "en": "Scope"},
66
+ "err_symlink": {"zh": "拒绝使用符号链接:{path}", "en": "Refusing to use a symbolic link: {path}"},
67
+ "err_format": {"zh": "收件箱格式不正确:{path}", "en": "The inbox file is malformed: {path}"},
68
+ "err_empty": {"zh": "{label}不能为空", "en": "{label} must not be empty"},
69
+ "err_too_long": {"zh": "{label}超过 {limit} 个字符;请拆成多条候选或精简",
70
+ "en": "{label} is longer than {limit} characters; split it into several candidates or shorten it"},
71
+ "err_scope": {"zh": "候选需要至少一个 --scope(适用范围)", "en": "A candidate needs at least one --scope"},
72
+ "err_confirm": {"zh": "状态变化需要用户明确表态:先向用户展示候选全文,用户确认后加 --confirmed",
73
+ "en": "A status change needs the user's explicit decision: show the user the full candidate first, then add --confirmed once they agree"},
74
+ "err_to": {"zh": "--to 必须是 {choices} 之一", "en": "--to must be one of: {choices}"},
75
+ "err_missing": {"zh": "没有这个候选:{id}", "en": "No such candidate: {id}"},
76
+ "err_days": {"zh": "--days 必须是正整数", "en": "--days must be a positive integer"},
77
+ "err_status": {"zh": "未知状态:{status}", "en": "Unknown status: {status}"},
78
+ "err_project": {"zh": "项目目录不存在:{path}", "en": "Project directory does not exist: {path}"},
79
+ "err_ids": {"zh": "需要至少一个候选编号", "en": "At least one candidate id is required"},
80
+ "err_need_to": {"zh": "decide 需要 --to", "en": "decide needs --to"},
81
+ "err_need_days": {"zh": "expire 需要 --days", "en": "expire needs --days"},
82
+ "formal_reminder": {"zh": "正式采纳只记录状态;写入 OPINION.md 须经 opinion-manager 的完整预览与确认。",
83
+ "en": "Adopting as formal only records the status; writing into OPINION.md needs opinion-manager's full preview and confirmation."},
84
+ "list_empty": {"zh": "没有符合条件的候选。", "en": "No matching candidates."},
85
+ "list_rule": {"zh": " - 规则:{text}", "en": " - Rule: {text}"},
86
+ "list_scope": {"zh": " - 适用:{scopes}", "en": " - Applies to: {scopes}"},
87
+ "list_quote": {"zh": " - 用户原话:{quote}", "en": " - User's words: {quote}"},
88
+ "brief_trial_header": {
89
+ "zh": "\n[试行候选 · 用户已同意在本项目试用,尚未正式;按其工作并在交付时说明是否适用]",
90
+ "en": "\n[Trial candidates · the user agreed to try these in this project; not formal yet. Follow them and say in your delivery whether they applied]"},
91
+ "brief_trial_entry": {"zh": "- {id} {title}:{text}(适用:{scopes})", "en": "- {id} {title}: {text} (applies to: {scopes})"},
92
+ "brief_trial_more": {"zh": "- …另有 {count} 条试行候选未展示:运行 inbox list --status trial 查看",
93
+ "en": "- ...{count} more trial candidates not shown: run inbox list --status trial"},
94
+ "brief_pending": {"zh": "\n[待确认候选 {count} 条,尚未生效;任务结束前可向用户集中确认]",
95
+ "en": "\n[{count} candidates await confirmation and are not in effect yet; ask the user to decide them together before the task ends]"},
96
+ }
97
+
98
+ PLACEHOLDER = re.compile(r"\{(\w+)\}")
99
+
100
+
101
+ # protocol 里的 {runtime} {project} 会被模型原样当作命令行执行,代入的路径必须经 shell 引用(POSIX)。
102
+ COMMAND_MESSAGES = {"protocol"}
103
+ PATH_FIELDS = ("runtime", "project")
104
+
105
+
106
+ def session_flag(session: str) -> str:
107
+ """命令行里的 `` --session <id>``(会话 ID 同样经 shlex.quote);没有会话 ID 时为空。"""
108
+ return f" --session {shlex.quote(str(session))}" if session else ""
109
+
110
+
111
+ def text(message_id: str, language: str, /, **fields: Any) -> str:
112
+ if message_id in COMMAND_MESSAGES:
113
+ fields = {key: shlex.quote(str(value)) if key in PATH_FIELDS else value for key, value in fields.items()}
114
+ return MESSAGES[message_id][language].format(**fields)