@unscientificjszhai/howto 1.0.2 → 1.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.
Files changed (51) hide show
  1. package/README.md +88 -29
  2. package/{README.CN.md → README.zh-hans-cn.md} +84 -25
  3. package/THIRD_PARTY_NOTICES.md +1 -0
  4. package/dist/ai/chatgpt-models.js +148 -0
  5. package/dist/ai/chatgpt.js +495 -0
  6. package/dist/ai/command-schema.js +8 -0
  7. package/dist/ai/errors.js +6 -0
  8. package/dist/ai/gemini.js +117 -4
  9. package/dist/ai/index.js +4 -1
  10. package/dist/ai/openai.js +105 -2
  11. package/dist/ai/usage-session.js +144 -0
  12. package/dist/auth/chatgpt/commands.js +90 -0
  13. package/dist/auth/chatgpt/errors.js +85 -0
  14. package/dist/auth/chatgpt/http.js +97 -0
  15. package/dist/auth/chatgpt/index.js +229 -0
  16. package/dist/auth/chatgpt/instructions.js +22 -0
  17. package/dist/auth/chatgpt/oauth.js +320 -0
  18. package/dist/auth/chatgpt/storage.js +366 -0
  19. package/dist/auth/chatgpt/types.js +1 -0
  20. package/dist/cli.js +77 -16
  21. package/dist/config-file.js +2 -0
  22. package/dist/config.js +10 -3
  23. package/dist/errors.js +4 -0
  24. package/dist/index.js +11 -4
  25. package/dist/init/ChatGptInitializationStep.js +223 -0
  26. package/dist/init/InitializationApp.js +71 -37
  27. package/dist/init/index.js +24 -5
  28. package/dist/init/state.js +14 -3
  29. package/dist/prompt.js +36 -6
  30. package/dist/shell/command-analysis.js +24 -4
  31. package/dist/ui/App.js +99 -10
  32. package/dist/ui/ConfirmView.js +6 -39
  33. package/dist/ui/InteractiveSessionProvider.js +7 -8
  34. package/dist/ui/ResolvePlaceholdersView.js +6 -1
  35. package/dist/ui/UsageApprovalView.js +320 -0
  36. package/dist/ui/interactive-session.js +180 -39
  37. package/dist/ui/keyboard-framing.js +102 -0
  38. package/dist/ui/paste-framing.js +69 -32
  39. package/dist/ui/resize-safe-output.js +2 -2
  40. package/dist/ui/run-interactive-command.js +2 -2
  41. package/dist/ui/text-input.js +4 -1
  42. package/dist/ui/use-keyboard-input.js +6 -1
  43. package/dist/ui/use-paste-aware-input.js +8 -3
  44. package/dist/usage/arguments.js +61 -0
  45. package/dist/usage/generate.js +156 -0
  46. package/dist/usage/output.js +216 -0
  47. package/dist/usage/risk.js +17 -0
  48. package/dist/usage/runner.js +238 -0
  49. package/dist/usage/types.js +1 -0
  50. package/dist/validation/usage-response.js +39 -0
  51. package/package.json +21 -19
