@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,335 @@
1
+ // Discord のコネクター。Gateway(常時接続)で受け、REST で送る。どちらも discord.js が担当する(ADR 0011)。
2
+ // 公式の Claude Code Discord プラグイン(external_plugins/discord)を手本にした。
3
+
4
+ import { once } from "node:events"
5
+ import { basename, extname } from "node:path"
6
+ import {
7
+ ActionRowBuilder,
8
+ ButtonBuilder,
9
+ ButtonStyle,
10
+ Client,
11
+ Events,
12
+ GatewayIntentBits,
13
+ MessageFlags,
14
+ Options,
15
+ Partials,
16
+ ThreadAutoArchiveDuration,
17
+ type Interaction,
18
+ type Message,
19
+ type MessageMentionOptions,
20
+ type SendableChannels,
21
+ } from "discord.js"
22
+ import { localId } from "../core/access.ts"
23
+ import { acknowledger, assertNumericId, attachmentOnlyText, fitUnits, parsePermissionData, permissionData, saveDownload, splitText, truncate, verdictText } from "./common.ts"
24
+ import { ApiClient } from "./http.ts"
25
+ import type { Attachment, Capabilities, ChatMessage, Connector, ConnectorDeps, Log, Relay } from "../core/relay.ts"
26
+
27
+ const SERVICE = "discord"
28
+ const LOGIN_TIMEOUT_SEC = 30
29
+ // エージェントの本文で、@everyone・@here やロールの通知を飛ばさない(プロンプトインジェクションで大勢に通知が飛ぶのを防ぐ)
30
+ const AGENT_MENTIONS: MessageMentionOptions = { parse: ["users"], repliedUser: true }
31
+ // 中継が決めた文面(承認の依頼、コード)では、誰にも通知を飛ばさない
32
+ const NO_MENTIONS: MessageMentionOptions = { parse: [] }
33
+ /** 受け取りの合図に付けるリアクション(ADR 0012) */
34
+ const ACK_EMOJI = "👀"
35
+ /** スレッドの名前の上限(Discord の仕様) */
36
+ const THREAD_NAME_MAX = 100
37
+
38
+ type DiscordConfig = { token: string }
39
+
40
+ /**
41
+ * ルームと人の ID。チャンネルは c<ID>、スレッドは c<親のチャンネル>/<スレッド>(親の登録を引き継ぐ。ADR 0011)。
42
+ * DM は、LINE・Chatwork と同じく相手の ID(u<ID>)をルームとして扱う
43
+ */
44
+ const channelKey = (id: string) => `${SERVICE}:c${id}`
45
+ const threadKey = (parentId: string, id: string) => `${SERVICE}:c${parentId}/${id}`
46
+ const userKey = (id: string) => `${SERVICE}:u${id}`
47
+
48
+ /** Bot のトークンがあれば、コネクターを作る */
49
+ export function discordFromEnv(env: Record<string, string | undefined>, deps: ConnectorDeps): DiscordConnector | undefined {
50
+ const token = env.RELAY_DISCORD_BOT_TOKEN
51
+ return token ? new DiscordConnector({ token }, deps.relay, deps.log) : undefined
52
+ }
53
+
54
+ export class DiscordConnector implements Connector {
55
+ readonly service = SERVICE
56
+ readonly label = "Discord"
57
+ readonly capabilities: Capabilities = {
58
+ // ファイルの上限は、ブーストのないサーバーの既定(10MiB)。ブーストで上がるが、低い方に合わせる
59
+ files: { maxBytes: 10 * 1024 * 1024, maxCount: 10 },
60
+ text: { max: 2000, parts: 10 },
61
+ }
62
+ // スレッドは c<親>/<スレッド>。送るときに、実際の親を確認する(channel())
63
+ readonly nestedRooms = true
64
+ /** 添付の取得用。添付は Discord の CDN にあり、認証は不要 */
65
+ private readonly cdn = new ApiClient({ label: "Discord", base: "https://cdn.discordapp.com", auth: () => ({}), errorMessage: (raw) => raw.slice(0, 200) })
66
+ private readonly acknowledge: ReturnType<typeof acknowledger>
67
+
68
+ constructor(
69
+ private readonly cfg: DiscordConfig,
70
+ private readonly relay: Relay,
71
+ private readonly log: Log,
72
+ private readonly client: Client = new Client({
73
+ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.DirectMessages],
74
+ // DM のチャンネルは、最初は中身のない形で届く。これがないと DM の発言を受け取れない
75
+ partials: [Partials.Channel],
76
+ // 常駐するので、覚えておく発言を絞る(既定はチャンネルごとに 200 件で、増え続ける)
77
+ makeCache: Options.cacheWithLimits({ ...Options.DefaultMakeCacheSettings, MessageManager: 50 }),
78
+ }),
79
+ private readonly now: () => number = Date.now,
80
+ ) {
81
+ this.acknowledge = acknowledger(log, this.label)
82
+ this.client.on(Events.MessageCreate, (msg) => {
83
+ this.handleMessage(msg).catch((err) => this.log.error("Discord の発言の処理に失敗しました", { error: String(err) }))
84
+ })
85
+ this.client.on(Events.InteractionCreate, (i) => {
86
+ this.handleInteraction(i).catch((err) => this.log.error("Discord のボタンの処理に失敗しました", { error: String(err) }))
87
+ })
88
+ this.client.on(Events.Error, (err) => this.log.error("Discord の接続でエラーが起きました", { error: String(err) }))
89
+ }
90
+
91
+ /** Gateway につなぎ、使えるようになるまで待つ。止まっている間の発言は届かない(fetch_messages で読める) */
92
+ async start(): Promise<void> {
93
+ const signal = AbortSignal.timeout(LOGIN_TIMEOUT_SEC * 1000)
94
+ try {
95
+ await Promise.all([once(this.client, Events.ClientReady, { signal }), this.client.login(this.cfg.token)])
96
+ } catch (err) {
97
+ throw signal.aborted ? new Error(`Discord につながりませんでした(${LOGIN_TIMEOUT_SEC} 秒)`) : err
98
+ }
99
+ this.log.info("Discord につながりました", { bot: this.client.user?.tag })
100
+ }
101
+
102
+ stop(): void {
103
+ void this.client.destroy()
104
+ }
105
+
106
+ async handleMessage(msg: Message): Promise<void> {
107
+ // Bot(自分を含む)と Webhook の発言は受けない。Bot どうしで応答し続けるのを防ぐ
108
+ if (msg.author.bot || msg.webhookId) return
109
+ const me = this.client.user?.id
110
+ if (!me) return
111
+ const isDM = msg.channel.isDMBased()
112
+ const room = isDM ? userKey(msg.author.id) : roomOf(msg.channel)
113
+ if (!room) return
114
+ const role = botRoleId(msg)
115
+ const attachments = attachmentsOf(msg)
116
+ const result = this.relay.receive({
117
+ id: msg.id,
118
+ room,
119
+ sender: userKey(msg.author.id),
120
+ senderName: msg.member?.displayName ?? msg.author.displayName,
121
+ text: renderContent(msg, me, role) || attachmentOnlyText(attachments),
122
+ ts: msg.createdTimestamp,
123
+ attachments,
124
+ isDM,
125
+ mentioned: isDM || isMentioned(msg, me, role),
126
+ toOthers: addressesOthers(msg),
127
+ })
128
+ // 入力中の表示は、返事を送るか 10 秒たつと消える。リアクションには Add Reactions の権限が必要
129
+ if (result.acknowledge) this.acknowledge(() => Promise.all([msg.react(ACK_EMOJI), "sendTyping" in msg.channel ? msg.channel.sendTyping() : undefined]))
130
+ }
131
+
132
+ async handleInteraction(i: Interaction): Promise<void> {
133
+ if (!i.isButton()) return
134
+ const p = parsePermissionData(i.customId)
135
+ if (!p) return
136
+ // 許可リストの人でなければ、answer が受け付けない
137
+ if (!this.relay.answer(userKey(i.user.id), p.id, p.verdict)) {
138
+ await i.reply({ content: verdictText(false, p.verdict), flags: MessageFlags.Ephemeral })
139
+ return
140
+ }
141
+ // ボタンを外して結果を追記する。同じ依頼に二度答えられないようにし、履歴にも残す。上限を超えないよう、元の文面を短くする
142
+ const suffix = `\n\n${verdictText(true, p.verdict)}`
143
+ try {
144
+ await i.update({ content: truncate(i.message.content, this.capabilities.text.max - suffix.length) + suffix, components: [] })
145
+ } finally {
146
+ this.relay.remindPending(userKey(i.user.id))
147
+ }
148
+ }
149
+
150
+ async send(room: string, text: string, opts?: { replyTo?: string; files?: string[] }): Promise<string[]> {
151
+ const ch = await this.channel(room)
152
+ const files = (opts?.files ?? []).map((f) => ({ attachment: f, name: basename(f) }))
153
+ const parts = splitText(text, this.capabilities.text.max, this.capabilities.text.parts)
154
+ if (parts.length === 0 && files.length === 0) throw new Error("本文が空です")
155
+ const ids: string[] = []
156
+ // ファイルと返信の参照は 1 通目に付ける
157
+ for (let i = 0; i < Math.max(parts.length, 1); i++) {
158
+ const sent = await ch.send({
159
+ content: parts[i] || undefined,
160
+ files: i === 0 ? files : [],
161
+ reply: i === 0 && opts?.replyTo ? { messageReference: opts.replyTo, failIfNotExists: false } : undefined,
162
+ allowedMentions: AGENT_MENTIONS,
163
+ })
164
+ ids.push(sent.id)
165
+ }
166
+ return ids
167
+ }
168
+
169
+ async sendApproval(user: string, text: string, requestId: string, opts?: { always?: boolean }): Promise<void> {
170
+ // ボタンでも、yes/no の文字でも答えられる
171
+ const row = new ActionRowBuilder<ButtonBuilder>().addComponents(
172
+ new ButtonBuilder().setCustomId(permissionData("allow", requestId)).setLabel("許可").setEmoji("✅").setStyle(ButtonStyle.Success),
173
+ ...(opts?.always ? [new ButtonBuilder().setCustomId(permissionData("always", requestId)).setLabel("常に許可").setEmoji("♾️").setStyle(ButtonStyle.Primary)] : []),
174
+ new ButtonBuilder().setCustomId(permissionData("deny", requestId)).setLabel("拒否").setEmoji("❌").setStyle(ButtonStyle.Danger),
175
+ )
176
+ const ch = await this.channel(user)
177
+ await ch.send({ content: truncate(text, this.capabilities.text.max), components: [row], allowedMentions: NO_MENTIONS })
178
+ }
179
+
180
+ async notice(room: string, text: string): Promise<boolean> {
181
+ await (await this.channel(room)).send({ content: text, allowedMentions: NO_MENTIONS })
182
+ return true
183
+ }
184
+
185
+ async download(room: string, messageId: string, dir: string): Promise<string[]> {
186
+ const msg = await this.message(room, messageId)
187
+ if (msg.attachments.size === 0) throw new Error("この発言には添付がありません")
188
+ const paths: string[] = []
189
+ for (const att of msg.attachments.values()) {
190
+ const res = await this.cdn.download(att.url, "none")
191
+ paths.push(await saveDownload(res, dir, `${this.now()}-${messageId}-${att.id}`, extname(att.name)))
192
+ }
193
+ return paths
194
+ }
195
+
196
+ async roomName(room: string): Promise<string | undefined> {
197
+ const r = parseRoom(room)
198
+ if (!r || r.kind === "dm") return undefined
199
+ const name = (id: string) => {
200
+ const ch = this.client.channels.cache.get(id)
201
+ return ch && "name" in ch && ch.name ? ch.name : undefined
202
+ }
203
+ const parent = name(r.channel)
204
+ if (!r.thread) return parent && `#${parent}`
205
+ const thread = name(r.thread)
206
+ return thread && `#${parent ?? "?"} › ${thread}`
207
+ }
208
+
209
+ async react(room: string, messageId: string, emoji: string): Promise<void> {
210
+ await (await this.message(room, messageId)).react(emoji)
211
+ }
212
+
213
+ async edit(room: string, messageId: string, text: string): Promise<void> {
214
+ const msg = await this.message(room, messageId)
215
+ if (msg.author.id !== this.client.user?.id) throw new Error("Bot が送った発言だけを編集できます")
216
+ await msg.edit({ content: truncate(text.trim(), this.capabilities.text.max), allowedMentions: AGENT_MENTIONS })
217
+ }
218
+
219
+ /** チャンネルの発言から公開スレッドを作る。スレッドの ID は、元の発言の ID と同じになる */
220
+ async createThread(room: string, messageId: string, name: string): Promise<string> {
221
+ const r = parseRoom(room)
222
+ if (r?.kind !== "channel" || r.thread) throw new Error("スレッドは、チャンネルの発言からだけ作れます")
223
+ const oneLine = name.replace(/\s+/g, " ").trim()
224
+ const title = oneLine.slice(0, fitUnits(oneLine, THREAD_NAME_MAX))
225
+ if (!title) throw new Error("スレッドの名前が空です")
226
+ const msg = await this.message(room, messageId)
227
+ const thread = msg.thread ?? (await msg.startThread({ name: title, autoArchiveDuration: ThreadAutoArchiveDuration.OneDay }))
228
+ return threadKey(r.channel, thread.id)
229
+ }
230
+
231
+ /** Discord の履歴を、古い順に読む(止まっている間の発言も含む) */
232
+ async history(room: string, limit: number): Promise<ChatMessage[]> {
233
+ const ch = await this.channel(room)
234
+ const me = this.client.user?.id ?? ""
235
+ const msgs = await ch.messages.fetch({ limit })
236
+ const role = "guild" in ch ? ch.guild.members.me?.roles.botRole?.id : undefined
237
+ return [...msgs.values()].reverse().map((m) => ({
238
+ id: m.id,
239
+ room,
240
+ sender: userKey(m.author.id),
241
+ senderName: m.member?.displayName ?? m.author.displayName,
242
+ text: renderContent(m, me, role),
243
+ ts: m.createdTimestamp,
244
+ attachments: attachmentsOf(m),
245
+ fromMe: m.author.id === me,
246
+ }))
247
+ }
248
+
249
+ private async message(room: string, messageId: string): Promise<Message> {
250
+ assertNumericId(messageId)
251
+ return (await this.channel(room)).messages.fetch(messageId)
252
+ }
253
+
254
+ /**
255
+ * ルームの ID を、送れる Discord のチャンネルにする。スレッドは、実際の親が ID の親と同じものだけを許す
256
+ * (登録したチャンネルの ID に、ほかのチャンネルのスレッドを付けて送るのを防ぐ)
257
+ */
258
+ private async channel(room: string): Promise<SendableChannels & { messages: Message["channel"]["messages"] }> {
259
+ const r = parseRoom(room)
260
+ if (!r) throw new Error(`Discord の ID の形が違います: ${room}`)
261
+ if (r.kind === "dm") {
262
+ const user = await this.client.users.fetch(r.user)
263
+ return user.dmChannel ?? (await user.createDM())
264
+ }
265
+ const ch = await this.client.channels.fetch(r.thread ?? r.channel).catch(() => null)
266
+ const ok = ch && ch.isSendable() && !ch.isDMBased() && (r.thread ? ch.isThread() && ch.parentId === r.channel : !ch.isThread())
267
+ if (!ok) throw new Error(`Discord のチャンネルが見つからないか、送れません: ${room}`)
268
+ return ch
269
+ }
270
+ }
271
+
272
+ /** ルームの ID を読む。channelKey・threadKey・userKey の逆 */
273
+ function parseRoom(room: string): { kind: "dm"; user: string } | { kind: "channel"; channel: string; thread?: string } | undefined {
274
+ if (!room.startsWith(`${SERVICE}:`)) return undefined
275
+ const id = localId(room)
276
+ const dm = /^u(\d+)$/.exec(id)
277
+ if (dm) return { kind: "dm", user: dm[1]! }
278
+ const m = /^c(\d+)(?:\/(\d+))?$/.exec(id)
279
+ return m ? { kind: "channel", channel: m[1]!, thread: m[2] } : undefined
280
+ }
281
+
282
+ /** ギルドのチャンネルのルーム ID。スレッドは親の ID を付ける */
283
+ function roomOf(ch: Message["channel"]): string | undefined {
284
+ if (ch.isThread()) return ch.parentId ? threadKey(ch.parentId, ch.id) : undefined
285
+ return channelKey(ch.id)
286
+ }
287
+
288
+ /**
289
+ * Bot への @、Bot 専用のロールへの @、Bot の発言への返信。@everyone・@here・ほかのロールはメンションとして扱わない(GLOSSARY)。
290
+ * repliedUser は、返信の通知をオンにしたかによらず、返信先の発言の送信者になる(discord.js の Message._patch)
291
+ */
292
+ function isMentioned(msg: Message, me: string, botRole: string | undefined): boolean {
293
+ return msg.mentions.users.has(me) || (botRole !== undefined && msg.mentions.roles.has(botRole)) || msg.mentions.repliedUser?.id === me
294
+ }
295
+
296
+ /**
297
+ * 送信者以外の人への @、ロールへの @、その人の発言への返信があるか(Bot と Bot 専用のロールを含む。Inbound.toOthers)。
298
+ * @everyone・@here は含まない(ADR 0028)
299
+ */
300
+ function addressesOthers(msg: Pick<Message, "author" | "mentions">): boolean {
301
+ const other = (id: string) => id !== msg.author.id
302
+ const reply = msg.mentions.repliedUser
303
+ return [...msg.mentions.users.keys()].some(other) || msg.mentions.roles.size > 0 || (!!reply && other(reply.id))
304
+ }
305
+
306
+ function botRoleId(msg: Message): string | undefined {
307
+ return msg.guild?.members.me?.roles.botRole?.id
308
+ }
309
+
310
+ function attachmentsOf(msg: Message): Attachment[] {
311
+ return [...msg.attachments.values()].map((a) => ({ name: a.name, type: a.contentType?.startsWith("image/") ? "image" : "file", size: a.size }))
312
+ }
313
+
314
+ /**
315
+ * 本文から Bot へのメンション(@Bot と Bot 専用のロール)を取り除き、ほかのメンションとチャンネルの記法を名前にする。
316
+ * 名前が分からなければ、記法のまま残す
317
+ */
318
+ export function renderContent(msg: Pick<Message, "content" | "mentions">, me: string, botRole?: string): string {
319
+ return msg.content
320
+ .replace(/<@!?(\d+)>/g, (s, id: string) => {
321
+ if (id === me) return ""
322
+ const u = msg.mentions.users.get(id)
323
+ return u ? `@${msg.mentions.members?.get(id)?.displayName ?? u.displayName}` : s
324
+ })
325
+ .replace(/<@&(\d+)>/g, (s, id: string) => {
326
+ if (id === botRole) return ""
327
+ const r = msg.mentions.roles.get(id)
328
+ return r ? `@${r.name}` : s
329
+ })
330
+ .replace(/<#(\d+)>/g, (s, id: string) => {
331
+ const c = msg.mentions.channels.get(id)
332
+ return c && "name" in c && c.name ? `#${c.name}` : s
333
+ })
334
+ .trim()
335
+ }
@@ -0,0 +1,137 @@
1
+ // コネクターが API を呼ぶときの共通の部分(タイムアウト、本文の形、エラー、回数制限での一時停止、添付の取得)と、
2
+ // Webhook の署名の検証。認証、エラーの本文、回数制限の読み方は、サービスごとにコネクターが渡す。
3
+
4
+ import { createHmac, timingSafeEqual } from "node:crypto"
5
+
6
+ export class ApiError extends Error {
7
+ constructor(
8
+ readonly status: number,
9
+ /** サービスが返したエラーの文面 */
10
+ readonly apiMessage: string,
11
+ message: string,
12
+ ) {
13
+ super(message)
14
+ }
15
+ }
16
+
17
+ /** オブジェクトは JSON で送る */
18
+ type Body = object | URLSearchParams | FormData
19
+
20
+ export type ApiConfig = {
21
+ /** エラーの文面に入れるサービスの名前 */
22
+ label: string
23
+ base: string
24
+ /** 認証のヘッダー。呼ぶたびに作る(期限のあるトークンを更新するサービスがある) */
25
+ auth: () => Record<string, string> | Promise<Record<string, string>>
26
+ /** エラーの本文から、サービスの文面を取り出す */
27
+ errorMessage: (raw: string) => string
28
+ /** 429 のときの扱い。resumeAt(ミリ秒)を返すと、その時刻まで呼び出しを止める。なければ、ふつうのエラーにする */
29
+ rateLimited?: (res: Response, apiMessage: string, now: number) => { resumeAt?: number; message: string }
30
+ now?: () => number
31
+ }
32
+
33
+ export class ApiClient {
34
+ private readonly base: string
35
+ private readonly origin?: string
36
+ private pausedUntil = 0
37
+
38
+ constructor(private readonly cfg: ApiConfig) {
39
+ this.base = cfg.base.replace(/\/$/, "")
40
+ this.origin = URL.parse(this.base)?.origin
41
+ }
42
+
43
+ /** 回数制限で、呼び出しを止めているか */
44
+ get paused(): boolean {
45
+ return this.now() < this.pausedUntil
46
+ }
47
+
48
+ /** API を呼び、JSON の応答を返す。本文がない(204 など)ときは null */
49
+ async call(method: string, path: string, body?: Body, timeoutMs = 15_000): Promise<unknown> {
50
+ this.checkPaused()
51
+ const headers: Record<string, string> = { ...(await this.cfg.auth()) }
52
+ let payload: string | URLSearchParams | FormData | undefined
53
+ if (body === undefined || body instanceof URLSearchParams || body instanceof FormData) {
54
+ payload = body
55
+ } else {
56
+ payload = JSON.stringify(body)
57
+ headers["Content-Type"] = "application/json"
58
+ }
59
+ const res = await fetch(`${this.base}${path}`, { method, headers, body: payload, signal: AbortSignal.timeout(timeoutMs) })
60
+ if (!res.ok) await this.fail(res)
61
+ const raw = await res.text()
62
+ if (!raw) return null
63
+ try {
64
+ return JSON.parse(raw)
65
+ } catch {
66
+ throw new Error(`${this.cfg.label} API: 応答を読めませんでした(${method} ${path.split("?")[0]})`)
67
+ }
68
+ }
69
+
70
+ /**
71
+ * 添付を取得する。url は API の中のパス(/ で始まる)か、保存先の完全な URL。保存先が API の外のホストのこともあるので、
72
+ * https か、API と同じ origin(モック)の URL だけを許す。転送(3xx)は自分でたどる。
73
+ * auth は、認証を付ける範囲。none:付けない(Chatwork の取得用 URL)、first:最初の URL だけ(LINE)、
74
+ * all:転送先にも(LINE WORKS は、転送先の保存先にも認証が必要)
75
+ */
76
+ async download(url: string, auth: "none" | "first" | "all", timeoutMs = 120_000): Promise<Response> {
77
+ this.checkPaused()
78
+ const signal = AbortSignal.timeout(timeoutMs)
79
+ let target = URL.parse(url.startsWith("/") ? `${this.base}${url}` : url)
80
+ // 転送は通常 1 回(API → 保存先)。それより多ければ異常とみなして止める
81
+ for (let hop = 0; hop < 3 && target; hop++) {
82
+ if (target.protocol !== "https:" && target.origin !== this.origin) break
83
+ const withAuth = auth === "all" || (auth === "first" && hop === 0)
84
+ const res = await fetch(target, { headers: withAuth ? await this.cfg.auth() : {}, redirect: "manual", signal })
85
+ const location = res.headers.get("location")
86
+ if (res.status >= 300 && res.status < 400 && location) {
87
+ await res.body?.cancel()
88
+ target = URL.parse(location, target.href)
89
+ continue
90
+ }
91
+ if (!res.ok) await this.fail(res)
92
+ return res
93
+ }
94
+ throw new Error(`${this.cfg.label} から取得できませんでした(取得用の URL が使えません)`)
95
+ }
96
+
97
+ private checkPaused(): void {
98
+ if (this.paused) {
99
+ throw new Error(`${this.cfg.label} の API の回数制限に達しています。${Math.ceil((this.pausedUntil - this.now()) / 1000)} 秒後に使えます`)
100
+ }
101
+ }
102
+
103
+ private async fail(res: Response): Promise<never> {
104
+ const msg = this.cfg.errorMessage(await res.text())
105
+ if (res.status === 429 && this.cfg.rateLimited) {
106
+ const r = this.cfg.rateLimited(res, msg, this.now())
107
+ if (r.resumeAt) this.pausedUntil = r.resumeAt
108
+ throw new ApiError(429, msg, r.message)
109
+ }
110
+ throw new ApiError(res.status, msg, `${this.cfg.label} API: HTTP ${res.status}: ${msg}`)
111
+ }
112
+
113
+ private now(): number {
114
+ return (this.cfg.now ?? Date.now)()
115
+ }
116
+ }
117
+
118
+ /** Webhook の署名(本文の HMAC-SHA256 を Base64 にしたもの)。LINE と LINE WORKS で同じ方式 */
119
+ export function sign(secret: string, body: string): string {
120
+ return createHmac("sha256", secret).update(body).digest("base64")
121
+ }
122
+
123
+ export function verifySignature(secret: string, body: string, signature: string): boolean {
124
+ const expected = Buffer.from(sign(secret, body), "base64")
125
+ const given = Buffer.from(signature, "base64")
126
+ return given.length === expected.length && timingSafeEqual(given, expected)
127
+ }
128
+
129
+ /** JSON のエラーの本文から、文面を取り出す。読めなければ先頭を返す */
130
+ export function jsonError(raw: string, pick: (body: Record<string, unknown>) => unknown): string {
131
+ try {
132
+ const message = pick(JSON.parse(raw) as Record<string, unknown>)
133
+ return typeof message === "string" ? message : message == null ? "" : JSON.stringify(message)
134
+ } catch {
135
+ return raw.slice(0, 200)
136
+ }
137
+ }
@@ -0,0 +1,63 @@
1
+ // エージェントが返す画像を、推測できない URL で公開する(ADR 0005)。LINE は画像を受け取らず、開かれるたびに URL から取得する。
2
+ // URL を知っていれば誰でも見られる。名前は 256 ビットの乱数にし、一覧は出さない。URL はログに出さない。
3
+
4
+ import { randomBytes } from "node:crypto"
5
+ import { mkdir, writeFile } from "node:fs/promises"
6
+ import { join } from "node:path"
7
+ import { RETENTION_MS } from "../core/retention.ts"
8
+
9
+ // LINE の画像メッセージの上限(本体 10MB、プレビュー 1MB)
10
+ export const MAX_IMAGE_BYTES = 10 * 1024 * 1024
11
+ const MAX_PREVIEW_BYTES = 1024 * 1024
12
+ // 小さいファイルが巨大な画像に展開される(圧縮爆弾)のを防ぐ
13
+ const MAX_PIXELS = 40_000_000
14
+ // 43 は、32 バイトの乱数を base64url にした長さ
15
+ const NAME_RE = /^[A-Za-z0-9_-]{43}(_p)?\.(jpg|png)$/
16
+ const EXTENSIONS: Record<string, string> = { jpeg: "jpg", png: "png" }
17
+ const TYPES: Record<string, string> = { jpg: "image/jpeg", png: "image/png" }
18
+
19
+ export class MediaStore {
20
+ constructor(readonly dir: string) {}
21
+
22
+ /** 画像を保存し、本体とプレビューのファイル名を返す。JPEG と PNG で 10MB までに限る */
23
+ async publish(path: string): Promise<{ original: string; preview: string }> {
24
+ const file = Bun.file(path)
25
+ if (file.size > MAX_IMAGE_BYTES) throw new Error(`画像が大きすぎます(10MB まで): ${path}`)
26
+ const data = await file.bytes()
27
+ const meta = await new Bun.Image(data, { maxPixels: MAX_PIXELS }).metadata().catch(() => undefined)
28
+ const ext = meta && EXTENSIONS[meta.format]
29
+ if (!ext) throw new Error(`送れるのは JPEG と PNG の画像だけです: ${path}`)
30
+
31
+ const name = randomBytes(32).toString("base64url")
32
+ await mkdir(this.dir, { recursive: true, mode: 0o700 })
33
+ const original = `${name}.${ext}`
34
+ await writeFile(join(this.dir, original), data, { mode: 0o600 })
35
+ if (data.length <= MAX_PREVIEW_BYTES) return { original, preview: original }
36
+ const preview = `${name}_p.jpg`
37
+ await writeFile(join(this.dir, preview), await shrink(data), { mode: 0o600 })
38
+ return { original, preview }
39
+ }
40
+
41
+ /** GET /media/<名前>。名前の形に合わないものは 404 にする */
42
+ serve(name: string): Response {
43
+ if (!NAME_RE.test(name)) return new Response("not found", { status: 404 })
44
+ return new Response(Bun.file(join(this.dir, name)), {
45
+ headers: {
46
+ "Content-Type": TYPES[name.split(".").pop()!]!,
47
+ "Cache-Control": `private, max-age=${RETENTION_MS / 1000}`,
48
+ "X-Content-Type-Options": "nosniff",
49
+ "X-Robots-Tag": "noindex",
50
+ "Referrer-Policy": "no-referrer",
51
+ },
52
+ })
53
+ }
54
+ }
55
+
56
+ /** 1MB 以下の JPEG の縮小版を作る。大きい辺の長さを大きい順に試し、収まった最初のものを使う */
57
+ async function shrink(data: Uint8Array): Promise<Uint8Array> {
58
+ for (const side of [1024, 512, 240]) {
59
+ const out = await new Bun.Image(data, { maxPixels: MAX_PIXELS }).resize(side, side, { fit: "inside", withoutEnlargement: true }).jpeg({ quality: 80 }).bytes()
60
+ if (out.length <= MAX_PREVIEW_BYTES) return out
61
+ }
62
+ throw new Error("プレビューを作れませんでした")
63
+ }