@zqagent/core 0.3.10 → 0.3.12

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 (37) hide show
  1. package/dist/{TurnEngine-BPKhWuSI.d.cts → TurnEngine-BSciNywD.d.cts} +23 -4
  2. package/dist/{TurnEngine-DtGEuVLT.d.ts → TurnEngine-BU4R7q_0.d.ts} +23 -4
  3. package/dist/index.cjs +144 -21
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.cts +53 -4
  6. package/dist/index.d.ts +53 -4
  7. package/dist/index.js +142 -21
  8. package/dist/index.js.map +1 -1
  9. package/dist/internal/engine/FileLogHook.d.cts +2 -1
  10. package/dist/internal/engine/FileLogHook.d.ts +2 -1
  11. package/dist/internal/llmConfig.cjs +15 -0
  12. package/dist/internal/llmConfig.cjs.map +1 -1
  13. package/dist/internal/llmConfig.d.cts +15 -0
  14. package/dist/internal/llmConfig.d.ts +15 -0
  15. package/dist/internal/llmConfig.js +15 -0
  16. package/dist/internal/llmConfig.js.map +1 -1
  17. package/dist/internal/providers/diagnostics.cjs +39 -5
  18. package/dist/internal/providers/diagnostics.cjs.map +1 -1
  19. package/dist/internal/providers/diagnostics.d.cts +35 -3
  20. package/dist/internal/providers/diagnostics.d.ts +35 -3
  21. package/dist/internal/providers/diagnostics.js +34 -4
  22. package/dist/internal/providers/diagnostics.js.map +1 -1
  23. package/dist/internal/providers/models.cjs.map +1 -1
  24. package/dist/internal/providers/models.js.map +1 -1
  25. package/dist/internal/update/controller.cjs +2 -2
  26. package/dist/internal/update/controller.cjs.map +1 -1
  27. package/dist/internal/update/controller.js +1 -1
  28. package/dist/internal/update/platform.cjs +2 -2
  29. package/dist/internal/update/platform.cjs.map +1 -1
  30. package/dist/internal/update/platform.js +1 -1
  31. package/dist/tools/explore.cjs +76 -4
  32. package/dist/tools/explore.cjs.map +1 -1
  33. package/dist/tools/explore.d.cts +2 -1
  34. package/dist/tools/explore.d.ts +2 -1
  35. package/dist/tools/explore.js +76 -4
  36. package/dist/tools/explore.js.map +1 -1
  37. package/package.json +4 -3
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
- import { M as Mode, S as ShellPolicy, E as EngineHook, C as CompactionStartInfo, a as CompactionDoneInfo, b as EventType, c as EngineErrorInfo, P as ProviderClient, T as TurnEngine } from './TurnEngine-BPKhWuSI.cjs';
2
- export { A as ApprovalOutcome, d as Approver, e as CompactionTrigger, D as Decision, O as OpenAIProvider, f as PermissionEngine, g as PermissionRequest, h as ShellSandboxStatus, i as TurnEngineOpts, W as WsEvent } from './TurnEngine-BPKhWuSI.cjs';
3
- import { T as TokenUsage, R as ReasoningEffort, M as Message } from './types-BYyXWWPW.cjs';
1
+ import { M as Mode, S as ShellPolicy, E as EngineHook, C as CompactionStartInfo, a as CompactionDoneInfo, b as EventType, c as EngineErrorInfo, P as ProviderClient, T as TurnEngine } from './TurnEngine-BSciNywD.cjs';
2
+ export { A as ApprovalOutcome, d as Approver, e as CompactionTrigger, D as Decision, O as OpenAIProvider, f as PermissionEngine, g as PermissionRequest, h as ShellSandboxStatus, i as TurnEngineOpts, W as WsEvent } from './TurnEngine-BSciNywD.cjs';
3
+ import { T as TokenUsage, M as Message, R as ReasoningEffort } from './types-BYyXWWPW.cjs';
4
4
  export { A as ATTACHMENT_DIR, d as AssistantTurn, e as AttachmentError, f as MAX_ATTACHMENTS, g as MAX_ATTACHMENT_BYTES, b as MessageAttachment, c as StoredAttachment, S as StreamChunk, h as ToolCall, a as ToolSchema, U as UPLOAD_DIR, W as WorkspaceFileRef, i as attachmentBytes, j as buildWorkspaceFileNotice, k as hasNonImageAttachments, n as normalizeAttachments, r as readStoredAttachment, s as saveAttachments, l as saveAttachmentsToWorkspace, m as splitByCapability, o as stripAttachments } from './types-BYyXWWPW.cjs';
5
5
  import { T as ToolRegistry } from './ToolRegistry-DouDvn9E.cjs';
6
6
  export { R as RiskClass, a as ToolMetadata, b as ToolSpec } from './ToolRegistry-DouDvn9E.cjs';
@@ -24,6 +24,7 @@ export { registerMediaTool } from './tools/media.cjs';
24
24
  export { QuestionHandler, parsePicks, registerAskTool, setQuestionHandler } from './tools/ask.cjs';
25
25
  export { PlanHandler, PlanReply, interpretPlanReply, isAffirmativeText, isRejectionText, registerPlanTool, setPlanHandler } from './internal/tools/plan.cjs';
26
26
  export { DirectoryHandler, registerDirectoryTool, setDirectoryHandler } from './tools/directories.cjs';
