Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.qoder.com/llms.txt

Use this file to discover all available pages before exploring further.

Functions

query()

The SDK’s main entry function. Creates an async generator that streams SDKMessage in message arrival order.
function query(params: {
  prompt: string | AsyncIterable<SDKUserMessage>;
  options?: Options;
}): Query

Parameters

ParameterTypeDescription
promptstring | AsyncIterable<SDKUserMessage>Pass a string for single-turn; pass an async iterable for multi-turn
optionsOptionsOptional session configuration

Return Value

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

Types

Options

Configuration object for query().
FieldTypeDefaultDescription
abortControllerAbortControllernew AbortController()Controller to cancel the session
additionalDirectoriesstring[][]Additional directories accessible to the AI
agentstringundefinedAgent name used by the main session; see Agents Reference
agentsRecord<string, AgentDefinition>undefinedProgrammatically defined subagents; see Agents Reference
allowDangerouslySkipPermissionsbooleanfalseAllow skipping permission checks; used with permissionMode: 'bypassPermissions'
allowedToolsstring[][]Tool allowlist; listed tools are pre-authorized. Built-in tool names are listed in Tools Reference
authAuthOptionsundefinedAuthentication configuration, required for query()
canUseToolCanUseToolundefinedCustom tool permission callback
continuebooleanfalseContinue the most recent session
cwdstringprocess.cwd()Working directory
disallowedToolsstring[][]Tool blocklist; priority is higher than allowedTools and permissionMode. Built-in tool names are listed in Tools Reference
enableFileCheckpointingbooleanfalseEnable file checkpointing for use with rewindFiles(); see Checkpoint
envRecord<string, string | undefined>process.envEnvironment variables passed to the CLI process
executable'bun' | 'deno' | 'node'Auto-detectedJavaScript runtime
executableArgsstring[][]Arguments passed to the runtime
experimentalCloudAgentCloudAgentOptionsundefinedSwitch to the Qoder Cloud Agent runtime (experimental); see Cloud Agent
extraArgsRecord<string, string | null>{}Additional arguments passed to the CLI
fallbackModelstringundefinedFallback model when the main model fails
forkSessionbooleanfalseFork into a new session ID when used with resume
hooksPartial<Record<HookEvent, HookCallbackMatcher[]>>{}Lifecycle hooks; see Hooks
includeHookEventsbooleanfalseInclude hook lifecycle events in the message stream
includePartialMessagesbooleanfalseInclude stream_event streaming fragments; see Streaming Output
maxTurnsnumberundefinedMaximum conversation turns (tool call round-trips)
mcpServersRecord<string, McpServerConfig>{}MCP server configuration; see MCP
modelstringCLI defaultModel to use; options: 'auto' / 'ultimate' / 'performance' / 'efficient' / 'lite'
pathToQoderCLIExecutablestringAuto-resolved bundled binaryPath to qodercli executable
permissionModePermissionMode'default'Session permission mode
permissionPromptToolNamestringundefinedMCP tool name for permission prompts; mutually exclusive with canUseTool
planModeInstructionsstringundefinedOverride plan mode workflow body when permissionMode: 'plan'
pluginsSdkPluginConfig[][]Load local plugins; see Plugins
promptSuggestionsbooleanfalseEmit prompt_suggestion messages after each turn’s result
resolveModelModelPolicyProviderundefinedDynamic model-selection callback. Passing it switches the query into dynamic-callback mode; see Model Policy
resolveModelTimeoutMsnumber500Callback timeout in milliseconds; only effective when resolveModel is passed
resumestringundefinedSession ID to resume
resumeSessionAtstringundefinedResume from a specified message UUID
sandboxSandboxSettingsundefinedSandbox configuration
sessionIdstringAuto-generatedSpecify session UUID
settingsstring | SettingsundefinedInline settings object or settings file path
settingSourcesSettingSource[]CLI defaultWhich filesystem settings to load; pass [] to skip user/project/local
skillsstring[] | 'all'undefinedEnabled Skills; pass 'all' to enable all; see Skills
spawnQoderCLIProcess(options: SpawnOptions) => SpawnedProcessundefinedCustom process spawn function
strictMcpConfigbooleanfalseStrict MCP validation
systemPromptstring | { type: 'preset'; preset: 'qodercli'; append?: string }undefinedSystem prompt. String overrides; preset form appends after qodercli preset
toolConfigToolConfigundefinedBuilt-in tool behavior configuration; see Tools
toolsstring[] | { type: 'preset'; preset: 'qodercli' }undefinedTool set. Pass a string array to restrict available tools; pass an empty array to disable all tools. Built-in tool names are listed in Tools Reference

AuthOptions

type AuthOptions =
  | { type: 'accessToken'; accessToken: string | { envVar: string } }
  | { type: 'qodercli' };
FormDescription
{ type: 'accessToken'; accessToken: string }Pass PAT directly
{ type: 'accessToken'; accessToken: { envVar } }Read PAT from specified environment variable; defaults to QODER_PERSONAL_ACCESS_TOKEN
{ type: 'qodercli' }Reuse local qodercli login session
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.
const q = query({
  prompt: 'Use the reviewer agent to inspect recent changes.',
  options: {
    allowedTools: ['Agent'],
    agents: {
      reviewer: {
        description: 'Reviews code quality and reports actionable findings.',
        prompt: 'Review the requested code and report concrete issues.',
        tools: ['Read', 'Grep', 'Glob'],
      },
    },
  },
});
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.
const q = query({
  prompt: 'Plan the implementation.',
  options: {
    agents: {
      planner: {
        description: 'Plans work before implementation.',
        prompt: 'Break work into steps, risks, and validation checks.',
        tools: ['Read', 'Grep', 'Glob'],
      },
    },
    agent: 'planner',
  },
});
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.
type AgentDefinition = {
  description: string;
  prompt: string;
  tools?: string[];
  disallowedTools?: string[];
  model?: string;
  mcpServers?: AgentMcpServerSpec[];
  skills?: string[];
  initialPrompt?: string;
  maxTurns?: number;
  effort?: EffortLevel;
  permissionMode?: PermissionMode;
};
FieldTypeRequiredDescription
descriptionstringYesAgent purpose description; the model uses it to decide when to invoke the Agent
promptstringYesAgent system prompt
toolsstring[]NoTool allowlist for this Agent
disallowedToolsstring[]NoTools excluded from this Agent’s tool set
modelstringNoModel override; 'inherit' means inherit the main session model
mcpServersAgentMcpServerSpec[]NoMCP server specs available to this Agent
skillsstring[]NoSkill names preloaded into the Agent context
initialPromptstringNoFirst user input automatically submitted when this Agent is used as the main session Agent
maxTurnsnumberNoMaximum API turns for the Agent
effortEffortLevelNoReasoning effort level
permissionModePermissionModeNoPermission mode for tool execution inside this Agent

description

Describes what tasks the Agent is suitable for. It affects whether the model chooses this Agent.
description: 'Runs project tests, analyzes failing output, and suggests fixes.'
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.
prompt: `You are a security reviewer.
Check for authentication bypass, authorization bugs, injection risks, and secret leaks.
Return findings sorted by severity.`

