@moxxy/plugin-provider-claude-code 0.44.0 → 0.46.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.
- package/dist/account-limit.d.ts +8 -0
- package/dist/account-limit.d.ts.map +1 -0
- package/dist/account-limit.js +23 -0
- package/dist/account-limit.js.map +1 -0
- package/dist/agent-provider.d.ts +61 -0
- package/dist/agent-provider.d.ts.map +1 -0
- package/dist/agent-provider.js +195 -0
- package/dist/agent-provider.js.map +1 -0
- package/dist/agent-session.d.ts +145 -0
- package/dist/agent-session.d.ts.map +1 -0
- package/dist/agent-session.js +703 -0
- package/dist/agent-session.js.map +1 -0
- package/dist/background-work.d.ts +42 -0
- package/dist/background-work.d.ts.map +1 -0
- package/dist/background-work.js +140 -0
- package/dist/background-work.js.map +1 -0
- package/dist/constants.d.ts +2 -2
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +2 -2
- package/dist/constants.js.map +1 -1
- package/dist/executable.d.ts +15 -0
- package/dist/executable.d.ts.map +1 -0
- package/dist/executable.js +30 -0
- package/dist/executable.js.map +1 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +55 -16
- package/dist/index.js.map +1 -1
- package/dist/login.d.ts +3 -0
- package/dist/login.d.ts.map +1 -1
- package/dist/login.js +8 -1
- package/dist/login.js.map +1 -1
- package/dist/offered-models.d.ts +13 -0
- package/dist/offered-models.d.ts.map +1 -0
- package/dist/offered-models.js +48 -0
- package/dist/offered-models.js.map +1 -0
- package/dist/own-settings.d.ts +12 -0
- package/dist/own-settings.d.ts.map +1 -0
- package/dist/own-settings.js +31 -0
- package/dist/own-settings.js.map +1 -0
- package/dist/questions.d.ts +6 -0
- package/dist/questions.d.ts.map +1 -0
- package/dist/questions.js +38 -0
- package/dist/questions.js.map +1 -0
- package/dist/scheduled-wakeups.d.ts +10 -0
- package/dist/scheduled-wakeups.d.ts.map +1 -0
- package/dist/scheduled-wakeups.js +30 -0
- package/dist/scheduled-wakeups.js.map +1 -0
- package/dist/sdk-install.d.ts +25 -0
- package/dist/sdk-install.d.ts.map +1 -0
- package/dist/sdk-install.js +94 -0
- package/dist/sdk-install.js.map +1 -0
- package/dist/sdk-types.d.ts +312 -0
- package/dist/sdk-types.d.ts.map +1 -0
- package/dist/sdk-types.js +8 -0
- package/dist/sdk-types.js.map +1 -0
- package/dist/subagents.d.ts +39 -0
- package/dist/subagents.d.ts.map +1 -0
- package/dist/subagents.js +114 -0
- package/dist/subagents.js.map +1 -0
- package/dist/task-list.d.ts +21 -0
- package/dist/task-list.d.ts.map +1 -0
- package/dist/task-list.js +68 -0
- package/dist/task-list.js.map +1 -0
- package/dist/translate.d.ts +66 -0
- package/dist/translate.d.ts.map +1 -0
- package/dist/translate.js +302 -0
- package/dist/translate.js.map +1 -0
- package/package.json +14 -9
- package/src/account-limit.ts +26 -0
- package/src/agent-cli.test.ts +83 -0
- package/src/agent-provider.test.ts +1176 -0
- package/src/agent-provider.ts +223 -0
- package/src/agent-session.ts +793 -0
- package/src/background-work.ts +163 -0
- package/src/constants.ts +2 -3
- package/src/event-coverage.test.ts +106 -0
- package/src/executable.test.ts +60 -0
- package/src/executable.ts +34 -0
- package/src/fake-claude.testkit.ts +376 -0
- package/src/fixtures/claude-agent-sdk-0.3.296.json +43 -0
- package/src/fixtures/claude-supported-models-0.3.296.json +218 -0
- package/src/index.test.ts +49 -0
- package/src/index.ts +61 -18
- package/src/login.ts +10 -1
- package/src/offered-models.test.ts +81 -0
- package/src/offered-models.ts +60 -0
- package/src/own-settings.test.ts +68 -0
- package/src/own-settings.ts +33 -0
- package/src/questions.test.ts +68 -0
- package/src/questions.ts +45 -0
- package/src/scheduled-wakeups.test.ts +41 -0
- package/src/scheduled-wakeups.ts +34 -0
- package/src/sdk-install.test.ts +124 -0
- package/src/sdk-install.ts +107 -0
- package/src/sdk-types.ts +278 -0
- package/src/subagents.ts +123 -0
- package/src/task-list.ts +65 -0
- package/src/translate.test.ts +474 -0
- package/src/translate.ts +306 -0
- package/dist/process.d.ts +0 -34
- package/dist/process.d.ts.map +0 -1
- package/dist/process.js +0 -197
- package/dist/process.js.map +0 -1
- package/dist/protocol.d.ts +0 -30
- package/dist/protocol.d.ts.map +0 -1
- package/dist/protocol.js +0 -368
- package/dist/protocol.js.map +0 -1
- package/dist/provider.d.ts +0 -53
- package/dist/provider.d.ts.map +0 -1
- package/dist/provider.js +0 -229
- package/dist/provider.js.map +0 -1
- package/src/process.test.ts +0 -208
- package/src/process.ts +0 -224
- package/src/protocol.ts +0 -390
- package/src/provider.test.ts +0 -671
- package/src/provider.ts +0 -267
package/src/protocol.ts
DELETED
|
@@ -1,390 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import type { ContentBlock, ProviderEvent, ProviderRequest, ToolDef } from '@moxxy/sdk';
|
|
3
|
-
import { zodToJsonSchema } from '@moxxy/sdk';
|
|
4
|
-
import { CLAUDE_CODE_SYSTEM } from './constants.js';
|
|
5
|
-
|
|
6
|
-
interface ProtocolState {
|
|
7
|
-
started: boolean;
|
|
8
|
-
ended: boolean;
|
|
9
|
-
/** Current streamed block. Native tool records are consumed by Claude itself. */
|
|
10
|
-
blockType?: 'text' | 'thinking' | 'tool_use' | 'tool_result';
|
|
11
|
-
stopReason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'error';
|
|
12
|
-
inputTokens?: number;
|
|
13
|
-
outputTokens?: number;
|
|
14
|
-
/** Present when moxxy tools were offered; streamed text is scanned for a call block. */
|
|
15
|
-
toolCalls?: ToolCallScan;
|
|
16
|
-
}
|
|
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
|
-
|
|
33
|
-
const EMPTY_TEXT_PLACEHOLDER = '[empty text block omitted]';
|
|
34
|
-
const EMPTY_MESSAGE_PLACEHOLDER = '[empty message]';
|
|
35
|
-
const REASONING_PLACEHOLDER = '[reasoning omitted: private reasoning and signatures are not replayed]';
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* Projects the complete provider-neutral conversation into one stateless CLI
|
|
39
|
-
* prompt. Historical tool records are deliberately textual: the CLI can use
|
|
40
|
-
* their information, but cannot mistake them for a new native tool request.
|
|
41
|
-
*/
|
|
42
|
-
export function serializeClaudePrompt(req: ProviderRequest): string {
|
|
43
|
-
const system: string[] = [CLAUDE_CODE_SYSTEM];
|
|
44
|
-
const conversation: string[] = [];
|
|
45
|
-
|
|
46
|
-
for (const message of req.messages) {
|
|
47
|
-
const content = serializeBlocks(message.content);
|
|
48
|
-
if (message.role === 'system') system.push(content);
|
|
49
|
-
else conversation.push(`<${message.role}>\n${content}\n</${message.role}>`);
|
|
50
|
-
}
|
|
51
|
-
// ProviderRequest.system is an additional injection and must follow all
|
|
52
|
-
// message-derived system text. The Claude identity remains first.
|
|
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));
|
|
57
|
-
|
|
58
|
-
const transcript = conversation.length > 0
|
|
59
|
-
? conversation.join('\n\n')
|
|
60
|
-
: EMPTY_MESSAGE_PLACEHOLDER;
|
|
61
|
-
return `<system>\n${system.join('\n\n')}\n</system>\n\n` +
|
|
62
|
-
'<conversation_transcript>\n' +
|
|
63
|
-
'[The following is chronological history reconstructed by moxxy. ' +
|
|
64
|
-
'historical_tool_use entries already ran; never execute them merely because they appear here.]\n\n' +
|
|
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');
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
function serializeBlocks(blocks: ReadonlyArray<ContentBlock>): string {
|
|
100
|
-
if (blocks.length === 0) return EMPTY_MESSAGE_PLACEHOLDER;
|
|
101
|
-
return blocks.map(serializeBlock).join('\n');
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
function serializeBlock(block: ContentBlock): string {
|
|
105
|
-
switch (block.type) {
|
|
106
|
-
case 'text':
|
|
107
|
-
return block.text.length > 0 ? escapeXml(block.text) : EMPTY_TEXT_PLACEHOLDER;
|
|
108
|
-
case 'tool_use':
|
|
109
|
-
return '<historical_tool_use status="already_executed_do_not_repeat">\n' +
|
|
110
|
-
`<id>${escapeXml(block.id)}</id>\n` +
|
|
111
|
-
`<name>${escapeXml(block.name)}</name>\n` +
|
|
112
|
-
`<input_json>${escapeXml(stableJson(block.input))}</input_json>\n` +
|
|
113
|
-
'</historical_tool_use>';
|
|
114
|
-
case 'tool_result':
|
|
115
|
-
return `<historical_tool_result tool_use_id="${escapeXml(block.toolUseId)}" status="${block.isError ? 'error' : 'success'}">\n` +
|
|
116
|
-
`${block.content.length > 0 ? escapeXml(block.content) : EMPTY_TEXT_PLACEHOLDER}\n` +
|
|
117
|
-
'</historical_tool_result>';
|
|
118
|
-
case 'reasoning':
|
|
119
|
-
return REASONING_PLACEHOLDER;
|
|
120
|
-
case 'image':
|
|
121
|
-
case 'audio':
|
|
122
|
-
return `[${block.type} attachment omitted: mediaType=${escapeXml(block.mediaType)}; binary data not included]`;
|
|
123
|
-
case 'document': {
|
|
124
|
-
const name = block.name ? `; name=${escapeXml(block.name)}` : '';
|
|
125
|
-
return `[document attachment omitted: mediaType=${escapeXml(block.mediaType)}${name}; binary data not included]`;
|
|
126
|
-
}
|
|
127
|
-
default:
|
|
128
|
-
return assertNever(block);
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
function assertNever(value: never): never {
|
|
133
|
-
throw new Error(`Unsupported content block: ${String(value)}`);
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
function stableJson(value: unknown): string {
|
|
137
|
-
const ancestors = new Set<object>();
|
|
138
|
-
const visit = (candidate: unknown): string => {
|
|
139
|
-
if (candidate === null) return 'null';
|
|
140
|
-
if (typeof candidate === 'string' || typeof candidate === 'boolean') return JSON.stringify(candidate);
|
|
141
|
-
if (typeof candidate === 'number') return Number.isFinite(candidate) ? JSON.stringify(candidate) : JSON.stringify(String(candidate));
|
|
142
|
-
if (typeof candidate === 'bigint') return JSON.stringify(`${candidate.toString()}n`);
|
|
143
|
-
if (typeof candidate === 'undefined') return JSON.stringify('[undefined]');
|
|
144
|
-
if (typeof candidate === 'function' || typeof candidate === 'symbol') return JSON.stringify(`[${typeof candidate} omitted]`);
|
|
145
|
-
if (typeof candidate !== 'object') return JSON.stringify(String(candidate));
|
|
146
|
-
if (ancestors.has(candidate)) return JSON.stringify('[circular reference omitted]');
|
|
147
|
-
|
|
148
|
-
ancestors.add(candidate);
|
|
149
|
-
let result: string;
|
|
150
|
-
if (Array.isArray(candidate)) {
|
|
151
|
-
result = `[${candidate.map(visit).join(',')}]`;
|
|
152
|
-
} else {
|
|
153
|
-
const record = candidate as Record<string, unknown>;
|
|
154
|
-
result = `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${visit(record[key])}`).join(',')}}`;
|
|
155
|
-
}
|
|
156
|
-
ancestors.delete(candidate);
|
|
157
|
-
return result;
|
|
158
|
-
};
|
|
159
|
-
return visit(value);
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
function escapeXml(value: string): string {
|
|
163
|
-
return value
|
|
164
|
-
.replaceAll('&', '&')
|
|
165
|
-
.replaceAll('<', '<')
|
|
166
|
-
.replaceAll('>', '>')
|
|
167
|
-
.replaceAll('"', '"')
|
|
168
|
-
.replaceAll("'", ''');
|
|
169
|
-
}
|
|
170
|
-
|
|
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('"', '"')
|
|
254
|
-
.replaceAll(''', "'")
|
|
255
|
-
.replaceAll('<', '<')
|
|
256
|
-
.replaceAll('>', '>')
|
|
257
|
-
.replaceAll('&', '&');
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
export function parseClaudeRecord(line: string, state: ProtocolState): ProviderEvent[] {
|
|
261
|
-
let value: unknown;
|
|
262
|
-
try {
|
|
263
|
-
value = JSON.parse(line);
|
|
264
|
-
} catch {
|
|
265
|
-
throw new Error('Claude CLI emitted malformed stream-json');
|
|
266
|
-
}
|
|
267
|
-
if (!isRecord(value) || typeof value.type !== 'string') {
|
|
268
|
-
throw new Error('Claude CLI emitted malformed stream-json record');
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
// Informational envelope records can appear between protocol events on newer
|
|
272
|
-
// Claude CLI versions. They carry no assistant content or terminal state.
|
|
273
|
-
if (value.type === 'system' || value.type === 'rate_limit_event') return [];
|
|
274
|
-
if (value.type === 'assistant' || value.type === 'user') return parseMessageRecord(value);
|
|
275
|
-
if (value.type === 'stream_event') return parseStreamEvent(value.event, state);
|
|
276
|
-
if (value.type === 'result') return parseResult(value, state);
|
|
277
|
-
throw new Error(`Claude CLI emitted unsupported stream-json record: ${value.type}`);
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
function parseMessageRecord(record: Record<string, unknown>): ProviderEvent[] {
|
|
281
|
-
if (!isRecord(record.message) || !Array.isArray(record.message.content)) {
|
|
282
|
-
throw new Error('Claude CLI emitted malformed assistant record');
|
|
283
|
-
}
|
|
284
|
-
for (const block of record.message.content) {
|
|
285
|
-
if (!isRecord(block) || typeof block.type !== 'string') {
|
|
286
|
-
throw new Error('Claude CLI emitted malformed assistant content');
|
|
287
|
-
}
|
|
288
|
-
if (block.type === 'text' && typeof block.text !== 'string') {
|
|
289
|
-
throw new Error('Claude CLI emitted malformed assistant text');
|
|
290
|
-
}
|
|
291
|
-
// Thinking stays private, while tool_use/tool_result are internal CLI
|
|
292
|
-
// bookkeeping that Claude has already executed. Translating any of these
|
|
293
|
-
// records to ProviderEvents would either expose private reasoning or make
|
|
294
|
-
// the moxxy dispatcher execute the same operation a second time.
|
|
295
|
-
if (block.type !== 'text' && block.type !== 'thinking' && block.type !== 'tool_use' && block.type !== 'tool_result') {
|
|
296
|
-
throw new Error('Claude CLI emitted unsupported assistant content');
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
// Partial text arrives through stream_event records.
|
|
300
|
-
return [];
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
function parseStreamEvent(raw: unknown, state: ProtocolState): ProviderEvent[] {
|
|
304
|
-
if (!isRecord(raw) || typeof raw.type !== 'string') {
|
|
305
|
-
throw new Error('Claude CLI emitted malformed stream event');
|
|
306
|
-
}
|
|
307
|
-
switch (raw.type) {
|
|
308
|
-
case 'message_start':
|
|
309
|
-
state.started = true;
|
|
310
|
-
return [];
|
|
311
|
-
case 'content_block_start': {
|
|
312
|
-
if (!isRecord(raw.content_block) || typeof raw.content_block.type !== 'string') {
|
|
313
|
-
throw new Error('Claude CLI emitted malformed content block');
|
|
314
|
-
}
|
|
315
|
-
if (raw.content_block.type !== 'text' && raw.content_block.type !== 'thinking' && raw.content_block.type !== 'tool_use' && raw.content_block.type !== 'tool_result') {
|
|
316
|
-
throw new Error('Claude CLI emitted unsupported content block');
|
|
317
|
-
}
|
|
318
|
-
state.blockType = raw.content_block.type;
|
|
319
|
-
return [];
|
|
320
|
-
}
|
|
321
|
-
case 'content_block_delta': {
|
|
322
|
-
if (!isRecord(raw.delta) || typeof raw.delta.type !== 'string') {
|
|
323
|
-
throw new Error('Claude CLI emitted malformed content delta');
|
|
324
|
-
}
|
|
325
|
-
if (state.blockType !== 'text') {
|
|
326
|
-
// input_json_delta and tool result deltas describe work performed by the
|
|
327
|
-
// child and must not escape as moxxy tool events.
|
|
328
|
-
return [];
|
|
329
|
-
}
|
|
330
|
-
if (raw.delta.type !== 'text_delta' || typeof raw.delta.text !== 'string') {
|
|
331
|
-
throw new Error('Claude CLI emitted unsupported text delta');
|
|
332
|
-
}
|
|
333
|
-
return scanText(raw.delta.text, state);
|
|
334
|
-
}
|
|
335
|
-
case 'content_block_stop':
|
|
336
|
-
state.blockType = undefined;
|
|
337
|
-
return [];
|
|
338
|
-
case 'message_stop':
|
|
339
|
-
return [];
|
|
340
|
-
case 'message_delta': {
|
|
341
|
-
if (!isRecord(raw.delta)) throw new Error('Claude CLI emitted malformed message delta');
|
|
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
|
-
}
|
|
347
|
-
if (isRecord(raw.usage) && typeof raw.usage.output_tokens === 'number') {
|
|
348
|
-
state.outputTokens = raw.usage.output_tokens;
|
|
349
|
-
}
|
|
350
|
-
return [];
|
|
351
|
-
}
|
|
352
|
-
case 'ping':
|
|
353
|
-
return [];
|
|
354
|
-
default:
|
|
355
|
-
throw new Error(`Claude CLI emitted unsupported stream event: ${raw.type}`);
|
|
356
|
-
}
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
function parseResult(record: Record<string, unknown>, state: ProtocolState): ProviderEvent[] {
|
|
360
|
-
if (state.ended) throw new Error('Claude CLI emitted more than one terminal result');
|
|
361
|
-
state.ended = true;
|
|
362
|
-
if (record.is_error === true || record.subtype !== 'success') {
|
|
363
|
-
const message = typeof record.result === 'string' ? record.result : 'Claude CLI request failed';
|
|
364
|
-
return [{ type: 'error', message, retryable: false }];
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
if (isRecord(record.usage)) {
|
|
368
|
-
const input = record.usage.input_tokens;
|
|
369
|
-
const output = record.usage.output_tokens;
|
|
370
|
-
if (typeof input === 'number') state.inputTokens = input;
|
|
371
|
-
if (typeof output === 'number') state.outputTokens = output;
|
|
372
|
-
}
|
|
373
|
-
const usage = state.inputTokens !== undefined && state.outputTokens !== undefined
|
|
374
|
-
? { inputTokens: state.inputTokens, outputTokens: state.outputTokens }
|
|
375
|
-
: undefined;
|
|
376
|
-
return [...flushText(state), { type: 'message_end', stopReason: state.stopReason, ...(usage ? { usage } : {}) }];
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
function mapStopReason(value: unknown): ProtocolState['stopReason'] {
|
|
380
|
-
switch (value) {
|
|
381
|
-
case 'end_turn': return 'end_turn';
|
|
382
|
-
case 'max_tokens': return 'max_tokens';
|
|
383
|
-
case 'stop_sequence': return 'stop_sequence';
|
|
384
|
-
default: throw new Error(`Claude CLI emitted unsupported stop reason: ${String(value)}`);
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
389
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
390
|
-
}
|