# 代理工具

URL: https://swb.one/zh-Hant/docs/setup/agent-tool

## 複製設定提示詞 [#setup-prompt]

https://swb.one/prompts/agent-tool.md

````
Read the setup guide at https://swb.one/docs/setup/agent-tool.

Help me connect my agent tool to SwB.
SwB carries messages and stores shared memory.

Ask me which chat apps already reach my agent.
Tell me that my existing chat connections stay the same.
Keep the existing Telegram bot settings.
Keep the existing WeChat ClawBot settings and binding.
Use one active receiver per Telegram bot token.
Run one WeChat ClawBot instance per binding.
Pair my agent with SwB over MCP as a separate connection.
Use MCP Events or a local webhook for notices about new messages.
If I want a direct Telegram connection to SwB, use a separate bot with a new token.
Use the Telegram setup guide at https://swb.one/docs/setup/telegram.

Ask me to choose a name for the agent.
Use up to 40 lowercase letters, digits and dashes.
Start with a letter or digit.
Use my chosen name in place of `my-tool`.
Use a SwB client with owner access for setup.
Call `connect(what="agent-tool", choose={"agent":"my-tool"})`.
Alternatively, run this command in my SwB folder.

```sh
swb connect agent-tool --choose agent=my-tool
```

Keep the existing key if the client already has one.
If SwB returns a pairing code, redeem it in a private terminal within ten minutes.
Use `POST /connect`.
Send `{"code":"<pairing code>"}` in the request body.
Send a `User-Agent` header that names the app on each HTTP request to SwB.
Read the response in memory.
Add a server named `swb` in the client settings.
Use `mcp_url` as the Streamable HTTP address.
Streamable HTTP lets the app call SwB tools over the network.
Use the returned `key` in the `Authorization: Bearer <key>` header.
Store the key in the app's private settings.
Keep credentials private.

## Messages

Use MCP to read messages, send replies and share memory.
Use `wait` or `inbox` to read messages from an open conversation.

## Personal agents

MCP Events sends a notice when a message arrives.
Call `events/list` to see the events SwB offers.
Use `events/subscribe` for `switchboard.message.created` with `mailbox_id` set to my agent name.
Use webhook delivery with a public HTTPS callback address.
A callback is the address that receives notices.
Use a secret with the prefix `whsec_` and a base64 value that decodes to 24 to 64 bytes.
Use the same secret to verify Standard Webhooks signatures at the callback.
Read the message with `get_message`.
Answer with `reply` and the conversation handle.

For a local webhook, pair the companion with the webhook feature.
A webhook receives messages at a web address.
Save the webhook configuration in `~/.config/swb/webhook/my-tool.json`.
Use my chosen agent name in the file name and the `name` field.
Set the required `key_env` field to a `SWB_KEY_<NAME>` variable.
Save my agent's paired SwB key in that variable on the companion device.
The companion uses this key to register the delivery route with SwB.
Use a loopback address or an address on a private or shared network.
A loopback address reaches the same device.
A shared address is in the `100.64.0.0/10` range.
Use a separate receiver secret to sign messages or send a bearer token.
Give the receiver and the companion the same receiver secret.
On the companion device, save it in the variable named in `secret_env`.
For `standard-webhooks`, use the same secret format as for MCP Events.
For a receiver that expects a bearer token, set `auth` to `bearer`.
For bearer tokens, use an HTTP loopback address or an HTTPS address.

```sh
swb companion connect https://swb.example.com --cap webhook
```

```json
{"name":"my-tool","url":"http://127.0.0.1:8644/webhooks/swb","auth":"standard-webhooks","key_env":"SWB_KEY_MY_TOOL","secret_env":"SWB_WEBHOOK_MY_TOOL"}
```

Use the handle from the webhook to answer with `reply`.
Call `inbox` when the agent starts.
The mailbox keeps messages if webhook delivery fails.
Use one delivery method per mailbox.

## Status hooks

Use a status hook if the tool can run a command when a session changes.
Use the same agent name in the command and in MCP.
Pair the device with a companion if I want to use status hooks or a driver.
A companion is a SwB program that connects this device to my SwB server.
Install the `swb` command with `pipx install swb.one`.
Use `companion_code` from the owner client.
Enter the code at the companion's hidden prompt.
Replace the example address with my SwB address.
Add one option for each feature I use.

```sh
swb companion connect https://swb.example.com --cap hooks --cap ade
```

Send one JSON object to `swb hook <name>` on standard input.
Use the session ID from the tool.
Use the folder and label from the session.
Set `event` to `start`, `working`, `blocked`, `idle`, `done` or `ended`.
Include `text` for the answer on a `done` event.

```json
{"event":"done","session":"session-1","name":"My session","dir":"/path/to/project","text":"Test complete"}
```

If a plugin can deliver messages to the session, read wakes from `swb hook <name> --wakes <session>`.
A wake is a message for an open session.
Read one JSON object per line.
Use the tool's supported interface to deliver the `text` to the session.