tools

Tool allowlist for the Agent. When set, the Agent can only use the listed tools.
tools: ['Read', 'Grep', 'Glob']
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.
disallowedTools: ['Bash', 'Write']
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:
ValueTierDescriptionSuitable forCredit cost
autoSmart routingIntelligently selects the best model, balancing capability and costMost daily development work; recommended default~1.0x
ultimateUltimateExpert-level deep reasoning and thinking capabilityComplex system design and difficult analysis~1.6x
performancePerformanceAdvanced reasoning and high-quality outputCore implementation, architecture design, refactoring~1.1x
efficientEfficientStandard reasoning with good cost efficiencyBasic code generation, unit tests, daily Q&A~0.3x
liteLiteBasic reasoning, free to useQuick validation, simple logic, quick questions0x
Agents also support two special forms:
ValueDescription
inheritInherit the main session model
Full model IDDirectly specify a model ID supported by the current CLI / backend

mcpServers

Limits or adds MCP servers available to this Agent.
type AgentMcpServerSpec =
  | string
  | Record<string, McpServerConfig>;
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.
skills: ['review', 'sdk-test-plugin:sdk-echo']
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.
initialPrompt: 'Start by scanning authentication and session management code.'
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.
maxTurns: 6

effort

type EffortLevel = 'low' | 'medium' | 'high' | 'max';
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.
type PermissionMode =
  | 'default'
  | 'acceptEdits'
  | 'bypassPermissions'
  | 'yolo'
  | 'plan'
  | 'dontAsk'
  | 'auto';
ValueMeaningSuitable for
'default'Standard permission behavior. Tool calls still pass through tool sets, allow / deny rules, runtime approval, or CLI default policyMost interactive subagents
'acceptEdits'Automatically accepts file-edit operations; other sensitive operations still follow the permission flowA subagent that is approved to modify workspace files
'bypassPermissions'Skips permission checks. High-risk mode, usually only for trusted automation or test environmentsControlled CI, temporary validation, one-off automation
'yolo'Compatibility alias for 'bypassPermissions'; also skips permission checksCompatibility with older configs; not recommended for new code
'plan'Plan mode. Suitable for producing a plan first; by default it does not perform real changesPlanning, design, review, or cases where the subagent should not modify files
'dontAsk'Does not ask interactively; operations that are not pre-authorized or allowed by rules are deniedNon-interactive environments, or workflows that should fail instead of prompting
'auto'Runtime capability decides allow or deny automatically; safe workspace file edits may be auto-allowedReduce confirmation interruptions while retaining runtime judgment
For permission semantics, see Permission Control.

AgentInfo

Agent summary returned by q.supportedAgents().
type AgentInfo = {
  name: string;
  description: string;
  model?: string;
};
FieldTypeDescription
namestringAgent name
descriptionstringAgent purpose description
modelstring | undefinedAgent model override; usually empty when unset or when model: 'inherit'
const q = query({
  prompt: 'List agents.',
  options: {
    agents: {
      reviewer: {
        description: 'Reviews code quality.',
        prompt: 'Review code and report findings.',
      },
    },
  },
});

const agents = await 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.
type ModelPolicyProvider = (
  context: ModelPolicyContext,
) => ModelPolicyResult | Promise<ModelPolicyResult>;
Triggering scenarios are distinguished by QoderModelPurpose:
ScenariopurposeNotes
Main conversation'main'Re-invoked between turns / tools — a session may trigger many times
Subagent'subagent'Subagents share the same provider
WebFetch tool'web_fetch'After WebFetch retrieves content, a second LLM call summarises it
ImageGen tool'image_gen'Used to pick the image-generation model
Context compaction'compact'Before compaction starts, the callback is queried for the compaction model
BYOKanySet model to a CustomModel object to route via a third-party LLM
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.
interface ModelPolicyContext {
  purpose: QoderModelPurpose;
  sessionId: string;
  availableModels: ModelInfo[];
}
FieldTypeRequiredDescription
purposeQoderModelPurposeyesPurpose of this LLM call
sessionIdstringyesCurrent session ID; the same value is passed across callback invocations within a session, so it can be used as a cache / telemetry key
availableModelsModelInfo[]yesThe models currently available to the account, supplied by the CLI on every get_model_policy request

QoderModelPurpose

type QoderModelPurpose =
  | 'main'
  | 'subagent'
  | 'web_fetch'
  | 'image_gen'
  | 'compact';
ValueTriggering scenario
'main'Main-conversation LLM call
'subagent'Subagent call
'web_fetch'Secondary LLM call triggered by the WebFetch tool
'image_gen'Image-generation call triggered by the ImageGen tool
'compact'Context compaction / summarisation

ModelPolicyResult

The callback’s return value.
interface ModelPolicyResult {
  model: string | (CustomModel & { model: string });
  parameters?: Record<string, unknown>;
}
FieldTypeRequiredDescription
modelstring | (CustomModel & { model: string })yesString: model identifier; object: BYOK credentials + model identifier
parametersRecord<string, unknown>noModel-parameter overrides (e.g. temperature, max_tokens)
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.
interface CustomModel {
  provider: string;
  model: string;
  api_key: string;
  style?: string;
}
FieldTypeRequiredDescription
providerstringyesProvider key — must match a BYOKProviderInfo.key
modelstringyesModel identifier — extracted by the SDK as the model ID for this call
api_keystringyesThe API Key supplied by the user
stylestringnoUpstream protocol style, e.g. "openai" / "anthropic"; defaults to "openai"
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().
interface SDKControlGetByokConfigResponse {
  providers: BYOKProviderInfo[];
}

interface BYOKProviderInfo {
  key: string;
  display_name: string;
  api_key_url: string;
  types: BYOKModelTypeInfo[];
}

interface BYOKModelTypeInfo {
  key?: string;
  display_name: string;
  models: BYOKModelInfo[];
}

interface BYOKModelInfo {
  key: string;
  display_name: string;
  is_vl: boolean;
  is_reasoning: boolean;
  format: string;
  max_input_tokens: number;
}

BYOKProviderInfo

FieldTypeDescription
keystringProvider key — fill into CustomModel.provider for BYOK
display_namestringDisplay name
api_key_urlstringURL pointing the user where to obtain an API Key
typesBYOKModelTypeInfo[]Model groups under this provider

BYOKModelTypeInfo

FieldTypeDescription
keystring | undefinedGroup key, common values: cp / tp / pg
display_namestringGroup display name
modelsBYOKModelInfo[]Models within the group

BYOKModelInfo

FieldTypeDescription
keystringModel ID — fill into CustomModel.model
display_namestringDisplay name
is_vlbooleanWhether vision / multi-modal input is supported
is_reasoningbooleanWhether this is a reasoning model
formatstringUpstream protocol format (e.g. openai)
max_input_tokensnumberMaximum input token count

ModelInfo

Summary of an available model returned by q.getAvailableModels(). Also used as the element type of ModelPolicyContext.availableModels.
interface ModelInfo {
  value: string;
  displayName: string;
  isEnabled?: boolean;
}
FieldTypeDescription
valuestringModel identifier — usable as ModelPolicyResult.model or q.setModel() argument
displayNamestringDisplay name
isEnabledboolean | undefinedWhether currently available; undefined is treated as available

