# ch10: CLI 進階 Flags + Agent SDK

## 30. CLI 進階 Flags 與互動命令（cli-reference.md / interactive-mode.md）

### Shell Script 中呼叫 Claude（Headless 模式）

```bash
# 必須先 unset，否則在 CC 環境內報錯
unset CLAUDECODE

# 基本 headless 呼叫（-p = --print = 無互動）
claude -p "分析 $FILE" --model claude-sonnet-4-6

# JSON 輸出，提取 result
RESULT=$(claude -p "生成摘要" --output-format json | jq -r '.result')

# 多步驟對話（保留 session context）
SESSION=$(claude -p "Step 1：列出問題" --output-format json | jq -r '.session_id')
claude -p "Step 2：修正問題" --resume "$SESSION" --output-format json | jq -r '.result'

# 成本上限（CI 安全，超過就中止）
claude -p "..." --max-budget-usd 2.00

# 不儲存 session（CI/CD 避免殘留）
claude -p "..." --no-session-persistence

# 限制 agentic loop 回合數（未文件化但有效！）
claude -p "..." --max-turns 1     # 只執行 1 輪不繼續 loop
```

### 未常見的 CLI Flags

```bash
# 工作目錄
claude --add-dir /extra/path           # 增加額外目錄（不改 cwd）

# Session 精確控制
claude --fork-session                   # --resume 時建立新 session ID（保留 context）
claude --session-id <uuid>             # 指定 session ID（而非隨機生成）
# ⚠️ --continue / --fork-session：對話歷史保留，但 session-scoped permissions 完全遺失！
# → 用戶之前核准的操作需要在新 session 重新核准（permissions 是 runtime 狀態）
claude --include-partial-messages      # headless：包含 streaming 中間事件
claude --input-format stream-json      # 指定輸入格式

# 初始化與維護（CI/排程用）
claude --init-only     # 執行 init hooks 後退出（環境驗證）
claude --maintenance   # 執行 maintenance hooks 後退出（夜間維護）

# MCP 精確控制
claude --mcp-config ./mcp.json            # 從指定檔案載入 MCP
claude --strict-mcp-config               # 只用 --mcp-config MCPs，忽略其他
claude --permission-prompt-tool my_mcp   # headless：用 MCP tool 處理 permission

# 設定層級
claude --setting-sources user,project    # 指定載入哪些設定層
claude --settings ./custom.json          # 額外設定（覆蓋/補充）

# 其他
claude --disable-slash-commands          # 停用所有 skills（CI 安全）
claude --betas interleaved-thinking      # beta features（API key 限定）
claude --teammate-mode auto|in-process|tmux  # Agent team 顯示模式
claude --teleport                        # web session → 本機 terminal

# 速度最佳化（v2.1.81 新增）
# --bare：跳過所有初始化（hooks/LSP/plugins/skill scan/auto-memory），大幅加速 scripts
# 限制：必須搭配 ANTHROPIC_API_KEY（不支援 OAuth/keychain），auto-memory 完全停用
# 適用：heartbeat scripts 等不需要 hooks 的無狀態 headless 呼叫
ANTHROPIC_API_KEY="..." claude -p "..." --bare   # 比標準 -p 更快

# Debug 類別過濾
claude --debug "api,mcp"                 # 只顯示指定類別
claude --debug "!statsig,!file"          # negation 排除類別

# Auth
claude auth login --email user@a.com --sso  # SSO 登入
claude auth status --text               # 純文字輸出
claude agents                           # 列出所有 subagents
```

### 互動模式 Slash Commands（補充）

```
/copy               — 複製最後一則回覆（多個 code block 顯示 picker）
/export [filename]  — 匯出對話為純文字
/context            — 彩色格子視覺化 context 使用量
/fork [name]        — 從當前點 fork 對話（類似 git branch）
/stats              — 每日使用量、streak、模型偏好圖表
/usage              — 方案上限 + rate limit 狀態
/extra-usage        — 設定額外 rate limit
/tasks              — 列出管理背景任務
/insights           — CC session 使用模式分析報告
/pr-comments [PR]   — 擷取 GitHub PR 評論進 context
/review             — review PR 品質/安全
/security-review    — 分析 pending changes 安全漏洞
/privacy-settings   — 隱私設定（Pro/Max）
/release-notes      — 完整 changelog
/remote-env         — 設定預設遠端環境
/mobile             — QR code 連接 mobile app
/passes             — 分享免費週（Pro plan）
/plan [description] — 進入 Plan Mode（v2.1.72：可直接帶描述，如 `/plan fix the auth bug`）
```