@@ -0,0 +1,495 @@
1
+ import { getChatGptAccessToken } from "../auth/chatgpt/index.js";
2
+ import { classifyChatGptHttpError } from "../auth/chatgpt/errors.js";
3
+ import { ConfigError } from "../config.js";
4
+ import { sanitizeUsageLookupResult } from "../usage/output.js";
5
+ import { COMMAND_GENERATION_SCHEMA, USAGE_COMMAND_GENERATION_SCHEMA } from "./command-schema.js";
6
+ import { chatGptHttpError, isRecord, readChatGptBody, requestChatGptModels, runChatGptRequest, } from "./chatgpt-models.js";
7
+ import { AiProviderError, UsageToolsUnsupportedError } from "./errors.js";
8
+ import { isExplicitUsageToolsUnsupported, parseUsageToolArguments, USAGE_TOOL_DESCRIPTION, USAGE_TOOL_NAME, USAGE_TOOL_PARAMETERS, UsageReplyTracker, } from "./usage-session.js";
9
+ const RESPONSES_URL = "https://api.openai.com/v1/responses";
10
+ const MAX_STREAM_BYTES = 2 * 1024 * 1024;
11
+ const MAX_OUTPUT_BYTES = 256 * 1024;
12
+ export class ChatGptCommandProvider {
13
+ config;
14
+ dependencies;
15
+ model;
16
+ constructor(config, dependencies = {}) {
17
+ this.config = config;
18
+ this.dependencies = dependencies;
19
+ if (config.model === undefined || config.model.trim() === "") {
20
+ throw new ConfigError("ChatGPT model is not configured. Run howto --chatgpt-models to list available models, or howto --init to select one.");
21
+ }
22
+ this.model = config.model;
23
+ }
24
+ createUsageSession(request) {
25
+ const initial = buildChatGptResponseRequest(this.model, request);
26
+ const input = initial.input;
27
+ const tracker = new UsageReplyTracker("chatgpt", this.model);
28
+ const knownCredentials = new Set();
29
+ const toolResults = new Map();
30
+ let credentialsChanged = false;
31
+ let modelVerified = false;
32
+ return {
33
+ getKnownCredentials: () => [...knownCredentials],
34
+ next: (replies, options, signal) => runChatGptRequest(this.model, signal, this.dependencies, async (requestSignal) => {
35
+ const previousCredentialCount = knownCredentials.size;
36
+ const observeCredentials = (values) => {
37
+ if (requestSignal.aborted)
38
+ return;
39
+ for (const value of values)
40
+ knownCredentials.add(value);
41
+ // 观察时即记录旋转,后续取消不能让重试丢失截断输出保护。
42
+ credentialsChanged ||=
43
+ previousCredentialCount > 0 && knownCredentials.size > previousCredentialCount;
44
+ };
45
+ const credentials = await (this.dependencies.getAccessToken ?? getChatGptAccessToken)({
46
+ accountId: this.config.account,
47
+ signal: requestSignal,
48
+ onCredentials: observeCredentials,
49
+ });
50
+ requestSignal.throwIfAborted();
51
+ observeCredentials([credentials.accessToken]);
52
+ // 审批期间凭据可能已刷新;在序列化工具结果前再次按最新的整组令牌脱敏。
53
+ for (const reply of tracker.accept(replies)) {
54
+ toolResults.set(reply.callId, reply.result);
55
+ input.push({
56
+ type: "function_call_output",
57
+ call_id: reply.callId,
58
+ output: "",
59
+ });
60
+ }
61
+ // 重试和后续轮次也重新处理历史结果,避免沿用旧凭据集合下的序列化内容。
62
+ for (const item of input) {
63
+ if (item.type !== "function_call_output" || typeof item.call_id !== "string")
64
+ continue;
65
+ const result = toolResults.get(item.call_id);
66
+ if (result === undefined)
67
+ continue;
68
+ const sanitized = sanitizeUsageLookupResult(result, [...knownCredentials]);
69
+ if (credentialsChanged) {
70
+ // 新令牌可能已被截断为无法精确匹配的片段;缓存重放同样适用。
71
+ for (const channel of ["stdout", "stderr"]) {
72
+ if (sanitized[`${channel}Truncated`]) {
73
+ sanitized[channel] =
74
+ "[redacted: truncated output omitted after credential rotation]";
75
+ sanitized.credentialsRedacted = true;
76
+ }
77
+ }
78
+ }
79
+ toolResults.set(item.call_id, sanitized);
80
+ item.output = JSON.stringify(sanitized);
81
+ }
82
+ const fetch = this.dependencies.fetch ?? globalThis.fetch;
83
+ if (!modelVerified) {
84
+ const models = await requestChatGptModels(credentials.accessToken, requestSignal, fetch);
85
+ if (!models.some((model) => model.slug === this.model)) {
86
+ throw new ConfigError("The selected ChatGPT model is unavailable for this account. Run howto --chatgpt-models or howto --init to select an available model.");
87
+ }
88
+ modelVerified = true;
89
+ }
90
+ requestSignal.throwIfAborted();
91
+ const parameters = {
92
+ ...initial,
93
+ input: [...input],
94
+ include: ["reasoning.encrypted_content"],
95
+ text: {
96
+ format: request.structuredOutput
97
+ ? {
98
+ type: "json_schema",
99
+ name: "command_usage_generation",
100
+ schema: USAGE_COMMAND_GENERATION_SCHEMA,
101
+ strict: true,
102
+ }
103
+ : { type: "json_object" },
104
+ },
105
+ ...(options.toolsEnabled
106
+ ? {
107
+ tools: [
108
+ {
109
+ type: "function",
110
+ name: USAGE_TOOL_NAME,
111
+ description: USAGE_TOOL_DESCRIPTION,
112
+ parameters: USAGE_TOOL_PARAMETERS,
113
+ strict: true,
114
+ },
115
+ ],
116
+ tool_choice: "auto",
117
+ parallel_tool_calls: false,
118
+ }
119
+ : {}),
120
+ };
121
+ const response = await fetch(RESPONSES_URL, {
122
+ method: "POST",
123
+ headers: {
124
+ Authorization: `Bearer ${credentials.accessToken}`,
125
+ Accept: "text/event-stream",
126
+ "Content-Type": "application/json",
127
+ },
128
+ body: JSON.stringify(parameters),
129
+ redirect: "error",
130
+ signal: requestSignal,
131
+ });
132
+ if (!response.ok) {
133
+ throw await usageChatGptHttpError(response, requestSignal, this.model, options.toolsEnabled);
134
+ }
135
+ const contentType = response.headers.get("content-type");
136
+ if (contentType !== null &&
137
+ contentType.split(";", 1)[0].trim().toLowerCase() !== "text/event-stream") {
138
+ void response.body?.cancel().catch(() => undefined);
139
+ throw new AiProviderError("chatgpt", this.model);
140
+ }
141
+ const output = await collectChatGptUsageOutput(response, requestSignal, this.model, options.toolsEnabled);
142
+ requestSignal.throwIfAborted();
143
+ const calls = [];
144
+ for (const item of output) {
145
+ if (item.type === "function_call") {
146
+ calls.push({
147
+ id: item.call_id,
148
+ name: item.name,
149
+ arguments: parseUsageToolArguments(item.arguments),
150
+ });
151
+ }
152
+ }
153
+ if (calls.length > 0) {
154
+ tracker.register(calls);
155
+ // store:false 会话必须回传完整 reasoning(含加密内容)、消息和调用项。
156
+ input.push(...output);
157
+ return { kind: "tool_calls", calls };
158
+ }
159
+ const rawText = output.map((item) => readCompletedItemText(item, this.model)).join("");
160
+ if (rawText.trim() === "" || Buffer.byteLength(rawText, "utf8") > MAX_OUTPUT_BYTES) {
161
+ throw new AiProviderError("chatgpt", this.model);
162
+ }
163
+ return { kind: "final", rawText };
164
+ }),
165
+ };
166
+ }
167
+ async generateCommands(request, signal) {
168
+ return runChatGptRequest(this.model, signal, this.dependencies, async (requestSignal) => {
169
+ const credentials = await (this.dependencies.getAccessToken ?? getChatGptAccessToken)({
170
+ accountId: this.config.account,
171
+ signal: requestSignal,
172
+ });
173
+ const fetch = this.dependencies.fetch ?? globalThis.fetch;
174
+ const models = await requestChatGptModels(credentials.accessToken, requestSignal, fetch);
175
+ if (!models.some((model) => model.slug === this.model)) {
176
+ throw new ConfigError("The selected ChatGPT model is unavailable for this account. Run howto --chatgpt-models or howto --init to select an available model.");
177
+ }
178
+ requestSignal.throwIfAborted();
179
+ // 使用显式 fetch,不读取 SDK 隐式环境头,也不经过可能记录原始 SSE 的 SDK 解码器。
180
+ const response = await fetch(RESPONSES_URL, {
181
+ method: "POST",
182
+ headers: {
183
+ Authorization: `Bearer ${credentials.accessToken}`,
184
+ Accept: "text/event-stream",
185
+ "Content-Type": "application/json",
186
+ },
187
+ body: JSON.stringify(buildChatGptResponseRequest(this.model, request)),
188
+ redirect: "error",
189
+ signal: requestSignal,
190
+ });
191
+ if (!response.ok)
192
+ throw await chatGptHttpError(response, requestSignal);
193
+ const contentType = response.headers.get("content-type");
194
+ if (contentType !== null &&
195
+ contentType.split(";", 1)[0].trim().toLowerCase() !== "text/event-stream") {
196
+ void response.body?.cancel().catch(() => undefined);
197
+ throw new AiProviderError("chatgpt", this.model);
198
+ }
199
+ return { rawText: await collectChatGptResponse(response, requestSignal, this.model) };
200
+ });
201
+ }
202
+ }
203
+ export function buildChatGptResponseRequest(model, request) {
204
+ return {
205
+ model,
206
+ instructions: request.systemPrompt,
207
+ input: [
208
+ {
209
+ role: "user",
210
+ // JSON mode 的输入校验可能不计入 instructions,需要在用户输入中明确格式。
211
+ content: request.structuredOutput
212
+ ? request.userPrompt
213
+ : `Return JSON matching the instructions.\n${request.userPrompt}`,
214
+ },
215
+ ],
216
+ store: false,
217
+ stream: true,
218
+ text: {
219
+ format: request.structuredOutput
220
+ ? {
221
+ type: "json_schema",
222
+ name: "command_generation",
223
+ description: "Shell command candidates generated for howto.",
224
+ schema: COMMAND_GENERATION_SCHEMA,
225
+ strict: true,
226
+ }
227
+ : { type: "json_object" },
228
+ },
229
+ };
230
+ }
231
+ async function usageChatGptHttpError(response, signal, model, toolsEnabled) {
232
+ if (!toolsEnabled)
233
+ return chatGptHttpError(response, signal);
234
+ let body;
235
+ try {
236
+ const chunks = [];
237
+ for await (const bytes of readChatGptBody(response, signal, 64 * 1024))
238
+ chunks.push(bytes);
239
+ body = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)));
240
+ }
241
+ catch {
242
+ // 非 JSON、过大或解码失败只按 HTTP 状态分类,不回显服务正文。
243
+ }
244
+ if (isExplicitUsageToolsUnsupported(body, response.status)) {
245
+ return new UsageToolsUnsupportedError("chatgpt", model);
246
+ }
247
+ const detail = isRecord(body) && isRecord(body.error) ? body.error : undefined;
248
+ return classifyChatGptHttpError(response.status, typeof detail?.code === "string" ? detail.code : undefined);
249
+ }
250
+ async function collectChatGptUsageOutput(response, signal, model, toolsEnabled) {
251
+ const fail = () => new AiProviderError("chatgpt", model);
252
+ const completed = new Map();
253
+ let completedBytes = 0;
254
+ for await (const frame of decodeChatGptEvents(response, signal)) {
255
+ if (frame.event !== "" &&
256
+ frame.event !== "message" &&
257
+ frame.event !== "error" &&
258
+ !frame.event.startsWith("response."))
259
+ continue;
260
+ if (frame.data === "[DONE]")
261
+ break;
262
+ const event = JSON.parse(frame.data);
263
+ if (!isRecord(event) || typeof event.type !== "string")
264
+ throw fail();
265
+ if (frame.event !== "" && frame.event !== "message" && frame.event !== event.type)
266
+ throw fail();
267
+ if (event.type === "error" || event.type === "response.failed") {
268
+ const error = isRecord(event.response) && isRecord(event.response.error)
269
+ ? event.response.error
270
+ : isRecord(event.error)
271
+ ? event.error
272
+ : event;
273
+ const code = typeof error.code === "string" ? error.code : undefined;
274
+ const status = typeof error.status === "number"
275
+ ? error.status
276
+ : /^(?:invalid_request_error|unsupported_\w+|(?:tools?|function_calling)_not_supported)$/.test(code ?? "")
277
+ ? 400
278
+ : undefined;
279
+ if (toolsEnabled && isExplicitUsageToolsUnsupported(error, status)) {
280
+ throw new UsageToolsUnsupportedError("chatgpt", model);
281
+ }
282
+ throw classifyChatGptHttpError(500, code);
283
+ }
284
+ if (event.type === "response.incomplete" ||
285
+ event.type === "response.refusal.delta" ||
286
+ event.type === "response.refusal.done" ||
287
+ ((event.type === "response.content_part.added" ||
288
+ event.type === "response.content_part.done") &&
289
+ isRecord(event.part) &&
290
+ event.part.type === "refusal"))
291
+ throw fail();
292
+ if (event.type === "response.output_item.done") {
293
+ const index = event.output_index;
294
+ if (typeof index !== "number" ||
295
+ !Number.isSafeInteger(index) ||
296
+ index < 0 ||
297
+ completed.has(index))
298
+ throw fail();
299
+ const item = readCompletedUsageItem(event.item, model);
300
+ completedBytes += Buffer.byteLength(JSON.stringify(item), "utf8");
301
+ if (completedBytes > MAX_OUTPUT_BYTES)
302
+ throw fail();
303
+ completed.set(index, item);
304
+ }
305
+ if (event.type === "response.completed") {
306
+ signal.throwIfAborted();
307
+ const final = event.response;
308
+ if (!isRecord(final) ||
309
+ final.status !== "completed" ||
310
+ final.error != null ||
311
+ final.incomplete_details != null ||
312
+ !Array.isArray(final.output))
313
+ throw fail();
314
+ const items = final.output.length === 0
315
+ ? [...completed].sort(([left], [right]) => left - right).map(([, item]) => item)
316
+ : final.output.map((value, index) => {
317
+ const item = readCompletedUsageItem(value, model);
318
+ const done = completed.get(index);
319
+ // 流中的完整 reasoning(尤其 encrypted_content)以 output_item.done 为准。
320
+ return item.type === "reasoning" && done?.type === "reasoning" && done.id === item.id
321
+ ? done
322
+ : item;
323
+ });
324
+ if (items.length === 0 || Buffer.byteLength(JSON.stringify(items), "utf8") > MAX_OUTPUT_BYTES)
325
+ throw fail();
326
+ return items;
327
+ }
328
+ }
329
+ throw fail();
330
+ }
331
+ function readCompletedUsageItem(item, model) {
332
+ if (!isRecord(item))
333
+ throw new AiProviderError("chatgpt", model);
334
+ if (item.type === "function_call") {
335
+ if (typeof item.call_id !== "string" ||
336
+ item.call_id === "" ||
337
+ typeof item.name !== "string" ||
338
+ item.name === "" ||
339
+ typeof item.arguments !== "string" ||
340
+ (item.status !== undefined && item.status !== "completed"))
341
+ throw new AiProviderError("chatgpt", model);
342
+ }
343
+ else {
344
+ readCompletedItemText(item, model);
345
+ }
346
+ return item;
347
+ }
348
+ async function collectChatGptResponse(response, signal, model) {
349
+ const completedItems = new Map();
350
+ let completedBytes = 0;
351
+ for await (const frame of decodeChatGptEvents(response, signal)) {
352
+ // 忽略其它协议事件;尤其不把未知事件的正文交给日志或异常消息。
353
+ if (frame.event !== "" &&
354
+ frame.event !== "message" &&
355
+ frame.event !== "error" &&
356
+ !frame.event.startsWith("response.")) {
357
+ continue;
358
+ }
359
+ if (frame.data === "[DONE]")
360
+ break;
361
+ const event = JSON.parse(frame.data);
362
+ if (!isRecord(event) || typeof event.type !== "string") {
363
+ throw new AiProviderError("chatgpt", model);
364
+ }
365
+ if (frame.event !== "" && frame.event !== "message" && frame.event !== event.type) {
366
+ throw new AiProviderError("chatgpt", model);
367
+ }
368
+ if (event.type === "error" || event.type === "response.failed") {
369
+ const error = isRecord(event.response) && isRecord(event.response.error)
370
+ ? event.response.error
371
+ : isRecord(event.error)
372
+ ? event.error
373
+ : event;
374
+ throw classifyChatGptHttpError(500, typeof error.code === "string" ? error.code : undefined);
375
+ }
376
+ if (event.type === "response.incomplete" ||
377
+ event.type === "response.refusal.delta" ||
378
+ event.type === "response.refusal.done" ||
379
+ ((event.type === "response.content_part.added" ||
380
+ event.type === "response.content_part.done") &&
381
+ isRecord(event.part) &&
382
+ event.part.type === "refusal")) {
383
+ throw new AiProviderError("chatgpt", model);
384
+ }
385
+ if (event.type === "response.output_item.done") {
386
+ const index = event.output_index;
387
+ if (typeof index !== "number" ||
388
+ !Number.isSafeInteger(index) ||
389
+ index < 0 ||
390
+ completedItems.has(index)) {
391
+ throw new AiProviderError("chatgpt", model);
392
+ }
393
+ const text = readCompletedItemText(event.item, model);
394
+ completedBytes += Buffer.byteLength(text, "utf8");
395
+ if (completedBytes > MAX_OUTPUT_BYTES)
396
+ throw new AiProviderError("chatgpt", model);
397
+ completedItems.set(index, text);
398
+ }
399
+ if (event.type === "response.completed") {
400
+ signal.throwIfAborted();
401
+ return readCompletedText(event.response, model, completedItems);
402
+ }
403
+ }
404
+ throw new AiProviderError("chatgpt", model);
405
+ }
406
+ function readCompletedText(response, model, completedItems) {
407
+ const fail = () => new AiProviderError("chatgpt", model);
408
+ if (!isRecord(response) ||
409
+ response.status !== "completed" ||
410
+ response.error != null ||
411
+ response.incomplete_details != null ||
412
+ !Array.isArray(response.output)) {
413
+ throw fail();
414
+ }
415
+ // 订阅共享流可能只在 output_item.done 携带完整内容,completed 的 output 为空。
416
+ // 只缓存已完成的项;delta/text.done 不能替代完整项或全局完成事件。
417
+ const text = response.output.length === 0
418
+ ? [...completedItems]
419
+ .sort(([left], [right]) => left - right)
420
+ .map(([, value]) => value)
421
+ .join("")
422
+ : response.output.map((item) => readCompletedItemText(item, model)).join("");
423
+ if (text.trim() === "" || Buffer.byteLength(text, "utf8") > MAX_OUTPUT_BYTES)
424
+ throw fail();
425
+ return text;
426
+ }
427
+ function readCompletedItemText(item, model) {
428
+ const fail = () => new AiProviderError("chatgpt", model);
429
+ if (!isRecord(item))
430
+ throw fail();
431
+ if (item.type === "reasoning") {
432
+ if (item.status !== undefined && item.status !== "completed")
433
+ throw fail();
434
+ return "";
435
+ }
436
+ if (item.type !== "message" ||
437
+ item.role !== "assistant" ||
438
+ item.status !== "completed" ||
439
+ !Array.isArray(item.content) ||
440
+ (item.phase != null && item.phase !== "final_answer" && item.phase !== "commentary")) {
441
+ throw fail();
442
+ }
443
+ let text = "";
444
+ for (const part of item.content) {
445
+ if (!isRecord(part) || part.type !== "output_text" || typeof part.text !== "string") {
446
+ throw fail();
447
+ }
448
+ if (item.phase !== "commentary")
449
+ text += part.text;
450
+ }
451
+ if (Buffer.byteLength(text, "utf8") > MAX_OUTPUT_BYTES)
452
+ throw fail();
453
+ return text;
454
+ }
455
+ async function* decodeChatGptEvents(response, signal) {
456
+ let event = "";
457
+ let data = [];
458
+ for await (const line of decodeChatGptLines(response, signal)) {
459
+ if (line === "") {
460
+ if (data.length > 0)
461
+ yield { event, data: data.join("\n") };
462
+ event = "";
463
+ data = [];
464
+ continue;
465
+ }
466
+ const colon = line.indexOf(":");
467
+ const field = colon < 0 ? line : line.slice(0, colon);
468
+ const value = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /, "");
469
+ if (field === "event")
470
+ event = value;
471
+ if (field === "data")
472
+ data.push(value);
473
+ }
474
+ // EOF 不能补全未以空行结束的事件;没有完整 completed 事件即为失败。
475
+ }
476
+ async function* decodeChatGptLines(response, signal) {
477
+ const decoder = new TextDecoder("utf-8", { fatal: true });
478
+ let pending = "";
479
+ for await (const bytes of readChatGptBody(response, signal, MAX_STREAM_BYTES)) {
480
+ pending += decoder.decode(bytes, { stream: true });
481
+ let index;
482
+ while ((index = pending.search(/[\r\n]/)) >= 0) {
483
+ // CRLF 可以恰好分在两个网络块之间,保留末尾 CR 等下一块。
484
+ if (pending[index] === "\r" && index === pending.length - 1)
485
+ break;
486
+ const line = pending.slice(0, index);
487
+ const delimiterLength = pending[index] === "\r" && pending[index + 1] === "\n" ? 2 : 1;
488
+ pending = pending.slice(index + delimiterLength);
489
+ yield line;
490
+ }
491
+ }
492
+ pending += decoder.decode();
493
+ if (pending.endsWith("\r"))
494
+ yield pending.slice(0, -1);
495
+ }
@@ -48,3 +48,11 @@ export const COMMAND_GENERATION_SCHEMA = {
48
48
  },
