@moxxy/plugin-provider-claude-code 0.41.2 → 0.42.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,93 @@
1
+ import { chmod, mkdtemp, writeFile } from 'node:fs/promises';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { afterEach, describe, expect, it } from 'vitest';
5
+ import { posixShell } from '@moxxy/vitest-preset/platform';
6
+ import type { ProviderAuthContext } from '@moxxy/sdk';
7
+ import { claudeLogin } from './login.js';
8
+ import { removeDir } from '@moxxy/vitest-preset/fs';
9
+
10
+ // A stand-in for the installed `claude` binary, speaking the same non-TTY login
11
+ // dialogue: it prints the sign-in URL and a paste prompt, then either finishes
12
+ // on its own (the browser's localhost callback) or waits for a pasted code.
13
+ const FAKE_CLAUDE = `#!/usr/bin/env node
14
+ const fs = require('node:fs');
15
+ const path = require('node:path');
16
+ const marker = path.join(__dirname, 'signed-in');
17
+ const [, , group, command] = process.argv;
18
+ if (group === 'auth' && command === 'status') {
19
+ console.log(JSON.stringify({ loggedIn: fs.existsSync(marker), email: 'me@example.com' }));
20
+ process.exit(0);
21
+ }
22
+ if (group === 'auth' && command === 'login') {
23
+ process.stdout.write('Opening browser to sign in…\\n');
24
+ process.stdout.write("If the browser didn't open, visit: https://claude.com/cai/oauth/authorize?code=true\\n");
25
+ process.stdout.write('Paste code here if prompted > ');
26
+ if (process.env.FAKE_CLAUDE_CALLBACK === '1') {
27
+ fs.writeFileSync(marker, '');
28
+ process.exit(0);
29
+ }
30
+ let input = '';
31
+ process.stdin.on('data', (chunk) => {
32
+ input += chunk;
33
+ if (!input.includes('\\n')) return;
34
+ if (input.trim() !== 'code#state') process.exit(3);
35
+ fs.writeFileSync(marker, '');
36
+ process.exit(0);
37
+ });
38
+ }
39
+ `;
40
+
41
+ const dirs: string[] = [];
42
+
43
+ afterEach(async () => {
44
+ delete process.env.FAKE_CLAUDE_CALLBACK;
45
+ await Promise.all(dirs.splice(0).map((dir) => removeDir(dir)));
46
+ });
47
+
48
+ async function fakeClaude(): Promise<string> {
49
+ const dir = await mkdtemp(join(tmpdir(), 'moxxy-claude-login-'));
50
+ dirs.push(dir);
51
+ const executable = join(dir, 'claude');
52
+ await writeFile(executable, FAKE_CLAUDE, 'utf8');
53
+ await chmod(executable, 0o755);
54
+ return executable;
55
+ }
56
+
57
+ /** The context `moxxy login --stdin-prompts` hands a provider when the desktop drives it. */
58
+ function desktopContext(executable: string, answer: () => Promise<string>) {
59
+ const output: string[] = [];
60
+ const questions: string[] = [];
61
+ const ctx: ProviderAuthContext = {
62
+ headless: false,
63
+ noOpen: true,
64
+ providerConfig: { executable },
65
+ write: (chunk) => { output.push(chunk); },
66
+ onAuthUrl: () => {},
67
+ prompt: async (question) => {
68
+ questions.push(question);
69
+ return await answer();
70
+ },
71
+ vault: { get: async () => null, set: async () => {}, delete: async () => false },
72
+ };
73
+ return { ctx, output, questions };
74
+ }
75
+
76
+ describe('Claude sign-in driven from the desktop', () => {
77
+ it.skipIf(!posixShell)('shows the CLI progress and hands the code pasted in the desktop to the CLI', async () => {
78
+ const { ctx, output, questions } = desktopContext(await fakeClaude(), async () => 'code#state');
79
+
80
+ await expect(claudeLogin(ctx)).resolves.toEqual({ accountId: 'me@example.com' });
81
+
82
+ expect(output.join('')).toContain("If the browser didn't open, visit: https://claude.com/cai/oauth/authorize?code=true");
83
+ expect(questions).toHaveLength(1);
84
+ expect(questions[0]).toMatch(/paste/i);
85
+ });
86
+
87
+ it.skipIf(!posixShell)('finishes when the browser completes the sign-in, without waiting for a pasted code', async () => {
88
+ process.env.FAKE_CLAUDE_CALLBACK = '1';
89
+ const { ctx } = desktopContext(await fakeClaude(), () => new Promise<string>(() => {}));
90
+
91
+ await expect(claudeLogin(ctx)).resolves.toEqual({ accountId: 'me@example.com' });
92
+ });
93
+ });
package/src/login.ts CHANGED
@@ -29,12 +29,30 @@ export interface ClaudeCommandResult {
29
29
  readonly error?: NodeJS.ErrnoException;
30
30
  }