27
+ import { ApiMode } from './internal/providers/diagnostics.cjs';
27
28
  import 'openai/resources/chat/completions.js';
28
29
  import 'openai/core.mjs';
29
30
  import '@zqagent/shared/model-capabilities';
@@ -323,6 +324,50 @@ declare class MarkdownRenderer {
323
324
  private _fgReset;
324
325
  }
325
326
 
327
+ /**
328
+ * 会话历史里「工具调用 ↔ 工具结果」的配对修复
329
+ *
330
+ * OpenAI 兼容接口要求:带 `tool_calls` 的 assistant 消息,之后必须**逐条**跟随
331
+ * 对应的 `tool` 消息(`tool_call_id` 一一对应),否则整个请求直接 400:
332
+ *
333
+ * An assistant message with 'tool_calls' must be followed by tool messages
334
+ * responding to each 'tool_call_id'. (insufficient tool messages following
335
+ * tool_calls message)
336
+ *
337
+ * 历史里出现这种「悬空」调用很常见,属于中断/崩溃后的正常残留:
338
+ * - 用户在工具执行途中 Ctrl+C,退出前把 `engine.messages` 原样落盘;
339
+ * - 进程被杀、断电,落盘时正好停在「assistant 已追加、结果还没写回」;
340
+ * - 从旧版本(还没有清洗逻辑)恢复的会话。
341
+ *
342
+ * 这些历史一旦被原样回放,之后**每一条消息**都会失败——用户看到的是一进会话
343
+ * 就报 400,且换模型也没用。因此发送前必须修掉,而不是只在新建会话时清一次。
344
+ *
345
+ * 修复规则(保守:宁可少一段工具调用,也不改动其它内容):
346
+ * 1. assistant 的 `tool_calls` 只保留「紧随其后有 tool 结果」的那些;
347
+ * 2. 一条都不剩时去掉 `tool_calls` 字段——若正文也空了,则整条消息丢弃
348
+ * (空 assistant 消息部分供应商同样会拒绝);
349
+ * 3. 没有对应调用的孤立 tool 消息丢弃(它同样会触发 400)。
350
+ */
351
+
352
+ interface RepairResult {
353
+ messages: Message[];
354
+ /** 被丢弃的「没有结果」的工具调用数 */
355
+ droppedCalls: number;
356
+ /** 被丢弃的孤立工具结果数 */
357
+ droppedResults: number;
358
+ /** 因为「只剩空正文」而被整条丢弃的 assistant 消息数 */
359
+ droppedMessages: number;
360
+ }
361
+ /**
362
+ * 修复工具调用配对,返回新数组(不修改入参)。
363
+ *
364
+ * 只有紧随 assistant 的连续 tool 消息算作它的结果——这也是 OpenAI 协议本身的
365
+ * 要求;更远位置的 tool 消息一律视为孤立结果。
366
+ */
367
+ declare function repairToolCallHistoryDetailed(messages: Message[]): RepairResult;
368
+ /** 修复工具调用配对(只看结果) */
369
+ declare function repairToolCallHistory(messages: Message[]): Message[];
370
+
326
371
  /**
327
372
  * Agent 提示词的多语言形状。
328
373
  *
@@ -1054,6 +1099,10 @@ interface CreateEngineOpts {
1054
1099
  * DeepSeek 自动跳过。
1055
1100
  */
1056
1101
  reasoningEffort?: ReasoningEffort;
1102
+ /** 单次请求超时(毫秒)。缺省取 OPENAI_TIMEOUT_MS,再缺省 10 分钟 */
1103
+ timeoutMs?: number | null;
1104
+ /** API 模式。缺省取 OPENAI_FORCE_API_MODE,再缺省 auto(Responses 优先) */
1105
+ apiMode?: ApiMode | null;
1057
1106
  /** 命令白名单(Auto 模式下自动放行的命令前缀,默认空数组) */
1058
1107
  allowedCommands?: string[];
1059
1108
  /**
@@ -1141,4 +1190,4 @@ interface CreateEngineOpts {
1141
1190
  */
1142
1191
  declare function createDefaultEngine(opts: CreateEngineOpts): TurnEngine;
1143
1192
 
