agentpaas-run.test.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  1. import { expect, test } from "bun:test"
  2. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"
  3. import { tmpdir } from "node:os"
  4. import path from "node:path"
  5. test("shows pipeline stages and resolves remote confirmations", async () => {
  6. const home = await mkdtemp(path.join(tmpdir(), "agentpaas-bridge-"))
  7. const originalHome = process.env.HOME
  8. const originalFetch = globalThis.fetch
  9. const updates: Array<{ title?: string; metadata?: Record<string, unknown> }> = []
  10. const confirmationBodies: unknown[] = []
  11. const permissionRequests: Array<{
  12. permission: string
  13. patterns: string[]
  14. always: string[]
  15. metadata: Record<string, unknown>
  16. }> = []
  17. const events: Array<[string, unknown]> = [
  18. ["started", { run_id: "run_1", thread_id: "thread_1" }],
  19. [
  20. "stage_started",
  21. {
  22. pipeline_id: "research67-one-round",
  23. stage_id: "idea-analysis",
  24. stage_name: "创意分析",
  25. attempt: 1,
  26. status: "running",
  27. },
  28. ],
  29. ["tool_call", { tool: "WriteFile", step: 1, content: '{"file_path":"/run/idea-analysis/work_plan.md"}' }],
  30. ["tool_result", { tool: "WriteFile", step: 1, content: "[OK] Created work_plan.md" }],
  31. [
  32. "tool_call",
  33. { tool: "WriteFile", step: 1, content: '{"file_path":"/run/idea-analysis/artifacts/search_queries.json"}' },
  34. ],
  35. ["tool_result", { tool: "WriteFile", step: 1, content: "[OK] Created search_queries.json" }],
  36. [
  37. "tool_call",
  38. { tool: "WriteFile", step: 1, content: '{"file_path":"/run/idea-analysis/artifacts/similar_papers.json"}' },
  39. ],
  40. ["tool_result", { tool: "WriteFile", step: 1, content: "[OK] Created similar_papers.json" }],
  41. ["tool_call", { tool: "WriteFile", step: 1, content: '{"file_path":"/run/idea-analysis/report.json"}' }],
  42. ["tool_result", { tool: "WriteFile", step: 1, content: "[OK] Created report.json" }],
  43. ["tool_call", { tool: "WriteFile", step: 1, content: '{"file_path":"/run/idea-analysis/report.md"}' }],
  44. ["tool_result", { tool: "WriteFile", step: 1, content: "[OK] Created report.md" }],
  45. [
  46. "stage_passed",
  47. {
  48. pipeline_id: "research67-one-round",
  49. stage_id: "idea-analysis",
  50. stage_name: "创意分析",
  51. attempt: 1,
  52. status: "passed",
  53. },
  54. ],
  55. [
  56. "stage_started",
  57. {
  58. pipeline_id: "research67-one-round",
  59. stage_id: "literature-review",
  60. stage_name: "文献检索",
  61. attempt: 1,
  62. status: "running",
  63. },
  64. ],
  65. [
  66. "tool_call",
  67. { tool: "ReadFile", step: "lit-upstream", content: "{'file_path':'/run/idea-analysis/report.json'}" },
  68. ],
  69. ["tool_result", { tool: "ReadFile", step: "lit-upstream", content: "idea analysis report" }],
  70. [
  71. "confirm_required",
  72. {
  73. run_id: "run_1",
  74. tool: "Shell",
  75. approval_id: "tc_shell",
  76. reason: "high-risk command",
  77. input: "rm generated.tmp",
  78. },
  79. ],
  80. ["think_chunk", { text: "检索中" }],
  81. ["tool_call", { tool: "arxiv_search", step: 2, content: '{"query":"topic-specific words","limit":10}' }],
  82. ["tool_result", { tool: "arxiv_search", step: 2, content: '{"status":"completed","result_count":10}' }],
  83. [
  84. "tool_call",
  85. { tool: "WriteFile", step: 3, content: '{"file_path":"/run/literature-review/artifacts/papers_selected.json"}' },
  86. ],
  87. ["tool_result", { tool: "WriteFile", step: 3, content: "[OK] Created papers_selected.json" }],
  88. [
  89. "confirm_required",
  90. {
  91. run_id: "run_1",
  92. tool: "WriteFile",
  93. approval_id: "tc_write",
  94. reason: "overwrite existing file",
  95. input: "report.json",
  96. },
  97. ],
  98. [
  99. "stage_passed",
  100. {
  101. pipeline_id: "research67-one-round",
  102. stage_id: "literature-review",
  103. stage_name: "文献检索",
  104. attempt: 1,
  105. status: "passed",
  106. },
  107. ],
  108. [
  109. "stage_started",
  110. {
  111. pipeline_id: "research67-one-round",
  112. stage_id: "paper-writing",
  113. stage_name: "实验前研究草稿撰写",
  114. attempt: 1,
  115. status: "running",
  116. },
  117. ],
  118. [
  119. "tool_call",
  120. {
  121. tool: "ReadFile",
  122. step: "paper-upstream",
  123. content: '{"file_path":"/run/literature-review/report.json"}',
  124. },
  125. ],
  126. ["tool_result", { tool: "ReadFile", step: "paper-upstream", content: "literature review report" }],
  127. [
  128. "tool_call",
  129. {
  130. tool: "WriteFile",
  131. step: "paper-scratch",
  132. content: '{"file_path":"/run/paper-writing/scratch.md","content":"later write /run/paper-writing/report.json"}',
  133. },
  134. ],
  135. ["tool_result", { tool: "WriteFile", step: "paper-scratch", content: "[OK] Created scratch.md" }],
  136. ["tool_call", { tool: "WriteFile", step: 4, content: '{"file_path":"/run/paper-writing/artifacts/outline.json"}' }],
  137. ["tool_result", { tool: "WriteFile", step: 4, content: "[OK] Created outline.json" }],
  138. [
  139. "tool_call",
  140. { tool: "WriteFile", step: 5, content: '{"file_path":"/run/paper-writing/artifacts/sections/abstract.tex"}' },
  141. ],
  142. ["tool_result", { tool: "WriteFile", step: 5, content: "[OK] Created abstract.tex" }],
  143. [
  144. "tool_call",
  145. {
  146. tool: "BuildResearchPaper",
  147. step: 6,
  148. content:
  149. '{"phase_dir":"/run/paper-writing","papers_selected_path":"/run/literature-review/artifacts/papers_selected.json"}',
  150. },
  151. ],
  152. ["tool_result", { tool: "BuildResearchPaper", step: 6, content: '{"status":"failed","passed":false}' }],
  153. [
  154. "tool_call",
  155. {
  156. tool: "WriteFile",
  157. step: "paper-repair",
  158. content: '{"file_path":"/run/paper-writing/artifacts/sections/abstract.tex"}',
  159. },
  160. ],
  161. ["tool_result", { tool: "WriteFile", step: "paper-repair", content: "[OK] Updated abstract.tex" }],
  162. [
  163. "tool_call",
  164. {
  165. tool: "BuildResearchPaper",
  166. step: 7,
  167. content:
  168. '{"phase_dir":"/run/paper-writing","papers_selected_path":"/run/literature-review/artifacts/papers_selected.json"}',
  169. },
  170. ],
  171. ["tool_result", { tool: "BuildResearchPaper", step: 7, content: '{"status":"completed","passed":true}' }],
  172. ["tool_call", { tool: "WriteFile", step: 8, content: '{"file_path":"/run/paper-writing/report.json"}' }],
  173. ["tool_call", { tool: "WriteFile", step: 8, content: '{"file_path":"/run/paper-writing/report.md"}' }],
  174. ["tool_result", { tool: "WriteFile", step: 8, content: "[OK] Created report.json" }],
  175. ["tool_result", { tool: "WriteFile", step: 8, content: "[OK] Created report.md" }],
  176. [
  177. "stage_passed",
  178. {
  179. pipeline_id: "research67-one-round",
  180. stage_id: "paper-writing",
  181. stage_name: "实验前研究草稿撰写",
  182. attempt: 1,
  183. status: "passed",
  184. },
  185. ],
  186. ["pipeline_completed", { pipeline_id: "research67-one-round", status: "completed" }],
  187. ["done", { run_id: "run_1", thread_id: "thread_1", status: "completed", output: "完成" }],
  188. ]
  189. try {
  190. process.env.HOME = home
  191. globalThis.fetch = Object.assign(
  192. async (input: URL | RequestInfo, init?: RequestInit) => {
  193. const pathname = new URL(input instanceof Request ? input.url : input.toString()).pathname
  194. if (pathname.endsWith("/verify")) return Response.json({ status: "verified", checks: [] })
  195. if (pathname === "/api/v1/agents") {
  196. return Response.json({
  197. agents: [{ id: "ag_pipeline", name: "Research67 三阶段研究草稿流水线" }],
  198. })
  199. }
  200. if (pathname === "/api/v1/agents/ag_pipeline/run/stream") {
  201. const body =
  202. events
  203. .map(
  204. ([event, data], index) =>
  205. `event: ${event}\ndata: ${JSON.stringify(data)}${index === 5 ? "\n\n: heartbeat" : ""}`,
  206. )
  207. .join("\n\n") + "\n\n"
  208. return new Response(body, { headers: { "Content-Type": "text/event-stream" } })
  209. }
  210. if (pathname === "/api/v1/agents/ag_pipeline/runs/run_1")
  211. return Response.json({
  212. status: "running",
  213. pending_confirmation: {
  214. approval_id: confirmationBodies.length ? "tc_write" : "tc_shell",
  215. status: "pending",
  216. },
  217. })
  218. if (pathname === "/api/v1/traces/run_1/confirm") {
  219. if (typeof init?.body !== "string") throw new Error("confirmation body must be JSON")
  220. confirmationBodies.push(JSON.parse(init.body))
  221. return Response.json({ run_id: "run_1", status: "confirmed" })
  222. }
  223. return new Response("not found", { status: 404 })
  224. },
  225. { preconnect: originalFetch.preconnect },
  226. )
  227. const configDir = path.join(home, ".agentpaas")
  228. await mkdir(configDir)
  229. await writeFile(
  230. path.join(configDir, "config.json"),
  231. JSON.stringify({ server: "http://agentpaas.test", api_key: "test-key" }),
  232. )
  233. const bridge = (await import(`../../../../.opencode/tool/agentpaas_run.ts?test=${Date.now()}`)).default
  234. const result = await bridge.execute(
  235. {
  236. input: "调查课题",
  237. agent_name: "Research67 三阶段研究草稿流水线",
  238. mode: "iterate",
  239. },
  240. {
  241. sessionID: "session_1",
  242. messageID: "message_1",
  243. agent: "research-67-pipeline",
  244. directory: "/workspace",
  245. worktree: "/workspace",
  246. abort: new AbortController().signal,
  247. metadata: (update: (typeof updates)[number]) => updates.push(update),
  248. ask: async (request: (typeof permissionRequests)[number]) => {
  249. permissionRequests.push(request)
  250. if (permissionRequests.length === 2) throw new Error("denied")
  251. },
  252. },
  253. )
  254. expect(updates.map((update) => update.title).join("\n")).not.toContain("正在调用")
  255. expect(updates.map((update) => update.title).join("\n")).not.toContain("arxiv_search")
  256. expect(JSON.stringify(updates.map((update) => update.metadata?.research67_progress))).not.toContain(
  257. "topic-specific words",
  258. )
  259. expect(updates).toContainEqual(
  260. expect.objectContaining({
  261. metadata: expect.objectContaining({
  262. latest_event: "heartbeat",
  263. research67_progress: expect.objectContaining({ activeSince: expect.any(Number) }),
  264. }),
  265. }),
  266. )
  267. expect(JSON.stringify(updates)).not.toContain("连接正常")
  268. const snapshots = updates.flatMap((update) => {
  269. const value = update.metadata?.research67_progress
  270. return value && typeof value === "object" ? [Object.fromEntries(Object.entries(value))] : []
  271. })
  272. expect(snapshots.some((snapshot) => snapshot.title === "Research67 · idea-analyst · 创意分析 · 制定分析计划")).toBe(
  273. true,
  274. )
  275. expect(snapshots).toContainEqual(
  276. expect.objectContaining({
  277. rows: expect.arrayContaining([
  278. expect.objectContaining({ id: "idea-analysis:plan", status: "completed" }),
  279. expect.objectContaining({ id: "idea-analysis:directions", status: "running" }),
  280. ]),
  281. }),
  282. )
  283. const litUpstream = updates.find(
  284. (update) => update.metadata?.latest_event === "tool_result" && update.metadata.step === "lit-upstream",
  285. )?.metadata?.research67_progress
  286. expect(litUpstream).toMatchObject({
  287. title: "Research67 · lit-searcher · 文献检索 · 制定检索计划",
  288. rows: expect.arrayContaining([
  289. expect.objectContaining({ id: "literature-review:plan", status: "running" }),
  290. expect.objectContaining({ id: "literature-review:report", status: "pending" }),
  291. ]),
  292. })
  293. expect(snapshots).toContainEqual(
  294. expect.objectContaining({
  295. footer: "正在进行 Guard / 阶段产物验收",
  296. activeSince: expect.any(Number),
  297. rows: expect.arrayContaining([expect.objectContaining({ id: "idea-analysis:report", status: "completed" })]),
  298. }),
  299. )
  300. for (const step of ["paper-upstream", "paper-scratch"]) {
  301. expect(
  302. updates.find((update) => update.metadata?.latest_event === "tool_result" && update.metadata.step === step)
  303. ?.metadata?.research67_progress,
  304. ).toMatchObject({
  305. title: "Research67 · paper-writer · 论文写作 · 写作计划与大纲",
  306. rows: expect.arrayContaining([
  307. expect.objectContaining({ id: "paper-writing:outline", status: "running" }),
  308. expect.objectContaining({ id: "paper-writing:compile", status: "pending" }),
  309. expect.objectContaining({ id: "paper-writing:report", status: "pending" }),
  310. ]),
  311. })
  312. }
  313. expect(
  314. updates.find(
  315. (update) =>
  316. update.metadata?.latest_event === "tool_result" &&
  317. update.metadata.latest_tool === "BuildResearchPaper" &&
  318. update.metadata.step === 6,
  319. )?.metadata?.research67_progress,
  320. ).toMatchObject({
  321. rows: expect.arrayContaining([
  322. expect.objectContaining({ id: "paper-writing:compile", status: "failed" }),
  323. expect.objectContaining({ id: "paper-writing:report", status: "pending" }),
  324. ]),
  325. footer: "当前操作失败,等待重试",
  326. })
  327. expect(
  328. updates.find(
  329. (update) => update.metadata?.latest_event === "tool_result" && update.metadata.step === "paper-repair",
  330. )?.metadata?.research67_progress,
  331. ).toMatchObject({
  332. rows: expect.arrayContaining([
  333. expect.objectContaining({ id: "paper-writing:compile", status: "pending" }),
  334. expect.objectContaining({ id: "paper-writing:report", status: "pending" }),
  335. ]),
  336. footer: "论文源文件已更新,等待重新编译",
  337. })
  338. expect(
  339. updates.find(
  340. (update) =>
  341. update.metadata?.latest_event === "tool_call" &&
  342. update.metadata.latest_tool === "BuildResearchPaper" &&
  343. update.metadata.step === 7,
  344. )?.metadata?.research67_progress,
  345. ).toMatchObject({
  346. title: "Research67 · paper-writer · 论文写作 · 编译双语 PDF",
  347. rows: expect.arrayContaining([expect.objectContaining({ id: "paper-writing:compile", status: "running" })]),
  348. })
  349. expect(snapshots).toContainEqual(
  350. expect.objectContaining({
  351. rows: expect.arrayContaining([
  352. expect.objectContaining({
  353. id: "literature-review:search",
  354. status: "running",
  355. detail: "已完成 1 轮检索",
  356. }),
  357. ]),
  358. }),
  359. )
  360. expect(snapshots).toContainEqual(
  361. expect.objectContaining({
  362. rows: expect.arrayContaining([
  363. expect.objectContaining({ id: "literature-review:search", status: "completed" }),
  364. expect.objectContaining({ id: "literature-review:select", status: "running" }),
  365. ]),
  366. }),
  367. )
  368. expect(snapshots).toContainEqual(
  369. expect.objectContaining({
  370. rows: expect.arrayContaining([
  371. expect.objectContaining({ id: "literature-review:select", status: "completed" }),
  372. expect.objectContaining({ id: "literature-review:report", status: "running" }),
  373. ]),
  374. }),
  375. )
  376. expect(snapshots).toContainEqual(
  377. expect.objectContaining({
  378. rows: expect.arrayContaining([
  379. expect.objectContaining({ id: "paper-writing:english", status: "running", detail: "1/8" }),
  380. ]),
  381. }),
  382. )
  383. expect(snapshots).toContainEqual(
  384. expect.objectContaining({
  385. rows: expect.arrayContaining([
  386. expect.objectContaining({ id: "paper-writing:compile", status: "completed" }),
  387. expect.objectContaining({ id: "paper-writing:report", status: "running" }),
  388. ]),
  389. }),
  390. )
  391. expect(snapshots).toContainEqual(
  392. expect.objectContaining({
  393. footer: "正在进行 Guard / 阶段产物验收",
  394. rows: expect.arrayContaining([
  395. expect.objectContaining({ id: "paper-writing:report", status: "completed", detail: undefined }),
  396. ]),
  397. }),
  398. )
  399. expect(updates.at(-1)?.metadata).toMatchObject({
  400. pipeline_id: "research67-one-round",
  401. stage_id: "paper-writing",
  402. stage_status: "passed",
  403. pipeline_status: "completed",
  404. status: "completed",
  405. research67_progress: {
  406. kind: "research67",
  407. rows: [
  408. expect.objectContaining({ id: "idea-analysis", status: "completed" }),
  409. expect.objectContaining({ id: "literature-review", status: "completed" }),
  410. expect.objectContaining({ id: "paper-writing", status: "completed" }),
  411. ],
  412. },
  413. })
  414. expect(permissionRequests).toHaveLength(2)
  415. expect(permissionRequests[0]).toEqual({
  416. permission: "agentpaas_confirm",
  417. patterns: ["ag_pipeline:run_1:tc_shell"],
  418. always: [],
  419. metadata: {
  420. run_id: "run_1",
  421. approval_id: "tc_shell",
  422. agent_name: "Research67 三阶段研究草稿流水线",
  423. tool: "Shell",
  424. reason: "high-risk command",
  425. input: "rm generated.tmp",
  426. },
  427. })
  428. expect(permissionRequests[1]).toMatchObject({
  429. permission: "agentpaas_confirm",
  430. patterns: ["ag_pipeline:run_1:tc_write"],
  431. metadata: { tool: "WriteFile", reason: "overwrite existing file", input: "report.json" },
  432. })
  433. expect(confirmationBodies).toEqual([
  434. { approved: true, approval_id: "tc_shell" },
  435. { approved: false, approval_id: "tc_write" },
  436. ])
  437. expect(result).toMatchObject({ output: expect.stringContaining("完成") })
  438. } finally {
  439. globalThis.fetch = originalFetch
  440. process.env.HOME = originalHome
  441. await rm(home, { recursive: true, force: true })
  442. }
  443. })
  444. test("preserves completed artifacts and forbids automatic reruns after failure", async () => {
  445. const home = await mkdtemp(path.join(tmpdir(), "agentpaas-bridge-failure-"))
  446. const originalHome = process.env.HOME
  447. const originalFetch = globalThis.fetch
  448. const updates: Array<{ title?: string; metadata?: Record<string, unknown> }> = []
  449. const workspacePath = "/workspace/runs/run_failure"
  450. const events: Array<[string, unknown]> = [
  451. ["started", { run_id: "run_failure", thread_id: "thread_failure" }],
  452. [
  453. "stage_started",
  454. {
  455. pipeline_id: "research67-one-round",
  456. stage_id: "paper-writing",
  457. stage_name: "实验前研究草稿撰写",
  458. attempt: 1,
  459. status: "running",
  460. },
  461. ],
  462. ["tool_call", { tool: "WriteFile", content: '{"file_path":"/run/paper-writing/artifacts/outline.json"}' }],
  463. ["tool_result", { tool: "WriteFile", content: "[OK] Created outline.json" }],
  464. [
  465. "stage_started",
  466. {
  467. pipeline_id: "research67-one-round",
  468. stage_id: "paper-writing",
  469. stage_name: "实验前研究草稿撰写",
  470. attempt: 1,
  471. status: "running",
  472. },
  473. ],
  474. ["tool_call", { tool: "CompileLatex", content: '{"tex_path":"/run/paper-writing/artifacts/paper.tex"}' }],
  475. ["tool_result", { tool: "CompileLatex", content: "[TOOL_ERROR] UnicodeDecodeError" }],
  476. [
  477. "tool_call",
  478. {
  479. tool: "WriteFile",
  480. step: "repair",
  481. content: '{"file_path":"/run/paper-writing/artifacts/paper.tex"}',
  482. },
  483. ],
  484. ["tool_result", { tool: "WriteFile", step: "repair", content: "[OK] Updated paper.tex" }],
  485. [
  486. "stage_started",
  487. {
  488. pipeline_id: "research67-one-round",
  489. stage_id: "paper-writing",
  490. stage_name: "实验前研究草稿撰写",
  491. attempt: 2,
  492. status: "running",
  493. },
  494. ],
  495. ["tool_call", { tool: "CompileLatex", content: '{"tex_path":"/run/paper-writing/artifacts/paper.tex"}' }],
  496. ["tool_result", { tool: "CompileLatex", content: "[TOOL_ERROR] UnicodeDecodeError" }],
  497. [
  498. "stage_failed",
  499. {
  500. pipeline_id: "research67-one-round",
  501. stage_id: "paper-writing",
  502. stage_name: "实验前研究草稿撰写",
  503. attempt: 2,
  504. status: "failed",
  505. error: "Native function-calling loop produced no final output",
  506. },
  507. ],
  508. [
  509. "error",
  510. {
  511. code: "AGENT_EXECUTION_FAILED",
  512. message: "Native function-calling loop produced no final output",
  513. workspace_path: workspacePath,
  514. },
  515. ],
  516. ["done", { run_id: "run_failure", thread_id: "thread_failure", status: "failed" }],
  517. ]
  518. try {
  519. process.env.HOME = home
  520. globalThis.fetch = Object.assign(
  521. async (input: URL | RequestInfo) => {
  522. const pathname = new URL(input instanceof Request ? input.url : input.toString()).pathname
  523. if (pathname.endsWith("/verify")) return Response.json({ status: "verified", checks: [] })
  524. if (pathname === "/api/v1/agents") {
  525. return Response.json({
  526. agents: [{ id: "ag_pipeline", name: "Research67 三阶段研究草稿流水线" }],
  527. })
  528. }
  529. if (pathname === "/api/v1/agents/ag_pipeline/run/stream") {
  530. const body =
  531. events.map(([event, data]) => `event: ${event}\ndata: ${JSON.stringify(data)}`).join("\n\n") + "\n\n"
  532. return new Response(body, { headers: { "Content-Type": "text/event-stream" } })
  533. }
  534. return new Response("not found", { status: 404 })
  535. },
  536. { preconnect: originalFetch.preconnect },
  537. )
  538. const configDir = path.join(home, ".agentpaas")
  539. await mkdir(configDir)
  540. await writeFile(
  541. path.join(configDir, "config.json"),
  542. JSON.stringify({ server: "http://agentpaas.test", api_key: "test-key" }),
  543. )
  544. const bridge = (await import(`../../../../.opencode/tool/agentpaas_run.ts?failure=${Date.now()}`)).default
  545. const result = await bridge.execute(
  546. { input: "调查课题", agent_name: "Research67 三阶段研究草稿流水线", mode: "iterate" },
  547. {
  548. sessionID: "session_failure",
  549. messageID: "message_failure",
  550. agent: "research-67-pipeline",
  551. directory: "/workspace",
  552. worktree: "/workspace",
  553. abort: new AbortController().signal,
  554. metadata: (update: (typeof updates)[number]) => updates.push(update),
  555. ask: async () => undefined,
  556. },
  557. )
  558. expect(result.output).toContain("Native function-calling loop produced no final output")
  559. expect(result.output).toContain(workspacePath)
  560. expect(result.output).toContain("失败严禁自动重跑、拆分任务或调用其他 subagent")
  561. expect(
  562. updates.find((update) => update.metadata?.latest_event === "tool_result" && update.metadata.step === "repair")
  563. ?.metadata?.research67_progress,
  564. ).toMatchObject({
  565. title: "Research67 · paper-writer · 论文写作 · 英文稿与参考文献",
  566. footer: "论文源文件已更新,等待重新编译",
  567. rows: expect.arrayContaining([
  568. expect.objectContaining({ id: "paper-writing:english", status: "running" }),
  569. expect.objectContaining({ id: "paper-writing:compile", status: "pending" }),
  570. ]),
  571. })
  572. const attemptStarts = updates.filter((update) => update.metadata?.latest_event === "stage_started")
  573. const firstAttemptProgress = attemptStarts[0]?.metadata?.research67_progress
  574. const firstActiveSince =
  575. firstAttemptProgress && typeof firstAttemptProgress === "object" && "activeSince" in firstAttemptProgress
  576. ? firstAttemptProgress.activeSince
  577. : undefined
  578. expect(attemptStarts[1]?.metadata?.research67_progress).toMatchObject({
  579. activeSince: firstActiveSince,
  580. rows: expect.arrayContaining([
  581. expect.objectContaining({ id: "paper-writing:outline", status: "running", detail: "1/2" }),
  582. ]),
  583. })
  584. expect(attemptStarts[2]?.metadata?.research67_progress).toMatchObject({
  585. activeSince: expect.any(Number),
  586. rows: expect.arrayContaining([
  587. expect.objectContaining({ id: "paper-writing:outline", status: "running", detail: undefined }),
  588. expect.objectContaining({ id: "paper-writing:english", status: "pending", detail: undefined }),
  589. expect.objectContaining({ id: "paper-writing:compile", status: "pending", detail: undefined }),
  590. ]),
  591. })
  592. expect(result.metadata).toMatchObject({
  593. run_id: "run_failure",
  594. status: "failed",
  595. error_code: "AGENT_EXECUTION_FAILED",
  596. workspace_path: workspacePath,
  597. research67_progress: {
  598. rows: expect.arrayContaining([
  599. expect.objectContaining({ id: "paper-writing:outline", status: "failed" }),
  600. expect.objectContaining({ id: "paper-writing:compile", status: "failed" }),
  601. expect.objectContaining({ id: "paper-writing:report", status: "pending" }),
  602. ]),
  603. },
  604. })
  605. } finally {
  606. globalThis.fetch = originalFetch
  607. process.env.HOME = originalHome
  608. await rm(home, { recursive: true, force: true })
  609. }
  610. })
  611. test("cancels the remote run when the local request is aborted", async () => {
  612. const home = await mkdtemp(path.join(tmpdir(), "agentpaas-bridge-cancel-"))
  613. const originalHome = process.env.HOME
  614. const originalFetch = globalThis.fetch
  615. const abort = new AbortController()
  616. const cancelledRuns: string[] = []
  617. let markStarted: (() => void) | undefined
  618. const started = new Promise<void>((resolve) => {
  619. markStarted = resolve
  620. })
  621. try {
  622. process.env.HOME = home
  623. globalThis.fetch = Object.assign(
  624. async (input: URL | RequestInfo, init?: RequestInit) => {
  625. const pathname = new URL(input instanceof Request ? input.url : input.toString()).pathname
  626. if (pathname.endsWith("/verify")) return Response.json({ status: "verified", checks: [] })
  627. if (pathname === "/api/v1/agents") {
  628. return Response.json({
  629. agents: [{ id: "ag_pipeline", name: "Research67 三阶段研究草稿流水线" }],
  630. })
  631. }
  632. if (pathname === "/api/v1/agents/ag_pipeline/run/stream") {
  633. const body = new ReadableStream<Uint8Array>({
  634. start(controller) {
  635. controller.enqueue(
  636. new TextEncoder().encode('event: started\ndata: {"run_id":"run_abort","thread_id":"thread_abort"}\n\n'),
  637. )
  638. init?.signal?.addEventListener(
  639. "abort",
  640. () => controller.error(new DOMException("Aborted", "AbortError")),
  641. {
  642. once: true,
  643. },
  644. )
  645. },
  646. })
  647. return new Response(body, { headers: { "Content-Type": "text/event-stream" } })
  648. }
  649. if (pathname === "/api/v1/agents/ag_pipeline/runs/run_abort/cancel") {
  650. cancelledRuns.push("run_abort")
  651. return Response.json({ run_id: "run_abort", status: "cancelled" })
  652. }
  653. return new Response("not found", { status: 404 })
  654. },
  655. { preconnect: originalFetch.preconnect },
  656. )
  657. const configDir = path.join(home, ".agentpaas")
  658. await mkdir(configDir)
  659. await writeFile(
  660. path.join(configDir, "config.json"),
  661. JSON.stringify({ server: "http://agentpaas.test", api_key: "test-key" }),
  662. )
  663. const bridge = (await import(`../../../../.opencode/tool/agentpaas_run.ts?cancel=${Date.now()}`)).default
  664. const running = bridge.execute(
  665. { input: "调查课题", agent_name: "Research67 三阶段研究草稿流水线", mode: "iterate" },
  666. {
  667. sessionID: "session_abort",
  668. messageID: "message_abort",
  669. agent: "research-67-pipeline",
  670. directory: "/workspace",
  671. worktree: "/workspace",
  672. abort: abort.signal,
  673. metadata: (update: { metadata?: Record<string, unknown> }) => {
  674. if (update.metadata?.run_id === "run_abort") markStarted?.()
  675. },
  676. ask: async () => undefined,
  677. },
  678. )
  679. await started
  680. abort.abort()
  681. await expect(running).rejects.toThrow("Aborted")
  682. expect(cancelledRuns).toEqual(["run_abort"])
  683. } finally {
  684. globalThis.fetch = originalFetch
  685. process.env.HOME = originalHome
  686. await rm(home, { recursive: true, force: true })
  687. }
  688. })
  689. test("reuses AgentPaaS thread and workspace across one OpenCode session", async () => {
  690. const home = await mkdtemp(path.join(tmpdir(), "agentpaas-conversation-"))
  691. const originalHome = process.env.HOME
  692. const originalFetch = globalThis.fetch
  693. const bodies: Array<Record<string, unknown>> = []
  694. let run = 0
  695. try {
  696. process.env.HOME = home
  697. globalThis.fetch = Object.assign(
  698. async (input: URL | RequestInfo, init?: RequestInit) => {
  699. const pathname = new URL(input instanceof Request ? input.url : input.toString()).pathname
  700. if (pathname.endsWith("/verify")) return Response.json({ status: "verified", checks: [] })
  701. if (pathname === "/api/v1/agents") {
  702. return Response.json({ agents: [{ id: "ag_research67", name: "research67" }] })
  703. }
  704. if (pathname === "/api/v1/agents/ag_research67/run/stream") {
  705. if (typeof init?.body !== "string") throw new Error("run body must be JSON")
  706. bodies.push(JSON.parse(init.body))
  707. run++
  708. const threadID = run < 3 ? "th_research" : "th_new"
  709. const body = [
  710. `event: started\ndata: ${JSON.stringify({ run_id: `run_${run}`, thread_id: threadID })}`,
  711. `event: done\ndata: ${JSON.stringify({
  712. run_id: `run_${run}`,
  713. thread_id: threadID,
  714. status: "completed",
  715. output: `answer ${run}`,
  716. })}`,
  717. ].join("\n\n")
  718. return new Response(`${body}\n\n`, { headers: { "Content-Type": "text/event-stream" } })
  719. }
  720. return new Response("not found", { status: 404 })
  721. },
  722. { preconnect: originalFetch.preconnect },
  723. )
  724. const configDir = path.join(home, ".agentpaas")
  725. await mkdir(configDir)
  726. await writeFile(
  727. path.join(configDir, "config.json"),
  728. JSON.stringify({ server: "http://agentpaas.test", api_key: "test-key" }),
  729. )
  730. const bridge = (await import(`../../../../.opencode/tool/agentpaas_run.ts?conversation=${Date.now()}`)).default
  731. const context = {
  732. sessionID: "session_research",
  733. messageID: "message_research",
  734. agent: "research67",
  735. directory: "/host/workspace",
  736. worktree: "/host/workspace",
  737. abort: new AbortController().signal,
  738. metadata: () => undefined,
  739. ask: async () => undefined,
  740. }
  741. await bridge.execute(
  742. { input: "先讨论问题", agent_name: "research67", mode: "chat", conversation: "continue" },
  743. context,
  744. )
  745. await bridge.execute(
  746. { input: "继续并查看产物", agent_name: "research67", mode: "chat", conversation: "continue" },
  747. context,
  748. )
  749. await bridge.execute({ input: "开始新课题", agent_name: "research67", mode: "chat", conversation: "new" }, context)
  750. expect(bodies[0]).toMatchObject({ thread_id: "", context: {} })
  751. expect(bodies[1]).toMatchObject({ thread_id: "th_research", context: { run_id: "run_1" } })
  752. expect(bodies[2]).toMatchObject({ thread_id: "", context: {} })
  753. expect(JSON.stringify(bodies)).not.toContain("/host/workspace")
  754. } finally {
  755. globalThis.fetch = originalFetch
  756. process.env.HOME = originalHome
  757. await rm(home, { recursive: true, force: true })
  758. }
  759. })