-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
2502 lines (2160 loc) · 98 KB
/
Copy pathbot.py
File metadata and controls
2502 lines (2160 loc) · 98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import atexit
import os
import secrets
import signal
import sys
import json
import asyncio
import re
import shutil
import subprocess
import threading
import weakref
from concurrent.futures import ThreadPoolExecutor
# Windows: aiodns が SelectorEventLoop を要求する問題を回避
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
import uuid
import base64
import io
import tempfile
import logging
from pathlib import Path
from datetime import datetime, timezone
# Windows cp932 で絵文字が encode できない問題を回避
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
except (AttributeError, OSError):
pass
import discord
from discord.ext import commands
from dotenv import load_dotenv
from aiohttp import web
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
log = logging.getLogger("bridge")
# ==============================
# 設定読み込み + 起動時検証
# ==============================
def _require_int(name: str, allow_zero_for: list[str] | None = None) -> int:
raw = os.getenv(name, "").strip()
if not raw:
if allow_zero_for and name in allow_zero_for:
return 0
raise SystemExit(f"環境変数 {name} が未設定です。.env を確認してください")
try:
return int(raw)
except ValueError:
raise SystemExit(f"環境変数 {name} は整数である必要があります(現値: {raw!r})")
TOKEN = os.getenv("DISCORD_TOKEN", "").strip().lstrip("") # BOM 付き .env への防御
if not TOKEN:
raise SystemExit("環境変数 DISCORD_TOKEN が未設定です。.env を確認してください")
FORUM_CHANNEL_ID = _require_int("FORUM_CHANNEL_ID")
LOG_CHANNEL_ID = _require_int("LOG_CHANNEL_ID", allow_zero_for=["LOG_CHANNEL_ID"])
GUILD_ID = _require_int("GUILD_ID", allow_zero_for=["GUILD_ID"])
ALLOWED_USERS = set(filter(None, (x.strip() for x in os.getenv("ALLOWED_USERS", "").split(","))))
if not ALLOWED_USERS:
log.warning("ALLOWED_USERS が空です。誰もコマンドを実行できません")
SKIP_PERMISSIONS = os.getenv("SKIP_PERMISSIONS", "false").lower() in ("true", "1", "yes")
HOOK_PORT = int(os.getenv("HOOK_PORT", "8585"))
CLAUDE_BIN = os.getenv("CLAUDE_BIN", "claude")
# --permission-mode に渡す値。空なら未指定(claude のデフォルト)
VALID_PERMISSION_MODES = {"", "default", "acceptEdits", "plan", "auto", "dontAsk", "bypassPermissions"}
PERMISSION_MODE = os.getenv("PERMISSION_MODE", "").strip()
if PERMISSION_MODE not in VALID_PERMISSION_MODES:
raise SystemExit(
f"PERMISSION_MODE が不正です: {PERMISSION_MODE!r}。"
f"有効値: {sorted(VALID_PERMISSION_MODES)}"
)
if SKIP_PERMISSIONS and PERMISSION_MODE:
log.warning(
"SKIP_PERMISSIONS=true と PERMISSION_MODE=%s が同時設定されています。"
"--dangerously-skip-permissions が優先され、PERMISSION_MODE は無視されます",
PERMISSION_MODE,
)
def _validate_numeric_env(name: str, value: str, allow_float: bool = False) -> str:
if not value:
return ""
try:
v = float(value) if allow_float else int(value)
except ValueError:
raise SystemExit(f"{name} は数値である必要があります(現値: {value!r})")
if v < 0:
raise SystemExit(f"{name} は 0 以上である必要があります(現値: {value!r})")
return value
MAX_TURNS = _validate_numeric_env("MAX_TURNS", os.getenv("MAX_TURNS", "").strip())
MAX_BUDGET_USD = _validate_numeric_env("MAX_BUDGET_USD", os.getenv("MAX_BUDGET_USD", "").strip(), allow_float=True)
# hook → bot HTTP の共有秘密。ローカル他プロセスからの偽リクエスト遮断用
HOOK_AUTH_TOKEN = secrets.token_hex(16)
HOOK_AUTH_HEADER = "X-Bridge-Auth"
SESSION_ID_RE = re.compile(r"^[A-Za-z0-9_\-]{1,128}$")
def is_valid_session_id(sid: str) -> bool:
return bool(sid) and bool(SESSION_ID_RE.match(sid))
SESSIONS_FILE = Path(__file__).parent / "sessions.json"
TEMP_DIR = Path(tempfile.gettempdir()) / "discord-claude-bridge"
TEMP_DIR.mkdir(exist_ok=True)
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"}
DISCORD_FILE_LIMIT = 24 * 1024 * 1024 # 25MB から少し余裕
def _validate_timeout(name: str, default: str) -> int:
raw = os.getenv(name, default).strip()
try:
v = int(raw)
except ValueError:
raise SystemExit(f"{name} は整数である必要があります(現値: {raw!r})")
if v < 0:
raise SystemExit(f"{name} は 0 以上である必要があります(現値: {v})")
return v
SOFT_TIMEOUT = _validate_timeout("SOFT_TIMEOUT", "600") # まだ動いてるよ通知 (0 で無効)
HARD_TIMEOUT = _validate_timeout("HARD_TIMEOUT", "3600") # 強制終了 (0 で無効化したい場合は超大値推奨)
if HARD_TIMEOUT == 0:
raise SystemExit("HARD_TIMEOUT=0 は許可されていません(必ず正の値を指定してください)")
if SOFT_TIMEOUT > 0 and SOFT_TIMEOUT >= HARD_TIMEOUT:
log.warning(
"SOFT_TIMEOUT(%d) >= HARD_TIMEOUT(%d): ソフト通知より先に強制終了するため通知は表示されません",
SOFT_TIMEOUT, HARD_TIMEOUT,
)
STREAM_LINE_BUFSIZE = 16 * 1024 * 1024 # 1行あたり最大16MB(画像 base64 を含む長行に対応)
# フォーラムタグ名
TAG_RUNNING = "実行中"
TAG_COMPLETED = "完了"
TAG_ERROR = "エラー"
# 走行中の Claude subprocess を追跡(bot 終了時に確実に kill するため)
_active_procs: "weakref.WeakSet[subprocess.Popen]" = weakref.WeakSet()
_active_procs_lock = threading.Lock()
# スレッドID → 現在実行中の subprocess。/cancel から取り出して kill する
_thread_procs: dict[int, subprocess.Popen] = {}
def _register_proc(proc: subprocess.Popen, thread_id: int | None = None):
with _active_procs_lock:
_active_procs.add(proc)
if thread_id is not None:
_thread_procs[thread_id] = proc
def _unregister_thread_proc(thread_id: int | None):
if thread_id is None:
return
with _active_procs_lock:
_thread_procs.pop(thread_id, None)
def get_thread_proc(thread_id: int) -> subprocess.Popen | None:
with _active_procs_lock:
return _thread_procs.get(thread_id)
def _kill_all_procs():
with _active_procs_lock:
procs = list(_active_procs)
for p in procs:
if p.poll() is None:
try:
p.kill()
except Exception:
pass
atexit.register(_kill_all_procs)
# 自分自身の PID を bot.pid に書く(restart helper や運用者用)
_BOT_PID_FILE = Path(__file__).parent / "bot.pid"
def _write_pid_file():
try:
_BOT_PID_FILE.write_text(str(os.getpid()), encoding="utf-8")
except OSError as e:
log.warning("bot.pid 書き込み失敗: %s", e)
def _remove_pid_file():
try:
if _BOT_PID_FILE.exists():
content = _BOT_PID_FILE.read_text(encoding="utf-8").strip()
# 自分のPIDが書かれてる場合だけ削除(他の bot に上書きされてたら触らない)
if content == str(os.getpid()):
_BOT_PID_FILE.unlink()
except OSError:
pass
_write_pid_file()
atexit.register(_remove_pid_file)
# /cwd で固定された thread → cwd
thread_cwds: dict[int, str] = {}
# /usage 用の累積使用量 (thread → {"input_tokens": N, "output_tokens": N, "cost_usd": float, "turns": N})
usage_stats: dict[int, dict] = {}
# /retry 用の直前 prompt (thread → prompt 本文)
last_prompts: dict[int, str] = {}
# AskUserQuestion の「自由入力」待ち。thread_id → (request_id, user_id, hook_type)
# 次にそのユーザーが投稿したメッセージが回答として吸い上げられる
pending_freetext: dict[int, tuple[str, int, str]] = {}
# ==============================
# 権限管理
# ==============================
# request_id → asyncio.Event (ボタン押下待ち)
permission_events: dict[str, asyncio.Event] = {}
# request_id → フックに返す結果
permission_results: dict[str, dict] = {}
# thread_id → 「常に許可」されたツール名のセット
allowed_tools: dict[str, set[str]] = {}
def format_tool_detail(tool_name: str, tool_input: dict) -> str:
if tool_name == "Bash":
cmd = tool_input.get("command", "")
return f"```bash\n{cmd[:800]}\n```"
if tool_name == "Write":
path = tool_input.get("file_path", "")
content = tool_input.get("content", "")
parts = [f"**ファイル:** `{path}`"]
if content:
parts.append(f"```\n{content[:600]}\n```")
return "\n".join(parts)
if tool_name in ("Edit", "MultiEdit"):
path = tool_input.get("file_path", "")
old = tool_input.get("old_string", "")
new = tool_input.get("new_string", "")
parts = [f"**ファイル:** `{path}`"]
if old:
parts.append(f"```diff\n- {old[:200]}\n+ {new[:200]}\n```")
return "\n".join(parts)
if tool_name == "NotebookEdit":
path = tool_input.get("notebook_path", tool_input.get("file_path", ""))
return f"**ノートブック:** `{path}`"
detail = json.dumps(tool_input, ensure_ascii=False, indent=2)
if len(detail) > 500:
detail = detail[:500] + "\n..."
return f"```json\n{detail}\n```"
async def safe_send(channel, content=None, **kwargs):
"""Discord 送信を NotFound/Forbidden/HTTPException から守る"""
if channel is None:
return None
try:
return await channel.send(content=content, **kwargs)
except discord.NotFound:
log.warning("送信先チャンネル/スレッドが存在しません (削除済?)")
except discord.Forbidden:
log.warning("送信権限がありません: %s", getattr(channel, "id", "?"))
except discord.HTTPException as e:
log.warning("Discord HTTP エラー: %s", e)
return None
async def safe_edit(message, content=None, **kwargs):
if message is None:
return None
try:
return await message.edit(content=content, **kwargs)
except discord.NotFound:
log.warning("編集対象メッセージが存在しません")
except discord.Forbidden:
log.warning("メッセージ編集権限がありません")
except discord.HTTPException as e:
log.warning("Discord HTTP エラー (edit): %s", e)
return None
class PermissionView(discord.ui.View):
"""許可 / 常に許可 / 拒否 ボタン"""
def __init__(self, request_id: str, tool_name: str, thread_id: str, hook_type: str):
super().__init__(timeout=600)
self.request_id = request_id
self.tool_name = tool_name
self.thread_id = thread_id
self.hook_type = hook_type
self._resolved = False
def _make_allow(self) -> dict:
if self.hook_type == "PermissionRequest":
return {
"hookSpecificOutput": {
"hookEventName": "PermissionRequest",
"decision": {"behavior": "allow"},
}
}
return {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
}
}
def _make_deny(self, reason: str) -> dict:
if self.hook_type == "PermissionRequest":
return {
"hookSpecificOutput": {
"hookEventName": "PermissionRequest",
"decision": {"behavior": "deny", "message": reason},
}
}
return {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": reason,
}
}
def _resolve(self, result: dict) -> bool:
if self._resolved:
return False
self._resolved = True
permission_results[self.request_id] = result
ev = permission_events.get(self.request_id)
if ev:
ev.set()
return True
async def _safe_edit_response(self, interaction: discord.Interaction, content: str):
try:
await interaction.response.edit_message(content=content, view=None)
except (discord.NotFound, discord.HTTPException) as e:
# interaction 期限切れや既応答済み
log.warning("ボタン応答編集失敗: %s", e)
async def interaction_check(self, interaction: discord.Interaction) -> bool:
# ALLOWED_USERS 以外のクリックを拒否
if str(interaction.user.id) not in ALLOWED_USERS:
try:
await interaction.response.send_message("権限がありません", ephemeral=True)
except (discord.NotFound, discord.HTTPException):
pass
return False
return True
@discord.ui.button(label="許可", style=discord.ButtonStyle.green, emoji="✅")
async def allow_btn(self, interaction: discord.Interaction, button: discord.ui.Button):
if not self._resolve(self._make_allow()):
await self._safe_edit_response(interaction, "既に処理済みです")
return
self.stop()
await self._safe_edit_response(interaction, f"✅ `{self.tool_name}` を許可しました")
@discord.ui.button(label="常に許可", style=discord.ButtonStyle.blurple, emoji="🔓")
async def always_allow_btn(self, interaction: discord.Interaction, button: discord.ui.Button):
allowed_tools.setdefault(self.thread_id, set()).add(self.tool_name)
if not self._resolve(self._make_allow()):
await self._safe_edit_response(interaction, "既に処理済みです")
return
self.stop()
await self._safe_edit_response(interaction, f"🔓 `{self.tool_name}` を常に許可しました(このスレッド内)")
@discord.ui.button(label="拒否", style=discord.ButtonStyle.red, emoji="❌")
async def deny_btn(self, interaction: discord.Interaction, button: discord.ui.Button):
if not self._resolve(self._make_deny("Discordユーザーが拒否しました")):
await self._safe_edit_response(interaction, "既に処理済みです")
return
self.stop()
await self._safe_edit_response(interaction, f"❌ `{self.tool_name}` を拒否しました")
async def on_timeout(self):
# タイムアウト時は許可(フック側がタイムアウトで詰まないように)
if self.request_id in permission_events and not self._resolved:
self._resolve(self._make_allow())
class QuestionView(discord.ui.View):
"""AskUserQuestion 用: 選択肢ボタン + 自由入力ボタン"""
def __init__(self, request_id: str, thread_id: str, hook_type: str, options: list):
super().__init__(timeout=600)
self.request_id = request_id
self.thread_id = thread_id
self.hook_type = hook_type
self._resolved = False
# ボタンは最大 25 個。「その他」用に 1 枠空けて 24 個まで選択肢ボタンに
for i, label in enumerate(options[:24]):
btn = discord.ui.Button(
label=(label or f"選択肢{i+1}")[:80],
style=discord.ButtonStyle.primary,
custom_id=f"q_{request_id}_{i}",
)
btn.callback = self._make_callback(label)
self.add_item(btn)
# 「その他(自由入力)」ボタン
free_btn = discord.ui.Button(
label="その他(自由入力)",
style=discord.ButtonStyle.secondary,
emoji="✏️",
custom_id=f"q_{request_id}_free",
)
free_btn.callback = self._free_callback
self.add_item(free_btn)
async def interaction_check(self, interaction: discord.Interaction) -> bool:
if str(interaction.user.id) not in ALLOWED_USERS:
try:
await interaction.response.send_message("権限がありません", ephemeral=True)
except (discord.NotFound, discord.HTTPException):
pass
return False
return True
def _build_response(self, answer: str) -> dict:
reason = f"User answered: {answer}. Treat this as the user's answer and continue."
if self.hook_type == "PermissionRequest":
return {
"hookSpecificOutput": {
"hookEventName": "PermissionRequest",
"decision": {"behavior": "deny", "message": reason},
}
}
return {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": reason,
}
}
def _resolve(self, answer: str) -> bool:
if self._resolved:
return False
self._resolved = True
permission_results[self.request_id] = self._build_response(answer)
ev = permission_events.get(self.request_id)
if ev:
ev.set()
return True
def _make_callback(self, answer: str):
async def cb(interaction: discord.Interaction):
if not self._resolve(answer):
try:
await interaction.response.edit_message(content="既に回答済みです", view=None)
except (discord.NotFound, discord.HTTPException):
pass
return
# 自由入力待ちエントリがあればクリア
try:
tid_int = int(self.thread_id)
if pending_freetext.get(tid_int, (None, 0, ""))[0] == self.request_id:
pending_freetext.pop(tid_int, None)
except (ValueError, TypeError):
pass
self.stop()
try:
await interaction.response.edit_message(content=f"✅ 回答: {answer[:200]}", view=None)
except (discord.NotFound, discord.HTTPException) as e:
log.warning("質問応答編集失敗: %s", e)
return cb
async def _free_callback(self, interaction: discord.Interaction):
if self._resolved:
try:
await interaction.response.edit_message(content="既に回答済みです", view=None)
except (discord.NotFound, discord.HTTPException):
pass
return
# このスレッドの次メッセージを回答として吸い上げる予約
try:
tid_int = int(self.thread_id)
except (ValueError, TypeError):
return
pending_freetext[tid_int] = (self.request_id, interaction.user.id, self.hook_type)
try:
await interaction.response.edit_message(
content=(
"✏️ **自由入力モード**\n"
f"このスレッドに次にメッセージを書き込むとそれが回答になります "
f"(<@{interaction.user.id}> の投稿のみ受付、10 分でタイムアウト)"
),
view=None,
)
except (discord.NotFound, discord.HTTPException) as e:
log.warning("自由入力ボタン応答編集失敗: %s", e)
async def on_timeout(self):
if self.request_id in permission_events and not self._resolved:
# 自由入力待ちもクリア
try:
tid_int = int(self.thread_id)
if pending_freetext.get(tid_int, (None, 0, ""))[0] == self.request_id:
pending_freetext.pop(tid_int, None)
except (ValueError, TypeError):
pass
self._resolve("(タイムアウト)")
async def _handle_ask_user_question(tool_input: dict, thread_id: str, hook_type: str) -> "web.Response":
questions = tool_input.get("questions") or tool_input.get("question")
q_list = []
if isinstance(questions, list):
q_list = questions
elif isinstance(questions, dict):
q_list = [questions]
elif isinstance(questions, str):
q_list = [{"question": questions, "options": []}]
q = q_list[0] if q_list else {}
q_text = q.get("question") or q.get("header") or tool_input.get("question") or "Claude からの質問"
options: list = []
for opt in (q.get("options") or []):
if isinstance(opt, dict):
label = opt.get("label") or opt.get("name") or opt.get("value") or ""
desc = opt.get("description") or ""
options.append(f"{label}: {desc}" if desc and label else (label or desc))
elif isinstance(opt, str):
options.append(opt)
if not options:
options = ["はい", "いいえ"]
request_id = str(uuid.uuid4())
event = asyncio.Event()
permission_events[request_id] = event
thread = None
if thread_id:
try:
thread = bot.get_channel(int(thread_id))
except (ValueError, TypeError):
thread = None
if thread is None:
permission_events.pop(request_id, None)
return web.json_response(make_quick_allow(hook_type))
try:
view = QuestionView(request_id, thread_id, hook_type, options)
await thread.send(f"❓ **Claudeからの質問**\n{str(q_text)[:1500]}", view=view)
except (discord.NotFound, discord.Forbidden, discord.HTTPException) as e:
log.warning("質問送信エラー: %s", e)
permission_events.pop(request_id, None)
permission_results.pop(request_id, None)
return web.json_response(make_quick_allow(hook_type))
try:
await asyncio.wait_for(event.wait(), timeout=600)
except asyncio.TimeoutError:
pass
result = permission_results.pop(request_id, None) or make_quick_allow(hook_type)
permission_events.pop(request_id, None)
return web.json_response(result)
def make_quick_allow(hook_type: str) -> dict:
if hook_type == "PermissionRequest":
return {
"hookSpecificOutput": {
"hookEventName": "PermissionRequest",
"decision": {"behavior": "allow"},
}
}
return {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
}
}
# Claude Code が現在送る Notification の notification_type
NOTIFICATION_ICONS = {
"permission_prompt": "🔐",
"idle_prompt": "💤",
"elicitation_dialog": "📝",
"elicitation_complete": "📨",
"elicitation_response": "📬",
"auth_success": "🔑",
}
@web.middleware
async def auth_middleware(request: web.Request, handler):
# /health は認証不要
if request.path == "/health":
return await handler(request)
token = request.headers.get(HOOK_AUTH_HEADER, "")
if not secrets.compare_digest(token, HOOK_AUTH_TOKEN):
return web.json_response({"error": "unauthorized"}, status=401)
return await handler(request)
async def handle_notification(request: web.Request) -> web.Response:
try:
data = await request.json()
except (json.JSONDecodeError, ValueError):
return web.json_response({}, status=400)
message = data.get("message", "") or ""
title = data.get("title", "") or ""
ntype = data.get("notification_type", "") or ""
thread_id = data.get("thread_id", "")
thread = None
if thread_id:
try:
thread = bot.get_channel(int(thread_id))
except (ValueError, TypeError):
thread = None
if thread is None:
return web.json_response({})
icon = NOTIFICATION_ICONS.get(ntype, "🔔")
header = f"{icon} **{title or '通知'}**"
if ntype:
header += f" `{ntype}`"
parts = [header]
if message:
parts.append(str(message)[:1800])
await safe_send(thread, "\n".join(parts))
return web.json_response({})
async def handle_permission_request(request: web.Request) -> web.Response:
try:
data = await request.json()
except (json.JSONDecodeError, ValueError):
return web.json_response(make_quick_allow("PreToolUse"), status=400)
hook_type = data.get("hook_type", "PreToolUse")
tool_name = data.get("tool_name", "unknown")
tool_input = data.get("tool_input", {}) or {}
thread_id = data.get("thread_id", "")
sensitive = bool(data.get("sensitive", False))
# AskUserQuestion は選択肢ボタンとして扱う(「常に許可」の対象外)
if tool_name == "AskUserQuestion":
return await _handle_ask_user_question(tool_input, thread_id, hook_type)
# sensitive path は「常に許可」を無視(毎回確認)
if not sensitive and thread_id in allowed_tools and tool_name in allowed_tools[thread_id]:
return web.json_response(make_quick_allow(hook_type))
request_id = str(uuid.uuid4())
event = asyncio.Event()
permission_events[request_id] = event
thread = None
if thread_id:
try:
thread = bot.get_channel(int(thread_id))
except (ValueError, TypeError):
thread = None
if thread is None:
# スレッド消失/未指定 → 詰まないように許可
permission_events.pop(request_id, None)
return web.json_response(make_quick_allow(hook_type))
try:
detail = format_tool_detail(tool_name, tool_input)
view = PermissionView(request_id, tool_name, thread_id, hook_type)
if sensitive:
header = (
f"⚠️ **センシティブパスへの書き込み要求: `{tool_name}`**\n"
f"(`--dangerously-skip-permissions` でも保護されるパス。"
f"承認するとブリッジが直接書き込みます)"
)
else:
header = f"🔐 **権限リクエスト: `{tool_name}`**"
await thread.send(f"{header}\n{detail}", view=view)
except (discord.NotFound, discord.Forbidden, discord.HTTPException) as e:
log.warning("権限リクエスト送信エラー: %s", e)
permission_events.pop(request_id, None)
permission_results.pop(request_id, None)
return web.json_response(make_quick_allow(hook_type))
try:
await asyncio.wait_for(event.wait(), timeout=600)
except asyncio.TimeoutError:
pass
result = permission_results.pop(request_id, None) or make_quick_allow(hook_type)
permission_events.pop(request_id, None)
return web.json_response(result)
async def handle_health(_request: web.Request) -> web.Response:
# bot.user 等は出さない(認証無しエンドポイントなので情報漏洩を最小化)
return web.json_response({"ok": True, "ready": bot.is_ready()})
# AppRunner を保持して bot 終了時に cleanup できるようにする
_hook_runner: web.AppRunner | None = None
async def start_hook_server():
"""フックサーバーを起動。on_ready の再発火(gateway 再接続)で二重起動しないようガードする。"""
global _hook_runner
if _hook_runner is not None:
# 既に起動済み
return
app = web.Application(middlewares=[auth_middleware])
app.router.add_post("/permission", handle_permission_request)
app.router.add_post("/notification", handle_notification)
app.router.add_get("/health", handle_health)
runner = web.AppRunner(app)
await runner.setup()
try:
site = web.TCPSite(runner, "127.0.0.1", HOOK_PORT)
await site.start()
except OSError as e:
await runner.cleanup()
raise SystemExit(
f"フックサーバー起動失敗 (port {HOOK_PORT}): {e}\n"
f"既存プロセスがポートを掴んでいるか、HOOK_PORT を別の番号に変えてください"
+ (f"\nLinux で HOOK_PORT={HOOK_PORT} は特権ポートです。1024 以上を使ってください"
if HOOK_PORT < 1024 else "")
)
_hook_runner = runner
log.info("Hook サーバー起動: http://127.0.0.1:%d", HOOK_PORT)
async def stop_hook_server():
global _hook_runner
if _hook_runner is not None:
try:
await _hook_runner.cleanup()
except Exception as e:
log.warning("フックサーバー cleanup 失敗: %s", e)
_hook_runner = None
_HOOK_SETTINGS_PATH: str | None = None
def build_hook_settings() -> str:
"""フック設定 JSON を生成して書き込む。並行書き込みを避けるため atomic rename。"""
base_dir = Path(__file__).parent.resolve()
pretooluse_script = str(base_dir / "hook_pretooluse.py")
permission_script = str(base_dir / "hook_permission_request.py")
notification_script = str(base_dir / "hook_notification.py")
settings = {
"hooks": {
"PreToolUse": [{
"hooks": [{
"type": "command",
"command": f'"{sys.executable}" "{pretooluse_script}"',
"timeout": 600,
}],
}],
"PermissionRequest": [{
"hooks": [{
"type": "command",
"command": f'"{sys.executable}" "{permission_script}"',
"timeout": 600,
}],
}],
"Notification": [{
"hooks": [{
"type": "command",
"command": f'"{sys.executable}" "{notification_script}"',
"timeout": 30,
}],
}],
},
}
settings_path = base_dir / ".claude_hook_settings.json"
tmp_path = settings_path.with_suffix(".json.tmp")
try:
tmp_path.write_text(json.dumps(settings, indent=2), encoding="utf-8")
os.replace(tmp_path, settings_path)
except OSError as e:
raise SystemExit(
f"フック設定ファイルの書き込みに失敗しました ({settings_path}): {e}\n"
f"ディスク容量とディレクトリの書き込み権限を確認してください"
)
return str(settings_path)
def _ensure_hook_settings_path() -> str:
"""起動時に1回だけ生成。並行 run_claude による race を回避する。"""
global _HOOK_SETTINGS_PATH
if _HOOK_SETTINGS_PATH is None:
_HOOK_SETTINGS_PATH = build_hook_settings()
return _HOOK_SETTINGS_PATH
# ==============================
# セッション管理
# ==============================
def load_sessions() -> dict:
# 前回 atomic rename が完了せず .tmp が残っているケースを救済
tmp = SESSIONS_FILE.with_suffix(".json.tmp")
if tmp.exists():
try:
if not SESSIONS_FILE.exists() or tmp.stat().st_mtime > SESSIONS_FILE.stat().st_mtime:
log.warning("%s が残存。本体より新しいので復旧します", tmp)
os.replace(tmp, SESSIONS_FILE)
else:
tmp.unlink(missing_ok=True)
except OSError as e:
log.warning("sessions.json.tmp 処理失敗: %s", e)
if not SESSIONS_FILE.exists():
return {}
try:
data = json.loads(SESSIONS_FILE.read_text(encoding="utf-8"))
if not isinstance(data, dict):
log.warning("%s が辞書形式ではありません。リセットします", SESSIONS_FILE)
return {}
return data
except (json.JSONDecodeError, OSError) as e:
log.warning("%s 読み込み失敗 (%s)。空のセッションで開始", SESSIONS_FILE, e)
return {}
def save_sessions(sessions: dict):
# 中断時に壊れないよう一旦 .tmp に書いて rename
tmp = SESSIONS_FILE.with_suffix(".json.tmp")
try:
tmp.write_text(json.dumps(sessions, indent=2, ensure_ascii=False), encoding="utf-8")
os.replace(tmp, SESSIONS_FILE)
except OSError as e:
log.error("セッション保存失敗: %s", e)
# ==============================
# Claude Code 実行
# ==============================
ANSI_RE = re.compile(r"\x1B\[[0-9;]*[a-zA-Z]")
def strip_ansi(text: str) -> str:
return ANSI_RE.sub("", text)
def _extract_images_from_blocks(blocks, images: list):
if not isinstance(blocks, list):
return
for b in blocks:
if not isinstance(b, dict):
continue
btype = b.get("type")
if btype == "image":
src = b.get("source", {}) or {}
if src.get("type") == "base64":
try:
data = base64.b64decode(src.get("data", ""))
except (ValueError, TypeError) as e:
log.warning("画像デコードエラー: %s", e)
continue
if not data:
log.warning("0バイト画像をスキップ")
continue
if len(data) > DISCORD_FILE_LIMIT:
log.warning("画像が大きすぎ (%d bytes), スキップ", len(data))
continue
media = src.get("media_type", "image/png")
ext = media.split("/")[-1] or "png"
images.append((data, f"image_{len(images)}.{ext}"))
elif btype == "tool_result":
_extract_images_from_blocks(b.get("content"), images)
# --resume が失敗したことを示唆する stderr パターン
_RESUME_FAIL_PATTERNS = (
"session not found",
"no such session",
"could not find session",
"session does not exist",
"session id not found",
)
def _stderr_indicates_resume_fail(stderr: str) -> bool:
if not stderr:
return False
s = stderr.lower()
return any(p in s for p in _RESUME_FAIL_PATTERNS)
def parse_stream_events(events: list, stderr: str, session_id: str | None) -> tuple[str, str | None, list, bool]:
"""戻り値: (output, new_session_id, images, is_error)"""
new_session_id = session_id
final_text = ""
fallback_text_parts: list[str] = []
images: list[tuple[bytes, str]] = []
is_error = False
error_msg = ""
result_subtype = ""
saw_result = False
for ev in events:
if not isinstance(ev, dict):
continue
etype = ev.get("type")
if etype == "system":
# init 以外の system サブタイプ (api_retry/compact_boundary 等) でも session_id を更新
new_session_id = ev.get("session_id") or new_session_id
elif etype == "assistant":
msg = ev.get("message") or {}
content = msg.get("content") if isinstance(msg, dict) else None
if isinstance(content, list):
for b in content:
if not isinstance(b, dict):
continue
if b.get("type") == "text":
fallback_text_parts.append(b.get("text", "") or "")
elif b.get("type") == "image":
_extract_images_from_blocks([b], images)
elif isinstance(content, str):
# SDK 仕様で content が string になる場合があるので拾う
fallback_text_parts.append(content)
elif etype == "user":
msg = ev.get("message") or {}
content = msg.get("content") if isinstance(msg, dict) else None
_extract_images_from_blocks(content, images)
elif etype == "result":
saw_result = True
new_session_id = ev.get("session_id") or new_session_id
is_error = bool(ev.get("is_error"))
result_subtype = ev.get("subtype", "") or ""
r = ev.get("result", "")
if isinstance(r, str):
final_text = r
error_msg = ev.get("error", "") or ""
# tool_use / tool_result / partial_message / hook_event / その他未知タイプは無視
# subtype が error_* なら成功でも実質失敗として扱う
if result_subtype.startswith("error_"):
is_error = True
if not error_msg:
error_msg = f"Claude Code: {result_subtype}"
# result イベントすら来なかった = subprocess が起動失敗 or auth エラー等
if not saw_result and stderr:
is_error = True
output = final_text or "\n".join(p for p in fallback_text_parts if p).strip()
if is_error and not output:
output = f"エラー: {error_msg or stderr or '不明なエラー'}"
elif is_error and stderr:
# 正常 output がある場合でも stderr を補足で添える (1500→2500字)
output = f"{output}\n\n---\nstderr (抜粋): {stderr.strip()[:1500]}"
if not output and stderr:
# auth エラー等を可視化(2500字まで)
output = f"エラー: {stderr.strip()[:2500]}"
if not output and not images:
output = "(Claude Codeからの応答が空でした。再度試してください)"
return output.strip(), new_session_id, images, is_error
def _drain_stderr(stream, sink: list):
"""stderr を別スレッドで読み、stdout 待機中の deadlock を防ぐ"""
try:
for line in iter(stream.readline, b""):
if not line:
break
sink.append(line)
except (OSError, ValueError):
pass
finally:
try:
stream.close()
except Exception:
pass