File size: 19,554 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 | /**
* SDK Control Schemas - Zod schemas for the control protocol.
*
* These schemas define the control protocol between SDK implementations and the CLI.
* Used by SDK builders (e.g., Python SDK) to communicate with the CLI process.
*
* SDK consumers should use coreSchemas.ts instead.
*/
import { z } from 'zod/v4'
import { lazySchema } from '../../utils/lazySchema.js'
import {
AccountInfoSchema,
AgentDefinitionSchema,
AgentInfoSchema,
FastModeStateSchema,
HookEventSchema,
HookInputSchema,
McpServerConfigForProcessTransportSchema,
McpServerStatusSchema,
ModelInfoSchema,
PermissionModeSchema,
PermissionUpdateSchema,
SDKMessageSchema,
SDKPostTurnSummaryMessageSchema,
SDKStreamlinedTextMessageSchema,
SDKStreamlinedToolUseSummaryMessageSchema,
SDKUserMessageSchema,
SlashCommandSchema,
} from './coreSchemas.js'
// ============================================================================
// External Type Placeholders
// ============================================================================
// JSONRPCMessage from @modelcontextprotocol/sdk - treat as unknown
export const JSONRPCMessagePlaceholder = lazySchema(() => z.unknown())
// ============================================================================
// Hook Callback Types
// ============================================================================
export const SDKHookCallbackMatcherSchema = lazySchema(() =>
z
.object({
matcher: z.string().optional(),
hookCallbackIds: z.array(z.string()),
timeout: z.number().optional(),
})
.describe('Configuration for matching and routing hook callbacks.'),
)
// ============================================================================
// Control Request Types
// ============================================================================
export const SDKControlInitializeRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('initialize'),
hooks: z
.record(HookEventSchema(), z.array(SDKHookCallbackMatcherSchema()))
.optional(),
sdkMcpServers: z.array(z.string()).optional(),
jsonSchema: z.record(z.string(), z.unknown()).optional(),
systemPrompt: z.string().optional(),
appendSystemPrompt: z.string().optional(),
agents: z.record(z.string(), AgentDefinitionSchema()).optional(),
promptSuggestions: z.boolean().optional(),
agentProgressSummaries: z.boolean().optional(),
})
.describe(
'Initializes the SDK session with hooks, MCP servers, and agent configuration.',
),
)
export const SDKControlInitializeResponseSchema = lazySchema(() =>
z
.object({
commands: z.array(SlashCommandSchema()),
agents: z.array(AgentInfoSchema()),
output_style: z.string(),
available_output_styles: z.array(z.string()),
models: z.array(ModelInfoSchema()),
account: AccountInfoSchema(),
pid: z
.number()
.optional()
.describe('@internal CLI process PID for tmux socket isolation'),
fast_mode_state: FastModeStateSchema().optional(),
})
.describe(
'Response from session initialization with available commands, models, and account info.',
),
)
export const SDKControlInterruptRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('interrupt'),
})
.describe('Interrupts the currently running conversation turn.'),
)
export const SDKControlPermissionRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('can_use_tool'),
tool_name: z.string(),
input: z.record(z.string(), z.unknown()),
permission_suggestions: z.array(PermissionUpdateSchema()).optional(),
blocked_path: z.string().optional(),
decision_reason: z.string().optional(),
title: z.string().optional(),
display_name: z.string().optional(),
tool_use_id: z.string(),
agent_id: z.string().optional(),
description: z.string().optional(),
})
.describe('Requests permission to use a tool with the given input.'),
)
export const SDKControlSetPermissionModeRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('set_permission_mode'),
mode: PermissionModeSchema(),
ultraplan: z
.boolean()
.optional()
.describe('@internal CCR ultraplan session marker.'),
})
.describe('Sets the permission mode for tool execution handling.'),
)
export const SDKControlSetModelRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('set_model'),
model: z.string().optional(),
})
.describe('Sets the model to use for subsequent conversation turns.'),
)
export const SDKControlSetMaxThinkingTokensRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('set_max_thinking_tokens'),
max_thinking_tokens: z.number().nullable(),
})
.describe(
'Sets the maximum number of thinking tokens for extended thinking.',
),
)
export const SDKControlMcpStatusRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('mcp_status'),
})
.describe('Requests the current status of all MCP server connections.'),
)
export const SDKControlMcpStatusResponseSchema = lazySchema(() =>
z
.object({
mcpServers: z.array(McpServerStatusSchema()),
})
.describe(
'Response containing the current status of all MCP server connections.',
),
)
export const SDKControlGetContextUsageRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('get_context_usage'),
})
.describe(
'Requests a breakdown of current context window usage by category.',
),
)
const ContextCategorySchema = lazySchema(() =>
z.object({
name: z.string(),
tokens: z.number(),
color: z.string(),
isDeferred: z.boolean().optional(),
}),
)
const ContextGridSquareSchema = lazySchema(() =>
z.object({
color: z.string(),
isFilled: z.boolean(),
categoryName: z.string(),
tokens: z.number(),
percentage: z.number(),
squareFullness: z.number(),
}),
)
export const SDKControlGetContextUsageResponseSchema = lazySchema(() =>
z
.object({
categories: z.array(ContextCategorySchema()),
totalTokens: z.number(),
maxTokens: z.number(),
rawMaxTokens: z.number(),
percentage: z.number(),
gridRows: z.array(z.array(ContextGridSquareSchema())),
model: z.string(),
memoryFiles: z.array(
z.object({
path: z.string(),
type: z.string(),
tokens: z.number(),
}),
),
mcpTools: z.array(
z.object({
name: z.string(),
serverName: z.string(),
tokens: z.number(),
isLoaded: z.boolean().optional(),
}),
),
deferredBuiltinTools: z
.array(
z.object({
name: z.string(),
tokens: z.number(),
isLoaded: z.boolean(),
}),
)
.optional(),
systemTools: z
.array(z.object({ name: z.string(), tokens: z.number() }))
.optional(),
systemPromptSections: z
.array(z.object({ name: z.string(), tokens: z.number() }))
.optional(),
agents: z.array(
z.object({
agentType: z.string(),
source: z.string(),
tokens: z.number(),
}),
),
slashCommands: z
.object({
totalCommands: z.number(),
includedCommands: z.number(),
tokens: z.number(),
})
.optional(),
skills: z
.object({
totalSkills: z.number(),
includedSkills: z.number(),
tokens: z.number(),
skillFrontmatter: z.array(
z.object({
name: z.string(),
source: z.string(),
tokens: z.number(),
}),
),
})
.optional(),
autoCompactThreshold: z.number().optional(),
isAutoCompactEnabled: z.boolean(),
messageBreakdown: z
.object({
toolCallTokens: z.number(),
toolResultTokens: z.number(),
attachmentTokens: z.number(),
assistantMessageTokens: z.number(),
userMessageTokens: z.number(),
toolCallsByType: z.array(
z.object({
name: z.string(),
callTokens: z.number(),
resultTokens: z.number(),
}),
),
attachmentsByType: z.array(
z.object({ name: z.string(), tokens: z.number() }),
),
})
.optional(),
apiUsage: z
.object({
input_tokens: z.number(),
output_tokens: z.number(),
cache_creation_input_tokens: z.number(),
cache_read_input_tokens: z.number(),
})
.nullable(),
})
.describe(
'Breakdown of current context window usage by category (system prompt, tools, messages, etc.).',
),
)
export const SDKControlRewindFilesRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('rewind_files'),
user_message_id: z.string(),
dry_run: z.boolean().optional(),
})
.describe('Rewinds file changes made since a specific user message.'),
)
export const SDKControlRewindFilesResponseSchema = 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.'),
)
export const SDKControlCancelAsyncMessageRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('cancel_async_message'),
message_uuid: z.string(),
})
.describe(
'Drops a pending async user message from the command queue by uuid. No-op if already dequeued for execution.',
),
)
export const SDKControlCancelAsyncMessageResponseSchema = lazySchema(() =>
z
.object({
cancelled: z.boolean(),
})
.describe(
'Result of a cancel_async_message operation. cancelled=false means the message was not in the queue (already dequeued or never enqueued).',
),
)
export const SDKControlSeedReadStateRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('seed_read_state'),
path: z.string(),
mtime: z.number(),
})
.describe(
'Seeds the readFileState cache with a path+mtime entry. Use when a prior Read was removed from context (e.g. by snip) so Edit validation would fail despite the client having observed the Read. The mtime lets the CLI detect if the file changed since the seeded Read — same staleness check as the normal path.',
),
)
export const SDKHookCallbackRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('hook_callback'),
callback_id: z.string(),
input: HookInputSchema(),
tool_use_id: z.string().optional(),
})
.describe('Delivers a hook callback with its input data.'),
)
export const SDKControlMcpMessageRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('mcp_message'),
server_name: z.string(),
message: JSONRPCMessagePlaceholder(),
})
.describe('Sends a JSON-RPC message to a specific MCP server.'),
)
export const SDKControlMcpSetServersRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('mcp_set_servers'),
servers: z.record(z.string(), McpServerConfigForProcessTransportSchema()),
})
.describe('Replaces the set of dynamically managed MCP servers.'),
)
export const SDKControlMcpSetServersResponseSchema = lazySchema(() =>
z
.object({
added: z.array(z.string()),
removed: z.array(z.string()),
errors: z.record(z.string(), z.string()),
})
.describe(
'Result of replacing the set of dynamically managed MCP servers.',
),
)
export const SDKControlReloadPluginsRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('reload_plugins'),
})
.describe(
'Reloads plugins from disk and returns the refreshed session components.',
),
)
export const SDKControlReloadPluginsResponseSchema = lazySchema(() =>
z
.object({
commands: z.array(SlashCommandSchema()),
agents: z.array(AgentInfoSchema()),
plugins: z.array(
z.object({
name: z.string(),
path: z.string(),
source: z.string().optional(),
}),
),
mcpServers: z.array(McpServerStatusSchema()),
error_count: z.number(),
})
.describe(
'Refreshed commands, agents, plugins, and MCP server status after reload.',
),
)
export const SDKControlMcpReconnectRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('mcp_reconnect'),
serverName: z.string(),
})
.describe('Reconnects a disconnected or failed MCP server.'),
)
export const SDKControlMcpToggleRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('mcp_toggle'),
serverName: z.string(),
enabled: z.boolean(),
})
.describe('Enables or disables an MCP server.'),
)
export const SDKControlStopTaskRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('stop_task'),
task_id: z.string(),
})
.describe('Stops a running task.'),
)
export const SDKControlApplyFlagSettingsRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('apply_flag_settings'),
settings: z.record(z.string(), z.unknown()),
})
.describe(
'Merges the provided settings into the flag settings layer, updating the active configuration.',
),
)
export const SDKControlGetSettingsRequestSchema = lazySchema(() =>
z
.object({
subtype: z.literal('get_settings'),
})
.describe(
'Returns the effective merged settings and the raw per-source settings.',
),
)
export const SDKControlGetSettingsResponseSchema = lazySchema(() =>
z
.object({
effective: z.record(z.string(), z.unknown()),
sources: z
.array(
z.object({
source: z.enum([
'userSettings',
'projectSettings',
'localSettings',
'flagSettings',
'policySettings',
]),
settings: z.record(z.string(), z.unknown()),
}),
)
.describe(
'Ordered low-to-high priority — later entries override earlier ones.',
),
applied: z
.object({
model: z.string(),
// String levels only — numeric effort is ant-only and the
// Zod→proto generator can't emit enum∪number unions.
effort: z.enum(['low', 'medium', 'high', 'max']).nullable(),
})
.optional()
.describe(
'Runtime-resolved values after env overrides, session state, and model-specific defaults are applied. Unlike `effective` (disk merge), these reflect what will actually be sent to the API.',
),
})
.describe(
'Effective merged settings plus raw per-source settings in merge order.',
),
)
export const SDKControlElicitationRequestSchema = lazySchema(() =>
z
.object({
subtype: 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(
'Requests the SDK consumer to handle an MCP elicitation (user input request).',
),
)
export const SDKControlElicitationResponseSchema = lazySchema(() =>
z
.object({
action: z.enum(['accept', 'decline', 'cancel']),
content: z.record(z.string(), z.unknown()).optional(),
})
.describe('Response from the SDK consumer for an elicitation request.'),
)
// ============================================================================
// Control Request/Response Wrappers
// ============================================================================
export const SDKControlRequestInnerSchema = lazySchema(() =>
z.union([
SDKControlInterruptRequestSchema(),
SDKControlPermissionRequestSchema(),
SDKControlInitializeRequestSchema(),
SDKControlSetPermissionModeRequestSchema(),
SDKControlSetModelRequestSchema(),
SDKControlSetMaxThinkingTokensRequestSchema(),
SDKControlMcpStatusRequestSchema(),
SDKControlGetContextUsageRequestSchema(),
SDKHookCallbackRequestSchema(),
SDKControlMcpMessageRequestSchema(),
SDKControlRewindFilesRequestSchema(),
SDKControlCancelAsyncMessageRequestSchema(),
SDKControlSeedReadStateRequestSchema(),
SDKControlMcpSetServersRequestSchema(),
SDKControlReloadPluginsRequestSchema(),
SDKControlMcpReconnectRequestSchema(),
SDKControlMcpToggleRequestSchema(),
SDKControlStopTaskRequestSchema(),
SDKControlApplyFlagSettingsRequestSchema(),
SDKControlGetSettingsRequestSchema(),
SDKControlElicitationRequestSchema(),
]),
)
export const SDKControlRequestSchema = lazySchema(() =>
z.object({
type: z.literal('control_request'),
request_id: z.string(),
request: SDKControlRequestInnerSchema(),
}),
)
export const ControlResponseSchema = lazySchema(() =>
z.object({
subtype: z.literal('success'),
request_id: z.string(),
response: z.record(z.string(), z.unknown()).optional(),
}),
)
export const ControlErrorResponseSchema = lazySchema(() =>
z.object({
subtype: z.literal('error'),
request_id: z.string(),
error: z.string(),
pending_permission_requests: z
.array(z.lazy(() => SDKControlRequestSchema()))
.optional(),
}),
)
export const SDKControlResponseSchema = lazySchema(() =>
z.object({
type: z.literal('control_response'),
response: z.union([ControlResponseSchema(), ControlErrorResponseSchema()]),
}),
)
export const SDKControlCancelRequestSchema = lazySchema(() =>
z
.object({
type: z.literal('control_cancel_request'),
request_id: z.string(),
})
.describe('Cancels a currently open control request.'),
)
export const SDKKeepAliveMessageSchema = lazySchema(() =>
z
.object({
type: z.literal('keep_alive'),
})
.describe('Keep-alive message to maintain WebSocket connection.'),
)
export const SDKUpdateEnvironmentVariablesMessageSchema = lazySchema(() =>
z
.object({
type: z.literal('update_environment_variables'),
variables: z.record(z.string(), z.string()),
})
.describe('Updates environment variables at runtime.'),
)
// ============================================================================
// Aggregate Message Types
// ============================================================================
export const StdoutMessageSchema = lazySchema(() =>
z.union([
SDKMessageSchema(),
SDKStreamlinedTextMessageSchema(),
SDKStreamlinedToolUseSummaryMessageSchema(),
SDKPostTurnSummaryMessageSchema(),
SDKControlResponseSchema(),
SDKControlRequestSchema(),
SDKControlCancelRequestSchema(),
SDKKeepAliveMessageSchema(),
]),
)
export const StdinMessageSchema = lazySchema(() =>
z.union([
SDKUserMessageSchema(),
SDKControlRequestSchema(),
SDKControlResponseSchema(),
SDKKeepAliveMessageSchema(),
SDKUpdateEnvironmentVariablesMessageSchema(),
]),
)
|