limixbot 0.3.85 → 0.3.87
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/dist/assets/{ActivityPanel-CY3DMVp-.js → ActivityPanel-DkdXgQfr.js} +1 -1
- package/dist/assets/{App-DI8W0_B1.js → App-CrtsCVmH.js} +11 -11
- package/dist/assets/{AppEventEditor-C9Qgmcqo.js → AppEventEditor-DMjeLO4H.js} +1 -1
- package/dist/assets/{BotSettingsDialog-N3rwg9CM.js → BotSettingsDialog-B6WgIN7J.js} +4 -4
- package/dist/assets/{BrowserPanel-C9z6ln50.js → BrowserPanel-CS5s4Ptn.js} +1 -1
- package/dist/assets/{BrowserProfilesManager-DElUoXDu.js → BrowserProfilesManager-D_teHrAi.js} +1 -1
- package/dist/assets/{CloudAddDialog-CRpjAGCj.js → CloudAddDialog-LkwKZKWh.js} +1 -1
- package/dist/assets/{ComputerFilesPane-BDJLywsp.js → ComputerFilesPane-CtzVDlSu.js} +1 -1
- package/dist/assets/{ComputerPanel-Duwmvh1w.js → ComputerPanel-B-aOm0l2.js} +2 -2
- package/dist/assets/{DataPanel-B3lK9PV5.js → DataPanel-BdtZ6MUb.js} +1 -1
- package/dist/assets/{DesktopViewer-DucsZp1P.js → DesktopViewer-CgYhDeNl.js} +1 -1
- package/dist/assets/{FilesView-DxB66Gnb.js → FilesView-CHWTqPLe.js} +1 -1
- package/dist/assets/{GrokMoveDialog-k_oT2YNk.js → GrokMoveDialog-DAt5M0eU.js} +1 -1
- package/dist/assets/{InspectorPanel-CO62b8Q8.js → InspectorPanel-DRTh1PUj.js} +1 -1
- package/dist/assets/{KeyboardShortcutsModal-DhkUasuz.js → KeyboardShortcutsModal-DABEQbmE.js} +1 -1
- package/dist/assets/{LiveDesktop-DYWwUKmp.js → LiveDesktop-M2PEoZo3.js} +1 -1
- package/dist/assets/{LocalVmWorkspace-B4zzvT6u.js → LocalVmWorkspace-CB3d6qou.js} +1 -1
- package/dist/assets/{MacLocalControl-WEcE5FU_.js → MacLocalControl-CMvGhT8k.js} +1 -1
- package/dist/assets/{MarkdownFilePreview-CTQI00z9.js → MarkdownFilePreview-DOFsbPSE.js} +1 -1
- package/dist/assets/{MenuMotion-Cl1BSA8W.js → MenuMotion-B5569Tnn.js} +1 -1
- package/dist/assets/{NewBotDialog-DlwcOejs.js → NewBotDialog-CLH5zmyu.js} +1 -1
- package/dist/assets/{PhoneAppDialog-B1_HpF1k.js → PhoneAppDialog-DVR1kkqg.js} +1 -1
- package/dist/assets/{PlacesRail-CAIFKxcp.js → PlacesRail-CdoknPbW.js} +1 -1
- package/dist/assets/{PluginsPanel--rjuQ0H6.js → PluginsPanel-CSJMCmoH.js} +1 -1
- package/dist/assets/{ProIntroduction-CdOsoSZM.js → ProIntroduction-Bpk_1Lyo.js} +1 -1
- package/dist/assets/{RemoteAgentSettingsPanel-Csolmca6.js → RemoteAgentSettingsPanel-BQfkU33I.js} +1 -1
- package/dist/assets/{RoomPanel-BaFLHtNj.js → RoomPanel-CEyNSwJA.js} +1 -1
- package/dist/assets/{RoutinesPage-iMqTJGOf.js → RoutinesPage-BgVlfVUK.js} +1 -1
- package/dist/assets/{SettingsModal-BtDWTzKq.js → SettingsModal-DC9ixki-.js} +4 -4
- package/dist/assets/{ShareTeamDialog-DtbT-j7j.js → ShareTeamDialog-BaM3TtXl.js} +1 -1
- package/dist/assets/{SignedInSites-Dbs3HG-Q.js → SignedInSites-DdJOlxcg.js} +1 -1
- package/dist/assets/{TeamLibraryPanel-DQlHm6J-.js → TeamLibraryPanel-WKfDpzby.js} +1 -1
- package/dist/assets/{TeamMapPage-kr5Oy3kJ.js → TeamMapPage-D8yJO-vi.js} +1 -1
- package/dist/assets/{TriggersPage-EdBOOViK.js → TriggersPage-CQd7jW5P.js} +1 -1
- package/dist/assets/{VisibilitySection-D7kyfsMI.js → VisibilitySection-CvJp0baU.js} +1 -1
- package/dist/assets/{WebhookTrigger-CjsooYKr.js → WebhookTrigger-BmwkDA-k.js} +1 -1
- package/dist/assets/{WorksOnGrid-C-09lH3E.js → WorksOnGrid-CNOFKiSk.js} +1 -1
- package/dist/assets/{abnfDiagram-YUKMZFIV-DQc35yUD.js → abnfDiagram-YUKMZFIV-B9SjvRft.js} +1 -1
- package/dist/assets/{activity-Dg618nNT.js → activity-BPGTh7Yr.js} +1 -1
- package/dist/assets/{architectureDiagram-47P4ROYG-BWLmVb0p.js → architectureDiagram-47P4ROYG-Y0WZVEC3.js} +1 -1
- package/dist/assets/{blockDiagram-E7TT5TSB-D8Lymdty.js → blockDiagram-E7TT5TSB-DAW6D0Qs.js} +1 -1
- package/dist/assets/{c4Diagram-CRA5TL53-CqBonRGR.js → c4Diagram-CRA5TL53-DgWcfgoB.js} +1 -1
- package/dist/assets/{calendar-days-27drhnjb.js → calendar-days-BVL3PytA.js} +1 -1
- package/dist/assets/channel-CQNgKOiP.js +1 -0
- package/dist/assets/{chunk-2Q5K7J3B-ChgEJxQ5.js → chunk-2Q5K7J3B-ByA03FrM.js} +1 -1
- package/dist/assets/{chunk-5VM5RSS4-DfPS9PdA.js → chunk-5VM5RSS4-xlotTgqK.js} +1 -1
- package/dist/assets/{chunk-7TKQ45FW-DkiHHZ8j.js → chunk-7TKQ45FW-CRSVX3bq.js} +1 -1
- package/dist/assets/{chunk-AW2ZBBNX-DRfAiJSk.js → chunk-AW2ZBBNX-NOkQuH6L.js} +1 -1
- package/dist/assets/{chunk-FVRAUYC3-CdfnnJAQ.js → chunk-FVRAUYC3-C41aYIlD.js} +2 -2
- package/dist/assets/{chunk-HTAEGDNF-Dnh0-Y52.js → chunk-HTAEGDNF-BU9h9CEv.js} +1 -1
- package/dist/assets/{chunk-JWPE2WC7-8lxnA6bi.js → chunk-JWPE2WC7-CT3gNjpj.js} +1 -1
- package/dist/assets/{chunk-KQW6MTUR-BIzq4Y-p.js → chunk-KQW6MTUR-Bsrsqr8o.js} +1 -1
- package/dist/assets/{chunk-XXDRQBXY-DRs7oDfQ.js → chunk-XXDRQBXY-BEdihic8.js} +1 -1
- package/dist/assets/{classDiagram-v2-K4WV4PDN-RBLGePAK.js → classDiagram-v2-K4WV4PDN-CR2kibsx.js} +1 -1
- package/dist/assets/{coins-C03ikkSY.js → coins-RaJNnxHP.js} +1 -1
- package/dist/assets/{core-5NPWYsa0.js → core-zzdwGa8g.js} +1 -1
- package/dist/assets/{cose-bilkent-JH36ORCC-BUzR1SjN.js → cose-bilkent-JH36ORCC-DtmqNFAw.js} +1 -1
- package/dist/assets/{cynefin-EF2NZ3EQ-CkfAwvzQ.js → cynefin-EF2NZ3EQ-BF0iH3E2.js} +1 -1
- package/dist/assets/{cynefinDiagram-3GCD6N5R-yivOd-Z-.js → cynefinDiagram-3GCD6N5R-DZBlZC1t.js} +1 -1
- package/dist/assets/{dagre-W4DXFKR2-DhYpXfrc.js → dagre-W4DXFKR2-DcOBTJZY.js} +1 -1
- package/dist/assets/{diagram-2UJZ2QOL-BinJfjKp.js → diagram-2UJZ2QOL-BoSI7wwB.js} +1 -1
- package/dist/assets/{diagram-OVF4WLC6-CCfBmpAm.js → diagram-OVF4WLC6-Cv5bQOUs.js} +1 -1
- package/dist/assets/{diagram-PFPMY2P6-CGA_sfaF.js → diagram-PFPMY2P6-Q-K2R8az.js} +1 -1
- package/dist/assets/{diagram-UMYRVEAY-DJAerOP7.js → diagram-UMYRVEAY-C5eNciGi.js} +1 -1
- package/dist/assets/{diagram-YEKJPTXX-DPtRam5_.js → diagram-YEKJPTXX-T8jiq-7m.js} +1 -1
- package/dist/assets/{diagram-ZIFT7M5P-Bf_aLf0C.js → diagram-ZIFT7M5P-jbTTXiBP.js} +1 -1
- package/dist/assets/{ebnfDiagram-VR2GEFS7-Cv84sRvv.js → ebnfDiagram-VR2GEFS7-Dr0Hkm5F.js} +1 -1
- package/dist/assets/{elk-IJKZMXRS-CvR8VpdS.js → elk-IJKZMXRS-ldRwbMXT.js} +1 -1
- package/dist/assets/{erDiagram-O2IAPWRE-CBcxNnSV.js → erDiagram-O2IAPWRE-lKhPZdPw.js} +1 -1
- package/dist/assets/{file-up-BCABGJwK.js → file-up-CwDfYMJX.js} +1 -1
- package/dist/assets/{flowDiagram-OXPTDLAJ-CilpbI81.js → flowDiagram-OXPTDLAJ-Bt5ImuS3.js} +1 -1
- package/dist/assets/{ganttDiagram-R7TSEDQI-BKGrXVBk.js → ganttDiagram-R7TSEDQI-DMBEyO9r.js} +1 -1
- package/dist/assets/{gitGraphDiagram-XJZIOB7I-156g_l6W.js → gitGraphDiagram-XJZIOB7I-BMvaoeeq.js} +1 -1
- package/dist/assets/{import-name-D5boWNNJ.js → import-name-D1LCVLwI.js} +1 -1
- package/dist/assets/{index-EzRA1IPJ.js → index-CMr0udaA.js} +1 -1
- package/dist/assets/{index-Bpm_5xjV.js → index-DQ0s44-4.js} +3 -3
- package/dist/assets/{infoDiagram-5W2HQ5XZ-Dl2TtZUV.js → infoDiagram-5W2HQ5XZ-Dmqvt04E.js} +1 -1
- package/dist/assets/{ishikawaDiagram-K3B6WC7H-DNL9hgrO.js → ishikawaDiagram-K3B6WC7H-CJT3vX9x.js} +1 -1
- package/dist/assets/{journeyDiagram-COXZFDF6-Crken5SK.js → journeyDiagram-COXZFDF6-CvnvFNPC.js} +1 -1
- package/dist/assets/{kanban-definition-P3RFRI5V-CF0XCeak.js → kanban-definition-P3RFRI5V-B22QalMO.js} +1 -1
- package/dist/assets/{mcp-servers-fxhSbAs2.js → mcp-servers-BXM5JroY.js} +1 -1
- package/dist/assets/{mermaid.core-D6KTFPnQ.js → mermaid.core-Bi9UG8-A.js} +4 -4
- package/dist/assets/{mindmap-definition-LZFPQGKD-D8slW4Bp.js → mindmap-definition-LZFPQGKD-Bpn8jXlI.js} +1 -1
- package/dist/assets/{minimize-Z4D-5y66.js → minimize-D5wnKpNs.js} +1 -1
- package/dist/assets/{monitor-B1CfPgTM.js → monitor-BjT253V5.js} +1 -1
- package/dist/assets/{new-bot-DqeQOWb_.js → new-bot-2ScyUvzu.js} +1 -1
- package/dist/assets/{org-library-B3JevYPk.js → org-library-D4SRpwyj.js} +1 -1
- package/dist/assets/{package-format-DeLYSyIb.js → package-format-CbGiqQRv.js} +1 -1
- package/dist/assets/{pegDiagram-BGZESJAR-CFUn9jSb.js → pegDiagram-BGZESJAR-ICuaNcyM.js} +1 -1
- package/dist/assets/{pieDiagram-CAPJLFHJ-CTiSsNhc.js → pieDiagram-CAPJLFHJ-CYao5xUk.js} +1 -1
- package/dist/assets/{quadrantDiagram-GDMTTRAM-C0Jkn5WF.js → quadrantDiagram-GDMTTRAM-C0FS8s_p.js} +1 -1
- package/dist/assets/{rail-Ccbcb3BL.js → rail-DsihOtcm.js} +1 -1
- package/dist/assets/{railroadDiagram-SM67HX2B-D_IpHeXW.js → railroadDiagram-SM67HX2B-TctBdcVc.js} +1 -1
- package/dist/assets/{remote-desktop-panel-DWLI0Q3h.js → remote-desktop-panel-BJWPgCoR.js} +1 -1
- package/dist/assets/{requirementDiagram-X7JNWC4A-CB21o-IH.js → requirementDiagram-X7JNWC4A-RQZvFlYG.js} +1 -1
- package/dist/assets/{sankeyDiagram-UM26HJRW-CMw7Vupi.js → sankeyDiagram-UM26HJRW-jWzCokNA.js} +1 -1
- package/dist/assets/{sequenceDiagram-ZO4K6R2Y-BkTujesZ.js → sequenceDiagram-ZO4K6R2Y-Dxu99Xe8.js} +1 -1
- package/dist/assets/{sizeCapture-INFHLROL-m0eF2BDH.js → sizeCapture-INFHLROL-_c_UY82x.js} +1 -1
- package/dist/assets/{stateDiagram-v2-TBUQTH76-DWt2k1xB.js → stateDiagram-v2-TBUQTH76-BNp6TXer.js} +1 -1
- package/dist/assets/{styles-mQkR4Dk7.js → styles-BynJsW7f.js} +2 -2
- package/dist/assets/styles-D27-oaxn.css +1 -0
- package/dist/assets/{swimlanes-N4OXWK64-DDKG7xji.js → swimlanes-N4OXWK64-C531KJdm.js} +1 -1
- package/dist/assets/swimlanesDiagram-K3J5GTZL-C9zx7FHx.js +8 -0
- package/dist/assets/{team-share-BFEeBdTy.js → team-share-D2B4SYkY.js} +1 -1
- package/dist/assets/{timeline-definition-YOQAKGHF-F-4Q6Pp2.js → timeline-definition-YOQAKGHF-B1CW0VCv.js} +1 -1
- package/dist/assets/{usecaseDiagram-VIAY4XPW-IapiCDZW.js → usecaseDiagram-VIAY4XPW-P2aJy4-N.js} +1 -1
- package/dist/assets/{vennDiagram-BLWOH2XV-DmmEitR0.js → vennDiagram-BLWOH2XV-CsZhz-Sy.js} +1 -1
- package/dist/assets/{vi-D7L34hOg.js → vi-D0kn8wkm.js} +2 -2
- package/dist/assets/{wardleyDiagram-YMQ3BMBF-BLk95K7j.js → wardleyDiagram-YMQ3BMBF-BNZmEpP2.js} +1 -1
- package/dist/assets/{xychartDiagram-TAQBALBS-BEmo1yQH.js → xychartDiagram-TAQBALBS-BktSq943.js} +1 -1
- package/dist/index.html +18 -4
- package/dist/rail.html +5 -5
- package/dist-server/cloud-home-start.js +4 -3
- package/dist-server/index.js +1181 -1162
- package/dist-server/package.json +1 -1
- package/dist-server/server/agent-endpoint-models.js +7 -1
- package/dist-server/server/bot-api-host.js +30 -14
- package/dist-server/server/bot-channels/channel-media.js +68 -0
- package/dist-server/server/bot-channels/discord.js +13 -2
- package/dist-server/server/bot-channels/engine.js +40 -10
- package/dist-server/server/bot-channels/facebook.js +19 -3
- package/dist-server/server/bot-channels/messenger.js +35 -21
- package/dist-server/server/bot-channels/telegram.js +23 -2
- package/dist-server/server/bot-channels/zalo-media.js +37 -0
- package/dist-server/server/bot-channels/zalo.js +15 -3
- package/dist-server/server/claude-endpoints.js +1 -0
- package/dist-server/server/cloud-computer-tools.js +1 -1
- package/dist-server/server/cloud-home-start.js +1 -0
- package/dist-server/server/codex-endpoints.js +7 -1
- package/dist-server/server/plan-usage.js +1 -1
- package/dist-server/shared/provider-icon.js +1 -1
- package/package.json +1 -1
- package/dist/assets/channel-CWZV0evK.js +0 -1
- package/dist/assets/styles-jaNBMg3t.css +0 -1
- package/dist/assets/swimlanesDiagram-K3J5GTZL-DfVFf-EU.js +0 -8
package/dist-server/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"type":"module","version":"0.3.
|
|
1
|
+
{"type":"module","version":"0.3.87"}
|
|
@@ -79,7 +79,13 @@ export async function discoverAgentEndpointModels(entry, fetchImpl = fetch) {
|
|
|
79
79
|
: " Check that the gateway address is reachable from Limix Bot's server.";
|
|
80
80
|
throw failure((timeout ? "The request timed out." : "Limix Bot's server could not reach the gateway.") + localHint);
|
|
81
81
|
}
|
|
82
|
-
if (
|
|
82
|
+
if (response.status === 403) {
|
|
83
|
+
const detail = await readCatalog(response, 8_192).catch(() => null);
|
|
84
|
+
if (detail && /\bclient_not_allowed\b/i.test(detail)) {
|
|
85
|
+
throw failure("The gateway rejected this model-list client (HTTP 403, client_not_allowed). Enter the exact model ID from your working setup to save without model discovery.");
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
else if (!response.ok)
|
|
83
89
|
await response.body?.cancel().catch(() => { });
|
|
84
90
|
if (response.status === 401 || response.status === 403) {
|
|
85
91
|
throw failure(`The gateway rejected the API key (HTTP ${response.status}). Use the gateway's client API key, not a ChatGPT or Claude login token.`);
|
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
// The Bot API's two sides. Outside: `POST /hooks/api/bots/<id>/messages` on the webhook receiver, a bearer key, a
|
|
2
|
-
// message in, the bot's reply out; the turn it starts is outside work (the "api" trigger), so it never acts for the
|
|
3
|
-
// person, is told the message came from outside, and anything that needs an approval waits for the person in the thread.
|
|
4
|
-
// Inside: the app's routes to switch it on, mint a key and switch it off, open only to whoever may edit the bot.
|
|
5
1
|
import { z } from "zod";
|
|
6
2
|
import { redactSecretsInText } from "../shared/redact.js";
|
|
7
3
|
import { BOT_API_UPGRADE, botApiEndpoint } from "../shared/bot-api.js";
|
|
@@ -68,6 +64,13 @@ function replyText(lines) {
|
|
|
68
64
|
return "";
|
|
69
65
|
return redactSecretsInText(picked.map((line) => line.text.trim()).join("\n\n"));
|
|
70
66
|
}
|
|
67
|
+
function messagesAfter(lines, id) {
|
|
68
|
+
const start = lines.findIndex(line => line.id === id);
|
|
69
|
+
if (start < 0)
|
|
70
|
+
return [];
|
|
71
|
+
const end = lines.findIndex((line, index) => index > start && line.role === "user");
|
|
72
|
+
return lines.slice(start + 1, end < 0 ? undefined : end);
|
|
73
|
+
}
|
|
71
74
|
export function createBotApiHost(deps) {
|
|
72
75
|
const manager = deps.manager ?? new BotApiManager();
|
|
73
76
|
const waitMs = deps.waitMs ?? BOT_API_DEFAULT_WAIT_MS;
|
|
@@ -108,7 +111,17 @@ export function createBotApiHost(deps) {
|
|
|
108
111
|
return { thread: threadId, status: "working" };
|
|
109
112
|
return { reply: replyText(after), thread: threadId };
|
|
110
113
|
}
|
|
111
|
-
|
|
114
|
+
function mediaPrompt(text, file) {
|
|
115
|
+
if (!file)
|
|
116
|
+
return text;
|
|
117
|
+
const path = file.path.replaceAll("&", "&").replaceAll('"', """);
|
|
118
|
+
return text + '\n\n<attached-' + file.kind + ' path="' + path + '" />';
|
|
119
|
+
}
|
|
120
|
+
function replyMedia(lines) {
|
|
121
|
+
const reply = lines.findLast(line => line.role === "bot" && line.kind === "text");
|
|
122
|
+
return reply?.attachments?.filter((file) => (file.kind === "image" && !file.fromTool) || file.kind === "file") ?? [];
|
|
123
|
+
}
|
|
124
|
+
async function runCall(botId, call, turnStarted, channel) {
|
|
112
125
|
const store = deps.store;
|
|
113
126
|
let threadId = call.thread;
|
|
114
127
|
if (threadId !== undefined) {
|
|
@@ -135,13 +148,13 @@ export function createBotApiHost(deps) {
|
|
|
135
148
|
store.patchTask(botId, threadId, { botApi: true, outside: true });
|
|
136
149
|
}
|
|
137
150
|
const receivedAt = Date.now();
|
|
138
|
-
const userMessage = store.appendMessage(threadId, { role: "user", kind: "text", text: message, via: "api" });
|
|
139
|
-
const after = () =>
|
|
151
|
+
const userMessage = store.appendMessage(threadId, { role: "user", kind: "text", text: message, via: "api", ...(channel?.attachment ? { attachments: [channel.attachment] } : {}) });
|
|
152
|
+
const after = () => messagesAfter(store.messagesFor(threadId), userMessage.id);
|
|
140
153
|
let settled;
|
|
141
154
|
let dispatchError;
|
|
142
155
|
markRunning(botId, threadId, true);
|
|
143
156
|
try {
|
|
144
|
-
await deps.startTurn(botId, botApiPrompt(message, receivedAt), {
|
|
157
|
+
await deps.startTurn(botId, mediaPrompt(botApiPrompt(message, receivedAt), channel?.attachment), {
|
|
145
158
|
threadId, automationSource: "api", unattended: true, userMessage,
|
|
146
159
|
onSettled: (outcome) => { settled = outcome; markRunning(botId, threadId, false); },
|
|
147
160
|
onDispatchError: (message) => { dispatchError = message; markRunning(botId, threadId, false); },
|
|
@@ -171,6 +184,7 @@ export function createBotApiHost(deps) {
|
|
|
171
184
|
return { status: 202, body: { thread: threadId, status: "needs_approval" } };
|
|
172
185
|
if (!settled.ok)
|
|
173
186
|
fail(502, COULD_NOT_ANSWER, settled.text);
|
|
187
|
+
channel?.collect(replyMedia(after()));
|
|
174
188
|
return { status: 200, body: { reply: replyText(after()), thread: threadId } };
|
|
175
189
|
}
|
|
176
190
|
/** Limix: a message from a chat channel this server itself reads (server/bot-channels), never from an outside caller. The
|
|
@@ -181,9 +195,10 @@ export function createBotApiHost(deps) {
|
|
|
181
195
|
if (!input.owner) {
|
|
182
196
|
if (!deps.canConfine(botId))
|
|
183
197
|
fail(403, CANNOT_CONFINE);
|
|
184
|
-
|
|
198
|
+
let attachments = [];
|
|
199
|
+
const answer = await runCall(botId, { message: input.text, ...(input.threadId ? { thread: input.threadId } : {}), wait: Math.round((input.waitMs ?? 600_000) / 1000) }, () => { }, { attachment: input.attachment, collect(files) { attachments = files; } });
|
|
185
200
|
const body = answer.body;
|
|
186
|
-
return { threadId: body.thread, reply: body.reply ?? "", ...(body.status ? { status: body.status } : {}) };
|
|
201
|
+
return { threadId: body.thread, ...(attachments.length ? { attachments } : {}), reply: body.reply ?? "", ...(body.status ? { status: body.status } : {}) };
|
|
187
202
|
}
|
|
188
203
|
let threadId = input.threadId;
|
|
189
204
|
const known = threadId ? store.taskByThread(botId, threadId) : undefined;
|
|
@@ -199,13 +214,13 @@ export function createBotApiHost(deps) {
|
|
|
199
214
|
fail(404, "no such bot");
|
|
200
215
|
threadId = task.threadId;
|
|
201
216
|
}
|
|
202
|
-
const userMessage = store.appendMessage(threadId, { role: "user", kind: "text", text: input.text });
|
|
203
|
-
const after = () =>
|
|
217
|
+
const userMessage = store.appendMessage(threadId, { role: "user", kind: "text", text: input.text, ...(input.attachment ? { attachments: [input.attachment] } : {}) });
|
|
218
|
+
const after = () => messagesAfter(store.messagesFor(threadId), userMessage.id);
|
|
204
219
|
let settled;
|
|
205
220
|
let dispatchError;
|
|
206
221
|
markRunning(botId, threadId, true);
|
|
207
222
|
try {
|
|
208
|
-
await deps.startTurn(botId, input.text, {
|
|
223
|
+
await deps.startTurn(botId, mediaPrompt(input.text, input.attachment), {
|
|
209
224
|
threadId, unattended: true, userMessage,
|
|
210
225
|
onSettled: (outcome) => { settled = outcome; markRunning(botId, threadId, false); },
|
|
211
226
|
onDispatchError: (message) => { dispatchError = message; markRunning(botId, threadId, false); },
|
|
@@ -229,7 +244,8 @@ export function createBotApiHost(deps) {
|
|
|
229
244
|
}
|
|
230
245
|
if (!settled.ok)
|
|
231
246
|
fail(502, COULD_NOT_ANSWER, settled.text);
|
|
232
|
-
|
|
247
|
+
const attachments = replyMedia(after());
|
|
248
|
+
return { threadId, reply: replyText(after()), ...(attachments.length ? { attachments } : {}) };
|
|
233
249
|
}
|
|
234
250
|
const door = async (req, res, url) => {
|
|
235
251
|
const match = PUBLIC_PATH.exec(url.pathname);
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { lstat, readFile } from "node:fs/promises";
|
|
2
|
+
import { basename, dirname } from "node:path";
|
|
3
|
+
import { Readable } from "node:stream";
|
|
4
|
+
import { imageDimensions } from "../../shared/provider-icon.js";
|
|
5
|
+
import { ATTACHMENTS_DIR, IMAGE_MAX_BYTES, sanitizeSharedFileName, saveFile, saveImage } from "../attachments.js";
|
|
6
|
+
import { mimeFor } from "../message-file.js";
|
|
7
|
+
import { fetchPublicPage } from "../wait-probes.js";
|
|
8
|
+
export const CHANNEL_FILE_LIMIT = 10 * 1024 * 1024;
|
|
9
|
+
const imageTypes = ["image/jpeg", "image/png", "image/webp"];
|
|
10
|
+
export async function storeChannelMedia(bytes, name, limit = CHANNEL_FILE_LIMIT) {
|
|
11
|
+
if (!bytes.length || bytes.length > limit)
|
|
12
|
+
throw Error("Attachment size is unsupported");
|
|
13
|
+
const mime = bytes.length <= IMAGE_MAX_BYTES ? imageTypes.find(type => imageDimensions(bytes, type)) : undefined;
|
|
14
|
+
if (mime) {
|
|
15
|
+
const file = saveImage(bytes, mime);
|
|
16
|
+
return { kind: "image", path: file.path, mime, name: sanitizeSharedFileName(name, mime) };
|
|
17
|
+
}
|
|
18
|
+
const stored = await saveFile(Readable.from([bytes]), name, mimeFor(name), { expectedBytes: bytes.length });
|
|
19
|
+
return { kind: "file", path: stored.path, name: stored.name, mime: stored.mime };
|
|
20
|
+
}
|
|
21
|
+
export async function fetchChannelMedia(url, domains, name, limit = CHANNEL_FILE_LIMIT) {
|
|
22
|
+
const target = new URL(url);
|
|
23
|
+
if (target.protocol !== "https:" || target.port || !domains.some(domain => target.hostname === domain || target.hostname.endsWith("." + domain))) {
|
|
24
|
+
throw Error("Unsupported attachment address");
|
|
25
|
+
}
|
|
26
|
+
const page = await fetchPublicPage(url, { maxBytes: limit + 1, timeoutMs: 30_000, maxRedirects: 0 });
|
|
27
|
+
if (!page.ok || page.headers["content-type"]?.startsWith("text/html"))
|
|
28
|
+
throw Error("Attachment unavailable");
|
|
29
|
+
return storeChannelMedia(page.body, name, limit);
|
|
30
|
+
}
|
|
31
|
+
export async function readChannelMedia(file, limit = CHANNEL_FILE_LIMIT) {
|
|
32
|
+
if (dirname(file.path) !== ATTACHMENTS_DIR || !/^[0-9a-f-]{36}\.[a-z0-9]{1,10}$/i.test(basename(file.path))) {
|
|
33
|
+
throw Error("Unsupported attachment path");
|
|
34
|
+
}
|
|
35
|
+
const stat = await lstat(file.path);
|
|
36
|
+
if (!stat.isFile() || !stat.size || stat.size > limit)
|
|
37
|
+
throw Error("Attachment size is unsupported");
|
|
38
|
+
const data = await readFile(file.path);
|
|
39
|
+
if (data.length > limit)
|
|
40
|
+
throw Error("Attachment size is unsupported");
|
|
41
|
+
return { data, filename: sanitizeSharedFileName(file.name ?? basename(file.path), file.mime), mime: file.mime };
|
|
42
|
+
}
|
|
43
|
+
export function channelFileBlob(file) {
|
|
44
|
+
return new Blob([Uint8Array.from(file.data)], { type: file.mime });
|
|
45
|
+
}
|
|
46
|
+
export async function readChannelDownload(response) {
|
|
47
|
+
if (!response.ok || !response.body || Number(response.headers.get("content-length")) > CHANNEL_FILE_LIMIT) {
|
|
48
|
+
await response.body?.cancel();
|
|
49
|
+
throw Error("Attachment unavailable");
|
|
50
|
+
}
|
|
51
|
+
const reader = response.body.getReader();
|
|
52
|
+
const chunks = [];
|
|
53
|
+
let size = 0;
|
|
54
|
+
try {
|
|
55
|
+
for (;;) {
|
|
56
|
+
const { done, value } = await reader.read();
|
|
57
|
+
if (done)
|
|
58
|
+
return Buffer.concat(chunks, size);
|
|
59
|
+
size += value.length;
|
|
60
|
+
if (size > CHANNEL_FILE_LIMIT)
|
|
61
|
+
throw Error("Attachment size is unsupported");
|
|
62
|
+
chunks.push(value);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
await reader.cancel().catch(() => { });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// asked for: Discord still hands a bot the text of direct messages and of messages that mention it, which is all it answers.
|
|
3
3
|
import WebSocket from "ws";
|
|
4
4
|
import { ChannelError, wait } from "./engine.js";
|
|
5
|
+
import { channelFileBlob, fetchChannelMedia, readChannelMedia } from "./channel-media.js";
|
|
5
6
|
const API = "https://discord.com/api/v10";
|
|
6
7
|
const GATEWAY = "wss://gateway.discord.gg/?v=10&encoding=json";
|
|
7
8
|
const INTENTS = (1 << 9) | (1 << 12);
|
|
@@ -15,7 +16,8 @@ export function discordAdapter(options = {}) {
|
|
|
15
16
|
const openSocket = options.openSocket ?? ((url) => new WebSocket(url));
|
|
16
17
|
const sleep = options.sleep ?? wait;
|
|
17
18
|
async function rest(token, method, path, body) {
|
|
18
|
-
const
|
|
19
|
+
const multipart = body instanceof FormData;
|
|
20
|
+
const response = await call(`${API}${path}`, { method, redirect: "error", headers: { authorization: `Bot ${token}`, ...(body && !multipart ? { "content-type": "application/json" } : {}) }, ...(body ? { body: multipart ? body : JSON.stringify(body) } : {}) })
|
|
19
21
|
.catch((error) => { throw new ChannelError("retry", `Discord: ${error instanceof Error ? error.message : String(error)}`); });
|
|
20
22
|
if (response.ok)
|
|
21
23
|
return response.status === 204 ? null : response.json().catch(() => null);
|
|
@@ -49,11 +51,13 @@ export function discordAdapter(options = {}) {
|
|
|
49
51
|
const mentioned = Array.isArray(event.mentions) && event.mentions.some((user) => user?.id === self);
|
|
50
52
|
if (!direct && !mentioned)
|
|
51
53
|
return null;
|
|
54
|
+
const attachment = Array.isArray(event.attachments) ? event.attachments[0] : undefined;
|
|
52
55
|
return {
|
|
53
56
|
id: String(event.id), chatId: String(event.channel_id), direct,
|
|
54
57
|
from: { id: String(event.author.id), name: event.member?.nick ?? event.author.global_name ?? event.author.username ?? String(event.author.id) },
|
|
55
58
|
text: String(event.content ?? "").replace(new RegExp(`<@!?${self}>`, "g"), "").trim(),
|
|
56
|
-
...(
|
|
59
|
+
...(attachment ? { media: true } : {}),
|
|
60
|
+
...(typeof attachment?.url === "string" ? { loadMedia: () => fetchChannelMedia(attachment.url, ["cdn.discordapp.com", "media.discordapp.net"], attachment.filename ?? "attachment.bin") } : {}),
|
|
57
61
|
};
|
|
58
62
|
};
|
|
59
63
|
/** One Gateway connection; resolves when it closes in a way worth reconnecting after. */
|
|
@@ -145,6 +149,13 @@ export function discordAdapter(options = {}) {
|
|
|
145
149
|
return {
|
|
146
150
|
done,
|
|
147
151
|
send: async (chatId, text) => { await rest(token, "POST", `/channels/${chatId}/messages`, { content: text, allowed_mentions: { parse: [] } }); },
|
|
152
|
+
sendMedia: async (chatId, attachment) => {
|
|
153
|
+
const file = await readChannelMedia(attachment);
|
|
154
|
+
const form = new FormData();
|
|
155
|
+
form.set("payload_json", JSON.stringify({ allowed_mentions: { parse: [] }, attachments: [{ id: 0, filename: file.filename }] }));
|
|
156
|
+
form.set("files[0]", channelFileBlob(file), file.filename);
|
|
157
|
+
await rest(token, "POST", `/channels/${chatId}/messages`, form);
|
|
158
|
+
},
|
|
148
159
|
typing: async (chatId) => { await rest(token, "POST", `/channels/${chatId}/typing`); },
|
|
149
160
|
};
|
|
150
161
|
},
|
|
@@ -28,6 +28,7 @@ const botSchema = z.object({
|
|
|
28
28
|
name: z.string().default(""),
|
|
29
29
|
enabled: z.boolean().default(true),
|
|
30
30
|
access: z.enum(["owner", "everyone"]).default("owner"),
|
|
31
|
+
groupMentions: z.boolean().optional(),
|
|
31
32
|
owner: z.object({ id: z.union([z.string(), z.number()]).transform(String), name: z.string() }).optional(),
|
|
32
33
|
link: z.object({ hash: z.string(), expiresAt: z.number() }).optional(),
|
|
33
34
|
offset: z.number().default(0),
|
|
@@ -41,7 +42,7 @@ const text = (label) => ({
|
|
|
41
42
|
badCode: `Mã không đúng hoặc đã hết hạn. Tạo mã mới trong app Limix: bot → Cài đặt → ${label}.`,
|
|
42
43
|
linkHere: "Hãy gửi /link MÃ trong tin nhắn riêng với bot.",
|
|
43
44
|
ownerOnly: "Bot này hiện chỉ trả lời chủ bot.",
|
|
44
|
-
textOnly: "
|
|
45
|
+
textOnly: "Bot chưa nhận được nội dung đọc được. Bạn hãy gửi chữ, ảnh hoặc tệp đính kèm.",
|
|
45
46
|
fresh: "Đã bắt đầu cuộc trò chuyện mới.",
|
|
46
47
|
approval: "Bot đang chờ bạn duyệt một bước trong app Limix.",
|
|
47
48
|
working: "Bot vẫn đang làm việc này. Xem kết quả trong app Limix.",
|
|
@@ -192,7 +193,7 @@ export function createBotChannels(deps) {
|
|
|
192
193
|
if (!entry)
|
|
193
194
|
return;
|
|
194
195
|
const send = (body) => reply(adapter, botId, session, message.chatId, body);
|
|
195
|
-
const command = /^\/(\w+)(?:@\w+)?(?:\s+(.*))?$/s.exec(message.text.trim());
|
|
196
|
+
const command = message.media ? null : /^\/(\w+)(?:@\w+)?(?:\s+(.*))?$/s.exec(message.text.trim());
|
|
196
197
|
if (command?.[1] === "start" && !command[2])
|
|
197
198
|
return void await send(say.start);
|
|
198
199
|
if (command?.[1] === "link") {
|
|
@@ -208,24 +209,45 @@ export function createBotChannels(deps) {
|
|
|
208
209
|
return void await send(say.linked);
|
|
209
210
|
}
|
|
210
211
|
const owner = message.direct && !adapter.guestsOnly && entry.owner?.id === message.from.id;
|
|
211
|
-
|
|
212
|
+
const everyone = entry.access === "everyone";
|
|
213
|
+
const allowsGuest = kind === "zalo" && !message.direct ? entry.groupMentions ?? everyone : everyone;
|
|
214
|
+
if (!owner && !allowsGuest)
|
|
212
215
|
return message.direct && !adapter.quietToStrangers ? void await send(say.ownerOnly) : undefined;
|
|
213
216
|
const conversation = message.direct ? message.chatId : `${message.chatId}:${message.from.id}`;
|
|
214
217
|
if (command?.[1] === "new") {
|
|
215
218
|
patch(kind, botId, (current) => { const chats = { ...current.chats }; delete chats[conversation]; return { ...current, chats }; });
|
|
216
219
|
return void await send(say.fresh);
|
|
217
220
|
}
|
|
218
|
-
if (!message.text.trim())
|
|
221
|
+
if (!message.text.trim() && !message.loadMedia)
|
|
219
222
|
return void await send(say.textOnly);
|
|
220
223
|
const pulse = () => void session.typing?.(message.chatId).catch(() => { });
|
|
221
224
|
pulse();
|
|
222
225
|
const typing = setInterval(pulse, 4_000);
|
|
223
226
|
try {
|
|
224
227
|
const known = read(kind).bots[botId]?.chats[conversation];
|
|
225
|
-
|
|
228
|
+
let attachment;
|
|
229
|
+
try {
|
|
230
|
+
attachment = await message.loadMedia?.();
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
return void await send("Bot chưa tải được tệp này. Bạn hãy thử gửi lại hoặc gửi tệp nhỏ hơn.");
|
|
234
|
+
}
|
|
235
|
+
const answer = await deps.ask(botId, { text: message.text || (attachment?.kind === "image" ? "Ảnh đính kèm" : "Tệp đính kèm"), ...(attachment ? { attachment } : {}), ...(known ? { threadId: known } : {}), title: `${adapter.label} · ${message.from.name}`, owner });
|
|
226
236
|
patch(kind, botId, (current) => ({ ...current, chats: { ...current.chats, [conversation]: answer.threadId } }));
|
|
227
237
|
clearInterval(typing);
|
|
228
|
-
|
|
238
|
+
const sendMedia = session.sendMedia;
|
|
239
|
+
const media = sendMedia ? answer.attachments ?? [] : [];
|
|
240
|
+
if (sendMedia)
|
|
241
|
+
for (const file of media) {
|
|
242
|
+
try {
|
|
243
|
+
await paced(adapter, botId, () => sendMedia(message.chatId, file));
|
|
244
|
+
}
|
|
245
|
+
catch {
|
|
246
|
+
await send("Bot chưa gửi được một tệp đính kèm qua kênh này.");
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
if (answer.reply.trim() || !media.length)
|
|
250
|
+
await send(answer.reply.trim() || (answer.status === "needs_approval" ? say.approval : answer.status === "working" ? say.working : say.empty));
|
|
229
251
|
}
|
|
230
252
|
catch (error) {
|
|
231
253
|
log(`${kind}: ${failure(error)}`);
|
|
@@ -304,6 +326,7 @@ export function createBotChannels(deps) {
|
|
|
304
326
|
return { connected: false, ...(login ? { login } : {}) };
|
|
305
327
|
return {
|
|
306
328
|
connected: true, username: entry.username, name: entry.name, enabled: entry.enabled, access: entry.access,
|
|
329
|
+
...(kind === "zalo" ? { groupMentions: entry.groupMentions ?? entry.access === "everyone" } : {}),
|
|
307
330
|
...(entry.owner ? { owner: entry.owner.name } : {}),
|
|
308
331
|
...(entry.link && entry.link.expiresAt > now() ? { linkExpiresAt: entry.link.expiresAt } : {}),
|
|
309
332
|
...(entry.error ? { error: entry.error } : {}),
|
|
@@ -319,6 +342,7 @@ export function createBotChannels(deps) {
|
|
|
319
342
|
const sameAccount = kept?.username === account.username;
|
|
320
343
|
data.bots[botId] = botSchema.parse({
|
|
321
344
|
sealed: seal(secret), username: account.username, name: account.name, enabled: true, access: kept?.access ?? (adapter.guestsOnly ? "everyone" : "owner"),
|
|
345
|
+
groupMentions: kept?.groupMentions,
|
|
322
346
|
...(kept?.owner ? { owner: kept.owner } : {}), offset: sameAccount ? kept.offset : 0, chats: sameAccount ? kept.chats : {},
|
|
323
347
|
});
|
|
324
348
|
write(kind, data);
|
|
@@ -343,7 +367,7 @@ export function createBotChannels(deps) {
|
|
|
343
367
|
current.state = { error: failure(error) }; });
|
|
344
368
|
}
|
|
345
369
|
const PATH = /^\/api\/bots\/([\w-]{1,128})\/(telegram|discord|zalo|facebook|messenger)(?:\/(link|unlink|login))?$/;
|
|
346
|
-
const changeSchema = z.object({ token: z.string().max(400).optional(), enabled: z.boolean().optional(), access: z.enum(["owner", "everyone"]).optional() }).strict();
|
|
370
|
+
const changeSchema = z.object({ token: z.string().max(400).optional(), enabled: z.boolean().optional(), access: z.enum(["owner", "everyone"]).optional(), groupMentions: z.boolean().optional() }).strict();
|
|
347
371
|
const routes = async ({ req, res, path, method, auth, json, readBody }) => {
|
|
348
372
|
const match = PATH.exec(path);
|
|
349
373
|
if (!match || !adapters.has(match[2]))
|
|
@@ -387,15 +411,21 @@ export function createBotChannels(deps) {
|
|
|
387
411
|
return json(res, 200, view(kind, botId));
|
|
388
412
|
}
|
|
389
413
|
const parsed = changeSchema.safeParse(await readBody(req));
|
|
390
|
-
if (!parsed.success)
|
|
414
|
+
if (!parsed.success || (kind !== "zalo" && parsed.data.groupMentions !== undefined))
|
|
391
415
|
return json(res, 400, { error: "invalid request" });
|
|
392
416
|
if (parsed.data.token !== undefined) {
|
|
393
417
|
if (deps.logins?.[kind])
|
|
394
418
|
return json(res, 400, { error: "invalid request" });
|
|
395
419
|
await connect(kind, botId, parsed.data.token.trim());
|
|
396
420
|
}
|
|
397
|
-
|
|
398
|
-
|
|
421
|
+
const { enabled, access, groupMentions } = parsed.data;
|
|
422
|
+
if (enabled !== undefined || access !== undefined || groupMentions !== undefined) {
|
|
423
|
+
patch(kind, botId, (current) => ({
|
|
424
|
+
...current,
|
|
425
|
+
enabled: enabled ?? current.enabled,
|
|
426
|
+
access: access ?? current.access,
|
|
427
|
+
groupMentions: groupMentions ?? current.groupMentions,
|
|
428
|
+
}));
|
|
399
429
|
if (parsed.data.enabled === false)
|
|
400
430
|
halt(kind, botId);
|
|
401
431
|
else
|
|
@@ -2,11 +2,12 @@
|
|
|
2
2
|
// Page's conversations, so no webhook address is needed; Meta counts each call against the Page's daily rate budget
|
|
3
3
|
// (about 4,800 calls per engaged person per day), which is what sets the poll interval.
|
|
4
4
|
import { ChannelError, wait } from "./engine.js";
|
|
5
|
+
import { channelFileBlob, fetchChannelMedia, readChannelMedia } from "./channel-media.js";
|
|
5
6
|
const GRAPH = "https://graph.facebook.com/v23.0";
|
|
6
7
|
const BUSY_MS = 8_000;
|
|
7
8
|
const IDLE_MS = 20_000;
|
|
8
9
|
const BUSY_FOR_MS = 3 * 60_000;
|
|
9
|
-
const FIELDS = "updated_time,messages.limit(5){id,message,from,created_time,attachments}";
|
|
10
|
+
const FIELDS = "updated_time,messages.limit(5){id,message,from,created_time,attachments{name,image_data,file_url,video_data}}";
|
|
10
11
|
export function facebookAdapter(options = {}) {
|
|
11
12
|
const call = options.fetch ?? fetch;
|
|
12
13
|
const sleep = options.sleep ?? wait;
|
|
@@ -15,9 +16,10 @@ export function facebookAdapter(options = {}) {
|
|
|
15
16
|
const url = new URL(`${GRAPH}${path}`);
|
|
16
17
|
if (method === "GET")
|
|
17
18
|
url.searchParams.set("access_token", token);
|
|
19
|
+
const multipart = body instanceof FormData;
|
|
18
20
|
const response = await call(url, {
|
|
19
|
-
method, ...(signal ? { signal } : {}),
|
|
20
|
-
...(method === "POST" ? { headers: { "content-type": "application/json"
|
|
21
|
+
method, redirect: "error", ...(signal ? { signal } : {}),
|
|
22
|
+
...(method === "POST" ? { headers: { authorization: `Bearer ${token}`, ...(!multipart ? { "content-type": "application/json" } : {}) }, body: multipart ? body : JSON.stringify(body ?? {}) } : {}),
|
|
21
23
|
}).catch((error) => { throw new ChannelError("retry", `Facebook: ${(error instanceof Error ? error.message : String(error)).replaceAll(token, "…")}`); });
|
|
22
24
|
const data = await response.json().catch(() => ({}));
|
|
23
25
|
if (response.ok && !data.error)
|
|
@@ -65,11 +67,15 @@ export function facebookAdapter(options = {}) {
|
|
|
65
67
|
const at = Date.parse(message.created_time);
|
|
66
68
|
if (!(at > since) || !message.from?.id || String(message.from.id) === self)
|
|
67
69
|
continue;
|
|
70
|
+
const attachment = message.attachments?.data?.[0];
|
|
71
|
+
const remoteFile = attachment?.file_url ?? attachment?.image_data?.url ?? attachment?.video_data?.url;
|
|
72
|
+
const filename = attachment?.name || (attachment?.image_data ? "image.jpg" : attachment?.video_data ? "video.mp4" : "attachment.bin");
|
|
68
73
|
fresh.push({
|
|
69
74
|
at, id: String(message.id), chatId: String(message.from.id), direct: true,
|
|
70
75
|
from: { id: String(message.from.id), name: String(message.from.name ?? message.from.id) },
|
|
71
76
|
text: typeof message.message === "string" ? message.message : "",
|
|
72
77
|
...(message.attachments?.data?.length ? { media: true } : {}),
|
|
78
|
+
...(typeof remoteFile === "string" ? { loadMedia: () => fetchChannelMedia(remoteFile, ["fbcdn.net", "fbsbx.com", "facebook.com"], filename) } : {}),
|
|
73
79
|
});
|
|
74
80
|
}
|
|
75
81
|
}
|
|
@@ -87,6 +93,16 @@ export function facebookAdapter(options = {}) {
|
|
|
87
93
|
return {
|
|
88
94
|
done,
|
|
89
95
|
send: async (chatId, text) => { await graph(token, "POST", "/me/messages", { recipient: { id: chatId }, messaging_type: "RESPONSE", message: { text } }); },
|
|
96
|
+
sendMedia: async (chatId, attachment) => {
|
|
97
|
+
const file = await readChannelMedia(attachment);
|
|
98
|
+
const type = attachment.kind === "image" ? "image" : file.mime === "video/mp4" ? "video" : "file";
|
|
99
|
+
const form = new FormData();
|
|
100
|
+
form.set("recipient", JSON.stringify({ id: chatId }));
|
|
101
|
+
form.set("messaging_type", "RESPONSE");
|
|
102
|
+
form.set("message", JSON.stringify({ attachment: { type, payload: { is_reusable: false } } }));
|
|
103
|
+
form.set("filedata", channelFileBlob(file), file.filename);
|
|
104
|
+
await graph(token, "POST", "/me/messages", form, AbortSignal.timeout(60_000));
|
|
105
|
+
},
|
|
90
106
|
typing: async (chatId) => { await graph(token, "POST", "/me/messages", { recipient: { id: chatId }, sender_action: "typing_on" }); },
|
|
91
107
|
};
|
|
92
108
|
},
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { PASS } from "../routes/table.js";
|
|
2
2
|
import { ChannelError } from "./engine.js";
|
|
3
|
+
import { fetchChannelMedia, readChannelMedia } from "./channel-media.js";
|
|
3
4
|
const OUTBOX_WAIT_MS = 25_000;
|
|
4
5
|
const SEND_WAIT_MS = 90_000;
|
|
5
6
|
export function messengerBridge(options) {
|
|
@@ -39,25 +40,32 @@ export function messengerBridge(options) {
|
|
|
39
40
|
wake();
|
|
40
41
|
resolve();
|
|
41
42
|
}, { once: true }));
|
|
43
|
+
const enqueue = (chatId, text, file) => new Promise((resolve, reject) => {
|
|
44
|
+
if (io.signal.aborted)
|
|
45
|
+
return reject(new ChannelError("drop", "Messenger: stopped"));
|
|
46
|
+
const id = ++nextId;
|
|
47
|
+
const timer = setTimeout(() => item.settle("timeout"), SEND_WAIT_MS);
|
|
48
|
+
const item = { id, chatId, text, file, settle: (error) => {
|
|
49
|
+
clearTimeout(timer);
|
|
50
|
+
pending.delete(id);
|
|
51
|
+
bridge.outbox = bridge.outbox.filter((each) => each !== item);
|
|
52
|
+
if (error)
|
|
53
|
+
reject(new ChannelError(error === "timeout" ? "retry" : "drop", `Messenger: ${error}`));
|
|
54
|
+
else
|
|
55
|
+
resolve();
|
|
56
|
+
} };
|
|
57
|
+
pending.set(id, item);
|
|
58
|
+
bridge.outbox.push(item);
|
|
59
|
+
for (const wake of bridge.waiters.splice(0))
|
|
60
|
+
wake();
|
|
61
|
+
});
|
|
42
62
|
return {
|
|
43
63
|
done,
|
|
44
|
-
send:
|
|
45
|
-
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
pending.delete(id);
|
|
50
|
-
bridge.outbox = bridge.outbox.filter((each) => each !== item);
|
|
51
|
-
if (error)
|
|
52
|
-
reject(new ChannelError(error === "timeout" ? "retry" : "drop", `Messenger: ${error}`));
|
|
53
|
-
else
|
|
54
|
-
resolve();
|
|
55
|
-
} };
|
|
56
|
-
pending.set(id, item);
|
|
57
|
-
bridge.outbox.push(item);
|
|
58
|
-
for (const wake of bridge.waiters.splice(0))
|
|
59
|
-
wake();
|
|
60
|
-
}),
|
|
64
|
+
send: enqueue,
|
|
65
|
+
sendMedia: async (chatId, media) => {
|
|
66
|
+
const file = await readChannelMedia(media);
|
|
67
|
+
await enqueue(chatId, "", { name: file.filename, base64: file.data.toString("base64") });
|
|
68
|
+
},
|
|
61
69
|
};
|
|
62
70
|
},
|
|
63
71
|
};
|
|
@@ -80,15 +88,17 @@ export function messengerBridge(options) {
|
|
|
80
88
|
if (!bridge.outbox.length)
|
|
81
89
|
await new Promise((resolve) => { const timer = setTimeout(resolve, OUTBOX_WAIT_MS); bridge.waiters.push(() => { clearTimeout(timer); resolve(); }); });
|
|
82
90
|
bridge.io.healthy();
|
|
83
|
-
return json(res, 200, { items: bridge.outbox.map(({ id, chatId, text }) => ({ id, chatId, text })) });
|
|
91
|
+
return json(res, 200, { items: bridge.outbox.slice(0, 1).map(({ id, chatId, text, file }) => ({ id, chatId, text, ...(file ? { file } : {}) })) });
|
|
84
92
|
}
|
|
85
93
|
if (method !== "POST")
|
|
86
94
|
return json(res, 405, { error: "method not allowed" });
|
|
87
95
|
const body = await readBody(req);
|
|
88
96
|
if (action === "sent") {
|
|
89
97
|
const item = pending.get(Number(body?.id));
|
|
90
|
-
|
|
91
|
-
|
|
98
|
+
const owned = item && bridge.outbox.includes(item);
|
|
99
|
+
if (owned)
|
|
100
|
+
item.settle(typeof body?.error === "string" ? body.error.slice(0, 200) : undefined);
|
|
101
|
+
return json(res, 200, { ok: Boolean(owned) });
|
|
92
102
|
}
|
|
93
103
|
const messages = Array.isArray(body?.messages) ? body.messages.slice(0, 50) : [];
|
|
94
104
|
for (const raw of messages) {
|
|
@@ -97,7 +107,11 @@ export function messengerBridge(options) {
|
|
|
97
107
|
if (!chatId || typeof raw.id !== "string")
|
|
98
108
|
continue;
|
|
99
109
|
const name = typeof raw.name === "string" && raw.name.trim() ? raw.name.trim().slice(0, 100) : chatId;
|
|
100
|
-
|
|
110
|
+
const url = typeof raw.fileUrl === "string" && raw.fileUrl.length <= 8_192 ? raw.fileUrl : undefined;
|
|
111
|
+
const filename = typeof raw.fileName === "string" && raw.fileName.length <= 512 ? raw.fileName : "attachment.bin";
|
|
112
|
+
bridge.io.deliver({ id: raw.id.slice(0, 200), chatId, direct: true, from: { id: chatId, name }, text,
|
|
113
|
+
...(url ? { media: true, loadMedia: () => fetchChannelMedia(url, ["fbcdn.net", "fbsbx.com", "facebook.com"], filename) } : {}),
|
|
114
|
+
});
|
|
101
115
|
}
|
|
102
116
|
bridge.io.healthy();
|
|
103
117
|
return json(res, 200, { ok: true });
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
// Telegram Bot API over long polling (getUpdates): no webhook, so nothing has to reach this server from outside.
|
|
2
2
|
import { ChannelError } from "./engine.js";
|
|
3
|
+
import { channelFileBlob, readChannelDownload, readChannelMedia, storeChannelMedia } from "./channel-media.js";
|
|
3
4
|
const TOKEN = /^\d{5,15}:[\w-]{30,60}$/;
|
|
4
5
|
const POLL_S = 25;
|
|
5
6
|
export function telegramAdapter(options = {}) {
|
|
6
7
|
const base = (options.apiBase ?? "https://api.telegram.org").replace(/\/$/, "");
|
|
7
8
|
const call = options.fetch ?? fetch;
|
|
8
9
|
async function api(token, method, body, signal) {
|
|
9
|
-
const
|
|
10
|
+
const payload = body instanceof FormData ? { body } : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) };
|
|
11
|
+
const response = await call(`${base}/bot${token}/${method}`, { method: "POST", ...payload, redirect: "error", ...(signal ? { signal } : {}) })
|
|
10
12
|
.catch((error) => { throw new ChannelError("retry", `Telegram: ${(error instanceof Error ? error.message : String(error)).replaceAll(token, "…")}`); });
|
|
11
13
|
const data = await response.json().catch(() => ({}));
|
|
12
14
|
if (response.ok && data.ok === true)
|
|
@@ -45,11 +47,22 @@ export function telegramAdapter(options = {}) {
|
|
|
45
47
|
if (!addressed)
|
|
46
48
|
return null;
|
|
47
49
|
const from = message.from;
|
|
50
|
+
const file = message.document ?? message.video ?? message.audio ?? message.voice ?? message.animation ??
|
|
51
|
+
message.video_note ?? message.sticker ?? (Array.isArray(message.photo) ? message.photo.at(-1) : undefined);
|
|
48
52
|
return {
|
|
49
53
|
id: String(message.message_id), chatId: String(message.chat.id), direct,
|
|
50
54
|
from: { id: String(from.id), name: [from.first_name, from.last_name].filter(Boolean).join(" ") || from.username || String(from.id) },
|
|
51
55
|
text: raw.replace(mention, "").trim(),
|
|
52
|
-
...(
|
|
56
|
+
...(file ? { media: true } : {}),
|
|
57
|
+
...(typeof file?.file_id === "string" ? { loadMedia: async () => {
|
|
58
|
+
const signal = AbortSignal.any([io.signal, AbortSignal.timeout(30_000)]);
|
|
59
|
+
const remote = await api(token, "getFile", { file_id: file.file_id }, signal);
|
|
60
|
+
const path = remote?.file_path;
|
|
61
|
+
if (typeof path !== "string" || !path.split("/").every(part => /^[\w.-]+$/.test(part) && part !== "." && part !== ".."))
|
|
62
|
+
throw Error("Attachment unavailable");
|
|
63
|
+
const response = await call(`${base}/file/bot${token}/${path}`, { signal, redirect: "error" });
|
|
64
|
+
return storeChannelMedia(await readChannelDownload(response), file.file_name ?? path.split("/").at(-1));
|
|
65
|
+
} } : {}),
|
|
53
66
|
};
|
|
54
67
|
};
|
|
55
68
|
const done = (async () => {
|
|
@@ -72,6 +85,14 @@ export function telegramAdapter(options = {}) {
|
|
|
72
85
|
return {
|
|
73
86
|
done,
|
|
74
87
|
send: async (chatId, text) => { await api(token, "sendMessage", { chat_id: Number(chatId), text }); },
|
|
88
|
+
sendMedia: async (chatId, attachment) => {
|
|
89
|
+
const file = await readChannelMedia(attachment);
|
|
90
|
+
const image = attachment.kind === "image" && attachment.mime !== "image/webp";
|
|
91
|
+
const form = new FormData();
|
|
92
|
+
form.set("chat_id", chatId);
|
|
93
|
+
form.set(image ? "photo" : "document", channelFileBlob(file), file.filename);
|
|
94
|
+
await api(token, image ? "sendPhoto" : "sendDocument", form, AbortSignal.timeout(60_000));
|
|
95
|
+
},
|
|
75
96
|
typing: async (chatId) => { await api(token, "sendChatAction", { chat_id: Number(chatId), action: "typing" }); },
|
|
76
97
|
};
|
|
77
98
|
},
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { Readable } from "node:stream";
|
|
2
|
+
import { imageDimensions } from "../../shared/provider-icon.js";
|
|
3
|
+
import { IMAGE_MAX_BYTES, saveFile, saveImage } from "../attachments.js";
|
|
4
|
+
import { fetchPublicPage } from "../wait-probes.js";
|
|
5
|
+
import { fetchChannelMedia, readChannelMedia } from "./channel-media.js";
|
|
6
|
+
const VIDEO_LIMIT = 32 * 1024 * 1024;
|
|
7
|
+
const ZALO_CDN = ["zaloapp.com", "zalo.me", "zdn.vn", "zadn.vn", "zalo.vn"];
|
|
8
|
+
export function receiveZaloFile(url, name) {
|
|
9
|
+
return fetchChannelMedia(url, ZALO_CDN, name);
|
|
10
|
+
}
|
|
11
|
+
export async function receiveZaloMedia(url, photo) {
|
|
12
|
+
const limit = photo ? IMAGE_MAX_BYTES : VIDEO_LIMIT;
|
|
13
|
+
const target = new URL(url);
|
|
14
|
+
if (target.protocol !== "https:" || !/(^|\.)(zaloapp\.com|zalo\.me|zdn\.vn|zadn\.vn|zalo\.vn)$/.test(target.hostname))
|
|
15
|
+
throw Error("Unsupported Zalo media address");
|
|
16
|
+
const page = await fetchPublicPage(url, { maxBytes: limit + 1, timeoutMs: 30000, maxRedirects: 0 });
|
|
17
|
+
if (!page.ok || !page.body.length || page.body.length > limit)
|
|
18
|
+
throw Error("Zalo media unavailable");
|
|
19
|
+
if (photo) {
|
|
20
|
+
const mime = ["image/jpeg", "image/png", "image/webp"].find(type => imageDimensions(page.body, type));
|
|
21
|
+
if (!mime)
|
|
22
|
+
throw Error("Unsupported image");
|
|
23
|
+
const { path } = saveImage(page.body, mime);
|
|
24
|
+
return { kind: "image", path, mime };
|
|
25
|
+
}
|
|
26
|
+
if (page.body.toString("ascii", 4, 8) !== "ftyp")
|
|
27
|
+
throw Error("Unsupported video");
|
|
28
|
+
const file = await saveFile(Readable.from([page.body]), "video.mp4", "video/mp4", { expectedBytes: page.body.length });
|
|
29
|
+
return { kind: "file", path: file.path, name: file.name, mime: file.mime };
|
|
30
|
+
}
|
|
31
|
+
export async function zaloUpload(file) {
|
|
32
|
+
const { data, filename } = await readChannelMedia(file, file.mime === "video/mp4" ? VIDEO_LIMIT : IMAGE_MAX_BYTES);
|
|
33
|
+
const dimensions = file.kind === "image" ? imageDimensions(data, file.mime) : undefined;
|
|
34
|
+
if (file.kind === "image" && !dimensions)
|
|
35
|
+
throw Error("Unsupported image");
|
|
36
|
+
return { data, filename, metadata: { ...dimensions, totalSize: data.length } };
|
|
37
|
+
}
|