ModelPolicyTimeoutError

class ModelPolicyTimeoutError extends Error {}
Thrown by the SDK when the resolveModel callback exceeds options.resolveModelTimeoutMs without returning. The query fails directly, with no fallback.

q.setModel()

setModel(model?: string): Promise<void>;
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()

getAvailableModels(): Promise<ModelInfo[]>;
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()

listByokProviders(): Promise<BYOKProviderInfo[] | null>;
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.

CanUseTool

Host-defined custom tool permission approval callback.
type CanUseTool = (
  toolName: string,
  input: Record<string, unknown>,
  options: CanUseToolOptions,
) => Promise<PermissionResult>;

CanUseToolOptions

type CanUseToolOptions = {
  signal: AbortSignal;
  suggestions?: PermissionUpdate[];
  blockedPath?: string;
  decisionReason?: string;
  decisionReasonType?: PermissionDecisionReasonType;
  classifierApprovable?: boolean;
  title?: string;
  displayName?: string;
  description?: string;
  toolUseID: string;
  agentID?: string;
  exitPlanMode?: ExitPlanModeApprovalDetails;
};
options FieldTypeDescription
signalAbortSignalAborted when cancelled
suggestionsPermissionUpdate[]Permission update suggestions from CLI
blockedPathstringFile path triggering authorization (file-related scenarios only)
decisionReasonstringHuman-readable authorization reason from CLI
decisionReasonTypePermissionDecisionReasonTypePermission reason classification
classifierApprovablebooleanWhether the current call can be auto-approved by the runtime classifier
title / displayName / descriptionstringHuman-readable authorization text generated at runtime
toolUseIDstringThis tool invocation’s ID
agentIDstringSub-Agent ID initiating the call
exitPlanModeExitPlanModeApprovalDetailsApproval details for exiting plan mode
For full usage and examples, see Permission Control.

PermissionMode

type PermissionMode =
  | 'default'
  | 'acceptEdits'
  | 'bypassPermissions'
  | 'yolo'
  | 'plan'
  | 'dontAsk'
  | 'auto';
ValueMeaningSuitable for
'default'Standard permission behavior. Tool calls are handled by tools, allow / deny rules, dynamic approval, or runtime policyMost interactive sessions
'acceptEdits'Automatically accepts file-edit operations; other sensitive operations still follow the permission flowSessions that are approved to modify workspace files
'bypassPermissions'Skips permission checks; must also set allowDangerouslySkipPermissions: trueTrusted automation or test environments
'yolo'Compatibility alias for 'bypassPermissions'; must also set allowDangerouslySkipPermissions: trueCompatibility with older configs; not recommended for new code
'plan'Plan mode. Suitable for producing a plan first; by default it does not perform real changesPlanning, design, review
'dontAsk'Does not ask interactively; operations that are not pre-authorized or allowed by rules are deniedNon-interactive environments, or workflows that should fail instead of prompting
'auto'Runtime capability decides allow or deny automatically; safe workspace file edits may be auto-allowedReduce confirmation interruptions while retaining runtime judgment
For more details, see Permission Control.

PermissionResult

Return value of CanUseTool.
type PermissionResult =
  | {
      behavior: 'allow';
      updatedInput?: Record<string, unknown>;
      updatedPermissions?: PermissionUpdate[];
      toolUseID?: string;
      decisionClassification?: PermissionDecisionClassification;
    }
  | {
      behavior: 'deny';
      message: string;
      interrupt?: boolean;
      toolUseID?: string;
      decisionClassification?: PermissionDecisionClassification;
    };
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.
type McpServerConfig =
  | McpStdioServerConfig
  | McpSSEServerConfig
  | McpHttpServerConfig
  | McpSdkServerConfigWithInstance;

McpStdioServerConfig

type McpStdioServerConfig = {
  type?: 'stdio';
  command: string;
  args?: string[];
  env?: Record<string, string>;
};

McpSSEServerConfig

type McpSSEServerConfig = {
  type: 'sse';
  url: string;
  headers?: Record<string, string>;
};

McpHttpServerConfig

type McpHttpServerConfig = {
  type: 'http';
  url: string;
  headers?: Record<string, string>;
};

McpSdkServerConfigWithInstance

type McpSdkServerConfigWithInstance = {
  type: 'sdk';
  name: string;
  instance: McpServer;
};
Returned by the createSdkMcpServer() factory; see MCP - In-Process Server.

SdkPluginConfig

Load local plugins.
type SdkPluginConfig = {
  type: 'local';
  path: string;
};
FieldTypeDescription
type'local'Currently only local is supported
pathstringAbsolute or relative path to the plugin directory

CloudAgentOptions

Type of Options.experimentalCloudAgent. Configures the agent / session reference for the Cloud runtime; full usage in Cloud Agent.
type CloudAgentOptions =
  | {
      session: { id: string };
      agent?: never;
      stream?: CloudAgentStreamOptions;
    }
  | {
      agent: CloudAgentReference;
      session: { create: CloudSessionCreateParams };
      stream?: CloudAgentStreamOptions;
    };

type CloudAgentReference =
  | { id: string; create?: never }
  | { create: AgentCreateParams; id?: never };

type CloudAgentStreamOptions = {
  afterId?: string;
  deltaFlushIntervalMs?: number;
};
FieldTypeDescription
agent.idstringReuse an existing Cloud Agent; mutually exclusive with agent.create
agent.createAgentCreateParamsCreate a new Cloud Agent; mutually exclusive with agent.id
session.idstringReuse an existing Cloud session; agent must not be passed
session.createCloudSessionCreateParamsCreate a new Cloud session; environment_id is required
stream.afterIdstringSSE replay anchor — start after this event ID
stream.deltaFlushIntervalMsnumberDelta merge / flush interval, in milliseconds

AgentCreateParams

Request body for creating a new Cloud Agent, matching the agent-create fields of the Qoder Cloud OpenAPI.
type AgentCreateParams = {
  model: string;
  name: string;
  description?: string | null;
  system?: string | null;
  tools?: Array<{
    type: 'agent_toolset_20260401';
    enabled_tools?: Array<
      | 'bash'
      | 'write'
      | 'glob'
      | 'web_fetch'
      | 'read'
      | 'edit'
      | 'grep'
      | 'web_search'
    >;
  }>;
  mcp_servers?: Array<{ name: string; type: 'url'; url: string }>;
  skills?: Array<{ skill_id: string; type: 'custom' }>;
  metadata?: Record<string, string>;
};
FieldTypeDescription
modelstringModel identifier. Accepted values: 'auto' / 'ultimate' / 'performance' / 'efficient' / 'lite'
namestringHuman-readable agent name
descriptionstring | nullDescription
systemstring | nullSystem prompt
toolssee aboveBuilt-in toolset; enabled_tools controls the allowlist
mcp_serverssee aboveURL-based MCP server connections
skillssee aboveUser-defined custom skills
metadataRecord<string, string>Arbitrary key-value metadata

CloudSessionCreateParams

