先決條件

  • Node.js 18+

安裝

從 NPM 安裝 @anthropic-ai/claude-code

npm install -g @anthropic-ai/claude-code

要查看 TypeScript SDK 原始碼,請造訪 NPM 上的 @anthropic-ai/claude-code 頁面

基本用法

透過 TypeScript SDK 的主要介面是 query 函數,它回傳一個非同步迭代器,在訊息到達時串流傳輸:

import { query } from "@anthropic-ai/claude-code";

for await (const message of query({
  prompt: "分析系統效能",
  options: {
    maxTurns: 5,
    appendSystemPrompt: "你是一位效能工程師",
    allowedTools: ["Bash", "Read", "WebSearch"],
    abortController: new AbortController(),
  }
})) {
  if (message.type === "result" && message.subtype === "success") {
    console.log(message.result);
  }
}

設定選項

參數類型描述預設值
abortControllerAbortController用於取消操作的中止控制器new AbortController()
additionalDirectoriesstring[]要包含在會話中的額外目錄undefined
allowedToolsstring[]Claude 被允許使用的工具清單預設啟用所有工具
appendSystemPromptstring要附加到預設系統提示的文字undefined
canUseTool(toolName: string, input: any) => Promise<ToolPermissionResult>工具使用的自訂權限函數undefined
continueboolean繼續最近的會話false
customSystemPromptstring完全替換預設系統提示undefined
cwdstring目前工作目錄process.cwd()
disallowedToolsstring[]Claude 不被允許使用的工具清單undefined
envDict<string>要設定的環境變數undefined
executable'bun' | 'deno' | 'node'要使用的 JavaScript 執行時間使用 Node.js 執行時為 node,使用 Bun 執行時為 bun
executableArgsstring[]要傳遞給可執行檔的參數[]
fallbackModelstring主要模型失敗時使用的模型undefined
hooksPartial<Record<HookEvent, HookCallbackMatcher[]>>用於自訂的生命週期鉤子undefined
includePartialMessagesboolean在訊息串流中包含部分串流事件false
maxThinkingTokensnumberClaude 思考過程的最大代幣數undefined
maxTurnsnumber對話輪次的最大數量undefined
mcpServersRecord<string, McpServerConfig>MCP 伺服器設定undefined
modelstring要使用的 Claude 模型使用 CLI 設定的預設值
pathToClaudeCodeExecutablestringClaude Code 可執行檔的路徑@anthropic-ai/claude-code 一起提供的可執行檔
permissionModePermissionMode會話的權限模式"default" (選項:"default""acceptEdits""bypassPermissions""plan")
resumestring要恢復的會話 IDundefined
stderr(data: string) => voidstderr 輸出的回調undefined
strictMcpConfigboolean強制執行嚴格的 MCP 設定驗證undefined

部分訊息串流

當啟用 includePartialMessages 時,SDK 將發出包含來自 Claude API 的原始串流事件的 stream_event 訊息。這讓您可以在內容生成時存取部分內容,對於實現即時 UI 更新或進度指示器很有用。

import { query } from "@anthropic-ai/claude-code";

for await (const message of query({
  prompt: "寫一篇關於人工智慧的長篇文章",
  options: {
    includePartialMessages: true,
    maxTurns: 1
  }
})) {
  // 處理部分串流事件
  if (message.type === "stream_event") {
    const event = message.event;
    
    // 在串流時存取部分文字
    if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
      process.stdout.write(event.delta.text);
    }
    
    // 追蹤思考進度
    if (event.type === "content_block_start" && event.content_block.type === "thinking") {
      console.log("\n[Claude 正在思考...]");
    }
  }
  
  // 仍然獲得最終結果
  if (message.type === "result" && message.subtype === "success") {
    console.log("\n最終結果:", message.result);
  }
}

每個 stream_event 訊息包含:

  • event:來自 API 的原始串流事件
  • session_id:目前會話識別碼
  • parent_tool_use_id:正在執行的工具 ID(如果適用)
  • uuid:此事件的唯一識別碼

部分訊息串流主要對需要對串流回應進行細粒度控制的進階用例有用。對於大多數應用程式,預設行為(等待完整訊息)就足夠了。

多輪對話

對於多輪對話,您有兩個選項。

您可以生成回應並恢復它們,或者您可以使用串流輸入模式,它接受訊息陣列的非同步/生成器。目前,串流輸入模式是透過訊息附加圖片的唯一方式。

