ocean-crew 0.0.0-stage → 0.4.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/LICENSE +21 -0
- package/README.md +156 -2
- package/THIRD_PARTY_NOTICES.md +159 -0
- package/client.js +31389 -0
- package/cordis.patch.yml +6 -0
- package/dist/host/chat/btw.js +436 -0
- package/dist/host/chat/channel.js +1241 -0
- package/dist/host/chat/chat-index.js +344 -0
- package/dist/host/chat/delivery.js +231 -0
- package/dist/host/chat/feed.js +165 -0
- package/dist/host/chat/handoffs.js +625 -0
- package/dist/host/chat/parts.js +2033 -0
- package/dist/host/chat/requests.js +155 -0
- package/dist/host/chat/resume.js +364 -0
- package/dist/host/chat/side.js +457 -0
- package/dist/host/chat/steer.js +346 -0
- package/dist/host/chat/turns.js +1457 -0
- package/dist/host/connectors/catalog.js +331 -0
- package/dist/host/connectors/gateway.js +339 -0
- package/dist/host/connectors/index.js +1235 -0
- package/dist/host/connectors/mail/index.js +912 -0
- package/dist/host/connectors/mail/presets.js +53 -0
- package/dist/host/connectors/mail/transport.js +519 -0
- package/dist/host/connectors/oauth.js +337 -0
- package/dist/host/core/constants.js +123 -0
- package/dist/host/core/diagnostics.js +310 -0
- package/dist/host/core/dsh-update.js +212 -0
- package/dist/host/core/events.js +16 -0
- package/dist/host/core/files.js +37 -0
- package/dist/host/core/folders.js +283 -0
- package/dist/host/core/home-lock.js +137 -0
- package/dist/host/core/links.js +52 -0
- package/dist/host/core/runtime.js +5 -0
- package/dist/host/core/store.js +662 -0
- package/dist/host/core/text.js +59 -0
- package/dist/host/core/thinking.js +60 -0
- package/dist/host/core/time-context.js +69 -0
- package/dist/host/core/update.js +466 -0
- package/dist/host/groups/calls.js +684 -0
- package/dist/host/groups/index.js +79 -0
- package/dist/host/groups/log.js +334 -0
- package/dist/host/groups/prompt.js +124 -0
- package/dist/host/groups/relay.js +489 -0
- package/dist/host/groups/round.js +992 -0
- package/dist/host/groups/tasks.js +217 -0
- package/dist/host/groups/tools.js +478 -0
- package/dist/host/groups/types.js +8 -0
- package/dist/host/im/format.js +228 -0
- package/dist/host/im/index.js +2461 -0
- package/dist/host/im/platforms/feishu.js +1134 -0
- package/dist/host/im/platforms/index.js +6 -0
- package/dist/host/im/platforms/media-type.js +70 -0
- package/dist/host/im/platforms/weixin.js +1117 -0
- package/dist/host/im/reaction.js +51 -0
- package/dist/host/im/supervisor.js +56 -0
- package/dist/host/team/agents.js +161 -0
- package/dist/host/team/models.js +427 -0
- package/dist/host/team/permissions.js +263 -0
- package/dist/host/team/privacy.js +108 -0
- package/dist/host/team/prompt.js +86 -0
- package/dist/host/team/providers.js +461 -0
- package/dist/host/team/roster.js +1011 -0
- package/dist/host/team/tools.js +1638 -0
- package/dist/host/work/approvals.js +290 -0
- package/dist/host/work/avatar-library.js +155 -0
- package/dist/host/work/avatar.js +132 -0
- package/dist/host/work/capabilities.js +862 -0
- package/dist/host/work/companion.js +306 -0
- package/dist/host/work/goal-skills.js +91 -0
- package/dist/host/work/goals.js +1337 -0
- package/dist/host/work/images.js +283 -0
- package/dist/host/work/learning.js +1021 -0
- package/dist/host/work/memory-pending.js +108 -0
- package/dist/host/work/memory.js +3237 -0
- package/dist/host/work/notify.js +146 -0
- package/dist/host/work/reset.js +43 -0
- package/dist/host/work/schedules.js +309 -0
- package/dist/host/work/secrets.js +702 -0
- package/dist/host/work/steward.js +166 -0
- package/dist/host/work/tts.js +192 -0
- package/dist/host/work/usage.js +84 -0
- package/dist/index.js +137 -0
- package/dist/shared/api.js +32 -0
- package/dist/shared/companion.js +110 -0
- package/dist/shared/config.js +3 -0
- package/dist/shared/coordination.js +6 -0
- package/dist/shared/group-replies.js +95 -0
- package/dist/shared/im-platforms.js +35 -0
- package/dist/shared/im.js +3 -0
- package/dist/shared/mentions.js +85 -0
- package/dist/shared/state.js +25 -0
- package/package.json +81 -5
|
@@ -0,0 +1,2461 @@
|
|
|
1
|
+
// IM: talk to Bots from chat apps. A connection is one IM bot account bound to a Bot;
|
|
2
|
+
// direct chats reach that Bot, platform group chats can be bound to a Ocean Crew group.
|
|
3
|
+
// The platform adapters (im/platforms/) own the wire; this module owns pairing,
|
|
4
|
+
// routing, cards and the send queues. Only the dsh holding the team lock connects.
|
|
5
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
6
|
+
import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { IM_PLATFORMS, imPlatform } from "../../shared/im-platforms.js";
|
|
9
|
+
import { viewCardText } from "../chat/parts.js";
|
|
10
|
+
import { listenGlobal } from "../core/events.js";
|
|
11
|
+
import { replaceFile } from "../core/files.js";
|
|
12
|
+
import { adapters as adapterRegistry } from "./platforms/index.js";
|
|
13
|
+
import { isSupportedImageType } from "./platforms/media-type.js";
|
|
14
|
+
import { startStatusReaction } from "./reaction.js";
|
|
15
|
+
import { failClass, nextAction } from "./supervisor.js";
|
|
16
|
+
const RECONCILE_MS = 15_000;
|
|
17
|
+
const RUNTIME_SAVE_MS = 400;
|
|
18
|
+
// How many undelivered texts one chat keeps, and how long a send may stay unconfirmed
|
|
19
|
+
// before it is reported as unknown rather than retried forever.
|
|
20
|
+
const OUTBOX_LIMIT = 50;
|
|
21
|
+
const RETRY_MS = 5_000;
|
|
22
|
+
const SEND_TIMEOUT_MS = 60_000;
|
|
23
|
+
const QUEUE_LIMIT = 100;
|
|
24
|
+
// The largest file an answer may carry out. The bytes are copied under the plugin home
|
|
25
|
+
// before the record is written, so a crash cannot leave a message naming a file that is
|
|
26
|
+
// gone; the copy is dropped once the send has an outcome.
|
|
27
|
+
const MEDIA_LIMIT = 25 * 1024 * 1024;
|
|
28
|
+
const TYPING_MS = 4_000;
|
|
29
|
+
// The first "typing" pulse does not wait for the four-second tick: a chat should see the
|
|
30
|
+
// Bot is working as soon as its message is handed over, not once the turn may already be
|
|
31
|
+
// over.
|
|
32
|
+
const TYPING_FIRST_MS = 250;
|
|
33
|
+
// A reaction left on a message no longer ends on its own; drop it after this long.
|
|
34
|
+
const REACTION_MAX_MS = 15 * 60_000;
|
|
35
|
+
const NUMBERS = /^\s*\d+(\s+\d+)*\s*$/;
|
|
36
|
+
// What a file handed to a chat may look like: an image when its extension says so, a
|
|
37
|
+
// file otherwise, and a media type for the platforms that want one.
|
|
38
|
+
const IMAGE_EXT = /\.(png|jpe?g|gif|webp|bmp)$/i;
|
|
39
|
+
const MIME_EXT = {
|
|
40
|
+
png: "image/png",
|
|
41
|
+
jpg: "image/jpeg",
|
|
42
|
+
jpeg: "image/jpeg",
|
|
43
|
+
gif: "image/gif",
|
|
44
|
+
webp: "image/webp",
|
|
45
|
+
pdf: "application/pdf",
|
|
46
|
+
txt: "text/plain",
|
|
47
|
+
md: "text/markdown",
|
|
48
|
+
json: "application/json",
|
|
49
|
+
zip: "application/zip",
|
|
50
|
+
};
|
|
51
|
+
// The registry is read as a map the tests (and a future adapter) can extend by platform id.
|
|
52
|
+
const adapters = adapterRegistry;
|
|
53
|
+
const secretField = (key) => key.replace(/[A-Z]/g, (char) => `_${char}`).toUpperCase();
|
|
54
|
+
// The admission reasons the host uses when it cannot take an image as an image.
|
|
55
|
+
const IMAGE_REFUSAL_REASONS = new Set([
|
|
56
|
+
"MODEL_DOES_NOT_SUPPORT_IMAGES",
|
|
57
|
+
"IMAGE_TOO_LARGE",
|
|
58
|
+
"IMAGES_TOO_LARGE",
|
|
59
|
+
"IMAGE_TOO_MANY_PIXELS",
|
|
60
|
+
"TOO_MANY_IMAGES",
|
|
61
|
+
"IMAGE_TYPE_MISMATCH",
|
|
62
|
+
]);
|
|
63
|
+
const isImageRefusal = (error) => {
|
|
64
|
+
if (error?.code !== "session/attachment-invalid" && error?.code !== "attachment-error")
|
|
65
|
+
return false;
|
|
66
|
+
const reason = error?.details?.reason;
|
|
67
|
+
if (reason === undefined)
|
|
68
|
+
return true;
|
|
69
|
+
return IMAGE_REFUSAL_REASONS.has(String(reason));
|
|
70
|
+
};
|
|
71
|
+
export function install(rt) {
|
|
72
|
+
const { ctx } = rt;
|
|
73
|
+
// works through its own record type. One cast states that gap.
|
|
74
|
+
const state = rt.state;
|
|
75
|
+
const imDir = join(rt.home, "im");
|
|
76
|
+
const mediaDir = join(imDir, "media");
|
|
77
|
+
// The health check and the per-message timeout; the plugin config may shorten
|
|
78
|
+
// them, which the unit tests use to see the supervisor work without fake timers.
|
|
79
|
+
const reconcileMs = Number(rt.config?.imReconcileMs) > 0 ? Number(rt.config.imReconcileMs) : RECONCILE_MS;
|
|
80
|
+
const sendTimeoutMs = Number(rt.config?.imSendTimeoutMs) > 0 ? Number(rt.config.imSendTimeoutMs) : SEND_TIMEOUT_MS;
|
|
81
|
+
const zh = () => String(rt.uiLanguage?.() ?? "").startsWith("Chinese");
|
|
82
|
+
const text = (key, values = {}) => {
|
|
83
|
+
const line = {
|
|
84
|
+
requested: zh()
|
|
85
|
+
? "已向 Ocean Crew 发出连接请求,请在电脑上的 Ocean Crew 设置 → IM 里允许。"
|
|
86
|
+
: "A connection request was sent to Ocean Crew; allow it in Settings → IM on the computer.",
|
|
87
|
+
unbound: zh()
|
|
88
|
+
? "这个 IM 机器人还没绑定 Bot,请在 Ocean Crew 设置 → IM 里选一个。"
|
|
89
|
+
: "This IM bot is not bound to a Bot yet; pick one in Ocean Crew Settings → IM.",
|
|
90
|
+
unboundGroup: zh()
|
|
91
|
+
? "这个群还没绑定,请在 Ocean Crew 设置 → IM 里给它选一个群或 Bot。"
|
|
92
|
+
: "This group is not bound yet; pick a group or a Bot for it in Ocean Crew Settings → IM.",
|
|
93
|
+
connected: zh()
|
|
94
|
+
? `已连接,现在可以和 ${values.target} 说话了。`
|
|
95
|
+
: `Connected — you can talk to ${values.target} now.`,
|
|
96
|
+
stopped: zh() ? "已停下。" : "Stopped.",
|
|
97
|
+
idle: zh() ? "现在没有在做的活。" : "Nothing is running.",
|
|
98
|
+
stale: zh() ? "这张卡已经答过了。" : "This card was already answered.",
|
|
99
|
+
noFile: zh()
|
|
100
|
+
? "这个文件发不过去,请在电脑上发。"
|
|
101
|
+
: "This file cannot be sent here; send it on the computer.",
|
|
102
|
+
greeting: zh() ? `你好,我是 ${values.name}。` : `Hello, I am ${values.name}.`,
|
|
103
|
+
question: zh() ? `${values.bot} 问你:` : `${values.bot} asks: `,
|
|
104
|
+
approval: zh() ? `${values.bot} 请你审批:` : `${values.bot} asks for approval: `,
|
|
105
|
+
secretAsk: zh()
|
|
106
|
+
? `${values.bot} 要密钥 ${values.name},请在电脑或手机 App 上填。`
|
|
107
|
+
: `${values.bot} needs the key ${values.name} — fill it on the computer or the phone app.`,
|
|
108
|
+
viewShow: zh()
|
|
109
|
+
? `${values.bot} 发了一个卡片,请在电脑或手机 App 上回复。`
|
|
110
|
+
: `${values.bot} shared a card — answer it on the computer or the phone app.`,
|
|
111
|
+
viewPick: zh()
|
|
112
|
+
? `${values.bot} 发了一个卡片,点下面的按钮就能回答。`
|
|
113
|
+
: `${values.bot} shared a card — press a button below to answer.`,
|
|
114
|
+
answered: zh() ? "已答" : "answered",
|
|
115
|
+
cmdHelp: zh()
|
|
116
|
+
? "可以用的命令:\n/status 查看这个 Bot 的状态\n/stop 停止正在进行的回合\n/new 开一段新会话\n/menu 打开操作卡片\n/help 显示这份帮助"
|
|
117
|
+
: "Commands:\n/status — this Bot's state\n/stop — stop the running turn\n/new — start a fresh conversation\n/menu — show the actions card\n/help — this list",
|
|
118
|
+
cmdStatus: zh()
|
|
119
|
+
? `${values.bot}:模型 ${values.model};${values.running ? "正在工作" : "空闲"};已开 ${values.parts} 段会话。`
|
|
120
|
+
: `${values.bot}: model ${values.model}; ${values.running ? "working" : "idle"}; ${values.parts} conversation part(s).`,
|
|
121
|
+
cmdStopped: zh() ? "已停止当前回合。" : "Stopped the running turn.",
|
|
122
|
+
cmdNothingRunning: zh() ? "现在没有在运行的任务。" : "Nothing is running.",
|
|
123
|
+
cmdNewStarted: zh()
|
|
124
|
+
? "已开始一段新会话,之前的上下文留在了上一段。"
|
|
125
|
+
: "Started a fresh conversation; the earlier context stays in the previous part.",
|
|
126
|
+
cmdNewBusy: zh()
|
|
127
|
+
? "Bot 正在工作,先 /stop 或等它结束。"
|
|
128
|
+
: "The Bot is working; /stop first or wait for it to finish.",
|
|
129
|
+
cmdGroupOnly: zh()
|
|
130
|
+
? "这个命令只能在和 Bot 的私聊里用。"
|
|
131
|
+
: "This command only works in a direct chat with the Bot.",
|
|
132
|
+
submit: zh() ? "提交" : "Send",
|
|
133
|
+
cancel: zh() ? "取消" : "Cancel",
|
|
134
|
+
yes: zh() ? "是" : "Yes",
|
|
135
|
+
no: zh() ? "否" : "No",
|
|
136
|
+
pickMany: zh() ? "可多选" : "Choose one or more",
|
|
137
|
+
menuBody: zh() ? `${values.bot} 的操作:下面是常用动作。` : `${values.bot} actions — pick one below.`,
|
|
138
|
+
stop: zh() ? "停止" : "Stop",
|
|
139
|
+
newPart: zh() ? "开新会话" : "New conversation",
|
|
140
|
+
status: zh() ? "状态" : "Status",
|
|
141
|
+
help: zh() ? "帮助" : "Help",
|
|
142
|
+
cmdUnknown: zh()
|
|
143
|
+
? `没有这个命令:${values.name}。发 /help 看看。`
|
|
144
|
+
: `No such command: ${values.name}. Send /help.`,
|
|
145
|
+
imageAsFile: zh()
|
|
146
|
+
? `图片没能直接给模型看(可能是当前模型不支持看图或文件过大),已作为 ${values.count} 个文件附上,可以用工具打开。`
|
|
147
|
+
: `The image could not be shown to the model (the model may not read images, or the file was too large); it is attached as ${values.count} file(s) for your tools to open.`,
|
|
148
|
+
numbers: zh() ? "回复编号" : "reply with the number",
|
|
149
|
+
numbersMulti: zh() ? "回复编号,多选用空格隔开" : "reply with the numbers, separated by spaces",
|
|
150
|
+
allow: zh() ? "允许一次" : "Allow once",
|
|
151
|
+
reject: zh() ? "拒绝" : "Reject",
|
|
152
|
+
}[key];
|
|
153
|
+
return line ?? key;
|
|
154
|
+
};
|
|
155
|
+
// ---------------------------------------------------------------- outbox
|
|
156
|
+
// Undelivered texts, per connection and chat, persisted beside the runtime file so a
|
|
157
|
+
// restart or a crash does not lose a reply the user is waiting for. Card sends keep
|
|
158
|
+
// their own persisted record (`cards`); this holds the plain texts and their state.
|
|
159
|
+
//
|
|
160
|
+
// A record is `{ id, chatKey, chat, state, attempts, body, buttons? }`. `body` and
|
|
161
|
+
// `buttons` are what the adapter needs; `state` is one of:
|
|
162
|
+
// queued - never attempted, or the platform refused without accepting it
|
|
163
|
+
// sending - an attempt was made and its outcome is not known yet (crash during send)
|
|
164
|
+
// unknown - the platform may have accepted it; never resent automatically
|
|
165
|
+
// A record is removed once the adapter resolves the send.
|
|
166
|
+
const outboxes = new Map(); // conn id → { data: { chats: { [chatKey]: records[] } }, timer }
|
|
167
|
+
const outboxPath = (id) => join(imDir, `${id}.outbox.json`);
|
|
168
|
+
const outboxOf = async (id) => {
|
|
169
|
+
let held = outboxes.get(id);
|
|
170
|
+
if (held !== undefined)
|
|
171
|
+
return held;
|
|
172
|
+
let data;
|
|
173
|
+
let unreadable;
|
|
174
|
+
try {
|
|
175
|
+
data = JSON.parse(await readFile(outboxPath(id), "utf8"));
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
// No file yet is the normal first start for a connection. Anything else means
|
|
179
|
+
// records exist but cannot be trusted: keep them for inspection and say so,
|
|
180
|
+
// instead of silently replacing them with an empty set.
|
|
181
|
+
if (error?.code !== "ENOENT")
|
|
182
|
+
unreadable = error;
|
|
183
|
+
}
|
|
184
|
+
if (unreadable !== undefined) {
|
|
185
|
+
const kept = `${outboxPath(id)}.corrupt-${Date.now()}`;
|
|
186
|
+
await rename(outboxPath(id), kept).catch(() => { });
|
|
187
|
+
rt.warn("ocean-crew: im outbox %s is unreadable (%s); kept it at %s and started empty", id, String(unreadable?.message ?? unreadable), kept);
|
|
188
|
+
}
|
|
189
|
+
held = {
|
|
190
|
+
data: {
|
|
191
|
+
chats: data?.chats !== null && typeof data?.chats === "object" && !Array.isArray(data.chats) ? data.chats : {},
|
|
192
|
+
},
|
|
193
|
+
timer: undefined,
|
|
194
|
+
};
|
|
195
|
+
outboxes.set(id, held);
|
|
196
|
+
return held;
|
|
197
|
+
};
|
|
198
|
+
// One write at a time per connection: two messages accepted together share the same
|
|
199
|
+
// temp path, and letting the writes interleave makes the loser fail for no reason.
|
|
200
|
+
const outboxWrites = new Map();
|
|
201
|
+
const writeOutbox = async (id) => {
|
|
202
|
+
const run = async () => {
|
|
203
|
+
const held = outboxes.get(id);
|
|
204
|
+
if (held === undefined)
|
|
205
|
+
return;
|
|
206
|
+
if (rt.readOnly() !== undefined) {
|
|
207
|
+
throw Object.assign(new Error(`this host cannot write the im outbox: ${rt.readOnly()}`), {
|
|
208
|
+
code: "bot/read-only",
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
try {
|
|
212
|
+
await mkdir(imDir, { recursive: true });
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
// Two connections writing at once can race the recursive mkdir on Linux;
|
|
216
|
+
// the directory existing is exactly the outcome this needs.
|
|
217
|
+
if (error?.code !== "EEXIST")
|
|
218
|
+
throw error;
|
|
219
|
+
}
|
|
220
|
+
const temp = join(imDir, `${id}.outbox.${process.pid}.tmp`);
|
|
221
|
+
try {
|
|
222
|
+
await writeFile(temp, JSON.stringify(held.data), { encoding: "utf8", mode: 0o600 });
|
|
223
|
+
await chmod(temp, 0o600);
|
|
224
|
+
await replaceFile(temp, outboxPath(id));
|
|
225
|
+
}
|
|
226
|
+
catch (error) {
|
|
227
|
+
await rm(temp, { force: true }).catch(() => { });
|
|
228
|
+
throw error;
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
const previous = outboxWrites.get(id) ?? Promise.resolve();
|
|
232
|
+
const next = previous.catch(() => { }).then(run);
|
|
233
|
+
outboxWrites.set(id, next);
|
|
234
|
+
try {
|
|
235
|
+
await next;
|
|
236
|
+
}
|
|
237
|
+
finally {
|
|
238
|
+
if (outboxWrites.get(id) === next)
|
|
239
|
+
outboxWrites.delete(id);
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
// One outgoing attachment on disk: the record in the outbox names this file, so a
|
|
243
|
+
// restart after the crash can still send exactly what the Bot handed over.
|
|
244
|
+
const mediaPath = (name) => {
|
|
245
|
+
const safe = name.replace(/[^A-Za-z0-9._ -]/g, "_").slice(-80) || "file";
|
|
246
|
+
return join(mediaDir, `${randomUUID()}-${safe}`);
|
|
247
|
+
};
|
|
248
|
+
const saveMedia = async (kind, name, data) => {
|
|
249
|
+
if (data.byteLength > MEDIA_LIMIT)
|
|
250
|
+
throw new Error(`the file is larger than ${MEDIA_LIMIT} bytes`);
|
|
251
|
+
await mkdir(mediaDir, { recursive: true });
|
|
252
|
+
const path = mediaPath(name);
|
|
253
|
+
await writeFile(path, data, { mode: 0o600 });
|
|
254
|
+
return { kind, name, path };
|
|
255
|
+
};
|
|
256
|
+
const dropMedia = (held) => held?.path === undefined ? Promise.resolve() : rm(held.path, { force: true }).catch(() => { });
|
|
257
|
+
// Records for one chat, in send order; a chat with none is absent.
|
|
258
|
+
const outboxRecords = async (id, chatKey) => {
|
|
259
|
+
const held = await outboxOf(id);
|
|
260
|
+
const list = held.data.chats[chatKey];
|
|
261
|
+
return Array.isArray(list) ? list : [];
|
|
262
|
+
};
|
|
263
|
+
const outboxAdd = async (id, chatKey, record) => {
|
|
264
|
+
const held = await outboxOf(id);
|
|
265
|
+
const list = Array.isArray(held.data.chats[chatKey]) ? held.data.chats[chatKey] : [];
|
|
266
|
+
list.push(record);
|
|
267
|
+
// Over the bound, a message that was never attempted goes first: an `unknown` one
|
|
268
|
+
// is evidence the user may need to see and a `sending` one is still in flight, so
|
|
269
|
+
// neither is evicted the way a stale queued text can be.
|
|
270
|
+
while (list.length > OUTBOX_LIMIT) {
|
|
271
|
+
const at = list.findIndex((entry) => entry.state === "queued" || entry.state === "failed");
|
|
272
|
+
if (at === -1)
|
|
273
|
+
break;
|
|
274
|
+
list.splice(at, 1);
|
|
275
|
+
}
|
|
276
|
+
held.data.chats[chatKey] = list;
|
|
277
|
+
// The record is durable before the caller may act on it.
|
|
278
|
+
await writeOutbox(id);
|
|
279
|
+
};
|
|
280
|
+
const outboxUpdate = async (id, chatKey, recordId, patch) => {
|
|
281
|
+
const held = await outboxOf(id);
|
|
282
|
+
const list = held.data.chats[chatKey];
|
|
283
|
+
if (!Array.isArray(list))
|
|
284
|
+
return;
|
|
285
|
+
const record = list.find((entry) => entry.id === recordId);
|
|
286
|
+
if (record === undefined)
|
|
287
|
+
return;
|
|
288
|
+
Object.assign(record, patch);
|
|
289
|
+
await writeOutbox(id);
|
|
290
|
+
};
|
|
291
|
+
const outboxRemove = async (id, chatKey, recordId) => {
|
|
292
|
+
const held = await outboxOf(id);
|
|
293
|
+
const list = held.data.chats[chatKey];
|
|
294
|
+
if (!Array.isArray(list))
|
|
295
|
+
return;
|
|
296
|
+
const at = list.findIndex((entry) => entry.id === recordId);
|
|
297
|
+
if (at === -1)
|
|
298
|
+
return;
|
|
299
|
+
list.splice(at, 1);
|
|
300
|
+
if (list.length === 0)
|
|
301
|
+
delete held.data.chats[chatKey];
|
|
302
|
+
await writeOutbox(id);
|
|
303
|
+
};
|
|
304
|
+
ctx.effect(() => () => {
|
|
305
|
+
for (const held of outboxes.values())
|
|
306
|
+
clearTimeout(held.timer);
|
|
307
|
+
outboxes.clear();
|
|
308
|
+
}, "ocean-crew: im outbox");
|
|
309
|
+
// ---------------------------------------------------------------- runtime file
|
|
310
|
+
const runtimes = new Map(); // id → { data: {runtime, cards, open}, timer }
|
|
311
|
+
const runtimeOf = async (id) => {
|
|
312
|
+
let held = runtimes.get(id);
|
|
313
|
+
if (held !== undefined)
|
|
314
|
+
return held;
|
|
315
|
+
let data;
|
|
316
|
+
try {
|
|
317
|
+
data = JSON.parse(await readFile(join(imDir, `${id}.json`), "utf8"));
|
|
318
|
+
}
|
|
319
|
+
catch {
|
|
320
|
+
data = undefined;
|
|
321
|
+
}
|
|
322
|
+
held = {
|
|
323
|
+
data: {
|
|
324
|
+
runtime: data?.runtime !== null && typeof data?.runtime === "object" ? data.runtime : {},
|
|
325
|
+
cards: data?.cards !== null && typeof data?.cards === "object" ? data.cards : {},
|
|
326
|
+
},
|
|
327
|
+
timer: undefined,
|
|
328
|
+
};
|
|
329
|
+
runtimes.set(id, held);
|
|
330
|
+
return held;
|
|
331
|
+
};
|
|
332
|
+
const scheduleWrite = (id) => {
|
|
333
|
+
const held = runtimes.get(id);
|
|
334
|
+
if (held === undefined || held.timer !== undefined)
|
|
335
|
+
return;
|
|
336
|
+
held.timer = setTimeout(() => {
|
|
337
|
+
held.timer = undefined;
|
|
338
|
+
void writeRuntime(id).catch((error) => rt.warn("ocean-crew: im runtime %s not saved: %s", id, error));
|
|
339
|
+
}, RUNTIME_SAVE_MS);
|
|
340
|
+
held.timer.unref?.();
|
|
341
|
+
};
|
|
342
|
+
const writeRuntime = async (id) => {
|
|
343
|
+
const held = runtimes.get(id);
|
|
344
|
+
if (held === undefined || rt.readOnly() !== undefined)
|
|
345
|
+
return;
|
|
346
|
+
await mkdir(imDir, { recursive: true });
|
|
347
|
+
const temp = join(imDir, `${id}.${process.pid}.tmp`);
|
|
348
|
+
try {
|
|
349
|
+
await writeFile(temp, JSON.stringify(held.data), { encoding: "utf8", mode: 0o600 });
|
|
350
|
+
await chmod(temp, 0o600);
|
|
351
|
+
await replaceFile(temp, join(imDir, `${id}.json`));
|
|
352
|
+
}
|
|
353
|
+
catch (error) {
|
|
354
|
+
await rm(temp, { force: true }).catch(() => { });
|
|
355
|
+
throw error;
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
const runtimeEnv = async (id) => {
|
|
359
|
+
const held = await runtimeOf(id);
|
|
360
|
+
return {
|
|
361
|
+
get: () => held.data.runtime,
|
|
362
|
+
set: (patch) => {
|
|
363
|
+
Object.assign(held.data.runtime, patch);
|
|
364
|
+
scheduleWrite(id);
|
|
365
|
+
},
|
|
366
|
+
};
|
|
367
|
+
};
|
|
368
|
+
// Sent cards: cardKey → [{ chatKey, messageId, answer? }]. Persisted so a restart
|
|
369
|
+
// does not send a card twice; an `answer` marks it settled from this side.
|
|
370
|
+
const cardsOf = async (id) => (await runtimeOf(id)).data;
|
|
371
|
+
const markCard = async (id, cardKey, chatKey, messageId, body) => {
|
|
372
|
+
const data = await cardsOf(id);
|
|
373
|
+
const entries = data.cards[cardKey] ?? [];
|
|
374
|
+
const held = entries.find((entry) => entry.chatKey === chatKey);
|
|
375
|
+
if (held !== undefined) {
|
|
376
|
+
held.messageId = messageId ?? held.messageId;
|
|
377
|
+
held.text = body ?? held.text;
|
|
378
|
+
}
|
|
379
|
+
else {
|
|
380
|
+
entries.push({ chatKey, messageId, text: body });
|
|
381
|
+
}
|
|
382
|
+
data.cards[cardKey] = entries;
|
|
383
|
+
scheduleWrite(id);
|
|
384
|
+
};
|
|
385
|
+
const settleCard = async (id, cardKey, answer) => {
|
|
386
|
+
const data = await cardsOf(id);
|
|
387
|
+
const entries = data.cards[cardKey];
|
|
388
|
+
if (entries === undefined)
|
|
389
|
+
return;
|
|
390
|
+
for (const entry of entries)
|
|
391
|
+
entry.answer ??= answer;
|
|
392
|
+
scheduleWrite(id);
|
|
393
|
+
};
|
|
394
|
+
// ------------------------------------------------------------- connections
|
|
395
|
+
// A binding change makes an older route unsafe: bump the generation so a recorded
|
|
396
|
+
// request no longer resolves to this connection.
|
|
397
|
+
const touchBinding = (conn) => {
|
|
398
|
+
conn.revision = Number(conn.revision ?? 0) + 1;
|
|
399
|
+
};
|
|
400
|
+
const connections = () => {
|
|
401
|
+
state.im ??= { connections: {} };
|
|
402
|
+
state.im.connections ??= {};
|
|
403
|
+
return state.im.connections;
|
|
404
|
+
};
|
|
405
|
+
const adaptersFor = () => Object.keys(adapters);
|
|
406
|
+
const hasSecrets = (conn) => Object.values(conn.secrets ?? {}).every((name) => rt.secretValue(name) !== undefined);
|
|
407
|
+
const fieldsOf = (conn) => {
|
|
408
|
+
const fields = { ...conn.settings };
|
|
409
|
+
for (const [key, name] of Object.entries(conn.secrets ?? {}))
|
|
410
|
+
fields[key] = rt.secretValue(name);
|
|
411
|
+
return fields;
|
|
412
|
+
};
|
|
413
|
+
const envFor = async (conn, runtime) => ({
|
|
414
|
+
fetch: globalThis.fetch,
|
|
415
|
+
WebSocket: globalThis.WebSocket,
|
|
416
|
+
config: rt.config.im?.[conn.platform],
|
|
417
|
+
runtime: runtime ?? (await runtimeEnv(conn.id)),
|
|
418
|
+
log: { warn: (template, ...args) => rt.warn(template, ...args) },
|
|
419
|
+
uploadFile: async (sessionId, file) => {
|
|
420
|
+
const uploads = ctx.get?.("fileUploads");
|
|
421
|
+
if (typeof uploads?.uploadStream !== "function")
|
|
422
|
+
throw new Error("no upload service");
|
|
423
|
+
const data = file.data?.[Symbol.asyncIterator] !== undefined
|
|
424
|
+
? file.data
|
|
425
|
+
: (async function* () {
|
|
426
|
+
yield file.data;
|
|
427
|
+
})();
|
|
428
|
+
const value = await uploads.uploadStream({ sessionId, data, name: file.name });
|
|
429
|
+
return value.receiptId;
|
|
430
|
+
},
|
|
431
|
+
});
|
|
432
|
+
// ------------------------------------------------------------------ send out
|
|
433
|
+
/** @type {Map<string, {handle:any, queues:Map<string, {jobs:any[], retry?:any, sending?:any}>, statuses:Map}>} */
|
|
434
|
+
const runners = new Map();
|
|
435
|
+
const statuses = new Map();
|
|
436
|
+
const referenceId = () => `MF-${randomBytes(4).toString("hex")}`;
|
|
437
|
+
const setStatus = (id, patch) => {
|
|
438
|
+
const next = { ...statuses.get(id), ...patch, at: Date.now() };
|
|
439
|
+
// Adapter errors can echo platform responses that quote the token; keep them out of the UI and logs.
|
|
440
|
+
if (typeof next.error === "string" && next.error !== "")
|
|
441
|
+
next.error = rt.redactSecrets(next.error);
|
|
442
|
+
statuses.set(id, next);
|
|
443
|
+
return next;
|
|
444
|
+
};
|
|
445
|
+
const origins = () => {
|
|
446
|
+
// `im` is optional in the saved state; a team made before IM existed gets one here.
|
|
447
|
+
state.im ??= { connections: {} };
|
|
448
|
+
const held = state.im;
|
|
449
|
+
held.connections ??= {};
|
|
450
|
+
if (held.origins === null || typeof held.origins !== "object" || Array.isArray(held.origins))
|
|
451
|
+
held.origins = {};
|
|
452
|
+
return held.origins;
|
|
453
|
+
};
|
|
454
|
+
const noteOrigin = (requestId, conn, chat, ownerKey, messageId, actor) => {
|
|
455
|
+
const all = origins();
|
|
456
|
+
// Immutable: a record answers one request, and a later request writes its own.
|
|
457
|
+
all[requestId] = {
|
|
458
|
+
connId: conn.id,
|
|
459
|
+
chatKey: chat.key,
|
|
460
|
+
ownerKey,
|
|
461
|
+
revision: Number(conn.revision ?? 0),
|
|
462
|
+
at: Date.now(),
|
|
463
|
+
...(typeof messageId === "string" && messageId !== "" ? { messageId } : {}),
|
|
464
|
+
...(typeof actor === "string" && actor !== "" ? { actor } : {}),
|
|
465
|
+
};
|
|
466
|
+
// The origin is part of the team state, so another window sees the same routing.
|
|
467
|
+
void rt.save().catch((error) => rt.warn("ocean-crew: im origin not saved: %s", error));
|
|
468
|
+
};
|
|
469
|
+
const originOf = (requestId) => {
|
|
470
|
+
if (requestId === undefined || requestId === "")
|
|
471
|
+
return undefined;
|
|
472
|
+
const held = origins()[requestId];
|
|
473
|
+
// A request older than a day is no longer something a reply belongs to.
|
|
474
|
+
if (held === undefined || Date.now() - held.at > 24 * 60 * 60_000)
|
|
475
|
+
return undefined;
|
|
476
|
+
return held;
|
|
477
|
+
};
|
|
478
|
+
// Which request a session's turn belongs to. A turn that started in the window is
|
|
479
|
+
// bound to "" so it cannot fall back to an earlier IM request.
|
|
480
|
+
const turnOrigins = new Map();
|
|
481
|
+
const sessionOrigins = new Map();
|
|
482
|
+
// DSH's user/message carries the message, not the turn it belongs to: the turn is on
|
|
483
|
+
// the turn/start event that opens it. The current turn is remembered from there, and a
|
|
484
|
+
// message that arrives before its turn/start is bound when the start lands.
|
|
485
|
+
const currentTurns = new Map();
|
|
486
|
+
const waitingTurns = new Map();
|
|
487
|
+
let sawSessionEvent = false;
|
|
488
|
+
// Latest request that addressed each Bot or group, for lines that carry no request.
|
|
489
|
+
const ownerOrigins = new Map();
|
|
490
|
+
const turnKey = (sessionId, turn) => `${sessionId}:${turn}`;
|
|
491
|
+
const bindTurn = (sessionId, turn, requestId) => {
|
|
492
|
+
if (typeof turn === "number" && Number.isInteger(turn))
|
|
493
|
+
turnOrigins.set(turnKey(sessionId, turn), requestId);
|
|
494
|
+
};
|
|
495
|
+
// The request an outbound event belongs to. A turn with no binding does not guess:
|
|
496
|
+
// after a restart an old turn is not something to send to the last chat that spoke.
|
|
497
|
+
// The turn an event belongs to, when the event names it or when the Session's current
|
|
498
|
+
// turn was told by turn/start.
|
|
499
|
+
const turnOf = (sessionId, event) => {
|
|
500
|
+
const named = event?.data?.turn;
|
|
501
|
+
if (typeof named === "number" && Number.isInteger(named))
|
|
502
|
+
return named;
|
|
503
|
+
return currentTurns.get(sessionId);
|
|
504
|
+
};
|
|
505
|
+
const requestFor = (sessionId, event) => {
|
|
506
|
+
const turn = turnOf(sessionId, event);
|
|
507
|
+
if (turn !== undefined) {
|
|
508
|
+
const bound = turnOrigins.get(turnKey(sessionId, turn));
|
|
509
|
+
return bound === undefined || bound === "" ? undefined : bound;
|
|
510
|
+
}
|
|
511
|
+
return sessionOrigins.get(sessionId);
|
|
512
|
+
};
|
|
513
|
+
// The last text a window turn produced, held until the turn ends so one answer goes
|
|
514
|
+
// out instead of every step. Only used when `imDeliverAnswers` is on.
|
|
515
|
+
const windowAnswers = new Map();
|
|
516
|
+
// A turn a scheduled reminder started: its answer is pushed to the chat that last
|
|
517
|
+
// talked to this Bot, so a reminder the user set up reaches them in IM.
|
|
518
|
+
const scheduledTurns = new Set();
|
|
519
|
+
const notifyAnswers = new Map();
|
|
520
|
+
const spokenAnswers = new Map();
|
|
521
|
+
const targetsOf = (conn) => {
|
|
522
|
+
const out = [];
|
|
523
|
+
for (const [chatKey, chat] of Object.entries((conn.chats ?? {}))) {
|
|
524
|
+
const target = chat.target ?? (chat.kind === "direct" ? { botId: conn.botId } : undefined);
|
|
525
|
+
out.push({ chatKey, chat, target });
|
|
526
|
+
}
|
|
527
|
+
return out;
|
|
528
|
+
};
|
|
529
|
+
// Chats of this connection that listen to a Bot's own chat or a group.
|
|
530
|
+
const listeners = (conn, match) => targetsOf(conn).filter(({ target }) => {
|
|
531
|
+
if (match.botId !== undefined)
|
|
532
|
+
return target?.botId === match.botId && rt.botOf(target.botId) !== undefined;
|
|
533
|
+
if (match.roomId !== undefined)
|
|
534
|
+
return target?.roomId === match.roomId && rt.roomOf(target.roomId) !== undefined;
|
|
535
|
+
return false;
|
|
536
|
+
});
|
|
537
|
+
// The chats one Bot's reply reaches. Default: the chat the request came from, on the
|
|
538
|
+
// connection it came from. `mirror: "all"` on that connection keeps the old behaviour
|
|
539
|
+
// of every chat that listens to the Bot. No request means the turn started in the
|
|
540
|
+
// window, and the window is not mirrored into IM.
|
|
541
|
+
const matchOf = (ownerKey) => rt.roomOf(ownerKey) !== undefined ? { roomId: ownerKey } : { botId: ownerKey };
|
|
542
|
+
const replyTargets = (requestId, ownerKey) => {
|
|
543
|
+
const record = originOf(requestId);
|
|
544
|
+
const keyOf = (owner) => (rt.roomOf(owner) !== undefined ? `room:${owner}` : `bot:${owner}`);
|
|
545
|
+
if (record === undefined || keyOf(record.ownerKey) !== ownerKey)
|
|
546
|
+
return [];
|
|
547
|
+
const conn = connections()[record.connId];
|
|
548
|
+
if (conn === undefined || !runners.has(conn.id))
|
|
549
|
+
return [];
|
|
550
|
+
// A binding change (new target, unpair, removal) invalidates the older route: a
|
|
551
|
+
// reply must not go to a chat that no longer listens to this Bot.
|
|
552
|
+
if (Number(conn.revision ?? 0) !== record.revision)
|
|
553
|
+
return [];
|
|
554
|
+
const chat = conn.chats?.[record.chatKey];
|
|
555
|
+
if (chat === undefined)
|
|
556
|
+
return [];
|
|
557
|
+
const target = chat.target ?? (chat.kind === "direct" ? { botId: conn.botId } : undefined);
|
|
558
|
+
if (target === undefined)
|
|
559
|
+
return [];
|
|
560
|
+
const resolved = target.botId !== undefined ? `bot:${target.botId}` : `room:${target.roomId}`;
|
|
561
|
+
if (resolved !== (rt.roomOf(record.ownerKey) !== undefined ? `room:${record.ownerKey}` : `bot:${record.ownerKey}`))
|
|
562
|
+
return [];
|
|
563
|
+
if (target.botId !== undefined && rt.botOf(target.botId) === undefined)
|
|
564
|
+
return [];
|
|
565
|
+
if (target.roomId !== undefined && rt.roomOf(target.roomId) === undefined)
|
|
566
|
+
return [];
|
|
567
|
+
if (conn.mirror === "all") {
|
|
568
|
+
return listeners(conn, matchOf(record.ownerKey)).map(({ chatKey, chat: held }) => ({
|
|
569
|
+
conn,
|
|
570
|
+
chatKey,
|
|
571
|
+
chat: held,
|
|
572
|
+
}));
|
|
573
|
+
}
|
|
574
|
+
return [{ conn, chatKey: record.chatKey, chat }];
|
|
575
|
+
};
|
|
576
|
+
// A job waits in the in-memory queue and, written first, in the outbox: a crash
|
|
577
|
+
// between the two leaves a record that the next start resends, never a silent loss.
|
|
578
|
+
// Accepting a message therefore means its queued record is already on disk; a message
|
|
579
|
+
// whose record cannot be written is not accepted, because nothing would bring it back.
|
|
580
|
+
const enqueue = async (conn, chatKey, job) => {
|
|
581
|
+
const runner = runners.get(conn.id);
|
|
582
|
+
if (runner === undefined)
|
|
583
|
+
return false;
|
|
584
|
+
// A host that does not own the team must not dispatch: the owner would send too.
|
|
585
|
+
if (rt.writerMode() === "readonly") {
|
|
586
|
+
rt.warn("ocean-crew: im send for %s refused: %s", conn.id, rt.readOnly());
|
|
587
|
+
return false;
|
|
588
|
+
}
|
|
589
|
+
const record = {
|
|
590
|
+
id: randomUUID(),
|
|
591
|
+
...(job.outboxId === undefined ? {} : { id: job.outboxId }),
|
|
592
|
+
chat: job.chat,
|
|
593
|
+
state: "queued",
|
|
594
|
+
attempts: 0,
|
|
595
|
+
body: job.text,
|
|
596
|
+
...(job.buttons === undefined ? {} : { buttons: job.buttons }),
|
|
597
|
+
...(job.media === undefined ? {} : { media: job.media }),
|
|
598
|
+
};
|
|
599
|
+
job.outboxId = record.id;
|
|
600
|
+
let queue = runner.queues.get(chatKey);
|
|
601
|
+
if (queue === undefined) {
|
|
602
|
+
queue = { jobs: [] };
|
|
603
|
+
runner.queues.set(chatKey, queue);
|
|
604
|
+
}
|
|
605
|
+
if (queue.jobs.length >= QUEUE_LIMIT) {
|
|
606
|
+
// Never drop the in-flight head: the successful send shifts its own job.
|
|
607
|
+
const at = queue.sending === queue.jobs[0] ? 1 : 0;
|
|
608
|
+
const [dropped] = queue.jobs.splice(at, 1);
|
|
609
|
+
if (dropped?.outboxId !== undefined)
|
|
610
|
+
await outboxRemove(conn.id, chatKey, dropped.outboxId).catch(() => { });
|
|
611
|
+
rt.warn("ocean-crew: im send queue for %s/%s is full; dropped the oldest message", conn.id, chatKey);
|
|
612
|
+
}
|
|
613
|
+
if (job.restored !== true) {
|
|
614
|
+
try {
|
|
615
|
+
await outboxAdd(conn.id, chatKey, record);
|
|
616
|
+
}
|
|
617
|
+
catch (error) {
|
|
618
|
+
rt.warn("ocean-crew: im message for %s not accepted: %s", conn.id, error);
|
|
619
|
+
setStatus(conn.id, {
|
|
620
|
+
state: "error",
|
|
621
|
+
error: `This message could not be queued for sending: ${rt.redactSecrets(String(error?.message ?? error)).slice(0, 200)}`,
|
|
622
|
+
});
|
|
623
|
+
return false;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
queue.jobs.push(job);
|
|
627
|
+
void drain(conn, chatKey);
|
|
628
|
+
return true;
|
|
629
|
+
};
|
|
630
|
+
// A platform send that never settles must not block this chat forever: the
|
|
631
|
+
// message is dropped as unknown after the timeout and the queue moves on.
|
|
632
|
+
const withSendTimeout = (sending) => {
|
|
633
|
+
if (!(sendTimeoutMs > 0))
|
|
634
|
+
return sending;
|
|
635
|
+
return new Promise((resolve, reject) => {
|
|
636
|
+
const timer = setTimeout(() => {
|
|
637
|
+
reject(Object.assign(new Error(`send timed out after ${sendTimeoutMs}ms`), { unknown: true }));
|
|
638
|
+
}, sendTimeoutMs);
|
|
639
|
+
timer.unref?.();
|
|
640
|
+
sending.then((value) => {
|
|
641
|
+
clearTimeout(timer);
|
|
642
|
+
resolve(value);
|
|
643
|
+
}, (error) => {
|
|
644
|
+
clearTimeout(timer);
|
|
645
|
+
reject(error);
|
|
646
|
+
});
|
|
647
|
+
});
|
|
648
|
+
};
|
|
649
|
+
const dropSend = (conn, how, error, notify = false) => {
|
|
650
|
+
const message = rt.redactSecrets(String(error?.message ?? error)).slice(0, 300);
|
|
651
|
+
const reference = referenceId();
|
|
652
|
+
if (notify)
|
|
653
|
+
rt.warn("ocean-crew: an IM notification for %s was not delivered; the platform may require the chat to message the Bot first", conn.id);
|
|
654
|
+
if (how === "permanent") {
|
|
655
|
+
// The connection may be fine; mark the message failure so the supervisor
|
|
656
|
+
// does not restart the link, and clear it on the next successful send.
|
|
657
|
+
setStatus(conn.id, { state: "error", error: message, referenceId: reference, messageError: true });
|
|
658
|
+
rt.warn("ocean-crew: im send for %s failed (%s): %s", conn.id, reference, message);
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
// Unknown: one message is gone, but the connection itself must not look broken.
|
|
662
|
+
setStatus(conn.id, { referenceId: reference, error: message });
|
|
663
|
+
rt.warn("ocean-crew: im send for %s dropped (%s): %s", conn.id, reference, message);
|
|
664
|
+
};
|
|
665
|
+
// One drain loop per chat. Enqueue cannot start a second one: with a durable write in
|
|
666
|
+
// front of the queue, two messages can be accepted while the first is still being
|
|
667
|
+
// persisted, and a "queue length is one" check would miss that case.
|
|
668
|
+
const drain = async (conn, chatKey) => {
|
|
669
|
+
const queue = runners.get(conn.id)?.queues.get(chatKey);
|
|
670
|
+
if (queue === undefined || queue.active === true)
|
|
671
|
+
return;
|
|
672
|
+
queue.active = true;
|
|
673
|
+
try {
|
|
674
|
+
await drainLoop(conn, chatKey);
|
|
675
|
+
}
|
|
676
|
+
finally {
|
|
677
|
+
queue.active = false;
|
|
678
|
+
}
|
|
679
|
+
// A message accepted while the loop was finishing still has to be sent, but a
|
|
680
|
+
// pending retry or a connection without a handle has its own wake-up.
|
|
681
|
+
if (queue.jobs.length > 0 && queue.retry === undefined && runners.get(conn.id)?.handle !== undefined) {
|
|
682
|
+
void drain(conn, chatKey);
|
|
683
|
+
}
|
|
684
|
+
};
|
|
685
|
+
const drainLoop = async (conn, chatKey) => {
|
|
686
|
+
const runner = runners.get(conn.id);
|
|
687
|
+
const queue = runner?.queues.get(chatKey);
|
|
688
|
+
// A reserved slot has no handle until connect() lands; start() re-kicks
|
|
689
|
+
// anything queued in the meantime.
|
|
690
|
+
if (runner?.handle === undefined || queue === undefined)
|
|
691
|
+
return;
|
|
692
|
+
while (queue.jobs.length > 0) {
|
|
693
|
+
const job = queue.jobs[0];
|
|
694
|
+
queue.sending = job;
|
|
695
|
+
if (job.outboxId !== undefined) {
|
|
696
|
+
// Written before the attempt, and awaited: a crash after this point leaves a
|
|
697
|
+
// record the next start reports as unknown instead of resending blindly.
|
|
698
|
+
try {
|
|
699
|
+
await outboxUpdate(conn.id, chatKey, job.outboxId, { state: "sending" });
|
|
700
|
+
}
|
|
701
|
+
catch (error) {
|
|
702
|
+
// The attempt cannot be recorded, so it must not start: sending anyway is
|
|
703
|
+
// how a message the platform accepted goes missing with no trace.
|
|
704
|
+
rt.warn("ocean-crew: im send for %s not attempted: %s", conn.id, error);
|
|
705
|
+
queue.retry = setTimeout(() => {
|
|
706
|
+
queue.retry = undefined;
|
|
707
|
+
void drain(conn, chatKey);
|
|
708
|
+
}, RETRY_MS);
|
|
709
|
+
queue.retry.unref?.();
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
try {
|
|
714
|
+
let media;
|
|
715
|
+
if (Array.isArray(job.media) && job.media.length > 0) {
|
|
716
|
+
media = [];
|
|
717
|
+
for (const held of job.media) {
|
|
718
|
+
try {
|
|
719
|
+
media.push({
|
|
720
|
+
kind: held.kind,
|
|
721
|
+
name: held.name,
|
|
722
|
+
...(held.mime === undefined ? {} : { mime: held.mime }),
|
|
723
|
+
...(held.voice === true ? { voice: true } : {}),
|
|
724
|
+
data: await readFile(held.path),
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
catch (error) {
|
|
728
|
+
// The copy is missing (another host cleaned it): the file is lost, and
|
|
729
|
+
// the text still goes rather than the whole job failing.
|
|
730
|
+
rt.warn("ocean-crew: im media for %s is gone: %s", conn.id, error?.message ?? error);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
// The adapter addresses the chat by `chat.key`; a job restored from the outbox
|
|
735
|
+
// or built from a stored chat entry may only know the key the queue uses.
|
|
736
|
+
const chat = job.chat?.key === undefined ? { ...job.chat, key: chatKey } : job.chat;
|
|
737
|
+
const sent = await withSendTimeout(runner.handle.send(chat, media === undefined ? job : { ...job, media }));
|
|
738
|
+
for (const held of job.media ?? [])
|
|
739
|
+
await dropMedia(held);
|
|
740
|
+
job.after?.(sent);
|
|
741
|
+
queue.jobs.shift();
|
|
742
|
+
if (job.outboxId !== undefined) {
|
|
743
|
+
void outboxRemove(conn.id, chatKey, job.outboxId).catch((error) => rt.warn("ocean-crew: im outbox for %s not cleaned up: %s", conn.id, error));
|
|
744
|
+
}
|
|
745
|
+
if (statuses.get(conn.id)?.messageError === true) {
|
|
746
|
+
setStatus(conn.id, { state: "ready", error: undefined, referenceId: undefined, messageError: false });
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
catch (error) {
|
|
750
|
+
const how = failClass(error);
|
|
751
|
+
if (how === "retry") {
|
|
752
|
+
// The platform refused without accepting it: the record stays queued.
|
|
753
|
+
if (job.outboxId !== undefined)
|
|
754
|
+
await outboxUpdate(conn.id, chatKey, job.outboxId, { state: "queued" }).catch(() => { });
|
|
755
|
+
const wait = Number(error?.retryAfter) > 0 ? error.retryAfter * 1000 : RETRY_MS;
|
|
756
|
+
queue.retry = setTimeout(() => {
|
|
757
|
+
void drain(conn, chatKey);
|
|
758
|
+
}, wait);
|
|
759
|
+
queue.retry.unref?.();
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
queue.jobs.shift();
|
|
763
|
+
for (const held of job.media ?? [])
|
|
764
|
+
await dropMedia(held);
|
|
765
|
+
// Nothing is resent automatically here: a permanent refusal and an unknown
|
|
766
|
+
// outcome both leave a record the user can see instead.
|
|
767
|
+
if (job.outboxId !== undefined)
|
|
768
|
+
await outboxUpdate(conn.id, chatKey, job.outboxId, {
|
|
769
|
+
state: how === "permanent" ? "failed" : "unknown",
|
|
770
|
+
error: rt.redactSecrets(String(error?.message ?? error)).slice(0, 300),
|
|
771
|
+
}).catch(() => { });
|
|
772
|
+
dropSend(conn, how, error, job.notify === true);
|
|
773
|
+
}
|
|
774
|
+
finally {
|
|
775
|
+
queue.sending = undefined;
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
};
|
|
779
|
+
const sendMedia = async (conn, chatKey, chat, items, note) => {
|
|
780
|
+
const saved = [];
|
|
781
|
+
for (const item of items)
|
|
782
|
+
saved.push({
|
|
783
|
+
...(await saveMedia(item.kind, item.name, item.data)),
|
|
784
|
+
...(item.mime === undefined ? {} : { mime: item.mime }),
|
|
785
|
+
...(item.voice === true ? { voice: true } : {}),
|
|
786
|
+
});
|
|
787
|
+
// The record is written before the queue is touched, like a text: a body that
|
|
788
|
+
// cannot be queued is refused instead of silently lost.
|
|
789
|
+
const accepted = await enqueue(conn, chatKey, { chat, text: note ?? "", media: saved });
|
|
790
|
+
if (!accepted)
|
|
791
|
+
for (const held of saved)
|
|
792
|
+
await dropMedia(held);
|
|
793
|
+
return accepted;
|
|
794
|
+
};
|
|
795
|
+
const sendText = async (conn, chat, body, buttons, after) => await enqueue(conn, chat.key, { chat, text: body, buttons, after });
|
|
796
|
+
const sendTo = async (conn, chatKey, chat, body, buttons, after, replyTo, look) => await enqueue(conn, chatKey, {
|
|
797
|
+
chat,
|
|
798
|
+
text: body,
|
|
799
|
+
buttons,
|
|
800
|
+
after,
|
|
801
|
+
...(replyTo ? { replyTo } : {}),
|
|
802
|
+
...(look?.card === true ? { card: true } : {}),
|
|
803
|
+
...(look?.title === undefined ? {} : { title: look.title }),
|
|
804
|
+
...(look?.form === undefined ? {} : { form: look.form }),
|
|
805
|
+
...(look?.notify === true ? { notify: true } : {}),
|
|
806
|
+
});
|
|
807
|
+
// Status reactions mark the message that asked for the work while its turn runs
|
|
808
|
+
// and settle to the outcome when the turn ends (dsh-im's status-reaction
|
|
809
|
+
// lifecycle; see NOTICE). Best effort: a platform or app without reaction
|
|
810
|
+
// support simply gets no marks, and a failed reaction never holds up a reply.
|
|
811
|
+
const pendingReactions = new Map(); // `${conn.id}:${chatKey}` → { reaction, sessionId, requestId, started, timer }
|
|
812
|
+
const reactionsOn = rt.config?.imReactions !== false;
|
|
813
|
+
const finishReaction = (key, outcome) => {
|
|
814
|
+
const held = pendingReactions.get(key);
|
|
815
|
+
if (held === undefined)
|
|
816
|
+
return;
|
|
817
|
+
pendingReactions.delete(key);
|
|
818
|
+
clearTimeout(held.timer);
|
|
819
|
+
if (outcome === "success")
|
|
820
|
+
void held.reaction.success();
|
|
821
|
+
else if (outcome === "error")
|
|
822
|
+
void held.reaction.error();
|
|
823
|
+
else
|
|
824
|
+
void held.reaction.clear();
|
|
825
|
+
};
|
|
826
|
+
const beginReaction = (conn, msg, sessionId, requestId) => {
|
|
827
|
+
if (!reactionsOn || typeof msg.messageId !== "string" || msg.messageId === "")
|
|
828
|
+
return;
|
|
829
|
+
const handle = runners.get(conn.id)?.handle;
|
|
830
|
+
if (typeof handle?.addReaction !== "function" || typeof handle?.removeReaction !== "function")
|
|
831
|
+
return;
|
|
832
|
+
const key = `${conn.id}:${msg.chat.key}`;
|
|
833
|
+
// A newer message in the same chat supersedes the mark of an older one.
|
|
834
|
+
finishReaction(key, "clear");
|
|
835
|
+
const reaction = startStatusReaction({
|
|
836
|
+
add: (emoji) => handle.addReaction(msg.chat, msg.messageId, emoji),
|
|
837
|
+
remove: (reactionId) => handle.removeReaction(msg.chat, msg.messageId, reactionId),
|
|
838
|
+
warn: (error) => rt.warn("ocean-crew im: status reaction failed: %s", error?.message ?? error),
|
|
839
|
+
});
|
|
840
|
+
if (reaction === undefined)
|
|
841
|
+
return;
|
|
842
|
+
const timer = setTimeout(() => finishReaction(key, "clear"), REACTION_MAX_MS);
|
|
843
|
+
timer.unref?.();
|
|
844
|
+
pendingReactions.set(key, { reaction, sessionId, requestId, started: false, timer });
|
|
845
|
+
};
|
|
846
|
+
// ----------------------------------------------------------------- inbound
|
|
847
|
+
const paired = (conn, senderId) => (conn.paired ?? []).some((entry) => entry.id === senderId);
|
|
848
|
+
const requested = (conn, msg) => {
|
|
849
|
+
if ((conn.requests ?? []).some((entry) => entry.id === msg.sender.id))
|
|
850
|
+
return false;
|
|
851
|
+
conn.requests = [
|
|
852
|
+
...(conn.requests ?? []),
|
|
853
|
+
{ id: msg.sender.id, name: msg.sender.name, chatKey: msg.chat.key, chatKind: msg.chat.kind, at: Date.now() },
|
|
854
|
+
];
|
|
855
|
+
return true;
|
|
856
|
+
};
|
|
857
|
+
const targetName = (_conn, target) => {
|
|
858
|
+
if (target?.botId !== undefined)
|
|
859
|
+
return rt.botOf(target.botId)?.name;
|
|
860
|
+
if (target?.roomId !== undefined)
|
|
861
|
+
return rt.roomOf(target.roomId)?.name;
|
|
862
|
+
return undefined;
|
|
863
|
+
};
|
|
864
|
+
const resolveTarget = (conn, chat) => {
|
|
865
|
+
const target = chat.target ?? (chat.kind === "direct" ? { botId: conn.botId } : undefined);
|
|
866
|
+
if (target?.botId !== undefined && rt.botOf(target.botId) !== undefined)
|
|
867
|
+
return target;
|
|
868
|
+
if (target?.roomId !== undefined && rt.roomOf(target.roomId) !== undefined)
|
|
869
|
+
return target;
|
|
870
|
+
return undefined;
|
|
871
|
+
};
|
|
872
|
+
// One card this chat was sent and has not answered yet. A button names its own
|
|
873
|
+
// card, so it must never fall through to a newer card of the same kind.
|
|
874
|
+
const openCard = (conn, chatKey, cardKey) => {
|
|
875
|
+
const entries = runtimes.get(conn.id)?.data?.cards[cardKey];
|
|
876
|
+
const entry = entries?.find((item) => item.chatKey === chatKey && item.answer === undefined);
|
|
877
|
+
return entry === undefined ? undefined : { cardKey, entry };
|
|
878
|
+
};
|
|
879
|
+
const questionById = (id) => {
|
|
880
|
+
for (const [sessionId, question] of Object.entries((state.questions ?? {}))) {
|
|
881
|
+
if (question.id === id)
|
|
882
|
+
return { sessionId, question };
|
|
883
|
+
}
|
|
884
|
+
return undefined;
|
|
885
|
+
};
|
|
886
|
+
const answerQuestionCard = async (conn, chat, cardKey, labels) => {
|
|
887
|
+
const held = openCard(conn, chat.key, cardKey);
|
|
888
|
+
if (held === undefined)
|
|
889
|
+
return false;
|
|
890
|
+
const found = questionById(held.cardKey.slice(2));
|
|
891
|
+
if (found === undefined) {
|
|
892
|
+
await sendCardReply(conn, chat, text("stale"));
|
|
893
|
+
return true;
|
|
894
|
+
}
|
|
895
|
+
const valid = labels.filter((label) => (found.question.options ?? []).some((option) => option.label === label));
|
|
896
|
+
if (valid.length === 0)
|
|
897
|
+
return false;
|
|
898
|
+
try {
|
|
899
|
+
await rt.answerQuestion(found.sessionId, found.question.id, { selected: valid });
|
|
900
|
+
await settleCard(conn.id, held.cardKey, valid.join(", "));
|
|
901
|
+
await settledEdits(conn);
|
|
902
|
+
}
|
|
903
|
+
catch (error) {
|
|
904
|
+
if (error?.code === "bot/stale") {
|
|
905
|
+
await settleCard(conn.id, held.cardKey, text("answered"));
|
|
906
|
+
await sendCardReply(conn, chat, text("stale"));
|
|
907
|
+
await settledEdits(conn);
|
|
908
|
+
return true;
|
|
909
|
+
}
|
|
910
|
+
throw error;
|
|
911
|
+
}
|
|
912
|
+
return true;
|
|
913
|
+
};
|
|
914
|
+
const viewValues = (node, choice, form) => {
|
|
915
|
+
if (node === undefined)
|
|
916
|
+
return undefined;
|
|
917
|
+
if (choice === "cancel")
|
|
918
|
+
return node.type === "form" ? { canceled: true } : undefined;
|
|
919
|
+
if (form !== undefined && typeof form === "object") {
|
|
920
|
+
if (node.type === "options") {
|
|
921
|
+
const key = Object.keys(form).find((name) => name.startsWith("sel:"));
|
|
922
|
+
const raw = key === undefined ? undefined : form[key];
|
|
923
|
+
const picked = (Array.isArray(raw) ? raw : raw === undefined ? [] : [raw]).filter((label) => typeof label === "string" && label !== "");
|
|
924
|
+
return picked.length === 0 ? undefined : { selected: picked };
|
|
925
|
+
}
|
|
926
|
+
if (node.type === "form") {
|
|
927
|
+
const fields = {};
|
|
928
|
+
for (const [name, raw] of Object.entries(form)) {
|
|
929
|
+
const match = /^f:([^:]+):(.+)$/.exec(name);
|
|
930
|
+
if (match === null || match[1] !== node.id)
|
|
931
|
+
continue;
|
|
932
|
+
fields[match[2]] = String(raw ?? "");
|
|
933
|
+
}
|
|
934
|
+
return Object.keys(fields).length === 0 ? undefined : { fields };
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
if (node.type === "confirm" && (choice === "yes" || choice === "no"))
|
|
938
|
+
return { confirmed: choice === "yes" };
|
|
939
|
+
if (node.type === "options" && /^o\d+$/.test(String(choice))) {
|
|
940
|
+
const label = node.options?.[Number(String(choice).slice(1))]?.label;
|
|
941
|
+
return typeof label === "string" ? { selected: [label] } : undefined;
|
|
942
|
+
}
|
|
943
|
+
return undefined;
|
|
944
|
+
};
|
|
945
|
+
const answerViewCard = async (conn, chat, cardKey, nodeId, choice, form) => {
|
|
946
|
+
const held = openCard(conn, chat.key, cardKey);
|
|
947
|
+
if (held === undefined)
|
|
948
|
+
return false;
|
|
949
|
+
const viewId = held.cardKey.slice(2);
|
|
950
|
+
const found = Object.entries((state.views ?? {})).find(([, pending]) => pending.id === viewId);
|
|
951
|
+
if (found === undefined) {
|
|
952
|
+
await sendCardReply(conn, chat, text("stale"));
|
|
953
|
+
return true;
|
|
954
|
+
}
|
|
955
|
+
const [sessionId, pending] = found;
|
|
956
|
+
const nodes = [];
|
|
957
|
+
const walk = (value) => {
|
|
958
|
+
if (value === null || typeof value !== "object")
|
|
959
|
+
return;
|
|
960
|
+
if (Array.isArray(value)) {
|
|
961
|
+
for (const child of value)
|
|
962
|
+
walk(child);
|
|
963
|
+
return;
|
|
964
|
+
}
|
|
965
|
+
if (["options", "confirm", "form"].includes(String(value.type)))
|
|
966
|
+
nodes.push(value);
|
|
967
|
+
for (const child of Object.values(value))
|
|
968
|
+
walk(child);
|
|
969
|
+
};
|
|
970
|
+
walk(pending.view);
|
|
971
|
+
const node = nodes.find((entry) => entry.id === nodeId);
|
|
972
|
+
const values = viewValues(node, choice, form);
|
|
973
|
+
if (values === undefined)
|
|
974
|
+
return false;
|
|
975
|
+
try {
|
|
976
|
+
await rt.answerView(sessionId, viewId, nodeId, values);
|
|
977
|
+
await settleCard(conn.id, held.cardKey, text("answered"));
|
|
978
|
+
await settledEdits(conn);
|
|
979
|
+
}
|
|
980
|
+
catch (error) {
|
|
981
|
+
if (error?.code === "bot/stale") {
|
|
982
|
+
await settleCard(conn.id, held.cardKey, text("answered"));
|
|
983
|
+
await sendCardReply(conn, chat, text("stale"));
|
|
984
|
+
await settledEdits(conn);
|
|
985
|
+
return true;
|
|
986
|
+
}
|
|
987
|
+
throw error;
|
|
988
|
+
}
|
|
989
|
+
return true;
|
|
990
|
+
};
|
|
991
|
+
const answerApprovalCard = async (conn, chat, cardKey, choice) => {
|
|
992
|
+
const held = openCard(conn, chat.key, cardKey);
|
|
993
|
+
if (held === undefined)
|
|
994
|
+
return false;
|
|
995
|
+
try {
|
|
996
|
+
rt.answerApproval(held.cardKey.slice(2), choice);
|
|
997
|
+
await settleCard(conn.id, held.cardKey, choice === "allow" ? text("allow") : text("reject"));
|
|
998
|
+
await settledEdits(conn);
|
|
999
|
+
}
|
|
1000
|
+
catch (error) {
|
|
1001
|
+
if (error?.code === "bot/stale") {
|
|
1002
|
+
await sendCardReply(conn, chat, text("stale"));
|
|
1003
|
+
return true;
|
|
1004
|
+
}
|
|
1005
|
+
throw error;
|
|
1006
|
+
}
|
|
1007
|
+
return true;
|
|
1008
|
+
};
|
|
1009
|
+
const sendCardReply = async (conn, chat, body) => sendText(conn, { key: chat.key, kind: chat.kind, title: chat.title }, body);
|
|
1010
|
+
// The chat's newest still-open card, questions and approvals together: a bare
|
|
1011
|
+
// number answers whatever arrived last, not always a question.
|
|
1012
|
+
const newestOpenCard = (conn, chatKey) => {
|
|
1013
|
+
const data = runtimes.get(conn.id)?.data;
|
|
1014
|
+
if (data === undefined)
|
|
1015
|
+
return undefined;
|
|
1016
|
+
for (const [cardKey, entries] of Object.entries(data.cards).reverse()) {
|
|
1017
|
+
if (!cardKey.startsWith("q:") && !cardKey.startsWith("a:"))
|
|
1018
|
+
continue;
|
|
1019
|
+
const entry = entries.find((item) => item.chatKey === chatKey && item.answer === undefined);
|
|
1020
|
+
if (entry !== undefined)
|
|
1021
|
+
return { cardKey, entry };
|
|
1022
|
+
}
|
|
1023
|
+
return undefined;
|
|
1024
|
+
};
|
|
1025
|
+
const onMessage = (conn) => async (msg) => {
|
|
1026
|
+
if (!paired(conn, msg.sender.id)) {
|
|
1027
|
+
if (msg.chat.kind === "group" && !msg.mentioned)
|
|
1028
|
+
return;
|
|
1029
|
+
if (!requested(conn, msg))
|
|
1030
|
+
return;
|
|
1031
|
+
await rt.save();
|
|
1032
|
+
await sendText(conn, msg.chat, text("requested"));
|
|
1033
|
+
return;
|
|
1034
|
+
}
|
|
1035
|
+
conn.chats ??= {};
|
|
1036
|
+
if (msg.chat.kind === "group" && !msg.mentioned)
|
|
1037
|
+
return;
|
|
1038
|
+
if (conn.chats[msg.chat.key] === undefined) {
|
|
1039
|
+
conn.chats[msg.chat.key] = { kind: msg.chat.kind, title: msg.chat.title, at: Date.now() };
|
|
1040
|
+
await rt.save();
|
|
1041
|
+
}
|
|
1042
|
+
const body = String(msg.text ?? "").trim();
|
|
1043
|
+
const chat = conn.chats[msg.chat.key];
|
|
1044
|
+
const target = resolveTarget(conn, chat);
|
|
1045
|
+
if (/^\/start(?:@\S+)?\s*$/.test(body)) {
|
|
1046
|
+
const name = target === undefined ? undefined : targetName(conn, target);
|
|
1047
|
+
await sendText(conn, msg.chat, name === undefined
|
|
1048
|
+
? text(msg.chat.kind === "group" ? "unboundGroup" : "unbound")
|
|
1049
|
+
: text("greeting", { name }));
|
|
1050
|
+
return;
|
|
1051
|
+
}
|
|
1052
|
+
if (/^\/stop(?:@\S+)?\s*$/.test(body)) {
|
|
1053
|
+
if (target === undefined) {
|
|
1054
|
+
await sendText(conn, msg.chat, text(msg.chat.kind === "group" ? "unboundGroup" : "unbound"));
|
|
1055
|
+
return;
|
|
1056
|
+
}
|
|
1057
|
+
const stopped = target.botId !== undefined ? await rt.stopChat(target.botId) : await rt.stopRoomWork(target.roomId);
|
|
1058
|
+
await sendText(conn, msg.chat, text(stopped ? "stopped" : "idle"));
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
if (NUMBERS.test(body)) {
|
|
1062
|
+
const picked = body.trim().split(/\s+/).map(Number);
|
|
1063
|
+
const held = newestOpenCard(conn, msg.chat.key);
|
|
1064
|
+
// Anything that does not clearly answer the newest open card — a stale
|
|
1065
|
+
// source, an out-of-range pick, several picks on a single choice — is a
|
|
1066
|
+
// normal message for the Bot, never swallowed and never 'stale'.
|
|
1067
|
+
if (held?.cardKey.startsWith("q:")) {
|
|
1068
|
+
const found = questionById(held.cardKey.slice(2));
|
|
1069
|
+
if (found !== undefined) {
|
|
1070
|
+
const options = found.question.options ?? [];
|
|
1071
|
+
const inRange = picked.length > 0 &&
|
|
1072
|
+
(found.question.multiSelect === true || picked.length === 1) &&
|
|
1073
|
+
picked.every((index) => options[index - 1] !== undefined);
|
|
1074
|
+
if (inRange &&
|
|
1075
|
+
(await answerQuestionCard(conn, msg.chat, held.cardKey, picked.map((index) => options[index - 1].label))))
|
|
1076
|
+
return;
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
else if (held?.cardKey.startsWith("a:") &&
|
|
1080
|
+
picked.length === 1 &&
|
|
1081
|
+
(picked[0] === 1 || picked[0] === 2) &&
|
|
1082
|
+
rt.approvalsView().some((entry) => `a:${entry.id}` === held.cardKey)) {
|
|
1083
|
+
if (await answerApprovalCard(conn, msg.chat, held.cardKey, picked[0] === 1 ? "allow" : "reject"))
|
|
1084
|
+
return;
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
if (target === undefined) {
|
|
1088
|
+
await sendText(conn, msg.chat, text(msg.chat.kind === "group" ? "unboundGroup" : "unbound"));
|
|
1089
|
+
return;
|
|
1090
|
+
}
|
|
1091
|
+
// A slash command is answered here, never queued into the Bot's Session: it is a
|
|
1092
|
+
// request about the chat, not work for the model.
|
|
1093
|
+
if (await runCommand(conn, msg, target))
|
|
1094
|
+
return;
|
|
1095
|
+
const sessionId = target.botId ?? target.roomId;
|
|
1096
|
+
const env = await envFor(conn);
|
|
1097
|
+
const upload = async (file) => {
|
|
1098
|
+
try {
|
|
1099
|
+
return await env.uploadFile(rt.botOf(sessionId) ? rt.chatOf(sessionId) : sessionId, file);
|
|
1100
|
+
}
|
|
1101
|
+
catch {
|
|
1102
|
+
await sendText(conn, msg.chat, text("noFile"));
|
|
1103
|
+
return undefined;
|
|
1104
|
+
}
|
|
1105
|
+
};
|
|
1106
|
+
const content = [];
|
|
1107
|
+
const labels = [];
|
|
1108
|
+
if (body !== "")
|
|
1109
|
+
labels.push(body);
|
|
1110
|
+
// An image only reaches the model as an image when its bytes are a type the host
|
|
1111
|
+
// accepts; anything else is a file, with a label saying what it is, so the model
|
|
1112
|
+
// still knows something arrived and can open it with its tools.
|
|
1113
|
+
const inline = [];
|
|
1114
|
+
const asFiles = [];
|
|
1115
|
+
const images = Array.isArray(msg.images) ? msg.images : [];
|
|
1116
|
+
for (const [index, image] of images.entries()) {
|
|
1117
|
+
const bytes = Buffer.from(String(image.data ?? ""), "base64");
|
|
1118
|
+
const mediaType = String(image.mediaType ?? "");
|
|
1119
|
+
if (!isSupportedImageType(mediaType) || bytes.byteLength === 0) {
|
|
1120
|
+
asFiles.push({
|
|
1121
|
+
name: `image-${index + 1}.${mediaType.split("/")[1]?.replace("jpeg", "jpg") ?? "bin"}`,
|
|
1122
|
+
data: bytes,
|
|
1123
|
+
});
|
|
1124
|
+
labels.push(`[Image ${index + 1} arrived as a file: ${mediaType || "unknown type"}]`);
|
|
1125
|
+
continue;
|
|
1126
|
+
}
|
|
1127
|
+
inline.push({
|
|
1128
|
+
type: "image",
|
|
1129
|
+
mediaType,
|
|
1130
|
+
data: image.data,
|
|
1131
|
+
...(image.name === undefined ? {} : { name: image.name }),
|
|
1132
|
+
});
|
|
1133
|
+
}
|
|
1134
|
+
for (const label of labels)
|
|
1135
|
+
content.push({ type: "text", text: label });
|
|
1136
|
+
content.push(...inline);
|
|
1137
|
+
for (const file of [...(Array.isArray(msg.files) ? msg.files : []), ...asFiles]) {
|
|
1138
|
+
const receiptId = await upload(file);
|
|
1139
|
+
if (receiptId !== undefined)
|
|
1140
|
+
content.push({ type: "file", receiptId });
|
|
1141
|
+
}
|
|
1142
|
+
if (content.length === 0)
|
|
1143
|
+
return;
|
|
1144
|
+
const requestId = `im:${conn.platform}:${randomUUID()}`;
|
|
1145
|
+
noteOrigin(requestId, conn, msg.chat, sessionId, msg.messageId, msg.sender?.id);
|
|
1146
|
+
ownerOrigins.set(sessionId, requestId);
|
|
1147
|
+
sessionOrigins.set(sessionId, requestId);
|
|
1148
|
+
try {
|
|
1149
|
+
await rt.sendUser({ sessionId, content, requestId });
|
|
1150
|
+
}
|
|
1151
|
+
catch (error) {
|
|
1152
|
+
if (inline.length === 0 || !isImageRefusal(error))
|
|
1153
|
+
throw error;
|
|
1154
|
+
// The host refuses the images (a model without vision, a size limit): the turn
|
|
1155
|
+
// still starts without them, and they are handed over as files to read instead.
|
|
1156
|
+
rt.warn("ocean-crew: im image not accepted by the host (%s); passing it as a file", error?.message ?? error);
|
|
1157
|
+
const fallback = content.filter((part) => part.type !== "image");
|
|
1158
|
+
const noted = [];
|
|
1159
|
+
for (const image of inline) {
|
|
1160
|
+
const receiptId = await upload({
|
|
1161
|
+
name: `image-${noted.length + 1}.${String(image.mediaType).split("/")[1]?.replace("jpeg", "jpg") ?? "png"}`,
|
|
1162
|
+
data: Buffer.from(String(image.data ?? ""), "base64"),
|
|
1163
|
+
});
|
|
1164
|
+
if (receiptId !== undefined) {
|
|
1165
|
+
fallback.push({ type: "file", receiptId });
|
|
1166
|
+
noted.push(receiptId);
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
fallback.push({
|
|
1170
|
+
type: "text",
|
|
1171
|
+
text: text("imageAsFile", { count: noted.length }),
|
|
1172
|
+
});
|
|
1173
|
+
await rt.sendUser({ sessionId, content: fallback, requestId });
|
|
1174
|
+
}
|
|
1175
|
+
// The chat sees the Bot working before the model's first token, not on a later tick.
|
|
1176
|
+
kickTyping(conn, msg.chat);
|
|
1177
|
+
// A room message is answered by member Bot turns under their own sessions, so
|
|
1178
|
+
// no single session end can settle its mark; only direct chats are marked.
|
|
1179
|
+
if (target.botId !== undefined)
|
|
1180
|
+
beginReaction(conn, msg, sessionId, requestId);
|
|
1181
|
+
};
|
|
1182
|
+
const commandWord = (msg) => {
|
|
1183
|
+
if ((Array.isArray(msg.images) && msg.images.length > 0) || (Array.isArray(msg.files) && msg.files.length > 0))
|
|
1184
|
+
return undefined;
|
|
1185
|
+
const text = String(msg.text ?? "").trim();
|
|
1186
|
+
if (!text.startsWith("/"))
|
|
1187
|
+
return undefined;
|
|
1188
|
+
const word = (text.split(/\s+/)[0] ?? "").slice(1).toLowerCase();
|
|
1189
|
+
return word === "" ? undefined : word;
|
|
1190
|
+
};
|
|
1191
|
+
const statusLine = async (bot) => {
|
|
1192
|
+
const model = (await rt.desiredModel?.(bot)) ?? bot.model ?? "?";
|
|
1193
|
+
const parts = Array.isArray(bot.segments) ? bot.segments.length : 0;
|
|
1194
|
+
const running = rt.live.get(rt.chatOf(bot.id))?.turn !== undefined;
|
|
1195
|
+
return text("cmdStatus", { bot: bot.name, model, running, parts });
|
|
1196
|
+
};
|
|
1197
|
+
const runCommand = async (conn, msg, target) => {
|
|
1198
|
+
const name = commandWord(msg);
|
|
1199
|
+
if (name === undefined)
|
|
1200
|
+
return false;
|
|
1201
|
+
const botId = target?.botId;
|
|
1202
|
+
const reply = async (body, buttons, look) => await sendTo(conn, msg.chat.key, msg.chat, body, buttons, undefined, typeof msg.messageId === "string" ? msg.messageId : undefined, look);
|
|
1203
|
+
if (botId === undefined) {
|
|
1204
|
+
if (name === "help") {
|
|
1205
|
+
await reply(text("cmdHelp"));
|
|
1206
|
+
return true;
|
|
1207
|
+
}
|
|
1208
|
+
if (name === "menu" || name === "status") {
|
|
1209
|
+
await reply(text("cmdGroupOnly"));
|
|
1210
|
+
return true;
|
|
1211
|
+
}
|
|
1212
|
+
if (name === "stop" || name === "new") {
|
|
1213
|
+
await reply(text("cmdGroupOnly"));
|
|
1214
|
+
return true;
|
|
1215
|
+
}
|
|
1216
|
+
return true;
|
|
1217
|
+
}
|
|
1218
|
+
const bot = rt.botOf(botId);
|
|
1219
|
+
if (bot === undefined)
|
|
1220
|
+
return true;
|
|
1221
|
+
if (name === "help") {
|
|
1222
|
+
await reply(text("cmdHelp"));
|
|
1223
|
+
return true;
|
|
1224
|
+
}
|
|
1225
|
+
if (name === "menu") {
|
|
1226
|
+
const buttons = imPlatform(conn.platform)?.buttons === true
|
|
1227
|
+
? [
|
|
1228
|
+
{ data: "c:stop", label: text("stop") },
|
|
1229
|
+
{ data: "c:new", label: text("newPart") },
|
|
1230
|
+
{ data: "c:status", label: text("status") },
|
|
1231
|
+
{ data: "c:help", label: text("help") },
|
|
1232
|
+
]
|
|
1233
|
+
: undefined;
|
|
1234
|
+
await reply(text("menuBody", { bot: bot.name }), buttons, { title: bot.name });
|
|
1235
|
+
return true;
|
|
1236
|
+
}
|
|
1237
|
+
if (name === "status") {
|
|
1238
|
+
await reply(await statusLine(bot));
|
|
1239
|
+
return true;
|
|
1240
|
+
}
|
|
1241
|
+
if (name === "new") {
|
|
1242
|
+
try {
|
|
1243
|
+
await rt.newPart?.(rt.chatOf(bot.id));
|
|
1244
|
+
await reply(text("cmdNewStarted"));
|
|
1245
|
+
}
|
|
1246
|
+
catch (error) {
|
|
1247
|
+
await reply(error?.code === "bot/busy" ? text("cmdNewBusy") : text("cmdNewBusy"));
|
|
1248
|
+
}
|
|
1249
|
+
return true;
|
|
1250
|
+
}
|
|
1251
|
+
await reply(text("cmdUnknown", { name }));
|
|
1252
|
+
return true;
|
|
1253
|
+
};
|
|
1254
|
+
const onAction = (conn) => async (action) => {
|
|
1255
|
+
if (!paired(conn, action.sender.id))
|
|
1256
|
+
return;
|
|
1257
|
+
const data = String(action.data ?? "");
|
|
1258
|
+
const chat = { key: action.chat.key, kind: action.chat.kind, title: action.chat.title };
|
|
1259
|
+
// Button data is `<kind>:<id>:<choice>`; the id is everything between the
|
|
1260
|
+
// first and the last colon, so an id with a colon in it still parses.
|
|
1261
|
+
const cut = data.lastIndexOf(":");
|
|
1262
|
+
const cardKey = data.slice(0, cut);
|
|
1263
|
+
const choice = data.slice(cut + 1);
|
|
1264
|
+
if (data.startsWith("c:") && data.length > 2) {
|
|
1265
|
+
const name = data.slice(2);
|
|
1266
|
+
const chat = { key: action.chat.key, kind: action.chat.kind, title: action.chat.title };
|
|
1267
|
+
const held = resolveTarget(conn, conn.chats?.[action.chat.key]);
|
|
1268
|
+
const bot = held?.botId === undefined ? undefined : rt.botOf(held.botId);
|
|
1269
|
+
if (name === "status" && bot !== undefined) {
|
|
1270
|
+
await sendCardReply(conn, chat, await statusLine(bot));
|
|
1271
|
+
}
|
|
1272
|
+
else if (name === "help") {
|
|
1273
|
+
await sendCardReply(conn, chat, text("cmdHelp"));
|
|
1274
|
+
}
|
|
1275
|
+
else if (name === "stop" && bot !== undefined) {
|
|
1276
|
+
const stopped = await rt.stopChat(bot.id);
|
|
1277
|
+
await sendCardReply(conn, chat, text(stopped ? "stopped" : "idle"));
|
|
1278
|
+
}
|
|
1279
|
+
else if (name === "new" && bot !== undefined) {
|
|
1280
|
+
try {
|
|
1281
|
+
await rt.newPart?.(rt.chatOf(bot.id));
|
|
1282
|
+
await sendCardReply(conn, chat, text("cmdNewStarted"));
|
|
1283
|
+
}
|
|
1284
|
+
catch {
|
|
1285
|
+
await sendCardReply(conn, chat, text("cmdNewBusy"));
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
else {
|
|
1289
|
+
await sendCardReply(conn, chat, text("cmdGroupOnly"));
|
|
1290
|
+
}
|
|
1291
|
+
return;
|
|
1292
|
+
}
|
|
1293
|
+
if (data.startsWith("q:") && cut > 2) {
|
|
1294
|
+
const found = questionById(cardKey.slice(2));
|
|
1295
|
+
const label = found?.question.options?.[Number(choice)]?.label;
|
|
1296
|
+
if (label === undefined) {
|
|
1297
|
+
await sendCardReply(conn, chat, text("stale"));
|
|
1298
|
+
return;
|
|
1299
|
+
}
|
|
1300
|
+
if (!(await answerQuestionCard(conn, chat, cardKey, [label])))
|
|
1301
|
+
await sendCardReply(conn, chat, text("stale"));
|
|
1302
|
+
return;
|
|
1303
|
+
}
|
|
1304
|
+
if (data.startsWith("a:") && cut > 2) {
|
|
1305
|
+
if (choice === "allow" || choice === "reject") {
|
|
1306
|
+
if (!(await answerApprovalCard(conn, chat, cardKey, choice)))
|
|
1307
|
+
await sendCardReply(conn, chat, text("stale"));
|
|
1308
|
+
}
|
|
1309
|
+
return;
|
|
1310
|
+
}
|
|
1311
|
+
if (data.startsWith("v:") && cut > 4) {
|
|
1312
|
+
const rest = data.slice(2);
|
|
1313
|
+
const inner = rest.lastIndexOf(":");
|
|
1314
|
+
const viewId = rest.slice(0, inner).split(":")[0];
|
|
1315
|
+
const nodeId = rest.slice(viewId.length + 1, inner);
|
|
1316
|
+
if (!(await answerViewCard(conn, chat, `v:${viewId}`, nodeId, choice, action.form)))
|
|
1317
|
+
await sendCardReply(conn, chat, text("stale"));
|
|
1318
|
+
}
|
|
1319
|
+
};
|
|
1320
|
+
// ------------------------------------------------------------------ cards
|
|
1321
|
+
const cardText = {
|
|
1322
|
+
question: (bot, question) => {
|
|
1323
|
+
const options = (question.options ?? [])
|
|
1324
|
+
.map((option, index) => `${index + 1}. ${option.label}${option.description ? ` — ${option.description}` : ""}`)
|
|
1325
|
+
.join("\n");
|
|
1326
|
+
const hint = question.multiSelect === true ? text("numbersMulti") : text("numbers");
|
|
1327
|
+
return `${text("question", { bot })}${question.question}${question.detail ? `\n${question.detail}` : ""}\n${options}\n(${hint})`;
|
|
1328
|
+
},
|
|
1329
|
+
approval: (bot, entry) => `${text("approval", { bot })}${entry.tool}${entry.reason ? ` — ${entry.reason}` : ""}${entry.detail?.text ? `\n${entry.detail.text}` : ""}${entry.detail?.code ? `\n${entry.detail.code}` : ""}`,
|
|
1330
|
+
};
|
|
1331
|
+
const cardButtons = {
|
|
1332
|
+
question: (question) => question.multiSelect === true
|
|
1333
|
+
? undefined
|
|
1334
|
+
: (question.options ?? []).map((option, index) => ({
|
|
1335
|
+
data: `q:${question.id}:${index}`,
|
|
1336
|
+
label: option.label,
|
|
1337
|
+
})),
|
|
1338
|
+
approval: (id) => [
|
|
1339
|
+
{ data: `a:${id}:allow`, label: text("allow") },
|
|
1340
|
+
{ data: `a:${id}:reject`, label: text("reject") },
|
|
1341
|
+
],
|
|
1342
|
+
};
|
|
1343
|
+
// What a view's card offers: buttons for one choice, a form when several answers or
|
|
1344
|
+
// typed fields are needed. The submit button carries the same `v:<view>:<node>:<choice>`
|
|
1345
|
+
// data the buttons use, so the action handler stays one path.
|
|
1346
|
+
const viewCardSpec = (viewId, view) => {
|
|
1347
|
+
const nodes = [];
|
|
1348
|
+
const walk = (value) => {
|
|
1349
|
+
if (value === null || typeof value !== "object")
|
|
1350
|
+
return;
|
|
1351
|
+
if (Array.isArray(value)) {
|
|
1352
|
+
for (const child of value)
|
|
1353
|
+
walk(child);
|
|
1354
|
+
return;
|
|
1355
|
+
}
|
|
1356
|
+
if (["options", "confirm", "form"].includes(String(value.type)) && typeof value.id === "string")
|
|
1357
|
+
nodes.push(value);
|
|
1358
|
+
for (const child of Object.values(value))
|
|
1359
|
+
walk(child);
|
|
1360
|
+
};
|
|
1361
|
+
walk(view);
|
|
1362
|
+
const node = nodes.find((entry) => entry.type === "options"
|
|
1363
|
+
? Array.isArray(entry.options) && entry.options.length > 0
|
|
1364
|
+
: entry.type === "form"
|
|
1365
|
+
? Array.isArray(entry.fields) && entry.fields.some((field) => typeof field?.id === "string")
|
|
1366
|
+
: true);
|
|
1367
|
+
if (node === undefined)
|
|
1368
|
+
return {};
|
|
1369
|
+
if (node.type === "confirm")
|
|
1370
|
+
return {
|
|
1371
|
+
buttons: [
|
|
1372
|
+
{ data: `v:${viewId}:${node.id}:yes`, label: String(node.confirmLabel ?? text("yes")) },
|
|
1373
|
+
{ data: `v:${viewId}:${node.id}:no`, label: String(node.cancelLabel ?? text("no")) },
|
|
1374
|
+
],
|
|
1375
|
+
};
|
|
1376
|
+
if (node.type === "options") {
|
|
1377
|
+
const labels = (node.options ?? [])
|
|
1378
|
+
.slice(0, 8)
|
|
1379
|
+
.map((option) => String(option?.label ?? ""))
|
|
1380
|
+
.filter((label) => label !== "");
|
|
1381
|
+
if (node.multi !== true)
|
|
1382
|
+
return {
|
|
1383
|
+
buttons: labels.slice(0, 4).map((label, index) => ({
|
|
1384
|
+
data: `v:${viewId}:${node.id}:o${index}`,
|
|
1385
|
+
label: label.slice(0, 20),
|
|
1386
|
+
})),
|
|
1387
|
+
};
|
|
1388
|
+
if (labels.length === 0)
|
|
1389
|
+
return {};
|
|
1390
|
+
return {
|
|
1391
|
+
form: {
|
|
1392
|
+
fields: [{ kind: "multi", name: `sel:${node.id}`, label: text("pickMany"), options: labels }],
|
|
1393
|
+
submit: { data: `v:${viewId}:${node.id}:submit`, label: text("submit") },
|
|
1394
|
+
},
|
|
1395
|
+
};
|
|
1396
|
+
}
|
|
1397
|
+
const fields = (node.fields ?? [])
|
|
1398
|
+
.filter((field) => typeof field?.id === "string" && field.readOnly !== true)
|
|
1399
|
+
.slice(0, 8)
|
|
1400
|
+
.map((field) => ({
|
|
1401
|
+
kind: "text",
|
|
1402
|
+
name: `f:${node.id}:${field.id}`,
|
|
1403
|
+
label: String(field.label ?? field.id),
|
|
1404
|
+
multiline: field.multiline === true,
|
|
1405
|
+
...(typeof field.value === "string" ? { initial: field.value } : {}),
|
|
1406
|
+
}));
|
|
1407
|
+
if (fields.length === 0)
|
|
1408
|
+
return {};
|
|
1409
|
+
return {
|
|
1410
|
+
form: {
|
|
1411
|
+
fields,
|
|
1412
|
+
submit: {
|
|
1413
|
+
data: `v:${viewId}:${node.id}:submit`,
|
|
1414
|
+
label: String(node.submitLabel ?? text("submit")),
|
|
1415
|
+
},
|
|
1416
|
+
cancel: {
|
|
1417
|
+
data: `v:${viewId}:${node.id}:cancel`,
|
|
1418
|
+
label: String(node.cancelLabel ?? text("cancel")),
|
|
1419
|
+
},
|
|
1420
|
+
},
|
|
1421
|
+
};
|
|
1422
|
+
};
|
|
1423
|
+
const sendCard = async (conn, cardKey, targets, body, buttons, look) => {
|
|
1424
|
+
for (const { chatKey, chat } of targets) {
|
|
1425
|
+
sendTo(conn, chatKey, { key: chatKey, kind: chat.kind, title: chat.title }, body, buttons, (sent) => {
|
|
1426
|
+
void markCard(conn.id, cardKey, chatKey, sent?.messageId, body);
|
|
1427
|
+
}, undefined, look);
|
|
1428
|
+
}
|
|
1429
|
+
// A card a chat never got (queued behind a failure) is still recorded below.
|
|
1430
|
+
for (const { chatKey } of targets)
|
|
1431
|
+
await markCard(conn.id, cardKey, chatKey, undefined, body);
|
|
1432
|
+
};
|
|
1433
|
+
const roomOfSession = (sessionId) => {
|
|
1434
|
+
const own = rt.roomOf(sessionId);
|
|
1435
|
+
if (own !== undefined)
|
|
1436
|
+
return own;
|
|
1437
|
+
const owner = rt.groupOwners.get(sessionId);
|
|
1438
|
+
return owner === undefined ? undefined : rt.roomOf(owner.roomId);
|
|
1439
|
+
};
|
|
1440
|
+
const diffCards = async () => {
|
|
1441
|
+
if (rt.readOnly() !== undefined)
|
|
1442
|
+
return;
|
|
1443
|
+
for (const conn of Object.values(connections())) {
|
|
1444
|
+
const runner = runners.get(conn.id);
|
|
1445
|
+
if (runner === undefined)
|
|
1446
|
+
continue;
|
|
1447
|
+
const data = await cardsOf(conn.id);
|
|
1448
|
+
// Questions: one card per open question id, sent to the Bot's chats, or to the
|
|
1449
|
+
// group chat when the question was raised in one.
|
|
1450
|
+
for (const [sessionId, question] of Object.entries((state.questions ?? {}))) {
|
|
1451
|
+
const cardKey = `q:${question.id}`;
|
|
1452
|
+
if (data.cards[cardKey] !== undefined)
|
|
1453
|
+
continue;
|
|
1454
|
+
const botId = rt.chatOwners.get(sessionId) ?? rt.pastOwners.get(sessionId)?.botId;
|
|
1455
|
+
const bot = rt.botOf(botId);
|
|
1456
|
+
const buttons = imPlatform(conn.platform)?.buttons === true ? cardButtons.question(question) : undefined;
|
|
1457
|
+
if (bot === undefined) {
|
|
1458
|
+
const room = roomOfSession(sessionId);
|
|
1459
|
+
if (room === undefined)
|
|
1460
|
+
continue;
|
|
1461
|
+
await sendCard(conn, cardKey, replyTargets(ownerOrigins.get(room.id), `room:${room.id}`), cardText.question(room.name ?? "this group chat", question), buttons);
|
|
1462
|
+
continue;
|
|
1463
|
+
}
|
|
1464
|
+
await sendCard(conn, cardKey, replyTargets(sessionOrigins.get(sessionId), `bot:${botId}`), cardText.question(bot.name, question), buttons);
|
|
1465
|
+
}
|
|
1466
|
+
// Secret requests: text only — the key is typed on the computer or phone.
|
|
1467
|
+
for (const [botId, list] of Object.entries((state.secretRequests ?? {}))) {
|
|
1468
|
+
const bot = rt.botOf(botId);
|
|
1469
|
+
if (bot === undefined)
|
|
1470
|
+
continue;
|
|
1471
|
+
for (const request of list) {
|
|
1472
|
+
const cardKey = `s:${request.id}`;
|
|
1473
|
+
if (request.status !== "pending" || data.cards[cardKey] !== undefined)
|
|
1474
|
+
continue;
|
|
1475
|
+
await sendCard(conn, cardKey, replyTargets(ownerOrigins.get(botId), `bot:${botId}`), text("secretAsk", { bot: bot.name, name: request.name }));
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
// Views awaiting a reply: a card, with buttons when the blueprint can be
|
|
1479
|
+
// answered by pressing one. A view from a group chat goes there.
|
|
1480
|
+
for (const [sessionId, view] of Object.entries((state.views ?? {}))) {
|
|
1481
|
+
const cardKey = `v:${view.id}`;
|
|
1482
|
+
if (data.cards[cardKey] !== undefined)
|
|
1483
|
+
continue;
|
|
1484
|
+
const botId = rt.chatOwners.get(sessionId);
|
|
1485
|
+
const bot = rt.botOf(botId);
|
|
1486
|
+
const rendered = viewCardText({ title: view.title, view: view.view });
|
|
1487
|
+
const spec = imPlatform(conn.platform)?.buttons === true ? viewCardSpec(view.id, view.view) : {};
|
|
1488
|
+
const buttons = spec.buttons;
|
|
1489
|
+
const look = { card: true, ...(spec.form === undefined ? {} : { form: spec.form }) };
|
|
1490
|
+
const body = (name) => `${text(buttons === undefined && spec.form === undefined ? "viewShow" : "viewPick", { bot: name })}${rendered !== "" ? `\n${rendered}` : view.title ? `\n${view.title}` : ""}`;
|
|
1491
|
+
if (bot === undefined) {
|
|
1492
|
+
const room = roomOfSession(sessionId);
|
|
1493
|
+
if (room === undefined)
|
|
1494
|
+
continue;
|
|
1495
|
+
await sendCard(conn, cardKey, replyTargets(ownerOrigins.get(room.id), `room:${room.id}`), body(room.name ?? "this group chat"), buttons, { ...look, title: room.name });
|
|
1496
|
+
continue;
|
|
1497
|
+
}
|
|
1498
|
+
await sendCard(conn, cardKey, replyTargets(sessionOrigins.get(sessionId), `bot:${botId}`), body(bot.name), buttons, {
|
|
1499
|
+
...look,
|
|
1500
|
+
title: bot.name,
|
|
1501
|
+
});
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
};
|
|
1505
|
+
// Buttons drop and the answer shows wherever the card was settled.
|
|
1506
|
+
const settledEdits = async (conn) => {
|
|
1507
|
+
const runner = runners.get(conn.id);
|
|
1508
|
+
const data = runtimes.get(conn.id)?.data;
|
|
1509
|
+
if (runner?.handle.edit === undefined || data === undefined)
|
|
1510
|
+
return;
|
|
1511
|
+
for (const entries of Object.values(data.cards)) {
|
|
1512
|
+
for (const entry of entries) {
|
|
1513
|
+
if (entry.answer === undefined || entry.messageId === undefined || entry.edited === true)
|
|
1514
|
+
continue;
|
|
1515
|
+
const chat = conn.chats?.[entry.chatKey];
|
|
1516
|
+
if (chat === undefined)
|
|
1517
|
+
continue;
|
|
1518
|
+
entry.edited = true;
|
|
1519
|
+
const body = entry.text !== undefined ? `${entry.text}\n— ${entry.answer}` : `(${text("answered")})`;
|
|
1520
|
+
runner.handle
|
|
1521
|
+
.edit({ key: entry.chatKey, kind: chat.kind, title: chat.title }, entry.messageId, { text: body })
|
|
1522
|
+
.catch(() => { });
|
|
1523
|
+
scheduleWrite(conn.id);
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
};
|
|
1527
|
+
// A card answered on the computer leaves the state; its IM copy settles too.
|
|
1528
|
+
const settleGone = async () => {
|
|
1529
|
+
for (const conn of Object.values(connections())) {
|
|
1530
|
+
const data = runtimes.get(conn.id)?.data;
|
|
1531
|
+
if (data === undefined)
|
|
1532
|
+
continue;
|
|
1533
|
+
let touched = false;
|
|
1534
|
+
const openIds = new Set(Object.values((state.questions ?? {})).map((question) => `q:${question.id}`));
|
|
1535
|
+
const openSecret = new Set(Object.values((state.secretRequests ?? {}))
|
|
1536
|
+
.flat()
|
|
1537
|
+
.filter((entry) => entry.status === "pending")
|
|
1538
|
+
.map((entry) => `s:${entry.id}`));
|
|
1539
|
+
const openViews = new Set(Object.values((state.views ?? {})).map((view) => `v:${view.id}`));
|
|
1540
|
+
const openCard = (cardKey) => cardKey.startsWith("q:")
|
|
1541
|
+
? openIds.has(cardKey)
|
|
1542
|
+
: cardKey.startsWith("a:")
|
|
1543
|
+
? rt.approvalsView().some((entry) => `a:${entry.id}` === cardKey)
|
|
1544
|
+
: cardKey.startsWith("s:")
|
|
1545
|
+
? openSecret.has(cardKey)
|
|
1546
|
+
: cardKey.startsWith("v:")
|
|
1547
|
+
? openViews.has(cardKey)
|
|
1548
|
+
: false;
|
|
1549
|
+
for (const [cardKey, entries] of Object.entries(data.cards)) {
|
|
1550
|
+
if (openCard(cardKey))
|
|
1551
|
+
continue;
|
|
1552
|
+
for (const entry of entries) {
|
|
1553
|
+
if (entry.answer === undefined) {
|
|
1554
|
+
entry.answer = text("answered");
|
|
1555
|
+
touched = true;
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
if (touched) {
|
|
1560
|
+
scheduleWrite(conn.id);
|
|
1561
|
+
await settledEdits(conn);
|
|
1562
|
+
}
|
|
1563
|
+
// A card whose source is gone stays only until its copies are settled and
|
|
1564
|
+
// edited where the platform can edit; keeping it forever grows the file.
|
|
1565
|
+
const editable = runners.get(conn.id)?.handle?.edit !== undefined;
|
|
1566
|
+
let pruned = false;
|
|
1567
|
+
for (const [cardKey, entries] of Object.entries(data.cards)) {
|
|
1568
|
+
if (openCard(cardKey))
|
|
1569
|
+
continue;
|
|
1570
|
+
const droppable = entries.length === 0 ||
|
|
1571
|
+
entries.every((entry) => entry.answer !== undefined &&
|
|
1572
|
+
(entry.edited === true ||
|
|
1573
|
+
entry.messageId === undefined ||
|
|
1574
|
+
!editable ||
|
|
1575
|
+
conn.chats?.[entry.chatKey] === undefined));
|
|
1576
|
+
if (droppable) {
|
|
1577
|
+
delete data.cards[cardKey];
|
|
1578
|
+
pruned = true;
|
|
1579
|
+
}
|
|
1580
|
+
}
|
|
1581
|
+
if (pruned)
|
|
1582
|
+
scheduleWrite(conn.id);
|
|
1583
|
+
}
|
|
1584
|
+
};
|
|
1585
|
+
// ---------------------------------------------------------------- lifecycle
|
|
1586
|
+
// `state.im.connections` is replaced wholesale when a save is adopted, so anything
|
|
1587
|
+
// bound at connect time looks the connection up again by id instead of keeping it.
|
|
1588
|
+
const fresh = (id) => connections()[id];
|
|
1589
|
+
const onStatus = (id) => (next) => {
|
|
1590
|
+
const patch = { state: next.state, error: next.error, messageError: false };
|
|
1591
|
+
// A successful connect ends the retry ladder; the supervisor restarts it on error.
|
|
1592
|
+
if (next.state === "ready") {
|
|
1593
|
+
patch.attempts = 0;
|
|
1594
|
+
patch.nextRetryAt = 0;
|
|
1595
|
+
}
|
|
1596
|
+
setStatus(id, patch);
|
|
1597
|
+
const conn = fresh(id);
|
|
1598
|
+
if (conn !== undefined &&
|
|
1599
|
+
next.account !== undefined &&
|
|
1600
|
+
(conn.account?.id !== next.account.id || conn.account?.name !== next.account.name)) {
|
|
1601
|
+
conn.account = next.account;
|
|
1602
|
+
void rt.save().catch(() => { });
|
|
1603
|
+
}
|
|
1604
|
+
};
|
|
1605
|
+
// A pending first pulse per connection and chat, so a message that lands while one is
|
|
1606
|
+
// waiting does not stack timers.
|
|
1607
|
+
const typingKicks = new Map();
|
|
1608
|
+
const typingPulse = (conn, chat, busy) => {
|
|
1609
|
+
const handle = runners.get(conn.id)?.handle;
|
|
1610
|
+
if (handle === undefined || typeof handle.typing !== "function")
|
|
1611
|
+
return;
|
|
1612
|
+
const key = { key: chat.key, kind: chat.kind, title: chat.title };
|
|
1613
|
+
void (busy ? handle.typing?.(key) : handle.stopTyping?.(key))?.catch?.(() => { });
|
|
1614
|
+
};
|
|
1615
|
+
const kickTyping = (conn, chat) => {
|
|
1616
|
+
if (typeof runners.get(conn.id)?.handle?.typing !== "function")
|
|
1617
|
+
return;
|
|
1618
|
+
const id = `${conn.id}:${chat.key}`;
|
|
1619
|
+
clearTimeout(typingKicks.get(id));
|
|
1620
|
+
const timer = setTimeout(() => {
|
|
1621
|
+
typingKicks.delete(id);
|
|
1622
|
+
typingPulse(conn, chat, true);
|
|
1623
|
+
}, TYPING_FIRST_MS);
|
|
1624
|
+
timer.unref?.();
|
|
1625
|
+
typingKicks.set(id, timer);
|
|
1626
|
+
};
|
|
1627
|
+
const stopTypingNow = (botId) => {
|
|
1628
|
+
for (const conn of Object.values(connections())) {
|
|
1629
|
+
if (runners.get(conn.id)?.handle === undefined)
|
|
1630
|
+
continue;
|
|
1631
|
+
for (const { chatKey, chat } of listeners(conn, { botId })) {
|
|
1632
|
+
clearTimeout(typingKicks.get(`${conn.id}:${chatKey}`));
|
|
1633
|
+
typingKicks.delete(`${conn.id}:${chatKey}`);
|
|
1634
|
+
typingPulse(conn, { ...chat, key: chatKey }, false);
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
};
|
|
1638
|
+
const busyOf = (target) => {
|
|
1639
|
+
if (target?.botId !== undefined)
|
|
1640
|
+
return rt.live.get(rt.chatOf(target.botId))?.turn !== undefined;
|
|
1641
|
+
if (target?.roomId !== undefined)
|
|
1642
|
+
return (rt.roomWorkView?.()[target.roomId] ?? []).length > 0;
|
|
1643
|
+
return false;
|
|
1644
|
+
};
|
|
1645
|
+
// Records a previous process left behind. A `queued` one never reached the platform and
|
|
1646
|
+
// is sent again; a `sending` one may have been accepted, so it is reported as unknown
|
|
1647
|
+
// and never resent; `failed` and `unknown` already settled and stay for the user to see
|
|
1648
|
+
// until the connection's next successful send clears them.
|
|
1649
|
+
const restoreOutbox = async (conn, runner) => {
|
|
1650
|
+
let held;
|
|
1651
|
+
try {
|
|
1652
|
+
held = await outboxOf(conn.id);
|
|
1653
|
+
}
|
|
1654
|
+
catch (error) {
|
|
1655
|
+
rt.warn("ocean-crew: im outbox %s unreadable: %s", conn.id, error);
|
|
1656
|
+
return;
|
|
1657
|
+
}
|
|
1658
|
+
let restored = 0;
|
|
1659
|
+
for (const [chatKey, list] of Object.entries((held.data.chats ?? {}))) {
|
|
1660
|
+
if (!Array.isArray(list))
|
|
1661
|
+
continue;
|
|
1662
|
+
// The record carries the chat it was meant for, so a restart before any new
|
|
1663
|
+
// message still knows where to send; `conn.chats` is only filled by inbound
|
|
1664
|
+
// traffic and is empty on a fresh start.
|
|
1665
|
+
for (const record of list) {
|
|
1666
|
+
if (record.state === "sending") {
|
|
1667
|
+
await outboxUpdate(conn.id, chatKey, record.id, {
|
|
1668
|
+
state: "unknown",
|
|
1669
|
+
error: "The send was interrupted before the platform answered",
|
|
1670
|
+
}).catch(() => { });
|
|
1671
|
+
continue;
|
|
1672
|
+
}
|
|
1673
|
+
if (record.state !== "queued")
|
|
1674
|
+
continue;
|
|
1675
|
+
let queue = runner.queues.get(chatKey);
|
|
1676
|
+
if (queue === undefined) {
|
|
1677
|
+
queue = { jobs: [] };
|
|
1678
|
+
runner.queues.set(chatKey, queue);
|
|
1679
|
+
}
|
|
1680
|
+
queue.jobs.push({
|
|
1681
|
+
chat: record.chat ?? { key: chatKey, kind: "direct", title: chatKey },
|
|
1682
|
+
text: record.body,
|
|
1683
|
+
...(record.buttons === undefined ? {} : { buttons: record.buttons }),
|
|
1684
|
+
outboxId: record.id,
|
|
1685
|
+
restored: true,
|
|
1686
|
+
});
|
|
1687
|
+
restored += 1;
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
if (restored > 0)
|
|
1691
|
+
rt.warn("ocean-crew: im outbox for %s resumed %d unsent message(s)", conn.id, restored);
|
|
1692
|
+
};
|
|
1693
|
+
const start = async (conn) => {
|
|
1694
|
+
const adapter = adapters[conn.platform];
|
|
1695
|
+
if (adapter === undefined || runners.has(conn.id))
|
|
1696
|
+
return;
|
|
1697
|
+
const platform = imPlatform(conn.platform);
|
|
1698
|
+
if (platform?.ws === true && globalThis.WebSocket === undefined) {
|
|
1699
|
+
setStatus(conn.id, { state: "error", error: "This dsh runs on a Node without WebSocket" });
|
|
1700
|
+
return;
|
|
1701
|
+
}
|
|
1702
|
+
// The slot is reserved before the async work: a concurrent sync cannot
|
|
1703
|
+
// start a second adapter for the same connection.
|
|
1704
|
+
const runner = { handle: undefined, queues: new Map(), typing: undefined };
|
|
1705
|
+
runners.set(conn.id, runner);
|
|
1706
|
+
setStatus(conn.id, { state: "connecting", error: undefined });
|
|
1707
|
+
try {
|
|
1708
|
+
const env = await envFor(conn);
|
|
1709
|
+
const handle = adapter.connect(fieldsOf(conn), env, {
|
|
1710
|
+
onMessage: (msg) => {
|
|
1711
|
+
const current = fresh(conn.id);
|
|
1712
|
+
return current === undefined
|
|
1713
|
+
? undefined
|
|
1714
|
+
: onMessage(current)(msg).catch((error) => rt.warn("ocean-crew: im message failed: %s", error));
|
|
1715
|
+
},
|
|
1716
|
+
onAction: (action) => {
|
|
1717
|
+
const current = fresh(conn.id);
|
|
1718
|
+
return current === undefined
|
|
1719
|
+
? undefined
|
|
1720
|
+
: onAction(current)(action).catch((error) => rt.warn("ocean-crew: im action failed: %s", error));
|
|
1721
|
+
},
|
|
1722
|
+
onStatus: onStatus(conn.id),
|
|
1723
|
+
});
|
|
1724
|
+
// A stop() during connect took the slot back: undo the just-started
|
|
1725
|
+
// adapter instead of leaving it running unreachable.
|
|
1726
|
+
if (runners.get(conn.id) !== runner) {
|
|
1727
|
+
void Promise.resolve(handle?.stop?.()).catch(() => { });
|
|
1728
|
+
return;
|
|
1729
|
+
}
|
|
1730
|
+
runner.handle = handle;
|
|
1731
|
+
await restoreOutbox(conn, runner);
|
|
1732
|
+
for (const chatKey of runner.queues.keys())
|
|
1733
|
+
void drain(conn, chatKey);
|
|
1734
|
+
if (typeof runner.handle?.typing === "function") {
|
|
1735
|
+
runner.typing = setInterval(() => {
|
|
1736
|
+
for (const { chat, target } of targetsOf(fresh(conn.id) ?? conn)) {
|
|
1737
|
+
typingPulse(conn, { ...chat, key: chat.key ?? chat }, target !== undefined && busyOf(target));
|
|
1738
|
+
}
|
|
1739
|
+
}, TYPING_MS);
|
|
1740
|
+
runner.typing.unref?.();
|
|
1741
|
+
}
|
|
1742
|
+
await diffCards();
|
|
1743
|
+
}
|
|
1744
|
+
catch (error) {
|
|
1745
|
+
runners.delete(conn.id);
|
|
1746
|
+
setStatus(conn.id, { state: "error", error: String(error?.message ?? error).slice(0, 300) });
|
|
1747
|
+
}
|
|
1748
|
+
};
|
|
1749
|
+
const stop = async (id) => {
|
|
1750
|
+
const runner = runners.get(id);
|
|
1751
|
+
runners.delete(id);
|
|
1752
|
+
if (runner?.typing !== undefined)
|
|
1753
|
+
clearInterval(runner.typing);
|
|
1754
|
+
for (const [key, timer] of typingKicks) {
|
|
1755
|
+
if (!key.startsWith(`${id}:`))
|
|
1756
|
+
continue;
|
|
1757
|
+
clearTimeout(timer);
|
|
1758
|
+
typingKicks.delete(key);
|
|
1759
|
+
}
|
|
1760
|
+
for (const queue of runner?.queues.values() ?? [])
|
|
1761
|
+
clearTimeout(queue.retry);
|
|
1762
|
+
await Promise.resolve(runner?.handle?.stop?.()).catch(() => { });
|
|
1763
|
+
if (statuses.get(id)?.state !== "error")
|
|
1764
|
+
setStatus(id, { state: "off" });
|
|
1765
|
+
};
|
|
1766
|
+
let stopped = false;
|
|
1767
|
+
const desiredOf = (conn) => stopped !== true &&
|
|
1768
|
+
adapters[conn.platform] !== undefined &&
|
|
1769
|
+
conn.enabled !== false &&
|
|
1770
|
+
rt.readOnly() === undefined &&
|
|
1771
|
+
hasSecrets(conn);
|
|
1772
|
+
// Syncs run one behind the other: endpoints, onSaved and the interval can all
|
|
1773
|
+
// fire while a sync is still starting an adapter, and they must see its
|
|
1774
|
+
// reserved slots rather than start a second adapter. Each connection gets one
|
|
1775
|
+
// decision per sync from supervisor.js: start, stop, restart or none.
|
|
1776
|
+
let syncing = Promise.resolve();
|
|
1777
|
+
const sync = () => {
|
|
1778
|
+
const run = syncing.then(async () => {
|
|
1779
|
+
const conns = connections();
|
|
1780
|
+
const now = Date.now();
|
|
1781
|
+
for (const conn of Object.values(conns)) {
|
|
1782
|
+
const desired = desiredOf(conn);
|
|
1783
|
+
const current = statuses.get(conn.id) ?? {};
|
|
1784
|
+
const decision = nextAction(now, {
|
|
1785
|
+
desired,
|
|
1786
|
+
running: runners.has(conn.id),
|
|
1787
|
+
state: current.state ?? "off",
|
|
1788
|
+
messageError: current.messageError === true,
|
|
1789
|
+
attempts: current.attempts ?? 0,
|
|
1790
|
+
nextRetryAt: current.nextRetryAt ?? 0,
|
|
1791
|
+
});
|
|
1792
|
+
if (decision.attempts !== (current.attempts ?? 0) || decision.nextRetryAt !== (current.nextRetryAt ?? 0)) {
|
|
1793
|
+
setStatus(conn.id, { attempts: decision.attempts, nextRetryAt: decision.nextRetryAt });
|
|
1794
|
+
}
|
|
1795
|
+
if (decision.action === "stop")
|
|
1796
|
+
await stop(conn.id);
|
|
1797
|
+
else if (decision.action === "restart") {
|
|
1798
|
+
await stop(conn.id);
|
|
1799
|
+
await start(conn);
|
|
1800
|
+
}
|
|
1801
|
+
else if (decision.action === "start")
|
|
1802
|
+
await start(conn);
|
|
1803
|
+
}
|
|
1804
|
+
for (const id of [...runners.keys()])
|
|
1805
|
+
if (conns[id] === undefined)
|
|
1806
|
+
await stop(id);
|
|
1807
|
+
for (const id of [...statuses.keys()])
|
|
1808
|
+
if (conns[id] === undefined)
|
|
1809
|
+
statuses.delete(id);
|
|
1810
|
+
for (const conn of Object.values(conns)) {
|
|
1811
|
+
if (conn.enabled === false || !runners.has(conn.id)) {
|
|
1812
|
+
if (statuses.get(conn.id)?.state !== "error")
|
|
1813
|
+
setStatus(conn.id, { state: "off" });
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
});
|
|
1817
|
+
syncing = run.catch(() => { });
|
|
1818
|
+
return run;
|
|
1819
|
+
};
|
|
1820
|
+
// ---------------------------------------------------------------- endpoints
|
|
1821
|
+
const secretName = (conn, key) => `IM_${conn.platform.toUpperCase()}_${conn.id.slice(3, 9).toUpperCase()}_${secretField(key)}`;
|
|
1822
|
+
const cleanFields = (platform, fields, base = {}) => {
|
|
1823
|
+
const given = fields !== null && typeof fields === "object" ? fields : {};
|
|
1824
|
+
const out = {};
|
|
1825
|
+
for (const field of platform.fields) {
|
|
1826
|
+
const value = given[field.key];
|
|
1827
|
+
if (field.options !== undefined) {
|
|
1828
|
+
out[field.key] = field.options.some(([id]) => id === value)
|
|
1829
|
+
? value
|
|
1830
|
+
: value === undefined && base[field.key] !== undefined
|
|
1831
|
+
? base[field.key]
|
|
1832
|
+
: field.options[0][0];
|
|
1833
|
+
}
|
|
1834
|
+
else if (typeof value === "string" && value.trim() !== "") {
|
|
1835
|
+
out[field.key] = value.trim();
|
|
1836
|
+
}
|
|
1837
|
+
else if (!field.secret) {
|
|
1838
|
+
if (value !== undefined && typeof value !== "string")
|
|
1839
|
+
throw new Error(`${field.label} must be text`);
|
|
1840
|
+
out[field.key] = value === undefined && base[field.key] !== undefined ? base[field.key] : "";
|
|
1841
|
+
}
|
|
1842
|
+
// Missing secret fields are allowed only on update, where the saved one stays.
|
|
1843
|
+
}
|
|
1844
|
+
return out;
|
|
1845
|
+
};
|
|
1846
|
+
const saveSecrets = async (conn, platform, fields) => {
|
|
1847
|
+
for (const field of platform.fields) {
|
|
1848
|
+
if (!field.secret || fields[field.key] === undefined)
|
|
1849
|
+
continue;
|
|
1850
|
+
const name = conn.secrets[field.key] ?? secretName(conn, field.key);
|
|
1851
|
+
await rt.secretEndpoint("secret-set", {
|
|
1852
|
+
name,
|
|
1853
|
+
value: fields[field.key],
|
|
1854
|
+
purpose: `${platform.name} IM bot`,
|
|
1855
|
+
scope: [],
|
|
1856
|
+
});
|
|
1857
|
+
conn.secrets[field.key] = name;
|
|
1858
|
+
}
|
|
1859
|
+
};
|
|
1860
|
+
const viewOf = (conn) => ({
|
|
1861
|
+
id: conn.id,
|
|
1862
|
+
platform: conn.platform,
|
|
1863
|
+
account: conn.account ?? null,
|
|
1864
|
+
botId: conn.botId ?? null,
|
|
1865
|
+
settings: conn.settings ?? {},
|
|
1866
|
+
secrets: Object.keys(conn.secrets ?? {}),
|
|
1867
|
+
enabled: conn.enabled !== false,
|
|
1868
|
+
paired: conn.paired ?? [],
|
|
1869
|
+
requests: conn.requests ?? [],
|
|
1870
|
+
chats: Object.fromEntries(Object.entries((conn.chats ?? {})).map(([key, chat]) => [
|
|
1871
|
+
key,
|
|
1872
|
+
{ ...chat },
|
|
1873
|
+
])),
|
|
1874
|
+
createdAt: conn.createdAt,
|
|
1875
|
+
});
|
|
1876
|
+
const endpoints = {
|
|
1877
|
+
async "im-add"(body) {
|
|
1878
|
+
const platform = imPlatform(String(body.platform ?? ""));
|
|
1879
|
+
if (platform === undefined || adapters[platform.id] === undefined)
|
|
1880
|
+
throw new Error("This platform is not available yet");
|
|
1881
|
+
const bot = rt.botOf(String(body.botId ?? ""));
|
|
1882
|
+
if (bot === undefined)
|
|
1883
|
+
throw new Error("Choose a Bot first");
|
|
1884
|
+
if (platform.login === "qr")
|
|
1885
|
+
throw new Error("This platform signs in by scanning a code; not available yet");
|
|
1886
|
+
const fields = cleanFields(platform, body.fields);
|
|
1887
|
+
for (const field of platform.fields) {
|
|
1888
|
+
if (!field.options && (fields[field.key] === undefined || String(fields[field.key]).trim() === ""))
|
|
1889
|
+
throw new Error(`${field.label} is required`);
|
|
1890
|
+
}
|
|
1891
|
+
const env = await envFor({ id: "im_check", platform: platform.id, settings: fields, secrets: {} }, { get: () => ({}), set: () => { } });
|
|
1892
|
+
const { account } = await adapters[platform.id].check(fields, env);
|
|
1893
|
+
const conn = {
|
|
1894
|
+
id: `im_${randomBytes(4).toString("hex")}`,
|
|
1895
|
+
platform: platform.id,
|
|
1896
|
+
account,
|
|
1897
|
+
botId: bot.id,
|
|
1898
|
+
settings: Object.fromEntries(platform.fields.filter((field) => !field.secret).map((field) => [field.key, fields[field.key]])),
|
|
1899
|
+
secrets: {},
|
|
1900
|
+
enabled: true,
|
|
1901
|
+
paired: [],
|
|
1902
|
+
requests: [],
|
|
1903
|
+
chats: {},
|
|
1904
|
+
// The default is that a reply answers the chat it came from.
|
|
1905
|
+
mirror: body.mirror === "all" ? "all" : "source",
|
|
1906
|
+
createdAt: Date.now(),
|
|
1907
|
+
};
|
|
1908
|
+
await saveSecrets(conn, platform, fields);
|
|
1909
|
+
connections()[conn.id] = conn;
|
|
1910
|
+
await rt.save();
|
|
1911
|
+
await sync();
|
|
1912
|
+
return viewOf(conn);
|
|
1913
|
+
},
|
|
1914
|
+
async "im-update"(body) {
|
|
1915
|
+
const conn = connections()[String(body.id ?? "")];
|
|
1916
|
+
if (conn !== undefined && (body.mirror === "source" || body.mirror === "all"))
|
|
1917
|
+
conn.mirror = body.mirror;
|
|
1918
|
+
if (conn === undefined)
|
|
1919
|
+
throw new Error("No such IM bot");
|
|
1920
|
+
const platform = imPlatform(conn.platform);
|
|
1921
|
+
if (platform === undefined)
|
|
1922
|
+
throw new Error("No such platform");
|
|
1923
|
+
if (body.botId !== undefined) {
|
|
1924
|
+
const bot = rt.botOf(String(body.botId));
|
|
1925
|
+
if (bot === undefined)
|
|
1926
|
+
throw new Error("Choose a Bot first");
|
|
1927
|
+
conn.botId = bot.id;
|
|
1928
|
+
}
|
|
1929
|
+
if (body.botId !== undefined || body.enabled !== undefined)
|
|
1930
|
+
touchBinding(conn);
|
|
1931
|
+
if (body.enabled !== undefined)
|
|
1932
|
+
conn.enabled = body.enabled === true;
|
|
1933
|
+
if (body.fields !== undefined) {
|
|
1934
|
+
const fields = cleanFields(platform, body.fields, conn.settings);
|
|
1935
|
+
const env = await envFor(conn);
|
|
1936
|
+
const check = { ...fields };
|
|
1937
|
+
for (const field of platform.fields) {
|
|
1938
|
+
if (field.secret && check[field.key] === undefined)
|
|
1939
|
+
check[field.key] = rt.secretValue(conn.secrets[field.key]);
|
|
1940
|
+
}
|
|
1941
|
+
const { account } = await adapters[conn.platform].check(check, env);
|
|
1942
|
+
conn.account = account;
|
|
1943
|
+
await saveSecrets(conn, platform, fields);
|
|
1944
|
+
for (const field of platform.fields) {
|
|
1945
|
+
if (!field.secret && fields[field.key] !== undefined)
|
|
1946
|
+
conn.settings[field.key] = fields[field.key];
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
await rt.save();
|
|
1950
|
+
// New settings invalidate the old failure: try again at once instead of
|
|
1951
|
+
// waiting out the previous backoff.
|
|
1952
|
+
setStatus(conn.id, { state: "off", error: undefined, attempts: 0, nextRetryAt: 0 });
|
|
1953
|
+
if (runners.has(conn.id))
|
|
1954
|
+
await stop(conn.id);
|
|
1955
|
+
await sync();
|
|
1956
|
+
return viewOf(conn);
|
|
1957
|
+
},
|
|
1958
|
+
async "im-remove"(body) {
|
|
1959
|
+
const id = String(body.id ?? "");
|
|
1960
|
+
const conn = connections()[id];
|
|
1961
|
+
if (conn === undefined)
|
|
1962
|
+
throw new Error("No such IM bot");
|
|
1963
|
+
await stop(id);
|
|
1964
|
+
for (const name of Object.values(conn.secrets ?? {})) {
|
|
1965
|
+
await rt.secretEndpoint("secret-delete", { name }).catch(() => { });
|
|
1966
|
+
}
|
|
1967
|
+
delete connections()[id];
|
|
1968
|
+
runtimes.delete(id);
|
|
1969
|
+
await rm(join(imDir, `${id}.json`), { force: true }).catch(() => { });
|
|
1970
|
+
await rt.save();
|
|
1971
|
+
return true;
|
|
1972
|
+
},
|
|
1973
|
+
async "im-pair"(body) {
|
|
1974
|
+
const conn = connections()[String(body.id ?? "")];
|
|
1975
|
+
if (conn === undefined)
|
|
1976
|
+
throw new Error("No such IM bot");
|
|
1977
|
+
const at = (conn.requests ?? []).findIndex((entry) => entry.id === String(body.senderId ?? ""));
|
|
1978
|
+
if (at === -1)
|
|
1979
|
+
throw new Error("This request is gone");
|
|
1980
|
+
const [request] = conn.requests.splice(at, 1);
|
|
1981
|
+
if (body.allow === true) {
|
|
1982
|
+
touchBinding(conn);
|
|
1983
|
+
conn.paired = [...(conn.paired ?? []), { id: request.id, name: request.name, at: Date.now() }];
|
|
1984
|
+
conn.chats ??= {};
|
|
1985
|
+
conn.chats[request.chatKey] ??= { kind: request.chatKind, title: request.name, at: Date.now() };
|
|
1986
|
+
await rt.save();
|
|
1987
|
+
const chat = conn.chats[request.chatKey];
|
|
1988
|
+
const target = resolveTarget(conn, chat);
|
|
1989
|
+
const name = target === undefined ? undefined : targetName(conn, target);
|
|
1990
|
+
await sendTo(conn, request.chatKey, { key: request.chatKey, kind: request.chatKind, title: chat.title }, name === undefined
|
|
1991
|
+
? text(request.chatKind === "group" ? "unboundGroup" : "unbound")
|
|
1992
|
+
: text("connected", { target: name }));
|
|
1993
|
+
}
|
|
1994
|
+
else {
|
|
1995
|
+
await rt.save();
|
|
1996
|
+
}
|
|
1997
|
+
return true;
|
|
1998
|
+
},
|
|
1999
|
+
async "im-unpair"(body) {
|
|
2000
|
+
const conn = connections()[String(body.id ?? "")];
|
|
2001
|
+
if (conn === undefined)
|
|
2002
|
+
throw new Error("No such IM bot");
|
|
2003
|
+
touchBinding(conn);
|
|
2004
|
+
conn.paired = (conn.paired ?? []).filter((entry) => entry.id !== String(body.senderId ?? ""));
|
|
2005
|
+
await rt.save();
|
|
2006
|
+
return true;
|
|
2007
|
+
},
|
|
2008
|
+
async "im-chat"(body) {
|
|
2009
|
+
const conn = connections()[String(body.id ?? "")];
|
|
2010
|
+
if (conn === undefined)
|
|
2011
|
+
throw new Error("No such IM bot");
|
|
2012
|
+
const chat = conn.chats?.[String(body.chatKey ?? "")];
|
|
2013
|
+
if (chat === undefined)
|
|
2014
|
+
throw new Error("No such chat");
|
|
2015
|
+
touchBinding(conn);
|
|
2016
|
+
if (body.remove === true) {
|
|
2017
|
+
delete conn.chats[String(body.chatKey ?? "")];
|
|
2018
|
+
}
|
|
2019
|
+
else if (body.target === null) {
|
|
2020
|
+
delete chat.target;
|
|
2021
|
+
}
|
|
2022
|
+
else if (body.target !== undefined) {
|
|
2023
|
+
const target = body.target;
|
|
2024
|
+
if (target.botId !== undefined && rt.botOf(target.botId) === undefined)
|
|
2025
|
+
throw new Error("Choose a Bot or a group");
|
|
2026
|
+
if (target.roomId !== undefined && rt.roomOf(target.roomId) === undefined)
|
|
2027
|
+
throw new Error("Choose a Bot or a group");
|
|
2028
|
+
chat.target =
|
|
2029
|
+
target.botId !== undefined ? { botId: String(target.botId) } : { roomId: String(target.roomId) };
|
|
2030
|
+
}
|
|
2031
|
+
await rt.save();
|
|
2032
|
+
return true;
|
|
2033
|
+
},
|
|
2034
|
+
async "im-retry"(body) {
|
|
2035
|
+
const conn = connections()[String(body.id ?? "")];
|
|
2036
|
+
if (conn === undefined)
|
|
2037
|
+
throw new Error("No such IM bot");
|
|
2038
|
+
// Manual retry: forget the wait and the failure marks, then reconnect now.
|
|
2039
|
+
setStatus(conn.id, {
|
|
2040
|
+
state: "off",
|
|
2041
|
+
error: undefined,
|
|
2042
|
+
attempts: 0,
|
|
2043
|
+
nextRetryAt: 0,
|
|
2044
|
+
referenceId: undefined,
|
|
2045
|
+
messageError: false,
|
|
2046
|
+
});
|
|
2047
|
+
if (runners.has(conn.id))
|
|
2048
|
+
await stop(conn.id);
|
|
2049
|
+
await sync();
|
|
2050
|
+
return true;
|
|
2051
|
+
},
|
|
2052
|
+
async "im-login-start"(body) {
|
|
2053
|
+
const platform = imPlatform(String(body.platform ?? ""));
|
|
2054
|
+
const adapter = platform === undefined ? undefined : adapters[platform.id];
|
|
2055
|
+
if (platform === undefined || typeof adapter?.loginStart !== "function")
|
|
2056
|
+
throw new Error("This platform has no QR login");
|
|
2057
|
+
const bot = rt.botOf(String(body.botId ?? ""));
|
|
2058
|
+
if (bot === undefined)
|
|
2059
|
+
throw new Error("Choose a Bot first");
|
|
2060
|
+
const env = await envFor({ id: "im_login", platform: platform.id, settings: {}, secrets: {} }, { get: () => ({}), set: () => { } });
|
|
2061
|
+
const login = await adapter.loginStart(env);
|
|
2062
|
+
return { loginId: login.loginId, qr: login.qr, expiresAt: login.expiresAt, botId: bot.id };
|
|
2063
|
+
},
|
|
2064
|
+
async "im-login-wait"(body) {
|
|
2065
|
+
const platform = imPlatform(String(body.platform ?? "weixin"));
|
|
2066
|
+
const adapter = platform === undefined ? undefined : adapters[platform.id];
|
|
2067
|
+
if (platform === undefined || typeof adapter?.loginWait !== "function")
|
|
2068
|
+
throw new Error("This platform has no QR login");
|
|
2069
|
+
const bot = rt.botOf(String(body.botId ?? ""));
|
|
2070
|
+
if (bot === undefined)
|
|
2071
|
+
throw new Error("Choose a Bot first");
|
|
2072
|
+
const env = await envFor({ id: "im_login", platform: platform.id, settings: {}, secrets: {} }, { get: () => ({}), set: () => { } });
|
|
2073
|
+
const login = await adapter.loginWait(String(body.loginId ?? ""), env);
|
|
2074
|
+
if (login.status !== "done")
|
|
2075
|
+
return { status: login.status };
|
|
2076
|
+
// Confirmed: create the connection with the platform credentials the
|
|
2077
|
+
// login returned, paired with the scanning owner — no review needed.
|
|
2078
|
+
const conn = {
|
|
2079
|
+
id: `im_${randomBytes(4).toString("hex")}`,
|
|
2080
|
+
platform: platform.id,
|
|
2081
|
+
account: login.connection.account,
|
|
2082
|
+
botId: bot.id,
|
|
2083
|
+
settings: login.connection.settings ?? {},
|
|
2084
|
+
secrets: {},
|
|
2085
|
+
enabled: true,
|
|
2086
|
+
paired: login.owner === undefined ? [] : [{ id: login.owner.id, name: login.owner.name, at: Date.now() }],
|
|
2087
|
+
requests: [],
|
|
2088
|
+
chats: login.owner === undefined
|
|
2089
|
+
? {}
|
|
2090
|
+
: { [login.owner.id]: { kind: "direct", title: login.owner.name, at: Date.now() } },
|
|
2091
|
+
createdAt: Date.now(),
|
|
2092
|
+
};
|
|
2093
|
+
for (const [key, value] of Object.entries((login.connection.secrets ?? {}))) {
|
|
2094
|
+
const name = secretName(conn, key);
|
|
2095
|
+
await rt.secretEndpoint("secret-set", { name, value, purpose: `${platform.name} IM bot`, scope: [] });
|
|
2096
|
+
conn.secrets[key] = name;
|
|
2097
|
+
}
|
|
2098
|
+
connections()[conn.id] = conn;
|
|
2099
|
+
await rt.save();
|
|
2100
|
+
await sync();
|
|
2101
|
+
return { status: "done", id: conn.id };
|
|
2102
|
+
},
|
|
2103
|
+
};
|
|
2104
|
+
const imEndpoint = async (endpoint, body) => {
|
|
2105
|
+
const result = await endpoints[endpoint]?.(body ?? {});
|
|
2106
|
+
if (result === undefined)
|
|
2107
|
+
throw new Error(`Unknown endpoint ${endpoint}`);
|
|
2108
|
+
void sync();
|
|
2109
|
+
void diffCards();
|
|
2110
|
+
return result;
|
|
2111
|
+
};
|
|
2112
|
+
// ------------------------------------------------------------------ im via
|
|
2113
|
+
// IM-originated user messages, keyed by session and event seq, so the client
|
|
2114
|
+
// can tag a message with the platform it came from. A Session's entries go
|
|
2115
|
+
// when it stops being the chat's current part.
|
|
2116
|
+
const imVia = new Map();
|
|
2117
|
+
const imViaView = () => {
|
|
2118
|
+
for (const sessionId of imVia.keys())
|
|
2119
|
+
if (!rt.chatOwners.has(sessionId))
|
|
2120
|
+
imVia.delete(sessionId);
|
|
2121
|
+
return Object.fromEntries([...imVia.entries()].map(([sessionId, seqs]) => [sessionId, { ...seqs }]));
|
|
2122
|
+
};
|
|
2123
|
+
// ----------------------------------------------------------------- outbound
|
|
2124
|
+
listenGlobal(ctx, "session/event", (session, event) => {
|
|
2125
|
+
if (!sawSessionEvent) {
|
|
2126
|
+
sawSessionEvent = true;
|
|
2127
|
+
rt.warn("ocean-crew: im now receives DSH session events");
|
|
2128
|
+
}
|
|
2129
|
+
if (event.type === "user/message") {
|
|
2130
|
+
// The turn that carries this message has started; a queued message must not
|
|
2131
|
+
// be settled by the end of the turn it waited behind.
|
|
2132
|
+
const rpcId = event.data?.source?.rpcId;
|
|
2133
|
+
if (typeof rpcId === "string")
|
|
2134
|
+
for (const held of pendingReactions.values())
|
|
2135
|
+
if (held.requestId === rpcId)
|
|
2136
|
+
held.started = true;
|
|
2137
|
+
}
|
|
2138
|
+
if (event.type === "turn/end") {
|
|
2139
|
+
scheduledTurns.delete(session.id);
|
|
2140
|
+
const spoken = spokenAnswers.get(session.id);
|
|
2141
|
+
spokenAnswers.delete(session.id);
|
|
2142
|
+
if (spoken !== undefined) {
|
|
2143
|
+
const voiceBotId = rt.chatOwners.get(session.id);
|
|
2144
|
+
if (voiceBotId !== undefined) {
|
|
2145
|
+
for (const { conn, chatKey, chat } of replyTargets(ownerOrigins.get(voiceBotId), `bot:${voiceBotId}`)) {
|
|
2146
|
+
if (chat.kind !== "direct" || typeof rt.speak !== "function")
|
|
2147
|
+
continue;
|
|
2148
|
+
const settingsView = rt.ttsSettingsView?.();
|
|
2149
|
+
const spokenFormat = conn.platform === "feishu" ? "opus" : "mp3";
|
|
2150
|
+
const voiceCompanion = rt.companionOf?.(voiceBotId);
|
|
2151
|
+
void (async () => {
|
|
2152
|
+
try {
|
|
2153
|
+
const audio = await rt.speak(spoken.replace(/[*_`#>]+/g, ""), spokenFormat, voiceCompanion?.voiceId);
|
|
2154
|
+
await sendMedia(conn, chatKey, { key: chatKey, kind: chat.kind, title: chat.title }, [
|
|
2155
|
+
{
|
|
2156
|
+
kind: "file",
|
|
2157
|
+
name: audio.name,
|
|
2158
|
+
data: audio.bytes,
|
|
2159
|
+
voice: settingsView?.voiceItem === true,
|
|
2160
|
+
},
|
|
2161
|
+
], "");
|
|
2162
|
+
}
|
|
2163
|
+
catch (error) {
|
|
2164
|
+
rt.warn("ocean-crew: im spoken answer failed: %s", error?.message ?? error);
|
|
2165
|
+
}
|
|
2166
|
+
})();
|
|
2167
|
+
}
|
|
2168
|
+
}
|
|
2169
|
+
}
|
|
2170
|
+
const notify = notifyAnswers.get(session.id);
|
|
2171
|
+
notifyAnswers.delete(session.id);
|
|
2172
|
+
if (notify !== undefined && notify.trim() !== "") {
|
|
2173
|
+
const owner = rt.chatOwners.get(session.id);
|
|
2174
|
+
const bot = rt.botOf(owner);
|
|
2175
|
+
if (owner !== undefined && bot !== undefined) {
|
|
2176
|
+
const targets = replyTargets(ownerOrigins.get(owner), `bot:${owner}`);
|
|
2177
|
+
if (targets.length === 0) {
|
|
2178
|
+
rt.warn("ocean-crew: im reminder answer for %s has no chat to go to; a chat must talk to the Bot first", session.id);
|
|
2179
|
+
}
|
|
2180
|
+
for (const { conn, chatKey, chat } of targets)
|
|
2181
|
+
sendTo(conn, chatKey, { key: chatKey, kind: chat.kind, title: chat.title }, notify, undefined, undefined, undefined, {
|
|
2182
|
+
card: true,
|
|
2183
|
+
title: bot.name,
|
|
2184
|
+
});
|
|
2185
|
+
}
|
|
2186
|
+
}
|
|
2187
|
+
const held = windowAnswers.get(session.id);
|
|
2188
|
+
if (held !== undefined) {
|
|
2189
|
+
windowAnswers.delete(session.id);
|
|
2190
|
+
if (held.trim() !== "") {
|
|
2191
|
+
const owner = rt.chatOwners.get(session.id);
|
|
2192
|
+
if (owner !== undefined)
|
|
2193
|
+
for (const conn of Object.values(connections())) {
|
|
2194
|
+
if (!runners.has(conn.id) || conn.mirror !== "all")
|
|
2195
|
+
continue;
|
|
2196
|
+
for (const { chatKey, chat } of listeners(conn, { botId: owner }))
|
|
2197
|
+
sendTo(conn, chatKey, { key: chatKey, kind: chat.kind, title: chat.title }, held);
|
|
2198
|
+
}
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
// An aborted or interrupted turn gets no verdict: the processing mark is
|
|
2202
|
+
// removed and the message stays unmarked, the way dsh-im clears it.
|
|
2203
|
+
const kind = event.data?.reason?.kind;
|
|
2204
|
+
const outcome = kind === "error"
|
|
2205
|
+
? "error"
|
|
2206
|
+
: kind === "aborted" || kind === "interrupted" || kind === "blocked"
|
|
2207
|
+
? "clear"
|
|
2208
|
+
: "success";
|
|
2209
|
+
for (const [key, held] of pendingReactions)
|
|
2210
|
+
if (held.sessionId === session.id && held.started)
|
|
2211
|
+
finishReaction(key, outcome);
|
|
2212
|
+
}
|
|
2213
|
+
const botId = rt.chatOwners.get(session.id);
|
|
2214
|
+
if (botId === undefined) {
|
|
2215
|
+
imVia.delete(session.id);
|
|
2216
|
+
return;
|
|
2217
|
+
}
|
|
2218
|
+
const rpcId = event.type === "user/message" ? event.data?.source?.rpcId : undefined;
|
|
2219
|
+
if (typeof rpcId === "string" && rpcId.startsWith("im:") && Number.isInteger(event.seq)) {
|
|
2220
|
+
imVia.set(session.id, { ...imVia.get(session.id), [event.seq]: rpcId.split(":")[1] });
|
|
2221
|
+
}
|
|
2222
|
+
// Which request this turn belongs to: the rpc id DSH echoes on the user message.
|
|
2223
|
+
// A turn from the window clears the session's request so it cannot inherit an
|
|
2224
|
+
// older IM route.
|
|
2225
|
+
if (event.type === "turn/start") {
|
|
2226
|
+
const turn = event.data?.turn;
|
|
2227
|
+
if (typeof turn === "number" && Number.isInteger(turn)) {
|
|
2228
|
+
currentTurns.set(session.id, turn);
|
|
2229
|
+
const waiting = waitingTurns.get(session.id);
|
|
2230
|
+
if (waiting !== undefined) {
|
|
2231
|
+
waitingTurns.delete(session.id);
|
|
2232
|
+
bindTurn(session.id, turn, waiting);
|
|
2233
|
+
}
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
if (event.type === "turn/end") {
|
|
2237
|
+
currentTurns.delete(session.id);
|
|
2238
|
+
const owner = rt.chatOwners.get(session.id);
|
|
2239
|
+
if (owner !== undefined)
|
|
2240
|
+
stopTypingNow(owner);
|
|
2241
|
+
}
|
|
2242
|
+
if (event.type === "user/message" && event.data?.source?.kind === "schedule")
|
|
2243
|
+
scheduledTurns.add(session.id);
|
|
2244
|
+
if (event.type === "user/message" && event.data?.source?.kind === "user") {
|
|
2245
|
+
const turn = turnOf(session.id, event);
|
|
2246
|
+
const wanted = typeof rpcId === "string" && rpcId.startsWith("im:") ? rpcId : "";
|
|
2247
|
+
if (typeof rpcId === "string" && rpcId.startsWith("im:"))
|
|
2248
|
+
sessionOrigins.set(session.id, rpcId);
|
|
2249
|
+
else
|
|
2250
|
+
sessionOrigins.delete(session.id);
|
|
2251
|
+
if (turn === undefined) {
|
|
2252
|
+
// The start event has not arrived yet: keep the id and bind it when it does.
|
|
2253
|
+
waitingTurns.set(session.id, wanted);
|
|
2254
|
+
}
|
|
2255
|
+
else {
|
|
2256
|
+
bindTurn(session.id, turn, wanted);
|
|
2257
|
+
}
|
|
2258
|
+
}
|
|
2259
|
+
const requestId = requestFor(session.id, event);
|
|
2260
|
+
const targets = replyTargets(requestId, `bot:${botId}`);
|
|
2261
|
+
if (targets.length === 0) {
|
|
2262
|
+
// A Bot that owes IM an answer and has no route for this turn is a routing
|
|
2263
|
+
// failure, not a window turn: record why, without the answer's text.
|
|
2264
|
+
if (event.type === "assistant/message" && ownerOrigins.has(botId))
|
|
2265
|
+
rt.warn("ocean-crew: im answer for %s not routed (%s)", session.id, requestId === undefined ? "no turn binding" : "origin no longer resolves");
|
|
2266
|
+
// A turn that started in the window answers the window. A scheduled reminder's
|
|
2267
|
+
// answer is pushed to the chat that last talked to the Bot; an ordinary window
|
|
2268
|
+
// turn reaches IM only when the user asked for that (`imDeliverAnswers`), and
|
|
2269
|
+
// then as one final answer rather than every step.
|
|
2270
|
+
if (event.type === "assistant/message") {
|
|
2271
|
+
const scheduled = scheduledTurns.has(session.id);
|
|
2272
|
+
for (const item of rt.displayItems(session.id, [event])) {
|
|
2273
|
+
if (item.kind !== "bot" || item.text.trim() === "")
|
|
2274
|
+
continue;
|
|
2275
|
+
if (scheduled && rt.config?.imNotify !== false)
|
|
2276
|
+
notifyAnswers.set(session.id, item.text);
|
|
2277
|
+
if (rt.config?.imDeliverAnswers === true)
|
|
2278
|
+
windowAnswers.set(session.id, item.text);
|
|
2279
|
+
}
|
|
2280
|
+
}
|
|
2281
|
+
return;
|
|
2282
|
+
}
|
|
2283
|
+
const voiceSettings = rt.ttsSettingsView?.();
|
|
2284
|
+
// A companion always speaks its answer; everyone else only when the page asked.
|
|
2285
|
+
const companion = rt.companionOf?.(botId);
|
|
2286
|
+
const voiceAuto = voiceSettings?.enabled !== false && (voiceSettings?.autoReply === true || companion !== undefined);
|
|
2287
|
+
if (event.type === "assistant/message" && voiceAuto) {
|
|
2288
|
+
for (const item of rt.displayItems(session.id, [event]))
|
|
2289
|
+
if (item.kind === "bot" && item.text.trim() !== "" && item.text.length <= 300)
|
|
2290
|
+
spokenAnswers.set(session.id, item.text);
|
|
2291
|
+
}
|
|
2292
|
+
for (const item of rt.displayItems(session.id, [event])) {
|
|
2293
|
+
if (item.kind !== "bot" && item.kind !== "view")
|
|
2294
|
+
continue;
|
|
2295
|
+
const body = item.kind === "bot"
|
|
2296
|
+
? item.text
|
|
2297
|
+
: viewCardText({ title: item.title, view: item.view }) || (item.title ?? "");
|
|
2298
|
+
const replyTo = originOf(requestId)?.messageId;
|
|
2299
|
+
const title = rt.botOf(botId)?.name;
|
|
2300
|
+
for (const { conn, chatKey, chat } of targets)
|
|
2301
|
+
sendTo(conn, chatKey, { key: chatKey, kind: chat.kind, title: chat.title }, body, undefined, undefined, replyTo, { card: true, ...(title === undefined ? {} : { title }) });
|
|
2302
|
+
}
|
|
2303
|
+
});
|
|
2304
|
+
rt.onRoomLine((room, line) => {
|
|
2305
|
+
if (line.botId === undefined ||
|
|
2306
|
+
line.kind !== undefined ||
|
|
2307
|
+
typeof line.text !== "string" ||
|
|
2308
|
+
line.text.trim() === "")
|
|
2309
|
+
return;
|
|
2310
|
+
const body = `**${line.who}**: ${line.text}`;
|
|
2311
|
+
// A group's lines go to the group chat the work came from; a group with no IM
|
|
2312
|
+
// origin sends nothing, and a stale binding sends nothing either.
|
|
2313
|
+
const targets = replyTargets(ownerOrigins.get(room.id), `room:${room.id}`);
|
|
2314
|
+
for (const { conn, chatKey, chat } of targets)
|
|
2315
|
+
sendTo(conn, chatKey, { key: chatKey, kind: chat.kind, title: chat.title }, body, undefined, undefined, undefined, {
|
|
2316
|
+
card: true,
|
|
2317
|
+
title: room.name,
|
|
2318
|
+
});
|
|
2319
|
+
});
|
|
2320
|
+
rt.onApproval((kind, data) => {
|
|
2321
|
+
if (kind === "open") {
|
|
2322
|
+
void (async () => {
|
|
2323
|
+
for (const conn of Object.values(connections())) {
|
|
2324
|
+
const runner = runners.get(conn.id);
|
|
2325
|
+
if (runner === undefined)
|
|
2326
|
+
continue;
|
|
2327
|
+
const bot = rt.botOf(data.botId);
|
|
2328
|
+
// An approval goes to the chat whose request triggered it; an approval raised
|
|
2329
|
+
// in the window stays in the window.
|
|
2330
|
+
const targets = data.roomId !== undefined
|
|
2331
|
+
? replyTargets(ownerOrigins.get(String(data.roomId)), `room:${data.roomId}`)
|
|
2332
|
+
: replyTargets(ownerOrigins.get(String(data.botId)), `bot:${data.botId}`);
|
|
2333
|
+
const buttons = imPlatform(conn.platform)?.buttons === true ? cardButtons.approval(data.id) : undefined;
|
|
2334
|
+
await sendCard(conn, `a:${data.id}`, targets, cardText.approval(bot?.name ?? "?", data), buttons);
|
|
2335
|
+
}
|
|
2336
|
+
})().catch((error) => rt.warn("ocean-crew: im approval card failed: %s", error));
|
|
2337
|
+
return;
|
|
2338
|
+
}
|
|
2339
|
+
void (async () => {
|
|
2340
|
+
for (const conn of Object.values(connections())) {
|
|
2341
|
+
await settleCard(conn.id, `a:${data.id}`, data.outcome === "allowed-once"
|
|
2342
|
+
? text("allow")
|
|
2343
|
+
: data.outcome === "rejected"
|
|
2344
|
+
? text("reject")
|
|
2345
|
+
: text("answered"));
|
|
2346
|
+
await settledEdits(conn);
|
|
2347
|
+
}
|
|
2348
|
+
})().catch(() => { });
|
|
2349
|
+
});
|
|
2350
|
+
rt.onSaved(() => {
|
|
2351
|
+
void diffCards()
|
|
2352
|
+
.then(settleGone)
|
|
2353
|
+
.catch(() => { });
|
|
2354
|
+
void sync().catch(() => { });
|
|
2355
|
+
});
|
|
2356
|
+
let interval;
|
|
2357
|
+
ctx.effect(() => {
|
|
2358
|
+
interval = setInterval(() => {
|
|
2359
|
+
void rt
|
|
2360
|
+
.refresh()
|
|
2361
|
+
.then(() => sync())
|
|
2362
|
+
.catch(() => { });
|
|
2363
|
+
}, reconcileMs);
|
|
2364
|
+
interval.unref?.();
|
|
2365
|
+
void rt
|
|
2366
|
+
.load()
|
|
2367
|
+
.then(() => sync())
|
|
2368
|
+
.catch(() => { });
|
|
2369
|
+
return () => {
|
|
2370
|
+
stopped = true;
|
|
2371
|
+
clearInterval(interval);
|
|
2372
|
+
return Promise.all([...runners.keys()].map(stop)).then(async () => {
|
|
2373
|
+
for (const held of runtimes.values())
|
|
2374
|
+
if (held.timer !== undefined)
|
|
2375
|
+
clearTimeout(held.timer);
|
|
2376
|
+
for (const key of pendingReactions.keys())
|
|
2377
|
+
finishReaction(key, "clear");
|
|
2378
|
+
await Promise.all([...runtimes.keys()].map(writeRuntime)).catch(() => { });
|
|
2379
|
+
});
|
|
2380
|
+
};
|
|
2381
|
+
}, "ocean-crew: im");
|
|
2382
|
+
const imView = () => ({
|
|
2383
|
+
connections: Object.values(connections()).map(viewOf),
|
|
2384
|
+
platforms: IM_PLATFORMS.filter((platform) => adaptersFor().includes(platform.id)).map((platform) => platform.id),
|
|
2385
|
+
});
|
|
2386
|
+
const imStatusView = () => Object.fromEntries([...statuses.entries()].map(([id, status]) => [
|
|
2387
|
+
id,
|
|
2388
|
+
{
|
|
2389
|
+
state: status.state ?? "off",
|
|
2390
|
+
...(status.error !== undefined ? { error: status.error } : {}),
|
|
2391
|
+
attempts: status.attempts ?? 0,
|
|
2392
|
+
...(status.nextRetryAt > 0 ? { nextRetryAt: status.nextRetryAt } : {}),
|
|
2393
|
+
...(status.referenceId !== undefined ? { referenceId: status.referenceId } : {}),
|
|
2394
|
+
at: status.at,
|
|
2395
|
+
},
|
|
2396
|
+
]));
|
|
2397
|
+
// The owner a Session speaks for: the group chat it belongs to, or the Bot whose own
|
|
2398
|
+
// chat it is. Both kinds have their own IM origins, and only those decide where a
|
|
2399
|
+
// file goes.
|
|
2400
|
+
const ownerOfSession = (sessionId) => {
|
|
2401
|
+
const room = rt.roomOf(sessionId);
|
|
2402
|
+
if (room !== undefined)
|
|
2403
|
+
return room.id;
|
|
2404
|
+
const member = rt.groupOwners.get(sessionId);
|
|
2405
|
+
if (member !== undefined)
|
|
2406
|
+
return member.roomId;
|
|
2407
|
+
return rt.chatOwners.get(sessionId) ?? rt.pastOwners.get(sessionId)?.botId;
|
|
2408
|
+
};
|
|
2409
|
+
// Hand a file to the chats the current request came from. Nothing is broadcast: the
|
|
2410
|
+
// origin record of the turn decides the targets, exactly as a text answer does.
|
|
2411
|
+
const imSendFile = async (sessionId, file) => {
|
|
2412
|
+
const owner = ownerOfSession(sessionId);
|
|
2413
|
+
if (owner === undefined)
|
|
2414
|
+
return { sent: 0, reason: "this conversation is not linked to an IM chat" };
|
|
2415
|
+
const requestId = ownerOrigins.get(owner);
|
|
2416
|
+
const targets = replyTargets(requestId, rt.roomOf(owner) !== undefined ? `room:${owner}` : `bot:${owner}`);
|
|
2417
|
+
if (targets.length === 0)
|
|
2418
|
+
return { sent: 0, reason: "this conversation is not linked to an IM chat" };
|
|
2419
|
+
let data;
|
|
2420
|
+
try {
|
|
2421
|
+
data = await readFile(String(file.path ?? ""));
|
|
2422
|
+
}
|
|
2423
|
+
catch {
|
|
2424
|
+
throw Object.assign(new Error(`Cannot read ${String(file.path ?? "")}.`), { code: "bot/not-found" });
|
|
2425
|
+
}
|
|
2426
|
+
if (data.byteLength > MEDIA_LIMIT) {
|
|
2427
|
+
throw Object.assign(new Error(`The file is larger than ${MEDIA_LIMIT} bytes.`), { code: "bot/invalid" });
|
|
2428
|
+
}
|
|
2429
|
+
const name = String(file.name ?? file.path ?? "file")
|
|
2430
|
+
.split(/[\\/]/)
|
|
2431
|
+
.pop() || "file";
|
|
2432
|
+
const kind = IMAGE_EXT.test(name) ? "image" : "file";
|
|
2433
|
+
const mime = MIME_EXT[name.split(".").pop()?.toLowerCase() ?? ""] ?? "application/octet-stream";
|
|
2434
|
+
let sent = 0;
|
|
2435
|
+
for (const target of targets) {
|
|
2436
|
+
if (await sendMedia(target.conn, target.chatKey,
|
|
2437
|
+
// The adapter reads the chat's key from the message it is given; a stored
|
|
2438
|
+
// chat entry is keyed by chatKey and does not carry it back.
|
|
2439
|
+
{ ...target.chat, key: target.chatKey }, [{ kind, name, mime, data, ...(file.voice === true ? { voice: true } : {}) }], String(file.note ?? "")))
|
|
2440
|
+
sent += 1;
|
|
2441
|
+
}
|
|
2442
|
+
return { sent };
|
|
2443
|
+
};
|
|
2444
|
+
// Which audio container the chat behind this request can draw a voice message from:
|
|
2445
|
+
// Feishu only from opus, WeChat's own bubble from mp3 (and its client ignores bot
|
|
2446
|
+
// voice bubbles, so plain audio is a file there). Unknown chats get no preference.
|
|
2447
|
+
const imVoicePlan = (sessionId) => {
|
|
2448
|
+
const owner = ownerOfSession(sessionId);
|
|
2449
|
+
if (owner === undefined)
|
|
2450
|
+
return {};
|
|
2451
|
+
const requestId = ownerOrigins.get(owner);
|
|
2452
|
+
const targets = replyTargets(requestId, rt.roomOf(owner) !== undefined ? `room:${owner}` : `bot:${owner}`);
|
|
2453
|
+
const platform = targets[0]?.conn?.platform;
|
|
2454
|
+
if (platform === "feishu")
|
|
2455
|
+
return { platform, format: "opus" };
|
|
2456
|
+
if (platform === "weixin")
|
|
2457
|
+
return { platform, format: "mp3" };
|
|
2458
|
+
return { platform };
|
|
2459
|
+
};
|
|
2460
|
+
Object.assign(rt, { imView, imStatusView, imViaView, imEndpoint, imSendFile, imVoicePlan });
|
|
2461
|
+
}
|