Request body for creating a new Cloud session.
type CloudSessionCreateParams = {
  environment_id: string;
  resources?: Array<{ type: 'file'; file_id: string; path?: string }>;
  title?: string | null;
  vault_ids?: Array<string>;
  memory_store_ids?: Array<string>;
};
FieldTypeDescription
environment_idstringContainer environment ID; required
resourcessee aboveResources mounted into the session container (currently only file)
titlestring | nullSession title
vault_idsstring[]Credential vault IDs
memory_store_idsstring[]Memory store IDs

SandboxSettings

Sandbox behavior configuration.
type SandboxSettings = {
  enabled?: boolean;
  autoAllowBashIfSandboxed?: boolean;
  excludedCommands?: string[];
  allowUnsandboxedCommands?: boolean;
  network?: SandboxNetworkConfig;
  filesystem?: SandboxFilesystemConfig;
  ignoreViolations?: { file?: string[]; network?: string[] };
  enableWeakerNestedSandbox?: boolean;
};
FieldTypeDefaultDescription
enabledbooleanfalseEnable sandbox
autoAllowBashIfSandboxedbooleantrueAuto-allow bash when sandbox is enabled
excludedCommandsstring[][]Commands that statically bypass sandbox (e.g., ['docker'])
allowUnsandboxedCommandsbooleantrueAllow model to request running commands outside sandbox (falls to canUseTool)
networkSandboxNetworkConfigundefinedNetwork restrictions
filesystemSandboxFilesystemConfigundefinedFilesystem restrictions
ignoreViolations{ file?, network? }undefinedViolations to ignore by pattern

SandboxNetworkConfig

type SandboxNetworkConfig = {
  allowLocalBinding?: boolean;
  allowUnixSockets?: string[];
  allowAllUnixSockets?: boolean;
  httpProxyPort?: number;
  socksProxyPort?: number;
};

SandboxFilesystemConfig

type SandboxFilesystemConfig = {
  allowWrite?: string[];
  denyWrite?: string[];
  denyRead?: string[];
  allowRead?: string[];
  allowManagedReadPathsOnly?: boolean;
};

SettingSource

Controls which filesystem settings are loaded.
type SettingSource = 'user' | 'project' | 'local';
ValueMeaningLocation
'user'User-level global settings~/.qoder/settings.json
'project'Project shared settings (version controlled).qoder/settings.json
'local'Project local settings (gitignored).qoder/settings.local.json
When omitted, all sources are loaded per CLI defaults; pass [] to skip entirely.

ToolConfig

Built-in tool behavior configuration.
type ToolConfig = {
  askUserQuestion?: {
    previewFormat?: 'markdown' | 'html';
  };
};

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.
CategoryTool nameDescription
Command executionBashExecute shell commands
File operationsReadRead file contents
File operationsEditEdit files by string matching
File operationsWriteCreate or overwrite files
SearchGlobSearch by filename pattern
SearchGrepSearch by content regex
NetworkWebFetchFetch and process URL content
NetworkWebSearchWeb search
AgentAgentInvoke a subagent
InteractionAskUserQuestionAsk the user a question
NotebookNotebookEditEdit notebook cells
Background tasksTaskOutputSend output to a background task
Background tasksTaskStopStop a background task
Plan / worktreeExitPlanModeExit plan mode
Plan / worktreeEnterWorktreeEnter a git worktree
Plan / worktreeExitWorktreeExit a worktree
ConfigConfigRead or write configuration
TodoTodoWriteManage todo items
MCP resourcesListMcpResourcesList MCP resources
MCP resourcesReadMcpResourceRead an MCP resource
MCP invocationMcpGeneric MCP tool call
Custom MCP tool names use this format:
mcp__{serverName}__{toolName}

tool()

Creates a type-safe SDK MCP tool definition.
function tool<Schema extends AnyZodRawShape>(
  name: string,
  description: string,
  inputSchema: Schema,
  handler: (
    args: InferShape<Schema>,
    extra: RequestHandlerExtra<ServerRequest, ServerNotification>,
  ) => Promise<CallToolResult>,
  extras?: ToolExtras,
): SdkMcpToolDefinition<Schema>;
ParameterTypeRequiredMeaningCurrent Qoder behavior
namestringYesUnique tool identifier within the current MCP serverForms the model-visible full tool name mcp__{serverName}__{name}; registration requires it to be non-empty
descriptionstringYesTool description shown to the model; describe when to use it, what it does, and what it returnsForwarded into the tool list and directly affects whether the model calls the tool correctly; registration requires it to be non-empty
inputSchemaSchema extends AnyZodRawShapeYesZod raw shape defining tool input parametersThe SDK uses it to generate the MCP input schema and infer handler args as InferShape<Schema>
handler(args, extra) => Promise<CallToolResult>YesAsync function executed when the tool is calledExecuted by the SDK when the model calls the tool; the return value is sent back to the model as a tool result
extrasToolExtrasNoExtra tool metadata, currently used for annotationsThe SDK registers supported annotations on the MCP server; this does not replace permission configuration
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

type AnyZodRawShape = ZodRawShapeCompat;
AnyZodRawShape is compatible with Zod 3 / Zod 4. It represents a field object, not z.object(...).

InferShape

type InferShape<T extends AnyZodRawShape> = ShapeOutput<T>;
InferShape infers the handler args type from the Zod raw shape.

SdkMcpToolDefinition

type SdkMcpToolDefinition<
  Schema extends AnyZodRawShape = AnyZodRawShape,
> = {
  name: string;
  description: string;
  inputSchema: Schema;
  annotations?: ToolAnnotations;
  handler: (
    args: InferShape<Schema>,
    extra: RequestHandlerExtra<ServerRequest, ServerNotification>,
  ) => Promise<CallToolResult>;
};

ToolExtras

type ToolExtras = {
  annotations?: ToolAnnotations;
};

ToolAnnotations

type ToolAnnotations = {
  title?: string;
  readOnlyHint?: boolean;
  destructiveHint?: boolean;
  openWorldHint?: boolean;
};
FieldTypeOptionalMeaningCurrent Qoder behavior
titlestringYesHuman-readable title for the toolMCP metadata; currently not documented as a verified Qoder behavioral capability
readOnlyHintbooleanYesMarks that the tool does not modify stateCurrent observable effect: read-only tools can be eligible for concurrent execution within the same batch of tool calls; this is not a permission switch
destructiveHintbooleanYesMarks that the tool may perform destructive updatesRisk metadata; currently does not automatically block an authorized tool execution
openWorldHintbooleanYesMarks whether the tool interacts with the external open worldExternal-interaction metadata; currently does not automatically block an authorized tool execution
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.
function createSdkMcpServer(
  options: CreateSdkMcpServerOptions,
): McpSdkServerConfigWithInstance;

CreateSdkMcpServerOptions

type CreateSdkMcpServerOptions = {
  name: string;
  version?: string;
  tools?: Array<SdkMcpToolDefinition<any>>;
};
FieldDefaultDescription
nameRequiredMCP server name; it becomes part of mcp__{serverName}__{toolName}
version'1.0.0'Server version information
toolsundefinedTools registered to this server

Return Value