使用會話管理恢復

import { query } from "@anthropic-ai/claude-code";

// 繼續最近的對話
for await (const message of query({
  prompt: "現在重構這個以獲得更好的效能",
  options: { continue: true }
})) { 
  if (message.type === "result" && message.subtype === "success") console.log(message.result);
}

// 恢復特定會話
for await (const message of query({
  prompt: "更新測試",
  options: {
    resume: "550e8400-e29b-41d4-a716-446655440000",
    maxTurns: 3
  }
})) {
  if (message.type === "result" && message.subtype === "success") console.log(message.result);
}

串流輸入模式

串流輸入模式允許您將訊息作為非同步可迭代物件提供,而不是單一字串。這啟用了多輪對話、圖片附件和動態訊息生成:

import { query } from "@anthropic-ai/claude-code";

// 為串流訊息建立非同步生成器
async function* generateMessages() {
  yield {
    type: "user" as const,
    message: {
      role: "user" as const,
      content: "開始分析這個程式碼庫"
    }
  };
  
  // 等待某些條件或使用者輸入
  await new Promise(resolve => setTimeout(resolve, 1000));
  
  yield {
    type: "user" as const,
    message: {
      role: "user" as const,
      content: "現在專注於身份驗證模組"
    }
  };
}

// 使用串流輸入
for await (const message of query({
  prompt: generateMessages(),
  options: {
    maxTurns: 5,
    allowedTools: ["Read", "Grep", "Bash"]
  }
})) {
  if (message.type === "result" && message.subtype === "success") {
    console.log(message.result);
  }
}

帶圖片的串流輸入

串流輸入模式是透過訊息附加圖片的唯一方式:

import { query } from "@anthropic-ai/claude-code";
import { readFileSync } from "fs";

async function* messagesWithImage() {
  // 發送帶文字的圖片
  yield {
    type: "user" as const,
    message: {
      role: "user" as const,
      content: [
        {
          type: "text",
          text: "分析這個螢幕截圖並建議改進"
        },
        {
          type: "image",
          source: {
            type: "base64",
            media_type: "image/png",
            data: readFileSync("screenshot.png", "base64")
          }
        }
      ]
    }
  };
}

for await (const message of query({
  prompt: messagesWithImage()
})) {
  if (message.type === "result" && message.subtype === "success") console.log(message.result);
}

自訂系統提示

系統提示定義您的代理的角色、專業知識和行為:

import { query } from "@anthropic-ai/claude-code";

// SRE 事件回應代理
for await (const message of query({
  prompt: "API 當機了,調查一下",
  options: {
    customSystemPrompt: "你是一位 SRE 專家。系統性地診斷問題並提供可行的解決方案。",
    maxTurns: 3
  }
})) {
  if (message.type === "result" && message.subtype === "success") console.log(message.result);
}

// 附加到預設系統提示
for await (const message of query({
  prompt: "重構這個函數",
  options: {
    appendSystemPrompt: "總是包含全面的錯誤處理和單元測試。",
    maxTurns: 2
  }
})) {
  if (message.type === "result" && message.subtype === "success") console.log(message.result);
}

MCP 伺服器整合

模型上下文協定(MCP)讓您為代理提供自訂工具和功能:

import { query } from "@anthropic-ai/claude-code";

// 帶監控工具的 SRE 代理
for await (const message of query({
  prompt: "調查支付服務中斷",
  options: {
    mcpConfig: "sre-tools.json",
    allowedTools: ["mcp__datadog", "mcp__pagerduty", "mcp__kubernetes"],
    appendSystemPrompt: "你是一位 SRE。使用監控資料來診斷問題。",
    maxTurns: 4
  }
})) {
  if (message.type === "result" && message.subtype === "success") console.log(message.result);
}

使用程序內 MCP 伺服器的自訂工具

SDK MCP 伺服器允許您建立直接在應用程式程序中執行的自訂工具,提供類型安全的工具執行,而無需單獨程序或網路通訊的開銷。

建立自訂工具

使用 createSdkMcpServertool 輔助函數來定義類型安全的自訂工具:

import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-code";
import { z } from "zod";

