Skip to main content

Functions

query()

The SDK’s main entry function. Creates an async generator that streams SDKMessage in message arrival order.

Parameters

Return Value

Returns Query — an AsyncGenerator<SDKMessage, void>, consumed via for await.

q.interrupt()

Stops the generation or tool execution for the current turn. When the Promise resolves, the turn has stopped. This does not close the session, so a multi-message session can continue with another turn. See Interrupting the current turn.

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.
The Agent tool is required: Custom subagents require the main session to delegate through the built-in Agent tool. The Agent tool must be included in allowedTools because Qoder invokes subagents through the Agent tool.
After registration, the model can invoke these subagents through the built-in 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.
When set, the main session uses that Agent’s 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.
Prefer a clear triggering scenario. Avoid broad descriptions such as 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.
When 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.
When 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.
The string form references an MCP server already configured in the session. The object form configures a dedicated MCP server for this Agent. For the MCP server configuration shape, see SDK References - McpServerConfig.

skills

List of skill names to preload into the Agent context. Plain skill names and plugin-qualified names are both supported.
For session-level skill behavior, see Skills.

initialPrompt

Automatically submitted as the first user input when this Agent becomes the main session Agent through options.agent.
This field only takes effect for the main session Agent. It is ignored when the Agent is invoked as a subagent through the Agent tool.

maxTurns

Limits the Agent’s maximum API turns. Use it to control cost, execution time, and loop risk.

effort

Controls the Agent’s reasoning effort level. Higher 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().
The returned list may include Agents registered through 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 Agent tool.
  • 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 Agent in a subagent’s tools.
  • initialPrompt only takes effect for the main session Agent specified by options.agent.

Model Policy

Dynamic model-selection capability of query(). 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.
Triggering scenarios are distinguished by QoderModelPurpose: Behavioural notes:
  • The callback may be triggered many times within a single session (re-invoked before every turn / tool / sub-task).
  • The model returned by the callback is the final model for that request; the SDK does not re-validate it.
  • Throwing an exception or returning an empty model fails 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 by q.getAvailableModels(). Must be non-empty, otherwise the query fails.
  • CustomModel object (BYOK) — the SDK extracts the object’s model field 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:
  • provider must match a key in the catalog, otherwise backend authentication fails.
  • A wrong api_key causes authentication to fail, which fails the query directly (dynamic-callback mode does not fall back).
  • BYOK calls report total_cost_usd as 0 on the platform; token usage is reported as-is and billed by the provider.

BYOK catalog types

The provider/model catalog returned by q.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

Thrown by the SDK when the resolveModel callback exceeds options.resolveModelTimeoutMs without returning. The query fails directly, with no fallback.

q.setModel()

Switches the model for fixed-model mode at runtime. Takes effect on the next LLM call. Effective only in fixed-model mode; in dynamic-callback mode, calling it does not override the callback’s result. Valid model IDs: see ModelInfo.value.

q.getAvailableModels()

Fetches the latest model list available to the current account in real time. Always returns the latest result, no caching; returns an empty array (does not throw) when the list cannot be fetched temporarily. In dynamic-callback mode, ModelPolicyContext.availableModels already carries the same up-to-date list, so calling this method explicitly is unnecessary.

q.listByokProviders()

Returns the BYOK provider/model catalog available to the current account as an array:
  • 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).
Field semantics: see BYOK catalog types.

q.getUsageInfo()

Fetches the current account’s quota and usage information from the running CLI in real time.
  • 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 UsageInfo object: the known account quota and usage fields whose runtime types are valid. Missing or invalid fields are omitted.
Return type: see 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

Returned by the 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

In tools, 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

Returns McpSdkServerConfigWithInstance, 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 conflicting decision values, "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.
Callers should first branch on 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.