Returns McpSdkServerConfigWithInstance, which can be passed directly as a value in options.mcpServers. For the full MCP server configuration, see McpServerConfig.
type McpSdkServerConfigWithInstance = {
  type: 'sdk';
  name: string;
  instance: McpServer;
};

CallToolResult

A tool handler returns the MCP protocol CallToolResult.
type CallToolResult = {
  content: McpToolResultContent[];
  isError?: boolean;
  _meta?: Record<string, unknown>;
};

McpToolResultContent

type McpToolResultContent =
  | { type: 'text'; text: string }
  | { type: 'image'; data: string; mimeType: string }
  | { type: 'audio'; data: string; mimeType: string }
  | {
      type: 'resource_link';
      uri: string;
      name?: string;
      description?: string;
      mimeType?: string;
    }
  | {
      type: 'resource';
      resource: {
        uri: string;
        mimeType?: string;
        text?: string;
        blob?: string;
      };
    };
FieldDescription
contentArray of content blocks returned to the model
isErrorWhen true, indicates the tool failed semantically
_metaTool-result metadata, forwarded with the MCP response

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

type AgentInput = {
  prompt: string;
  agent?: string;
  timeout_ms?: number;
};

type AgentOutput = {
  result: string;
  agent?: string;
  error?: string;
};

BashInput / BashOutput

type BashInput = {
  command: string;
  timeout?: number;
  description?: string;
  run_in_background?: boolean;
  dangerouslyDisableSandbox?: boolean;
};

type BashOutput = {
  stdout: string;
  stderr: string;
  exitCode: number;
  interrupted?: boolean;
};

FileReadInput / FileReadOutput

The runtime tool name is Read; the type names remain FileReadInput / FileReadOutput.
type FileReadInput = {
  file_path: string;
  offset?: number;
  limit?: number;
  pages?: string;
};

type FileReadOutput =
  | {
      type: 'text';
      text: string;
      file_path: string;
      totalLines?: number;
    }
  | {
      type: 'image';
      source: {
        type: 'base64';
        media_type: string;
        data: string;
      };
      file_path: string;
    }
  | {
      type: 'notebook';
      cells: Array<{
        cell_number: number;
        cell_type: 'code' | 'markdown' | 'raw';
        source: string;
        outputs?: string[];
      }>;
      file_path: string;
    }
  | {
      type: 'pdf';
      pages: Array<{
        page_number: number;
        content: string;
      }>;
      file_path: string;
      totalPages: number;
    }
  | {
      type: 'parts';
      parts: Array<
        | { type: 'text'; text: string }
        | { type: 'image'; source: { type: 'base64'; media_type: string; data: string } }
      >;
      file_path: string;
    }
  | {
      type: 'file_unchanged';
      file_path: string;
      message: string;
    };

FileEditInput / FileEditOutput

The runtime tool name is Edit.
type FileEditInput = {
  file_path: string;
  old_string: string;
  new_string: string;
  replace_all?: boolean;
};

type FileEditOutput = {
  success: boolean;
  file_path: string;
  diff?: string;
  error?: string;
};

FileWriteInput / FileWriteOutput

The runtime tool name is Write.
type FileWriteInput = {
  file_path: string;
  content: string;
};

type FileWriteOutput = {
  success: boolean;
  file_path: string;
  bytesWritten?: number;
  error?: string;
};

GlobInput / GlobOutput

type GlobInput = {
  pattern: string;
  path?: string;
};

type GlobOutput = {
  files: string[];
  totalMatches: number;
  truncated?: boolean;
};

GrepInput / GrepOutput

type GrepInput = {
  pattern: string;
  path?: string;
  glob?: string;
  type?: string;
  output_mode?: 'content' | 'files_with_matches' | 'count';
  head_limit?: number;
  offset?: number;
  context?: number;
  '-A'?: number;
  '-B'?: number;
  '-C'?: number;
  '-i'?: boolean;
  '-n'?: boolean;
  multiline?: boolean;
};

type GrepOutput = {
  results: string;
  matchCount: number;
  truncated?: boolean;
};

WebFetchInput / WebFetchOutput

type WebFetchInput = {
  url: string;
  prompt: string;
};

type WebFetchOutput = {
  content: string;
  url: string;
  statusCode?: number;
  error?: string;
  redirectUrl?: string;
};

WebSearchInput / WebSearchOutput

type WebSearchInput = {
  query: string;
  allowed_domains?: string[];
  blocked_domains?: string[];
};

type WebSearchOutput = {
  results: Array<{
    title: string;
    url: string;
    snippet: string;
  }>;
  query: string;
};

AskUserQuestionInput / AskUserQuestionOutput

type AskUserQuestionInput = {
  question: string;
  options?: string[];
  default?: string;
};

type AskUserQuestionOutput = {
  answer: string;
};

NotebookEditInput / NotebookEditOutput

type NotebookEditInput = {
  notebook_path: string;
  cell_id?: string;
  cell_type?: 'code' | 'markdown';
  new_source: string;
  edit_mode?: 'replace' | 'insert' | 'delete';
};

type NotebookEditOutput = {
  success: boolean;
  notebook_path: string;
  error?: string;
};

TaskOutputInput

type TaskOutputInput = {
  task_id: string;
  output: string;
};

TaskStopInput / TaskStopOutput

type TaskStopInput = {
  task_id: string;
  reason?: string;
};

type TaskStopOutput = {
  success: boolean;
  task_id: string;
  error?: string;
};

ExitPlanModeInput / ExitPlanModeOutput

type ExitPlanModeInput = {
  confirm?: boolean;
};

type ExitPlanModeOutput = {
  success: boolean;
  error?: string;
};

ConfigInput / ConfigOutput

type ConfigInput = {
  action: 'get' | 'set' | 'list';
  key?: string;
  value?: unknown;
  scope?: 'user' | 'project' | 'local';
};

type ConfigOutput = {
  success: boolean;
  value?: unknown;
  values?: Record<string, unknown>;
  error?: string;
};

EnterWorktreeInput / EnterWorktreeOutput

type EnterWorktreeInput = {
  name?: string;
};

type EnterWorktreeOutput = {
  worktree_path: string;
  branch_name: string;
  success: boolean;
  error?: string;
};

ExitWorktreeInput / ExitWorktreeOutput

type ExitWorktreeInput = {
  action: 'keep' | 'remove';
  discard_changes?: boolean;
};

type ExitWorktreeOutput = {
  success: boolean;
  error?: string;
  uncommitted_files?: string[];
  unmerged_commits?: string[];
};

TodoWriteInput / TodoWriteOutput

type TodoWriteInput = {
  todos: Array<{
    id?: string;
    content: string;
    status: 'pending' | 'in_progress' | 'completed';
    priority?: 'low' | 'medium' | 'high';
  }>;
};

type TodoWriteOutput = {
  success: boolean;
  todos: Array<{
    id: string;
    content: string;
    status: 'pending' | 'in_progress' | 'completed';
    priority?: 'low' | 'medium' | 'high';
  }>;
  error?: string;
};

ListMcpResourcesInput / ListMcpResourcesOutput

type ListMcpResourcesInput = {
  server_name: string;
};

