task-output-tool.test.ts 44 KB

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