@tscgoods/claude-code-effort-discovery 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,6 +29,29 @@ Claude Code 2.1.x 里 effort 是 `low / medium / high / xhigh / max`(客户端
29
29
 
30
30
  没配置也能用:插件会退回读 `~/.claude/settings.json` 的 `env.ANTHROPIC_BASE_URL` / `ANTHROPIC_AUTH_TOKEN` 和 `modelPicker.options` 里的模型别名。
31
31
 
32
+ ## 网关别名映射(重要)
33
+
34
+ Claude 的网关别名(如 `ccs-claude-newapi--deepseek-v4.1-flash-1017[1m]`)通常**不校验** `output_config.effort`——传 `bogus` 也返回 200。这时插件只能诚实报 `no-validation`,不会凭空写档位。
35
+
36
+ 如果你在**另一个 OpenAI 兼容网关**上已经探测到同一模型的真实档位,可以在共享配置里建立别名映射,让会话启动时注入真相:
37
+
38
+ ```jsonc
39
+ // ~/.config/effort-discovery.json
40
+ {
41
+ "aliases": {
42
+ "ccs-claude-newapi--deepseek-v4.1-flash-1017[1m]": "deepseek-v4.1-flash-1017"
43
+ }
44
+ }
45
+ ```
46
+
47
+ 插件会读 `~/.cache/effort-discovery/` 下所有缓存(`cache.json` / `dsh.json` / `claude-code.json`),按别名找到实测档位,在 SessionStart 注入:
48
+
49
+ ```
50
+ ⚠ 不要选 medium / xhigh:Claude 的选择器仍会显示它们,但网关实测不支持/会忽略。
51
+ ```
52
+
53
+ **注意**:Claude Code 只有 `maxEffortLevel`(上限封顶)一个杠杆,没法隐藏中间档位;这个方案是"注入提醒",不改选择器。
54
+
32
55
  ## 安装
33
56
 
34
57
  开发期(就地加载,改完 `/reload-plugins` 生效):
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tscgoods/claude-code-effort-discovery",
3
- "version": "0.3.1",
3
+ "version": "0.4.1",
4
4
  "description": "Claude Code plugin: discover which reasoning-effort levels your gateway model accepts, report them, and cap /effort to them.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/scripts/lib.mjs CHANGED
@@ -29,6 +29,57 @@ export function claudeSettingsPath() {
29
29
  return join(process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude"), "settings.json")
30
30
  }
31
31
 
32
+ export const CLAUDE_LEVELS = ["low", "medium", "high", "xhigh", "max"]
33
+
34
+ /** 网关别名 → 真实模型 id 的映射(在 ~/.config/effort-discovery.json 的 aliases 里) */
35
+ export function loadAliases() {
36
+ const config = loadConfig()
37
+ const aliases = config.aliases
38
+ return aliases && typeof aliases === "object" && !Array.isArray(aliases) ? aliases : {}
39
+ }
40
+
41
+ /** 在所有缓存里查找某个模型的实测档位;优先有 levels 的证据 */
42
+ export function findProbe(modelID, aliases = {}) {
43
+ const canonical = aliases[modelID] ?? modelID
44
+ const dir = cacheDir()
45
+ const candidates = []
46
+
47
+ for (const file of ["cache.json", "dsh.json", "claude-code.json"]) {
48
+ const json = readJson(join(dir, file))
49
+ if (!json || typeof json === "object" && (json.owner || json.byProvider)) continue
50
+ const entries = json.models ?? json
51
+ if (!entries || typeof entries !== "object") continue
52
+ for (const [key, value] of Object.entries(entries)) {
53
+ if (!value || typeof value !== "object" || !("levels" in value)) continue
54
+ const match =
55
+ key === modelID ||
56
+ key === canonical ||
57
+ key.endsWith(`/${modelID}`) ||
58
+ key.endsWith(`/${canonical}`)
59
+ if (match) {
60
+ candidates.push({
61
+ from: key,
62
+ file,
63
+ source: value.source ?? "unknown",
64
+ levels: value.levels ?? null,
65
+ at: value.at ?? 0,
66
+ })
67
+ }
68
+ }
69
+ }
70
+
71
+ candidates.sort(
72
+ (a, b) => (b.levels?.length ?? 0) - (a.levels?.length ?? 0) || b.at - a.at,
73
+ )
74
+ return candidates[0]
75
+ }
76
+
77
+ /** 给出"实测支持"之外的 Claude 档位(即不该选的) */
78
+ export function unsupportedClaudeLevels(levels) {
79
+ if (!Array.isArray(levels) || levels.length === 0) return []
80
+ return CLAUDE_LEVELS.filter((level) => !levels.includes(level))
81
+ }
82
+
32
83
  export function readJson(path) {
33
84
  try {
34
85
  return JSON.parse(readFileSync(path, "utf8"))
@@ -94,8 +145,9 @@ export function normalizeBaseURL(input) {
94
145
  }
95
146
 
96
147
  /**
97
- * 用 output_config.effort 从高到低试探;2xx 视为该档位可用(并假定更低档位可用)。
98
- * @returns {Promise<{levels: string[] | null, source: string, at: number}>}
148
+ * Anthropic Messages 协议档位探测:
149
+ * 先用非法档位判断网关是否真的校验;不校验就返回 no-validation,
150
+ * 绝不把“2xx”误当成“支持全部档位”。
99
151
  */
100
152
  export async function probeAnthropic({ baseURL, apiKey, model, headers = {}, ladder = ANTHROPIC_LADDER, timeoutMs = 30_000 }) {
101
153
  const base = normalizeBaseURL(baseURL)
@@ -104,8 +156,7 @@ export async function probeAnthropic({ baseURL, apiKey, model, headers = {}, lad
104
156
  let withBeta = true
105
157
  let unknown = false
106
158
 
107
- for (let index = 0; index < ladder.length; index++) {
108
- const level = ladder[index]
159
+ const send = async (level) => {
109
160
  const head = {
110
161
  "Content-Type": "application/json",
111
162
  "anthropic-version": "2023-06-01",
@@ -116,10 +167,8 @@ export async function probeAnthropic({ baseURL, apiKey, model, headers = {}, lad
116
167
  head.Authorization = `Bearer ${apiKey}`
117
168
  head["x-api-key"] = apiKey
118
169
  }
119
-
120
- let response
121
170
  try {
122
- response = await fetch(url, {
171
+ const response = await fetch(url, {
123
172
  method: "POST",
124
173
  headers: head,
125
174
  body: JSON.stringify({
@@ -130,32 +179,63 @@ export async function probeAnthropic({ baseURL, apiKey, model, headers = {}, lad
130
179
  }),
131
180
  signal: AbortSignal.timeout(timeoutMs),
132
181
  })
182
+ return { status: response.status, text: await response.text() }
133
183
  } catch {
184
+ return undefined
185
+ }
186
+ }
187
+
188
+ const fatal = (r) =>
189
+ r && [401, 403, 429].includes(r.status)
190
+ ? { levels: null, source: `http-${r.status}`, at: Date.now() }
191
+ : undefined
192
+
193
+ // 1) sentinel
194
+ const sentinel = await send("effort-discovery-probe")
195
+ const fatalSentinel = fatal(sentinel)
196
+ if (fatalSentinel) return fatalSentinel
197
+ if (sentinel) {
198
+ if (sentinel.status >= 200 && sentinel.status < 300) {
199
+ return { levels: null, source: "no-validation", at: Date.now() }
200
+ }
201
+ const listed = parseLevels(sentinel.text)
202
+ if (listed) return { levels: listed, source: "validated", at: Date.now() }
203
+ if (
204
+ sentinel.status === 400 &&
205
+ /effort-2025-11-24|anthropic-beta/i.test(sentinel.text) &&
206
+ !/output_config|does not support|unsupported|invalid value/i.test(sentinel.text)
207
+ ) {
208
+ withBeta = false
209
+ }
210
+ }
211
+
212
+ // 2) ladder
213
+ for (let index = 0; index < ladder.length; index++) {
214
+ const result = await send(ladder[index])
215
+ const fatalResult = fatal(result)
216
+ if (fatalResult) return fatalResult
217
+ if (!result) {
134
218
  unknown = true
135
219
  continue
136
220
  }
221
+ if (result.status >= 200 && result.status < 300) {
222
+ return { levels: ladder.slice(index), source: "validated", at: Date.now() }
223
+ }
137
224
 
138
- if (response.ok) return { levels: ladder.slice(index), source: "validated", at: Date.now() }
139
-
140
- const text = await response.text()
141
- const mentionsBeta = /effort-2025-11-24|anthropic-beta/i.test(text)
142
- const mentionsEffort = /output_config|effort|does not support/i.test(text)
225
+ const mentionsBeta = /effort-2025-11-24|anthropic-beta/i.test(result.text)
226
+ const mentionsEffort = /output_config|does not support|unsupported|invalid value/i.test(result.text)
143
227
 
144
- if (response.status === 400 && mentionsBeta && !mentionsEffort && withBeta) {
228
+ if (result.status === 400 && mentionsBeta && !mentionsEffort && withBeta) {
145
229
  withBeta = false
146
230
  index--
147
231
  continue
148
232
  }
149
-
150
- if (response.status === 400 || response.status === 422) {
233
+ if (result.status === 400 || result.status === 422) {
234
+ const listed = parseLevels(result.text)
235
+ if (listed) return { levels: listed, source: "validated", at: Date.now() }
151
236
  if (!mentionsEffort && !mentionsBeta) unknown = true
152
237
  continue
153
238
  }
154
-
155
- if (response.status === 401 || response.status === 403 || response.status === 429) {
156
- return { levels: null, source: `http-${response.status}`, at: Date.now() }
157
- }
158
-
159
239
  unknown = true
160
240
  }
161
241
 
package/scripts/probe.mjs CHANGED
@@ -1,7 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
+ CLAUDE_LEVELS,
3
4
  cachePath,
4
5
  claudeGateway,
6
+ findProbe,
7
+ loadAliases,
5
8
  loadConfig,
6
9
  normalizeBaseURL,
7
10
  probeAnthropic,
@@ -64,6 +67,7 @@ if (models.length === 0) {
64
67
  }
65
68
 
66
69
  const result = { at: Date.now(), provider: providerID, baseURL, models: {} }
70
+ const aliases = loadAliases()
67
71
  for (const model of models) {
68
72
  const probed = await probeAnthropic({
69
73
  baseURL,
@@ -71,7 +75,17 @@ for (const model of models) {
71
75
  model,
72
76
  headers: typeof entry?.headers === "object" && entry.headers ? entry.headers : {},
73
77
  })
74
- result.models[model] = probed
78
+ const authoritative = findProbe(model, aliases)
79
+ result.models[model] = {
80
+ ...probed,
81
+ alias: aliases[model] ?? null,
82
+ authoritativeLevels: authoritative?.levels ?? null,
83
+ authoritativeFrom: authoritative?.from ?? null,
84
+ unsupportedInClaude:
85
+ probed.levels?.length > 0
86
+ ? CLAUDE_LEVELS.filter((level) => !probed.levels.includes(level))
87
+ : null,
88
+ }
75
89
  await new Promise((resolve) => setTimeout(resolve, 200))
76
90
  }
77
91
  writeJson(cachePath(), result)
@@ -1,47 +1,72 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFileSync } from "node:fs"
3
- import { cachePath, readJson } from "./lib.mjs"
3
+ import {
4
+ CLAUDE_LEVELS,
5
+ cachePath,
6
+ findProbe,
7
+ loadAliases,
8
+ readJson,
9
+ unsupportedClaudeLevels,
10
+ } from "./lib.mjs"
4
11
 
5
- // SessionStart / PostModelSwitch hook: 只读缓存,不联网、不改文件
12
+ // SessionStart / PostModelSwitch hook:只读缓存,不联网、不改配置
6
13
  let input = {}
7
14
  try {
8
15
  const raw = readFileSync(0, "utf8")
9
16
  if (raw.trim().length > 0) input = JSON.parse(raw)
10
17
  } catch {}
11
18
 
12
- const cache = readJson(cachePath())
13
- if (!cache || !cache.models) process.exit(0)
14
-
15
- const currentModel =
16
- input?.model?.id ?? input?.to_model ?? input?.model_id ?? input?.requested_model ?? undefined
19
+ const aliases = loadAliases()
20
+ const modelName = input?.model?.id ?? input?.to_model ?? input?.model_id ?? input?.requested_model ?? ""
21
+ const probe = modelName ? findProbe(modelName, aliases) : undefined
17
22
 
18
- const entries = Object.entries(cache.models).filter(([, info]) => Array.isArray(info.levels))
19
- if (entries.length === 0) process.exit(0)
23
+ const lines = []
20
24
 
21
- const describe = ([model, info]) => `${model}: ${info.levels.join(" / ")} (${info.source})`
22
- const current = currentModel
23
- ? entries.find(([model]) => model === currentModel || currentModel.includes(model))
24
- : undefined
25
+ if (probe?.levels?.length) {
26
+ const supported = probe.levels.filter((level) => CLAUDE_LEVELS.includes(level))
27
+ const unsupported = unsupportedClaudeLevels(probe.levels)
28
+ const canonical = aliases[modelName]
29
+ lines.push(
30
+ `${modelName} 的网关实测档位: ${probe.levels.join(" / ")}(证据: ${probe.source}, ${probe.from})`,
31
+ )
32
+ if (canonical) lines.push(`网关别名映射: ${modelName} → ${canonical}`)
33
+ if (unsupported.length > 0) {
34
+ lines.push(
35
+ `⚠ 不要选 ${unsupported.join(" / ")}:Claude 的选择器仍会显示它们,但网关实测不支持/会忽略。`,
36
+ )
37
+ } else {
38
+ lines.push("实测档位覆盖 Claude 的全部选项,可以放心选择。")
39
+ }
40
+ } else {
41
+ // 没有证据:明确说明,而不是编造
42
+ lines.push(
43
+ `${modelName || "当前模型"}: 网关未给出可信的 effort 声明(no-validation),插件不改写档位。`,
44
+ )
45
+ if (probe) lines.push(`最近一次探测: ${probe.source}(${probe.from})`)
46
+ if (modelName && !aliases[modelName]) {
47
+ lines.push("提示: 可在 ~/.config/effort-discovery.json 的 aliases 里把该别名映射到真实模型 id。")
48
+ }
49
+ }
25
50
 
26
- const lines = current
27
- ? [`当前模型支持: ${describe(current)}`, `其他模型: ${entries.filter(([m]) => m !== current[0]).map(describe).join("; ") || "无"}`]
28
- : entries.map(describe)
29
-
30
- const summary = lines.join("\n").slice(0, 9000)
31
- const age = Math.round((Date.now() - (cache.at ?? Date.now())) / 60000)
51
+ const cache = readJson(cachePath())
52
+ if (cache?.models) {
53
+ const others = Object.entries(cache.models)
54
+ .filter(([model]) => model !== modelName)
55
+ .map(([model, info]) => `${model}: ${(info.levels ?? []).join(" ") || "unknown"}`)
56
+ if (others.length > 0) lines.push(`其他模型缓存: ${others.join("; ")}`)
57
+ }
32
58
 
59
+ const age = probe?.at ? Math.round((Date.now() - probe.at) / 60000) : null
33
60
  const message =
34
- `effort-discovery: ${current ? `${current[0]} 支持 ${(current[1].levels ?? []).join(", ")}` : "已缓存模型档位"}` +
35
- `(${age} 分钟前探测;/effort-discovery:probe-effort 可刷新)`
61
+ `effort-discovery${age !== null ? `(${age} 分钟前探测)` : ""}:\n${lines.join("\n")}\n` +
62
+ `刷新请运行 /effort-discovery:probe-effort。`
36
63
 
37
64
  process.stdout.write(
38
65
  JSON.stringify({
39
- systemMessage: message,
66
+ systemMessage: message.slice(0, 1000),
40
67
  hookSpecificOutput: {
41
68
  hookEventName: input?.hook_event_name ?? "SessionStart",
42
- additionalContext:
43
- `网关的 reasoning effort 探测结果(缓存 ${age} 分钟前):\n${summary}\n` +
44
- `选择档位时只使用列出的级别;未列出的级别会被网关拒绝或忽略。`,
69
+ additionalContext: `网关 effort 实测结果:\n${lines.join("\n")}`,
45
70
  },
46
71
  }) + "\n",
47
72
  )