This commit is contained in:
commit
db82325ed7
216 files changed
+33718
No files matched your search
@@ -0,0 +1,387 @@
|
||||
package run.webup.platform;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
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();
|
||||
}
|
||||
|
||||
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 void tool(UUID id, String lease, ModelGateway.Call call, String output) {
|
||||
locked(id, lease);
|
||||
message(
|
||||
id,
|
||||
Map.of("role", "tool", "tool_call_id", call.id(), "name", call.name(), "content", output));
|
||||
event(id, "TOOL_RESULT", call.name() + ": " + output);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void requireSource(UUID id, String lease) {
|
||||
locked(id, lease);
|
||||
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);
|
||||
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();
|
||||
if (action.equals("resume") && status.equals("PAUSED")) {
|
||||
db.update(
|
||||
"UPDATE ai_tasks SET status='QUEUED',error='',requested_action='',max_steps=CASE WHEN"
|
||||
+ " max_steps<=step_count THEN step_count+30 ELSE max_steps END 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' 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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user