@dotlabo/agent-chat-relay 0.0.0-stage → 0.2.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +109 -0
  2. package/LICENSE +21 -0
  3. package/README.md +154 -2
  4. package/bin/agent-chat-relay +22 -0
  5. package/package.json +69 -4
  6. package/src/connectors/chatwork.ts +289 -0
  7. package/src/connectors/common.ts +106 -0
  8. package/src/connectors/discord.ts +335 -0
  9. package/src/connectors/http.ts +137 -0
  10. package/src/connectors/line-media.ts +63 -0
  11. package/src/connectors/line.ts +444 -0
  12. package/src/connectors/terminal.ts +367 -0
  13. package/src/core/access.ts +250 -0
  14. package/src/core/instructions.ts +21 -0
  15. package/src/core/mcp.ts +160 -0
  16. package/src/core/relay.ts +1063 -0
  17. package/src/core/retention.ts +44 -0
  18. package/src/harness/config.ts +137 -0
  19. package/src/harness/harness.ts +327 -0
  20. package/src/harness/log-file.ts +34 -0
  21. package/src/harness/pi/config.ts +51 -0
  22. package/src/harness/pi/state.ts +97 -0
  23. package/src/harness/pi/tool-approval.ts +128 -0
  24. package/src/harness/protect.ts +37 -0
  25. package/src/home.ts +67 -0
  26. package/src/jev.ts +201 -0
  27. package/src/main.ts +275 -0
  28. package/src/prompt.ts +12 -0
  29. package/src/serve-args.ts +56 -0
  30. package/src/shutdown.ts +52 -0
  31. package/src/terminal.ts +172 -0
  32. package/src/vendor/pi/adapter.js +3238 -0
  33. package/src/vendor/pi/managed-extension.ts +94 -0
  34. package/src/vendor/pi/managed-pi-rpc.ts +102 -0
  35. package/src/vendor/pi/managed-read.ts +99 -0
  36. package/src/vendor/pi/package.json +7 -0
  37. package/src/vendor/pi/pi-LICENSE +21 -0
  38. package/src/vendor/pi/pi-acp-LICENSE +21 -0
  39. package/src/version.ts +4 -0
  40. package/src/workspace.ts +117 -0
