@moxxy/plugin-provider-claude-code 0.30.0 → 0.31.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,208 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { PassThrough } from 'node:stream';
3
+ import type { ChildProcessWithoutNullStreams } from 'node:child_process';
4
+ import { afterEach, describe, expect, it, vi } from 'vitest';
5
+ import { ClaudeProcessError, runClaudeProcess, type ClaudeProcessOptions, type ClaudeSpawnOptions } from './process.js';
6
+
7
+ class ControlledChild extends EventEmitter {
8
+ readonly stdin = new PassThrough();
9
+ readonly stdout = new PassThrough();
10
+ readonly stderr = new PassThrough();
11
+ readonly stdio = [this.stdin, this.stdout, this.stderr] as const;
12
+ exitCode: number | null = null;
13
+ signalCode: NodeJS.Signals | null = null;
14
+ readonly kills: NodeJS.Signals[] = [];
15
+
16
+ constructor(private readonly closeOn: NodeJS.Signals | undefined = 'SIGTERM') {
17
+ super();
18
+ }
19
+
20
+ kill(signal: NodeJS.Signals = 'SIGTERM'): boolean {
21
+ this.kills.push(signal);
22
+ if (signal === this.closeOn) this.close(null, signal);
23
+ return true;
24
+ }
25
+
26
+ close(code: number | null = 0, signal: NodeJS.Signals | null = null): void {
27
+ if (this.exitCode !== null || this.signalCode !== null) return;
28
+ this.exitCode = code;
29
+ this.signalCode = signal;
30
+ this.emit('close', code, signal);
31
+ }
32
+
33
+ asChild(): ChildProcessWithoutNullStreams {
34
+ return this as unknown as ChildProcessWithoutNullStreams;
35
+ }
36
+ }
37
+
38
+ const baseOptions: ClaudeProcessOptions = {
39
+ executable: 'claude',
40
+ model: 'claude-sonnet-4-6',
41
+ prompt: 'hello',
42
+ cwd: '/tmp',
43
+ nativeTools: false,
44
+ allowedTools: [],
45
+ };
46
+
47
+ function processWith(child: ControlledChild, overrides: Partial<ClaudeProcessOptions> = {}) {
48
+ return runClaudeProcess({ ...baseOptions, ...overrides, spawn: () => child.asChild() });
49
+ }
50
+
51
+ async function rejection(promise: Promise<unknown>): Promise<Error> {
52
+ try {
53
+ await promise;
54
+ throw new Error('expected rejection');
55
+ } catch (error) {
56
+ return error as Error;
57
+ }
58
+ }
59
+
60
+ async function flush(): Promise<void> {
61
+ await Promise.resolve();
62
+ await Promise.resolve();
63
+ }
64
+
65
+ afterEach(() => {
66
+ vi.useRealTimers();
67
+ });
68
+
69
+ describe('runClaudeProcess lifecycle', () => {
70
+ it('removes nested Claude environment markers without mutating the parent environment', async () => {
71
+ const child = new ControlledChild();
72
+ let spawnOptions: ClaudeSpawnOptions | undefined;
73
+ const oldClaudeCode = process.env.CLAUDECODE;
74
+ const oldEntrypoint = process.env.CLAUDE_CODE_ENTRYPOINT;
75
+ process.env.CLAUDECODE = '1';
76
+ process.env.CLAUDE_CODE_ENTRYPOINT = 'cli';
77
+ try {
78
+ const lines = runClaudeProcess({
79
+ ...baseOptions,
80
+ spawn: (_file, _args, options) => {
81
+ spawnOptions = options;
82
+ return child.asChild();
83
+ },
84
+ });
85
+ const pending = lines.next();
86
+ child.close(0);
87
+ await pending;
88
+ expect(spawnOptions?.env.CLAUDECODE).toBeUndefined();
89
+ expect(spawnOptions?.env.CLAUDE_CODE_ENTRYPOINT).toBeUndefined();
90
+ expect(process.env.CLAUDECODE).toBe('1');
91
+ expect(process.env.CLAUDE_CODE_ENTRYPOINT).toBe('cli');
92
+ } finally {
93
+ if (oldClaudeCode === undefined) delete process.env.CLAUDECODE;
94
+ else process.env.CLAUDECODE = oldClaudeCode;
95
+ if (oldEntrypoint === undefined) delete process.env.CLAUDE_CODE_ENTRYPOINT;
96
+ else process.env.CLAUDE_CODE_ENTRYPOINT = oldEntrypoint;
97
+ }
98
+ });
99
+
100
+ it('cancels promptly with one abort error and leaves no timer or child alive', async () => {
101
+ vi.useFakeTimers();
102
+ const child = new ControlledChild();
103
+ const controller = new AbortController();
104
+ const lines = processWith(child, { signal: controller.signal });
105
+ const pending = lines.next();
106
+ controller.abort();
107
+ const error = await rejection(pending);
108
+ expect(error).toMatchObject({ failure: 'aborted' });
109
+ expect(child.kills).toEqual(['SIGTERM']);
110
+ expect(vi.getTimerCount()).toBe(0);
111
+ expect(await lines.next()).toEqual({ done: true, value: undefined });
112
+ });
113
+
114
+ it('times out startup and clears all lifecycle timers', async () => {
115
+ vi.useFakeTimers();
116
+ const child = new ControlledChild();
117
+ const errorPromise = rejection(processWith(child, { startupTimeoutMs: 50 }).next());
118
+ await vi.advanceTimersByTimeAsync(50);
119
+ const error = await errorPromise;
120
+ expect(error).toMatchObject({ failure: 'startup_timeout' });
121
+ expect(child.kills).toEqual(['SIGTERM']);
122
+ expect(vi.getTimerCount()).toBe(0);
123
+ });
124
+
125
+ it('resets the idle timeout on every non-empty record', async () => {
126
+ vi.useFakeTimers();
127
+ const child = new ControlledChild();
128
+ const lines = processWith(child, { startupTimeoutMs: 100, idleTimeoutMs: 100 });
129
+ const first = lines.next();
130
+ await vi.advanceTimersByTimeAsync(90);
131
+ child.stdout.write('{"type":"system"}\n');
132
+ expect(await first).toMatchObject({ done: false });
133
+
134
+ const second = lines.next();
135
+ await vi.advanceTimersByTimeAsync(90);
136
+ child.stdout.write('{"type":"system"}\n');
137
+ expect(await second).toMatchObject({ done: false });
138
+
139
+ const timedOut = rejection(lines.next());
140
+ await vi.advanceTimersByTimeAsync(101);
141
+ expect(await timedOut).toMatchObject({ failure: 'idle_timeout' });
142
+ expect(child.kills).toEqual(['SIGTERM']);
143
+ expect(vi.getTimerCount()).toBe(0);
144
+ });
145
+
146
+ it('caps stderr and accepts a final unterminated record within the cap', async () => {
147
+ const child = new ControlledChild();
148
+ const lines = processWith(child, { maxStderrChars: 5, maxRecordChars: 20 });
149
+ const first = lines.next();
150
+ child.stderr.write('abcdefgh');
151
+ child.stdout.write('{"ok":true}');
152
+ child.close(7);
153
+ expect(await first).toEqual({ done: false, value: '{"ok":true}' });
154
+ expect(await lines.next()).toEqual({ done: true, value: { exitCode: 7, stderr: 'abcde' } });
155
+ });
156
+
157
+ it('rejects an oversized unterminated record as a protocol failure', async () => {
158
+ vi.useFakeTimers();
159
+ const child = new ControlledChild();
160
+ const lines = processWith(child, { maxRecordChars: 5 });
161
+ const pending = lines.next();
162
+ child.stdout.write('123456');
163
+ expect(await rejection(pending)).toMatchObject({ failure: 'protocol' });
164
+ expect(child.kills).toEqual(['SIGTERM']);
165
+ expect(vi.getTimerCount()).toBe(0);
166
+ });
167
+
168
+ it('escalates SIGTERM to SIGKILL once even when cleanup requests termination again', async () => {
169
+ vi.useFakeTimers();
170
+ const child = new ControlledChild('SIGKILL');
171
+ const controller = new AbortController();
172
+ const errorPromise = rejection(processWith(child, { signal: controller.signal }).next());
173
+ controller.abort();
174
+ await flush();
175
+ expect(child.kills).toEqual(['SIGTERM']);
176
+ await vi.advanceTimersByTimeAsync(1_000);
177
+ expect(await errorPromise).toMatchObject({ failure: 'aborted' });
178
+ expect(child.kills).toEqual(['SIGTERM', 'SIGKILL']);
179
+ expect(vi.getTimerCount()).toBe(0);
180
+ });
181
+
182
+ it('terminates immediately when the consumer returns early', async () => {
183
+ vi.useFakeTimers();
184
+ const child = new ControlledChild();
185
+ const lines = processWith(child);
186
+ const first = lines.next();
187
+ child.stdout.write('record\n');
188
+ expect(await first).toEqual({ done: false, value: 'record' });
189
+ await lines.return({ exitCode: 0, stderr: '' });
190
+ expect(child.kills).toEqual(['SIGTERM']);
191
+ expect(vi.getTimerCount()).toBe(0);
192
+ });
193
+
194
+ it('leaves no child or timer after normal completion', async () => {
195
+ vi.useFakeTimers();
196
+ const child = new ControlledChild();
197
+ const lines = processWith(child);
198
+ const pending = lines.next();
199
+ child.close(0);
200
+ expect(await pending).toEqual({ done: true, value: { exitCode: 0, stderr: '' } });
201
+ expect(child.kills).toEqual([]);
202
+ expect(vi.getTimerCount()).toBe(0);
203
+ });
204
+
205
+ it('preserves the typed process error identity', () => {
206
+ expect(new ClaudeProcessError('protocol', 'bad')).toBeInstanceOf(Error);
207
+ });
208
+ });
package/src/process.ts ADDED
@@ -0,0 +1,220 @@
1
+ import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
2
+
3
+ export interface ClaudeSpawnOptions {
4
+ readonly env: NodeJS.ProcessEnv;
5
+ readonly cwd: string;
6
+ }
7
+
8
+ export type ClaudeSpawn = (
9
+ executable: string,
10
+ args: ReadonlyArray<string>,
11
+ options: ClaudeSpawnOptions,
12
+ ) => ChildProcessWithoutNullStreams;
13
+
14
+ export type ClaudeProcessFailure = 'aborted' | 'startup_timeout' | 'idle_timeout' | 'protocol';
15
+
16
+ export class ClaudeProcessError extends Error {
17
+ constructor(readonly failure: ClaudeProcessFailure, message: string) {
18
+ super(message);
19
+ this.name = 'ClaudeProcessError';
20
+ }
21
+ }
22
+
23
+ export interface ClaudeProcessOptions {
24
+ readonly executable: string;
25
+ readonly model: string;
26
+ readonly prompt: string;
27
+ readonly cwd: string;
28
+ readonly nativeTools: boolean;
29
+ readonly permissionMode?: string;
30
+ readonly allowedTools: ReadonlyArray<string>;
31
+ readonly signal?: AbortSignal;
32
+ readonly spawn?: ClaudeSpawn;
33
+ readonly startupTimeoutMs?: number;
34
+ readonly idleTimeoutMs?: number;
35
+ readonly maxStderrChars?: number;
36
+ readonly maxRecordChars?: number;
37
+ }
38
+
39
+ export interface ClaudeProcessResult {
40
+ readonly exitCode: number;
41
+ readonly stderr: string;
42
+ }
43
+
44
+ const DEFAULT_STARTUP_TIMEOUT_MS = 30_000;
45
+ const DEFAULT_IDLE_TIMEOUT_MS = 120_000;
46
+ const DEFAULT_MAX_STDERR_CHARS = 2048;
47
+ const DEFAULT_MAX_RECORD_CHARS = 64 * 1024;
48
+ const KILL_GRACE_MS = 1_000;
49
+
50
+ type QueueItem = { readonly line: string } | { readonly error: Error } | { readonly done: true };
51
+
52
+ export async function* runClaudeProcess(
53
+ options: ClaudeProcessOptions,
54
+ ): AsyncGenerator<string, ClaudeProcessResult> {
55
+ const args = buildArgs(options);
56
+ const env = { ...process.env };
57
+ // Claude refuses nested interactive sessions. Moxxy is the parent here, not a
58
+ // nested Claude Code instance, even when it was launched from Claude Code.
59
+ delete env.CLAUDECODE;
60
+ delete env.CLAUDE_CODE_ENTRYPOINT;
61
+ const spawnImpl = options.spawn ?? ((file, childArgs, childOptions) => spawn(file, [...childArgs], {
62
+ stdio: ['pipe', 'pipe', 'pipe'], env: childOptions.env, cwd: childOptions.cwd,
63
+ }));
64
+
65
+ const child = spawnImpl(options.executable, args, { env, cwd: options.cwd });
66
+
67
+ const queue: QueueItem[] = [];
68
+ let wake: (() => void) | undefined;
69
+ let stdout = '';
70
+ let stderr = '';
71
+ let closed = false;
72
+ let failure: Error | undefined;
73
+ let timer: ReturnType<typeof setTimeout> | undefined;
74
+ let killTimer: ReturnType<typeof setTimeout> | undefined;
75
+ let terminationRequested = false;
76
+ const startupTimeoutMs = positive(options.startupTimeoutMs, DEFAULT_STARTUP_TIMEOUT_MS);
77
+ const idleTimeoutMs = positive(options.idleTimeoutMs, DEFAULT_IDLE_TIMEOUT_MS);
78
+ const maxStderrChars = positive(options.maxStderrChars, DEFAULT_MAX_STDERR_CHARS);
79
+ const maxRecordChars = positive(options.maxRecordChars, DEFAULT_MAX_RECORD_CHARS);
80
+
81
+ const push = (item: QueueItem): void => {
82
+ queue.push(item);
83
+ const notify = wake;
84
+ wake = undefined;
85
+ notify?.();
86
+ };
87
+ const clearWatchdog = (): void => {
88
+ if (timer) clearTimeout(timer);
89
+ timer = undefined;
90
+ };
91
+ const terminate = (): void => {
92
+ if (closed || child.exitCode !== null || child.signalCode !== null || terminationRequested) return;
93
+ terminationRequested = true;
94
+ child.kill('SIGTERM');
95
+ killTimer = setTimeout(() => {
96
+ killTimer = undefined;
97
+ if (!closed && child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
98
+ }, KILL_GRACE_MS);
99
+ killTimer.unref?.();
100
+ };
101
+ const fail = (error: Error): void => {
102
+ if (failure) return;
103
+ failure = error;
104
+ clearWatchdog();
105
+ terminate();
106
+ // Cancellation/failure is terminal: discard records received but not yet
107
+ // consumed so no text can be emitted after the single error event.
108
+ queue.length = 0;
109
+ push({ error });
110
+ };
111
+ const arm = (kind: 'startup' | 'idle'): void => {
112
+ clearWatchdog();
113
+ const delay = kind === 'startup' ? startupTimeoutMs : idleTimeoutMs;
114
+ timer = setTimeout(() => fail(new ClaudeProcessError(
115
+ kind === 'startup' ? 'startup_timeout' : 'idle_timeout',
116
+ kind === 'startup'
117
+ ? `Claude CLI did not produce a stream record within ${delay}ms`
118
+ : `Claude CLI stream was idle for ${delay}ms`,
119
+ )), delay);
120
+ timer.unref?.();
121
+ };
122
+ const onAbort = (): void => fail(new ClaudeProcessError('aborted', 'Claude CLI request aborted'));
123
+
124
+ child.stdin.on('error', (error) => {
125
+ // EPIPE commonly follows cancellation; the abort error is the useful one.
126
+ if (!failure) fail(error);
127
+ });
128
+ child.stderr.setEncoding('utf8');
129
+ child.stderr.on('data', (chunk: string) => {
130
+ if (stderr.length < maxStderrChars) stderr += chunk.slice(0, maxStderrChars - stderr.length);
131
+ });
132
+ child.stdout.setEncoding('utf8');
133
+ child.stdout.on('data', (chunk: string) => {
134
+ if (failure) return;
135
+ stdout += chunk;
136
+ if (stdout.length > maxRecordChars && !stdout.includes('\n')) {
137
+ fail(new ClaudeProcessError('protocol', `Claude CLI emitted a stream record larger than ${maxRecordChars} characters`));
138
+ return;
139
+ }
140
+ let newline = stdout.indexOf('\n');
141
+ while (newline >= 0 && !failure) {
142
+ const line = stdout.slice(0, newline).replace(/\r$/, '');
143
+ stdout = stdout.slice(newline + 1);
144
+ if (line.length > maxRecordChars) {
145
+ fail(new ClaudeProcessError('protocol', `Claude CLI emitted a stream record larger than ${maxRecordChars} characters`));
146
+ return;
147
+ }
148
+ if (line.trim()) {
149
+ arm('idle');
150
+ push({ line });
151
+ }
152
+ newline = stdout.indexOf('\n');
153
+ }
154
+ if (stdout.length > maxRecordChars) {
155
+ fail(new ClaudeProcessError('protocol', `Claude CLI emitted a stream record larger than ${maxRecordChars} characters`));
156
+ }
157
+ });
158
+
159
+ const completion = new Promise<number>((resolve) => {
160
+ child.once('error', (error) => {
161
+ fail(error);
162
+ });
163
+ child.once('close', (code) => {
164
+ closed = true;
165
+ clearWatchdog();
166
+ if (killTimer) clearTimeout(killTimer);
167
+ killTimer = undefined;
168
+ if (!failure && stdout.trim()) {
169
+ if (stdout.length > maxRecordChars) {
170
+ fail(new ClaudeProcessError('protocol', `Claude CLI emitted a stream record larger than ${maxRecordChars} characters`));
171
+ } else {
172
+ // A final JSON record need not end in a newline.
173
+ push({ line: stdout.replace(/\r$/, '') });
174
+ }
175
+ }
176
+ push({ done: true });
177
+ resolve(code ?? 1);
178
+ });
179
+ });
180
+
181
+ options.signal?.addEventListener('abort', onAbort, { once: true });
182
+ if (options.signal?.aborted) onAbort();
183
+ else arm('startup');
184
+ if (!failure) child.stdin.end(options.prompt, 'utf8');
185
+
186
+ try {
187
+ while (true) {
188
+ if (queue.length === 0) await new Promise<void>((resolve) => { wake = resolve; });
189
+ const item = queue.shift();
190
+ if (!item) continue;
191
+ if ('error' in item) throw item.error;
192
+ if ('done' in item) break;
193
+ yield item.line;
194
+ }
195
+ const exitCode = await completion;
196
+ return { exitCode, stderr: stderr.trim() };
197
+ } finally {
198
+ clearWatchdog();
199
+ options.signal?.removeEventListener('abort', onAbort);
200
+ terminate();
201
+ try { await completion; } catch { /* surfaced through the queue */ }
202
+ if (killTimer) clearTimeout(killTimer);
203
+ }
204
+ }
205
+
206
+ function buildArgs(options: ClaudeProcessOptions): string[] {
207
+ const args = ['--print', '--verbose', '--output-format', 'stream-json', '--include-partial-messages', '--model', options.model];
208
+ if (options.nativeTools) {
209
+ args.push('--tools', ...(options.allowedTools.length > 0 ? options.allowedTools : ['']));
210
+ if (options.permissionMode) args.push('--permission-mode', options.permissionMode);
211
+ if (options.allowedTools.length > 0) args.push('--allowedTools', ...options.allowedTools);
212
+ } else {
213
+ args.splice(args.length - 2, 0, '--tools', '');
214
+ }
215
+ return args;
216
+ }
217
+
218
+ function positive(value: number | undefined, fallback: number): number {
219
+ return value !== undefined && value > 0 ? value : fallback;
220
+ }
@@ -0,0 +1,248 @@
1
+ import type { ContentBlock, ProviderEvent, ProviderRequest } from '@moxxy/sdk';
2
+ import { CLAUDE_CODE_SYSTEM } from './constants.js';
3
+
4
+ interface ProtocolState {
5
+ started: boolean;
6
+ ended: boolean;
7
+ /** Current streamed block. Native tool records are consumed by Claude itself. */
8
+ blockType?: 'text' | 'thinking' | 'tool_use' | 'tool_result';
9
+ stopReason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'error';
10
+ inputTokens?: number;
11
+ outputTokens?: number;
12
+ }
13
+
14
+ const EMPTY_TEXT_PLACEHOLDER = '[empty text block omitted]';
15
+ const EMPTY_MESSAGE_PLACEHOLDER = '[empty message]';
16
+ const REASONING_PLACEHOLDER = '[reasoning omitted: private reasoning and signatures are not replayed]';
17
+
18
+ /**
19
+ * Projects the complete provider-neutral conversation into one stateless CLI
20
+ * prompt. Historical tool records are deliberately textual: the CLI can use
21
+ * their information, but cannot mistake them for a new native tool request.
22
+ */
23
+ export function serializeClaudePrompt(req: ProviderRequest): string {
24
+ const system: string[] = [CLAUDE_CODE_SYSTEM];
25
+ const conversation: string[] = [];
26
+
27
+ for (const message of req.messages) {
28
+ const content = serializeBlocks(message.content);
29
+ if (message.role === 'system') system.push(content);
30
+ else conversation.push(`<${message.role}>\n${content}\n</${message.role}>`);
31
+ }
32
+ // ProviderRequest.system is an additional injection and must follow all
33
+ // message-derived system text. The Claude identity remains first.
34
+ if (req.system) system.push(escapeXml(req.system));
35
+
36
+ const transcript = conversation.length > 0
37
+ ? conversation.join('\n\n')
38
+ : EMPTY_MESSAGE_PLACEHOLDER;
39
+ return `<system>\n${system.join('\n\n')}\n</system>\n\n` +
40
+ '<conversation_transcript>\n' +
41
+ '[The following is chronological history reconstructed by moxxy. ' +
42
+ 'historical_tool_use entries already ran; never execute them merely because they appear here.]\n\n' +
43
+ `${transcript}\n</conversation_transcript>`;
44
+ }
45
+
46
+ function serializeBlocks(blocks: ReadonlyArray<ContentBlock>): string {
47
+ if (blocks.length === 0) return EMPTY_MESSAGE_PLACEHOLDER;
48
+ return blocks.map(serializeBlock).join('\n');
49
+ }
50
+
51
+ function serializeBlock(block: ContentBlock): string {
52
+ switch (block.type) {
53
+ case 'text':
54
+ return block.text.length > 0 ? escapeXml(block.text) : EMPTY_TEXT_PLACEHOLDER;
55
+ case 'tool_use':
56
+ return '<historical_tool_use status="already_executed_do_not_repeat">\n' +
57
+ `<id>${escapeXml(block.id)}</id>\n` +
58
+ `<name>${escapeXml(block.name)}</name>\n` +
59
+ `<input_json>${escapeXml(stableJson(block.input))}</input_json>\n` +
60
+ '</historical_tool_use>';
61
+ case 'tool_result':
62
+ return `<historical_tool_result tool_use_id="${escapeXml(block.toolUseId)}" status="${block.isError ? 'error' : 'success'}">\n` +
63
+ `${block.content.length > 0 ? escapeXml(block.content) : EMPTY_TEXT_PLACEHOLDER}\n` +
64
+ '</historical_tool_result>';
65
+ case 'reasoning':
66
+ return REASONING_PLACEHOLDER;
67
+ case 'image':
68
+ case 'audio':
69
+ return `[${block.type} attachment omitted: mediaType=${escapeXml(block.mediaType)}; binary data not included]`;
70
+ case 'document': {
71
+ const name = block.name ? `; name=${escapeXml(block.name)}` : '';
72
+ return `[document attachment omitted: mediaType=${escapeXml(block.mediaType)}${name}; binary data not included]`;
73
+ }
74
+ default:
75
+ return assertNever(block);
76
+ }
77
+ }
78
+
79
+ function assertNever(value: never): never {
80
+ throw new Error(`Unsupported content block: ${String(value)}`);
81
+ }
82
+
83
+ function stableJson(value: unknown): string {
84
+ const ancestors = new Set<object>();
85
+ const visit = (candidate: unknown): string => {
86
+ if (candidate === null) return 'null';
87
+ if (typeof candidate === 'string' || typeof candidate === 'boolean') return JSON.stringify(candidate);
88
+ if (typeof candidate === 'number') return Number.isFinite(candidate) ? JSON.stringify(candidate) : JSON.stringify(String(candidate));
89
+ if (typeof candidate === 'bigint') return JSON.stringify(`${candidate.toString()}n`);
90
+ if (typeof candidate === 'undefined') return JSON.stringify('[undefined]');
91
+ if (typeof candidate === 'function' || typeof candidate === 'symbol') return JSON.stringify(`[${typeof candidate} omitted]`);
92
+ if (typeof candidate !== 'object') return JSON.stringify(String(candidate));
93
+ if (ancestors.has(candidate)) return JSON.stringify('[circular reference omitted]');
94
+
95
+ ancestors.add(candidate);
96
+ let result: string;
97
+ if (Array.isArray(candidate)) {
98
+ result = `[${candidate.map(visit).join(',')}]`;
99
+ } else {
100
+ const record = candidate as Record<string, unknown>;
101
+ result = `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${visit(record[key])}`).join(',')}}`;
102
+ }
103
+ ancestors.delete(candidate);
104
+ return result;
105
+ };
106
+ return visit(value);
107
+ }
108
+
109
+ function escapeXml(value: string): string {
110
+ return value
111
+ .replaceAll('&', '&amp;')
112
+ .replaceAll('<', '&lt;')
113
+ .replaceAll('>', '&gt;')
114
+ .replaceAll('"', '&quot;')
115
+ .replaceAll("'", '&apos;');
116
+ }
117
+
118
+ export function createProtocolState(): ProtocolState {
119
+ return { started: false, ended: false, stopReason: 'end_turn' };
120
+ }
121
+
122
+ export function parseClaudeRecord(line: string, state: ProtocolState): ProviderEvent[] {
123
+ let value: unknown;
124
+ try {
125
+ value = JSON.parse(line);
126
+ } catch {
127
+ throw new Error('Claude CLI emitted malformed stream-json');
128
+ }
129
+ if (!isRecord(value) || typeof value.type !== 'string') {
130
+ throw new Error('Claude CLI emitted malformed stream-json record');
131
+ }
132
+
133
+ // Informational envelope records can appear between protocol events on newer
134
+ // Claude CLI versions. They carry no assistant content or terminal state.
135
+ if (value.type === 'system' || value.type === 'rate_limit_event') return [];
136
+ if (value.type === 'assistant' || value.type === 'user') return parseMessageRecord(value);
137
+ if (value.type === 'stream_event') return parseStreamEvent(value.event, state);
138
+ if (value.type === 'result') return parseResult(value, state);
139
+ throw new Error(`Claude CLI emitted unsupported stream-json record: ${value.type}`);
140
+ }
141
+
142
+ function parseMessageRecord(record: Record<string, unknown>): ProviderEvent[] {
143
+ if (!isRecord(record.message) || !Array.isArray(record.message.content)) {
144
+ throw new Error('Claude CLI emitted malformed assistant record');
145
+ }
146
+ for (const block of record.message.content) {
147
+ if (!isRecord(block) || typeof block.type !== 'string') {
148
+ throw new Error('Claude CLI emitted malformed assistant content');
149
+ }
150
+ if (block.type === 'text' && typeof block.text !== 'string') {
151
+ throw new Error('Claude CLI emitted malformed assistant text');
152
+ }
153
+ // Thinking stays private, while tool_use/tool_result are internal CLI
154
+ // bookkeeping that Claude has already executed. Translating any of these
155
+ // records to ProviderEvents would either expose private reasoning or make
156
+ // the moxxy dispatcher execute the same operation a second time.
157
+ if (block.type !== 'text' && block.type !== 'thinking' && block.type !== 'tool_use' && block.type !== 'tool_result') {
158
+ throw new Error('Claude CLI emitted unsupported assistant content');
159
+ }
160
+ }
161
+ // Partial text arrives through stream_event records.
162
+ return [];
163
+ }
164
+
165
+ function parseStreamEvent(raw: unknown, state: ProtocolState): ProviderEvent[] {
166
+ if (!isRecord(raw) || typeof raw.type !== 'string') {
167
+ throw new Error('Claude CLI emitted malformed stream event');
168
+ }
169
+ switch (raw.type) {
170
+ case 'message_start':
171
+ state.started = true;
172
+ return [];
173
+ case 'content_block_start': {
174
+ if (!isRecord(raw.content_block) || typeof raw.content_block.type !== 'string') {
175
+ throw new Error('Claude CLI emitted malformed content block');
176
+ }
177
+ if (raw.content_block.type !== 'text' && raw.content_block.type !== 'thinking' && raw.content_block.type !== 'tool_use' && raw.content_block.type !== 'tool_result') {
178
+ throw new Error('Claude CLI emitted unsupported content block');
179
+ }
180
+ state.blockType = raw.content_block.type;
181
+ return [];
182
+ }
183
+ case 'content_block_delta': {
184
+ if (!isRecord(raw.delta) || typeof raw.delta.type !== 'string') {
185
+ throw new Error('Claude CLI emitted malformed content delta');
186
+ }
187
+ if (state.blockType !== 'text') {
188
+ // input_json_delta and tool result deltas describe work performed by the
189
+ // child and must not escape as moxxy tool events.
190
+ return [];
191
+ }
192
+ if (raw.delta.type !== 'text_delta' || typeof raw.delta.text !== 'string') {
193
+ throw new Error('Claude CLI emitted unsupported text delta');
194
+ }
195
+ return [{ type: 'text_delta', delta: raw.delta.text }];
196
+ }
197
+ case 'content_block_stop':
198
+ state.blockType = undefined;
199
+ return [];
200
+ case 'message_stop':
201
+ return [];
202
+ case 'message_delta': {
203
+ 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);
205
+ if (isRecord(raw.usage) && typeof raw.usage.output_tokens === 'number') {
206
+ state.outputTokens = raw.usage.output_tokens;
207
+ }
208
+ return [];
209
+ }
210
+ case 'ping':
211
+ return [];
212
+ default:
213
+ throw new Error(`Claude CLI emitted unsupported stream event: ${raw.type}`);
214
+ }
215
+ }
216
+
217
+ function parseResult(record: Record<string, unknown>, state: ProtocolState): ProviderEvent[] {
218
+ if (state.ended) throw new Error('Claude CLI emitted more than one terminal result');
219
+ state.ended = true;
220
+ if (record.is_error === true || record.subtype !== 'success') {
221
+ const message = typeof record.result === 'string' ? record.result : 'Claude CLI request failed';
222
+ return [{ type: 'error', message, retryable: false }];
223
+ }
224
+
225
+ if (isRecord(record.usage)) {
226
+ const input = record.usage.input_tokens;
227
+ const output = record.usage.output_tokens;
228
+ if (typeof input === 'number') state.inputTokens = input;
229
+ if (typeof output === 'number') state.outputTokens = output;
230
+ }
231
+ const usage = state.inputTokens !== undefined && state.outputTokens !== undefined
232
+ ? { inputTokens: state.inputTokens, outputTokens: state.outputTokens }
233
+ : undefined;
234
+ return [{ type: 'message_end', stopReason: state.stopReason, ...(usage ? { usage } : {}) }];
235
+ }
236
+
237
+ function mapStopReason(value: unknown): ProtocolState['stopReason'] {
238
+ switch (value) {
239
+ case 'end_turn': return 'end_turn';
240
+ case 'max_tokens': return 'max_tokens';
241
+ case 'stop_sequence': return 'stop_sequence';
242
+ default: throw new Error(`Claude CLI emitted unsupported stop reason: ${String(value)}`);
243
+ }
244
+ }
245
+
246
+ function isRecord(value: unknown): value is Record<string, unknown> {
247
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
248
+ }