type ListMcpResourcesOutput = {
  resources: Array<{
    uri: string;
    name: string;
    description?: string;
    mimeType?: string;
  }>;
  server_name: string;
};

ReadMcpResourceInput

type ReadMcpResourceInput = {
  server_name: string;
  uri: string;
};

McpInput / McpOutput

type McpInput = {
  server_name: string;
  tool_name: string;
  arguments?: Record<string, unknown>;
};

type McpOutput = {
  content: unknown;
  isError?: boolean;
};

ToolInputSchemas

type ToolInputSchemas =
  | AgentInput
  | BashInput
  | FileReadInput
  | FileEditInput
  | FileWriteInput
  | GlobInput
  | GrepInput
  | WebFetchInput
  | WebSearchInput
  | AskUserQuestionInput
  | NotebookEditInput
  | TaskOutputInput
  | TaskStopInput
  | ExitPlanModeInput
  | ConfigInput
  | EnterWorktreeInput
  | ExitWorktreeInput
  | TodoWriteInput
  | ListMcpResourcesInput
  | ReadMcpResourceInput
  | McpInput;

ToolOutputSchemas

type ToolOutputSchemas =
  | AgentOutput
  | BashOutput
  | FileReadOutput
  | FileEditOutput
  | FileWriteOutput
  | GlobOutput
  | GrepOutput
  | WebFetchOutput
  | WebSearchOutput
  | AskUserQuestionOutput
  | NotebookEditOutput
  | TaskStopOutput
  | ExitPlanModeOutput
  | ConfigOutput
  | EnterWorktreeOutput
  | ExitWorktreeOutput
  | TodoWriteOutput
  | ListMcpResourcesOutput
  | McpOutput;

Hooks Reference

For usage guide and examples, see Hooks.

Event Overview

EventTriggerControllable Behavior
PreToolUseBefore tool invocationIntercept / allow / modify input
PostToolUseAfter tool succeedsAudit / inject context / override output
PostToolUseFailureAfter tool failsError handling / logging
UserPromptSubmitBefore user prompt is sentInject context / intercept
SessionStartSession beginsInitialize / inject context
SessionEndSession endsCleanup / logging
StopAI stops generatingPrevent stop, force continuation
SubagentStartSubagent startsObserve / log
SubagentStopSubagent stopsObserve / log
PreCompactBefore context compactionObserve / log
PostCompactAfter context compactionObserve / log
CwdChangedWorking directory changesObserve / log
InstructionsLoadedInstruction file loadedObserve / log
FileChangedFile created/modified/deletedObserve / log
PermissionRequestPermission requestedAuto-approve / deny permission requests

HookEvent

Union type of registrable hook events.
type HookEvent =
  | 'PreToolUse'
  | 'PostToolUse'
  | 'PostToolUseFailure'
  | 'UserPromptSubmit'
  | 'SessionStart'
  | 'SessionEnd'
  | 'Stop'
  | 'SubagentStart'
  | 'SubagentStop'
  | 'PreCompact'
  | 'PostCompact'
  | 'CwdChanged'
  | 'InstructionsLoaded'
  | 'FileChanged'
  | 'PermissionRequest';

HookCallback

type HookCallback = (
  input: HookInput,
  toolUseID: string | undefined,
  options: { signal: AbortSignal }
) => Promise<HookJSONOutput>;

HookCallbackMatcher

interface HookCallbackMatcher {
  matcher?: string;
  hooks: HookCallback[];
  timeout?: number;
}
FieldTypeDescription
matcherstringOptional regex; filters by tool_name
hooksHookCallback[]Callback list executed on match
timeoutnumberOptional timeout in seconds (default: 60)

BaseHookInput

Common input fields shared by all hook events.
interface BaseHookInput {
  hook_event_name: string;
  session_id: string;
  transcript_path: string;
  cwd: string;
}
FieldTypeDescription
hook_event_namestringEvent type identifier (e.g. "PreToolUse")
session_idstringUnique identifier for the current session
transcript_pathstringPath to session transcript file (JSONL format)
cwdstringCurrent working directory of the session

HookJSONOutput

Return type for hook callbacks.
interface HookJSONOutput {
  continue?: boolean;
  stopReason?: string;
  decision?: string;
  reason?: string;
  hookSpecificOutput?: object;
}
FieldTypeDefaultDescription
continuebooleantrueSet to false to terminate the session. Only effective for PreToolUse, PostToolUse, PostToolUseFailure, UserPromptSubmit, Stop, SubagentStop
stopReasonstringHuman-readable reason for stopping (used with continue: false)
decisionstring"approve" or "block". "block" prevents tool execution; for Stop events, "block" prevents stopping and forces continuation
reasonstringReason for the decision (shown to the model; for Stop event "block", injected as a continuation prompt)
hookSpecificOutputobjectEvent-specific output (see each event type)
When multiple hooks return conflicting decision values, "deny" / "block" takes precedence (strictest rule wins).

PreToolUseHookInput

interface PreToolUseHookInput extends BaseHookInput {
  hook_event_name: 'PreToolUse';
  permission_mode: string | undefined;
  tool_name: string;
  tool_input: unknown;
}
FieldTypeDescription
permission_modestring | undefinedCurrent session permission mode
tool_namestringName of the tool being called
tool_inputunknownArguments passed to the tool
hookSpecificOutput:
FieldTypeDescription
hookEventName"PreToolUse"Must be set
permissionDecisionstring"allow" / "deny" / "ask" / "defer"
permissionDecisionReasonstringReason for the permission decision
updatedInputRecord<string, unknown>Modified tool input, replaces original tool_input
additionalContextstringExtra context injected into the model’s next turn

PostToolUseHookInput

interface PostToolUseHookInput extends BaseHookInput {
  hook_event_name: 'PostToolUse';
  tool_name: string;
  tool_input: unknown;
  tool_response: unknown;
}
FieldTypeDescription
tool_namestringName of the tool that was called
tool_inputunknownArguments passed to the tool
tool_responseunknownTool execution result
Output behavior:
FieldLocationBehavior
hookSpecificOutput.updatedToolOutputEvent-specific outputOverrides tool_response; model only sees the overridden value
hookSpecificOutput.additionalContextEvent-specific outputAppends supplementary context without modifying original result
decision: "block" + reasonTop-level outputPrevents agent from further processing this tool result
hookSpecificOutput:
FieldTypeDescription
hookEventName"PostToolUse"Must be set
updatedToolOutputstringOverrides tool response content
additionalContextstringExtra context appended alongside tool result
When multiple hooks set updatedToolOutput, the last non-empty value wins. For chained transforms, execute them sequentially within a single callback.

PostToolUseFailureHookInput

interface PostToolUseFailureHookInput extends BaseHookInput {
  hook_event_name: 'PostToolUseFailure';
  tool_name: string;
  tool_input: unknown;
  error: string;
  is_interrupt: boolean | undefined;
}
FieldTypeDescription
tool_namestringName of the failed tool
tool_inputunknownArguments passed to the tool
errorstringError message
is_interruptboolean | undefinedWhether caused by an interrupt/abort

UserPromptSubmitHookInput

