@namzu/anthropic 2.0.1 → 3.0.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.
@@ -0,0 +1,237 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import {
4
+ findDraft07Only,
5
+ findStrictSchemaViolations,
6
+ getBuiltinTools,
7
+ renderToolSchema,
8
+ toSchemaDialect,
9
+ } from '@namzu/sdk'
10
+
11
+ /**
12
+ * The test that would have caught both outages.
13
+ *
14
+ * Every other test in this repo renders a schema and asserts something about
15
+ * the object. Both production breakages were schemas that looked fine as
16
+ * objects and were rejected by the wire:
17
+ *
18
+ * - `edit.insertLine` used `oneOf`, which strict tool use refuses.
19
+ * - `read.readRange` is a Zod tuple, which renders draft-07 `items: [a, b]`
20
+ * while this wire requires draft 2020-12 — rejected with `strict` unset,
21
+ * so a guard scoped to strict never saw it.
22
+ *
23
+ * Neither could fail offline, because neither was wrong offline. So this one
24
+ * talks to the real API.
25
+ *
26
+ * It asks the cheapest question that still exercises schema validation:
27
+ * `max_tokens: 1` and a one-word prompt. Validation happens before generation,
28
+ * so a rejected schema costs nothing and an accepted one costs a single token.
29
+ *
30
+ * Skipped without a key, so CI stays green where none is configured. Run it
31
+ * with:
32
+ *
33
+ * ANTHROPIC_API_KEY=… pnpm --filter @namzu/anthropic test
34
+ */
35
+
36
+ const KEY = process.env.ANTHROPIC_API_KEY
37
+ const MODEL = process.env.NAMZU_WIRE_TEST_MODEL ?? 'claude-haiku-4-5'
38
+
39
+ interface WireResult {
40
+ readonly ok: boolean
41
+ readonly status: number
42
+ readonly message: string
43
+ }
44
+
45
+ async function offerTools(tools: unknown[]): Promise<WireResult> {
46
+ const res = await fetch('https://api.anthropic.com/v1/messages', {
47
+ method: 'POST',
48
+ headers: {
49
+ 'x-api-key': KEY as string,
50
+ 'anthropic-version': '2023-06-01',
51
+ 'content-type': 'application/json',
52
+ },
53
+ body: JSON.stringify({
54
+ model: MODEL,
55
+ max_tokens: 1,
56
+ messages: [{ role: 'user', content: 'hi' }],
57
+ tools,
58
+ }),
59
+ })
60
+ const body: unknown = await res.json().catch(() => ({}))
61
+ const message =
62
+ (body as { error?: { message?: string } } | null)?.error?.message ?? (res.ok ? '' : 'unknown')
63
+ return { ok: res.ok, status: res.status, message }
64
+ }
65
+
66
+ /** A tool as this driver would put it on the wire. */
67
+ function wireTool(name: string, schema: Record<string, unknown>, strict: boolean): unknown {
68
+ return {
69
+ name,
70
+ description: 'contract probe',
71
+ input_schema: toSchemaDialect(schema, '2020-12'),
72
+ ...(strict ? { strict: true } : {}),
73
+ }
74
+ }
75
+
76
+ describe.skipIf(!KEY)('every shipped tool is expressible on this wire', () => {
77
+ const tools = getBuiltinTools()
78
+
79
+ it('offers all of them in one request, the way a real run does', async () => {
80
+ // One request with the whole toolset, because that is the shape that
81
+ // broke: the wire rejects the WHOLE request for one bad schema, so a
82
+ // per-tool loop would pass while a real run still died.
83
+ const payload = tools.map((t) =>
84
+ wireTool(
85
+ t.name,
86
+ (t.modelInputSchema as Record<string, unknown> | undefined) ??
87
+ renderToolSchema(t.inputSchema),
88
+ Boolean(t.enforceModelInput),
89
+ ),
90
+ )
91
+
92
+ const result = await offerTools(payload)
93
+ expect(result.ok, `HTTP ${result.status}: ${result.message}`).toBe(true)
94
+ }, 180_000)
95
+
96
+ it.each(tools.map((t) => [t.name, t] as const))(
97
+ '%s alone',
98
+ async (name, tool) => {
99
+ // And individually, so a failure names the tool instead of the batch.
100
+ const schema =
101
+ (tool.modelInputSchema as Record<string, unknown> | undefined) ??
102
+ renderToolSchema(tool.inputSchema)
103
+ const result = await offerTools([wireTool(name, schema, Boolean(tool.enforceModelInput))])
104
+ expect(result.ok, `HTTP ${result.status}: ${result.message}`).toBe(true)
105
+ },
106
+ 180_000,
107
+ )
108
+ })
109
+
110
+ describe.skipIf(!KEY)('the dialect conversion is what makes the difference', () => {
111
+ it('rejects the draft-07 tuple and accepts the converted one', async () => {
112
+ // Pins the actual mechanism rather than trusting that conversion helped.
113
+ // If the wire ever starts accepting draft-07 tuples this test says so,
114
+ // and if it ever stops accepting `prefixItems` it says that too.
115
+ const draft07 = {
116
+ type: 'object',
117
+ properties: {
118
+ range: {
119
+ type: 'array',
120
+ minItems: 2,
121
+ maxItems: 2,
122
+ items: [{ type: 'integer' }, { type: 'integer' }],
123
+ },
124
+ },
125
+ }
126
+
127
+ const before = await offerTools([{ name: 'probe', description: 'p', input_schema: draft07 }])
128
+ expect(before.ok).toBe(false)
129
+ expect(before.message).toMatch(/2020-12/)
130
+
131
+ const after = await offerTools([
132
+ { name: 'probe', description: 'p', input_schema: toSchemaDialect(draft07, '2020-12') },
133
+ ])
134
+ expect(after.ok, `HTTP ${after.status}: ${after.message}`).toBe(true)
135
+ }, 180_000)
136
+ })
137
+
138
+ /**
139
+ * The strict subset, measured rather than read.
140
+ *
141
+ * `findStrictSchemaViolations` carries a deny-list, and the first version of it
142
+ * was derived from prose. It was wrong in both directions: it refused
143
+ * `minLength`/`maxLength`, which this wire accepts, so it would have blocked
144
+ * working tools; and it permitted `prefixItems`, which this wire rejects, so it
145
+ * would have vouched for a broken one. A deny-list nobody probed is a guess in
146
+ * a confident tone.
147
+ *
148
+ * This block is where the list comes from. Each row is one request; a row that
149
+ * changes means the subset moved, and the deny-list has to move with it.
150
+ */
151
+ const STRICT_SUBSET: readonly (readonly [string, Record<string, unknown>, boolean])[] = [
152
+ ['minLength/maxLength', { type: 'string', minLength: 1, maxLength: 9 }, true],
153
+ ['pattern', { type: 'string', pattern: '^a+$' }, true],
154
+ ['format', { type: 'string', format: 'uri' }, true],
155
+ ['enum', { type: 'string', enum: ['a', 'b'] }, true],
156
+ ['anyOf', { anyOf: [{ type: 'integer' }, { const: 'end' }] }, true],
157
+ // `minItems` is a bound on the VALUE, not a rejected keyword: 0 and 1 pass,
158
+ // anything above does not. A blanket denial would refuse the ordinary
159
+ // spelling of a non-empty array.
160
+ ['minItems: 0', { type: 'array', items: { type: 'string' }, minItems: 0 }, true],
161
+ ['minItems: 1', { type: 'array', items: { type: 'string' }, minItems: 1 }, true],
162
+ ['minItems: 2', { type: 'array', items: { type: 'string' }, minItems: 2 }, false],
163
+ ['maxItems', { type: 'array', items: { type: 'string' }, maxItems: 3 }, false],
164
+ ['uniqueItems', { type: 'array', items: { type: 'string' }, uniqueItems: true }, false],
165
+ ['minimum', { type: 'integer', minimum: 0 }, false],
166
+ ['oneOf', { oneOf: [{ type: 'integer' }, { const: 'end' }] }, false],
167
+ ['not', { not: { type: 'null' } }, false],
168
+ // The one that interacts with the dialect fix: a tuple is unexpressible
169
+ // under strict in EITHER spelling, so converting it only changes the error.
170
+ ['prefixItems', { type: 'array', prefixItems: [{ type: 'integer' }] }, false],
171
+ ]
172
+
173
+ describe.skipIf(!KEY)('the strict subset is what the deny-list says it is', () => {
174
+ it.each(STRICT_SUBSET.map(([label, schema, accepted]) => [label, schema, accepted] as const))(
175
+ 'strict + %s',
176
+ async (label, propSchema, accepted) => {
177
+ const result = await offerTools([
178
+ {
179
+ name: 'probe',
180
+ description: 'p',
181
+ strict: true,
182
+ input_schema: {
183
+ type: 'object',
184
+ properties: { f: propSchema },
185
+ required: ['f'],
186
+ additionalProperties: false,
187
+ },
188
+ },
189
+ ])
190
+ expect(result.ok, `${label}: HTTP ${result.status}: ${result.message}`).toBe(accepted)
191
+
192
+ // And the offline check has to agree with the wire, which is the
193
+ // whole point of pinning both in one place.
194
+ expect(findStrictSchemaViolations({ properties: { f: propSchema } }).length === 0).toBe(
195
+ accepted,
196
+ )
197
+ },
198
+ 180_000,
199
+ )
200
+
201
+ it('rejects the draft-07 tuple before it ever gets to the strict question', async () => {
202
+ // Dialect first, subset second. This is why a guard scoped to strict
203
+ // could not have caught `read.readRange`: the tuple is refused with
204
+ // `strict` unset too.
205
+ const tuple = {
206
+ type: 'object',
207
+ properties: { f: { type: 'array', items: [{ type: 'integer' }, { type: 'integer' }] } },
208
+ }
209
+ const result = await offerTools([{ name: 'probe', description: 'p', input_schema: tuple }])
210
+
211
+ expect(result.ok).toBe(false)
212
+ expect(result.message).toMatch(/2020-12/)
213
+ }, 180_000)
214
+ })
215
+
216
+ describe('what can be checked without a key', () => {
217
+ it('leaves no draft-07-only construct in any shipped tool', () => {
218
+ // The offline half of the same guarantee, so a contributor without a
219
+ // key still gets the signal — just not the proof.
220
+ for (const tool of getBuiltinTools()) {
221
+ const schema =
222
+ (tool.modelInputSchema as Record<string, unknown> | undefined) ??
223
+ renderToolSchema(tool.inputSchema)
224
+ const converted = toSchemaDialect(schema, '2020-12')
225
+ expect(findDraft07Only(converted), tool.name).toEqual([])
226
+ }
227
+ })
228
+
229
+ it('still finds one before conversion, so the sweep is not vacuous', () => {
230
+ // `read` renders a Zod tuple. If this ever stops finding anything, the
231
+ // test above has quietly become a tautology.
232
+ const withTuple = getBuiltinTools().filter(
233
+ (t) => !t.modelInputSchema && findDraft07Only(renderToolSchema(t.inputSchema)).length > 0,
234
+ )
235
+ expect(withTuple.map((t) => t.name)).toContain('read')
236
+ })
237
+ })
package/src/client.ts CHANGED
@@ -20,6 +20,7 @@ import {
20
20
  isProviderRequestError,
21
21
  modelVersionAtLeast,
22
22
  providerVendorError,
23
+ toSchemaDialect,
23
24
  toolResultToText,
24
25
  } from '@namzu/sdk'