// 使用自訂工具建立 SDK MCP 伺服器
const customServer = createSdkMcpServer({
  name: "my-custom-tools",
  version: "1.0.0",
  tools: [
    tool(
      "calculate_compound_interest",
      "計算投資的複利",
      {
        principal: z.number().describe("初始投資金額"),
        rate: z.number().describe("年利率(以小數表示,例如 0.05 表示 5%)"),
        time: z.number().describe("投資期間(年)"),
        n: z.number().default(12).describe("每年複利頻率")
      },
      async (args) => {
        const amount = args.principal * Math.pow(1 + args.rate / args.n, args.n * args.time);
        const interest = amount - args.principal;
        
        return {
          content: [{
            type: "text",
            text: `最終金額:$${amount.toFixed(2)}\n賺取利息:$${interest.toFixed(2)}`
          }]
        };
      }
    ),
    tool(
      "fetch_user_data",
      "從您的應用程式資料庫獲取使用者資料",
      {
        userId: z.string().describe("要獲取的使用者 ID"),
        fields: z.array(z.string()).optional().describe("要回傳的特定欄位")
      },
      async (args) => {
        // 直接存取您應用程式的資料層
        const userData = await myDatabase.getUser(args.userId, args.fields);
        
        return {
          content: [{
            type: "text",
            text: JSON.stringify(userData, null, 2)
          }]
        };
      }
    )
  ]
});

// 在查詢中使用自訂工具
for await (const message of query({
  prompt: "計算 $10,000 在 5% 利率下 10 年的複利",
  options: {
    mcpServers: {
      "my-custom-tools": customServer
    },
    maxTurns: 3
  }
})) {
  if (message.type === "result") {
    console.log(message.result);
  }
}

使用 Zod 的類型安全

tool 輔助函數從您的 Zod 模式提供完整的 TypeScript 類型推斷:

tool(
  "process_data",
  "使用類型安全處理結構化資料",
  {
    // Zod 模式定義執行時驗證和 TypeScript 類型
    data: z.object({
      name: z.string(),
      age: z.number().min(0).max(150),
      email: z.string().email(),
      preferences: z.array(z.string()).optional()
    }),
    format: z.enum(["json", "csv", "xml"]).default("json")
  },
  async (args) => {
    // args 根據模式完全類型化
    // TypeScript 知道:args.data.name 是字串,args.data.age 是數字等
    console.log(`${args.format} 格式處理 ${args.data.name} 的資料`);
    
    // 您的處理邏輯在這裡
    return {
      content: [{
        type: "text",
        text: `已處理 ${args.data.name} 的資料`
      }]
    };
  }
)

鉤子

鉤子允許您透過在代理生命週期的各個點執行自訂回調來自訂和擴展 Claude Code 的行為。與執行 bash 命令的 CLI 鉤子不同,SDK 鉤子是在程序內執行的 JavaScript/TypeScript 函數。

定義鉤子

鉤子按事件類型組織,具有可選的匹配器來篩選何時執行:

import { query } from "@anthropic-ai/claude-code";

for await (const message of query({
  prompt: "分析程式碼庫",
  options: {
    hooks: {
      PreToolUse: [
        {
          matcher: "Write",
          hooks: [
            async (input, toolUseId, { signal }) => {
              console.log(`即將寫入檔案:${input.tool_input.file_path}`);
              
              // 驗證操作
              if (input.tool_input.file_path.includes('.env')) {
                return {
                  decision: 'block',
                  stopReason: '無法寫入環境檔案'
                };
              }
              
              // 允許操作
              return { continue: true };
            }
          ]
        }
      ],
      PostToolUse: [
        {
          matcher: "Write|Edit",
          hooks: [
            async (input, toolUseId, { signal }) => {
              console.log(`檔案已修改:${input.tool_response.filePath}`);
              // 執行您的自訂格式化或驗證
              return { continue: true };
            }
          ]
        }
      ]
    }
  }
})) {
  if (message.type === "result") console.log(message.result);
}

可用的鉤子事件

  • PreToolUse:在工具執行前執行。可以阻止工具或提供回饋。
  • PostToolUse:在成功工具執行後執行。
  • UserPromptSubmit:當使用者提交提示時執行。
  • SessionStart:當會話開始時執行。
  • SessionEnd:當會話結束時執行。
  • Stop:當 Claude 即將停止回應時執行。
  • SubagentStop:當子代理即將停止時執行。
  • PreCompact:在對話壓縮前執行。
  • Notification:當發送通知時執行。

鉤子輸入類型

每個鉤子根據事件接收類型化輸入:

// PreToolUse 輸入
type PreToolUseHookInput = {
  hook_event_name: 'PreToolUse';
  session_id: string;
  transcript_path: string;
  cwd: string;
  permission_mode?: string;
  tool_name: string;
  tool_input: unknown;
}