### 指令別名
```
/reset, /new        → /clear
/config, /settings  → 設定（同一個）
/desktop, /app      → Desktop connector
/rewind, /checkpoint → rewind 功能
```

### 新環境變數
```bash
CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1      # 停用背景任務
CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false  # 停用 prompt 建議
CLAUDE_CODE_TASK_LIST_ID=my-project         # 跨 session 共享 task list
```

### PR 狀態欄
Footer 彩色底線：🟢 passed / 🟡 pending / 🔴 failed / ⚪ draft / 🟣 merged，每 60 秒自動更新。

### `--maintenance` Night Agent 用途
```bash
claude --maintenance   # 執行 PreMaintenance + PostMaintenance hooks 後退出
# 適合 launchd plist: ExitProgramArgument = ["claude", "--maintenance"]
```

---


---

## Always Check
- SQL injection / XSS in user input handling
- Auth bypass conditions

## Style
- Follow existing naming conventions
- No unused imports

## Skip
- Autogenerated files: dist/, generated/
```

### 監控使用量

```
claude.ai/analytics/code-review
```
- PR 審查數、weekly cost、feedback rate、per-repo 細分
- 設月消費上限：`claude.ai/admin-settings/usage`

### PR 規模與 Finding 統計

- 大型 PR（>1000 行）：84% 有 findings，平均 7.5 issues
- 小型 PR（<50 行）：31% 有 findings，平均 0.5 issues

### 本機 Plugin（不需 Team/Enterprise）

```bash
/plugin install code-review@claude-code-plugins
/code-review   # 推送前手動觸發
```

### 限制

- 不支援 ZDR（Zero Data Retention）
- 約 20 分鐘完成，不適合作為 merge gate

### 與手動 @claude 觸發的差異

| | 自動 PR Review | 手動 `@claude` |
|--|--|--|
| 觸發 | PR open/push | PR comment |
| 費用 | $15-25/review | 依任務規模 |
| 適合 | 所有 PR 一致性審查 | 特定問題追問 |
| 設定 | Admin 啟用 | `/install-github-app` |

---

## 32. Claude Agent SDK（程式化 Agent）

前身為 Claude Code SDK，讓 Claude 在程式中自主操作工具完成任務。

### 安裝

```bash
pip install claude-agent-sdk           # Python
npm install @anthropic-ai/claude-agent-sdk  # TypeScript
```

### vs Client SDK vs CLI

| | Agent SDK | Client SDK | CLI (claude -p) |
|--|--|--|--|
| 工具迴圈 | 自動處理 | 手動 tool_call | 自動處理 |
| 內建工具 | ✅ Read/Write/Bash 等 | ❌ | ✅ |
| 適用 | CI/CD、Production | 簡單 API 呼叫 | 腳本、一次性 |

### 認證注意

```python
agent = ClaudeAgent(api_key=os.environ["ANTHROPIC_API_KEY"])
```

**重要**：只能用 API key，**不支援** claude.ai OAuth 登入。
Free/Pro/Max 帳號的 rate limit **不適用**於 Agent SDK。

### 基本用法

```python
import asyncio
from claude_agent_sdk import ClaudeAgent

async def main():
    agent = ClaudeAgent()
    result = await agent.run("分析 src/ 並寫摘要")
    print(result)

asyncio.run(main())
```

### Sessions（對話續接）

```python
r1 = await agent.run("分析 auth.py")
session_id = r1.session_id
r2 = await agent.run("為上面的函式寫測試", session_id=session_id)
```

### Subagents（AgentDefinition）

```python
from claude_agent_sdk import AgentDefinition

reviewer = AgentDefinition(
    name="code-reviewer",
    tools=["Read", "Glob", "Grep"],   # 限制工具
    system_prompt="嚴格審查程式碼..."
)
result = await agent.run("審查變更", subagents=[reviewer])
```

### Hooks

```python
@agent.hook(HookType.PRE_TOOL_USE)
async def before_tool(tool_name, tool_input):
    # return {"action": "block"} 可阻止
    pass

@agent.hook(HookType.STOP)
async def on_stop(result): pass
```

Hook 類型：PRE_TOOL_USE / POST_TOOL_USE / STOP / SESSION_START / SESSION_END

### 常用選項

```python
agent = ClaudeAgent(
    allowed_tools=["Read", "Glob"],   # 只允許讀取
    disallowed_tools=["Bash"],
    max_budget_usd=2.00,              # 成本上限
    mcp_servers=[MCPServerConfig(...)]
)
```

---

