task-output-tool.test.ts 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366
  1. import { mkdtemp, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import {
  6. HookEventName,
  7. SessionEventType,
  8. TASK_OUTPUT_PROVIDER_DESCRIPTION,
  9. TASK_OUTPUT_TOOL_NAME,
  10. createRootTraceContext,
  11. createSessionId,
  12. createToolCallId,
  13. createTurnId,
  14. type BackgroundExecutionSnapshot,
  15. type ExecutionResult,
  16. } from "@zcode/contracts";
  17. import { createInMemoryHookRunner } from "../src/hooks/index.js";
  18. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  19. import {
  20. InMemoryRuntimeTaskRegistry,
  21. type RuntimeTaskSnapshot,
  22. } from "../src/runtime-task/registry.js";
  23. import { createToolExecutor } from "../src/tool/executor.js";
  24. import { claimRuntimeBackgroundTaskNotification } from "../src/tool/executor/background-task-registry.js";
  25. import { BackgroundTaskTracker } from "../src/tool/executor/background-tasks.js";
  26. import {
  27. formatTaskOutputModelContent,
  28. resolveTaskOutputLength,
  29. taskOutputToolEntry,
  30. truncateTaskOutput,
  31. } from "../src/tool/handlers/task-output.js";
  32. import { createToolRegistry } from "../src/tool/registry.js";
  33. import type { ToolExecutionContext } from "../src/tool/types.js";
  34. afterEach(() => {
  35. vi.useRealTimers();
  36. vi.unstubAllEnvs();
  37. });
  38. describe("TaskOutput tool", () => {
  39. it("exposes the canonical provider contract and local-only aliases", () => {
  40. const registry = createToolRegistry();
  41. registry.register(taskOutputToolEntry);
  42. expect(registry.toContracts()).toEqual([
  43. expect.objectContaining({
  44. name: TASK_OUTPUT_TOOL_NAME,
  45. description: TASK_OUTPUT_PROVIDER_DESCRIPTION,
  46. inputSchema: taskOutputToolEntry.inputSchema,
  47. readOnly: true,
  48. concurrentSafe: true,
  49. needsApproval: false,
  50. sideEffectScope: "none",
  51. }),
  52. ]);
  53. expect(registry.toContracts()).toHaveLength(1);
  54. for (const alias of ["AgentOutputTool", "BashOutputTool", "AgentOutput", "BashOutput"]) {
  55. expect(registry.get(alias)?.handler).toBe(taskOutputToolEntry.handler);
  56. }
  57. });
  58. it("returns not_ready for a running Agent even when its output file is absent", async () => {
  59. const registry = registryWithTask(runtimeTask());
  60. const output = await taskOutputToolEntry.handler(
  61. { task_id: "agent_1", block: false },
  62. toolContext(registry),
  63. );
  64. expect(output).toMatchObject({
  65. retrieval_status: "not_ready",
  66. task: {
  67. task_id: "agent_1",
  68. task_type: "local_agent",
  69. status: "running",
  70. output: "",
  71. },
  72. });
  73. });
  74. it("marks terminal tasks notified and emits the provider result XML", async () => {
  75. const registry = registryWithTask(
  76. runtimeTask({
  77. status: "completed",
  78. output: completedAgentOutput("answer <raw>&\n"),
  79. }),
  80. );
  81. const output = await taskOutputToolEntry.handler(
  82. { task_id: "agent_1", block: false },
  83. toolContext(registry),
  84. );
  85. expect(registry.get("agent_1")?.notified).toBe(true);
  86. expect(formatTaskOutputModelContent(output)).toBe(
  87. [
  88. "<retrieval_status>success</retrieval_status>",
  89. "<task_id>agent_1</task_id>",
  90. "<task_type>local_agent</task_type>",
  91. "<status>completed</status>",
  92. "<output>\nanswer <raw>&\n</output>",
  93. ].join("\n\n"),
  94. );
  95. });
  96. it.each([false, true])(
  97. "does not consume the completion claim when terminal projection fails (block=%s)",
  98. async (block) => {
  99. const taskId = `bash_projection_failure_${String(block)}`;
  100. const registry = registryWithTask(
  101. runtimeTask({
  102. agentId: taskId,
  103. agentType: "local_bash",
  104. taskId,
  105. taskType: "local_bash",
  106. type: "local_bash",
  107. status: "completed",
  108. }),
  109. );
  110. await expect(
  111. taskOutputToolEntry.handler(
  112. { task_id: taskId, block, timeout: 100 },
  113. toolContext(registry, {
  114. executionPort: {
  115. getBackgroundTask: async () => {
  116. throw new Error("background snapshot unavailable");
  117. },
  118. } as never,
  119. }),
  120. ),
  121. ).rejects.toThrow("background snapshot unavailable");
  122. expect(registry.get(taskId)?.notified).not.toBe(true);
  123. },
  124. );
  125. it.each([false, true])(
  126. "does not consume the completion claim when aborted during terminal projection (block=%s)",
  127. async (block) => {
  128. const taskId = `bash_projection_abort_${String(block)}`;
  129. const registry = registryWithTask(
  130. runtimeTask({
  131. agentId: taskId,
  132. agentType: "local_bash",
  133. taskId,
  134. taskType: "local_bash",
  135. type: "local_bash",
  136. status: "completed",
  137. }),
  138. );
  139. const controller = new AbortController();
  140. const result = executionResult("finished", "", 0);
  141. let resolveSnapshot!: (snapshot: BackgroundExecutionSnapshot | undefined) => void;
  142. const snapshotPromise = new Promise<BackgroundExecutionSnapshot | undefined>((resolve) => {
  143. resolveSnapshot = resolve;
  144. });
  145. const outputPromise = taskOutputToolEntry.handler(
  146. { task_id: taskId, block, timeout: 100 },
  147. toolContext(registry, {
  148. abortSignal: controller.signal,
  149. executionPort: {
  150. getBackgroundTask: () => snapshotPromise,
  151. } as never,
  152. }),
  153. );
  154. controller.abort();
  155. resolveSnapshot({
  156. taskId,
  157. status: "completed",
  158. startedAt: result.startedAt,
  159. completedAt: result.completedAt,
  160. result,
  161. });
  162. await expect(outputPromise).rejects.toMatchObject({ name: "AbortError" });
  163. expect(registry.get(taskId)?.notified).not.toBe(true);
  164. },
  165. );
  166. it("omits empty optional tags and formats task:null as retrieval status only", () => {
  167. expect(
  168. formatTaskOutputModelContent({
  169. retrieval_status: "not_ready",
  170. task: {
  171. task_id: "agent_1",
  172. task_type: "local_agent",
  173. status: "running",
  174. description: "Research task",
  175. output: " \n\t",
  176. exitCode: null,
  177. },
  178. }),
  179. ).toBe(
  180. [
  181. "<retrieval_status>not_ready</retrieval_status>",
  182. "<task_id>agent_1</task_id>",
  183. "<task_type>local_agent</task_type>",
  184. "<status>running</status>",
  185. ].join("\n\n"),
  186. );
  187. expect(formatTaskOutputModelContent({ retrieval_status: "timeout", task: null })).toBe(
  188. "<retrieval_status>timeout</retrieval_status>",
  189. );
  190. });
  191. it("prefers the completed Agent result over disk output and joins blocks with one newline", async () => {
  192. const outputRoot = await mkdtemp(join(tmpdir(), "zcode-task-output-agent-"));
  193. const outputFile = join(outputRoot, "task.output");
  194. await writeFile(outputFile, "raw transcript", "utf8");
  195. const registry = registryWithTask(
  196. runtimeTask({
  197. status: "completed",
  198. outputFile,
  199. output: completedAgentOutput("first", "second"),
  200. }),
  201. );
  202. try {
  203. const output = (await taskOutputToolEntry.handler(
  204. { task_id: "agent_1", block: false },
  205. toolContext(registry),
  206. )) as any;
  207. expect(output.task.output).toBe("first\nsecond");
  208. expect(output.task.result).toBe("first\nsecond");
  209. } finally {
  210. await rm(outputRoot, { recursive: true, force: true });
  211. }
  212. });
  213. it("falls back to Bash snapshot stdout then stderr and includes exit code", async () => {
  214. const registry = registryWithTask(
  215. runtimeTask({
  216. agentId: "bash_1",
  217. agentType: "local_bash",
  218. taskId: "bash_1",
  219. taskType: "local_bash",
  220. type: "local_bash",
  221. status: "completed",
  222. }),
  223. );
  224. const result = executionResult("stdout", "stderr", 7);
  225. const output = await taskOutputToolEntry.handler(
  226. { task_id: "bash_1", block: false },
  227. toolContext(registry, {
  228. executionPort: {
  229. async run() {
  230. return result;
  231. },
  232. async getBackgroundTask() {
  233. return {
  234. taskId: "bash_1",
  235. status: "completed",
  236. startedAt: result.startedAt,
  237. completedAt: result.completedAt,
  238. outputPath: "/tmp/bash_1.output",
  239. result,
  240. };
  241. },
  242. },
  243. }),
  244. );
  245. expect(output).toMatchObject({
  246. retrieval_status: "success",
  247. task: {
  248. task_id: "bash_1",
  249. task_type: "local_bash",
  250. output: "stdout\nstderr",
  251. exitCode: 7,
  252. },
  253. });
  254. expect((output as any).task.outputFile).toBeUndefined();
  255. expect(formatTaskOutputModelContent(output)).toContain("<exit_code>7</exit_code>");
  256. });
  257. /**
  258. * dwf run 的产物回投(桌面实测 bug)。dwf 从不写 outputFile,所以泛型投影只会回空串——
  259. * 产物必须从 registry 条目的 `resultText` 上取。
  260. */
  261. function dwfRunTask(overrides: Partial<RuntimeTaskSnapshot> = {}): RuntimeTaskSnapshot {
  262. return runtimeTask({
  263. agentId: "dwfrun_1",
  264. agentType: "local_dynamic_workflow",
  265. description: "Dynamic workflow run",
  266. status: "completed",
  267. taskId: "dwfrun_1",
  268. taskType: "local_dynamic_workflow",
  269. type: "local_dynamic_workflow",
  270. ...overrides,
  271. });
  272. }
  273. it("returns the stored artifact text for a settled dynamic workflow run", async () => {
  274. const registry = registryWithTask(dwfRunTask({ resultText: "the final answer" }));
  275. const output = await taskOutputToolEntry.handler(
  276. { task_id: "dwfrun_1", block: false },
  277. toolContext(registry),
  278. );
  279. expect(output).toMatchObject({
  280. retrieval_status: "success",
  281. task: {
  282. task_id: "dwfrun_1",
  283. task_type: "local_dynamic_workflow",
  284. status: "completed",
  285. output: "the final answer",
  286. result: "the final answer",
  287. },
  288. });
  289. expect(formatTaskOutputModelContent(output)).toContain("<output>\nthe final answer\n</output>");
  290. });
  291. it("returns an empty output for a dynamic workflow run with no stored artifact", async () => {
  292. const registry = registryWithTask(dwfRunTask());
  293. const output = await taskOutputToolEntry.handler(
  294. { task_id: "dwfrun_1", block: false },
  295. toolContext(registry),
  296. );
  297. expect(output).toMatchObject({
  298. retrieval_status: "success",
  299. task: { task_id: "dwfrun_1", output: "" },
  300. });
  301. expect((output as { task: Record<string, unknown> }).task.result).toBeUndefined();
  302. });
  303. it("passes a dynamic workflow run failure through as error", async () => {
  304. const registry = registryWithTask(
  305. dwfRunTask({ status: "failed", error: "script threw TypeError" }),
  306. );
  307. const output = await taskOutputToolEntry.handler(
  308. { task_id: "dwfrun_1", block: false },
  309. toolContext(registry),
  310. );
  311. expect(output).toMatchObject({
  312. task: { status: "failed", error: "script threw TypeError" },
  313. });
  314. });
  315. it("reads the canonical Bash output file when the execution snapshot has no streams", async () => {
  316. const outputRoot = await mkdtemp(join(tmpdir(), "zcode-task-output-bash-"));
  317. const outputFile = join(outputRoot, "bash.output");
  318. await writeFile(outputFile, "persisted bash output", "utf8");
  319. const registry = registryWithTask(
  320. runtimeTask({
  321. agentId: "bash_1",
  322. agentType: "local_bash",
  323. taskId: "bash_1",
  324. taskType: "local_bash",
  325. type: "local_bash",
  326. status: "completed",
  327. outputFile,
  328. exitCode: 9,
  329. }),
  330. );
  331. try {
  332. const output = await taskOutputToolEntry.handler(
  333. { task_id: "bash_1", block: false },
  334. toolContext(registry, {
  335. executionPort: {
  336. async run() {
  337. return executionResult("", "", 0);
  338. },
  339. async getBackgroundTask() {
  340. return {
  341. taskId: "bash_1",
  342. status: "completed",
  343. startedAt: new Date("2026-07-25T00:00:00.000Z"),
  344. completedAt: new Date("2026-07-25T00:00:01.000Z"),
  345. outputPath: outputFile,
  346. };
  347. },
  348. },
  349. }),
  350. );
  351. expect(output).toMatchObject({
  352. task: {
  353. output: "persisted bash output",
  354. exitCode: 9,
  355. outputFile,
  356. },
  357. });
  358. } finally {
  359. await rm(outputRoot, { recursive: true, force: true });
  360. }
  361. });
  362. it("reads running Bash output from the canonical file instead of progress tails", async () => {
  363. const outputRoot = await mkdtemp(join(tmpdir(), "zcode-task-output-bash-running-"));
  364. const outputFile = join(outputRoot, "bash.output");
  365. await writeFile(outputFile, "stdout-1\nstderr-1\nstdout-2\n", "utf8");
  366. const registry = registryWithTask(
  367. runtimeTask({
  368. agentId: "bash_1",
  369. agentType: "local_bash",
  370. taskId: "bash_1",
  371. taskType: "local_bash",
  372. type: "local_bash",
  373. status: "running",
  374. outputFile,
  375. }),
  376. );
  377. try {
  378. const output = await taskOutputToolEntry.handler(
  379. { task_id: "bash_1", block: false },
  380. toolContext(registry, {
  381. executionPort: {
  382. async run() {
  383. return executionResult("", "", 0);
  384. },
  385. async getBackgroundTask() {
  386. return {
  387. taskId: "bash_1",
  388. status: "running",
  389. startedAt: new Date("2026-07-25T00:00:00.000Z"),
  390. outputPath: outputFile,
  391. stdoutPersistedOutputPath: outputFile,
  392. stdoutTail: "stale tail",
  393. };
  394. },
  395. },
  396. }),
  397. );
  398. expect(output).toMatchObject({
  399. retrieval_status: "not_ready",
  400. task: {
  401. output: "stdout-1\nstderr-1\nstdout-2\n",
  402. outputFile,
  403. status: "running",
  404. },
  405. });
  406. } finally {
  407. await rm(outputRoot, { recursive: true, force: true });
  408. }
  409. });
  410. it("reads a fixed 30000-byte prefix from a running Bash output file", async () => {
  411. vi.stubEnv("BASH_MAX_OUTPUT_LENGTH", "1");
  412. const outputRoot = await mkdtemp(join(tmpdir(), "zcode-task-output-bash-running-prefix-"));
  413. const outputFile = join(outputRoot, "bash.output");
  414. const expectedPrefix = "a".repeat(30_000);
  415. await writeFile(outputFile, `${expectedPrefix}${"z".repeat(10_000)}`, "utf8");
  416. const registry = registryWithTask(
  417. runtimeTask({
  418. agentId: "bash_1",
  419. agentType: "local_bash",
  420. taskId: "bash_1",
  421. taskType: "local_bash",
  422. type: "local_bash",
  423. status: "running",
  424. outputFile,
  425. }),
  426. );
  427. try {
  428. const output = (await taskOutputToolEntry.handler(
  429. { task_id: "bash_1", block: false },
  430. toolContext(registry, {
  431. executionPort: {
  432. async run() {
  433. return executionResult("", "", 0);
  434. },
  435. async getBackgroundTask() {
  436. return {
  437. taskId: "bash_1",
  438. status: "running",
  439. startedAt: new Date("2026-07-25T00:00:00.000Z"),
  440. outputPath: outputFile,
  441. stdoutPersistedOutputPath: outputFile,
  442. stdoutTail: "stale tail",
  443. };
  444. },
  445. },
  446. }),
  447. )) as any;
  448. expect(output).toMatchObject({
  449. retrieval_status: "not_ready",
  450. task: {
  451. output: expectedPrefix,
  452. outputFile,
  453. status: "running",
  454. },
  455. });
  456. expect(formatTaskOutputModelContent(output)).not.toContain("[Truncated. Full output:");
  457. } finally {
  458. await rm(outputRoot, { recursive: true, force: true });
  459. }
  460. });
  461. it("applies the Bash prefix limit before TaskOutput truncation after a blocking timeout", async () => {
  462. vi.stubEnv("TASK_MAX_OUTPUT_LENGTH", "20000");
  463. const outputRoot = await mkdtemp(join(tmpdir(), "zcode-task-output-bash-timeout-prefix-"));
  464. const outputFile = join(outputRoot, "bash.output");
  465. const expectedPrefix = `${"a".repeat(29_999)}P`;
  466. await writeFile(outputFile, `${expectedPrefix}${"z".repeat(10_000)}`, "utf8");
  467. const registry = registryWithTask(
  468. runtimeTask({
  469. agentId: "bash_1",
  470. agentType: "local_bash",
  471. taskId: "bash_1",
  472. taskType: "local_bash",
  473. type: "local_bash",
  474. status: "running",
  475. outputFile,
  476. }),
  477. );
  478. try {
  479. const output = (await taskOutputToolEntry.handler(
  480. { task_id: "bash_1", block: true, timeout: 0 },
  481. toolContext(registry, {
  482. executionPort: {
  483. async run() {
  484. return executionResult("", "", 0);
  485. },
  486. async getBackgroundTask() {
  487. return {
  488. taskId: "bash_1",
  489. status: "running",
  490. startedAt: new Date("2026-07-25T00:00:00.000Z"),
  491. outputPath: outputFile,
  492. stdoutPersistedOutputPath: outputFile,
  493. };
  494. },
  495. },
  496. }),
  497. )) as any;
  498. expect(output).toMatchObject({
  499. retrieval_status: "timeout",
  500. task: {
  501. output: expectedPrefix,
  502. outputFile,
  503. status: "running",
  504. },
  505. });
  506. const modelContent = formatTaskOutputModelContent(output);
  507. expect(modelContent).toContain(`[Truncated. Full output: ${outputFile}]`);
  508. expect(modelContent).toMatch(/P\n<\/output>$/u);
  509. expect(modelContent).not.toMatch(/z\n<\/output>$/u);
  510. } finally {
  511. await rm(outputRoot, { recursive: true, force: true });
  512. }
  513. });
  514. it("falls back to Bash snapshot tails when the canonical output file is unavailable", async () => {
  515. const registry = registryWithTask(
  516. runtimeTask({
  517. agentId: "bash_1",
  518. agentType: "local_bash",
  519. taskId: "bash_1",
  520. taskType: "local_bash",
  521. type: "local_bash",
  522. status: "running",
  523. }),
  524. );
  525. const output = await taskOutputToolEntry.handler(
  526. { task_id: "bash_1", block: false },
  527. toolContext(registry, {
  528. executionPort: {
  529. async run() {
  530. return executionResult("", "", 0);
  531. },
  532. async getBackgroundTask() {
  533. return {
  534. taskId: "bash_1",
  535. status: "running",
  536. startedAt: new Date("2026-07-25T00:00:00.000Z"),
  537. outputPath: "/missing/bash.output",
  538. stdoutPersistedOutputPath: "/missing/bash.output",
  539. stdoutTail: "merged tail",
  540. stderrTail: "framework warning",
  541. };
  542. },
  543. },
  544. }),
  545. );
  546. expect(output).toMatchObject({
  547. retrieval_status: "not_ready",
  548. task: {
  549. output: "merged tail\nframework warning",
  550. },
  551. });
  552. expect((output as any).task.outputFile).toBeUndefined();
  553. });
  554. it("keeps legacy split Bash files readable without advertising either as complete output", async () => {
  555. const outputRoot = await mkdtemp(join(tmpdir(), "zcode-task-output-bash-legacy-split-"));
  556. const stdoutPath = join(outputRoot, "stdout.log");
  557. const stderrPath = join(outputRoot, "stderr.log");
  558. const stdout = `stdout-${"s".repeat(20_000)}`;
  559. const stderr = `stderr-${"e".repeat(20_000)}`;
  560. await Promise.all([
  561. writeFile(stdoutPath, stdout, "utf8"),
  562. writeFile(stderrPath, stderr, "utf8"),
  563. ]);
  564. const registry = registryWithTask(
  565. runtimeTask({
  566. agentId: "bash_1",
  567. agentType: "local_bash",
  568. taskId: "bash_1",
  569. taskType: "local_bash",
  570. type: "local_bash",
  571. status: "completed",
  572. outputFile: stdoutPath,
  573. }),
  574. );
  575. const result = executionResult("capped stdout", "capped stderr", 7);
  576. result.stdout.truncated = true;
  577. result.stdout.artifactPath = stdoutPath;
  578. result.stderr.truncated = true;
  579. result.stderr.artifactPath = stderrPath;
  580. try {
  581. const output = (await taskOutputToolEntry.handler(
  582. { task_id: "bash_1", block: false },
  583. toolContext(registry, {
  584. executionPort: {
  585. async run() {
  586. return result;
  587. },
  588. async getBackgroundTask() {
  589. return {
  590. taskId: "bash_1",
  591. status: "completed",
  592. startedAt: result.startedAt,
  593. completedAt: result.completedAt,
  594. outputPath: stdoutPath,
  595. stdoutPersistedOutputPath: stdoutPath,
  596. stderrPersistedOutputPath: stderrPath,
  597. result,
  598. };
  599. },
  600. },
  601. }),
  602. )) as any;
  603. expect(output).toMatchObject({
  604. retrieval_status: "success",
  605. task: {
  606. exitCode: 7,
  607. output: `${stdout}\n${stderr}`,
  608. },
  609. });
  610. expect(output.task.outputFile).toBeUndefined();
  611. const modelContent = formatTaskOutputModelContent(output);
  612. expect(modelContent).toContain(`${stdout}\n${stderr}`);
  613. expect(modelContent).not.toContain("[Truncated. Full output:");
  614. } finally {
  615. await rm(outputRoot, { recursive: true, force: true });
  616. }
  617. });
  618. it("uses the canonical Bash file as the truthful Full output target", async () => {
  619. const outputRoot = await mkdtemp(join(tmpdir(), "zcode-task-output-bash-full-output-"));
  620. const outputFile = join(outputRoot, "bash.output");
  621. const fullOutput = `first-line\n${"x".repeat(40_000)}\nlast-line`;
  622. await writeFile(outputFile, fullOutput, "utf8");
  623. const registry = registryWithTask(
  624. runtimeTask({
  625. agentId: "bash_1",
  626. agentType: "local_bash",
  627. taskId: "bash_1",
  628. taskType: "local_bash",
  629. type: "local_bash",
  630. status: "completed",
  631. outputFile,
  632. }),
  633. );
  634. try {
  635. const output = (await taskOutputToolEntry.handler(
  636. { task_id: "bash_1", block: false },
  637. toolContext(registry, {
  638. executionPort: {
  639. async run() {
  640. return executionResult("", "", 0);
  641. },
  642. async getBackgroundTask() {
  643. return {
  644. taskId: "bash_1",
  645. status: "completed",
  646. startedAt: new Date("2026-07-25T00:00:00.000Z"),
  647. completedAt: new Date("2026-07-25T00:00:01.000Z"),
  648. outputPath: outputFile,
  649. stdoutPersistedOutputPath: outputFile,
  650. };
  651. },
  652. },
  653. }),
  654. )) as any;
  655. expect(output.task.output).toBe(fullOutput);
  656. expect(output.task.outputFile).toBe(outputFile);
  657. expect(formatTaskOutputModelContent(output)).toContain(
  658. `[Truncated. Full output: ${outputFile}]`,
  659. );
  660. } finally {
  661. await rm(outputRoot, { recursive: true, force: true });
  662. }
  663. });
  664. it("does not advertise the canonical file when framework stderr is appended", async () => {
  665. const outputRoot = await mkdtemp(join(tmpdir(), "zcode-task-output-bash-framework-error-"));
  666. const outputFile = join(outputRoot, "bash.output");
  667. await writeFile(outputFile, "merged command output", "utf8");
  668. const registry = registryWithTask(
  669. runtimeTask({
  670. agentId: "bash_1",
  671. agentType: "local_bash",
  672. taskId: "bash_1",
  673. taskType: "local_bash",
  674. type: "local_bash",
  675. status: "completed",
  676. outputFile,
  677. }),
  678. );
  679. const result = executionResult("", "framework warning", 1);
  680. try {
  681. const output = (await taskOutputToolEntry.handler(
  682. { task_id: "bash_1", block: false },
  683. toolContext(registry, {
  684. executionPort: {
  685. async run() {
  686. return result;
  687. },
  688. async getBackgroundTask() {
  689. return {
  690. taskId: "bash_1",
  691. status: "completed",
  692. startedAt: result.startedAt,
  693. completedAt: result.completedAt,
  694. outputPath: outputFile,
  695. stdoutPersistedOutputPath: outputFile,
  696. result,
  697. };
  698. },
  699. },
  700. }),
  701. )) as any;
  702. expect(output.task.output).toBe("merged command output\nframework warning");
  703. expect(output.task.outputFile).toBeUndefined();
  704. } finally {
  705. await rm(outputRoot, { recursive: true, force: true });
  706. }
  707. });
  708. it("uses the Agent output file and error when no completed result is available", async () => {
  709. const outputRoot = await mkdtemp(join(tmpdir(), "zcode-task-output-agent-failed-"));
  710. const outputFile = join(outputRoot, "agent.output");
  711. await writeFile(outputFile, "partial agent output", "utf8");
  712. const registry = registryWithTask(
  713. runtimeTask({
  714. status: "failed",
  715. error: "agent failed",
  716. outputFile,
  717. }),
  718. );
  719. try {
  720. const output = await taskOutputToolEntry.handler(
  721. { task_id: "agent_1", block: false },
  722. toolContext(registry),
  723. );
  724. expect(output).toMatchObject({
  725. retrieval_status: "success",
  726. task: {
  727. status: "failed",
  728. output: "partial agent output",
  729. error: "agent failed",
  730. },
  731. });
  732. expect(formatTaskOutputModelContent(output)).toContain("<error>agent failed</error>");
  733. } finally {
  734. await rm(outputRoot, { recursive: true, force: true });
  735. }
  736. });
  737. it("waits in 100ms steps and emits one progress event before returning success", async () => {
  738. vi.useFakeTimers();
  739. const registry = registryWithTask(runtimeTask());
  740. const events: Array<{ type: string; payload: unknown }> = [];
  741. const promise = taskOutputToolEntry.handler(
  742. { task_id: "agent_1", block: true, timeout: 1_000 },
  743. toolContext(registry, {
  744. emitEvent: async (event) => {
  745. events.push({ type: event.type, payload: event.payload });
  746. },
  747. }),
  748. );
  749. await vi.advanceTimersByTimeAsync(0);
  750. registry.update("agent_1", (task) => ({
  751. ...task,
  752. status: "completed",
  753. output: completedAgentOutput("finished"),
  754. }));
  755. await vi.advanceTimersByTimeAsync(100);
  756. await expect(promise).resolves.toMatchObject({
  757. retrieval_status: "success",
  758. task: { status: "completed", output: "finished" },
  759. });
  760. expect(events).toEqual([
  761. expect.objectContaining({
  762. type: SessionEventType.ToolCallProgress,
  763. payload: expect.objectContaining({
  764. toolName: TASK_OUTPUT_TOOL_NAME,
  765. elapsedMs: 0,
  766. }),
  767. }),
  768. ]);
  769. });
  770. it("returns timeout with the latest task, and task:null when the task disappears", async () => {
  771. const activeRegistry = registryWithTask(runtimeTask());
  772. await expect(
  773. taskOutputToolEntry.handler(
  774. { task_id: "agent_1", block: true, timeout: 0 },
  775. toolContext(activeRegistry),
  776. ),
  777. ).resolves.toMatchObject({
  778. retrieval_status: "timeout",
  779. task: { status: "running" },
  780. });
  781. vi.useFakeTimers();
  782. const removedRegistry = registryWithTask(runtimeTask());
  783. const removedPromise = taskOutputToolEntry.handler(
  784. { task_id: "agent_1", block: true, timeout: 1_000 },
  785. toolContext(removedRegistry),
  786. );
  787. await vi.advanceTimersByTimeAsync(0);
  788. removedRegistry.remove("agent_1");
  789. await vi.advanceTimersByTimeAsync(100);
  790. await expect(removedPromise).resolves.toEqual({
  791. retrieval_status: "timeout",
  792. task: null,
  793. });
  794. });
  795. it("throws AbortError while blocking", async () => {
  796. vi.useFakeTimers();
  797. const registry = registryWithTask(runtimeTask());
  798. const controller = new AbortController();
  799. const promise = taskOutputToolEntry.handler(
  800. { task_id: "agent_1", block: true, timeout: 1_000 },
  801. toolContext(registry, { abortSignal: controller.signal }),
  802. );
  803. const rejection = expect(promise).rejects.toMatchObject({ name: "AbortError" });
  804. await vi.advanceTimersByTimeAsync(0);
  805. controller.abort();
  806. await vi.advanceTimersByTimeAsync(100);
  807. await rejection;
  808. });
  809. it("returns the exact empty and unknown task failures from the handler", async () => {
  810. const registry = registryWithTask(runtimeTask());
  811. const context = toolContext(registry);
  812. await expect(taskOutputToolEntry.handler({ task_id: "" }, context)).resolves.toEqual({
  813. result: false,
  814. errorCode: 1,
  815. message: "Task ID is required",
  816. });
  817. await expect(taskOutputToolEntry.handler({ task_id: "missing" }, context)).resolves.toEqual({
  818. result: false,
  819. errorCode: 2,
  820. message: "No task found with ID: missing",
  821. });
  822. });
  823. it("projects schema and TaskOutput handler failures through the executor", async () => {
  824. const sessionId = createSessionId("task-output-validation");
  825. const turnId = createTurnId("task-output-validation");
  826. const traceContext = createRootTraceContext({ sessionId, turnId });
  827. const registry = createToolRegistry();
  828. registry.register(taskOutputToolEntry);
  829. const executor = createToolExecutor({
  830. emitEvent: async () => undefined,
  831. permissionService: new PermissionService(defaultPermissionConfig),
  832. registry,
  833. runtimeTaskRegistry: new InMemoryRuntimeTaskRegistry(),
  834. sessionId,
  835. turnId,
  836. traceContext,
  837. });
  838. const missingField = await executor.execute(
  839. {
  840. id: createToolCallId("task-output-missing-field"),
  841. input: {},
  842. name: TASK_OUTPUT_TOOL_NAME,
  843. },
  844. { traceContext },
  845. );
  846. expect(missingField.success).toBe(false);
  847. expect(missingField.error?.message).toBe("Tool input failed inputSchema validation");
  848. expect(missingField.modelContent).toBe(
  849. [
  850. "<tool_use_error>InputValidationError: TaskOutput failed due to the following issue:",
  851. "The required parameter `task_id` is missing</tool_use_error>",
  852. ].join("\n"),
  853. );
  854. for (const testCase of [
  855. {
  856. id: "task-output-empty-id",
  857. input: { task_id: "" },
  858. message: "Task ID is required",
  859. },
  860. {
  861. id: "task-output-unknown-id",
  862. input: { task_id: "missing" },
  863. message: "No task found with ID: missing",
  864. },
  865. ] as const) {
  866. const result = await executor.execute(
  867. {
  868. id: createToolCallId(testCase.id),
  869. input: testCase.input,
  870. name: TASK_OUTPUT_TOOL_NAME,
  871. },
  872. { traceContext },
  873. );
  874. expect(result.success).toBe(false);
  875. expect(result.error?.message).toBe(testCase.message);
  876. expect(result.modelContent).toBe(`<tool_use_error>${testCase.message}</tool_use_error>`);
  877. }
  878. });
  879. it("rejects empty and unknown task IDs before tool hooks and execution start", async () => {
  880. const sessionId = createSessionId("task-output-pre-hook-validation");
  881. const turnId = createTurnId("task-output-pre-hook-validation");
  882. const traceContext = createRootTraceContext({ sessionId, turnId });
  883. const registry = createToolRegistry();
  884. registry.register(taskOutputToolEntry);
  885. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  886. const events: SessionEventType[] = [];
  887. let preToolUseCalls = 0;
  888. let postToolUseFailureCalls = 0;
  889. const hookRunner = createInMemoryHookRunner({
  890. hooks: [
  891. {
  892. event: HookEventName.PreToolUse,
  893. matcher: TASK_OUTPUT_TOOL_NAME,
  894. callback: async () => {
  895. preToolUseCalls += 1;
  896. return {};
  897. },
  898. },
  899. {
  900. event: HookEventName.PostToolUseFailure,
  901. matcher: TASK_OUTPUT_TOOL_NAME,
  902. callback: async () => {
  903. postToolUseFailureCalls += 1;
  904. return {};
  905. },
  906. },
  907. ],
  908. });
  909. const executor = createToolExecutor({
  910. emitEvent: async (event) => {
  911. events.push(event.type);
  912. },
  913. hookRunner,
  914. permissionService: new PermissionService(defaultPermissionConfig),
  915. registry,
  916. runtimeTaskRegistry,
  917. sessionId,
  918. turnId,
  919. traceContext,
  920. });
  921. for (const testCase of [
  922. { input: { task_id: "" }, message: "Task ID is required" },
  923. { input: { task_id: "missing" }, message: "No task found with ID: missing" },
  924. ]) {
  925. const result = await executor.execute(
  926. {
  927. id: createToolCallId(`task-output-pre-hook-${testCase.input.task_id || "empty"}`),
  928. input: testCase.input,
  929. name: TASK_OUTPUT_TOOL_NAME,
  930. },
  931. { traceContext },
  932. );
  933. expect(result.success).toBe(false);
  934. expect(result.modelContent).toBe(`<tool_use_error>${testCase.message}</tool_use_error>`);
  935. }
  936. expect(preToolUseCalls).toBe(0);
  937. expect(postToolUseFailureCalls).toBe(0);
  938. expect(events).toEqual([SessionEventType.ToolCallError, SessionEventType.ToolCallError]);
  939. });
  940. it("tails generic task output at 8 MiB with the omitted-output prefix", async () => {
  941. const outputRoot = await mkdtemp(join(tmpdir(), "zcode-task-output-tail-"));
  942. const outputFile = join(outputRoot, "workflow.output");
  943. await writeFile(outputFile, `${"a".repeat(1024)}${"b".repeat(8 * 1024 * 1024)}`, "utf8");
  944. const registry = registryWithTask(
  945. runtimeTask({
  946. agentId: "workflow_1",
  947. agentType: "local_workflow",
  948. taskId: "workflow_1",
  949. taskType: "local_workflow",
  950. type: "local_workflow",
  951. status: "completed",
  952. outputFile,
  953. }),
  954. );
  955. try {
  956. const output = (await taskOutputToolEntry.handler(
  957. { task_id: "workflow_1", block: false },
  958. toolContext(registry),
  959. )) as any;
  960. expect(output.task.output).toHaveLength(
  961. 8 * 1024 * 1024 + "[1KB of earlier output omitted]\n".length,
  962. );
  963. expect(output.task.output).toMatch(/^\[1KB of earlier output omitted\]\n/u);
  964. expect(output.task.output.endsWith("b".repeat(1024))).toBe(true);
  965. } finally {
  966. await rm(outputRoot, { recursive: true, force: true });
  967. }
  968. });
  969. it("applies the source-aligned TASK_MAX_OUTPUT_LENGTH rules and truncation prefix", () => {
  970. expect(resolveTaskOutputLength(undefined)).toBe(32_000);
  971. expect(resolveTaskOutputLength("invalid")).toBe(32_000);
  972. expect(resolveTaskOutputLength("0")).toBe(32_000);
  973. expect(resolveTaskOutputLength("100suffix")).toBe(100);
  974. expect(resolveTaskOutputLength("200000")).toBe(160_000);
  975. const output = "x".repeat(40_000);
  976. const truncated = truncateTaskOutput(output, "/tmp/agent_1.output");
  977. expect(truncated).toHaveLength(32_000);
  978. expect(truncated).toMatch(/^\[Truncated\. Full output: \/tmp\/agent_1\.output\]\n\n/u);
  979. expect(truncated.endsWith("x".repeat(100))).toBe(true);
  980. const maximum = truncateTaskOutput("x".repeat(200_000), "/tmp/agent_1.output", "160000");
  981. expect(maximum).toHaveLength(160_000);
  982. const shortLimitPrefix = "[Truncated. Full output: /tmp/agent_1.output]\n\n";
  983. expect(truncateTaskOutput("x".repeat(100), "/tmp/agent_1.output", "10")).toBe(
  984. shortLimitPrefix + "x".repeat(100).slice(shortLimitPrefix.length - 10),
  985. );
  986. });
  987. it("persists mapped XML above 100000 characters with the persisted-output envelope", async () => {
  988. vi.stubEnv("TASK_MAX_OUTPUT_LENGTH", "160000");
  989. const sessionId = createSessionId("task-output-persist");
  990. const turnId = createTurnId("task-output-persist");
  991. const traceContext = createRootTraceContext({ sessionId, turnId });
  992. const registry = createToolRegistry();
  993. registry.register(taskOutputToolEntry);
  994. const runtimeTaskRegistry = registryWithTask(
  995. runtimeTask({
  996. status: "completed",
  997. output: completedAgentOutput("x".repeat(120_000)),
  998. outputFile: "/tmp/agent_1.output",
  999. }),
  1000. );
  1001. const persisted: Array<{ content: string; contentType?: string }> = [];
  1002. const executor = createToolExecutor({
  1003. artifactStore: {
  1004. async writeToolResultArtifact(request) {
  1005. persisted.push({
  1006. content: request.content,
  1007. contentType: request.contentType,
  1008. });
  1009. return {
  1010. id: "artifact_task_output",
  1011. uri: "artifact://task-output",
  1012. path: "/tmp/tool-results/task-output.txt",
  1013. bytes: Buffer.byteLength(request.content),
  1014. contentType: request.contentType ?? "text/plain",
  1015. createdAt: new Date(),
  1016. };
  1017. },
  1018. async readToolResultArtifact() {
  1019. throw new Error("not used");
  1020. },
  1021. },
  1022. emitEvent: async () => undefined,
  1023. permissionService: new PermissionService(defaultPermissionConfig),
  1024. registry,
  1025. runtimeTaskRegistry,
  1026. sessionId,
  1027. turnId,
  1028. traceContext,
  1029. });
  1030. const result = await executor.execute(
  1031. {
  1032. id: createToolCallId("task-output-persist"),
  1033. input: { task_id: "agent_1", block: false },
  1034. name: TASK_OUTPUT_TOOL_NAME,
  1035. },
  1036. { traceContext },
  1037. );
  1038. expect(result.success).toBe(true);
  1039. expect(persisted).toHaveLength(1);
  1040. expect(persisted[0]?.contentType).toBe("text/plain");
  1041. expect(persisted[0]?.content).toMatch(/^<retrieval_status>success<\/retrieval_status>/u);
  1042. expect(persisted[0]?.content).toContain("<output>\n");
  1043. const persistedContent = persisted[0]?.content ?? "";
  1044. const formattedSize = `${(persistedContent.length / 1024).toFixed(1).replace(/\.0$/u, "")}KB`;
  1045. expect(String(result.modelContent)).toMatch(
  1046. new RegExp(
  1047. `^<persisted-output>\\nOutput too large \\(${formattedSize.replace(".", "\\.")}\\)\\. Full output saved to: `,
  1048. "u",
  1049. ),
  1050. );
  1051. expect(String(result.modelContent)).toContain("\n...\n</persisted-output>");
  1052. expect(String(result.modelContent)).not.toContain("Tool output truncated by resultBudget");
  1053. });
  1054. it("keeps the original XML when 100000-character artifact persistence fails", async () => {
  1055. vi.stubEnv("TASK_MAX_OUTPUT_LENGTH", "160000");
  1056. const sessionId = createSessionId("task-output-persist-failure");
  1057. const turnId = createTurnId("task-output-persist-failure");
  1058. const traceContext = createRootTraceContext({ sessionId, turnId });
  1059. const registry = createToolRegistry();
  1060. registry.register(taskOutputToolEntry);
  1061. const runtimeTaskRegistry = registryWithTask(
  1062. runtimeTask({
  1063. status: "completed",
  1064. output: completedAgentOutput("\u0800".repeat(150_000)),
  1065. outputFile: "/tmp/agent_1.output",
  1066. }),
  1067. );
  1068. const executor = createToolExecutor({
  1069. artifactStore: {
  1070. async writeToolResultArtifact() {
  1071. throw new Error("disk full");
  1072. },
  1073. async readToolResultArtifact() {
  1074. throw new Error("not used");
  1075. },
  1076. },
  1077. emitEvent: async () => undefined,
  1078. permissionService: new PermissionService(defaultPermissionConfig),
  1079. registry,
  1080. runtimeTaskRegistry,
  1081. sessionId,
  1082. turnId,
  1083. traceContext,
  1084. });
  1085. const result = await executor.execute(
  1086. {
  1087. id: createToolCallId("task-output-persist-failure"),
  1088. input: { task_id: "agent_1", block: false },
  1089. name: TASK_OUTPUT_TOOL_NAME,
  1090. },
  1091. { traceContext },
  1092. );
  1093. expect(result.success).toBe(true);
  1094. expect(String(result.modelContent)).toMatch(/^<retrieval_status>success<\/retrieval_status>/u);
  1095. expect(String(result.modelContent)).toContain("\u0800".repeat(1_000));
  1096. expect(String(result.modelContent)).not.toContain("<persisted-output>");
  1097. expect(String(result.modelContent)).not.toContain("Tool output truncated by resultBudget");
  1098. });
  1099. it("uses notified as the single completion notification claim in both orderings", async () => {
  1100. const taskOutputFirst = registryWithTask(runtimeTask({ status: "completed" }));
  1101. await taskOutputToolEntry.handler(
  1102. { task_id: "agent_1", block: false },
  1103. toolContext(taskOutputFirst),
  1104. );
  1105. expect(
  1106. claimRuntimeBackgroundTaskNotification(
  1107. { runtimeTaskRegistry: taskOutputFirst } as never,
  1108. { id: "tool_bash", input: {}, name: "Bash" },
  1109. "agent_1",
  1110. ),
  1111. ).toBe(false);
  1112. const completionFirst = registryWithTask(runtimeTask({ status: "completed" }));
  1113. expect(
  1114. claimRuntimeBackgroundTaskNotification(
  1115. { runtimeTaskRegistry: completionFirst } as never,
  1116. { id: "tool_bash", input: {}, name: "Bash" },
  1117. "agent_1",
  1118. ),
  1119. ).toBe(true);
  1120. await taskOutputToolEntry.handler(
  1121. { task_id: "agent_1", block: false },
  1122. toolContext(completionFirst),
  1123. );
  1124. expect(completionFirst.get("agent_1")?.notified).toBe(true);
  1125. });
  1126. it("does not enqueue a Bash completion after TaskOutput claimed the terminal task", async () => {
  1127. const taskId = "bash_task_output_first";
  1128. const runtimeTaskRegistry = registryWithTask(
  1129. runtimeTask({
  1130. agentId: taskId,
  1131. agentType: "local_bash",
  1132. taskId,
  1133. taskType: "local_bash",
  1134. type: "local_bash",
  1135. status: "completed",
  1136. exitCode: 0,
  1137. }),
  1138. );
  1139. await taskOutputToolEntry.handler(
  1140. { task_id: taskId, block: false },
  1141. toolContext(runtimeTaskRegistry),
  1142. );
  1143. const sessionId = createSessionId("task-output-notification-race");
  1144. const turnId = createTurnId("task-output-notification-race");
  1145. const traceContext = createRootTraceContext({ sessionId, turnId });
  1146. const notifications: string[] = [];
  1147. let completeEvent = () => undefined;
  1148. const completedEvent = new Promise<void>((resolve) => {
  1149. completeEvent = resolve;
  1150. });
  1151. const tracker = new BackgroundTaskTracker({
  1152. emitEvent: async (event: { type: SessionEventType }) => {
  1153. if (event.type === SessionEventType.BackgroundTaskCompleted) completeEvent();
  1154. },
  1155. enqueueBackgroundTaskNotification: (notification: { text: string }) => {
  1156. notifications.push(notification.text);
  1157. },
  1158. executionPort: {
  1159. async run() {
  1160. throw new Error("run should not be called");
  1161. },
  1162. async waitForBackgroundTask() {
  1163. return {
  1164. taskId,
  1165. status: "completed" as const,
  1166. startedAt: new Date("2026-07-25T00:00:00.000Z"),
  1167. completedAt: new Date("2026-07-25T00:00:01.000Z"),
  1168. result: executionResult("done", "", 0),
  1169. };
  1170. },
  1171. },
  1172. runtimeTaskRegistry,
  1173. runtimeScope: "main",
  1174. sessionId,
  1175. } as never);
  1176. await tracker.trackBackgroundTask(
  1177. {
  1178. id: "tool_bash_task_output_first",
  1179. input: { command: "echo done" },
  1180. name: "Bash",
  1181. } as never,
  1182. { backgroundTaskId: taskId, status: "backgrounded" },
  1183. traceContext,
  1184. turnId,
  1185. );
  1186. await completedEvent;
  1187. expect(notifications).toEqual([]);
  1188. expect(runtimeTaskRegistry.get(taskId)).toMatchObject({
  1189. notified: true,
  1190. status: "completed",
  1191. exitCode: 0,
  1192. });
  1193. });
  1194. });
  1195. function runtimeTask(overrides: Partial<RuntimeTaskSnapshot> = {}): RuntimeTaskSnapshot {
  1196. return {
  1197. taskId: "agent_1",
  1198. agentId: "agent_1",
  1199. agentType: "general-purpose",
  1200. description: "Research task",
  1201. status: "running",
  1202. startedAt: new Date("2026-07-25T00:00:00.000Z"),
  1203. type: "local_agent",
  1204. taskType: "local_agent",
  1205. isBackgrounded: true,
  1206. ...overrides,
  1207. };
  1208. }
  1209. function registryWithTask(task: RuntimeTaskSnapshot): InMemoryRuntimeTaskRegistry {
  1210. const registry = new InMemoryRuntimeTaskRegistry();
  1211. registry.register(task);
  1212. return registry;
  1213. }
  1214. function toolContext(
  1215. registry: InMemoryRuntimeTaskRegistry,
  1216. overrides: Partial<ToolExecutionContext> = {},
  1217. ): ToolExecutionContext {
  1218. return {
  1219. abortSignal: new AbortController().signal,
  1220. runtimeTaskRegistry: registry,
  1221. sessionId: "sess_task_output" as never,
  1222. toolCallId: "tool_task_output",
  1223. traceId: "trace_task_output" as never,
  1224. workingDirectory: "/tmp",
  1225. workspaceRoot: "/tmp",
  1226. ...overrides,
  1227. };
  1228. }
  1229. function completedAgentOutput(...texts: string[]) {
  1230. return {
  1231. status: "completed" as const,
  1232. agentId: "agent_1",
  1233. agentType: "general-purpose",
  1234. description: "Research task",
  1235. prompt: "Research this",
  1236. content: texts.map((text) => ({ type: "text" as const, text })),
  1237. totalToolUseCount: 1,
  1238. totalDurationMs: 10,
  1239. totalTokens: 5,
  1240. };
  1241. }
  1242. function executionResult(stdout: string, stderr: string, exitCode: number): ExecutionResult {
  1243. const startedAt = new Date("2026-07-25T00:00:00.000Z");
  1244. const completedAt = new Date("2026-07-25T00:00:01.000Z");
  1245. return {
  1246. status: "completed",
  1247. exitCode,
  1248. stdout: {
  1249. text: stdout,
  1250. bytes: Buffer.byteLength(stdout),
  1251. truncated: false,
  1252. },
  1253. stderr: {
  1254. text: stderr,
  1255. bytes: Buffer.byteLength(stderr),
  1256. truncated: false,
  1257. },
  1258. durationMs: 1_000,
  1259. timedOut: false,
  1260. cancelled: false,
  1261. startedAt,
  1262. completedAt,
  1263. };
  1264. }