| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772 |
- import { expect, test } from "bun:test"
- import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"
- import { tmpdir } from "node:os"
- import path from "node:path"
- test("shows pipeline stages and resolves remote confirmations", async () => {
- const home = await mkdtemp(path.join(tmpdir(), "agentpaas-bridge-"))
- const originalHome = process.env.HOME
- const originalFetch = globalThis.fetch
- const updates: Array<{ title?: string; metadata?: Record<string, unknown> }> = []
- const confirmationBodies: unknown[] = []
- const permissionRequests: Array<{
- permission: string
- patterns: string[]
- always: string[]
- metadata: Record<string, unknown>
- }> = []
- const events: Array<[string, unknown]> = [
- ["started", { run_id: "run_1", thread_id: "thread_1" }],
- [
- "stage_started",
- {
- pipeline_id: "research67-one-round",
- stage_id: "idea-analysis",
- stage_name: "创意分析",
- attempt: 1,
- status: "running",
- },
- ],
- ["tool_call", { tool: "WriteFile", step: 1, content: '{"file_path":"/run/idea-analysis/work_plan.md"}' }],
- ["tool_result", { tool: "WriteFile", step: 1, content: "[OK] Created work_plan.md" }],
- [
- "tool_call",
- { tool: "WriteFile", step: 1, content: '{"file_path":"/run/idea-analysis/artifacts/search_queries.json"}' },
- ],
- ["tool_result", { tool: "WriteFile", step: 1, content: "[OK] Created search_queries.json" }],
- [
- "tool_call",
- { tool: "WriteFile", step: 1, content: '{"file_path":"/run/idea-analysis/artifacts/similar_papers.json"}' },
- ],
- ["tool_result", { tool: "WriteFile", step: 1, content: "[OK] Created similar_papers.json" }],
- ["tool_call", { tool: "WriteFile", step: 1, content: '{"file_path":"/run/idea-analysis/report.json"}' }],
- ["tool_result", { tool: "WriteFile", step: 1, content: "[OK] Created report.json" }],
- ["tool_call", { tool: "WriteFile", step: 1, content: '{"file_path":"/run/idea-analysis/report.md"}' }],
- ["tool_result", { tool: "WriteFile", step: 1, content: "[OK] Created report.md" }],
- [
- "stage_passed",
- {
- pipeline_id: "research67-one-round",
- stage_id: "idea-analysis",
- stage_name: "创意分析",
- attempt: 1,
- status: "passed",
- },
- ],
- [
- "stage_started",
- {
- pipeline_id: "research67-one-round",
- stage_id: "literature-review",
- stage_name: "文献检索",
- attempt: 1,
- status: "running",
- },
- ],
- [
- "tool_call",
- { tool: "ReadFile", step: "lit-upstream", content: "{'file_path':'/run/idea-analysis/report.json'}" },
- ],
- ["tool_result", { tool: "ReadFile", step: "lit-upstream", content: "idea analysis report" }],
- [
- "confirm_required",
- {
- run_id: "run_1",
- tool: "Shell",
- approval_id: "tc_shell",
- reason: "high-risk command",
- input: "rm generated.tmp",
- },
- ],
- ["think_chunk", { text: "检索中" }],
- ["tool_call", { tool: "arxiv_search", step: 2, content: '{"query":"topic-specific words","limit":10}' }],
- ["tool_result", { tool: "arxiv_search", step: 2, content: '{"status":"completed","result_count":10}' }],
- [
- "tool_call",
- { tool: "WriteFile", step: 3, content: '{"file_path":"/run/literature-review/artifacts/papers_selected.json"}' },
- ],
- ["tool_result", { tool: "WriteFile", step: 3, content: "[OK] Created papers_selected.json" }],
- [
- "confirm_required",
- {
- run_id: "run_1",
- tool: "WriteFile",
- approval_id: "tc_write",
- reason: "overwrite existing file",
- input: "report.json",
- },
- ],
- [
- "stage_passed",
- {
- pipeline_id: "research67-one-round",
- stage_id: "literature-review",
- stage_name: "文献检索",
- attempt: 1,
- status: "passed",
- },
- ],
- [
- "stage_started",
- {
- pipeline_id: "research67-one-round",
- stage_id: "paper-writing",
- stage_name: "实验前研究草稿撰写",
- attempt: 1,
- status: "running",
- },
- ],
- [
- "tool_call",
- {
- tool: "ReadFile",
- step: "paper-upstream",
- content: '{"file_path":"/run/literature-review/report.json"}',
- },
- ],
- ["tool_result", { tool: "ReadFile", step: "paper-upstream", content: "literature review report" }],
- [
- "tool_call",
- {
- tool: "WriteFile",
- step: "paper-scratch",
- content: '{"file_path":"/run/paper-writing/scratch.md","content":"later write /run/paper-writing/report.json"}',
- },
- ],
- ["tool_result", { tool: "WriteFile", step: "paper-scratch", content: "[OK] Created scratch.md" }],
- ["tool_call", { tool: "WriteFile", step: 4, content: '{"file_path":"/run/paper-writing/artifacts/outline.json"}' }],
- ["tool_result", { tool: "WriteFile", step: 4, content: "[OK] Created outline.json" }],
- [
- "tool_call",
- { tool: "WriteFile", step: 5, content: '{"file_path":"/run/paper-writing/artifacts/sections/abstract.tex"}' },
- ],
- ["tool_result", { tool: "WriteFile", step: 5, content: "[OK] Created abstract.tex" }],
- [
- "tool_call",
- {
- tool: "BuildResearchPaper",
- step: 6,
- content:
- '{"phase_dir":"/run/paper-writing","papers_selected_path":"/run/literature-review/artifacts/papers_selected.json"}',
- },
- ],
- ["tool_result", { tool: "BuildResearchPaper", step: 6, content: '{"status":"failed","passed":false}' }],
- [
- "tool_call",
- {
- tool: "WriteFile",
- step: "paper-repair",
- content: '{"file_path":"/run/paper-writing/artifacts/sections/abstract.tex"}',
- },
- ],
- ["tool_result", { tool: "WriteFile", step: "paper-repair", content: "[OK] Updated abstract.tex" }],
- [
- "tool_call",
- {
- tool: "BuildResearchPaper",
- step: 7,
- content:
- '{"phase_dir":"/run/paper-writing","papers_selected_path":"/run/literature-review/artifacts/papers_selected.json"}',
- },
- ],
- ["tool_result", { tool: "BuildResearchPaper", step: 7, content: '{"status":"completed","passed":true}' }],
- ["tool_call", { tool: "WriteFile", step: 8, content: '{"file_path":"/run/paper-writing/report.json"}' }],
- ["tool_call", { tool: "WriteFile", step: 8, content: '{"file_path":"/run/paper-writing/report.md"}' }],
- ["tool_result", { tool: "WriteFile", step: 8, content: "[OK] Created report.json" }],
- ["tool_result", { tool: "WriteFile", step: 8, content: "[OK] Created report.md" }],
- [
- "stage_passed",
- {
- pipeline_id: "research67-one-round",
- stage_id: "paper-writing",
- stage_name: "实验前研究草稿撰写",
- attempt: 1,
- status: "passed",
- },
- ],
- ["pipeline_completed", { pipeline_id: "research67-one-round", status: "completed" }],
- ["done", { run_id: "run_1", thread_id: "thread_1", status: "completed", output: "完成" }],
- ]
- try {
- process.env.HOME = home
- globalThis.fetch = Object.assign(
- async (input: URL | RequestInfo, init?: RequestInit) => {
- const pathname = new URL(input instanceof Request ? input.url : input.toString()).pathname
- if (pathname.endsWith("/verify")) return Response.json({ status: "verified", checks: [] })
- if (pathname === "/api/v1/agents") {
- return Response.json({
- agents: [{ id: "ag_pipeline", name: "Research67 三阶段研究草稿流水线" }],
- })
- }
- if (pathname === "/api/v1/agents/ag_pipeline/run/stream") {
- const body =
- events
- .map(
- ([event, data], index) =>
- `event: ${event}\ndata: ${JSON.stringify(data)}${index === 5 ? "\n\n: heartbeat" : ""}`,
- )
- .join("\n\n") + "\n\n"
- return new Response(body, { headers: { "Content-Type": "text/event-stream" } })
- }
- if (pathname === "/api/v1/agents/ag_pipeline/runs/run_1")
- return Response.json({
- status: "running",
- pending_confirmation: {
- approval_id: confirmationBodies.length ? "tc_write" : "tc_shell",
- status: "pending",
- },
- })
- if (pathname === "/api/v1/traces/run_1/confirm") {
- if (typeof init?.body !== "string") throw new Error("confirmation body must be JSON")
- confirmationBodies.push(JSON.parse(init.body))
- return Response.json({ run_id: "run_1", status: "confirmed" })
- }
- return new Response("not found", { status: 404 })
- },
- { preconnect: originalFetch.preconnect },
- )
- const configDir = path.join(home, ".agentpaas")
- await mkdir(configDir)
- await writeFile(
- path.join(configDir, "config.json"),
- JSON.stringify({ server: "http://agentpaas.test", api_key: "test-key" }),
- )
- const bridge = (await import(`../../../../.opencode/tool/agentpaas_run.ts?test=${Date.now()}`)).default
- const result = await bridge.execute(
- {
- input: "调查课题",
- agent_name: "Research67 三阶段研究草稿流水线",
- mode: "iterate",
- },
- {
- sessionID: "session_1",
- messageID: "message_1",
- agent: "research-67-pipeline",
- directory: "/workspace",
- worktree: "/workspace",
- abort: new AbortController().signal,
- metadata: (update: (typeof updates)[number]) => updates.push(update),
- ask: async (request: (typeof permissionRequests)[number]) => {
- permissionRequests.push(request)
- if (permissionRequests.length === 2) throw new Error("denied")
- },
- },
- )
- expect(updates.map((update) => update.title).join("\n")).not.toContain("正在调用")
- expect(updates.map((update) => update.title).join("\n")).not.toContain("arxiv_search")
- expect(JSON.stringify(updates.map((update) => update.metadata?.research67_progress))).not.toContain(
- "topic-specific words",
- )
- expect(updates).toContainEqual(
- expect.objectContaining({
- metadata: expect.objectContaining({
- latest_event: "heartbeat",
- research67_progress: expect.objectContaining({ activeSince: expect.any(Number) }),
- }),
- }),
- )
- expect(JSON.stringify(updates)).not.toContain("连接正常")
- const snapshots = updates.flatMap((update) => {
- const value = update.metadata?.research67_progress
- return value && typeof value === "object" ? [Object.fromEntries(Object.entries(value))] : []
- })
- expect(snapshots.some((snapshot) => snapshot.title === "Research67 · idea-analyst · 创意分析 · 制定分析计划")).toBe(
- true,
- )
- expect(snapshots).toContainEqual(
- expect.objectContaining({
- rows: expect.arrayContaining([
- expect.objectContaining({ id: "idea-analysis:plan", status: "completed" }),
- expect.objectContaining({ id: "idea-analysis:directions", status: "running" }),
- ]),
- }),
- )
- const litUpstream = updates.find(
- (update) => update.metadata?.latest_event === "tool_result" && update.metadata.step === "lit-upstream",
- )?.metadata?.research67_progress
- expect(litUpstream).toMatchObject({
- title: "Research67 · lit-searcher · 文献检索 · 制定检索计划",
- rows: expect.arrayContaining([
- expect.objectContaining({ id: "literature-review:plan", status: "running" }),
- expect.objectContaining({ id: "literature-review:report", status: "pending" }),
- ]),
- })
- expect(snapshots).toContainEqual(
- expect.objectContaining({
- footer: "正在进行 Guard / 阶段产物验收",
- activeSince: expect.any(Number),
- rows: expect.arrayContaining([expect.objectContaining({ id: "idea-analysis:report", status: "completed" })]),
- }),
- )
- for (const step of ["paper-upstream", "paper-scratch"]) {
- expect(
- updates.find((update) => update.metadata?.latest_event === "tool_result" && update.metadata.step === step)
- ?.metadata?.research67_progress,
- ).toMatchObject({
- title: "Research67 · paper-writer · 论文写作 · 写作计划与大纲",
- rows: expect.arrayContaining([
- expect.objectContaining({ id: "paper-writing:outline", status: "running" }),
- expect.objectContaining({ id: "paper-writing:compile", status: "pending" }),
- expect.objectContaining({ id: "paper-writing:report", status: "pending" }),
- ]),
- })
- }
- expect(
- updates.find(
- (update) =>
- update.metadata?.latest_event === "tool_result" &&
- update.metadata.latest_tool === "BuildResearchPaper" &&
- update.metadata.step === 6,
- )?.metadata?.research67_progress,
- ).toMatchObject({
- rows: expect.arrayContaining([
- expect.objectContaining({ id: "paper-writing:compile", status: "failed" }),
- expect.objectContaining({ id: "paper-writing:report", status: "pending" }),
- ]),
- footer: "当前操作失败,等待重试",
- })
- expect(
- updates.find(
- (update) => update.metadata?.latest_event === "tool_result" && update.metadata.step === "paper-repair",
- )?.metadata?.research67_progress,
- ).toMatchObject({
- rows: expect.arrayContaining([
- expect.objectContaining({ id: "paper-writing:compile", status: "pending" }),
- expect.objectContaining({ id: "paper-writing:report", status: "pending" }),
- ]),
- footer: "论文源文件已更新,等待重新编译",
- })
- expect(
- updates.find(
- (update) =>
- update.metadata?.latest_event === "tool_call" &&
- update.metadata.latest_tool === "BuildResearchPaper" &&
- update.metadata.step === 7,
- )?.metadata?.research67_progress,
- ).toMatchObject({
- title: "Research67 · paper-writer · 论文写作 · 编译双语 PDF",
- rows: expect.arrayContaining([expect.objectContaining({ id: "paper-writing:compile", status: "running" })]),
- })
- expect(snapshots).toContainEqual(
- expect.objectContaining({
- rows: expect.arrayContaining([
- expect.objectContaining({
- id: "literature-review:search",
- status: "running",
- detail: "已完成 1 轮检索",
- }),
- ]),
- }),
- )
- expect(snapshots).toContainEqual(
- expect.objectContaining({
- rows: expect.arrayContaining([
- expect.objectContaining({ id: "literature-review:search", status: "completed" }),
- expect.objectContaining({ id: "literature-review:select", status: "running" }),
- ]),
- }),
- )
- expect(snapshots).toContainEqual(
- expect.objectContaining({
- rows: expect.arrayContaining([
- expect.objectContaining({ id: "literature-review:select", status: "completed" }),
- expect.objectContaining({ id: "literature-review:report", status: "running" }),
- ]),
- }),
- )
- expect(snapshots).toContainEqual(
- expect.objectContaining({
- rows: expect.arrayContaining([
- expect.objectContaining({ id: "paper-writing:english", status: "running", detail: "1/8" }),
- ]),
- }),
- )
- expect(snapshots).toContainEqual(
- expect.objectContaining({
- rows: expect.arrayContaining([
- expect.objectContaining({ id: "paper-writing:compile", status: "completed" }),
- expect.objectContaining({ id: "paper-writing:report", status: "running" }),
- ]),
- }),
- )
- expect(snapshots).toContainEqual(
- expect.objectContaining({
- footer: "正在进行 Guard / 阶段产物验收",
- rows: expect.arrayContaining([
- expect.objectContaining({ id: "paper-writing:report", status: "completed", detail: undefined }),
- ]),
- }),
- )
- expect(updates.at(-1)?.metadata).toMatchObject({
- pipeline_id: "research67-one-round",
- stage_id: "paper-writing",
- stage_status: "passed",
- pipeline_status: "completed",
- status: "completed",
- research67_progress: {
- kind: "research67",
- rows: [
- expect.objectContaining({ id: "idea-analysis", status: "completed" }),
- expect.objectContaining({ id: "literature-review", status: "completed" }),
- expect.objectContaining({ id: "paper-writing", status: "completed" }),
- ],
- },
- })
- expect(permissionRequests).toHaveLength(2)
- expect(permissionRequests[0]).toEqual({
- permission: "agentpaas_confirm",
- patterns: ["ag_pipeline:run_1:tc_shell"],
- always: [],
- metadata: {
- run_id: "run_1",
- approval_id: "tc_shell",
- agent_name: "Research67 三阶段研究草稿流水线",
- tool: "Shell",
- reason: "high-risk command",
- input: "rm generated.tmp",
- },
- })
- expect(permissionRequests[1]).toMatchObject({
- permission: "agentpaas_confirm",
- patterns: ["ag_pipeline:run_1:tc_write"],
- metadata: { tool: "WriteFile", reason: "overwrite existing file", input: "report.json" },
- })
- expect(confirmationBodies).toEqual([
- { approved: true, approval_id: "tc_shell" },
- { approved: false, approval_id: "tc_write" },
- ])
- expect(result).toMatchObject({ output: expect.stringContaining("完成") })
- } finally {
- globalThis.fetch = originalFetch
- process.env.HOME = originalHome
- await rm(home, { recursive: true, force: true })
- }
- })
- test("preserves completed artifacts and forbids automatic reruns after failure", async () => {
- const home = await mkdtemp(path.join(tmpdir(), "agentpaas-bridge-failure-"))
- const originalHome = process.env.HOME
- const originalFetch = globalThis.fetch
- const updates: Array<{ title?: string; metadata?: Record<string, unknown> }> = []
- const workspacePath = "/workspace/runs/run_failure"
- const events: Array<[string, unknown]> = [
- ["started", { run_id: "run_failure", thread_id: "thread_failure" }],
- [
- "stage_started",
- {
- pipeline_id: "research67-one-round",
- stage_id: "paper-writing",
- stage_name: "实验前研究草稿撰写",
- attempt: 1,
- status: "running",
- },
- ],
- ["tool_call", { tool: "WriteFile", content: '{"file_path":"/run/paper-writing/artifacts/outline.json"}' }],
- ["tool_result", { tool: "WriteFile", content: "[OK] Created outline.json" }],
- [
- "stage_started",
- {
- pipeline_id: "research67-one-round",
- stage_id: "paper-writing",
- stage_name: "实验前研究草稿撰写",
- attempt: 1,
- status: "running",
- },
- ],
- ["tool_call", { tool: "CompileLatex", content: '{"tex_path":"/run/paper-writing/artifacts/paper.tex"}' }],
- ["tool_result", { tool: "CompileLatex", content: "[TOOL_ERROR] UnicodeDecodeError" }],
- [
- "tool_call",
- {
- tool: "WriteFile",
- step: "repair",
- content: '{"file_path":"/run/paper-writing/artifacts/paper.tex"}',
- },
- ],
- ["tool_result", { tool: "WriteFile", step: "repair", content: "[OK] Updated paper.tex" }],
- [
- "stage_started",
- {
- pipeline_id: "research67-one-round",
- stage_id: "paper-writing",
- stage_name: "实验前研究草稿撰写",
- attempt: 2,
- status: "running",
- },
- ],
- ["tool_call", { tool: "CompileLatex", content: '{"tex_path":"/run/paper-writing/artifacts/paper.tex"}' }],
- ["tool_result", { tool: "CompileLatex", content: "[TOOL_ERROR] UnicodeDecodeError" }],
- [
- "stage_failed",
- {
- pipeline_id: "research67-one-round",
- stage_id: "paper-writing",
- stage_name: "实验前研究草稿撰写",
- attempt: 2,
- status: "failed",
- error: "Native function-calling loop produced no final output",
- },
- ],
- [
- "error",
- {
- code: "AGENT_EXECUTION_FAILED",
- message: "Native function-calling loop produced no final output",
- workspace_path: workspacePath,
- },
- ],
- ["done", { run_id: "run_failure", thread_id: "thread_failure", status: "failed" }],
- ]
- try {
- process.env.HOME = home
- globalThis.fetch = Object.assign(
- async (input: URL | RequestInfo) => {
- const pathname = new URL(input instanceof Request ? input.url : input.toString()).pathname
- if (pathname.endsWith("/verify")) return Response.json({ status: "verified", checks: [] })
- if (pathname === "/api/v1/agents") {
- return Response.json({
- agents: [{ id: "ag_pipeline", name: "Research67 三阶段研究草稿流水线" }],
- })
- }
- if (pathname === "/api/v1/agents/ag_pipeline/run/stream") {
- const body =
- events.map(([event, data]) => `event: ${event}\ndata: ${JSON.stringify(data)}`).join("\n\n") + "\n\n"
- return new Response(body, { headers: { "Content-Type": "text/event-stream" } })
- }
- return new Response("not found", { status: 404 })
- },
- { preconnect: originalFetch.preconnect },
- )
- const configDir = path.join(home, ".agentpaas")
- await mkdir(configDir)
- await writeFile(
- path.join(configDir, "config.json"),
- JSON.stringify({ server: "http://agentpaas.test", api_key: "test-key" }),
- )
- const bridge = (await import(`../../../../.opencode/tool/agentpaas_run.ts?failure=${Date.now()}`)).default
- const result = await bridge.execute(
- { input: "调查课题", agent_name: "Research67 三阶段研究草稿流水线", mode: "iterate" },
- {
- sessionID: "session_failure",
- messageID: "message_failure",
- agent: "research-67-pipeline",
- directory: "/workspace",
- worktree: "/workspace",
- abort: new AbortController().signal,
- metadata: (update: (typeof updates)[number]) => updates.push(update),
- ask: async () => undefined,
- },
- )
- expect(result.output).toContain("Native function-calling loop produced no final output")
- expect(result.output).toContain(workspacePath)
- expect(result.output).toContain("失败严禁自动重跑、拆分任务或调用其他 subagent")
- expect(
- updates.find((update) => update.metadata?.latest_event === "tool_result" && update.metadata.step === "repair")
- ?.metadata?.research67_progress,
- ).toMatchObject({
- title: "Research67 · paper-writer · 论文写作 · 英文稿与参考文献",
- footer: "论文源文件已更新,等待重新编译",
- rows: expect.arrayContaining([
- expect.objectContaining({ id: "paper-writing:english", status: "running" }),
- expect.objectContaining({ id: "paper-writing:compile", status: "pending" }),
- ]),
- })
- const attemptStarts = updates.filter((update) => update.metadata?.latest_event === "stage_started")
- const firstAttemptProgress = attemptStarts[0]?.metadata?.research67_progress
- const firstActiveSince =
- firstAttemptProgress && typeof firstAttemptProgress === "object" && "activeSince" in firstAttemptProgress
- ? firstAttemptProgress.activeSince
- : undefined
- expect(attemptStarts[1]?.metadata?.research67_progress).toMatchObject({
- activeSince: firstActiveSince,
- rows: expect.arrayContaining([
- expect.objectContaining({ id: "paper-writing:outline", status: "running", detail: "1/2" }),
- ]),
- })
- expect(attemptStarts[2]?.metadata?.research67_progress).toMatchObject({
- activeSince: expect.any(Number),
- rows: expect.arrayContaining([
- expect.objectContaining({ id: "paper-writing:outline", status: "running", detail: undefined }),
- expect.objectContaining({ id: "paper-writing:english", status: "pending", detail: undefined }),
- expect.objectContaining({ id: "paper-writing:compile", status: "pending", detail: undefined }),
- ]),
- })
- expect(result.metadata).toMatchObject({
- run_id: "run_failure",
- status: "failed",
- error_code: "AGENT_EXECUTION_FAILED",
- workspace_path: workspacePath,
- research67_progress: {
- rows: expect.arrayContaining([
- expect.objectContaining({ id: "paper-writing:outline", status: "failed" }),
- expect.objectContaining({ id: "paper-writing:compile", status: "failed" }),
- expect.objectContaining({ id: "paper-writing:report", status: "pending" }),
- ]),
- },
- })
- } finally {
- globalThis.fetch = originalFetch
- process.env.HOME = originalHome
- await rm(home, { recursive: true, force: true })
- }
- })
- test("cancels the remote run when the local request is aborted", async () => {
- const home = await mkdtemp(path.join(tmpdir(), "agentpaas-bridge-cancel-"))
- const originalHome = process.env.HOME
- const originalFetch = globalThis.fetch
- const abort = new AbortController()
- const cancelledRuns: string[] = []
- let markStarted: (() => void) | undefined
- const started = new Promise<void>((resolve) => {
- markStarted = resolve
- })
- try {
- process.env.HOME = home
- globalThis.fetch = Object.assign(
- async (input: URL | RequestInfo, init?: RequestInit) => {
- const pathname = new URL(input instanceof Request ? input.url : input.toString()).pathname
- if (pathname.endsWith("/verify")) return Response.json({ status: "verified", checks: [] })
- if (pathname === "/api/v1/agents") {
- return Response.json({
- agents: [{ id: "ag_pipeline", name: "Research67 三阶段研究草稿流水线" }],
- })
- }
- if (pathname === "/api/v1/agents/ag_pipeline/run/stream") {
- const body = new ReadableStream<Uint8Array>({
- start(controller) {
- controller.enqueue(
- new TextEncoder().encode('event: started\ndata: {"run_id":"run_abort","thread_id":"thread_abort"}\n\n'),
- )
- init?.signal?.addEventListener(
- "abort",
- () => controller.error(new DOMException("Aborted", "AbortError")),
- {
- once: true,
- },
- )
- },
- })
- return new Response(body, { headers: { "Content-Type": "text/event-stream" } })
- }
- if (pathname === "/api/v1/agents/ag_pipeline/runs/run_abort/cancel") {
- cancelledRuns.push("run_abort")
- return Response.json({ run_id: "run_abort", status: "cancelled" })
- }
- return new Response("not found", { status: 404 })
- },
- { preconnect: originalFetch.preconnect },
- )
- const configDir = path.join(home, ".agentpaas")
- await mkdir(configDir)
- await writeFile(
- path.join(configDir, "config.json"),
- JSON.stringify({ server: "http://agentpaas.test", api_key: "test-key" }),
- )
- const bridge = (await import(`../../../../.opencode/tool/agentpaas_run.ts?cancel=${Date.now()}`)).default
- const running = bridge.execute(
- { input: "调查课题", agent_name: "Research67 三阶段研究草稿流水线", mode: "iterate" },
- {
- sessionID: "session_abort",
- messageID: "message_abort",
- agent: "research-67-pipeline",
- directory: "/workspace",
- worktree: "/workspace",
- abort: abort.signal,
- metadata: (update: { metadata?: Record<string, unknown> }) => {
- if (update.metadata?.run_id === "run_abort") markStarted?.()
- },
- ask: async () => undefined,
- },
- )
- await started
- abort.abort()
- await expect(running).rejects.toThrow("Aborted")
- expect(cancelledRuns).toEqual(["run_abort"])
- } finally {
- globalThis.fetch = originalFetch
- process.env.HOME = originalHome
- await rm(home, { recursive: true, force: true })
- }
- })
- test("reuses AgentPaaS thread and workspace across one OpenCode session", async () => {
- const home = await mkdtemp(path.join(tmpdir(), "agentpaas-conversation-"))
- const originalHome = process.env.HOME
- const originalFetch = globalThis.fetch
- const bodies: Array<Record<string, unknown>> = []
- let run = 0
- try {
- process.env.HOME = home
- globalThis.fetch = Object.assign(
- async (input: URL | RequestInfo, init?: RequestInit) => {
- const pathname = new URL(input instanceof Request ? input.url : input.toString()).pathname
- if (pathname.endsWith("/verify")) return Response.json({ status: "verified", checks: [] })
- if (pathname === "/api/v1/agents") {
- return Response.json({ agents: [{ id: "ag_research67", name: "research67" }] })
- }
- if (pathname === "/api/v1/agents/ag_research67/run/stream") {
- if (typeof init?.body !== "string") throw new Error("run body must be JSON")
- bodies.push(JSON.parse(init.body))
- run++
- const threadID = run < 3 ? "th_research" : "th_new"
- const body = [
- `event: started\ndata: ${JSON.stringify({ run_id: `run_${run}`, thread_id: threadID })}`,
- `event: done\ndata: ${JSON.stringify({
- run_id: `run_${run}`,
- thread_id: threadID,
- status: "completed",
- output: `answer ${run}`,
- })}`,
- ].join("\n\n")
- return new Response(`${body}\n\n`, { headers: { "Content-Type": "text/event-stream" } })
- }
- return new Response("not found", { status: 404 })
- },
- { preconnect: originalFetch.preconnect },
- )
- const configDir = path.join(home, ".agentpaas")
- await mkdir(configDir)
- await writeFile(
- path.join(configDir, "config.json"),
- JSON.stringify({ server: "http://agentpaas.test", api_key: "test-key" }),
- )
- const bridge = (await import(`../../../../.opencode/tool/agentpaas_run.ts?conversation=${Date.now()}`)).default
- const context = {
- sessionID: "session_research",
- messageID: "message_research",
- agent: "research67",
- directory: "/host/workspace",
- worktree: "/host/workspace",
- abort: new AbortController().signal,
- metadata: () => undefined,
- ask: async () => undefined,
- }
- await bridge.execute(
- { input: "先讨论问题", agent_name: "research67", mode: "chat", conversation: "continue" },
- context,
- )
- await bridge.execute(
- { input: "继续并查看产物", agent_name: "research67", mode: "chat", conversation: "continue" },
- context,
- )
- await bridge.execute({ input: "开始新课题", agent_name: "research67", mode: "chat", conversation: "new" }, context)
- expect(bodies[0]).toMatchObject({ thread_id: "", context: {} })
- expect(bodies[1]).toMatchObject({ thread_id: "th_research", context: { run_id: "run_1" } })
- expect(bodies[2]).toMatchObject({ thread_id: "", context: {} })
- expect(JSON.stringify(bodies)).not.toContain("/host/workspace")
- } finally {
- globalThis.fetch = originalFetch
- process.env.HOME = originalHome
- await rm(home, { recursive: true, force: true })
- }
- })
|