@dotlabo/agent-chat-relay 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +132 -2
- package/bin/agent-chat-relay +22 -0
- package/package.json +65 -4
- package/src/connectors/chatwork.ts +289 -0
- package/src/connectors/common.ts +106 -0
- package/src/connectors/discord.ts +335 -0
- package/src/connectors/http.ts +137 -0
- package/src/connectors/line-media.ts +63 -0
- package/src/connectors/line.ts +444 -0
- package/src/core/access.ts +240 -0
- package/src/core/instructions.ts +21 -0
- package/src/core/mcp.ts +160 -0
- package/src/core/relay.ts +949 -0
- package/src/core/retention.ts +44 -0
- package/src/harness/config.ts +137 -0
- package/src/harness/harness.ts +254 -0
- package/src/harness/log-file.ts +34 -0
- package/src/harness/pi/config.ts +49 -0
- package/src/harness/pi/state.ts +97 -0
- package/src/harness/pi/tool-approval.ts +70 -0
- package/src/home.ts +67 -0
- package/src/jev.ts +201 -0
- package/src/main.ts +255 -0
- package/src/prompt.ts +12 -0
- package/src/serve-args.ts +56 -0
- package/src/shutdown.ts +52 -0
- package/src/vendor/pi/adapter.js +3223 -0
- package/src/vendor/pi/managed-extension.ts +86 -0
- package/src/vendor/pi/managed-pi-rpc.ts +99 -0
- package/src/vendor/pi/managed-read.ts +99 -0
- package/src/vendor/pi/package.json +7 -0
- package/src/vendor/pi/pi-LICENSE +21 -0
- package/src/vendor/pi/pi-acp-LICENSE +21 -0
- package/src/version.ts +4 -0
- package/src/workspace.ts +117 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 yamato
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,133 @@
|
|
|
1
|
-
#
|
|
1
|
+
# agent-chat-relay
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
LINE・Chatwork・Discord のルームから、Claude Code などのコーディングエージェントに作業を依頼するための中継サーバーです。
|
|
4
|
+
|
|
5
|
+
ルームでの発言をエージェントのセッションに渡し、エージェントは MCP ツールを使ってルームに返信します。エージェントとは ACP(Agent Client Protocol)でやり取りするので、特定のエージェントに固有の機能には依存しません。設計の経緯は [ADR 0006](docs/adr/0006-own-core-drives-any-harness-over-acp.md) にあります。
|
|
6
|
+
|
|
7
|
+
## 主な機能
|
|
8
|
+
|
|
9
|
+
- 登録したルームで Bot 宛ての発言があると、エージェントに渡して、返事をルームに投稿します。
|
|
10
|
+
- エージェントは、ほかのルームへの投稿、過去の発言の参照、添付ファイルの受け取りと送信ができます。
|
|
11
|
+
- エージェントがファイルの書き込みやコマンドの実行をするときは、承認者の DM に承認を依頼します。
|
|
12
|
+
- ルームと承認者は、ペアリング用のコードで登録します。
|
|
13
|
+
|
|
14
|
+
## 対応状況
|
|
15
|
+
|
|
16
|
+
| 種類 | 対象 | 状況 |
|
|
17
|
+
|---|---|---|
|
|
18
|
+
| チャットサービス | LINE | 対応済み(実環境で確認済み) |
|
|
19
|
+
| | Chatwork・Discord | 対応済み(モックで確認済み。実環境では未確認) |
|
|
20
|
+
| | LINE WORKS | 未対応 |
|
|
21
|
+
| ハーネス | Claude Code | 対応済み |
|
|
22
|
+
| | pi | macOS(Apple Silicon)でモックを使って確認済み。Linux は [#23](https://github.com/Dot-labo/harness-chat-adapter/issues/23) で確認予定 |
|
|
23
|
+
| | OpenCode | 試験的。実行承認が働かないため、既定では起動しません([#7](https://github.com/Dot-labo/harness-chat-adapter/issues/7)) |
|
|
24
|
+
| OS | macOS(Apple Silicon) | 動作確認済み |
|
|
25
|
+
| | Ubuntu 24.04(x86_64) | CI でテストが通ることのみ確認済み |
|
|
26
|
+
|
|
27
|
+
## 前提条件
|
|
28
|
+
|
|
29
|
+
- [Bun](https://bun.sh/) 1.4 以降:中継は Bun で動きます。npm でインストールする場合も必要です。
|
|
30
|
+
- Claude Code を使う場合:[Claude Code](https://code.claude.com/docs/en/setup) をインストールしてログインしておいてください。中継は PATH 上の `claude` を起動します。
|
|
31
|
+
- pi を使う場合:pi の別途インストールは不要です。[pi のモデルと認証の準備](docs/relay-setup.md#pi-のモデルと認証の準備)のあと、`agent-chat-relay serve pi` で起動します。
|
|
32
|
+
- git:既定の作業ディレクトリを、独立した git リポジトリにするために使います。
|
|
33
|
+
- [cloudflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/)(LINE を使う場合):Webhook を公開するために使います。
|
|
34
|
+
|
|
35
|
+
## インストール
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
bun install -g @dotlabo/agent-chat-relay
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
`npm install -g @dotlabo/agent-chat-relay` でもインストールできます(実行には Bun を使います)。コマンドは `agent-chat-relay` で、`ac-relay` という短い別名もあります。
|
|
42
|
+
|
|
43
|
+
## 使い方
|
|
44
|
+
|
|
45
|
+
Chatwork を使う場合の流れです。Bot のアカウントの準備や、LINE・Discord を使う場合の手順は [docs/relay-setup.md](docs/relay-setup.md) を参照してください。
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
# 1. Bot の API トークンを保存する(入力内容は表示されません)
|
|
49
|
+
agent-chat-relay secrets chatwork
|
|
50
|
+
|
|
51
|
+
# 2. 中継を起動する
|
|
52
|
+
agent-chat-relay serve
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
起動したら、Bot に DM(Chatwork ではダイレクトチャット。先に Bot とコンタクトになっておく必要があります)を送ってください。ペアリング用のコードが返ってくるので、別のターミナルで承認します。これで自分が承認者として登録されます。ルームも同じ手順で登録できます。
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
agent-chat-relay pair <コード>
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
エージェントは、既定では中継専用の作業ディレクトリ(`~/.agent-chat-relay/workspace/`)で作業します。普段のフォルダで作業させるには、`--workspace` で明示します。そのフォルダの中身は、登録したルームの誰の依頼からでも、実行承認なしで読まれ、ルームへ送られえます。秘密情報を置いたフォルダは指定しないでください([docs/relay-setup.md](docs/relay-setup.md#普段の環境で動かす))。
|
|
62
|
+
|
|
63
|
+
```sh
|
|
64
|
+
cd ~/work/project
|
|
65
|
+
agent-chat-relay serve --workspace .
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
中継のデータ(ルームの登録、許可リスト、秘密情報、作業ディレクトリ、ログ)は `~/.agent-chat-relay/` に置きます。`RELAY_HOME` で変えられます。
|
|
69
|
+
|
|
70
|
+
## 秘密情報の管理
|
|
71
|
+
|
|
72
|
+
チャットサービスのトークンなどの秘密情報は、`agent-chat-relay secrets` で `~/.agent-chat-relay/.env` に保存します。ファイルは平文で、権限を 0600(自分だけが読み書きできる)にします。
|
|
73
|
+
|
|
74
|
+
ファイルに保存せず、環境変数で渡すこともできます。環境変数は、ファイルより優先します。値をコマンドラインに直接書くとシェルの履歴に残るため、`read -rs` などで入力してください。
|
|
75
|
+
|
|
76
|
+
```sh
|
|
77
|
+
read -rs RELAY_CHATWORK_API_TOKEN && export RELAY_CHATWORK_API_TOKEN
|
|
78
|
+
agent-chat-relay serve
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
環境変数の名前は次のとおりです。
|
|
82
|
+
|
|
83
|
+
| チャットサービス | 環境変数 |
|
|
84
|
+
|---|---|
|
|
85
|
+
| LINE | `RELAY_LINE_CHANNEL_SECRET`・`RELAY_LINE_CHANNEL_TOKEN` |
|
|
86
|
+
| Chatwork | `RELAY_CHATWORK_API_TOKEN` |
|
|
87
|
+
| Discord | `RELAY_DISCORD_BOT_TOKEN` |
|
|
88
|
+
|
|
89
|
+
## 開発
|
|
90
|
+
|
|
91
|
+
リポジトリを clone し、`scripts/relay.sh` で動かします。コマンドは `agent-chat-relay` と同じです。データはリポジトリ内の `.local/relay/` に置き、秘密情報は dotenvx で暗号化してリポジトリ直下の `.env` に保存します(public リポジトリに誤ってコミットしても漏れないようにするため)。
|
|
92
|
+
|
|
93
|
+
```sh
|
|
94
|
+
git clone https://github.com/Dot-labo/agent-chat-relay.git
|
|
95
|
+
cd agent-chat-relay
|
|
96
|
+
mise trust
|
|
97
|
+
mise install
|
|
98
|
+
mise exec -- bun install
|
|
99
|
+
scripts/relay.sh secrets chatwork
|
|
100
|
+
scripts/relay.sh serve
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
- [mise](https://mise.jdx.dev/):Bun と cloudflared は、`mise.toml` で固定したバージョンを mise でインストールします。Ubuntu では、git と curl も必要です(`sudo apt install git curl`)。
|
|
104
|
+
- [dotenvx](https://dotenvx.com/):`scripts/relay.sh secrets` で使います。1.51 と 2.38 で動作を確認しています。インストール方法は、`brew tap dotenvx/brew && brew trust dotenvx/brew && brew install dotenvx`、`mise use -g dotenvx`、`curl -sfS https://dotenvx.sh | sh`、`npm i -g @dotenvx/dotenvx` のいずれかです。使わない場合は、`.env` を作らずに、秘密情報を環境変数で渡してください。
|
|
105
|
+
- テストは `mise exec -- bun test`、型検査と lint(Oxlint)は `mise exec -- bun run check`、変更した行のミューテーションテストは `mise exec -- bun run mutation` です(ADR 0021)。`bun run mutation` は、走らせる e2e も表示します(ADR 0023)。PR を出す前は `mise exec -- bun run pre-pr` で、これらをまとめて走らせ、PR 本文の「確認」の下書きを得ます。書いた本文は、PR を作る前に `mise exec -- bun run pr-body <本文のファイル>` で確かめます。CI も PR の本文に同じ検査をかけます(ADR 0025)。実際のハーネスを使う確認は [docs/relay-setup.md](docs/relay-setup.md#モックでの確認) にあります。
|
|
106
|
+
|
|
107
|
+
### clone して使っていた環境からの移行
|
|
108
|
+
|
|
109
|
+
`scripts/relay.sh` で使っていたデータは、自動では移りません。インストールした `agent-chat-relay` に移るときは、中継を止めてから、次のようにします。
|
|
110
|
+
|
|
111
|
+
```sh
|
|
112
|
+
mkdir -p ~/.agent-chat-relay && chmod 700 ~/.agent-chat-relay
|
|
113
|
+
cp <リポジトリ>/.local/relay/access.json ~/.agent-chat-relay/
|
|
114
|
+
agent-chat-relay secrets chatwork # 使っているサービスの分だけ、入れ直す
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
- ルームの登録と許可リスト(`access.json`)は、そのまま使えます。
|
|
118
|
+
- 秘密情報は、dotenvx で暗号化した `.env` を読めないので、入れ直します。
|
|
119
|
+
- 作業ディレクトリの場所が変わるので、前のセッションは `--session-id` で再開できません(再開できるのは、同じ作業ディレクトリで作ったセッションだけです)。前の作業ディレクトリの中身が必要なら、`~/.agent-chat-relay/workspace/` に移してください。
|
|
120
|
+
|
|
121
|
+
## ドキュメント
|
|
122
|
+
|
|
123
|
+
| ファイル | 内容 |
|
|
124
|
+
|---|---|
|
|
125
|
+
| [docs/relay-setup.md](docs/relay-setup.md) | チャットサービスの準備、起動、ペアリング、動作確認の項目 |
|
|
126
|
+
| [docs/relay.md](docs/relay.md) | 仕様 |
|
|
127
|
+
| [docs/releasing.md](docs/releasing.md) | npm へのリリースの手順 |
|
|
128
|
+
| [docs/adr/](docs/adr/) | 設計判断の記録 |
|
|
129
|
+
| [GLOSSARY.md](GLOSSARY.md) | 用語集 |
|
|
130
|
+
|
|
131
|
+
## 経緯
|
|
132
|
+
|
|
133
|
+
当初は cc-connect の外部アダプターとして作っていました。その実装と記録は、タグ `cc-connect-final` の `old/` にあります。
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# agent-chat-relay の入り口(ADR 0019)。中継の本体を Bun で動かす。
|
|
3
|
+
# Bun は、起動したディレクトリの .env を環境変数に読み込み、bunfig.toml の preload を実行する。
|
|
4
|
+
# どこからでも起動するので、どちらも読ませない(--no-env-file --config=/dev/null)
|
|
5
|
+
set -e
|
|
6
|
+
|
|
7
|
+
# npm や bun は、このファイルへのシンボリックリンクを PATH に置くので、リンクをたどってパッケージの場所を求める
|
|
8
|
+
self=$0
|
|
9
|
+
while [ -L "$self" ]; do
|
|
10
|
+
link=$(readlink "$self")
|
|
11
|
+
case $link in
|
|
12
|
+
/*) self=$link ;;
|
|
13
|
+
*) self=$(dirname "$self")/$link ;;
|
|
14
|
+
esac
|
|
15
|
+
done
|
|
16
|
+
root=$(cd "$(dirname "$self")/.." && pwd -P)
|
|
17
|
+
|
|
18
|
+
if ! command -v bun >/dev/null 2>&1; then
|
|
19
|
+
echo "agent-chat-relay: bun が見つかりません。https://bun.sh の手順でインストールしてください" >&2
|
|
20
|
+
exit 1
|
|
21
|
+
fi
|
|
22
|
+
exec bun --no-env-file --config=/dev/null "$root/src/main.ts" "$@"
|
package/package.json
CHANGED
|
@@ -1,6 +1,67 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dotlabo/agent-chat-relay",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "LINE・Chatwork・Discord のルームから、Claude Code などのコーディングエージェントに作業を依頼するための中継サーバー(ACP・MCP)",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"publishConfig": {
|
|
7
|
+
"access": "public"
|
|
8
|
+
},
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/Dot-labo/agent-chat-relay.git"
|
|
12
|
+
},
|
|
13
|
+
"homepage": "https://github.com/Dot-labo/agent-chat-relay#readme",
|
|
14
|
+
"bugs": "https://github.com/Dot-labo/agent-chat-relay/issues",
|
|
15
|
+
"keywords": [
|
|
16
|
+
"acp",
|
|
17
|
+
"mcp",
|
|
18
|
+
"claude-code",
|
|
19
|
+
"line",
|
|
20
|
+
"chatwork",
|
|
21
|
+
"discord",
|
|
22
|
+
"agent"
|
|
23
|
+
],
|
|
24
|
+
"type": "module",
|
|
25
|
+
"bin": {
|
|
26
|
+
"agent-chat-relay": "bin/agent-chat-relay",
|
|
27
|
+
"ac-relay": "bin/agent-chat-relay"
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"bin/",
|
|
31
|
+
"src/"
|
|
32
|
+
],
|
|
33
|
+
"engines": {
|
|
34
|
+
"bun": ">=1.4.0"
|
|
35
|
+
},
|
|
36
|
+
"os": [
|
|
37
|
+
"darwin",
|
|
38
|
+
"linux"
|
|
39
|
+
],
|
|
40
|
+
"scripts": {
|
|
41
|
+
"relay": "bin/agent-chat-relay",
|
|
42
|
+
"test": "bun test",
|
|
43
|
+
"check": "tsc --noEmit && oxlint && bun --no-env-file --config=/dev/null scripts/check.ts",
|
|
44
|
+
"docs:adr": "bun --no-env-file --config=/dev/null scripts/adr-index.ts",
|
|
45
|
+
"mutation": "scripts/mutation.sh",
|
|
46
|
+
"pre-pr": "bun --no-env-file --config=/dev/null scripts/pre-pr.ts",
|
|
47
|
+
"pr-body": "bun --no-env-file --config=/dev/null scripts/pr-body.ts"
|
|
48
|
+
},
|
|
49
|
+
"dependencies": {
|
|
50
|
+
"@agentclientprotocol/claude-agent-acp": "0.101.0",
|
|
51
|
+
"@agentclientprotocol/sdk": "2.4.0",
|
|
52
|
+
"@earendil-works/pi-coding-agent": "1.5.2",
|
|
53
|
+
"@modelcontextprotocol/sdk": "1.32.2",
|
|
54
|
+
"cross-spawn": "7.0.6",
|
|
55
|
+
"discord.js": "14.28.1",
|
|
56
|
+
"pi-acp-protocol-sdk": "npm:@agentclientprotocol/sdk@0.26.0",
|
|
57
|
+
"zod": "4.6.7"
|
|
58
|
+
},
|
|
59
|
+
"devDependencies": {
|
|
60
|
+
"@types/bun": "1.4.4",
|
|
61
|
+
"fallow": "3.44.0",
|
|
62
|
+
"fast-check": "4.10.3",
|
|
63
|
+
"oxlint": "1.94.0",
|
|
64
|
+
"oxlint-tsgolint": "7.0.2007",
|
|
65
|
+
"typescript": "7.0.2"
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
// Chatwork のコネクター。API のポーリングで受け、REST API で送る(ADR 0010)。
|
|
2
|
+
// Bot は、専用の Chatwork アカウントの API トークンで発言する。
|
|
3
|
+
|
|
4
|
+
import { basename, extname } from "node:path"
|
|
5
|
+
import { localId } from "../core/access.ts"
|
|
6
|
+
import { assertNumericId, attachmentOnlyText, remember, saveDownload, splitText, truncate } from "./common.ts"
|
|
7
|
+
import { ApiClient, jsonError } from "./http.ts"
|
|
8
|
+
import type { Attachment, Capabilities, Connector, ConnectorDeps, Log, Relay } from "../core/relay.ts"
|
|
9
|
+
|
|
10
|
+
const SERVICE = "chatwork"
|
|
11
|
+
// 本文の上限は 65535 字。返信の記法を付ける分を残す
|
|
12
|
+
const MAX_TEXT = 65000
|
|
13
|
+
// 取得は 1 回ごとに、ルーム一覧 1 回と、更新のあったルームごとに 2 回。回数制限(5 分に 300 回)を送信と分け合うので、間隔を 2 秒より短くしない
|
|
14
|
+
const MIN_POLL_MS = 2000
|
|
15
|
+
const IMAGE_EXT = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp"])
|
|
16
|
+
|
|
17
|
+
type CwRoom = { room_id: number; name: string; type: "my" | "direct" | "group"; last_update_time: number }
|
|
18
|
+
type CwMessage = { message_id: string; account: { account_id: number; name: string }; body: string; send_time: number }
|
|
19
|
+
|
|
20
|
+
type ChatworkConfig = {
|
|
21
|
+
apiToken: string
|
|
22
|
+
apiBase?: string
|
|
23
|
+
/** ポーリングの間隔(ミリ秒)。既定は 5 秒 */
|
|
24
|
+
pollMs?: number
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** ルームと人の ID。DM(ダイレクトチャット)は、LINE と同じく相手の ID をルームとして扱う */
|
|
28
|
+
const roomKey = (roomId: number) => `${SERVICE}:r${roomId}`
|
|
29
|
+
const userKey = (accountId: number) => `${SERVICE}:u${accountId}`
|
|
30
|
+
|
|
31
|
+
/** API トークンがあれば、コネクターを作る */
|
|
32
|
+
export function chatworkFromEnv(env: Record<string, string | undefined>, deps: ConnectorDeps): ChatworkConnector | undefined {
|
|
33
|
+
const apiToken = env.RELAY_CHATWORK_API_TOKEN
|
|
34
|
+
if (!apiToken) return undefined
|
|
35
|
+
const pollMs = Number(env.RELAY_CHATWORK_POLL_SEC) * 1000 || undefined
|
|
36
|
+
return new ChatworkConnector({ apiToken, apiBase: env.RELAY_CHATWORK_API_BASE, pollMs }, deps.relay, deps.log)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export class ChatworkConnector implements Connector {
|
|
40
|
+
readonly service = SERVICE
|
|
41
|
+
readonly label = "Chatwork"
|
|
42
|
+
readonly capabilities: Capabilities = {
|
|
43
|
+
// ルームごとの投稿の制限(10 秒に 10 回)に当たらないよう、1 回の返事の投稿(本文とファイル)を 8 回までにする
|
|
44
|
+
files: { maxBytes: 5 * 1024 * 1024, maxCount: 5 },
|
|
45
|
+
text: { max: MAX_TEXT, parts: 3 },
|
|
46
|
+
}
|
|
47
|
+
private readonly api: ApiClient
|
|
48
|
+
private me?: { id: number; name: string; mention: RegExp }
|
|
49
|
+
/** この時刻(Unix 秒)より前の発言は、停止中に届いたものとして記録だけする */
|
|
50
|
+
private startedAt = 0
|
|
51
|
+
private readonly roomNames = new Map<number, string>()
|
|
52
|
+
/**
|
|
53
|
+
* ルームごとの、最後に差分を取得したときの last_update_time。last_update_time は秒単位なので、同じ秒のうちに
|
|
54
|
+
* 後から届いた発言を取りこぼさないよう、同じ時刻でもう一度だけ取得する(done が false の間)
|
|
55
|
+
*/
|
|
56
|
+
private readonly fetched = new Map<number, { t: number; done: boolean }>()
|
|
57
|
+
/** DM の相手 → ダイレクトチャットのルーム ID */
|
|
58
|
+
private readonly dmRooms = new Map<number, number>()
|
|
59
|
+
/** 受け取った発言(ルーム ID-メッセージ ID)→ 送信者と本文。重複の除去、返信の記法、添付の取得に使う */
|
|
60
|
+
private readonly messages = new Map<string, { author: number; body: string }>()
|
|
61
|
+
private timer?: Timer
|
|
62
|
+
private lastError = ""
|
|
63
|
+
|
|
64
|
+
constructor(
|
|
65
|
+
private readonly cfg: ChatworkConfig,
|
|
66
|
+
private readonly relay: Relay,
|
|
67
|
+
private readonly log: Log,
|
|
68
|
+
private readonly now: () => number = Date.now,
|
|
69
|
+
) {
|
|
70
|
+
this.api = new ApiClient({
|
|
71
|
+
label: this.label,
|
|
72
|
+
base: cfg.apiBase ?? "https://api.chatwork.com/v2",
|
|
73
|
+
auth: () => ({ "x-chatworktoken": cfg.apiToken }),
|
|
74
|
+
errorMessage: (raw) => jsonError(raw, (b) => (b.errors as string[] | undefined)?.join(", ")),
|
|
75
|
+
rateLimited: (res, msg, now) =>
|
|
76
|
+
// ルームごとの投稿の制限(10 秒に 10 回)は、ヘッダーではなくエラーの文面でしか見分けられない。そのルームにだけかかる。
|
|
77
|
+
// 全体の制限(5 分に 300 回)なら、解除の時刻(x-ratelimit-reset。Unix 秒)まで止める。ヘッダーがなければ 1 分待つ
|
|
78
|
+
/per room/i.test(msg)
|
|
79
|
+
? { message: "このルームへの投稿が多すぎます。10 秒ほど待ってから送ってください" }
|
|
80
|
+
: { resumeAt: Number(res.headers.get("x-ratelimit-reset")) * 1000 || now + 60_000, message: "Chatwork の API の回数制限(5 分に 300 回)に達しました" },
|
|
81
|
+
now,
|
|
82
|
+
})
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Bot のアカウントを確認し、ポーリングを始める。今あるルームの更新時刻を起点にし、起動時には差分を取得しない。
|
|
87
|
+
* force=0 の差分の起点は Chatwork がトークンごとに覚えているので、停止中の発言は、そのルームの次の差分に含まれて届く
|
|
88
|
+
*/
|
|
89
|
+
async start(): Promise<void> {
|
|
90
|
+
const [me, rooms] = await Promise.all([this.api.call("GET", "/me") as Promise<{ account_id: number; name: string }>, this.listRooms()])
|
|
91
|
+
this.me = { id: me.account_id, name: me.name, mention: selfMention(me.account_id, me.name) }
|
|
92
|
+
this.startedAt = Math.floor(this.now() / 1000)
|
|
93
|
+
for (const r of rooms) this.fetched.set(r.room_id, { t: r.last_update_time, done: true })
|
|
94
|
+
this.schedule()
|
|
95
|
+
this.log.info("Chatwork のポーリングを始めました")
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
stop(): void {
|
|
99
|
+
clearTimeout(this.timer)
|
|
100
|
+
this.timer = undefined
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
private schedule(): void {
|
|
104
|
+
this.timer = setTimeout(
|
|
105
|
+
() => {
|
|
106
|
+
this.poll()
|
|
107
|
+
.then(() => (this.lastError = ""))
|
|
108
|
+
.catch((err) => {
|
|
109
|
+
// 同じ失敗を取得のたびに書かない
|
|
110
|
+
const msg = String(err)
|
|
111
|
+
if (msg !== this.lastError) this.log.error("Chatwork から取得できませんでした", { error: msg })
|
|
112
|
+
this.lastError = msg
|
|
113
|
+
})
|
|
114
|
+
.finally(() => {
|
|
115
|
+
if (this.timer) this.schedule()
|
|
116
|
+
})
|
|
117
|
+
},
|
|
118
|
+
Math.max(MIN_POLL_MS, this.cfg.pollMs ?? 5000),
|
|
119
|
+
)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** ルーム一覧で更新のあったルームだけ、前回からの差分を取得する */
|
|
123
|
+
async poll(): Promise<void> {
|
|
124
|
+
if (this.api.paused) return
|
|
125
|
+
for (const r of await this.listRooms()) {
|
|
126
|
+
if (r.type === "my") continue
|
|
127
|
+
const prev = this.fetched.get(r.room_id)
|
|
128
|
+
// 起動後に現れたグループチャットは、Bot が追加されたもの(LINE の join に当たる。Chatwork にはその通知がない)
|
|
129
|
+
if (!prev && r.type === "group") this.relay.joined(roomKey(r.room_id))
|
|
130
|
+
if (prev && r.last_update_time <= prev.t && prev.done) continue
|
|
131
|
+
const msgs = await this.list<CwMessage>(`/rooms/${r.room_id}/messages?force=0`)
|
|
132
|
+
this.fetched.set(r.room_id, { t: r.last_update_time, done: prev?.t === r.last_update_time })
|
|
133
|
+
// 差分の並び順は、ドキュメントに書かれていない
|
|
134
|
+
for (const m of msgs.sort((a, b) => a.send_time - b.send_time)) this.handle(r, m)
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private handle(r: CwRoom, m: CwMessage): void {
|
|
139
|
+
const key = `${r.room_id}-${m.message_id}`
|
|
140
|
+
if (this.messages.has(key)) return
|
|
141
|
+
const author = m.account.account_id
|
|
142
|
+
remember(this.messages, key, { author, body: m.body })
|
|
143
|
+
if (!this.me || author === this.me.id) return
|
|
144
|
+
const isDM = r.type === "direct"
|
|
145
|
+
if (isDM) this.dmRooms.set(author, r.room_id)
|
|
146
|
+
const parsed = parseBody(m.body, this.me, this.me.mention)
|
|
147
|
+
// 受け取りの合図は出さない。リアクションの API がなく、既読はほかの人に見えない(ADR 0012)
|
|
148
|
+
this.relay.receive({
|
|
149
|
+
id: m.message_id,
|
|
150
|
+
room: isDM ? userKey(author) : roomKey(r.room_id),
|
|
151
|
+
sender: userKey(author),
|
|
152
|
+
senderName: m.account.name,
|
|
153
|
+
text: parsed.text,
|
|
154
|
+
ts: m.send_time * 1000,
|
|
155
|
+
attachments: parsed.attachments,
|
|
156
|
+
isDM,
|
|
157
|
+
mentioned: isDM || parsed.mentioned,
|
|
158
|
+
toOthers: addressesOthers(m.body, author),
|
|
159
|
+
stale: m.send_time < this.startedAt,
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async send(room: string, text: string, opts?: { replyTo?: string; files?: string[] }): Promise<string[]> {
|
|
164
|
+
const rid = await this.roomId(room)
|
|
165
|
+
const files = opts?.files ?? []
|
|
166
|
+
const parts = splitText(text, this.capabilities.text.max, this.capabilities.text.parts)
|
|
167
|
+
const replyTo = opts?.replyTo
|
|
168
|
+
const author = replyTo ? this.messages.get(`${rid}-${replyTo}`)?.author : undefined
|
|
169
|
+
if (parts.length > 0 && author !== undefined) parts[0] = `[rp aid=${author} to=${rid}-${replyTo}]\n${parts[0]}`
|
|
170
|
+
if (parts.length === 0 && files.length === 0) throw new Error("本文が空です")
|
|
171
|
+
// 本文の最後の 1 通は、1 つ目のファイルに添える。ファイルの投稿は、メッセージ ID を返さない
|
|
172
|
+
const caption = files.length > 0 ? parts.pop() : undefined
|
|
173
|
+
const ids: string[] = []
|
|
174
|
+
for (const p of parts) ids.push(await this.post(rid, p))
|
|
175
|
+
for (const [i, f] of files.entries()) {
|
|
176
|
+
const form = new FormData()
|
|
177
|
+
form.append("file", Bun.file(f), basename(f))
|
|
178
|
+
if (i === 0 && caption) form.append("message", caption)
|
|
179
|
+
await this.api.call("POST", `/rooms/${rid}/files`, form, 60_000)
|
|
180
|
+
}
|
|
181
|
+
return ids
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async sendApproval(user: string, text: string, _requestId: string): Promise<void> {
|
|
185
|
+
// ボタンはないので、yes/no の文字で答えてもらう
|
|
186
|
+
await this.post(await this.roomId(user), text)
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async notice(room: string, text: string): Promise<boolean> {
|
|
190
|
+
await this.post(await this.roomId(room), text)
|
|
191
|
+
return true
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async download(room: string, messageId: string, dir: string): Promise<string[]> {
|
|
195
|
+
assertNumericId(messageId)
|
|
196
|
+
const rid = await this.roomId(room)
|
|
197
|
+
const body =
|
|
198
|
+
this.messages.get(`${rid}-${messageId}`)?.body ?? ((await this.api.call("GET", `/rooms/${rid}/messages/${messageId}`)) as CwMessage).body
|
|
199
|
+
const ids = [...new Set([...body.matchAll(/\[download:(\d+)\]/g)].map((m) => m[1]!))]
|
|
200
|
+
if (ids.length === 0) throw new Error("この発言には添付がありません")
|
|
201
|
+
const paths: string[] = []
|
|
202
|
+
for (const fid of ids) {
|
|
203
|
+
const file = (await this.api.call("GET", `/rooms/${rid}/files/${fid}?create_download_url=1`)) as { filename: string; download_url?: string }
|
|
204
|
+
// 取得用の URL の有効期限は 30 秒。API トークンは付けない(別のホストへ渡さない)
|
|
205
|
+
const res = await this.api.download(file.download_url ?? "", "none")
|
|
206
|
+
paths.push(await saveDownload(res, dir, `${this.now()}-${messageId}-${fid}`, extname(file.filename)))
|
|
207
|
+
}
|
|
208
|
+
return paths
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async roomName(room: string): Promise<string | undefined> {
|
|
212
|
+
const m = /^r(\d+)$/.exec(localId(room))
|
|
213
|
+
return m ? this.roomNames.get(Number(m[1])) : undefined
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async edit(room: string, messageId: string, text: string): Promise<void> {
|
|
217
|
+
assertNumericId(messageId)
|
|
218
|
+
const rid = await this.roomId(room)
|
|
219
|
+
await this.api.call("PUT", `/rooms/${rid}/messages/${messageId}`, new URLSearchParams({ body: truncate(text.trim(), this.capabilities.text.max) }))
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
private async post(rid: number, body: string): Promise<string> {
|
|
223
|
+
const res = (await this.api.call("POST", `/rooms/${rid}/messages`, new URLSearchParams({ body }))) as { message_id: string }
|
|
224
|
+
return res.message_id
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
private async listRooms(): Promise<CwRoom[]> {
|
|
228
|
+
const list = await this.list<CwRoom>("/rooms")
|
|
229
|
+
for (const r of list) this.roomNames.set(r.room_id, r.name)
|
|
230
|
+
return list
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** 一覧を返す API。0 件のときは 204 で本文がない */
|
|
234
|
+
private async list<T>(path: string): Promise<T[]> {
|
|
235
|
+
return ((await this.api.call("GET", path)) as T[] | null) ?? []
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** ルームの ID を、Chatwork のルーム ID にする。DM の相手なら、コンタクトからダイレクトチャットを探す */
|
|
239
|
+
private async roomId(id: string): Promise<number> {
|
|
240
|
+
const m = /^([ru])(\d+)$/.exec(localId(id))
|
|
241
|
+
if (!id.startsWith(`${SERVICE}:`) || !m) throw new Error(`Chatwork の ID の形が違います: ${id}`)
|
|
242
|
+
const n = Number(m[2])
|
|
243
|
+
if (m[1] === "r") return n
|
|
244
|
+
let rid = this.dmRooms.get(n)
|
|
245
|
+
if (rid === undefined) {
|
|
246
|
+
for (const c of await this.list<{ account_id: number; room_id: number }>("/contacts")) this.dmRooms.set(c.account_id, c.room_id)
|
|
247
|
+
rid = this.dmRooms.get(n)
|
|
248
|
+
}
|
|
249
|
+
if (rid === undefined) throw new Error("この人とのダイレクトチャットが見つかりません(Bot のコンタクトではありません)")
|
|
250
|
+
return rid
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Bot へのメンション(To と、Bot の発言への返信)。Chatwork の画面で付けると、記法の後ろに「名前さん」が入る */
|
|
255
|
+
function selfMention(id: number, name: string): RegExp {
|
|
256
|
+
return new RegExp(`\\[(?:To:${id}|rp aid=${id} to=\\d+-\\d+)\\][ \\t]*(?:${escapeRegExp(name)}(?:さん)?)?`, "g")
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** 送信者以外の人への To か、その人の発言への返信があるか(Bot を含む。Inbound.toOthers)。全員宛て([toall])は含まない(ADR 0028) */
|
|
260
|
+
export function addressesOthers(body: string, author: number): boolean {
|
|
261
|
+
return [...body.matchAll(/\[(?:To:(\d+)|rp aid=(\d+) to=\d+-\d+)\]/g)].some(([, to, rp]) => Number(to ?? rp) !== author)
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** 本文から、Bot へのメンションと返信の記法を取り除き、添付を取り出す。ほかの記法はそのまま渡す */
|
|
265
|
+
export function parseBody(
|
|
266
|
+
body: string,
|
|
267
|
+
me: { id: number; name: string },
|
|
268
|
+
self = selfMention(me.id, me.name),
|
|
269
|
+
): { text: string; attachments: Attachment[]; mentioned: boolean } {
|
|
270
|
+
const attachments: Attachment[] = []
|
|
271
|
+
let text = body.replace(self, "")
|
|
272
|
+
const mentioned = text !== body
|
|
273
|
+
text = text.replace(/\[download:\d+\]([\s\S]*?)\[\/download\]/g, (_, label: string) => {
|
|
274
|
+
// 表示は「ファイル名 (12.34 KB)」
|
|
275
|
+
const name = label.replace(/\s*\([\d.,]+\s*[KMG]?B\)\s*$/i, "").trim() || "file"
|
|
276
|
+
attachments.push({ name, type: IMAGE_EXT.has(extname(name).toLowerCase()) ? "image" : "file" })
|
|
277
|
+
return ""
|
|
278
|
+
})
|
|
279
|
+
text = text
|
|
280
|
+
.replace(/\[preview [^\]]*\]/g, "")
|
|
281
|
+
.replace(/\[info\]\s*\[title\]\[dtext:file_uploaded\]\[\/title\]\s*\[\/info\]/g, "")
|
|
282
|
+
.trim()
|
|
283
|
+
text ||= attachmentOnlyText(attachments)
|
|
284
|
+
return { text, attachments, mentioned }
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function escapeRegExp(s: string): string {
|
|
288
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
|
289
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// コネクターが共通で使うユーティリティ。
|
|
2
|
+
|
|
3
|
+
import { mkdir, writeFile } from "node:fs/promises"
|
|
4
|
+
import { join } from "node:path"
|
|
5
|
+
import type { Attachment, Log, Verdict } from "../core/relay.ts"
|
|
6
|
+
|
|
7
|
+
const CACHE_CAP = 1000
|
|
8
|
+
const MAX_DOWNLOAD_BYTES = 25 * 1024 * 1024
|
|
9
|
+
const TOO_LARGE = "大きすぎるため取得しません(25MB まで)"
|
|
10
|
+
export const TRUNCATED_NOTE = "\n\n(長すぎるため、ここから先は省略しました)"
|
|
11
|
+
|
|
12
|
+
/** 追加し、上限を超えたら古いものから捨てる。プロセスのメモリ上にだけ置くキャッシュ(重複の除去、ID の対応など)に使う */
|
|
13
|
+
export function remember(c: Set<string>, key: string): void
|
|
14
|
+
export function remember<V>(c: Map<string, V>, key: string, value: V): void
|
|
15
|
+
export function remember<V>(c: Set<string> | Map<string, V>, key: string, value?: V): void {
|
|
16
|
+
if (c instanceof Set) c.add(key)
|
|
17
|
+
else c.set(key, value!)
|
|
18
|
+
if (c.size > CACHE_CAP) c.delete(c.keys().next().value!)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** UTF-16 で limit 単位に収まる長さ。サロゲートペアの途中では切らない */
|
|
22
|
+
export function fitUnits(s: string, limit: number): number {
|
|
23
|
+
if (s.length <= limit) return s.length
|
|
24
|
+
const code = s.charCodeAt(limit - 1)
|
|
25
|
+
return code >= 0xd800 && code <= 0xdbff ? limit - 1 : limit
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** max 単位を超える本文を切り、省略したことを書き添える */
|
|
29
|
+
export function truncate(text: string, max: number): string {
|
|
30
|
+
return text.length <= max ? text : text.slice(0, fitUnits(text, max - TRUNCATED_NOTE.length)) + TRUNCATED_NOTE
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 本文を、1 通 max 単位で parts 通までに分ける。段落、行、空白の切れ目で分ける(前半にしかなければ、そのまま切る)。
|
|
35
|
+
* 入りきらない分は、最後の 1 通を切って省略を書き添える
|
|
36
|
+
*/
|
|
37
|
+
export function splitText(text: string, max: number, parts: number): string[] {
|
|
38
|
+
const out: string[] = []
|
|
39
|
+
let rest = text.trim()
|
|
40
|
+
while (rest.length > max && out.length < parts - 1) {
|
|
41
|
+
let cut = fitUnits(rest, max)
|
|
42
|
+
for (const sep of ["\n\n", "\n", " "]) {
|
|
43
|
+
const i = rest.lastIndexOf(sep, cut - sep.length)
|
|
44
|
+
if (i > max / 2) {
|
|
45
|
+
cut = i
|
|
46
|
+
break
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
out.push(rest.slice(0, cut).trimEnd())
|
|
50
|
+
rest = rest.slice(cut).trimStart()
|
|
51
|
+
}
|
|
52
|
+
if (rest) out.push(truncate(rest, max))
|
|
53
|
+
return out
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 取得した添付を dir に保存する(25MB まで)。名前は <stem><ext>。ext は記号を除いてから使う */
|
|
57
|
+
export async function saveDownload(res: Response, dir: string, stem: string, ext: string): Promise<string> {
|
|
58
|
+
if (Number(res.headers.get("content-length") ?? 0) > MAX_DOWNLOAD_BYTES) throw new Error(TOO_LARGE)
|
|
59
|
+
const buf = Buffer.from(await res.arrayBuffer())
|
|
60
|
+
if (buf.length > MAX_DOWNLOAD_BYTES) throw new Error(TOO_LARGE)
|
|
61
|
+
await mkdir(dir, { recursive: true, mode: 0o700 })
|
|
62
|
+
const path = join(dir, `${stem}${ext.replace(/[^.a-zA-Z0-9]/g, "")}`)
|
|
63
|
+
await writeFile(path, buf, { mode: 0o600 })
|
|
64
|
+
return path
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** コネクターの API が受け付けるメッセージ ID か(数字だけ)。パスに入れる前に確認する */
|
|
68
|
+
export function assertNumericId(id: string): void {
|
|
69
|
+
if (!/^\d+$/.test(id)) throw new Error("message_id の形が違います")
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 本文がなく添付だけの発言の、本文の代わり */
|
|
73
|
+
export function attachmentOnlyText(attachments: Attachment[]): string {
|
|
74
|
+
if (attachments.length === 0) return ""
|
|
75
|
+
return attachments.every((a) => a.type === "image") ? "(画像)" : "(ファイル)"
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** 受け取りの合図を出す関数を作る(ADR 0012)。失敗しても発言の処理は止めず、同じ失敗は続けてログに書かない */
|
|
79
|
+
export function acknowledger(log: Log, label: string): (run: () => Promise<unknown>) => void {
|
|
80
|
+
let last = ""
|
|
81
|
+
return (run) => {
|
|
82
|
+
run().then(
|
|
83
|
+
() => (last = ""),
|
|
84
|
+
(err) => {
|
|
85
|
+
const msg = String(err)
|
|
86
|
+
if (msg !== last) log.error(`${label} で受け取りの合図を出せませんでした`, { error: msg })
|
|
87
|
+
last = msg
|
|
88
|
+
},
|
|
89
|
+
)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** 承認のボタンに載せる値(perm:allow:<ID>・perm:deny:<ID>) */
|
|
94
|
+
export const permissionData = (verdict: Verdict, requestId: string) => `perm:${verdict}:${requestId}`
|
|
95
|
+
|
|
96
|
+
/** ボタンの値から、答えと依頼の ID を読む。形が違えば undefined */
|
|
97
|
+
export function parsePermissionData(data: string): { verdict: Verdict; id: string } | undefined {
|
|
98
|
+
const m = /^perm:(allow|always|deny):([a-km-z]{5})$/.exec(data)
|
|
99
|
+
return m ? { verdict: m[1] as Verdict, id: m[2]! } : undefined
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** ボタンで答えたあとに見せる文言 */
|
|
103
|
+
export function verdictText(ok: boolean, verdict: Verdict): string {
|
|
104
|
+
if (!ok) return "その依頼は見つからないか、すでに答えが出ています"
|
|
105
|
+
return { allow: "✅ 許可しました", always: "✅ 常に許可しました", deny: "❌ 拒否しました" }[verdict]
|
|
106
|
+
}
|