1144
- export { type AgentDef, AgentRegistry, BUILTIN_AGENTS, CODE_INSTRUCTIONS, COWORK_INSTRUCTIONS, CompactionDoneInfo, CompactionStartInfo, CompositeHook, type ConfinementResult, ConsoleHook, type ConsoleHookOptions, type CreateEngineOpts, DEFAULT_ALLOWED_COMMANDS, DISCUSS_MODE_CONTEXT, type DownloadResult, EngineErrorInfo, EngineHook, EventType, type GitResult, MCP_CALL_TOOL, MCP_GUIDANCE, MCP_SEARCH_TOOL, MarkdownRenderer, McpBuiltinContext, type McpConnectResult, type McpLazyOptions, McpManager, type McpManagerOptions, McpServerConfig, Message, Mode, OCR_GUIDANCE, PLAN_MODE_CONTEXT, PROMPT_LANGS, type PermissionConfig, type PromptLang, type PromptSet, ProviderClient, ReasoningEffort, type ResolveVcsOptions, type ResolvedBin, type ResolvedMedia, type RestoreResult, SHADOW_DIR, SandboxMode, SandboxOptions, SessionVcs, ShellPolicy, SubagentHook, type TerminalMetaView, type TerminalRecordView, type TerminalSource, TokenUsage, ToolRegistry, type TurnCommit, TurnEngine, type VcsConfigMode, VcsHook, type VcsMode, type VcsPlan, agentRef, assessCommand, buildEnvBlock, buildExplorerInstructions, buildInstructions, createDefaultEngine, downloadFfmpeg, getPrompts, gitMessage, gitOk, installHints, isGitRepo, loadPermissionConfig, matchPromptLang, normalizePromptLang, promptSets, registerTerminalTools, resetFfmpegCache, resolveMedia, resolveVcsPlan, runGit, sessionIndexPath };
1193
+ export { type AgentDef, AgentRegistry, BUILTIN_AGENTS, CODE_INSTRUCTIONS, COWORK_INSTRUCTIONS, CompactionDoneInfo, CompactionStartInfo, CompositeHook, type ConfinementResult, ConsoleHook, type ConsoleHookOptions, type CreateEngineOpts, DEFAULT_ALLOWED_COMMANDS, DISCUSS_MODE_CONTEXT, type DownloadResult, EngineErrorInfo, EngineHook, EventType, type GitResult, MCP_CALL_TOOL, MCP_GUIDANCE, MCP_SEARCH_TOOL, MarkdownRenderer, McpBuiltinContext, type McpConnectResult, type McpLazyOptions, McpManager, type McpManagerOptions, McpServerConfig, Message, Mode, OCR_GUIDANCE, PLAN_MODE_CONTEXT, PROMPT_LANGS, type PermissionConfig, type PromptLang, type PromptSet, ProviderClient, ReasoningEffort, type RepairResult, type ResolveVcsOptions, type ResolvedBin, type ResolvedMedia, type RestoreResult, SHADOW_DIR, SandboxMode, SandboxOptions, SessionVcs, ShellPolicy, SubagentHook, type TerminalMetaView, type TerminalRecordView, type TerminalSource, TokenUsage, ToolRegistry, type TurnCommit, TurnEngine, type VcsConfigMode, VcsHook, type VcsMode, type VcsPlan, agentRef, assessCommand, buildEnvBlock, buildExplorerInstructions, buildInstructions, createDefaultEngine, downloadFfmpeg, getPrompts, gitMessage, gitOk, installHints, isGitRepo, loadPermissionConfig, matchPromptLang, normalizePromptLang, promptSets, registerTerminalTools, repairToolCallHistory, repairToolCallHistoryDetailed, resetFfmpegCache, resolveMedia, resolveVcsPlan, runGit, sessionIndexPath };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { M as Mode, S as ShellPolicy, E as EngineHook, C as CompactionStartInfo, a as CompactionDoneInfo, b as EventType, c as EngineErrorInfo, P as ProviderClient, T as TurnEngine } from './TurnEngine-DtGEuVLT.js';
2
- export { A as ApprovalOutcome, d as Approver, e as CompactionTrigger, D as Decision, O as OpenAIProvider, f as PermissionEngine, g as PermissionRequest, h as ShellSandboxStatus, i as TurnEngineOpts, W as WsEvent } from './TurnEngine-DtGEuVLT.js';
3
- import { T as TokenUsage, R as ReasoningEffort, M as Message } from './types-BYyXWWPW.js';
1
+ import { M as Mode, S as ShellPolicy, E as EngineHook, C as CompactionStartInfo, a as CompactionDoneInfo, b as EventType, c as EngineErrorInfo, P as ProviderClient, T as TurnEngine } from './TurnEngine-BU4R7q_0.js';
2
+ export { A as ApprovalOutcome, d as Approver, e as CompactionTrigger, D as Decision, O as OpenAIProvider, f as PermissionEngine, g as PermissionRequest, h as ShellSandboxStatus, i as TurnEngineOpts, W as WsEvent } from './TurnEngine-BU4R7q_0.js';
3
+ import { T as TokenUsage, M as Message, R as ReasoningEffort } from './types-BYyXWWPW.js';
4
4
  export { A as ATTACHMENT_DIR, d as AssistantTurn, e as AttachmentError, f as MAX_ATTACHMENTS, g as MAX_ATTACHMENT_BYTES, b as MessageAttachment, c as StoredAttachment, S as StreamChunk, h as ToolCall, a as ToolSchema, U as UPLOAD_DIR, W as WorkspaceFileRef, i as attachmentBytes, j as buildWorkspaceFileNotice, k as hasNonImageAttachments, n as normalizeAttachments, r as readStoredAttachment, s as saveAttachments, l as saveAttachmentsToWorkspace, m as splitByCapability, o as stripAttachments } from './types-BYyXWWPW.js';
5
5
  import { T as ToolRegistry } from './ToolRegistry-Cy0fQxrb.js';
6
6
  export { R as RiskClass, a as ToolMetadata, b as ToolSpec } from './ToolRegistry-Cy0fQxrb.js';
@@ -24,6 +24,7 @@ export { registerMediaTool } from './tools/media.js';
24
24
  export { QuestionHandler, parsePicks, registerAskTool, setQuestionHandler } from './tools/ask.js';
25
25
  export { PlanHandler, PlanReply, interpretPlanReply, isAffirmativeText, isRejectionText, registerPlanTool, setPlanHandler } from './internal/tools/plan.js';
