Functions
query()
The SDK’s main entry function. Creates an async generator that streams SDKMessage in message arrival order.
Parameters
Return Value
ReturnsQuery — an AsyncGenerator<SDKMessage, void>, consumed via for await.
q.interrupt()
Types
Options
Configuration object for query().
AuthOptions
Convenience constructors:
accessToken(token) / accessTokenFromEnv(envVar?) / qodercliAuth(); see SDK Authentication.
options.agents
Type: Record<string, AgentDefinition>
Registers custom Agents available to the current query() session. The object key is the Agent name and the value is that Agent’s definition.
TheAgenttool is required: Custom subagents require the main session to delegate through the built-inAgenttool. The Agent tool must be included inallowedToolsbecause Qoder invokes subagents through the Agent tool.
Agent tool. The main session must include Agent in its tool set to delegate work; allowedTools: ['Agent'] is the required pre-authorization form. If you use options.tools to narrow the main session’s available tools, include Agent there as well.
options.agent
Type: string
Specifies which Agent identity the main session should run as. The value can be a name registered in options.agents, or a built-in / plugin Agent name discovered by the current CLI.
prompt, model, and tool restrictions. When omitted, the session uses the default main-session behavior.
AgentDefinition
Definition of a custom Agent. The fields below are the stable capabilities currently covered and verified by the SDK.
description
Describes what tasks the Agent is suitable for. It affects whether the model chooses this Agent.
Helpful assistant.
prompt
The Agent’s system prompt. Use it to define the role, constraints, and output format.
tools
Tool allowlist for the Agent. When set, the Agent can only use the listed tools.
tools is omitted, the subagent default tool set is used. A subagent’s tool set does not inherit trimming from the main session’s allowedTools.
disallowedTools
Excludes specific tools from the Agent’s tool set.
disallowedTools is omitted, the subagent does not inherit trimming from the main session’s disallowedTools. Usually avoid setting both tools and disallowedTools unless you know the final tool set explicitly.
model
Specifies the model for the Agent. When omitted, the session default model is used. Supported model tiers include:
Agents also support two special forms:
mcpServers
Limits or adds MCP servers available to this Agent.
skills
List of skill names to preload into the Agent context. Plain skill names and plugin-qualified names are both supported.
initialPrompt
Automatically submitted as the first user input when this Agent becomes the main session Agent through options.agent.
Agent tool.
maxTurns
Limits the Agent’s maximum API turns. Use it to control cost, execution time, and loop risk.
effort
effort is usually suitable for complex reviews, architecture analysis, and high-risk changes, but increases latency and token usage.
permissionMode
Controls the permission mode for tool execution inside this Agent. It uses the same semantics as the session-level permissionMode, but its scope is limited to this Agent. For the session-level permission chain, allowedTools / disallowedTools / canUseTool priority, and examples, see Permission Control.
For permission semantics, see Permission Control.
AgentInfo
Agent summary returned by q.supportedAgents().
options.agents, and may also include built-in, project, user, or plugin Agents discovered by the current CLI. The actual available entries depend on the qodercli version and current configuration.
Context and Invocation Boundaries
- Subagents use independent context and do not receive the parent session’s full history.
- The main information passed from the parent session to a subagent is the task prompt supplied to the
Agenttool. - A subagent’s intermediate tool results do not directly enter the parent session; the parent session receives the subagent’s final response.
- Subagents cannot spawn their own subagents, so do not put
Agentin a subagent’stools. initialPromptonly takes effect for the main session Agent specified byoptions.agent.
Model Policy
Dynamic model-selection capability ofquery(). Two modes: fixed-model (no resolveModel, uses options.model or backend default) and dynamic-callback (pass resolveModel, the callback decides the model before every LLM call). For full concepts, triggers and error handling see Model Policy.
options.resolveModel
Type: ModelPolicyProvider
Entry point for dynamic-callback mode. Once passed, dynamic-callback mode is enabled and the SDK calls this callback before every LLM request to fetch the model. The model returned by the callback is the final model for that request; there is no automatic fallback.
options.resolveModelTimeoutMs
Type: number, default 500
Callback timeout, in milliseconds. On timeout ModelPolicyTimeoutError is thrown and the query fails (no fallback). Only effective when resolveModel is passed.
ModelPolicyProvider
Callback function signature. May be synchronous or asynchronous.
QoderModelPurpose:
Behavioural notes:
- The callback may be triggered many times within a single session (re-invoked before every turn / tool / sub-task).
- The
modelreturned by the callback is the final model for that request; the SDK does not re-validate it. - Throwing an exception or returning an empty
modelfails the query. See Model Policy — Error handling.
ModelPolicyContext
The context passed to the callback on every invocation.
QoderModelPurpose
ModelPolicyResult
The callback’s return value.
Supported
parameters keys:
model forms:
- String — any model ID supported by the backend (such as
auto/performance/glm51); the exact set of valid values is returned in real time byq.getAvailableModels(). Must be non-empty, otherwise the query fails. CustomModelobject (BYOK) — the SDK extracts the object’smodelfield as the model identifier for this call, and forwards the remaining fields as credentials to the CLI for routing to a third-party LLM.
CustomModel
BYOK credentials. In the resolveModel callback, set the model field to this object directly, and that LLM request will be routed to a third-party provider.
Notes:
providermust match akeyin the catalog, otherwise backend authentication fails.- A wrong
api_keycauses authentication to fail, which fails the query directly (dynamic-callback mode does not fall back). - BYOK calls report
total_cost_usdas 0 on the platform; token usage is reported as-is and billed by the provider.
BYOK catalog types
The provider/model catalog returned byq.listByokProviders().
BYOKProviderInfo
BYOKModelTypeInfo
BYOKModelInfo
ModelInfo
Summary of an available model returned by q.getAvailableModels(). Also used as the element type of ModelPolicyContext.availableModels.
ModelContextConfig
Context-window configuration keyed by tier label, such as "200K" or "1M".
ModelThinkingConfig
Thinking / reasoning configuration for a model.
ModelPromotion
Promotion / discount info forwarded from the model list API. Nested field names stay in the server’s snake_case form.
ServerModelJson
Raw JSON-compatible model entry from the model list API. Use this when a server field is needed before it has a first-class ModelInfo field.
UsageInfo
Account quota and usage snapshot returned by q.getUsageInfo().
Each bucket reports
used / remaining / percentage against its total (or cap for the org package) in unit (typically credits).
Missing fields, or fields with an unexpected runtime type, are omitted from the returned object.
ModelPolicyTimeoutError
resolveModel callback exceeds options.resolveModelTimeoutMs without returning. The query fails directly, with no fallback.
q.setModel()
ModelInfo.value.
q.getAvailableModels()
ModelPolicyContext.availableModels already carries the same up-to-date list, so calling this method explicitly is unnecessary.
q.listByokProviders()
- Returns
null: the CLI does not support this API (graceful fallback, no exception). - Returns an array (may be empty): the list of providers available to the current account (an empty array means the account has not enabled BYOK).
q.getUsageInfo()
- Returns
null: the CLI is unauthenticated, an older CLI version does not support this API, or the CLI did not return an object (graceful fallback, no exception). - Returns a
UsageInfoobject: the known account quota and usage fields whose runtime types are valid. Missing or invalid fields are omitted.
UsageInfo.
CanUseTool
Host-defined custom tool permission approval callback.
CanUseToolOptions
For full usage and examples, see Permission Control.
PermissionMode
For more details, see Permission Control.
PermissionResult
Return value of CanUseTool.
allow.updatedInput replaces the actual parameters the tool receives when modified. deny.interrupt: true denies and also interrupts the Agent.
McpServerConfig
MCP server configuration, passed to Options.mcpServers.
McpStdioServerConfig
McpSSEServerConfig
McpHttpServerConfig
McpSdkServerConfigWithInstance
createSdkMcpServer() factory; see MCP - In-Process Server.
SdkPluginConfig
Load local plugins.
CloudAgentOptions
Type of Options.experimentalCloudAgent. Configures the agent / session reference for the Cloud runtime; full usage in Cloud Agent.
AgentCreateParams
Request body for creating a new Cloud Agent, matching the agent-create fields of the Qoder Cloud OpenAPI.
CloudSessionCreateParams
Request body for creating a new Cloud session.
SettingSource
Controls which filesystem settings are loaded.
When omitted, all sources are loaded per CLI defaults; pass
[] to skip entirely.
ToolConfig
Built-in tool behavior configuration.
Built-in Tool List
Intools, allowedTools, disallowedTools, canUseTool, hook matchers, and Agent tool allowlists, built-in tools use the runtime tool names in the table below.
Custom MCP tool names use this format:
tool()
Creates a type-safe SDK MCP tool definition.
tool() itself is a factory for defining tools. Registration constraints such as non-empty name, non-empty description, and duplicate tool names are validated by createSdkMcpServer() when tools are registered.
AnyZodRawShape
AnyZodRawShape is compatible with Zod 3 / Zod 4. It represents a field object, not z.object(...).
InferShape
InferShape infers the handler args type from the Zod raw shape.
SdkMcpToolDefinition
ToolExtras
ToolAnnotations
These fields are metadata and scheduling hints, not permission switches. Whether execution is allowed is still determined by
tools, allowedTools, disallowedTools, permissionMode, canUseTool, and hooks. In the feature documentation, the verified behavior capabilities are readOnlyHint, destructiveHint, and openWorldHint; title is retained here only as MCP metadata in the type reference.
createSdkMcpServer()
Creates an MCP server that runs in the same process as the SDK.
CreateSdkMcpServerOptions
Return Value
ReturnsMcpSdkServerConfigWithInstance, which can be passed directly as a value in options.mcpServers. For the full MCP server configuration, see McpServerConfig.
CallToolResult
A tool handler returns the MCP protocol CallToolResult.
McpToolResultContent
Built-in Tool Input and Output Types
The SDK provides input / output structures for built-in tools at the type level. Note: these are TypeScript type names; permission configuration still uses the runtime tool names above.AgentInput / AgentOutput
BashInput / BashOutput
FileReadInput / FileReadOutput
The runtime tool name is Read; the type names remain FileReadInput / FileReadOutput.
FileEditInput / FileEditOutput
The runtime tool name is Edit.
FileWriteInput / FileWriteOutput
The runtime tool name is Write.
GlobInput / GlobOutput
GrepInput / GrepOutput
WebFetchInput / WebFetchOutput
WebSearchInput / WebSearchOutput
AskUserQuestionInput / AskUserQuestionOutput
NotebookEditInput / NotebookEditOutput
TaskOutputInput
TaskStopInput / TaskStopOutput
ExitPlanModeInput / ExitPlanModeOutput
ConfigInput / ConfigOutput
EnterWorktreeInput / EnterWorktreeOutput
ExitWorktreeInput / ExitWorktreeOutput
TodoWriteInput / TodoWriteOutput
ListMcpResourcesInput / ListMcpResourcesOutput
ReadMcpResourceInput
McpInput / McpOutput
ToolInputSchemas
ToolOutputSchemas
Hooks Reference
For usage guide and examples, see Hooks.Event Overview
HookEvent
Union type of registrable hook events.
HookCallback
HookCallbackMatcher
BaseHookInput
Common input fields shared by all hook events.
HookJSONOutput
Return type for hook callbacks.
When multiple hooks return conflictingdecisionvalues,"deny"/"block"takes precedence (strictest rule wins).
PreToolUseHookInput
hookSpecificOutput:
PostToolUseHookInput
Output behavior:
hookSpecificOutput:
When multiple hooks set updatedToolOutput, the last non-empty value wins. For chained transforms, execute them sequentially within a single callback.
PostToolUseFailureHookInput
UserPromptSubmitHookInput
hookSpecificOutput:
SessionStartHookInput
hookSpecificOutput:
SessionEndHookInput
StopHookInput
Return
{ decision: 'block', reason: '...' } to prevent the AI from stopping and force continuation. reason is injected as a continuation prompt into the model context.
SubagentStartHookInput
SubagentStopHookInput
PreCompactHookInput
PostCompactHookInput
CwdChangedHookInput
InstructionsLoadedHookInput
FileChangedHookInput
PermissionRequestHookInput
hookSpecificOutput:
decision is one of:
- Approve:
{ behavior: "allow", updatedInput?: Record<string, unknown>, updatedPermissions?: PermissionUpdate[] } - Deny:
{ behavior: "deny", message?: string }
Message Types
SDKMessage
Discriminated union of all messages flowing from Query.
message.type, then further dispatch on subtype (only system / result types have subtypes).
SDKAssistantMessage
AI’s complete reply, delivered once per turn.
SDKUserMessage
User message or tool result feedback.
SDKUserMessageReplay
Historical user messages replayed during session resume.
SDKResultMessage
Final message when the entire session ends.
SDKSystemMessage
Session initialization message (subtype: 'init'). Other system events are delivered via separate message types; see the various SDK*Message types below.
SDKPartialAssistantMessage
Requires includePartialMessages: true; streams out incrementally per token. For full usage, see Streaming Output.
SDKCompactBoundaryMessage
Boundary marker for context compaction completion.
SDKStatusMessage
Session running state changes (e.g., compacting).
SDKMcpStatusChangeMessage
MCP connection pool state change.
SDKAPIRetryMessage
Automatic retry on network/service errors.
SDKLocalCommandOutputMessage
Output from local slash commands.
SDKHookStartedMessage
Hook begins execution.
SDKHookProgressMessage
Hook execution output in progress.
SDKHookResponseMessage
Hook finishes.
SDKTaskStartedMessage
Sub-Agent task starts.
SDKTaskProgressMessage
Sub-Agent task progress.
SDKTaskNotificationMessage
Sub-Agent task finishes.
SDKSessionStateChangedMessage
Main session running state change.
SDKSessionTitleChangedMessage
Session title change.
SDKBridgeStateMessage
Bridge connection state change.
SDKFilesPersistedEvent
File checkpoint persistence result.
SDKElicitationCompleteMessage
MCP elicitation complete.
SDKPermissionDeniedMessage
Tool call short-circuited by permission policy (dontAsk / auto / deny rule, etc.).
SDKPromptSuggestionMessage
When promptSuggestions: true is enabled, next-step suggestions that may be received after each turn’s result.
SDKCloudAgentEventMessage
Under the Cloud runtime (options.experimentalCloudAgent), events forwarded from the Qoder Cloud session SSE stream. See Cloud Agent for full usage.
SDKPermissionDenial
Element in the SDKResultMessage.permission_denials array.