## CLI session driver

Use a driver if the tool has commands to list and message open sessions.
A driver is a file that maps SwB operations to commands from the tool.
Use Linux or macOS for a custom driver.
Save the driver as a JSON file in `~/.config/swb/ade/`.
Use `$XDG_CONFIG_HOME/swb/ade/` if that environment variable is set.
The account that runs the companion must own the folder and file.
Set `name` to the same agent name.
Set `available`, `list` and `send` to the tool's commands.
Use `argv` to list each command and its arguments separately.
Use JSON output for the session list and reply.
Map the session ID, label, folder and state from the list response.
In `send`, use `{session}` as a separate argument for the session ID.
Use `"stdin": "text"` or put `{text}` immediately after a separate `--` argument.
Use `check` to confirm a session is idle before sending.
Use `wait` and `read` when the tool returns its reply from a separate command.
Use only the tool's documented commands.

Use this example for the structure.
Replace the example commands and JSON fields with those of my tool.

```json
{
  "name": "my-tool",
  "available": {"argv": ["my-tool", "status", "--json"]},
  "list": {
    "argv": ["my-tool", "sessions", "--json"],
    "sessions": "sessions",
    "id": "id",
    "name": "label",
    "dir": "folder",
    "state": "status",
    "states": {"ready": "idle", "running": "working", "approval": "blocked"}
  },
  "check": {
    "argv": ["my-tool", "sessions", "show", "{session}", "--json"],
    "expect": {"id": "{session}", "status": "ready"}
  },
  "send": {
    "argv": ["my-tool", "sessions", "send", "{session}", "--json", "--", "{text}"],
    "reply": "answer"
  }
}
```

Replace `my-tool` with my agent name in the file name.
Set these permissions for new and existing manifests before you call `targets`.
The folder needs mode `0700`. The file needs mode `0600`.

```sh
chmod 00700 "${XDG_CONFIG_HOME:-$HOME/.config}/swb/ade"
chmod 0600 "${XDG_CONFIG_HOME:-$HOME/.config}/swb/ade/my-tool.json"
```

Call `targets(block="local")` from the owner client.
Send a test message to the session address returned by `targets`.
Read the answer with `result` and the conversation from `send`.

## Check the connection

Call `inbox` from the paired client.
Call `swb_guide(trigger="setup")` from the same client.
From the owner client, use `send` to send a test message to `agent:my-tool`.
Replace `my-tool` with my chosen name.
Read it with `inbox` from the paired client.
Answer with `reply` and the item's handle.
Read the answer from the owner client with `result` and the conversation from `send`.

Call `memory_summary` from the paired client.
Read the tool's shared notes, such as `AGENTS.md`.
Select facts to share.
Keep credentials and private details on the device.
Use `memory_sync` with `source="agents-md"`.
Give each fact a stable `source_key`.
Use the project slug for project memory.
````

把提示詞貼給以 SwB 擁有者身分登入的代理。

MCP 是應用程式使用外部工具的方式。為代理選個簡短的名稱。請以擁有者身分登入的代理依下方範例呼叫 `connect`。

```python
connect(what="agent-tool", choose={"agent":"example-agent"})
```

名稱最多 40 個字元，可用小寫英文字母、數字和連字號。開頭請用小寫英文字母或數字。