26
26
  export { DirectoryHandler, registerDirectoryTool, setDirectoryHandler } from './tools/directories.js';
27
+ import { ApiMode } from './internal/providers/diagnostics.js';
27
28
  import 'openai/resources/chat/completions.js';
28
29
  import 'openai/core.mjs';
29
30
  import '@zqagent/shared/model-capabilities';
@@ -323,6 +324,50 @@ declare class MarkdownRenderer {
323
324
  private _fgReset;
324
325
  }
325
326
 
327
+ /**
328
+ * 会话历史里「工具调用 ↔ 工具结果」的配对修复
329
+ *
330
+ * OpenAI 兼容接口要求:带 `tool_calls` 的 assistant 消息,之后必须**逐条**跟随
331
+ * 对应的 `tool` 消息(`tool_call_id` 一一对应),否则整个请求直接 400:
332
+ *
333
+ * An assistant message with 'tool_calls' must be followed by tool messages
334
+ * responding to each 'tool_call_id'. (insufficient tool messages following
335
+ * tool_calls message)
336
+ *
337
+ * 历史里出现这种「悬空」调用很常见,属于中断/崩溃后的正常残留:
338
+ * - 用户在工具执行途中 Ctrl+C,退出前把 `engine.messages` 原样落盘;
339
+ * - 进程被杀、断电,落盘时正好停在「assistant 已追加、结果还没写回」;
340
+ * - 从旧版本(还没有清洗逻辑)恢复的会话。
341
+ *
342
+ * 这些历史一旦被原样回放,之后**每一条消息**都会失败——用户看到的是一进会话
343
+ * 就报 400,且换模型也没用。因此发送前必须修掉,而不是只在新建会话时清一次。
344
+ *
345
+ * 修复规则(保守:宁可少一段工具调用,也不改动其它内容):
346
+ * 1. assistant 的 `tool_calls` 只保留「紧随其后有 tool 结果」的那些;
347
+ * 2. 一条都不剩时去掉 `tool_calls` 字段——若正文也空了,则整条消息丢弃
348
+ * (空 assistant 消息部分供应商同样会拒绝);
349
+ * 3. 没有对应调用的孤立 tool 消息丢弃(它同样会触发 400)。
350
+ */
351
+
352
+ interface RepairResult {
353
+ messages: Message[];
354
+ /** 被丢弃的「没有结果」的工具调用数 */
355
+ droppedCalls: number;
356
+ /** 被丢弃的孤立工具结果数 */
357
+ droppedResults: number;
358
+ /** 因为「只剩空正文」而被整条丢弃的 assistant 消息数 */
359
+ droppedMessages: number;
360
+ }
361
+ /**
362
+ * 修复工具调用配对,返回新数组(不修改入参)。
363
+ *
364
+ * 只有紧随 assistant 的连续 tool 消息算作它的结果——这也是 OpenAI 协议本身的
365
+ * 要求;更远位置的 tool 消息一律视为孤立结果。
366
+ */
367
+ declare function repairToolCallHistoryDetailed(messages: Message[]): RepairResult;
368
+ /** 修复工具调用配对(只看结果) */
369
+ declare function repairToolCallHistory(messages: Message[]): Message[];
370
+
326
371
  /**
327
372
  * Agent 提示词的多语言形状。
328
373
  *
@@ -1054,6 +1099,10 @@ interface CreateEngineOpts {
1054
1099
  * DeepSeek 自动跳过。
1055
1100
  */
1056
1101
  reasoningEffort?: ReasoningEffort;
1102
+ /** 单次请求超时(毫秒)。缺省取 OPENAI_TIMEOUT_MS,再缺省 10 分钟 */
1103
+ timeoutMs?: number | null;
1104
+ /** API 模式。缺省取 OPENAI_FORCE_API_MODE,再缺省 auto(Responses 优先) */
1105
+ apiMode?: ApiMode | null;
1057
1106
  /** 命令白名单(Auto 模式下自动放行的命令前缀,默认空数组) */
1058
1107
  allowedCommands?: string[];
1059
1108
  /**
@@ -1141,4 +1190,4 @@ interface CreateEngineOpts {
1141
1190
  */
1142
1191
  declare function createDefaultEngine(opts: CreateEngineOpts): TurnEngine;
1143
1192
 
