@moxxy/plugin-provider-claude-code 0.30.0 → 0.32.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.
@@ -1,36 +1,567 @@
1
- import { describe, expect, it } from 'vitest';
2
- import { CLAUDE_CODE_SYSTEM, CLAUDE_OAUTH_BETA } from './constants.js';
3
- import { claudeCodeProviderDef, createClaudeCodeClient } from './index.js';
1
+ import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
2
+ import { EventEmitter } from 'node:events';
3
+ import { PassThrough } from 'node:stream';
4
+ import { chmod, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { afterEach, describe, expect, it } from 'vitest';
8
+ import { z } from 'zod';
9
+ import type { ProviderEvent, ProviderRequest } from '@moxxy/sdk';
10
+ import {
11
+ CLAUDE_CODE_DEFAULT_MODEL,
12
+ claudeCodeModels,
13
+ claudeCodeProviderDef,
14
+ createClaudeCodeClient,
15
+ __setClaudeCommandRunner,
16
+ } from './index.js';
17
+
18
+ class ControlledProviderChild extends EventEmitter {
19
+ readonly stdin = new PassThrough();
20
+ readonly stdout = new PassThrough();
21
+ readonly stderr = new PassThrough();
22
+ exitCode: number | null = null;
23
+ signalCode: NodeJS.Signals | null = null;
24
+ readonly kills: NodeJS.Signals[] = [];
25
+
26
+ kill(signal: NodeJS.Signals = 'SIGTERM'): boolean {
27
+ this.kills.push(signal);
28
+ this.signalCode = signal;
29
+ this.emit('close', null, signal);
30
+ return true;
31
+ }
32
+
33
+ asChild(): ChildProcessWithoutNullStreams {
34
+ return this as unknown as ChildProcessWithoutNullStreams;
35
+ }
36
+ }
37
+
38
+ const tempDirs: string[] = [];
39
+ afterEach(async () => {
40
+ await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
41
+ });
4
42
 
5
43
  describe('claude-code provider definition', () => {
6
- it('registers as an OAuth provider named claude-code with Claude models', () => {
44
+ it('projects the provider-neutral host workspace into client config', async () => {
45
+ __setClaudeCommandRunner(async () => ({ code: 0, stdout: '{"loggedIn":true}', stderr: '' }));
46
+ const resolved = await claudeCodeProviderDef.resolveCredentials!({
47
+ vault: { get: async () => null, set: async () => undefined },
48
+ providerConfig: { mode: 'native-tools' },
49
+ host: { cwd: '/session/workspace' },
50
+ });
51
+ expect(resolved).toMatchObject({ mode: 'native-tools', cwd: '/session/workspace' });
52
+ });
53
+
54
+ it('registers the exact Claude Code catalog and its native web-search capability', () => {
7
55
  expect(claudeCodeProviderDef.name).toBe('claude-code');
8
56
  expect(claudeCodeProviderDef.auth?.kind).toBe('oauth');
9
- expect(claudeCodeProviderDef.models.length).toBeGreaterThan(0);
10
- expect(claudeCodeProviderDef.models.map((m) => m.id)).toContain('claude-sonnet-4-6');
11
- });
12
-
13
- it('builds an OAuth-mode client that reports the claude-code name', () => {
14
- const client = createClaudeCodeClient({ oauthToken: 'tok' });
15
- expect(client.name).toBe('claude-code');
16
- const inner = (client as unknown as { client: { apiKey: unknown; authToken: unknown } }).client;
17
- expect(inner.apiKey).toBeNull();
18
- expect(inner.authToken).toBe('tok');
19
- });
20
-
21
- it('forwards the OAuth beta headers and identity preamble to AnthropicProvider', () => {
22
- // These two are load-bearing: a subscription token is rejected by the
23
- // Messages API unless `anthropic-beta: oauth-2025-04-20` is sent and the
24
- // system prompt leads with the exact CLAUDE_CODE_SYSTEM line. A silent
25
- // drop/typo in the forwarding object compiles fine and only surfaces as a
26
- // runtime 401/400 — pin the contract here.
27
- const client = createClaudeCodeClient({ oauthToken: 'tok' });
28
- const oauth = (
29
- client as unknown as { oauth: { beta: ReadonlyArray<string>; systemPreamble?: string } }
30
- ).oauth;
31
- expect(oauth.beta).toEqual([...CLAUDE_OAUTH_BETA]);
32
- expect(oauth.beta).toContain('oauth-2025-04-20');
33
- expect(oauth.beta).toContain('claude-code-20250219');
34
- expect(oauth.systemPreamble).toBe(CLAUDE_CODE_SYSTEM);
57
+ expect(CLAUDE_CODE_DEFAULT_MODEL).toBe('claude-sonnet-4-6');
58
+ expect(claudeCodeProviderDef.models).toBe(claudeCodeModels);
59
+ expect(claudeCodeProviderDef.models.map((model) => model.id)).toEqual([
60
+ 'claude-sonnet-4-6',
61
+ 'claude-fable-5',
62
+ 'claude-opus-4-8',
63
+ 'claude-opus-4-7',
64
+ 'claude-opus-4-6',
65
+ 'claude-haiku-4-5-20251001',
66
+ ]);
67
+ for (const model of claudeCodeProviderDef.models) {
68
+ expect(model).toMatchObject({
69
+ supportsStreaming: true,
70
+ supportsTools: false,
71
+ supportsImages: false,
72
+ supportsDocuments: false,
73
+ supportsAudio: false,
74
+ supportsReasoning: false,
75
+ hostedTools: ['web_search'],
76
+ });
77
+ }
78
+ });
79
+
80
+ it('streams text through a fake Claude executable with structured non-interactive arguments', async () => {
81
+ const dir = await makeFakeClaude([
82
+ { type: 'system', subtype: 'init' },
83
+ { type: 'rate_limit_event', rate_limit_info: { status: 'allowed' } },
84
+ { type: 'stream_event', event: { type: 'message_start', message: {} } },
85
+ { type: 'stream_event', event: { type: 'content_block_start', content_block: { type: 'text', text: '' } } },
86
+ { type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'text_delta', text: 'Hello ' } } },
87
+ { type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'text_delta', text: 'world' } } },
88
+ { type: 'stream_event', event: { type: 'content_block_stop' } },
89
+ { type: 'stream_event', event: { type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 2 } } },
90
+ { type: 'stream_event', event: { type: 'message_stop' } },
91
+ { type: 'result', subtype: 'success', is_error: false, result: 'Hello world', usage: { input_tokens: 8, output_tokens: 2 } },
92
+ ]);
93
+ const client = createClaudeCodeClient({ executable: join(dir, 'claude') });
94
+ const events = await collect(client.stream(textRequest()));
95
+
96
+ expect(events).toEqual([
97
+ { type: 'message_start', model: 'claude-sonnet-4-6' },
98
+ { type: 'text_delta', delta: 'Hello ' },
99
+ { type: 'text_delta', delta: 'world' },
100
+ { type: 'message_end', stopReason: 'end_turn', usage: { inputTokens: 8, outputTokens: 2 } },
101
+ ]);
102
+ const args = JSON.parse(await readFile(join(dir, 'args.json'), 'utf8')) as string[];
103
+ expect(args).toEqual(expect.arrayContaining([
104
+ '--print', '--verbose', '--output-format', 'stream-json', '--include-partial-messages',
105
+ '--tools', 'WebSearch', '--allowedTools', 'WebSearch',
106
+ ]));
107
+ const input = await readFile(join(dir, 'input.txt'), 'utf8');
108
+ expect(input).toContain('system instructions');
109
+ expect(input).toContain('<user>\nprior user');
110
+ expect(input).toContain('<assistant>\nprior assistant');
111
+ expect(input).toContain('<user>\nlatest user');
112
+ expect(input).not.toContain('oauth-secret');
35
113
  });