@@ -0,0 +1,1063 @@
1
+ // 中核(ADR 0006)。コネクターから受けた発言を、ルームの登録と送信者の許可で絞って記録し、
2
+ // セッションにまとめて渡す。チャット用ツール(MCP)からの送信と、実行承認の中継も担当する。
3
+
4
+ import { randomInt } from "node:crypto"
5
+ import { realpathSync, statSync } from "node:fs"
6
+ import { basename, isAbsolute, relative, resolve, sep } from "node:path"
7
+ import { AccessStore, canSendTo, serviceOf, type GateResult, type ReceiveMode } from "./access.ts"
8
+ import { INSTRUCTIONS } from "./instructions.ts"
9
+
10
+ type LogFn = (msg: string, extra?: Record<string, unknown>) => void
11
+ /** info は通常の通知、error は失敗 */
12
+ export type Log = { info: LogFn; error: LogFn }
13
+
14
+ export type Attachment = { name: string; type: string; size?: number }
15
+
16
+ export type ChatMessage = {
17
+ id: string
18
+ room: string
19
+ sender: string
20
+ senderName?: string
21
+ text: string
22
+ ts: number
23
+ attachments: Attachment[]
24
+ fromMe?: boolean
25
+ }
26
+
27
+ export type Incoming = ChatMessage & {
28
+ isDM: boolean
29
+ mentioned: boolean
30
+ /** 送信者以外の人への宛てがある(Inbound.toOthers。ADR 0028) */
31
+ toOthers?: boolean
32
+ /** 中継が止まっている間に届いた発言。登録したルームと許可した人の DM のものは記録だけして、エージェントには渡さない */
33
+ stale?: boolean
34
+ /** 別の側の作業中でも、その作業に差し込む(端末の /now。ADR 0030) */
35
+ cutIn?: boolean
36
+ }
37
+
38
+ /** コネクターが申告する、送れるものの上限。中核は、これで送る前に確認し、エージェントへの案内を組み立てる */
39
+ export type Capabilities = {
40
+ /** 送れるファイル。送れなければ書かない */
41
+ files?: {
42
+ /** 送れる種類(案内に書く。例:「JPEG と PNG の画像」)。種類を問わなければ書かない */
43
+ kinds?: string
44
+ maxBytes: number
45
+ /** 1 回に送れる数 */
46
+ maxCount: number
47
+ }
48
+ /** 本文の 1 通の上限(文字数)と、超えたときに分けて送る通数の上限(1 なら分けずに切り詰める) */
49
+ text: { max: number; parts: number }
50
+ }
51
+
52
+ /** コネクターによっては使えない操作(Connector の省略できるメソッド) */
53
+ export type OptionalOperation = "react" | "edit" | "history" | "createThread"
54
+
55
+ /** receive の結果。acknowledge なら、コネクターが受け取りの合図を出す(ADR 0012) */
56
+ export type ReceiveResult = GateResult & { acknowledge?: boolean }
57
+
58
+ /** 中継の HTTP サーバーに追加するルート(Webhook など)。中継が 1 つのサーバーにまとめて開く */
59
+ export type Routes = Bun.Serve.Routes<undefined, string>
60
+
61
+ /** チャットサービスごとのコネクター */
62
+ export interface Connector {
63
+ /** ID の先頭(line、chatwork など) */
64
+ readonly service: string
65
+ /** 案内に出すサービスの名前 */
66
+ readonly label: string
67
+ readonly capabilities: Capabilities
68
+ /**
69
+ * 「親/子」の ID(Discord のスレッドなど)を使うか。使うコネクターは、子が本当にその親の中にあるかを、送るときに確認する
70
+ * (中核は、子の ID を親の登録で通すため)。使わないコネクターへは、その形の ID で送らない
71
+ */
72
+ readonly nestedRooms?: boolean
73
+ /**
74
+ * このサービスの発言を、ほかのサービスの発言と同じターンに入れない(管理者の端末。ADR 0030)。
75
+ * 作業中のターンが別の側のものなら、差し込まずに待ち、届いた順に別のターンとして渡す
76
+ */
77
+ readonly ownTurns?: boolean
78
+ /** HTTP のエンドポイントが必要なら、そのルート */
79
+ readonly routes?: Routes
80
+ /** 受け取りを始める(ポーリング、常時接続など)。エンドポイントだけで受けるなら、何もしなくてよい */
81
+ start(): Promise<void>
82
+ stop(): void
83
+ /** ルームへ送る。files は中継が確認した、作業ディレクトリの中のファイルの実パス。送ったメッセージの ID を返す */
84
+ send(room: string, text: string, opts?: { replyTo?: string; files?: string[] }): Promise<string[]>
85
+ /** 承認者の DM へ、実行承認の依頼を送る */
86
+ sendApproval(user: string, text: string, requestId: string, opts?: { always?: boolean }): Promise<void>
87
+ /**
88
+ * 直前の発言への返事として、短い案内を送る(ペアリングのコードなど)。送れる手段がないときは何もせず、false を返す。
89
+ * push は、返事として送れないとき、通数を使って送ってよいこと。通数がルームの人数分になるところ(LINE のグループ)では、使わない(ADR 0024)
90
+ */
91
+ notice(room: string, text: string, opts?: { push?: boolean }): Promise<boolean>
92
+ /** 添付をローカルに取得し、パスを返す */
93
+ download(room: string, messageId: string, dir: string): Promise<string[]>
94
+ roomName(room: string): Promise<string | undefined>
95
+ react?(room: string, messageId: string, emoji: string): Promise<void>
96
+ edit?(room: string, messageId: string, text: string): Promise<void>
97
+ /** ルームの最近の発言を、サービスの履歴から古い順に読む。なければ、中継の記録を使う */
98
+ history?(room: string, limit: number): Promise<ChatMessage[]>
99
+ /** ルームの発言からスレッドを作り、スレッドのルームの ID(親/子)を返す。その発言にスレッドがあれば、それを返す */
100
+ createThread?(room: string, messageId: string, name: string): Promise<string>
101
+ }
102
+
103
+ /** 環境変数(秘密情報)からコネクターを作る。秘密情報がなければ undefined */
104
+ export type ConnectorFactory = (env: Record<string, string | undefined>, deps: ConnectorDeps) => Connector | undefined
105
+
106
+ /** コネクターを作るときに渡すもの */
107
+ export type ConnectorDeps = {
108
+ relay: Relay
109
+ log: Log
110
+ /** 中継のデータの置き場(RELAY_HOME)。コネクターは、この下に自分のファイルを置ける */
111
+ home: string
112
+ }
113
+
114
+ /** 発言を渡す先のセッション(ACP のハーネス)。prompt はターンが終わると解決する */
115
+ export interface Session {
116
+ prompt(text: string): Promise<void>
117
+ /**
118
+ * 作業中のターンに発言を差し込む(ADR 0018)。ハーネスが対応していなければ持たない。
119
+ * 差し込めたら true。ターンがすでに終わっていて差し込めなかったら false(発言は渡っていない)
120
+ */
121
+ steer?(text: string): Promise<boolean>
122
+ }
123
+
124
+ /**
125
+ * always は、ハーネスが示した「常に許可」の範囲(選択肢の名前)。示されていなければ書かない。
126
+ * agentText は、そのターンでエージェントが書いた文。承認依頼の送り先を推すのに使う(ADR 0026)
127
+ */
128
+ export type PermissionRequest = { title: string; input: string; always?: string; agentText?: string; requireFullDisplay?: true }
129
+
130
+ /**
131
+ * 送り先を推すときに渡す、そのターンの発言。sender は ID(推した結果を戻すのにだけ使い、外へは送らない)。
132
+ * name は表示名、room はルームの名前(DM なら「DM」)で、なければ空。ID では補わない
133
+ */
134
+ export type AttributionMessage = { sender: string; name: string; room: string; mentioned: boolean; text: string }
135
+ export type AttributionQuery = { title: string; input: string; agentText: string; messages: AttributionMessage[] }
136
+ /** 推した依頼者と、その確率。下限に届かないなど、推せなければ undefined */
137
+ export type Attributor = (q: AttributionQuery) => Promise<{ sender: string; probability: number } | undefined>
138
+ /**
139
+ * 他人宛ての判定(ADR 0029)に渡す発言。sender は、同じ人に同じ名前を付けるのにだけ使い、外へは送らない。
140
+ * fromMe は Bot の発言。name は表示名で、なければ空
141
+ */
142
+ export type ScreenMessage = { sender: string; name: string; fromMe: boolean; text: string }
143
+ /** service はサービスの名前、room はルームの名前(なければ空)。recent は、同じルームの直前の発言(古い順) */
144
+ export type ScreenQuery = { service: string; room: string; recent: ScreenMessage[]; message: ScreenMessage }
145
+ /** drop なら、他人宛てとして外す。probabilities はログに書く。判定できなければ undefined(渡す) */
146
+ export type Screener = (q: ScreenQuery) => Promise<{ drop: boolean; probabilities: Record<string, number> } | undefined>
147
+ /** always は「常に許可」(ADR 0015) */
148
+ export type Verdict = "allow" | "always" | "deny"
149
+
150
+ /**
151
+ * ハーネスの途中経過(ADR 0030)。text はエージェントが書いた文の続き。tool はツールの実行で、id は同じツールの行を更新するのにだけ使い、表示しない
152
+ */
153
+ export type Progress = { kind: "text"; text: string } | { kind: "tool"; id: string; title: string; status?: string }
154
+
155
+ /**
156
+ * 中継の状態(ADR 0030)。turn は作業中のターンで、lane はその側(ownTurns のサービス。ほかのルームなら空)、rooms はそのターンに発言を渡したルームの名前。
157
+ * approvals は答えを待っている承認依頼の数、queued は側ごとの、まだ渡していない発言の数。
158
+ * steering は、作業中のターンに差し込めるか(ハーネスが対応していて、差し込みに失敗していない。ADR 0018)。差し込めなければ、cutIn の発言も次のターンを待つ
159
+ */
160
+ export type RelayStatus = { turn?: { lane: string; rooms: string[] }; approvals: number; queued: Record<string, number>; steering: boolean }
161
+
162
+ /** 中継が見ている人(管理者の端末)へ流すもの。sent は、エージェントが reply で送った発言 */
163
+ export type RelayEvent =
164
+ | { type: "status"; status: RelayStatus }
165
+ | { type: "progress"; progress: Progress }
166
+ | { type: "sent"; room: string; name?: string; text: string }
167
+
168
+ // 承認の返事。ID は 5 文字で、l(1 と紛らわしい)は使わない
169
+ const PERMISSION_REPLY_RE = /^\s*(y|yes|n|no|always)\s+([a-km-z]{5})\s*$/i
170
+ const PERMISSION_TIMEOUT_MS = 30 * 60 * 1000
171
+ /** 承認依頼の束(ADR 0014)。最後の依頼からこの時間、次の依頼が来なければ送る。最初の依頼からは最大 maxMs 待つ */
172
+ const BATCHING = { quietMs: 1000, maxMs: 3000 }
173
+ /** 1 つの束に入れる依頼の数。文面の長さでも分ける(approvalMax) */
174
+ const MAX_BATCH = 5
175
+ /** 「常に許可」の範囲は省略せずに見せる。これより長ければ、「常に許可」を出さない */
176
+ const MAX_ALWAYS_SCOPE = 200
177
+ /** 1 件だけの依頼の題名は、これより長ければ省く(Claude Code の Bash では、題名がコマンドそのもの) */
178
+ const MAX_SINGLE_TITLE = 200
179
+ const MAX_BATCH_TITLE = 100
180
+ const MAX_BATCH_INPUT = 200
181
+ /** 承認依頼の文面の上限から差し引く分。送り直すときに前に足す文と、Discord で答えたあとに足す結果が入るようにする */
182
+ const APPROVAL_MARGIN = 50
183
+ /** コネクターの本文の上限の下限。依頼 1 件の題名・答え方・「常に許可」の範囲を省かずに、承認依頼の文面に収めるため */
184
+ const MIN_TEXT = 1000
185
+ const RECORD_LIMIT = 200
186
+ /**
187
+ * ターンの知らせ(ADR 0024)。メンションのあったルームへ、種類ごとに 1 回まで出す。文は固定で、エラーの中身と会話の中身は出さない。
188
+ * failed:session/prompt が失敗した(ハーネスの異常終了を含む)。approval:承認依頼に答えがないまま時間がたった。
189
+ * slow:返事もターンの終わりもないまま時間がたった。silent:返事を送らないままターンが終わった
190
+ */
191
+ export const TURN_NOTICES = {
192
+ failed: "今は不調で返事ができません。記録して調べています。",
193
+ approval: "実行の承認を待っているため、作業が止まっています。",
194
+ slow: "時間がかかっています。止まっている可能性もあります。",
195
+ silent: "返事を送らないまま、作業を終えました。",
196
+ } as const
197
+ type TurnNoticeKind = keyof typeof TURN_NOTICES
198
+ /** 知らせを出すまでの時間。approval は承認依頼を送ってから、slow はルームの発言を渡してから */
199
+ type NoticeTiming = { approvalMs: number; slowMs: number }
200
+ const NOTICE_TIMING: NoticeTiming = { approvalMs: 10 * 60 * 1000, slowMs: 20 * 60 * 1000 }
201
+
202
+ /** 管理者が環境変数で変える、知らせを出すまでの時間(分)。決めた範囲の整数以外は、書き間違いとして起動しない */
203
+ export function noticeTimingFromEnv(env: Record<string, string | undefined>): NoticeTiming {
204
+ return {
205
+ // 承認依頼は PERMISSION_TIMEOUT_MS で拒否になるので、それより前に知らせる
206
+ approvalMs: minutes(env, "RELAY_APPROVAL_NOTICE_MIN", NOTICE_TIMING.approvalMs, PERMISSION_TIMEOUT_MS / 60_000 - 1),
207
+ slowMs: minutes(env, "RELAY_SLOW_NOTICE_MIN", NOTICE_TIMING.slowMs, 24 * 60),
208
+ }
209
+ }
210
+
211
+ function minutes(env: Record<string, string | undefined>, name: string, fallback: number, max: number): number {
212
+ const v = env[name]
213
+ if (!v) return fallback
214
+ const n = Number(v)
215
+ if (!/^\d+$/.test(v) || n < 1 || n > max) throw new Error(`${name} に指定できるのは 1〜${max} の整数(分)です(今は ${JSON.stringify(v)})`)
216
+ return n * 60_000
217
+ }
218
+
219
+ /** ターンに渡した発言のルームごとの状態 */
220
+ type TurnRoom = { mentioned: boolean; replied: boolean; notified: Set<TurnNoticeKind>; slow?: Timer }
221
+
222
+ function stopSlowTimers(turn: Map<string, TurnRoom>): void {
223
+ for (const r of turn.values()) clearTimeout(r.slow)
224
+ }
225
+
226
+ /**
227
+ * 承認依頼の送り先(ADR 0026)。to があれば、その承認者だけに送る。Jev で決めたときは、その確率(probability)がある。
228
+ * to がなければ全員に送り、文面に、依頼が届いた時点でターンに渡していた発言の送り手(senders)を並べる
229
+ */
230
+ type Route = { to?: string; probability?: number; senders: TurnSender[] }
231
+ /** ターンに発言を渡した人。ルームごと。mentioned は、そのルームでメンションしたか */
232
+ type TurnSender = Pick<AttributionMessage, "room" | "sender" | "name" | "mentioned">
233
+
234
+ type PendingRequest = { id: string; req: PermissionRequest; resolve: (v: Verdict) => void; route: Route }
235
+ /** 承認依頼の束。送るまでは opened、送ったあとは id で答えられる。束の中の依頼は、送り先が同じ */
236
+ type Batch = { id: string; items: PendingRequest[]; opened: number; timeout: Timer; flush?: Timer; waiting?: Timer }
237
+
238
+ export class Relay {
239
+ private readonly connectors = new Map<string, Connector>()
240
+ /** 中継が受けた発言と送った発言の記録(メモリだけ)。どのサービスでも記録するが、fetch_messages で読むのは、履歴を読めないコネクターのときだけ */
241
+ private readonly records = new Map<string, ChatMessage[]>()
242
+ private readonly queue: Incoming[] = []
243
+ /** 送った承認依頼の束(束の ID から) */
244
+ private readonly batches = new Map<string, Batch>()
245
+ /** まだ送っていない束 */
246
+ private collecting?: Batch
247
+ private session?: Session
248
+ private running = false
249
+ /** 作業中のターンを見ている run() を、発言が届いたことで起こす */
250
+ private arrived?: () => void
251
+ /** 差し込みに失敗したら、以後は使わない */
252
+ private steerable = true
253
+ private introduced = false
254
+ /** 作業中のターンに渡した発言のルーム。ターンの知らせ(ADR 0024)に使う */
255
+ private turn?: Map<string, TurnRoom>
256
+ /** 作業中のターンに渡した発言。承認依頼の送り先を決めるのに使う(ADR 0026) */
257
+ private turnMessages: Incoming[] = []
258
+ /** 発言を渡すときに調べたルームの名前。承認依頼の文面に使う */
259
+ private readonly roomNames = new Map<string, string | undefined>()
260
+ /** 送っている途中の知らせ。中継が止まる前に待つ */
261
+ private readonly sending = new Set<Promise<void>>()
262
+ /** run() が動いていれば、その Promise */
263
+ private runningTurns?: Promise<void>
264
+ /** 他人宛ての判定(ADR 0029)に回した発言と、その答え(true なら渡す)。渡した発言とともに消えるよう、WeakMap にする */
265
+ private readonly screening = new WeakMap<Incoming, Promise<boolean>>()
266
+ /** 待ち行列に入った順番。差し込めなかった発言を、もとの位置に戻すのに使う */
267
+ private readonly order = new WeakMap<Incoming, number>()
268
+ private arrivals = 0
269
+ /** 作業中のターンの側(laneOf。ADR 0030)。ターンがなければ使わない */
270
+ private turnLane = ""
271
+ /** 中継の様子を見ているもの(管理者の端末) */
272
+ private readonly observers = new Set<(e: RelayEvent) => void>()
273
+ private statusPending = false
274
+
275
+ constructor(
276
+ private readonly access: AccessStore,
277
+ private readonly log: Log = { info: (m, e) => console.log(`relay: ${m}`, e ?? ""), error: (m, e) => console.error(`relay: ${m}`, e ?? "") },
278
+ /** reply で送れるファイルの置き場所(作業ディレクトリ)。ない場合はファイルを送れない(ADR 0009) */
279
+ private readonly workspace?: string,
280
+ private readonly batching = BATCHING,
281
+ private readonly timing = NOTICE_TIMING,
282
+ /** 送り手が複数いるターンで、承認依頼の依頼者を推す(Jev。ADR 0026)。なければ全員に送る */
283
+ private readonly attribute?: Attributor,
284
+ /** 受信モードが「他人宛てを除く(Jev)」のルームで、他人宛てかを判定する(ADR 0029)。なければ「他人宛てを除く」と同じに動く */
285
+ private readonly screen?: Screener,
286
+ ) {}
287
+
288
+ addConnector(c: Connector): void {
289
+ if (c.capabilities.text.max < MIN_TEXT)
290
+ throw new Error(`${c.label} の本文の上限(${c.capabilities.text.max} 字)では、承認依頼の文面が収まりません。${MIN_TEXT} 字以上にするか、approvalText を直してください`)
291
+ this.connectors.set(c.service, c)
292
+ }
293
+
294
+ /** エージェントへの最初の案内。送れるものは、つながっているサービスの分だけ書く */
295
+ instructions(): string {
296
+ return INSTRUCTIONS.replace("{sending}", this.sendingGuide())
297
+ }
298
+
299
+ /** コネクターによっては使えない操作を、使えるサービスと使えないサービスに分ける(ツールの説明とエラーに書く。ADR 0013) */
300
+ servicesFor(op: OptionalOperation): { supported: string[]; unsupported: string[] } {
301
+ const r = { supported: [] as string[], unsupported: [] as string[] }
302
+ for (const c of this.connectors.values()) (c[op] ? r.supported : r.unsupported).push(`${c.label}(${c.service}:)`)
303
+ return r
304
+ }
305
+
306
+ /** サービスごとの、送れるファイルと本文の長さ */
307
+ sendingGuide(): string {
308
+ return [...this.connectors.values()].map((c) => `- ${c.label}(${c.service}:):${describeCapabilities(c.capabilities)}`).join("\n")
309
+ }
310
+
311
+ attach(session: Session): void {
312
+ this.session = session
313
+ this.changed()
314
+ this.kick()
315
+ }
316
+
317
+ // ---- 管理者の端末へ流すもの(ADR 0030) ----
318
+
319
+ /** 中継の様子を受け取る。やめるときは、返した関数を呼ぶ */
320
+ observe(fn: (e: RelayEvent) => void): () => void {
321
+ this.observers.add(fn)
322
+ return () => this.observers.delete(fn)
323
+ }
324
+
325
+ status(): RelayStatus {
326
+ const queued: Record<string, number> = {}
327
+ for (const m of this.queue) {
328
+ const lane = this.laneOf(m)
329
+ queued[lane] = (queued[lane] ?? 0) + 1
330
+ }
331
+ const approvals = [...this.batches.values(), ...(this.collecting ? [this.collecting] : [])].reduce((n, b) => n + b.items.length, 0)
332
+ const rooms = [...(this.turn?.keys() ?? [])].map((r) => this.roomNames.get(r) ?? r)
333
+ const steering = this.session?.steer !== undefined && this.steerable
334
+ return { ...(this.turn ? { turn: { lane: this.turnLane, rooms } } : {}), approvals, queued, steering }
335
+ }
336
+
337
+ /** ハーネスの途中経過。チャットの記録には入れず、ルームにも送らない */
338
+ progress(p: Progress): void {
339
+ this.emit({ type: "progress", progress: p })
340
+ }
341
+
342
+ private emit(e: RelayEvent): void {
343
+ for (const fn of this.observers) {
344
+ try {
345
+ fn(e)
346
+ } catch (err) {
347
+ this.log.error("端末へ流せませんでした", { error: String(err) })
348
+ }
349
+ }
350
+ }
351
+
352
+ /** 状態が変わった。同じ処理の中の変化は、まとめて 1 回だけ流す */
353
+ private changed(): void {
354
+ if (this.statusPending || this.observers.size === 0) return
355
+ this.statusPending = true
356
+ queueMicrotask(() => {
357
+ this.statusPending = false
358
+ this.emit({ type: "status", status: this.status() })
359
+ })
360
+ }
361
+
362
+ /** コネクターが受けた発言 */
363
+ receive(m: Incoming): ReceiveResult {
364
+ // 古い依頼の実行、古い承認の返事、ペアリングのコードを出さないよう、許可の判定(gate)を通さない
365
+ if (m.stale) {
366
+ if (!canSendTo(this.access.load(), m.room)) return { action: "drop" }
367
+ this.record(m)
368
+ return { action: "record" }
369
+ }
370
+ const r = this.access.gate(m)
371
+ if (r.action === "pair") void this.pairingNotice(m.room, r.code, r.isResend)
372
+ if (r.action === "record") {
373
+ this.record(m)
374
+ // 本文は書かない(ADR 0028)
375
+ if (r.toOthers) this.log.info("他人宛ての発言を、エージェントに渡さずに記録しました", { room: m.room, reason: "structure" })
376
+ }
377
+ if (r.action !== "deliver") return r
378
+ const p = PERMISSION_REPLY_RE.exec(m.text)
379
+ if (m.isDM && p) {
380
+ const word = p[1]!.toLowerCase()
381
+ const ok = this.answer(m.sender, p[2]!.toLowerCase(), word === "always" ? "always" : word.startsWith("y") ? "allow" : "deny")
382
+ void this.connector(m.room)
383
+ ?.notice(m.room, ok ? "受け付けました" : "その依頼は見つからないか、すでに答えが出ています")
384
+ .finally(() => ok && this.remindPending(m.sender))
385
+ return r
386
+ }
387
+ // 判定には、この発言より前の、同じルームの発言を渡す
388
+ if (r.screen && this.screen) this.screening.set(m, this.screenMessage(this.screen, m, [...(this.records.get(m.room) ?? [])]))
389
+ this.record(m)
390
+ this.order.set(m, this.arrivals++)
391
+ this.queue.push(m)
392
+ this.changed()
393
+ this.kick()
394
+ // 受信モードが「すべて」のルームの、メンションのない発言には出さない
395
+ return { ...r, acknowledge: m.mentioned }
396
+ }
397
+
398
+ joined(room: string): void {
399
+ const r = this.access.joined(room)
400
+ if (r.action === "pair") void this.pairingNotice(room, r.code, r.isResend)
401
+ }
402
+
403
+ // ---- 実行承認の中継 ----
404
+
405
+ requestPermission(req: PermissionRequest): Promise<Verdict> {
406
+ const approvers = this.access.load().allowFrom
407
+ if (approvers.length === 0) {
408
+ this.log.error("実行承認を送れる人がいないため、拒否しました", { tool: req.title })
409
+ return Promise.resolve("deny")
410
+ }
411
+ // 依頼が届いた時点の発言で決める。依頼のあとに届いた発言は、その依頼のきっかけになりえない
412
+ const roomName = (m: Incoming) => (m.isDM ? "DM" : (this.roomNames.get(m.room) ?? ""))
413
+ const messages = this.turnMessages.map((m) => ({ sender: m.sender, name: m.senderName ?? "", room: roomName(m), mentioned: m.mentioned, text: m.text }))
414
+ // 承認者に見せる一覧では、名前がなければ ID を書く
415
+ const senders = turnSenders(
416
+ this.turnMessages.map((m) => ({ sender: m.sender, name: m.senderName ?? m.sender, room: roomName(m) || m.room, mentioned: m.mentioned })),
417
+ )
418
+ const users = new Set(messages.map((m) => m.sender))
419
+ const candidates = [...users].filter((u) => approvers.includes(u))
420
+ // 送り手が 1 人なら、その人が承認者のときだけ絞る(そうでなければ to はなく、全員に送る)
421
+ if (users.size === 1) return this.enqueue(req, { to: candidates[0], senders })
422
+ if (candidates.length === 0 || !this.attribute) return this.enqueue(req, { senders })
423
+ // 送り手が複数いれば、依頼者を推す。推せなければ全員に送る。推した人が承認者でなければ、その束には全員が答えられる(canAnswer)
424
+ return this.attribute({ title: req.title, input: req.input, agentText: req.agentText ?? "", messages })
425
+ .catch((err) => {
426
+ this.log.error("承認依頼の依頼者を推せませんでした", { error: String(err) })
427
+ return undefined
428
+ })
429
+ .then((guess) => this.enqueue(req, { to: guess?.sender, probability: guess?.probability, senders }))
430
+ }
431
+
432
+ private enqueue(req: PermissionRequest, route: Route): Promise<Verdict> {
433
+ const always = req.always && req.always.length <= MAX_ALWAYS_SCOPE ? req.always : undefined
434
+ const normalized = req.requireFullDisplay
435
+ ? { ...req, always, title: approvalLiteral(req.title), input: approvalLiteral(req.input) }
436
+ : { ...req, always }
437
+ if (normalized.requireFullDisplay) {
438
+ const item = { req: normalized, id: ID_PLACEHOLDER, route }
439
+ const max = MIN_TEXT - APPROVAL_MARGIN
440
+ // 送り先の人が許可リストから外れると、出し直し時は全員向けの文面になる。
441
+ if (
442
+ approvalText([item], ID_PLACEHOLDER, max, false).length > max ||
443
+ (route.to && approvalText([item], ID_PLACEHOLDER, max, true).length > max)
444
+ ) {
445
+ this.log.error("操作と対象をすべて表示できないため、実行を拒否しました", { tool: req.title })
446
+ return Promise.resolve("deny")
447
+ }
448
+ }
449
+ return new Promise<Verdict>((resolve) => {
450
+ const pending = { req: normalized, resolve, route }
451
+ if (normalized.requireFullDisplay && (normalized.title.length > MAX_BATCH_TITLE || normalized.input.length > MAX_BATCH_INPUT)) {
452
+ // 束にすると全文が収まらない依頼は 1 件で送る。収集中の束はそのまま待つ。
453
+ const b = this.newBatch()
454
+ b.items.push({ id: this.newPermissionId(), ...pending })
455
+ this.sendBatch(b)
456
+ return
457
+ }
458
+ let b = this.collecting ?? this.openBatch()
459
+ // 送り先が違えば、今の束を先に送る(ADR 0026)。
460
+ // 足すと文面が上限を超えるときも同じ。コネクターが文面を切ると、依頼や「常に許可」の範囲が見えないまま、束全体に答えられてしまう(ADR 0015)。
461
+ // 長さは全員への文面で測る。1 人への文面がそれより長く上限を超えたら、送るときに依頼ごとに分ける(sendBatchTo)
462
+ const head = b.items[0]?.route
463
+ if (head && (head.to !== route.to || approvalText([...b.items, { id: ID_PLACEHOLDER, ...pending }], ID_PLACEHOLDER, Infinity, false).length > this.approvalMax())) {
464
+ clearTimeout(b.flush)
465
+ this.sendBatch(b)
466
+ b = this.openBatch()
467
+ }
468
+ b.items.push({ id: this.newPermissionId(), ...pending })
469
+ clearTimeout(b.flush)
470
+ if (b.items.length >= MAX_BATCH) return this.sendBatch(b)
471
+ const wait = Math.min(this.batching.quietMs, b.opened + this.batching.maxMs - Date.now())
472
+ b.flush = setTimeout(() => this.sendBatch(b), Math.max(0, wait))
473
+ })
474
+ }
475
+
476
+ private newBatch(): Batch {
477
+ const b: Batch = { id: "", items: [], opened: Date.now(), timeout: setTimeout(() => this.expire(b), PERMISSION_TIMEOUT_MS) }
478
+ return b
479
+ }
480
+
481
+ private openBatch(): Batch {
482
+ return this.collecting = this.newBatch()
483
+ }
484
+
485
+ private sendBatch(b: Batch): void {
486
+ if (this.collecting === b) this.collecting = undefined
487
+ // 依頼が 1 つなら、その依頼の ID をそのまま束の ID にする
488
+ b.id = b.items.length === 1 ? b.items[0]!.id : this.newPermissionId()
489
+ this.batches.set(b.id, b)
490
+ b.waiting = setTimeout(() => this.noticeTurn("approval"), this.timing.approvalMs)
491
+ this.changed()
492
+ const approvers = this.access.load().allowFrom
493
+ for (const user of approvers) if (canAnswer(b, user, approvers)) this.sendBatchTo(user, b)
494
+ }
495
+
496
+ private sendBatchTo(user: string, b: Batch, lead = ""): void {
497
+ const c = this.connector(user)
498
+ if (!c) return
499
+ const max = c.capabilities.text.max - APPROVAL_MARGIN
500
+ const narrowed = b.items[0]!.route.to === user
501
+ const text = approvalText(b.items, b.id, max, narrowed)
502
+ // 束を組んだあとに、上限の短いサービスの承認者が足されると、束が収まらない。束全体への答えは出さず、依頼ごとの ID で 1 件ずつ送る
503
+ const parts =
504
+ text.length <= max ? [{ items: b.items, id: b.id, text }] : b.items.map((i) => ({ items: [i], id: i.id, text: approvalText([i], i.id, max, narrowed) }))
505
+ for (const [n, p] of parts.entries()) {
506
+ c.sendApproval(user, (n === 0 ? lead : "") + p.text, p.id, { always: p.items.every((i) => i.req.always) })
507
+ .catch((err) => this.log.error("承認の依頼を送れませんでした", { user, error: String(err) }))
508
+ }
509
+ }
510
+
511
+ /** 束を組むときの文面の上限。承認者のいるサービスのうち、本文の上限がいちばん短いものに合わせる */
512
+ private approvalMax(): number {
513
+ const limits = this.access.load().allowFrom.flatMap((u) => this.connector(u)?.capabilities.text.max ?? [])
514
+ return Math.min(...limits) - APPROVAL_MARGIN
515
+ }
516
+
517
+ private expire(b: Batch): void {
518
+ if (b.items.length === 0) return
519
+ this.log.info("実行承認の返事がなく、拒否しました", { id: b.id })
520
+ this.settle(b, b.items, "deny")
521
+ }
522
+
523
+ private settle(b: Batch, items: PendingRequest[], verdict: Verdict): void {
524
+ // 「常に許可」が示されていない依頼には、今回だけの許可として答える
525
+ for (const item of items) item.resolve(verdict === "always" && !item.req.always ? "allow" : verdict)
526
+ b.items = b.items.filter((i) => !items.includes(i))
527
+ this.changed()
528
+ if (b.items.length > 0) return
529
+ clearTimeout(b.timeout)
530
+ clearTimeout(b.waiting)
531
+ this.batches.delete(b.id)
532
+ }
533
+
534
+ private newPermissionId(): string {
535
+ let id: string
536
+ do id = permissionId()
537
+ while (this.batches.has(id) || [...this.batches.values(), this.collecting].some((b) => b?.items.some((i) => i.id === id)))
538
+ return id
539
+ }
540
+
541
+ /** 承認者からの返事。id は束の ID(束のすべての依頼に答える)か、依頼の ID。許可リストの人でなければ受け付けない */
542
+ answer(sender: string, id: string, verdict: Verdict): boolean {
543
+ const approvers = this.access.load().allowFrom
544
+ const whole = this.batches.get(id)
545
+ if (whole) {
546
+ if (!canAnswer(whole, sender, approvers)) return false
547
+ this.settle(whole, whole.items, verdict)
548
+ return true
549
+ }
550
+ for (const b of this.batches.values()) {
551
+ const item = b.items.find((i) => i.id === id)
552
+ if (item) {
553
+ if (!canAnswer(b, sender, approvers)) return false
554
+ this.settle(b, [item], verdict)
555
+ return true
556
+ }
557
+ }
558
+ return false
559
+ }
560
+
561
+ /** 答えを受け付けたあとに呼ぶ。答えていない束が残っていれば、いちばん古い束をその人へ出し直す */
562
+ remindPending(user: string): void {
563
+ // 答えてから呼ばれるまでのあいだに、許可リストから外れたかもしれない。ほかの人だけに送った束は出さない
564
+ const approvers = this.access.load().allowFrom
565
+ const pending = [...this.batches.values()].filter((b) => canAnswer(b, user, approvers))
566
+ const oldest = pending[0]
567
+ if (!oldest) return
568
+ const left = pending.reduce((n, b) => n + b.items.length, 0)
569
+ this.sendBatchTo(user, oldest, `答えていない依頼が残っています(残り ${left} 件)\n\n`)
570
+ }
571
+
572
+ // ---- チャット用ツール(MCP)から呼ばれる操作 ----
573
+
574
+ async reply(room: string, text: string, replyTo?: string, files: string[] = []): Promise<string[]> {
575
+ const c = this.allowedConnector(room)
576
+ const paths = sendablePaths(files, this.workspace)
577
+ checkFiles(c, paths)
578
+ const ids = await c.send(room, text, { replyTo, files: paths })
579
+ this.replied(room)
580
+ this.emit({ type: "sent", room, name: this.roomNames.get(room), text })
581
+ const attachments = paths.map((p) => ({ name: basename(p), type: "file" }))
582
+ this.record({ id: ids[0] ?? `sent-${Date.now()}`, room, sender: "me", text, ts: Date.now(), attachments, fromMe: true })
583
+ return ids
584
+ }
585
+
586
+ async fetchMessages(room: string, limit = 20): Promise<ChatMessage[]> {
587
+ const c = this.allowedConnector(room)
588
+ const n = Math.min(Math.max(limit, 1), 100)
589
+ if (c.history) return c.history(room, n)
590
+ return (this.records.get(room) ?? []).slice(-n)
591
+ }
592
+
593
+ async download(room: string, messageId: string, dir: string): Promise<string[]> {
594
+ return this.allowedConnector(room).download(room, messageId, dir)
595
+ }
596
+
597
+ async react(room: string, messageId: string, emoji: string): Promise<void> {
598
+ const c = this.allowedConnector(room)
599
+ if (!c.react) throw this.unsupported(c, "react", "リアクションを付けられません", "reply で伝えてください")
600
+ await c.react(room, messageId, emoji)
601
+ }
602
+
603
+ async edit(room: string, messageId: string, text: string): Promise<void> {
604
+ const c = this.allowedConnector(room)
605
+ if (!c.edit) throw this.unsupported(c, "edit", "送った発言を編集できません", "新しく reply してください")
606
+ await c.edit(room, messageId, text)
607
+ }
608
+
609
+ /** スレッドは親の登録を引き継ぐ(ADR 0011)ので、登録したルームの発言からだけ作る */
610
+ async createThread(room: string, messageId: string, name: string): Promise<string> {
611
+ const c = this.allowedConnector(room)
612
+ if (!c.createThread) throw this.unsupported(c, "createThread", "スレッドを作れません", "そのまま reply してください")
613
+ return c.createThread(room, messageId, name)
614
+ }
615
+
616
+ async listRooms(): Promise<{ chat_id: string; name?: string; kind: "room" | "dm"; receive?: ReceiveMode }[]> {
617
+ const a = this.access.load()
618
+ const rooms = await Promise.all(
619
+ Object.entries(a.rooms).map(async ([room, p]) => ({ chat_id: room, name: await this.roomName(room), kind: "room" as const, receive: p.receive })),
620
+ )
621
+ return [...rooms, ...a.allowFrom.map((user) => ({ chat_id: user, kind: "dm" as const }))]
622
+ }
623
+
624
+ /** 他人宛てかを Jev で判定する。外すなら false。判定できなければ渡す(ADR 0029) */
625
+ private async screenMessage(screen: Screener, m: Incoming, recent: ChatMessage[]): Promise<boolean> {
626
+ const toScreen = (x: ChatMessage): ScreenMessage => ({ sender: x.sender, name: x.senderName ?? "", fromMe: x.fromMe === true, text: x.text })
627
+ const query = { service: this.connector(m.room)?.label ?? "", room: (await this.roomName(m.room)) ?? "", recent: recent.map(toScreen), message: toScreen(m) }
628
+ const r = await screen(query).catch((err) => {
629
+ this.log.error("他人宛てかを判定できませんでした", { error: String(err) })
630
+ return undefined
631
+ })
632
+ if (!r) return true
633
+ // 本文は書かない。しきい値を確かめられるよう、渡した発言の確率も書く
634
+ if (r.drop) this.log.info("他人宛ての発言を、エージェントに渡さずに記録しました", { room: m.room, reason: "jev", ...r.probabilities })
635
+ else this.log.info("Jev で他人宛てでないと判定し、渡しました", { room: m.room, ...r.probabilities })
636
+ return !r.drop
637
+ }
638
+
639
+ /**
640
+ * 待ち行列の、今ある発言を取り出す。他人宛ての判定を待っている発言があれば、その答えを待ち、外す発言を除く。
641
+ * 待つ間に届いた発言は残すので、発言の順番は変わらない
642
+ */
643
+ private async take(pick: (m: Incoming) => boolean): Promise<Incoming[]> {
644
+ const batch = this.queue.filter(pick)
645
+ const keep = await Promise.all(batch.map((m) => this.screening.get(m) ?? Promise.resolve(true)))
646
+ for (const m of batch) this.queue.splice(this.queue.indexOf(m), 1)
647
+ this.changed()
648
+ return batch.filter((_, i) => keep[i])
649
+ }
650
+
651
+ /** 渡せなかった発言を、届いた順の位置に戻す。あとから届いた発言より前に渡る */
652
+ private requeue(batch: Incoming[]): void {
653
+ this.queue.push(...batch)
654
+ this.queue.sort((a, b) => this.arrival(a) - this.arrival(b))
655
+ this.changed()
656
+ }
657
+
658
+ /** 発言が届いた順番 */
659
+ private arrival(m: Incoming): number {
660
+ return this.order.get(m) ?? 0
661
+ }
662
+
663
+ /**
664
+ * 発言の側(ADR 0030)。ownTurns のコネクター(管理者の端末)ならそのサービス、ほかのルームはすべて空。
665
+ * 側が違う発言は、同じターンに入れない
666
+ */
667
+ private laneOf(m: Incoming): string {
668
+ return this.connector(m.room)?.ownTurns ? serviceOf(m.room) : ""
669
+ }
670
+
671
+ private kick(): void {
672
+ this.arrived?.()
673
+ if (this.running || !this.session || this.queue.length === 0) return
674
+ this.running = true
675
+ this.runningTurns = this.run()
676
+ }
677
+
678
+ private async run(): Promise<void> {
679
+ try {
680
+ while (this.session && this.queue.length > 0) {
681
+ // いちばん古い発言の側の発言を、まとめて 1 つのターンにする(ADR 0030)
682
+ const lane = this.laneOf(this.queue[0]!)
683
+ const batch = await this.take((m) => this.laneOf(m) === lane)
684
+ if (batch.length === 0) continue
685
+ const text = await this.render(batch)
686
+ const turnRooms = new Map<string, TurnRoom>()
687
+ this.turn = turnRooms
688
+ this.turnLane = lane
689
+ this.delivered(turnRooms, batch)
690
+ let failed = false
691
+ const turn = this.session
692
+ .prompt(text)
693
+ .catch((err) => {
694
+ failed = true
695
+ this.log.error("セッションへの入力に失敗しました", { error: String(err) })
696
+ })
697
+ // 差し込みの結果を待つ間にターンが終わっても、時間のたった知らせを出さない
698
+ .finally(() => stopSlowTimers(turnRooms))
699
+ await this.steerUntil(this.session, turn, turnRooms, lane)
700
+ this.endTurn(turnRooms, failed)
701
+ }
702
+ } finally {
703
+ this.running = false
704
+ }
705
+ }
706
+
707
+ /**
708
+ * ターンが終わるまで、届いた発言をそのターンに差し込む(ADR 0018)。
709
+ * 差し込めないハーネスや、差し込めなかった発言は、ためておき、ターンが終わってからまとめて渡す。
710
+ * 差し込みの結果を待つ間にターンが終わったら、次の発言は差し込まず、次のターンで渡す(#50)。
711
+ * 差し込めた発言のルームは、rooms に足す。
712
+ * 差し込むのは、そのターンと同じ側の発言と、明示して差し込む発言(cutIn)だけ。ほかは、ターンが終わるまで待つ(ADR 0030)。
713
+ * cutIn の発言は、同じ側でそれより前に届いて待っている発言と一緒に差し込む。同じ人の発言を、送った順に渡すため
714
+ */
715
+ private async steerUntil(session: Session, turn: Promise<void>, rooms: Map<string, TurnRoom>, lane: string): Promise<void> {
716
+ const steer = session.steer?.bind(session)
717
+ if (!steer || !this.steerable) return turn
718
+ const cutsIn = (m: Incoming) => this.queue.some((c) => c.cutIn === true && this.laneOf(c) === this.laneOf(m) && this.arrival(c) >= this.arrival(m))
719
+ const joins = (m: Incoming) => this.laneOf(m) === lane || cutsIn(m)
720
+ let done = false
721
+ const ended = turn.then(() => {
722
+ done = true
723
+ return "ended" as const
724
+ })
725
+ for (;;) {
726
+ if (done) return
727
+ if (this.queue.some(joins)) {
728
+ const batch = await this.take(joins)
729
+ if (batch.length === 0) continue
730
+ try {
731
+ const text = await this.render(batch)
732
+ if (!done && (await steer(text))) {
733
+ this.delivered(rooms, batch)
734
+ continue
735
+ }
736
+ } catch (err) {
737
+ this.steerable = false
738
+ this.log.error("作業中のターンへの差し込みに失敗しました。以後は、ターンが終わってから渡します", { error: String(err) })
739
+ }
740
+ // 渡せなかった発言は、あとから届いた発言より前に渡す
741
+ this.requeue(batch)
742
+ await turn
743
+ return
744
+ }
745
+ const next = await Promise.race([ended, new Promise<"arrived">((r) => (this.arrived = () => r("arrived")))])
746
+ this.arrived = undefined
747
+ if (next === "ended") return
748
+ }
749
+ }
750
+
751
+ async render(batch: Incoming[]): Promise<string> {
752
+ const parts: string[] = []
753
+ if (!this.introduced) {
754
+ parts.push(this.instructions(), "")
755
+ this.introduced = true
756
+ }
757
+ const names = new Map(await Promise.all([...new Set(batch.map((m) => m.room))].map(async (r) => [r, await this.roomName(r)] as const)))
758
+ for (const [room, name] of names) this.roomNames.set(room, name)
759
+ for (const m of batch) {
760
+ const name = names.get(m.room)
761
+ const attrs: Record<string, string> = {
762
+ chat_id: m.room,
763
+ ...(name ? { chat: name } : {}),
764
+ message_id: m.id,
765
+ user: m.senderName ?? m.sender,
766
+ user_id: m.sender,
767
+ ts: new Date(m.ts).toISOString(),
768
+ ...(m.mentioned ? { mentioned: "true" } : {}),
769
+ }
770
+ if (m.attachments.length > 0) attrs.attachments = m.attachments.map(describeAttachment).join("; ")
771
+ const attrText = Object.entries(attrs)
772
+ .map(([k, v]) => `${k}="${escapeXml(v)}"`)
773
+ .join(" ")
774
+ parts.push(`<message ${attrText}>\n${escapeXml(m.text)}\n</message>`)
775
+ }
776
+ return parts.join("\n")
777
+ }
778
+
779
+ private record(m: ChatMessage): void {
780
+ const list = this.records.get(m.room) ?? []
781
+ list.push(m)
782
+ if (list.length > RECORD_LIMIT) list.splice(0, list.length - RECORD_LIMIT)
783
+ this.records.set(m.room, list)
784
+ }
785
+
786
+ private async pairingNotice(room: string, code: string, isResend: boolean): Promise<void> {
787
+ const lead = isResend ? "まだ登録されていません" : "このルームは登録されていません"
788
+ await this.connector(room)
789
+ ?.notice(room, `${lead}。管理者が端末で次を実行すると登録されます。\n\nrelay pair ${code}`)
790
+ .catch((err) => this.log.error("ペアリングのコードを送れませんでした", { error: String(err) }))
791
+ }
792
+
793
+ // ---- ターンの知らせ(ADR 0024) ----
794
+
795
+ /** ターンに渡した発言のルームを足す。ルームに最初のメンションを渡してから slowMs、返事もターンの終わりもなければ、知らせる */
796
+ private delivered(turn: Map<string, TurnRoom>, batch: Incoming[]): void {
797
+ this.turnMessages.push(...batch)
798
+ for (const m of batch) {
799
+ const r = turn.get(m.room) ?? { mentioned: false, replied: false, notified: new Set() }
800
+ turn.set(m.room, r)
801
+ r.mentioned ||= m.mentioned
802
+ if (r.mentioned) r.slow ??= setTimeout(() => this.noticeRoom(m.room, r, "slow"), this.timing.slowMs)
803
+ }
804
+ this.changed()
805
+ }
806
+
807
+ /** そのターンで、ルームへ返事した */
808
+ private replied(room: string): void {
809
+ const r = this.turn?.get(room)
810
+ if (r) r.replied = true
811
+ }
812
+
813
+ private endTurn(turn: Map<string, TurnRoom>, failed: boolean): void {
814
+ // 時間のたった知らせを、次のターンに持ち越さない
815
+ stopSlowTimers(turn)
816
+ for (const [room, r] of turn) this.noticeRoom(room, r, failed ? "failed" : "silent")
817
+ this.turn = undefined
818
+ this.turnMessages = []
819
+ this.changed()
820
+ }
821
+
822
+ /** 作業中のターンのルームすべてに知らせる */
823
+ private noticeTurn(kind: TurnNoticeKind): void {
824
+ for (const [room, r] of this.turn ?? []) this.noticeRoom(room, r, kind)
825
+ }
826
+
827
+ /**
828
+ * メンションのあったルームにだけ、種類ごとに 1 回まで知らせる。受信モードが「すべて」のルームの雑談では、だれも返事を待っていない。
829
+ * 時間がかかっていることと、返事のない終わりは、そのターンにルームへ返事していれば知らせない
830
+ */
831
+ private noticeRoom(room: string, r: TurnRoom, kind: TurnNoticeKind): void {
832
+ if (!r.mentioned || r.notified.has(kind)) return
833
+ if ((kind === "slow" || kind === "silent") && r.replied) return
834
+ r.notified.add(kind)
835
+ const p = this.connector(room)
836
+ ?.notice(room, TURN_NOTICES[kind], { push: true })
837
+ .then(
838
+ (sent) => (sent ? this.log.info("ルームに知らせました", { room, kind }) : this.log.info("ルームに知らせる手段がないため、知らせませんでした", { room, kind })),
839
+ (err) => this.log.error("ルームに知らせられませんでした", { room, kind, error: String(err) }),
840
+ )
841
+ if (!p) return
842
+ this.sending.add(p)
843
+ void p.finally(() => this.sending.delete(p))
844
+ }
845
+
846
+ /**
847
+ * 作業中のターンが終わり、知らせを送り終わるまで待つ(最大 timeoutMs)。ハーネスが落ちたとき、中継を止める前に呼ぶ。
848
+ * ターンは、ハーネスとの接続が切れると失敗で終わる
849
+ */
850
+ async drain(timeoutMs: number): Promise<void> {
851
+ let timer: Timer | undefined
852
+ const timeout = new Promise<void>((r) => (timer = setTimeout(r, timeoutMs)))
853
+ const settled = (async () => {
854
+ await this.runningTurns
855
+ await Promise.allSettled(this.sending)
856
+ })()
857
+ await Promise.race([settled, timeout])
858
+ clearTimeout(timer)
859
+ }
860
+
861
+ private connector(id: string): Connector | undefined {
862
+ return this.connectors.get(serviceOf(id))
863
+ }
864
+
865
+ private roomName(room: string): Promise<string | undefined> {
866
+ return this.connector(room)?.roomName(room).catch(() => undefined) ?? Promise.resolve(undefined)
867
+ }
868
+
869
+ private unsupported(c: Connector, op: OptionalOperation, what: string, instead: string): Error {
870
+ const { supported } = this.servicesFor(op)
871
+ return new Error(`${c.label} では${what}${supported.length > 0 ? `(使えるのは ${supported.join("、")})` : ""}。${instead}`)
872
+ }
873
+
874
+ private allowedConnector(room: string): Connector {
875
+ const c = this.connector(room)
876
+ if (!c) throw new Error(`知らないチャットサービスです: ${room}`)
877
+ if (room.includes("/") && !c.nestedRooms) throw new Error(`${c.label} の ID の形が違います: ${room}`)
878
+ if (!canSendTo(this.access.load(), room)) throw new Error(`${room} は登録されていません(list_rooms で送れるルームが分かります)`)
879
+ return c
880
+ }
881
+ }
882
+
883
+ /** 送るファイルを確認し、実パスを返す。作業ディレクトリの外(リンクで外を指すものも含む)は送らない(ADR 0009) */
884
+ export function sendablePaths(files: string[], workspace: string | undefined): string[] {
885
+ if (files.length === 0) return []
886
+ if (!workspace) throw new Error("ファイルは送れません")
887
+ const root = realpathSync(workspace)
888
+ return files.map((f) => {
889
+ let real: string
890
+ try {
891
+ real = realpathSync(resolve(root, f))
892
+ } catch {
893
+ throw new Error(`ファイルが見つかりません: ${f}`)
894
+ }
895
+ const rel = relative(root, real)
896
+ if (rel === "" || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) throw new Error(`作業ディレクトリの外のファイルは送れません: ${f}`)
897
+ if (!statSync(real).isFile()) throw new Error(`ファイルではありません: ${f}`)
898
+ return real
899
+ })
900
+ }
901
+
902
+ /** コネクターが申告した上限で、送るファイルを確認する。送れないものがあれば、何も送らずにエラーにする */
903
+ function checkFiles(c: Connector, paths: string[]): void {
904
+ if (paths.length === 0) return
905
+ const f = c.capabilities.files
906
+ if (!f) throw new Error(`${c.label} ではファイルを送れません`)
907
+ if (paths.length > f.maxCount) throw new Error(`${c.label} で一度に送れるファイルは ${f.maxCount} 個までです`)
908
+ for (const p of paths) {
909
+ if (statSync(p).size > f.maxBytes) throw new Error(`${c.label} で送れるファイルは ${mb(f.maxBytes)} までです: ${basename(p)}`)
910
+ }
911
+ }
912
+
913
+ function describeCapabilities(cap: Capabilities): string {
914
+ const f = cap.files
915
+ const files = f ? `ファイルは${f.kinds ? ` ${f.kinds}だけ` : "種類を問わず"}、1 個 ${mb(f.maxBytes)}・1 回 ${f.maxCount} 個まで。` : "ファイルは送れない。"
916
+ const t = cap.text
917
+ const text = t.parts > 1 ? `本文は 1 通 ${t.max} 字までで、超えると ${t.parts} 通まで分けて送る(残りは省略)。` : `本文は ${t.max} 字まで(超えた分は省略)。`
918
+ return files + text
919
+ }
920
+
921
+ function mb(bytes: number): string {
922
+ return `${Math.round(bytes / 1024 / 1024)}MB`
923
+ }
924
+
925
+ function permissionId(): string {
926
+ const letters = "abcdefghijkmnopqrstuvwxyz"
927
+ return Array.from({ length: 5 }, () => letters[randomInt(letters.length)]).join("")
928
+ }
929
+
930
+ function escapeXml(s: string): string {
931
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;")
932
+ }
933
+
934
+ function describeAttachment(a: Attachment): string {
935
+ // 名前は送信者が決められる。区切り文字で枠を壊されないよう置き換える
936
+ const name = a.name.replace(/[[\]\r\n;]/g, "_")
937
+ return a.size === undefined ? `${name} (${a.type})` : `${name} (${a.type}, ${Math.ceil(a.size / 1024)}KB)`
938
+ }
939
+
940
+ /** 承認の対象を装飾・リンク・タグとして解釈させない。元の操作の文字は置き換えず、表示だけ変える。 */
941
+ function approvalLiteral(text: string): string {
942
+ return text.replace(/[-!#&*+<=>@[\\\]^_`|~:\p{Cf}]/gu, ch => `\\u{${ch.codePointAt(0)!.toString(16)}}`)
943
+ }
944
+
945
+ /**
946
+ * その人が束に答えられるか(ADR 0026)。許可リストの人で、束の送り先が 1 人ならその人。
947
+ * 送り先の人が許可リストから外れたら、答えられる人がいなくならないよう、全員が答えられる
948
+ */
949
+ function canAnswer(b: Batch, user: string, approvers: string[]): boolean {
950
+ if (!approvers.includes(user)) return false
951
+ const to = b.items[0]!.route.to
952
+ return to === user || !approvers.some((a) => a === to)
953
+ }
954
+
955
+ /** ターンに発言を渡した人を、ルームごとに、渡した順に並べる。そのルームで 1 度でもメンションした人は、依頼者にする */
956
+ function turnSenders(messages: TurnSender[]): TurnSender[] {
957
+ const senders = new Map<string, TurnSender>()
958
+ for (const m of messages) {
959
+ const key = JSON.stringify([m.room, m.sender])
960
+ const s = senders.get(key) ?? { room: m.room, sender: m.sender, name: m.name, mentioned: false }
961
+ s.mentioned ||= m.mentioned
962
+ senders.set(key, s)
963
+ }
964
+ return [...senders.values()]
965
+ }
966
+
967
+ /** 承認依頼の文面に並べる名前の上限と、発言した人の一覧の上限 */
968
+ const MAX_NAME = 40
969
+ const MAX_SENDERS_TEXT = 300
970
+
971
+ /**
972
+ * 束の送り先の決め方を、受け取った人に示す欄(ADR 0026)。その人だけに送ったならそう書き、全員に送ったなら、ターンに発言を渡した人を並べる。
973
+ * ターンの外で届いた依頼には書かない
974
+ */
975
+ function routeLines(pending: Pick<PendingRequest, "route">[], narrowed: boolean): string[] {
976
+ if (narrowed) {
977
+ // Jev で決めた依頼があれば、そのうちいちばん低い確率を書く
978
+ const p = pending.flatMap((i) => i.route.probability ?? [])
979
+ const by = p.length === 0 ? "" : `Jev の判定(確率 ${Math.min(...p).toFixed(2)})で、`
980
+ return [`${by}あなたの発言による依頼として、あなただけに送っています。`]
981
+ }
982
+ // 束の依頼ごとの、届いた時点の送り手を合わせる。依頼者を先にし、一覧に収まらない人は、後ろから「ほか N 人」にまとめる
983
+ const senders = turnSenders(pending.flatMap((i) => i.route.senders))
984
+ if (senders.length === 0) return []
985
+ const ordered = [...senders.filter((s) => s.mentioned), ...senders.filter((s) => !s.mentioned)]
986
+ // だれも並べなければ必ず収まる
987
+ for (let shown = ordered.length; ; shown--) {
988
+ const lines = sendersLines(ordered.slice(0, shown), ordered.length - shown)
989
+ if (lines.join("\n").length <= MAX_SENDERS_TEXT) return lines
990
+ }
991
+ }
992
+
993
+ function sendersLines(shown: TurnSender[], omitted: number): string[] {
994
+ const lines = ["この作業中の発言(どの発言による依頼かは分かりません)"]
995
+ for (const [label, mentioned] of [
996
+ ["依頼者", true],
997
+ ["そのほかの発言", false],
998
+ ] as const) {
999
+ const rooms = Map.groupBy(
1000
+ shown.filter((s) => s.mentioned === mentioned),
1001
+ (s) => safeName(s.room),
1002
+ )
1003
+ if (rooms.size === 0) continue
1004
+ lines.push(label, ...[...rooms].map(([room, list]) => `・${room}:${list.map((s) => safeName(s.name)).join("、")}`))
1005
+ }
1006
+ if (omitted !== 0) lines.push(`・ほか ${omitted} 人`)
1007
+ return lines
1008
+ }
1009
+
1010
+ /** 送った人やルームの持ち主が決める名前を、文面に入れられる形にする。改行で偽の答え方を紛れ込ませない */
1011
+ function safeName(s: string): string {
1012
+ return truncate(s.replace(/[\p{Cc}\p{Zl}\p{Zp}\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu, " ").trim() || "(名前なし)", MAX_NAME)
1013
+ }
1014
+
1015
+ /** 束を送る前に文面の長さを測るときの ID(本物と同じ 5 文字) */
1016
+ const ID_PLACEHOLDER = "xxxxx"
1017
+
1018
+ /**
1019
+ * 承認依頼の束の文面。依頼が 1 つなら、その依頼だけを書き、入力を省いて max に収める。
1020
+ * narrowed は、受け取る人が束の送り先の 1 人か
1021
+ */
1022
+ function approvalText(pending: Pick<PendingRequest, "id" | "req" | "route">[], id: string, max: number, narrowed: boolean): string {
1023
+ const route = routeLines(pending, narrowed)
1024
+ if (pending.length === 1) {
1025
+ const { req } = pending[0]!
1026
+ const head = [`🔐 実行の承認:${req.requireFullDisplay ? req.title : truncate(req.title, MAX_SINGLE_TITLE)}`, ...(route.length === 0 ? [] : ["", ...route])].join("\n")
1027
+ const answers = [`許可:yes ${id}`, ...(req.always ? [`常に許可:always ${id}(${req.always})`] : []), `拒否:no ${id}`].join("\n")
1028
+ const room = Math.min(1500, max - head.length - answers.length - 4)
1029
+ return [head, "", req.requireFullDisplay ? req.input : truncate(req.input, room), "", answers].join("\n")
1030
+ }
1031
+ const items = pending.map((i, n) =>
1032
+ [
1033
+ `${n + 1}. ${truncate(i.req.title, MAX_BATCH_TITLE)}`,
1034
+ truncate(i.req.input, MAX_BATCH_INPUT),
1035
+ ...(i.req.always ? [`常に許可の範囲:${i.req.always}`] : []),
1036
+ `(この依頼だけ:yes ${i.id}・${i.req.always ? `always ${i.id}・` : ""}no ${i.id})`,
1037
+ ].join("\n"),
1038
+ )
1039
+ const always = pending.every((i) => i.req.always) ? [`すべて常に許可:always ${id}`] : []
1040
+ return [
1041
+ `🔐 実行の承認(${pending.length} 件)`,
1042
+ "",
1043
+ ...(route.length === 0 ? [] : [...route, ""]),
1044
+ `すべて許可:yes ${id}`,
1045
+ ...always,
1046
+ `すべて拒否:no ${id}`,
1047
+ "",
1048
+ ...items.flatMap((t) => [t, ""]),
1049
+ ]
1050
+ .join("\n")
1051
+ .trimEnd()
1052
+ }
1053
+
1054
+ /** max 文字を超えるなら、省いたことを書き添えて、全体を max 文字に収める */
1055
+ function truncate(s: string, max: number): string {
1056
+ if (s.length <= max) return s
1057
+ const note = (n: number) => `…(${n} 文字を省略)`
1058
+ let keep = Math.max(0, max - note(s.length).length)
1059
+ // 絵文字など(サロゲートペア)の途中で切らない
1060
+ const code = s.charCodeAt(keep - 1)
1061
+ if (code >= 0xd800 && code <= 0xdbff) keep--
1062
+ return s.slice(0, keep) + note(s.length - keep)
1063
+ }