49
49
  },
50
50
  };
51
+ export const USAGE_COMMAND_GENERATION_SCHEMA = {
52
+ ...COMMAND_GENERATION_SCHEMA,
53
+ required: ["commands", "failureReason"],
54
+ properties: {
55
+ commands: { ...COMMAND_GENERATION_SCHEMA.properties.commands, minItems: 0 },
56
+ failureReason: { type: "string" },
57
+ },
58
+ };
package/dist/ai/errors.js CHANGED
@@ -9,6 +9,12 @@ export class AiProviderError extends Error {
9
9
  this.model = model;
10
10
  }
11
11
  }
12
+ export class UsageToolsUnsupportedError extends AiProviderError {
13
+ constructor(provider, model) {
14
+ super(provider, model);
15
+ this.name = "UsageToolsUnsupportedError";
16
+ }
17
+ }
12
18
  function formatProviderError(provider, model) {
13
19
  return `AI provider request failed (provider: ${provider}, model: ${sanitizeUserVisibleErrorMessage(model)})`;
14
20
  }
package/dist/ai/gemini.js CHANGED
@@ -1,12 +1,96 @@
1
- import { GoogleGenAI, } from "@google/genai";
2
- import { COMMAND_GENERATION_SCHEMA } from "./command-schema.js";
1
+ import { GoogleGenAI, FunctionCallingConfigMode, } from "@google/genai";
2
+ import { COMMAND_GENERATION_SCHEMA, USAGE_COMMAND_GENERATION_SCHEMA } from "./command-schema.js";
3
3
  import { AiProviderError } from "./errors.js";