25
26
  import {
@@ -375,7 +376,16 @@ function toAnthropicTools(
375
376
  return {
376
377
  name: t.function.name,
377
378
  description: t.function.description ?? '',
378
- input_schema: t.function.parameters ?? { type: 'object' },
379
+ // This wire parses draft 2020-12, and the renderer emits draft-07.
380
+ // The two disagree about tuples — draft-07 puts the positional
381
+ // schemas in `items`, 2020-12 in `prefixItems` — and the wire
382
+ // rejects the WHOLE request for it, not the one field. Converting
383
+ // here rather than in the renderer keeps the dialect where the
384
+ // knowledge is: only this file knows which wire it is talking to.
385
+ input_schema: toSchemaDialect(
386
+ (t.function.parameters as Record<string, unknown> | undefined) ?? { type: 'object' },
387
+ '2020-12',
388
+ ),
379
389
  ...(strict ? { strict: true } : {}),
380
390
  }
381
391
  })
@@ -57,6 +57,21 @@ export interface ThinkingCapability {
57
57
  readonly canDisable: boolean
58
58
  /** Which `effort` levels this model accepts; empty means none. */
59
59
  readonly effort: EffortLevels
60
+ /**
61
+ * The levels still accepted when thinking is switched off.
62
+ *
63
+ * Usually the same set. The Opus 5 family is the exception: it refuses
64
+ * `xhigh` and `max` alongside `thinking: {type:"disabled"}` — *"effort 'max'
65
+ * is not supported when thinking is disabled"* — while accepting `high`.
66
+ *
67
+ * This started as a blanket rule applied to every model that can disable
68
+ * thinking, on the reasoning that the pairing is incoherent anyway. Measured,
69
+ * that was too wide: Sonnet 5 and Opus 4.8 both accept `disabled` + `max`,
70
+ * so the blanket rule was silently dropping an effort the caller asked for
71
+ * and the wire would have honoured. Incoherent-looking is not the same as
72
+ * rejected, and only the wire gets to say which.
73
+ */
74
+ readonly effortWhenDisabled: EffortLevels
60
75
  }
