> ## 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.

# SDK リファレンス

<div id="functions" />

## Functions

<div id="query" />

### `query()`

SDK のメインエントリ関数です。async generator を作成し、メッセージの到着順に `SDKMessage` をストリーム出力します。

```typescript theme={null}
function query(params: {
  prompt: string | AsyncIterable<SDKUserMessage>;
  options?: Options;
}): Query
```

<div id="パラメータ" />

#### パラメータ

| パラメータ     | 型                                                                | 説明                                |
| :-------- | :--------------------------------------------------------------- | :-------------------------------- |
| `prompt`  | `string \| AsyncIterable<`[`SDKUserMessage`](#sdkusermessage)`>` | シングルターンは文字列、マルチターンは非同期イテラブルオブジェクト |
| `options` | [`Options`](#options)                                            | オプションのセッション設定                     |

<div id="戻り値" />

#### 戻り値

`Query` を返します。これは `AsyncGenerator<`[`SDKMessage`](#sdkmessage)`, void>` であり、`for await` で消費します。

<div id="types" />

## Types

<div id="options" />

### `Options`

`query()` の設定オブジェクトです。

| フィールド                             | 型                                                                                                 | デフォルト値                  | 説明                                                                                              |
| :-------------------------------- | :------------------------------------------------------------------------------------------------ | :---------------------- | :---------------------------------------------------------------------------------------------- |
| `abortController`                 | `AbortController`                                                                                 | `new AbortController()` | セッションをキャンセルするコントローラー                                                                            |
| `additionalDirectories`           | `string[]`                                                                                        | `[]`                    | AI がアクセス可能な追加ディレクトリ                                                                             |
| `agent`                           | `string`                                                                                          | `undefined`             | メインセッションで使用する Agent 名。[Agents Reference](#optionsagent) を参照                                     |
| `agents`                          | `Record<string, AgentDefinition>`                                                                 | `undefined`             | プログラムで定義するサブエージェント。[Agents Reference](#optionsagents) を参照                                       |
| `allowDangerouslySkipPermissions` | `boolean`                                                                                         | `false`                 | 権限チェックのスキップを許可。`permissionMode: 'bypassPermissions'` と併用                                        |
| `allowedTools`                    | `string[]`                                                                                        | `[]`                    | ツールホワイトリスト。事前承認で通過。組み込みツール名は [Tools Reference](#組み込みツール一覧) を参照                                  |
| `auth`                            | [`AuthOptions`](#authoptions)                                                                     | `undefined`             | 認証設定。**`query()` で必須**                                                                          |
| `canUseTool`                      | [`CanUseTool`](#canusetool)                                                                       | `undefined`             | カスタムツール権限コールバック                                                                                 |
| `continue`                        | `boolean`                                                                                         | `false`                 | 最後のセッションを継続                                                                                     |
| `cwd`                             | `string`                                                                                          | `process.cwd()`         | 作業ディレクトリ                                                                                        |
| `disallowedTools`                 | `string[]`                                                                                        | `[]`                    | ツールブラックリスト。`allowedTools` および `permissionMode` より優先。組み込みツール名は [Tools Reference](#組み込みツール一覧) を参照 |
| `enableFileCheckpointing`         | `boolean`                                                                                         | `false`                 | ファイルチェックポイントの有効化。`rewindFiles()` と併用。[Checkpoint](/ja/cli/sdk/checkpoint) を参照                   |
| `env`                             | `Record<string, string \| undefined>`                                                             | `process.env`           | CLI プロセスに渡す環境変数                                                                                 |
| `proxy`                           | `string`                                                                                          | `undefined`             | CLI プロセスで使用するプロキシ URL。`http://`、`https://`、`socks5://`、`socks://` をサポート                         |
| `executable`                      | `'bun' \| 'deno' \| 'node'`                                                                       | 自動検出                    | JavaScript ランタイム                                                                                |
| `executableArgs`                  | `string[]`                                                                                        | `[]`                    | ランタイムに渡す引数                                                                                      |
| `experimentalCloudAgent`          | [`CloudAgentOptions`](#cloudagentoptions)                                                         | `undefined`             | Qoder Cloud Agent ランタイム（experimental）に切り替え。[Cloud Agent](/ja/cli/sdk/cloud-agent) を参照           |
| `extraArgs`                       | `Record<string, string \| null>`                                                                  | `{}`                    | CLI に渡す追加引数                                                                                     |
| `fallbackModel`                   | `string`                                                                                          | `undefined`             | メインモデル失敗時の代替モデル                                                                                 |
| `forkSession`                     | `boolean`                                                                                         | `false`                 | `resume` と併用時に新しいセッション ID にフォーク                                                                 |
| `hooks`                           | `Partial<Record<`[`HookEvent`](#hookevent)`, `[`HookCallbackMatcher`](#hookcallbackmatcher)`[]>>` | `{}`                    | ライフサイクルフック。[Hooks](/ja/cli/sdk/hooks) を参照                                                       |
| `includeHookEvents`               | `boolean`                                                                                         | `false`                 | メッセージストリームに hook ライフサイクルイベントを含める                                                                |
| `includePartialMessages`          | `boolean`                                                                                         | `false`                 | `stream_event` ストリームフラグメントを含める。[ストリーム出力](/ja/cli/sdk/streaming-output) を参照                      |
| `maxTurns`                        | `number`                                                                                          | `undefined`             | 最大対話ターン数（ツール呼び出しのラウンドトリップ数）                                                                     |
| `mcpServers`                      | `Record<string, `[`McpServerConfig`](#mcpserverconfig)`>`                                         | `{}`                    | MCP サーバー設定。[MCP](/ja/cli/sdk/mcp) を参照                                                           |
| `model`                           | `string`                                                                                          | CLI デフォルト               | 使用モデル。選択肢: `'auto'` / `'ultimate'` / `'performance'` / `'efficient'` / `'lite'`                 |
| `pathToQoderCLIExecutable`        | `string`                                                                                          | バンドル済みバイナリを自動解決         | qodercli 実行ファイルパス                                                                               |
| `permissionMode`                  | [`PermissionMode`](#permissionmode)                                                               | `'default'`             | セッション権限モード                                                                                      |
| `permissionPromptToolName`        | `string`                                                                                          | `undefined`             | 権限プロンプト用の MCP ツール名。`canUseTool` と排他                                                             |
| `planModeInstructions`            | `string`                                                                                          | `undefined`             | `permissionMode: 'plan'` 時に計画モードのワークフロー本文を上書き                                                   |
| `plugins`                         | [`SdkPluginConfig`](#sdkpluginconfig)`[]`                                                         | `[]`                    | ローカルプラグインの読み込み。[Plugins](/ja/cli/sdk/plugins) を参照                                               |
| `promptSuggestions`               | `boolean`                                                                                         | `false`                 | 各ターンの result 後に `prompt_suggestion` メッセージを発行                                                    |
| `resolveModel`                    | [`ModelPolicyProvider`](#modelpolicyprovider)                                                     | `undefined`             | 動的モデル選択コールバック。渡した時点で動的コールバックモードに切り替わる。[Model Policy](/ja/cli/sdk/model-policy) を参照              |
| `resolveModelTimeoutMs`           | `number`                                                                                          | `500`                   | コールバックタイムアウト（ミリ秒）。`resolveModel` を渡したときのみ有効                                                     |
| `resume`                          | `string`                                                                                          | `undefined`             | 復元するセッション ID                                                                                    |
| `resumeSessionAt`                 | `string`                                                                                          | `undefined`             | 指定メッセージ UUID から復元                                                                               |
| `sandbox`                         | [`SandboxSettings`](#sandboxsettings)                                                             | `undefined`             | サンドボックス設定                                                                                       |
| `sessionId`                       | `string`                                                                                          | 自動生成                    | セッション UUID の指定                                                                                  |
| `settings`                        | `string \| Settings`                                                                              | `undefined`             | インライン settings オブジェクトまたは settings ファイルパス                                                        |
| `settingSources`                  | [`SettingSource`](#settingsource)`[]`                                                             | CLI デフォルト               | ロードする filesystem settings。`[]` で user/project/local をスキップ                                       |
| `skills`                          | `string[] \| 'all'`                                                                               | `undefined`             | 有効にする Skill。`'all'` で全て有効化。[Skills](/ja/cli/sdk/skills) を参照                                     |
| `spawnQoderCLIProcess`            | `(options: SpawnOptions) => SpawnedProcess`                                                       | `undefined`             | カスタムプロセス spawn 関数                                                                               |
| `strictMcpConfig`                 | `boolean`                                                                                         | `false`                 | 厳密な MCP 検証                                                                                      |
| `systemPrompt`                    | `string \| { type: 'preset'; preset: 'qodercli'; append?: string }`                               | `undefined`             | システムプロンプト。文字列で上書き、preset 形式では qodercli プリセットの後に append                                          |
| `toolConfig`                      | [`ToolConfig`](#toolconfig)                                                                       | `undefined`             | 組み込みツール動作設定。[Tools](/ja/cli/sdk/tools) を参照                                                      |
| `tools`                           | `string[] \| { type: 'preset'; preset: 'qodercli' }`                                              | `undefined`             | ツール集合。文字列配列で利用可能ツールを制限。空配列で全ツール無効化。組み込みツール名は [Tools Reference](#組み込みツール一覧) を参照                  |

<div id="authoptions" />

### `AuthOptions`

```typescript theme={null}
type AuthOptions =
  | { type: 'accessToken'; accessToken: string | { envVar: string } }
  | { type: 'qodercli' };
```

| 形式                                                 | 説明                                                     |
| :------------------------------------------------- | :----------------------------------------------------- |
| `{ type: 'accessToken'; accessToken: string }`     | PAT を直接渡す                                              |
| `{ type: 'accessToken'; accessToken: { envVar } }` | 指定環境変数から PAT を読み取り。デフォルト `QODER_PERSONAL_ACCESS_TOKEN` |
| `{ type: 'qodercli' }`                             | ローカルの `qodercli login` 状態を再利用                          |

便利なコンストラクター：`accessToken(token)` / `accessTokenFromEnv(envVar?)` / `qodercliAuth()`。[SDK 認証](/ja/cli/sdk/authentication) を参照。

<div id="optionsagents" />

### `options.agents`

**型:** `Record<string, AgentDefinition>`

現在の `query()` セッションで利用できるカスタム Agent を登録します。オブジェクトの key が Agent 名、value がその Agent 定義です。

> **`Agent` ツールが必要です**: カスタムサブエージェントは、メインセッションから組み込み `Agent` ツール経由で委任されます。Qoder は Agent ツールを通じてサブエージェントを起動するため、`allowedTools` に `Agent` を含める必要があります。

```typescript theme={null}
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'],
      },
    },
  },
});
```

登録後、モデルは組み込み `Agent` ツールを通じてこれらのサブエージェントを呼び出せます。メインセッションがタスクを委任するには、ツール集合に `Agent` が含まれている必要があります。`allowedTools: ['Agent']` は必須の事前承認指定です。`options.tools` でメインセッションの利用可能ツールを絞る場合も、`Agent` を含めてください。

<div id="optionsagent" />

### `options.agent`

**型:** `string`

メインセッションをどの Agent 身分で実行するかを指定します。値には `options.agents` に登録した名前、または現在の CLI が検出した組み込み / プラグイン Agent 名を指定できます。

```typescript theme={null}
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',
  },
});
```

設定すると、メインセッションはその Agent の `prompt`、`model`、ツール制限を使用します。省略時はデフォルトのメインセッション動作になります。

<div id="agentdefinition" />

### `AgentDefinition`

カスタム Agent の定義です。以下のフィールドは、現行 SDK でカバーされ、機能テストで検証されている安定機能です。

```typescript theme={null}
type AgentDefinition = {
  description: string;
  prompt: string;
  tools?: string[];
  disallowedTools?: string[];
  model?: string;
  mcpServers?: AgentMcpServerSpec[];
  skills?: string[];
  initialPrompt?: string;
  maxTurns?: number;
  effort?: EffortLevel;
  permissionMode?: PermissionMode;
};
```

| フィールド             | 型                      | 必須  | 説明                                                  |
| ----------------- | ---------------------- | --- | --------------------------------------------------- |
| `description`     | `string`               | はい  | Agent の用途説明。モデルはこれを見ていつ呼び出すかを判断します                  |
| `prompt`          | `string`               | はい  | Agent のシステムプロンプト                                    |
| `tools`           | `string[]`             | いいえ | Agent が使用できるツールのホワイトリスト                             |
| `disallowedTools` | `string[]`             | いいえ | Agent のツール集合から除外するツール                               |
| `model`           | `string`               | いいえ | モデル上書き。`'inherit'` はメインセッションのモデルを継承します              |
| `mcpServers`      | `AgentMcpServerSpec[]` | いいえ | Agent が使用できる MCP server 仕様                          |
| `skills`          | `string[]`             | いいえ | Agent コンテキストへプリロードする skill 名                        |
| `initialPrompt`   | `string`               | いいえ | この Agent がメインセッション Agent として使われるときに自動送信される最初のユーザー入力 |
| `maxTurns`        | `number`               | いいえ | Agent の最大 API ターン数                                  |
| `effort`          | `EffortLevel`          | いいえ | 推論努力レベル                                             |
| `permissionMode`  | `PermissionMode`       | いいえ | この Agent 内でのツール実行の権限モード                             |

<div id="description" />

#### `description`

Agent がどのようなタスクに適しているかを説明します。モデルがこの Agent を選ぶかどうかに影響します。

```typescript theme={null}
description: 'Runs project tests, analyzes failing output, and suggests fixes.'
```

トリガーとなるシナリオを明確に書くことを推奨します。`Helpful assistant` のような広すぎる説明は避けてください。

<div id="prompt" />

#### `prompt`

Agent のシステムプロンプトです。役割、制約、出力形式を定義します。

```typescript theme={null}
prompt: `You are a security reviewer.
Check for authentication bypass, authorization bugs, injection risks, and secret leaks.
Return findings sorted by severity.`
```

<div id="tools" />

#### `tools`

Agent が使用できるツールのホワイトリストです。設定すると、Agent は列挙されたツールだけを使用できます。

```typescript theme={null}
tools: ['Read', 'Grep', 'Glob']
```

`tools` を省略すると、サブエージェントのデフォルトツール表が使われます。サブエージェントのツール表は、メインセッションの `allowedTools` による絞り込みを継承しません。

<div id="disallowedtools" />

#### `disallowedTools`

Agent のツール集合から指定ツールを除外します。

```typescript theme={null}
disallowedTools: ['Bash', 'Write']
```

`disallowedTools` を省略しても、サブエージェントはメインセッションの `disallowedTools` による絞り込みを継承しません。最終的なツール集合を明確に把握している場合を除き、通常は `tools` と `disallowedTools` を同時に設定しないでください。

<div id="model" />

#### `model`

Agent に使用するモデルを指定します。省略時はセッションのデフォルトモデルを使います。対応するモデル階層は次の通りです。

| 値             | 階層          | 説明                         | 適した用途                     | Credit 消費 |
| ------------- | ----------- | -------------------------- | ------------------------- | --------- |
| `auto`        | スマートルーティング  | 能力とコストのバランスを取り、最適なモデルを自動選択 | 大半の日常開発作業。デフォルト推奨         | \~1.0x    |
| `ultimate`    | Ultimate    | エキスパート級の深い推論と思考能力          | 複雑なシステム設計、高難度の問題分析        | \~1.6x    |
| `performance` | Performance | 高度な推論能力と高品質な出力             | 中核機能実装、アーキテクチャ設計、リファクタリング | \~1.1x    |
| `efficient`   | Efficient   | 標準推論能力と高いコスト効率             | 基本的なコード生成、単体テスト、日常 Q\&A   | \~0.3x    |
| `lite`        | Lite        | 基本推論能力。無料利用                | クイック検証、単純なロジック、短い質問       | 0x        |

Agent は次の特殊形式もサポートします。

| 値         | 説明                                    |
| --------- | ------------------------------------- |
| `inherit` | メインセッションのモデルを継承                       |
| 完全なモデル ID | 現在の CLI / backend がサポートするモデル ID を直接指定 |

<div id="mcpservers" />

#### `mcpServers`

この Agent が利用できる MCP server を制限または追加します。

```typescript theme={null}
type AgentMcpServerSpec =
  | string
  | Record<string, McpServerConfig>;
```

文字列形式は、セッションで既に設定されている MCP server 名を参照します。オブジェクト形式は、その Agent 専用の MCP server を設定します。MCP server 設定構造は [SDK References - McpServerConfig](#mcpserverconfig) を参照してください。

<div id="skills" />

#### `skills`

Agent コンテキストにプリロードする skill 名の一覧です。通常の skill 名とプラグイン修飾名の両方をサポートします。

```typescript theme={null}
skills: ['review', 'sdk-test-plugin:sdk-echo']
```

セッションレベルの skill 動作は [Skills](/ja/cli/sdk/skills) を参照してください。

<div id="initialprompt" />

#### `initialPrompt`

この Agent が `options.agent` によってメインセッション Agent になったとき、最初のユーザー入力として自動送信されます。

```typescript theme={null}
initialPrompt: 'Start by scanning authentication and session management code.'
```

このフィールドはメインセッション Agent にのみ有効です。`Agent` ツール経由でサブエージェントとして呼ばれる場合は無視されます。

<div id="maxturns" />

#### `maxTurns`

Agent の最大 API ターン数を制限します。コスト、実行時間、ループリスクを制御するのに適しています。

```typescript theme={null}
maxTurns: 6
```

<div id="effort" />

#### `effort`

```typescript theme={null}
type EffortLevel = 'low' | 'medium' | 'high' | 'max';
```

Agent の推論努力レベルを制御します。より高い `effort` は、複雑なレビュー、アーキテクチャ分析、高リスク変更に適していますが、レイテンシと token 消費が増えます。

<div id="permissionmode" />

#### `permissionMode`

この Agent 内部のツール実行に対する権限モードを制御します。セッションレベルの `permissionMode` と同じ意味体系を使いますが、作用範囲はこの Agent に限定されます。セッションレベルの権限チェーン、`allowedTools` / `disallowedTools` / `canUseTool` の優先順位と例は [権限制御](/ja/cli/sdk/permissions#デフォルトポリシーの制御permissionmode) を参照してください。

```typescript theme={null}
type PermissionMode =
  | 'default'
  | 'acceptEdits'
  | 'bypassPermissions'
  | 'yolo'
  | 'plan'
  | 'dontAsk'
  | 'auto';
```

| 値                     | 意味                                                               | 適した用途                               |
| --------------------- | ---------------------------------------------------------------- | ----------------------------------- |
| `'default'`           | 標準権限動作。ツール呼び出しはツール集合、allow / deny ルール、ランタイム承認、CLI デフォルトポリシーを通ります | 大半の対話型サブエージェント                      |
| `'acceptEdits'`       | ファイル編集系操作を自動承認します。その他の機密操作は通常の権限フローに従います                         | ワークスペースファイルの変更を許可したサブエージェント         |
| `'bypassPermissions'` | 権限チェックをスキップします。高リスクモードで、通常は信頼済み自動化やテスト環境に限定します                   | 制御された CI、一時検証、一回限りの自動化              |
| `'yolo'`              | `'bypassPermissions'` の互換エイリアス。同様に権限チェックをスキップします                 | 旧設定との互換。新規コードでの優先使用は非推奨             |
| `'plan'`              | 計画モード。まず実行計画を出す用途に適し、デフォルトでは実変更を行いません                            | 計画、設計、レビュー、サブエージェントにファイルを変更させたくない場合 |
| `'dontAsk'`           | 対話確認を行いません。事前承認されていない、またはルールで許可されていない操作は拒否されます                   | 非対話環境、または確認ではなく失敗させたいワークフロー         |
| `'auto'`              | ランタイム能力が allow / deny を自動判断します。安全なワークスペース内ファイル編集は自動許可される場合があります  | 確認の中断を減らしつつランタイム判断を残したい場合           |

権限の意味は [権限制御](/ja/cli/sdk/permissions) を参照してください。

<div id="agentinfo" />

### `AgentInfo`

`q.supportedAgents()` が返す Agent の概要です。

```typescript theme={null}
type AgentInfo = {
  name: string;
  description: string;
  model?: string;
};
```

| フィールド         | 型                     | 説明                                                |
| ------------- | --------------------- | ------------------------------------------------- |
| `name`        | `string`              | Agent 名                                           |
| `description` | `string`              | Agent の用途説明                                       |
| `model`       | `string \| undefined` | Agent のモデル上書き。未設定または `model: 'inherit'` の場合は通常空です |

```typescript theme={null}
const q = query({
  prompt: 'List agents.',
  options: {
    agents: {
      reviewer: {
        description: 'Reviews code quality.',
        prompt: 'Review code and report findings.',
      },
    },
  },
});

const agents = await q.supportedAgents();
```

返却リストには `options.agents` で登録した Agent が含まれるほか、現在の CLI が検出した組み込み、プロジェクト、ユーザー、プラグイン Agent が含まれる場合があります。実際に利用できる項目は qodercli のバージョンと現在の設定に依存します。

<div id="コンテキストと呼び出し境界" />

### コンテキストと呼び出し境界

* サブエージェントは独立したコンテキストを使用し、親セッションの完全な履歴を受け取りません。
* 親セッションからサブエージェントへ渡される主な情報は、`Agent` ツール呼び出し時に渡すタスク prompt です。
* サブエージェントの中間ツール結果は親セッションに直接入りません。親セッションが受け取るのはサブエージェントの最終応答です。
* サブエージェントはさらに自分のサブエージェントを生成できないため、サブエージェントの `tools` に `Agent` を入れないでください。
* `initialPrompt` は `options.agent` で指定したメインセッション Agent にのみ有効です。

***

<div id="model-policy" />

### Model Policy

`query()` の動的モデル選択能力。二つのモードがあります：固定モデルモード（`resolveModel` を渡さず、`options.model` またはバックエンドのデフォルトを使用）と動的コールバックモード（`resolveModel` を渡し、LLM 呼び出しの都度コールバックがモデルを決定）。詳細な概念・トリガー・エラー処理は [Model Policy](/ja/cli/sdk/model-policy) を参照。

<div id="optionsresolvemodel" />

#### `options.resolveModel`

**型:** [`ModelPolicyProvider`](#modelpolicyprovider)

動的コールバックモードのエントリポイント。渡した瞬間にこのモードに切り替わり、SDK は LLM リクエスト前に毎回コールバックを呼んでモデルを取得します。コールバックが返す `model` がそのリクエストの最終モデルであり、**自動フォールバックはありません**。

<div id="optionsresolvemodeltimeoutms" />

#### `options.resolveModelTimeoutMs`

**型:** `number`、デフォルト `500`

コールバックのタイムアウト（ミリ秒）。タイムアウトすると [`ModelPolicyTimeoutError`](#modelpolicytimeouterror) がスローされ、クエリは失敗します（フォールバックなし）。`resolveModel` を渡したときのみ有効。

<div id="modelpolicyprovider" />

### `ModelPolicyProvider`

コールバック関数のシグネチャ。同期・非同期どちらでも構いません。

```typescript theme={null}
type ModelPolicyProvider = (
  context: ModelPolicyContext,
) => ModelPolicyResult | Promise<ModelPolicyResult>;
```

発火シナリオは [`QoderModelPurpose`](#qodermodelpurpose) で区別されます：

| シナリオ         | `purpose`     | 説明                                                                |
| ------------ | ------------- | ----------------------------------------------------------------- |
| メイン会話        | `'main'`      | 各ターン / ツール間で再呼び出され、1 セッションで複数回発火する可能性あり                           |
| サブエージェント     | `'subagent'`  | サブエージェントは同じプロバイダを共有                                               |
| WebFetch ツール | `'web_fetch'` | WebFetch がコンテンツ取得後に二次 LLM 呼び出しで要約                                 |
| ImageGen ツール | `'image_gen'` | 画像生成モデル選択用                                                        |
| コンテキスト圧縮     | `'compact'`   | 圧縮開始前にコールバックへ圧縮用モデルを問い合わせ                                         |
| BYOK         | 任意            | `model` に [`CustomModel`](#custommodel) オブジェクトを渡してサードパーティ LLM 経路へ |

動作のポイント：

* 同じセッション内で複数回発火します（各ターン / ツール / サブタスク前に再度問い合わせ）。
* コールバックが返す `model` がそのリクエストの最終モデルであり、SDK は再検証しません。
* 例外スローや空 `model` はクエリを直接失敗させます。詳細は [Model Policy — エラー処理](/ja/cli/sdk/model-policy#エラー処理) を参照。

<div id="modelpolicycontext" />

### `ModelPolicyContext`

コールバックが毎回受け取るコンテキスト。

```typescript theme={null}
interface ModelPolicyContext {
  purpose: QoderModelPurpose;
  sessionId: string;
  availableModels: ModelInfo[];
}
```

| フィールド             | 型                                         | 必須 | 説明                                                              |
| ----------------- | ----------------------------------------- | -- | --------------------------------------------------------------- |
| `purpose`         | [`QoderModelPurpose`](#qodermodelpurpose) | はい | 当該 LLM 呼び出しの用途                                                  |
| `sessionId`       | `string`                                  | はい | 現在のセッション ID。同じセッション内の複数回コールバックで同じ値を受け取るため、キャッシュ / テレメトリキーとして使える |
| `availableModels` | [`ModelInfo`](#modelinfo)`[]`             | はい | 現在のアカウントで利用可能なモデル一覧（CLI が `get_model_policy` リクエストごとに同梱）        |

<div id="qodermodelpurpose" />

### `QoderModelPurpose`

```typescript theme={null}
type QoderModelPurpose =
  | 'main'
  | 'subagent'
  | 'web_fetch'
  | 'image_gen'
  | 'compact';
```

| 値             | 発火シナリオ                      |
| ------------- | --------------------------- |
| `'main'`      | メイン会話の LLM 呼び出し             |
| `'subagent'`  | サブエージェント呼び出し                |
| `'web_fetch'` | WebFetch ツールが起こす二次 LLM 呼び出し |
| `'image_gen'` | ImageGen ツールが起こす画像生成呼び出し    |
| `'compact'`   | コンテキスト圧縮 / 要約               |

<div id="modelpolicyresult" />

### `ModelPolicyResult`

コールバックの戻り値。

```typescript theme={null}
interface ModelPolicyResult {
  model: string | (CustomModel & { model: string });
  parameters?: Record<string, unknown>;
}
```

| フィールド        | 型                                                                 | 必須  | 説明                                           |
| ------------ | ----------------------------------------------------------------- | --- | -------------------------------------------- |
| `model`      | `string \| (`[`CustomModel`](#custommodel)` & { model: string })` | はい  | 文字列: モデル識別子 / オブジェクト: BYOK 認証情報 + モデル識別子     |
| `parameters` | `Record<string, unknown>`                                         | いいえ | このリクエストのモデルパラメータ上書き。SDK 制御レイヤーのキーは camelCase |

サポートされる `parameters` キー：

| キー                | 型        | 説明                                                                                                                                                                     |
| ----------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `contextWindow`   | `number` | この LLM リクエストで使うコンテキストウィンドウの token 数。選択したモデルがサポートする値を指定します。通常は [`ModelInfo.context_config`](#modelcontextconfig) から取得します                                                |
| `reasoningEffort` | `string` | この LLM リクエストで使う思考 / 推論の深さ。選択したモデルがサポートするレベルを指定します。通常は [`ModelInfo.thinking_config`](#modelthinkingconfig) から取得します。一般的な値は `none`、`low`、`medium`、`high`、`xhigh`、`max` です |

`model` の形式：

* **文字列** — バックエンドが対応する任意のモデル ID（`auto` / `performance` / `glm51` など）。有効値は [`q.getAvailableModels()`](#qgetavailablemodels) が実時間で返します。**空文字不可**で、空だとクエリが失敗します。
* **`CustomModel` オブジェクト**（BYOK） — SDK はオブジェクトの `model` フィールドを抽出してこの呼び出しのモデル識別子として扱い、それ以外のフィールドは認証情報として CLI に転送し、サードパーティ LLM へルーティングします。

<div id="custommodel" />

### `CustomModel`

BYOK 認証情報。`resolveModel` コールバック内で `model` フィールドにこのオブジェクトを直接設定すると、その LLM リクエストはサードパーティプロバイダへルーティングされます。

```typescript theme={null}
interface CustomModel {
  provider: string;
  model: string;
  api_key: string;
  style?: string;
}
```

| フィールド      | 型        | 必須  | 説明                                                             |
| ---------- | -------- | --- | -------------------------------------------------------------- |
| `provider` | `string` | はい  | プロバイダ識別子。[`BYOKProviderInfo.key`](#byokproviderinfo) と一致する必要あり |
| `model`    | `string` | はい  | モデル識別子。SDK がこの呼び出しのモデル ID として抽出                                |
| `api_key`  | `string` | はい  | ユーザーが提供する API Key                                              |
| `style`    | `string` | いいえ | 上流プロトコル形式。`"openai"` / `"anthropic"` など。デフォルト `"openai"`       |

注意点：

* `provider` はカタログの `key` と一致しなければバックエンド認証に失敗します。
* `api_key` が誤っていると認証失敗としてクエリが直接失敗します（動的コールバックモードはフォールバックしません）。
* BYOK 呼び出しはプラットフォーム上で `total_cost_usd` が 0 として計上され、トークン使用量は実際の値で報告され、プロバイダ側で課金されます。

<div id="byok-カタログ型" />

### BYOK カタログ型

[`q.listByokProviders()`](#qlistbyokproviders) が返す provider/model カタログ。

```typescript theme={null}
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;
}
```

<div id="byokproviderinfo" />

#### `BYOKProviderInfo`

| フィールド          | 型                     | 説明                                          |
| -------------- | --------------------- | ------------------------------------------- |
| `key`          | `string`              | プロバイダ識別子。BYOK 時は `CustomModel.provider` に設定 |
| `display_name` | `string`              | 表示名                                         |
| `api_key_url`  | `string`              | ユーザーに API Key の取得先を案内する URL                 |
| `types`        | `BYOKModelTypeInfo[]` | このプロバイダ配下のモデルグループ                           |

<div id="byokmodeltypeinfo" />

#### `BYOKModelTypeInfo`

| フィールド          | 型                     | 説明                               |
| -------------- | --------------------- | -------------------------------- |
| `key`          | `string \| undefined` | グループ識別子。よく見る値：`cp` / `tp` / `pg` |
| `display_name` | `string`              | グループ表示名                          |
| `models`       | `BYOKModelInfo[]`     | グループ配下のモデル                       |

<div id="byokmodelinfo" />

#### `BYOKModelInfo`

| フィールド              | 型         | 説明                             |
| ------------------ | --------- | ------------------------------ |
| `key`              | `string`  | モデル ID。`CustomModel.model` に設定 |
| `display_name`     | `string`  | 表示名                            |
| `is_vl`            | `boolean` | ビジョン / マルチモーダル入力の対応可否          |
| `is_reasoning`     | `boolean` | 推論型モデルかどうか                     |
| `format`           | `string`  | 上流プロトコル形式（`openai` など）         |
| `max_input_tokens` | `number`  | 最大入力トークン数                      |

<div id="modelinfo" />

### `ModelInfo`

[`q.getAvailableModels()`](#qgetavailablemodels) が返す利用可能モデルのサマリ。[`ModelPolicyContext.availableModels`](#modelpolicycontext) の要素型としても使われます。

```typescript theme={null}
interface ModelInfo {
  value: string;
  displayName: string;
  description: string;
  isEnabled: boolean;
  isNew?: boolean;
  isFree?: boolean;
  priceFactor?: number;
  context_config?: ModelContextConfig;
  thinking_config?: ModelThinkingConfig;
  promotion?: ModelPromotion;
  serverModel?: ServerModelJson;
}
```

| フィールド             | 型                                                            | 説明                                                                                            |
| ----------------- | ------------------------------------------------------------ | --------------------------------------------------------------------------------------------- |
| `value`           | `string`                                                     | モデル識別子。[`ModelPolicyResult.model`](#modelpolicyresult) や [`q.setModel()`](#qsetmodel) の引数に使用可 |
| `displayName`     | `string`                                                     | 表示名                                                                                           |
| `description`     | `string`                                                     | モデル説明テキスト                                                                                     |
| `isEnabled`       | `boolean`                                                    | 現在利用可能かどうか                                                                                    |
| `isNew`           | `boolean \| undefined`                                       | 新しく公開されたモデルかどうか                                                                               |
| `isFree`          | `boolean \| undefined`                                       | 無料モデルかどうか                                                                                     |
| `priceFactor`     | `number \| undefined`                                        | 価格係数                                                                                          |
| `context_config`  | [`ModelContextConfig`](#modelcontextconfig) `\| undefined`   | コンテキストウィンドウ設定（階層ラベル -> token 数）                                                               |
| `thinking_config` | [`ModelThinkingConfig`](#modelthinkingconfig) `\| undefined` | 思考（推論）設定                                                                                      |
| `promotion`       | [`ModelPromotion`](#modelpromotion) `\| undefined`           | モデル一覧 API からのプロモーション/割引情報。未指定ならプロモーションなし                                                      |
| `serverModel`     | [`ServerModelJson`](#servermodeljson) `\| undefined`         | CLI がモデル一覧 API から原文のまま転送するモデルエントリ                                                             |

<div id="modelcontextconfig" />

### `ModelContextConfig`

`"200K"` や `"1M"` などの階層ラベルで索引されるコンテキストウィンドウ設定。

```typescript theme={null}
type ModelContextConfig = Record<string, ModelContextWindowEntry>;

interface ModelContextWindowEntry {
  token_count: number;
  is_default?: boolean;
}
```

| フィールド         | 型                      | 説明            |
| ------------- | ---------------------- | ------------- |
| `token_count` | `number`               | この階層の token 数 |
| `is_default`  | `boolean \| undefined` | デフォルト階層かどうか   |

<div id="modelthinkingconfig" />

### `ModelThinkingConfig`

モデルの思考（推論）設定。

```typescript theme={null}
interface ModelThinkingConfig {
  disabled?: ModelThinkingDisabled;
  enabled?: ModelThinkingEnabled;
}

interface ModelThinkingDisabled {
  description?: string;
}

interface ModelThinkingEnabled {
  description?: string;
  efforts?: Record<string, ModelEffortEntry>;
  is_default?: boolean;
}

interface ModelEffortEntry {
  description?: string;
  is_default?: boolean;
}
```

| フィールド             | 型                                               | 説明                                        |
| ----------------- | ----------------------------------------------- | ----------------------------------------- |
| `disabled`        | `ModelThinkingDisabled \| undefined`            | 思考を無効にした場合の設定                             |
| `enabled`         | `ModelThinkingEnabled \| undefined`             | 思考を有効にした場合の設定。effort レベルを含む               |
| `enabled.efforts` | `Record<string, ModelEffortEntry> \| undefined` | `"low"` / `"high"` など各 effort の説明とデフォルト指定 |

<div id="modelpromotion" />

### `ModelPromotion`

モデル一覧 API から転送されるプロモーション/割引情報。ネストしたフィールド名はサーバーの snake\_case 形式のままです。

```typescript theme={null}
type LocalizedModelText = {
  en?: string;
  zh?: string;
} & Record<string, string | undefined>;

interface ModelPromotion {
  active: boolean;
  badge?: LocalizedModelText;
  description?: LocalizedModelText;
  discount_factor?: number;
  before_promotion_price_factor?: number;
  timezone?: string;
  rule_id?: string;
  window_start?: string;
  window_end?: string;
}
```

| フィールド                           | 型                                 | 説明                           |
| ------------------------------- | --------------------------------- | ---------------------------- |
| `active`                        | `boolean`                         | このモデルのプロモーションが現在有効かどうか       |
| `badge`                         | `LocalizedModelText \| undefined` | 短いローカライズ済みラベル                |
| `description`                   | `LocalizedModelText \| undefined` | より詳しいローカライズ済み説明              |
| `discount_factor`               | `number \| undefined`             | プロモーション中の割引後価格係数             |
| `before_promotion_price_factor` | `number \| undefined`             | プロモーション前の元の価格係数              |
| `timezone`                      | `string \| undefined`             | プロモーション時間帯の判定に使う IANA タイムゾーン |
| `rule_id`                       | `string \| undefined`             | サーバールール識別子                   |
| `window_start`                  | `string \| undefined`             | 毎日の開始時刻。`HH:mm` 形式           |
| `window_end`                    | `string \| undefined`             | 毎日の終了時刻。`HH:mm` 形式           |

<div id="servermodeljson" />

### `ServerModelJson`

モデル一覧 API からの JSON 互換の原文モデルエントリ。サーバーに新しいフィールドが追加され、まだ `ModelInfo` の一級フィールドになっていない場合に参照できます。

```typescript theme={null}
type ServerModelJson = Record<string, ServerModelJsonValue>;
```

<div id="usageinfo" />

### `UsageInfo`

[`q.getUsageInfo()`](#qgetusageinfo) が返すアカウントのクォータと使用量のスナップショット。

```typescript theme={null}
interface UsageInfo {
  userId?: string;
  userType?: string;
  totalUsagePercentage?: number;
  isHighestTier?: boolean;
  expiresAt?: number;
  upgradeUrl?: string;
  userQuota?: UsageQuotaBucket;
  addOnQuota?: UsageAddOnQuotaBucket;
  isQuotaExceeded?: boolean;
  isPlanQuotaProrated?: boolean;
  orgResourcePackage?: UsageOrgResourcePackage;
}

interface UsageQuotaBucket {
  total?: number;
  used?: number;
  remaining?: number;
  percentage?: number;
  unit?: string;
}

interface UsageAddOnQuotaBucket extends UsageQuotaBucket {
  detailUrl?: string;
}

interface UsageOrgResourcePackage {
  used?: number;
  cap?: number;
  remaining?: number;
  percentage?: number;
  available?: boolean;
  unit?: string;
}
```

| フィールド                  | 型                                      | 説明                                                           |
| ---------------------- | -------------------------------------- | ------------------------------------------------------------ |
| `userId`               | `string \| undefined`                  | アカウント ID                                                     |
| `userType`             | `string \| undefined`                  | プラン区分（`free`、`pro`、`teams` など）                               |
| `totalUsagePercentage` | `number \| undefined`                  | 全クォータの全体使用率、`0`–`100`                                        |
| `isHighestTier`        | `boolean \| undefined`                 | すでに最上位プランかどうか                                                |
| `expiresAt`            | `number \| undefined`                  | 現在のプラン/クォータ有効期限、Unix ミリ秒                                     |
| `upgradeUrl`           | `string \| undefined`                  | アップグレードページ URL（アップグレード可能な場合）                                 |
| `userQuota`            | `UsageQuotaBucket \| undefined`        | プラン内蔵クォータ                                                    |
| `addOnQuota`           | `UsageAddOnQuotaBucket \| undefined`   | アカウントにアドオンクォータがある場合に返る購入済みアドオンクォータ（`detailUrl` は使用量ページへのリンク） |
| `isQuotaExceeded`      | `boolean \| undefined`                 | 利用可能なクォータをすべて使い切ったかどうか                                       |
| `isPlanQuotaProrated`  | `boolean \| undefined`                 | 当期のプランクォータが日割り計算されているか                                       |
| `orgResourcePackage`   | `UsageOrgResourcePackage \| undefined` | 組織共有リソースパッケージ（`available` は利用可否）                             |

各バケットは `unit`（通常は `credits`）単位で、`total`（組織パッケージは `cap`）に対する `used` / `remaining` / `percentage` を報告します。
欠落したフィールド、または実行時型が想定と異なるフィールドは、返却オブジェクトから省略されます。

<div id="modelpolicytimeouterror" />

### `ModelPolicyTimeoutError`

```typescript theme={null}
class ModelPolicyTimeoutError extends Error {}
```

`resolveModel` コールバックが `options.resolveModelTimeoutMs` を超えても返さないときに SDK がスローします。クエリは直接失敗し、フォールバックはしません。

<div id="qsetmodel" />

### `q.setModel()`

```typescript theme={null}
setModel(model?: string): Promise<void>;
```

固定モデルモードで実行中にモデルを切り替えます。次の LLM 呼び出しから有効。固定モデルモードでのみ有効で、動的コールバックモードでは呼んでもコールバック結果を上書きしません。有効なモデル ID は [`ModelInfo.value`](#modelinfo) を参照。

<div id="qgetavailablemodels" />

### `q.getAvailableModels()`

```typescript theme={null}
getAvailableModels(): Promise<ModelInfo[]>;
```

現在のアカウントで利用可能なモデル一覧をリアルタイムに取得。常に最新結果を返し、キャッシュしません；一時的に取得不能なときは空配列を返し（例外はスローしません）。動的コールバックモードでは [`ModelPolicyContext.availableModels`](#modelpolicycontext) がすでに同等のリストを実時間で運ぶため、明示的に呼ぶ必要はありません。

<div id="qlistbyokproviders" />

### `q.listByokProviders()`

```typescript theme={null}
listByokProviders(): Promise<BYOKProviderInfo[] | null>;
```

現在のアカウントで利用可能な BYOK provider/model カタログを配列で返します：

* `null` を返す場合：CLI がこの API をサポートしていない（グレースフルフォールバック、例外なし）。
* 配列を返す場合（空の場合あり）：現在のアカウントで利用可能な provider リスト（空配列はアカウントが BYOK 未開通）。

フィールドの意味は [BYOK カタログ型](#byok-カタログ型) を参照。

<div id="qgetusageinfo" />

### `q.getUsageInfo()`

```typescript theme={null}
getUsageInfo(): Promise<UsageInfo | null>;
```

実行中の CLI から現在のアカウントのクォータと使用量情報をリアルタイムに取得します。

* `null` を返す場合：CLI が未認証、旧バージョンの CLI がこの API をサポートしていない、または CLI がオブジェクトを返さない場合（グレースフルフォールバック、例外なし）。
* [`UsageInfo`](#usageinfo) オブジェクトを返す場合：実行時型が正しい既知のアカウントクォータ/使用量フィールド。欠落または型が不正なフィールドは省略されます。

```typescript theme={null}
import { query, qodercliAuth } from '@qoder-ai/qoder-agent-sdk';

const q = query({
  prompt: userMessages(),
  options: { auth: qodercliAuth() },
});

const usage = await q.getUsageInfo();
if (usage) {
  console.log(`プラン：${usage.userType}、使用 ${usage.totalUsagePercentage}%`);
  console.log(`プランクォータ残り：${usage.userQuota?.remaining}/${usage.userQuota?.total} ${usage.userQuota?.unit}`);
}
```

戻り値の型は [`UsageInfo`](#usageinfo) を参照。

***

<div id="canusetool" />

### `CanUseTool`

ホストがカスタムするツール権限承認コールバックです。

```typescript theme={null}
type CanUseTool = (
  toolName: string,
  input: Record<string, unknown>,
  options: CanUseToolOptions,
) => Promise<PermissionResult>;
```

<div id="canusetooloptions" />

#### `CanUseToolOptions`

```typescript theme={null}
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` フィールド                         | 型                              | 説明                           |
| :-------------------------------------- | :----------------------------- | :--------------------------- |
| `signal`                                | `AbortSignal`                  | キャンセル時に abort される            |
| `suggestions`                           | `PermissionUpdate[]`           | CLI が提案する権限更新                |
| `blockedPath`                           | `string`                       | 承認をトリガーしたファイルパス（ファイル関連シーンのみ） |
| `decisionReason`                        | `string`                       | CLI が提供する人間が読める承認理由          |
| `decisionReasonType`                    | `PermissionDecisionReasonType` | 権限理由の分類                      |
| `classifierApprovable`                  | `boolean`                      | 現在の呼び出しがランタイム分類器で自動承認可能かどうか  |
| `title` / `displayName` / `description` | `string`                       | ランタイムで生成された人間が読める承認テキスト      |
| `toolUseID`                             | `string`                       | 今回のツール呼び出し ID                |
| `agentID`                               | `string`                       | 呼び出しを発行したサブエージェント ID         |
| `exitPlanMode`                          | `ExitPlanModeApprovalDetails`  | 計画モードを終了するときの承認詳細            |

完全な使用法と例は [権限制御](/ja/cli/sdk/permissions#ランタイム承認canusetool) を参照してください。

<div id="permissionmode" />

### `PermissionMode`

```typescript theme={null}
type PermissionMode =
  | 'default'
  | 'acceptEdits'
  | 'bypassPermissions'
  | 'yolo'
  | 'plan'
  | 'dontAsk'
  | 'auto';
```

| 値                     | 意味                                                                           | 適した用途                       |
| :-------------------- | :--------------------------------------------------------------------------- | :-------------------------- |
| `'default'`           | 標準権限動作。ツール呼び出しは `tools`、allow / deny ルール、動的承認、ランタイムポリシーで処理されます               | 大半の対話型セッション                 |
| `'acceptEdits'`       | ファイル編集系操作を自動承認します。その他の機密操作は通常の権限フローに従います                                     | ワークスペースファイルの変更を許可したセッション    |
| `'bypassPermissions'` | 権限チェックをスキップします。`allowDangerouslySkipPermissions: true` も必要です                 | 信頼済み自動化またはテスト環境             |
| `'yolo'`              | `'bypassPermissions'` の互換エイリアス。`allowDangerouslySkipPermissions: true` も必要です | 旧設定との互換。新規コードでの優先使用は非推奨     |
| `'plan'`              | 計画モード。まず実行計画を出す用途に適し、デフォルトでは実変更を行いません                                        | 計画、設計、レビュー                  |
| `'dontAsk'`           | 対話確認を行いません。事前承認されていない、またはルールで許可されていない操作は拒否されます                               | 非対話環境、または確認ではなく失敗させたいワークフロー |
| `'auto'`              | ランタイム能力が allow / deny を自動判断します。安全なワークスペース内ファイル編集は自動許可される場合があります              | 確認の中断を減らしつつランタイム判断を残したい場合   |

詳細は [権限制御](/ja/cli/sdk/permissions#デフォルトポリシーの制御permissionmode) を参照してください。

<div id="permissionresult" />

### `PermissionResult`

`CanUseTool` の戻り値です。

```typescript theme={null}
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` を変更すると、ツールが実際に受け取る入力パラメータが置き換わります。`deny.interrupt: true` は拒否と同時にエージェントを中断します。

<div id="mcpserverconfig" />

### `McpServerConfig`

MCP サーバー設定。`Options.mcpServers` に渡します。

```typescript theme={null}
type McpServerConfig =
  | McpStdioServerConfig
  | McpSSEServerConfig
  | McpHttpServerConfig
  | McpSdkServerConfigWithInstance;
```

<div id="mcpstdioserverconfig" />

#### `McpStdioServerConfig`

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

<div id="mcpsseserverconfig" />

#### `McpSSEServerConfig`

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

<div id="mcphttpserverconfig" />

#### `McpHttpServerConfig`

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

<div id="mcpsdkserverconfigwithinstance" />

#### `McpSdkServerConfigWithInstance`

```typescript theme={null}
type McpSdkServerConfigWithInstance = {
  type: 'sdk';
  name: string;
  instance: McpServer;
};
```

`createSdkMcpServer()` ファクトリから返されます。[MCP - In-Process Server](/ja/cli/sdk/mcp#in-process-server推奨) を参照。

<div id="sdkpluginconfig" />

### `SdkPluginConfig`

ローカルプラグインの読み込みです。

```typescript theme={null}
type SdkPluginConfig = {
  type: 'local';
  path: string;
};
```

| フィールド  | 型         | 説明                      |
| :----- | :-------- | :---------------------- |
| `type` | `'local'` | 現在は local のみサポート        |
| `path` | `string`  | プラグインディレクトリの絶対パスまたは相対パス |

<div id="cloudagentoptions" />

### `CloudAgentOptions`

`Options.experimentalCloudAgent` の型です。Cloud ランタイムの agent / session 参照を構成します。詳しい使い方は [Cloud Agent](/ja/cli/sdk/cloud-agent) を参照してください。

```typescript theme={null}
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;
};
```

| フィールド                         | 型                                                       | 説明                                          |
| :---------------------------- | :------------------------------------------------------ | :------------------------------------------ |
| `agent.id`                    | `string`                                                | 既存の Cloud Agent を再利用。`agent.create` と相互排他   |
| `agent.create`                | [`AgentCreateParams`](#agentcreateparams)               | 新しい Cloud Agent を作成。`agent.id` と相互排他        |
| `session.id`                  | `string`                                                | 既存の Cloud session を再利用。`agent` を併せて渡してはならない |
| `session.create`              | [`CloudSessionCreateParams`](#cloudsessioncreateparams) | 新しい Cloud session を作成。`environment_id` は必須  |
| `stream.afterId`              | `string`                                                | SSE replay の起点となるイベント ID                    |
| `stream.deltaFlushIntervalMs` | `number`                                                | デルタ内容のマージ / フラッシュ間隔（ミリ秒）                    |

<div id="agentcreateparams" />

### `AgentCreateParams`

新しい Cloud Agent を作成するためのリクエストボディです。Qoder Cloud OpenAPI の agent create フィールドに対応します。

```typescript theme={null}
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>;
};
```

| フィールド         | 型                        | 説明                                                                                 |
| :------------ | :----------------------- | :--------------------------------------------------------------------------------- |
| `model`       | `string`                 | モデル識別子。使用可能な値：`'auto'` / `'ultimate'` / `'performance'` / `'efficient'` / `'lite'` |
| `name`        | `string`                 | 人間可読の agent 名                                                                      |
| `description` | `string \| null`         | 説明                                                                                 |
| `system`      | `string \| null`         | system prompt                                                                      |
| `tools`       | 上記参照                     | ビルトインツールセット。`enabled_tools` で許可リストを指定                                              |
| `mcp_servers` | 上記参照                     | URL 形式の MCP server 接続                                                              |
| `skills`      | 上記参照                     | ユーザー定義のカスタム Skill                                                                  |
| `metadata`    | `Record<string, string>` | 任意のキー / 値メタデータ                                                                     |

<div id="cloudsessioncreateparams" />

### `CloudSessionCreateParams`

新しい Cloud session を作成するためのリクエストボディです。

```typescript theme={null}
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>;
};
```

| フィールド              | 型                | 説明                                     |
| :----------------- | :--------------- | :------------------------------------- |
| `environment_id`   | `string`         | コンテナ環境 ID。**必須**                       |
| `resources`        | 上記参照             | session コンテナにマウントするリソース（現状は `file` のみ） |
| `title`            | `string \| null` | セッションタイトル                              |
| `vault_ids`        | `string[]`       | 認証情報の vault ID                         |
| `memory_store_ids` | `string[]`       | memory store ID                        |

<div id="sandboxsettings" />

### `SandboxSettings`

サンドボックス動作設定です。

```typescript theme={null}
type SandboxSettings = {
  enabled?: boolean;
  autoAllowBashIfSandboxed?: boolean;
  excludedCommands?: string[];
  allowUnsandboxedCommands?: boolean;
  network?: SandboxNetworkConfig;
  filesystem?: SandboxFilesystemConfig;
  ignoreViolations?: { file?: string[]; network?: string[] };
  enableWeakerNestedSandbox?: boolean;
};
```

| フィールド                      | 型                         | デフォルト       | 説明                                             |
| :------------------------- | :------------------------ | :---------- | :--------------------------------------------- |
| `enabled`                  | `boolean`                 | `false`     | サンドボックスの有効化                                    |
| `autoAllowBashIfSandboxed` | `boolean`                 | `true`      | サンドボックス有効時に bash を自動通過                         |
| `excludedCommands`         | `string[]`                | `[]`        | サンドボックスを静的にバイパスするコマンド（例: `['docker']`）         |
| `allowUnsandboxedCommands` | `boolean`                 | `true`      | モデルがサンドボックス外でコマンドを実行することを許可（`canUseTool` に落ちる） |
| `network`                  | `SandboxNetworkConfig`    | `undefined` | ネットワーク制限                                       |
| `filesystem`               | `SandboxFilesystemConfig` | `undefined` | ファイルシステム制限                                     |
| `ignoreViolations`         | `{ file?, network? }`     | `undefined` | パターンで無視する違反                                    |

<div id="sandboxnetworkconfig" />

#### `SandboxNetworkConfig`

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

<div id="sandboxfilesystemconfig" />

#### `SandboxFilesystemConfig`

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

<div id="settingsource" />

### `SettingSource`

ロードする filesystem settings を制御します。

```typescript theme={null}
type SettingSource = 'user' | 'project' | 'local';
```

| 値           | 意味                             | 場所                           |
| :---------- | :----------------------------- | :--------------------------- |
| `'user'`    | ユーザーレベルのグローバル settings         | `~/.qoder/settings.json`     |
| `'project'` | プロジェクト共有 settings（バージョン管理）     | `.qoder/settings.json`       |
| `'local'`   | プロジェクトローカル settings（gitignore） | `.qoder/settings.local.json` |

省略時は CLI デフォルトで全ソースをロード。`[]` を渡すと完全にスキップします。

<div id="toolconfig" />

### `ToolConfig`

組み込みツール動作設定です。

```typescript theme={null}
type ToolConfig = {
  askUserQuestion?: {
    previewFormat?: 'markdown' | 'html';
  };
};
```

<div id="組み込みツール一覧" />

### 組み込みツール一覧

`tools`、`allowedTools`、`disallowedTools`、`canUseTool`、hooks matcher、Agent のツールホワイトリストでは、組み込みツールは下表のランタイムツール名を使用します。

| カテゴリ          | ツール名               | 説明                |
| ------------- | ------------------ | ----------------- |
| コマンド実行        | `Bash`             | shell コマンドを実行     |
| ファイル操作        | `Read`             | ファイル内容を読む         |
| ファイル操作        | `Edit`             | 文字列一致に基づいてファイルを編集 |
| ファイル操作        | `Write`            | ファイルを作成または上書き     |
| 検索            | `Glob`             | ファイル名パターンで検索      |
| 検索            | `Grep`             | 内容の正規表現で検索        |
| ネットワーク        | `WebFetch`         | URL 内容を取得して処理     |
| ネットワーク        | `WebSearch`        | Web 検索            |
| Agent         | `Agent`            | サブエージェントを呼び出す     |
| 対話            | `AskUserQuestion`  | ユーザーに質問する         |
| Notebook      | `NotebookEdit`     | Notebook セルを編集    |
| バックグラウンドタスク   | `TaskOutput`       | バックグラウンドタスクへ出力を送る |
| バックグラウンドタスク   | `TaskStop`         | バックグラウンドタスクを停止    |
| 計画 / worktree | `ExitPlanMode`     | 計画モードを終了          |
| 計画 / worktree | `EnterWorktree`    | git worktree に入る  |
| 計画 / worktree | `ExitWorktree`     | worktree を終了      |
| 設定            | `Config`           | 設定を読み書き           |
| Todo          | `TodoWrite`        | Todo 項目を管理        |
| MCP リソース      | `ListMcpResources` | MCP resources を列挙 |
| MCP リソース      | `ReadMcpResource`  | MCP resource を読む  |
| MCP 呼び出し      | `Mcp`              | 汎用 MCP ツール呼び出し    |

カスタム MCP ツール名の形式は次の通りです。

```text theme={null}
mcp__{serverName}__{toolName}
```

<div id="tool" />

### `tool()`

型安全な SDK MCP ツール定義を作成します。

```typescript theme={null}
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>;
```

| パラメータ         | 型                                          | 必須  | 意味                                   | 現在の Qoder の挙動                                                                      |
| ------------- | ------------------------------------------ | --- | ------------------------------------ | ---------------------------------------------------------------------------------- |
| `name`        | `string`                                   | はい  | 現在の MCP server 内で一意なツール識別子           | モデルから見える完全なツール名 `mcp__{serverName}__{name}` を構成します。登録時は空文字不可                       |
| `description` | `string`                                   | はい  | モデルに見せるツール説明。いつ使うか、何をするか、何を返すかを説明します | ツール一覧へそのまま渡され、モデルが正しく呼び出すかに直接影響します。登録時は空文字不可                                       |
| `inputSchema` | `Schema extends AnyZodRawShape`            | はい  | ツール入力パラメータを定義する Zod raw shape        | SDK はこれを使って MCP input schema を生成し、handler の `args` を `InferShape<Schema>` として推論します |
| `handler`     | `(args, extra) => Promise<CallToolResult>` | はい  | ツール呼び出し時に実行される非同期関数                  | モデルがツールを呼ぶと SDK が実行します。戻り値は tool result としてモデルへ返されます                               |
| `extras`      | `ToolExtras`                               | いいえ | ツール追加メタ情報。現在は `annotations` に使用      | SDK は対応する annotations を MCP server に登録します。権限設定の代替にはなりません                           |

`tool()` 自体はツールを定義する factory 関数です。`name`、`description`、重複ツール名などの登録制約は、`createSdkMcpServer()` がツール登録時に検証します。

<div id="anyzodrawshape" />

#### `AnyZodRawShape`

```typescript theme={null}
type AnyZodRawShape = ZodRawShapeCompat;
```

`AnyZodRawShape` は Zod 3 / Zod 4 と互換です。これはフィールドオブジェクトを表し、`z.object(...)` ではありません。

<div id="infershape" />

#### `InferShape`

```typescript theme={null}
type InferShape<T extends AnyZodRawShape> = ShapeOutput<T>;
```

`InferShape` は Zod raw shape から handler の `args` 型を推論します。

<div id="sdkmcptooldefinition" />

#### `SdkMcpToolDefinition`

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

<div id="toolextras" />

#### `ToolExtras`

```typescript theme={null}
type ToolExtras = {
  annotations?: ToolAnnotations;
};
```

<div id="toolannotations" />

#### `ToolAnnotations`

```typescript theme={null}
type ToolAnnotations = {
  title?: string;
  readOnlyHint?: boolean;
  destructiveHint?: boolean;
  openWorldHint?: boolean;
};
```

| フィールド             | 型         | 任意 | 意味                             | 現在の Qoder の挙動                                                                   |
| ----------------- | --------- | -- | ------------------------------ | ------------------------------------------------------------------------------- |
| `title`           | `string`  | はい | ツールの人間向けタイトル                   | MCP メタ情報。現在は検証済み Qoder 挙動能力としては説明していません                                         |
| `readOnlyHint`    | `boolean` | はい | ツールが状態を変更しないことを示す              | 現在観測できる効果は、読み取り専用ツールが同一 batch の tool calls 内で並行実行可能になる条件を満たせることです。権限スイッチではありません |
| `destructiveHint` | `boolean` | はい | ツールが破壊的更新を行う可能性を示す             | リスクメタ情報。承認済みツールの実行を自動的に止めるものではありません                                             |
| `openWorldHint`   | `boolean` | はい | ツールが外部の open world とやり取りするかを示す | 外部やり取りのメタ情報。承認済みツールの実行を自動的に止めるものではありません                                         |

これらのフィールドはメタ情報とスケジューリングヒントであり、権限スイッチではありません。実行可否は引き続き `tools`、`allowedTools`、`disallowedTools`、`permissionMode`、`canUseTool`、hooks によって決まります。機能ドキュメントで検証済み挙動能力として扱うのは `readOnlyHint`、`destructiveHint`、`openWorldHint` です。`title` は MCP メタ情報として型リファレンスに残しています。

<div id="createsdkmcpserver" />

### `createSdkMcpServer()`

SDK と同一プロセスで動作する MCP server を作成します。

```typescript theme={null}
function createSdkMcpServer(
  options: CreateSdkMcpServerOptions,
): McpSdkServerConfigWithInstance;
```

<div id="createsdkmcpserveroptions" />

#### `CreateSdkMcpServerOptions`

```typescript theme={null}
type CreateSdkMcpServerOptions = {
  name: string;
  version?: string;
  tools?: Array<SdkMcpToolDefinition<any>>;
};
```

| フィールド     | デフォルト       | 説明                                                 |
| --------- | ----------- | -------------------------------------------------- |
| `name`    | 必須          | MCP server 名。`mcp__{serverName}__{toolName}` に入ります |
| `version` | `'1.0.0'`   | server バージョン情報                                     |
| `tools`   | `undefined` | この server に登録するツール一覧                               |

<a id="createsdkmcpserver-return-value" />

<div id="戻り値" />

#### 戻り値

`McpSdkServerConfigWithInstance` を返します。これは `options.mcpServers` の値としてそのまま渡せます。完全な MCP server 設定は [McpServerConfig](#mcpserverconfig) を参照してください。

```typescript theme={null}
type McpSdkServerConfigWithInstance = {
  type: 'sdk';
  name: string;
  instance: McpServer;
};
```

<div id="calltoolresult" />

### `CallToolResult`

ツール handler は MCP プロトコルの `CallToolResult` を返します。

```typescript theme={null}
type CallToolResult = {
  content: McpToolResultContent[];
  isError?: boolean;
  _meta?: Record<string, unknown>;
};
```

<div id="mcptoolresultcontent" />

#### `McpToolResultContent`

```typescript theme={null}
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;
      };
    };
```

| フィールド     | 説明                                |
| --------- | --------------------------------- |
| `content` | モデルへ返す content block 配列           |
| `isError` | `true` の場合、ツールが意味的に失敗したことを示します    |
| `_meta`   | ツール結果メタデータ。MCP レスポンスとともに透過的に渡されます |

<div id="組み込みツール入力出力型" />

### 組み込みツール入力出力型

SDK は型レベルで組み込みツールの入力 / 出力構造を提供します。注意: これらは TypeScript の型名です。権限設定では引き続き上記のランタイムツール名を使用します。

<div id="agentinput-agentoutput" />

#### `AgentInput` / `AgentOutput`

```typescript theme={null}
type AgentInput = {
  prompt: string;
  agent?: string;
  timeout_ms?: number;
};

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

<div id="bashinput-bashoutput" />

#### `BashInput` / `BashOutput`

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

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

<div id="filereadinput-filereadoutput" />

#### `FileReadInput` / `FileReadOutput`

ランタイムツール名は `Read` です。型名は `FileReadInput` / `FileReadOutput` のままです。

```typescript theme={null}
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;
    };
```

<div id="fileeditinput-fileeditoutput" />

#### `FileEditInput` / `FileEditOutput`

ランタイムツール名は `Edit` です。

```typescript theme={null}
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;
};
```

<div id="filewriteinput-filewriteoutput" />

#### `FileWriteInput` / `FileWriteOutput`

ランタイムツール名は `Write` です。

```typescript theme={null}
type FileWriteInput = {
  file_path: string;
  content: string;
};

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

<div id="globinput-globoutput" />

#### `GlobInput` / `GlobOutput`

```typescript theme={null}
type GlobInput = {
  pattern: string;
  path?: string;
};

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

<div id="grepinput-grepoutput" />

#### `GrepInput` / `GrepOutput`

```typescript theme={null}
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;
};
```

<div id="webfetchinput-webfetchoutput" />

#### `WebFetchInput` / `WebFetchOutput`

```typescript theme={null}
type WebFetchInput = {
  url: string;
  prompt: string;
};

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

<div id="websearchinput-websearchoutput" />

#### `WebSearchInput` / `WebSearchOutput`

```typescript theme={null}
type WebSearchInput = {
  query: string;
  allowed_domains?: string[];
  blocked_domains?: string[];
};

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

<div id="askuserquestioninput-askuserquestionoutput" />

#### `AskUserQuestionInput` / `AskUserQuestionOutput`

```typescript theme={null}
type AskUserQuestionInput = {
  question: string;
  options?: string[];
  default?: string;
};

type AskUserQuestionOutput = {
  answer: string;
};
```

<div id="notebookeditinput-notebookeditoutput" />

#### `NotebookEditInput` / `NotebookEditOutput`

```typescript theme={null}
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;
};
```

<div id="taskoutputinput" />

#### `TaskOutputInput`

```typescript theme={null}
type TaskOutputInput = {
  task_id: string;
  output: string;
};
```

<div id="taskstopinput-taskstopoutput" />

#### `TaskStopInput` / `TaskStopOutput`

```typescript theme={null}
type TaskStopInput = {
  task_id: string;
  reason?: string;
};

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

<div id="exitplanmodeinput-exitplanmodeoutput" />

#### `ExitPlanModeInput` / `ExitPlanModeOutput`

```typescript theme={null}
type ExitPlanModeInput = {
  confirm?: boolean;
};

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

<div id="configinput-configoutput" />

#### `ConfigInput` / `ConfigOutput`

```typescript theme={null}
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;
};
```

<div id="enterworktreeinput-enterworktreeoutput" />

#### `EnterWorktreeInput` / `EnterWorktreeOutput`

```typescript theme={null}
type EnterWorktreeInput = {
  name?: string;
};

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

<div id="exitworktreeinput-exitworktreeoutput" />

#### `ExitWorktreeInput` / `ExitWorktreeOutput`

```typescript theme={null}
type ExitWorktreeInput = {
  action: 'keep' | 'remove';
  discard_changes?: boolean;
};

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

<div id="todowriteinput-todowriteoutput" />

#### `TodoWriteInput` / `TodoWriteOutput`

```typescript theme={null}
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;
};
```

<div id="listmcpresourcesinput-listmcpresourcesoutput" />

#### `ListMcpResourcesInput` / `ListMcpResourcesOutput`

```typescript theme={null}
type ListMcpResourcesInput = {
  server_name: string;
};

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

<div id="readmcpresourceinput" />

#### `ReadMcpResourceInput`

```typescript theme={null}
type ReadMcpResourceInput = {
  server_name: string;
  uri: string;
};
```

<div id="mcpinput-mcpoutput" />

#### `McpInput` / `McpOutput`

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

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

<div id="toolinputschemas" />

#### `ToolInputSchemas`

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

<div id="tooloutputschemas" />

#### `ToolOutputSchemas`

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

***

<div id="hooks-リファレンス" />

## Hooks リファレンス

使用ガイドとサンプルは [Hooks](/ja/cli/sdk/hooks) を参照してください。

<div id="イベント概要" />

### イベント概要

| イベント                 | トリガー           | 制御可能な動作                |
| -------------------- | -------------- | ---------------------- |
| `PreToolUse`         | ツール呼び出し前       | インターセプト / 許可 / 入力の変更   |
| `PostToolUse`        | ツール成功後         | 監査 / コンテキスト注入 / 出力の上書き |
| `PostToolUseFailure` | ツール失敗後         | エラーハンドリング / ロギング       |
| `UserPromptSubmit`   | ユーザープロンプト送信前   | コンテキスト注入 / インターセプト     |
| `SessionStart`       | セッション開始時       | 初期化 / コンテキスト注入         |
| `SessionEnd`         | セッション終了時       | クリーンアップ / ロギング         |
| `Stop`               | AI が生成を停止した時   | 停止の防止、続行の強制            |
| `SubagentStart`      | サブエージェント開始時    | 監視 / ロギング              |
| `SubagentStop`       | サブエージェント停止時    | 監視 / ロギング              |
| `PreCompact`         | コンテキスト圧縮前      | 監視 / ロギング              |
| `PostCompact`        | コンテキスト圧縮後      | 監視 / ロギング              |
| `CwdChanged`         | 作業ディレクトリ変更時    | 監視 / ロギング              |
| `InstructionsLoaded` | 命令ファイルロード時     | 監視 / ロギング              |
| `FileChanged`        | ファイルの作成/変更/削除時 | 監視 / ロギング              |
| `PermissionRequest`  | パーミッション要求時     | パーミッション要求を自動承認 / 拒否    |

<div id="hookevent" />

### `HookEvent`

登録可能な hook イベントの共用体型です。

```typescript theme={null}
type HookEvent =
  | 'PreToolUse'
  | 'PostToolUse'
  | 'PostToolUseFailure'
  | 'UserPromptSubmit'
  | 'SessionStart'
  | 'SessionEnd'
  | 'Stop'
  | 'SubagentStart'
  | 'SubagentStop'
  | 'PreCompact'
  | 'PostCompact'
  | 'CwdChanged'
  | 'InstructionsLoaded'
  | 'FileChanged'
  | 'PermissionRequest';
```

<div id="hookcallback" />

### `HookCallback`

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

<div id="hookcallbackmatcher" />

### `HookCallbackMatcher`

```typescript theme={null}
interface HookCallbackMatcher {
  matcher?: string;
  hooks: HookCallback[];
  timeout?: number;
}
```

| フィールド     | 型                | 説明                              |
| :-------- | :--------------- | :------------------------------ |
| `matcher` | `string`         | オプションの正規表現。`tool_name` でフィルタリング |
| `hooks`   | `HookCallback[]` | マッチ時に実行されるコールバックリスト             |
| `timeout` | `number`         | オプション。タイムアウト（秒）、デフォルト 60        |

<div id="basehookinput" />

### `BaseHookInput`

すべての hook イベントで共有される入力フィールドです。

```typescript theme={null}
interface BaseHookInput {
  hook_event_name: string;
  session_id: string;
  transcript_path: string;
  cwd: string;
}
```

| フィールド             | 型        | 説明                           |
| :---------------- | :------- | :--------------------------- |
| `hook_event_name` | `string` | イベントタイプ識別子（例：`"PreToolUse"`） |
| `session_id`      | `string` | 現在のセッションの一意識別子               |
| `transcript_path` | `string` | セッション記録ファイルパス（JSONL 形式）      |
| `cwd`             | `string` | セッションの現在の作業ディレクトリ            |

<div id="hookjsonoutput" />

### `HookJSONOutput`

Hook コールバックの戻り値の型です。

```typescript theme={null}
interface HookJSONOutput {
  continue?: boolean;
  stopReason?: string;
  decision?: string;
  reason?: string;
  hookSpecificOutput?: object;
}
```

| フィールド                | 型         | デフォルト  | 説明                                                                                                                   |
| :------------------- | :-------- | :----- | :------------------------------------------------------------------------------------------------------------------- |
| `continue`           | `boolean` | `true` | `false` に設定するとセッションを終了。`PreToolUse`、`PostToolUse`、`PostToolUseFailure`、`UserPromptSubmit`、`Stop`、`SubagentStop` のみ有効 |
| `stopReason`         | `string`  | —      | 停止理由（`continue: false` と併用）                                                                                          |
| `decision`           | `string`  | —      | `"approve"` または `"block"`。`"block"` はツール実行を阻止。`Stop` イベントでは停止を防止し続行を強制                                               |
| `reason`             | `string`  | —      | 決定理由（モデルに表示。`Stop` イベントの `"block"` では続行プロンプトとして注入）                                                                   |
| `hookSpecificOutput` | `object`  | —      | イベント固有の出力（各イベント型を参照）                                                                                                 |

> 複数の hook が競合する `decision` 値を返した場合、`"deny"` / `"block"` が優先されます（最も厳格なルールが適用）。

***

<div id="pretoolusehookinput" />

### `PreToolUseHookInput`

```typescript theme={null}
interface PreToolUseHookInput extends BaseHookInput {
  hook_event_name: 'PreToolUse';
  permission_mode: string | undefined;
  tool_name: string;
  tool_input: unknown;
}
```

| フィールド             | 型                     | 説明                  |
| :---------------- | :-------------------- | :------------------ |
| `permission_mode` | `string \| undefined` | 現在のセッションのパーミッションモード |
| `tool_name`       | `string`              | 呼び出されるツール名          |
| `tool_input`      | `unknown`             | ツールに渡される引数          |

**`hookSpecificOutput`：**

| フィールド                      | 型                         | 説明                                         |
| :------------------------- | :------------------------ | :----------------------------------------- |
| `hookEventName`            | `"PreToolUse"`            | 必須                                         |
| `permissionDecision`       | `string`                  | `"allow"` / `"deny"` / `"ask"` / `"defer"` |
| `permissionDecisionReason` | `string`                  | パーミッション決定理由                                |
| `updatedInput`             | `Record<string, unknown>` | 変更されたツール入力。元の `tool_input` を置換             |
| `additionalContext`        | `string`                  | モデルの次のターンに注入される追加コンテキスト                    |

<div id="posttoolusehookinput" />

### `PostToolUseHookInput`

```typescript theme={null}
interface PostToolUseHookInput extends BaseHookInput {
  hook_event_name: 'PostToolUse';
  tool_name: string;
  tool_input: unknown;
  tool_response: unknown;
}
```

| フィールド           | 型         | 説明         |
| :-------------- | :-------- | :--------- |
| `tool_name`     | `string`  | 呼び出されたツール名 |
| `tool_input`    | `unknown` | ツールに渡された引数 |
| `tool_response` | `unknown` | ツールの実行結果   |

**出力動作：**

| フィールド                                  | 場所       | 動作                                      |
| :------------------------------------- | :------- | :-------------------------------------- |
| `hookSpecificOutput.updatedToolOutput` | イベント固有出力 | `tool_response` を**上書き**。モデルは上書き後の値のみ参照 |
| `hookSpecificOutput.additionalContext` | イベント固有出力 | 補足コンテキストを**追加**。元の結果は変更しない              |
| `decision: "block"` + `reason`         | トップレベル出力 | エージェントがこのツール結果をさらに処理することを阻止             |

**`hookSpecificOutput`：**

| フィールド               | 型               | 説明                  |
| :------------------ | :-------------- | :------------------ |
| `hookEventName`     | `"PostToolUse"` | 必須                  |
| `updatedToolOutput` | `string`        | ツールレスポンスの内容を上書き     |
| `additionalContext` | `string`        | ツール結果に付加される追加コンテキスト |

> 複数の hook が `updatedToolOutput` を設定した場合、**最後の非空値**が有効になります。チェーン変換が必要な場合は、単一のコールバック内で順次実行してください。

<div id="posttoolusefailurehookinput" />

### `PostToolUseFailureHookInput`

```typescript theme={null}
interface PostToolUseFailureHookInput extends BaseHookInput {
  hook_event_name: 'PostToolUseFailure';
  tool_name: string;
  tool_input: unknown;
  error: string;
  is_interrupt: boolean | undefined;
}
```

| フィールド          | 型                      | 説明             |
| :------------- | :--------------------- | :------------- |
| `tool_name`    | `string`               | 失敗したツール名       |
| `tool_input`   | `unknown`              | ツールに渡された引数     |
| `error`        | `string`               | エラーメッセージ       |
| `is_interrupt` | `boolean \| undefined` | 中断/中止によるものかどうか |

<div id="userpromptsubmithookinput" />

### `UserPromptSubmitHookInput`

```typescript theme={null}
interface UserPromptSubmitHookInput extends BaseHookInput {
  hook_event_name: 'UserPromptSubmit';
  prompt: string;
}
```

| フィールド    | 型        | 説明         |
| :------- | :------- | :--------- |
| `prompt` | `string` | ユーザー入力テキスト |

**`hookSpecificOutput`：**

| フィールド               | 型                    | 説明                      |
| :------------------ | :------------------- | :---------------------- |
| `hookEventName`     | `"UserPromptSubmit"` | 必須                      |
| `additionalContext` | `string`             | ユーザープロンプトに追加される追加コンテキスト |

<div id="sessionstarthookinput" />

### `SessionStartHookInput`

```typescript theme={null}
interface SessionStartHookInput extends BaseHookInput {
  hook_event_name: 'SessionStart';
  source: string;
}
```

| フィールド    | 型        | 説明                                                           |
| :------- | :------- | :----------------------------------------------------------- |
| `source` | `string` | セッション開始理由：`"startup"` / `"resume"` / `"clear"` / `"compact"` |

**`hookSpecificOutput`：**

| フィールド               | 型                | 説明                   |
| :------------------ | :--------------- | :------------------- |
| `hookEventName`     | `"SessionStart"` | 必須                   |
| `additionalContext` | `string`         | セッション開始時に注入されるコンテキスト |

<div id="sessionendhookinput" />

### `SessionEndHookInput`

```typescript theme={null}
interface SessionEndHookInput extends BaseHookInput {
  hook_event_name: 'SessionEnd';
  reason: string;
}
```

| フィールド    | 型        | 説明                                                                                                                  |
| :------- | :------- | :------------------------------------------------------------------------------------------------------------------ |
| `reason` | `string` | セッション終了理由：`"clear"` / `"resume"` / `"logout"` / `"prompt_input_exit"` / `"other"` / `"bypass_permissions_disabled"` |

<div id="stophookinput" />

### `StopHookInput`

```typescript theme={null}
interface StopHookInput extends BaseHookInput {
  hook_event_name: 'Stop';
  stop_hook_active: boolean;
}
```

| フィールド              | 型         | 説明                         |
| :----------------- | :-------- | :------------------------- |
| `stop_hook_active` | `boolean` | Stop hook が現在停止を防止しているかどうか |

`{ decision: 'block', reason: '...' }` を返すと AI の停止を防止し続行を強制します。`reason` は続行プロンプトとしてモデルコンテキストに注入されます。

<div id="subagentstarthookinput" />

### `SubagentStartHookInput`

```typescript theme={null}
interface SubagentStartHookInput extends BaseHookInput {
  hook_event_name: 'SubagentStart';
  agent_id: string;
  agent_type: string;
}
```

| フィールド        | 型        | 説明                   |
| :----------- | :------- | :------------------- |
| `agent_id`   | `string` | サブエージェントインスタンスの一意識別子 |
| `agent_type` | `string` | サブエージェントのタイプ/ロール     |

<div id="subagentstophookinput" />

### `SubagentStopHookInput`

```typescript theme={null}
interface SubagentStopHookInput extends BaseHookInput {
  hook_event_name: 'SubagentStop';
  stop_hook_active: boolean;
}
```

| フィールド              | 型         | 説明                         |
| :----------------- | :-------- | :------------------------- |
| `stop_hook_active` | `boolean` | Stop hook が現在停止を防止しているかどうか |

<div id="precompacthookinput" />

### `PreCompactHookInput`

```typescript theme={null}
interface PreCompactHookInput extends BaseHookInput {
  hook_event_name: 'PreCompact';
  trigger: string;
  custom_instructions: string | null;
}
```

| フィールド                 | 型                | 説明                           |
| :-------------------- | :--------------- | :--------------------------- |
| `trigger`             | `string`         | トリガー理由：`"manual"` / `"auto"` |
| `custom_instructions` | `string \| null` | 圧縮サマリーのカスタム命令                |

<div id="postcompacthookinput" />

### `PostCompactHookInput`

```typescript theme={null}
interface PostCompactHookInput extends BaseHookInput {
  hook_event_name: 'PostCompact';
  trigger: string;
  compact_summary: string;
}
```

| フィールド             | 型        | 説明                           |
| :---------------- | :------- | :--------------------------- |
| `trigger`         | `string` | トリガー理由：`"manual"` / `"auto"` |
| `compact_summary` | `string` | コンテキスト圧縮後に生成されたサマリー          |

<div id="cwdchangedhookinput" />

### `CwdChangedHookInput`

```typescript theme={null}
interface CwdChangedHookInput extends BaseHookInput {
  hook_event_name: 'CwdChanged';
  old_cwd: string;
  new_cwd: string;
}
```

| フィールド     | 型        | 説明           |
| :-------- | :------- | :----------- |
| `old_cwd` | `string` | 変更前の作業ディレクトリ |
| `new_cwd` | `string` | 変更後の作業ディレクトリ |

<div id="instructionsloadedhookinput" />

### `InstructionsLoadedHookInput`

```typescript theme={null}
interface InstructionsLoadedHookInput extends BaseHookInput {
  hook_event_name: 'InstructionsLoaded';
  load_reason: string;
}
```

| フィールド         | 型        | 説明                                               |
| :------------ | :------- | :----------------------------------------------- |
| `load_reason` | `string` | ロード理由：`"nested_traversal"` / `"path_glob_match"` |

<div id="filechangedhookinput" />

### `FileChangedHookInput`

```typescript theme={null}
interface FileChangedHookInput extends BaseHookInput {
  hook_event_name: 'FileChanged';
  file_path: string;
  event: string;
}
```

| フィールド       | 型        | 説明                                             |
| :---------- | :------- | :--------------------------------------------- |
| `file_path` | `string` | 変更されたファイルのパス                                   |
| `event`     | `string` | ファイルシステムイベント：`"change"` / `"add"` / `"unlink"` |

<div id="permissionrequesthookinput" />

### `PermissionRequestHookInput`

```typescript theme={null}
interface PermissionRequestHookInput extends BaseHookInput {
  hook_event_name: 'PermissionRequest';
  tool_name: string;
  tool_input: unknown;
  permission_suggestions: PermissionUpdate[] | undefined;
}
```

| フィールド                    | 型                                 | 説明              |
| :----------------------- | :-------------------------------- | :-------------- |
| `tool_name`              | `string`                          | パーミッションを要求するツール |
| `tool_input`             | `unknown`                         | ツール入力引数         |
| `permission_suggestions` | `PermissionUpdate[] \| undefined` | 提案されるパーミッションルール |

**`hookSpecificOutput`：**

| フィールド           | 型                     | 説明              |
| :-------------- | :-------------------- | :-------------- |
| `hookEventName` | `"PermissionRequest"` | 必須              |
| `decision`      | `object`              | パーミッション決定（下記参照） |

`decision` は以下のいずれかです：

* **承認：** `{ behavior: "allow", updatedInput?: Record<string, unknown>, updatedPermissions?: PermissionUpdate[] }`
* **拒否：** `{ behavior: "deny", message?: string }`

<div id="message-types" />

## Message Types

<div id="sdkmessage" />

### `SDKMessage`

`Query` からストリーム出力されるすべてのメッセージの判別ユニオンです。

```typescript theme={null}
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;
```

呼び出し側はまず `message.type` で分岐し、次に `subtype` でさらに細分化します（`system` / `result` 型のみ subtype を持ちます）。

<div id="sdkassistantmessage" />

### `SDKAssistantMessage`

AI の完全な応答。ターンごとに1回到達します。

```typescript theme={null}
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 }
    >;
  };
};
```

<div id="sdkusermessage" />

### `SDKUserMessage`

ユーザーメッセージまたはツール結果のフィードバックです。

```typescript theme={null}
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;
};
```

<div id="sdkusermessagereplay" />

### `SDKUserMessageReplay`

セッション復元時にリプレイされる履歴ユーザーメッセージです。

```typescript theme={null}
type SDKUserMessageReplay = SDKUserMessage & {
  uuid: string;
  session_id: string;
  isReplay: true;
};
```

<div id="sdkresultmessage" />

### `SDKResultMessage`

セッション全体が終了した時の最終メッセージです。

```typescript theme={null}
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';
      // success と同じ共通フィールド
      errors: string[];
    };
```

<div id="sdksystemmessage" />

### `SDKSystemMessage`

セッション初期化メッセージ（`subtype: 'init'`）。その他のシステムイベントは個別のメッセージ型で送達されます。以下の各 `SDK*Message` を参照してください。

```typescript theme={null}
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';
};
```

<div id="sdkpartialassistantmessage" />

### `SDKPartialAssistantMessage`

`includePartialMessages: true` の有効化が必要です。トークン単位で増分ストリーム出力されます。完全な使用法は [ストリーム出力](/ja/cli/sdk/streaming-output) を参照してください。

```typescript theme={null}
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;
    };
  };
};
```

<div id="sdkcompactboundarymessage" />

### `SDKCompactBoundaryMessage`

コンテキスト圧縮完了の境界マーカーです。

```typescript theme={null}
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;
    };
  };
};
```

<div id="sdkstatusmessage" />

### `SDKStatusMessage`

セッション実行ステータスの変化（例: 圧縮中）です。

```typescript theme={null}
type SDKStatusMessage = {
  type: 'system';
  subtype: 'status';
  status: 'compacting' | null;
  permissionMode?: PermissionMode;
  uuid: string;
  session_id: string;
};
```

<div id="sdkmcpstatuschangemessage" />

### `SDKMcpStatusChangeMessage`

MCP コネクションプールのステータス変化です。

```typescript theme={null}
type SDKMcpStatusChangeMessage = {
  type: 'system';
  subtype: 'mcp_status_change';
  servers: McpServerStatus[];
  uuid: string;
  session_id: string;
};
```

<div id="sdkapiretrymessage" />

### `SDKAPIRetryMessage`

ネットワーク/サービス異常時の自動リトライです。

```typescript theme={null}
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;
};
```

<div id="sdklocalcommandoutputmessage" />

### `SDKLocalCommandOutputMessage`

ローカル slash command の出力です。

```typescript theme={null}
type SDKLocalCommandOutputMessage = {
  type: 'system';
  subtype: 'local_command_output';
  content: string;
  uuid: string;
  session_id: string;
};
```

<div id="sdkhookstartedmessage" />

### `SDKHookStartedMessage`

Hook の実行開始です。

```typescript theme={null}
type SDKHookStartedMessage = {
  type: 'system';
  subtype: 'hook_started';
  hook_id: string;
  hook_name: string;
  hook_event: string;
  uuid: string;
  session_id: string;
};
```

<div id="sdkhookprogressmessage" />

### `SDKHookProgressMessage`

Hook 実行中の出力です。

```typescript theme={null}
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;
};
```

<div id="sdkhookresponsemessage" />

### `SDKHookResponseMessage`

Hook の終了です。

```typescript theme={null}
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;
};
```

<div id="sdktaskstartedmessage" />

### `SDKTaskStartedMessage`

サブエージェントタスクの開始です。

```typescript theme={null}
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;
};
```

<div id="sdktaskprogressmessage" />

### `SDKTaskProgressMessage`

サブエージェントタスクの進捗です。

```typescript theme={null}
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;
};
```

<div id="sdktasknotificationmessage" />

### `SDKTaskNotificationMessage`

サブエージェントタスクの終了です。

```typescript theme={null}
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;
};
```

<div id="sdksessionstatechangedmessage" />

### `SDKSessionStateChangedMessage`

メインセッションの実行ステータス変化です。

```typescript theme={null}
type SDKSessionStateChangedMessage = {
  type: 'system';
  subtype: 'session_state_changed';
  state: 'idle' | 'running' | 'requires_action';
  uuid: string;
  session_id: string;
};
```

<div id="sdksessiontitlechangedmessage" />

### `SDKSessionTitleChangedMessage`

セッションタイトルの変化です。

```typescript theme={null}
type SDKSessionTitleChangedMessage = {
  type: 'system';
  subtype: 'session_title_changed';
  title: string;
  source: 'ai' | 'custom';
  revision: number;
  uuid: string;
  session_id: string;
};
```

<div id="sdkbridgestatemessage" />

### `SDKBridgeStateMessage`

Bridge 接続ステータスの変化です。

```typescript theme={null}
type SDKBridgeStateMessage = {
  type: 'system';
  subtype: 'bridge_state';
  state: string;
  detail?: string;
  uuid: string;
  session_id: string;
};
```

<div id="sdkfilespersistedevent" />

### `SDKFilesPersistedEvent`

ファイルチェックポイントの永続化結果です。

```typescript theme={null}
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;
};
```

<div id="sdkelicitationcompletemessage" />

### `SDKElicitationCompleteMessage`

MCP elicitation の完了です。

```typescript theme={null}
type SDKElicitationCompleteMessage = {
  type: 'system';
  subtype: 'elicitation_complete';
  mcp_server_name: string;
  elicitation_id: string;
  uuid: string;
  session_id: string;
};
```

<div id="sdkpermissiondeniedmessage" />

### `SDKPermissionDeniedMessage`

ツール呼び出しが権限ポリシーによりショートサーキット拒否された場合（`dontAsk` / `auto` / deny rule など）です。

```typescript theme={null}
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;
};
```

<div id="sdkpromptsuggestionmessage" />

### `SDKPromptSuggestionMessage`

`promptSuggestions: true` 有効化後、各ターンの result 後に受信可能な次ステップの提案です。

```typescript theme={null}
type SDKPromptSuggestionMessage = {
  type: 'prompt_suggestion';
  suggestion: string;
  uuid: string;
  session_id: string;
};
```

<div id="sdkcloudagenteventmessage" />

### `SDKCloudAgentEventMessage`

Cloud ランタイム（`options.experimentalCloudAgent`）下で、Qoder Cloud session の SSE ストリームから転送されるイベントです。詳しい使い方は [Cloud Agent](/ja/cli/sdk/cloud-agent) を参照してください。

```typescript theme={null}
type SDKCloudAgentEventMessage = {
  type: 'cloud_agent_event';
  event: string;
  id?: string;
  data: unknown;
  uuid: string;
  session_id: string;
};
```

| フィールド        | 型         | 説明                                                                  |
| :----------- | :-------- | :------------------------------------------------------------------ |
| `event`      | `string`  | Cloud イベント名（例：`user.message`、`agent.message`、`session.status_idle`） |
| `id`         | `string`  | SSE イベント ID。`stream.afterId` の replay 起点として使用可能                     |
| `data`       | `unknown` | Cloud イベント payload（`turn_id` などのフィールドを含む）                           |
| `session_id` | `string`  | このイベントが属する Cloud session ID                                         |

<div id="sdkpermissiondenial" />

### `SDKPermissionDenial`

`SDKResultMessage.permission_denials` 配列内の要素です。

```typescript theme={null}
type SDKPermissionDenial = {
  tool_name: string;
  tool_use_id: string;
  tool_input: Record<string, unknown>;
};
```
