Files
webup-cloud/backend/src/main/java/run/webup/platform/TaskService.java
T
WebUp Cloud 6d55806b4f
Verify control plane / verify (push) Canceled after 0s
Verify control plane / verify (pull_request) Canceled after 0s
Verify the declared Node entry before completing Agent tasks
2026-11-08 23:20:47 +08:00

549 lines
21 KiB
Java

package run.webup.platform;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.*;
import java.util.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class TaskService {
private final JdbcTemplate db;
private final WalletService wallets;
private final ObjectMapper json;
private final QueueService queue;
public TaskService(
JdbcTemplate db, WalletService wallets, ObjectMapper json, QueueService queue) {
this.db = db;
this.wallets = wallets;
this.json = json;
this.queue = queue;
}
String encode(Object value) {
try {
return json.writeValueAsString(value);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public Map<String, Object> find(UUID id, UUID user) {
var rows =
db.queryForList(
"SELECT t.*,r.amount AS budget,r.spent FROM ai_tasks t JOIN wallet_reservations r ON"
+ " r.id=t.reservation_id WHERE t.id=? AND t.user_id=?",
id,
user);
if (rows.isEmpty()) throw new ApiError.Failure(404, "任务不存在");
var row = rows.getFirst();
row.remove("lease_token");
return row;
}
@Transactional
public Map<String, Object> create(
UUID user, UUID project, UUID model, String prompt, BigDecimal budget, String key) {
var own =
db.queryForList(
"SELECT id,status FROM projects WHERE id=? AND owner_id=? FOR UPDATE", project, user);
if (own.isEmpty()) throw new ApiError.Failure(404, "项目不存在");
var prior =
db.queryForList(
"SELECT id,project_id,model_id,prompt,reservation_id FROM ai_tasks WHERE user_id=? AND"
+ " idempotency_key=?",
user,
key);
if (!prior.isEmpty()) {
var p = prior.getFirst();
BigDecimal old =
db.queryForObject(
"SELECT amount FROM wallet_reservations WHERE id=?",
BigDecimal.class,
p.get("reservation_id"));
if (!project.toString().equals(p.get("project_id").toString())
|| !model.toString().equals(p.get("model_id").toString())
|| !prompt.equals(p.get("prompt"))
|| old.compareTo(budget) != 0) throw new ApiError.Failure(409, "幂等键已用于其他任务");
return find(UUID.fromString(p.get("id").toString()), user);
}
if (!"DRAFT".equals(own.getFirst().get("status"))) throw new ApiError.Failure(409, "请先使用未归档项目");
if (db.queryForObject(
"SELECT COUNT(*) FROM ai_tasks WHERE project_id=? AND status IN"
+ " ('QUEUED','RUNNING','PAUSED','REVIEW_REQUIRED')",
Integer.class,
project)
> 0) throw new ApiError.Failure(409, "该项目已有活动任务,请先完成或取消");
var models =
db.queryForList(
"SELECT m.*,p.api_type,p.base_url,p.auth_mode,v.id AS price_id FROM ai_models m JOIN"
+ " ai_providers p ON p.id=m.provider_id JOIN ai_model_price_versions v ON"
+ " v.id=m.current_price_version WHERE m.id=? AND m.enabled=TRUE AND"
+ " p.enabled=TRUE",
model);
if (models.isEmpty()) throw new ApiError.Failure(400, "模型未开放或供应商已禁用");
var config = models.getFirst();
if (!Boolean.TRUE.equals(config.get("tools_enabled")))
throw new ApiError.Failure(400, "此模型未声明工具调用能力,不能执行 Agent 任务");
UUID id = UUID.randomUUID(), reservation = wallets.reserve(user, budget, "task:" + id);
db.update(
"INSERT INTO"
+ " ai_tasks(id,project_id,user_id,model_id,price_version_id,reservation_id,prompt,model_config,status,idempotency_key)"
+ " VALUES (?,?,?,?,?,?,?,?,'QUEUED',?)",
id,
project,
user,
model,
config.get("price_id"),
reservation,
prompt,
encode(config),
key);
var last =
db.queryForList(
"SELECT id FROM ai_tasks WHERE project_id=? AND status='COMPLETED' ORDER BY created_at"
+ " DESC LIMIT 1",
project);
int seq = 0;
if (!last.isEmpty())
for (String message :
db.queryForList(
"SELECT payload FROM ai_task_messages WHERE task_id=? ORDER BY sequence_no",
String.class,
last.getFirst().get("id")))
db.update(
"INSERT INTO ai_task_messages(id,task_id,sequence_no,payload) VALUES (?,?,?,?)",
UUID.randomUUID(),
id,
seq++,
message);
else {
String requirements =
db.queryForObject("SELECT requirements FROM projects WHERE id=?", String.class, project);
message(
id,
Map.of(
"role",
"system",
"content",
"You are a full-stack development agent. Work only in /workspace through tools."
+ " Preserve existing project files and data. Build and test changes."
+ " Never claim success unless commands and checks confirm it."
+ " Split large files into small tool calls; append chunks with run_command when"
+ " needed. A tool call must fit the model output limit. Actually write source"
+ " files rather than only describing them."
+ " Do not access credentials, private networks, or other projects."
+ " Requirements: "
+ requirements));
seq = 1;
}
db.update(
"INSERT INTO ai_task_messages(id,task_id,sequence_no,payload) VALUES (?,?,?,?)",
UUID.randomUUID(),
id,
seq,
encode(Map.of("role", "user", "content", prompt)));
event(id, "QUEUED", "任务已入队,预算已预留;等待 Worker 和隔离环境");
return find(id, user);
}
public void event(UUID task, String type, String detail) {
db.update(
"INSERT INTO ai_task_steps(id,task_id,event,detail) VALUES (?,?,?,?)",
UUID.randomUUID(),
task,
type,
detail);
}
private Map<String, Object> locked(UUID id, String lease) {
var row = db.queryForMap("SELECT * FROM ai_tasks WHERE id=? FOR UPDATE", id);
if (!"RUNNING".equals(row.get("status")) || !Objects.equals(lease, row.get("lease_token")))
throw new ApiError.Failure(409, "任务租约已失效");
return row;
}
@Transactional
public Map<String, Object> claim() {
var queueConfig = queue.lock();
// Expired calls are ambiguous: never replay them automatically or silently release their
// budget.
for (var row :
db.queryForList(
"SELECT id FROM ai_tasks WHERE status='RUNNING' AND"
+ " lease_expires_at<CURRENT_TIMESTAMP")) {
if (db.update(
"UPDATE ai_tasks SET status='REVIEW_REQUIRED',error='Worker"
+ " 租约过期,需核对上游费用及工具状态',updated_at=CURRENT_TIMESTAMP WHERE id=? AND"
+ " status='RUNNING' AND lease_expires_at<CURRENT_TIMESTAMP",
row.get("id"))
== 1) event(UUID.fromString(row.get("id").toString()), "REVIEW_REQUIRED", "租约过期,未自动重放请求");
}
if (queue.occupied() >= ((Number) queueConfig.get("max_concurrent")).longValue()) return null;
for (var row :
db.queryForList(
"SELECT id FROM ai_tasks WHERE status='QUEUED' ORDER BY "
+ QueueService.ORDER
+ " LIMIT 10")) {
String lease = UUID.randomUUID().toString();
UUID id = UUID.fromString(row.get("id").toString());
if (db.update(
"UPDATE ai_tasks SET"
+ " status='RUNNING',run_next=FALSE,lease_token=?,lease_expires_at=?,attempt=attempt+1,updated_at=CURRENT_TIMESTAMP"
+ " WHERE id=? AND status='QUEUED'",
lease,
Timestamp.from(Instant.now().plusSeconds(300)),
id)
== 1) {
event(id, "RUNNING", "Worker 已领取任务");
return db.queryForMap("SELECT * FROM ai_tasks WHERE id=?", id);
}
}
return null;
}
@Transactional
public String beginExecution(UUID id, String lease) {
var task = locked(id, lease);
String action = task.get("requested_action").toString();
if (!action.isBlank()) return action;
db.update(
"UPDATE ai_tasks SET started_at=COALESCE(started_at,CURRENT_TIMESTAMP) WHERE id=?", id);
queue.consume(id);
return "";
}
@Transactional
public void heartbeat(UUID id, String lease) {
locked(id, lease);
db.update(
"UPDATE ai_tasks SET lease_expires_at=?,updated_at=CURRENT_TIMESTAMP WHERE id=?",
Timestamp.from(Instant.now().plusSeconds(300)),
id);
}
public List<JsonNode> history(UUID id) {
return db
.queryForList(
"SELECT payload FROM ai_task_messages WHERE task_id=? ORDER BY sequence_no",
String.class,
id)
.stream()
.map(
s -> {
try {
return json.readTree(s);
} catch (Exception e) {
throw new IllegalStateException(e);
}
})
.toList();
}
record AgentHistory(List<JsonNode> messages, String summary, int through, int last) {
boolean canRotate() {
return through < 0 ? messages.size() > 2 : last > through;
}
}
AgentHistory agentHistory(UUID id) {
var saved =
db.queryForList(
"SELECT through_sequence,summary FROM ai_task_context_checkpoints WHERE task_id=?", id);
int through =
saved.isEmpty() ? -1 : ((Number) saved.getFirst().get("through_sequence")).intValue();
String summary = saved.isEmpty() ? "" : saved.getFirst().get("summary").toString();
var rows =
db.queryForList(
"SELECT sequence_no,payload FROM ai_task_messages WHERE task_id=? AND"
+ " (sequence_no=0 OR sequence_no>?) ORDER BY sequence_no",
id,
through);
var messages = new ArrayList<JsonNode>(rows.size());
for (var row : rows) {
try {
messages.add(json.readTree(row.get("payload").toString()));
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
throw new IllegalStateException(e);
}
}
int last = rows.isEmpty() ? through : ((Number) rows.getLast().get("sequence_no")).intValue();
return new AgentHistory(messages, summary, through, last);
}
@Transactional
public void checkpoint(UUID id, String lease, AgentHistory history, String summary) {
locked(id, lease);
if (!history.canRotate()) return;
if (history.through() < 0) {
db.update(
"INSERT INTO ai_task_context_checkpoints(task_id,through_sequence,summary) VALUES"
+ " (?,?,?)",
id,
history.last(),
summary);
} else {
int updated =
db.update(
"UPDATE ai_task_context_checkpoints SET through_sequence=?,summary=?"
+ " WHERE task_id=? AND through_sequence=?",
history.last(),
summary,
id,
history.through());
if (updated != 1) throw new ApiError.Failure(409, "任务上下文交接记录已更新");
}
event(id, "CONTEXT_COMPACTED", "压缩上下文中");
}
public Map<String, Object> config(UUID id) {
return db.queryForMap("SELECT * FROM ai_tasks WHERE id=?", id);
}
public Map<String, Object> price(UUID id) {
return db.queryForMap("SELECT * FROM ai_model_price_versions WHERE id=?", id);
}
public BigDecimal remaining(UUID reservation) {
return db.queryForObject(
"SELECT amount-spent FROM wallet_reservations WHERE id=?", BigDecimal.class, reservation);
}
public Map<String, Object> provider(UUID id) {
var rows = db.queryForList("SELECT * FROM ai_providers WHERE id=? AND enabled=TRUE", id);
if (rows.isEmpty()) throw new ApiError.Failure(503, "供应商已停用");
return rows.getFirst();
}
private void message(UUID id, Object payload) {
Integer seq =
db.queryForObject(
"SELECT COALESCE(MAX(sequence_no),-1)+1 FROM ai_task_messages WHERE task_id=?",
Integer.class,
id);
db.update(
"INSERT INTO ai_task_messages(id,task_id,sequence_no,payload) VALUES (?,?,?,?)",
UUID.randomUUID(),
id,
seq,
encode(payload));
}
@Transactional
public void response(UUID id, String lease, ModelGateway.Result result) {
var t = locked(id, lease);
UUID priceId = UUID.fromString(t.get("price_version_id").toString()),
reservation = UUID.fromString(t.get("reservation_id").toString());
var u = result.usage();
String requestId = id + ":" + t.get("step_count") + ":" + result.requestId();
if (requestId.length() > 200) requestId = SecurityConfig.hash(requestId);
BigDecimal amount = ModelGateway.cost(u, price(priceId));
db.update(
"INSERT INTO"
+ " ai_usage_records(id,task_id,price_version_id,request_id,input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,amount,billing_status,raw_usage)"
+ " VALUES (?,?,?,?,?,?,?,?,?,?,?)",
UUID.randomUUID(),
id,
priceId,
requestId,
u.input(),
u.output(),
u.cacheRead(),
u.cacheWrite(),
amount,
u.exact() ? "EXACT" : "REVIEW_REQUIRED",
encode(u.raw()));
if (!u.exact()) {
db.update(
"UPDATE ai_tasks SET status='REVIEW_REQUIRED',error='供应商缺少完整 usage,未执行估算扣费' WHERE id=?",
id);
event(id, "REVIEW_REQUIRED", "保留预留金额,等待人工核对 usage");
return;
}
wallets.charge(reservation, amount, "usage:" + requestId);
message(id, result.assistant());
db.update("UPDATE ai_tasks SET step_count=step_count+1 WHERE id=?", id);
event(
id,
"MODEL_RESPONSE",
"输入 " + u.input() + ",输出 " + u.output() + ",缓存读 " + u.cacheRead() + ",费用 CNY " + amount);
}
@Transactional
public boolean tool(UUID id, String lease, ModelGateway.Call call, String output)
throws JsonProcessingException {
return tool(id, lease, call, output, false);
}
@Transactional
public boolean tool(
UUID id, String lease, ModelGateway.Call call, String output, boolean trackChanges)
throws JsonProcessingException {
locked(id, lease);
var result = json.readTree(output);
if (trackChanges) {
var report = result instanceof ObjectNode object ? object.remove("fileChanges") : null;
recordFileChanges(id, report);
output = result.toString();
}
boolean failed =
result.hasNonNull("error")
|| result.path("timedOut").asBoolean(false)
|| result.path("exitCode").asInt(0) != 0;
var payload =
json.createObjectNode()
.put("role", "tool")
.put("tool_call_id", call.id())
.put("name", call.name())
.put("content", output);
if (failed) payload.put("is_error", true);
message(id, payload);
event(id, "TOOL_RESULT", call.name() + ": " + output);
return failed;
}
private void recordFileChanges(UUID task, JsonNode report) {
if (report == null || !report.path("files").isArray() || report.path("files").size() > 120) {
db.update("UPDATE ai_tasks SET file_changes_partial=TRUE WHERE id=?", task);
return;
}
boolean partial = !report.path("complete").asBoolean(false);
for (var file : report.path("files")) {
String path = file.path("path").asText(), status = file.path("status").asText();
int added = file.path("added").asInt(-1), removed = file.path("removed").asInt(-1);
if (path.isEmpty()
|| path.indexOf(0) >= 0
|| path.getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 1000
|| !Set.of("ADDED", "MODIFIED", "DELETED").contains(status)
|| added < 0
|| removed < 0) {
partial = true;
continue;
}
boolean binary = file.path("binary").asBoolean(false);
int updated =
db.update(
"UPDATE ai_task_file_changes SET last_status=?,added_lines=added_lines+?,"
+ " removed_lines=removed_lines+?,binary_change=(binary_change OR ?)"
+ " WHERE task_id=? AND file_path=?",
status,
added,
removed,
binary,
task,
path);
if (updated == 0) {
db.update(
"INSERT INTO ai_task_file_changes"
+ " (task_id,file_path,last_status,added_lines,removed_lines,binary_change)"
+ " VALUES (?,?,?,?,?,?)",
task,
path,
status,
added,
removed,
binary);
}
}
db.update(
"UPDATE ai_tasks SET file_change_checks=file_change_checks+1,"
+ " file_changes_partial=(file_changes_partial OR ?) WHERE id=?",
partial,
task);
}
@Transactional
public void markFileChangesPartial(UUID task, String lease) {
locked(task, lease);
recordFileChanges(task, null);
}
@Transactional
public void requireSource(UUID id, String lease, String missingStart) {
locked(id, lease);
if (!missingStart.isEmpty()) {
message(
id,
Map.of(
"role",
"user",
"content",
"The workspace is missing the Node startup file declared in package.json: "
+ missingStart
+ ". Use the tools to create the entry point or correct the start script to match"
+ " the project, then verify that the app can start before finishing."));
event(id, "SOURCE_REQUIRED", "缺少 package.json 指定的启动文件 " + missingStart + ",已要求 AI 补齐");
return;
}
message(
id,
Map.of(
"role",
"user",
"content",
"The actual project workspace contains no non-empty source files. The website has NOT"
+ " been created. Use write_file or run_command to create the real source files,"
+ " then build and test them. Do not finish with only an explanation."));
event(id, "SOURCE_REQUIRED", "工作区没有实际源码,已要求 AI 继续写入文件;未标记开发完成");
}
@Transactional
public void finish(UUID id, String lease, String status, String error, boolean release) {
var t = locked(id, lease);
if ("CANCEL".equals(t.get("requested_action"))
&& !Set.of("CANCELLED", "REVIEW_REQUIRED").contains(status)) {
status = "CANCELLED";
error = "用户已停止任务,已结算产生的费用";
release = true;
}
db.update(
"UPDATE ai_tasks SET"
+ " status=?,error=?,requested_action='',lease_token=NULL,lease_expires_at=NULL,updated_at=CURRENT_TIMESTAMP"
+ " WHERE id=?",
status,
error,
id);
if (release) {
wallets.release(UUID.fromString(t.get("reservation_id").toString()));
queue.refundUnused(id);
}
event(id, status, error);
}
@Transactional
public Map<String, Object> action(UUID id, UUID user, String action) {
find(id, user);
var t = db.queryForMap("SELECT * FROM ai_tasks WHERE id=? FOR UPDATE", id);
String status = t.get("status").toString();
boolean stopping = status.equals("RUNNING") && "CANCEL".equals(t.get("requested_action"));
if (action.equals("cancel") && (stopping || status.equals("CANCELLED"))) return find(id, user);
if (stopping) throw new ApiError.Failure(409, "任务正在停止");
if (action.equals("resume") && status.equals("PAUSED")) {
db.update("UPDATE ai_tasks SET status='QUEUED',error='',requested_action='' WHERE id=?", id);
event(id, "QUEUED", "用户继续任务");
} else if (action.equals("pause") && (status.equals("QUEUED") || status.equals("RUNNING"))) {
if (status.equals("QUEUED")) db.update("UPDATE ai_tasks SET status='PAUSED' WHERE id=?", id);
else db.update("UPDATE ai_tasks SET requested_action='PAUSE' WHERE id=?", id);
event(id, "PAUSE_REQUESTED", "当前步骤结束后暂停");
} else if (action.equals("cancel") && (status.equals("QUEUED") || status.equals("PAUSED"))) {
db.update(
"UPDATE ai_tasks SET status='CANCELLED',requested_action='',updated_at=CURRENT_TIMESTAMP"
+ " WHERE id=?",
id);
wallets.release(UUID.fromString(t.get("reservation_id").toString()));
queue.refundUnused(id);
event(id, "CANCELLED", "用户取消,未使用预留已释放");
} else if (action.equals("cancel") && status.equals("RUNNING")) {
db.update("UPDATE ai_tasks SET requested_action='CANCEL' WHERE id=?", id);
event(id, "CANCEL_REQUESTED", "当前调用结算后取消");
} else throw new ApiError.Failure(409, "当前状态不允许该操作;待核对任务需管理员处理");
return find(id, user);
}
}