61
76
 
62
77
  const MANUAL_ONLY: ThinkingCapability = {
@@ -64,6 +79,7 @@ const MANUAL_ONLY: ThinkingCapability = {
64
79
  manual: true,
65
80
  canDisable: true,
66
81
  effort: NO_EFFORT,
82
+ effortWhenDisabled: NO_EFFORT,
67
83
  }
68
84
 
69
85
  /**
@@ -91,7 +107,13 @@ export function resolveThinkingCapability(model: string): ThinkingCapability {
91
107
  // parser can compare, and it is the one model supporting both modes while
92
108
  // refusing to be switched off.
93
109
  if (/^(?:anthropic\/)?claude-mythos-preview$/.test(normalized)) {
94
- return { adaptive: true, manual: true, canDisable: false, effort: FULL_EFFORT }
110
+ return {
111
+ adaptive: true,
112
+ manual: true,
113
+ canDisable: false,
114
+ effort: FULL_EFFORT,
115
+ effortWhenDisabled: FULL_EFFORT,
116
+ }
95
117
  }
96
118
 
97
119
  const parsed = parseVersionedModelId(model, MODEL_ID_GRAMMAR)
@@ -101,17 +123,42 @@ export function resolveThinkingCapability(model: string): ThinkingCapability {
101
123
 
102
124
  // Always-on families: thinking cannot be disabled at any version.
103
125
  if (family === 'fable' || family === 'mythos') {
104
- return { adaptive: true, manual: false, canDisable: false, effort: FULL_EFFORT }
126
+ return {
127
+ adaptive: true,
128
+ manual: false,
129
+ canDisable: false,
130
+ effort: FULL_EFFORT,
131
+ effortWhenDisabled: FULL_EFFORT,
132
+ }
105
133
  }
106
134
 
107
135
  // 4.7 and later dropped manual mode outright.
108
136
  if (major > 4 || (major === 4 && minor >= 7)) {
109
- return { adaptive: true, manual: false, canDisable: true, effort: FULL_EFFORT }
137
+ // The Opus 5 family alone caps effort while thinking is off. Measured,
138
+ // not inferred: `claude-opus-5` refuses `disabled` + `xhigh`/`max` and
139
+ // accepts `disabled` + `high`, while `claude-sonnet-5` and
140
+ // `claude-opus-4-8` accept `disabled` + `max`. A version comparison of
141
+ // "5 and later" would have caught Sonnet 5 too and dropped an effort
142
+ // that wire honours.
143
+ const opus5Plus = family === 'opus' && major >= 5
144
+ return {
145
+ adaptive: true,
146
+ manual: false,
147
+ canDisable: true,
148
+ effort: FULL_EFFORT,
149
+ effortWhenDisabled: opus5Plus ? EFFORT_BASE : FULL_EFFORT,
150
+ }
110
151
  }
111
152
 
112
153
  // 4.6 accepts both; manual is deprecated there but still functional.
113
154
  if (major === 4 && minor === 6) {
114
- return { adaptive: true, manual: true, canDisable: true, effort: EFFORT_WITHOUT_XHIGH }
155
+ return {
156
+ adaptive: true,
157
+ manual: true,
158
+ canDisable: true,
159
+ effort: EFFORT_WITHOUT_XHIGH,
160
+ effortWhenDisabled: EFFORT_WITHOUT_XHIGH,
161
+ }
115
162
  }
116
163
 
117
164
  // 4.5 and earlier are manual-only. Opus 4.5 is the one that also takes
@@ -119,7 +166,8 @@ export function resolveThinkingCapability(model: string): ThinkingCapability {
119
166
  // takes only the first three levels: `xhigh` did not exist yet and `max`
120
167
  // is rejected there.
121
168
  const isOpus45 = family === 'opus' && major === 4 && minor === 5
122
- return { ...MANUAL_ONLY, effort: isOpus45 ? EFFORT_BASE : NO_EFFORT }
169
+ const base = isOpus45 ? EFFORT_BASE : NO_EFFORT
170
+ return { ...MANUAL_ONLY, effort: base, effortWhenDisabled: base }
123
171
  }
124
172
 
125
173
  /** The `thinking` body value, or `undefined` to send no thinking field. */
@@ -189,21 +237,25 @@ export function resolveThinkingBody(
189
237
  * request without it is the same request at the model's own default, whereas
190
238
  * refusing would fail a call that has a correct answer.
191
239
  *
192
- * The COMBINATION has to be legal. On Opus 5 and later,
193
- * `thinking: {type: "disabled"}` is accepted at effort `high` or below and
194
- * **rejected at `xhigh`/`max`**, enforced per request. Rather than encode
195
- * "Opus 5 and later" as a second version comparison, this refuses the pairing
196
- * on every model that can disable thinking — it is incoherent anyway, since it
197
- * asks a model not to think and then to think as hard as possible.
240
+ * The COMBINATION has to be legal, and the legal set is per model rather than
241
+ * universal. Opus 5 accepts `thinking: {type: "disabled"}` at `high` or below
242
+ * and **rejects it at `xhigh`/`max`** — so this asks the capability for the set
243
+ * that applies when thinking is off, instead of the set that applies generally.
244
+ *
245
+ * That distinction was earned. The rule started as a blanket refusal on every
246
+ * model that can disable thinking, on the reasoning that the pairing is
247
+ * incoherent anyway — asking a model not to think and then to think as hard as
248
+ * possible. Measured, Sonnet 5 and Opus 4.8 both accept it, so the blanket rule
249
+ * was discarding an effort the caller asked for and the wire would have
250
+ * honoured. Incoherent-looking is not the same as rejected.
198
251
  */
199
252
  export function resolveEffort(
200
253
  effort: ReasoningEffort | undefined,
201
254
  thinkingBody: ResolvedThinkingBody,
202
255
  capability: ThinkingCapability,
203
256
  ): ReasoningEffort | undefined {
204
- if (effort === undefined || !capability.effort.includes(effort)) return undefined
205
- if (thinkingBody?.type === 'disabled' && (effort === 'xhigh' || effort === 'max')) {
206
- return undefined
207
- }
208
- return effort
257
+ if (effort === undefined) return undefined
258
+ const allowed =
259
+ thinkingBody?.type === 'disabled' ? capability.effortWhenDisabled : capability.effort
260
+ return allowed.includes(effort) ? effort : undefined
209
261
  }