1144
- export { type AgentDef, AgentRegistry, BUILTIN_AGENTS, CODE_INSTRUCTIONS, COWORK_INSTRUCTIONS, CompactionDoneInfo, CompactionStartInfo, CompositeHook, type ConfinementResult, ConsoleHook, type ConsoleHookOptions, type CreateEngineOpts, DEFAULT_ALLOWED_COMMANDS, DISCUSS_MODE_CONTEXT, type DownloadResult, EngineErrorInfo, EngineHook, EventType, type GitResult, MCP_CALL_TOOL, MCP_GUIDANCE, MCP_SEARCH_TOOL, MarkdownRenderer, McpBuiltinContext, type McpConnectResult, type McpLazyOptions, McpManager, type McpManagerOptions, McpServerConfig, Message, Mode, OCR_GUIDANCE, PLAN_MODE_CONTEXT, PROMPT_LANGS, type PermissionConfig, type PromptLang, type PromptSet, ProviderClient, ReasoningEffort, type ResolveVcsOptions, type ResolvedBin, type ResolvedMedia, type RestoreResult, SHADOW_DIR, SandboxMode, SandboxOptions, SessionVcs, ShellPolicy, SubagentHook, type TerminalMetaView, type TerminalRecordView, type TerminalSource, TokenUsage, ToolRegistry, type TurnCommit, TurnEngine, type VcsConfigMode, VcsHook, type VcsMode, type VcsPlan, agentRef, assessCommand, buildEnvBlock, buildExplorerInstructions, buildInstructions, createDefaultEngine, downloadFfmpeg, getPrompts, gitMessage, gitOk, installHints, isGitRepo, loadPermissionConfig, matchPromptLang, normalizePromptLang, promptSets, registerTerminalTools, resetFfmpegCache, resolveMedia, resolveVcsPlan, runGit, sessionIndexPath };
1193
+ export { type AgentDef, AgentRegistry, BUILTIN_AGENTS, CODE_INSTRUCTIONS, COWORK_INSTRUCTIONS, CompactionDoneInfo, CompactionStartInfo, CompositeHook, type ConfinementResult, ConsoleHook, type ConsoleHookOptions, type CreateEngineOpts, DEFAULT_ALLOWED_COMMANDS, DISCUSS_MODE_CONTEXT, type DownloadResult, EngineErrorInfo, EngineHook, EventType, type GitResult, MCP_CALL_TOOL, MCP_GUIDANCE, MCP_SEARCH_TOOL, MarkdownRenderer, McpBuiltinContext, type McpConnectResult, type McpLazyOptions, McpManager, type McpManagerOptions, McpServerConfig, Message, Mode, OCR_GUIDANCE, PLAN_MODE_CONTEXT, PROMPT_LANGS, type PermissionConfig, type PromptLang, type PromptSet, ProviderClient, ReasoningEffort, type RepairResult, type ResolveVcsOptions, type ResolvedBin, type ResolvedMedia, type RestoreResult, SHADOW_DIR, SandboxMode, SandboxOptions, SessionVcs, ShellPolicy, SubagentHook, type TerminalMetaView, type TerminalRecordView, type TerminalSource, TokenUsage, ToolRegistry, type TurnCommit, TurnEngine, type VcsConfigMode, VcsHook, type VcsMode, type VcsPlan, agentRef, assessCommand, buildEnvBlock, buildExplorerInstructions, buildInstructions, createDefaultEngine, downloadFfmpeg, getPrompts, gitMessage, gitOk, installHints, isGitRepo, loadPermissionConfig, matchPromptLang, normalizePromptLang, promptSets, registerTerminalTools, repairToolCallHistory, repairToolCallHistoryDetailed, resetFfmpegCache, resolveMedia, resolveVcsPlan, runGit, sessionIndexPath };
package/dist/index.js CHANGED
@@ -216,10 +216,22 @@ function authErrorHints(message, code = "") {
216
216
  "\u51ED\u636E\u65E0\u6548\uFF1A\u82E5\u7528\u7684\u662F\u300C\u5FD7\u524D\u5927\u6A21\u578B\uFF08\u5185\u7F6E\uFF09\u300D\uFF0C\u5728\u8282\u70B9\u8BBE\u7F6E\u7684\u6A21\u578B\u9875\u70B9\u300C\u5237\u65B0\u5185\u7F6E\u6A21\u578B\u300D\u91CD\u65B0\u9886\u53D6 Key\uFF08\u5728\u63A7\u5236\u53F0\u91CD\u7F6E\u8FC7 Key \u540E\u9700\u8981\u8FD9\u4E00\u6B65\uFF09\uFF1B\u82E5\u662F\u81EA\u586B\u7684\u4F9B\u5E94\u5546\uFF0C\u8BF7\u68C0\u67E5 Key \u662F\u5426\u6B63\u786E\u6216\u5DF2\u8FC7\u671F"
217
217
  ];
218
218
  }
