@leocm/flowcraft 2.2.0 → 2.3.0

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 (96) hide show
  1. package/README.md +7 -2
  2. package/bin/cli.js +108 -108
  3. package/flowcraft.yaml +30 -30
  4. package/install.sh +24 -24
  5. package/lib/args.js +38 -38
  6. package/lib/config.js +20 -20
  7. package/lib/copy.js +131 -131
  8. package/lib/fix.js +110 -110
  9. package/lib/fsutil.js +104 -104
  10. package/lib/global.js +229 -229
  11. package/lib/init.js +43 -43
  12. package/lib/runtime.js +84 -84
  13. package/lib/version.js +55 -55
  14. package/lib/wizard.js +125 -125
  15. package/package.json +33 -33
  16. package/presets/backend.yaml +20 -20
  17. package/presets/default.yaml +15 -15
  18. package/presets/frontend.yaml +20 -20
  19. package/presets/quick-fix.yaml +15 -15
  20. package/setup/.claude/hooks/check-phase-test.py +152 -152
  21. package/setup/.claude/hooks/check-phase-write.py +235 -235
  22. package/setup/.claude/hooks/dispatch.py +67 -67
  23. package/setup/.claude/hooks/file-suggestion.py +45 -45
  24. package/setup/.claude/hooks/flowcraft_env.py +162 -162
  25. package/setup/.claude/hooks/permission-request.py +132 -132
  26. package/setup/.claude/hooks/post-tool-failure.py +36 -36
  27. package/setup/.claude/hooks/pre-compact.py +66 -66
  28. package/setup/.claude/hooks/review-runner.py +846 -846
  29. package/setup/.claude/hooks/setup-keys.py +282 -282
  30. package/setup/.claude/hooks/statusline.py +63 -63
  31. package/setup/.claude/hooks/stop-check.py +186 -186
  32. package/setup/.claude/hooks/subagent-start.py +50 -50
  33. package/setup/.claude/hooks/subagent-stop.py +63 -63
  34. package/setup/.claude/hooks/task-completed.py +57 -57
  35. package/setup/.claude/hooks/task_manager.py +592 -592
  36. package/setup/.claude/hooks/user-prompt-submit.py +91 -91
  37. package/setup/.claude/settings.json +233 -233
  38. package/setup/.claude/skills/Pstatus/SKILL.md +68 -68
  39. package/setup/.claude/skills/archive/SKILL.md +195 -195
  40. package/setup/.claude/skills/brainstorming/SKILL.md +5 -5
  41. package/setup/.claude/skills/brainstorming/scripts/server.cjs +723 -723
  42. package/setup/.claude/skills/brainstorming/scripts/start-server.py +245 -245
  43. package/setup/.claude/skills/brainstorming/scripts/stop-server.py +178 -178
  44. package/setup/.claude/skills/brainstorming/visual-companion.md +298 -298
  45. package/setup/.claude/skills/chrome-integration/SKILL.md +66 -66
  46. package/setup/.claude/skills/code-review/SKILL.md +264 -264
  47. package/setup/.claude/skills/executing-plans/SKILL.md +1 -1
  48. package/setup/.claude/skills/gitnexus/gitnexus-cli/SKILL.md +67 -67
  49. package/setup/.claude/skills/gitnexus/gitnexus-debugging/SKILL.md +1 -1
  50. package/setup/.claude/skills/gitnexus/gitnexus-exploring/SKILL.md +1 -1
  51. package/setup/.claude/skills/gitnexus/gitnexus-guide/SKILL.md +1 -1
  52. package/setup/.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md +1 -1
  53. package/setup/.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md +1 -1
  54. package/setup/.claude/skills/methodology/SKILL.md +124 -0
  55. package/setup/.claude/skills/phase/SKILL.md +62 -62
  56. package/setup/.claude/skills/playwright/SKILL.md +85 -85
  57. package/setup/.claude/skills/review/SKILL.md +97 -97
  58. package/setup/.claude/skills/task/SKILL.md +26 -26
  59. package/setup/.claude/skills/test-driven-development/SKILL.md +1 -1
  60. package/setup/.claude/skills/ui-ux-pro-max/SKILL.md +1 -1
  61. package/setup/.claude/skills/verification-before-completion/SKILL.md +1 -1
  62. package/setup/.claude/skills/writing-plans/SKILL.md +1 -1
  63. package/setup/.codex/.agents/skills/archive/SKILL.md +195 -195
  64. package/setup/.codex/.agents/skills/brainstorming/SKILL.md +5 -5
  65. package/setup/.codex/.agents/skills/brainstorming/scripts/server.cjs +723 -723
  66. package/setup/.codex/.agents/skills/brainstorming/scripts/start-server.py +245 -245
  67. package/setup/.codex/.agents/skills/brainstorming/scripts/stop-server.py +178 -178
  68. package/setup/.codex/.agents/skills/brainstorming/visual-companion.md +298 -298
  69. package/setup/.codex/.agents/skills/chrome-integration/SKILL.md +66 -66
  70. package/setup/.codex/.agents/skills/code-review/SKILL.md +264 -264
  71. package/setup/.codex/.agents/skills/executing-plans/SKILL.md +1 -1
  72. package/setup/.codex/.agents/skills/gitnexus/gitnexus-cli/SKILL.md +67 -67
  73. package/setup/.codex/.agents/skills/gitnexus/gitnexus-debugging/SKILL.md +1 -1
  74. package/setup/.codex/.agents/skills/gitnexus/gitnexus-exploring/SKILL.md +1 -1
  75. package/setup/.codex/.agents/skills/gitnexus/gitnexus-guide/SKILL.md +1 -1
  76. package/setup/.codex/.agents/skills/gitnexus/gitnexus-impact-analysis/SKILL.md +1 -1
  77. package/setup/.codex/.agents/skills/gitnexus/gitnexus-refactoring/SKILL.md +1 -1
  78. package/setup/.codex/.agents/skills/methodology/SKILL.md +124 -0
  79. package/setup/.codex/.agents/skills/phase/SKILL.md +62 -62
  80. package/setup/.codex/.agents/skills/playwright/SKILL.md +85 -85
  81. package/setup/.codex/.agents/skills/review/SKILL.md +97 -97
  82. package/setup/.codex/.agents/skills/task/SKILL.md +27 -27
  83. package/setup/.codex/.agents/skills/test-driven-development/SKILL.md +1 -1
  84. package/setup/.codex/.agents/skills/ui-ux-pro-max/SKILL.md +1 -1
  85. package/setup/.codex/.agents/skills/verification-before-completion/SKILL.md +1 -1
  86. package/setup/.codex/.agents/skills/writing-plans/SKILL.md +1 -1
  87. package/setup/.codex/hooks/review-runner.py +851 -851
  88. package/setup/.codex/hooks/setup-keys.py +287 -287
  89. package/setup/AGENTS.md +11 -1
  90. package/setup/CLAUDE.md +11 -1
  91. package/setup/install.sh +24 -24
  92. package/setup/tests/test_decision_timeout.py +241 -241
  93. package/setup/tests/test_hook_guards.py +357 -357
  94. package/setup/tests/test_sdlc_bootstrap.py +167 -167
  95. package/setup/tests/test_sessionlog_switch.py +199 -199
  96. package/setup/tests/test_task_manager.py +148 -148
