@gullabs/claude-cli 0.2.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 ADDED
@@ -0,0 +1,191 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other
42
+ transformations represent, as a whole, an original work of authorship.
43
+ For the purposes of this License, Derivative Works shall not include
44
+ works that remain separable from, or merely link (or bind by name)
45
+ to the interfaces of, the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as "Not a
57
+ Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any patent
81
+ claim embodied in the Work constitutes direct or contributory patent
82
+ infringement, then any patent licenses granted to You under this
83
+ License for that Work shall terminate as of the date such litigation
84
+ is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the
87
+ Work or Derivative Works thereof in any medium, with or without
88
+ modifications, and in Source or Object form, provided that You
89
+ meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative
92
+ Works a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works
98
+ that You distribute, all copyright, patent, trademark, and
99
+ attribution notices from the Source form of the Work,
100
+ excluding those notices that do not pertain to any part of
101
+ the Derivative Works; and
102
+
103
+ (d) If the Work includes a "NOTICE" text file as part of its
104
+ distribution, You must include a readable copy of the
105
+ attribution notices contained within such NOTICE file, in
106
+ at least one of the following places: within a NOTICE text
107
+ file distributed as part of the Derivative Works; within
108
+ the Source form or documentation, if provided along with the
109
+ Derivative Works; or, within a display generated by the
110
+ Derivative Works, if and wherever such third-party notices
111
+ normally appear. The contents of the NOTICE file are for
112
+ informational purposes only and do not modify the License.
113
+ You may add Your own attribution notices within Derivative
114
+ Works that You distribute, alongside or in addition to the
115
+ NOTICE text from the Work, provided that such additional
116
+ attribution notices cannot be construed as modifying the
117
+ License.
118
+
119
+ You may add Your own license statement for Your modifications and
120
+ may provide additional grant of rights to use, reproduce, modify,
121
+ and distribute Your modifications as a separate agreement from
122
+ this License.
123
+
124
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
125
+ any Contribution intentionally submitted for inclusion in the Work
126
+ by You to the Licensor shall be under the terms and conditions of
127
+ this License, without any additional terms or conditions.
128
+ Notwithstanding the above, nothing herein shall supersede or modify
129
+ the terms of any separate license agreement you may have executed
130
+ with Licensor regarding such Contributions.
131
+
132
+ 6. Trademarks. This License does not grant permission to use the trade
133
+ names, trademarks, service marks, or product names of the Licensor,
134
+ except as required for reasonable and customary use in describing the
135
+ origin of the Work and reproducing the content of the NOTICE file.
136
+
137
+ 7. Disclaimer of Warranty. Unless required by applicable law or
138
+ agreed to in writing, Licensor provides the Work (and each
139
+ Contributor provides its Contributions) on an "AS IS" BASIS,
140
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
141
+ implied, including, without limitation, any warranties or conditions
142
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
143
+ PARTICULAR PURPOSE. You are solely responsible for determining the
144
+ appropriateness of using or reproducing the Work and assume any
145
+ risks associated with Your exercise of permissions under this License.
146
+
147
+ 8. Limitation of Liability. In no event and under no legal theory,
148
+ whether in tort (including negligence), contract, or otherwise,
149
+ unless required by applicable law (such as deliberate and grossly
150
+ negligent acts) or agreed to in writing, shall any Contributor be
151
+ liable to You for damages, including any direct, indirect, special,
152
+ incidental, or exemplary damages of any character arising as a
153
+ result of this License or out of the use or inability to use the
154
+ Work (including but not limited to damages for loss of goodwill,
155
+ work stoppage, computer failure or malfunction, or all other
156
+ commercial damages or losses), even if such Contributor has been
157
+ advised of the possibility of such damages.
158
+
159
+ 9. Accepting Warranty or Additional Liability. While redistributing
160
+ the Work or Derivative Works thereof, You may choose to offer,
161
+ and charge a fee for, acceptance of support, warranty, indemnity,
162
+ or other liability obligations and/or rights consistent with this
163
+ License. However, in accepting such obligations, You may offer only
164
+ conditions that are consistent with this terms and conditions of this
165
+ License, and may charge a fee for such acceptance only in a manner
166
+ consistent with the terms of this License.
167
+
168
+ END OF TERMS AND CONDITIONS
169
+
170
+ APPENDIX: How to apply the Apache License to your work.
171
+
172
+ To apply the Apache License to your work, attach the following
173
+ boilerplate notice, with the fields enclosed by brackets "[]"
174
+ replaced with your own identifying information. (Don't include
175
+ the brackets!) The text should be enclosed in the appropriate
176
+ comment syntax for the file format in please. Also attach a copy of
177
+ this License to your work.
178
+
179
+ Copyright 2026 Gul Labs
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,85 @@
1
+ # @gullabs/claude-cli
2
+
3
+ > **DEV-ONLY.** This package shells out to a locally-authenticated `claude`
4
+ > CLI session. It is impossible to run in production by construction (no
5
+ > CI/serverless environment has an interactive CLI login). Never use this as
6
+ > a fallback for an API provider — it exists purely to make iterating on long
7
+ > Temporal workflows free during development.
8
+
9
+ `@gullabs/claude-cli` is a text-only, pure `ProviderAdapter` for
10
+ [`@gullabs/core`](../core) that routes LLM calls through the `claude`
11
+ (Claude Code) CLI instead of an API key. Because the CLI owns its own
12
+ OAuth/keychain-backed session, calls made through this adapter cost $0 in API
13
+ spend — the CLI reports its own cost for observability, but that number is
14
+ never fed into `@gullabs/core`'s cost engine (`Cost.microUsd` naturally
15
+ resolves to `null` because these models are unpriced).
16
+
17
+ ## Install
18
+
19
+ ```sh
20
+ pnpm add -D @gullabs/claude-cli
21
+ ```
22
+
23
+ ## Key exports
24
+
25
+ | Export | Kind | Description |
26
+ | --------------------------- | -------- | --------------------------------------------------------------- |
27
+ | `claudeCliAdapter` | function | Creates the `ProviderAdapter` (`id: 'claude-cli'`). |
28
+ | `ClaudeCliAdapterOptions` | type | `{ runner?, claudePath?, maxConcurrency? }`. |
29
+ | `buildClaudeCliRunner` | function | The real `node:child_process`-backed `ClaudeCliRunner` factory. |
30
+ | `ClaudeCliRunner` | type | The process-execution seam; inject a fake in tests. |
31
+ | `claudeCliModelDescriptors` | value | `ModelDescriptor[]` for the 4 supported model ids. |
32
+ | `claudeCliRegistry` | value | `ModelRegistry` built from `claudeCliModelDescriptors`. |
33
+
34
+ ## Quick example
35
+
36
+ ```ts
37
+ import { claudeCliAdapter } from '@gullabs/claude-cli'
38
+ import { createClient } from '@gullabs/core'
39
+
40
+ const client = createClient({ adapters: [claudeCliAdapter()] })
41
+
42
+ const result = await client.generate(
43
+ {
44
+ model: 'claude-haiku-4-5-20251001',
45
+ messages: [{ role: 'user', parts: [{ kind: 'text', text: 'Hello' }] }],
46
+ },
47
+ { auth: { cliSession: true } },
48
+ )
49
+ ```
50
+
51
+ Auth is always `{ cliSession: true }` — never an API key. Passing anything
52
+ else throws `LlmError({ kind: 'invalid_auth' })` explaining that these
53
+ dev-only providers route through a locally-authenticated CLI session, not an
54
+ API key.
55
+
56
+ ## `--safe-mode`, never `--bare`
57
+
58
+ The adapter always invokes the CLI with `--safe-mode`. It never passes
59
+ `--bare`, because `--bare` disables OAuth/keychain auth entirely — which
60
+ would break subscription-based Claude Code auth and defeat the entire point
61
+ of this package (working with **zero** API-key configuration). The full
62
+ invariant argv (never caller-configurable) is:
63
+
64
+ ```
65
+ -p --output-format json --safe-mode --tools "" --disable-slash-commands --no-session-persistence
66
+ ```
67
+
68
+ `--model`, `--effort`, `--system-prompt`, and `--json-schema` are appended
69
+ from the request when applicable; the prompt itself is always sent over
70
+ stdin, never as a positional argv entry.
71
+
72
+ ## Concurrency
73
+
74
+ The adapter caps concurrent `claude` CLI invocations with an internal
75
+ semaphore, defaulting to `maxConcurrency: 2`. Override via
76
+ `claudeCliAdapter({ maxConcurrency: N })`.
77
+
78
+ ## Supported models
79
+
80
+ `claude-fable-5`, `claude-opus-4-8`, `claude-sonnet-5`,
81
+ `claude-haiku-4-5-20251001`. Each accepts an optional
82
+ `{ reasoning: { effort }, timeoutMs }` config — no sampling knobs
83
+ (`temperature`/`topP`/`topK`/`maxOutputTokens`/`stopSequences`) are accepted;
84
+ the CLI does not support tuning any of them, and the strict config schema
85
+ rejects unknown keys.
package/dist/index.cjs ADDED
@@ -0,0 +1,407 @@
1
+ 'use strict';
2
+
3
+ var promises = require('fs/promises');
4
+ var os = require('os');
5
+ var path = require('path');
6
+ var core = require('@gullabs/core');
7
+ var child_process = require('child_process');
8
+ var zod = require('zod');
9
+
10
+ // src/adapter.ts
11
+ function buildClaudeCliRunner(claudePath = "claude") {
12
+ return {
13
+ run(args, input, opts) {
14
+ return new Promise((resolve, reject) => {
15
+ if (opts.signal?.aborted === true) {
16
+ const err = new Error("claude-cli call aborted");
17
+ err.name = "AbortError";
18
+ reject(err);
19
+ return;
20
+ }
21
+ const child = child_process.spawn(claudePath, args, {
22
+ cwd: opts.cwd,
23
+ stdio: ["pipe", "pipe", "pipe"]
24
+ });
25
+ let stdout = "";
26
+ let stderr = "";
27
+ let settled = false;
28
+ let pendingError;
29
+ let timeoutHandle;
30
+ let killTimeoutHandle;
31
+ const cleanupTimers = () => {
32
+ if (timeoutHandle !== void 0) clearTimeout(timeoutHandle);
33
+ if (killTimeoutHandle !== void 0) clearTimeout(killTimeoutHandle);
34
+ };
35
+ const cleanup = () => {
36
+ cleanupTimers();
37
+ if (opts.signal !== void 0) {
38
+ opts.signal.removeEventListener("abort", onAbort);
39
+ }
40
+ };
41
+ const killChild = () => {
42
+ child.kill("SIGTERM");
43
+ killTimeoutHandle = setTimeout(() => {
44
+ child.kill("SIGKILL");
45
+ }, 5e3);
46
+ };
47
+ const beginReject = (err) => {
48
+ if (settled || pendingError !== void 0) return;
49
+ pendingError = err;
50
+ cleanupTimers();
51
+ killChild();
52
+ };
53
+ const onAbort = () => {
54
+ const err = new Error("claude-cli call aborted");
55
+ err.name = "AbortError";
56
+ beginReject(err);
57
+ };
58
+ if (opts.signal !== void 0) {
59
+ opts.signal.addEventListener("abort", onAbort, { once: true });
60
+ }
61
+ if (opts.timeoutMs !== void 0) {
62
+ timeoutHandle = setTimeout(() => {
63
+ const err = new Error(`claude-cli call exceeded ${opts.timeoutMs}ms timeout`);
64
+ err.name = "TimeoutError";
65
+ beginReject(err);
66
+ }, opts.timeoutMs);
67
+ }
68
+ child.stdout.on("data", (chunk) => {
69
+ stdout += chunk.toString("utf8");
70
+ });
71
+ child.stderr.on("data", (chunk) => {
72
+ stderr += chunk.toString("utf8");
73
+ });
74
+ child.once("error", (err) => {
75
+ if (settled) return;
76
+ settled = true;
77
+ cleanup();
78
+ reject(pendingError ?? err);
79
+ });
80
+ child.once("close", (exitCode) => {
81
+ if (settled) return;
82
+ settled = true;
83
+ cleanup();
84
+ if (pendingError !== void 0) {
85
+ reject(pendingError);
86
+ } else {
87
+ resolve({ stdout, stderr, exitCode });
88
+ }
89
+ });
90
+ child.stdin.end(input, "utf8");
91
+ });
92
+ }
93
+ };
94
+ }
95
+
96
+ // src/adapter.ts
97
+ var Semaphore = class {
98
+ available;
99
+ queue = [];
100
+ constructor(max) {
101
+ this.available = max;
102
+ }
103
+ async acquire() {
104
+ if (this.available > 0) {
105
+ this.available -= 1;
106
+ return () => {
107
+ this.release();
108
+ };
109
+ }
110
+ await new Promise((resolve) => {
111
+ this.queue.push(resolve);
112
+ });
113
+ this.available -= 1;
114
+ return () => {
115
+ this.release();
116
+ };
117
+ }
118
+ release() {
119
+ this.available += 1;
120
+ const next = this.queue.shift();
121
+ if (next !== void 0) next();
122
+ }
123
+ };
124
+ function mapFinishReason(stopReason) {
125
+ if (stopReason === void 0) return void 0;
126
+ switch (stopReason) {
127
+ case "end_turn":
128
+ return "stop";
129
+ case "tool_use":
130
+ return "stop";
131
+ default:
132
+ return "other";
133
+ }
134
+ }
135
+ function mapUsage(usage) {
136
+ const inputTokens = usage?.input_tokens ?? 0;
137
+ const outputTokens = usage?.output_tokens ?? 0;
138
+ const cachedInputTokens = usage?.cache_read_input_tokens;
139
+ const details = {
140
+ input: inputTokens,
141
+ output: outputTokens,
142
+ ...cachedInputTokens !== void 0 ? { cached: cachedInputTokens } : {}
143
+ };
144
+ const raw = usage !== void 0 ? usage : null;
145
+ return {
146
+ inputTokens,
147
+ outputTokens,
148
+ details,
149
+ raw,
150
+ ...cachedInputTokens !== void 0 ? { cachedInputTokens } : {}
151
+ };
152
+ }
153
+ function partText(part) {
154
+ if (part.kind !== "text") {
155
+ throw new core.LlmError(
156
+ "claude-cli is text-only; non-text message parts are not supported",
157
+ {
158
+ kind: "bad_request",
159
+ retryable: false,
160
+ provider: "claude-cli"
161
+ }
162
+ );
163
+ }
164
+ return part.text;
165
+ }
166
+ function messageText(msg) {
167
+ return msg.parts.map(partText).join("");
168
+ }
169
+ function buildPrompt(messages) {
170
+ if (messages.length === 1 && messages[0]?.parts.length === 1) {
171
+ return partText(messages[0].parts[0]);
172
+ }
173
+ return messages.map((msg) => {
174
+ const label = msg.role === "assistant" ? "Assistant" : "User";
175
+ return `${label}:
176
+ ${messageText(msg)}`;
177
+ }).join("\n\n");
178
+ }
179
+ function looksAuthy(text) {
180
+ return /login|auth|unauthorized/i.test(text);
181
+ }
182
+ function looksRateLimited(text) {
183
+ return /rate limit|429/i.test(text);
184
+ }
185
+ function classifyRunFailure(envelope, result) {
186
+ const combinedText = `${envelope?.subtype ?? ""} ${result.stderr}`;
187
+ if (looksAuthy(combinedText)) {
188
+ return new core.LlmError(
189
+ `claude CLI reported an authentication failure: ${result.stderr.slice(-500)}`,
190
+ { kind: "invalid_auth", retryable: false, provider: "claude-cli" }
191
+ );
192
+ }
193
+ if (looksRateLimited(combinedText)) {
194
+ return new core.LlmError(
195
+ `claude CLI reported rate limiting: ${result.stderr.slice(-500)}`,
196
+ {
197
+ kind: "rate_limited",
198
+ retryable: true,
199
+ provider: "claude-cli"
200
+ }
201
+ );
202
+ }
203
+ if (envelope?.is_error === true) {
204
+ return new core.LlmError(
205
+ `claude CLI reported an error (subtype: ${envelope.subtype ?? "unknown"}): ${result.stderr.slice(-500)}`,
206
+ { kind: "server", retryable: false, provider: "claude-cli" }
207
+ );
208
+ }
209
+ const stderrTail = result.stderr.slice(-500);
210
+ return new core.LlmError(
211
+ `claude CLI exited with code ${String(result.exitCode)}: ${stderrTail}`,
212
+ { kind: "unknown", retryable: false, provider: "claude-cli" }
213
+ );
214
+ }
215
+ function claudeCliAdapter(opts) {
216
+ const runner = opts?.runner ?? buildClaudeCliRunner(opts?.claudePath);
217
+ const semaphore = new Semaphore(opts?.maxConcurrency ?? 2);
218
+ return {
219
+ id: "claude-cli",
220
+ async run(req, ctx) {
221
+ const hasCliSession = "cliSession" in ctx.auth && ctx.auth.cliSession;
222
+ if (!hasCliSession) {
223
+ throw new core.LlmError(
224
+ "@gullabs/claude-cli requires auth: { cliSession: true } \u2014 these dev-only providers route through a locally-authenticated `claude` CLI session, not an API key",
225
+ { kind: "invalid_auth", retryable: false, provider: "claude-cli" }
226
+ );
227
+ }
228
+ const warnings = [];
229
+ const model = req.model;
230
+ const config = req.config;
231
+ const prompt = buildPrompt(req.messages);
232
+ const args = [
233
+ "-p",
234
+ "--output-format",
235
+ "json",
236
+ "--safe-mode",
237
+ "--tools",
238
+ "",
239
+ "--disable-slash-commands",
240
+ "--no-session-persistence"
241
+ ];
242
+ args.push("--model", model);
243
+ const effort = config.reasoning?.effort;
244
+ if (effort !== void 0) {
245
+ args.push("--effort", String(effort));
246
+ }
247
+ if (req.system !== void 0) {
248
+ args.push("--system-prompt", req.system);
249
+ }
250
+ if (req.outputJsonSchema !== void 0) {
251
+ args.push("--json-schema", JSON.stringify(req.outputJsonSchema));
252
+ }
253
+ const timeoutMs = req.attemptTimeoutMs ?? config.timeoutMs;
254
+ const cwd = await promises.mkdtemp(path.join(os.tmpdir(), "claude-cli-"));
255
+ const release = await semaphore.acquire();
256
+ let result;
257
+ try {
258
+ result = await runner.run(args, prompt, {
259
+ cwd,
260
+ ...timeoutMs !== void 0 ? { timeoutMs } : {},
261
+ ...ctx.signal !== void 0 ? { signal: ctx.signal } : {}
262
+ });
263
+ } catch (rawErr) {
264
+ release();
265
+ await promises.rm(cwd, { recursive: true, force: true });
266
+ if (rawErr instanceof core.LlmError) throw rawErr;
267
+ if (typeof rawErr === "object" && rawErr !== null && "code" in rawErr && rawErr.code === "ENOENT") {
268
+ throw new core.LlmError(
269
+ "claude CLI not found on PATH \u2014 install Claude Code and run `claude auth login`",
270
+ { kind: "unknown", retryable: false, provider: "claude-cli" }
271
+ );
272
+ }
273
+ if (rawErr instanceof Error && rawErr.name === "AbortError") {
274
+ throw new core.LlmError(rawErr.message || "claude-cli call aborted", {
275
+ kind: "aborted",
276
+ retryable: false,
277
+ provider: "claude-cli"
278
+ });
279
+ }
280
+ if (rawErr instanceof Error && rawErr.name === "TimeoutError") {
281
+ throw new core.LlmError(rawErr.message || "claude-cli call timed out", {
282
+ kind: "timeout",
283
+ retryable: true,
284
+ provider: "claude-cli"
285
+ });
286
+ }
287
+ throw new core.LlmError(
288
+ `claude-cli runner failed: ${rawErr instanceof Error ? rawErr.message : String(rawErr)}`,
289
+ { kind: "unknown", retryable: false, provider: "claude-cli", cause: rawErr }
290
+ );
291
+ }
292
+ release();
293
+ await promises.rm(cwd, { recursive: true, force: true });
294
+ let envelope;
295
+ try {
296
+ envelope = JSON.parse(result.stdout);
297
+ } catch {
298
+ envelope = void 0;
299
+ }
300
+ if (result.exitCode !== 0 || envelope?.is_error === true || envelope === void 0) {
301
+ throw classifyRunFailure(envelope, result);
302
+ }
303
+ const text = envelope.result ?? "";
304
+ let rawStructured;
305
+ if (req.outputJsonSchema !== void 0) {
306
+ try {
307
+ rawStructured = JSON.parse(text);
308
+ } catch {
309
+ warnings.push({
310
+ type: "other",
311
+ message: "claude-cli: failed to parse structured output as JSON"
312
+ });
313
+ }
314
+ }
315
+ const usage = mapUsage(envelope.usage);
316
+ const finishReason = mapFinishReason(envelope.stop_reason);
317
+ const providerMetadata = {
318
+ ...envelope.total_cost_usd !== void 0 ? { totalCostUsd: envelope.total_cost_usd } : {},
319
+ ...envelope.session_id !== void 0 ? { sessionId: envelope.session_id } : {},
320
+ ...envelope.subtype !== void 0 ? { subtype: envelope.subtype } : {},
321
+ ...envelope.num_turns !== void 0 ? { numTurns: envelope.num_turns } : {}
322
+ };
323
+ const adapterResult = {
324
+ model,
325
+ usage,
326
+ warnings,
327
+ ...text.length > 0 ? { text } : {},
328
+ ...rawStructured !== void 0 ? { rawStructured } : {},
329
+ ...finishReason !== void 0 ? { finishReason } : {},
330
+ ...Object.keys(providerMetadata).length > 0 ? { providerMetadata } : {}
331
+ };
332
+ return adapterResult;
333
+ }
334
+ };
335
+ }
336
+ var CLAUDE_CLI_MODEL_IDS = [
337
+ "claude-fable-5",
338
+ "claude-opus-4-8",
339
+ "claude-sonnet-5",
340
+ "claude-haiku-4-5-20251001"
341
+ ];
342
+ var CLAUDE_CLI_EFFORTS = ["low", "medium", "high", "xhigh", "max"];
343
+ function buildClaudeCliConfigSchema(modelName) {
344
+ return zod.z.strictObject({
345
+ reasoning: zod.z.strictObject({
346
+ effort: zod.z.enum(CLAUDE_CLI_EFFORTS).meta({
347
+ title: "Reasoning Effort",
348
+ description: `Reasoning effort forwarded to the claude CLI's --effort flag for ${modelName}.`
349
+ })
350
+ }).optional().meta({
351
+ title: "Reasoning",
352
+ description: `Reasoning configuration for ${modelName}.`
353
+ }),
354
+ timeoutMs: zod.z.number().int().positive().max(18e5).optional().meta({
355
+ title: "Timeout",
356
+ description: "Logical request timeout in milliseconds; forwarded to the CLI runner."
357
+ })
358
+ }).meta({
359
+ title: `${modelName}Config`,
360
+ description: `Strict claude-cli config for model ${modelName}. Text-only, no sampling knobs, effort-based reasoning.`
361
+ });
362
+ }
363
+ var ClaudeFable5ConfigSchema = buildClaudeCliConfigSchema("claude-fable-5");
364
+ var ClaudeOpus48ConfigSchema = buildClaudeCliConfigSchema("claude-opus-4-8");
365
+ var ClaudeSonnet5ConfigSchema = buildClaudeCliConfigSchema("claude-sonnet-5");
366
+ var ClaudeHaiku45ConfigSchema = buildClaudeCliConfigSchema(
367
+ "claude-haiku-4-5-20251001"
368
+ );
369
+ var CONFIG_SCHEMAS = {
370
+ "claude-fable-5": ClaudeFable5ConfigSchema,
371
+ "claude-opus-4-8": ClaudeOpus48ConfigSchema,
372
+ "claude-sonnet-5": ClaudeSonnet5ConfigSchema,
373
+ "claude-haiku-4-5-20251001": ClaudeHaiku45ConfigSchema
374
+ };
375
+ var claudeCliModelDescriptors = CLAUDE_CLI_MODEL_IDS.map(
376
+ (id) => {
377
+ const configSchema = CONFIG_SCHEMAS[id];
378
+ return {
379
+ id,
380
+ provider: "claude-cli",
381
+ capabilities: {
382
+ structuredOutput: true,
383
+ nativeStructuredOutput: true,
384
+ reasoningApi: "level",
385
+ sampling: "fixed",
386
+ vision: false
387
+ },
388
+ configSchema,
389
+ configJsonSchema: core.toConfigJsonSchema(configSchema),
390
+ validateConfig: core.zodToStandardSchema(configSchema)
391
+ };
392
+ }
393
+ );
394
+ var claudeCliRegistry = core.createModelRegistry(
395
+ claudeCliModelDescriptors
396
+ );
397
+
398
+ exports.ClaudeFable5ConfigSchema = ClaudeFable5ConfigSchema;
399
+ exports.ClaudeHaiku45ConfigSchema = ClaudeHaiku45ConfigSchema;
400
+ exports.ClaudeOpus48ConfigSchema = ClaudeOpus48ConfigSchema;
401
+ exports.ClaudeSonnet5ConfigSchema = ClaudeSonnet5ConfigSchema;
402
+ exports.buildClaudeCliRunner = buildClaudeCliRunner;
403
+ exports.claudeCliAdapter = claudeCliAdapter;
404
+ exports.claudeCliModelDescriptors = claudeCliModelDescriptors;
405
+ exports.claudeCliRegistry = claudeCliRegistry;
406
+ //# sourceMappingURL=index.cjs.map
407
+ //# sourceMappingURL=index.cjs.map