agentpaas_run.ts 49 KB

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