interface UserPromptSubmitHookInput extends BaseHookInput {
  hook_event_name: 'UserPromptSubmit';
  prompt: string;
}
FieldTypeDescription
promptstringUser input text
hookSpecificOutput:
FieldTypeDescription
hookEventName"UserPromptSubmit"Must be set
additionalContextstringExtra context appended to the user prompt

SessionStartHookInput

interface SessionStartHookInput extends BaseHookInput {
  hook_event_name: 'SessionStart';
  source: string;
}
FieldTypeDescription
sourcestringSession start reason: "startup" / "resume" / "clear" / "compact"
hookSpecificOutput:
FieldTypeDescription
hookEventName"SessionStart"Must be set
additionalContextstringContext injected at session start

SessionEndHookInput

interface SessionEndHookInput extends BaseHookInput {
  hook_event_name: 'SessionEnd';
  reason: string;
}
FieldTypeDescription
reasonstringSession end reason: "clear" / "resume" / "logout" / "prompt_input_exit" / "other" / "bypass_permissions_disabled"

StopHookInput

interface StopHookInput extends BaseHookInput {
  hook_event_name: 'Stop';
  stop_hook_active: boolean;
}
FieldTypeDescription
stop_hook_activebooleanWhether a Stop hook is currently preventing stop
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

interface SubagentStartHookInput extends BaseHookInput {
  hook_event_name: 'SubagentStart';
  agent_id: string;
  agent_type: string;
}
FieldTypeDescription
agent_idstringUnique identifier of the subagent instance
agent_typestringType/role of the subagent

SubagentStopHookInput

interface SubagentStopHookInput extends BaseHookInput {
  hook_event_name: 'SubagentStop';
  stop_hook_active: boolean;
}
FieldTypeDescription
stop_hook_activebooleanWhether a Stop hook is currently preventing stop

PreCompactHookInput

interface PreCompactHookInput extends BaseHookInput {
  hook_event_name: 'PreCompact';
  trigger: string;
  custom_instructions: string | null;
}
FieldTypeDescription
triggerstringTrigger reason: "manual" / "auto"
custom_instructionsstring | nullCustom instructions for compaction summary

PostCompactHookInput

interface PostCompactHookInput extends BaseHookInput {
  hook_event_name: 'PostCompact';
  trigger: string;
  compact_summary: string;
}
FieldTypeDescription
triggerstringTrigger reason: "manual" / "auto"
compact_summarystringSummary generated after context compaction

CwdChangedHookInput

interface CwdChangedHookInput extends BaseHookInput {
  hook_event_name: 'CwdChanged';
  old_cwd: string;
  new_cwd: string;
}
FieldTypeDescription
old_cwdstringWorking directory before the change
new_cwdstringWorking directory after the change

InstructionsLoadedHookInput

interface InstructionsLoadedHookInput extends BaseHookInput {
  hook_event_name: 'InstructionsLoaded';
  load_reason: string;
}
FieldTypeDescription
load_reasonstringLoad reason: "nested_traversal" / "path_glob_match"

FileChangedHookInput

interface FileChangedHookInput extends BaseHookInput {
  hook_event_name: 'FileChanged';
  file_path: string;
  event: string;
}
FieldTypeDescription
file_pathstringPath of the changed file
eventstringFilesystem event: "change" / "add" / "unlink"

PermissionRequestHookInput

interface PermissionRequestHookInput extends BaseHookInput {
  hook_event_name: 'PermissionRequest';
  tool_name: string;
  tool_input: unknown;
  permission_suggestions: PermissionUpdate[] | undefined;
}
FieldTypeDescription
tool_namestringTool requesting permission
tool_inputunknownTool input arguments
permission_suggestionsPermissionUpdate[] | undefinedSuggested permission rules
hookSpecificOutput:
FieldTypeDescription
hookEventName"PermissionRequest"Must be set
decisionobjectPermission decision (see below)
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.
type SDKMessage =
  | SDKAssistantMessage
  | SDKUserMessage
  | SDKUserMessageReplay
  | SDKResultMessage
  | SDKSystemMessage
  | SDKPartialAssistantMessage
  | SDKCompactBoundaryMessage
  | SDKStatusMessage
  | SDKMcpStatusChangeMessage
  | SDKAPIRetryMessage
  | SDKLocalCommandOutputMessage
  | SDKHookStartedMessage
  | SDKHookProgressMessage
  | SDKHookResponseMessage
  | SDKTaskStartedMessage
  | SDKTaskProgressMessage
  | SDKTaskNotificationMessage
  | SDKSessionStateChangedMessage
  | SDKSessionTitleChangedMessage
  | SDKBridgeStateMessage
  | SDKFilesPersistedEvent
  | SDKElicitationCompleteMessage
  | SDKPermissionDeniedMessage
  | SDKPromptSuggestionMessage
  | SDKCloudAgentEventMessage;
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.
type SDKAssistantMessage = {
  type: 'assistant';
  uuid: string;
  session_id: string;
  parent_tool_use_id: string | null;
  message: {
    role: 'assistant';
    content: Array<
      | { type: 'text'; text: string }
      | { type: 'tool_use'; id: string; name: string; input: unknown }
      | { type: 'thinking'; thinking: string }
    >;
  };
};

SDKUserMessage

User message or tool result feedback.
type SDKUserMessage = {
  type: 'user';
  uuid?: string;
  session_id?: string;
  parent_tool_use_id: string | null;
  message: {
    role: 'user';
    content: Array<
      | { type: 'text'; text: string }
      | { type: 'image'; source: { type: 'base64'; media_type: string; data: string } }
      | { type: 'tool_result'; tool_use_id: string; content: string | unknown[]; is_error?: boolean }
    >;
  };
  isSynthetic?: boolean;
  tool_use_result?: unknown;
};

SDKUserMessageReplay

Historical user messages replayed during session resume.
type SDKUserMessageReplay = SDKUserMessage & {
  uuid: string;
  session_id: string;
  isReplay: true;
};

SDKResultMessage

Final message when the entire session ends.
type SDKResultMessage =
  | {
      type: 'result';
      subtype: 'success';
      uuid: string;
      session_id: string;
      duration_ms: number;
      duration_api_ms: number;
      is_error: boolean;
      num_turns: number;
      result: string;
      permission_denials: SDKPermissionDenial[];
    }
  | {
      type: 'result';
      subtype:
        | 'error_max_turns'
        | 'error_during_execution'
        | 'error_max_structured_output_retries';
      // Same common fields as success
      errors: string[];
    };

SDKSystemMessage

Session initialization message (subtype: 'init'). Other system events are delivered via separate message types; see the various SDK*Message types below.
type SDKSystemMessage = {
  type: 'system';
  subtype: 'init';
  uuid: string;
  session_id: string;
  qodercli_version: string;
  protocol_version?: string;
  apiKeySource: 'user' | 'project' | 'org' | 'temporary';
  cwd: string;
  model: string;
  permissionMode: PermissionMode;
  tools: string[];
  slash_commands: string[];
  output_style: string;
  agents?: string[];
  skills: string[];
  plugins: { name: string; path: string; source?: string }[];
  mcp_servers: { name: string; status: string }[];
  fast_mode_state?: 'off' | 'cooldown' | 'on';
};