// PostToolUse 輸入
type PostToolUseHookInput = {
  hook_event_name: 'PostToolUse';
  session_id: string;
  transcript_path: string;
  cwd: string;
  permission_mode?: string;
  tool_name: string;
  tool_input: unknown;
  tool_response: unknown;
}

鉤子輸出

鉤子回傳控制執行流程的輸出:

interface HookJSONOutput {
  // 繼續執行(預設:true)
  continue?: boolean;
  
  // 抑制輸出給使用者
  suppressOutput?: boolean;
  
  // 停止原因(顯示給模型)
  stopReason?: string;
  
  // PreToolUse 鉤子的決定
  decision?: 'approve' | 'block';
  
  // 要顯示的系統訊息
  systemMessage?: string;
  
  // 鉤子特定輸出
  hookSpecificOutput?: {
    // 對於 PreToolUse
    permissionDecision?: 'allow' | 'deny' | 'ask';
    permissionDecisionReason?: string;
    
    // 對於 UserPromptSubmit 或 PostToolUse
    additionalContext?: string;
  };
}

實際範例

記錄和監控

const hooks = {
  PreToolUse: [
    {
      hooks: [
        async (input) => {
          // 記錄所有工具使用
          await logToMonitoring({
            event: 'tool_use',
            tool: input.tool_name,
            input: input.tool_input,
            session: input.session_id
          });
          
          return { continue: true };
        }
      ]
    }
  ]
};

檔案操作驗證

const hooks = {
  PreToolUse: [
    {
      matcher: "Write|Edit",
      hooks: [
        async (input) => {
          const filePath = input.tool_input.file_path;
          
          // 阻止敏感檔案
          const sensitivePatterns = ['.env', '.git/',   'secrets/', '*.key'];
          
          for (const pattern of sensitivePatterns) {
            if (filePath.includes(pattern)) {
              return {
                decision: 'block',
                stopReason: `無法修改符合 ${pattern} 的敏感檔案`
              };
            }
          }
          
          return { continue: true };
        }
      ]
    }
  ]
};

自動格式化程式碼

import { exec } from 'child_process';
import { promisify } from 'util';

const execAsync = promisify(exec);

const hooks = {
  PostToolUse: [
    {
      matcher: "Write|Edit|MultiEdit",
      hooks: [
        async (input) => {
          const filePath = input.tool_response.filePath;
          
          // 根據檔案類型自動格式化
          if (filePath.endsWith('.ts') || filePath.endsWith('.tsx')) {
            await execAsync(`prettier --write "${filePath}"`);
          } else if (filePath.endsWith('.py')) {
            await execAsync(`black "${filePath}"`);
          }
          
          return { continue: true };
        }
      ]
    }
  ]
};

提示增強

const hooks = {
  UserPromptSubmit: [
    {
      hooks: [
        async (input) => {
          // 為提示添加上下文
          const projectContext = await loadProjectContext();
          
          return {
            continue: true,
            hookSpecificOutput: {
              hookEventName: 'UserPromptSubmit',
              additionalContext: `專案上下文:${projectContext}`
            }
          };
        }
      ]
    }
  ]
};

自訂壓縮指令

const hooks = {
  PreCompact: [
    {
      hooks: [
        async (input) => {
          const trigger = input.trigger; // 'manual' 或 'auto'
          
          return {
            continue: true,
            systemMessage: '專注於保留實作細節和錯誤解決方案'
          };
        }
      ]
    }
  ]
};

