public String run()

in spring-ai-alibaba-jmanus/src/main/java/com/alibaba/cloud/ai/example/manus/agent/BaseAgent.java [171:246]


	public String run(Map<String, Object> data) {
		currentStep = 0;
		if (state != AgentState.IN_PROGRESS) {
			throw new IllegalStateException("Cannot run agent from state: " + state);
		}

		setData(data);

		// Create agent execution record
		AgentExecutionRecord agentRecord = new AgentExecutionRecord(getPlanId(), getName(), getDescription());
		agentRecord.setMaxSteps(maxSteps);
		agentRecord.setStatus(state.toString());
		// Record execution in recorder if we have a plan ID
		if (planId != null && planExecutionRecorder != null) {
			planExecutionRecorder.recordAgentExecution(planId, agentRecord);
		}
		List<String> results = new ArrayList<>();
		try {
			state = AgentState.IN_PROGRESS;
			agentRecord.setStatus(state.toString());

			while (currentStep < maxSteps && !state.equals(AgentState.COMPLETED)) {
				currentStep++;
				log.info("Executing round {}/{}", currentStep, maxSteps);

				AgentExecResult stepResult = step();

				if (isStuck()) {
					handleStuckState(agentRecord);
				}
				else {
					// 更新全局状态以保持一致性
					log.info("Agent state: {}", stepResult.getState());
					state = stepResult.getState();
				}

				results.add("Round " + currentStep + ": " + stepResult.getResult());

				// Update agent record after each step
				agentRecord.setCurrentStep(currentStep);
			}

			if (currentStep >= maxSteps) {
				results.add("Terminated: Reached max rounds (" + maxSteps + ")");
			}

			// Set final state in record
			agentRecord.setEndTime(LocalDateTime.now());
			agentRecord.setStatus(state.toString());
			agentRecord.setCompleted(state.equals(AgentState.COMPLETED));

			// Calculate execution time in seconds
			long executionTimeSeconds = java.time.Duration.between(agentRecord.getStartTime(), agentRecord.getEndTime())
				.getSeconds();
			String status = agentRecord.isCompleted() ? "成功" : (agentRecord.isStuck() ? "执行卡住" : "未完成");
			agentRecord.setResult(String.format("执行%s [耗时%d秒] [消耗步骤%d] ", status, executionTimeSeconds, currentStep));

		}
		catch (Exception e) {
			log.error("Agent execution failed", e);
			// 记录异常信息到agentRecord
			agentRecord.setErrorMessage(e.getMessage());
			agentRecord.setCompleted(false);
			agentRecord.setEndTime(LocalDateTime.now());
			agentRecord.setResult(String.format("执行失败 [错误: %s]", e.getMessage()));
			results.add("Execution failed: " + e.getMessage());
			throw e; // 重新抛出异常,让上层调用者知道发生了错误
		}
		finally {
			state = AgentState.COMPLETED; // Reset state after execution

			agentRecord.setStatus(state.toString());
			llmService.removeAgentChatClient(planId);
		}
		return results.isEmpty() ? "" : results.get(results.size() - 1);
	}