SDKPartialAssistantMessage

Requires includePartialMessages: true; streams out incrementally per token. For full usage, see Streaming Output.
type SDKPartialAssistantMessage = {
  type: 'stream_event';
  uuid: string;
  session_id: string;
  parent_tool_use_id: string | null;
  event: {
    type: string;
    index?: number;
    delta?: {
      type?: string;
      text?: string;
      partial_json?: string;
      thinking?: string;
    };
    content_block?: {
      type: string;
      id?: string;
      name?: string;
      text?: string;
    };
  };
};

SDKCompactBoundaryMessage

Boundary marker for context compaction completion.
type SDKCompactBoundaryMessage = {
  type: 'system';
  subtype: 'compact_boundary';
  uuid: string;
  session_id: string;
  compact_metadata: {
    trigger: 'manual' | 'auto';
    pre_tokens: number;
    preserved_segment?: {
      head_uuid: string;
      anchor_uuid: string;
      tail_uuid: string;
    };
  };
};

SDKStatusMessage

Session running state changes (e.g., compacting).
type SDKStatusMessage = {
  type: 'system';
  subtype: 'status';
  status: 'compacting' | null;
  permissionMode?: PermissionMode;
  uuid: string;
  session_id: string;
};

SDKMcpStatusChangeMessage

MCP connection pool state change.
type SDKMcpStatusChangeMessage = {
  type: 'system';
  subtype: 'mcp_status_change';
  servers: McpServerStatus[];
  uuid: string;
  session_id: string;
};

SDKAPIRetryMessage

Automatic retry on network/service errors.
type SDKAPIRetryMessage = {
  type: 'system';
  subtype: 'api_retry';
  attempt: number;
  max_retries: number;
  retry_delay_ms: number;
  error_status: number | null;
  error: SDKAssistantMessageError;
  uuid: string;
  session_id: string;
};

SDKLocalCommandOutputMessage

Output from local slash commands.
type SDKLocalCommandOutputMessage = {
  type: 'system';
  subtype: 'local_command_output';
  content: string;
  uuid: string;
  session_id: string;
};

SDKHookStartedMessage

Hook begins execution.
type SDKHookStartedMessage = {
  type: 'system';
  subtype: 'hook_started';
  hook_id: string;
  hook_name: string;
  hook_event: string;
  uuid: string;
  session_id: string;
};

SDKHookProgressMessage

Hook execution output in progress.
type SDKHookProgressMessage = {
  type: 'system';
  subtype: 'hook_progress';
  hook_id: string;
  hook_name: string;
  hook_event: string;
  stdout: string;
  stderr: string;
  output: string;
  uuid: string;
  session_id: string;
};

SDKHookResponseMessage

Hook finishes.
type SDKHookResponseMessage = {
  type: 'system';
  subtype: 'hook_response';
  hook_id: string;
  hook_name: string;
  hook_event: string;
  output: string;
  stdout: string;
  stderr: string;
  exit_code?: number;
  outcome: 'success' | 'error' | 'cancelled';
  uuid: string;
  session_id: string;
};

SDKTaskStartedMessage

Sub-Agent task starts.
type SDKTaskStartedMessage = {
  type: 'system';
  subtype: 'task_started';
  task_id: string;
  tool_use_id?: string;
  description: string;
  task_type?: string;
  workflow_name?: string;
  prompt?: string;
  uuid: string;
  session_id: string;
};

SDKTaskProgressMessage

Sub-Agent task progress.
type SDKTaskProgressMessage = {
  type: 'system';
  subtype: 'task_progress';
  task_id: string;
  tool_use_id?: string;
  description: string;
  usage: {
    total_tokens: number;
    tool_uses: number;
    duration_ms: number;
  };
  last_tool_name?: string;
  summary?: string;
  uuid: string;
  session_id: string;
};

SDKTaskNotificationMessage

Sub-Agent task finishes.
type SDKTaskNotificationMessage = {
  type: 'system';
  subtype: 'task_notification';
  task_id: string;
  tool_use_id?: string;
  status: 'completed' | 'failed' | 'stopped';
  output_file: string;
  summary: string;
  usage?: {
    total_tokens: number;
    tool_uses: number;
    duration_ms: number;
  };
  uuid: string;
  session_id: string;
};

SDKSessionStateChangedMessage

Main session running state change.
type SDKSessionStateChangedMessage = {
  type: 'system';
  subtype: 'session_state_changed';
  state: 'idle' | 'running' | 'requires_action';
  uuid: string;
  session_id: string;
};

SDKSessionTitleChangedMessage

Session title change.
type SDKSessionTitleChangedMessage = {
  type: 'system';
  subtype: 'session_title_changed';
  title: string;
  source: 'ai' | 'custom';
  revision: number;
  uuid: string;
  session_id: string;
};

SDKBridgeStateMessage

Bridge connection state change.
type SDKBridgeStateMessage = {
  type: 'system';
  subtype: 'bridge_state';
  state: string;
  detail?: string;
  uuid: string;
  session_id: string;
};

SDKFilesPersistedEvent

File checkpoint persistence result.
type SDKFilesPersistedEvent = {
  type: 'system';
  subtype: 'files_persisted';
  files: { filename: string; file_id: string }[];
  failed: { filename: string; error: string }[];
  processed_at: string;
  uuid: string;
  session_id: string;
};

SDKElicitationCompleteMessage

MCP elicitation complete.
type SDKElicitationCompleteMessage = {
  type: 'system';
  subtype: 'elicitation_complete';
  mcp_server_name: string;
  elicitation_id: string;
  uuid: string;
  session_id: string;
};

SDKPermissionDeniedMessage

Tool call short-circuited by permission policy (dontAsk / auto / deny rule, etc.).
type SDKPermissionDeniedMessage = {
  type: 'system';
  subtype: 'permission_denied';
  tool_name: string;
  tool_use_id: string;
  agent_id?: string;
  decision_reason_type?: string;
  decision_reason?: string;
  message: string;
  uuid: string;
  session_id: string;
};

SDKPromptSuggestionMessage

When promptSuggestions: true is enabled, next-step suggestions that may be received after each turn’s result.
type SDKPromptSuggestionMessage = {
  type: 'prompt_suggestion';
  suggestion: string;
  uuid: string;
  session_id: string;
};

SDKCloudAgentEventMessage

Under the Cloud runtime (options.experimentalCloudAgent), events forwarded from the Qoder Cloud session SSE stream. See Cloud Agent for full usage.
type SDKCloudAgentEventMessage = {
  type: 'cloud_agent_event';
  event: string;
  id?: string;
  data: unknown;
  uuid: string;
  session_id: string;
};
FieldTypeDescription
eventstringCloud event name, e.g. user.message, agent.message, session.status_idle
idstringSSE event ID; usable as stream.afterId for replay
dataunknownCloud event payload (includes turn_id and other fields)
session_idstringCloud session ID this event belongs to

SDKPermissionDenial

Element in the SDKResultMessage.permission_denials array.
type SDKPermissionDenial = {
  tool_name: string;
  tool_use_id: string;
  tool_input: Record<string, unknown>;
};