mycto_agent 0.1.5 → 0.1.7

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/dist/index.d.mts CHANGED
@@ -696,6 +696,8 @@ type LLMStreamEvent = {
696
696
  } | {
697
697
  type: 'tool-result';
698
698
  toolCallId: string;
699
+ toolName: string;
700
+ args: Record<string, unknown>;
699
701
  result: unknown;
700
702
  } | {
701
703
  type: 'finish';
@@ -740,8 +742,9 @@ interface ProviderConfig {
740
742
  * - openai: 使用 @ai-sdk/openai (兼容 OpenAI API 的服务)
741
743
  * - google: 使用 @ai-sdk/google
742
744
  * - zhipu: 使用 @ai-sdk/openai (智谱 GLM,OpenAI 兼容)
745
+ * - kimi: 使用 @ai-sdk/openai-compatible (Moonshot Kimi)
743
746
  */
744
- type: 'anthropic' | 'openai' | 'google' | 'zhipu';
747
+ type: 'anthropic' | 'openai' | 'google' | 'zhipu' | 'kimi';
745
748
  options: ProviderOptions;
746
749
  models: ModelInfo[];
747
750
  }
@@ -842,7 +845,7 @@ declare function calculateCost(providerId: string, modelId: string, tokens: {
842
845
  */
843
846
 
844
847
  /** Provider 类型 */
845
- type ProviderType = 'anthropic' | 'openai' | 'google' | 'zhipu';
848
+ type ProviderType = 'anthropic' | 'openai' | 'google' | 'zhipu' | 'kimi';
846
849
  /** OpenAgent 配置选项 */
847
850
  interface OpenAgentOptions {
848
851
  /** Provider 类型 */
@@ -957,13 +960,13 @@ declare class OpenAgent {
957
960
  */
958
961
  private executeTool;
959
962
  /**
960
- * 非流式对话(带 Agent Loop)
963
+ * 非流式对话(AI SDK 自动多步)
961
964
  */
962
965
  chat(message: string, options?: {
963
966
  sessionId?: string;
964
967
  }): Promise<ChatResult>;
965
968
  /**
966
- * 流式对话
969
+ * 流式对话(AI SDK 自动多步)
967
970
  */
968
971
  stream(message: string, options?: {
969
972
  sessionId?: string;
@@ -1005,6 +1008,10 @@ declare function google(apiKey: string, model?: string): OpenAgent;
1005
1008
  * 快速创建 Zhipu/GLM Agent
1006
1009
  */
1007
1010
  declare function zhipu(apiKey: string, model?: string): OpenAgent;
1011
+ /**
1012
+ * 快速创建 Kimi Agent
1013
+ */
1014
+ declare function kimi(apiKey: string, model?: string): OpenAgent;
1008
1015
 
1009
1016
  /**
1010
1017
  * OpenAgent Tool Definition
@@ -1600,4 +1607,4 @@ declare function isInitialized(): boolean;
1600
1607
  */
1601
1608
  declare function resetOpenAgent(): void;
1602
1609
 
1603
- export { type AgentConfig, type AgentDefinition, type AgentMode, AgentNotFoundError, type AgentStreamEvent, type BashArgs, type BatchSaveMessageInput, type ChatResult, ContextOverflowError, type CreatePartInput, type CreateSessionInput, type EditArgs, type ExecutorType, type FilePart, type GlobArgs, type GrepArgs, type LLMStreamEvent, type LLMStreamInput, type LLMStreamResult, type LLMUsage, type LogLevel, type Logger, McpConnectionError, type McpServerConfig, type McpServerType, type McpStatus, MemorySessionStore, type Message, type MessageError, type MessagePart, type MessageRole, type MessageWithParts, type ModelInfo, ModelNotFoundError, OpenAgent, type OpenAgentConfig, OpenAgentError, type OpenAgentOptions, PROVIDERS, type PartType, type PermissionAction, PermissionDeniedError, type PermissionRequest, type PermissionRule, type PromptInput, type PromptResult, ProviderApiError, type ProviderConfig, type ProviderInfo, type ProviderOptions, type ProviderType, type ReadArgs, type ReasoningPart, type SandboxExecutor, type Session, SessionBusyError, SessionNotFoundError, type SessionStatus, type SessionStore, type SkillDefinition, type SnapshotPart, type StreamEvent, TOOL_PERMISSIONS, type TextPart, type TodoItem, type TodoPriority, type TodoStatus, type TokenUsage, type ToolCallRecord, type ToolContext, type ToolDefinition, ToolExecutionError, type ToolInfo, type ToolPart, type ToolResult, type ToolStatus, type WriteArgs, anthropic, bashTool, batchSaveMessage, batchUpdateSession, buildSystemPrompt, builtinTools, calculateCost, clearAgents, clearTodos, clearTools, configureFromOpenCodeConfig, configureProvider, configureProviders, createAgent, createLogger, createMemoryStore, createMessage, createPart, createSession, defineTool, deleteSession, editTool, estimateJsonTokens, estimateMessageTokens, estimateMessagesTokens, estimateTokens, extractErrorInfo, generateId, getAIToolsForAgent, getAgent, getAllAgentNames, getAllTools, getAllowedToolsForMode, getAvailableSkills, getBuiltinTools, getDefaultAgent, getDefaultAgentNames, getDefaultModel, getLanguageModel, getMessage, getModeChangePrompt, getModelInfo, getProvider, getProviders, getSession, getSessionMessages, getSessionStore, getTodos, getTool, getToolDescriptions, getToolsForAgent, getToolsForMode, globTool, google, grepTool, hasSessionStore, initOpenAgent, isContextOverflowError, isInitialized, isToolAllowedInMode, listSessions, stream as llmStream, localBashExecutor, localEditExecutor, localGlobExecutor, localGrepExecutor, localReadExecutor, localWriteExecutor, messageId, openai, partId, questionTool, readTool, registerAgent, registerAgents, registerSkill, registerTool, registerTools, resetOpenAgent, resetProviders, sessionId, setSessionStore, setTodos, skillTool, smartReplace, taskTool, toAITool, toAITools, toMessageError, toModelMessages, todoreadTool, todowriteTool, toolCallId, truncateForAI, truncateSimple, truncateToolOutput, unregisterAgent, unregisterTool, updateMessage, updatePart, updateSession, webfetchTool, writeTool, zhipu };
1610
+ export { type AgentConfig, type AgentDefinition, type AgentMode, AgentNotFoundError, type AgentStreamEvent, type BashArgs, type BatchSaveMessageInput, type ChatResult, ContextOverflowError, type CreatePartInput, type CreateSessionInput, type EditArgs, type ExecutorType, type FilePart, type GlobArgs, type GrepArgs, type LLMStreamEvent, type LLMStreamInput, type LLMStreamResult, type LLMUsage, type LogLevel, type Logger, McpConnectionError, type McpServerConfig, type McpServerType, type McpStatus, MemorySessionStore, type Message, type MessageError, type MessagePart, type MessageRole, type MessageWithParts, type ModelInfo, ModelNotFoundError, OpenAgent, type OpenAgentConfig, OpenAgentError, type OpenAgentOptions, PROVIDERS, type PartType, type PermissionAction, PermissionDeniedError, type PermissionRequest, type PermissionRule, type PromptInput, type PromptResult, ProviderApiError, type ProviderConfig, type ProviderInfo, type ProviderOptions, type ProviderType, type ReadArgs, type ReasoningPart, type SandboxExecutor, type Session, SessionBusyError, SessionNotFoundError, type SessionStatus, type SessionStore, type SkillDefinition, type SnapshotPart, type StreamEvent, TOOL_PERMISSIONS, type TextPart, type TodoItem, type TodoPriority, type TodoStatus, type TokenUsage, type ToolCallRecord, type ToolContext, type ToolDefinition, ToolExecutionError, type ToolInfo, type ToolPart, type ToolResult, type ToolStatus, type WriteArgs, anthropic, bashTool, batchSaveMessage, batchUpdateSession, buildSystemPrompt, builtinTools, calculateCost, clearAgents, clearTodos, clearTools, configureFromOpenCodeConfig, configureProvider, configureProviders, createAgent, createLogger, createMemoryStore, createMessage, createPart, createSession, defineTool, deleteSession, editTool, estimateJsonTokens, estimateMessageTokens, estimateMessagesTokens, estimateTokens, extractErrorInfo, generateId, getAIToolsForAgent, getAgent, getAllAgentNames, getAllTools, getAllowedToolsForMode, getAvailableSkills, getBuiltinTools, getDefaultAgent, getDefaultAgentNames, getDefaultModel, getLanguageModel, getMessage, getModeChangePrompt, getModelInfo, getProvider, getProviders, getSession, getSessionMessages, getSessionStore, getTodos, getTool, getToolDescriptions, getToolsForAgent, getToolsForMode, globTool, google, grepTool, hasSessionStore, initOpenAgent, isContextOverflowError, isInitialized, isToolAllowedInMode, kimi, listSessions, stream as llmStream, localBashExecutor, localEditExecutor, localGlobExecutor, localGrepExecutor, localReadExecutor, localWriteExecutor, messageId, openai, partId, questionTool, readTool, registerAgent, registerAgents, registerSkill, registerTool, registerTools, resetOpenAgent, resetProviders, sessionId, setSessionStore, setTodos, skillTool, smartReplace, taskTool, toAITool, toAITools, toMessageError, toModelMessages, todoreadTool, todowriteTool, toolCallId, truncateForAI, truncateSimple, truncateToolOutput, unregisterAgent, unregisterTool, updateMessage, updatePart, updateSession, webfetchTool, writeTool, zhipu };
package/dist/index.d.ts CHANGED
@@ -696,6 +696,8 @@ type LLMStreamEvent = {
696
696
  } | {
697
697
  type: 'tool-result';
698
698
  toolCallId: string;
699
+ toolName: string;
700
+ args: Record<string, unknown>;
699
701
  result: unknown;
700
702
  } | {
701
703
  type: 'finish';
@@ -740,8 +742,9 @@ interface ProviderConfig {
740
742
  * - openai: 使用 @ai-sdk/openai (兼容 OpenAI API 的服务)
741
743
  * - google: 使用 @ai-sdk/google
742
744
  * - zhipu: 使用 @ai-sdk/openai (智谱 GLM,OpenAI 兼容)
745
+ * - kimi: 使用 @ai-sdk/openai-compatible (Moonshot Kimi)
743
746
  */
744
- type: 'anthropic' | 'openai' | 'google' | 'zhipu';
747
+ type: 'anthropic' | 'openai' | 'google' | 'zhipu' | 'kimi';
745
748
  options: ProviderOptions;
746
749
  models: ModelInfo[];
747
750
  }
@@ -842,7 +845,7 @@ declare function calculateCost(providerId: string, modelId: string, tokens: {
842
845
  */
843
846
 
844
847
  /** Provider 类型 */
845
- type ProviderType = 'anthropic' | 'openai' | 'google' | 'zhipu';
848
+ type ProviderType = 'anthropic' | 'openai' | 'google' | 'zhipu' | 'kimi';
846
849
  /** OpenAgent 配置选项 */
847
850
  interface OpenAgentOptions {
848
851
  /** Provider 类型 */
@@ -957,13 +960,13 @@ declare class OpenAgent {
957
960
  */
958
961
  private executeTool;
959
962
  /**
960
- * 非流式对话(带 Agent Loop)
963
+ * 非流式对话(AI SDK 自动多步)
961
964
  */
962
965
  chat(message: string, options?: {
963
966
  sessionId?: string;
964
967
  }): Promise<ChatResult>;
965
968
  /**
966
- * 流式对话
969
+ * 流式对话(AI SDK 自动多步)
967
970
  */
968
971
  stream(message: string, options?: {
969
972
  sessionId?: string;
@@ -1005,6 +1008,10 @@ declare function google(apiKey: string, model?: string): OpenAgent;
1005
1008
  * 快速创建 Zhipu/GLM Agent
1006
1009
  */
1007
1010
  declare function zhipu(apiKey: string, model?: string): OpenAgent;
1011
+ /**
1012
+ * 快速创建 Kimi Agent
1013
+ */
1014
+ declare function kimi(apiKey: string, model?: string): OpenAgent;
1008
1015
 
1009
1016
  /**
1010
1017
  * OpenAgent Tool Definition
@@ -1600,4 +1607,4 @@ declare function isInitialized(): boolean;
1600
1607
  */
1601
1608
  declare function resetOpenAgent(): void;
1602
1609
 
1603
- export { type AgentConfig, type AgentDefinition, type AgentMode, AgentNotFoundError, type AgentStreamEvent, type BashArgs, type BatchSaveMessageInput, type ChatResult, ContextOverflowError, type CreatePartInput, type CreateSessionInput, type EditArgs, type ExecutorType, type FilePart, type GlobArgs, type GrepArgs, type LLMStreamEvent, type LLMStreamInput, type LLMStreamResult, type LLMUsage, type LogLevel, type Logger, McpConnectionError, type McpServerConfig, type McpServerType, type McpStatus, MemorySessionStore, type Message, type MessageError, type MessagePart, type MessageRole, type MessageWithParts, type ModelInfo, ModelNotFoundError, OpenAgent, type OpenAgentConfig, OpenAgentError, type OpenAgentOptions, PROVIDERS, type PartType, type PermissionAction, PermissionDeniedError, type PermissionRequest, type PermissionRule, type PromptInput, type PromptResult, ProviderApiError, type ProviderConfig, type ProviderInfo, type ProviderOptions, type ProviderType, type ReadArgs, type ReasoningPart, type SandboxExecutor, type Session, SessionBusyError, SessionNotFoundError, type SessionStatus, type SessionStore, type SkillDefinition, type SnapshotPart, type StreamEvent, TOOL_PERMISSIONS, type TextPart, type TodoItem, type TodoPriority, type TodoStatus, type TokenUsage, type ToolCallRecord, type ToolContext, type ToolDefinition, ToolExecutionError, type ToolInfo, type ToolPart, type ToolResult, type ToolStatus, type WriteArgs, anthropic, bashTool, batchSaveMessage, batchUpdateSession, buildSystemPrompt, builtinTools, calculateCost, clearAgents, clearTodos, clearTools, configureFromOpenCodeConfig, configureProvider, configureProviders, createAgent, createLogger, createMemoryStore, createMessage, createPart, createSession, defineTool, deleteSession, editTool, estimateJsonTokens, estimateMessageTokens, estimateMessagesTokens, estimateTokens, extractErrorInfo, generateId, getAIToolsForAgent, getAgent, getAllAgentNames, getAllTools, getAllowedToolsForMode, getAvailableSkills, getBuiltinTools, getDefaultAgent, getDefaultAgentNames, getDefaultModel, getLanguageModel, getMessage, getModeChangePrompt, getModelInfo, getProvider, getProviders, getSession, getSessionMessages, getSessionStore, getTodos, getTool, getToolDescriptions, getToolsForAgent, getToolsForMode, globTool, google, grepTool, hasSessionStore, initOpenAgent, isContextOverflowError, isInitialized, isToolAllowedInMode, listSessions, stream as llmStream, localBashExecutor, localEditExecutor, localGlobExecutor, localGrepExecutor, localReadExecutor, localWriteExecutor, messageId, openai, partId, questionTool, readTool, registerAgent, registerAgents, registerSkill, registerTool, registerTools, resetOpenAgent, resetProviders, sessionId, setSessionStore, setTodos, skillTool, smartReplace, taskTool, toAITool, toAITools, toMessageError, toModelMessages, todoreadTool, todowriteTool, toolCallId, truncateForAI, truncateSimple, truncateToolOutput, unregisterAgent, unregisterTool, updateMessage, updatePart, updateSession, webfetchTool, writeTool, zhipu };
1610
+ export { type AgentConfig, type AgentDefinition, type AgentMode, AgentNotFoundError, type AgentStreamEvent, type BashArgs, type BatchSaveMessageInput, type ChatResult, ContextOverflowError, type CreatePartInput, type CreateSessionInput, type EditArgs, type ExecutorType, type FilePart, type GlobArgs, type GrepArgs, type LLMStreamEvent, type LLMStreamInput, type LLMStreamResult, type LLMUsage, type LogLevel, type Logger, McpConnectionError, type McpServerConfig, type McpServerType, type McpStatus, MemorySessionStore, type Message, type MessageError, type MessagePart, type MessageRole, type MessageWithParts, type ModelInfo, ModelNotFoundError, OpenAgent, type OpenAgentConfig, OpenAgentError, type OpenAgentOptions, PROVIDERS, type PartType, type PermissionAction, PermissionDeniedError, type PermissionRequest, type PermissionRule, type PromptInput, type PromptResult, ProviderApiError, type ProviderConfig, type ProviderInfo, type ProviderOptions, type ProviderType, type ReadArgs, type ReasoningPart, type SandboxExecutor, type Session, SessionBusyError, SessionNotFoundError, type SessionStatus, type SessionStore, type SkillDefinition, type SnapshotPart, type StreamEvent, TOOL_PERMISSIONS, type TextPart, type TodoItem, type TodoPriority, type TodoStatus, type TokenUsage, type ToolCallRecord, type ToolContext, type ToolDefinition, ToolExecutionError, type ToolInfo, type ToolPart, type ToolResult, type ToolStatus, type WriteArgs, anthropic, bashTool, batchSaveMessage, batchUpdateSession, buildSystemPrompt, builtinTools, calculateCost, clearAgents, clearTodos, clearTools, configureFromOpenCodeConfig, configureProvider, configureProviders, createAgent, createLogger, createMemoryStore, createMessage, createPart, createSession, defineTool, deleteSession, editTool, estimateJsonTokens, estimateMessageTokens, estimateMessagesTokens, estimateTokens, extractErrorInfo, generateId, getAIToolsForAgent, getAgent, getAllAgentNames, getAllTools, getAllowedToolsForMode, getAvailableSkills, getBuiltinTools, getDefaultAgent, getDefaultAgentNames, getDefaultModel, getLanguageModel, getMessage, getModeChangePrompt, getModelInfo, getProvider, getProviders, getSession, getSessionMessages, getSessionStore, getTodos, getTool, getToolDescriptions, getToolsForAgent, getToolsForMode, globTool, google, grepTool, hasSessionStore, initOpenAgent, isContextOverflowError, isInitialized, isToolAllowedInMode, kimi, listSessions, stream as llmStream, localBashExecutor, localEditExecutor, localGlobExecutor, localGrepExecutor, localReadExecutor, localWriteExecutor, messageId, openai, partId, questionTool, readTool, registerAgent, registerAgents, registerSkill, registerTool, registerTools, resetOpenAgent, resetProviders, sessionId, setSessionStore, setTodos, skillTool, smartReplace, taskTool, toAITool, toAITools, toMessageError, toModelMessages, todoreadTool, todowriteTool, toolCallId, truncateForAI, truncateSimple, truncateToolOutput, unregisterAgent, unregisterTool, updateMessage, updatePart, updateSession, webfetchTool, writeTool, zhipu };
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@
3
3
  var anthropic$1 = require('@ai-sdk/anthropic');
4
4
  var openai$1 = require('@ai-sdk/openai');
5
5
  var google$1 = require('@ai-sdk/google');
6
+ var openaiCompatible = require('@ai-sdk/openai-compatible');
6
7
  var jsTiktoken = require('js-tiktoken');
7
8
  var ai = require('ai');
8
9
  var zod = require('zod');
@@ -746,6 +747,8 @@ function configureFromOpenCodeConfig(config) {
746
747
  type = "google";
747
748
  } else if (providerId === "zhipu" || providerId === "zhipuai" || providerId.includes("glm")) {
748
749
  type = "zhipu";
750
+ } else if (providerId === "kimi" || providerId === "moonshot" || providerId.includes("kimi")) {
751
+ type = "kimi";
749
752
  }
750
753
  const models = Object.entries(providerConfig.models).map(([modelId, model]) => ({
751
754
  id: model.id || modelId,
@@ -843,6 +846,15 @@ function getOrCreateProviderInstance(providerId) {
843
846
  instance = openai$1.createOpenAI(options);
844
847
  break;
845
848
  }
849
+ case "kimi": {
850
+ instance = openaiCompatible.createOpenAICompatible({
851
+ name: "kimi",
852
+ baseURL: config.options.baseURL || "https://opencode.ai/zen/v1",
853
+ apiKey: config.options.apiKey,
854
+ headers: config.options.headers
855
+ });
856
+ break;
857
+ }
846
858
  default:
847
859
  throw new Error(`Unknown provider type: ${config.type}`);
848
860
  }
@@ -884,6 +896,9 @@ function getLanguageModel(providerId, modelId) {
884
896
  if (config.type === "zhipu") {
885
897
  return instance.chat(modelId);
886
898
  }
899
+ if (config.type === "kimi") {
900
+ return instance.chatModel(modelId);
901
+ }
887
902
  return instance(modelId);
888
903
  }
889
904
  function getDefaultModel() {
@@ -1313,6 +1328,8 @@ async function stream(input) {
1313
1328
  yield {
1314
1329
  type: "tool-result",
1315
1330
  toolCallId: e.toolCallId,
1331
+ toolName: e.toolName,
1332
+ args: e.args ?? e.input ?? {},
1316
1333
  result: e.result ?? e.output
1317
1334
  };
1318
1335
  break;
@@ -3270,6 +3287,7 @@ __export(agent_exports, {
3270
3287
  anthropic: () => anthropic,
3271
3288
  createAgent: () => createAgent,
3272
3289
  google: () => google,
3290
+ kimi: () => kimi,
3273
3291
  openai: () => openai,
3274
3292
  zhipu: () => zhipu
3275
3293
  });
@@ -3304,6 +3322,13 @@ function zhipu(apiKey, model) {
3304
3322
  model: model ?? "glm-4.7"
3305
3323
  });
3306
3324
  }
3325
+ function kimi(apiKey, model) {
3326
+ return new exports.OpenAgent({
3327
+ provider: "kimi",
3328
+ apiKey,
3329
+ model: model ?? "kimi-k2.5-free"
3330
+ });
3331
+ }
3307
3332
  var log6, DEFAULT_MODELS; exports.OpenAgent = void 0;
3308
3333
  var init_agent2 = __esm({
3309
3334
  "src/agent.ts"() {
@@ -3334,6 +3359,11 @@ var init_agent2 = __esm({
3334
3359
  id: "glm-4.7",
3335
3360
  contextWindow: 128e3,
3336
3361
  maxOutput: 8192
3362
+ },
3363
+ kimi: {
3364
+ id: "kimi-k2.5-free",
3365
+ contextWindow: 128e3,
3366
+ maxOutput: 8192
3337
3367
  }
3338
3368
  };
3339
3369
  exports.OpenAgent = class {
@@ -3483,7 +3513,7 @@ You can read, write, and edit files, search code, and execute commands.`
3483
3513
  }
3484
3514
  }
3485
3515
  /**
3486
- * 非流式对话(带 Agent Loop)
3516
+ * 非流式对话(AI SDK 自动多步)
3487
3517
  */
3488
3518
  async chat(message, options) {
3489
3519
  await this.ensureInitialized();
@@ -3496,90 +3526,61 @@ You can read, write, and edit files, search code, and execute commands.`
3496
3526
  const msgId = `msg_${Date.now()}`;
3497
3527
  const ctx = this.createToolContext(sessionId2, msgId);
3498
3528
  const tools = getAIToolsForAgent(this.agent, ctx, this.mode);
3529
+ const messages = await getSessionMessages(sessionId2);
3530
+ const modelMessages = await toModelMessages(messages);
3531
+ const result = await stream({
3532
+ providerId: this.providerId,
3533
+ modelId: this.modelId,
3534
+ messages: modelMessages,
3535
+ system: buildSystemPrompt(this.agent),
3536
+ tools,
3537
+ temperature: this.temperature,
3538
+ maxOutputTokens: this.maxOutputTokens,
3539
+ maxSteps: this.maxSteps
3540
+ // AI SDK 自动处理多步
3541
+ });
3499
3542
  let fullText = "";
3500
3543
  const toolCalls = [];
3501
3544
  let totalUsage = { input: 0, output: 0 };
3502
3545
  let totalCost = 0;
3503
3546
  let finishReason = "unknown";
3504
- let step = 0;
3505
- while (step < this.maxSteps) {
3506
- step++;
3507
- log6.debug(`Agent loop step ${step}/${this.maxSteps}`);
3508
- const messages = await getSessionMessages(sessionId2);
3509
- const modelMessages = await toModelMessages(messages);
3510
- const result = await stream({
3511
- providerId: this.providerId,
3512
- modelId: this.modelId,
3513
- messages: modelMessages,
3514
- system: buildSystemPrompt(this.agent),
3515
- tools,
3516
- temperature: this.temperature,
3517
- maxOutputTokens: this.maxOutputTokens,
3518
- maxSteps: 1
3519
- // 每次只执行一步,由我们控制循环
3520
- });
3521
- let stepText = "";
3522
- const stepToolCalls = [];
3523
- for await (const event of result.fullStream) {
3524
- switch (event.type) {
3525
- case "text-delta":
3526
- stepText += event.text;
3527
- break;
3528
- case "tool-call":
3529
- stepToolCalls.push({
3530
- id: event.toolCallId,
3531
- name: event.toolName,
3532
- args: event.args,
3533
- status: "PENDING",
3534
- providerMetadata: event.providerMetadata
3535
- });
3536
- break;
3537
- case "finish":
3538
- finishReason = event.finishReason;
3539
- totalUsage.input += event.usage.tokens.input;
3540
- totalUsage.output += event.usage.tokens.output;
3541
- totalCost += event.usage.cost;
3542
- break;
3543
- }
3544
- }
3545
- if (stepText) {
3546
- fullText += (fullText && stepText ? "\n" : "") + stepText;
3547
- }
3548
- if (stepToolCalls.length === 0) {
3549
- if (stepText) {
3550
- await batchSaveMessage({
3551
- sessionId: sessionId2,
3552
- role: "ASSISTANT",
3553
- parts: [{ type: "TEXT", text: stepText }]
3547
+ const assistantParts = [];
3548
+ for await (const event of result.fullStream) {
3549
+ switch (event.type) {
3550
+ case "text-delta":
3551
+ fullText += event.text;
3552
+ break;
3553
+ case "tool-call":
3554
+ log6.debug(`Tool call: ${event.toolName}`, { args: event.args });
3555
+ break;
3556
+ case "tool-result":
3557
+ toolCalls.push({
3558
+ name: event.toolName,
3559
+ input: event.args,
3560
+ output: String(event.result),
3561
+ status: "COMPLETED"
3554
3562
  });
3555
- }
3556
- break;
3557
- }
3558
- const assistantParts = [];
3559
- if (stepText) {
3560
- assistantParts.push({ type: "TEXT", text: stepText });
3561
- }
3562
- for (const call of stepToolCalls) {
3563
- log6.debug(`Executing tool: ${call.name}`, { args: call.args });
3564
- const result2 = await this.executeTool(call.name, call.args, ctx);
3565
- call.output = result2.output;
3566
- call.status = "COMPLETED";
3567
- toolCalls.push({
3568
- name: call.name,
3569
- input: call.args,
3570
- output: result2.output,
3571
- status: "COMPLETED"
3572
- });
3573
- assistantParts.push({
3574
- type: "TOOL",
3575
- toolName: call.name,
3576
- toolCallId: call.id,
3577
- toolInput: call.args,
3578
- toolOutput: result2.output,
3579
- toolStatus: "COMPLETED",
3580
- toolMeta: call.providerMetadata
3581
- });
3563
+ assistantParts.push({
3564
+ type: "TOOL",
3565
+ toolName: event.toolName,
3566
+ toolCallId: event.toolCallId,
3567
+ toolInput: event.args,
3568
+ toolOutput: String(event.result),
3569
+ toolStatus: "COMPLETED"
3570
+ });
3571
+ break;
3572
+ case "finish":
3573
+ finishReason = event.finishReason;
3574
+ totalUsage.input += event.usage.tokens.input;
3575
+ totalUsage.output += event.usage.tokens.output;
3576
+ totalCost += event.usage.cost;
3577
+ break;
3582
3578
  }
3579
+ }
3580
+ if (fullText) {
3581
+ assistantParts.unshift({ type: "TEXT", text: fullText });
3582
+ }
3583
+ if (assistantParts.length > 0) {
3583
3584
  await batchSaveMessage({
3584
3585
  sessionId: sessionId2,
3585
3586
  role: "ASSISTANT",
@@ -3596,7 +3597,7 @@ You can read, write, and edit files, search code, and execute commands.`
3596
3597
  };
3597
3598
  }
3598
3599
  /**
3599
- * 流式对话
3600
+ * 流式对话(AI SDK 自动多步)
3600
3601
  */
3601
3602
  async *stream(message, options) {
3602
3603
  await this.ensureInitialized();
@@ -3609,105 +3610,78 @@ You can read, write, and edit files, search code, and execute commands.`
3609
3610
  const msgId = `msg_${Date.now()}`;
3610
3611
  const ctx = this.createToolContext(sessionId2, msgId);
3611
3612
  const tools = getAIToolsForAgent(this.agent, ctx, this.mode);
3613
+ const messages = await getSessionMessages(sessionId2);
3614
+ const modelMessages = await toModelMessages(messages);
3612
3615
  let fullText = "";
3613
3616
  const toolCalls = [];
3614
3617
  let totalUsage = { input: 0, output: 0 };
3615
3618
  let totalCost = 0;
3616
3619
  let finishReason = "unknown";
3617
- let step = 0;
3620
+ const assistantParts = [];
3618
3621
  try {
3619
- while (step < this.maxSteps) {
3620
- step++;
3621
- const messages = await getSessionMessages(sessionId2);
3622
- const modelMessages = await toModelMessages(messages);
3623
- const result = await stream({
3624
- providerId: this.providerId,
3625
- modelId: this.modelId,
3626
- messages: modelMessages,
3627
- system: buildSystemPrompt(this.agent),
3628
- tools,
3629
- temperature: this.temperature,
3630
- maxOutputTokens: this.maxOutputTokens,
3631
- maxSteps: 1
3632
- });
3633
- let stepText = "";
3634
- const stepToolCalls = [];
3635
- for await (const event of result.fullStream) {
3636
- switch (event.type) {
3637
- case "text-delta":
3638
- stepText += event.text;
3639
- yield { type: "text", text: event.text };
3640
- break;
3641
- case "reasoning-delta":
3642
- yield { type: "reasoning", text: event.text };
3643
- break;
3644
- case "tool-call":
3645
- stepToolCalls.push({
3646
- id: event.toolCallId,
3647
- name: event.toolName,
3648
- args: event.args,
3649
- status: "PENDING",
3650
- providerMetadata: event.providerMetadata
3651
- });
3652
- yield {
3653
- type: "tool-start",
3654
- name: event.toolName,
3655
- input: event.args
3656
- };
3657
- break;
3658
- case "finish":
3659
- finishReason = event.finishReason;
3660
- totalUsage.input += event.usage.tokens.input;
3661
- totalUsage.output += event.usage.tokens.output;
3662
- totalCost += event.usage.cost;
3663
- break;
3664
- case "error":
3665
- yield { type: "error", error: event.error };
3666
- return;
3667
- }
3668
- }
3669
- if (stepText) {
3670
- fullText += (fullText && stepText ? "\n" : "") + stepText;
3671
- }
3672
- if (stepToolCalls.length === 0) {
3673
- if (stepText) {
3674
- await batchSaveMessage({
3675
- sessionId: sessionId2,
3676
- role: "ASSISTANT",
3677
- parts: [{ type: "TEXT", text: stepText }]
3622
+ const result = await stream({
3623
+ providerId: this.providerId,
3624
+ modelId: this.modelId,
3625
+ messages: modelMessages,
3626
+ system: buildSystemPrompt(this.agent),
3627
+ tools,
3628
+ temperature: this.temperature,
3629
+ maxOutputTokens: this.maxOutputTokens,
3630
+ maxSteps: this.maxSteps
3631
+ // AI SDK 自动处理多步
3632
+ });
3633
+ for await (const event of result.fullStream) {
3634
+ switch (event.type) {
3635
+ case "text-delta":
3636
+ fullText += event.text;
3637
+ yield { type: "text", text: event.text };
3638
+ break;
3639
+ case "reasoning-delta":
3640
+ yield { type: "reasoning", text: event.text };
3641
+ break;
3642
+ case "tool-call":
3643
+ yield {
3644
+ type: "tool-start",
3645
+ name: event.toolName,
3646
+ input: event.args
3647
+ };
3648
+ break;
3649
+ case "tool-result":
3650
+ toolCalls.push({
3651
+ name: event.toolName,
3652
+ input: event.args,
3653
+ output: String(event.result),
3654
+ status: "COMPLETED"
3678
3655
  });
3679
- }
3680
- break;
3681
- }
3682
- const assistantParts = [];
3683
- if (stepText) {
3684
- assistantParts.push({ type: "TEXT", text: stepText });
3685
- }
3686
- for (const call of stepToolCalls) {
3687
- const toolResult = await this.executeTool(call.name, call.args, ctx);
3688
- call.output = toolResult.output;
3689
- call.status = "COMPLETED";
3690
- toolCalls.push({
3691
- name: call.name,
3692
- input: call.args,
3693
- output: toolResult.output,
3694
- status: "COMPLETED"
3695
- });
3696
- yield {
3697
- type: "tool-end",
3698
- name: call.name,
3699
- output: toolResult.output
3700
- };
3701
- assistantParts.push({
3702
- type: "TOOL",
3703
- toolName: call.name,
3704
- toolCallId: call.id,
3705
- toolInput: call.args,
3706
- toolOutput: toolResult.output,
3707
- toolStatus: "COMPLETED",
3708
- toolMeta: call.providerMetadata
3709
- });
3656
+ assistantParts.push({
3657
+ type: "TOOL",
3658
+ toolName: event.toolName,
3659
+ toolCallId: event.toolCallId,
3660
+ toolInput: event.args,
3661
+ toolOutput: String(event.result),
3662
+ toolStatus: "COMPLETED"
3663
+ });
3664
+ yield {
3665
+ type: "tool-end",
3666
+ name: event.toolName,
3667
+ output: String(event.result)
3668
+ };
3669
+ break;
3670
+ case "finish":
3671
+ finishReason = event.finishReason;
3672
+ totalUsage.input += event.usage.tokens.input;
3673
+ totalUsage.output += event.usage.tokens.output;
3674
+ totalCost += event.usage.cost;
3675
+ break;
3676
+ case "error":
3677
+ yield { type: "error", error: event.error };
3678
+ return;
3710
3679
  }
3680
+ }
3681
+ if (fullText) {
3682
+ assistantParts.unshift({ type: "TEXT", text: fullText });
3683
+ }
3684
+ if (assistantParts.length > 0) {
3711
3685
  await batchSaveMessage({
3712
3686
  sessionId: sessionId2,
3713
3687
  role: "ASSISTANT",
@@ -3858,6 +3832,7 @@ exports.initOpenAgent = initOpenAgent;
3858
3832
  exports.isContextOverflowError = isContextOverflowError;
3859
3833
  exports.isInitialized = isInitialized;
3860
3834
  exports.isToolAllowedInMode = isToolAllowedInMode;
3835
+ exports.kimi = kimi;
3861
3836
  exports.listSessions = listSessions;
3862
3837
  exports.llmStream = stream;
3863
3838
  exports.localBashExecutor = localBashExecutor;