鉤子執行行為

  • 並行化:所有匹配的鉤子並行執行
  • 超時:鉤子遵守選項中的中止信號
  • 錯誤處理:鉤子錯誤會被記錄但不會停止執行
  • 匹配器:支援正規表達式模式(例如 "Write|Edit"

結合鉤子與 canUseTool

雖然 canUseTool 提供權限控制,鉤子提供更廣泛的生命週期整合:

for await (const message of query({
  prompt: "建構功能",
  options: {
    // 細粒度權限控制
    canUseTool: async (toolName, input) => {
      // 根據執行時條件修改輸入或拒絕
      return { behavior: "allow", updatedInput: input };
    },
    
    // 用於監控和自動化的生命週期鉤子
    hooks: {
      PreToolUse: [
        {
          hooks: [
            async (input) => {
              // 記錄、驗證或準備
              return { continue: true };
            }
          ]
        }
      ]
    }
  }
})) {
  // 處理訊息
}

使用 canUseTool 的權限控制

canUseTool 回調提供對工具執行的細粒度控制。它在每次工具使用前被呼叫,可以允許、拒絕或修改工具輸入:

type ToolPermissionResult = 
  | { behavior: "allow"; updatedInput?: any }
  | { behavior: "deny"; message?: string };

for await (const message of query({
  prompt: "分析使用者行為並計算指標",
  options: {
    mcpServers: {
      "analytics": analyticsServer
    },
    canUseTool: async (toolName: string, input: any) => {
      // 控制可以使用哪些工具
      if (toolName.startsWith("mcp__analytics__")) {
        // 檢查分析工具的權限
        const hasPermission = await checkUserPermissions(toolName);
        
        return hasPermission
          ? { behavior: "allow", updatedInput: input }
          : { behavior: "deny", message: "權限不足" };
      }
      
      // 修改某些工具的輸入
      if (toolName === "Bash") {
        // 添加安全檢查或修改命令
        const safeInput = sanitizeBashCommand(input);
        return { behavior: "allow", updatedInput: safeInput };
      }
      
      // 預設允許其他工具
      return { behavior: "allow", updatedInput: input };
    }
  }
})) {
  if (message.type === "result") console.log(message.result);
}

canUseTool 的使用案例

  • 權限管理:在允許工具執行前檢查使用者權限
  • 輸入驗證:在執行前驗證或清理工具輸入
  • 速率限制:對昂貴操作實施速率限制
  • 審計記錄:記錄工具使用以符合合規或除錯需求
  • 動態權限:根據執行時條件啟用/停用工具
// 範例:網頁抓取速率限制器
const rateLimits = new Map<string, { count: number; resetTime: number }>();

const canUseTool = async (toolName: string, input: any) => {
  // 對網頁抓取進行速率限制以防止 IP 封鎖和 API 配額問題
  if (toolName === "WebFetch" || toolName === "WebSearch") {
    const now = Date.now();
    const limit = rateLimits.get(toolName) || { count: 0, resetTime: now + 60000 };
    
    // 每分鐘重置計數器
    if (now > limit.resetTime) {
      limit.count = 0;
      limit.resetTime = now + 60000;
    }
    
    // 每分鐘最多允許 10 個請求
    if (limit.count >= 10) {
      return { 
        behavior: "deny", 
        message: `速率限制超出:每分鐘最多 10 個 ${toolName} 請求。在 ${Math.ceil((limit.resetTime - now) / 1000)} 秒後重置` 
      };
    }
    
    limit.count++;
    rateLimits.set(toolName, limit);
    
    // 記錄抓取活動以進行監控
    console.log(`${toolName} 請求 ${limit.count}/10 到:${input.url || input.query}`);
  }
  
  // 防止 bash 腳本中的意外無限迴圈
  if (toolName === "Bash" && input.command?.includes("while true")) {
    return { 
      behavior: "deny", 
      message: "不允許無限迴圈" 
    };
  }
  
  return { behavior: "allow", updatedInput: input };
};

輸出格式

文字輸出(預設)

// 預設文字輸出
for await (const message of query({
  prompt: "解釋檔案 src/components/Header.tsx"
})) {
  if (message.type === "result" && message.subtype === "success") {
    console.log(message.result);
    // 輸出:這是一個顯示...的 React 元件
  }
}

JSON 輸出

// 收集所有訊息以進行類似 JSON 的存取
const messages = [];
for await (const message of query({
  prompt: "資料層如何運作?"
})) {
  messages.push(message);
}

// 存取帶有元資料的結果訊息
const result = messages.find(m => m.type === "result" && message.subtype === "success");
console.log({
  result: result.result,
  cost: result.total_cost_usd,
  duration: result.duration_ms
});

輸入格式

// 直接提示
for await (const message of query({
  prompt: "解釋這個程式碼"
})) {
  if (message.type === "result" && message.subtype === "success") console.log(message.result);
}

// 從變數
const userInput = "解釋這個程式碼";
for await (const message of query({ prompt: userInput })) {
  if (message.type === "result" && message.subtype === "success") console.log(message.result);
}

代理整合範例

SRE 事件回應代理

import { query } from "@anthropic-ai/claude-code";

// 自動化事件回應代理
async function investigateIncident(
  incidentDescription: string,
  severity = "medium"
) {
  const messages = [];

  for await (const message of query({
    prompt: `事件:${incidentDescription}(嚴重性:${severity}`,
    options: {
      appendSystemPrompt: "你是一位 SRE 專家。診斷問題、評估影響並提供立即行動項目。",
      maxTurns: 6,
      allowedTools: ["Bash", "Read", "WebSearch", "mcp__datadog"],
      mcpConfig: "monitoring-tools.json"
    }
  })) {
    messages.push(message);
  }

  return messages.find(m => m.type === "result" && message.subtype === "success");
}

// 使用方式
const result = await investigateIncident("支付 API 回傳 500 錯誤", "high");
console.log(result.result);

自動化安全審查

import { query } from "@anthropic-ai/claude-code";
import { execSync } from "child_process";

async function auditPR(prNumber: number) {
  // 獲取 PR 差異
  const prDiff = execSync(`gh pr diff ${prNumber}`, { encoding: 'utf8' });

  const messages = [];
  for await (const message of query({
    prompt: prDiff,
    options: {
      appendSystemPrompt: "你是一位安全工程師。審查這個 PR 是否有漏洞、不安全模式和合規問題。",
      maxTurns: 3,
      allowedTools: ["Read", "Grep", "WebSearch"]
    }
  })) {
    messages.push(message);
  }

  return messages.find(m => m.type === "result" && message.subtype === "success");
}

// 使用方式
const report = await auditPR(123);
console.log(JSON.stringify(report, null, 2));

多輪法律助理

import { query } from "@anthropic-ai/claude-code";

async function legalReview() {
  // 開始法律審查會話
  let sessionId: string;

  for await (const message of query({
    prompt: "開始法律審查會話",
    options: { maxTurns: 1 }
  })) {
    if (message.type === "system" && message.subtype === "init") {
      sessionId = message.session_id;
    }
  }

  // 使用相同會話進行多步驟審查
  const steps = [
    "審查 contract.pdf 的責任條款",
    "檢查 GDPR 要求的合規性",
    "生成風險的執行摘要"
  ];

  for (const step of steps) {
    for await (const message of query({
      prompt: step,
      options: { resume: sessionId, maxTurns: 2 }
    })) {
      if (message.type === "result" && message.subtype === "success") {
        console.log(`步驟:${step}`);
        console.log(message.result);
      }
    }
  }
}

訊息模式

從 JSON API 回傳的訊息根據以下模式嚴格類型化:

type SDKMessage =
  // 助理訊息
  | {
      type: "assistant";
      uuid: string;
      session_id: string;
      message: Message; // 來自 Anthropic SDK
      parent_tool_use_id: string | null;
    }

  // 使用者訊息(輸入)
  | {
      type: "user";
      uuid?: string;
      session_id: string;
      message: MessageParam; // 來自 Anthropic SDK
      parent_tool_use_id: string | null;
    }

  // 使用者訊息(輸出/重播,需要 UUID)
  | {
      type: "user";
      uuid: string;
      session_id: string;
      message: MessageParam; // 來自 Anthropic SDK
      parent_tool_use_id: string | null;
    }

  // 成功時作為最後訊息發出
  | {
      type: "result";
      subtype: "success";
      uuid: UUID;
      session_id: string;
      duration_ms: number;
      duration_api_ms: number;
      is_error: boolean;
      num_turns: number;
      result: string;
      total_cost_usd: number;
      usage: Usage;
      permission_denials: SDKPermissionDenial[];
    }

  // 錯誤或最大輪次時作為最後訊息發出
  | {
      type: "result";
      subtype: "error_max_turns" | "error_during_execution";
      uuid: UUID;
      session_id: string;
      duration_ms: number;
      duration_api_ms: number;
      is_error: boolean;
      num_turns: number;
      total_cost_usd: number;
      usage: Usage;
      permission_denials: SDKPermissionDenial[];
    }

  // 在對話開始時作為第一個訊息發出
  | {
      type: "system";
      subtype: "init";
      uuid: UUID;
      session_id: string;
      apiKeySource: "user" | "project" | "org" | "temporary";
      cwd: string;
      tools: string[];
      mcp_servers: {
        name: string;
        status: string;
      }[];
      model: string;
      permissionMode: "default" | "acceptEdits" | "bypassPermissions" | "plan";
      slash_commands: string[];
      output_style: string;
    };

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

額外的支援類型:

MessageMessageParamUsage 類型可在 Anthropic TypeScript SDK 中取得。

相關資源