---
title: 使用 ant apply 以程式碼管理資源
url: https://platform.claude.com/docs/zh-TW/cli-sdks-libraries/cli/apply
description: 將代理、環境、技能、記憶儲存區、部署和保管庫宣告為儲存庫中的檔案，並使用 ant apply 讓 API 的資源與這些檔案保持同步。
---

`ant apply` 會從檔案建立和更新 Claude API 資源：代理、環境、技能、記憶儲存區、部署和保管庫。這些檔案存放在您的儲存庫中，並透過與您的程式碼相同的審查流程進行變更。您在檔案中描述每個資源，執行 `ant apply`，然後核准它顯示的計畫。接著您提交它寫入的 `claude-lock.json`，這樣下次執行時就會更新相同的資源，而不是建立新的資源。

若要安裝 CLI 並進行驗證，請參閱 [CLI 快速入門](https://platform.claude.com/docs/zh-TW/cli-sdks-libraries/cli/quickstart)。`ant apply` 需要 CLI 1.30.0 或更新版本。

## 套用您的第一個代理

將代理撰寫為 `agents/` 下的 Markdown 檔案，然後套用它：

<CodeGroup>
  <CodeGroupItem>
    ```bash CLI
    ant apply agents/summarizer.md
    ```

    <File filename="agents/summarizer.md">
      ```markdown
      ---
      name: Summarizer
      model: claude-opus-5-5
      tools:
        - type: agent_toolset_20260401
      ---

      You are a helpful assistant that writes concise summaries.
      ```
    </File>
  </CodeGroupItem>
</CodeGroup>

「Frontmatter」（前置資料）包含代理的設定（即[定義您的代理](https://platform.claude.com/docs/zh-TW/managed-agents/agent-setup)中的欄位），主體則是代理的「system prompt」（系統提示）。`ant apply` 會根據檔案的路徑（此處為 `agents/` 目錄）[推斷](https://platform.claude.com/docs/zh-TW/cli-sdks-libraries/cli/apply#kind-inference)該檔案是一個代理。

在互動式終端機中，`ant apply` 會印出計畫並等待您核准：

```text Output wrap
First apply  ./claude-lock.json does not exist yet and will be created

Resources will be created with
  credentials   API key (--api-key / ANTHROPIC_API_KEY)
  host          api.anthropic.com
  organization  1b0c2a4d-6c1f-4f0e-9a57-2e8d1c3b4a5f
  workspace     wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ

Preview  ./claude-lock.json (new)

± Name                    Plan
+ ./agents/summarizer.md  create

Resources  + 1 to create

Apply these changes? (y)es / (n)o / (d)etails y

Apply  ./claude-lock.json

± Name                    Status
+ ./agents/summarizer.md  created    agent_011CYm1BLqPXpQRk5khsSXrs

Resources  + 1 created

State written to ./claude-lock.json
```

回答 `d` 可先查看詳細資訊，包括每個新資源的欄位，或每項更新的逐欄位差異。`--dry-run` 會印出該詳細計畫後直接結束，不會變更任何內容。

若要變更代理，請編輯檔案並再次執行 `ant apply`。此時計畫會顯示更新，而非建立。

## 提交 claude-lock.json

第一次執行 `ant apply` 時，會在您執行命令的目錄中寫入 `claude-lock.json`，也就是「lockfile」（鎖定檔），因此請從儲存庫根目錄執行。它會記錄每個檔案所建立資源的 ID，以及這些資源所屬的組織和工作區：

```json claude-lock.json
{
  "version": 1,
  "origin": {
    "base_url": "https://api.anthropic.com",
    "organization_id": "1b0c2a4d-6c1f-4f0e-9a57-2e8d1c3b4a5f",
    "workspace_id": "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ"
  },
  "resources": {
    "./agents/summarizer.md": {
      "kind": "agent",
      "id": "agent_011CYm1BLqPXpQRk5khsSXrs",
      "version": "1",
      "hash": "d23251c8d99b3613a64f3f8d87f5fad4",
      "remote_hash": "1b771bee5bdbf600a5ad972fdac32d94"
    }
  }
}
```

請將它與您的檔案一起提交。下一次執行（無論是在您的機器上還是在 CI 中）會透過它找到這些資源，而不會再次建立。您也可以從中讀取代理的 ID 來[啟動工作階段](https://platform.claude.com/docs/zh-TW/managed-agents/sessions)。其中的兩個雜湊值分別是上次傳送內容與 API 回傳內容的指紋。後續執行就是藉此察覺檔案已被編輯，或資源已在這些檔案之外遭到變更。

## 擴展為專案

您也可以用宣告方式將其他資源定義為檔案。檔案的內容就是您會傳送到該類型建立端點的請求主體：

* [環境](https://platform.claude.com/docs/zh-TW/managed-agents/environments)是 `environments/` 中的 YAML 檔案。
* [記憶儲存區](https://platform.claude.com/docs/zh-TW/managed-agents/memory)是 `memory_stores/` 中的 YAML 檔案。
* [部署](https://platform.claude.com/docs/zh-TW/managed-agents/scheduled-deployments)是 `deployments/` 中的 Markdown 檔案：frontmatter 是請求主體，內文則成為啟動每個工作階段的訊息。
* [技能](https://platform.claude.com/docs/zh-TW/managed-agents/skills)是根目錄含有 `SKILL.md` 的目錄，慣例上放在 `skills/` 下，並以單一套件上傳。
* [保管庫](https://platform.claude.com/docs/zh-TW/managed-agents/vaults)是 `vaults/` 中的 YAML 檔案，其唯一的欄位是 `display_name` 以及選用的 `metadata`。保管庫檔案需要 CLI 1.34.0 或更新版本。

除了技能之外，任何資源都可以用 YAML、JSON 或 Markdown 撰寫。在 Markdown 中，frontmatter 是請求主體，內文則填入該類型的文字欄位：代理的 `system`、環境或記憶儲存區的 `description`、部署的第一則訊息。保管庫沒有文字欄位，因此 `ant apply` 會拒絕含有內文的保管庫 Markdown 檔案。

資源之間透過路徑互相參照。凡是 API 需要另一個資源 ID 的地方，請改為填寫該資源檔案的相對路徑。在此專案中，reviewer 代理在 `skills` 下列出 `../skills/pr-summary`，lead 代理在其成員名單中列出 `./reviewer.md`，部署則透過路徑指定其代理、環境和記憶儲存區。`ant apply` 會依相依順序建立這些資源，並填入實際的 ID。此專案共有六個檔案：

<FileExplorer>
  <File filename="agents/reviewer.md">
    ```markdown
    ---
    name: Code reviewer
    model: claude-opus-5-5
    tools:
      - type: agent_toolset_20260401
    skills:
      - ../skills/pr-summary
    ---

    You review pull requests for correctness, security, and readability.
    ```
  </File>

  <File filename="agents/lead.md">
    ```markdown
    ---
    name: Engineering lead
    model: claude-opus-5-5
    multiagent:
      type: coordinator
      agents:
        - ./reviewer.md
    ---

    You coordinate engineering work. Delegate code review to the reviewer.
    ```
  </File>

  <File filename="skills/pr-summary/SKILL.md">
    ```markdown
    ---
    name: pr-summary
    description: Summarize a pull request's changes and risks in the team's review format.
    ---

    # PR summary

    List what changed, why, and anything a reviewer should look at closely, in three short sections.
    ```
  </File>

  <File filename="environments/cloud.yaml">
    ```yaml
    # yaml-language-server: $schema=https://platform.claude.com/schemas/ant/beta/environment.json
    name: review-env
    description: Cloud container with limited networking for review sessions.
    config:
      type: cloud
      networking:
        type: limited
        allow_package_managers: true
    ```
  </File>

  <File filename="memory_stores/review-notes.yaml">
    ```yaml
    # yaml-language-server: $schema=https://platform.claude.com/schemas/ant/beta/memory_store.json
    name: Review notes
    description: Recurring issues and house-style decisions the reviewer has recorded between runs.
    ```
  </File>

  <File filename="deployments/nightly.md">
    ```markdown
    ---
    name: Nightly review
    agent: ../agents/reviewer.md # the API's agent field: sent as {type: agent, id, version}
    environment_id: ../environments/cloud.yaml # sent as the environment's ID
    resources:
      - path: ../memory_stores/review-notes.yaml
        access: read_write
    schedule:
      type: cron
      expression: "0 3 * * *"
      timezone: America/Los_Angeles
    ---

    Review any open pull requests. Start with the oldest.
    ```
  </File>
</FileExplorer>

套用整個目錄：

```bash CLI
ant apply .
```

完成後，`claude-lock.json` 會包含專案中每個檔案的項目。

這些檔案透過相對路徑互相指向。`ant apply` 會將代理和技能的參照固定到它剛套用的版本，因此當您編輯 `reviewer.md` 或技能時，所有參照它們的資源都會在同一次執行中一併更新。路徑也可以用在物件內，例如部署的 `resources` 項目，其中 `access` 等其他鍵會保持不變。

若要指向不由這些檔案管理的資源，請改為填寫其 ID（`agent_...`、`skill_...`）。其他任何內容，例如 `{type: anthropic, skill_id: xlsx}`，都會原樣傳送到 API。技能參照也可以是 `https://github.com/<owner>/<repo>/tree/<branch>/<dir>` 形式的 GitHub URL，例如 Anthropic 開源[技能儲存庫](https://github.com/anthropics/skills)中的某個目錄。`ant apply` 會下載並上傳該目錄，並將其固定在解析出的 commit，直到您使用 `--upgrade` 執行為止（若為私人儲存庫，請設定 `GITHUB_TOKEN`）。

### ant apply 如何推斷檔案的類型

`ant apply` 走訪目錄時，會依下列條件的順序，以第一個符合的條件判斷每個檔案的類型：

1. 檔案中的頂層 `type` 欄位。
2. 檔案直接所在的目錄：`agents/`、`environments/`、`memory_stores/`、`deployments/` 或 `vaults/`。
3. 以類型開頭的檔案名稱，例如 `environment_staging.md`。
   * 保管庫是例外：`ant apply` 不會從 `vault_staging.yaml` 這類名稱取得類型，因為其他工具會將其機密檔案命名為 `vault.yml`。請將保管庫檔案放在 `vaults/` 中，或為其加上 `type: vault`。

不符合任何條件的檔案（例如 README 和 CI 設定）會被略過，除非您在命令列上明確指定。若明確指定的 Markdown 檔案不符合任何條件，會被視為代理；若明確指定的 YAML 或 JSON 檔案不符合任何條件，則會產生錯誤。

## 編輯並重新套用

不帶引數執行 `ant apply` 時，會同步 lockfile 所追蹤的每個檔案。在終端機中，它也會列出 lockfile 所在目錄下尚未追蹤的資源檔案，並詢問是否要加入。若您從檔案中刪除某個欄位，且 API 允許清除該欄位，資源上的該欄位就會被清除。您從未設定過的欄位，或 API 無法清除的欄位，則會保留目前的值。

如果資源在這些檔案之外（例如在 Claude Console 中）遭到編輯、封存或刪除，計畫的結尾會顯示 `This plan cannot be applied:` 及原因，接著命令會以 `refusing to apply` 結束。傳入 `--force` 可覆寫該編輯，或建立替代資源。

刪除檔案時，其資源會保留下來並顯示警告，使用 `--prune` 則會移除該資源（一般資源會被封存，技能則會被刪除）。因此，重新命名檔案等同於宣告一個新資源，舊資源會一直保留，直到您執行 prune 為止。

`ant apply` 無法接管您在 Console 中或使用 `ant beta:agents create` 建立的資源。只有 lockfile 中記錄的資源才會受到管理，因此套用一個描述現有代理的檔案，會建立出第二個代理。如果您是透過 Console 的 **Export as code** 下載代理，下載內容會附帶專屬的 `claude-lock.json`，因此套用它會更新您在 Console 中建立的資源。

## 在 CI 中執行 ant apply

在沒有終端機的環境中，`ant apply` 會印出計畫，然後以 `cannot ask for confirmation without a terminal; re-run with --yes to apply, or --dry-run to see the plan only` 停止。請依下列方式設定 CI：

* 合併後，在預設分支上執行 `ant apply --yes .`，並指定專案目錄。若只執行 `ant apply --yes`，則只會同步 lockfile 已追蹤的檔案，新加入的檔案會被略過。
* 在 pull request 上執行 `ant apply --dry-run .`，為審查者印出計畫。此步驟僅供參考，即使計畫遭到阻擋，也會以 0 結束。
* 在工作結束時提交更新後的 `claude-lock.json`，即使套用步驟中途失敗也要提交，因為部分完成的套用仍會記錄已建立的資源。
* 一次只執行一個套用作業，因為沒有任何機制會鎖定 lockfile。
* 使用「Workload Identity Federation」（工作負載身分聯合）進行驗證，而非使用儲存的 API 金鑰，且所用身分必須能存取 `claude-lock.json` 中記錄的組織和工作區。詳情請參閱 [Workload Identity Federation](https://platform.claude.com/docs/zh-TW/manage-claude/workload-identity-federation)。`ant apply` 會拒絕解析到其他組織或工作區的憑證。

如需完整的 GitHub Actions 工作流程，請參閱 [CLI README 中的 CI 範例](https://github.com/anthropics/anthropic-cli#in-ci)。

## 旗標

| 旗標                   | 效果                                                                                                 |
| -------------------- | -------------------------------------------------------------------------------------------------- |
| `--dry-run`          | 印出計畫後結束，不會套用變更，也不會寫入 lockfile。即使計畫遭到阻擋，也會以 0 結束。                                                   |
| `--yes`              | 不經確認直接套用。在沒有終端機的環境中為必要選項。                                                                          |
| `--force`            | 即使資源已在這些檔案之外遭到變更、封存或刪除，仍強制套用。                                                                      |
| `--prune`            | 移除仍記錄在 lockfile 中、但已不再於任何檔案中宣告的資源。                                                                 |
| `--upgrade`          | 重新解析透過 GitHub URL 參照的技能；若未使用此旗標，這些技能會維持固定在 lockfile 中記錄的 commit。                                   |
| `--lock-file <path>` | 使用指定的 lockfile，而不是從目前目錄往上層搜尋。請為每個組織或工作區各保留一個 lockfile：若 lockfile 的組織或工作區與您的憑證不符，`ant apply` 會拒絕使用。 |
| `--verbose`、`-v`     | 在計畫中顯示未變更的資源及完整的欄位值。                                                                               |

## 後續步驟

<CardGroup cols={3}>
  <Card title="啟動工作階段" icon="terminal" href="https://platform.claude.com/docs/zh-TW/managed-agents/sessions">
    從 CLI 或 SDK 執行您已套用的代理
  </Card>

  <Card title="排程部署" icon="clock" href="https://platform.claude.com/docs/zh-TW/managed-agents/scheduled-deployments">
    部署欄位、執行歷程記錄與暫停
  </Card>

  <Card title="CLI 指令碼與自動化" icon="code" href="https://platform.claude.com/docs/zh-TW/cli-sdks-libraries/cli/scripting">
    指令碼撰寫模式，以及在 Claude Code 中的使用方式
  </Card>
</CardGroup>
