ai-sdk-provider-gemini-cli-agentic 0.1.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 +21 -0
- package/dist/index.cjs +689 -0
- package/dist/index.d.cts +236 -0
- package/dist/index.d.ts +236 -0
- package/dist/index.js +680 -0
- package/package.json +73 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,689 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var provider = require('@ai-sdk/provider');
|
|
4
|
+
var child_process = require('child_process');
|
|
5
|
+
var crypto = require('crypto');
|
|
6
|
+
var providerUtils = require('@ai-sdk/provider-utils');
|
|
7
|
+
var zod = require('zod');
|
|
8
|
+
|
|
9
|
+
// src/gemini-cli-provider.ts
|
|
10
|
+
|
|
11
|
+
// src/stream-parser.ts
|
|
12
|
+
function parseStreamJsonLine(line) {
|
|
13
|
+
try {
|
|
14
|
+
const event = JSON.parse(line);
|
|
15
|
+
if (!event.type || typeof event.type !== "string") return null;
|
|
16
|
+
return event;
|
|
17
|
+
} catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function isInitEvent(event) {
|
|
22
|
+
return event.type === "init";
|
|
23
|
+
}
|
|
24
|
+
function isMessageEvent(event) {
|
|
25
|
+
return event.type === "message";
|
|
26
|
+
}
|
|
27
|
+
function isToolUseEvent(event) {
|
|
28
|
+
return event.type === "tool_use";
|
|
29
|
+
}
|
|
30
|
+
function isToolResultEvent(event) {
|
|
31
|
+
return event.type === "tool_result";
|
|
32
|
+
}
|
|
33
|
+
function isResultEvent(event) {
|
|
34
|
+
return event.type === "result";
|
|
35
|
+
}
|
|
36
|
+
function isErrorEvent(event) {
|
|
37
|
+
return event.type === "error";
|
|
38
|
+
}
|
|
39
|
+
function createEmptyUsage() {
|
|
40
|
+
return {
|
|
41
|
+
inputTokens: {
|
|
42
|
+
total: 0,
|
|
43
|
+
noCache: 0,
|
|
44
|
+
cacheRead: 0,
|
|
45
|
+
cacheWrite: 0
|
|
46
|
+
},
|
|
47
|
+
outputTokens: {
|
|
48
|
+
total: 0,
|
|
49
|
+
text: void 0,
|
|
50
|
+
reasoning: void 0
|
|
51
|
+
},
|
|
52
|
+
raw: void 0
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function convertStatsToUsage(stats) {
|
|
56
|
+
const inputTotal = stats.input_tokens ?? stats.input ?? 0;
|
|
57
|
+
const outputTotal = stats.output_tokens ?? 0;
|
|
58
|
+
const cached = stats.cached ?? 0;
|
|
59
|
+
return {
|
|
60
|
+
inputTokens: {
|
|
61
|
+
total: inputTotal,
|
|
62
|
+
noCache: inputTotal - cached,
|
|
63
|
+
cacheRead: cached,
|
|
64
|
+
cacheWrite: 0
|
|
65
|
+
},
|
|
66
|
+
outputTokens: {
|
|
67
|
+
total: outputTotal,
|
|
68
|
+
text: void 0,
|
|
69
|
+
reasoning: void 0
|
|
70
|
+
},
|
|
71
|
+
raw: stats
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// src/message-mapper.ts
|
|
76
|
+
function isTextPart(p) {
|
|
77
|
+
return typeof p === "object" && p !== null && "type" in p && p.type === "text" && "text" in p && typeof p.text === "string";
|
|
78
|
+
}
|
|
79
|
+
function isToolItem(p) {
|
|
80
|
+
if (typeof p !== "object" || p === null) return false;
|
|
81
|
+
const obj = p;
|
|
82
|
+
if (typeof obj.toolName !== "string") return false;
|
|
83
|
+
const out = obj.output;
|
|
84
|
+
if (!out || out.type !== "text" && out.type !== "json") return false;
|
|
85
|
+
if (out.type === "text" && typeof out.value !== "string") return false;
|
|
86
|
+
return true;
|
|
87
|
+
}
|
|
88
|
+
function mapMessagesToPrompt(prompt) {
|
|
89
|
+
const warnings = [];
|
|
90
|
+
const parts = [];
|
|
91
|
+
let systemText;
|
|
92
|
+
for (const msg of prompt) {
|
|
93
|
+
if (msg.role === "system") {
|
|
94
|
+
systemText = typeof msg.content === "string" ? msg.content : String(msg.content);
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
if (msg.role === "user") {
|
|
98
|
+
if (typeof msg.content === "string") {
|
|
99
|
+
parts.push(`Human: ${msg.content}`);
|
|
100
|
+
} else if (Array.isArray(msg.content)) {
|
|
101
|
+
const text = msg.content.filter(isTextPart).map((p) => p.text).join("\n");
|
|
102
|
+
if (text) parts.push(`Human: ${text}`);
|
|
103
|
+
}
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (msg.role === "assistant") {
|
|
107
|
+
if (typeof msg.content === "string") {
|
|
108
|
+
parts.push(`Assistant: ${msg.content}`);
|
|
109
|
+
} else if (Array.isArray(msg.content)) {
|
|
110
|
+
const text = msg.content.filter(isTextPart).map((p) => p.text).join("\n");
|
|
111
|
+
if (text) parts.push(`Assistant: ${text}`);
|
|
112
|
+
}
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (msg.role === "tool") {
|
|
116
|
+
if (Array.isArray(msg.content)) {
|
|
117
|
+
for (const maybeTool of msg.content) {
|
|
118
|
+
if (!isToolItem(maybeTool)) continue;
|
|
119
|
+
const value = maybeTool.output.type === "text" ? maybeTool.output.value : JSON.stringify(maybeTool.output.value);
|
|
120
|
+
parts.push(`Tool Result (${maybeTool.toolName}): ${value}`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
let promptText = "";
|
|
127
|
+
if (systemText) promptText += systemText + "\n\n";
|
|
128
|
+
promptText += parts.join("\n\n");
|
|
129
|
+
return { promptText, ...warnings.length ? { warnings } : {} };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// src/logger.ts
|
|
133
|
+
var defaultLogger = {
|
|
134
|
+
debug: (message) => console.debug(`[DEBUG] ${message}`),
|
|
135
|
+
info: (message) => console.info(`[INFO] ${message}`),
|
|
136
|
+
warn: (message) => console.warn(`[WARN] ${message}`),
|
|
137
|
+
error: (message) => console.error(`[ERROR] ${message}`)
|
|
138
|
+
};
|
|
139
|
+
var noopLogger = {
|
|
140
|
+
debug: () => {
|
|
141
|
+
},
|
|
142
|
+
info: () => {
|
|
143
|
+
},
|
|
144
|
+
warn: () => {
|
|
145
|
+
},
|
|
146
|
+
error: () => {
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
function getLogger(logger) {
|
|
150
|
+
if (logger === false) {
|
|
151
|
+
return noopLogger;
|
|
152
|
+
}
|
|
153
|
+
if (logger === void 0) {
|
|
154
|
+
return defaultLogger;
|
|
155
|
+
}
|
|
156
|
+
return logger;
|
|
157
|
+
}
|
|
158
|
+
function createVerboseLogger(logger, verbose = false) {
|
|
159
|
+
if (verbose) {
|
|
160
|
+
return logger;
|
|
161
|
+
}
|
|
162
|
+
return {
|
|
163
|
+
debug: () => {
|
|
164
|
+
},
|
|
165
|
+
info: () => {
|
|
166
|
+
},
|
|
167
|
+
warn: logger.warn.bind(logger),
|
|
168
|
+
error: logger.error.bind(logger)
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
function createAPICallError({
|
|
172
|
+
message,
|
|
173
|
+
code,
|
|
174
|
+
exitCode,
|
|
175
|
+
stderr,
|
|
176
|
+
promptExcerpt,
|
|
177
|
+
isRetryable = false
|
|
178
|
+
}) {
|
|
179
|
+
const data = { code, exitCode, stderr, promptExcerpt };
|
|
180
|
+
return new provider.APICallError({
|
|
181
|
+
message,
|
|
182
|
+
isRetryable,
|
|
183
|
+
url: "gemini-cli://exec",
|
|
184
|
+
requestBodyValues: promptExcerpt ? { prompt: promptExcerpt } : void 0,
|
|
185
|
+
data
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
function createAuthenticationError(message) {
|
|
189
|
+
return new provider.LoadAPIKeyError({
|
|
190
|
+
message: message || 'Authentication failed. Run "gemini" to authenticate.'
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
function isAuthenticationError(err) {
|
|
194
|
+
if (err instanceof provider.LoadAPIKeyError) return true;
|
|
195
|
+
if (err instanceof provider.APICallError) {
|
|
196
|
+
const data = err.data;
|
|
197
|
+
if (data?.exitCode === 401) return true;
|
|
198
|
+
}
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
var geminiCliProviderOptionsSchema = zod.z.object({
|
|
202
|
+
approvalMode: zod.z.enum(["default", "auto_edit", "yolo"]).optional(),
|
|
203
|
+
yolo: zod.z.boolean().optional(),
|
|
204
|
+
sandbox: zod.z.boolean().optional(),
|
|
205
|
+
includeDirectories: zod.z.array(zod.z.string().min(1)).optional(),
|
|
206
|
+
allowedTools: zod.z.array(zod.z.string().min(1)).optional(),
|
|
207
|
+
allowedMcpServerNames: zod.z.array(zod.z.string().min(1)).optional()
|
|
208
|
+
}).strict();
|
|
209
|
+
function mapGeminiFinishReason(status) {
|
|
210
|
+
switch (status) {
|
|
211
|
+
case "success":
|
|
212
|
+
return { unified: "stop", raw: status };
|
|
213
|
+
case "error":
|
|
214
|
+
return { unified: "error", raw: status };
|
|
215
|
+
default:
|
|
216
|
+
return { unified: "stop", raw: status };
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
var GeminiCliLanguageModel = class {
|
|
220
|
+
specificationVersion = "v3";
|
|
221
|
+
provider = "gemini-cli";
|
|
222
|
+
defaultObjectGenerationMode = "json";
|
|
223
|
+
supportsImageUrls = false;
|
|
224
|
+
supportedUrls = {};
|
|
225
|
+
supportsStructuredOutputs = false;
|
|
226
|
+
modelId;
|
|
227
|
+
settings;
|
|
228
|
+
logger;
|
|
229
|
+
sessionId;
|
|
230
|
+
constructor(options) {
|
|
231
|
+
this.modelId = options.id;
|
|
232
|
+
this.settings = options.settings ?? {};
|
|
233
|
+
const baseLogger = getLogger(this.settings.logger);
|
|
234
|
+
this.logger = createVerboseLogger(baseLogger, this.settings.verbose ?? false);
|
|
235
|
+
if (!this.modelId || this.modelId.trim() === "") {
|
|
236
|
+
throw new provider.NoSuchModelError({ modelId: this.modelId, modelType: "languageModel" });
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
mergeSettings(providerOptions) {
|
|
240
|
+
if (!providerOptions) return this.settings;
|
|
241
|
+
return {
|
|
242
|
+
...this.settings,
|
|
243
|
+
approvalMode: providerOptions.approvalMode ?? this.settings.approvalMode,
|
|
244
|
+
yolo: providerOptions.yolo ?? this.settings.yolo,
|
|
245
|
+
sandbox: providerOptions.sandbox ?? this.settings.sandbox,
|
|
246
|
+
includeDirectories: providerOptions.includeDirectories ?? this.settings.includeDirectories,
|
|
247
|
+
allowedTools: providerOptions.allowedTools ?? this.settings.allowedTools,
|
|
248
|
+
allowedMcpServerNames: providerOptions.allowedMcpServerNames ?? this.settings.allowedMcpServerNames
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
buildArgs(promptText, settings = this.settings) {
|
|
252
|
+
const cmd = settings.geminiPath ?? "gemini";
|
|
253
|
+
const args = [];
|
|
254
|
+
args.push("--output-format", "stream-json");
|
|
255
|
+
if (this.modelId && this.modelId !== "auto") {
|
|
256
|
+
args.push("-m", this.modelId);
|
|
257
|
+
}
|
|
258
|
+
if (settings.yolo) {
|
|
259
|
+
args.push("--yolo");
|
|
260
|
+
} else if (settings.approvalMode) {
|
|
261
|
+
args.push("--approval-mode", settings.approvalMode);
|
|
262
|
+
}
|
|
263
|
+
if (settings.sandbox) {
|
|
264
|
+
args.push("--sandbox");
|
|
265
|
+
}
|
|
266
|
+
if (settings.includeDirectories?.length) {
|
|
267
|
+
for (const dir of settings.includeDirectories) {
|
|
268
|
+
args.push("--include-directories", dir);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (settings.allowedTools?.length) {
|
|
272
|
+
args.push("--allowed-tools", ...settings.allowedTools);
|
|
273
|
+
}
|
|
274
|
+
if (settings.allowedMcpServerNames?.length) {
|
|
275
|
+
args.push("--allowed-mcp-server-names", ...settings.allowedMcpServerNames);
|
|
276
|
+
}
|
|
277
|
+
if (settings.resume) {
|
|
278
|
+
if (typeof settings.resume === "string") {
|
|
279
|
+
args.push("--resume", settings.resume);
|
|
280
|
+
} else {
|
|
281
|
+
args.push("--resume", "latest");
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
args.push(promptText);
|
|
285
|
+
const env = {
|
|
286
|
+
...process.env,
|
|
287
|
+
...settings.env || {}
|
|
288
|
+
};
|
|
289
|
+
return { cmd, args, env, cwd: settings.cwd };
|
|
290
|
+
}
|
|
291
|
+
mapWarnings(options) {
|
|
292
|
+
const unsupported = [];
|
|
293
|
+
const add = (setting, name) => {
|
|
294
|
+
if (setting !== void 0) {
|
|
295
|
+
unsupported.push({
|
|
296
|
+
type: "unsupported",
|
|
297
|
+
feature: name,
|
|
298
|
+
details: `Gemini CLI does not support ${name}; it will be ignored.`
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
add(options.temperature, "temperature");
|
|
303
|
+
add(options.topP, "topP");
|
|
304
|
+
add(options.topK, "topK");
|
|
305
|
+
add(options.presencePenalty, "presencePenalty");
|
|
306
|
+
add(options.frequencyPenalty, "frequencyPenalty");
|
|
307
|
+
add(options.stopSequences?.length ? options.stopSequences : void 0, "stopSequences");
|
|
308
|
+
return unsupported;
|
|
309
|
+
}
|
|
310
|
+
handleSpawnError(err, promptExcerpt) {
|
|
311
|
+
const e = err && typeof err === "object" ? err : void 0;
|
|
312
|
+
const message = String((e?.message ?? err) || "Failed to run Gemini CLI");
|
|
313
|
+
if (/login|auth|unauthorized/i.test(message)) {
|
|
314
|
+
return createAuthenticationError(message);
|
|
315
|
+
}
|
|
316
|
+
return createAPICallError({
|
|
317
|
+
message,
|
|
318
|
+
code: typeof e?.code === "string" ? e.code : void 0,
|
|
319
|
+
promptExcerpt
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
async doGenerate(options) {
|
|
323
|
+
this.logger.debug(`[gemini-cli] Starting doGenerate request with model: ${this.modelId}`);
|
|
324
|
+
const { promptText, warnings: mappingWarnings } = mapMessagesToPrompt(options.prompt);
|
|
325
|
+
const promptExcerpt = promptText.slice(0, 200);
|
|
326
|
+
const warnings = [
|
|
327
|
+
...this.mapWarnings(options),
|
|
328
|
+
...mappingWarnings?.map((m) => ({ type: "other", message: m })) || []
|
|
329
|
+
];
|
|
330
|
+
const providerOptions = await providerUtils.parseProviderOptions({
|
|
331
|
+
provider: this.provider,
|
|
332
|
+
providerOptions: options.providerOptions,
|
|
333
|
+
schema: geminiCliProviderOptionsSchema
|
|
334
|
+
});
|
|
335
|
+
const effectiveSettings = this.mergeSettings(providerOptions);
|
|
336
|
+
const { cmd, args, env, cwd } = this.buildArgs(promptText, effectiveSettings);
|
|
337
|
+
this.logger.debug(`[gemini-cli] Executing: ${cmd} ${args.slice(0, -1).join(" ")} [prompt]`);
|
|
338
|
+
let text = "";
|
|
339
|
+
let usage = createEmptyUsage();
|
|
340
|
+
let finishReason = { unified: "stop", raw: void 0 };
|
|
341
|
+
const content = [];
|
|
342
|
+
const toolResults = /* @__PURE__ */ new Map();
|
|
343
|
+
const child = child_process.spawn(cmd, args, { env, cwd, stdio: ["ignore", "pipe", "pipe"] });
|
|
344
|
+
let onAbort;
|
|
345
|
+
if (options.abortSignal) {
|
|
346
|
+
if (options.abortSignal.aborted) {
|
|
347
|
+
child.kill("SIGTERM");
|
|
348
|
+
throw options.abortSignal.reason ?? new Error("Request aborted");
|
|
349
|
+
}
|
|
350
|
+
onAbort = () => child.kill("SIGTERM");
|
|
351
|
+
options.abortSignal.addEventListener("abort", onAbort, { once: true });
|
|
352
|
+
}
|
|
353
|
+
const startTime = Date.now();
|
|
354
|
+
try {
|
|
355
|
+
await new Promise((resolve, reject) => {
|
|
356
|
+
let stderr = "";
|
|
357
|
+
child.stderr.on("data", (d) => stderr += String(d));
|
|
358
|
+
child.stdout.setEncoding("utf8");
|
|
359
|
+
child.stdout.on("data", (chunk) => {
|
|
360
|
+
const lines = chunk.split(/\r?\n/).filter(Boolean);
|
|
361
|
+
for (const line of lines) {
|
|
362
|
+
const event = parseStreamJsonLine(line);
|
|
363
|
+
if (!event) continue;
|
|
364
|
+
this.logger.debug(`[gemini-cli] Event: ${event.type}`);
|
|
365
|
+
if (isInitEvent(event)) {
|
|
366
|
+
this.sessionId = event.session_id;
|
|
367
|
+
this.logger.debug(`[gemini-cli] Session: ${this.sessionId}`);
|
|
368
|
+
}
|
|
369
|
+
if (isMessageEvent(event) && event.role === "assistant" && event.content) {
|
|
370
|
+
if (event.delta) {
|
|
371
|
+
text += event.content;
|
|
372
|
+
} else {
|
|
373
|
+
text = event.content;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
if (isToolUseEvent(event)) {
|
|
377
|
+
toolResults.set(event.tool_id, { toolName: event.tool_name });
|
|
378
|
+
content.push({
|
|
379
|
+
type: "tool-call",
|
|
380
|
+
toolCallId: event.tool_id,
|
|
381
|
+
toolName: event.tool_name,
|
|
382
|
+
input: JSON.stringify(event.parameters)
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
if (isToolResultEvent(event)) {
|
|
386
|
+
const toolInfo = toolResults.get(event.tool_id);
|
|
387
|
+
content.push({
|
|
388
|
+
type: "tool-result",
|
|
389
|
+
toolCallId: event.tool_id,
|
|
390
|
+
toolName: toolInfo?.toolName ?? "unknown",
|
|
391
|
+
result: event.output,
|
|
392
|
+
isError: event.status === "error"
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
if (isResultEvent(event)) {
|
|
396
|
+
if (event.stats) {
|
|
397
|
+
usage = convertStatsToUsage(event.stats);
|
|
398
|
+
}
|
|
399
|
+
finishReason = mapGeminiFinishReason(event.status);
|
|
400
|
+
}
|
|
401
|
+
if (isErrorEvent(event)) {
|
|
402
|
+
reject(
|
|
403
|
+
createAPICallError({
|
|
404
|
+
message: event.error,
|
|
405
|
+
stderr,
|
|
406
|
+
promptExcerpt
|
|
407
|
+
})
|
|
408
|
+
);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
});
|
|
412
|
+
child.on("error", (e) => {
|
|
413
|
+
this.logger.error(`[gemini-cli] Spawn error: ${String(e)}`);
|
|
414
|
+
reject(this.handleSpawnError(e, promptExcerpt));
|
|
415
|
+
});
|
|
416
|
+
child.on("close", (code) => {
|
|
417
|
+
const duration = Date.now() - startTime;
|
|
418
|
+
if (code === 0) {
|
|
419
|
+
this.logger.info(`[gemini-cli] Completed in ${duration}ms`);
|
|
420
|
+
resolve();
|
|
421
|
+
} else {
|
|
422
|
+
this.logger.error(`[gemini-cli] Exited with code ${code}`);
|
|
423
|
+
reject(
|
|
424
|
+
createAPICallError({
|
|
425
|
+
message: `Gemini CLI exited with code ${code}`,
|
|
426
|
+
exitCode: code ?? void 0,
|
|
427
|
+
stderr,
|
|
428
|
+
promptExcerpt
|
|
429
|
+
})
|
|
430
|
+
);
|
|
431
|
+
}
|
|
432
|
+
});
|
|
433
|
+
});
|
|
434
|
+
} finally {
|
|
435
|
+
if (options.abortSignal && onAbort) {
|
|
436
|
+
options.abortSignal.removeEventListener("abort", onAbort);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
if (text) {
|
|
440
|
+
content.unshift({ type: "text", text });
|
|
441
|
+
}
|
|
442
|
+
return {
|
|
443
|
+
content: content.length > 0 ? content : [{ type: "text", text: "" }],
|
|
444
|
+
usage,
|
|
445
|
+
finishReason,
|
|
446
|
+
warnings,
|
|
447
|
+
response: { id: providerUtils.generateId(), timestamp: /* @__PURE__ */ new Date(), modelId: this.modelId },
|
|
448
|
+
request: { body: promptText },
|
|
449
|
+
providerMetadata: {
|
|
450
|
+
"gemini-cli": { ...this.sessionId ? { sessionId: this.sessionId } : {} }
|
|
451
|
+
}
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
async doStream(options) {
|
|
455
|
+
this.logger.debug(`[gemini-cli] Starting doStream request with model: ${this.modelId}`);
|
|
456
|
+
const { promptText, warnings: mappingWarnings } = mapMessagesToPrompt(options.prompt);
|
|
457
|
+
const promptExcerpt = promptText.slice(0, 200);
|
|
458
|
+
const warnings = [
|
|
459
|
+
...this.mapWarnings(options),
|
|
460
|
+
...mappingWarnings?.map((m) => ({ type: "other", message: m })) || []
|
|
461
|
+
];
|
|
462
|
+
const providerOptions = await providerUtils.parseProviderOptions({
|
|
463
|
+
provider: this.provider,
|
|
464
|
+
providerOptions: options.providerOptions,
|
|
465
|
+
schema: geminiCliProviderOptionsSchema
|
|
466
|
+
});
|
|
467
|
+
const effectiveSettings = this.mergeSettings(providerOptions);
|
|
468
|
+
const { cmd, args, env, cwd } = this.buildArgs(promptText, effectiveSettings);
|
|
469
|
+
this.logger.debug(`[gemini-cli] Streaming: ${cmd} ${args.slice(0, -1).join(" ")} [prompt]`);
|
|
470
|
+
const model = this;
|
|
471
|
+
const abortSignal = options.abortSignal;
|
|
472
|
+
const stream = new ReadableStream({
|
|
473
|
+
start(controller) {
|
|
474
|
+
const startTime = Date.now();
|
|
475
|
+
const child = child_process.spawn(cmd, args, { env, cwd, stdio: ["ignore", "pipe", "pipe"] });
|
|
476
|
+
controller.enqueue({ type: "stream-start", warnings });
|
|
477
|
+
let stderr = "";
|
|
478
|
+
let lastUsage;
|
|
479
|
+
let textId;
|
|
480
|
+
let lastStatus;
|
|
481
|
+
const toolResults = /* @__PURE__ */ new Map();
|
|
482
|
+
const onAbort = () => child.kill("SIGTERM");
|
|
483
|
+
if (abortSignal) {
|
|
484
|
+
if (abortSignal.aborted) {
|
|
485
|
+
child.kill("SIGTERM");
|
|
486
|
+
controller.error(abortSignal.reason ?? new Error("Request aborted"));
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
abortSignal.addEventListener("abort", onAbort, { once: true });
|
|
490
|
+
}
|
|
491
|
+
child.stderr.on("data", (d) => stderr += String(d));
|
|
492
|
+
child.stdout.setEncoding("utf8");
|
|
493
|
+
child.stdout.on("data", (chunk) => {
|
|
494
|
+
const lines = chunk.split(/\r?\n/).filter(Boolean);
|
|
495
|
+
for (const line of lines) {
|
|
496
|
+
const event = parseStreamJsonLine(line);
|
|
497
|
+
if (!event) continue;
|
|
498
|
+
model.logger.debug(`[gemini-cli] Stream event: ${event.type}`);
|
|
499
|
+
if (isInitEvent(event)) {
|
|
500
|
+
model.sessionId = event.session_id;
|
|
501
|
+
controller.enqueue({
|
|
502
|
+
type: "response-metadata",
|
|
503
|
+
id: crypto.randomUUID(),
|
|
504
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
505
|
+
modelId: event.model ?? model.modelId
|
|
506
|
+
});
|
|
507
|
+
continue;
|
|
508
|
+
}
|
|
509
|
+
if (isMessageEvent(event) && event.role === "assistant" && event.content) {
|
|
510
|
+
if (!textId) {
|
|
511
|
+
textId = crypto.randomUUID();
|
|
512
|
+
controller.enqueue({ type: "text-start", id: textId });
|
|
513
|
+
}
|
|
514
|
+
controller.enqueue({
|
|
515
|
+
type: "text-delta",
|
|
516
|
+
id: textId,
|
|
517
|
+
delta: event.content
|
|
518
|
+
});
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
if (isToolUseEvent(event)) {
|
|
522
|
+
toolResults.set(event.tool_id, { toolName: event.tool_name });
|
|
523
|
+
controller.enqueue({
|
|
524
|
+
type: "tool-call",
|
|
525
|
+
toolCallId: event.tool_id,
|
|
526
|
+
toolName: event.tool_name,
|
|
527
|
+
input: JSON.stringify(event.parameters),
|
|
528
|
+
providerExecuted: true
|
|
529
|
+
});
|
|
530
|
+
continue;
|
|
531
|
+
}
|
|
532
|
+
if (isToolResultEvent(event)) {
|
|
533
|
+
const toolInfo = toolResults.get(event.tool_id);
|
|
534
|
+
controller.enqueue({
|
|
535
|
+
type: "tool-result",
|
|
536
|
+
toolCallId: event.tool_id,
|
|
537
|
+
toolName: toolInfo?.toolName ?? "unknown",
|
|
538
|
+
result: event.output,
|
|
539
|
+
isError: event.status === "error"
|
|
540
|
+
});
|
|
541
|
+
continue;
|
|
542
|
+
}
|
|
543
|
+
if (isResultEvent(event)) {
|
|
544
|
+
if (event.stats) {
|
|
545
|
+
lastUsage = convertStatsToUsage(event.stats);
|
|
546
|
+
}
|
|
547
|
+
lastStatus = event.status;
|
|
548
|
+
continue;
|
|
549
|
+
}
|
|
550
|
+
if (isErrorEvent(event)) {
|
|
551
|
+
controller.error(
|
|
552
|
+
createAPICallError({
|
|
553
|
+
message: event.error,
|
|
554
|
+
stderr,
|
|
555
|
+
promptExcerpt
|
|
556
|
+
})
|
|
557
|
+
);
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
});
|
|
562
|
+
child.on("error", (e) => {
|
|
563
|
+
model.logger.error(`[gemini-cli] Stream spawn error: ${String(e)}`);
|
|
564
|
+
if (abortSignal) {
|
|
565
|
+
abortSignal.removeEventListener("abort", onAbort);
|
|
566
|
+
}
|
|
567
|
+
controller.error(model.handleSpawnError(e, promptExcerpt));
|
|
568
|
+
});
|
|
569
|
+
child.on("close", (code) => {
|
|
570
|
+
const duration = Date.now() - startTime;
|
|
571
|
+
if (abortSignal) {
|
|
572
|
+
abortSignal.removeEventListener("abort", onAbort);
|
|
573
|
+
}
|
|
574
|
+
if (textId) {
|
|
575
|
+
controller.enqueue({ type: "text-end", id: textId });
|
|
576
|
+
}
|
|
577
|
+
if (code === 0) {
|
|
578
|
+
model.logger.info(`[gemini-cli] Stream completed in ${duration}ms`);
|
|
579
|
+
controller.enqueue({
|
|
580
|
+
type: "finish",
|
|
581
|
+
finishReason: mapGeminiFinishReason(lastStatus),
|
|
582
|
+
usage: lastUsage ?? createEmptyUsage()
|
|
583
|
+
});
|
|
584
|
+
controller.close();
|
|
585
|
+
} else {
|
|
586
|
+
model.logger.error(`[gemini-cli] Stream exited with code ${code}`);
|
|
587
|
+
controller.error(
|
|
588
|
+
createAPICallError({
|
|
589
|
+
message: `Gemini CLI exited with code ${code}`,
|
|
590
|
+
exitCode: code ?? void 0,
|
|
591
|
+
stderr,
|
|
592
|
+
promptExcerpt
|
|
593
|
+
})
|
|
594
|
+
);
|
|
595
|
+
}
|
|
596
|
+
});
|
|
597
|
+
},
|
|
598
|
+
cancel() {
|
|
599
|
+
}
|
|
600
|
+
});
|
|
601
|
+
return { stream, request: { body: promptText } };
|
|
602
|
+
}
|
|
603
|
+
};
|
|
604
|
+
var loggerFunctionSchema = zod.z.object({
|
|
605
|
+
debug: zod.z.function(),
|
|
606
|
+
info: zod.z.function(),
|
|
607
|
+
warn: zod.z.function(),
|
|
608
|
+
error: zod.z.function()
|
|
609
|
+
});
|
|
610
|
+
var settingsSchema = zod.z.object({
|
|
611
|
+
geminiPath: zod.z.string().optional(),
|
|
612
|
+
cwd: zod.z.string().optional(),
|
|
613
|
+
includeDirectories: zod.z.array(zod.z.string().min(1)).optional(),
|
|
614
|
+
approvalMode: zod.z.enum(["default", "auto_edit", "yolo"]).optional(),
|
|
615
|
+
yolo: zod.z.boolean().optional(),
|
|
616
|
+
sandbox: zod.z.boolean().optional(),
|
|
617
|
+
allowedTools: zod.z.array(zod.z.string().min(1)).optional(),
|
|
618
|
+
allowedMcpServerNames: zod.z.array(zod.z.string().min(1)).optional(),
|
|
619
|
+
resume: zod.z.union([zod.z.string(), zod.z.boolean()]).optional(),
|
|
620
|
+
model: zod.z.string().optional(),
|
|
621
|
+
env: zod.z.record(zod.z.string(), zod.z.string()).optional(),
|
|
622
|
+
verbose: zod.z.boolean().optional(),
|
|
623
|
+
logger: zod.z.union([zod.z.literal(false), loggerFunctionSchema]).optional()
|
|
624
|
+
}).strict();
|
|
625
|
+
function validateSettings(settings) {
|
|
626
|
+
const warnings = [];
|
|
627
|
+
const errors = [];
|
|
628
|
+
const result = settingsSchema.safeParse(settings);
|
|
629
|
+
if (!result.success) {
|
|
630
|
+
for (const issue of result.error.issues) {
|
|
631
|
+
const path = issue.path.join(".");
|
|
632
|
+
errors.push(`${path}: ${issue.message}`);
|
|
633
|
+
}
|
|
634
|
+
return { valid: false, warnings, errors };
|
|
635
|
+
}
|
|
636
|
+
const s = settings;
|
|
637
|
+
if (s.yolo && s.approvalMode && s.approvalMode !== "yolo") {
|
|
638
|
+
warnings.push("Both yolo and approvalMode are set. yolo takes precedence.");
|
|
639
|
+
}
|
|
640
|
+
return { valid: true, warnings, errors };
|
|
641
|
+
}
|
|
642
|
+
function validateModelId(modelId) {
|
|
643
|
+
if (!modelId || modelId.trim() === "") {
|
|
644
|
+
return "Model ID cannot be empty";
|
|
645
|
+
}
|
|
646
|
+
return void 0;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
// src/gemini-cli-provider.ts
|
|
650
|
+
function createGeminiCli(options = {}) {
|
|
651
|
+
const logger = getLogger(options.defaultSettings?.logger);
|
|
652
|
+
if (options.defaultSettings) {
|
|
653
|
+
const v = validateSettings(options.defaultSettings);
|
|
654
|
+
if (!v.valid) {
|
|
655
|
+
throw new Error(`Invalid default settings: ${v.errors.join(", ")}`);
|
|
656
|
+
}
|
|
657
|
+
for (const w of v.warnings) logger.warn(`Gemini CLI Provider: ${w}`);
|
|
658
|
+
}
|
|
659
|
+
const createModel = (modelId, settings = {}) => {
|
|
660
|
+
const merged = { ...options.defaultSettings, ...settings };
|
|
661
|
+
const v = validateSettings(merged);
|
|
662
|
+
if (!v.valid) throw new Error(`Invalid settings: ${v.errors.join(", ")}`);
|
|
663
|
+
for (const w of v.warnings) logger.warn(`Gemini CLI: ${w}`);
|
|
664
|
+
return new GeminiCliLanguageModel({ id: modelId, settings: merged });
|
|
665
|
+
};
|
|
666
|
+
const provider$1 = function(modelId, settings) {
|
|
667
|
+
if (new.target) throw new Error("The Gemini CLI provider function cannot be called with new.");
|
|
668
|
+
return createModel(modelId, settings);
|
|
669
|
+
};
|
|
670
|
+
provider$1.languageModel = createModel;
|
|
671
|
+
provider$1.chat = createModel;
|
|
672
|
+
provider$1.embeddingModel = ((modelId) => {
|
|
673
|
+
throw new provider.NoSuchModelError({ modelId, modelType: "embeddingModel" });
|
|
674
|
+
});
|
|
675
|
+
provider$1.imageModel = ((modelId) => {
|
|
676
|
+
throw new provider.NoSuchModelError({ modelId, modelType: "imageModel" });
|
|
677
|
+
});
|
|
678
|
+
return provider$1;
|
|
679
|
+
}
|
|
680
|
+
var geminiCli = createGeminiCli();
|
|
681
|
+
|
|
682
|
+
exports.GeminiCliLanguageModel = GeminiCliLanguageModel;
|
|
683
|
+
exports.createAPICallError = createAPICallError;
|
|
684
|
+
exports.createAuthenticationError = createAuthenticationError;
|
|
685
|
+
exports.createGeminiCli = createGeminiCli;
|
|
686
|
+
exports.geminiCli = geminiCli;
|
|
687
|
+
exports.isAuthenticationError = isAuthenticationError;
|
|
688
|
+
exports.validateModelId = validateModelId;
|
|
689
|
+
exports.validateSettings = validateSettings;
|