@cloudflare/ai-chat 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,7 @@ import { getAgentByName } from "agents";
3
3
  import { describe, it, expect } from "vitest";
4
4
  import worker from "./worker";
5
5
  import type { UIMessage as ChatMessage } from "ai";
6
+ import { convertToModelMessages } from "ai";
6
7
  import {
7
8
  applyChunkToParts,
8
9
  type MessageParts,
@@ -675,7 +676,7 @@ describe("Tool approval (needsApproval) duplicate message prevention", () => {
675
676
  state: string;
676
677
  approval?: { approved: boolean };
677
678
  };
678
- expect(toolPart.state).toBe("approval-responded");
679
+ expect(toolPart.state).toBe("output-denied");
679
680
  expect(toolPart.approval).toEqual({ approved: false });
680
681
 
681
682
  ws.close(1000);
@@ -746,6 +747,68 @@ describe("Tool approval (needsApproval) duplicate message prevention", () => {
746
747
  ws.close(1000);
747
748
  });
748
749
 
750
+ it("CF_AGENT_TOOL_APPROVAL rejection from approval-requested sets output-denied", async () => {
751
+ const room = crypto.randomUUID();
752
+ const ctx = createExecutionContext();
753
+ const req = new Request(
754
+ `http://example.com/agents/test-chat-agent/${room}`,
755
+ { headers: { Upgrade: "websocket" } }
756
+ );
757
+ const res = await worker.fetch(req, env, ctx);
758
+ expect(res.status).toBe(101);
759
+ const ws = res.webSocket as WebSocket;
760
+ ws.accept();
761
+ await ctx.waitUntil(Promise.resolve());
762
+
763
+ const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
764
+ const toolCallId = "call_approval_requested_rejected";
765
+
766
+ await agentStub.persistMessages([
767
+ {
768
+ id: "user-1",
769
+ role: "user",
770
+ parts: [{ type: "text", text: "Execute tool" }]
771
+ },
772
+ {
773
+ id: "assistant-1",
774
+ role: "assistant",
775
+ parts: [
776
+ {
777
+ type: "tool-testTool",
778
+ toolCallId,
779
+ state: "approval-requested",
780
+ input: { param: "value" },
781
+ approval: { id: "approval-789" }
782
+ }
783
+ ] as ChatMessage["parts"]
784
+ }
785
+ ]);
786
+
787
+ ws.send(
788
+ JSON.stringify({
789
+ type: "cf_agent_tool_approval",
790
+ toolCallId,
791
+ approved: false
792
+ })
793
+ );
794
+
795
+ await new Promise((resolve) => setTimeout(resolve, 200));
796
+
797
+ const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
798
+ const assistantMessages = messages.filter((m) => m.role === "assistant");
799
+
800
+ expect(assistantMessages.length).toBe(1);
801
+
802
+ const toolPart = assistantMessages[0].parts[0] as {
803
+ state: string;
804
+ approval?: { id: string; approved: boolean };
805
+ };
806
+ expect(toolPart.state).toBe("output-denied");
807
+ expect(toolPart.approval).toEqual({ id: "approval-789", approved: false });
808
+
809
+ ws.close(1000);
810
+ });
811
+
749
812
  it("CF_AGENT_TOOL_APPROVAL with non-existent toolCallId logs warning", async () => {
750
813
  const room = crypto.randomUUID();
751
814
  const ctx = createExecutionContext();
@@ -1006,7 +1069,7 @@ describe("Tool approval auto-continuation (needsApproval)", () => {
1006
1069
  ws.close(1000);
1007
1070
  });
1008
1071
 
1009
- it("CF_AGENT_TOOL_APPROVAL with approved: false and autoContinue does NOT continue", async () => {
1072
+ it("CF_AGENT_TOOL_APPROVAL with approved: false and autoContinue triggers continuation", async () => {
1010
1073
  const room = crypto.randomUUID();
1011
1074
  const ctx = createExecutionContext();
1012
1075
  const req = new Request(
@@ -1020,9 +1083,8 @@ describe("Tool approval auto-continuation (needsApproval)", () => {
1020
1083
  await ctx.waitUntil(Promise.resolve());
1021
1084
 
1022
1085
  const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1023
- const toolCallId = "call_rejected_no_continue";
1086
+ const toolCallId = "call_rejected_continue";
1024
1087
 
1025
- // Persist assistant message with tool in input-available state
1026
1088
  await agentStub.persistMessages([
1027
1089
  {
1028
1090
  id: "user-1",
@@ -1043,7 +1105,6 @@ describe("Tool approval auto-continuation (needsApproval)", () => {
1043
1105
  }
1044
1106
  ]);
1045
1107
 
1046
- // Send rejection with autoContinue: true — should NOT continue
1047
1108
  ws.send(
1048
1109
  JSON.stringify({
1049
1110
  type: "cf_agent_tool_approval",
@@ -1058,7 +1119,6 @@ describe("Tool approval auto-continuation (needsApproval)", () => {
1058
1119
  const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1059
1120
  const assistantMessages = messages.filter((m) => m.role === "assistant");
1060
1121
 
1061
- // Should have 1 assistant message, no continuation
1062
1122
  expect(assistantMessages.length).toBe(1);
1063
1123
 
1064
1124
  const assistantMsg = assistantMessages[0];
@@ -1066,11 +1126,11 @@ describe("Tool approval auto-continuation (needsApproval)", () => {
1066
1126
  state: string;
1067
1127
  approval?: { approved: boolean };
1068
1128
  };
1069
- expect(toolPart.state).toBe("approval-responded");
1129
+ expect(toolPart.state).toBe("output-denied");
1070
1130
  expect(toolPart.approval).toEqual({ approved: false });
1071
1131
 
1072
- // No continuation parts
1073
- expect(assistantMsg.parts.length).toBe(1);
1132
+ // Continuation parts should be appended (LLM sees denial and responds)
1133
+ expect(assistantMsg.parts.length).toBeGreaterThan(1);
1074
1134
 
1075
1135
  ws.close(1000);
1076
1136
  });
@@ -1298,3 +1358,600 @@ describe("Tool approval persistence across reconnect", () => {
1298
1358
  ws.close(1000);
1299
1359
  });
1300
1360
  });
1361
+
1362
+ describe("Tool approval denial produces tool_result via convertToModelMessages", () => {
1363
+ it("rejected approval yields tool-result in model messages (required by Anthropic)", async () => {
1364
+ const room = crypto.randomUUID();
1365
+ const ctx = createExecutionContext();
1366
+ const req = new Request(
1367
+ `http://example.com/agents/test-chat-agent/${room}`,
1368
+ { headers: { Upgrade: "websocket" } }
1369
+ );
1370
+ const res = await worker.fetch(req, env, ctx);
1371
+ expect(res.status).toBe(101);
1372
+ const ws = res.webSocket as WebSocket;
1373
+ ws.accept();
1374
+ await ctx.waitUntil(Promise.resolve());
1375
+
1376
+ const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1377
+ const toolCallId = "call_e2e_denied";
1378
+
1379
+ await agentStub.persistMessages([
1380
+ {
1381
+ id: "user-1",
1382
+ role: "user",
1383
+ parts: [{ type: "text", text: "Run the tool" }]
1384
+ },
1385
+ {
1386
+ id: "assistant-1",
1387
+ role: "assistant",
1388
+ parts: [
1389
+ {
1390
+ type: "tool-testTool",
1391
+ toolCallId,
1392
+ state: "approval-requested",
1393
+ input: { param: "value" },
1394
+ approval: { id: "approval-e2e" }
1395
+ }
1396
+ ] as ChatMessage["parts"]
1397
+ }
1398
+ ]);
1399
+
1400
+ ws.send(
1401
+ JSON.stringify({
1402
+ type: "cf_agent_tool_approval",
1403
+ toolCallId,
1404
+ approved: false
1405
+ })
1406
+ );
1407
+
1408
+ await new Promise((resolve) => setTimeout(resolve, 200));
1409
+
1410
+ const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1411
+ const modelMessages = await convertToModelMessages(messages);
1412
+
1413
+ const toolMessage = modelMessages.find((m) => m.role === "tool");
1414
+ expect(toolMessage).toBeDefined();
1415
+
1416
+ const toolContent = toolMessage!.content as Array<{
1417
+ type: string;
1418
+ [key: string]: unknown;
1419
+ }>;
1420
+
1421
+ const approvalResponse = toolContent.find(
1422
+ (c) => c.type === "tool-approval-response"
1423
+ );
1424
+ expect(approvalResponse).toBeDefined();
1425
+ expect(approvalResponse!.approved).toBe(false);
1426
+
1427
+ const toolResult = toolContent.find((c) => c.type === "tool-result");
1428
+ expect(toolResult).toBeDefined();
1429
+ expect(toolResult!.toolCallId).toBe(toolCallId);
1430
+ expect(toolResult!.toolName).toBe("testTool");
1431
+
1432
+ ws.close(1000);
1433
+ });
1434
+ });
1435
+
1436
+ describe("CF_AGENT_TOOL_RESULT with approval states and output-error", () => {
1437
+ it("applies tool result to a tool in approval-requested state", async () => {
1438
+ const room = crypto.randomUUID();
1439
+ const ctx = createExecutionContext();
1440
+ const req = new Request(
1441
+ `http://example.com/agents/test-chat-agent/${room}`,
1442
+ { headers: { Upgrade: "websocket" } }
1443
+ );
1444
+ const res = await worker.fetch(req, env, ctx);
1445
+ expect(res.status).toBe(101);
1446
+ const ws = res.webSocket as WebSocket;
1447
+ ws.accept();
1448
+ await ctx.waitUntil(Promise.resolve());
1449
+
1450
+ const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1451
+ const toolCallId = "call_approval_tool_result";
1452
+
1453
+ await agentStub.persistMessages([
1454
+ {
1455
+ id: "user-1",
1456
+ role: "user",
1457
+ parts: [{ type: "text", text: "Execute tool" }]
1458
+ },
1459
+ {
1460
+ id: "assistant-1",
1461
+ role: "assistant",
1462
+ parts: [
1463
+ {
1464
+ type: "tool-testTool",
1465
+ toolCallId,
1466
+ state: "approval-requested",
1467
+ input: { param: "value" },
1468
+ approval: { id: "approval-tr-1" }
1469
+ }
1470
+ ] as ChatMessage["parts"]
1471
+ }
1472
+ ]);
1473
+
1474
+ ws.send(
1475
+ JSON.stringify({
1476
+ type: "cf_agent_tool_result",
1477
+ toolCallId,
1478
+ toolName: "testTool",
1479
+ output: { result: "done" }
1480
+ })
1481
+ );
1482
+
1483
+ await new Promise((resolve) => setTimeout(resolve, 200));
1484
+
1485
+ const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1486
+ const assistantMessages = messages.filter((m) => m.role === "assistant");
1487
+
1488
+ expect(assistantMessages.length).toBe(1);
1489
+
1490
+ const toolPart = assistantMessages[0].parts[0] as {
1491
+ state: string;
1492
+ output?: unknown;
1493
+ };
1494
+ expect(toolPart.state).toBe("output-available");
1495
+ expect(toolPart.output).toEqual({ result: "done" });
1496
+
1497
+ ws.close(1000);
1498
+ });
1499
+
1500
+ it("sets output-error state with errorText via CF_AGENT_TOOL_RESULT", async () => {
1501
+ const room = crypto.randomUUID();
1502
+ const ctx = createExecutionContext();
1503
+ const req = new Request(
1504
+ `http://example.com/agents/test-chat-agent/${room}`,
1505
+ { headers: { Upgrade: "websocket" } }
1506
+ );
1507
+ const res = await worker.fetch(req, env, ctx);
1508
+ expect(res.status).toBe(101);
1509
+ const ws = res.webSocket as WebSocket;
1510
+ ws.accept();
1511
+ await ctx.waitUntil(Promise.resolve());
1512
+
1513
+ const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1514
+ const toolCallId = "call_output_error";
1515
+
1516
+ await agentStub.persistMessages([
1517
+ {
1518
+ id: "user-1",
1519
+ role: "user",
1520
+ parts: [{ type: "text", text: "Execute tool" }]
1521
+ },
1522
+ {
1523
+ id: "assistant-1",
1524
+ role: "assistant",
1525
+ parts: [
1526
+ {
1527
+ type: "tool-testTool",
1528
+ toolCallId,
1529
+ state: "approval-requested",
1530
+ input: { param: "value" },
1531
+ approval: { id: "approval-err-1" }
1532
+ }
1533
+ ] as ChatMessage["parts"]
1534
+ }
1535
+ ]);
1536
+
1537
+ ws.send(
1538
+ JSON.stringify({
1539
+ type: "cf_agent_tool_result",
1540
+ toolCallId,
1541
+ toolName: "testTool",
1542
+ output: null,
1543
+ state: "output-error",
1544
+ errorText: "User declined: not authorized"
1545
+ })
1546
+ );
1547
+
1548
+ await new Promise((resolve) => setTimeout(resolve, 200));
1549
+
1550
+ const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1551
+ const assistantMessages = messages.filter((m) => m.role === "assistant");
1552
+
1553
+ expect(assistantMessages.length).toBe(1);
1554
+
1555
+ const toolPart = assistantMessages[0].parts[0] as {
1556
+ state: string;
1557
+ errorText?: string;
1558
+ };
1559
+ expect(toolPart.state).toBe("output-error");
1560
+ expect(toolPart.errorText).toBe("User declined: not authorized");
1561
+
1562
+ ws.close(1000);
1563
+ });
1564
+
1565
+ it("output-error produces tool_result with custom errorText in model messages", async () => {
1566
+ const room = crypto.randomUUID();
1567
+ const ctx = createExecutionContext();
1568
+ const req = new Request(
1569
+ `http://example.com/agents/test-chat-agent/${room}`,
1570
+ { headers: { Upgrade: "websocket" } }
1571
+ );
1572
+ const res = await worker.fetch(req, env, ctx);
1573
+ expect(res.status).toBe(101);
1574
+ const ws = res.webSocket as WebSocket;
1575
+ ws.accept();
1576
+ await ctx.waitUntil(Promise.resolve());
1577
+
1578
+ const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1579
+ const toolCallId = "call_e2e_error";
1580
+
1581
+ await agentStub.persistMessages([
1582
+ {
1583
+ id: "user-1",
1584
+ role: "user",
1585
+ parts: [{ type: "text", text: "Run the tool" }]
1586
+ },
1587
+ {
1588
+ id: "assistant-1",
1589
+ role: "assistant",
1590
+ parts: [
1591
+ {
1592
+ type: "tool-testTool",
1593
+ toolCallId,
1594
+ state: "input-available",
1595
+ input: { param: "value" }
1596
+ }
1597
+ ] as ChatMessage["parts"]
1598
+ }
1599
+ ]);
1600
+
1601
+ ws.send(
1602
+ JSON.stringify({
1603
+ type: "cf_agent_tool_result",
1604
+ toolCallId,
1605
+ toolName: "testTool",
1606
+ output: null,
1607
+ state: "output-error",
1608
+ errorText: "Denied: insufficient permissions"
1609
+ })
1610
+ );
1611
+
1612
+ await new Promise((resolve) => setTimeout(resolve, 200));
1613
+
1614
+ const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1615
+ const modelMessages = await convertToModelMessages(messages);
1616
+
1617
+ const toolMessage = modelMessages.find((m) => m.role === "tool");
1618
+ expect(toolMessage).toBeDefined();
1619
+
1620
+ const toolContent = toolMessage!.content as Array<{
1621
+ type: string;
1622
+ [key: string]: unknown;
1623
+ }>;
1624
+
1625
+ const toolResult = toolContent.find((c) => c.type === "tool-result");
1626
+ expect(toolResult).toBeDefined();
1627
+ expect(toolResult!.toolCallId).toBe(toolCallId);
1628
+
1629
+ const output = toolResult!.output as { type: string; value: string };
1630
+ expect(output.type).toBe("error-text");
1631
+ expect(output.value).toBe("Denied: insufficient permissions");
1632
+
1633
+ ws.close(1000);
1634
+ });
1635
+
1636
+ it("CF_AGENT_TOOL_RESULT does not update tool already in output-denied state", async () => {
1637
+ const room = crypto.randomUUID();
1638
+ const ctx = createExecutionContext();
1639
+ const req = new Request(
1640
+ `http://example.com/agents/test-chat-agent/${room}`,
1641
+ { headers: { Upgrade: "websocket" } }
1642
+ );
1643
+ const res = await worker.fetch(req, env, ctx);
1644
+ expect(res.status).toBe(101);
1645
+ const ws = res.webSocket as WebSocket;
1646
+ ws.accept();
1647
+ await ctx.waitUntil(Promise.resolve());
1648
+
1649
+ const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1650
+ const toolCallId = "call_already_denied";
1651
+
1652
+ await agentStub.persistMessages([
1653
+ {
1654
+ id: "user-1",
1655
+ role: "user",
1656
+ parts: [{ type: "text", text: "Execute tool" }]
1657
+ },
1658
+ {
1659
+ id: "assistant-1",
1660
+ role: "assistant",
1661
+ parts: [
1662
+ {
1663
+ type: "tool-testTool",
1664
+ toolCallId,
1665
+ state: "output-denied",
1666
+ input: { param: "value" },
1667
+ approval: { id: "approval-denied-guard", approved: false }
1668
+ }
1669
+ ] as ChatMessage["parts"]
1670
+ }
1671
+ ]);
1672
+
1673
+ ws.send(
1674
+ JSON.stringify({
1675
+ type: "cf_agent_tool_result",
1676
+ toolCallId,
1677
+ toolName: "testTool",
1678
+ output: { result: "override attempt" }
1679
+ })
1680
+ );
1681
+
1682
+ await new Promise((resolve) => setTimeout(resolve, 200));
1683
+
1684
+ const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1685
+ const assistantMessages = messages.filter((m) => m.role === "assistant");
1686
+
1687
+ expect(assistantMessages.length).toBe(1);
1688
+
1689
+ const toolPart = assistantMessages[0].parts[0] as {
1690
+ state: string;
1691
+ };
1692
+ expect(toolPart.state).toBe("output-denied");
1693
+
1694
+ ws.close(1000);
1695
+ });
1696
+
1697
+ it("CF_AGENT_TOOL_RESULT does not update tool already in output-available state", async () => {
1698
+ const room = crypto.randomUUID();
1699
+ const ctx = createExecutionContext();
1700
+ const req = new Request(
1701
+ `http://example.com/agents/test-chat-agent/${room}`,
1702
+ { headers: { Upgrade: "websocket" } }
1703
+ );
1704
+ const res = await worker.fetch(req, env, ctx);
1705
+ expect(res.status).toBe(101);
1706
+ const ws = res.webSocket as WebSocket;
1707
+ ws.accept();
1708
+ await ctx.waitUntil(Promise.resolve());
1709
+
1710
+ const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1711
+ const toolCallId = "call_already_completed_tr";
1712
+
1713
+ await agentStub.persistMessages([
1714
+ {
1715
+ id: "user-1",
1716
+ role: "user",
1717
+ parts: [{ type: "text", text: "Execute tool" }]
1718
+ },
1719
+ {
1720
+ id: "assistant-1",
1721
+ role: "assistant",
1722
+ parts: [
1723
+ {
1724
+ type: "tool-testTool",
1725
+ toolCallId,
1726
+ state: "output-available",
1727
+ input: { param: "value" },
1728
+ output: { result: "original" }
1729
+ }
1730
+ ] as ChatMessage["parts"]
1731
+ }
1732
+ ]);
1733
+
1734
+ ws.send(
1735
+ JSON.stringify({
1736
+ type: "cf_agent_tool_result",
1737
+ toolCallId,
1738
+ toolName: "testTool",
1739
+ output: { result: "override attempt" }
1740
+ })
1741
+ );
1742
+
1743
+ await new Promise((resolve) => setTimeout(resolve, 200));
1744
+
1745
+ const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1746
+ const assistantMessages = messages.filter((m) => m.role === "assistant");
1747
+
1748
+ expect(assistantMessages.length).toBe(1);
1749
+
1750
+ const toolPart = assistantMessages[0].parts[0] as {
1751
+ state: string;
1752
+ output?: unknown;
1753
+ };
1754
+ expect(toolPart.state).toBe("output-available");
1755
+ expect(toolPart.output).toEqual({ result: "original" });
1756
+
1757
+ ws.close(1000);
1758
+ });
1759
+
1760
+ it("applies tool result to a tool in approval-responded state", async () => {
1761
+ const room = crypto.randomUUID();
1762
+ const ctx = createExecutionContext();
1763
+ const req = new Request(
1764
+ `http://example.com/agents/test-chat-agent/${room}`,
1765
+ { headers: { Upgrade: "websocket" } }
1766
+ );
1767
+ const res = await worker.fetch(req, env, ctx);
1768
+ expect(res.status).toBe(101);
1769
+ const ws = res.webSocket as WebSocket;
1770
+ ws.accept();
1771
+ await ctx.waitUntil(Promise.resolve());
1772
+
1773
+ const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1774
+ const toolCallId = "call_responded_tool_result";
1775
+
1776
+ await agentStub.persistMessages([
1777
+ {
1778
+ id: "user-1",
1779
+ role: "user",
1780
+ parts: [{ type: "text", text: "Execute tool" }]
1781
+ },
1782
+ {
1783
+ id: "assistant-1",
1784
+ role: "assistant",
1785
+ parts: [
1786
+ {
1787
+ type: "tool-testTool",
1788
+ toolCallId,
1789
+ state: "approval-responded",
1790
+ input: { param: "value" },
1791
+ approval: { id: "approval-resp-1", approved: true }
1792
+ }
1793
+ ] as ChatMessage["parts"]
1794
+ }
1795
+ ]);
1796
+
1797
+ ws.send(
1798
+ JSON.stringify({
1799
+ type: "cf_agent_tool_result",
1800
+ toolCallId,
1801
+ toolName: "testTool",
1802
+ output: { result: "custom result" }
1803
+ })
1804
+ );
1805
+
1806
+ await new Promise((resolve) => setTimeout(resolve, 200));
1807
+
1808
+ const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1809
+ const assistantMessages = messages.filter((m) => m.role === "assistant");
1810
+
1811
+ expect(assistantMessages.length).toBe(1);
1812
+
1813
+ const toolPart = assistantMessages[0].parts[0] as {
1814
+ state: string;
1815
+ output?: unknown;
1816
+ };
1817
+ expect(toolPart.state).toBe("output-available");
1818
+ expect(toolPart.output).toEqual({ result: "custom result" });
1819
+
1820
+ ws.close(1000);
1821
+ });
1822
+
1823
+ it("output-error without errorText uses default message", async () => {
1824
+ const room = crypto.randomUUID();
1825
+ const ctx = createExecutionContext();
1826
+ const req = new Request(
1827
+ `http://example.com/agents/test-chat-agent/${room}`,
1828
+ { headers: { Upgrade: "websocket" } }
1829
+ );
1830
+ const res = await worker.fetch(req, env, ctx);
1831
+ expect(res.status).toBe(101);
1832
+ const ws = res.webSocket as WebSocket;
1833
+ ws.accept();
1834
+ await ctx.waitUntil(Promise.resolve());
1835
+
1836
+ const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1837
+ const toolCallId = "call_default_error";
1838
+
1839
+ await agentStub.persistMessages([
1840
+ {
1841
+ id: "user-1",
1842
+ role: "user",
1843
+ parts: [{ type: "text", text: "Execute tool" }]
1844
+ },
1845
+ {
1846
+ id: "assistant-1",
1847
+ role: "assistant",
1848
+ parts: [
1849
+ {
1850
+ type: "tool-testTool",
1851
+ toolCallId,
1852
+ state: "input-available",
1853
+ input: { param: "value" }
1854
+ }
1855
+ ] as ChatMessage["parts"]
1856
+ }
1857
+ ]);
1858
+
1859
+ ws.send(
1860
+ JSON.stringify({
1861
+ type: "cf_agent_tool_result",
1862
+ toolCallId,
1863
+ toolName: "testTool",
1864
+ output: null,
1865
+ state: "output-error"
1866
+ })
1867
+ );
1868
+
1869
+ await new Promise((resolve) => setTimeout(resolve, 200));
1870
+
1871
+ const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1872
+ const assistantMessages = messages.filter((m) => m.role === "assistant");
1873
+
1874
+ expect(assistantMessages.length).toBe(1);
1875
+
1876
+ const toolPart = assistantMessages[0].parts[0] as {
1877
+ state: string;
1878
+ errorText?: string;
1879
+ };
1880
+ expect(toolPart.state).toBe("output-error");
1881
+ expect(toolPart.errorText).toBe("Tool execution denied by user");
1882
+
1883
+ ws.close(1000);
1884
+ });
1885
+
1886
+ it("output-error on approval-responded produces tool_result via convertToModelMessages", async () => {
1887
+ const room = crypto.randomUUID();
1888
+ const ctx = createExecutionContext();
1889
+ const req = new Request(
1890
+ `http://example.com/agents/test-chat-agent/${room}`,
1891
+ { headers: { Upgrade: "websocket" } }
1892
+ );
1893
+ const res = await worker.fetch(req, env, ctx);
1894
+ expect(res.status).toBe(101);
1895
+ const ws = res.webSocket as WebSocket;
1896
+ ws.accept();
1897
+ await ctx.waitUntil(Promise.resolve());
1898
+
1899
+ const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
1900
+ const toolCallId = "call_e2e_responded_error";
1901
+
1902
+ await agentStub.persistMessages([
1903
+ {
1904
+ id: "user-1",
1905
+ role: "user",
1906
+ parts: [{ type: "text", text: "Run the tool" }]
1907
+ },
1908
+ {
1909
+ id: "assistant-1",
1910
+ role: "assistant",
1911
+ parts: [
1912
+ {
1913
+ type: "tool-testTool",
1914
+ toolCallId,
1915
+ state: "approval-responded",
1916
+ input: { param: "value" },
1917
+ approval: { id: "approval-e2e-2", approved: true }
1918
+ }
1919
+ ] as ChatMessage["parts"]
1920
+ }
1921
+ ]);
1922
+
1923
+ ws.send(
1924
+ JSON.stringify({
1925
+ type: "cf_agent_tool_result",
1926
+ toolCallId,
1927
+ toolName: "testTool",
1928
+ output: null,
1929
+ state: "output-error",
1930
+ errorText: "Execution failed: timeout"
1931
+ })
1932
+ );
1933
+
1934
+ await new Promise((resolve) => setTimeout(resolve, 200));
1935
+
1936
+ const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
1937
+ const modelMessages = await convertToModelMessages(messages);
1938
+
1939
+ const toolMessage = modelMessages.find((m) => m.role === "tool");
1940
+ expect(toolMessage).toBeDefined();
1941
+
1942
+ const toolContent = toolMessage!.content as Array<{
1943
+ type: string;
1944
+ [key: string]: unknown;
1945
+ }>;
1946
+
1947
+ const toolResult = toolContent.find((c) => c.type === "tool-result");
1948
+ expect(toolResult).toBeDefined();
1949
+ expect(toolResult!.toolCallId).toBe(toolCallId);
1950
+
1951
+ const output = toolResult!.output as { type: string; value: string };
1952
+ expect(output.type).toBe("error-text");
1953
+ expect(output.value).toBe("Execution failed: timeout");
1954
+
1955
+ ws.close(1000);
1956
+ });
1957
+ });