收到配對碼後，換取[代理金鑰](/zh-Hant/docs/setup/mcp-client#取得金鑰)。這樣 SwB 就能向同名的本機工作階段傳送訊息。

<Tabs items={['MCP', '本機工作階段']}>
<Tab value="MCP">
將 SwB 回傳的設定加入應用程式。將金鑰儲存在應用程式的私有設定中。SwB 會以你選的名稱顯示代理。

從另一個 SwB 應用程式傳送一則測試訊息。在已連接的應用程式中呼叫 `inbox`。用收到的 `handle` 呼叫 `reply` 回覆。

應用程式也可以透過[收件匣事件串流](/zh-Hant/docs/connect#收件匣事件串流)接收訊息。
</Tab>
<Tab value="本機工作階段">
若應用程式提供列出工作階段和傳送訊息的指令，請用[驅動程式](#driver-manifest)。若應用程式能在狀態改變時執行指令，請用[狀態掛鉤](#status-hooks)。

依照[配對裝置](/zh-Hant/docs/companion#配對裝置)的說明操作。

請以擁有者身分登入的代理呼叫 `targets(block="local")`。傳送測試訊息給回傳的完整位址 `local:session:<companion>:<harness>:<session>`。用 `result` 查看回覆。
</Tab>
</Tabs>

## 個人代理 [#personal-agents]

MCP Events 會在新訊息送達時傳送通知。回呼網址用來接收通知。

透過 `events/list` 查看可用事件。用 `events/subscribe` 訂閱 `switchboard.message.created`。將 `mailbox_id` 設為配對時選的代理名稱。

使用 Webhook 傳遞時，請使用公開 HTTPS 回呼網址。密鑰由 `whsec_` 前綴和 base64 值組成。base64 部分解碼後應為 24 至 64 位元組。接收端使用同一把密鑰驗證 Standard Webhooks 簽章。

用通知中的 `message_id` 呼叫 `get_message` 讀取訊息。用對話識別碼呼叫 `reply` 回覆。

應用程式在同一部裝置或私有網路上接收訊息時，使用 [Companion 的本機 Webhook](/zh-Hant/docs/companion#local-webhook)。

```sh
swb companion connect https://swb.example.com --cap webhook
```

用配對取得的 SwB 金鑰授權傳遞路由。在 `key_env` 填入儲存這把金鑰的 `SWB_KEY_<NAME>` 變數名稱。另用一把接收端密鑰簽署訊息或作為 Bearer 權杖。

每個信箱選用一種傳遞方式。

### 保留現有的聊天連線 [#existing-channels]

告訴負責設定的代理，哪些聊天應用程式已連到你的代理。

保留現有 Telegram 機器人的設定。保留現有 微信 ClawBot 的設定和綁定。每個 Telegram 機器人權杖只由一個程式接收訊息。每個綁定只執行一個 微信 ClawBot 執行個體。

透過 MCP 將代理另外配對到 SwB。用 MCP Events 或本機 Webhook 接收新訊息通知。若要將 Telegram 直接連到 SwB，請用新權杖[另設一個機器人](/zh-Hant/docs/setup/telegram)。

## 驅動程式設定檔 [#driver-manifest]

將驅動程式設定儲存為 JSON 檔案。儲存目錄為 `$XDG_CONFIG_HOME/swb/ade/`。預設目錄為 `~/.config/swb/ade/`。

在 Linux 或 macOS 上使用自訂驅動程式。目錄和檔案須由執行 Companion 的帳號擁有。把 `example-agent` 換成你的代理名稱。將目錄權限設為 `0700`。將檔案權限設為 `0600`。既有設定也適用這些權限。

```sh
chmod 00700 "${XDG_CONFIG_HOME:-$HOME/.config}/swb/ade"
chmod 0600 "${XDG_CONFIG_HOME:-$HOME/.config}/swb/ade/example-agent.json"
```

| 欄位 | 用途 |
| - | - |
| `name` | SwB 使用的代理名稱 |
| `available` | 檢查工具是否可用的指令 |
| `list` | 列出工作階段的指令，以及名稱和狀態等欄位在輸出中的位置 |
| `check` | 傳送前確認工作階段狀態的指令 |
| `send` | 將訊息交給工作階段的指令 |
| `wait`, `read` | 等候工作階段完成及讀取回覆的指令 |

在 `sessions` 填入陣列的位置。如果輸出本身就是陣列，請填空字串。在 `id`、`name`、`dir` 和 `state` 填入各欄位的位置。在 `states` 將工具的狀態對應至 SwB 的狀態。

在 `argv` 陣列中填入指令與參數。在 `send` 中把 `{session}` 當成單一參數。把 `{text}` 放在參數 `--` 的正後方，或設定 `"stdin": "text"`，透過標準輸入傳送訊息。

以下是 Paseo 的傳送指令範例。

```json
{
  "send": {
    "argv": ["paseo", "send", "{session}", "--no-wait", "--json", "--", "{text}"],
    "expect": {
      "agentId": "{session}",
      "status": "sent"
    }
  }
}
```

若要從傳送指令的輸出讀取回覆，請使用 `send.reply`。若用另一個指令讀取回覆，請使用 `read.reply`。

請參閱[內建驅動程式範例](https://github.com/ZhehanZhang/SwB/tree/release/1.0/src/switchboard/companion/caps/ade_presets)。

在使用驅動程式的裝置上啟動 Companion。把範例網址換成你的 SwB 網址。

```sh
swb companion connect https://swb.example.com --cap ade
```

## 狀態掛鉤 [#status-hooks]

掛鉤是工作階段狀態改變時執行的指令。用 `--cap hooks` 啟動 Companion。在應用程式中執行 `swb hook <name>`，透過標準輸入傳入一個 JSON 事件。`<name>` 是 SwB 使用的代理名稱。

```sh
swb companion connect https://swb.example.com --cap hooks
```

同一工作階段的各個事件使用相同的 `session`。

```json
{"event":"start","session":"example-session","name":"Example session","dir":"/path/to/workspace"}
```

`event` 可填 `start`、`working`、`blocked`、`idle`、`done` 或 `ended`。傳送 `done` 事件時，請將回覆填入 `text`。

為每個已開啟的工作階段執行 `swb hook <name> --wakes <session>`。這個指令為每則訊息輸出一行 JSON，其中包含 `text` 和 `conversation`。透過應用程式的 API 將文字交給工作階段。串流開啟前，訊息會留在代理的信箱。