31
31
 
32
+ /**
33
+ * A GUI host's side of the CLI's interactive login: it shows the CLI's output
34
+ * and answers the CLI's paste prompt, since the CLI has no terminal of its own.
35
+ */
36
+ export interface ClaudeLoginRelay {
37
+ readonly write: (chunk: string) => void;
38
+ readonly askCode: () => Promise<string>;
39
+ }
40
+
41
+ interface CommandOptions {
42
+ readonly inherit?: boolean;
43
+ readonly relay?: ClaudeLoginRelay;
44
+ }
45
+
32
46
  type CommandRunner = (
33
47
  executable: string,
34
48
  args: readonly string[],
35
- options?: { readonly inherit?: boolean },
49
+ options?: CommandOptions,
36
50
  ) => Promise<ClaudeCommandResult>;
37
51
 
52
+ /** The CLI's non-TTY login asks for a code only when the browser's automatic return fails. */
53
+ const PASTE_PROMPT = /paste code/i;
54
+ const PASTE_QUESTION = 'If your browser shows a sign-in code instead of finishing on its own, paste it here.';
55
+
38
56
  let runCommandImpl: CommandRunner = runCommand;
39
57
  /** Test seam. */
40
58
  export function __setClaudeCommandRunner(runner: CommandRunner): void {
@@ -101,7 +119,16 @@ export async function claudeLogin(ctx: ProviderAuthContext): Promise<ProviderOAu
101
119
  if (status.state === 'signed-in') return status.accountId ? { accountId: status.accountId } : {};
102
120
  if (status.state !== 'signed-out') throw authError(status);
103
121
 
104
- const login = await runCommandImpl(executable, CLAUDE_AUTH_LOGIN_ARGS, { inherit: true });
122
+ // A GUI host (the desktop) has no terminal to hand the CLI, so relay its
123
+ // dialogue through the host instead.
124
+ const prompt = ctx.prompt;
125
+ const login = await runCommandImpl(
126
+ executable,
127
+ CLAUDE_AUTH_LOGIN_ARGS,
128
+ ctx.noOpen && prompt
129
+ ? { relay: { write: ctx.write, askCode: () => prompt(PASTE_QUESTION) } }
130
+ : { inherit: true },
131
+ );
105
132
  if (login.error) throw authError({ state: login.error.code === 'ENOENT' ? 'missing' : 'error', executable, message: login.error.message });
106
133
  if (login.code !== 0) {
107
134
  throw new MoxxyError({
@@ -171,19 +198,35 @@ function authError(status: ClaudeCliAuthStatus): MoxxyError {
171
198
  async function runCommand(
172
199
  executable: string,
173
200
  args: readonly string[],
174
- options: { readonly inherit?: boolean } = {},
201
+ options: CommandOptions = {},
175
202
  ): Promise<ClaudeCommandResult> {
203
+ const { relay } = options;
176
204
  return await new Promise((resolve) => {
177
205
  const spawnOptions: SpawnOptions = options.inherit
178
206
  ? { stdio: 'inherit' }
179
- : { stdio: ['ignore', 'pipe', 'pipe'] };
207
+ : { stdio: [relay ? 'pipe' : 'ignore', 'pipe', 'pipe'] };
180
208
  const child = spawn(executable, [...args], spawnOptions);
181
209
  let stdout = '';
182
210
  let stderr = '';
211
+ let askedForCode = false;
212
+ // The CLI may exit (browser callback) before the pasted code arrives.
213
+ child.stdin?.on('error', () => {});
183
214
  child.stdout?.setEncoding('utf8');
184
215
  child.stderr?.setEncoding('utf8');
185
- child.stdout?.on('data', (chunk: string) => { stdout += chunk; });
186
- child.stderr?.on('data', (chunk: string) => { stderr += chunk; });
216
+ child.stdout?.on('data', (chunk: string) => {
217
+ stdout += chunk;
218
+ if (!relay) return;
219
+ relay.write(chunk);
220
+ if (askedForCode || !PASTE_PROMPT.test(stdout)) return;
221
+ askedForCode = true;
222
+ void relay.askCode().then((code) => {
223
+ if (code.trim() && child.stdin?.writable) child.stdin.write(`${code.trim()}\n`);
224
+ });
225
+ });
226
+ child.stderr?.on('data', (chunk: string) => {
227
+ stderr += chunk;
228
+ relay?.write(chunk);
229
+ });
187
230
  child.once('error', (error: NodeJS.ErrnoException) => resolve({ code: 1, stdout, stderr, error }));
188
231
  child.once('close', (code) => resolve({ code: code ?? 1, stdout, stderr }));
189
232
  });
@@ -37,7 +37,7 @@ class ControlledChild extends EventEmitter {
37
37
 
38
38
  const baseOptions: ClaudeProcessOptions = {
39
39
  executable: 'claude',
40
- model: 'claude-sonnet-5',
40
+ model: 'claude-sonnet-5-5',
41
41
  prompt: 'hello',
42
42
  cwd: '/tmp',
43
43
  nativeTools: false,
package/src/protocol.ts CHANGED
@@ -1,4 +1,6 @@
1
- import type { ContentBlock, ProviderEvent, ProviderRequest } from '@moxxy/sdk';
1
+ import { randomUUID } from 'node:crypto';
2
+ import type { ContentBlock, ProviderEvent, ProviderRequest, ToolDef } from '@moxxy/sdk';
3
+ import { zodToJsonSchema } from '@moxxy/sdk';
2
4
  import { CLAUDE_CODE_SYSTEM } from './constants.js';
3
5
 
4
6
  interface ProtocolState {
@@ -9,8 +11,25 @@ interface ProtocolState {
9
11
  stopReason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'error';
10
12
  inputTokens?: number;
11
13
  outputTokens?: number;
14
+ /** Present when moxxy tools were offered; streamed text is scanned for a call block. */
15
+ toolCalls?: ToolCallScan;
12
16
  }
13
17
 
18
+ interface ToolCallScan {
19
+ /** Trailing text withheld because it may be the start of TOOL_CALLS_OPEN. */
20
+ held: string;
21
+ /** Text after TOOL_CALLS_OPEN once a block has started. */
22
+ block?: string;
23
+ }
24
+
25
+ const TOOL_CALLS_OPEN = '<moxxy_tool_calls>';
26
+ const TOOL_CALLS_CLOSE = '</moxxy_tool_calls>';
27
+ // Weaker models otherwise attempt a native call for a same-named tool, which
28
+ // the CLI rejects, and then give up.
29
+ const TOOL_CALLS_REMINDER = '[moxxy: native tool calls are unavailable here and will fail. ' +
30
+ `To use a moxxy tool, end your reply with a ${TOOL_CALLS_OPEN} block as described in the system section.]`;
31
+ const TOOL_CALL_PATTERN =/<call name="([^"]+)">([\s\S]*?)<\/call>/g;
32
+
14
33
  const EMPTY_TEXT_PLACEHOLDER = '[empty text block omitted]';
15
34
  const EMPTY_MESSAGE_PLACEHOLDER = '[empty message]';
16
35
  const REASONING_PLACEHOLDER = '[reasoning omitted: private reasoning and signatures are not replayed]';
@@ -32,6 +51,9 @@ export function serializeClaudePrompt(req: ProviderRequest): string {
32
51
  // ProviderRequest.system is an additional injection and must follow all
33
52
  // message-derived system text. The Claude identity remains first.
34
53
  if (req.system) system.push(escapeXml(req.system));
54
+ const tools = req.tools ?? [];
55
+ const hasTools = tools.length > 0;
56
+ if (hasTools) system.push(serializeTools(tools));
35
57
 
36
58
  const transcript = conversation.length > 0
37
59
  ? conversation.join('\n\n')
@@ -40,7 +62,38 @@ export function serializeClaudePrompt(req: ProviderRequest): string {
40
62
  '<conversation_transcript>\n' +
41
63
  '[The following is chronological history reconstructed by moxxy. ' +
42
64
  'historical_tool_use entries already ran; never execute them merely because they appear here.]\n\n' +
43
- `${transcript}\n</conversation_transcript>`;
65
+ `${transcript}\n</conversation_transcript>` +
66
+ (hasTools ? `\n\n${TOOL_CALLS_REMINDER}` : '');
67
+ }
68
+
69
+ /**
70
+ * The CLI runs with Claude's own tools disabled, so moxxy tools are offered as
71
+ * a text protocol. The model ends its reply with one call block, the stream
72
+ * parser turns it into tool_use events, and moxxy dispatches them through its
73
+ * normal permission path.
74
+ */
75
+ function serializeTools(tools: ReadonlyArray<ToolDef>): string {
76
+ const definitions = tools.map((tool) =>
77
+ `<tool name="${escapeXml(tool.name)}">\n` +
78
+ `<description>${escapeXml(tool.description)}</description>\n` +
79
+ `<input_schema>${jsonForXml(tool.inputJsonSchema ?? zodToJsonSchema(tool.inputSchema))}</input_schema>\n` +
80
+ '</tool>');
81
+ return '<moxxy_tools>\n' +
82
+ 'The host application (moxxy) executes the tools below for you. They are not native Claude Code tools: ' +
83
+ 'native tools with the same names are disabled in this session and calling them fails, so use only the block below. ' +
84
+ 'To call one or more of them, end your reply with exactly one block in this format, not wrapped in any other tags, and then stop writing:\n\n' +
85
+ `${TOOL_CALLS_OPEN}\n<call name="TOOL_NAME">{"param": "value"}</call>\n${TOOL_CALLS_CLOSE}\n\n` +
86
+ "Each call body is a single JSON object matching that tool's input_schema. moxxy runs the calls and continues the conversation " +
87
+ 'with their results as historical_tool_result entries. Never invent tool results.\n\n' +
88
+ `${definitions.join('\n')}\n</moxxy_tools>`;
89
+ }
90
+
91
+ /** JSON with markup characters escaped as JSON unicode escapes, so it stays valid JSON. */
92
+ function jsonForXml(value: unknown): string {
93
+ return JSON.stringify(value)
94
+ .replaceAll('&', '\\u0026')
95
+ .replaceAll('<', '\\u003c')
96
+ .replaceAll('>', '\\u003e');
44
97
  }
45
98
 
46
99
  function serializeBlocks(blocks: ReadonlyArray<ContentBlock>): string {
@@ -115,8 +168,93 @@ function escapeXml(value: string): string {
115
168
  .replaceAll("'", '&apos;');
116
169
  }
117
170
 
118
- export function createProtocolState(): ProtocolState {
119
- return { started: false, ended: false, stopReason: 'end_turn' };
171
+ export function createProtocolState(opts: { readonly toolCalls?: boolean } = {}): ProtocolState {
172
+ return {
173
+ started: false,
174
+ ended: false,
175
+ stopReason: 'end_turn',
176
+ ...(opts.toolCalls ? { toolCalls: { held: '' } } : {}),
177
+ };
178
+ }
179
+
180
+ /**
181
+ * Passes text through until a tool-call block opens, then withholds it. A
182
+ * closed block becomes tool_use events plus a terminal `tool_use` message_end.
183
+ * Anything the model writes after the block (typically invented results) is
184
+ * dropped because the caller stops reading at message_end.
185
+ */
186
+ function scanText(delta: string, state: ProtocolState): ProviderEvent[] {
187
+ const scan = state.toolCalls;
188
+ if (!scan) return [{ type: 'text_delta', delta }];
189
+ if (scan.block === undefined) {
190
+ const text = scan.held + delta;
191
+ const open = text.indexOf(TOOL_CALLS_OPEN);
192
+ if (open < 0) {
193
+ const keep = partialOpenLength(text);
194
+ scan.held = text.slice(text.length - keep);
195
+ const visible = text.slice(0, text.length - keep);
196
+ return visible ? [{ type: 'text_delta', delta: visible }] : [];
197
+ }
198
+ scan.held = '';
199
+ scan.block = '';
200
+ const before = text.slice(0, open);
201
+ const rest = scanText(text.slice(open + TOOL_CALLS_OPEN.length), state);
202
+ return before ? [{ type: 'text_delta', delta: before }, ...rest] : rest;
203
+ }
204
+ scan.block += delta;
205
+ const close = scan.block.indexOf(TOOL_CALLS_CLOSE);
206
+ if (close < 0) return [];
207
+ const events: ProviderEvent[] = [];
208
+ for (const match of scan.block.slice(0, close).matchAll(TOOL_CALL_PATTERN)) {
209
+ const id = `moxxy_${randomUUID()}`;
210
+ events.push(
211
+ { type: 'tool_use_start', id, name: unescapeXml(match[1] ?? '') },
212
+ { type: 'tool_use_end', id, input: parseCallInput((match[2] ?? '').trim()) },
213
+ );
214
+ }
215
+ if (events.length === 0) {
216
+ // A block without any call is not a request; show it and stop scanning.
217
+ const raw = TOOL_CALLS_OPEN + scan.block;
218
+ state.toolCalls = undefined;
219
+ return [{ type: 'text_delta', delta: raw }];
220
+ }
221
+ state.ended = true;
222
+ return [...events, { type: 'message_end', stopReason: 'tool_use' }];
223
+ }
224
+
225
+ /** A held partial tag or a block that never closed is plain output. */
226
+ function flushText(state: ProtocolState): ProviderEvent[] {
227
+ const scan = state.toolCalls;
228
+ if (!scan) return [];
229
+ const rest = scan.block === undefined ? scan.held : TOOL_CALLS_OPEN + scan.block;
230
+ state.toolCalls = { held: '' };
231
+ return rest ? [{ type: 'text_delta', delta: rest }] : [];
232
+ }
233
+
234
+ function partialOpenLength(text: string): number {
235
+ for (let length = Math.min(text.length, TOOL_CALLS_OPEN.length - 1); length > 0; length -= 1) {
236
+ if (TOOL_CALLS_OPEN.startsWith(text.slice(text.length - length))) return length;
237
+ }
238
+ return 0;
239
+ }
240
+
241
+ function parseCallInput(body: string): unknown {
242
+ try {
243
+ return JSON.parse(body);
244
+ } catch {
245
+ // Kept as a string so the dispatcher's schema check reports the problem
246
+ // to the model instead of running the tool with empty input.
247
+ return body;
248
+ }
249
+ }
250
+
251
+ function unescapeXml(value: string): string {
252
+ return value
253
+ .replaceAll('&quot;', '"')
254
+ .replaceAll('&apos;', "'")
255
+ .replaceAll('&lt;', '<')
256
+ .replaceAll('&gt;', '>')
257
+ .replaceAll('&amp;', '&');
120
258
  }
121
259
 
122
260
  export function parseClaudeRecord(line: string, state: ProtocolState): ProviderEvent[] {
@@ -192,7 +330,7 @@ function parseStreamEvent(raw: unknown, state: ProtocolState): ProviderEvent[] {
192
330
  if (raw.delta.type !== 'text_delta' || typeof raw.delta.text !== 'string') {
193
331
  throw new Error('Claude CLI emitted unsupported text delta');
194
332
  }
195
- return [{ type: 'text_delta', delta: raw.delta.text }];
333
+ return scanText(raw.delta.text, state);
196
334
  }
197
335
  case 'content_block_stop':
198
336
  state.blockType = undefined;
@@ -201,7 +339,11 @@ function parseStreamEvent(raw: unknown, state: ProtocolState): ProviderEvent[] {
201
339
  return [];
202
340
  case 'message_delta': {
203
341
  if (!isRecord(raw.delta)) throw new Error('Claude CLI emitted malformed message delta');
204
- if (raw.delta.stop_reason != null) state.stopReason = mapStopReason(raw.delta.stop_reason);
342
+ // `tool_use` ends an internal CLI round trip (a native tool call, or a
343
+ // rejected attempt at one); the CLI continues with another message.
344
+ if (raw.delta.stop_reason != null && raw.delta.stop_reason !== 'tool_use') {
345
+ state.stopReason = mapStopReason(raw.delta.stop_reason);
346
+ }
205
347
  if (isRecord(raw.usage) && typeof raw.usage.output_tokens === 'number') {
206
348
  state.outputTokens = raw.usage.output_tokens;
207
349
  }
@@ -231,7 +373,7 @@ function parseResult(record: Record<string, unknown>, state: ProtocolState): Pro
231
373
  const usage = state.inputTokens !== undefined && state.outputTokens !== undefined
232
374
  ? { inputTokens: state.inputTokens, outputTokens: state.outputTokens }
233
375
  : undefined;
234
- return [{ type: 'message_end', stopReason: state.stopReason, ...(usage ? { usage } : {}) }];
376
+ return [...flushText(state), { type: 'message_end', stopReason: state.stopReason, ...(usage ? { usage } : {}) }];
235
377
  }
236
378
 
237
379
  function mapStopReason(value: unknown): ProtocolState['stopReason'] {