diff --git a/CHANGELOG.md b/CHANGELOG.md index 44f7acf0..83e31674 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ ### Added +- 新增单代理与多代理异步对话 API:接收后返回任务回执,客户端断线不停止执行;支持按用户隔离的幂等提交、持久状态与结果查询、显式取消以及服务重启后的中断状态。同步接口保持兼容。 + - 启动时以统一最新 SQLite 定义自动检查全部项目管理表,缺表建表、缺字段补字段,无需维护逐字段迁移列表;保留已有数据和额外表/字段,结构补齐失败回滚并阻止启动。HITL 与通知表纳入统一初始化,历史漏洞外键迁移保留额外列、索引、触发器及依赖记录。 ### Fixed diff --git a/docs/en-US/async-conversation-api.md b/docs/en-US/async-conversation-api.md new file mode 100644 index 00000000..cdb6c9ae --- /dev/null +++ b/docs/en-US/async-conversation-api.md @@ -0,0 +1,17 @@ +# Asynchronous conversations + +Submit to `POST /api/eino-agent/runs` or `POST /api/multi-agent/runs` with the corresponding synchronous request body and a required `Idempotency-Key` header (1–200 bytes). Multi-agent execution must be enabled. Omit conversationId to create a conversation, or supply an existing accessible conversation. + +A 202 receipt contains runId, conversationId, assistantMessageId, status and statusUrl. The Location header points to statusUrl. After acceptance the client may disconnect; execution has its own 600-minute budget. Individual model and tool limits still apply. + +Poll statusUrl with authentication to read durable status, result and timestamps. Result contains the original execution response or error. Read saved messages and process details through the existing conversation/message endpoints. The event subscription endpoint only delivers subsequent events, without replay. + +Keys are scoped to the authenticated user. Repeating the same key and request returns the original receipt; a different request with the same key returns 409. Retry lost receipts with the original key and body. Use a new key for a new invocation. Concurrent submissions to an occupied conversation return 409 before appending messages. + +Explicitly cancel the current conversation task with `POST /api/agent-loop/cancel` and `{"conversationId":"..."}`. Cancellation is conversation-scoped: verify that the active run still matches the intended receipt before cancelling. + +Submission requires agent:execute and chat:write; queries require endpoint permission and conversation access. Background execution retains the authenticated principal. Existing synchronous endpoints retain their response contract and request-bound cancellation behavior. + +Running, completed, failed, cancelled, timeout and interrupted states are persisted, along with finalization/cleanup outcomes. Check finalized=true in the execution response for successful final delivery; a token usage summary is not a success signal. + +The current runtime assumes one server instance owns its database. On startup, unfinished running receipts become interrupted and remain queryable. Tools are not automatically replayed after a restart. Database write failures during acceptance return an error rather than a receipt. diff --git a/docs/zh-CN/async-conversation-api.md b/docs/zh-CN/async-conversation-api.md new file mode 100644 index 00000000..044e2658 --- /dev/null +++ b/docs/zh-CN/async-conversation-api.md @@ -0,0 +1,28 @@ +# 异步对话 API + +长任务使用 `POST /api/eino-agent/runs`(单代理)或 `POST /api/multi-agent/runs`(多代理,需启用配置)。请求体与对应同步接口相同;支持已有 conversationId,省略时创建会话。原同步接口仍等待最终结果,连接断开会取消同步执行。 + +```sh +curl -X POST "$CSAI_URL/api/eino-agent/runs" \ + -H "Authorization: Bearer $CSAI_TOKEN" \ + -H 'Content-Type: application/json' \ + -H 'Idempotency-Key: example-task-001' \ + -d '{"message":"整理本次任务的计划"}' +``` + +HTTP 202 示例: + +```json +{"runId":"...","conversationId":"...","assistantMessageId":"...","status":"running","statusUrl":"/api/eino-agent/runs/..."} +``` + +收到回执后可关闭连接。`GET statusUrl` 返回 `status`、`result`、标识及时间戳。`result` 为原执行入口的最终响应或错误;任务尚未结束时为空对象。单次任务总预算为600分钟,独立工具和模型限制仍有效。以查询到的终态为准,不以 token usage summary 判断成功。 + +- 幂等键必填,1–200字节,按认证用户隔离。同键、相同请求返回原回执;同键不同请求返回409。回执丢失时使用原键和原请求重试。新一轮执行使用新键。 +- 同一会话已有任务时返回409,不追加该冲突请求的消息。 +- 使用 `POST /api/agent-loop/cancel` 和 `{"conversationId":"..."}` 显式取消当前会话任务。取消是会话级操作,请先确认当前运行与待取消回执一致。 +- 通过 `/api/conversations/{conversationId}` 查看对话;通过 `/api/messages/{assistantMessageId}/process-details` 读取保存的过程;活动任务也可订阅 `/api/agent-loop/task-events?conversationId=...`。订阅不回放历史。 +- 状态可为 running、completed、failed、cancelled、timeout、interrupted,以及交付检查或资源清理状态。只有执行响应的 finalized=true 才表示成功最终交付。 +- 提交需要 agent:execute 与 chat:write;查询仍要求接口权限及对话访问权限,后台执行保留提交者主体。 +- 回执与结果保存在服务端数据库。当前运行模型为单实例独占数据库;服务启动会将遗留 running 标记 interrupted。不会自动重放未完成工具;需要用户决定是否在原会话继续。 +- 异步能力不保证外部工具永不失败,也不承诺进程崩溃后的自动续跑。数据库不可写时提交返回错误,不能将此视为已接收。 diff --git a/internal/app/app.go b/internal/app/app.go index c7ce5896..b7b2d8ff 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -1026,6 +1026,10 @@ func setupRoutes( // Eino ADK 单代理(ChatModelAgent + Runner;不依赖 multi_agent.enabled) protected.POST("/eino-agent", agentHandler.EinoSingleAgentLoop) + protected.POST("/eino-agent/runs", agentHandler.SubmitSingleAgentRun) + protected.POST("/multi-agent/runs", agentHandler.SubmitMultiAgentRun) + protected.GET("/eino-agent/runs/:runId", agentHandler.GetAgentRun) + protected.GET("/multi-agent/runs/:runId", agentHandler.GetAgentRun) protected.POST("/eino-agent/stream", agentHandler.EinoSingleAgentLoopStream) protected.GET("/hitl/pending", agentHandler.ListHITLPending) protected.GET("/hitl/logs", agentHandler.ListHITLLogs) diff --git a/internal/database/agent_runs.go b/internal/database/agent_runs.go new file mode 100644 index 00000000..699bca2f --- /dev/null +++ b/internal/database/agent_runs.go @@ -0,0 +1,58 @@ +package database + +import ( + "encoding/json" + "time" +) + +// AgentRun is a durable receipt for an accepted asynchronous invocation. +type AgentRun struct { + RunID string `json:"runId"` + UserID string `json:"-"` + Key string `json:"-"` + Fingerprint string `json:"-"` + ConversationID string `json:"conversationId"` + AssistantMessageID string `json:"assistantMessageId"` + Status string `json:"status"` + Result json.RawMessage `json:"result,omitempty"` + CreatedAt string `json:"createdAt"` + UpdatedAt string `json:"updatedAt"` +} + +func (db *DB) initAgentRuns() error { + _, err := db.Exec(`CREATE TABLE IF NOT EXISTS agent_async_runs ( + run_id TEXT PRIMARY KEY, user_id TEXT NOT NULL, idempotency_key TEXT NOT NULL, + fingerprint TEXT NOT NULL, conversation_id TEXT NOT NULL, assistant_message_id TEXT NOT NULL, + status TEXT NOT NULL, result TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL, updated_at TEXT NOT NULL, + UNIQUE(user_id, idempotency_key))`) + if err != nil { + return err + } + _, err = db.Exec(`UPDATE agent_async_runs SET status='interrupted', result='{"error":"server restarted before completion"}', updated_at=? WHERE status='running'`, time.Now().UTC().Format(time.RFC3339Nano)) + return err +} +func (db *DB) CreateAgentRun(r *AgentRun) error { + r.CreatedAt = time.Now().UTC().Format(time.RFC3339Nano) + r.UpdatedAt = r.CreatedAt + _, err := db.Exec(`INSERT INTO agent_async_runs(run_id,user_id,idempotency_key,fingerprint,conversation_id,assistant_message_id,status,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?)`, r.RunID, r.UserID, r.Key, r.Fingerprint, r.ConversationID, r.AssistantMessageID, r.Status, r.CreatedAt, r.UpdatedAt) + return err +} +func (db *DB) GetAgentRun(id string) (*AgentRun, error) { return db.readAgentRun("run_id=?", id) } +func (db *DB) FindAgentRun(user, key string) (*AgentRun, error) { + return db.readAgentRun("user_id=? AND idempotency_key=?", user, key) +} +func (db *DB) readAgentRun(where string, args ...interface{}) (*AgentRun, error) { + r := &AgentRun{} + var raw string + err := db.QueryRow(`SELECT run_id,user_id,idempotency_key,fingerprint,conversation_id,assistant_message_id,status,result,created_at,updated_at FROM agent_async_runs WHERE `+where, args...).Scan(&r.RunID, &r.UserID, &r.Key, &r.Fingerprint, &r.ConversationID, &r.AssistantMessageID, &r.Status, &raw, &r.CreatedAt, &r.UpdatedAt) + r.Result = json.RawMessage(raw) + return r, err +} +func (db *DB) FinishAgentRun(id, status string, result interface{}) error { + raw, err := json.Marshal(result) + if err != nil { + return err + } + _, err = db.Exec(`UPDATE agent_async_runs SET status=?,result=?,updated_at=? WHERE run_id=?`, status, string(raw), time.Now().UTC().Format(time.RFC3339Nano), id) + return err +} diff --git a/internal/database/agent_runs_test.go b/internal/database/agent_runs_test.go new file mode 100644 index 00000000..d143beb4 --- /dev/null +++ b/internal/database/agent_runs_test.go @@ -0,0 +1,47 @@ +package database + +import ( + "go.uber.org/zap" + "path/filepath" + "testing" +) + +func TestAgentRunPersistenceAndRecovery(t *testing.T) { + path := filepath.Join(t.TempDir(), "runs.db") + db, err := NewDB(path, zap.NewNop()) + if err != nil { + t.Fatal(err) + } + r := &AgentRun{RunID: "one", UserID: "user", Key: "key", Fingerprint: "hash", ConversationID: "conv", Status: "running"} + if err = db.CreateAgentRun(r); err != nil { + t.Fatal(err) + } + dup := *r + dup.RunID = "duplicate" + if err = db.CreateAgentRun(&dup); err == nil { + t.Fatal("duplicate key accepted") + } + done := *r + done.RunID = "done" + done.Key = "done" + if err = db.CreateAgentRun(&done); err != nil { + t.Fatal(err) + } + if err = db.FinishAgentRun("done", "completed", map[string]string{"response": "saved"}); err != nil { + t.Fatal(err) + } + db.Close() + db, err = NewDB(path, zap.NewNop()) + if err != nil { + t.Fatal(err) + } + defer db.Close() + got, err := db.FindAgentRun("user", "key") + if err != nil || got.Status != "interrupted" { + t.Fatalf("recovery: %+v %v", got, err) + } + got, err = db.GetAgentRun("done") + if err != nil || got.Status != "completed" || string(got.Result) != `{"response":"saved"}` { + t.Fatalf("terminal result: %+v %v", got, err) + } +} diff --git a/internal/database/database.go b/internal/database/database.go index 02fb807a..cbca4699 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -163,6 +163,10 @@ func NewDB(dbPath string, logger *zap.Logger) (*DB, error) { _ = db.Close() return nil, fmt.Errorf("初始化表失败: %w", err) } + if err := database.initAgentRuns(); err != nil { + _ = db.Close() + return nil, err + } if err := database.migrateLegacyToolGuardBlocks(); err != nil { _ = db.Close() return nil, fmt.Errorf("迁移历史安全拦截记录失败: %w", err) diff --git a/internal/handler/agent.go b/internal/handler/agent.go index 3c21fa26..0e5907ec 100644 --- a/internal/handler/agent.go +++ b/internal/handler/agent.go @@ -182,6 +182,8 @@ func discardPlanningIfEchoesToolResult(respPlan *responsePlanAgg, toolData inter // AgentHandler Agent处理器 type AgentHandler struct { + asyncWorkers sync.WaitGroup + asyncSubmitMu sync.Mutex agent *agent.Agent db *database.DB logger *zap.Logger diff --git a/internal/handler/agent_multi_json_runner.go b/internal/handler/agent_multi_json_runner.go new file mode 100644 index 00000000..930549ae --- /dev/null +++ b/internal/handler/agent_multi_json_runner.go @@ -0,0 +1,120 @@ +package handler + +import ( + "context" + "cyberstrike-ai/internal/agentfinalizer" + "cyberstrike-ai/internal/config" + "cyberstrike-ai/internal/multiagent" + "github.com/gin-gonic/gin" + "go.uber.org/zap" + "net/http" + "strings" + "time" +) + +func (h *AgentHandler) runMultiJSON(taskCtx, baseCtx context.Context, cancelWithCause context.CancelCauseFunc, req *ChatRequest, prep *multiAgentPrepared, status *string, respond func(int, interface{})) { + progressCallback := h.createProgressCallback(taskCtx, cancelWithCause, prep.ConversationID, prep.AssistantMessageID, nil) + taskCtx = multiagent.WithHITLToolInterceptor(taskCtx, func(ctx context.Context, toolName, arguments string) (string, error) { + return h.interceptHITLForEinoTool(ctx, cancelWithCause, prep.ConversationID, prep.AssistantMessageID, nil, toolName, arguments) + }) + runCfg, _, err := h.configForAIChannel(req.AIChannelID) + if err != nil { + respond(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + curHist := prep.History + curMsg := prep.FinalMessage + var result *multiagent.RunResult + var runErr error + var emptyResponseContinueAttempt int + var finalizationAutoContinueAttempt int + effectiveOrch := config.NormalizeMultiAgentOrchestration(h.config.MultiAgent.Orchestration) + if o := strings.TrimSpace(req.Orchestration); o != "" { + effectiveOrch = config.NormalizeMultiAgentOrchestration(o) + } + agentMode := "eino_" + effectiveOrch + var decision agentfinalizer.Decision + var autoCancelledPendingExecutionIDs []string + for { + result, runErr = multiagent.RunDeepAgent( + taskCtx, + runCfg, + &runCfg.MultiAgent, + h.agent, + h.db, + h.logger, + prep.ConversationID, + h.conversationProjectID(prep.ConversationID), + curMsg, + curHist, + prep.RoleTools, + progressCallback, + h.agentsMarkdownDir, + strings.TrimSpace(req.Orchestration), + chatReasoningToClientIntent(req.Reasoning), + h.agentSessionContextBlock(prep.ConversationID), + ) + if runErr != nil { + if shouldPersistEinoAgentTraceAfterRunError(baseCtx) { + h.persistEinoAgentTraceForResume(prep.ConversationID, result) + } + h.logger.Error("Eino DeepAgent 执行失败", zap.Error(runErr)) + clientErr := multiagent.EinoClientRunErrorMessage(runErr) + errMsg := "执行失败: " + clientErr + if prep.AssistantMessageID != "" { + _, _ = h.db.Exec("UPDATE messages SET content = ?, updated_at = ? WHERE id = ?", errMsg, time.Now(), prep.AssistantMessageID) + } + errData := multiagent.EinoClientRunErrorFields(runErr) + errData["error"] = errMsg + respond(http.StatusInternalServerError, errData) + return + } + mw := &h.config.MultiAgent.EinoMiddleware + if h.tryContinueOnEinoEmptyResponse(taskCtx, mw, prep.ConversationID, result, &emptyResponseContinueAttempt, &curHist, &curMsg, progressCallback) { + continue + } + decision = h.decideAgentRunForDeliveryWithPolicy(prep.ConversationID, prep.AssistantMessageID, agentMode, result, result.MCPExecutionIDs, requestRequiresExecutionEvidence(req)) + if cancelled := h.cleanupPendingToolExecutionsAfterIteration(taskCtx, prep.ConversationID, decision, progressCallback); len(cancelled) > 0 { + autoCancelledPendingExecutionIDs = mergeMCPExecutionIDLists(autoCancelledPendingExecutionIDs, cancelled) + decision = h.decideAgentRunForDeliveryWithPolicy(prep.ConversationID, prep.AssistantMessageID, agentMode, result, result.MCPExecutionIDs, requestRequiresExecutionEvidence(req)) + } + if h.tryAutoContinueAfterFinalization(taskCtx, prep.ConversationID, result, decision, &finalizationAutoContinueAttempt, &curHist, &curMsg, progressCallback) { + continue + } + break + } + + h.persistFinalizationDecision(prep.ConversationID, prep.AssistantMessageID, agentMode, result.MCPExecutionIDs, multiagent.AggregatedReasoningFromTraceJSON(result.LastAgentTraceInput), decision) + + if result.LastAgentTraceInput != "" || result.LastAgentTraceOutput != "" { + if err := h.db.SaveAgentTrace(prep.ConversationID, result.LastAgentTraceInput, result.LastAgentTraceOutput); err != nil { + h.logger.Warn("保存代理轨迹失败", zap.Error(err)) + } + } + + responseText := decision.FinalText + if !decision.Finalizable { + responseText = finalizationBlockedMessage(decision) + } + + *status = decision.Status + if *status == "" { + *status = "completed" + } + respond(http.StatusOK, ChatResponse{ + Response: responseText, + MCPExecutionIDs: result.MCPExecutionIDs, + ConversationID: prep.ConversationID, + Time: time.Now(), + Finalizable: decision.Finalizable, + Finalized: decision.Finalized, + Status: decision.Status, + CompletionReason: decision.CompletionReason, + EvidenceVerified: decision.EvidenceVerified, + EvidenceRefs: decision.EvidenceRefs, + PendingExecutionIDs: decision.PendingExecutionIDs, + MissingChecks: decision.MissingChecks, + AutoCancelledPendingExecutionIDs: autoCancelledPendingExecutionIDs, + }) +} diff --git a/internal/handler/agent_single_json_runner.go b/internal/handler/agent_single_json_runner.go new file mode 100644 index 00000000..c84e93cd --- /dev/null +++ b/internal/handler/agent_single_json_runner.go @@ -0,0 +1,104 @@ +package handler + +import ( + "context" + "cyberstrike-ai/internal/agentfinalizer" + "cyberstrike-ai/internal/multiagent" + "github.com/gin-gonic/gin" + "net/http" +) + +func (h *AgentHandler) runSingleJSON(taskCtx, baseCtx context.Context, cancelWithCause context.CancelCauseFunc, req *ChatRequest, prep *multiAgentPrepared, status *string, respond func(int, interface{})) { + progressCallback := h.createProgressCallback(taskCtx, cancelWithCause, prep.ConversationID, prep.AssistantMessageID, nil) + taskCtx = multiagent.WithHITLToolInterceptor(taskCtx, func(ctx context.Context, toolName, arguments string) (string, error) { + return h.interceptHITLForEinoTool(ctx, cancelWithCause, prep.ConversationID, prep.AssistantMessageID, nil, toolName, arguments) + }) + + if h.config == nil { + respond(http.StatusInternalServerError, gin.H{"error": "服务器配置未加载"}) + return + } + runCfg, _, err := h.configForAIChannel(req.AIChannelID) + if err != nil { + respond(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + curHist := prep.History + curMsg := prep.FinalMessage + var result *multiagent.RunResult + var runErr error + var emptyResponseContinueAttempt int + var finalizationAutoContinueAttempt int + var decision agentfinalizer.Decision + var autoCancelledPendingExecutionIDs []string + for { + result, runErr = multiagent.RunEinoSingleChatModelAgent( + taskCtx, + runCfg, + &runCfg.MultiAgent, + h.agent, + h.db, + h.logger, + prep.ConversationID, + h.conversationProjectID(prep.ConversationID), + curMsg, + curHist, + prep.RoleTools, + progressCallback, + chatReasoningToClientIntent(req.Reasoning), + h.agentSessionContextBlock(prep.ConversationID), + ) + if runErr != nil { + if shouldPersistEinoAgentTraceAfterRunError(baseCtx) { + h.persistEinoAgentTraceForResume(prep.ConversationID, result) + } + respond(http.StatusInternalServerError, gin.H{"error": runErr.Error()}) + return + } + mw := &h.config.MultiAgent.EinoMiddleware + if h.tryContinueOnEinoEmptyResponse(taskCtx, mw, prep.ConversationID, result, &emptyResponseContinueAttempt, &curHist, &curMsg, progressCallback) { + continue + } + decision = h.decideAgentRunForDeliveryWithPolicy(prep.ConversationID, prep.AssistantMessageID, "eino_single", result, result.MCPExecutionIDs, requestRequiresExecutionEvidence(req)) + if cancelled := h.cleanupPendingToolExecutionsAfterIteration(taskCtx, prep.ConversationID, decision, progressCallback); len(cancelled) > 0 { + autoCancelledPendingExecutionIDs = mergeMCPExecutionIDLists(autoCancelledPendingExecutionIDs, cancelled) + decision = h.decideAgentRunForDeliveryWithPolicy(prep.ConversationID, prep.AssistantMessageID, "eino_single", result, result.MCPExecutionIDs, requestRequiresExecutionEvidence(req)) + } + if h.tryAutoContinueAfterFinalization(taskCtx, prep.ConversationID, result, decision, &finalizationAutoContinueAttempt, &curHist, &curMsg, progressCallback) { + continue + } + break + } + + h.persistFinalizationDecision(prep.ConversationID, prep.AssistantMessageID, "eino_single", result.MCPExecutionIDs, multiagent.AggregatedReasoningFromTraceJSON(result.LastAgentTraceInput), decision) + if result.LastAgentTraceInput != "" || result.LastAgentTraceOutput != "" { + _ = h.db.SaveAgentTrace(prep.ConversationID, result.LastAgentTraceInput, result.LastAgentTraceOutput) + } + + responseText := decision.FinalText + if !decision.Finalizable { + responseText = finalizationBlockedMessage(decision) + } + + *status = decision.Status + if *status == "" { + *status = "completed" + } + respond(http.StatusOK, gin.H{ + "response": responseText, + "conversationId": prep.ConversationID, + "mcpExecutionIds": result.MCPExecutionIDs, + "assistantMessageId": prep.AssistantMessageID, + "agentMode": "eino_single", + "finalized": decision.Finalized, + "finalizable": decision.Finalizable, + "status": decision.Status, + "completionReason": decision.CompletionReason, + "evidenceVerified": decision.EvidenceVerified, + "evidenceRefs": decision.EvidenceRefs, + "pendingExecutionIds": decision.PendingExecutionIDs, + "missingChecks": decision.MissingChecks, + "autoCancelledPendingExecutionIds": autoCancelledPendingExecutionIDs, + }) +} diff --git a/internal/handler/async_agent_runs.go b/internal/handler/async_agent_runs.go new file mode 100644 index 00000000..e2a12ec2 --- /dev/null +++ b/internal/handler/async_agent_runs.go @@ -0,0 +1,211 @@ +package handler + +import ( + "context" + "crypto/sha256" + "database/sql" + "encoding/hex" + "encoding/json" + "errors" + "net/http" + "strings" + "sync" + "time" + + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/mcp" + "cyberstrike-ai/internal/security" + "github.com/gin-gonic/gin" + "go.uber.org/zap" +) + +func (h *AgentHandler) SubmitSingleAgentRun(c *gin.Context) { h.submitAgentRun(c, false) } +func (h *AgentHandler) SubmitMultiAgentRun(c *gin.Context) { h.submitAgentRun(c, true) } +func (h *AgentHandler) submitAgentRun(c *gin.Context, multi bool) { + h.submitAgentRunWithExecutor(c, multi, h.executeAcceptedRun) +} + +type acceptedRunExecutor func(context.Context, context.Context, context.CancelCauseFunc, context.CancelFunc, ChatRequest, *multiAgentPrepared, *database.AgentRun, bool) + +func (h *AgentHandler) submitAgentRunWithExecutor(c *gin.Context, multi bool, execute acceptedRunExecutor) { + session, ok := security.CurrentSession(c) + if !ok || !session.Permissions["chat:write"] || !session.Permissions["agent:execute"] { + c.JSON(403, gin.H{"error": "forbidden"}) + return + } + key := strings.TrimSpace(c.GetHeader("Idempotency-Key")) + if key == "" || len(key) > 200 { + c.JSON(400, gin.H{"error": "Idempotency-Key must contain 1–200 bytes"}) + return + } + var req ChatRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(400, gin.H{"error": err.Error()}) + return + } + raw, _ := json.Marshal(struct { + Request ChatRequest + Multi bool + }{req, multi}) + sum := sha256.Sum256(raw) + fingerprint := hex.EncodeToString(sum[:]) + // Serialize acceptance, not execution. A retry cannot create messages before its receipt is checked. + h.asyncSubmitMu.Lock() + defer h.asyncSubmitMu.Unlock() + old, err := h.db.FindAgentRun(session.UserID, key) + if err == nil { + if old.Fingerprint != fingerprint { + c.JSON(409, gin.H{"error": "idempotency key reused with different request"}) + return + } + if !h.agentConversationAllowed(c, old.ConversationID) { + c.JSON(403, gin.H{"error": "forbidden"}) + return + } + h.agentRunReceipt(c, old) + return + } + if !errors.Is(err, sql.ErrNoRows) { + c.JSON(500, gin.H{"error": "cannot read run receipt"}) + return + } + if h.config == nil || (multi && !h.config.MultiAgent.Enabled) { + c.JSON(400, gin.H{"error": "agent mode unavailable"}) + return + } + if _, _, err := h.configForAIChannel(req.AIChannelID); err != nil { + c.JSON(400, gin.H{"error": err.Error()}) + return + } + if id := strings.TrimSpace(req.ConversationID); id != "" { + if !h.agentConversationAllowed(c, id) { + c.JSON(403, gin.H{"error": "forbidden"}) + return + } + if h.tasks.GetTask(id) != nil { + c.JSON(409, gin.H{"error": "conversation already running"}) + return + } + } + source := "eino_agent_async" + if multi { + source = "multi_agent_async" + } + prep, err := h.prepareMultiAgentSession(&req, c, source) + if err != nil { + code, msg := multiAgentHTTPErrorStatus(err) + c.JSON(code, gin.H{"error": msg}) + return + } + base, cancel := context.WithCancelCause(detachedAgentContext(c.Request.Context())) + ctx, timeoutCancel := context.WithTimeout(base, 600*time.Minute) + task, err := h.tasks.StartTask(prep.ConversationID, req.Message, cancel) + if err != nil { + timeoutCancel() + cancel(nil) + c.JSON(409, gin.H{"error": err.Error()}) + return + } + record := &database.AgentRun{RunID: task.RunID, UserID: session.UserID, Key: key, Fingerprint: fingerprint, ConversationID: prep.ConversationID, AssistantMessageID: prep.AssistantMessageID, Status: "running"} + if err = h.db.CreateAgentRun(record); err != nil { + timeoutCancel() + cancel(nil) + _ = h.tasks.FinishTaskRun(prep.ConversationID, task.RunID, "failed") + c.JSON(500, gin.H{"error": "cannot persist run receipt"}) + return + } + ctx = h.tasks.BindProcessScope(ctx, prep.ConversationID, task.RunID) + ctx = mcp.WithMCPConversationID(ctx, prep.ConversationID) + ctx = mcp.WithToolRunRegistry(ctx, h.tasks) + ctx = mcp.WithEinoExecuteRunRegistry(ctx, h.tasks) + h.asyncWorkers.Add(1) + go func() { + defer h.asyncWorkers.Done() + execute(ctx, base, cancel, timeoutCancel, req, prep, record, multi) + }() + h.agentRunReceipt(c, record) +} +func (h *AgentHandler) agentRunReceipt(c *gin.Context, r *database.AgentRun) { + url := "/api/eino-agent/runs/" + r.RunID + c.Header("Location", url) + c.JSON(http.StatusAccepted, gin.H{"runId": r.RunID, "conversationId": r.ConversationID, "assistantMessageId": r.AssistantMessageID, "status": r.Status, "statusUrl": url}) +} +func (h *AgentHandler) GetAgentRun(c *gin.Context) { + r, err := h.db.GetAgentRun(c.Param("runId")) + if errors.Is(err, sql.ErrNoRows) { + c.JSON(404, gin.H{"error": "run not found"}) + return + } + if err != nil { + c.JSON(500, gin.H{"error": "cannot read run"}) + return + } + if !h.agentConversationAllowed(c, r.ConversationID) { + c.JSON(403, gin.H{"error": "forbidden"}) + return + } + c.JSON(200, r) +} +func (h *AgentHandler) executeAcceptedRun(ctx, base context.Context, cancel context.CancelCauseFunc, timeoutCancel context.CancelFunc, req ChatRequest, prep *multiAgentPrepared, record *database.AgentRun, multi bool) { + h.executeAcceptedRunBody(ctx, base, cancel, timeoutCancel, prep, record, func(status *string, respond func(int, interface{})) { + h.activateHITLForConversation(prep.ConversationID, req.Hitl) + if h.hitlManager != nil { + defer h.hitlManager.DeactivateConversation(prep.ConversationID) + } + if role, ok := h.roleForWorkflow(&req); ok { + h.runWorkflowJSON(ctx, base, cancel, &req, prep, role, status, respond) + return + } + if multi { + h.runMultiJSON(ctx, base, cancel, &req, prep, status, respond) + } else { + h.runSingleJSON(ctx, base, cancel, &req, prep, status, respond) + } + }) +} + +func (h *AgentHandler) executeAcceptedRunBody(ctx, base context.Context, cancel context.CancelCauseFunc, timeoutCancel context.CancelFunc, prep *multiAgentPrepared, record *database.AgentRun, body func(*string, func(int, interface{}))) { + status := "failed" + var result interface{} = gin.H{"error": "execution ended without a result"} + defer func() { + if p := recover(); p != nil { + status = "failed" + result = gin.H{"error": "internal execution failure"} + h.logger.Error("async agent panic", zap.Any("panic", p)) + } + if errors.Is(context.Cause(base), ErrTaskCancelled) { + status = "cancelled" + } else if errors.Is(ctx.Err(), context.DeadlineExceeded) { + status = "timeout" + } + if err := h.tasks.FinishTaskRun(prep.ConversationID, record.RunID, status); err != nil { + status = taskCleanupStatus(err) + result = gin.H{"error": err.Error()} + } + // Cleanup may race an explicit cancellation; use the registry's settled outcome. + for _, finished := range h.tasks.GetCompletedTasks() { + if finished.RunID == record.RunID { + status = finished.Status + break + } + } + if err := h.db.FinishAgentRun(record.RunID, status, result); err != nil { + h.logger.Error("persist async run result", zap.String("runId", record.RunID), zap.Error(err)) + } + timeoutCancel() + cancel(nil) + }() + body(&status, func(code int, payload interface{}) { + result = payload + if code >= 400 { + status = "failed" + } + }) +} + +// lockAgentAdmission covers preparation through registration across all chat transports. +func (h *AgentHandler) lockAgentAdmission() func() { + h.asyncSubmitMu.Lock() + var once sync.Once + return func() { once.Do(h.asyncSubmitMu.Unlock) } +} diff --git a/internal/handler/async_agent_runs_test.go b/internal/handler/async_agent_runs_test.go new file mode 100644 index 00000000..34d2e1e0 --- /dev/null +++ b/internal/handler/async_agent_runs_test.go @@ -0,0 +1,191 @@ +package handler + +import ( + "context" + "cyberstrike-ai/internal/config" + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/security" + "encoding/json" + "github.com/gin-gonic/gin" + "go.uber.org/zap" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestAsyncAdmissionDisconnectIdempotencyAndAccess(t *testing.T) { + gin.SetMode(gin.TestMode) + db, err := database.NewDB(filepath.Join(t.TempDir(), "async.db"), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + defer db.Close() + user, err := db.CreateRBACUser("caller", "Caller", "hash", true, nil) + if err != nil { + t.Fatal(err) + } + cfg := &config.Config{} + cfg.MultiAgent.Enabled = true + cfg.OpenAI.Model = "test" + h := &AgentHandler{db: db, logger: zap.NewNop(), tasks: NewAgentTaskManager(), config: cfg} + defer h.tasks.Shutdown() + session := security.Session{UserID: user.ID, Scope: database.RBACScopeAll, Permissions: map[string]bool{"chat:write": true, "agent:execute": true}} + contexts := make(chan context.Context, 2) + release := make(chan struct{}) + done := make(chan struct{}, 2) + executor := func(ctx, base context.Context, cancel context.CancelCauseFunc, timeout context.CancelFunc, req ChatRequest, p *multiAgentPrepared, r *database.AgentRun, multi bool) { + contexts <- ctx + <-release + status := "completed" + if ctx.Err() != nil { + status = "cancelled" + } + _ = h.tasks.FinishTaskRun(p.ConversationID, r.RunID, status) + _ = db.FinishAgentRun(r.RunID, status, map[string]string{"response": "done"}) + timeout() + cancel(nil) + done <- struct{}{} + } + submit := func(ctx context.Context, key, body string, multi bool) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest("POST", "/api/eino-agent/runs", strings.NewReader(body)).WithContext(ctx) + c.Request.Header.Set("Content-Type", "application/json") + c.Request.Header.Set("Idempotency-Key", key) + c.Set(security.ContextSessionKey, session) + h.submitAgentRunWithExecutor(c, multi, executor) + return w + } + parent, cancel := context.WithCancel(context.Background()) + w := submit(parent, "first", `{"message":"long task"}`, false) + if w.Code != 202 { + t.Fatalf("submit %d %s", w.Code, w.Body) + } + var receipt struct{ RunID, ConversationID string } + if err = json.Unmarshal(w.Body.Bytes(), &receipt); err != nil { + t.Fatal(err) + } + ctx := <-contexts + cancel() + if ctx.Err() != nil { + t.Fatal("client disconnect cancelled worker") + } + retry := submit(context.Background(), "first", `{"message":"long task"}`, false) + if retry.Code != 202 || !strings.Contains(retry.Body.String(), receipt.RunID) { + t.Fatalf("retry: %d %s", retry.Code, retry.Body) + } + if w = submit(context.Background(), "first", `{"message":"changed"}`, false); w.Code != 409 { + t.Fatalf("mismatch %d", w.Code) + } + before, _ := db.GetMessages(receipt.ConversationID) + body := `{"message":"conflict","conversationId":"` + receipt.ConversationID + `"}` + if w = submit(context.Background(), "second", body, false); w.Code != 409 { + t.Fatalf("conflict %d %s", w.Code, w.Body) + } + after, _ := db.GetMessages(receipt.ConversationID) + if len(before) != len(after) { + t.Fatal("conflict polluted conversation") + } + // GET uses resource permissions, even when a caller guesses a run ID. + w = httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Params = gin.Params{{Key: "runId", Value: receipt.RunID}} + c.Set(security.ContextSessionKey, security.Session{UserID: "stranger", Scope: database.RBACScopeAssigned}) + h.GetAgentRun(c) + if w.Code != 403 { + t.Fatalf("unauthorized get %d", w.Code) + } + if ok, err := h.tasks.CancelTask(receipt.ConversationID, ErrTaskCancelled); !ok || err != nil { + t.Fatalf("cancel %v %v", ok, err) + } + select { + case <-ctx.Done(): + case <-time.After(time.Second): + t.Fatal("explicit cancel did not stop worker") + } + close(release) + <-done + saved, err := db.GetAgentRun(receipt.RunID) + if err != nil || saved.Status != "cancelled" { + t.Fatalf("status %+v %v", saved, err) + } + // Multi-agent uses the same acceptance contract. + w = submit(context.Background(), "multi", `{"message":"other"}`, true) + if w.Code != 202 { + t.Fatalf("multi %d %s", w.Code, w.Body) + } + <-contexts + <-done +} + +func TestAsyncWorkerFinalizesCancellationDeadlineAndPanic(t *testing.T) { + for _, mode := range []string{"completed", "cancelled", "timeout", "panic"} { + t.Run(mode, func(t *testing.T) { + db, err := database.NewDB(filepath.Join(t.TempDir(), "run.db"), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + defer db.Close() + h := &AgentHandler{db: db, logger: zap.NewNop(), tasks: NewAgentTaskManager()} + defer h.tasks.Shutdown() + base, cancel := context.WithCancelCause(context.Background()) + ctx, timeout := context.WithTimeout(base, time.Hour) + if mode == "timeout" { + timeout() + ctx, timeout = context.WithDeadline(base, time.Now().Add(-time.Second)) + } + task, err := h.tasks.StartTask("conv", "message", cancel) + if err != nil { + t.Fatal(err) + } + r := &database.AgentRun{RunID: task.RunID, UserID: "user", Key: mode, ConversationID: "conv", Status: "running"} + if err = db.CreateAgentRun(r); err != nil { + t.Fatal(err) + } + prep := &multiAgentPrepared{ConversationID: "conv"} + h.executeAcceptedRunBody(ctx, base, cancel, timeout, prep, r, func(status *string, respond func(int, interface{})) { + if mode == "panic" { + panic("test") + } + if mode == "cancelled" { + cancel(ErrTaskCancelled) + } + *status = "completed" + respond(200, map[string]string{"response": "result"}) + }) + got, err := db.GetAgentRun(task.RunID) + want := mode + if mode == "panic" { + want = "failed" + } + if err != nil || got.Status != want { + t.Fatalf("got %+v err %v want %s", got, err, want) + } + if h.tasks.GetTask("conv") != nil { + t.Fatal("task remained active") + } + }) + } +} + +func TestOpenAPIAsyncRunEndpoints(t *testing.T) { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest("GET", "/api/openapi.json", nil) + (&OpenAPIHandler{}).GetOpenAPISpec(c) + if w.Code != 200 { + t.Fatalf("spec %d", w.Code) + } + var spec map[string]interface{} + if err := json.Unmarshal(w.Body.Bytes(), &spec); err != nil { + t.Fatal(err) + } + paths := spec["paths"].(map[string]interface{}) + for _, path := range []string{"/api/eino-agent/runs", "/api/multi-agent/runs", "/api/eino-agent/runs/{runId}", "/api/multi-agent/runs/{runId}"} { + if paths[path] == nil { + t.Errorf("missing %s", path) + } + } +} diff --git a/internal/handler/eino_single_agent.go b/internal/handler/eino_single_agent.go index fbfd6c9d..b3ed6207 100644 --- a/internal/handler/eino_single_agent.go +++ b/internal/handler/eino_single_agent.go @@ -91,6 +91,8 @@ func (h *AgentHandler) EinoSingleAgentLoopStream(c *gin.Context) { zap.String("conversationId", req.ConversationID), ) + releaseAdmission := h.lockAgentAdmission() + defer releaseAdmission() prep, err := h.prepareMultiAgentSession(&req, c, "eino_agent_stream") if err != nil { sendEvent("error", err.Error(), nil) @@ -117,7 +119,7 @@ func (h *AgentHandler) EinoSingleAgentLoopStream(c *gin.Context) { "userMessageId": prep.UserMessageID, }) } - if h.runRoleWorkflowStreamIfBound(c, &req, prep, sendEvent) { + if h.runRoleWorkflowStreamIfBound(c, &req, prep, sendEvent, releaseAdmission) { return } @@ -187,6 +189,7 @@ func (h *AgentHandler) EinoSingleAgentLoopStream(c *gin.Context) { } else { taskRunID = startedTask.RunID } + releaseAdmission() baseCtx = h.tasks.BindProcessScope(baseCtx, conversationID, taskRunID) taskCtx = h.tasks.BindProcessScope(taskCtx, conversationID, taskRunID) taskOwned = true @@ -437,6 +440,8 @@ func (h *AgentHandler) EinoSingleAgentLoop(c *gin.Context) { h.logger.Info("收到 Eino ADK 单代理非流式请求", zap.String("conversationId", req.ConversationID)) + releaseAdmission := h.lockAgentAdmission() + defer releaseAdmission() prep, err := h.prepareMultiAgentSession(&req, c, "eino_agent") if err != nil { status, msg := multiAgentHTTPErrorStatus(err) @@ -447,15 +452,10 @@ func (h *AgentHandler) EinoSingleAgentLoop(c *gin.Context) { if h.hitlManager != nil { defer h.hitlManager.DeactivateConversation(prep.ConversationID) } - if h.runRoleWorkflowJSONIfBound(c, &req, prep) { + if h.runRoleWorkflowJSONIfBound(c, &req, prep, releaseAdmission) { return } - var progressBuf strings.Builder - progressCallbackRaw := func(eventType, message string, data interface{}) { - progressBuf.WriteString(eventType) - progressBuf.WriteByte('\n') - } baseCtx, cancelWithCause := context.WithCancelCause(c.Request.Context()) defer cancelWithCause(nil) taskCtx, timeoutCancel := context.WithTimeout(baseCtx, 600*time.Minute) @@ -465,6 +465,7 @@ func (h *AgentHandler) EinoSingleAgentLoop(c *gin.Context) { c.JSON(http.StatusConflict, gin.H{"error": startErr.Error()}) return } + releaseAdmission() taskCtx = h.tasks.BindProcessScope(taskCtx, prep.ConversationID, jsonTask.RunID) taskCtx = mcp.WithMCPConversationID(taskCtx, prep.ConversationID) taskCtx = mcp.WithToolRunRegistry(taskCtx, h.tasks) @@ -473,96 +474,5 @@ func (h *AgentHandler) EinoSingleAgentLoop(c *gin.Context) { defer func() { _ = h.tasks.FinishTaskRun(prep.ConversationID, jsonTask.RunID, jsonTaskStatus) }() respond := h.taskFinishingJSONResponder(c, prep.ConversationID, jsonTask.RunID, func() string { return jsonTaskStatus }) - progressCallback := h.createProgressCallback(taskCtx, cancelWithCause, prep.ConversationID, prep.AssistantMessageID, progressCallbackRaw) - taskCtx = multiagent.WithHITLToolInterceptor(taskCtx, func(ctx context.Context, toolName, arguments string) (string, error) { - return h.interceptHITLForEinoTool(ctx, cancelWithCause, prep.ConversationID, prep.AssistantMessageID, nil, toolName, arguments) - }) - - if h.config == nil { - respond(http.StatusInternalServerError, gin.H{"error": "服务器配置未加载"}) - return - } - runCfg, _, err := h.configForAIChannel(req.AIChannelID) - if err != nil { - respond(http.StatusBadRequest, gin.H{"error": err.Error()}) - return - } - - curHist := prep.History - curMsg := prep.FinalMessage - var result *multiagent.RunResult - var runErr error - var emptyResponseContinueAttempt int - var finalizationAutoContinueAttempt int - var decision agentfinalizer.Decision - var autoCancelledPendingExecutionIDs []string - for { - result, runErr = multiagent.RunEinoSingleChatModelAgent( - taskCtx, - runCfg, - &runCfg.MultiAgent, - h.agent, - h.db, - h.logger, - prep.ConversationID, - h.conversationProjectID(prep.ConversationID), - curMsg, - curHist, - prep.RoleTools, - progressCallback, - chatReasoningToClientIntent(req.Reasoning), - h.agentSessionContextBlock(prep.ConversationID), - ) - if runErr != nil { - if shouldPersistEinoAgentTraceAfterRunError(baseCtx) { - h.persistEinoAgentTraceForResume(prep.ConversationID, result) - } - respond(http.StatusInternalServerError, gin.H{"error": runErr.Error()}) - return - } - mw := &h.config.MultiAgent.EinoMiddleware - if h.tryContinueOnEinoEmptyResponse(taskCtx, mw, prep.ConversationID, result, &emptyResponseContinueAttempt, &curHist, &curMsg, progressCallback) { - continue - } - decision = h.decideAgentRunForDeliveryWithPolicy(prep.ConversationID, prep.AssistantMessageID, "eino_single", result, result.MCPExecutionIDs, requestRequiresExecutionEvidence(&req)) - if cancelled := h.cleanupPendingToolExecutionsAfterIteration(taskCtx, prep.ConversationID, decision, progressCallback); len(cancelled) > 0 { - autoCancelledPendingExecutionIDs = mergeMCPExecutionIDLists(autoCancelledPendingExecutionIDs, cancelled) - decision = h.decideAgentRunForDeliveryWithPolicy(prep.ConversationID, prep.AssistantMessageID, "eino_single", result, result.MCPExecutionIDs, requestRequiresExecutionEvidence(&req)) - } - if h.tryAutoContinueAfterFinalization(taskCtx, prep.ConversationID, result, decision, &finalizationAutoContinueAttempt, &curHist, &curMsg, progressCallback) { - continue - } - break - } - - h.persistFinalizationDecision(prep.ConversationID, prep.AssistantMessageID, "eino_single", result.MCPExecutionIDs, multiagent.AggregatedReasoningFromTraceJSON(result.LastAgentTraceInput), decision) - if result.LastAgentTraceInput != "" || result.LastAgentTraceOutput != "" { - _ = h.db.SaveAgentTrace(prep.ConversationID, result.LastAgentTraceInput, result.LastAgentTraceOutput) - } - - responseText := decision.FinalText - if !decision.Finalizable { - responseText = finalizationBlockedMessage(decision) - } - - jsonTaskStatus = decision.Status - if jsonTaskStatus == "" { - jsonTaskStatus = "completed" - } - respond(http.StatusOK, gin.H{ - "response": responseText, - "conversationId": prep.ConversationID, - "mcpExecutionIds": result.MCPExecutionIDs, - "assistantMessageId": prep.AssistantMessageID, - "agentMode": "eino_single", - "finalized": decision.Finalized, - "finalizable": decision.Finalizable, - "status": decision.Status, - "completionReason": decision.CompletionReason, - "evidenceVerified": decision.EvidenceVerified, - "evidenceRefs": decision.EvidenceRefs, - "pendingExecutionIds": decision.PendingExecutionIDs, - "missingChecks": decision.MissingChecks, - "autoCancelledPendingExecutionIds": autoCancelledPendingExecutionIDs, - }) + h.runSingleJSON(taskCtx, baseCtx, cancelWithCause, &req, prep, &jsonTaskStatus, respond) } diff --git a/internal/handler/multi_agent.go b/internal/handler/multi_agent.go index 7ea97834..6e9ecfa3 100644 --- a/internal/handler/multi_agent.go +++ b/internal/handler/multi_agent.go @@ -108,6 +108,8 @@ func (h *AgentHandler) MultiAgentLoopStream(c *gin.Context) { zap.String("conversationId", req.ConversationID), ) + releaseAdmission := h.lockAgentAdmission() + defer releaseAdmission() prep, err := h.prepareMultiAgentSession(&req, c, "multi_agent_stream") if err != nil { sendEvent("error", err.Error(), nil) @@ -134,7 +136,7 @@ func (h *AgentHandler) MultiAgentLoopStream(c *gin.Context) { "userMessageId": prep.UserMessageID, }) } - if h.runRoleWorkflowStreamIfBound(c, &req, prep, sendEvent) { + if h.runRoleWorkflowStreamIfBound(c, &req, prep, sendEvent, releaseAdmission) { return } @@ -194,6 +196,7 @@ func (h *AgentHandler) MultiAgentLoopStream(c *gin.Context) { } else { taskRunID = startedTask.RunID } + releaseAdmission() baseCtx = h.tasks.BindProcessScope(baseCtx, conversationID, taskRunID) taskCtx = h.tasks.BindProcessScope(taskCtx, conversationID, taskRunID) taskOwned = true @@ -456,6 +459,8 @@ func (h *AgentHandler) MultiAgentLoop(c *gin.Context) { h.logger.Info("收到 Eino DeepAgent 非流式请求", zap.String("conversationId", req.ConversationID)) + releaseAdmission := h.lockAgentAdmission() + defer releaseAdmission() prep, err := h.prepareMultiAgentSession(&req, c, "multi_agent") if err != nil { status, msg := multiAgentHTTPErrorStatus(err) @@ -466,7 +471,7 @@ func (h *AgentHandler) MultiAgentLoop(c *gin.Context) { if h.hitlManager != nil { defer h.hitlManager.DeactivateConversation(prep.ConversationID) } - if h.runRoleWorkflowJSONIfBound(c, &req, prep) { + if h.runRoleWorkflowJSONIfBound(c, &req, prep, releaseAdmission) { return } @@ -479,6 +484,7 @@ func (h *AgentHandler) MultiAgentLoop(c *gin.Context) { c.JSON(http.StatusConflict, gin.H{"error": startErr.Error()}) return } + releaseAdmission() taskCtx = h.tasks.BindProcessScope(taskCtx, prep.ConversationID, jsonTask.RunID) taskCtx = mcp.WithMCPConversationID(taskCtx, prep.ConversationID) taskCtx = mcp.WithToolRunRegistry(taskCtx, h.tasks) @@ -487,110 +493,7 @@ func (h *AgentHandler) MultiAgentLoop(c *gin.Context) { defer func() { _ = h.tasks.FinishTaskRun(prep.ConversationID, jsonTask.RunID, jsonTaskStatus) }() respond := h.taskFinishingJSONResponder(c, prep.ConversationID, jsonTask.RunID, func() string { return jsonTaskStatus }) - progressCallback := h.createProgressCallback(taskCtx, cancelWithCause, prep.ConversationID, prep.AssistantMessageID, nil) - taskCtx = multiagent.WithHITLToolInterceptor(taskCtx, func(ctx context.Context, toolName, arguments string) (string, error) { - return h.interceptHITLForEinoTool(ctx, cancelWithCause, prep.ConversationID, prep.AssistantMessageID, nil, toolName, arguments) - }) - runCfg, _, err := h.configForAIChannel(req.AIChannelID) - if err != nil { - respond(http.StatusBadRequest, gin.H{"error": err.Error()}) - return - } - - curHist := prep.History - curMsg := prep.FinalMessage - var result *multiagent.RunResult - var runErr error - var emptyResponseContinueAttempt int - var finalizationAutoContinueAttempt int - effectiveOrch := config.NormalizeMultiAgentOrchestration(h.config.MultiAgent.Orchestration) - if o := strings.TrimSpace(req.Orchestration); o != "" { - effectiveOrch = config.NormalizeMultiAgentOrchestration(o) - } - agentMode := "eino_" + effectiveOrch - var decision agentfinalizer.Decision - var autoCancelledPendingExecutionIDs []string - for { - result, runErr = multiagent.RunDeepAgent( - taskCtx, - runCfg, - &runCfg.MultiAgent, - h.agent, - h.db, - h.logger, - prep.ConversationID, - h.conversationProjectID(prep.ConversationID), - curMsg, - curHist, - prep.RoleTools, - progressCallback, - h.agentsMarkdownDir, - strings.TrimSpace(req.Orchestration), - chatReasoningToClientIntent(req.Reasoning), - h.agentSessionContextBlock(prep.ConversationID), - ) - if runErr != nil { - if shouldPersistEinoAgentTraceAfterRunError(baseCtx) { - h.persistEinoAgentTraceForResume(prep.ConversationID, result) - } - h.logger.Error("Eino DeepAgent 执行失败", zap.Error(runErr)) - clientErr := multiagent.EinoClientRunErrorMessage(runErr) - errMsg := "执行失败: " + clientErr - if prep.AssistantMessageID != "" { - _, _ = h.db.Exec("UPDATE messages SET content = ?, updated_at = ? WHERE id = ?", errMsg, time.Now(), prep.AssistantMessageID) - } - errData := multiagent.EinoClientRunErrorFields(runErr) - errData["error"] = errMsg - respond(http.StatusInternalServerError, errData) - return - } - mw := &h.config.MultiAgent.EinoMiddleware - if h.tryContinueOnEinoEmptyResponse(taskCtx, mw, prep.ConversationID, result, &emptyResponseContinueAttempt, &curHist, &curMsg, progressCallback) { - continue - } - decision = h.decideAgentRunForDeliveryWithPolicy(prep.ConversationID, prep.AssistantMessageID, agentMode, result, result.MCPExecutionIDs, requestRequiresExecutionEvidence(&req)) - if cancelled := h.cleanupPendingToolExecutionsAfterIteration(taskCtx, prep.ConversationID, decision, progressCallback); len(cancelled) > 0 { - autoCancelledPendingExecutionIDs = mergeMCPExecutionIDLists(autoCancelledPendingExecutionIDs, cancelled) - decision = h.decideAgentRunForDeliveryWithPolicy(prep.ConversationID, prep.AssistantMessageID, agentMode, result, result.MCPExecutionIDs, requestRequiresExecutionEvidence(&req)) - } - if h.tryAutoContinueAfterFinalization(taskCtx, prep.ConversationID, result, decision, &finalizationAutoContinueAttempt, &curHist, &curMsg, progressCallback) { - continue - } - break - } - - h.persistFinalizationDecision(prep.ConversationID, prep.AssistantMessageID, agentMode, result.MCPExecutionIDs, multiagent.AggregatedReasoningFromTraceJSON(result.LastAgentTraceInput), decision) - - if result.LastAgentTraceInput != "" || result.LastAgentTraceOutput != "" { - if err := h.db.SaveAgentTrace(prep.ConversationID, result.LastAgentTraceInput, result.LastAgentTraceOutput); err != nil { - h.logger.Warn("保存代理轨迹失败", zap.Error(err)) - } - } - - responseText := decision.FinalText - if !decision.Finalizable { - responseText = finalizationBlockedMessage(decision) - } - - jsonTaskStatus = decision.Status - if jsonTaskStatus == "" { - jsonTaskStatus = "completed" - } - respond(http.StatusOK, ChatResponse{ - Response: responseText, - MCPExecutionIDs: result.MCPExecutionIDs, - ConversationID: prep.ConversationID, - Time: time.Now(), - Finalizable: decision.Finalizable, - Finalized: decision.Finalized, - Status: decision.Status, - CompletionReason: decision.CompletionReason, - EvidenceVerified: decision.EvidenceVerified, - EvidenceRefs: decision.EvidenceRefs, - PendingExecutionIDs: decision.PendingExecutionIDs, - MissingChecks: decision.MissingChecks, - AutoCancelledPendingExecutionIDs: autoCancelledPendingExecutionIDs, - }) + h.runMultiJSON(taskCtx, baseCtx, cancelWithCause, &req, prep, &jsonTaskStatus, respond) } // persistEinoAgentTraceForResume 在 Eino 运行异常结束时写入代理轨迹(库列 last_react_*),供下一请求 loadHistoryFromAgentTrace 软续跑。 @@ -655,6 +558,8 @@ func formatInterruptContinueUserMessage(note string) string { func multiAgentHTTPErrorStatus(err error) (int, string) { msg := err.Error() switch { + case errors.Is(err, ErrTaskAlreadyRunning): + return http.StatusConflict, msg case strings.Contains(msg, "无权访问"): return http.StatusForbidden, msg case strings.Contains(msg, "对话不存在"): diff --git a/internal/handler/multi_agent_prepare.go b/internal/handler/multi_agent_prepare.go index 9da5e142..9ddd967e 100644 --- a/internal/handler/multi_agent_prepare.go +++ b/internal/handler/multi_agent_prepare.go @@ -90,6 +90,9 @@ func (h *AgentHandler) prepareMultiAgentSession(req *ChatRequest, c *gin.Context return nil, fmt.Errorf("无权访问该对话") } } + if h.tasks != nil && h.tasks.GetTask(conversationID) != nil { + return nil, ErrTaskAlreadyRunning + } if err := h.db.SetConversationRoleName(conversationID, req.Role); err != nil { h.logger.Warn("更新对话角色失败", zap.String("conversationId", conversationID), zap.String("role", req.Role), zap.Error(err)) } diff --git a/internal/handler/openapi.go b/internal/handler/openapi.go index 2deea5e7..26b22115 100644 --- a/internal/handler/openapi.go +++ b/internal/handler/openapi.go @@ -6610,6 +6610,7 @@ func (h *OpenAPIHandler) GetOpenAPISpec(c *gin.Context) { }, } + addAgentRunSpec(spec) enrichSpecWithI18nKeys(spec) c.JSON(http.StatusOK, spec) } diff --git a/internal/handler/openapi_agent_runs.go b/internal/handler/openapi_agent_runs.go new file mode 100644 index 00000000..28c12d4d --- /dev/null +++ b/internal/handler/openapi_agent_runs.go @@ -0,0 +1,20 @@ +package handler + +// addAgentRunSpec reuses each synchronous request schema without changing it. +func addAgentRunSpec(spec map[string]interface{}) { + paths := spec["paths"].(map[string]interface{}) + for _, base := range []string{"/api/eino-agent", "/api/multi-agent"} { + original := paths[base].(map[string]interface{})["post"].(map[string]interface{}) + paths[base+"/runs"] = map[string]interface{}{"post": map[string]interface{}{ + "tags": []string{"对话交互"}, "summary": "异步提交对话任务", "description": "接收后返回202,客户端断线不取消任务。必须提供按用户隔离的 Idempotency-Key;相同键和请求返回原回执,不同请求返回409。通过 statusUrl 查询最终结果;取消使用 /api/agent-loop/cancel。", + "requestBody": original["requestBody"], + "parameters": []map[string]interface{}{{"in": "header", "name": "Idempotency-Key", "required": true, "schema": map[string]interface{}{"type": "string", "minLength": 1, "maxLength": 200}}}, + "responses": map[string]interface{}{"202": map[string]interface{}{"description": "已接收:runId、conversationId、assistantMessageId、status、statusUrl;Location 为查询地址"}, "400": map[string]interface{}{"description": "参数或模式无效"}, "403": map[string]interface{}{"description": "无权限"}, "409": map[string]interface{}{"description": "幂等键载荷冲突或会话正在执行"}, "500": map[string]interface{}{"description": "接收记录失败"}}, + }} + paths[base+"/runs/{runId}"] = map[string]interface{}{"get": map[string]interface{}{ + "tags": []string{"对话交互"}, "summary": "查询异步对话任务", "description": "返回持久状态、result、会话和消息标识及时间。服务重启后未完成任务为 interrupted,不自动重放。", + "parameters": []map[string]interface{}{{"in": "path", "name": "runId", "required": true, "schema": map[string]interface{}{"type": "string"}}}, + "responses": map[string]interface{}{"200": map[string]interface{}{"description": "任务状态与结果"}, "403": map[string]interface{}{"description": "无权访问对话"}, "404": map[string]interface{}{"description": "任务不存在"}}, + }} + } +} diff --git a/internal/handler/run_workflow_json.go b/internal/handler/run_workflow_json.go new file mode 100644 index 00000000..eec1e98e --- /dev/null +++ b/internal/handler/run_workflow_json.go @@ -0,0 +1,82 @@ +package handler + +import ( + "context" + "cyberstrike-ai/internal/config" + workflowrunner "cyberstrike-ai/internal/workflow" + "errors" + "github.com/gin-gonic/gin" + "net/http" + "time" +) + +func (h *AgentHandler) runWorkflowJSON(taskCtx, baseCtx context.Context, cancelWithCause context.CancelCauseFunc, req *ChatRequest, prep *multiAgentPrepared, role config.RoleConfig, status *string, respond func(int, interface{})) { + *status = "completed" + conversationID := prep.ConversationID + assistantMessageID := prep.AssistantMessageID + progress := h.createProgressCallback(taskCtx, cancelWithCause, conversationID, assistantMessageID, nil) + result, err := workflowrunner.RunRoleBoundWorkflow(taskCtx, workflowrunner.RunArgs{ + DB: h.db, + Logger: h.logger, + Role: role, + AppCfg: h.config, + Agent: h.agent, + ConversationID: conversationID, + ProjectID: h.conversationProjectID(conversationID), + UserMessage: prep.FinalMessage, + History: prep.History, + RoleTools: prep.RoleTools, + AgentsMarkdownDir: h.agentsMarkdownDir, + SystemPromptExtra: h.agentSessionContextBlock(conversationID), + AssistantMessageID: assistantMessageID, + Progress: progress, + }) + if err != nil { + cause := context.Cause(baseCtx) + if errors.Is(cause, ErrTaskCancelled) { + *status = "cancelled" + cancelMsg := "任务已被用户取消,后续操作已停止。" + if assistantMessageID != "" { + _ = h.appendAssistantMessageNotice(assistantMessageID, cancelMsg) + _ = h.db.AddProcessDetail(assistantMessageID, conversationID, "cancelled", cancelMsg, nil) + } + respond(http.StatusOK, gin.H{ + "status": "cancelled", + "message": cancelMsg, + "conversationId": conversationID, + }) + return + } + errMsg := "执行角色绑定流程失败: " + err.Error() + *status = "failed" + if assistantMessageID != "" { + _, _ = h.db.Exec("UPDATE messages SET content = ?, updated_at = ? WHERE id = ?", errMsg, time.Now(), assistantMessageID) + } + respond(http.StatusInternalServerError, gin.H{"error": errMsg, "conversationId": conversationID}) + return + } + decision := h.finalizeWorkflowRunForDelivery(prep.ConversationID, prep.AssistantMessageID, result) + responseText := decision.FinalText + if !decision.Finalizable { + responseText = finalizationBlockedMessage(decision) + *status = decision.Status + } + respond(http.StatusOK, gin.H{ + "response": responseText, + "conversationId": prep.ConversationID, + "assistantMessageId": prep.AssistantMessageID, + "agentMode": "workflow", + "workflowRunId": result.RunID, + "workflowStatus": result.Status, + "awaitingHitl": result.AwaitingHITL, + "finalized": decision.Finalized, + "finalizable": decision.Finalizable, + "status": decision.Status, + "completionReason": decision.CompletionReason, + "evidenceVerified": decision.EvidenceVerified, + "evidenceRefs": decision.EvidenceRefs, + "pendingExecutionIds": decision.PendingExecutionIDs, + "missingChecks": decision.MissingChecks, + }) + return +} diff --git a/internal/handler/task_lifecycle.go b/internal/handler/task_lifecycle.go index a7d8fb77..e9987f73 100644 --- a/internal/handler/task_lifecycle.go +++ b/internal/handler/task_lifecycle.go @@ -11,7 +11,10 @@ import ( // ShutdownTasks stops local work before shared MCP clients and databases close. func (h *AgentHandler) ShutdownTasks() { if h != nil && h.tasks != nil { + h.asyncSubmitMu.Lock() h.tasks.Shutdown() + h.asyncSubmitMu.Unlock() + h.asyncWorkers.Wait() if h.logger != nil { for _, task := range h.tasks.GetActiveTasks() { h.logger.Warn("服务关闭时任务仍有未完成的清理", zap.String("runId", task.RunID), zap.String("cleanupError", task.CleanupError)) diff --git a/internal/handler/workflow_integration.go b/internal/handler/workflow_integration.go index d6627772..3c40ea8c 100644 --- a/internal/handler/workflow_integration.go +++ b/internal/handler/workflow_integration.go @@ -60,6 +60,7 @@ func (h *AgentHandler) runRoleWorkflowStreamIfBound( req *ChatRequest, prep *multiAgentPrepared, sendEvent func(eventType, message string, data interface{}), + releaseAdmission ...func(), ) bool { role, ok := h.roleForWorkflow(req) if !ok || prep == nil { @@ -110,6 +111,9 @@ func (h *AgentHandler) runRoleWorkflowStreamIfBound( } else { taskRunID = startedTask.RunID } + for _, release := range releaseAdmission { + release() + } baseCtx = h.tasks.BindProcessScope(baseCtx, conversationID, taskRunID) taskCtx = h.tasks.BindProcessScope(taskCtx, conversationID, taskRunID) taskOwned = true @@ -204,14 +208,13 @@ func (h *AgentHandler) runRoleWorkflowStreamIfBound( return true } -func (h *AgentHandler) runRoleWorkflowJSONIfBound(c *gin.Context, req *ChatRequest, prep *multiAgentPrepared) bool { +func (h *AgentHandler) runRoleWorkflowJSONIfBound(c *gin.Context, req *ChatRequest, prep *multiAgentPrepared, releaseAdmission ...func()) bool { role, ok := h.roleForWorkflow(req) if !ok || prep == nil { return false } conversationID := prep.ConversationID - assistantMessageID := prep.AssistantMessageID userMessage := "" if req != nil { userMessage = req.Message @@ -245,74 +248,14 @@ func (h *AgentHandler) runRoleWorkflowJSONIfBound(c *gin.Context, req *ChatReque } else { taskRunID = startedTask.RunID } + for _, release := range releaseAdmission { + release() + } baseCtx = h.tasks.BindProcessScope(baseCtx, conversationID, taskRunID) taskCtx = h.tasks.BindProcessScope(taskCtx, conversationID, taskRunID) taskOwned = true respond := h.taskFinishingJSONResponder(c, conversationID, taskRunID, func() string { return taskStatus }) - progress := h.createProgressCallback(taskCtx, cancelWithCause, conversationID, assistantMessageID, nil) - result, err := workflowrunner.RunRoleBoundWorkflow(taskCtx, workflowrunner.RunArgs{ - DB: h.db, - Logger: h.logger, - Role: role, - AppCfg: h.config, - Agent: h.agent, - ConversationID: conversationID, - ProjectID: h.conversationProjectID(conversationID), - UserMessage: prep.FinalMessage, - History: prep.History, - RoleTools: prep.RoleTools, - AgentsMarkdownDir: h.agentsMarkdownDir, - SystemPromptExtra: h.agentSessionContextBlock(conversationID), - AssistantMessageID: assistantMessageID, - Progress: progress, - }) - if err != nil { - cause := context.Cause(baseCtx) - if errors.Is(cause, ErrTaskCancelled) { - taskStatus = "cancelled" - cancelMsg := "任务已被用户取消,后续操作已停止。" - if assistantMessageID != "" { - _ = h.appendAssistantMessageNotice(assistantMessageID, cancelMsg) - _ = h.db.AddProcessDetail(assistantMessageID, conversationID, "cancelled", cancelMsg, nil) - } - respond(http.StatusOK, gin.H{ - "status": "cancelled", - "message": cancelMsg, - "conversationId": conversationID, - }) - return true - } - errMsg := "执行角色绑定流程失败: " + err.Error() - taskStatus = "failed" - if assistantMessageID != "" { - _, _ = h.db.Exec("UPDATE messages SET content = ?, updated_at = ? WHERE id = ?", errMsg, time.Now(), assistantMessageID) - } - respond(http.StatusInternalServerError, gin.H{"error": errMsg, "conversationId": conversationID}) - return true - } - decision := h.finalizeWorkflowRunForDelivery(prep.ConversationID, prep.AssistantMessageID, result) - responseText := decision.FinalText - if !decision.Finalizable { - responseText = finalizationBlockedMessage(decision) - taskStatus = decision.Status - } - respond(http.StatusOK, gin.H{ - "response": responseText, - "conversationId": prep.ConversationID, - "assistantMessageId": prep.AssistantMessageID, - "agentMode": "workflow", - "workflowRunId": result.RunID, - "workflowStatus": result.Status, - "awaitingHitl": result.AwaitingHITL, - "finalized": decision.Finalized, - "finalizable": decision.Finalizable, - "status": decision.Status, - "completionReason": decision.CompletionReason, - "evidenceVerified": decision.EvidenceVerified, - "evidenceRefs": decision.EvidenceRefs, - "pendingExecutionIds": decision.PendingExecutionIDs, - "missingChecks": decision.MissingChecks, - }) + h.runWorkflowJSON(taskCtx, baseCtx, cancelWithCause, req, prep, role, &taskStatus, respond) return true }