@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.
- package/CHANGELOG.md +109 -0
- package/LICENSE +21 -0
- package/README.md +154 -2
- package/bin/agent-chat-relay +22 -0
- package/package.json +69 -4
- package/src/connectors/chatwork.ts +289 -0
- package/src/connectors/common.ts +106 -0
- package/src/connectors/discord.ts +335 -0
- package/src/connectors/http.ts +137 -0
- package/src/connectors/line-media.ts +63 -0
- package/src/connectors/line.ts +444 -0
- package/src/connectors/terminal.ts +367 -0
- package/src/core/access.ts +250 -0
- package/src/core/instructions.ts +21 -0
- package/src/core/mcp.ts +160 -0
- package/src/core/relay.ts +1063 -0
- package/src/core/retention.ts +44 -0
- package/src/harness/config.ts +137 -0
- package/src/harness/harness.ts +327 -0
- package/src/harness/log-file.ts +34 -0
- package/src/harness/pi/config.ts +51 -0
- package/src/harness/pi/state.ts +97 -0
- package/src/harness/pi/tool-approval.ts +128 -0
- package/src/harness/protect.ts +37 -0
- package/src/home.ts +67 -0
- package/src/jev.ts +201 -0
- package/src/main.ts +275 -0
- package/src/prompt.ts +12 -0
- package/src/serve-args.ts +56 -0
- package/src/shutdown.ts +52 -0
- package/src/terminal.ts +172 -0
- package/src/vendor/pi/adapter.js +3238 -0
- package/src/vendor/pi/managed-extension.ts +94 -0
- package/src/vendor/pi/managed-pi-rpc.ts +102 -0
- package/src/vendor/pi/managed-read.ts +99 -0
- package/src/vendor/pi/package.json +7 -0
- package/src/vendor/pi/pi-LICENSE +21 -0
- package/src/vendor/pi/pi-acp-LICENSE +21 -0
- package/src/version.ts +4 -0
- package/src/workspace.ts +117 -0
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
// Chatwork のコネクター。API のポーリングで受け、REST API で送る(ADR 0010)。
|
|
2
|
+
// Bot は、専用の Chatwork アカウントの API トークンで発言する。
|
|
3
|
+
|
|
4
|
+
import { basename, extname } from "node:path"
|
|
5
|
+
import { localId } from "../core/access.ts"
|
|
6
|
+
import { assertNumericId, attachmentOnlyText, remember, saveDownload, splitText, truncate } from "./common.ts"
|
|
7
|
+
import { ApiClient, jsonError } from "./http.ts"
|
|
8
|
+
import type { Attachment, Capabilities, Connector, ConnectorDeps, Log, Relay } from "../core/relay.ts"
|
|
9
|
+
|
|
10
|
+
const SERVICE = "chatwork"
|
|
11
|
+
// 本文の上限は 65535 字。返信の記法を付ける分を残す
|
|
12
|
+
const MAX_TEXT = 65000
|
|
13
|
+
// 取得は 1 回ごとに、ルーム一覧 1 回と、更新のあったルームごとに 2 回。回数制限(5 分に 300 回)を送信と分け合うので、間隔を 2 秒より短くしない
|
|
14
|
+
const MIN_POLL_MS = 2000
|
|
15
|
+
const IMAGE_EXT = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp"])
|
|
16
|
+
|
|
17
|
+
type CwRoom = { room_id: number; name: string; type: "my" | "direct" | "group"; last_update_time: number }
|
|
18
|
+
type CwMessage = { message_id: string; account: { account_id: number; name: string }; body: string; send_time: number }
|
|
19
|
+
|
|
20
|
+
type ChatworkConfig = {
|
|
21
|
+
apiToken: string
|
|
22
|
+
apiBase?: string
|
|
23
|
+
/** ポーリングの間隔(ミリ秒)。既定は 5 秒 */
|
|
24
|
+
pollMs?: number
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** ルームと人の ID。DM(ダイレクトチャット)は、LINE と同じく相手の ID をルームとして扱う */
|
|
28
|
+
const roomKey = (roomId: number) => `${SERVICE}:r${roomId}`
|
|
29
|
+
const userKey = (accountId: number) => `${SERVICE}:u${accountId}`
|
|
30
|
+
|
|
31
|
+
/** API トークンがあれば、コネクターを作る */
|
|
32
|
+
export function chatworkFromEnv(env: Record<string, string | undefined>, deps: ConnectorDeps): ChatworkConnector | undefined {
|
|
33
|
+
const apiToken = env.RELAY_CHATWORK_API_TOKEN
|
|
34
|
+
if (!apiToken) return undefined
|
|
35
|
+
const pollMs = Number(env.RELAY_CHATWORK_POLL_SEC) * 1000 || undefined
|
|
36
|
+
return new ChatworkConnector({ apiToken, apiBase: env.RELAY_CHATWORK_API_BASE, pollMs }, deps.relay, deps.log)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export class ChatworkConnector implements Connector {
|
|
40
|
+
readonly service = SERVICE
|
|
41
|
+
readonly label = "Chatwork"
|
|
42
|
+
readonly capabilities: Capabilities = {
|
|
43
|
+
// ルームごとの投稿の制限(10 秒に 10 回)に当たらないよう、1 回の返事の投稿(本文とファイル)を 8 回までにする
|
|
44
|
+
files: { maxBytes: 5 * 1024 * 1024, maxCount: 5 },
|
|
45
|
+
text: { max: MAX_TEXT, parts: 3 },
|
|
46
|
+
}
|
|
47
|
+
private readonly api: ApiClient
|
|
48
|
+
private me?: { id: number; name: string; mention: RegExp }
|
|
49
|
+
/** この時刻(Unix 秒)より前の発言は、停止中に届いたものとして記録だけする */
|
|
50
|
+
private startedAt = 0
|
|
51
|
+
private readonly roomNames = new Map<number, string>()
|
|
52
|
+
/**
|
|
53
|
+
* ルームごとの、最後に差分を取得したときの last_update_time。last_update_time は秒単位なので、同じ秒のうちに
|
|
54
|
+
* 後から届いた発言を取りこぼさないよう、同じ時刻でもう一度だけ取得する(done が false の間)
|
|
55
|
+
*/
|
|
56
|
+
private readonly fetched = new Map<number, { t: number; done: boolean }>()
|
|
57
|
+
/** DM の相手 → ダイレクトチャットのルーム ID */
|
|
58
|
+
private readonly dmRooms = new Map<number, number>()
|
|
59
|
+
/** 受け取った発言(ルーム ID-メッセージ ID)→ 送信者と本文。重複の除去、返信の記法、添付の取得に使う */
|
|
60
|
+
private readonly messages = new Map<string, { author: number; body: string }>()
|
|
61
|
+
private timer?: Timer
|
|
62
|
+
private lastError = ""
|
|
63
|
+
|
|
64
|
+
constructor(
|
|
65
|
+
private readonly cfg: ChatworkConfig,
|
|
66
|
+
private readonly relay: Relay,
|
|
67
|
+
private readonly log: Log,
|
|
68
|
+
private readonly now: () => number = Date.now,
|
|
69
|
+
) {
|
|
70
|
+
this.api = new ApiClient({
|
|
71
|
+
label: this.label,
|
|
72
|
+
base: cfg.apiBase ?? "https://api.chatwork.com/v2",
|
|
73
|
+
auth: () => ({ "x-chatworktoken": cfg.apiToken }),
|
|
74
|
+
errorMessage: (raw) => jsonError(raw, (b) => (b.errors as string[] | undefined)?.join(", ")),
|
|
75
|
+
rateLimited: (res, msg, now) =>
|
|
76
|
+
// ルームごとの投稿の制限(10 秒に 10 回)は、ヘッダーではなくエラーの文面でしか見分けられない。そのルームにだけかかる。
|
|
77
|
+
// 全体の制限(5 分に 300 回)なら、解除の時刻(x-ratelimit-reset。Unix 秒)まで止める。ヘッダーがなければ 1 分待つ
|
|
78
|
+
/per room/i.test(msg)
|
|
79
|
+
? { message: "このルームへの投稿が多すぎます。10 秒ほど待ってから送ってください" }
|
|
80
|
+
: { resumeAt: Number(res.headers.get("x-ratelimit-reset")) * 1000 || now + 60_000, message: "Chatwork の API の回数制限(5 分に 300 回)に達しました" },
|
|
81
|
+
now,
|
|
82
|
+
})
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Bot のアカウントを確認し、ポーリングを始める。今あるルームの更新時刻を起点にし、起動時には差分を取得しない。
|
|
87
|
+
* force=0 の差分の起点は Chatwork がトークンごとに覚えているので、停止中の発言は、そのルームの次の差分に含まれて届く
|
|
88
|
+
*/
|
|
89
|
+
async start(): Promise<void> {
|
|
90
|
+
const [me, rooms] = await Promise.all([this.api.call("GET", "/me") as Promise<{ account_id: number; name: string }>, this.listRooms()])
|
|
91
|
+
this.me = { id: me.account_id, name: me.name, mention: selfMention(me.account_id, me.name) }
|
|
92
|
+
this.startedAt = Math.floor(this.now() / 1000)
|
|
93
|
+
for (const r of rooms) this.fetched.set(r.room_id, { t: r.last_update_time, done: true })
|
|
94
|
+
this.schedule()
|
|
95
|
+
this.log.info("Chatwork のポーリングを始めました")
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
stop(): void {
|
|
99
|
+
clearTimeout(this.timer)
|
|
100
|
+
this.timer = undefined
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
private schedule(): void {
|
|
104
|
+
this.timer = setTimeout(
|
|
105
|
+
() => {
|
|
106
|
+
this.poll()
|
|
107
|
+
.then(() => (this.lastError = ""))
|
|
108
|
+
.catch((err) => {
|
|
109
|
+
// 同じ失敗を取得のたびに書かない
|
|
110
|
+
const msg = String(err)
|
|
111
|
+
if (msg !== this.lastError) this.log.error("Chatwork から取得できませんでした", { error: msg })
|
|
112
|
+
this.lastError = msg
|
|
113
|
+
})
|
|
114
|
+
.finally(() => {
|
|
115
|
+
if (this.timer) this.schedule()
|
|
116
|
+
})
|
|
117
|
+
},
|
|
118
|
+
Math.max(MIN_POLL_MS, this.cfg.pollMs ?? 5000),
|
|
119
|
+
)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** ルーム一覧で更新のあったルームだけ、前回からの差分を取得する */
|
|
123
|
+
async poll(): Promise<void> {
|
|
124
|
+
if (this.api.paused) return
|
|
125
|
+
for (const r of await this.listRooms()) {
|
|
126
|
+
if (r.type === "my") continue
|
|
127
|
+
const prev = this.fetched.get(r.room_id)
|
|
128
|
+
// 起動後に現れたグループチャットは、Bot が追加されたもの(LINE の join に当たる。Chatwork にはその通知がない)
|
|
129
|
+
if (!prev && r.type === "group") this.relay.joined(roomKey(r.room_id))
|
|
130
|
+
if (prev && r.last_update_time <= prev.t && prev.done) continue
|
|
131
|
+
const msgs = await this.list<CwMessage>(`/rooms/${r.room_id}/messages?force=0`)
|
|
132
|
+
this.fetched.set(r.room_id, { t: r.last_update_time, done: prev?.t === r.last_update_time })
|
|
133
|
+
// 差分の並び順は、ドキュメントに書かれていない
|
|
134
|
+
for (const m of msgs.sort((a, b) => a.send_time - b.send_time)) this.handle(r, m)
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private handle(r: CwRoom, m: CwMessage): void {
|
|
139
|
+
const key = `${r.room_id}-${m.message_id}`
|
|
140
|
+
if (this.messages.has(key)) return
|
|
141
|
+
const author = m.account.account_id
|
|
142
|
+
remember(this.messages, key, { author, body: m.body })
|
|
143
|
+
if (!this.me || author === this.me.id) return
|
|
144
|
+
const isDM = r.type === "direct"
|
|
145
|
+
if (isDM) this.dmRooms.set(author, r.room_id)
|
|
146
|
+
const parsed = parseBody(m.body, this.me, this.me.mention)
|
|
147
|
+
// 受け取りの合図は出さない。リアクションの API がなく、既読はほかの人に見えない(ADR 0012)
|
|
148
|
+
this.relay.receive({
|
|
149
|
+
id: m.message_id,
|
|
150
|
+
room: isDM ? userKey(author) : roomKey(r.room_id),
|
|
151
|
+
sender: userKey(author),
|
|
152
|
+
senderName: m.account.name,
|
|
153
|
+
text: parsed.text,
|
|
154
|
+
ts: m.send_time * 1000,
|
|
155
|
+
attachments: parsed.attachments,
|
|
156
|
+
isDM,
|
|
157
|
+
mentioned: isDM || parsed.mentioned,
|
|
158
|
+
toOthers: addressesOthers(m.body, author),
|
|
159
|
+
stale: m.send_time < this.startedAt,
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async send(room: string, text: string, opts?: { replyTo?: string; files?: string[] }): Promise<string[]> {
|
|
164
|
+
const rid = await this.roomId(room)
|
|
165
|
+
const files = opts?.files ?? []
|
|
166
|
+
const parts = splitText(text, this.capabilities.text.max, this.capabilities.text.parts)
|
|
167
|
+
const replyTo = opts?.replyTo
|
|
168
|
+
const author = replyTo ? this.messages.get(`${rid}-${replyTo}`)?.author : undefined
|
|
169
|
+
if (parts.length > 0 && author !== undefined) parts[0] = `[rp aid=${author} to=${rid}-${replyTo}]\n${parts[0]}`
|
|
170
|
+
if (parts.length === 0 && files.length === 0) throw new Error("本文が空です")
|
|
171
|
+
// 本文の最後の 1 通は、1 つ目のファイルに添える。ファイルの投稿は、メッセージ ID を返さない
|
|
172
|
+
const caption = files.length > 0 ? parts.pop() : undefined
|
|
173
|
+
const ids: string[] = []
|
|
174
|
+
for (const p of parts) ids.push(await this.post(rid, p))
|
|
175
|
+
for (const [i, f] of files.entries()) {
|
|
176
|
+
const form = new FormData()
|
|
177
|
+
form.append("file", Bun.file(f), basename(f))
|
|
178
|
+
if (i === 0 && caption) form.append("message", caption)
|
|
179
|
+
await this.api.call("POST", `/rooms/${rid}/files`, form, 60_000)
|
|
180
|
+
}
|
|
181
|
+
return ids
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async sendApproval(user: string, text: string, _requestId: string): Promise<void> {
|
|
185
|
+
// ボタンはないので、yes/no の文字で答えてもらう
|
|
186
|
+
await this.post(await this.roomId(user), text)
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async notice(room: string, text: string): Promise<boolean> {
|
|
190
|
+
await this.post(await this.roomId(room), text)
|
|
191
|
+
return true
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async download(room: string, messageId: string, dir: string): Promise<string[]> {
|
|
195
|
+
assertNumericId(messageId)
|
|
196
|
+
const rid = await this.roomId(room)
|
|
197
|
+
const body =
|
|
198
|
+
this.messages.get(`${rid}-${messageId}`)?.body ?? ((await this.api.call("GET", `/rooms/${rid}/messages/${messageId}`)) as CwMessage).body
|
|
199
|
+
const ids = [...new Set([...body.matchAll(/\[download:(\d+)\]/g)].map((m) => m[1]!))]
|
|
200
|
+
if (ids.length === 0) throw new Error("この発言には添付がありません")
|
|
201
|
+
const paths: string[] = []
|
|
202
|
+
for (const fid of ids) {
|
|
203
|
+
const file = (await this.api.call("GET", `/rooms/${rid}/files/${fid}?create_download_url=1`)) as { filename: string; download_url?: string }
|
|
204
|
+
// 取得用の URL の有効期限は 30 秒。API トークンは付けない(別のホストへ渡さない)
|
|
205
|
+
const res = await this.api.download(file.download_url ?? "", "none")
|
|
206
|
+
paths.push(await saveDownload(res, dir, `${this.now()}-${messageId}-${fid}`, extname(file.filename)))
|
|
207
|
+
}
|
|
208
|
+
return paths
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async roomName(room: string): Promise<string | undefined> {
|
|
212
|
+
const m = /^r(\d+)$/.exec(localId(room))
|
|
213
|
+
return m ? this.roomNames.get(Number(m[1])) : undefined
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async edit(room: string, messageId: string, text: string): Promise<void> {
|
|
217
|
+
assertNumericId(messageId)
|
|
218
|
+
const rid = await this.roomId(room)
|
|
219
|
+
await this.api.call("PUT", `/rooms/${rid}/messages/${messageId}`, new URLSearchParams({ body: truncate(text.trim(), this.capabilities.text.max) }))
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
private async post(rid: number, body: string): Promise<string> {
|
|
223
|
+
const res = (await this.api.call("POST", `/rooms/${rid}/messages`, new URLSearchParams({ body }))) as { message_id: string }
|
|
224
|
+
return res.message_id
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
private async listRooms(): Promise<CwRoom[]> {
|
|
228
|
+
const list = await this.list<CwRoom>("/rooms")
|
|
229
|
+
for (const r of list) this.roomNames.set(r.room_id, r.name)
|
|
230
|
+
return list
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** 一覧を返す API。0 件のときは 204 で本文がない */
|
|
234
|
+
private async list<T>(path: string): Promise<T[]> {
|
|
235
|
+
return ((await this.api.call("GET", path)) as T[] | null) ?? []
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** ルームの ID を、Chatwork のルーム ID にする。DM の相手なら、コンタクトからダイレクトチャットを探す */
|
|
239
|
+
private async roomId(id: string): Promise<number> {
|
|
240
|
+
const m = /^([ru])(\d+)$/.exec(localId(id))
|
|
241
|
+
if (!id.startsWith(`${SERVICE}:`) || !m) throw new Error(`Chatwork の ID の形が違います: ${id}`)
|
|
242
|
+
const n = Number(m[2])
|
|
243
|
+
if (m[1] === "r") return n
|
|
244
|
+
let rid = this.dmRooms.get(n)
|
|
245
|
+
if (rid === undefined) {
|
|
246
|
+
for (const c of await this.list<{ account_id: number; room_id: number }>("/contacts")) this.dmRooms.set(c.account_id, c.room_id)
|
|
247
|
+
rid = this.dmRooms.get(n)
|
|
248
|
+
}
|
|
249
|
+
if (rid === undefined) throw new Error("この人とのダイレクトチャットが見つかりません(Bot のコンタクトではありません)")
|
|
250
|
+
return rid
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Bot へのメンション(To と、Bot の発言への返信)。Chatwork の画面で付けると、記法の後ろに「名前さん」が入る */
|
|
255
|
+
function selfMention(id: number, name: string): RegExp {
|
|
256
|
+
return new RegExp(`\\[(?:To:${id}|rp aid=${id} to=\\d+-\\d+)\\][ \\t]*(?:${escapeRegExp(name)}(?:さん)?)?`, "g")
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** 送信者以外の人への To か、その人の発言への返信があるか(Bot を含む。Inbound.toOthers)。全員宛て([toall])は含まない(ADR 0028) */
|
|
260
|
+
export function addressesOthers(body: string, author: number): boolean {
|
|
261
|
+
return [...body.matchAll(/\[(?:To:(\d+)|rp aid=(\d+) to=\d+-\d+)\]/g)].some(([, to, rp]) => Number(to ?? rp) !== author)
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** 本文から、Bot へのメンションと返信の記法を取り除き、添付を取り出す。ほかの記法はそのまま渡す */
|
|
265
|
+
export function parseBody(
|
|
266
|
+
body: string,
|
|
267
|
+
me: { id: number; name: string },
|
|
268
|
+
self = selfMention(me.id, me.name),
|
|
269
|
+
): { text: string; attachments: Attachment[]; mentioned: boolean } {
|
|
270
|
+
const attachments: Attachment[] = []
|
|
271
|
+
let text = body.replace(self, "")
|
|
272
|
+
const mentioned = text !== body
|
|
273
|
+
text = text.replace(/\[download:\d+\]([\s\S]*?)\[\/download\]/g, (_, label: string) => {
|
|
274
|
+
// 表示は「ファイル名 (12.34 KB)」
|
|
275
|
+
const name = label.replace(/\s*\([\d.,]+\s*[KMG]?B\)\s*$/i, "").trim() || "file"
|
|
276
|
+
attachments.push({ name, type: IMAGE_EXT.has(extname(name).toLowerCase()) ? "image" : "file" })
|
|
277
|
+
return ""
|
|
278
|
+
})
|
|
279
|
+
text = text
|
|
280
|
+
.replace(/\[preview [^\]]*\]/g, "")
|
|
281
|
+
.replace(/\[info\]\s*\[title\]\[dtext:file_uploaded\]\[\/title\]\s*\[\/info\]/g, "")
|
|
282
|
+
.trim()
|
|
283
|
+
text ||= attachmentOnlyText(attachments)
|
|
284
|
+
return { text, attachments, mentioned }
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function escapeRegExp(s: string): string {
|
|
288
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
|
289
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// コネクターが共通で使うユーティリティ。
|
|
2
|
+
|
|
3
|
+
import { mkdir, writeFile } from "node:fs/promises"
|
|
4
|
+
import { join } from "node:path"
|
|
5
|
+
import type { Attachment, Log, Verdict } from "../core/relay.ts"
|
|
6
|
+
|
|
7
|
+
const CACHE_CAP = 1000
|
|
8
|
+
const MAX_DOWNLOAD_BYTES = 25 * 1024 * 1024
|
|
9
|
+
const TOO_LARGE = "大きすぎるため取得しません(25MB まで)"
|
|
10
|
+
export const TRUNCATED_NOTE = "\n\n(長すぎるため、ここから先は省略しました)"
|
|
11
|
+
|
|
12
|
+
/** 追加し、上限を超えたら古いものから捨てる。プロセスのメモリ上にだけ置くキャッシュ(重複の除去、ID の対応など)に使う */
|
|
13
|
+
export function remember(c: Set<string>, key: string): void
|
|
14
|
+
export function remember<V>(c: Map<string, V>, key: string, value: V): void
|
|
15
|
+
export function remember<V>(c: Set<string> | Map<string, V>, key: string, value?: V): void {
|
|
16
|
+
if (c instanceof Set) c.add(key)
|
|
17
|
+
else c.set(key, value!)
|
|
18
|
+
if (c.size > CACHE_CAP) c.delete(c.keys().next().value!)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** UTF-16 で limit 単位に収まる長さ。サロゲートペアの途中では切らない */
|
|
22
|
+
export function fitUnits(s: string, limit: number): number {
|
|
23
|
+
if (s.length <= limit) return s.length
|
|
24
|
+
const code = s.charCodeAt(limit - 1)
|
|
25
|
+
return code >= 0xd800 && code <= 0xdbff ? limit - 1 : limit
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** max 単位を超える本文を切り、省略したことを書き添える */
|
|
29
|
+
export function truncate(text: string, max: number): string {
|
|
30
|
+
return text.length <= max ? text : text.slice(0, fitUnits(text, max - TRUNCATED_NOTE.length)) + TRUNCATED_NOTE
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 本文を、1 通 max 単位で parts 通までに分ける。段落、行、空白の切れ目で分ける(前半にしかなければ、そのまま切る)。
|
|
35
|
+
* 入りきらない分は、最後の 1 通を切って省略を書き添える
|
|
36
|
+
*/
|
|
37
|
+
export function splitText(text: string, max: number, parts: number): string[] {
|
|
38
|
+
const out: string[] = []
|
|
39
|
+
let rest = text.trim()
|
|
40
|
+
while (rest.length > max && out.length < parts - 1) {
|
|
41
|
+
let cut = fitUnits(rest, max)
|
|
42
|
+
for (const sep of ["\n\n", "\n", " "]) {
|
|
43
|
+
const i = rest.lastIndexOf(sep, cut - sep.length)
|
|
44
|
+
if (i > max / 2) {
|
|
45
|
+
cut = i
|
|
46
|
+
break
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
out.push(rest.slice(0, cut).trimEnd())
|
|
50
|
+
rest = rest.slice(cut).trimStart()
|
|
51
|
+
}
|
|
52
|
+
if (rest) out.push(truncate(rest, max))
|
|
53
|
+
return out
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 取得した添付を dir に保存する(25MB まで)。名前は <stem><ext>。ext は記号を除いてから使う */
|
|
57
|
+
export async function saveDownload(res: Response, dir: string, stem: string, ext: string): Promise<string> {
|
|
58
|
+
if (Number(res.headers.get("content-length") ?? 0) > MAX_DOWNLOAD_BYTES) throw new Error(TOO_LARGE)
|
|
59
|
+
const buf = Buffer.from(await res.arrayBuffer())
|
|
60
|
+
if (buf.length > MAX_DOWNLOAD_BYTES) throw new Error(TOO_LARGE)
|
|
61
|
+
await mkdir(dir, { recursive: true, mode: 0o700 })
|
|
62
|
+
const path = join(dir, `${stem}${ext.replace(/[^.a-zA-Z0-9]/g, "")}`)
|
|
63
|
+
await writeFile(path, buf, { mode: 0o600 })
|
|
64
|
+
return path
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** コネクターの API が受け付けるメッセージ ID か(数字だけ)。パスに入れる前に確認する */
|
|
68
|
+
export function assertNumericId(id: string): void {
|
|
69
|
+
if (!/^\d+$/.test(id)) throw new Error("message_id の形が違います")
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 本文がなく添付だけの発言の、本文の代わり */
|
|
73
|
+
export function attachmentOnlyText(attachments: Attachment[]): string {
|
|
74
|
+
if (attachments.length === 0) return ""
|
|
75
|
+
return attachments.every((a) => a.type === "image") ? "(画像)" : "(ファイル)"
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** 受け取りの合図を出す関数を作る(ADR 0012)。失敗しても発言の処理は止めず、同じ失敗は続けてログに書かない */
|
|
79
|
+
export function acknowledger(log: Log, label: string): (run: () => Promise<unknown>) => void {
|
|
80
|
+
let last = ""
|
|
81
|
+
return (run) => {
|
|
82
|
+
run().then(
|
|
83
|
+
() => (last = ""),
|
|
84
|
+
(err) => {
|
|
85
|
+
const msg = String(err)
|
|
86
|
+
if (msg !== last) log.error(`${label} で受け取りの合図を出せませんでした`, { error: msg })
|
|
87
|
+
last = msg
|
|
88
|
+
},
|
|
89
|
+
)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** 承認のボタンに載せる値(perm:allow:<ID>・perm:deny:<ID>) */
|
|
94
|
+
export const permissionData = (verdict: Verdict, requestId: string) => `perm:${verdict}:${requestId}`
|
|
95
|
+
|
|
96
|
+
/** ボタンの値から、答えと依頼の ID を読む。形が違えば undefined */
|
|
97
|
+
export function parsePermissionData(data: string): { verdict: Verdict; id: string } | undefined {
|
|
98
|
+
const m = /^perm:(allow|always|deny):([a-km-z]{5})$/.exec(data)
|
|
99
|
+
return m ? { verdict: m[1] as Verdict, id: m[2]! } : undefined
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** ボタンで答えたあとに見せる文言 */
|
|
103
|
+
export function verdictText(ok: boolean, verdict: Verdict): string {
|
|
104
|
+
if (!ok) return "その依頼は見つからないか、すでに答えが出ています"
|
|
105
|
+
return { allow: "✅ 許可しました", always: "✅ 常に許可しました", deny: "❌ 拒否しました" }[verdict]
|
|
106
|
+
}
|