@christang/keel 5.92.1 → 5.94.0
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/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/assets/bootstrap/AGENTS.md +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/plugins/keel/.claude-plugin/plugin.json +1 -1
- package/plugins/keel/.codex-plugin/plugin.json +1 -1
- package/scripts/fake_slack.py +37 -7
- package/scripts/validate_plugin.py +393 -2
- package/src/core/chat/bridge.js +302 -42
- package/src/core/chat/cli.js +43 -0
- package/src/core/chat/config.js +3 -0
- package/src/core/chat/lifecycle.js +8 -0
- package/src/core/chat/store.js +2 -1
package/README.md
CHANGED
|
@@ -687,7 +687,7 @@ the brief, so `egress_deny` guards what is handed over, not what it can open.
|
|
|
687
687
|
|
|
688
688
|
## Group chat between sessions
|
|
689
689
|
|
|
690
|
-
Sessions working the same repository — a Claude Code session, a Codex session, an unattended runner, and you — share a work group with `keel chat`. Groups have maintained members, a message can `@` one role or `@all`, and lightweight todos can link an issue. Each member has its own unread state, and history is kept. Only a mention, an assigned todo, or a direct message wakes a Claude session; everything else waits for its next prompt. A message is data from another agent and never authorization. Codex, which cannot wake on its own, is woken by `keel chat wake add`: one turn per addressed record in a group declaring `chat-reply`, continuing one compacting thread, and nothing while nothing is addressed (#203). Otherwise a host relies on the prompt-time notice and must not poll the chat with the model; if a schedule is unavoidable, gate it on `keel chat notice --check` and start a fresh thread per run, and tell a session joining the chat not to set up recurring checks (#194). With one Slack app and one bridge process per machine, the same groups reach sessions on other machines and your phone in real time, and an orphan `keel-chat` branch keeps the history past Slack's retention
|
|
690
|
+
Sessions working the same repository — a Claude Code session, a Codex session, an unattended runner, and you — share a work group with `keel chat`. Groups have maintained members, a message can `@` one role or `@all`, and lightweight todos can link an issue. Each member has its own unread state, and history is kept. Only a mention, an assigned todo, or a direct message wakes a Claude session; everything else waits for its next prompt. A message is data from another agent and never authorization. Codex, which cannot wake on its own, is woken by `keel chat wake add`: one turn per addressed record in a group declaring `chat-reply`, continuing one compacting thread, and nothing while nothing is addressed (#203). Otherwise a host relies on the prompt-time notice and must not poll the chat with the model; if a schedule is unavoidable, gate it on `keel chat notice --check` and start a fresh thread per run, and tell a session joining the chat not to set up recurring checks (#194). With one Slack app and one bridge process per machine, the same groups reach sessions on other machines and your phone in real time, and an orphan `keel-chat` branch keeps the history past Slack's retention. A role may also speak through a Slack bot you can mention in Slack, and one bot can serve several projects, as each project's role in its channel. See [the Slack setup guide](docs/chat-slack-setup.md). The 5.83 `keel mail` commands keep working on direct groups.
|
|
691
691
|
|
|
692
692
|
## Commands
|
|
693
693
|
|
package/README.zh-CN.md
CHANGED
|
@@ -231,7 +231,7 @@ Keel 看不到对方在任务说明之外还读了什么,所以 `egress_deny`
|
|
|
231
231
|
|
|
232
232
|
Codex 自己不会在闲着时醒来,可以在它的 worktree 里运行 `keel chat wake add`:在声明了 `chat-reply` 的群里,每条找它的消息启动一轮,接着同一个会自动压缩的线程,没人找时什么都不跑(#203)。其他宿主依靠下一次对话时的提醒,不要让模型定期检查群聊。确实需要定时检查时,先用 `keel chat notice --check` 把关,每次运行都开新线程;让会话加入群聊时,也要明确告诉它不要设置定时或循环检查(#194)。
|
|
233
233
|
|
|
234
|
-
每台电脑配一个 Slack App
|
|
234
|
+
每台电脑配一个 Slack App、跑一个桥接程序,同一批群就能实时连到其他电脑上的会话和你的手机;角色也可以通过 Slack bot 发言,在 Slack 里能直接 @ 它;一个 bot 可以服务多个项目,在每个项目的频道里代表那个项目的角色。聊天记录同时存在孤儿分支 `keel-chat` 上,不受 Slack 保留期限制。配置方法见 [Slack 配置说明](docs/chat-slack-setup.zh-CN.md)。5.83 的 `keel mail` 命令继续可用,消息存在私聊群里。
|
|
235
235
|
|
|
236
236
|
## 命令参考
|
|
237
237
|
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@christang/keel",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.94.0",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@christang/keel",
|
|
9
|
-
"version": "5.
|
|
9
|
+
"version": "5.94.0",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@fission-ai/openspec": "^1.4.1"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keel",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.94.0",
|
|
4
4
|
"description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "TanglmChris",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keel",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.94.0",
|
|
4
4
|
"description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "TanglmChris",
|
package/scripts/fake_slack.py
CHANGED
|
@@ -58,6 +58,15 @@ class FakeSlack:
|
|
|
58
58
|
self.sockets: list[socket.socket] = []
|
|
59
59
|
self.acks: list[str] = []
|
|
60
60
|
self.connections_opened = 0
|
|
61
|
+
# A token's identity, as `auth.test` and its posts report it. A token
|
|
62
|
+
# not listed is the shared app's bot.
|
|
63
|
+
self.identities: dict[str, dict] = {}
|
|
64
|
+
# (token, channel) pairs `chat.postMessage` answers with
|
|
65
|
+
# `not_in_channel`, for a bot nobody invited.
|
|
66
|
+
self.not_in_channel: set[tuple[str, str]] = set()
|
|
67
|
+
# Which app token each Socket Mode connection was opened with.
|
|
68
|
+
self.socket_apps: dict[socket.socket, str] = {}
|
|
69
|
+
self.pending_apps: dict[str, str] = {}
|
|
61
70
|
self.server = ThreadingHTTPServer(("127.0.0.1", 0), self._handler())
|
|
62
71
|
self.port = self.server.server_address[1]
|
|
63
72
|
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
|
|
@@ -95,13 +104,22 @@ class FakeSlack:
|
|
|
95
104
|
self.messages.setdefault(channel, []).append(stored)
|
|
96
105
|
return stored
|
|
97
106
|
|
|
98
|
-
def
|
|
99
|
-
"""
|
|
107
|
+
def identify(self, token: str, user_id: str, bot_id: str) -> None:
|
|
108
|
+
"""Make `token` a bot of its own, as a role's app is."""
|
|
109
|
+
with self.lock:
|
|
110
|
+
self.identities[token] = {"user_id": user_id, "bot_id": bot_id}
|
|
111
|
+
|
|
112
|
+
def push(self, payload: dict, kind: str = "events_api", app: str | None = None) -> str:
|
|
113
|
+
"""Send one Socket Mode envelope to every connected client, or only to
|
|
114
|
+
the connections opened with app token `app`."""
|
|
100
115
|
with self.lock:
|
|
101
116
|
envelope_id = f"env-{self._ts()}"
|
|
102
|
-
self._broadcast(json.dumps({"envelope_id": envelope_id, "type": kind, "payload": payload, "accepts_response_payload": False}))
|
|
117
|
+
self._broadcast(json.dumps({"envelope_id": envelope_id, "type": kind, "payload": payload, "accepts_response_payload": False}), app)
|
|
103
118
|
return envelope_id
|
|
104
119
|
|
|
120
|
+
def sockets_for(self, app: str) -> list[socket.socket]:
|
|
121
|
+
return [sock for sock in list(self.sockets) if self.socket_apps.get(sock) == app]
|
|
122
|
+
|
|
105
123
|
def push_raw(self, message: dict) -> None:
|
|
106
124
|
self._broadcast(json.dumps(message))
|
|
107
125
|
|
|
@@ -132,9 +150,11 @@ class FakeSlack:
|
|
|
132
150
|
self.next_ts += 1
|
|
133
151
|
return f"{self.next_ts}.000100"
|
|
134
152
|
|
|
135
|
-
def _broadcast(self, text: str) -> None:
|
|
153
|
+
def _broadcast(self, text: str, app: str | None = None) -> None:
|
|
136
154
|
frame = ws_frame(text)
|
|
137
155
|
for sock in list(self.sockets):
|
|
156
|
+
if app is not None and self.socket_apps.get(sock) != app:
|
|
157
|
+
continue
|
|
138
158
|
try:
|
|
139
159
|
sock.sendall(frame)
|
|
140
160
|
except OSError:
|
|
@@ -148,11 +168,19 @@ class FakeSlack:
|
|
|
148
168
|
self.calls.append({"method": method, "params": params, "rate_limited": True, "at": time.time()})
|
|
149
169
|
return 429, {"Retry-After": str(retry_after)}, {"ok": False, "error": "ratelimited"}
|
|
150
170
|
self.calls.append({"method": method, "params": params, "at": time.time()})
|
|
171
|
+
token = str(params.get("_auth", "")).removeprefix("Bearer ")
|
|
172
|
+
identity = self.identities.get(token, {"user_id": "UBOT", "bot_id": "BBOT"})
|
|
151
173
|
if method == "auth.test":
|
|
152
|
-
return 200, {}, {"ok": True,
|
|
174
|
+
return 200, {}, {"ok": True, **identity, "team_id": "T1"}
|
|
153
175
|
if method == "apps.connections.open":
|
|
154
176
|
self.connections_opened += 1
|
|
155
|
-
|
|
177
|
+
key = f"c{self.connections_opened}"
|
|
178
|
+
self.pending_apps[key] = token
|
|
179
|
+
return 200, {}, {"ok": True, "url": f"ws://127.0.0.1:{self.port}/socket?app={key}"}
|
|
180
|
+
if method == "conversations.open":
|
|
181
|
+
return 200, {}, {"ok": True, "channel": {"id": f"D{params.get('users', '')}"}}
|
|
182
|
+
if method == "chat.postMessage" and (token, params.get("channel", "")) in self.not_in_channel:
|
|
183
|
+
return 200, {}, {"ok": False, "error": "not_in_channel"}
|
|
156
184
|
if method == "chat.postMessage":
|
|
157
185
|
metadata = params.get("metadata")
|
|
158
186
|
if isinstance(metadata, str):
|
|
@@ -162,7 +190,7 @@ class FakeSlack:
|
|
|
162
190
|
"type": "message",
|
|
163
191
|
"text": params.get("text", ""),
|
|
164
192
|
"username": params.get("username"),
|
|
165
|
-
"bot_id": "
|
|
193
|
+
"bot_id": identity["bot_id"],
|
|
166
194
|
"metadata": metadata,
|
|
167
195
|
}
|
|
168
196
|
if params.get("thread_ts"):
|
|
@@ -238,6 +266,8 @@ class FakeSlack:
|
|
|
238
266
|
except OSError:
|
|
239
267
|
return
|
|
240
268
|
fake.sockets.append(sock)
|
|
269
|
+
key = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query).get("app", [""])[0]
|
|
270
|
+
fake.socket_apps[sock] = fake.pending_apps.get(key, "")
|
|
241
271
|
self.close_connection = True
|
|
242
272
|
self._read_frames(sock)
|
|
243
273
|
|
|
@@ -47,8 +47,8 @@ REQUIRED_SCRIPTS = [
|
|
|
47
47
|
"scripts/validate_plugin.py",
|
|
48
48
|
]
|
|
49
49
|
|
|
50
|
-
PACKAGE_VERSION = "5.
|
|
51
|
-
PROTOCOL_VERSION = "5.
|
|
50
|
+
PACKAGE_VERSION = "5.94.0"
|
|
51
|
+
PROTOCOL_VERSION = "5.94.0"
|
|
52
52
|
LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
|
|
53
53
|
OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
|
|
54
54
|
# Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
|
|
@@ -3421,6 +3421,381 @@ def validate_chat_bridge_inbound_scenario() -> int:
|
|
|
3421
3421
|
return 0
|
|
3422
3422
|
|
|
3423
3423
|
|
|
3424
|
+
def role_keychain(base: Path, tokens: dict[str, str]) -> Path:
|
|
3425
|
+
"""A `security` double answering only the given Keychain accounts."""
|
|
3426
|
+
script = base / "role-keychain.sh"
|
|
3427
|
+
cases = "".join(f' *"-a {account} "*|*"-a {account}") echo {token} ;;\n' for account, token in tokens.items())
|
|
3428
|
+
write_text(script, f'#!/bin/sh\ncase "$* " in\n{cases} *) exit 44 ;;\nesac\n')
|
|
3429
|
+
script.chmod(0o755)
|
|
3430
|
+
return script
|
|
3431
|
+
|
|
3432
|
+
|
|
3433
|
+
def slack_posts_of(slack, channel: str, record_id: str) -> list[dict]:
|
|
3434
|
+
return [m for m in slack.messages.get(channel, []) if (m.get("metadata") or {}).get("event_payload", {}).get("id") == record_id]
|
|
3435
|
+
|
|
3436
|
+
|
|
3437
|
+
def bot_status(cwd: Path, env: dict[str, str], bot: str) -> dict:
|
|
3438
|
+
status = chat_json(run_keel(cwd, "chat", "bridge", "status", "--json", env=env))
|
|
3439
|
+
return next((entry for entry in status.get("bots") or [] if entry.get("bot") == bot), {})
|
|
3440
|
+
|
|
3441
|
+
|
|
3442
|
+
def validate_chat_role_apps_scenario() -> int:
|
|
3443
|
+
"""Issue #187: a role may post under its own Slack app.
|
|
3444
|
+
|
|
3445
|
+
`slack.bots` registers a role's bot by its user id. A role whose Keychain
|
|
3446
|
+
token `auth.test` confirms posts with that token and without a borrowed
|
|
3447
|
+
name; a token for another bot is not used; a channel the role's bot is not
|
|
3448
|
+
in falls back to the shared app; a person's mention of a role's bot wakes
|
|
3449
|
+
the role; and the bridge's own edits through a role app are not imported
|
|
3450
|
+
back as someone else's.
|
|
3451
|
+
"""
|
|
3452
|
+
label = "chat-role-apps:"
|
|
3453
|
+
if chat_bridge_node_missing("chat-role-apps"):
|
|
3454
|
+
return 3
|
|
3455
|
+
FakeSlack = fake_slack_class()
|
|
3456
|
+
with tempfile.TemporaryDirectory(prefix="keel-chat-roles-") as raw, FakeSlack() as slack:
|
|
3457
|
+
base = Path(raw)
|
|
3458
|
+
rtl, verify, env = chat_scratch_group(base)
|
|
3459
|
+
chat_slack_config(rtl, {"soc": "CSOC"}, bots={"UBOTRTL": "rtl", "UBOTVERIFY": "verify"})
|
|
3460
|
+
keychain = role_keychain(base, {"bot:rtl": "xoxb-role-rtl"})
|
|
3461
|
+
slack.identify("xoxb-role-rtl", "UBOTRTL", "BROLERTL")
|
|
3462
|
+
benv = {**chat_bridge_environment(env, base / "home", slack), "KEEL_CHAT_SECURITY": str(keychain)}
|
|
3463
|
+
|
|
3464
|
+
def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
|
|
3465
|
+
return run_keel(cwd, "chat", *args, env=benv)
|
|
3466
|
+
|
|
3467
|
+
def once() -> bool:
|
|
3468
|
+
result = chat(rtl, "bridge", "run", "--once")
|
|
3469
|
+
if result.returncode != 0:
|
|
3470
|
+
report(f"{label} bridge run --once failed: {result.stderr.strip()} {result.stdout.strip()}")
|
|
3471
|
+
return result.returncode == 0
|
|
3472
|
+
|
|
3473
|
+
chat(rtl, "bridge", "add")
|
|
3474
|
+
chat(rtl, "bot", "add", "rtl")
|
|
3475
|
+
own_id = chat_json(chat(rtl, "post", "soc", "rtl speaks", "--json")).get("id", "")
|
|
3476
|
+
shared_id = chat_json(chat(verify, "post", "soc", "verify speaks", "--json")).get("id", "")
|
|
3477
|
+
chat(rtl, "edit", own_id, "rtl speaks (v2)")
|
|
3478
|
+
if not once():
|
|
3479
|
+
return 1
|
|
3480
|
+
by_id = {slack_payload(c).get("id"): c["params"] for c in slack.calls_to("chat.postMessage") if slack_payload(c).get("id")}
|
|
3481
|
+
own = by_id.get(own_id) or {}
|
|
3482
|
+
if own.get("_auth") != "Bearer xoxb-role-rtl":
|
|
3483
|
+
report(f"{label} rtl's post did not use rtl's own app token: {own.get('_auth')!r}")
|
|
3484
|
+
return 1
|
|
3485
|
+
if own.get("username"):
|
|
3486
|
+
report(f"{label} rtl's post through its own app still borrows a name: {own.get('username')!r}")
|
|
3487
|
+
return 1
|
|
3488
|
+
other = by_id.get(shared_id) or {}
|
|
3489
|
+
if other.get("_auth") != "Bearer xoxb-test-bot":
|
|
3490
|
+
report(f"{label} verify, registered but without a token here, did not post through the shared app: {other.get('_auth')!r}")
|
|
3491
|
+
return 1
|
|
3492
|
+
if other.get("username") != "verify":
|
|
3493
|
+
report(f"{label} verify's post through the shared app is not under its name: {other.get('username')!r}")
|
|
3494
|
+
return 1
|
|
3495
|
+
own_ts = (slack_posts_of(slack, "CSOC", own_id) or [{}])[0].get("ts")
|
|
3496
|
+
updates = [c["params"] for c in slack.calls_to("chat.update") if c["params"].get("ts") == own_ts]
|
|
3497
|
+
if not updates:
|
|
3498
|
+
report(f"{label} the edit of rtl's record never called chat.update.")
|
|
3499
|
+
return 1
|
|
3500
|
+
if updates[0].get("_auth") != "Bearer xoxb-role-rtl":
|
|
3501
|
+
report(f"{label} the edit of rtl's record did not use the app that posted it: {updates[0].get('_auth')!r}")
|
|
3502
|
+
return 1
|
|
3503
|
+
if bot_status(rtl, benv, "rtl").get("roles") != ["rtl/rtl"]:
|
|
3504
|
+
report(f"{label} status does not list bot rtl serving rtl/rtl: {bot_status(rtl, benv, 'rtl')!r}")
|
|
3505
|
+
return 1
|
|
3506
|
+
if bot_status(rtl, benv, "verify"):
|
|
3507
|
+
report(f"{label} status lists verify, which has no token on this machine.")
|
|
3508
|
+
return 1
|
|
3509
|
+
|
|
3510
|
+
slack.identify("xoxb-role-rtl", "UOTHER", "BOTHER")
|
|
3511
|
+
wrong_id = chat_json(chat(rtl, "post", "soc", "after a token swap", "--json")).get("id", "")
|
|
3512
|
+
if not once():
|
|
3513
|
+
return 1
|
|
3514
|
+
wrong = next((c["params"] for c in slack.calls_to("chat.postMessage") if slack_payload(c).get("id") == wrong_id), {})
|
|
3515
|
+
if wrong.get("_auth") != "Bearer xoxb-test-bot":
|
|
3516
|
+
report(f"{label} a token whose auth.test names another bot was used for rtl: {wrong.get('_auth')!r}")
|
|
3517
|
+
return 1
|
|
3518
|
+
if wrong.get("username") != "rtl":
|
|
3519
|
+
report(f"{label} the fallback post is not under rtl's name: {wrong.get('username')!r}")
|
|
3520
|
+
return 1
|
|
3521
|
+
if bot_status(rtl, benv, "rtl").get("roles") != []:
|
|
3522
|
+
report(f"{label} status does not list the bot whose id no project maps as serving nothing: {bot_status(rtl, benv, 'rtl')!r}")
|
|
3523
|
+
return 1
|
|
3524
|
+
|
|
3525
|
+
slack.identify("xoxb-role-rtl", "UBOTRTL", "BROLERTL")
|
|
3526
|
+
slack.not_in_channel.add(("xoxb-role-rtl", "CSOC"))
|
|
3527
|
+
out_id = chat_json(chat(rtl, "post", "soc", "nobody invited me", "--json")).get("id", "")
|
|
3528
|
+
if not once():
|
|
3529
|
+
return 1
|
|
3530
|
+
landed = slack_posts_of(slack, "CSOC", out_id)
|
|
3531
|
+
if len(landed) != 1:
|
|
3532
|
+
report(f"{label} a post refused with not_in_channel landed {len(landed)} times, not once.")
|
|
3533
|
+
return 1
|
|
3534
|
+
if landed[0].get("username") != "rtl":
|
|
3535
|
+
report(f"{label} the not_in_channel fallback is not under rtl's name: {landed[0]!r}")
|
|
3536
|
+
return 1
|
|
3537
|
+
if "CSOC" not in (bot_status(rtl, benv, "rtl").get("invite") or []):
|
|
3538
|
+
report(f"{label} status does not name the channel rtl's bot must be invited to: {bot_status(rtl, benv, 'rtl')!r}")
|
|
3539
|
+
return 1
|
|
3540
|
+
slack.not_in_channel.clear()
|
|
3541
|
+
|
|
3542
|
+
bridge = start_chat_bridge(rtl, benv)
|
|
3543
|
+
try:
|
|
3544
|
+
if not slack.wait_for(lambda: slack.sockets, 10):
|
|
3545
|
+
report(f"{label} the bridge never connected: {stop_chat_bridge(bridge).strip()}")
|
|
3546
|
+
return 1
|
|
3547
|
+
slack.push(slack_event("CSOC", user="UOWNER", text="<@UBOTVERIFY> rerun please", ts="1800000001.000100"))
|
|
3548
|
+
if not slack.wait_for(lambda: chat_records_with(rtl, "soc", "rerun please")):
|
|
3549
|
+
report(f"{label} the owner's message mentioning a role's bot was not imported.")
|
|
3550
|
+
return 1
|
|
3551
|
+
mention = chat_records_with(rtl, "soc", "rerun please")[0]
|
|
3552
|
+
if "@verify rerun please" not in mention:
|
|
3553
|
+
report(f"{label} the bot mention was not rewritten to the role:\n{mention}")
|
|
3554
|
+
return 1
|
|
3555
|
+
if " - verify" not in mention:
|
|
3556
|
+
report(f"{label} the bot mention did not become a mention of verify:\n{mention}")
|
|
3557
|
+
return 1
|
|
3558
|
+
slack.push(slack_event("CSOC", subtype="message_changed", message={"ts": own_ts, "bot_id": "BROLERTL", "text": "rewritten by an echo"}, ts="1800000002.000100"))
|
|
3559
|
+
slack.push(slack_event("CSOC", user="UOWNER", text="marker after the echo", ts="1800000003.000100"))
|
|
3560
|
+
if not slack.wait_for(lambda: chat_records_with(rtl, "soc", "marker after the echo")):
|
|
3561
|
+
report(f"{label} the marker message after the echo was not imported.")
|
|
3562
|
+
return 1
|
|
3563
|
+
if chat_records_with(rtl, "soc", "rewritten by an echo"):
|
|
3564
|
+
report(f"{label} the bridge's own edit through rtl's app was imported back as an edit.")
|
|
3565
|
+
return 1
|
|
3566
|
+
finally:
|
|
3567
|
+
stop_chat_bridge(bridge)
|
|
3568
|
+
|
|
3569
|
+
if "chat-role-apps" not in {name for name, _ in SCENARIOS}:
|
|
3570
|
+
report(f"{label} scenario is not registered.")
|
|
3571
|
+
return 1
|
|
3572
|
+
report("chat-role-apps scenario passed.")
|
|
3573
|
+
return 0
|
|
3574
|
+
|
|
3575
|
+
|
|
3576
|
+
def validate_chat_role_direct_scenario() -> int:
|
|
3577
|
+
"""Issue #187: a role's own app takes direct messages.
|
|
3578
|
+
|
|
3579
|
+
With `app:<role>` beside `bot:<role>`, the bridge opens a second Socket
|
|
3580
|
+
Mode connection for that app. A registered person's direct message becomes
|
|
3581
|
+
a record in the direct group and wakes the role; the role's answer goes
|
|
3582
|
+
back to that person's direct-message channel and nowhere else; a
|
|
3583
|
+
stranger's is ignored; and one sent while the bridge was down arrives once.
|
|
3584
|
+
"""
|
|
3585
|
+
label = "chat-role-direct:"
|
|
3586
|
+
if chat_bridge_node_missing("chat-role-direct"):
|
|
3587
|
+
return 3
|
|
3588
|
+
FakeSlack = fake_slack_class()
|
|
3589
|
+
with tempfile.TemporaryDirectory(prefix="keel-chat-direct-") as raw, FakeSlack() as slack:
|
|
3590
|
+
base = Path(raw)
|
|
3591
|
+
rtl, _verify, env = chat_scratch_group(base)
|
|
3592
|
+
chat_slack_config(rtl, {"soc": "CSOC"}, bots={"UBOTRTL": "rtl"})
|
|
3593
|
+
keychain = role_keychain(base, {"bot:rtl": "xoxb-role-rtl", "app:rtl": "xapp-role-rtl"})
|
|
3594
|
+
slack.identify("xoxb-role-rtl", "UBOTRTL", "BROLERTL")
|
|
3595
|
+
benv = {**chat_bridge_environment(env, base / "home", slack), "KEEL_CHAT_SECURITY": str(keychain)}
|
|
3596
|
+
run_keel(rtl, "chat", "bridge", "add", env=benv)
|
|
3597
|
+
run_keel(rtl, "chat", "bot", "add", "rtl", env=benv)
|
|
3598
|
+
signal = mailbox_common_dir(rtl) / "keel-chat" / "signal" / "rtl"
|
|
3599
|
+
|
|
3600
|
+
def direct(user: str, text: str, ts: str) -> dict:
|
|
3601
|
+
return slack_event("DUOWNER" if user == "UOWNER" else f"D{user}", channel_type="im", user=user, text=text, ts=ts)
|
|
3602
|
+
|
|
3603
|
+
bridge = start_chat_bridge(rtl, benv)
|
|
3604
|
+
try:
|
|
3605
|
+
if not slack.wait_for(lambda: slack.sockets_for("xapp-role-rtl"), 10):
|
|
3606
|
+
report(f"{label} the bridge opened no Socket Mode connection with rtl's app token: {stop_chat_bridge(bridge).strip()}")
|
|
3607
|
+
return 1
|
|
3608
|
+
if not slack.wait_for(lambda: slack.sockets_for("xapp-test-app"), 10):
|
|
3609
|
+
report(f"{label} the shared app's connection is missing beside rtl's.")
|
|
3610
|
+
return 1
|
|
3611
|
+
size = signal.stat().st_size if signal.exists() else 0
|
|
3612
|
+
slack.push(direct("UOWNER", "status?", "1800000001.000100"), app="xapp-role-rtl")
|
|
3613
|
+
if not slack.wait_for(lambda: chat_records_with(rtl, "dm-owner--rtl", "status?")):
|
|
3614
|
+
report(f"{label} the owner's direct message to rtl's app did not reach dm-owner--rtl.")
|
|
3615
|
+
return 1
|
|
3616
|
+
if "from: owner" not in chat_records_with(rtl, "dm-owner--rtl", "status?")[0]:
|
|
3617
|
+
report(f"{label} the direct message was not recorded from owner.")
|
|
3618
|
+
return 1
|
|
3619
|
+
if not signal.exists() or signal.stat().st_size <= size:
|
|
3620
|
+
report(f"{label} the direct message did not touch rtl's signal file.")
|
|
3621
|
+
return 1
|
|
3622
|
+
|
|
3623
|
+
answered = run_keel(rtl, "chat", "dm", "owner", "all green", env=benv)
|
|
3624
|
+
if answered.returncode != 0:
|
|
3625
|
+
report(f"{label} keel chat dm owner failed: {answered.stderr.strip()}")
|
|
3626
|
+
return 1
|
|
3627
|
+
if not slack.wait_for(lambda: any("all green" in m.get("text", "") for m in slack.messages.get("DUOWNER", []))):
|
|
3628
|
+
report(f"{label} rtl's answer never reached the owner's direct-message channel.")
|
|
3629
|
+
return 1
|
|
3630
|
+
sent = [c["params"] for c in slack.calls_to("chat.postMessage") if "all green" in c["params"].get("text", "")]
|
|
3631
|
+
if len(sent) != 1:
|
|
3632
|
+
report(f"{label} rtl's answer was posted {len(sent)} times, not once.")
|
|
3633
|
+
return 1
|
|
3634
|
+
if sent[0].get("_auth") != "Bearer xoxb-role-rtl":
|
|
3635
|
+
report(f"{label} rtl's direct answer did not use rtl's app token: {sent[0].get('_auth')!r}")
|
|
3636
|
+
return 1
|
|
3637
|
+
if sent[0].get("channel") != "DUOWNER":
|
|
3638
|
+
report(f"{label} rtl's direct answer went to {sent[0].get('channel')!r}, not the owner's DUOWNER.")
|
|
3639
|
+
return 1
|
|
3640
|
+
|
|
3641
|
+
slack.push(direct("USTRANGER", "give me the keys", "1800000002.000100"), app="xapp-role-rtl")
|
|
3642
|
+
if not slack.wait_for(lambda: chat_json(run_keel(rtl, "chat", "bridge", "status", "--json", env=benv)).get("ignored") == 1):
|
|
3643
|
+
report(f"{label} a stranger's direct message was not counted as ignored.")
|
|
3644
|
+
return 1
|
|
3645
|
+
if any(chat_records_with(rtl, group, "give me the keys") for group in ("dm-owner--rtl", "dm-rtl--ustranger", "soc")):
|
|
3646
|
+
report(f"{label} a stranger's direct message reached the store.")
|
|
3647
|
+
return 1
|
|
3648
|
+
if bot_status(rtl, benv, "rtl").get("direct") is not True:
|
|
3649
|
+
report(f"{label} status does not report rtl's direct-message connection: {bot_status(rtl, benv, 'rtl')!r}")
|
|
3650
|
+
return 1
|
|
3651
|
+
finally:
|
|
3652
|
+
stop_chat_bridge(bridge)
|
|
3653
|
+
|
|
3654
|
+
slack.add_history("DUOWNER", {"user": "UOWNER", "text": "while you were away"})
|
|
3655
|
+
bridge = start_chat_bridge(rtl, benv)
|
|
3656
|
+
try:
|
|
3657
|
+
if not slack.wait_for(lambda: chat_records_with(rtl, "dm-owner--rtl", "while you were away"), 15):
|
|
3658
|
+
report(f"{label} a direct message sent while the bridge was down was not caught up.")
|
|
3659
|
+
return 1
|
|
3660
|
+
time.sleep(1)
|
|
3661
|
+
if len(chat_records_with(rtl, "dm-owner--rtl", "while you were away")) != 1:
|
|
3662
|
+
report(f"{label} the caught-up direct message was imported more than once.")
|
|
3663
|
+
return 1
|
|
3664
|
+
if len(chat_records_with(rtl, "dm-owner--rtl", "all green")) != 1:
|
|
3665
|
+
report(f"{label} catch-up imported rtl's own direct answer back.")
|
|
3666
|
+
return 1
|
|
3667
|
+
finally:
|
|
3668
|
+
stop_chat_bridge(bridge)
|
|
3669
|
+
|
|
3670
|
+
if "chat-role-direct" not in {name for name, _ in SCENARIOS}:
|
|
3671
|
+
report(f"{label} scenario is not registered.")
|
|
3672
|
+
return 1
|
|
3673
|
+
report("chat-role-direct scenario passed.")
|
|
3674
|
+
return 0
|
|
3675
|
+
|
|
3676
|
+
|
|
3677
|
+
def validate_chat_shared_bots_scenario() -> int:
|
|
3678
|
+
"""Issue #187: one registered bot is a different role in each project.
|
|
3679
|
+
|
|
3680
|
+
A bot listed once with `keel chat bot add` serves the role each project's
|
|
3681
|
+
`slack.bots` maps its id to: both projects post with its token to their own
|
|
3682
|
+
channels, a mention of it in one project's channel reaches only that
|
|
3683
|
+
project's role, and a bot serving two roles opens no direct-message
|
|
3684
|
+
connection, because a direct message cannot say which project it is for.
|
|
3685
|
+
"""
|
|
3686
|
+
label = "chat-shared-bots:"
|
|
3687
|
+
if chat_bridge_node_missing("chat-shared-bots"):
|
|
3688
|
+
return 3
|
|
3689
|
+
FakeSlack = fake_slack_class()
|
|
3690
|
+
with tempfile.TemporaryDirectory(prefix="keel-chat-shared-") as raw, FakeSlack() as slack:
|
|
3691
|
+
base = Path(raw)
|
|
3692
|
+
env = chat_environment()
|
|
3693
|
+
keychain = role_keychain(base, {"bot:pm": "xoxb-bot-pm", "app:pm": "xapp-bot-pm"})
|
|
3694
|
+
slack.identify("xoxb-bot-pm", "UBOTPM", "BBOTPM")
|
|
3695
|
+
benv = {**chat_bridge_environment(env, base / "home", slack), "KEEL_CHAT_SECURITY": str(keychain)}
|
|
3696
|
+
repos = {}
|
|
3697
|
+
for name, channel in (("a", "CA"), ("b", "CB")):
|
|
3698
|
+
repo = mailbox_repository(base / name)
|
|
3699
|
+
run_keel(repo, "chat", "role", "--set", f"{name}-pm", env=env)
|
|
3700
|
+
run_keel(repo, "chat", "group", "create", "ops", env=env)
|
|
3701
|
+
chat_slack_config(repo, {"ops": channel}, bots={"UBOTPM": f"{name}-pm"})
|
|
3702
|
+
run_keel(repo, "chat", "bridge", "add", env=benv)
|
|
3703
|
+
repos[name] = repo
|
|
3704
|
+
added = run_keel(repos["a"], "chat", "bot", "add", "pm", env=benv)
|
|
3705
|
+
if added.returncode != 0:
|
|
3706
|
+
report(f"{label} keel chat bot add pm failed: {added.stderr.strip()}")
|
|
3707
|
+
return 1
|
|
3708
|
+
listed = run_keel(repos["a"], "chat", "bot", "list", env=benv)
|
|
3709
|
+
if "pm" not in listed.stdout:
|
|
3710
|
+
report(f"{label} keel chat bot list does not show pm: {listed.stdout.strip()} {listed.stderr.strip()}")
|
|
3711
|
+
return 1
|
|
3712
|
+
if "xoxb-bot-pm" in listed.stdout + listed.stderr:
|
|
3713
|
+
report(f"{label} keel chat bot list printed a token.")
|
|
3714
|
+
return 1
|
|
3715
|
+
ids = {name: chat_json(run_keel(repo, "chat", "post", "ops", f"{name} reporting", "--json", env=benv)).get("id", "") for name, repo in repos.items()}
|
|
3716
|
+
|
|
3717
|
+
bridge = start_chat_bridge(repos["a"], benv)
|
|
3718
|
+
try:
|
|
3719
|
+
if not slack.wait_for(lambda: slack.sockets_for("xapp-test-app"), 10):
|
|
3720
|
+
report(f"{label} the bridge never connected: {stop_chat_bridge(bridge).strip()}")
|
|
3721
|
+
return 1
|
|
3722
|
+
for name, channel in (("a", "CA"), ("b", "CB")):
|
|
3723
|
+
if not slack.wait_for(lambda: slack_posts_of(slack, channel, ids[name])):
|
|
3724
|
+
report(f"{label} project {name}'s post never reached {channel}.")
|
|
3725
|
+
return 1
|
|
3726
|
+
sent = next(c["params"] for c in slack.calls_to("chat.postMessage") if slack_payload(c).get("id") == ids[name])
|
|
3727
|
+
if sent.get("_auth") != "Bearer xoxb-bot-pm":
|
|
3728
|
+
report(f"{label} project {name}'s role did not post through the shared pm bot: {sent.get('_auth')!r}")
|
|
3729
|
+
return 1
|
|
3730
|
+
slack.push(slack_event("CA", user="UOWNER", text="<@UBOTPM> status?", ts="1800000001.000100"))
|
|
3731
|
+
if not slack.wait_for(lambda: chat_records_with(repos["a"], "ops", "status?")):
|
|
3732
|
+
report(f"{label} the owner's mention of the pm bot in CA did not reach project a.")
|
|
3733
|
+
return 1
|
|
3734
|
+
if " - a-pm" not in chat_records_with(repos["a"], "ops", "status?")[0]:
|
|
3735
|
+
report(f"{label} the mention in CA did not become a mention of a-pm.")
|
|
3736
|
+
return 1
|
|
3737
|
+
if chat_records_with(repos["b"], "ops", "status?"):
|
|
3738
|
+
report(f"{label} a mention in project a's channel reached project b.")
|
|
3739
|
+
return 1
|
|
3740
|
+
if slack.sockets_for("xapp-bot-pm"):
|
|
3741
|
+
report(f"{label} a bot serving two roles opened a direct-message connection.")
|
|
3742
|
+
return 1
|
|
3743
|
+
pm = bot_status(repos["a"], benv, "pm")
|
|
3744
|
+
if sorted(pm.get("roles") or []) != ["a/a-pm", "b/b-pm"]:
|
|
3745
|
+
report(f"{label} status does not list pm serving a/a-pm and b/b-pm: {pm!r}")
|
|
3746
|
+
return 1
|
|
3747
|
+
if pm.get("direct") is not False:
|
|
3748
|
+
report(f"{label} status does not report pm's direct messages as off: {pm!r}")
|
|
3749
|
+
return 1
|
|
3750
|
+
if "2 roles" not in str(pm.get("direct_note", "")):
|
|
3751
|
+
report(f"{label} status does not say why pm's direct messages are off: {pm!r}")
|
|
3752
|
+
return 1
|
|
3753
|
+
finally:
|
|
3754
|
+
stop_chat_bridge(bridge)
|
|
3755
|
+
|
|
3756
|
+
if "chat-shared-bots" not in {name for name, _ in SCENARIOS}:
|
|
3757
|
+
report(f"{label} scenario is not registered.")
|
|
3758
|
+
return 1
|
|
3759
|
+
report("chat-shared-bots scenario passed.")
|
|
3760
|
+
return 0
|
|
3761
|
+
|
|
3762
|
+
|
|
3763
|
+
def validate_chat_role_apps_are_documented_scenario() -> int:
|
|
3764
|
+
"""Issue #187: the setup guides and READMEs describe shared bots.
|
|
3765
|
+
|
|
3766
|
+
Both guides carry the bot section — `keel chat bot add`, the Keychain
|
|
3767
|
+
accounts named by bot, the `slack.bots` mapping, that one bot serves a role
|
|
3768
|
+
in each of several projects, and that such a bot takes no direct messages
|
|
3769
|
+
— and neither still ties a token to a role or equates the app limit with a
|
|
3770
|
+
machine count.
|
|
3771
|
+
"""
|
|
3772
|
+
label = "chat-role-apps-are-documented:"
|
|
3773
|
+
guides = {
|
|
3774
|
+
"docs/chat-slack-setup.md": ("serve a role in each of several projects", "takes no direct messages"),
|
|
3775
|
+
"docs/chat-slack-setup.zh-CN.md": ("在多个项目里各当一个角色", "不接私聊"),
|
|
3776
|
+
}
|
|
3777
|
+
for relative, phrases in guides.items():
|
|
3778
|
+
text = (ROOT / relative).read_text(encoding="utf-8")
|
|
3779
|
+
for needle in ('"bots"', "keel chat bot add", "bot:<name>", "app:<name>", "chat:write.public", "im:history", *phrases):
|
|
3780
|
+
if needle not in text:
|
|
3781
|
+
report(f"{label} {relative} does not carry {needle!r}.")
|
|
3782
|
+
return 1
|
|
3783
|
+
for stale in ("bot:<role>", "which means 10 machines", "也就是最多 10 台电脑"):
|
|
3784
|
+
if stale in text:
|
|
3785
|
+
report(f"{label} {relative} still says {stale!r}.")
|
|
3786
|
+
return 1
|
|
3787
|
+
readmes = {"README.md": "one bot can serve several projects", "README.zh-CN.md": "一个 bot 可以服务多个项目"}
|
|
3788
|
+
for relative, needle in readmes.items():
|
|
3789
|
+
if needle not in (ROOT / relative).read_text(encoding="utf-8"):
|
|
3790
|
+
report(f"{label} {relative} does not say {needle!r}.")
|
|
3791
|
+
return 1
|
|
3792
|
+
if "chat-role-apps-are-documented" not in {name for name, _ in SCENARIOS}:
|
|
3793
|
+
report(f"{label} scenario is not registered.")
|
|
3794
|
+
return 1
|
|
3795
|
+
report("chat-role-apps-are-documented scenario passed.")
|
|
3796
|
+
return 0
|
|
3797
|
+
|
|
3798
|
+
|
|
3424
3799
|
def validate_chat_bridge_lifecycle_scenario() -> int:
|
|
3425
3800
|
"""Issue #187: the bridge runs unattended but stays visible and controllable.
|
|
3426
3801
|
|
|
@@ -35772,6 +36147,22 @@ SCENARIOS: tuple = (
|
|
|
35772
36147
|
"chat-bridge-lifecycle",
|
|
35773
36148
|
validate_chat_bridge_lifecycle_scenario,
|
|
35774
36149
|
),
|
|
36150
|
+
(
|
|
36151
|
+
"chat-role-apps",
|
|
36152
|
+
validate_chat_role_apps_scenario,
|
|
36153
|
+
),
|
|
36154
|
+
(
|
|
36155
|
+
"chat-role-direct",
|
|
36156
|
+
validate_chat_role_direct_scenario,
|
|
36157
|
+
),
|
|
36158
|
+
(
|
|
36159
|
+
"chat-role-apps-are-documented",
|
|
36160
|
+
validate_chat_role_apps_are_documented_scenario,
|
|
36161
|
+
),
|
|
36162
|
+
(
|
|
36163
|
+
"chat-shared-bots",
|
|
36164
|
+
validate_chat_shared_bots_scenario,
|
|
36165
|
+
),
|
|
35775
36166
|
(
|
|
35776
36167
|
"chat-archive",
|
|
35777
36168
|
validate_chat_archive_scenario,
|
package/src/core/chat/bridge.js
CHANGED
|
@@ -45,6 +45,40 @@ function readRegistry() {
|
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
+
// The bots this machine holds tokens for, by name (chat-shared-bots D1). Names
|
|
49
|
+
// only: the tokens stay in the Keychain.
|
|
50
|
+
function botsFile() {
|
|
51
|
+
return path.join(keelHome(), "chat", "bots.json");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function readBots() {
|
|
55
|
+
try {
|
|
56
|
+
const parsed = JSON.parse(fs.readFileSync(botsFile(), "utf8"));
|
|
57
|
+
return Array.isArray(parsed.bots) ? parsed.bots.filter((entry) => typeof entry === "string") : [];
|
|
58
|
+
} catch {
|
|
59
|
+
return [];
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function writeBots(bots) {
|
|
64
|
+
const file = botsFile();
|
|
65
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
66
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
67
|
+
fs.writeFileSync(temp, `${JSON.stringify({ bots: [...new Set(bots)].sort() }, null, 2)}\n`);
|
|
68
|
+
fs.renameSync(temp, file);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function addBot(name) {
|
|
72
|
+
store.checkName(name, "Bot");
|
|
73
|
+
writeBots([...readBots(), name]);
|
|
74
|
+
return name;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function removeBot(name) {
|
|
78
|
+
writeBots(readBots().filter((entry) => entry !== name));
|
|
79
|
+
return name;
|
|
80
|
+
}
|
|
81
|
+
|
|
48
82
|
function writeRegistry(projects) {
|
|
49
83
|
const file = registryFile();
|
|
50
84
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
@@ -161,9 +195,15 @@ function iconFields(project, role) {
|
|
|
161
195
|
return icon.startsWith(":") ? { icon_emoji: icon } : { icon_url: icon };
|
|
162
196
|
}
|
|
163
197
|
|
|
164
|
-
|
|
198
|
+
// The verified bot that `project` maps to `role`, or null: the role then
|
|
199
|
+
// speaks through the shared app (chat-shared-bots D2).
|
|
200
|
+
function roleApp(ctx, project, role) {
|
|
201
|
+
return (project.roleBots && project.roleBots.get(role)) || null;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async function postRecord(ctx, project, record, channel, direct = null) {
|
|
165
205
|
const { where } = project;
|
|
166
|
-
const call = (method, params) => slack.callWithRetry(method, params,
|
|
206
|
+
const call = (method, params, token = ctx.token) => slack.callWithRetry(method, params, token, {
|
|
167
207
|
onWait: (name, seconds) => ctx.log(`Slack asked to wait ${seconds}s before ${name}.`),
|
|
168
208
|
});
|
|
169
209
|
if (record.kind === "done" || record.kind === "edit" || record.kind === "retract") {
|
|
@@ -175,12 +215,19 @@ async function postRecord(ctx, project, record, channel) {
|
|
|
175
215
|
return;
|
|
176
216
|
}
|
|
177
217
|
if (record.kind === "done") {
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
await call("chat.update", { channel: target.channel, ts: target.ts, text: slackText(project, original, bodyText({ ...original, text: record.text })) });
|
|
218
|
+
// The shared app is not in a role's direct-message channel.
|
|
219
|
+
const poster = target.direct && target.as ? roleApp(ctx, project, target.as) : null;
|
|
220
|
+
await call("reactions.add", { channel: target.channel, timestamp: target.ts, name: "white_check_mark" }, poster ? poster.token : ctx.token);
|
|
182
221
|
} else {
|
|
183
|
-
|
|
222
|
+
// Slack lets only the app that posted a message change it (D4).
|
|
223
|
+
const poster = target.as ? roleApp(ctx, project, target.as) : null;
|
|
224
|
+
const token = poster ? poster.token : ctx.token;
|
|
225
|
+
if (record.kind === "edit") {
|
|
226
|
+
const original = store.findRecord(where, record.target) || {};
|
|
227
|
+
await call("chat.update", { channel: target.channel, ts: target.ts, text: slackText(project, original, bodyText({ ...original, text: record.text })) }, token);
|
|
228
|
+
} else {
|
|
229
|
+
await call("chat.delete", { channel: target.channel, ts: target.ts }, token);
|
|
230
|
+
}
|
|
184
231
|
}
|
|
185
232
|
writePosted(where, record.id, { channel: target.channel, ts: target.ts, kind: record.kind });
|
|
186
233
|
return;
|
|
@@ -198,8 +245,38 @@ async function postRecord(ctx, project, record, channel) {
|
|
|
198
245
|
if (parent && parent.ts) params.thread_ts = parent.thread_ts || parent.ts;
|
|
199
246
|
else params.text = `↳ reply to ${record.reply_to}\n${params.text}`;
|
|
200
247
|
}
|
|
201
|
-
|
|
248
|
+
if (direct) {
|
|
249
|
+
// A direct group goes to the person's direct-message channel, only ever
|
|
250
|
+
// through the role's own app (D6).
|
|
251
|
+
delete params.username;
|
|
252
|
+
delete params.icon_emoji;
|
|
253
|
+
delete params.icon_url;
|
|
254
|
+
const sent = await call("chat.postMessage", params, direct.token);
|
|
255
|
+
writePosted(where, record.id, { channel, ts: sent.ts, thread_ts: params.thread_ts || null, as: direct.role, direct: true });
|
|
256
|
+
rememberTs(project, channel, sent.ts, record.id);
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
const app = roleApp(ctx, project, record.from);
|
|
260
|
+
let response = null;
|
|
261
|
+
let as = null;
|
|
262
|
+
if (app) {
|
|
263
|
+
const own = { ...params };
|
|
264
|
+
delete own.username;
|
|
265
|
+
delete own.icon_emoji;
|
|
266
|
+
delete own.icon_url;
|
|
267
|
+
try {
|
|
268
|
+
response = await call("chat.postMessage", own, app.token);
|
|
269
|
+
as = record.from;
|
|
270
|
+
} catch (error) {
|
|
271
|
+
// A private channel nobody invited the role's bot to: the record goes
|
|
272
|
+
// out through the shared app, and status says where to invite it (D4).
|
|
273
|
+
if (!(error instanceof slack.SlackError) || error.error !== "not_in_channel") throw error;
|
|
274
|
+
app.invite.add(channel);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
if (!response) response = await call("chat.postMessage", params);
|
|
202
278
|
const posted = { channel, ts: response.ts, thread_ts: params.thread_ts || null };
|
|
279
|
+
if (as) posted.as = as;
|
|
203
280
|
writePosted(where, record.id, posted);
|
|
204
281
|
rememberTs(project, channel, response.ts, record.id);
|
|
205
282
|
// Another project on this machine that maps the same channel gets the
|
|
@@ -222,14 +299,53 @@ function pendingOutbound(project) {
|
|
|
222
299
|
pending.push({ record, channel });
|
|
223
300
|
}
|
|
224
301
|
}
|
|
302
|
+
for (const { app, user, group } of directGroups(project)) {
|
|
303
|
+
for (const record of store.readLog(where, group)) {
|
|
304
|
+
if (!OUTBOUND_ORIGINS.has(record.origin || "local") || record.from !== app.role || !DIRECT_KINDS.has(record.kind)) continue;
|
|
305
|
+
if (readPosted(where, record.id)) continue;
|
|
306
|
+
pending.push({ record, channel: null, direct: { app, user } });
|
|
307
|
+
}
|
|
308
|
+
}
|
|
225
309
|
return pending.sort((a, b) => (a.record.id < b.record.id ? -1 : 1));
|
|
226
310
|
}
|
|
227
311
|
|
|
312
|
+
const DIRECT_KINDS = new Set(["message", "todo", "done", "edit", "retract"]);
|
|
313
|
+
|
|
314
|
+
// Bots that take direct messages: verified, with an app-level token, and
|
|
315
|
+
// serving exactly one role, since a direct message cannot say which project it
|
|
316
|
+
// is for (chat-shared-bots D4).
|
|
317
|
+
function directApps(ctx) {
|
|
318
|
+
return [...(ctx.bots || new Map()).values()].filter((app) => app.state === "verified" && app.appToken && app.serves.length === 1);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// Each direct group between a registered person and a role whose app takes
|
|
322
|
+
// direct messages for this project.
|
|
323
|
+
function directGroups(project) {
|
|
324
|
+
const result = [];
|
|
325
|
+
for (const app of project.directApps || []) {
|
|
326
|
+
for (const [user, person] of Object.entries(project.settings.members)) {
|
|
327
|
+
if (person === app.role) continue;
|
|
328
|
+
const group = store.directName(person, app.role);
|
|
329
|
+
result.push({ app, user, person, group });
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
return result;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
async function imChannel(ctx, app, user) {
|
|
336
|
+
if (!app.ims.has(user)) {
|
|
337
|
+
const opened = await slack.callWithRetry("conversations.open", { users: user }, app.token);
|
|
338
|
+
app.ims.set(user, opened.channel && opened.channel.id);
|
|
339
|
+
}
|
|
340
|
+
return app.ims.get(user);
|
|
341
|
+
}
|
|
342
|
+
|
|
228
343
|
async function flushOutbound(ctx) {
|
|
229
344
|
let posted = 0;
|
|
230
345
|
for (const project of ctx.projects) {
|
|
231
|
-
for (const { record, channel } of pendingOutbound(project)) {
|
|
232
|
-
await postRecord(ctx, project, record,
|
|
346
|
+
for (const { record, channel, direct } of pendingOutbound(project)) {
|
|
347
|
+
if (direct) await postRecord(ctx, project, record, await imChannel(ctx, direct.app, direct.user), direct.app);
|
|
348
|
+
else await postRecord(ctx, project, record, channel);
|
|
233
349
|
posted += 1;
|
|
234
350
|
}
|
|
235
351
|
}
|
|
@@ -323,12 +439,13 @@ async function handleBotMessage(ctx, channel, event) {
|
|
|
323
439
|
// This bridge's own posts without a record — its online and stopped
|
|
324
440
|
// notices — carry nothing to import.
|
|
325
441
|
if (event.bot_id && event.bot_id === ctx.self.bot_id && !event.metadata) return;
|
|
442
|
+
const own = ctx.ownBots.has(event.bot_id);
|
|
326
443
|
const metadata = await metadataOf(ctx, channel, event);
|
|
327
444
|
if (!metadata || metadata.event_type !== METADATA_TYPE) return;
|
|
328
445
|
const payload = metadata.event_payload || {};
|
|
329
446
|
for (const project of projectsFor(ctx, channel)) {
|
|
330
447
|
// This bridge's own post, for this project, is already the local record.
|
|
331
|
-
if (
|
|
448
|
+
if (own && payload.project === project.where.project) continue;
|
|
332
449
|
importKeelRecord(ctx, project, channel, payload, event);
|
|
333
450
|
}
|
|
334
451
|
}
|
|
@@ -353,7 +470,7 @@ function lenientMentions(project, group, text) {
|
|
|
353
470
|
|
|
354
471
|
function humanText(project, event) {
|
|
355
472
|
let text = String(event.text || "").replace(/<@([A-Z0-9]+)(\|[^>]*)?>/g, (match, user) => {
|
|
356
|
-
const role = project.settings.members[user];
|
|
473
|
+
const role = project.settings.members[user] || project.settings.bots[user];
|
|
357
474
|
return role ? `@${role}` : match;
|
|
358
475
|
});
|
|
359
476
|
for (const file of event.files || []) {
|
|
@@ -393,7 +510,7 @@ function handleHumanMessage(ctx, channel, event) {
|
|
|
393
510
|
imported = true;
|
|
394
511
|
}
|
|
395
512
|
// Someone no project registered: never relayed, only counted (D16).
|
|
396
|
-
if (!registered && event.user
|
|
513
|
+
if (!registered && !ctx.ownUsers.has(event.user)) ctx.stats.ignored += 1;
|
|
397
514
|
return imported;
|
|
398
515
|
}
|
|
399
516
|
|
|
@@ -404,7 +521,7 @@ function authorOf(project, message) {
|
|
|
404
521
|
|
|
405
522
|
function handleChanged(ctx, channel, event) {
|
|
406
523
|
const message = event.message || {};
|
|
407
|
-
if (message.bot_id &&
|
|
524
|
+
if (message.bot_id && ctx.ownBots.has(message.bot_id)) return;
|
|
408
525
|
for (const project of projectsFor(ctx, channel)) {
|
|
409
526
|
const id = recordAt(project, channel, message.ts);
|
|
410
527
|
if (!id) continue;
|
|
@@ -422,7 +539,7 @@ function handleChanged(ctx, channel, event) {
|
|
|
422
539
|
|
|
423
540
|
function handleDeleted(ctx, channel, event) {
|
|
424
541
|
const previous = event.previous_message || {};
|
|
425
|
-
if (previous.bot_id &&
|
|
542
|
+
if (previous.bot_id && ctx.ownBots.has(previous.bot_id)) return;
|
|
426
543
|
const ts = event.deleted_ts || previous.ts;
|
|
427
544
|
for (const project of projectsFor(ctx, channel)) {
|
|
428
545
|
const id = recordAt(project, channel, ts);
|
|
@@ -436,7 +553,7 @@ function handleDeleted(ctx, channel, event) {
|
|
|
436
553
|
}
|
|
437
554
|
|
|
438
555
|
function handleReaction(ctx, event) {
|
|
439
|
-
if (event.reaction !== "white_check_mark" || !event.item || event.user
|
|
556
|
+
if (event.reaction !== "white_check_mark" || !event.item || ctx.ownUsers.has(event.user)) return;
|
|
440
557
|
const channel = event.item.channel;
|
|
441
558
|
for (const project of projectsFor(ctx, channel)) {
|
|
442
559
|
const role = project.settings.members[event.user];
|
|
@@ -532,6 +649,67 @@ async function catchUp(ctx) {
|
|
|
532
649
|
}
|
|
533
650
|
}
|
|
534
651
|
|
|
652
|
+
// --- direct messages to a role's app (D6) ---------------------------------------
|
|
653
|
+
|
|
654
|
+
function handleDirectEvent(ctx, app, event) {
|
|
655
|
+
if (!event || event.type !== "message" || ![undefined, "file_share"].includes(event.subtype)) return;
|
|
656
|
+
// Its own answers, seen again by catch-up, are already local records.
|
|
657
|
+
if (event.bot_id) return;
|
|
658
|
+
ctx.stats.last_event = store.isoLocal(new Date());
|
|
659
|
+
const channel = event.channel;
|
|
660
|
+
let registered = false;
|
|
661
|
+
for (const project of ctx.projects) {
|
|
662
|
+
if (!(project.directApps || []).includes(app)) continue;
|
|
663
|
+
const person = project.settings.members[event.user];
|
|
664
|
+
noteSeen(project, channel, event.ts);
|
|
665
|
+
if (!person || person === app.role) continue;
|
|
666
|
+
registered = true;
|
|
667
|
+
if (recordAt(project, channel, event.ts)) continue;
|
|
668
|
+
const group = store.directName(person, app.role);
|
|
669
|
+
if (!store.groupState(store.readLog(project.where, group)).exists) {
|
|
670
|
+
store.createGroup(project.where, person, group, [app.role], { direct: true });
|
|
671
|
+
}
|
|
672
|
+
const record = store.writeRecord(project.where, {
|
|
673
|
+
group,
|
|
674
|
+
kind: "message",
|
|
675
|
+
from: person,
|
|
676
|
+
created: tsToIso(event.ts),
|
|
677
|
+
mentions: [],
|
|
678
|
+
origin: "slack",
|
|
679
|
+
text: humanText(project, event),
|
|
680
|
+
}, new Date(Math.round(Number(event.ts) * 1000)));
|
|
681
|
+
writePosted(project.where, record.id, { channel, ts: event.ts, origin: "slack", as: app.role, direct: true });
|
|
682
|
+
rememberTs(project, channel, event.ts, record.id);
|
|
683
|
+
}
|
|
684
|
+
if (!registered && !ctx.ownUsers.has(event.user)) ctx.stats.ignored += 1;
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
// Each registered person's direct-message channel with the role's app, from
|
|
688
|
+
// the last ts processed, through the same handler as live events.
|
|
689
|
+
async function catchUpDirect(ctx, app) {
|
|
690
|
+
const users = new Set();
|
|
691
|
+
for (const project of ctx.projects) {
|
|
692
|
+
if (!(project.directApps || []).includes(app)) continue;
|
|
693
|
+
for (const [user, person] of Object.entries(project.settings.members)) if (person !== app.role) users.add(user);
|
|
694
|
+
}
|
|
695
|
+
for (const user of users) {
|
|
696
|
+
const channel = await imChannel(ctx, app, user);
|
|
697
|
+
if (!channel) continue;
|
|
698
|
+
const seen = ctx.projects.filter((project) => (project.directApps || []).includes(app)).map((project) => lastSeen(project, channel));
|
|
699
|
+
const oldest = seen.some((ts) => !ts) ? null : seen.reduce((a, b) => (Number(a) < Number(b) ? a : b));
|
|
700
|
+
const messages = [];
|
|
701
|
+
let cursor = null;
|
|
702
|
+
do {
|
|
703
|
+
const page = await slack.callWithRetry("conversations.history", {
|
|
704
|
+
channel, oldest: oldest || undefined, limit: 200, cursor: cursor || undefined,
|
|
705
|
+
}, app.token);
|
|
706
|
+
messages.push(...(page.messages || []));
|
|
707
|
+
cursor = page.response_metadata && page.response_metadata.next_cursor;
|
|
708
|
+
} while (cursor);
|
|
709
|
+
for (const message of messages.reverse()) handleDirectEvent(ctx, app, { type: "message", channel, channel_type: "im", ...message });
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
|
|
535
713
|
// --- the running process --------------------------------------------------------
|
|
536
714
|
|
|
537
715
|
function statusFile() {
|
|
@@ -551,6 +729,7 @@ function writeStatus(ctx) {
|
|
|
551
729
|
last_event: ctx.stats.last_event,
|
|
552
730
|
ignored: ctx.stats.ignored,
|
|
553
731
|
unposted: unpostedCount(ctx.projects),
|
|
732
|
+
bots: botReport(ctx),
|
|
554
733
|
updated: store.isoLocal(new Date()),
|
|
555
734
|
};
|
|
556
735
|
const file = statusFile();
|
|
@@ -564,6 +743,59 @@ function writeStatus(ctx) {
|
|
|
564
743
|
}
|
|
565
744
|
}
|
|
566
745
|
|
|
746
|
+
// Each bot this machine lists, with the roles it serves (chat-shared-bots D5).
|
|
747
|
+
function botReport(ctx) {
|
|
748
|
+
return [...(ctx.bots || new Map()).values()].map((app) => {
|
|
749
|
+
let directNote = null;
|
|
750
|
+
if (app.state === "verified" && app.appToken && app.serves.length > 1) directNote = `off: serves ${app.serves.length} roles, and a direct message cannot say which project it is for`;
|
|
751
|
+
else if (app.state === "verified" && !app.appToken) directNote = `off: no app:${app.name} token`;
|
|
752
|
+
return {
|
|
753
|
+
bot: app.name,
|
|
754
|
+
state: app.state,
|
|
755
|
+
...(app.reason ? { reason: app.reason } : {}),
|
|
756
|
+
roles: app.serves.map((entry) => entry.label),
|
|
757
|
+
direct: Boolean(app.connected),
|
|
758
|
+
...(directNote ? { direct_note: directNote } : {}),
|
|
759
|
+
invite: [...app.invite].sort(),
|
|
760
|
+
};
|
|
761
|
+
});
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// Checks each listed bot's Keychain token with auth.test, then gives each
|
|
765
|
+
// project's role the bot its `slack.bots` maps to it (D2).
|
|
766
|
+
async function verifyBots(ctx) {
|
|
767
|
+
const bots = new Map();
|
|
768
|
+
for (const name of readBots()) {
|
|
769
|
+
const tokens = lifecycle.botTokens(name);
|
|
770
|
+
const app = { name, role: null, token: tokens.bot, appToken: tokens.app, state: "failed", reason: null, user_id: null, bot_id: null, serves: [], invite: new Set(), connected: false, socket: null, ims: new Map() };
|
|
771
|
+
if (!tokens.bot) {
|
|
772
|
+
app.reason = `no bot:${name} token in the Keychain`;
|
|
773
|
+
} else {
|
|
774
|
+
try {
|
|
775
|
+
const auth = await slack.callWithRetry("auth.test", {}, tokens.bot, { attempts: 2 });
|
|
776
|
+
app.user_id = auth.user_id || null;
|
|
777
|
+
app.bot_id = auth.bot_id || null;
|
|
778
|
+
app.state = "verified";
|
|
779
|
+
} catch (error) {
|
|
780
|
+
app.reason = error.message;
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
bots.set(name, app);
|
|
784
|
+
}
|
|
785
|
+
for (const project of ctx.projects) {
|
|
786
|
+
project.roleBots = new Map();
|
|
787
|
+
for (const app of bots.values()) {
|
|
788
|
+
if (app.state !== "verified") continue;
|
|
789
|
+
const role = project.settings.bots[app.user_id];
|
|
790
|
+
if (!role) continue;
|
|
791
|
+
project.roleBots.set(role, app);
|
|
792
|
+
app.serves.push({ project, role, label: `${project.where.project}/${role}` });
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
for (const app of bots.values()) if (app.serves.length === 1) app.role = app.serves[0].role;
|
|
796
|
+
return bots;
|
|
797
|
+
}
|
|
798
|
+
|
|
567
799
|
function readStatus() {
|
|
568
800
|
let status = {};
|
|
569
801
|
try {
|
|
@@ -592,6 +824,7 @@ function fullStatus() {
|
|
|
592
824
|
last_event: null,
|
|
593
825
|
ignored: 0,
|
|
594
826
|
unposted: 0,
|
|
827
|
+
bots: [],
|
|
595
828
|
...status,
|
|
596
829
|
paused: Boolean(until),
|
|
597
830
|
paused_until: until ? new Date(until).toISOString() : null,
|
|
@@ -624,9 +857,22 @@ async function createContext(log, { needApp }) {
|
|
|
624
857
|
connected: false,
|
|
625
858
|
stopping: false,
|
|
626
859
|
self: {},
|
|
860
|
+
queue: Promise.resolve(),
|
|
627
861
|
};
|
|
862
|
+
ctx.onHello = () => catchUp(ctx);
|
|
863
|
+
ctx.onEvent = (event) => handleEvent(ctx, event);
|
|
628
864
|
const auth = await slack.callWithRetry("auth.test", {}, bot);
|
|
629
865
|
ctx.self = { bot_id: auth.bot_id || null, user_id: auth.user_id || null };
|
|
866
|
+
ctx.bots = await verifyBots(ctx);
|
|
867
|
+
for (const project of ctx.projects) project.directApps = directApps(ctx).filter((app) => app.serves[0].project === project);
|
|
868
|
+
for (const app of directApps(ctx)) {
|
|
869
|
+
app.onHello = () => catchUpDirect(ctx, app);
|
|
870
|
+
app.onEvent = (event) => handleDirectEvent(ctx, app, event);
|
|
871
|
+
}
|
|
872
|
+
// Posts and actions through a verified role app are this bridge's own (D5).
|
|
873
|
+
const verified = [...ctx.bots.values()].filter((app) => app.state === "verified");
|
|
874
|
+
ctx.ownBots = new Set([ctx.self.bot_id, ...verified.map((app) => app.bot_id)].filter(Boolean));
|
|
875
|
+
ctx.ownUsers = new Set([ctx.self.user_id, ...verified.map((app) => app.user_id)].filter(Boolean));
|
|
630
876
|
return ctx;
|
|
631
877
|
}
|
|
632
878
|
|
|
@@ -639,14 +885,15 @@ async function runOnce(log) {
|
|
|
639
885
|
}
|
|
640
886
|
|
|
641
887
|
// Events are handled one at a time, in arrival order, so a reply never lands
|
|
642
|
-
// before the message it answers.
|
|
643
|
-
|
|
888
|
+
// before the message it answers. Every connection — the shared app's and each
|
|
889
|
+
// role app's — feeds the same queue. `conn` holds the connection's app token,
|
|
890
|
+
// its socket and state, and what to do on hello and on each event.
|
|
891
|
+
function socketSession(ctx, conn) {
|
|
644
892
|
return new Promise((resolve) => {
|
|
645
|
-
|
|
646
|
-
slack.callWithRetry("apps.connections.open", {}, ctx.appToken).then((opened) => {
|
|
893
|
+
slack.callWithRetry("apps.connections.open", {}, conn.appToken).then((opened) => {
|
|
647
894
|
if (ctx.stopping) return resolve();
|
|
648
895
|
const socket = new WebSocket(opened.url);
|
|
649
|
-
|
|
896
|
+
conn.socket = socket;
|
|
650
897
|
socket.onmessage = (message) => {
|
|
651
898
|
let data = null;
|
|
652
899
|
try {
|
|
@@ -656,9 +903,9 @@ function socketSession(ctx) {
|
|
|
656
903
|
}
|
|
657
904
|
if (data.envelope_id) socket.send(JSON.stringify({ envelope_id: data.envelope_id }));
|
|
658
905
|
if (data.type === "hello") {
|
|
659
|
-
|
|
906
|
+
conn.connected = true;
|
|
660
907
|
writeStatus(ctx);
|
|
661
|
-
queue = queue.then(() =>
|
|
908
|
+
ctx.queue = ctx.queue.then(() => conn.onHello()).then(() => writeStatus(ctx)).catch((error) => ctx.log(`catch-up failed: ${error.message}`));
|
|
662
909
|
return;
|
|
663
910
|
}
|
|
664
911
|
if (data.type === "disconnect") {
|
|
@@ -666,26 +913,47 @@ function socketSession(ctx) {
|
|
|
666
913
|
return;
|
|
667
914
|
}
|
|
668
915
|
if (data.type === "events_api" && data.payload) {
|
|
669
|
-
queue = queue
|
|
670
|
-
.then(() =>
|
|
916
|
+
ctx.queue = ctx.queue
|
|
917
|
+
.then(() => conn.onEvent(data.payload.event))
|
|
671
918
|
.then(() => writeStatus(ctx))
|
|
672
919
|
.catch((error) => ctx.log(`event failed: ${error.message}`));
|
|
673
920
|
}
|
|
674
921
|
};
|
|
675
922
|
socket.onclose = () => {
|
|
676
|
-
|
|
677
|
-
|
|
923
|
+
conn.connected = false;
|
|
924
|
+
conn.socket = null;
|
|
678
925
|
writeStatus(ctx);
|
|
679
926
|
resolve();
|
|
680
927
|
};
|
|
681
928
|
socket.onerror = () => {};
|
|
682
929
|
}, (error) => {
|
|
683
|
-
ctx.log(`could not open a Socket Mode connection: ${error.message}`);
|
|
930
|
+
ctx.log(`could not open a Socket Mode connection${conn.role ? ` for ${conn.role}'s app` : ""}: ${error.message}`);
|
|
684
931
|
resolve();
|
|
685
932
|
});
|
|
686
933
|
});
|
|
687
934
|
}
|
|
688
935
|
|
|
936
|
+
// Keeps one connection up until the bridge stops, with backoff between
|
|
937
|
+
// attempts and nothing while paused.
|
|
938
|
+
async function keepConnected(ctx, conn) {
|
|
939
|
+
let backoff = 1000;
|
|
940
|
+
while (!ctx.stopping) {
|
|
941
|
+
if (lifecycle.pausedUntil()) {
|
|
942
|
+
await slack.sleep(500);
|
|
943
|
+
continue;
|
|
944
|
+
}
|
|
945
|
+
const opened = Date.now();
|
|
946
|
+
await socketSession(ctx, conn);
|
|
947
|
+
if (ctx.stopping || lifecycle.pausedUntil()) continue;
|
|
948
|
+
backoff = Date.now() - opened > 30000 ? 1000 : Math.min(backoff * 2, 30000);
|
|
949
|
+
await slack.sleep(backoff);
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
function connections(ctx) {
|
|
954
|
+
return [ctx, ...directApps(ctx)];
|
|
955
|
+
}
|
|
956
|
+
|
|
689
957
|
function packageVersion() {
|
|
690
958
|
try {
|
|
691
959
|
return JSON.parse(fs.readFileSync(path.resolve(__dirname, "..", "..", "..", "package.json"), "utf8")).version || null;
|
|
@@ -734,7 +1002,7 @@ async function run(log) {
|
|
|
734
1002
|
clearInterval(archiveTimer);
|
|
735
1003
|
stopped = (async () => {
|
|
736
1004
|
if (reason) await Promise.race([announce(ctx, `:red_circle: ${machine} bridge stopped${reason === "signal" ? "" : ` (${reason})`}; this machine's sessions will catch up when it restarts.`), slack.sleep(5000)]);
|
|
737
|
-
if (
|
|
1005
|
+
for (const conn of connections(ctx)) if (conn.socket) conn.socket.close();
|
|
738
1006
|
})();
|
|
739
1007
|
return stopped;
|
|
740
1008
|
};
|
|
@@ -764,7 +1032,7 @@ async function run(log) {
|
|
|
764
1032
|
return;
|
|
765
1033
|
}
|
|
766
1034
|
if (lifecycle.pausedUntil()) {
|
|
767
|
-
if (
|
|
1035
|
+
for (const conn of connections(ctx)) if (conn.socket) conn.socket.close();
|
|
768
1036
|
return;
|
|
769
1037
|
}
|
|
770
1038
|
flush();
|
|
@@ -773,18 +1041,7 @@ async function run(log) {
|
|
|
773
1041
|
process.once("SIGINT", () => stop("signal"));
|
|
774
1042
|
await announce(ctx, `:large_green_circle: ${machine} bridge online, relaying ${ctx.projects.length} project${ctx.projects.length === 1 ? "" : "s"}.`);
|
|
775
1043
|
await flush();
|
|
776
|
-
|
|
777
|
-
while (!ctx.stopping) {
|
|
778
|
-
if (lifecycle.pausedUntil()) {
|
|
779
|
-
await slack.sleep(500);
|
|
780
|
-
continue;
|
|
781
|
-
}
|
|
782
|
-
const opened = Date.now();
|
|
783
|
-
await socketSession(ctx);
|
|
784
|
-
if (ctx.stopping || lifecycle.pausedUntil()) continue;
|
|
785
|
-
backoff = Date.now() - opened > 30000 ? 1000 : Math.min(backoff * 2, 30000);
|
|
786
|
-
await slack.sleep(backoff);
|
|
787
|
-
}
|
|
1044
|
+
await Promise.all(connections(ctx).map((conn) => keepConnected(ctx, conn)));
|
|
788
1045
|
if (stopped) await stopped;
|
|
789
1046
|
ctx.connected = false;
|
|
790
1047
|
writeStatus(ctx);
|
|
@@ -793,6 +1050,9 @@ async function run(log) {
|
|
|
793
1050
|
|
|
794
1051
|
module.exports = {
|
|
795
1052
|
METADATA_TYPE,
|
|
1053
|
+
addBot,
|
|
1054
|
+
readBots,
|
|
1055
|
+
removeBot,
|
|
796
1056
|
addProject,
|
|
797
1057
|
keelHome,
|
|
798
1058
|
readPosted,
|
package/src/core/chat/cli.js
CHANGED
|
@@ -38,6 +38,7 @@ const USAGE = [
|
|
|
38
38
|
"keel chat bridge install|uninstall|start|stop (the macOS login item that keeps the bridge running)",
|
|
39
39
|
"keel chat bridge pause <30m|2h|1d> | resume",
|
|
40
40
|
"keel chat bridge status [--json]",
|
|
41
|
+
"keel chat bot add|remove <name> | list (the Slack bots this machine holds Keychain tokens for, as bot:<name> and app:<name>)",
|
|
41
42
|
"keel chat notice (what is unread and addressed to you, for any host; always exits 0)",
|
|
42
43
|
"keel chat notice --check (for schedulers: no output; exit 0 only when something addressed to you is unread, else 1)",
|
|
43
44
|
"keel chat hook session-start|user-prompt-submit|file-changed|session-end (Claude Code hook; JSON on stdin)",
|
|
@@ -370,6 +371,38 @@ function dispatch(where, options) {
|
|
|
370
371
|
}
|
|
371
372
|
}
|
|
372
373
|
|
|
374
|
+
// The machine's bot list (chat-shared-bots D1). It needs no repository and
|
|
375
|
+
// shows only whether each Keychain entry exists, never its value.
|
|
376
|
+
function runBot(rest) {
|
|
377
|
+
const bridge = require("./bridge");
|
|
378
|
+
const lifecycle = require("./lifecycle");
|
|
379
|
+
const [action, name] = rest;
|
|
380
|
+
switch (action) {
|
|
381
|
+
case "add":
|
|
382
|
+
if (!name) throw new ChatError("keel chat bot add needs a bot name.");
|
|
383
|
+
out(`Listed bot ${bridge.addBot(name)}. Store its tokens as Keychain accounts bot:${name} and app:${name} of service keel-chat-slack, map its Slack user id to a role in each project's keel/chat.json slack.bots, and restart the bridge.`);
|
|
384
|
+
return 0;
|
|
385
|
+
case "remove":
|
|
386
|
+
if (!name) throw new ChatError("keel chat bot remove needs a bot name.");
|
|
387
|
+
out(`Unlisted bot ${bridge.removeBot(name)}; its Keychain entries are untouched. Restart the bridge to stop using it.`);
|
|
388
|
+
return 0;
|
|
389
|
+
case "list": {
|
|
390
|
+
const bots = bridge.readBots();
|
|
391
|
+
if (!bots.length) {
|
|
392
|
+
out("No bots listed on this machine. Add one with `keel chat bot add <name>`.");
|
|
393
|
+
return 0;
|
|
394
|
+
}
|
|
395
|
+
for (const bot of bots) {
|
|
396
|
+
const tokens = lifecycle.botTokens(bot);
|
|
397
|
+
out(`${bot}: bot token ${tokens.bot ? "stored" : "missing"}, app token ${tokens.app ? "stored" : "missing"}`);
|
|
398
|
+
}
|
|
399
|
+
return 0;
|
|
400
|
+
}
|
|
401
|
+
default:
|
|
402
|
+
throw new ChatError(`Unknown keel chat bot action ${JSON.stringify(action)}: use add, remove, or list.`);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
373
406
|
function runBridge(where, rest, options) {
|
|
374
407
|
const bridge = require("./bridge");
|
|
375
408
|
const lifecycle = require("./lifecycle");
|
|
@@ -393,6 +426,14 @@ function runBridge(where, rest, options) {
|
|
|
393
426
|
const lines = [`keel chat bridge: ${status.installed ? "installed as a login item" : "not installed"}; ${status.running ? `running (pid ${status.pid}), ${status.connected ? "connected" : "not connected"}` : "not running"}${status.paused ? `, paused until ${status.paused_until}` : ""}.`];
|
|
394
427
|
if (status.running) lines.push(`Serving ${status.projects.length} project${status.projects.length === 1 ? "" : "s"}; last event ${status.last_event || "none yet"}; ${status.unposted} waiting to send; ${status.ignored} ignored from unregistered senders.`);
|
|
395
428
|
else lines.push("Slack messages are not reaching this machine's sessions; local chat still works and nothing is lost.");
|
|
429
|
+
for (const app of status.bots || []) {
|
|
430
|
+
const parts = [`Bot ${app.bot}: ${app.state}`];
|
|
431
|
+
if (app.reason) parts.push(app.reason);
|
|
432
|
+
if (app.state === "verified") parts.push(app.roles.length ? `serves ${app.roles.join(", ")}` : "serves no role: no project's slack.bots maps its id");
|
|
433
|
+
if (app.state === "verified") parts.push(app.direct ? "direct messages connected" : `direct messages ${app.direct_note || "not connected"}`);
|
|
434
|
+
if (app.invite && app.invite.length) parts.push(`invite it to ${app.invite.join(", ")}; until then it posts through the shared app there`);
|
|
435
|
+
lines.push(`${parts.join("; ")}.`);
|
|
436
|
+
}
|
|
396
437
|
out(lines.join("\n"));
|
|
397
438
|
return 0;
|
|
398
439
|
}
|
|
@@ -502,6 +543,8 @@ function runChat(argv) {
|
|
|
502
543
|
if (options.positionals[0] === "bridge" && !["add", "remove"].includes(options.positionals[1])) {
|
|
503
544
|
return runBridge(null, options.positionals.slice(1), options);
|
|
504
545
|
}
|
|
546
|
+
// The bot list belongs to the machine, like the bridge.
|
|
547
|
+
if (options.positionals[0] === "bot") return runBot(options.positionals.slice(1));
|
|
505
548
|
// A notice is read by hosts on every prompt: outside a repository it says
|
|
506
549
|
// nothing and still exits 0.
|
|
507
550
|
if (options.positionals[0] === "notice" && !store.locate(cwd)) return 0;
|
package/src/core/chat/config.js
CHANGED
|
@@ -52,6 +52,9 @@ function slackSettings(worktree) {
|
|
|
52
52
|
error,
|
|
53
53
|
owner: typeof slack.owner === "string" ? slack.owner : null,
|
|
54
54
|
members: stringMap(slack.members),
|
|
55
|
+
// A role's own Slack app, by its bot user id (issue #187, chat-role-apps
|
|
56
|
+
// D1); a role not listed speaks through the machine's shared app.
|
|
57
|
+
bots: stringMap(slack.bots),
|
|
55
58
|
channels: stringMap(slack.channels),
|
|
56
59
|
icons: stringMap(slack.icons),
|
|
57
60
|
};
|
|
@@ -48,6 +48,13 @@ function tokens() {
|
|
|
48
48
|
return { app: app || null, bot: bot || null };
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
+
// A registered bot's tokens (chat-shared-bots D1): Keychain only, by the
|
|
52
|
+
// bot's name, because an environment variable would have to encode that name
|
|
53
|
+
// in its own.
|
|
54
|
+
function botTokens(name) {
|
|
55
|
+
return { bot: keychainToken(`bot:${name}`), app: keychainToken(`app:${name}`) };
|
|
56
|
+
}
|
|
57
|
+
|
|
51
58
|
function missingTokens(which) {
|
|
52
59
|
return new ChatError(
|
|
53
60
|
`No Slack ${which}: set KEEL_SLACK_APP_TOKEN and KEEL_SLACK_BOT_TOKEN, or store them in the macOS Keychain `
|
|
@@ -197,6 +204,7 @@ function stop() {
|
|
|
197
204
|
}
|
|
198
205
|
|
|
199
206
|
module.exports = {
|
|
207
|
+
botTokens,
|
|
200
208
|
KEYCHAIN_SERVICE,
|
|
201
209
|
LABEL,
|
|
202
210
|
bridgeDir,
|
package/src/core/chat/store.js
CHANGED
|
@@ -48,7 +48,7 @@ const FIELD_ORDER = [
|
|
|
48
48
|
const RESERVED_GROUPS = new Set([
|
|
49
49
|
"role", "group", "post", "dm", "unread", "read", "show", "list", "help",
|
|
50
50
|
"hook", "notice", "todo", "todos", "done", "edit", "retract", "search",
|
|
51
|
-
"bridge", "archive", "transcript",
|
|
51
|
+
"bridge", "archive", "transcript", "bot",
|
|
52
52
|
]);
|
|
53
53
|
|
|
54
54
|
class ChatError extends Error {}
|
|
@@ -736,6 +736,7 @@ function readGroups(where, role, group) {
|
|
|
736
736
|
}
|
|
737
737
|
|
|
738
738
|
module.exports = {
|
|
739
|
+
checkName,
|
|
739
740
|
ALL,
|
|
740
741
|
ChatError,
|
|
741
742
|
DATA_NOTICE,
|