@@ -1,282 +1,282 @@
1
- #!/usr/bin/env python3
2
- """SDLC cross-model review key setup (cross-platform).
3
-
4
- Auto-discovers providers from ~/.claude/settings.json / settings.local.json /
5
- ~/.codex/config.toml / env ANTHROPIC_*, lists model-catalog.json alternatives,
6
- lets the user complete missing info (key/base_url/model/context), then writes to
7
- BOTH ~/.claude/api-keys.json and ~/.codex/api-keys.json (per-directory, no
8
- cross-use).
9
-
10
- Usage:
11
- python .codex/hooks/setup-keys.py
12
- """
13
- import json
14
- import os
15
- import re
16
- import sys
17
- import urllib.parse
18
- from pathlib import Path
19
-
20
- import flowcraft_env # noqa: F401 — UTF-8 stdio 双保险(R2)
21
-
22
- SCRIPT_DIR = Path(__file__).resolve().parent
23
- if SCRIPT_DIR.name == "hooks":
24
- REPO = SCRIPT_DIR.parent.parent
25
- else:
26
- REPO = SCRIPT_DIR.parent
27
- os.environ.setdefault("SDLC_CATALOG", str(REPO / ".codex" / "model-catalog.json"))
28
-
29
- HOME = os.path.expanduser("~")
30
- CATALOG = os.environ.get("SDLC_CATALOG", "")
31
- CLAUDE_SETTINGS = os.path.join(HOME, ".claude", "settings.json")
32
- CLAUDE_SETTINGS_LOCAL = os.path.join(HOME, ".claude", "settings.local.json")
33
- CODEX_CONFIG = os.path.join(HOME, ".codex", "config.toml")
34
- KEY_CLAUDE = os.path.join(HOME, ".claude", "api-keys.json")
35
- KEY_CODEX = os.path.join(HOME, ".codex", "api-keys.json")
36
-
37
-
38
- def host_of(url):
39
- try:
40
- return urllib.parse.urlparse(url).netloc.lower()
41
- except Exception:
42
- return ""
43
-
44
-
45
- # --- 0) catalog ---
46
- cat = {}
47
- if os.path.exists(CATALOG):
48
- try:
49
- for p in json.load(open(CATALOG, encoding="utf-8")).get("providers", []):
50
- cat[p["id"]] = {
51
- "name": p.get("name", p["id"]),
52
- "base_url": p.get("base_url", ""),
53
- "key_env": p.get("key_env", p["id"].upper() + "_API_KEY"),
54
- "default_model": p.get("default_model", ""),
55
- "default_context": p.get("default_context", ""),
56
- "models": p.get("models", []),
57
- }
58
- except Exception as e:
59
- print("catalog parse failed: %s" % e, file=sys.stderr)
60
-
61
-
62
- def find_cat_id(url):
63
- h = host_of(url)
64
- if not h:
65
- return ""
66
- for k, c in cat.items():
67
- if host_of(c["base_url"]) == h:
68
- return k
69
- return h.split(".")[0]
70
-
71
-
72
- def ctx_for(model, entry):
73
- for m in entry.get("models", []):
74
- if m.get("name") == model:
75
- return str(m.get("context", ""))
76
- return str(entry.get("default_context", ""))
77
-
78
-
79
- def main() -> int:
80
- # --- 1) discovery ---
81
- discovered = [] # (id, name, base_url, model, key, source)
82
-
83
- def add_disc(pid, base, model, key, source):
84
- if not base:
85
- return
86
- name = cat.get(pid, {}).get("name", pid) if pid in cat else pid
87
- discovered.append({
88
- "id": pid, "name": name, "base_url": base,
89
- "model": model or "", "key": key or "", "source": source,
90
- })
91
-
92
- for sf in (CLAUDE_SETTINGS, CLAUDE_SETTINGS_LOCAL):
93
- if not os.path.exists(sf):
94
- continue
95
- try:
96
- j = json.load(open(sf, encoding="utf-8"))
97
- base = j.get("env", {}).get("ANTHROPIC_BASE_URL", "")
98
- if base:
99
- model = (j.get("env", {}).get("ANTHROPIC_MODEL", "") or
100
- j.get("env", {}).get("ANTHROPIC_DEFAULT_SONNET_MODEL", ""))
101
- key = (j.get("env", {}).get("ANTHROPIC_AUTH_TOKEN", "") or
102
- j.get("env", {}).get("ANTHROPIC_API_KEY", ""))
103
- add_disc(find_cat_id(base), base, model, key, sf)
104
- except Exception:
105
- pass
106
-
107
- if os.path.exists(CODEX_CONFIG):
108
- try:
109
- t = open(CODEX_CONFIG, encoding="utf-8").read()
110
- for mb in re.finditer(r"\[model_providers\.([^\]]+)\](.*?)(?=\n\[|\Z)", t, re.S):
111
- pname = mb.group(1).strip()
112
- block = mb.group(2)
113
- b = re.search(r'base_url\s*=\s*"([^"]+)"', block)
114
- if not b:
115
- continue
116
- b = b.group(1)
117
- if "anthropic" not in b:
118
- b = b.rstrip("/") + "/anthropic"
119
- m = re.search(r'^\s*model\s*=\s*"([^"]+)"', t, re.M)
120
- add_disc(find_cat_id(b), b, m.group(1) if m else "", "", CODEX_CONFIG)
121
- except Exception:
122
- pass
123
-
124
- env_base = os.environ.get("ANTHROPIC_BASE_URL", "")
125
- if env_base:
126
- env_model = (os.environ.get("ANTHROPIC_MODEL", "") or
127
- os.environ.get("ANTHROPIC_DEFAULT_SONNET_MODEL", ""))
128
- env_key = (os.environ.get("ANTHROPIC_AUTH_TOKEN", "") or
129
- os.environ.get("ANTHROPIC_API_KEY", ""))
130
- add_disc(find_cat_id(env_base), env_base, env_model, env_key, "env ANTHROPIC_*")
131
-
132
- # dedup by id (first wins: claude settings > codex config > env)
133
- seen = set()
134
- deduped = []
135
- for d in discovered:
136
- if d["id"] and d["id"] not in seen:
137
- seen.add(d["id"])
138
- deduped.append(d)
139
- discovered = deduped
140
-
141
- # --- 2) existing data ---
142
- data = {}
143
- if os.path.exists(KEY_CODEX):
144
- try:
145
- data = json.load(open(KEY_CODEX, encoding="utf-8"))
146
- except Exception:
147
- pass
148
-
149
- # merge discovered into data (fill missing)
150
- for d in discovered:
151
- pid = d["id"]
152
- if not pid:
153
- continue
154
- e = data.setdefault(pid, {})
155
- e.setdefault("name", d["name"])
156
- e.setdefault("base_url", d["base_url"])
157
- e.setdefault("model", d["model"])
158
- e.setdefault("key", d["key"])
159
- if d["model"] and pid in cat:
160
- ctx = ctx_for(d["model"], cat[pid])
161
- if ctx:
162
- e.setdefault("context", ctx)
163
-
164
- print("== 自动发现 ==")
165
- if discovered:
166
- for d in discovered:
167
- print(" [%s] %s base=%s model=%s key=%s source=%s" % (
168
- d["id"], d["name"], d["base_url"], d["model"] or "-",
169
- "已填" if d["key"] else "缺失", d["source"]))
170
- else:
171
- print(" (未发现已配置 provider)")
172
-
173
- # --- 3) catalog options not complete ---
174
- options = []
175
- for k, c in sorted(cat.items()):
176
- if any(d["id"] == k for d in discovered):
177
- continue
178
- e = data.get(k, {})
179
- complete = bool(e.get("key")) and bool(e.get("base_url")) and bool(e.get("model"))
180
- if complete:
181
- continue
182
- options.append((k, c, bool(e)))
183
- if options:
184
- print("== 清单可选项(未发现或信息不全,选中后补缺失项)==")
185
- for i, (k, c, has) in enumerate(options, 1):
186
- st = "已存在(待补)" if has else "未配置"
187
- models = ", ".join(m["name"] + "(" + str(m.get("context", "")) + ")" for m in c.get("models", []))
188
- print(" [%d] %s (%s) %s 默认=%s(%s) key_env=%s [%s]" % (
189
- i, c["name"], k, c["base_url"], c["default_model"],
190
- c["default_context"], c["key_env"], st))
191
- if models:
192
- print(" 可选: %s" % models)
193
- sel = input(" 选择要添加/补全的编号(逗号分隔,回车跳过): ").strip()
194
- for part in sel.split(","):
195
- part = part.strip()
196
- if not part.isdigit():
197
- continue
198
- n = int(part)
199
- if n < 1 or n > len(options):
200
- continue
201
- k, c, _ = options[n - 1]
202
- e = data.setdefault(k, {})
203
- e.setdefault("name", c["name"])
204
- e.setdefault("base_url", c["base_url"])
205
- e.setdefault("model", c["default_model"])
206
- e.setdefault("context", c["default_context"])
207
- if not e.get("key"):
208
- inp = input(" API key(%s,必填): " % c["key_env"]).strip()
209
- if inp:
210
- e["key"] = inp
211
- if not e.get("base_url"):
212
- inp = input(" base_url(Anthropic 兼容,必填): ").strip()
213
- if inp:
214
- e["base_url"] = inp
215
- models = [m["name"] for m in c.get("models", [])]
216
- inp = input(" 模型 [默认 %s;可选: %s;留空用默认]: " % (e.get("model"), ", ".join(models))).strip()
217
- if inp:
218
- e["model"] = inp
219
- ctx = ctx_for(inp, c)
220
- if ctx:
221
- e["context"] = ctx
222
- inp = input(" 上下文大小 [当前 %s,留空保留]: " % e.get("context", "")).strip()
223
- if inp:
224
- e["context"] = inp
225
- else:
226
- print("== 清单中无待配置项 ==")
227
-
228
- # --- 4) custom provider ---
229
- inp = input("添加/更新自定义 provider?(y/n,默认 n): ").strip().lower()
230
- if inp in ("y", "yes"):
231
- pid = input(" provider id(如 mygw): ").strip()
232
- if pid:
233
- e = data.setdefault(pid, {})
234
- e.setdefault("name", input(" 名称: ").strip() or pid)
235
- inp = input(" base_url(Anthropic 兼容)[现有 %s,留空保留]: " % e.get("base_url", "")).strip()
236
- if inp:
237
- e["base_url"] = inp
238
- inp = input(" model [现有 %s,留空保留]: " % e.get("model", "")).strip()
239
- if inp:
240
- e["model"] = inp
241
- inp = input(" 上下文大小 [现有 %s,留空保留]: " % e.get("context", "")).strip()
242
- if inp:
243
- e["context"] = inp
244
- if not e.get("key"):
245
- inp = input(" API key: ").strip()
246
- if inp:
247
- e["key"] = inp
248
-
249
- # --- 5) fill defaults from catalog ---
250
- for k, c in cat.items():
251
- e = data.get(k)
252
- if not e:
253
- continue
254
- e.setdefault("name", c["name"])
255
- e.setdefault("base_url", c["base_url"])
256
- e.setdefault("model", c["default_model"])
257
- e.setdefault("context", c["default_context"])
258
-
259
- # --- 6) write both files ---
260
- os.makedirs(os.path.dirname(KEY_CLAUDE), exist_ok=True)
261
- os.makedirs(os.path.dirname(KEY_CODEX), exist_ok=True)
262
- s = json.dumps(data, ensure_ascii=False, indent=4)
263
- for kf in (KEY_CLAUDE, KEY_CODEX):
264
- with open(kf, "w", encoding="utf-8") as fh:
265
- fh.write(s)
266
- if os.name != "nt":
267
- try:
268
- os.chmod(kf, 0o600)
269
- except Exception:
270
- pass
271
- print("已保存: %s" % KEY_CLAUDE)
272
- print("已保存: %s" % KEY_CODEX)
273
- print("配置摘要:")
274
- for pid, c in sorted(data.items()):
275
- print(" [%s] %s base=%s model=%s context=%s key=%s" % (
276
- pid, c.get("name", ""), c.get("base_url", ""), c.get("model", ""),
277
- c.get("context", ""), "已填" if c.get("key") else "缺失"))
278
- return 0
279
-
280
-
281
- if __name__ == "__main__":
282
- sys.exit(main())
1
+ #!/usr/bin/env python3
2
+ """SDLC cross-model review key setup (cross-platform).
3
+
4
+ Auto-discovers providers from ~/.claude/settings.json / settings.local.json /
5
+ ~/.codex/config.toml / env ANTHROPIC_*, lists model-catalog.json alternatives,
6
+ lets the user complete missing info (key/base_url/model/context), then writes to
7
+ BOTH ~/.claude/api-keys.json and ~/.codex/api-keys.json (per-directory, no
8
+ cross-use).
9
+
10
+ Usage:
11
+ python .codex/hooks/setup-keys.py
12
+ """
13
+ import json
14
+ import os
15
+ import re
16
+ import sys
17
+ import urllib.parse
18
+ from pathlib import Path
19
+
20
+ import flowcraft_env # noqa: F401 — UTF-8 stdio 双保险(R2)
21
+
22
+ SCRIPT_DIR = Path(__file__).resolve().parent
23
+ if SCRIPT_DIR.name == "hooks":
24
+ REPO = SCRIPT_DIR.parent.parent
25
+ else:
26
+ REPO = SCRIPT_DIR.parent
27
+ os.environ.setdefault("SDLC_CATALOG", str(REPO / ".codex" / "model-catalog.json"))
28
+
29
+ HOME = os.path.expanduser("~")
30
+ CATALOG = os.environ.get("SDLC_CATALOG", "")
31
+ CLAUDE_SETTINGS = os.path.join(HOME, ".claude", "settings.json")
32
+ CLAUDE_SETTINGS_LOCAL = os.path.join(HOME, ".claude", "settings.local.json")
33
+ CODEX_CONFIG = os.path.join(HOME, ".codex", "config.toml")
34
+ KEY_CLAUDE = os.path.join(HOME, ".claude", "api-keys.json")
35
+ KEY_CODEX = os.path.join(HOME, ".codex", "api-keys.json")
36
+
37
+
38
+ def host_of(url):
39
+ try:
40
+ return urllib.parse.urlparse(url).netloc.lower()
41
+ except Exception:
42
+ return ""
43
+
44
+
45
+ # --- 0) catalog ---
46
+ cat = {}
47
+ if os.path.exists(CATALOG):
48
+ try:
49
+ for p in json.load(open(CATALOG, encoding="utf-8")).get("providers", []):
50
+ cat[p["id"]] = {
51
+ "name": p.get("name", p["id"]),
52
+ "base_url": p.get("base_url", ""),
53
+ "key_env": p.get("key_env", p["id"].upper() + "_API_KEY"),
54
+ "default_model": p.get("default_model", ""),
55
+ "default_context": p.get("default_context", ""),
56
+ "models": p.get("models", []),
57
+ }
58
+ except Exception as e:
59
+ print("catalog parse failed: %s" % e, file=sys.stderr)
60
+
61
+
62
+ def find_cat_id(url):
63
+ h = host_of(url)
64
+ if not h:
65
+ return ""
66
+ for k, c in cat.items():
67
+ if host_of(c["base_url"]) == h:
68
+ return k
69
+ return h.split(".")[0]
70
+
71
+
72
+ def ctx_for(model, entry):
73
+ for m in entry.get("models", []):
74
+ if m.get("name") == model:
75
+ return str(m.get("context", ""))
76
+ return str(entry.get("default_context", ""))
77
+
78
+
79
+ def main() -> int:
80
+ # --- 1) discovery ---
81
+ discovered = [] # (id, name, base_url, model, key, source)
82
+
83
+ def add_disc(pid, base, model, key, source):
84
+ if not base:
85
+ return
86
+ name = cat.get(pid, {}).get("name", pid) if pid in cat else pid
87
+ discovered.append({
88
+ "id": pid, "name": name, "base_url": base,
89
+ "model": model or "", "key": key or "", "source": source,
90
+ })
91
+
92
+ for sf in (CLAUDE_SETTINGS, CLAUDE_SETTINGS_LOCAL):
93
+ if not os.path.exists(sf):
94
+ continue
95
+ try:
96
+ j = json.load(open(sf, encoding="utf-8"))
97
+ base = j.get("env", {}).get("ANTHROPIC_BASE_URL", "")
98
+ if base:
99
+ model = (j.get("env", {}).get("ANTHROPIC_MODEL", "") or
100
+ j.get("env", {}).get("ANTHROPIC_DEFAULT_SONNET_MODEL", ""))
101
+ key = (j.get("env", {}).get("ANTHROPIC_AUTH_TOKEN", "") or
102
+ j.get("env", {}).get("ANTHROPIC_API_KEY", ""))
103
+ add_disc(find_cat_id(base), base, model, key, sf)
104
+ except Exception:
105
+ pass
106
+
107
+ if os.path.exists(CODEX_CONFIG):
108
+ try:
109
+ t = open(CODEX_CONFIG, encoding="utf-8").read()
110
+ for mb in re.finditer(r"\[model_providers\.([^\]]+)\](.*?)(?=\n\[|\Z)", t, re.S):
111
+ pname = mb.group(1).strip()
112
+ block = mb.group(2)
113
+ b = re.search(r'base_url\s*=\s*"([^"]+)"', block)
114
+ if not b:
115
+ continue
116
+ b = b.group(1)
117
+ if "anthropic" not in b:
118
+ b = b.rstrip("/") + "/anthropic"
119
+ m = re.search(r'^\s*model\s*=\s*"([^"]+)"', t, re.M)
120
+ add_disc(find_cat_id(b), b, m.group(1) if m else "", "", CODEX_CONFIG)
121
+ except Exception:
122
+ pass
123
+
124
+ env_base = os.environ.get("ANTHROPIC_BASE_URL", "")
125
+ if env_base:
126
+ env_model = (os.environ.get("ANTHROPIC_MODEL", "") or
127
+ os.environ.get("ANTHROPIC_DEFAULT_SONNET_MODEL", ""))
128
+ env_key = (os.environ.get("ANTHROPIC_AUTH_TOKEN", "") or
129
+ os.environ.get("ANTHROPIC_API_KEY", ""))
130
+ add_disc(find_cat_id(env_base), env_base, env_model, env_key, "env ANTHROPIC_*")
131
+
132
+ # dedup by id (first wins: claude settings > codex config > env)
133
+ seen = set()
134
+ deduped = []
135
+ for d in discovered:
136
+ if d["id"] and d["id"] not in seen:
137
+ seen.add(d["id"])
138
+ deduped.append(d)
139
+ discovered = deduped
140
+
141
+ # --- 2) existing data ---
142
+ data = {}
143
+ if os.path.exists(KEY_CODEX):
144
+ try:
145
+ data = json.load(open(KEY_CODEX, encoding="utf-8"))
146
+ except Exception:
147
+ pass
148
+
149
+ # merge discovered into data (fill missing)
150
+ for d in discovered:
151
+ pid = d["id"]
152
+ if not pid:
153
+ continue
154
+ e = data.setdefault(pid, {})
155
+ e.setdefault("name", d["name"])
156
+ e.setdefault("base_url", d["base_url"])
157
+ e.setdefault("model", d["model"])
158
+ e.setdefault("key", d["key"])
159
+ if d["model"] and pid in cat:
160
+ ctx = ctx_for(d["model"], cat[pid])
161
+ if ctx:
162
+ e.setdefault("context", ctx)
163
+
164
+ print("== 自动发现 ==")
165
+ if discovered:
166
+ for d in discovered:
167
+ print(" [%s] %s base=%s model=%s key=%s source=%s" % (
168
+ d["id"], d["name"], d["base_url"], d["model"] or "-",
169
+ "已填" if d["key"] else "缺失", d["source"]))
170
+ else:
171
+ print(" (未发现已配置 provider)")
172
+
173
+ # --- 3) catalog options not complete ---
174
+ options = []
175
+ for k, c in sorted(cat.items()):
176
+ if any(d["id"] == k for d in discovered):
177
+ continue
178
+ e = data.get(k, {})
179
+ complete = bool(e.get("key")) and bool(e.get("base_url")) and bool(e.get("model"))
180
+ if complete:
181
+ continue
182
+ options.append((k, c, bool(e)))
183
+ if options:
184
+ print("== 清单可选项(未发现或信息不全,选中后补缺失项)==")
185
+ for i, (k, c, has) in enumerate(options, 1):
186
+ st = "已存在(待补)" if has else "未配置"
187
+ models = ", ".join(m["name"] + "(" + str(m.get("context", "")) + ")" for m in c.get("models", []))
188
+ print(" [%d] %s (%s) %s 默认=%s(%s) key_env=%s [%s]" % (
189
+ i, c["name"], k, c["base_url"], c["default_model"],
190
+ c["default_context"], c["key_env"], st))
191
+ if models:
192
+ print(" 可选: %s" % models)
193
+ sel = input(" 选择要添加/补全的编号(逗号分隔,回车跳过): ").strip()
194
+ for part in sel.split(","):
195
+ part = part.strip()
196
+ if not part.isdigit():
197
+ continue
198
+ n = int(part)
199
+ if n < 1 or n > len(options):
200
+ continue
201
+ k, c, _ = options[n - 1]
202
+ e = data.setdefault(k, {})
203
+ e.setdefault("name", c["name"])
204
+ e.setdefault("base_url", c["base_url"])
205
+ e.setdefault("model", c["default_model"])
206
+ e.setdefault("context", c["default_context"])
207
+ if not e.get("key"):
208
+ inp = input(" API key(%s,必填): " % c["key_env"]).strip()
209
+ if inp:
210
+ e["key"] = inp
211
+ if not e.get("base_url"):
212
+ inp = input(" base_url(Anthropic 兼容,必填): ").strip()
213
+ if inp:
214
+ e["base_url"] = inp
215
+ models = [m["name"] for m in c.get("models", [])]
216
+ inp = input(" 模型 [默认 %s;可选: %s;留空用默认]: " % (e.get("model"), ", ".join(models))).strip()
217
+ if inp:
218
+ e["model"] = inp
219
+ ctx = ctx_for(inp, c)
220
+ if ctx:
221
+ e["context"] = ctx
222
+ inp = input(" 上下文大小 [当前 %s,留空保留]: " % e.get("context", "")).strip()
223
+ if inp:
224
+ e["context"] = inp
225
+ else:
226
+ print("== 清单中无待配置项 ==")
227
+
228
+ # --- 4) custom provider ---
229
+ inp = input("添加/更新自定义 provider?(y/n,默认 n): ").strip().lower()
230
+ if inp in ("y", "yes"):
231
+ pid = input(" provider id(如 mygw): ").strip()
232
+ if pid:
233
+ e = data.setdefault(pid, {})
234
+ e.setdefault("name", input(" 名称: ").strip() or pid)
235
+ inp = input(" base_url(Anthropic 兼容)[现有 %s,留空保留]: " % e.get("base_url", "")).strip()
236
+ if inp:
237
+ e["base_url"] = inp
238
+ inp = input(" model [现有 %s,留空保留]: " % e.get("model", "")).strip()
239
+ if inp:
240
+ e["model"] = inp
241
+ inp = input(" 上下文大小 [现有 %s,留空保留]: " % e.get("context", "")).strip()
242
+ if inp:
243
+ e["context"] = inp
244
+ if not e.get("key"):
245
+ inp = input(" API key: ").strip()
246
+ if inp:
247
+ e["key"] = inp
248
+
249
+ # --- 5) fill defaults from catalog ---
250
+ for k, c in cat.items():
251
+ e = data.get(k)
252
+ if not e:
253
+ continue
254
+ e.setdefault("name", c["name"])
255
+ e.setdefault("base_url", c["base_url"])
256
+ e.setdefault("model", c["default_model"])
257
+ e.setdefault("context", c["default_context"])
258
+
259
+ # --- 6) write both files ---
260
+ os.makedirs(os.path.dirname(KEY_CLAUDE), exist_ok=True)
261
+ os.makedirs(os.path.dirname(KEY_CODEX), exist_ok=True)
262
+ s = json.dumps(data, ensure_ascii=False, indent=4)
263
+ for kf in (KEY_CLAUDE, KEY_CODEX):
264
+ with open(kf, "w", encoding="utf-8") as fh:
265
+ fh.write(s)
266
+ if os.name != "nt":
267
+ try:
268
+ os.chmod(kf, 0o600)
269
+ except Exception:
270
+ pass
271
+ print("已保存: %s" % KEY_CLAUDE)
272
+ print("已保存: %s" % KEY_CODEX)
273
+ print("配置摘要:")
274
+ for pid, c in sorted(data.items()):
275
+ print(" [%s] %s base=%s model=%s context=%s key=%s" % (
276
+ pid, c.get("name", ""), c.get("base_url", ""), c.get("model", ""),
277
+ c.get("context", ""), "已填" if c.get("key") else "缺失"))
278
+ return 0
279
+
280
+
281
+ if __name__ == "__main__":
282
+ sys.exit(main())