219
+ function toolCallHistoryHints(message, code = "") {
220
+ const text = `${message} ${code}`;
221
+ if (!/tool_calls|tool[_ ]?call[_ ]?id/i.test(text) || !/must be followed by tool messages|insufficient tool messages|no tool output found|tool messages responding/i.test(
222
+ text
223
+ )) {
224
+ return [];
225
+ }
226
+ return [
227
+ "\u8FD9\u4E0D\u662F\u6A21\u578B\u6216\u4F59\u989D\u95EE\u9898\uFF1A\u4F1A\u8BDD\u5386\u53F2\u91CC\u6709\u4E00\u6761\u300C\u5DE5\u5177\u8C03\u7528\u6CA1\u6709\u62FF\u5230\u7ED3\u679C\u300D\u7684\u8BB0\u5F55\uFF08\u901A\u5E38\u662F\u4E0A\u6B21\u5728\u5DE5\u5177\u6267\u884C\u4E2D\u6309\u4E86 Ctrl+C\uFF0C\u6216\u8FDB\u7A0B\u88AB\u4E2D\u65AD\uFF09",
228
+ "\u5F15\u64CE\u5DF2\u81EA\u52A8\u6E05\u7406\u5E76\u91CD\u8BD5\uFF1B\u5982\u679C\u4ECD\u62A5\u540C\u6837\u7684\u9519\u8BEF\uFF0C\u7528 /new \u5F00\u4E00\u4E2A\u65B0\u4F1A\u8BDD\u5373\u53EF\uFF08\u65E7\u4F1A\u8BDD\u7684\u5386\u53F2\u91CC\u8FD8\u7559\u7740\u8FD9\u6761\u8BB0\u5F55\uFF09"
229
+ ];
230
+ }
219
231
  function paramErrorHints(message, code = "") {
220
232
  const text = `${message} ${code}`;
221
233
  const hints = [];
222
- if (/not[_\s]*(activated|enabled|purchased)|arrearage|quota|subscription|insufficient|未开通|欠费|额度|余额不足/i.test(
234
+ if (/not[_\s]*(activated|enabled|purchased)|arrearage|quota|subscription|billing|未开通|欠费|额度|余额不足|insufficient[_\s]*(quota|balance|credit|funds)/i.test(
223
235
  text
224
236
  )) {
225
237
  hints.push(
@@ -243,9 +255,23 @@ function paramErrorHints(message, code = "") {
243
255
  }
244
256
  return hints;
245
257
  }
246
- function llmTimeoutMs() {
258
+ var DEFAULT_LLM_TIMEOUT_MS = 6e5;
259
+ function normLlmTimeoutMs(v) {
260
+ if (v === null || v === void 0 || v === "") return null;
261
+ const n = Number(v);
262
+ if (!Number.isFinite(n) || n <= 0) return null;
263
+ return Math.min(Math.round(n), 30 * 6e4);
264
+ }
265
+ function llmTimeoutMs(explicit) {
266
+ const fromArg = normLlmTimeoutMs(explicit);
267
+ if (fromArg) return fromArg;
247
268
  const n = Number(process.env.OPENAI_TIMEOUT_MS);
248
- return Number.isFinite(n) && n > 0 ? n : 6e5;
269
+ return Number.isFinite(n) && n > 0 ? n : DEFAULT_LLM_TIMEOUT_MS;
270
+ }
271
+ function normApiMode(v) {
272
+ const s = typeof v === "string" ? v.trim().toLowerCase() : "";
273
+ if (s === "auto" || s === "responses" || s === "chat") return s;
274
+ return null;
249
275
  }
250
276
  function llmStreamIdleMs() {
251
277
  const n = Number(process.env.OPENAI_STREAM_IDLE_MS);
@@ -2091,6 +2117,76 @@ function applyToolResultBudget(tool, result, opts = {}) {
2091
2117
  return { content, truncated: true, savedPath };
2092
2118
  }
2093
2119
 
2120
+ // src/engine/history.ts
2121
+ function repairToolCallHistoryDetailed(messages) {
2122
+ const out = [];
2123
+ let droppedCalls = 0;
2124
+ let droppedResults = 0;
2125
+ let droppedMessages = 0;
2126
+ let i = 0;
2127
+ while (i < messages.length) {
2128
+ const m = messages[i];
2129
+ if (m.role === "tool") {
2130
+ droppedResults += 1;
2131
+ i += 1;
2132
+ continue;
2133
+ }
2134
+ const calls = m.role === "assistant" ? m.tool_calls : void 0;
2135
+ if (!calls?.length) {
2136
+ if (m.role === "assistant" && m.tool_calls) {
2137
+ const { tool_calls, ...rest } = m;
2138
+ void tool_calls;
2139
+ out.push(rest);
2140
+ } else {
2141
+ out.push(m);
2142
+ }
2143
+ i += 1;
2144
+ continue;
2145
+ }
2146
+ const responders = /* @__PURE__ */ new Map();
2147
+ const notices = [];
2148
+ let j = i + 1;
2149
+ while (j < messages.length) {
2150
+ const t = messages[j];
2151
+ if (t.role === "notice") {
2152
+ notices.push(t);
2153
+ j += 1;
2154
+ continue;
2155
+ }
2156
+ if (t.role !== "tool") break;
2157
+ if (t.tool_call_id && !responders.has(t.tool_call_id)) {
2158
+ responders.set(t.tool_call_id, t);
2159
+ }
2160
+ j += 1;
2161
+ }
2162
+ const kept = calls.filter((tc) => tc.id && responders.has(tc.id));
2163
+ droppedCalls += calls.length - kept.length;
2164
+ droppedResults += responders.size - kept.length;
2165
+ if (kept.length === 0) {
2166
+ const { tool_calls, ...rest } = m;
2167
+ void tool_calls;
2168
+ if ((rest.content ?? "").trim() !== "") out.push(rest);
2169
+ else droppedMessages += 1;
2170
+ out.push(...notices);
2171
+ } else {
2172
+ out.push(kept.length === calls.length ? m : { ...m, tool_calls: kept });
2173
+ for (const tc of kept) out.push(responders.get(tc.id));
2174
+ out.push(...notices);
2175
+ }
2176
+ i = j;
2177
+ }
2178
+ const unchanged = out.length === messages.length && out.every((m, idx) => m === messages[idx]);
2179
+ return {
2180
+ messages: unchanged ? messages : out,
2181
+ droppedCalls,
2182
+ droppedResults,
2183
+ droppedMessages
2184
+ };
2185
+ }
2186
+ function repairToolCallHistory(messages) {
2187
+ return repairToolCallHistoryDetailed(messages).messages;
2188
+ }
2189
+
2094
2190
  // src/engine/TurnEngine.ts
2095
2191
  import * as crypto from "crypto";
2096
2192
  import * as fs3 from "fs";
@@ -2631,6 +2727,7 @@ ${notice}` : text,
2631
2727
  attachments = routed.attachments;
2632
2728
  this.taskId = taskId;
2633
2729
  this._turnStartTime = Date.now();
2730
+ this.messages = repairToolCallHistory(this.messages);
2634
2731
  this.messages.push({
2635
2732
  role: "user",
2636
2733
  content: userInput,
@@ -3632,7 +3729,7 @@ ${notice}` : text,
3632
3729
  /** 过滤 notice + 剥离 display-only 字段,得到最终发送视图 */
3633
3730
  _finalizeOutbound(sourceMessages) {
3634
3731
  const _STRIP = /* @__PURE__ */ new Set(["source", "_display", "ts", "reasoning", "usage", "attachmentRefs"]);
3635
- return sourceMessages.filter((m) => m.role !== "notice").map((m) => {
3732
+ const stripped = sourceMessages.filter((m) => m.role !== "notice").map((m) => {
3636
3733
  if (m.role === "tool") {
3637
3734
  return {
3638
3735
  role: "tool",
@@ -3641,15 +3738,16 @@ ${notice}` : text,
3641
3738
  };
3642
3739
  }
3643
3740
  const staleAttachments = Boolean(m.attachments?.length) && (m.ts ?? 0) < this._turnStartTime;
3644
- const stripped = {};
3741
+ const plain = {};
3645
3742
  for (const [k, v] of Object.entries(m)) {
3646
3743
  if (staleAttachments && k === "attachments") continue;
3647
3744
  if (!_STRIP.has(k)) {
3648
- stripped[k] = v;
3745
+ plain[k] = v;
3649
3746
  }
3650
3747
  }
3651
- return stripped;
3748
+ return plain;
3652
3749
  });
3750
+ return repairToolCallHistory(stripped);
3653
3751
  }
3654
3752
  /** 软阈值(token 数):达到它只淘汰旧工具结果 */
3655
3753
  _softTriggerTokens() {
@@ -4402,6 +4500,11 @@ var ResponsesApiError = class extends Error {
4402
4500
  type;
4403
4501
  requestId;
4404
4502
  };
4503
+ var NO_AUTH_KEY = "not-needed";
4504
+ var degradedModes = /* @__PURE__ */ new Map();
4505
+ function modeKey(baseURL, model) {
4506
+ return `${baseURL}::${model}`;
4507
+ }
4405
4508
  var OpenAIProvider = class {
4406
4509
  /** OpenAI SDK 客户端 */
4407
4510
  client;
@@ -4409,23 +4512,31 @@ var OpenAIProvider = class {
4409
4512
  _logDir;
4410
4513
  /** 服务端点 baseURL(用于识别 DeepSeek 等特定供应商) */
4411
4514
  _baseURL;
4412
- /** 模型 → API 模式缓存:某模型不支持 Responses 后,后续直走 Chat */
4413
- _modeByModel = /* @__PURE__ */ new Map();
4515
+ /**
4516
+ * 本实例的 API 模式。
4517
+ *
4518
+ * 显式配置 > 全局 `OPENAI_FORCE_API_MODE` > auto(先 Responses 再降级)。
4519
+ * 早先只有全局环境变量一种表达方式,一个节点挂两家供应商时无法各自指定。
4520
+ */
4521
+ _apiMode;
4414
4522
  constructor(opts) {
4523
+ const explicitKey = opts.apiKey !== void 0;
4415
4524
  const apiKey = cleanLlmValue(opts.apiKey ?? process.env.OPENAI_API_KEY);
4416
4525
  const baseURL = normalizeBaseURL(opts.baseURL ?? process.env.OPENAI_BASE_URL);
4417
- if (!apiKey) {
4526
+ if (!apiKey && !explicitKey) {
4418
4527
  throw new Error(sanitizeEmoji("\u274C \u672A\u8BBE\u7F6E OPENAI_API_KEY \u73AF\u5883\u53D8\u91CF"));
4419
4528
  }
4529
+ const effectiveKey = apiKey ?? NO_AUTH_KEY;
4420
4530
  this._baseURL = baseURL ?? "";
4531
+ this._apiMode = normApiMode(opts.apiMode) ?? normApiMode(process.env.OPENAI_FORCE_API_MODE) ?? "auto";
4421
4532
  const agent = socksAgent();
4422
4533
  const proxyHint = unsupportedProxyHint();
4423
4534
  if (proxyHint) console.warn(`[llm] ${proxyHint}`);
4424
4535
  const baseFetch = agent ? makeSocksFetch(agent) : ((input, init) => globalThis.fetch(input, init));
4425
4536
  this.client = new OpenAI({
4426
- apiKey,
4537
+ apiKey: effectiveKey,
4427
4538
  ...baseURL ? { baseURL } : {},
4428
- timeout: llmTimeoutMs(),
4539
+ timeout: llmTimeoutMs(opts.timeoutMs),
4429
4540
  maxRetries: llmMaxRetries(),
4430
4541
  // 类型:SDK 期望 (RequestInfo, RequestInit) => Promise<Response>,
4431
4542
  // node-fetch 的 Response 与 DOM Response 结构不同,此处显式放宽
@@ -4442,14 +4553,17 @@ var OpenAIProvider = class {
4442
4553
  /**
4443
4554
  * 解析指定模型的 API 模式。
4444
4555
  *
4445
- * 优先级:环境变量 OPENAI_FORCE_API_MODE(responses|chat)强制指定
4446
- * > 运行时降级缓存(该模型曾因"不支持"失败而缓存为 chat)
4556
+ * 优先级:本实例的显式配置(responses|chat)
4557
+ * > 运行时降级缓存(该端点+模型曾因"不支持"失败而缓存为 chat)
4447
4558
  * > 默认 responses(Responses 优先)。
4448
4559
  */
4449
4560
  _resolveMode(model) {
4450
- const forced = process.env.OPENAI_FORCE_API_MODE?.toLowerCase();
4451
- if (forced === "responses" || forced === "chat") return forced;
4452
- return this._modeByModel.get(model) ?? "responses";
4561
+ if (this._apiMode !== "auto") return this._apiMode;
4562
+ return degradedModes.get(modeKey(this._baseURL, model)) ?? "responses";
4563
+ }
4564
+ /** 记录「该端点+模型不支持 Responses」,后续同进程内的请求直走 Chat */
4565
+ _markChatMode(model) {
4566
+ degradedModes.set(modeKey(this._baseURL, model), "chat");
4453
4567
  }
4454
4568
  /**
4455
4569
  * Responses 失败的分类(决定「能不能改走 Chat Completions」以及要不要缓存降级)。
@@ -4525,7 +4639,7 @@ var OpenAIProvider = class {
4525
4639
  } catch (err) {
4526
4640
  const kind = this._responsesFailureKind(err, true);
4527
4641
  if (kind) {
4528
- if (kind === "endpoint") this._modeByModel.set(model, "chat");
4642
+ if (kind === "endpoint") this._markChatMode(model);
4529
4643
  console.warn(
4530
4644
  `[llm] ${model} Responses API \u4E0D\u53EF\u7528(${kind})\uFF0C\u6539\u7528 Chat Completions (${String(
4531
4645
  err?.message ?? err
@@ -4599,7 +4713,7 @@ var OpenAIProvider = class {
4599
4713
  } catch (err) {
4600
4714
  const kind = this._responsesFailureKind(err, true);
4601
4715
  if (kind) {
4602
- if (kind === "endpoint") this._modeByModel.set(model, "chat");
4716
+ if (kind === "endpoint") this._markChatMode(model);
4603
4717
  console.warn(
4604
4718
  `[llm] ${model} Responses API \u4E0D\u53EF\u7528(${kind})\uFF0C\u6539\u7528 Chat Completions (${String(
4605
4719
  err?.message ?? err
@@ -4645,7 +4759,7 @@ var OpenAIProvider = class {
4645
4759
  } catch (err) {
4646
4760
  const kind = emitted ? null : this._responsesFailureKind(err, false);
4647
4761
  if (!kind) throw enrichLlmError(err, this._baseURL);
4648
- if (kind === "endpoint") this._modeByModel.set(ctx.model, "chat");
4762
+ if (kind === "endpoint") this._markChatMode(ctx.model);
4649
4763
  console.warn(
4650
4764
  `[llm] ${ctx.model} Responses \u6D41\u5185\u5931\u8D25(${kind})\uFF0C\u6539\u7528 Chat Completions (${String(
4651
4765
  err?.message ?? err
@@ -7169,6 +7283,9 @@ var ConsoleHook = class {
7169
7283
  for (const hint of authErrorHints(error, errorType)) {
7170
7284
  cliLog(` \u{1F4A1} ${hint}`);
7171
7285
  }
7286
+ for (const hint of toolCallHistoryHints(error, errorType)) {
7287
+ cliLog(` \u{1F4A1} ${hint}`);
7288
+ }
7172
7289
  for (const hint of paramErrorHints(error)) {
7173
7290
  cliLog(` \u{1F4A1} ${hint}`);
7174
7291
  }
@@ -13175,6 +13292,8 @@ function createDefaultEngine(opts) {
13175
13292
  mode = "interactive" /* INTERACTIVE */,
13176
13293
  maxIterations = DEFAULT_MAX_ITERATIONS,
13177
13294
  reasoningEffort,
13295
+ timeoutMs,
13296
+ apiMode,
13178
13297
  allowedCommands = [],
13179
13298
  shellPolicy = "approve",
13180
13299
  sandbox,
@@ -13195,7 +13314,7 @@ function createDefaultEngine(opts) {
13195
13314
  } = opts;
13196
13315
  const envEffort = process.env.OPENAI_REASONING_EFFORT?.toLowerCase();
13197
13316
  const effectiveEffort = reasoningEffort ?? (envEffort === "low" || envEffort === "medium" || envEffort === "high" ? envEffort : void 0);
13198
- const effectiveProvider = provider ?? new OpenAIProvider({ logDir });
13317
+ const effectiveProvider = provider ?? new OpenAIProvider({ logDir, timeoutMs, apiMode });
13199
13318
  const sandboxPlan = resolveSandbox({ ...sandbox, workspace });
13200
13319
  const registry = new ToolRegistry();
13201
13320
  const conflictGuard = new ConflictGuard();
@@ -13371,6 +13490,8 @@ export {
13371
13490
  registerTerminalTools,
13372
13491
  registerTodoTool,
13373
13492
  registerWebTools,
13493
+ repairToolCallHistory,
13494
+ repairToolCallHistoryDetailed,
13374
13495
  resetFfmpegCache,
13375
13496
  resetSandboxCache,
13376
13497
  resolveMedia,