Client agent 名前空間
client.agent の各メソッドの使い方、入力、出力リファレンス。
Client agent 名前空間
client.agent は実行中の coding agent を制御する主要サーフェスです。このページではすべての public method について、呼び出し形、input、return value、使用例、注意点を整理します。
Lifecycle メソッド
agent.start(session, config?)
Signature
await client.agent.start(session: string, config?: AgentStartConfig): Promise<{
status: "started" | "already_running";
provider: string;
sessionId: string;
}>Input
| Field | Type | Required | Description |
|---|---|---|---|
session | string | yes | 対象の SNA session ID。存在しない場合は server が自動作成します。 |
config.provider | string | no | claude-code、codex、opencode、grok、cursor などの runtime id。 |
config.modelProvider | string | no | モデルベンダのアトリビューション metadata。assistant が書いた canonical row に保存されます。 |
config.prompt | string | no | 起動直後に送る初期 prompt。 |
config.model | string | no | ランタイムの model slug。 |
config.permissionMode | string | no | Permission behavior, for example acceptEdits or bypassPermissions. |
config.configDir | string | no | ランタイム config directory の override。Claude は CLAUDE_CONFIG_DIR、Codex は CODEX_HOME を使います。 |
config.force | boolean | no | 既存ランタイムを終了して新しく起動します。 |
config.cwd | string | no | このランタイムの作業ディレクトリ。 |
config.history | unknown[] | no | resume に使う runtime-neutral history。 |
config.systemPrompt | string | no | base system prompt を置き換えます。 |
config.appendSystemPrompt | string | no | system prompt にテキストを追記します。 |
config.allowedTools | string[] | no | agent が使える tool をこの一覧に制限します。 |
config.disallowedTools | string[] | no | 特定の tool をブロックします。 |
config.mcpServers | Record<string, unknown> | no | agent に公開する MCP server。 |
config.reasoningLevel | `0 | 1 | 2 |
config.providerOptions | Record<string, unknown> | no | ランタイム別 option。Codex の serviceTier、profile、config などを渡します。 |
config.extraArgs | string[] | no | deprecated な raw CLI flag。typed field を優先してください。 |
Codex では providerOptions で serviceTier、profile、config を指定できます。profile は --profile <name> として渡され、config は codex app-server と codex exec の両方に、繰り返し指定できる -c key=value override として渡されます。
Returns
| Field | Description |
|---|---|
status | process を spawn した場合は started、session にすでにランタイムがある場合は already_running。 |
provider | 使用されたランタイム。 |
sessionId | ランタイム session ID。 |
Example
const started = await client.agent.start("default", {
provider: "claude-code",
model: "claude-sonnet-4-6",
permissionMode: "acceptEdits",
cwd: "/Users/me/project",
reasoningLevel: 3,
});Notes
- With HTTP enabled, the promise resolves after the process has been spawned.
- It does not guarantee the runtime init handshake has reached an idle state. If the UI must wait for readiness, call
getStatusuntilagentStatus === "idle". - Calling
sendimmediately afterstartis safe in normal usage because stdin queues the message.
agent.send(session, message, opts?)
Signature
await client.agent.send(
session: string,
message: string,
opts?: { images?: Array<{ base64: string; mimeType: string }>; meta?: Record<string, unknown> },
): Promise<{ status: "sent" }>Input
| Field | Type | Required | Description |
|---|---|---|---|
session | string | yes | 実行中の session ID。 |
message | string | yes | agent に送る user message。 |
opts.images | { base64: string; mimeType: string }[] | no | multimodal input をサポートするランタイムに渡す画像添付。 |
opts.meta | Record<string, unknown> | no | user message と一緒に保存する追加 metadata。 |
Returns
message が受理されると { status: "sent" } を返します。HTTP が有効な場合、promise が resolve する前に message も保存されます。
Example
await client.agent.send("default", "Please inspect the failing test.");
await client.agent.send("default", "What is in this screenshot?", {
images: [{ base64: pngBase64, mimeType: "image/png" }],
});Notes
- Use this only for stateful interactive sessions.
- For a stateless one-shot task, use
runOnceorrunOnceStream.
agent.kill(session)
Signature
await client.agent.kill(session: string): Promise<{ status: "killed" | "no_session" }>Input: session は終了したい agent process の session ID です。
Returns: ランタイムを停止した場合は killed、session が存在しない場合は no_session。
Example
await client.agent.kill("default");Notes: session record は残り、実行中の process だけが終了します。
agent.restart(session, config?)
Signature
await client.agent.restart(session: string, config?: Partial<AgentStartConfig>): Promise<{
status: "restarted";
provider: string;
sessionId: string;
}>Input: start と同じ config shape ですが、すべての field が optional です。
Returns: restart 後の runtime id と新しい runtime session ID を返します。
Example
await client.agent.restart("default", { model: "claude-opus-4-6" });Notes: runtime-level 設定を変更した後、または CLI process が不健全になったときに使います。
agent.interrupt(session)
Signature
await client.agent.interrupt(session: string): Promise<{ status: "interrupted" | "no_session" }>Use it when ユーザーが stop button を押したが、次の message のために session は残したいときに使います。
Example
await client.agent.interrupt("default");
await client.agent.send("default", "Try a simpler approach.");agent.resume(session, opts?)
Signature
await client.agent.resume(session: string, opts?: {
provider?: string;
model?: string;
permissionMode?: string;
configDir?: string;
prompt?: string;
extraArgs?: string[];
providerOptions?: Record<string, unknown>;
}): Promise<{
status: "resumed";
provider: string;
sessionId: string;
historyCount: number;
}>Input
| Field | Description |
|---|---|
session | 保存済み history から resume する session。 |
opts.provider | ランタイム override。 |
opts.model | モデル override。 |
opts.permissionMode | permission mode override。 |
opts.configDir | ランタイム config directory override。 |
opts.prompt | resume 中に送る optional prompt。 |
opts.providerOptions | ランタイム別 option。 |
Returns
| Field | Description |
|---|---|
status | 成功時は常に resumed。 |
provider | resumed session に使われたランタイム。 |
sessionId | ランタイム session ID。 |
historyCount | 読み込んだ persisted message 数。 |
Example
const resumed = await client.agent.resume("default", { provider: "codex" });
console.log(resumed.historyCount);agent.getStatus(session)
Signature
await client.agent.getStatus(session: string): Promise<{
alive: boolean;
agentStatus: "idle" | "busy" | "disconnected";
sessionId: string | null;
ccSessionId: string | null;
eventCount: number;
messageCount: number;
lastMessage: { actor: string; kind: string; content: string; created_at: string } | null;
config: { provider: string; model: string; permissionMode: string; extraArgs?: string[] } | null;
}>Use it when runtime state に依存する control を描画する、または start 後に準備完了を待つときに使います。
Example
const status = await client.agent.getStatus("default");
if (status.alive && status.agentStatus === "idle") {
await client.agent.send("default", "Next task");
}One-shot と completion メソッド
agent.completion(opts)
Signature
await client.agent.completion(opts: CompletionOptions): Promise<CompletionResult>Input
| Field | Type | Required | Description |
|---|---|---|---|
prompt | string | yes | 送信する prompt。 |
model | string | no | モデル slug。 |
systemPrompt | string | no | system prompt を置き換えます。 |
appendSystemPrompt | string | no | system prompt に追記します。 |
label | string | no | trace label。 |
timeout | number | no | millisecond 単位の timeout。 |
extraArgs | string[] | no | deprecated な raw CLI flag。 |
env | Record<string, string> | no | environment override。 |
reasoningLevel | `0 | 1 | 2 |
providerOptions | Record<string, unknown> | no | ランタイム別 option。 |
Returns
| Field | Type | Description |
|---|---|---|
text | string | 生成された text。 |
usage.inputTokens | number | input token 数。 |
usage.outputTokens | number | output token 数。 |
usage.cacheReadTokens | number | cache read token 数。 |
usage.cacheCreationTokens | number | cache creation token 数。 |
costUsd | number | USD ベースの推定コスト。 |
durationMs | number | 総所要時間。 |
durationApiMs | number | ランタイム API の所要時間。 |
model | string | 使用されたモデル。 |
Example
const result = await client.agent.completion({
prompt: "Summarize this changelog.",
model: "claude-haiku-4-5-20251001",
label: "summary",
});
console.log(result.text, result.costUsd);Use completion instead of runOnce when agent session、tool、event streaming が不要なタスクでは runOnce より completion を使います。
agent.runOnce(opts)
Signature
await client.agent.runOnce(opts: RunOnceOptions): Promise<{
result: string;
usage: Record<string, unknown> | null;
}>Input
| Field | Type | Required | Description |
|---|---|---|---|
message | string | yes | タスク prompt。 |
model | string | no | モデル slug。 |
systemPrompt | string | no | system prompt を置き換えます。 |
appendSystemPrompt | string | no | system prompt に追記します。 |
permissionMode | string | no | permission の動作。 |
cwd | string | no | 作業ディレクトリ。 |
timeout | number | no | millisecond 単位の timeout。 |
provider | string | no | runtime id。 |
extraArgs | string[] | no | deprecated な raw CLI flag。 |
reasoningLevel | `0 | 1 | 2 |
providerOptions | Record<string, unknown> | no | ランタイム別 option。 |
Example
const { result } = await client.agent.runOnce({
provider: "claude-code",
message: "Find the most likely cause of the failing build.",
cwd: process.cwd(),
timeout: 60_000,
});Notes: server が temporary session を作成し、完了を待ってから片付けます。
agent.runOnceStream(opts)
Signature
for await (const event of client.agent.runOnceStream(opts: RunOnceOptions)) {
// event is Record<string, unknown>
}Returns: an AsyncGenerator<Record<string, unknown>> of SSE events.
Example
for await (const event of client.agent.runOnceStream({ message: "Explain this file." })) {
if (event.type === "assistant_delta") process.stdout.write(String(event.delta ?? ""));
if (event.type === "complete") break;
}Notes: http: true が必要です。POST /agent/run-once/stream を使います。
Model と configuration メソッド
agent.listModels(runtime, config?)
Signature
await client.agent.listModels(runtime: string, config?: ListModelsConfig): Promise<ListModelsResult>Input
| Field | Type | Description |
|---|---|---|
runtime | string | 調べるランタイム。例: claude-code、codex、opencode、grok、cursor。 |
config.cliPath | string | モデル一覧取得だけに使うランタイム CLI パス上書き。エージェントの spawn パスにはランチャーの runtimePaths を使ってください。 |
config.refresh | boolean | cache を使わず再取得します。 |
Returns
type ListModelsResult = {
models: Array<{
id: string;
label: string;
provider: string;
source: "static" | "api" | "cli";
contextWindow?: number;
deprecated?: boolean;
notes?: string;
}>;
source: "static" | "api" | "cli" | "mixed";
fetchedAt: number;
error?: string;
};Example
const catalog = await client.agent.listModels("opencode", { refresh: true });
if (catalog.error) console.warn(catalog.error);agent.setModel(session, model)
Signature
await client.agent.setModel(session: string, model: string): Promise<{
status: "updated" | "no_session";
model: string;
}>Example
await client.agent.setModel("default", "claude-opus-4-6");agent.setPermissionMode(session, permissionMode)
Signature
await client.agent.setPermissionMode(session: string, permissionMode: string): Promise<{
status: "updated" | "no_session";
permissionMode: string;
}>Example
await client.agent.setPermissionMode("default", "acceptEdits");agent.update(session, patch)
Signature
await client.agent.update(
session: string,
patch: { cwd?: string; model?: string; permissionMode?: string },
): Promise<{
status: "updated";
applied: "in-place" | "respawn";
runtimeId: string;
fields: string[];
}>Example
const updated = await client.agent.update("default", {
cwd: "/Users/me/other-project",
model: "gpt-5.5",
});
console.log(updated.applied); // "in-place" or "respawn"Notes: 一部のランタイムは変更を in-place で適用できます。その他のランタイムでは DB-backed history replay を使った respawn が必要です。
Event streaming メソッド
agent.streamEvents(session, since?)
Signature
for await (const event of client.agent.streamEvents(session: string, since?: number)) {
// event is Record<string, unknown>
}Use it when WebSocket ではなく SSE を使いたいときに使います。http: true が必要です。
agent.subscribe(session, opts?)
Signature
await client.agent.subscribe(session: string, opts?: {
since?: number;
includeHistory?: boolean;
tail?: number;
}): Promise<{ cursor: number; oldestCursor?: number; hasMore: boolean }>Input
| Field | Description |
|---|---|
since | この event cursor から開始します。 |
includeHistory | persisted history を event として replay します。 |
tail | 最後の N 件の persisted message だけを replay します。since と includeHistory とは同時に使えません。 |
Example
client.agent.onEvent(({ session, cursor, event, isHistory }) => {
if (!isHistory) renderEvent(session, cursor, event);
});
const sub = await client.agent.subscribe("default", { tail: 20 });agent.getMessages(session, opts?)
Signature
await client.agent.getMessages(session: string, opts?: {
before?: number;
limit?: number;
}): Promise<{
events: Array<{ cursor: number; event: Record<string, unknown> }>;
oldestCursor?: number;
hasMore: boolean;
}>Use it when 古い persisted message の reverse pagination を実装するときに使います。
agent.unsubscribe(session)
Signature
await client.agent.unsubscribe(session: string): Promise<void>Notes: reconnect resubscription state からもその session を削除します。
agent.onEvent(handler)
Signature
const unsubscribe = client.agent.onEvent((event: {
session: string;
cursor: number;
event: Record<string, unknown>;
isHistory?: boolean;
}) => void);Common event types
| Type | Meaning |
|---|---|
thinking | agent 内部の reasoning block。 |
thinking_delta | reasoning のストリーミング断片。 |
assistant | assistant に見える response block。 |
assistant_delta | streaming text fragment。 |
tool_use | agent が tool を呼び出しています。 |
tool_use_delta | runtime が対応する場合の tool input のストリーミング断片。 |
tool_result | tool 実行結果。 |
permission_needed | runtime が承認判断を待っている状態。 |
complete | turn が完了しました。 |
interrupted | turn が正常完了前に中断されました。 |
error | runtime error。 |
user_message | multi-client sync のために echo された user message。 |
Permission メソッド
agent.subscribePermissions()
Signature
await client.agent.subscribePermissions(): Promise<{ pendingCount: number }>Use it when UI が tool approval prompt を受け取る必要があるときに使います。最初の permission prompt を逃せない場合は、agent を開始する前に subscribe してください。
agent.unsubscribePermissions()
Signature
await client.agent.unsubscribePermissions(): Promise<void>agent.getPendingPermissions(session?)
Signature
await client.agent.getPendingPermissions(session?: string): Promise<{
pending: Array<{
sessionId: string;
request: Record<string, unknown>;
createdAt: number;
}>;
}>Use it when UI の reconnect 時に、disconnected の間に届いた prompt を復元するときに使います。
agent.respondPermission(session, approved)
Signature
await client.agent.respondPermission(
session: string,
approved: boolean,
): Promise<{ status: "approved" | "denied" }>Example
client.agent.onPermissionRequest(({ session, request }) => {
const safe = request.tool === "Edit";
client.agent.respondPermission(session, safe);
});agent.onPermissionRequest(handler)
Signature
const unsubscribe = client.agent.onPermissionRequest((event: {
session: string;
request: Record<string, unknown>;
createdAt: number;
isHistory?: boolean;
}) => void);Use it when human approval のために modal、notification、command palette prompt を開くときに使います。