agentpaas_run.ts 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  1. /// <reference path="../env.d.ts" />
  2. import { tool } from "@opencode-ai/plugin"
  3. import { pendingRequest, clearPendingRequest, recoverRequest, cancelAndObserve } from "../lib/recovery"
  4. import {
  5. loadAgentPaaSConfig,
  6. resolveAgentID,
  7. digest,
  8. canonicalJSON,
  9. requestContext,
  10. loadConversationState,
  11. saveConversationState,
  12. formatRunResult,
  13. scientificLabel,
  14. requestJSON,
  15. verifyAgent,
  16. trackRun,
  17. } from "../lib/agentpaas"
  18. type SSEEvent = { event: string; data: unknown }
  19. type ProgressStatus = "completed" | "running" | "pending" | "failed" | "paused" | "cancelled" | "skipped" | "unknown"
  20. type ProgressMilestone = {
  21. id: string
  22. label: string
  23. status: ProgressStatus
  24. done?: Set<string>
  25. total?: number
  26. detail?: string
  27. }
  28. type ProgressStage = {
  29. id: string
  30. label: string
  31. status: ProgressStatus
  32. milestones: ProgressMilestone[]
  33. }
  34. export default tool({
  35. description: `把任务转发给 PaaS 目录中的智能体执行,返回真实运行状态、答案和产物。
  36. 参数说明:
  37. - agent_id / agent_name:至少填写一个;优先使用目录返回的 ID,同名时必须使用 ID
  38. - input:要执行的用户任务指令
  39. - input_file_ids:已通过 agentpaas_upload 上传的文件 ID,不接受客户端路径
  40. - mode:iterate(多轮迭代,默认)/ chat(单轮)/ edit(单轮并指定目标子智能体)
  41. - target_subagent:mode=edit 时的目标子智能体 ID
  42. - work_dir:可选的服务端可见工作目录;留空时由 AgentPaaS 创建隔离 workspace
  43. - conversation:continue(默认,沿用远端 thread 并引用上一轮成果)/ new(新课题)
  44. - thread_id:可选的远端会话线程 ID;显式值优先于自动映射
  45. - parameters:额外参数,原样传给远端智能体
  46. 适用于 PaaS 目录中的本地或远端智能体,包括科研、数据分析、软件工程和问答等已注册能力。
  47. 查询、继续观察或控制已有任务请用 agentpaas_task,不要再次提交。`,
  48. args: {
  49. input: tool.schema.string().describe("用户任务指令"),
  50. background: tool.schema
  51. .boolean()
  52. .optional()
  53. .describe("长任务设为 true:受理并保存编号后返回,在服务端继续执行;用 task/watch 查看,用 cancel 停止"),
  54. agent_name: tool.schema.string().optional().describe("远端 AgentPaaS 智能体名称;与 agent_id 至少填写一个"),
  55. agent_id: tool.schema.string().optional().describe("目录返回的稳定 ID;同名智能体用 ID 选择"),
  56. input_file_ids: tool.schema
  57. .array(tool.schema.string())
  58. .optional()
  59. .describe("agentpaas_upload 返回的 file_id;不接受客户端路径"),
  60. mode: tool.schema.enum(["iterate", "chat", "edit"]).default("iterate"),
  61. target_subagent: tool.schema.string().optional().describe("mode=edit 时的目标子智能 ID"),
  62. work_dir: tool.schema.string().optional().describe("服务端可见工作目录;通常留空,由 AgentPaaS 创建"),
  63. thread_id: tool.schema.string().optional().describe("远端会话线程 ID;通常留空,由 OpenCode session 自动维护"),
  64. conversation: tool.schema.enum(["continue", "new"]).default("continue").describe("复用当前对话或开始新课题"),
  65. question_id: tool.schema.number().int().min(1).max(125).optional().describe("Science 125 科学问题编号"),
  66. feedback_kind: tool.schema.enum(["human", "program_check", "execution_result", "evidence"]).optional(),
  67. input_artifact_ids: tool.schema
  68. .array(tool.schema.string())
  69. .optional()
  70. .describe("续跑时选取的上一轮产物 ID;省略时复用上一轮已登记产物"),
  71. idempotency_key: tool.schema.string().optional().describe("同一请求重试时复用;不同请求必须使用不同键"),
  72. max_cost_usd: tool.schema
  73. .number()
  74. .positive()
  75. .finite()
  76. .optional()
  77. .describe("仅支持预检查声明可用的 CEK 单智能体;按服务端计量在调用结算后检查,非供应商硬限额"),
  78. parameters: tool.schema
  79. .record(tool.schema.string(), tool.schema.any())
  80. .optional()
  81. .describe("额外参数,原样传给远端智能体"),
  82. },
  83. async execute(args, context) {
  84. const config = await loadAgentPaaSConfig()
  85. if (args.mode === "edit" && !args.target_subagent) {
  86. throw new Error("mode=edit 时必须提供 target_subagent")
  87. }
  88. const agentID = await resolveAgentID(config, args.agent_id || args.agent_name || "", context.abort)
  89. const agentName = args.agent_name || agentID
  90. context.metadata({ title: `PaaS ${agentName} · 执行前检查`, metadata: { agent_id: agentID, status: "checking" } })
  91. const preflight = await verifyAgent(config, agentID, context.abort, undefined, true)
  92. if (preflight.blocked) throw new Error(preflight.summary)
  93. if (args.max_cost_usd !== undefined && preflight.client_budget_supported !== true)
  94. throw new Error("此智能体未声明支持客户端费用预算,任务未提交;不能承诺限额会生效。")
  95. const conversation = args.conversation ?? "continue"
  96. const conversationKey = `${config.url}\n${agentID}\n${digest(config.apiKey)}`
  97. const savedConversation =
  98. conversation === "new" ? undefined : await loadConversationState(context.sessionID, conversationKey)
  99. const threadID = args.thread_id?.trim() || savedConversation?.threadID || ""
  100. const continueRunID =
  101. conversation === "continue" && (!args.thread_id?.trim() || args.thread_id.trim() === savedConversation?.threadID)
  102. ? savedConversation?.runID || ""
  103. : ""
  104. // Observation mode does not change the admitted business task.
  105. const intent = digest(canonicalJSON({ ...args, background: undefined, idempotency_key: undefined, conversation }))
  106. const idempotencyKey =
  107. args.idempotency_key?.trim() ||
  108. `opencode-${digest(canonicalJSON([context.sessionID, context.messageID, agentID, intent]))}`
  109. // Freeze the parent before submitting. Once `started` advances the session,
  110. // retrying this same request must not turn it into a new research revision.
  111. const admission = await requestContext(config, agentID, idempotencyKey, { intent, threadID, runID: continueRunID })
  112. const rememberRecovered = async (run: Record<string, unknown>) => {
  113. const runID = getString(run.run_id),
  114. remoteThreadID = getString(run.session_id) || getString(run.thread_id)
  115. if (!runID || !remoteThreadID) return
  116. const latest = await loadConversationState(context.sessionID, conversationKey)
  117. if (!latest || latest.runID === admission.runID || latest.runID === runID)
  118. await saveConversationState(context.sessionID, conversationKey, { threadID: remoteThreadID, runID })
  119. }
  120. const inputFiles = await Promise.all(
  121. (args.input_file_ids ?? []).map(async (id) => {
  122. const file = await requestJSON(config, `/files/${encodeURIComponent(id)}`, context.abort)
  123. if (file.file_id !== id || file.status !== "available") throw new Error(`输入文件不可用:${id}`)
  124. return file
  125. }),
  126. )
  127. // OpenCode 的宿主机目录不会自动挂载进 AgentPaaS Docker。只有调用方
  128. // 明确给出服务端可见路径时才覆盖,否则让 PaaS 创建并隔离 run workspace。
  129. const workDir = args.work_dir
  130. const url = `${config.url}/api/v1/agents/${encodeURIComponent(agentID)}/run/stream`
  131. let resp: Response
  132. await pendingRequest(config, agentID, idempotencyKey)
  133. const admissionAbort = new AbortController()
  134. const admissionTimer = setTimeout(() => admissionAbort.abort(), 30000)
  135. try {
  136. resp = await fetch(url, {
  137. method: "POST",
  138. headers: {
  139. Authorization: `Bearer ${config.apiKey}`,
  140. "Content-Type": "application/json",
  141. Accept: "text/event-stream",
  142. "Idempotency-Key": idempotencyKey,
  143. },
  144. body: JSON.stringify({
  145. input: args.input,
  146. cancel_on_disconnect: false,
  147. ...(inputFiles.length ? { input_files: inputFiles } : {}),
  148. mode: args.mode,
  149. target_subagent: args.target_subagent ?? "",
  150. thread_id: admission.threadID,
  151. parameters: {
  152. ...args.parameters,
  153. ...(args.max_cost_usd !== undefined ? { client_budget_usd: args.max_cost_usd } : {}),
  154. },
  155. context: {
  156. ...(workDir ? { work_dir: workDir } : {}),
  157. ...(admission.runID ? { run_id: admission.runID } : {}),
  158. ...(args.question_id ? { question_id: args.question_id } : {}),
  159. ...(args.feedback_kind ? { feedback_kind: args.feedback_kind } : {}),
  160. ...(args.input_artifact_ids ? { input_artifact_ids: args.input_artifact_ids } : {}),
  161. },
  162. }),
  163. signal: AbortSignal.any([context.abort, admissionAbort.signal]),
  164. redirect: "error",
  165. })
  166. } catch (err) {
  167. clearTimeout(admissionTimer)
  168. if (!context.abort.aborted) {
  169. const recovered = await recoverRequest(config, agentID, idempotencyKey, context.abort).catch(() => undefined)
  170. if (recovered) {
  171. await rememberRecovered(recovered).catch(() => undefined)
  172. return formatRunResult(agentName, recovered, { agent_id: agentID, admission_recovered: true })
  173. }
  174. }
  175. throw new Error(
  176. `AgentPaaS 请求失败: ${err instanceof Error ? err.message : String(err)};idempotency_key=${idempotencyKey}。可能已受理,请查询原任务;不得换键自动重跑。`,
  177. )
  178. }
  179. if (!resp.ok) {
  180. clearTimeout(admissionTimer)
  181. const detail = await resp.text().catch(() => "")
  182. throw new Error(`AgentPaaS HTTP ${resp.status}: ${detail.slice(0, 500)}`)
  183. }
  184. if (!resp.body) {
  185. clearTimeout(admissionTimer)
  186. throw new Error("AgentPaaS 响应没有 body")
  187. }
  188. const errors: string[] = []
  189. const warnings: string[] = []
  190. const liveMetadata: Record<string, unknown> = {
  191. agent_name: agentName,
  192. agent_id: agentID,
  193. idempotency_key: idempotencyKey,
  194. status: "running",
  195. preflight,
  196. }
  197. let done: Record<string, unknown> | null = null
  198. let startedRunID = ""
  199. let sawCancelled = false
  200. let lastThinkUpdate = 0
  201. const progress = createResearch67Progress()
  202. const researchUI = /research|科研/i.test(agentName) || context.agent.startsWith("research")
  203. const updateMetadata = (title: string, next: Record<string, unknown>) => {
  204. Object.assign(liveMetadata, next)
  205. const snapshot = researchUI ? progress.snapshot() : undefined
  206. context.metadata({
  207. title: snapshot?.title ?? (researchUI ? title : title.replaceAll("Research67", agentName)),
  208. metadata: { ...liveMetadata, ...(snapshot ? { research67_progress: snapshot } : {}) },
  209. })
  210. }
  211. let remoteCancellation: Promise<unknown> | undefined
  212. const cancelOnAbort = () => {
  213. if (args.background) return
  214. if (!startedRunID || remoteCancellation) return
  215. remoteCancellation = cancelAndObserve(config, agentID, startedRunID).then(
  216. (result) => {
  217. updateMetadata("PaaS 取消状态", result)
  218. },
  219. (error) => {
  220. updateMetadata("PaaS 取消未确认,请查询原任务", {
  221. cancellation_status: "unconfirmed",
  222. cancellation_error: String(error),
  223. })
  224. },
  225. )
  226. }
  227. context.abort.addEventListener("abort", cancelOnAbort, { once: true })
  228. try {
  229. for await (const ev of parseSSE(resp.body)) {
  230. const data = asRecord(ev.data)
  231. if (ev.event === "started") {
  232. clearTimeout(admissionTimer)
  233. startedRunID = getString(data?.run_id)
  234. if (!startedRunID) throw new Error("PaaS started 事件缺少 run_id;不能确认任务受理情况")
  235. const remoteThreadID = getString(data?.thread_id) || getString(data?.session_id)
  236. await trackRun(config, {
  237. agent_id: agentID,
  238. agent_name: agentName,
  239. run_id: startedRunID,
  240. thread_id: remoteThreadID,
  241. })
  242. .then(() => clearPendingRequest(config, agentID, idempotencyKey))
  243. .catch(() => {
  244. warnings.push(
  245. `本机任务索引写入失败,请保存 agent_id=${agentID}、run_id=${startedRunID},稍后用 status 查询。`,
  246. )
  247. })
  248. if (remoteThreadID && startedRunID) {
  249. const latest = await loadConversationState(context.sessionID, conversationKey)
  250. if (admission.created || !latest || latest.runID === admission.runID || latest.runID === startedRunID) {
  251. await saveConversationState(context.sessionID, conversationKey, {
  252. threadID: remoteThreadID,
  253. runID: startedRunID,
  254. })
  255. }
  256. }
  257. if (context.abort.aborted) cancelOnAbort()
  258. updateMetadata("Research67 正在运行", {
  259. run_id: data?.run_id,
  260. thread_id: data?.thread_id,
  261. latest_event: ev.event,
  262. })
  263. if (args.background) {
  264. // Breaking cancels only this reader. The worker owns the durable run.
  265. done = { ...data, status: "queued", run_id: startedRunID }
  266. break
  267. }
  268. } else if (ev.event === "stage_started") {
  269. const stageName = getString(data?.stage_name) || getString(data?.stage_id) || "未知阶段"
  270. progress.startStage(getString(data?.stage_id), getPositiveInteger(data?.attempt))
  271. updateMetadata(`Research67 正在进行 ${stageName}`, {
  272. pipeline_id: data?.pipeline_id,
  273. stage_id: data?.stage_id,
  274. stage_name: stageName,
  275. stage_status: data?.status,
  276. attempt: data?.attempt,
  277. latest_event: ev.event,
  278. })
  279. } else if (ev.event === "stage_passed") {
  280. const stageName = getString(data?.stage_name) || getString(data?.stage_id) || "当前阶段"
  281. progress.finishStage(getString(data?.stage_id), "completed")
  282. updateMetadata(`Research67 已通过 ${stageName}`, {
  283. pipeline_id: data?.pipeline_id,
  284. stage_id: data?.stage_id,
  285. stage_name: stageName,
  286. stage_status: data?.status,
  287. attempt: data?.attempt,
  288. latest_event: ev.event,
  289. })
  290. } else if (ev.event === "stage_failed") {
  291. const stageName = getString(data?.stage_name) || getString(data?.stage_id) || "当前阶段"
  292. progress.finishStage(getString(data?.stage_id), "failed")
  293. updateMetadata(`Research67 阶段失败:${stageName}`, {
  294. pipeline_id: data?.pipeline_id,
  295. stage_id: data?.stage_id,
  296. stage_name: stageName,
  297. stage_status: data?.status,
  298. stage_error: data?.error,
  299. attempt: data?.attempt,
  300. latest_event: ev.event,
  301. status: "failed",
  302. })
  303. } else if (ev.event === "pipeline_completed") {
  304. progress.finishPipeline()
  305. updateMetadata("Research67 流水线已完成", {
  306. pipeline_id: data?.pipeline_id,
  307. pipeline_status: data?.status,
  308. latest_event: ev.event,
  309. status: "completed",
  310. })
  311. } else if (ev.event === "confirm_required") {
  312. const runID = getString(data?.run_id) || getString(liveMetadata.run_id)
  313. const toolName = getString(data?.tool) || "高风险工具"
  314. const reason = getString(data?.reason)
  315. const input = getString(data?.input)
  316. if (!runID) throw new Error("AgentPaaS confirm_required 事件缺少 run_id")
  317. const approvalID = getString(data?.approval_id)
  318. if (!approvalID) throw new Error("PaaS 确认事件缺少 approval_id;请升级执行服务,不能批准未绑定的操作。")
  319. // Replayed journals can contain already-resolved confirmations.
  320. // Only ask about the operation that is still pending on the worker.
  321. const current = await requestJSON(
  322. config,
  323. `/agents/${encodeURIComponent(agentID)}/runs/${encodeURIComponent(runID)}`,
  324. context.abort,
  325. )
  326. const pending = asRecord(current.pending_confirmation) || asRecord(current.pending_approval)
  327. if (!pending || pending.approval_id !== approvalID || pending.status !== "pending") continue
  328. progress.note(`等待确认 · ${toolName}`)
  329. updateMetadata(`Research67 正在等待确认:${toolName}`, {
  330. latest_event: ev.event,
  331. pending_confirmation: true,
  332. confirmation_tool: toolName,
  333. confirmation_reason: reason,
  334. confirmation_input: input,
  335. })
  336. let approved = true
  337. try {
  338. await context.ask({
  339. permission: "agentpaas_confirm",
  340. patterns: [`${agentID}:${runID}:${approvalID}`],
  341. always: [],
  342. metadata: {
  343. run_id: runID,
  344. approval_id: approvalID,
  345. agent_name: agentName,
  346. tool: toolName,
  347. reason,
  348. input,
  349. },
  350. })
  351. } catch {
  352. approved = false
  353. }
  354. await resolveConfirmation(config, agentID, runID, approved, context.abort, approvalID)
  355. progress.note(approved ? "确认已通过,继续执行" : "确认被拒绝,等待流程处理")
  356. updateMetadata(`Research67 已${approved ? "批准" : "拒绝"} ${toolName}`, {
  357. latest_event: "confirmation_resolved",
  358. pending_confirmation: false,
  359. confirmation_approved: approved,
  360. })
  361. } else if (ev.event === "tool_call") {
  362. const toolName = getString(data?.tool) || "工具"
  363. progress.toolCall(toolName, getString(data?.content))
  364. updateMetadata(withStage("Research67 正在处理当前步骤", liveMetadata), {
  365. latest_event: ev.event,
  366. latest_tool: toolName,
  367. step: data?.step,
  368. })
  369. } else if (ev.event === "tool_result") {
  370. const toolName = getString(data?.tool) || getString(liveMetadata.latest_tool) || "工具"
  371. progress.toolResult(toolName, getString(data?.content))
  372. updateMetadata(withStage("Research67 已更新当前步骤", liveMetadata), {
  373. latest_event: ev.event,
  374. latest_tool: toolName,
  375. step: data?.step,
  376. })
  377. } else if (ev.event === "think" || ev.event === "think_chunk") {
  378. const now = Date.now()
  379. if (ev.event === "think" || now - lastThinkUpdate >= 1000) {
  380. lastThinkUpdate = now
  381. updateMetadata(withStage("Research67 正在思考", liveMetadata), {
  382. latest_event: ev.event,
  383. step: data?.step,
  384. })
  385. }
  386. } else if (ev.event === "answer") {
  387. updateMetadata(withStage("Research67 正在整理结果", liveMetadata), {
  388. latest_event: ev.event,
  389. step: data?.step,
  390. })
  391. } else if (ev.event === "heartbeat") {
  392. updateMetadata(withStage("Research67 仍在运行", liveMetadata), { latest_event: ev.event })
  393. } else if (ev.event === "error") {
  394. const message = extractMessage(ev.data)
  395. errors.push(message)
  396. updateMetadata("Research67 执行失败", {
  397. latest_event: ev.event,
  398. status: "failed",
  399. error_code: data?.code,
  400. error_message: message,
  401. workspace_path: data?.workspace_path ?? liveMetadata.workspace_path,
  402. })
  403. } else if (ev.event === "paused") {
  404. progress.pause()
  405. updateMetadata("Research67 已暂停", {
  406. latest_event: ev.event,
  407. status: "paused",
  408. checkpoint_id: data?.checkpoint_id,
  409. workspace_path: data?.workspace_path ?? liveMetadata.workspace_path,
  410. })
  411. } else if (ev.event === "approval_required") {
  412. // Durable human gates stop the stream. Surface the approval card; a separate
  413. // control action must approve it and re-subscribe to the same run.
  414. updateMetadata("Research67 等待人工反馈", {
  415. latest_event: ev.event,
  416. status: "waiting_human",
  417. pending_approval: data,
  418. })
  419. } else if (ev.event === "cancelled") {
  420. sawCancelled = true
  421. progress.cancel()
  422. updateMetadata("Research67 已取消", { latest_event: ev.event, status: "cancelled" })
  423. } else if (ev.event === "research_status" && data) {
  424. updateMetadata(scientificLabel(data.status), { scientific_status: data.status, latest_event: ev.event })
  425. } else if (ev.event === "done" && data) {
  426. done = data
  427. break
  428. }
  429. }
  430. } catch (error) {
  431. if (context.abort.aborted) throw error
  432. errors.push(error instanceof Error ? error.message : String(error))
  433. } finally {
  434. clearTimeout(admissionTimer)
  435. context.abort.removeEventListener("abort", cancelOnAbort)
  436. if (remoteCancellation) await remoteCancellation
  437. }
  438. if (!done && !startedRunID && !context.abort.aborted) {
  439. done = (await recoverRequest(config, agentID, idempotencyKey, context.abort).catch(() => undefined)) ?? null
  440. if (done) {
  441. liveMetadata.admission_recovered = true
  442. await rememberRecovered(done).catch(() =>
  443. warnings.push("任务已找回,会话映射保存失败;继续修订前请 select 此 run_id。"),
  444. )
  445. }
  446. }
  447. if ((!done || args.background) && startedRunID && !context.abort.aborted) {
  448. // A dropped transport is not a failed run. Query, never resubmit.
  449. const snapshot = await requestJSON(
  450. config,
  451. `/agents/${encodeURIComponent(agentID)}/runs/${encodeURIComponent(startedRunID)}`,
  452. context.abort,
  453. ).catch(() => null)
  454. if (snapshot) done = snapshot
  455. if (snapshot && !args.background) liveMetadata.connection_recovered = true
  456. if (!snapshot && args.background) {
  457. done = { ...done, status: "unknown" }
  458. warnings.push("任务已受理,最新状态暂不可读取;请用原 run_id 恢复查看,不要重复提交。")
  459. }
  460. }
  461. if (!done) {
  462. const hint = sawCancelled ? "(收到 cancelled 事件)" : "(未收到 done 事件,连接可能中断)"
  463. throw new Error(
  464. `AgentPaaS 任务未正常结束${hint}${errors.length ? ":" + errors.join("; ") : ""}。run_id=${startedRunID || "尚未收到"};idempotency_key=${idempotencyKey}。请先查询原运行状态,不要换键重复执行。`,
  465. )
  466. }
  467. const status = typeof done.status === "string" ? done.status : "unknown"
  468. if (["completed", "partial", "needs_clarification", "failed"].includes(status)) progress.stopUnverified()
  469. if (status === "paused") progress.pause()
  470. if (status === "cancelled") progress.cancel()
  471. const progressMetadata = researchUI ? progress.snapshot() : undefined
  472. const metadata = {
  473. agent_name: agentName,
  474. agent_id: agentID,
  475. idempotency_key: idempotencyKey,
  476. run_id: done.run_id ?? liveMetadata.run_id,
  477. thread_id: done.thread_id ?? done.session_id ?? liveMetadata.thread_id,
  478. status,
  479. steps: done.steps,
  480. total_tokens: done.total_tokens ?? asRecord(done.usage)?.total_tokens,
  481. cost_usd: done.cost_usd ?? asRecord(done.usage)?.cost_usd,
  482. research: done.research,
  483. artifacts: Array.isArray(done.artifacts) ? done.artifacts : [],
  484. workspace_path: done.workspace_path ?? liveMetadata.workspace_path,
  485. error_code: liveMetadata.error_code,
  486. error_message: liveMetadata.error_message,
  487. connection_recovered: liveMetadata.connection_recovered,
  488. admission_recovered: liveMetadata.admission_recovered,
  489. checkpoint_id: done.checkpoint_id ?? liveMetadata.checkpoint_id,
  490. pending_approval: done.pending_approval ?? liveMetadata.pending_approval,
  491. preflight,
  492. background: args.background === true,
  493. warnings,
  494. ...(progressMetadata ? { research67_progress: progressMetadata } : {}),
  495. }
  496. const result = formatRunResult(agentName, { ...done, ...metadata, output: done.output }, metadata)
  497. return {
  498. ...result,
  499. output: [
  500. args.background ? "后台任务已受理;关闭当前观察不会取消执行。重新打开后用 /paas-tasks 找回。" : "",
  501. preflight.summary,
  502. result.output,
  503. ...warnings,
  504. ]
  505. .filter(Boolean)
  506. .join("\n"),
  507. }
  508. },
  509. })
  510. async function resolveConfirmation(
  511. config: { url: string; apiKey: string },
  512. agentID: string,
  513. runID: string,
  514. approved: boolean,
  515. signal: AbortSignal,
  516. approvalID: string,
  517. ) {
  518. // Compatibility adapter: legacy local runs keep their existing confirmation API.
  519. // Remote runs must use their owner-aware route; never fall back after a failed POST.
  520. const remote = agentID.startsWith("locostack:")
  521. const endpoint = remote
  522. ? `/api/v1/agents/${encodeURIComponent(agentID)}/runs/${encodeURIComponent(runID)}/confirm`
  523. : `/api/v1/traces/${encodeURIComponent(runID)}/confirm`
  524. const resp = await fetch(`${config.url}${endpoint}`, {
  525. method: "POST",
  526. headers: {
  527. Authorization: `Bearer ${config.apiKey}`,
  528. "Content-Type": "application/json",
  529. },
  530. body: JSON.stringify({ approved, approval_id: approvalID }),
  531. signal,
  532. redirect: "error",
  533. })
  534. if (resp.ok) return
  535. const detail = await resp.text().catch(() => "")
  536. throw new Error(`AgentPaaS 确认请求失败: HTTP ${resp.status}: ${detail.slice(0, 500)}`)
  537. }
  538. async function* parseSSE(body: ReadableStream<Uint8Array>): AsyncGenerator<SSEEvent> {
  539. const reader = body.getReader()
  540. const decoder = new TextDecoder()
  541. let buffer = ""
  542. try {
  543. while (true) {
  544. const { done, value } = await reader.read()
  545. if (done) break
  546. buffer += decoder.decode(value, { stream: true })
  547. buffer = buffer.replace(/\r\n/g, "\n")
  548. let idx: number
  549. while ((idx = buffer.indexOf("\n\n")) >= 0) {
  550. const chunk = buffer.slice(0, idx)
  551. buffer = buffer.slice(idx + 2)
  552. const event = parseSSEField(chunk, "event")
  553. const dataRaw = parseSSEField(chunk, "data")
  554. if (!event && chunk.split("\n").some((line) => line.trim() === ": heartbeat")) {
  555. yield { event: "heartbeat", data: undefined }
  556. continue
  557. }
  558. let data: unknown = dataRaw
  559. if (dataRaw !== "") {
  560. try {
  561. data = JSON.parse(dataRaw)
  562. } catch {
  563. /* 非 JSON 当纯文本 */
  564. }
  565. }
  566. if (event) yield { event, data }
  567. }
  568. }
  569. } finally {
  570. await reader.cancel().catch(() => undefined)
  571. reader.releaseLock()
  572. }
  573. }
  574. function parseSSEField(chunk: string, field: string): string {
  575. const lines = chunk.split("\n")
  576. const parts: string[] = []
  577. for (const line of lines) {
  578. if (line.startsWith(":")) continue
  579. const m = line.match(new RegExp(`^${field}:\\s?(.*)$`))
  580. if (m) parts.push(m[1])
  581. }
  582. return parts.join("\n")
  583. }
  584. function extractMessage(data: unknown): string {
  585. if (data && typeof data === "object" && "message" in data) return String((data as Record<string, unknown>).message)
  586. return String(data)
  587. }
  588. function asRecord(value: unknown): Record<string, unknown> | undefined {
  589. if (!value || typeof value !== "object" || Array.isArray(value)) return undefined
  590. const result: Record<string, unknown> = {}
  591. for (const [key, item] of Object.entries(value)) result[key] = item
  592. return result
  593. }
  594. function getString(value: unknown): string {
  595. return typeof value === "string" ? value : ""
  596. }
  597. function getPositiveInteger(value: unknown): number {
  598. return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : 1
  599. }
  600. function getWriteFilePath(content: string): string {
  601. try {
  602. const filePath = getString(asRecord(JSON.parse(content))?.file_path)
  603. if (filePath) return filePath
  604. } catch {}
  605. return content.match(/["']file_path["']\s*:\s*(["'])(.*?)\1/)?.[2] ?? ""
  606. }
  607. function withStage(title: string, metadata: Record<string, unknown>): string {
  608. const stageName = getString(metadata.stage_name)
  609. return stageName ? `${title}(${stageName})` : title
  610. }
  611. function createResearch67Progress() {
  612. const stages: ProgressStage[] = [
  613. {
  614. id: "ontology-seed",
  615. label: "本体构建 · seed ontology",
  616. status: "pending",
  617. milestones: [
  618. { id: "parse", label: "解析问题与学科路由", status: "pending", done: new Set(), total: 1 },
  619. { id: "seed", label: "生成基础本体", status: "pending", done: new Set(), total: 1 },
  620. ],
  621. },
  622. {
  623. id: "ontology-audit",
  624. label: "ontology-auditor · 本体审计",
  625. status: "pending",
  626. milestones: [
  627. { id: "schema", label: "检查 schema 和关系", status: "pending", done: new Set(), total: 1 },
  628. { id: "gaps", label: "识别证据与机制缺口", status: "pending", done: new Set(), total: 1 },
  629. ],
  630. },
  631. {
  632. id: "ontology-enrichment",
  633. label: "ontology-enricher · 知识补全",
  634. status: "pending",
  635. milestones: [
  636. { id: "kb", label: "召回本地知识库与教材锚点", status: "pending", done: new Set(), total: 1 },
  637. { id: "search", label: "检索与来源核验", status: "pending", done: new Set(), detail: "尚未开始" },
  638. { id: "patch", label: "生成本体补丁", status: "pending", done: new Set(), total: 1 },
  639. ],
  640. },
  641. {
  642. id: "hypothesis-build",
  643. label: "hypothesis-builder · 假设构建",
  644. status: "pending",
  645. milestones: [
  646. { id: "hypothesis", label: "生成可证伪假设", status: "pending", done: new Set(), total: 1 },
  647. { id: "falsifiers", label: "生成可证伪条件", status: "pending", done: new Set(), total: 1 },
  648. ],
  649. },
  650. {
  651. id: "research-plan",
  652. label: "plan-builder · 研究计划",
  653. status: "pending",
  654. milestones: [
  655. { id: "plan", label: "形成研究计划本体", status: "pending", done: new Set(), total: 1 },
  656. { id: "dag", label: "编译 Action DAG", status: "pending", done: new Set(), total: 1 },
  657. ],
  658. },
  659. {
  660. id: "evaluation",
  661. label: "action-reasoner · 证据评估",
  662. status: "pending",
  663. milestones: [
  664. { id: "assess", label: "评估假设支持状态", status: "pending", done: new Set(), total: 1 },
  665. { id: "synthesis", label: "形成边界化结论", status: "pending", done: new Set(), total: 1 },
  666. ],
  667. },
  668. {
  669. id: "experiment-design",
  670. label: "exp-planner · 实验规划 / 授权包",
  671. status: "pending",
  672. milestones: [
  673. { id: "protocol", label: "生成实验协议", status: "pending", done: new Set(), total: 1 },
  674. { id: "authorization", label: "生成授权与数据回传要求", status: "pending", done: new Set(), total: 1 },
  675. ],
  676. },
  677. {
  678. id: "experiment-execution",
  679. label: "exp-executor · 授权实验执行",
  680. status: "pending",
  681. milestones: [
  682. { id: "auth", label: "确认授权与执行边界", status: "pending", done: new Set(), total: 1 },
  683. { id: "run", label: "运行计算/数据实验", status: "pending", done: new Set(), total: 1 },
  684. { id: "receipt", label: "保存执行日志与结果", status: "pending", done: new Set(), total: 1 },
  685. ],
  686. },
  687. {
  688. id: "result-analysis",
  689. label: "result-analyzer · 结果分析",
  690. status: "pending",
  691. milestones: [
  692. { id: "analysis", label: "分析实验或回传数据", status: "pending", done: new Set(), total: 1 },
  693. { id: "patch", label: "生成 observation patch", status: "pending", done: new Set(), total: 1 },
  694. ],
  695. },
  696. {
  697. id: "paper-writing",
  698. label: "paper-writer · 论文写作",
  699. status: "pending",
  700. milestones: [
  701. { id: "outline", label: "写作计划与大纲", status: "pending", done: new Set(), total: 2 },
  702. { id: "english", label: "英文稿与参考文献", status: "pending", done: new Set(), total: 8 },
  703. { id: "chinese", label: "中文稿", status: "pending", done: new Set(), total: 7 },
  704. { id: "compile", label: "编译双语 PDF", status: "pending", done: new Set(), total: 2 },
  705. { id: "report", label: "形成交付报告", status: "pending", done: new Set(), total: 2 },
  706. ],
  707. },
  708. {
  709. id: "data-verification",
  710. label: "data-verifier · 数据与主张核验",
  711. status: "pending",
  712. milestones: [
  713. { id: "claims", label: "核验论文主张与来源", status: "pending", done: new Set(), total: 1 },
  714. { id: "numbers", label: "核验数据和表述一致性", status: "pending", done: new Set(), total: 1 },
  715. ],
  716. },
  717. {
  718. id: "paper-review",
  719. label: "paper-reviewer · 论文评审",
  720. status: "pending",
  721. milestones: [
  722. { id: "rubric", label: "按科学性和可复现性评分", status: "pending", done: new Set(), total: 1 },
  723. { id: "gaps", label: "输出研究缺口", status: "pending", done: new Set(), total: 1 },
  724. ],
  725. },
  726. {
  727. id: "review-feedback",
  728. label: "review-feedback · 反馈迭代",
  729. status: "pending",
  730. milestones: [
  731. { id: "compile", label: "编译评审反馈", status: "pending", done: new Set(), total: 1 },
  732. { id: "next", label: "生成下一轮 action 与本体补丁", status: "pending", done: new Set(), total: 1 },
  733. ],
  734. },
  735. {
  736. id: "ontology-reaudit",
  737. label: "ontology-auditor · 本体再审计",
  738. status: "pending",
  739. milestones: [
  740. { id: "audit", label: "检查反馈后的本体", status: "pending", done: new Set(), total: 1 },
  741. { id: "decision", label: "决定完成或进入下一轮", status: "pending", done: new Set(), total: 1 },
  742. ],
  743. },
  744. // 兼容旧三阶段 Lite pipeline 事件。
  745. {
  746. id: "idea-analysis",
  747. label: "idea-analyst · 创意分析",
  748. status: "pending",
  749. milestones: [
  750. { id: "plan", label: "制定分析计划", status: "pending", done: new Set(), total: 1 },
  751. { id: "directions", label: "生成检索方向", status: "pending", done: new Set(), total: 2 },
  752. { id: "report", label: "形成分析报告", status: "pending", done: new Set(), total: 2 },
  753. ],
  754. },
  755. {
  756. id: "literature-review",
  757. label: "lit-searcher · 文献检索",
  758. status: "pending",
  759. milestones: [
  760. { id: "plan", label: "制定检索计划", status: "pending", done: new Set(), total: 1 },
  761. { id: "search", label: "检索候选文献", status: "pending", done: new Set(), detail: "尚未开始" },
  762. { id: "select", label: "筛选入选论文", status: "pending", done: new Set(), total: 1 },
  763. { id: "report", label: "形成文献综述", status: "pending", done: new Set(), total: 2 },
  764. ],
  765. },
  766. ]
  767. const observedStages: ProgressStage[] = []
  768. let current: ProgressStage | undefined
  769. let active: ProgressMilestone | undefined
  770. const pendingArtifacts = new Map<string, Array<Array<{ milestone: ProgressMilestone; key: string }>>>()
  771. let searchCalls = 0
  772. let note = ""
  773. let activeSince = Date.now()
  774. let activeAttempt = 0
  775. let timerRunning = false
  776. const aliases: Record<string, string> = {
  777. ontology_seed: "ontology-seed",
  778. "seed-ontology": "ontology-seed",
  779. "audit-ontology": "ontology-audit",
  780. audit_ontology: "ontology-reaudit",
  781. ontology_audit: "ontology-audit",
  782. "ontology-enrich": "ontology-enrichment",
  783. ontology_enrichment: "ontology-enrichment",
  784. "enrich-evidence": "ontology-enrichment",
  785. enrich_evidence: "ontology-enrichment",
  786. search: "ontology-enrichment",
  787. "build-hypothesis": "hypothesis-build",
  788. build_hypothesis: "hypothesis-build",
  789. "hypothesis-builder": "hypothesis-build",
  790. "plan-build": "research-plan",
  791. "build-research-plan": "research-plan",
  792. build_research_plan: "research-plan",
  793. "action-dag": "research-plan",
  794. synthesis: "evaluation",
  795. "falsification-assessment": "evaluation",
  796. falsification_assessment: "evaluation",
  797. "experiment-plan": "experiment-design",
  798. experiment_design: "experiment-design",
  799. experiment_execution: "experiment-execution",
  800. result_analysis: "result-analysis",
  801. paper_writing: "paper-writing",
  802. data_verification: "data-verification",
  803. paper_review: "paper-review",
  804. review_feedback: "review-feedback",
  805. }
  806. const genericMilestones = (): ProgressMilestone[] => [
  807. { id: "run", label: "远端阶段执行中", status: "pending", done: new Set(), total: 1 },
  808. { id: "receipt", label: "等待 receipt / artifact", status: "pending", done: new Set(), total: 1 },
  809. ]
  810. const normalizeStageID = (stageID: string) => aliases[stageID] ?? aliases[stageID.replaceAll("_", "-")] ?? stageID
  811. const findOrCreateStage = (stageID: string) => {
  812. const normalized = normalizeStageID(stageID || "remote-stage")
  813. let stage = stages.find((item) => item.id === normalized)
  814. if (stage) {
  815. if (!observedStages.includes(stage)) observedStages.push(stage)
  816. return stage
  817. }
  818. stage = {
  819. id: normalized,
  820. label: `${stageID || "remote-stage"} · 远端阶段`,
  821. status: "pending",
  822. milestones: genericMilestones(),
  823. }
  824. stages.push(stage)
  825. observedStages.push(stage)
  826. return stage
  827. }
  828. const startMilestone = (milestone: ProgressMilestone) => {
  829. if (!current) return
  830. if (milestone.status === "completed") return
  831. milestone.status = "running"
  832. if (milestone.detail === "尚未开始") milestone.detail = undefined
  833. if (active !== milestone) activeSince = Date.now()
  834. active = milestone
  835. timerRunning = true
  836. note = ""
  837. }
  838. const resetStage = (stage: ProgressStage) => {
  839. for (const milestone of stage.milestones) {
  840. milestone.status = "pending"
  841. milestone.done?.clear()
  842. milestone.detail = milestone.id === "search" ? "尚未开始" : undefined
  843. }
  844. if (["literature-review", "ontology-enrichment"].includes(stage.id)) searchCalls = 0
  845. pendingArtifacts.clear()
  846. }
  847. const artifact = (filePath: string) => {
  848. if (!current) return undefined
  849. const value = filePath.replaceAll("\\", "/").toLowerCase()
  850. const stage = value
  851. .split("/")
  852. .findLastIndex((part) => part === current?.id || new RegExp(`^${current?.id}_a\\d+$`).test(part))
  853. if (stage < 0) return undefined
  854. const relative = value
  855. .split("/")
  856. .slice(stage + 1)
  857. .join("/")
  858. const match = (milestoneID: string, key: string) => {
  859. const milestone = current?.milestones.find((item) => item.id === milestoneID)
  860. return milestone ? { milestone, key } : undefined
  861. }
  862. if (relative === "work_plan.md") {
  863. return match(current.id === "paper-writing" ? "outline" : "plan", "work_plan")
  864. }
  865. if (current.id === "idea-analysis") {
  866. if (relative === "artifacts/search_queries.json") return match("directions", "search_queries")
  867. if (relative === "artifacts/similar_papers.json") return match("directions", "similar_papers")
  868. if (relative === "report.json") return match("report", "report_json")
  869. if (relative === "report.md") return match("report", "report_md")
  870. }
  871. if (["literature-review", "ontology-enrichment"].includes(current.id)) {
  872. if (relative === "artifacts/papers_selected.json") return match("select", "papers_selected")
  873. if (relative === "report.json") return match("report", "report_json")
  874. if (relative === "report.md") return match("report", "report_md")
  875. if (relative.endsWith("search-log.jsonl")) return match("search", "search_log")
  876. }
  877. if (current.id === "experiment-design") {
  878. if (relative.endsWith("experiment_protocol.json")) return match("protocol", "experiment_protocol")
  879. if (relative.endsWith("external_authorization_package.json"))
  880. return match("authorization", "external_authorization_package")
  881. }
  882. if (current.id !== "paper-writing") return undefined
  883. if (relative === "artifacts/outline.json") return match("outline", "outline")
  884. const section = relative.match(
  885. /^artifacts\/sections\/(abstract|introduction|related_work|method|experiments|conclusion)\.tex$/,
  886. )
  887. if (section) return match("english", `section:${section[1]}`)
  888. if (relative === "artifacts/paper.tex") return match("english", "paper_tex")
  889. if (relative === "artifacts/references.bib") return match("english", "references")
  890. const sectionZh = relative.match(
  891. /^artifacts\/sections_zh\/(abstract|introduction|related_work|method|experiments|conclusion)\.tex$/,
  892. )
  893. if (sectionZh) return match("chinese", `section:${sectionZh[1]}`)
  894. if (relative === "artifacts/paper_zh.tex") return match("chinese", "paper_zh_tex")
  895. if (relative === "report.json") return match("report", "report_json")
  896. if (relative === "report.md") return match("report", "report_md")
  897. return undefined
  898. }
  899. const invalidatePaperBuild = (items: Array<{ milestone: ProgressMilestone; key: string }>) => {
  900. if (current?.id !== "paper-writing") return
  901. if (!items.some((item) => ["english", "chinese"].includes(item.milestone.id))) return
  902. const compile = current.milestones.find((item) => item.id === "compile")!
  903. const report = current.milestones.find((item) => item.id === "report")!
  904. if (compile.status === "pending" && !compile.done?.size && report.status === "pending") return
  905. compile.status = "pending"
  906. compile.done?.clear()
  907. report.status = "pending"
  908. report.done?.clear()
  909. if (active === compile || active === report) active = undefined
  910. activeSince = Date.now()
  911. timerRunning = true
  912. note = "论文源文件已更新,等待重新编译"
  913. }
  914. const completeArtifact = (item: { milestone: ProgressMilestone; key: string }) => {
  915. item.milestone.done?.add(item.key)
  916. if (!item.milestone.total || (item.milestone.done?.size ?? 0) < item.milestone.total) return
  917. item.milestone.status = "completed"
  918. if (active !== item.milestone || !current) return
  919. const next = current.milestones[current.milestones.indexOf(item.milestone) + 1]
  920. if (next) return startMilestone(next)
  921. active = undefined
  922. activeSince = Date.now()
  923. timerRunning = true
  924. note = "正在进行 Guard / 阶段产物验收"
  925. }
  926. const enqueueArtifacts = (toolName: string, items: Array<{ milestone: ProgressMilestone; key: string }>) => {
  927. const queue = pendingArtifacts.get(toolName) ?? []
  928. queue.push(items)
  929. pendingArtifacts.set(toolName, queue)
  930. }
  931. const dequeueArtifacts = (toolName: string) => {
  932. const queue = pendingArtifacts.get(toolName)
  933. const items = queue?.shift()
  934. if (!queue?.length) pendingArtifacts.delete(toolName)
  935. return items
  936. }
  937. return {
  938. startStage(stageID: string, attempt: number) {
  939. const stage = findOrCreateStage(stageID)
  940. if (stage === current && attempt <= activeAttempt) return
  941. if (stage === current) resetStage(stage)
  942. current = stage
  943. activeAttempt = attempt
  944. // A later stage starting says nothing about whether earlier stages ran.
  945. current.status = "running"
  946. startMilestone(current.milestones[0])
  947. },
  948. finishStage(stageID: string, status: "completed" | "failed") {
  949. const stage = findOrCreateStage(stageID)
  950. stage.status = status
  951. if (status === "completed") {
  952. for (const milestone of stage.milestones) milestone.status = "completed"
  953. } else {
  954. for (const milestone of stage.milestones) {
  955. if (milestone.status === "running") milestone.status = "failed"
  956. }
  957. }
  958. current = stage
  959. active = status === "failed" ? active : undefined
  960. timerRunning = false
  961. note = status === "failed" ? "阶段执行失败" : "阶段验收通过"
  962. },
  963. finishPipeline() {
  964. // Terminal pipeline status is not evidence that every predefined stage ran.
  965. for (const stage of observedStages) {
  966. if (stage.status === "running") stage.status = "unknown"
  967. for (const milestone of stage.milestones) {
  968. if (milestone.status === "running") milestone.status = "unknown"
  969. }
  970. }
  971. active = undefined
  972. timerRunning = false
  973. note = "流程已结束;阶段状态以服务端事件为准"
  974. },
  975. stopUnverified() {
  976. for (const stage of observedStages) {
  977. if (stage.status === "running") stage.status = "unknown"
  978. for (const milestone of stage.milestones) {
  979. if (milestone.status === "running") milestone.status = "unknown"
  980. }
  981. }
  982. active = undefined
  983. timerRunning = false
  984. },
  985. pause() {
  986. if (current?.status === "running") current.status = "paused"
  987. if (active?.status === "running") active.status = "paused"
  988. timerRunning = false
  989. note = "任务已暂停,等待恢复"
  990. },
  991. cancel() {
  992. if (current?.status === "running") current.status = "cancelled"
  993. if (active?.status === "running") active.status = "cancelled"
  994. timerRunning = false
  995. note = "任务已取消"
  996. },
  997. note(value: string) {
  998. note = value
  999. },
  1000. toolCall(toolName: string, content: string) {
  1001. const lower = toolName.toLowerCase()
  1002. if (
  1003. current?.id === "ontology-enrichment" &&
  1004. ["kbsearch", "websearch", "webfetch", "openalex_search", "crossref_search"].includes(lower)
  1005. ) {
  1006. const milestone = current.milestones.find((item) => item.id === "search")!
  1007. startMilestone(milestone)
  1008. return
  1009. }
  1010. if (current?.id === "literature-review" && ["arxiv_search", "openalex_search"].includes(lower)) {
  1011. const milestone = current.milestones.find((item) => item.id === "search")!
  1012. startMilestone(milestone)
  1013. return
  1014. }
  1015. if (current?.id === "paper-writing" && lower === "compilelatex") {
  1016. const milestone = current.milestones.find((item) => item.id === "compile")!
  1017. const key = content.toLowerCase().includes("paper_zh.tex") ? "paper_zh_pdf" : "paper_pdf"
  1018. milestone.done?.delete(key)
  1019. if (milestone.status === "completed") milestone.status = "pending"
  1020. startMilestone(milestone)
  1021. enqueueArtifacts(lower, [{ milestone, key }])
  1022. return
  1023. }
  1024. if (current?.id === "paper-writing" && lower === "buildresearchpaper") {
  1025. const milestone = current.milestones.find((item) => item.id === "compile")!
  1026. milestone.status = "pending"
  1027. milestone.done?.clear()
  1028. startMilestone(milestone)
  1029. enqueueArtifacts(lower, [
  1030. { milestone, key: "paper_pdf" },
  1031. { milestone, key: "paper_zh_pdf" },
  1032. ])
  1033. return
  1034. }
  1035. if (lower !== "writefile") return
  1036. const item = artifact(getWriteFilePath(content))
  1037. if (!item) {
  1038. enqueueArtifacts(lower, [])
  1039. return
  1040. }
  1041. if (
  1042. ["literature-review", "ontology-enrichment"].includes(current?.id ?? "") &&
  1043. item.milestone.id === "select" &&
  1044. searchCalls
  1045. ) {
  1046. const searchMilestone = current?.milestones.find((milestone) => milestone.id === "search")
  1047. if (searchMilestone) searchMilestone.status = "completed"
  1048. }
  1049. startMilestone(item.milestone)
  1050. enqueueArtifacts(lower, [item])
  1051. },
  1052. toolResult(toolName: string, content: string) {
  1053. const lower = toolName.toLowerCase()
  1054. const failed = /\[(?:tool_)?error\]|mcp_error|"status"\s*:\s*"(?:failed|error)"|"passed"\s*:\s*false/i.test(
  1055. content,
  1056. )
  1057. if (
  1058. current?.id === "ontology-enrichment" &&
  1059. ["kbsearch", "websearch", "webfetch", "openalex_search", "crossref_search"].includes(lower)
  1060. ) {
  1061. if (!failed) searchCalls++
  1062. const milestone = current.milestones.find((item) => item.id === "search")!
  1063. milestone.detail = searchCalls ? `已完成 ${searchCalls} 轮检索/核验` : "等待检索重试"
  1064. return
  1065. }
  1066. if (current?.id === "literature-review" && ["arxiv_search", "openalex_search"].includes(lower)) {
  1067. if (!failed) searchCalls++
  1068. const milestone = current.milestones.find((item) => item.id === "search")!
  1069. milestone.detail = searchCalls ? `已完成 ${searchCalls} 轮检索` : "等待检索重试"
  1070. return
  1071. }
  1072. const items = dequeueArtifacts(lower)
  1073. if (!items) return
  1074. if (!failed) {
  1075. items.forEach(completeArtifact)
  1076. invalidatePaperBuild(items)
  1077. }
  1078. if (failed) {
  1079. for (const item of items) item.milestone.status = "failed"
  1080. note = "当前操作失败,等待重试"
  1081. }
  1082. },
  1083. snapshot() {
  1084. if (!current) return undefined
  1085. const rows = observedStages.flatMap((stage) => {
  1086. const detail = stage.status === "running" ? active?.label : undefined
  1087. const parent = [{ id: stage.id, label: stage.label, status: stage.status, detail, depth: 0 }]
  1088. if (stage !== current || !["running", "failed"].includes(stage.status)) return parent
  1089. return parent.concat(
  1090. stage.milestones.map((milestone) => ({
  1091. id: `${stage.id}:${milestone.id}`,
  1092. label: milestone.label,
  1093. status: milestone.status,
  1094. detail:
  1095. milestone.detail ??
  1096. (milestone.status !== "completed" && milestone.total && milestone.done?.size
  1097. ? `${milestone.done.size}/${milestone.total}`
  1098. : undefined),
  1099. depth: 1,
  1100. })),
  1101. )
  1102. })
  1103. return {
  1104. kind: "research67",
  1105. title: active ? `Research67 · ${current.label} · ${active.label}` : `Research67 · ${current.label}`,
  1106. rows,
  1107. activeSince: timerRunning ? activeSince : undefined,
  1108. footer: note || (!active ? "进度已更新" : undefined),
  1109. }
  1110. },
  1111. }
  1112. }