|
@@ -74,6 +74,9 @@ class RunRequest(BaseModel):
|
|
|
default="",
|
|
default="",
|
|
|
description="Required for mode=edit: name of the sub-agent to invoke (e.g. 'call_physwriter')",
|
|
description="Required for mode=edit: name of the sub-agent to invoke (e.g. 'call_physwriter')",
|
|
|
)
|
|
)
|
|
|
|
|
+ # 会话记忆 P1:本消息归属的对话 thread;缺省则新建。与 continue-run
|
|
|
|
|
+ # 正交(thread=对话语境,continue=产物复用,仅 context.run_id 显式驱动)。
|
|
|
|
|
+ thread_id: str = Field(default="", description="对话线程 id;缺省自动新建")
|
|
|
|
|
|
|
|
class RollbackRequest(BaseModel):
|
|
class RollbackRequest(BaseModel):
|
|
|
target_version: int
|
|
target_version: int
|
|
@@ -552,13 +555,20 @@ async def run_agent(
|
|
|
target = target.setdefault(p, {})
|
|
target = target.setdefault(p, {})
|
|
|
target[parts[-1]] = val
|
|
target[parts[-1]] = val
|
|
|
|
|
|
|
|
|
|
+ # 会话记忆 P1:解析/新建 thread,run 归属之
|
|
|
|
|
+ from agentpaas.engine import thread_memory as _tm
|
|
|
|
|
+ thread_id = _tm.get_or_create_thread(
|
|
|
|
|
+ db, tenant.tenant_id, agent_id, req.thread_id, req.input)
|
|
|
|
|
+
|
|
|
# Create run record
|
|
# Create run record
|
|
|
run_id = gen_id("run_")
|
|
run_id = gen_id("run_")
|
|
|
now = now_utc()
|
|
now = now_utc()
|
|
|
db.execute(
|
|
db.execute(
|
|
|
- "INSERT INTO runs (id, agent_id, agent_version, tenant_id, input, status, idempotency_key, created_at) "
|
|
|
|
|
- "VALUES (?, ?, ?, ?, ?, 'running', ?, ?)",
|
|
|
|
|
- (run_id, agent_id, agent["current_version"], tenant.tenant_id, req.input, idempotency_key, now)
|
|
|
|
|
|
|
+ "INSERT INTO runs (id, agent_id, agent_version, tenant_id, input, status, "
|
|
|
|
|
+ "idempotency_key, thread_id, created_at) "
|
|
|
|
|
+ "VALUES (?, ?, ?, ?, ?, 'running', ?, ?, ?)",
|
|
|
|
|
+ (run_id, agent_id, agent["current_version"], tenant.tenant_id, req.input,
|
|
|
|
|
+ idempotency_key, thread_id, now)
|
|
|
)
|
|
)
|
|
|
db.commit()
|
|
db.commit()
|
|
|
|
|
|
|
@@ -569,17 +579,22 @@ async def run_agent(
|
|
|
source_dir = agent.get("source_dir", "") or ""
|
|
source_dir = agent.get("source_dir", "") or ""
|
|
|
run_dir = agent.get("run_dir", "") or ""
|
|
run_dir = agent.get("run_dir", "") or ""
|
|
|
|
|
|
|
|
|
|
+ # 注入顺序(MEMORY_DESIGN §2.2):本会话前情 → KB 检索 → 用户问题
|
|
|
|
|
+ enriched_input = req.input
|
|
|
|
|
+ preamble = _tm.build_preamble(db, thread_id)
|
|
|
|
|
+
|
|
|
# KB context injection: enrich input with top-K retrieved passages
|
|
# KB context injection: enrich input with top-K retrieved passages
|
|
|
kb_ids = json.loads(agent.get("kb_ids") or "[]")
|
|
kb_ids = json.loads(agent.get("kb_ids") or "[]")
|
|
|
kb_search_mode = agent.get("kb_search_mode") or "bm25"
|
|
kb_search_mode = agent.get("kb_search_mode") or "bm25"
|
|
|
- enriched_input = req.input
|
|
|
|
|
|
|
+ kb_ctx = ""
|
|
|
if kb_ids:
|
|
if kb_ids:
|
|
|
# audit #30: pass tenant_id so KB lookup is scoped, not global.
|
|
# audit #30: pass tenant_id so KB lookup is scoped, not global.
|
|
|
kb_ctx = _build_kb_context(db, kb_ids, req.input,
|
|
kb_ctx = _build_kb_context(db, kb_ids, req.input,
|
|
|
tenant_id=tenant.tenant_id,
|
|
tenant_id=tenant.tenant_id,
|
|
|
search_mode=kb_search_mode)
|
|
search_mode=kb_search_mode)
|
|
|
- if kb_ctx:
|
|
|
|
|
- enriched_input = f"{kb_ctx}\n\n[用户问题]\n{req.input}"
|
|
|
|
|
|
|
+ _segments = [s for s in (preamble, kb_ctx) if s]
|
|
|
|
|
+ if _segments:
|
|
|
|
|
+ enriched_input = "\n\n".join(_segments) + f"\n\n[用户问题]\n{req.input}"
|
|
|
|
|
|
|
|
# Continue-run not currently wired on the sync /run endpoint — only
|
|
# Continue-run not currently wired on the sync /run endpoint — only
|
|
|
# /run/stream supports it. Initialize empty so _execute_agent's
|
|
# /run/stream supports it. Initialize empty so _execute_agent's
|
|
@@ -625,10 +640,15 @@ async def run_agent(
|
|
|
)
|
|
)
|
|
|
db.commit()
|
|
db.commit()
|
|
|
|
|
|
|
|
|
|
+ # 会话记忆:刷新 thread 时间 + 排入滚动压缩(串行后台队列)
|
|
|
|
|
+ _tm.touch_thread(db, thread_id)
|
|
|
|
|
+ _tm.enqueue_compress(thread_id, config, tenant.tenant_id)
|
|
|
|
|
+
|
|
|
resp = {
|
|
resp = {
|
|
|
"run_id": run_id,
|
|
"run_id": run_id,
|
|
|
"status": "completed",
|
|
"status": "completed",
|
|
|
"output": str(result),
|
|
"output": str(result),
|
|
|
|
|
+ "thread_id": thread_id,
|
|
|
"usage": {
|
|
"usage": {
|
|
|
"input_tokens": trace_info.get("input_tokens", 0),
|
|
"input_tokens": trace_info.get("input_tokens", 0),
|
|
|
"output_tokens": trace_info.get("output_tokens", 0),
|
|
"output_tokens": trace_info.get("output_tokens", 0),
|
|
@@ -706,17 +726,26 @@ async def run_agent_stream(
|
|
|
source_dir = agent.get("source_dir", "") or ""
|
|
source_dir = agent.get("source_dir", "") or ""
|
|
|
run_dir = agent.get("run_dir", "") or ""
|
|
run_dir = agent.get("run_dir", "") or ""
|
|
|
|
|
|
|
|
- # KB context injection for streaming run
|
|
|
|
|
|
|
+ # 会话记忆 P1:thread 解析(run 记录在下方流式分支创建,这里先拿 id)
|
|
|
|
|
+ from agentpaas.engine import thread_memory as _tm
|
|
|
|
|
+ thread_id = _tm.get_or_create_thread(
|
|
|
|
|
+ db, tenant.tenant_id, agent_id, req.thread_id, req.input)
|
|
|
|
|
+
|
|
|
|
|
+ # 注入顺序:本会话前情 → KB 检索 → 用户问题
|
|
|
kb_ids = json.loads(agent.get("kb_ids") or "[]")
|
|
kb_ids = json.loads(agent.get("kb_ids") or "[]")
|
|
|
kb_search_mode = agent.get("kb_search_mode") or "bm25"
|
|
kb_search_mode = agent.get("kb_search_mode") or "bm25"
|
|
|
- stream_input = req.input
|
|
|
|
|
|
|
+ preamble = _tm.build_preamble(db, thread_id)
|
|
|
|
|
+ kb_ctx = ""
|
|
|
if kb_ids:
|
|
if kb_ids:
|
|
|
# audit #30: pass tenant_id so KB lookup is scoped, not global.
|
|
# audit #30: pass tenant_id so KB lookup is scoped, not global.
|
|
|
kb_ctx = _build_kb_context(db, kb_ids, req.input,
|
|
kb_ctx = _build_kb_context(db, kb_ids, req.input,
|
|
|
tenant_id=tenant.tenant_id,
|
|
tenant_id=tenant.tenant_id,
|
|
|
search_mode=kb_search_mode)
|
|
search_mode=kb_search_mode)
|
|
|
- if kb_ctx:
|
|
|
|
|
- stream_input = f"{kb_ctx}\n\n[用户问题]\n{req.input}"
|
|
|
|
|
|
|
+ _segments = [s for s in (preamble, kb_ctx) if s]
|
|
|
|
|
+ if _segments:
|
|
|
|
|
+ stream_input = "\n\n".join(_segments) + f"\n\n[用户问题]\n{req.input}"
|
|
|
|
|
+ else:
|
|
|
|
|
+ stream_input = req.input
|
|
|
|
|
|
|
|
# Default empty — the continue-run injection block (when present) sets
|
|
# Default empty — the continue-run injection block (when present) sets
|
|
|
# this to the previous run's workspace. Initialized here so the inner
|
|
# this to the previous run's workspace. Initialized here so the inner
|
|
@@ -854,9 +883,10 @@ async def run_agent_stream(
|
|
|
run_id = gen_id("run_")
|
|
run_id = gen_id("run_")
|
|
|
now = now_utc()
|
|
now = now_utc()
|
|
|
db.execute(
|
|
db.execute(
|
|
|
- "INSERT INTO runs (id, agent_id, agent_version, tenant_id, input, status, created_at) "
|
|
|
|
|
- "VALUES (?, ?, ?, ?, ?, 'running', ?)",
|
|
|
|
|
- (run_id, agent_id, agent["current_version"], tenant.tenant_id, req.input, now)
|
|
|
|
|
|
|
+ "INSERT INTO runs (id, agent_id, agent_version, tenant_id, input, status, "
|
|
|
|
|
+ "thread_id, created_at) VALUES (?, ?, ?, ?, ?, 'running', ?, ?)",
|
|
|
|
|
+ (run_id, agent_id, agent["current_version"], tenant.tenant_id, req.input,
|
|
|
|
|
+ thread_id, now)
|
|
|
)
|
|
)
|
|
|
db.commit()
|
|
db.commit()
|
|
|
|
|
|
|
@@ -873,7 +903,7 @@ async def run_agent_stream(
|
|
|
# /runs/<id>/cancel without having to wait for the final 'done' event.
|
|
# /runs/<id>/cancel without having to wait for the final 'done' event.
|
|
|
# Without this the user might click Stop before any other event lands
|
|
# Without this the user might click Stop before any other event lands
|
|
|
# and the frontend wouldn't know which run to cancel.
|
|
# and the frontend wouldn't know which run to cancel.
|
|
|
- yield f"event: started\ndata: {json.dumps({'run_id': run_id}, ensure_ascii=False)}\n\n"
|
|
|
|
|
|
|
+ yield f"event: started\ndata: {json.dumps({'run_id': run_id, 'thread_id': thread_id}, ensure_ascii=False)}\n\n"
|
|
|
|
|
|
|
|
def _persist_subprocess_pid(pid):
|
|
def _persist_subprocess_pid(pid):
|
|
|
"""Hook fired by cancel.bind_proc/unbind_proc — write the live
|
|
"""Hook fired by cancel.bind_proc/unbind_proc — write the live
|
|
@@ -1035,8 +1065,15 @@ async def run_agent_stream(
|
|
|
trace_json, now_utc(), run_id),
|
|
trace_json, now_utc(), run_id),
|
|
|
)
|
|
)
|
|
|
db.commit()
|
|
db.commit()
|
|
|
|
|
+ # 会话记忆:刷新 thread + 排入滚动压缩
|
|
|
|
|
+ try:
|
|
|
|
|
+ _tm.touch_thread(db, thread_id)
|
|
|
|
|
+ _tm.enqueue_compress(thread_id, config, tenant.tenant_id)
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ pass
|
|
|
event_queue.put({"event": "done", "data": {
|
|
event_queue.put({"event": "done", "data": {
|
|
|
"run_id": run_id,
|
|
"run_id": run_id,
|
|
|
|
|
+ "thread_id": thread_id,
|
|
|
"status": final_status, "output": final,
|
|
"status": final_status, "output": final,
|
|
|
"steps": trace_info.get("steps", 0),
|
|
"steps": trace_info.get("steps", 0),
|
|
|
"total_tokens": trace_info.get("total_tokens", 0),
|
|
"total_tokens": trace_info.get("total_tokens", 0),
|
|
@@ -1297,6 +1334,63 @@ async def list_runs(
|
|
|
return {"runs": runs}
|
|
return {"runs": runs}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
+# ── 会话记忆 thread API ──
|
|
|
|
|
+
|
|
|
|
|
+@router.get("/{agent_id}/threads")
|
|
|
|
|
+async def list_threads(
|
|
|
|
|
+ agent_id: str,
|
|
|
|
|
+ limit: int = 20,
|
|
|
|
|
+ tenant: TenantContext = Depends(get_tenant),
|
|
|
|
|
+ db: Database = Depends(get_database),
|
|
|
|
|
+):
|
|
|
|
|
+ """该智能体最近的对话线程(工作台「历史会话」用)。"""
|
|
|
|
|
+ rows = db.fetchall(
|
|
|
|
|
+ "SELECT t.id, t.title, t.status, t.updated_at, "
|
|
|
|
|
+ "(SELECT COUNT(*) FROM runs r WHERE r.thread_id = t.id) AS run_count "
|
|
|
|
|
+ "FROM threads t WHERE t.agent_id = ? AND t.tenant_id = ? AND t.status = 'active' "
|
|
|
|
|
+ "ORDER BY t.updated_at DESC LIMIT ?",
|
|
|
|
|
+ (agent_id, tenant.tenant_id, limit))
|
|
|
|
|
+ return {"threads": rows}
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+@router.get("/{agent_id}/threads/{thread_id}/runs")
|
|
|
|
|
+async def thread_runs(
|
|
|
|
|
+ agent_id: str,
|
|
|
|
|
+ thread_id: str,
|
|
|
|
|
+ tenant: TenantContext = Depends(get_tenant),
|
|
|
|
|
+ db: Database = Depends(get_database),
|
|
|
|
|
+):
|
|
|
|
|
+ """thread 内的消息流(恢复历史会话气泡)。"""
|
|
|
|
|
+ th = db.fetchone(
|
|
|
|
|
+ "SELECT id FROM threads WHERE id = ? AND tenant_id = ? AND agent_id = ?",
|
|
|
|
|
+ (thread_id, tenant.tenant_id, agent_id))
|
|
|
|
|
+ if not th:
|
|
|
|
|
+ raise HTTPException(404, {"error": {"code": "THREAD_NOT_FOUND"}})
|
|
|
|
|
+ runs = db.fetchall(
|
|
|
|
|
+ "SELECT id, input, output, status, workspace_path, created_at "
|
|
|
|
|
+ "FROM runs WHERE thread_id = ? ORDER BY created_at ASC",
|
|
|
|
|
+ (thread_id,))
|
|
|
|
|
+ return {"thread_id": thread_id, "runs": runs}
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+@router.post("/{agent_id}/threads/{thread_id}/archive")
|
|
|
|
|
+async def archive_thread(
|
|
|
|
|
+ agent_id: str,
|
|
|
|
|
+ thread_id: str,
|
|
|
|
|
+ tenant: TenantContext = Depends(get_tenant),
|
|
|
|
|
+ db: Database = Depends(get_database),
|
|
|
|
|
+):
|
|
|
|
|
+ """归档对话线程(不删,列表隐藏)。"""
|
|
|
|
|
+ n = db.execute(
|
|
|
|
|
+ "UPDATE threads SET status = 'archived', updated_at = ? "
|
|
|
|
|
+ "WHERE id = ? AND tenant_id = ? AND agent_id = ?",
|
|
|
|
|
+ (now_utc(), thread_id, tenant.tenant_id, agent_id)).rowcount
|
|
|
|
|
+ db.commit()
|
|
|
|
|
+ if not n:
|
|
|
|
|
+ raise HTTPException(404, {"error": {"code": "THREAD_NOT_FOUND"}})
|
|
|
|
|
+ return {"ok": True}
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
# ── Workspace File API ──
|
|
# ── Workspace File API ──
|
|
|
|
|
|
|
|
@router.get("/{agent_id}/runs/{run_id}/workspace")
|
|
@router.get("/{agent_id}/runs/{run_id}/workspace")
|