@eserstack/ai 0.0.0-bootstrap.0 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +13 -0
- package/README.md +498 -0
- package/dist/adapters/ajan-bridge.d.ts +69 -0
- package/dist/adapters/ajan-bridge.js +661 -0
- package/dist/adapters/anthropic.d.ts +25 -0
- package/dist/adapters/anthropic.js +567 -0
- package/dist/adapters/claude-code.d.ts +28 -0
- package/dist/adapters/claude-code.js +462 -0
- package/dist/adapters/cli-shared.d.ts +36 -0
- package/dist/adapters/cli-shared.js +207 -0
- package/dist/adapters/gemini.d.ts +19 -0
- package/dist/adapters/gemini.js +91 -0
- package/dist/adapters/google-shared.d.ts +58 -0
- package/dist/adapters/google-shared.js +424 -0
- package/dist/adapters/kiro.d.ts +19 -0
- package/dist/adapters/kiro.js +195 -0
- package/dist/adapters/mod.d.ts +61 -0
- package/dist/adapters/mod.js +129 -0
- package/dist/adapters/ollama.d.ts +20 -0
- package/dist/adapters/ollama.js +226 -0
- package/dist/adapters/openai.d.ts +25 -0
- package/dist/adapters/openai.js +553 -0
- package/dist/adapters/opencode.d.ts +19 -0
- package/dist/adapters/opencode.js +158 -0
- package/dist/adapters/vertexai.d.ts +19 -0
- package/dist/adapters/vertexai.js +96 -0
- package/dist/batch.d.ts +35 -0
- package/dist/batch.js +2 -0
- package/dist/commands/ask.d.ts +30 -0
- package/dist/commands/ask.js +404 -0
- package/dist/commands/list.d.ts +2 -0
- package/dist/commands/list.js +35 -0
- package/dist/config.d.ts +21 -0
- package/dist/config.js +16 -0
- package/dist/content.d.ts +14 -0
- package/dist/content.js +103 -0
- package/dist/detect.d.ts +9 -0
- package/dist/detect.js +125 -0
- package/dist/errors.d.ts +62 -0
- package/dist/errors.js +135 -0
- package/dist/generation.d.ts +126 -0
- package/dist/generation.js +96 -0
- package/dist/main.d.ts +22 -0
- package/dist/main.js +42 -0
- package/dist/mod.d.ts +16 -0
- package/dist/mod.js +11 -0
- package/dist/model.d.ts +27 -0
- package/dist/model.js +12 -0
- package/dist/module.d.ts +10 -0
- package/dist/module.js +21 -0
- package/dist/package.json +74 -0
- package/dist/registry.d.ts +22 -0
- package/dist/registry.js +97 -0
- package/dist/streams/layers.d.ts +4 -0
- package/dist/streams/layers.js +33 -0
- package/dist/streams/mod.d.ts +2 -0
- package/dist/streams/mod.js +5 -0
- package/dist/streams/sources.d.ts +6 -0
- package/dist/streams/sources.js +76 -0
- package/dist/types.d.ts +79 -0
- package/dist/types.js +2 -0
- package/package.json +63 -1
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
import * as results from "@eserstack/primitives/results";
|
|
3
|
+
import * as generation from "../generation.js";
|
|
4
|
+
import * as errors from "../errors.js";
|
|
5
|
+
import * as cliShared from "./cli-shared.js";
|
|
6
|
+
// =============================================================================
|
|
7
|
+
// Claude Code Model
|
|
8
|
+
// =============================================================================
|
|
9
|
+
export class ClaudeCodeModel {
|
|
10
|
+
capabilities = [
|
|
11
|
+
"text_generation",
|
|
12
|
+
"streaming",
|
|
13
|
+
"tool_calling",
|
|
14
|
+
"structured_output",
|
|
15
|
+
];
|
|
16
|
+
provider = "claude-code";
|
|
17
|
+
modelId;
|
|
18
|
+
binary;
|
|
19
|
+
config;
|
|
20
|
+
constructor(binary, cfg) {
|
|
21
|
+
this.binary = binary;
|
|
22
|
+
this.config = cfg;
|
|
23
|
+
this.modelId = cfg.model;
|
|
24
|
+
}
|
|
25
|
+
async generateText(options, signal) {
|
|
26
|
+
let args;
|
|
27
|
+
try {
|
|
28
|
+
args = buildArgs(this.config, options, "json");
|
|
29
|
+
}
|
|
30
|
+
catch (err) {
|
|
31
|
+
// buildArgs throws a BadRequestError for a json_schema format without an
|
|
32
|
+
// object schema; anything else is a bug and propagates.
|
|
33
|
+
if (err instanceof errors.BadRequestError) {
|
|
34
|
+
return results.fail(err);
|
|
35
|
+
}
|
|
36
|
+
throw err;
|
|
37
|
+
}
|
|
38
|
+
const prompt = cliShared.formatMessagesAsText(options.messages, options.system);
|
|
39
|
+
// Pipe prompt via stdin to avoid E2BIG on large inputs (ARG_MAX ~256KB).
|
|
40
|
+
// Claude Code reads from stdin when no -p flag is provided.
|
|
41
|
+
const process = cliShared.spawnCliProcess(this.binary, args, {
|
|
42
|
+
signal,
|
|
43
|
+
stdinData: prompt,
|
|
44
|
+
// The ACP path honours properties.cwd; this one silently did not, so the
|
|
45
|
+
// same config produced an agent rooted at the project on one path and at
|
|
46
|
+
// whatever directory the caller happened to be in on the other. Undefined
|
|
47
|
+
// still means "inherit", which is the previous behaviour when unset.
|
|
48
|
+
cwd: this.config.properties?.["cwd"],
|
|
49
|
+
});
|
|
50
|
+
const stderrPromise = cliShared.captureStderr(process.stderr);
|
|
51
|
+
try {
|
|
52
|
+
const chunks = [];
|
|
53
|
+
const decoder = new TextDecoder();
|
|
54
|
+
for await (const chunk of process.stdout) {
|
|
55
|
+
chunks.push(decoder.decode(chunk, { stream: true }));
|
|
56
|
+
}
|
|
57
|
+
const exit = await process.waitForExit();
|
|
58
|
+
const stderr = await stderrPromise;
|
|
59
|
+
const exitError = cliShared.classifyExitCode("claude-code", exit.code, stderr);
|
|
60
|
+
if (exitError !== null) {
|
|
61
|
+
return results.fail(exitError);
|
|
62
|
+
}
|
|
63
|
+
const rawOutput = chunks.join("");
|
|
64
|
+
return results.ok(parseJsonResult(rawOutput, this.modelId));
|
|
65
|
+
}
|
|
66
|
+
finally {
|
|
67
|
+
await cliShared.stopCliProcess(process, stderrPromise);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
async *streamText(options, signal) {
|
|
71
|
+
// A --json-schema reply arrives whole, in the CLI's final result event, so
|
|
72
|
+
// it is read with the json output format and yielded in one piece.
|
|
73
|
+
if (options.responseFormat?.type === "json_schema") {
|
|
74
|
+
yield* this.#streamStructuredReply(options, signal);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
// Configurable via properties.streamFormat: "text" (default) or "stream-json"
|
|
78
|
+
// - "text": true byte-level streaming, each stdout chunk → content_delta
|
|
79
|
+
// - "stream-json": structured JSONL events (tool calls, usage stats)
|
|
80
|
+
const streamFormat = this.config.properties?.["streamFormat"] ??
|
|
81
|
+
"text";
|
|
82
|
+
const args = buildArgs(this.config, options, streamFormat);
|
|
83
|
+
const prompt = cliShared.formatMessagesAsText(options.messages, options.system);
|
|
84
|
+
// Pipe prompt via stdin to avoid E2BIG on large inputs.
|
|
85
|
+
const process = cliShared.spawnCliProcess(this.binary, args, {
|
|
86
|
+
signal,
|
|
87
|
+
stdinData: prompt,
|
|
88
|
+
// The ACP path honours properties.cwd; this one silently did not, so the
|
|
89
|
+
// same config produced an agent rooted at the project on one path and at
|
|
90
|
+
// whatever directory the caller happened to be in on the other. Undefined
|
|
91
|
+
// still means "inherit", which is the previous behaviour when unset.
|
|
92
|
+
cwd: this.config.properties?.["cwd"],
|
|
93
|
+
});
|
|
94
|
+
const stderrPromise = cliShared.captureStderr(process.stderr);
|
|
95
|
+
try {
|
|
96
|
+
if (streamFormat === "stream-json") {
|
|
97
|
+
yield* this.#streamJsonEvents(process, stderrPromise);
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
yield* this.#streamRawText(process, stderrPromise);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
catch (err) {
|
|
104
|
+
if (err instanceof errors.AiError) {
|
|
105
|
+
yield { kind: "error", error: err };
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
yield {
|
|
109
|
+
kind: "error",
|
|
110
|
+
error: new errors.AiError(err instanceof Error ? err.message : String(err), {
|
|
111
|
+
provider: "claude-code",
|
|
112
|
+
cause: err instanceof Error ? err : undefined,
|
|
113
|
+
}),
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
finally {
|
|
118
|
+
// Also reached when the consumer stops reading early.
|
|
119
|
+
await cliShared.stopCliProcess(process, stderrPromise);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
async *#streamStructuredReply(options, signal) {
|
|
123
|
+
const result = await this.generateText(options, signal);
|
|
124
|
+
if (results.isFail(result)) {
|
|
125
|
+
yield { kind: "error", error: result.error };
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
for (const block of result.value.content) {
|
|
129
|
+
if (block.kind === "text" && block.text !== "") {
|
|
130
|
+
yield { kind: "content_delta", textDelta: block.text };
|
|
131
|
+
}
|
|
132
|
+
else if (block.kind === "tool_call") {
|
|
133
|
+
yield { kind: "tool_call_delta", toolCall: block.toolCall };
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
yield {
|
|
137
|
+
kind: "message_done",
|
|
138
|
+
stopReason: result.value.stopReason,
|
|
139
|
+
usage: result.value.usage,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
async *#streamRawText(process, stderrPromise) {
|
|
143
|
+
const decoder = new TextDecoder();
|
|
144
|
+
const reader = process.stdout.getReader();
|
|
145
|
+
try {
|
|
146
|
+
let readResult = await reader.read();
|
|
147
|
+
while (readResult.done !== true) {
|
|
148
|
+
const text = decoder.decode(readResult.value, { stream: true });
|
|
149
|
+
if (text.length > 0) {
|
|
150
|
+
yield { kind: "content_delta", textDelta: text };
|
|
151
|
+
}
|
|
152
|
+
// Reads stay sequential: each chunk is yielded in order before the
|
|
153
|
+
// next one is requested.
|
|
154
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
155
|
+
readResult = await reader.read();
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
finally {
|
|
159
|
+
reader.releaseLock();
|
|
160
|
+
}
|
|
161
|
+
const exit = await process.waitForExit();
|
|
162
|
+
const stderr = await stderrPromise;
|
|
163
|
+
const exitError = cliShared.classifyExitCode("claude-code", exit.code, stderr);
|
|
164
|
+
if (exitError !== null) {
|
|
165
|
+
yield { kind: "error", error: exitError };
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
yield {
|
|
169
|
+
kind: "message_done",
|
|
170
|
+
stopReason: "end_turn",
|
|
171
|
+
usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
async *#streamJsonEvents(process, stderrPromise) {
|
|
176
|
+
for await (const event of cliShared.parseJsonlStream(process.stdout)) {
|
|
177
|
+
const streamEvent = mapStreamEvent(event);
|
|
178
|
+
if (streamEvent !== null) {
|
|
179
|
+
yield streamEvent;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
const exit = await process.waitForExit();
|
|
183
|
+
const stderr = await stderrPromise;
|
|
184
|
+
const exitError = cliShared.classifyExitCode("claude-code", exit.code, stderr);
|
|
185
|
+
if (exitError !== null) {
|
|
186
|
+
yield { kind: "error", error: exitError };
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
close() {
|
|
190
|
+
return Promise.resolve();
|
|
191
|
+
}
|
|
192
|
+
getRawClient() {
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
// =============================================================================
|
|
197
|
+
// Factory
|
|
198
|
+
// =============================================================================
|
|
199
|
+
export const claudeCodeFactory = {
|
|
200
|
+
provider: "claude-code",
|
|
201
|
+
createModel: async (cfg) => {
|
|
202
|
+
const binary = await cliShared.resolveBinary("claude", cfg);
|
|
203
|
+
return new ClaudeCodeModel(binary, cfg);
|
|
204
|
+
},
|
|
205
|
+
};
|
|
206
|
+
// =============================================================================
|
|
207
|
+
// Internal Helpers
|
|
208
|
+
// =============================================================================
|
|
209
|
+
/**
|
|
210
|
+
* Builds the claude CLI arguments for one request. Exported for tests.
|
|
211
|
+
*
|
|
212
|
+
* @throws {errors.BadRequestError} for a `json_schema` format without an
|
|
213
|
+
* object `jsonSchema`.
|
|
214
|
+
*/
|
|
215
|
+
export const buildArgs = (cfg, options, outputFormat) => {
|
|
216
|
+
const args = [];
|
|
217
|
+
// "text" format streams raw text to stdout — no --output-format needed (it's the default)
|
|
218
|
+
if (outputFormat !== "text") {
|
|
219
|
+
args.push("--output-format", outputFormat);
|
|
220
|
+
}
|
|
221
|
+
// stream-json requires --verbose in Claude Code CLI
|
|
222
|
+
if (outputFormat === "stream-json") {
|
|
223
|
+
args.push("--verbose");
|
|
224
|
+
}
|
|
225
|
+
// Only when set. Pushed unconditionally, an empty model produced
|
|
226
|
+
// `claude --model ` with a dangling flag, which the CLI rejects with exit 1 --
|
|
227
|
+
// so a caller that legitimately wanted the CLI's own default could not express
|
|
228
|
+
// it, and got a spawn failure instead.
|
|
229
|
+
if (cfg.model !== "") {
|
|
230
|
+
args.push("--model", cfg.model);
|
|
231
|
+
}
|
|
232
|
+
// Only limit turns if explicitly configured
|
|
233
|
+
const maxTurns = cfg.properties?.["maxTurns"];
|
|
234
|
+
if (maxTurns !== undefined) {
|
|
235
|
+
args.push("--max-turns", String(maxTurns));
|
|
236
|
+
}
|
|
237
|
+
// Note: claude CLI does not support --max-tokens; token limits are model-level
|
|
238
|
+
const allowedTools = cfg.properties?.["allowedTools"];
|
|
239
|
+
if (allowedTools !== undefined) {
|
|
240
|
+
for (const tool of allowedTools) {
|
|
241
|
+
args.push("--allowedTools", tool);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
// Pass through additional CLI flags from properties
|
|
245
|
+
const extraArgs = cfg.properties?.["args"];
|
|
246
|
+
if (extraArgs !== undefined) {
|
|
247
|
+
args.push(...extraArgs);
|
|
248
|
+
}
|
|
249
|
+
// The CLI's --effort takes the same five levels as GenerateTextOptions.
|
|
250
|
+
if (options.effort !== undefined) {
|
|
251
|
+
args.push("--effort", options.effort);
|
|
252
|
+
}
|
|
253
|
+
const schema = jsonSchemaArg(options.responseFormat);
|
|
254
|
+
if (schema !== null) {
|
|
255
|
+
args.push("--json-schema", schema);
|
|
256
|
+
}
|
|
257
|
+
return args;
|
|
258
|
+
};
|
|
259
|
+
/**
|
|
260
|
+
* Returns a json_schema format's schema as the CLI's `--json-schema` value, or
|
|
261
|
+
* null when there is none to send. The CLI has no JSON mode without a schema,
|
|
262
|
+
* so `json_object` and `text` send nothing, as on the `anthropic` provider.
|
|
263
|
+
*
|
|
264
|
+
* @throws {errors.BadRequestError} for a `json_schema` format without an
|
|
265
|
+
* object `jsonSchema`.
|
|
266
|
+
*/
|
|
267
|
+
const jsonSchemaArg = (responseFormat) => {
|
|
268
|
+
if (responseFormat?.type !== "json_schema") {
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
return JSON.stringify(generation.requireJsonSchema(responseFormat, "claude-code"));
|
|
272
|
+
};
|
|
273
|
+
export const parseJsonResult = (rawOutput, modelId) => {
|
|
274
|
+
const trimmed = rawOutput.trim();
|
|
275
|
+
const plain = (text) => ({
|
|
276
|
+
content: [{ kind: "text", text }],
|
|
277
|
+
stopReason: "end_turn",
|
|
278
|
+
usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
|
|
279
|
+
modelId,
|
|
280
|
+
});
|
|
281
|
+
// 1. A single JSON value — either a result object or (Claude Code CLI v2
|
|
282
|
+
// `--output-format json`) an ARRAY of stream events
|
|
283
|
+
// [{type:"system"}, {type:"assistant"}, …, {type:"result", result}].
|
|
284
|
+
try {
|
|
285
|
+
const parsed = JSON.parse(trimmed);
|
|
286
|
+
return Array.isArray(parsed)
|
|
287
|
+
? mapResultFromArray(parsed, modelId)
|
|
288
|
+
: mapResultFromJson(parsed, modelId);
|
|
289
|
+
}
|
|
290
|
+
catch {
|
|
291
|
+
// not a single JSON value — fall through
|
|
292
|
+
}
|
|
293
|
+
// 2. JSONL: one JSON event per line (other CLI versions stream this way).
|
|
294
|
+
const events = [];
|
|
295
|
+
for (const line of trimmed.split(/\r?\n/)) {
|
|
296
|
+
const l = line.trim();
|
|
297
|
+
if (l.length === 0)
|
|
298
|
+
continue;
|
|
299
|
+
try {
|
|
300
|
+
events.push(JSON.parse(l));
|
|
301
|
+
}
|
|
302
|
+
catch {
|
|
303
|
+
// skip non-JSON line
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
if (events.length > 0) {
|
|
307
|
+
return mapResultFromArray(events, modelId);
|
|
308
|
+
}
|
|
309
|
+
// 3. Not JSON at all → the model printed the bare line; use it. But never echo
|
|
310
|
+
// a JSON-looking blob back as a commit message (that's the bug we guard).
|
|
311
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
312
|
+
return plain("");
|
|
313
|
+
}
|
|
314
|
+
return plain(trimmed);
|
|
315
|
+
};
|
|
316
|
+
/**
|
|
317
|
+
* Reduce the Claude Code v2 event array to a single result. Prefers the
|
|
318
|
+
* `{type:"result"}` event's `structured_output` (the reply to `--json-schema`)
|
|
319
|
+
* or `result` field (the canonical final text), then the last
|
|
320
|
+
* `{type:"assistant"}` message, delegating to {@link mapResultFromJson} for the
|
|
321
|
+
* actual mapping.
|
|
322
|
+
*/
|
|
323
|
+
const mapResultFromArray = (events, modelId) => {
|
|
324
|
+
const isObj = (e) => e !== null && typeof e === "object";
|
|
325
|
+
const resultEvent = events.find((e) => isObj(e) &&
|
|
326
|
+
e["type"] === "result" &&
|
|
327
|
+
(e["result"] !== undefined || e["structured_output"] !== undefined));
|
|
328
|
+
if (resultEvent !== undefined) {
|
|
329
|
+
return mapResultFromJson(resultEvent, modelId);
|
|
330
|
+
}
|
|
331
|
+
for (let i = events.length - 1; i >= 0; i--) {
|
|
332
|
+
const e = events[i];
|
|
333
|
+
if (isObj(e) && e["type"] === "assistant" && isObj(e["message"])) {
|
|
334
|
+
return mapResultFromJson(e, modelId);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
// Nothing recognizable — return empty text rather than the raw transcript.
|
|
338
|
+
return {
|
|
339
|
+
content: [{ kind: "text", text: "" }],
|
|
340
|
+
stopReason: "end_turn",
|
|
341
|
+
usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
|
|
342
|
+
modelId,
|
|
343
|
+
};
|
|
344
|
+
};
|
|
345
|
+
const mapResultFromJson = (
|
|
346
|
+
// The response is untyped vendor JSON; only the mapped fields are read.
|
|
347
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
348
|
+
parsed, modelId) => {
|
|
349
|
+
const contentBlocks = [];
|
|
350
|
+
// With --json-schema, the reply is the result event's structured_output, not
|
|
351
|
+
// its result field. Otherwise Claude Code JSON output has { result: "text" }
|
|
352
|
+
// or { type: "result", result: "text" }.
|
|
353
|
+
if (parsed.structured_output !== undefined &&
|
|
354
|
+
parsed.structured_output !== null) {
|
|
355
|
+
contentBlocks.push({
|
|
356
|
+
kind: "text",
|
|
357
|
+
text: JSON.stringify(parsed.structured_output),
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
else if (parsed.result !== undefined) {
|
|
361
|
+
contentBlocks.push({ kind: "text", text: String(parsed.result) });
|
|
362
|
+
}
|
|
363
|
+
else if (parsed.message?.content !== undefined) {
|
|
364
|
+
for (const block of parsed.message.content) {
|
|
365
|
+
if (block.type === "text") {
|
|
366
|
+
contentBlocks.push({ kind: "text", text: block.text });
|
|
367
|
+
}
|
|
368
|
+
else if (block.type === "tool_use") {
|
|
369
|
+
contentBlocks.push({
|
|
370
|
+
kind: "tool_call",
|
|
371
|
+
toolCall: {
|
|
372
|
+
id: block.id ?? block.name,
|
|
373
|
+
name: block.name,
|
|
374
|
+
arguments: block.input ?? {},
|
|
375
|
+
},
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
else if (typeof parsed === "string") {
|
|
381
|
+
contentBlocks.push({ kind: "text", text: parsed });
|
|
382
|
+
}
|
|
383
|
+
if (contentBlocks.length === 0) {
|
|
384
|
+
// Unrecognized shape: emit empty text rather than dumping the raw JSON as
|
|
385
|
+
// if it were the model's answer (that produced the JSON-as-commit-msg bug).
|
|
386
|
+
contentBlocks.push({ kind: "text", text: "" });
|
|
387
|
+
}
|
|
388
|
+
return {
|
|
389
|
+
content: contentBlocks,
|
|
390
|
+
stopReason: mapStopReason(parsed.stop_reason ?? parsed.message?.stop_reason),
|
|
391
|
+
usage: {
|
|
392
|
+
inputTokens: parsed.usage?.input_tokens ?? 0,
|
|
393
|
+
outputTokens: parsed.usage?.output_tokens ?? 0,
|
|
394
|
+
totalTokens: (parsed.usage?.input_tokens ?? 0) + (parsed.usage?.output_tokens ?? 0),
|
|
395
|
+
},
|
|
396
|
+
modelId,
|
|
397
|
+
rawResponse: parsed,
|
|
398
|
+
};
|
|
399
|
+
};
|
|
400
|
+
/**
|
|
401
|
+
* Maps the stop reason the CLI reports. A declined request stays a refusal, so
|
|
402
|
+
* a caller can tell it from an answer.
|
|
403
|
+
*/
|
|
404
|
+
const mapStopReason = (reason) => {
|
|
405
|
+
if (reason === "tool_use") {
|
|
406
|
+
return "tool_use";
|
|
407
|
+
}
|
|
408
|
+
if (reason === "refusal") {
|
|
409
|
+
return "refusal";
|
|
410
|
+
}
|
|
411
|
+
return "end_turn";
|
|
412
|
+
};
|
|
413
|
+
const mapStreamEvent = (event) => {
|
|
414
|
+
if (event === null || typeof event !== "object") {
|
|
415
|
+
return null;
|
|
416
|
+
}
|
|
417
|
+
// Stream events are untyped JSON; each field is checked before use.
|
|
418
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
419
|
+
const obj = event;
|
|
420
|
+
// Claude Code stream-json events
|
|
421
|
+
if (obj.type === "assistant") {
|
|
422
|
+
// Message content event
|
|
423
|
+
if (obj.message?.content !== undefined) {
|
|
424
|
+
for (const block of obj.message.content) {
|
|
425
|
+
if (block.type === "text") {
|
|
426
|
+
return { kind: "content_delta", textDelta: block.text };
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
return null;
|
|
431
|
+
}
|
|
432
|
+
if (obj.type === "content_block_delta") {
|
|
433
|
+
if (obj.delta?.type === "text_delta") {
|
|
434
|
+
return { kind: "content_delta", textDelta: obj.delta.text };
|
|
435
|
+
}
|
|
436
|
+
return null;
|
|
437
|
+
}
|
|
438
|
+
if (obj.type === "result") {
|
|
439
|
+
return {
|
|
440
|
+
kind: "message_done",
|
|
441
|
+
stopReason: obj.subtype === "tool_use"
|
|
442
|
+
? "tool_use"
|
|
443
|
+
: mapStopReason(obj.stop_reason),
|
|
444
|
+
usage: {
|
|
445
|
+
inputTokens: obj.usage?.input_tokens ?? 0,
|
|
446
|
+
outputTokens: obj.usage?.output_tokens ?? 0,
|
|
447
|
+
totalTokens: (obj.usage?.input_tokens ?? 0) + (obj.usage?.output_tokens ?? 0),
|
|
448
|
+
},
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
if (obj.type === "error") {
|
|
452
|
+
return {
|
|
453
|
+
kind: "error",
|
|
454
|
+
error: new errors.AiError(obj.error?.message ?? "Unknown Claude Code error", { provider: "claude-code" }),
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
// Generic text content
|
|
458
|
+
if (obj.content !== undefined && typeof obj.content === "string") {
|
|
459
|
+
return { kind: "content_delta", textDelta: obj.content };
|
|
460
|
+
}
|
|
461
|
+
return null;
|
|
462
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type * as config from "../config.ts";
|
|
2
|
+
import type * as generation from "../generation.ts";
|
|
3
|
+
import type * as types from "../types.ts";
|
|
4
|
+
import * as errors from "../errors.ts";
|
|
5
|
+
export declare const resolveBinary: (defaultName: string, cfg: config.ResolvedConfigTarget) => Promise<string>;
|
|
6
|
+
export type CliProcess = {
|
|
7
|
+
readonly stdout: ReadableStream<Uint8Array>;
|
|
8
|
+
readonly stderr: ReadableStream<Uint8Array>;
|
|
9
|
+
readonly waitForExit: () => Promise<{
|
|
10
|
+
readonly code: number;
|
|
11
|
+
readonly success: boolean;
|
|
12
|
+
}>;
|
|
13
|
+
/** Sends the signal (SIGTERM by default); does nothing once it has exited. */
|
|
14
|
+
readonly kill: (signal?: string) => void;
|
|
15
|
+
};
|
|
16
|
+
export type SpawnOptions = {
|
|
17
|
+
readonly cwd?: string;
|
|
18
|
+
readonly env?: Record<string, string>;
|
|
19
|
+
readonly signal?: AbortSignal;
|
|
20
|
+
/** Data to pipe to stdin. When set, stdin is piped and closed after writing. */
|
|
21
|
+
readonly stdinData?: string;
|
|
22
|
+
};
|
|
23
|
+
export declare const spawnCliProcess: (binary: string, args: readonly string[], options?: SpawnOptions) => CliProcess;
|
|
24
|
+
/**
|
|
25
|
+
* Ends a CLI process when the caller is done with it: kills it if it is still
|
|
26
|
+
* running, then waits for its stderr capture to end, which happens when the
|
|
27
|
+
* process exits. Call it from `finally` in the scope that spawned the process.
|
|
28
|
+
* A stream whose consumer stops early otherwise leaves the CLI running, blocked
|
|
29
|
+
* on a stdout pipe that nobody reads.
|
|
30
|
+
*/
|
|
31
|
+
export declare const stopCliProcess: (process: CliProcess, stderrPromise: Promise<string>) => Promise<void>;
|
|
32
|
+
export declare function parseJsonlStream(stdout: ReadableStream<Uint8Array>): AsyncIterable<unknown>;
|
|
33
|
+
export declare const parseTextOutput: (stdout: ReadableStream<Uint8Array>, modelId: string) => Promise<generation.GenerateTextResult>;
|
|
34
|
+
export declare const captureStderr: (stderr: ReadableStream<Uint8Array>) => Promise<string>;
|
|
35
|
+
export declare const classifyExitCode: (provider: string, code: number, stderr: string) => errors.AiError | null;
|
|
36
|
+
export declare const formatMessagesAsText: (messages: readonly types.Message[], system?: string) => string;
|