114
+
115
+ it('can disable native WebSearch without enabling any other Claude tools', async () => {
116
+ const dir = await makeFakeClaude([
117
+ { type: 'result', subtype: 'success', is_error: false, usage: { input_tokens: 1, output_tokens: 1 } },
118
+ ]);
119
+ await collect(createClaudeCodeClient({
120
+ executable: join(dir, 'claude'),
121
+ webSearch: false,
122
+ }).stream(textRequest()));
123
+
124
+ const args = JSON.parse(await readFile(join(dir, 'args.json'), 'utf8')) as string[];
125
+ expect(args).toEqual(expect.arrayContaining(['--tools', '']));
126
+ expect(args).not.toContain('WebSearch');
127
+ expect(args).not.toContain('--allowedTools');
128
+ });
129
+
130
+ it('consumes streamed thinking blocks without exposing their deltas', async () => {
131
+ const dir = await makeFakeClaude([
132
+ { type: 'stream_event', event: { type: 'message_start', message: {} } },
133
+ { type: 'stream_event', event: { type: 'content_block_start', content_block: { type: 'thinking', thinking: '' } } },
134
+ { type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'thinking_delta', thinking: 'private chain of thought' } } },
135
+ { type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'signature_delta', signature: 'private-signature' } } },
136
+ { type: 'stream_event', event: { type: 'content_block_stop' } },
137
+ { type: 'stream_event', event: { type: 'content_block_start', content_block: { type: 'text', text: '' } } },
138
+ { type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'text_delta', text: 'Visible answer' } } },
139
+ { type: 'stream_event', event: { type: 'content_block_stop' } },
140
+ { type: 'result', subtype: 'success', is_error: false, result: 'Visible answer', usage: { input_tokens: 3, output_tokens: 2 } },
141
+ ]);
142
+ const events = await collect(createClaudeCodeClient({ executable: join(dir, 'claude') }).stream(textRequest()));
143
+
144
+ expect(events).toEqual([
145
+ { type: 'message_start', model: 'claude-sonnet-4-6' },
146
+ { type: 'text_delta', delta: 'Visible answer' },
147
+ { type: 'message_end', stopReason: 'end_turn', usage: { inputTokens: 3, outputTokens: 2 } },
148
+ ]);
149
+ expect(JSON.stringify(events)).not.toContain('private chain of thought');
150
+ expect(JSON.stringify(events)).not.toContain('private-signature');
151
+ });
152
+
153
+ it('accepts complete assistant records containing thinking blocks without exposing them', async () => {
154
+ const dir = await makeFakeClaude([
155
+ { type: 'assistant', message: { content: [
156
+ { type: 'thinking', thinking: 'private chain of thought', signature: 'private-signature' },
157
+ { type: 'text', text: 'Visible answer' },
158
+ ] } },
159
+ { type: 'result', subtype: 'success', is_error: false, result: 'Visible answer', usage: { input_tokens: 3, output_tokens: 2 } },
160
+ ]);
161
+ const events = await collect(createClaudeCodeClient({ executable: join(dir, 'claude') }).stream(textRequest()));
162
+
163
+ expect(events).toEqual([
164
+ { type: 'message_start', model: 'claude-sonnet-4-6' },
165
+ { type: 'message_end', stopReason: 'end_turn', usage: { inputTokens: 3, outputTokens: 2 } },
166
+ ]);
167
+ expect(JSON.stringify(events)).not.toContain('private chain of thought');
168
+ expect(JSON.stringify(events)).not.toContain('private-signature');
169
+ });
170
+
171
+ it('reconstructs two turns for each stateless CLI invocation without a session id', async () => {
172
+ const dir = await makeFakeClaude([
173
+ { type: 'stream_event', event: { type: 'content_block_start', content_block: { type: 'text', text: '' } } },
174
+ { type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'text_delta', text: 'first answer' } } },
175
+ { type: 'result', subtype: 'success', is_error: false, result: 'first answer', usage: { input_tokens: 2, output_tokens: 2 } },
176
+ ]);
177
+ const client = createClaudeCodeClient({ executable: join(dir, 'claude') });
178
+
179
+ await collect(client.stream({
180
+ model: CLAUDE_CODE_DEFAULT_MODEL,
181
+ messages: [{ role: 'user', content: [{ type: 'text', text: 'first prompt' }] }],
182
+ }));
183
+ const firstInput = await readFile(join(dir, 'input.txt'), 'utf8');
184
+ expect(firstInput).toContain('<user>\nfirst prompt\n</user>');
185
+
186
+ await collect(client.stream({
187
+ model: CLAUDE_CODE_DEFAULT_MODEL,
188
+ messages: [
189
+ { role: 'user', content: [{ type: 'text', text: 'first prompt' }] },
190
+ { role: 'assistant', content: [{ type: 'text', text: 'first answer' }] },
191
+ { role: 'user', content: [{ type: 'text', text: 'follow up' }] },
192
+ ],
193
+ }));
194
+ const secondInput = await readFile(join(dir, 'input.txt'), 'utf8');
195
+ expect(secondInput.indexOf('first prompt')).toBeLessThan(secondInput.indexOf('first answer'));
196
+ expect(secondInput.indexOf('first answer')).toBeLessThan(secondInput.indexOf('follow up'));
197
+ const args = JSON.parse(await readFile(join(dir, 'args.json'), 'utf8')) as string[];
198
+ expect(args.some((arg) => /session|resume/i.test(arg))).toBe(false);
199
+ });
200
+
201
+ it('projects prior moxxy tools and unsafe content deterministically as inert text', async () => {
202
+ const dir = await makeFakeClaude([
203
+ { type: 'result', subtype: 'success', is_error: false, usage: { input_tokens: 1, output_tokens: 1 } },
204
+ ]);
205
+ const client = createClaudeCodeClient({ executable: join(dir, 'claude') });
206
+ const rawBase64 = 'U0VDUkVUX0JJTkFSWV9QQVlMT0FE';
207
+ const request: ProviderRequest = {
208
+ model: CLAUDE_CODE_DEFAULT_MODEL,
209
+ messages: [
210
+ { role: 'assistant', content: [
211
+ { type: 'reasoning', text: 'private chain', signature: 'signed-secret' },
212
+ { type: 'tool_use', id: 'call-1', name: 'Read', input: { z: 2, a: 1 } },
213
+ ] },
214
+ { role: 'tool_result', content: [
215
+ { type: 'tool_result', toolUseId: 'call-1', content: 'file contents' },
216
+ ] },
217
+ { role: 'user', content: [
218
+ { type: 'image', mediaType: 'image/png', data: rawBase64 },
219
+ { type: 'text', text: '' },
220
+ ] },
221
+ ],
222
+ };
223
+
224
+ await collect(client.stream(request));
225
+ const first = await readFile(join(dir, 'input.txt'), 'utf8');
226
+ await collect(client.stream(request));
227
+ const replay = await readFile(join(dir, 'input.txt'), 'utf8');
228
+
229
+ expect(replay).toBe(first);
230
+ expect(first).toContain('<historical_tool_use status="already_executed_do_not_repeat">');
231
+ expect(first).toContain('<input_json>{&quot;a&quot;:1,&quot;z&quot;:2}</input_json>');
232
+ expect(first).toContain('<historical_tool_result tool_use_id="call-1" status="success">');
233
+ expect(first).toContain('[reasoning omitted: private reasoning and signatures are not replayed]');
234
+ expect(first).toContain('[image attachment omitted: mediaType=image/png; binary data not included]');
235
+ expect(first).toContain('[empty text block omitted]');
236
+ expect(first).not.toContain('private chain');
237
+ expect(first).not.toContain('signed-secret');
238
+ expect(first).not.toContain(rawBase64);
239
+ });
240
+
241
+ it('runs native tools in the configured workspace without emitting dispatcher tool events', async () => {
242
+ const workspace = await mkdtemp(join(tmpdir(), 'moxxy-claude-workspace-'));
243
+ tempDirs.push(workspace);
244
+ const dir = await makeFakeClaude([
245
+ { type: 'assistant', message: { content: [{ type: 'tool_use', id: 'edit-1', name: 'Write', input: { file_path: 'done.txt' } }] } },
246
+ { type: 'stream_event', event: { type: 'content_block_start', content_block: { type: 'tool_use', id: 'edit-1', name: 'Write' } } },
247
+ { type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'input_json_delta', partial_json: '{}' } } },
248
+ { type: 'stream_event', event: { type: 'content_block_stop' } },
249
+ { type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 'edit-1', content: 'ok' }] } },
250
+ { type: 'stream_event', event: { type: 'content_block_start', content_block: { type: 'text', text: '' } } },
251
+ { type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'text_delta', text: 'Edited.' } } },
252
+ { type: 'result', subtype: 'success', is_error: false, result: 'Edited.', usage: { input_tokens: 4, output_tokens: 1 } },
253
+ ], { path: 'done.txt', content: 'edited by native tool\n' });
254
+ const client = createClaudeCodeClient({
255
+ executable: join(dir, 'claude'),
256
+ mode: 'native-tools',
257
+ permissionMode: 'acceptEdits',
258
+ allowedTools: ['Read', 'Write'],
259
+ cwd: workspace,
260
+ });
261
+ const events = await collect(client.stream(textRequest()));
262
+
263
+ expect(events.filter((event) => event.type.startsWith('tool_use'))).toEqual([]);
264
+ expect(events.filter((event) => event.type === 'message_end')).toHaveLength(1);
265
+ expect(events).toContainEqual({ type: 'text_delta', delta: 'Edited.' });
266
+ expect(await readFile(join(dir, 'cwd.txt'), 'utf8')).toBe(await realpath(workspace));
267
+ expect(await readFile(join(workspace, 'done.txt'), 'utf8')).toBe('edited by native tool\n');
268
+ const args = JSON.parse(await readFile(join(dir, 'args.json'), 'utf8')) as string[];
269
+ expect(args).toEqual(expect.arrayContaining([
270
+ '--tools', 'Read', 'Write', '--permission-mode', 'acceptEdits', '--allowedTools', 'Read', 'Write',
271
+ ]));
272
+ expect(args).not.toContain('bypassPermissions');
273
+ expect(args).not.toEqual(expect.arrayContaining(['--tools', '']));
274
+ });
275
+
276
+ it('leaves the safe permission default to Claude and uses a valid no-tools invocation for an empty native allow-list', async () => {
277
+ const dir = await makeFakeClaude([
278
+ { type: 'result', subtype: 'success', is_error: false, usage: { input_tokens: 1, output_tokens: 1 } },
279
+ ]);
280
+ await collect(createClaudeCodeClient({
281
+ executable: join(dir, 'claude'),
282
+ mode: 'native-tools',
283
+ allowedTools: [],
284
+ }).stream(textRequest()));
285
+
286
+ const args = JSON.parse(await readFile(join(dir, 'args.json'), 'utf8')) as string[];
287
+ expect(args).toEqual(expect.arrayContaining(['--tools', '']));
288
+ expect(args).not.toContain('--permission-mode');
289
+ expect(args).not.toContain('--allowedTools');
290
+ expect(args).not.toContain('bypassPermissions');
291
+ });
292
+
293
+ it.each(['claude-fable-5', 'claude-opus-4-8'])('passes the selected %s model as an exact structured argument', async (model) => {
294
+ const dir = await makeFakeClaude([
295
+ { type: 'result', subtype: 'success', is_error: false, usage: { input_tokens: 1, output_tokens: 1 } },
296
+ ]);
297
+ const client = createClaudeCodeClient({ executable: join(dir, 'claude') });
298
+ await collect(client.stream({ ...textRequest(), model }));
299
+
300
+ const args = JSON.parse(await readFile(join(dir, 'args.json'), 'utf8')) as string[];
301
+ expect(args.slice(-2)).toEqual(['--model', model]);
302
+ expect(args.filter((arg) => arg === '--model')).toHaveLength(1);
303
+ });
304
+
305
+ it('uses the persisted provider-item model as its default selection', async () => {
306
+ const dir = await makeFakeClaude([
307
+ { type: 'result', subtype: 'success', is_error: false, usage: { input_tokens: 1, output_tokens: 1 } },
308
+ ]);
309
+ const client = claudeCodeProviderDef.createClient({ model: 'claude-fable-5', executable: join(dir, 'claude') });
310
+ await collect(client.stream({ ...textRequest(), model: '' }));
311
+
312
+ const args = JSON.parse(await readFile(join(dir, 'args.json'), 'utf8')) as string[];
313
+ expect(args.slice(-2)).toEqual(['--model', 'claude-fable-5']);
314
+ });
315
+
316
+ it('returns actionable errors for locally unsupported and CLI-rejected models', async () => {
317
+ const supported = claudeCodeModels.map((model) => model.id);
318
+ const unsupported = await collect(createClaudeCodeClient({
319
+ spawn: () => { throw new Error('should not spawn'); },
320
+ }).stream({ ...textRequest(), model: 'claude-imaginary-9' }));
321
+ expect(unsupported[1]).toMatchObject({
322
+ type: 'error',
323
+ message: expect.stringContaining('claude-imaginary-9'),
324
+ retryable: false,
325
+ });
326
+ for (const model of supported) expect((unsupported[1] as { message: string }).message).toContain(model);
327
+
328
+ const dir = await makeFakeClaude([
329
+ { type: 'result', subtype: 'error_during_execution', is_error: true, result: 'Model is unavailable' },
330
+ ]);
331
+ const rejected = await collect(createClaudeCodeClient({ executable: join(dir, 'claude') }).stream({
332
+ ...textRequest(),
333
+ model: 'claude-fable-5',
334
+ }));
335
+ expect(rejected[1]).toMatchObject({
336
+ type: 'error',
337
+ message: expect.stringMatching(/Claude Code rejected model "claude-fable-5".*Model is unavailable/),
338
+ retryable: false,
339
+ });
340
+ for (const model of supported) expect((rejected[1] as { message: string }).message).toContain(model);
341
+ });
342
+
343
+ it.each([
344
+ ['Not logged in. Authentication required', /signed out|authentication/i, false],
345
+ ['Rate limit exceeded (429)', /service failure.*rate limit/i, true],
346
+ ['Service temporarily unavailable', /service failure.*unavailable/i, true],
347
+ ] as const)('classifies CLI failure %s', async (detail, message, retryable) => {
348
+ const dir = await makeFakeClaude([
349
+ { type: 'result', subtype: 'error_during_execution', is_error: true, result: detail },
350
+ ]);
351
+ const events = await collect(createClaudeCodeClient({ executable: join(dir, 'claude') }).stream(textRequest()));
352
+ expect(events[1]).toMatchObject({ type: 'error', message: expect.stringMatching(message), retryable });
353
+ expect(events.filter((event) => event.type === 'error')).toHaveLength(1);
354
+ });
355
+
356
+ it('emits exactly one non-retryable error when a request is cancelled', async () => {
357
+ const child = new ControlledProviderChild();
358
+ const controller = new AbortController();
359
+ const eventsPromise = collect(createClaudeCodeClient({ spawn: () => child.asChild() }).stream({
360
+ ...textRequest(),
361
+ signal: controller.signal,
362
+ }));
363
+ controller.abort();
364
+ const events = await eventsPromise;
365
+ expect(events.filter((event) => event.type === 'error')).toEqual([{
366
+ type: 'error',
367
+ message: 'Claude CLI request aborted',
368
+ retryable: false,
369
+ }]);
370
+ expect(child.kills).toEqual(['SIGTERM']);
371
+ });
372
+
373
+ it('reports a missing executable and an unexpected exit as actionable non-retryable errors', async () => {
374
+ const missing = Object.assign(new Error('spawn claude ENOENT'), { code: 'ENOENT' });
375
+ const missingEvents = await collect(createClaudeCodeClient({
376
+ executable: '/missing/claude',
377
+ spawn: () => { throw missing; },
378
+ }).stream(textRequest()));
379
+ expect(missingEvents[1]).toMatchObject({
380
+ type: 'error',
381
+ message: expect.stringMatching(/executable not found.*npm install/i),
382
+ retryable: false,
383
+ });
384
+
385
+ const dir = await makeFailingClaude('unexpected local failure', 9);
386
+ const exitEvents = await collect(createClaudeCodeClient({ executable: join(dir, 'claude') }).stream(textRequest()));
387
+ expect(exitEvents[1]).toMatchObject({
388
+ type: 'error',
389
+ message: expect.stringContaining('unexpected local failure'),
390
+ retryable: false,
391
+ });
392
+ expect(exitEvents.filter((event) => event.type === 'error')).toHaveLength(1);
393
+ });
394
+
395
+ it('surfaces a permission denial as a clear non-retryable error', async () => {
396
+ const dir = await makeFakeClaude([
397
+ { type: 'result', subtype: 'error_during_execution', is_error: true, result: 'Permission denied for Edit' },
398
+ ]);
399
+ const events = await collect(createClaudeCodeClient({
400
+ executable: join(dir, 'claude'),
401
+ mode: 'native-tools',
402
+ allowedTools: ['Read'],
403
+ }).stream(textRequest()));
404
+ expect(events[1]).toMatchObject({
405
+ type: 'error',
406
+ message: expect.stringMatching(/Claude Code permission denied.*Edit/i),
407
+ retryable: false,
408
+ });
409
+ expect(events.some((event) => event.type === 'message_end')).toBe(false);
410
+ });
411
+
412
+ it('does not inject a moxxy-managed Claude token into the child environment', async () => {
413
+ let childEnv: NodeJS.ProcessEnv | undefined;
414
+ const prior = process.env.CLAUDE_CODE_OAUTH_TOKEN;
415
+ delete process.env.CLAUDE_CODE_OAUTH_TOKEN;
416
+ const dir = await makeFakeClaude([
417
+ { type: 'result', subtype: 'success', is_error: false, usage: { input_tokens: 1, output_tokens: 1 } },
418
+ ]);
419
+ const client = createClaudeCodeClient({
420
+ executable: join(dir, 'claude'),
421
+ spawn: (file, args, options) => {
422
+ childEnv = options.env;
423
+ return spawn(file, [...args], { stdio: ['pipe', 'pipe', 'pipe'], env: options.env, cwd: options.cwd });
424
+ },
425
+ });
426
+ try {
427
+ await collect(client.stream(textRequest()));
428
+ expect(childEnv?.CLAUDE_CODE_OAUTH_TOKEN).toBeUndefined();
429
+ } finally {
430
+ if (prior === undefined) delete process.env.CLAUDE_CODE_OAUTH_TOKEN;
431
+ else process.env.CLAUDE_CODE_OAUTH_TOKEN = prior;
432
+ }
433
+ });
434
+
435
+ it('orders the identity, message-derived system text, and extra system text', async () => {
436
+ const dir = await makeFakeClaude([
437
+ { type: 'result', subtype: 'success', is_error: false, usage: { input_tokens: 1, output_tokens: 1 } },
438
+ ]);
439
+ const client = createClaudeCodeClient({ executable: join(dir, 'claude') });
440
+ const base = textRequest();
441
+ const request: ProviderRequest = {
442
+ ...base,
443
+ messages: [
444
+ { role: 'system', content: [{ type: 'text', text: 'message system' }] },
445
+ ...base.messages,
446
+ ],
447
+ };
448
+ await collect(client.stream(request));
449
+ const input = await readFile(join(dir, 'input.txt'), 'utf8');
450
+ expect(input.indexOf("You are Claude Code")).toBeLessThan(input.indexOf('message system'));
451
+ expect(input.indexOf('message system')).toBeLessThan(input.indexOf('system instructions'));
452
+ });
453
+
454
+ it('rejects capabilities that the text-only descriptors disable', async () => {
455
+ const spawn = () => { throw new Error('should not spawn'); };
456
+ const client = createClaudeCodeClient({ spawn });
457
+
458
+ const withTools = await collect(client.stream({
459
+ ...textRequest(),
460
+ tools: [{
461
+ name: 'lookup',
462
+ description: 'Look something up',
463
+ inputSchema: z.object({}),
464
+ handler: async () => 'unused',
465
+ }],
466
+ }));
467
+ expect(withTools[1]).toMatchObject({
468
+ type: 'error',
469
+ message: expect.stringContaining('does not support tools'),
470
+ retryable: false,
471
+ });
472
+
473
+ const withReasoning = await collect(client.stream({ ...textRequest(), reasoning: true }));
474
+ expect(withReasoning[1]).toMatchObject({
475
+ type: 'error',
476
+ message: expect.stringContaining('does not support reasoning'),
477
+ retryable: false,
478
+ });
479
+ });
480
+
481
+ it('turns malformed and unsupported records into non-retryable errors', async () => {
482
+ for (const output of [['not json'], [JSON.stringify({ type: 'mystery' })]]) {
483
+ const dir = await makeFakeClaudeRaw(output);
484
+ const events = await collect(createClaudeCodeClient({ executable: join(dir, 'claude') }).stream(textRequest()));
485
+ expect(events[0]?.type).toBe('message_start');
486
+ expect(events[1]).toMatchObject({ type: 'error', retryable: false });
487
+ }
488
+ });
489
+
490
+ it('estimates tokens deterministically without spawning Claude', async () => {
491
+ let spawned = false;
492
+ const client = createClaudeCodeClient({ spawn: () => { spawned = true; throw new Error('should not spawn'); } });
493
+ const request = textRequest();
494
+ const first = await client.countTokens(request);
495
+ expect(await client.countTokens(request)).toBe(first);
496
+ expect(first).toBeGreaterThan(0);
497
+ expect(spawned).toBe(false);
498
+ });
499
+ });
500
+
501
+ function textRequest(): ProviderRequest {
502
+ return {
503
+ model: 'claude-sonnet-4-6',
504
+ system: 'system instructions',
505
+ messages: [
506
+ { role: 'user', content: [{ type: 'text', text: 'prior user' }] },
507
+ { role: 'assistant', content: [{ type: 'text', text: 'prior assistant' }] },
508
+ { role: 'user', content: [{ type: 'text', text: 'latest user' }] },
509
+ ],
510
+ };
511
+ }
512
+
513
+ async function makeFailingClaude(stderr: string, exitCode: number): Promise<string> {
514
+ const dir = await mkdtemp(join(tmpdir(), 'moxxy-claude-test-'));
515
+ tempDirs.push(dir);
516
+ const executable = join(dir, 'claude');
517
+ await writeFile(executable, `#!/usr/bin/env node\nconsole.error(${JSON.stringify(stderr)});\nprocess.exit(${exitCode});\n`, 'utf8');
518
+ await chmod(executable, 0o755);
519
+ return dir;
520
+ }
521
+
522
+ async function makeFakeClaude(
523
+ records: unknown[],
524
+ workspaceWrite?: { readonly path: string; readonly content: string },
525
+ ): Promise<string> {
526
+ return makeFakeClaudeRaw(records.map((record) => JSON.stringify(record)), workspaceWrite);
527
+ }
528
+
529
+ async function makeFakeClaudeRaw(
530
+ lines: string[],
531
+ workspaceWrite?: { readonly path: string; readonly content: string },
532
+ ): Promise<string> {
533
+ const dir = await mkdtemp(join(tmpdir(), 'moxxy-claude-test-'));
534
+ tempDirs.push(dir);
535
+ const executable = join(dir, 'claude');
536
+ const source = `#!/usr/bin/env node
537
+ const fs = require('node:fs');
538
+ const path = require('node:path');
539
+ let input = '';
540
+ process.stdin.setEncoding('utf8');
541
+ process.stdin.on('data', chunk => input += chunk);
542
+ process.stdin.on('end', () => {
543
+ const args = process.argv.slice(2);
544
+ fs.writeFileSync(path.join(__dirname, 'args.json'), JSON.stringify(args));
545
+ fs.writeFileSync(path.join(__dirname, 'input.txt'), input);
546
+ const permissionModeIndex = args.indexOf('--permission-mode');
547
+ if (permissionModeIndex >= 0 && !['acceptEdits', 'plan', 'dontAsk', 'bypassPermissions'].includes(args[permissionModeIndex + 1])) {
548
+ console.error('Invalid permission mode: ' + args[permissionModeIndex + 1]);
549
+ process.exitCode = 2;
550
+ return;
551
+ }
552
+ fs.writeFileSync(path.join(__dirname, 'cwd.txt'), process.cwd());
553
+ const workspaceWrite = ${JSON.stringify(workspaceWrite)};
554
+ if (workspaceWrite) fs.writeFileSync(path.join(process.cwd(), workspaceWrite.path), workspaceWrite.content);
555
+ for (const line of ${JSON.stringify(lines)}) console.log(line);
36
556
  });
557
+ `;
558
+ await writeFile(executable, source, 'utf8');
559
+ await chmod(executable, 0o755);
560
+ return dir;
561
+ }
562
+
563
+ async function collect(stream: AsyncIterable<ProviderEvent>): Promise<ProviderEvent[]> {
564
+ const events: ProviderEvent[] = [];
565
+ for await (const event of stream) events.push(event);
566
+ return events;
567
+ }