File size: 56,493 Bytes
064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 | /**
* SDK Core Schemas - Zod schemas for serializable SDK data types.
*
* These schemas are the single source of truth for SDK data types.
* TypeScript types are generated from these schemas and committed for IDE support.
*
* @see scripts/generate-sdk-types.ts for type generation
*/
import { z } from 'zod/v4'
import { lazySchema } from '../../utils/lazySchema.js'
// ============================================================================
// Usage & Model Types
// ============================================================================
export const ModelUsageSchema = lazySchema(() =>
z.object({
inputTokens: z.number(),
outputTokens: z.number(),
cacheReadInputTokens: z.number(),
cacheCreationInputTokens: z.number(),
webSearchRequests: z.number(),
costUSD: z.number(),
contextWindow: z.number(),
maxOutputTokens: z.number(),
}),
)
// ============================================================================
// Output Format Types
// ============================================================================
export const OutputFormatTypeSchema = lazySchema(() => z.literal('json_schema'))
export const BaseOutputFormatSchema = lazySchema(() =>
z.object({
type: OutputFormatTypeSchema(),
}),
)
export const JsonSchemaOutputFormatSchema = lazySchema(() =>
z.object({
type: z.literal('json_schema'),
schema: z.record(z.string(), z.unknown()),
}),
)
export const OutputFormatSchema = lazySchema(() =>
JsonSchemaOutputFormatSchema(),
)
// ============================================================================
// Config Types
// ============================================================================
export const ApiKeySourceSchema = lazySchema(() =>
z.enum(['user', 'project', 'org', 'temporary', 'oauth']),
)
export const ConfigScopeSchema = lazySchema(() =>
z.enum(['local', 'user', 'project']).describe('Config scope for settings.'),
)
export const SdkBetaSchema = lazySchema(() =>
z.literal('context-1m-2025-08-07'),
)
export const ThinkingAdaptiveSchema = lazySchema(() =>
z
.object({
type: z.literal('adaptive'),
})
.describe('Claude decides when and how much to think (Opus 4.6+).'),
)
export const ThinkingEnabledSchema = lazySchema(() =>
z
.object({
type: z.literal('enabled'),
budgetTokens: z.number().optional(),
})
.describe('Fixed thinking token budget (older models)'),
)
export const ThinkingDisabledSchema = lazySchema(() =>
z
.object({
type: z.literal('disabled'),
})
.describe('No extended thinking'),
)
export const ThinkingConfigSchema = lazySchema(() =>
z
.union([
ThinkingAdaptiveSchema(),
ThinkingEnabledSchema(),
ThinkingDisabledSchema(),
])
.describe(
"Controls Claude's thinking/reasoning behavior. When set, takes precedence over the deprecated maxThinkingTokens.",
),
)
// ============================================================================
// MCP Server Config Types (serializable only)
// ============================================================================
export const McpStdioServerConfigSchema = lazySchema(() =>
z.object({
type: z.literal('stdio').optional(), // Optional for backwards compatibility
command: z.string(),
args: z.array(z.string()).optional(),
env: z.record(z.string(), z.string()).optional(),
}),
)
export const McpSSEServerConfigSchema = lazySchema(() =>
z.object({
type: z.literal('sse'),
url: z.string(),
headers: z.record(z.string(), z.string()).optional(),
}),
)
export const McpHttpServerConfigSchema = lazySchema(() =>
z.object({
type: z.literal('http'),
url: z.string(),
headers: z.record(z.string(), z.string()).optional(),
}),
)
export const McpSdkServerConfigSchema = lazySchema(() =>
z.object({
type: z.literal('sdk'),
name: z.string(),
}),
)
export const McpServerConfigForProcessTransportSchema = lazySchema(() =>
z.union([
McpStdioServerConfigSchema(),
McpSSEServerConfigSchema(),
McpHttpServerConfigSchema(),
McpSdkServerConfigSchema(),
]),
)
export const McpClaudeAIProxyServerConfigSchema = lazySchema(() =>
z.object({
type: z.literal('claudeai-proxy'),
url: z.string(),
id: z.string(),
}),
)
// Broader config type for status responses (includes claudeai-proxy which is output-only)
export const McpServerStatusConfigSchema = lazySchema(() =>
z.union([
McpServerConfigForProcessTransportSchema(),
McpClaudeAIProxyServerConfigSchema(),
]),
)
export const McpServerStatusSchema = lazySchema(() =>
z
.object({
name: z.string().describe('Server name as configured'),
status: z
.enum(['connected', 'failed', 'needs-auth', 'pending', 'disabled'])
.describe('Current connection status'),
serverInfo: z
.object({
name: z.string(),
version: z.string(),
})
.optional()
.describe('Server information (available when connected)'),
error: z
.string()
.optional()
.describe("Error message (available when status is 'failed')"),
config: McpServerStatusConfigSchema()
.optional()
.describe('Server configuration (includes URL for HTTP/SSE servers)'),
scope: z
.string()
.optional()
.describe(
'Configuration scope (e.g., project, user, local, claudeai, managed)',
),
tools: z
.array(
z.object({
name: z.string(),
description: z.string().optional(),
annotations: z
.object({
readOnly: z.boolean().optional(),
destructive: z.boolean().optional(),
openWorld: z.boolean().optional(),
})
.optional(),
}),
)
.optional()
.describe('Tools provided by this server (available when connected)'),
capabilities: z
.object({
experimental: z.record(z.string(), z.unknown()).optional(),
})
.optional()
.describe(
"@internal Server capabilities (available when connected). experimental['claude/channel'] is only present if the server's plugin is on the approved channels allowlist — use its presence to decide whether to show an Enable-channel prompt.",
),
})
.describe('Status information for an MCP server connection.'),
)
export const McpSetServersResultSchema = lazySchema(() =>
z
.object({
added: z.array(z.string()).describe('Names of servers that were added'),
removed: z
.array(z.string())
.describe('Names of servers that were removed'),
errors: z
.record(z.string(), z.string())
.describe(
'Map of server names to error messages for servers that failed to connect',
),
})
.describe('Result of a setMcpServers operation.'),
)
// ============================================================================
// Permission Types
// ============================================================================
export const PermissionUpdateDestinationSchema = lazySchema(() =>
z.enum([
'userSettings',
'projectSettings',
'localSettings',
'session',
'cliArg',
]),
)
export const PermissionBehaviorSchema = lazySchema(() =>
z.enum(['allow', 'deny', 'ask']),
)
export const PermissionRuleValueSchema = lazySchema(() =>
z.object({
toolName: z.string(),
ruleContent: z.string().optional(),
}),
)
export const PermissionUpdateSchema = lazySchema(() =>
z.discriminatedUnion('type', [
z.object({
type: z.literal('addRules'),
rules: z.array(PermissionRuleValueSchema()),
behavior: PermissionBehaviorSchema(),
destination: PermissionUpdateDestinationSchema(),
}),
z.object({
type: z.literal('replaceRules'),
rules: z.array(PermissionRuleValueSchema()),
behavior: PermissionBehaviorSchema(),
destination: PermissionUpdateDestinationSchema(),
}),
z.object({
type: z.literal('removeRules'),
rules: z.array(PermissionRuleValueSchema()),
behavior: PermissionBehaviorSchema(),
destination: PermissionUpdateDestinationSchema(),
}),
z.object({
type: z.literal('setMode'),
mode: z.lazy(() => PermissionModeSchema()),
destination: PermissionUpdateDestinationSchema(),
}),
z.object({
type: z.literal('addDirectories'),
directories: z.array(z.string()),
destination: PermissionUpdateDestinationSchema(),
}),
z.object({
type: z.literal('removeDirectories'),
directories: z.array(z.string()),
destination: PermissionUpdateDestinationSchema(),
}),
]),
)
export const PermissionDecisionClassificationSchema = lazySchema(() =>
z
.enum(['user_temporary', 'user_permanent', 'user_reject'])
.describe(
'Classification of this permission decision for telemetry. SDK hosts ' +
'that prompt users (desktop apps, IDEs) should set this to reflect ' +
'what actually happened: user_temporary for allow-once, user_permanent ' +
'for always-allow (both the click and later cache hits), user_reject ' +
'for deny. If unset, the CLI infers conservatively (temporary for ' +
'allow, reject for deny). The vocabulary matches tool_decision OTel ' +
'events (monitoring-usage docs).',
),
)
export const PermissionResultSchema = lazySchema(() =>
z.union([
z.object({
behavior: z.literal('allow'),
// Optional - may not be provided if hook sets permission without input modification
updatedInput: z.record(z.string(), z.unknown()).optional(),
updatedPermissions: z.array(PermissionUpdateSchema()).optional(),
toolUseID: z.string().optional(),
decisionClassification:
PermissionDecisionClassificationSchema().optional(),
}),
z.object({
behavior: z.literal('deny'),
message: z.string(),
interrupt: z.boolean().optional(),
toolUseID: z.string().optional(),
decisionClassification:
PermissionDecisionClassificationSchema().optional(),
}),
]),
)
export const PermissionModeSchema = lazySchema(() =>
z
.enum(['default', 'acceptEdits', 'bypassPermissions', 'plan', 'dontAsk'])
.describe(
'Permission mode for controlling how tool executions are handled. ' +
"'default' - Standard behavior, prompts for dangerous operations. " +
"'acceptEdits' - Auto-accept file edit operations. " +
"'bypassPermissions' - Bypass all permission checks (requires allowDangerouslySkipPermissions). " +
"'plan' - Planning mode, no actual tool execution. " +
"'dontAsk' - Don't prompt for permissions, deny if not pre-approved.",
),
)
// ============================================================================
// Hook Types
// ============================================================================
export const HOOK_EVENTS = [
'PreToolUse',
'PostToolUse',
'PostToolUseFailure',
'Notification',
'UserPromptSubmit',
'SessionStart',
'SessionEnd',
'Stop',
'StopFailure',
'SubagentStart',
'SubagentStop',
'PreCompact',
'PostCompact',
'PermissionRequest',
'PermissionDenied',
'Setup',
'TeammateIdle',
'TaskCreated',
'TaskCompleted',
'Elicitation',
'ElicitationResult',
'ConfigChange',
'WorktreeCreate',
'WorktreeRemove',
'InstructionsLoaded',
'CwdChanged',
'FileChanged',
] as const
export const HookEventSchema = lazySchema(() => z.enum(HOOK_EVENTS))
export const BaseHookInputSchema = lazySchema(() =>
z.object({
session_id: z.string(),
transcript_path: z.string(),
cwd: z.string(),
permission_mode: z.string().optional(),
agent_id: z
.string()
.optional()
.describe(
'Subagent identifier. Present only when the hook fires from within a subagent ' +
'(e.g., a tool called by an AgentTool worker). Absent for the main thread, ' +
'even in --agent sessions. Use this field (not agent_type) to distinguish ' +
'subagent calls from main-thread calls.',
),
agent_type: z
.string()
.optional()
.describe(
'Agent type name (e.g., "general-purpose", "code-reviewer"). Present when the ' +
'hook fires from within a subagent (alongside agent_id), or on the main thread ' +
'of a session started with --agent (without agent_id).',
),
}),
)
// Use .and() instead of .extend() to preserve BaseHookInput & {...} in generated types
export const PreToolUseHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('PreToolUse'),
tool_name: z.string(),
tool_input: z.unknown(),
tool_use_id: z.string(),
}),
),
)
export const PermissionRequestHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('PermissionRequest'),
tool_name: z.string(),
tool_input: z.unknown(),
permission_suggestions: z.array(PermissionUpdateSchema()).optional(),
}),
),
)
export const PostToolUseHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('PostToolUse'),
tool_name: z.string(),
tool_input: z.unknown(),
tool_response: z.unknown(),
tool_use_id: z.string(),
}),
),
)
export const PostToolUseFailureHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('PostToolUseFailure'),
tool_name: z.string(),
tool_input: z.unknown(),
tool_use_id: z.string(),
error: z.string(),
is_interrupt: z.boolean().optional(),
}),
),
)
export const PermissionDeniedHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('PermissionDenied'),
tool_name: z.string(),
tool_input: z.unknown(),
tool_use_id: z.string(),
reason: z.string(),
}),
),
)
export const NotificationHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('Notification'),
message: z.string(),
title: z.string().optional(),
notification_type: z.string(),
}),
),
)
export const UserPromptSubmitHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('UserPromptSubmit'),
prompt: z.string(),
}),
),
)
export const SessionStartHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('SessionStart'),
source: z.enum(['startup', 'resume', 'clear', 'compact']),
agent_type: z.string().optional(),
model: z.string().optional(),
}),
),
)
export const SetupHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('Setup'),
trigger: z.enum(['init', 'maintenance']),
}),
),
)
export const StopHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('Stop'),
stop_hook_active: z.boolean(),
last_assistant_message: z
.string()
.optional()
.describe(
'Text content of the last assistant message before stopping. ' +
'Avoids the need to read and parse the transcript file.',
),
}),
),
)
export const StopFailureHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('StopFailure'),
error: SDKAssistantMessageErrorSchema(),
error_details: z.string().optional(),
last_assistant_message: z.string().optional(),
}),
),
)
export const SubagentStartHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('SubagentStart'),
agent_id: z.string(),
agent_type: z.string(),
}),
),
)
export const SubagentStopHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('SubagentStop'),
stop_hook_active: z.boolean(),
agent_id: z.string(),
agent_transcript_path: z.string(),
agent_type: z.string(),
last_assistant_message: z
.string()
.optional()
.describe(
'Text content of the last assistant message before stopping. ' +
'Avoids the need to read and parse the transcript file.',
),
}),
),
)
export const PreCompactHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('PreCompact'),
trigger: z.enum(['manual', 'auto']),
custom_instructions: z.string().nullable(),
}),
),
)
export const PostCompactHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('PostCompact'),
trigger: z.enum(['manual', 'auto']),
compact_summary: z
.string()
.describe('The conversation summary produced by compaction'),
}),
),
)
export const TeammateIdleHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('TeammateIdle'),
teammate_name: z.string(),
team_name: z.string(),
}),
),
)
export const TaskCreatedHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('TaskCreated'),
task_id: z.string(),
task_subject: z.string(),
task_description: z.string().optional(),
teammate_name: z.string().optional(),
team_name: z.string().optional(),
}),
),
)
export const TaskCompletedHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('TaskCompleted'),
task_id: z.string(),
task_subject: z.string(),
task_description: z.string().optional(),
teammate_name: z.string().optional(),
team_name: z.string().optional(),
}),
),
)
export const ElicitationHookInputSchema = lazySchema(() =>
BaseHookInputSchema()
.and(
z.object({
hook_event_name: z.literal('Elicitation'),
mcp_server_name: z.string(),
message: z.string(),
mode: z.enum(['form', 'url']).optional(),
url: z.string().optional(),
elicitation_id: z.string().optional(),
requested_schema: z.record(z.string(), z.unknown()).optional(),
}),
)
.describe(
'Hook input for the Elicitation event. Fired when an MCP server requests user input. Hooks can auto-respond (accept/decline) instead of showing the dialog.',
),
)
export const ElicitationResultHookInputSchema = lazySchema(() =>
BaseHookInputSchema()
.and(
z.object({
hook_event_name: z.literal('ElicitationResult'),
mcp_server_name: z.string(),
elicitation_id: z.string().optional(),
mode: z.enum(['form', 'url']).optional(),
action: z.enum(['accept', 'decline', 'cancel']),
content: z.record(z.string(), z.unknown()).optional(),
}),
)
.describe(
'Hook input for the ElicitationResult event. Fired after the user responds to an MCP elicitation. Hooks can observe or override the response before it is sent to the server.',
),
)
export const CONFIG_CHANGE_SOURCES = [
'user_settings',
'project_settings',
'local_settings',
'policy_settings',
'skills',
] as const
export const ConfigChangeHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('ConfigChange'),
source: z.enum(CONFIG_CHANGE_SOURCES),
file_path: z.string().optional(),
}),
),
)
export const INSTRUCTIONS_LOAD_REASONS = [
'session_start',
'nested_traversal',
'path_glob_match',
'include',
'compact',
] as const
export const INSTRUCTIONS_MEMORY_TYPES = [
'User',
'Project',
'Local',
'Managed',
] as const
export const InstructionsLoadedHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('InstructionsLoaded'),
file_path: z.string(),
memory_type: z.enum(INSTRUCTIONS_MEMORY_TYPES),
load_reason: z.enum(INSTRUCTIONS_LOAD_REASONS),
globs: z.array(z.string()).optional(),
trigger_file_path: z.string().optional(),
parent_file_path: z.string().optional(),
}),
),
)
export const WorktreeCreateHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('WorktreeCreate'),
name: z.string(),
}),
),
)
export const WorktreeRemoveHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('WorktreeRemove'),
worktree_path: z.string(),
}),
),
)
export const CwdChangedHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('CwdChanged'),
old_cwd: z.string(),
new_cwd: z.string(),
}),
),
)
export const FileChangedHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('FileChanged'),
file_path: z.string(),
event: z.enum(['change', 'add', 'unlink']),
}),
),
)
export const EXIT_REASONS = [
'clear',
'resume',
'logout',
'prompt_input_exit',
'other',
'bypass_permissions_disabled',
] as const
export const ExitReasonSchema = lazySchema(() => z.enum(EXIT_REASONS))
export const SessionEndHookInputSchema = lazySchema(() =>
BaseHookInputSchema().and(
z.object({
hook_event_name: z.literal('SessionEnd'),
reason: ExitReasonSchema(),
}),
),
)
export const HookInputSchema = lazySchema(() =>
z.union([
PreToolUseHookInputSchema(),
PostToolUseHookInputSchema(),
PostToolUseFailureHookInputSchema(),
PermissionDeniedHookInputSchema(),
NotificationHookInputSchema(),
UserPromptSubmitHookInputSchema(),
SessionStartHookInputSchema(),
SessionEndHookInputSchema(),
StopHookInputSchema(),
StopFailureHookInputSchema(),
SubagentStartHookInputSchema(),
SubagentStopHookInputSchema(),
PreCompactHookInputSchema(),
PostCompactHookInputSchema(),
PermissionRequestHookInputSchema(),
SetupHookInputSchema(),
TeammateIdleHookInputSchema(),
TaskCreatedHookInputSchema(),
TaskCompletedHookInputSchema(),
ElicitationHookInputSchema(),
ElicitationResultHookInputSchema(),
ConfigChangeHookInputSchema(),
InstructionsLoadedHookInputSchema(),
WorktreeCreateHookInputSchema(),
WorktreeRemoveHookInputSchema(),
CwdChangedHookInputSchema(),
FileChangedHookInputSchema(),
]),
)
export const AsyncHookJSONOutputSchema = lazySchema(() =>
z.object({
async: z.literal(true),
asyncTimeout: z.number().optional(),
}),
)
export const PreToolUseHookSpecificOutputSchema = lazySchema(() =>
z.object({
hookEventName: z.literal('PreToolUse'),
permissionDecision: PermissionBehaviorSchema().optional(),
permissionDecisionReason: z.string().optional(),
updatedInput: z.record(z.string(), z.unknown()).optional(),
additionalContext: z.string().optional(),
}),
)
export const UserPromptSubmitHookSpecificOutputSchema = lazySchema(() =>
z.object({
hookEventName: z.literal('UserPromptSubmit'),
additionalContext: z.string().optional(),
}),
)
export const SessionStartHookSpecificOutputSchema = lazySchema(() =>
z.object({
hookEventName: z.literal('SessionStart'),
additionalContext: z.string().optional(),
initialUserMessage: z.string().optional(),
watchPaths: z.array(z.string()).optional(),
}),
)
export const SetupHookSpecificOutputSchema = lazySchema(() =>
z.object({
hookEventName: z.literal('Setup'),
additionalContext: z.string().optional(),
}),
)
export const SubagentStartHookSpecificOutputSchema = lazySchema(() =>
z.object({
hookEventName: z.literal('SubagentStart'),
additionalContext: z.string().optional(),
}),
)
export const PostToolUseHookSpecificOutputSchema = lazySchema(() =>
z.object({
hookEventName: z.literal('PostToolUse'),
additionalContext: z.string().optional(),
updatedMCPToolOutput: z.unknown().optional(),
}),
)
export const PostToolUseFailureHookSpecificOutputSchema = lazySchema(() =>
z.object({
hookEventName: z.literal('PostToolUseFailure'),
additionalContext: z.string().optional(),
}),
)
export const PermissionDeniedHookSpecificOutputSchema = lazySchema(() =>
z.object({
hookEventName: z.literal('PermissionDenied'),
retry: z.boolean().optional(),
}),
)
export const NotificationHookSpecificOutputSchema = lazySchema(() =>
z.object({
hookEventName: z.literal('Notification'),
additionalContext: z.string().optional(),
}),
)
export const PermissionRequestHookSpecificOutputSchema = lazySchema(() =>
z.object({
hookEventName: z.literal('PermissionRequest'),
decision: z.union([
z.object({
behavior: z.literal('allow'),
updatedInput: z.record(z.string(), z.unknown()).optional(),
updatedPermissions: z.array(PermissionUpdateSchema()).optional(),
}),
z.object({
behavior: z.literal('deny'),
message: z.string().optional(),
interrupt: z.boolean().optional(),
}),
]),
}),
)
export const CwdChangedHookSpecificOutputSchema = lazySchema(() =>
z.object({
hookEventName: z.literal('CwdChanged'),
watchPaths: z.array(z.string()).optional(),
}),
)
export const FileChangedHookSpecificOutputSchema = lazySchema(() =>
z.object({
hookEventName: z.literal('FileChanged'),
watchPaths: z.array(z.string()).optional(),
}),
)
export const SyncHookJSONOutputSchema = lazySchema(() =>
z.object({
continue: z.boolean().optional(),
suppressOutput: z.boolean().optional(),
stopReason: z.string().optional(),
decision: z.enum(['approve', 'block']).optional(),
systemMessage: z.string().optional(),
reason: z.string().optional(),
hookSpecificOutput: z
.union([
PreToolUseHookSpecificOutputSchema(),
UserPromptSubmitHookSpecificOutputSchema(),
SessionStartHookSpecificOutputSchema(),
SetupHookSpecificOutputSchema(),
SubagentStartHookSpecificOutputSchema(),
PostToolUseHookSpecificOutputSchema(),
PostToolUseFailureHookSpecificOutputSchema(),
PermissionDeniedHookSpecificOutputSchema(),
NotificationHookSpecificOutputSchema(),
PermissionRequestHookSpecificOutputSchema(),
ElicitationHookSpecificOutputSchema(),
ElicitationResultHookSpecificOutputSchema(),
CwdChangedHookSpecificOutputSchema(),
FileChangedHookSpecificOutputSchema(),
WorktreeCreateHookSpecificOutputSchema(),
])
.optional(),
}),
)
export const ElicitationHookSpecificOutputSchema = lazySchema(() =>
z
.object({
hookEventName: z.literal('Elicitation'),
action: z.enum(['accept', 'decline', 'cancel']).optional(),
content: z.record(z.string(), z.unknown()).optional(),
})
.describe(
'Hook-specific output for the Elicitation event. Return this to programmatically accept or decline an MCP elicitation request.',
),
)
export const ElicitationResultHookSpecificOutputSchema = lazySchema(() =>
z
.object({
hookEventName: z.literal('ElicitationResult'),
action: z.enum(['accept', 'decline', 'cancel']).optional(),
content: z.record(z.string(), z.unknown()).optional(),
})
.describe(
'Hook-specific output for the ElicitationResult event. Return this to override the action or content before the response is sent to the MCP server.',
),
)
export const WorktreeCreateHookSpecificOutputSchema = lazySchema(() =>
z
.object({
hookEventName: z.literal('WorktreeCreate'),
worktreePath: z.string(),
})
.describe(
'Hook-specific output for the WorktreeCreate event. Provides the absolute path to the created worktree directory. Command hooks print the path on stdout instead.',
),
)
export const HookJSONOutputSchema = lazySchema(() =>
z.union([AsyncHookJSONOutputSchema(), SyncHookJSONOutputSchema()]),
)
export const PromptRequestOptionSchema = lazySchema(() =>
z.object({
key: z
.string()
.describe('Unique key for this option, returned in the response'),
label: z.string().describe('Display text for this option'),
description: z
.string()
.optional()
.describe('Optional description shown below the label'),
}),
)
export const PromptRequestSchema = lazySchema(() =>
z.object({
prompt: z
.string()
.describe(
'Request ID. Presence of this key marks the line as a prompt request.',
),
message: z.string().describe('The prompt message to display to the user'),
options: z
.array(PromptRequestOptionSchema())
.describe('Available options for the user to choose from'),
}),
)
export const PromptResponseSchema = lazySchema(() =>
z.object({
prompt_response: z
.string()
.describe('The request ID from the corresponding prompt request'),
selected: z.string().describe('The key of the selected option'),
}),
)
// ============================================================================
// Skill/Command Types
// ============================================================================
export const SlashCommandSchema = lazySchema(() =>
z
.object({
name: z.string().describe('Skill name (without the leading slash)'),
description: z.string().describe('Description of what the skill does'),
argumentHint: z
.string()
.describe('Hint for skill arguments (e.g., "<file>")'),
})
.describe(
'Information about an available skill (invoked via /command syntax).',
),
)
export const AgentInfoSchema = lazySchema(() =>
z
.object({
name: z.string().describe('Agent type identifier (e.g., "Explore")'),
description: z.string().describe('Description of when to use this agent'),
model: z
.string()
.optional()
.describe(
"Model alias this agent uses. If omitted, inherits the parent's model",
),
})
.describe(
'Information about an available subagent that can be invoked via the Task tool.',
),
)
export const ModelInfoSchema = lazySchema(() =>
z
.object({
value: z.string().describe('Model identifier to use in API calls'),
displayName: z.string().describe('Human-readable display name'),
description: z
.string()
.describe("Description of the model's capabilities"),
supportsEffort: z
.boolean()
.optional()
.describe('Whether this model supports effort levels'),
supportedEffortLevels: z
.array(z.enum(['low', 'medium', 'high', 'max']))
.optional()
.describe('Available effort levels for this model'),
supportsAdaptiveThinking: z
.boolean()
.optional()
.describe(
'Whether this model supports adaptive thinking (Claude decides when and how much to think)',
),
supportsFastMode: z
.boolean()
.optional()
.describe('Whether this model supports fast mode'),
supportsAutoMode: z
.boolean()
.optional()
.describe('Whether this model supports auto mode'),
})
.describe('Information about an available model.'),
)
export const AccountInfoSchema = lazySchema(() =>
z
.object({
email: z.string().optional(),
organization: z.string().optional(),
subscriptionType: z.string().optional(),
tokenSource: z.string().optional(),
apiKeySource: z.string().optional(),
apiProvider: z
.enum(['firstParty', 'bedrock', 'vertex', 'foundry'])
.optional()
.describe(
'Active API backend. Anthropic OAuth login only applies when "firstParty"; for 3P providers the other fields are absent and auth is external (AWS creds, gcloud ADC, etc.).',
),
})
.describe("Information about the logged in user's account."),
)
// ============================================================================
// Agent Definition Types
// ============================================================================
export const AgentMcpServerSpecSchema = lazySchema(() =>
z.union([
z.string(),
z.record(z.string(), McpServerConfigForProcessTransportSchema()),
]),
)
export const AgentDefinitionSchema = lazySchema(() =>
z
.object({
description: z
.string()
.describe('Natural language description of when to use this agent'),
tools: z
.array(z.string())
.optional()
.describe(
'Array of allowed tool names. If omitted, inherits all tools from parent',
),
disallowedTools: z
.array(z.string())
.optional()
.describe('Array of tool names to explicitly disallow for this agent'),
prompt: z.string().describe("The agent's system prompt"),
model: z
.string()
.optional()
.describe(
"Model alias (e.g. 'sonnet', 'opus', 'haiku') or full model ID (e.g. 'claude-opus-4-5'). If omitted or 'inherit', uses the main model",
),
mcpServers: z.array(AgentMcpServerSpecSchema()).optional(),
criticalSystemReminder_EXPERIMENTAL: z
.string()
.optional()
.describe('Experimental: Critical reminder added to system prompt'),
skills: z
.array(z.string())
.optional()
.describe('Array of skill names to preload into the agent context'),
initialPrompt: z
.string()
.optional()
.describe(
'Auto-submitted as the first user turn when this agent is the main thread agent. Slash commands are processed. Prepended to any user-provided prompt.',
),
maxTurns: z
.number()
.int()
.positive()
.optional()
.describe(
'Maximum number of agentic turns (API round-trips) before stopping',
),
background: z
.boolean()
.optional()
.describe(
'Run this agent as a background task (non-blocking, fire-and-forget) when invoked',
),
memory: z
.enum(['user', 'project', 'local'])
.optional()
.describe(
"Scope for auto-loading agent memory files. 'user' - ~/.claude/agent-memory/<agentType>/, 'project' - .claude/agent-memory/<agentType>/, 'local' - .claude/agent-memory-local/<agentType>/",
),
effort: z
.union([z.enum(['low', 'medium', 'high', 'max']), z.number().int()])
.optional()
.describe(
'Reasoning effort level for this agent. Either a named level or an integer',
),
permissionMode: PermissionModeSchema()
.optional()
.describe(
'Permission mode controlling how tool executions are handled',
),
})
.describe(
'Definition for a custom subagent that can be invoked via the Agent tool.',
),
)
// ============================================================================
// Settings Types
// ============================================================================
export const SettingSourceSchema = lazySchema(() =>
z
.enum(['user', 'project', 'local'])
.describe(
'Source for loading filesystem-based settings. ' +
"'user' - Global user settings (~/.claude/settings.json). " +
"'project' - Project settings (.claude/settings.json). " +
"'local' - Local settings (.claude/settings.local.json).",
),
)
export const SdkPluginConfigSchema = lazySchema(() =>
z
.object({
type: z
.literal('local')
.describe("Plugin type. Currently only 'local' is supported"),
path: z
.string()
.describe('Absolute or relative path to the plugin directory'),
})
.describe('Configuration for loading a plugin.'),
)
// ============================================================================
// Rewind Types
// ============================================================================
export const RewindFilesResultSchema = lazySchema(() =>
z
.object({
canRewind: z.boolean(),
error: z.string().optional(),
filesChanged: z.array(z.string()).optional(),
insertions: z.number().optional(),
deletions: z.number().optional(),
})
.describe('Result of a rewindFiles operation.'),
)
// ============================================================================
// External Type Placeholders
// ============================================================================
//
// These schemas use z.unknown() as placeholders for external types.
// The generation script uses TypeOverrideMap to output the correct TS type references.
// This allows us to define SDK message types in Zod while maintaining proper typing.
/** Placeholder for APIUserMessage from @anthropic-ai/sdk */
export const APIUserMessagePlaceholder = lazySchema(() => z.unknown())
/** Placeholder for APIAssistantMessage from @anthropic-ai/sdk */
export const APIAssistantMessagePlaceholder = lazySchema(() => z.unknown())
/** Placeholder for RawMessageStreamEvent from @anthropic-ai/sdk */
export const RawMessageStreamEventPlaceholder = lazySchema(() => z.unknown())
/** Placeholder for UUID from crypto */
export const UUIDPlaceholder = lazySchema(() => z.string())
/** Placeholder for NonNullableUsage (mapped type over Usage) */
export const NonNullableUsagePlaceholder = lazySchema(() => z.unknown())
// ============================================================================
// SDK Message Types
// ============================================================================
export const SDKAssistantMessageErrorSchema = lazySchema(() =>
z.enum([
'authentication_failed',
'billing_error',
'rate_limit',
'invalid_request',
'server_error',
'unknown',
'max_output_tokens',
]),
)
export const SDKStatusSchema = lazySchema(() =>
z.union([z.literal('compacting'), z.null()]),
)
// SDKUserMessage content without uuid/session_id
const SDKUserMessageContentSchema = lazySchema(() =>
z.object({
type: z.literal('user'),
message: APIUserMessagePlaceholder(),
parent_tool_use_id: z.string().nullable(),
isSynthetic: z.boolean().optional(),
tool_use_result: z.unknown().optional(),
priority: z.enum(['now', 'next', 'later']).optional(),
timestamp: z
.string()
.optional()
.describe(
'ISO timestamp when the message was created on the originating process. Older emitters omit it; consumers should fall back to receive time.',
),
}),
)
export const SDKUserMessageSchema = lazySchema(() =>
SDKUserMessageContentSchema().extend({
uuid: UUIDPlaceholder().optional(),
session_id: z.string().optional(),
}),
)
export const SDKUserMessageReplaySchema = lazySchema(() =>
SDKUserMessageContentSchema().extend({
uuid: UUIDPlaceholder(),
session_id: z.string(),
isReplay: z.literal(true),
}),
)
export const SDKRateLimitInfoSchema = lazySchema(() =>
z
.object({
status: z.enum(['allowed', 'allowed_warning', 'rejected']),
resetsAt: z.number().optional(),
rateLimitType: z
.enum([
'five_hour',
'seven_day',
'seven_day_opus',
'seven_day_sonnet',
'overage',
])
.optional(),
utilization: z.number().optional(),
overageStatus: z
.enum(['allowed', 'allowed_warning', 'rejected'])
.optional(),
overageResetsAt: z.number().optional(),
overageDisabledReason: z
.enum([
'overage_not_provisioned',
'org_level_disabled',
'org_level_disabled_until',
'out_of_credits',
'seat_tier_level_disabled',
'member_level_disabled',
'seat_tier_zero_credit_limit',
'group_zero_credit_limit',
'member_zero_credit_limit',
'org_service_level_disabled',
'org_service_zero_credit_limit',
'no_limits_configured',
'unknown',
])
.optional(),
isUsingOverage: z.boolean().optional(),
surpassedThreshold: z.number().optional(),
})
.describe('Rate limit information for claude.ai subscription users.'),
)
export const SDKAssistantMessageSchema = lazySchema(() =>
z.object({
type: z.literal('assistant'),
message: APIAssistantMessagePlaceholder(),
parent_tool_use_id: z.string().nullable(),
error: SDKAssistantMessageErrorSchema().optional(),
uuid: UUIDPlaceholder(),
session_id: z.string(),
}),
)
export const SDKRateLimitEventSchema = lazySchema(() =>
z
.object({
type: z.literal('rate_limit_event'),
rate_limit_info: SDKRateLimitInfoSchema(),
uuid: UUIDPlaceholder(),
session_id: z.string(),
})
.describe('Rate limit event emitted when rate limit info changes.'),
)
export const SDKStreamlinedTextMessageSchema = lazySchema(() =>
z
.object({
type: z.literal('streamlined_text'),
text: z
.string()
.describe('Text content preserved from the assistant message'),
session_id: z.string(),
uuid: UUIDPlaceholder(),
})
.describe(
'@internal Streamlined text message - replaces SDKAssistantMessage in streamlined output. Text content preserved, thinking and tool_use blocks removed.',
),
)
export const SDKStreamlinedToolUseSummaryMessageSchema = lazySchema(() =>
z
.object({
type: z.literal('streamlined_tool_use_summary'),
tool_summary: z
.string()
.describe('Summary of tool calls (e.g., "Read 2 files, wrote 1 file")'),
session_id: z.string(),
uuid: UUIDPlaceholder(),
})
.describe(
'@internal Streamlined tool use summary - replaces tool_use blocks in streamlined output with a cumulative summary string.',
),
)
export const SDKPermissionDenialSchema = lazySchema(() =>
z.object({
tool_name: z.string(),
tool_use_id: z.string(),
tool_input: z.record(z.string(), z.unknown()),
}),
)
export const SDKResultSuccessSchema = lazySchema(() =>
z.object({
type: z.literal('result'),
subtype: z.literal('success'),
duration_ms: z.number(),
duration_api_ms: z.number(),
is_error: z.boolean(),
num_turns: z.number(),
result: z.string(),
stop_reason: z.string().nullable(),
total_cost_usd: z.number(),
usage: NonNullableUsagePlaceholder(),
modelUsage: z.record(z.string(), ModelUsageSchema()),
permission_denials: z.array(SDKPermissionDenialSchema()),
structured_output: z.unknown().optional(),
fast_mode_state: FastModeStateSchema().optional(),
uuid: UUIDPlaceholder(),
session_id: z.string(),
}),
)
export const SDKResultErrorSchema = lazySchema(() =>
z.object({
type: z.literal('result'),
subtype: z.enum([
'error_during_execution',
'error_max_turns',
'error_max_budget_usd',
'error_max_structured_output_retries',
]),
duration_ms: z.number(),
duration_api_ms: z.number(),
is_error: z.boolean(),
num_turns: z.number(),
stop_reason: z.string().nullable(),
total_cost_usd: z.number(),
usage: NonNullableUsagePlaceholder(),
modelUsage: z.record(z.string(), ModelUsageSchema()),
permission_denials: z.array(SDKPermissionDenialSchema()),
errors: z.array(z.string()),
fast_mode_state: FastModeStateSchema().optional(),
uuid: UUIDPlaceholder(),
session_id: z.string(),
}),
)
export const SDKResultMessageSchema = lazySchema(() =>
z.union([SDKResultSuccessSchema(), SDKResultErrorSchema()]),
)
export const SDKSystemMessageSchema = lazySchema(() =>
z.object({
type: z.literal('system'),
subtype: z.literal('init'),
agents: z.array(z.string()).optional(),
apiKeySource: ApiKeySourceSchema(),
betas: z.array(z.string()).optional(),
claude_code_version: z.string(),
cwd: z.string(),
tools: z.array(z.string()),
mcp_servers: z.array(
z.object({
name: z.string(),
status: z.string(),
}),
),
model: z.string(),
permissionMode: PermissionModeSchema(),
slash_commands: z.array(z.string()),
output_style: z.string(),
skills: z.array(z.string()),
plugins: z.array(
z.object({
name: z.string(),
path: z.string(),
source: z
.string()
.optional()
.describe(
'@internal Plugin source identifier in "name\\@marketplace" format. Sentinels: "name\\@inline" for --plugin-dir, "name\\@builtin" for built-in plugins.',
),
}),
),
fast_mode_state: FastModeStateSchema().optional(),
uuid: UUIDPlaceholder(),
session_id: z.string(),
}),
)
export const SDKPartialAssistantMessageSchema = lazySchema(() =>
z.object({
type: z.literal('stream_event'),
event: RawMessageStreamEventPlaceholder(),
parent_tool_use_id: z.string().nullable(),
uuid: UUIDPlaceholder(),
session_id: z.string(),
}),
)
export const SDKCompactBoundaryMessageSchema = lazySchema(() =>
z.object({
type: z.literal('system'),
subtype: z.literal('compact_boundary'),
compact_metadata: z.object({
trigger: z.enum(['manual', 'auto']),
pre_tokens: z.number(),
preserved_segment: z
.object({
head_uuid: UUIDPlaceholder(),
anchor_uuid: UUIDPlaceholder(),
tail_uuid: UUIDPlaceholder(),
})
.optional()
.describe(
'Relink info for messagesToKeep. Loaders splice the preserved ' +
'segment at anchor_uuid (summary for suffix-preserving, ' +
'boundary for prefix-preserving partial compact) so resume ' +
'includes preserved content. Unset when compaction summarizes ' +
'everything (no messagesToKeep).',
),
}),
uuid: UUIDPlaceholder(),
session_id: z.string(),
}),
)
export const SDKStatusMessageSchema = lazySchema(() =>
z.object({
type: z.literal('system'),
subtype: z.literal('status'),
status: SDKStatusSchema(),
permissionMode: PermissionModeSchema().optional(),
uuid: UUIDPlaceholder(),
session_id: z.string(),
}),
)
export const SDKPostTurnSummaryMessageSchema = lazySchema(() =>
z
.object({
type: z.literal('system'),
subtype: z.literal('post_turn_summary'),
summarizes_uuid: z.string(),
status_category: z.enum([
'blocked',
'waiting',
'completed',
'review_ready',
'failed',
]),
status_detail: z.string(),
is_noteworthy: z.boolean(),
title: z.string(),
description: z.string(),
recent_action: z.string(),
needs_action: z.string(),
artifact_urls: z.array(z.string()),
uuid: UUIDPlaceholder(),
session_id: z.string(),
})
.describe(
'@internal Background post-turn summary emitted after each assistant turn. summarizes_uuid points to the assistant message this summarizes.',
),
)
export const SDKAPIRetryMessageSchema = lazySchema(() =>
z
.object({
type: z.literal('system'),
subtype: z.literal('api_retry'),
attempt: z.number(),
max_retries: z.number(),
retry_delay_ms: z.number(),
error_status: z.number().nullable(),
error: SDKAssistantMessageErrorSchema(),
uuid: UUIDPlaceholder(),
session_id: z.string(),
})
.describe(
'Emitted when an API request fails with a retryable error and will be retried after a delay. error_status is null for connection errors (e.g. timeouts) that had no HTTP response.',
),
)
export const SDKLocalCommandOutputMessageSchema = lazySchema(() =>
z
.object({
type: z.literal('system'),
subtype: z.literal('local_command_output'),
content: z.string(),
uuid: UUIDPlaceholder(),
session_id: z.string(),
})
.describe(
'Output from a local slash command (e.g. /voice, /cost). Displayed as assistant-style text in the transcript.',
),
)
export const SDKHookStartedMessageSchema = lazySchema(() =>
z.object({
type: z.literal('system'),
subtype: z.literal('hook_started'),
hook_id: z.string(),
hook_name: z.string(),
hook_event: z.string(),
uuid: UUIDPlaceholder(),
session_id: z.string(),
}),
)
export const SDKHookProgressMessageSchema = lazySchema(() =>
z.object({
type: z.literal('system'),
subtype: z.literal('hook_progress'),
hook_id: z.string(),
hook_name: z.string(),
hook_event: z.string(),
stdout: z.string(),
stderr: z.string(),
output: z.string(),
uuid: UUIDPlaceholder(),
session_id: z.string(),
}),
)
export const SDKHookResponseMessageSchema = lazySchema(() =>
z.object({
type: z.literal('system'),
subtype: z.literal('hook_response'),
hook_id: z.string(),
hook_name: z.string(),
hook_event: z.string(),
output: z.string(),
stdout: z.string(),
stderr: z.string(),
exit_code: z.number().optional(),
outcome: z.enum(['success', 'error', 'cancelled']),
uuid: UUIDPlaceholder(),
session_id: z.string(),
}),
)
export const SDKToolProgressMessageSchema = lazySchema(() =>
z.object({
type: z.literal('tool_progress'),
tool_use_id: z.string(),
tool_name: z.string(),
parent_tool_use_id: z.string().nullable(),
elapsed_time_seconds: z.number(),
task_id: z.string().optional(),
uuid: UUIDPlaceholder(),
session_id: z.string(),
}),
)
export const SDKAuthStatusMessageSchema = lazySchema(() =>
z.object({
type: z.literal('auth_status'),
isAuthenticating: z.boolean(),
output: z.array(z.string()),
error: z.string().optional(),
uuid: UUIDPlaceholder(),
session_id: z.string(),
}),
)
export const SDKFilesPersistedEventSchema = lazySchema(() =>
z.object({
type: z.literal('system'),
subtype: z.literal('files_persisted'),
files: z.array(
z.object({
filename: z.string(),
file_id: z.string(),
}),
),
failed: z.array(
z.object({
filename: z.string(),
error: z.string(),
}),
),
processed_at: z.string(),
uuid: UUIDPlaceholder(),
session_id: z.string(),
}),
)
export const SDKTaskNotificationMessageSchema = lazySchema(() =>
z.object({
type: z.literal('system'),
subtype: z.literal('task_notification'),
task_id: z.string(),
tool_use_id: z.string().optional(),
status: z.enum(['completed', 'failed', 'stopped']),
output_file: z.string(),
summary: z.string(),
usage: z
.object({
total_tokens: z.number(),
tool_uses: z.number(),
duration_ms: z.number(),
})
.optional(),
uuid: UUIDPlaceholder(),
session_id: z.string(),
}),
)
export const SDKTaskStartedMessageSchema = lazySchema(() =>
z.object({
type: z.literal('system'),
subtype: z.literal('task_started'),
task_id: z.string(),
tool_use_id: z.string().optional(),
description: z.string(),
task_type: z.string().optional(),
workflow_name: z
.string()
.optional()
.describe(
"meta.name from the workflow script (e.g. 'spec'). Only set when task_type is 'local_workflow'.",
),
prompt: z.string().optional(),
uuid: UUIDPlaceholder(),
session_id: z.string(),
}),
)
export const SDKSessionStateChangedMessageSchema = lazySchema(() =>
z
.object({
type: z.literal('system'),
subtype: z.literal('session_state_changed'),
state: z.enum(['idle', 'running', 'requires_action']),
uuid: UUIDPlaceholder(),
session_id: z.string(),
})
.describe(
"Mirrors notifySessionStateChanged. 'idle' fires after heldBackResult flushes and the bg-agent do-while exits — authoritative turn-over signal.",
),
)
export const SDKTaskProgressMessageSchema = lazySchema(() =>
z.object({
type: z.literal('system'),
subtype: z.literal('task_progress'),
task_id: z.string(),
tool_use_id: z.string().optional(),
description: z.string(),
usage: z.object({
total_tokens: z.number(),
tool_uses: z.number(),
duration_ms: z.number(),
}),
last_tool_name: z.string().optional(),
summary: z.string().optional(),
uuid: UUIDPlaceholder(),
session_id: z.string(),
}),
)
export const SDKToolUseSummaryMessageSchema = lazySchema(() =>
z.object({
type: z.literal('tool_use_summary'),
summary: z.string(),
preceding_tool_use_ids: z.array(z.string()),
uuid: UUIDPlaceholder(),
session_id: z.string(),
}),
)
export const SDKElicitationCompleteMessageSchema = lazySchema(() =>
z
.object({
type: z.literal('system'),
subtype: z.literal('elicitation_complete'),
mcp_server_name: z.string(),
elicitation_id: z.string(),
uuid: UUIDPlaceholder(),
session_id: z.string(),
})
.describe(
'Emitted when an MCP server confirms that a URL-mode elicitation is complete.',
),
)
/** @internal */
export const SDKPromptSuggestionMessageSchema = lazySchema(() =>
z
.object({
type: z.literal('prompt_suggestion'),
suggestion: z.string(),
uuid: UUIDPlaceholder(),
session_id: z.string(),
})
.describe(
'Predicted next user prompt, emitted after each turn when promptSuggestions is enabled.',
),
)
// ============================================================================
// Session Listing Types
// ============================================================================
export const SDKSessionInfoSchema = lazySchema(() =>
z
.object({
sessionId: z.string().describe('Unique session identifier (UUID).'),
summary: z
.string()
.describe(
'Display title for the session: custom title, auto-generated summary, or first prompt.',
),
lastModified: z
.number()
.describe('Last modified time in milliseconds since epoch.'),
fileSize: z
.number()
.optional()
.describe(
'File size in bytes. Only populated for local JSONL storage.',
),
customTitle: z
.string()
.optional()
.describe('User-set session title via /rename.'),
firstPrompt: z
.string()
.optional()
.describe('First meaningful user prompt in the session.'),
gitBranch: z
.string()
.optional()
.describe('Git branch at the end of the session.'),
cwd: z.string().optional().describe('Working directory for the session.'),
tag: z.string().optional().describe('User-set session tag.'),
createdAt: z
.number()
.optional()
.describe(
"Creation time in milliseconds since epoch, extracted from the first entry's timestamp.",
),
})
.describe('Session metadata returned by listSessions and getSessionInfo.'),
)
export const SDKMessageSchema = lazySchema(() =>
z.union([
SDKAssistantMessageSchema(),
SDKUserMessageSchema(),
SDKUserMessageReplaySchema(),
SDKResultMessageSchema(),
SDKSystemMessageSchema(),
SDKPartialAssistantMessageSchema(),
SDKCompactBoundaryMessageSchema(),
SDKStatusMessageSchema(),
SDKAPIRetryMessageSchema(),
SDKLocalCommandOutputMessageSchema(),
SDKHookStartedMessageSchema(),
SDKHookProgressMessageSchema(),
SDKHookResponseMessageSchema(),
SDKToolProgressMessageSchema(),
SDKAuthStatusMessageSchema(),
SDKTaskNotificationMessageSchema(),
SDKTaskStartedMessageSchema(),
SDKTaskProgressMessageSchema(),
SDKSessionStateChangedMessageSchema(),
SDKFilesPersistedEventSchema(),
SDKToolUseSummaryMessageSchema(),
SDKRateLimitEventSchema(),
SDKElicitationCompleteMessageSchema(),
SDKPromptSuggestionMessageSchema(),
]),
)
export const FastModeStateSchema = lazySchema(() =>
z
.enum(['off', 'cooldown', 'on'])
.describe(
'Fast mode state: off, in cooldown after rate limit, or actively enabled.',
),
)
|