4
+ import { runUsageProviderRequest, USAGE_TOOL_DESCRIPTION, USAGE_TOOL_NAME, USAGE_TOOL_PARAMETERS, UsageReplyTracker, } from "./usage-session.js";
4
5
  export class GeminiCommandProvider {
5
6
  client;
6
7
  model;
7
- constructor(config) {
8
+ apiKey;
9
+ timeoutMilliseconds;
10
+ constructor(config, dependencies = {}) {
8
11
  this.model = config.model;
9
- this.client = new GoogleGenAI(buildGeminiClientOptions(config));
12
+ this.apiKey = config.apiKey;
13
+ this.timeoutMilliseconds = dependencies.timeoutMilliseconds;
14
+ this.client = dependencies.client ?? new GoogleGenAI(buildGeminiClientOptions(config));
15
+ }
16
+ createUsageSession(request) {
17
+ const contents = [{ role: "user", parts: [{ text: request.userPrompt }] }];
18
+ const tracker = new UsageReplyTracker("gemini", this.model);
19
+ const associations = new Map();
20
+ let turn = 0;
21
+ return {
22
+ getKnownCredentials: () => (this.apiKey === undefined ? [] : [this.apiKey]),
23
+ next: (replies, options, signal) => runUsageProviderRequest("gemini", this.model, signal, this.timeoutMilliseconds, options.toolsEnabled, async (requestSignal) => {
24
+ const fresh = tracker.accept(replies);
25
+ if (fresh.length > 0) {
26
+ contents.push({
27
+ role: "user",
28
+ parts: fresh.map((reply) => {
29
+ const association = associations.get(reply.callId);
30
+ if (association === undefined)
31
+ throw new AiProviderError("gemini", this.model);
32
+ return {
33
+ functionResponse: {
34
+ name: association.name,
35
+ ...(association.nativeId === undefined ? {} : { id: association.nativeId }),
36
+ response: { output: reply.result },
37
+ },
38
+ };
39
+ }),
40
+ });
41
+ }
42
+ const parameters = {
43
+ model: this.model,
44
+ contents: [...contents],
45
+ config: {
46
+ systemInstruction: request.systemPrompt,
47
+ responseMimeType: "application/json",
48
+ abortSignal: requestSignal,
49
+ httpOptions: { retryOptions: { attempts: 1 } },
50
+ automaticFunctionCalling: { disable: true },
51
+ ...(request.structuredOutput
52
+ ? { responseJsonSchema: USAGE_COMMAND_GENERATION_SCHEMA }
53
+ : {}),
54
+ ...(options.toolsEnabled
55
+ ? {
56
+ tools: [
57
+ {
58
+ functionDeclarations: [
59
+ {
60
+ name: USAGE_TOOL_NAME,
61
+ description: USAGE_TOOL_DESCRIPTION,
62
+ parametersJsonSchema: USAGE_TOOL_PARAMETERS,
63
+ },
64
+ ],
65
+ },
66
+ ],
67
+ toolConfig: {
68
+ functionCallingConfig: { mode: FunctionCallingConfigMode.AUTO },
69
+ },
70
+ }
71
+ : {}),
72
+ },
73
+ };
74
+ const response = await this.client.models.generateContent(parameters);
75
+ requestSignal.throwIfAborted();
76
+ const content = response.candidates?.[0]?.content;
77
+ const calls = readGeminiUsageCalls(content, this.model, turn++);
78
+ if (calls.length > 0) {
79
+ tracker.register(calls.map(({ call }) => call));
80
+ for (const { call, nativeId } of calls) {
81
+ associations.set(call.id, { name: call.name, nativeId });
82
+ }
83
+ // 不用 SDK functionCalls getter 重建消息,原样保留所有 model parts 与签名。
84
+ contents.push({ ...content, role: "model" });
85
+ return { kind: "tool_calls", calls: calls.map(({ call }) => call) };
86
+ }
87
+ const rawText = extractGeminiResponseText(response);
88
+ if (rawText === undefined || rawText.trim() === "") {
89
+ throw new AiProviderError("gemini", this.model);
90
+ }
91
+ return { kind: "final", rawText };
92
+ }),
93
+ };
10
94
  }
11
95
  async generateCommands(request, signal) {
12
96
  let rawText;
@@ -23,6 +107,35 @@ export class GeminiCommandProvider {
23
107
  return { rawText };
24
108
  }
25
109
  }
110
+ function readGeminiUsageCalls(content, model, turn) {
111
+ const parts = asRecord(content)?.parts;
112
+ if (!Array.isArray(parts) || parts.length === 0)
113
+ throw new AiProviderError("gemini", model);
114
+ const calls = [];
115
+ for (const [index, value] of parts.entries()) {
116
+ const part = asRecord(value);
117
+ if (part === undefined ||
118
+ (Object.hasOwn(part, "thought") && typeof part.thought !== "boolean") ||
119
+ (Object.hasOwn(part, "text") && typeof part.text !== "string")) {
120
+ throw new AiProviderError("gemini", model);
121
+ }
122
+ if (!Object.hasOwn(part, "functionCall"))
123
+ continue;
124
+ const call = asRecord(part.functionCall);
125
+ if (call === undefined ||
126
+ typeof call.name !== "string" ||
127
+ call.name === "" ||
128
+ (call.id !== undefined && (typeof call.id !== "string" || call.id === ""))) {
129
+ throw new AiProviderError("gemini", model);
130
+ }
131
+ const nativeId = call.id;
132
+ calls.push({
133
+ call: { id: nativeId ?? `gemini-${turn}-${index}`, name: call.name, arguments: call.args },
134
+ nativeId,
135
+ });
136
+ }
137
+ return calls;
138
+ }
26
139
  export function extractGeminiResponseText(response) {
27
140
  // SDK 的 text getter 会记录未知字段;这里只读取首候选的已知字段。
28
141
  const candidates = asRecord(response)?.candidates;
package/dist/ai/index.js CHANGED
@@ -1,7 +1,10 @@
1
+ import { ChatGptCommandProvider } from "./chatgpt.js";
1
2
  import { GeminiCommandProvider } from "./gemini.js";
2
3
  import { OpenAiCommandProvider } from "./openai.js";
3
4
  export function createCommandProvider(config) {
4
5
  switch (config.aiProvider) {
6
+ case "chatgpt":
7
+ return new ChatGptCommandProvider(config.chatgpt);
5
8
  case "openai":
6
9
  return new OpenAiCommandProvider(config.openai);
7
10
  case "gemini":
@@ -12,4 +15,4 @@ export function createCommandProvider(config) {
12
15
  }
13
16
  }
14
17
  }
15
- export { AiProviderError } from "./errors.js";
18
+ export { AiProviderError, UsageToolsUnsupportedError } from "./errors.js";