clawgram 2.26.0 → 2.27.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/dist/account-scopes.js +76 -0
- package/dist/action-context.js +2 -0
- package/dist/actions-manage.js +198 -0
- package/dist/actions-read.js +394 -0
- package/dist/actions-send.js +302 -0
- package/dist/channel.js +20 -907
- package/dist/group-reply-address.js +6 -1
- package/dist/inbound-pipeline.js +75 -8
- package/npm-shrinkwrap.json +2 -2
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
package/dist/channel.js
CHANGED
|
@@ -1,13 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.createChannelPlugin = exports.canonicalAction = exports.CORE_ACTION_SYNONYMS = void 0;
|
|
7
|
-
exports.resolveAccountOperatorIds = resolveAccountOperatorIds;
|
|
3
|
+
exports.createChannelPlugin = exports.canonicalAction = exports.CORE_ACTION_SYNONYMS = exports.resolveAccountOperatorIds = void 0;
|
|
8
4
|
const core_1 = require("openclaw/plugin-sdk/core");
|
|
9
|
-
const node_os_1 = __importDefault(require("node:os"));
|
|
10
|
-
const node_path_1 = __importDefault(require("node:path"));
|
|
11
5
|
/**
|
|
12
6
|
* How long a file fetched by `fetch-media` stays on disk.
|
|
13
7
|
*
|
|
@@ -16,10 +10,6 @@ const node_path_1 = __importDefault(require("node:path"));
|
|
|
16
10
|
* that a chat full of images does not silently become a copy of itself in the
|
|
17
11
|
* temp directory.
|
|
18
12
|
*/
|
|
19
|
-
// Час, а не сутки: `fetch-media` существует ради «прочитать и переслать», и
|
|
20
|
-
// файл нужен ровно на время хода. Сутки означали сутки чужой личной переписки
|
|
21
|
-
// на диске (A5-13).
|
|
22
|
-
const FETCHED_MEDIA_TTL_MS = 60 * 60 * 1000;
|
|
23
13
|
/**
|
|
24
14
|
* What this channel promises the Gateway.
|
|
25
15
|
*
|
|
@@ -50,49 +40,29 @@ const CHANNEL_CAPABILITIES = {
|
|
|
50
40
|
},
|
|
51
41
|
},
|
|
52
42
|
};
|
|
53
|
-
const media_1 = require("./media");
|
|
54
|
-
const fetch_media_1 = require("./fetch-media");
|
|
55
43
|
const channel_runtime_1 = require("openclaw/plugin-sdk/channel-runtime");
|
|
56
|
-
const param_readers_1 = require("openclaw/plugin-sdk/param-readers");
|
|
57
44
|
const tool_send_1 = require("openclaw/plugin-sdk/tool-send");
|
|
58
45
|
const events_1 = require("telegram/events");
|
|
59
46
|
const gramjs_client_1 = require("./gramjs-client");
|
|
60
|
-
const history_1 = require("./history");
|
|
61
|
-
const send_scope_1 = require("./send-scope");
|
|
62
47
|
const account_registry_1 = require("./account-registry");
|
|
63
48
|
const joins_1 = require("./joins");
|
|
64
|
-
const reactions_1 = require("./reactions");
|
|
65
|
-
const manage_1 = require("./manage");
|
|
66
|
-
const state_dir_1 = require("./state-dir");
|
|
67
|
-
const chat_info_1 = require("./chat-info");
|
|
68
|
-
const topics_1 = require("./topics");
|
|
69
|
-
const dialogs_1 = require("./dialogs");
|
|
70
49
|
const group_tool_policy_1 = require("./group-tool-policy");
|
|
71
50
|
const secret_refs_1 = require("./secret-refs");
|
|
72
51
|
const secret_ref_runtime_1 = require("openclaw/plugin-sdk/secret-ref-runtime");
|
|
73
|
-
const group_reply_address_1 = require("./group-reply-address");
|
|
74
|
-
const group_visible_reply_guard_1 = require("./group-visible-reply-guard");
|
|
75
52
|
const helpers_1 = require("./helpers");
|
|
76
53
|
const proxy_config_1 = require("./proxy-config");
|
|
77
54
|
const constants_1 = require("./constants");
|
|
78
55
|
const actions_1 = require("./actions");
|
|
79
56
|
Object.defineProperty(exports, "CORE_ACTION_SYNONYMS", { enumerable: true, get: function () { return actions_1.CORE_ACTION_SYNONYMS; } });
|
|
80
57
|
Object.defineProperty(exports, "canonicalAction", { enumerable: true, get: function () { return actions_1.canonicalAction; } });
|
|
58
|
+
const actions_read_1 = require("./actions-read");
|
|
59
|
+
const actions_manage_1 = require("./actions-manage");
|
|
60
|
+
const actions_send_1 = require("./actions-send");
|
|
61
|
+
const account_scopes_1 = require("./account-scopes");
|
|
62
|
+
Object.defineProperty(exports, "resolveAccountOperatorIds", { enumerable: true, get: function () { return account_scopes_1.resolveAccountOperatorIds; } });
|
|
81
63
|
const outbound_1 = require("./outbound");
|
|
82
64
|
const inbound_pipeline_1 = require("./inbound-pipeline");
|
|
83
|
-
const attachments_1 = require("./attachments");
|
|
84
65
|
const actionLog = (0, core_1.createSubsystemLogger)("channels/clawgram");
|
|
85
|
-
/**
|
|
86
|
-
* Read scope as configured for the account. Left `undefined` when the key is
|
|
87
|
-
* absent so `isChatReadable` can tell "not configured" from "configured empty" —
|
|
88
|
-
* the first means no restriction, the second denies everything.
|
|
89
|
-
*/
|
|
90
|
-
function readAccountReadChats(account) {
|
|
91
|
-
return (0, history_1.normalizeScopeList)(account?.readChats);
|
|
92
|
-
}
|
|
93
|
-
function resolveAccountReadChats(cfg, accountId) {
|
|
94
|
-
return readAccountReadChats(cfg?.channels?.["clawgram"]?.accounts?.[accountId]);
|
|
95
|
-
}
|
|
96
66
|
/**
|
|
97
67
|
* Хэндл в `allowFrom` — обещание, которое Telegram не держит.
|
|
98
68
|
*
|
|
@@ -119,58 +89,6 @@ function warnAboutHandleAllowlistEntries(cfg, accountId) {
|
|
|
119
89
|
why: "a released handle can be taken by someone else; numeric ids do not change hands",
|
|
120
90
|
});
|
|
121
91
|
}
|
|
122
|
-
/**
|
|
123
|
-
* Outbound scope as configured. Handed to `isChatSendable` raw: an absent
|
|
124
|
-
* value means "unrestricted" and an empty list means "deny", and only the
|
|
125
|
-
* raw value tells those apart — same shape as `readChats`.
|
|
126
|
-
*/
|
|
127
|
-
function resolveAccountSendChats(cfg, accountId) {
|
|
128
|
-
return cfg?.channels?.["clawgram"]?.accounts?.[accountId]?.sendChats;
|
|
129
|
-
}
|
|
130
|
-
/** One refusal for every outbound action, so the three read the same. */
|
|
131
|
-
function refuseOutboundOutsideScope(action, accountId, target) {
|
|
132
|
-
const refusal = (0, send_scope_1.describeSendRefusal)(target);
|
|
133
|
-
actionLog.warn(`clawgram ${action} refused: ${refusal.reason}`, { accountId, ...refusal.logFields });
|
|
134
|
-
throw refusal.error;
|
|
135
|
-
}
|
|
136
|
-
/**
|
|
137
|
-
* Management scope as configured. Handed to `isChatManageable` raw: unlike
|
|
138
|
-
* `readChats`, an absent value already means "deny", so there is nothing to
|
|
139
|
-
* tell apart here.
|
|
140
|
-
*/
|
|
141
|
-
/** Chat discovery as configured; absent means "deny", like management scope. */
|
|
142
|
-
/**
|
|
143
|
-
* Кому уходит операционная телеметрия ядра в личке.
|
|
144
|
-
*
|
|
145
|
-
* `operatorIds` — если задан. Иначе `allowFrom`, но только когда это
|
|
146
|
-
* конкретный список: со звёздочкой он означает «пишет кто угодно», и слать
|
|
147
|
-
* туда пути secret-store нельзя (A5-11). Пустой результат означает «оператор
|
|
148
|
-
* не назван», и уведомление подавляется везде.
|
|
149
|
-
*
|
|
150
|
-
* Запоминается при старте аккаунта — см. реестр в system-notice.ts.
|
|
151
|
-
*/
|
|
152
|
-
function resolveAccountOperatorIds(cfg, accountId) {
|
|
153
|
-
const account = cfg?.channels?.["clawgram"]?.accounts?.[accountId];
|
|
154
|
-
// Только явный список. Умолчание «operatorIds = allowFrom» делало
|
|
155
|
-
// оператором каждого допущенного собеседника — и телеметрию с путями
|
|
156
|
-
// secret-store получал любой из них (D2-03, A5-11). Не назван — не
|
|
157
|
-
// назван: уведомления подавляются везде.
|
|
158
|
-
const raw = account?.operatorIds;
|
|
159
|
-
if (raw === undefined || raw === null)
|
|
160
|
-
return [];
|
|
161
|
-
const entries = Array.isArray(raw) ? raw : [raw];
|
|
162
|
-
return entries.map((entry) => String(entry).trim()).filter(Boolean);
|
|
163
|
-
}
|
|
164
|
-
function resolveAccountDiscoverChats(cfg, accountId) {
|
|
165
|
-
return cfg?.channels?.["clawgram"]?.accounts?.[accountId]?.discoverChats;
|
|
166
|
-
}
|
|
167
|
-
function resolveAccountManageChats(cfg, accountId) {
|
|
168
|
-
return cfg?.channels?.["clawgram"]?.accounts?.[accountId]?.manageChats;
|
|
169
|
-
}
|
|
170
|
-
/** Same normalization `readChats` gets, for the resolved-account copy. */
|
|
171
|
-
function readAccountManageChats(account) {
|
|
172
|
-
return (0, history_1.normalizeScopeList)(account?.manageChats);
|
|
173
|
-
}
|
|
174
92
|
const createChannelPlugin = (runtimes, pluginRuntime) => {
|
|
175
93
|
const resolveRuntimeAccountId = (cfg, preferred) => {
|
|
176
94
|
const configured = (0, helpers_1.resolveConfiguredAccountId)(cfg, preferred);
|
|
@@ -262,7 +180,7 @@ const createChannelPlugin = (runtimes, pluginRuntime) => {
|
|
|
262
180
|
apiHash: (0, secret_refs_1.readSecretInput)(account?.apiHash),
|
|
263
181
|
sessionString: (0, secret_refs_1.readSecretInput)(account?.sessionString),
|
|
264
182
|
...(0, helpers_1.resolveAccountScopes)(cfg, accountId),
|
|
265
|
-
readChats: readAccountReadChats(account),
|
|
183
|
+
readChats: (0, account_scopes_1.readAccountReadChats)(account),
|
|
266
184
|
enabled: account?.enabled,
|
|
267
185
|
accountId,
|
|
268
186
|
proxy: (0, proxy_config_1.resolveProxyConfig)(account?.proxy),
|
|
@@ -271,7 +189,7 @@ const createChannelPlugin = (runtimes, pluginRuntime) => {
|
|
|
271
189
|
// client from a config object this function had already stripped it
|
|
272
190
|
// from, so the setting validated, deployed and did nothing.
|
|
273
191
|
replyParseMode: account?.replyParseMode,
|
|
274
|
-
manageChats: readAccountManageChats(account),
|
|
192
|
+
manageChats: (0, account_scopes_1.readAccountManageChats)(account),
|
|
275
193
|
// Optional secret: absent must stay absent, not become "".
|
|
276
194
|
twoFaPassword: account?.twoFaPassword === undefined || account?.twoFaPassword === null
|
|
277
195
|
? undefined
|
|
@@ -332,8 +250,8 @@ const createChannelPlugin = (runtimes, pluginRuntime) => {
|
|
|
332
250
|
// отправки (A5-12) и операторы (A5-11). Одна запись, снимается при
|
|
333
251
|
// остановке аккаунта (D2-11).
|
|
334
252
|
(0, account_registry_1.rememberAccount)(accountId, {
|
|
335
|
-
sendChats: resolveAccountSendChats(cfg, accountId),
|
|
336
|
-
operatorIds: resolveAccountOperatorIds(cfg, accountId),
|
|
253
|
+
sendChats: (0, account_scopes_1.resolveAccountSendChats)(cfg, accountId),
|
|
254
|
+
operatorIds: (0, account_scopes_1.resolveAccountOperatorIds)(cfg, accountId),
|
|
337
255
|
});
|
|
338
256
|
warnAboutHandleAllowlistEntries(cfg, accountId);
|
|
339
257
|
const me = await gram.getMe();
|
|
@@ -591,822 +509,17 @@ const createChannelPlugin = (runtimes, pluginRuntime) => {
|
|
|
591
509
|
// decides what a name means. An unknown name stays itself and falls
|
|
592
510
|
// through to the unsupported-action error, as before.
|
|
593
511
|
const canonical = (0, actions_1.canonicalAction)(action);
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
const listAccountId = resolveRuntimeAccountId(cfg, accountId);
|
|
599
|
-
if (!listAccountId) {
|
|
600
|
-
throw new Error("clawgram: no configured account found");
|
|
601
|
-
}
|
|
602
|
-
// Reading is not a side effect, so a dry run still answers — reporting
|
|
603
|
-
// an empty window would look like a quiet chat rather than a no-op.
|
|
604
|
-
if (!(0, history_1.isChatReadable)(listParams.target, resolveAccountReadChats(cfg, listAccountId))) {
|
|
605
|
-
actionLog.warn("clawgram list refused: chat outside read scope", {
|
|
606
|
-
accountId: listAccountId,
|
|
607
|
-
target: listParams.target,
|
|
608
|
-
});
|
|
609
|
-
throw new Error(`clawgram: not-allowed-chat ${listParams.target}`);
|
|
610
|
-
}
|
|
611
|
-
const listGram = requireRuntimeFor(listAccountId);
|
|
612
|
-
const history = await listGram.listMessages(listParams);
|
|
613
|
-
// Metadata only. Message text is the user's correspondence and has no
|
|
614
|
-
// business in a log that is read while debugging something else.
|
|
615
|
-
actionLog.info("clawgram handleAction list completed", {
|
|
616
|
-
accountId: listAccountId,
|
|
617
|
-
target: listParams.target,
|
|
618
|
-
limit: listParams.limit,
|
|
619
|
-
since: listParams.since ?? null,
|
|
620
|
-
until: listParams.until ?? null,
|
|
621
|
-
returned: history.messages.length,
|
|
622
|
-
truncated: history.truncated,
|
|
623
|
-
});
|
|
624
|
-
return (0, core_1.jsonResult)({
|
|
625
|
-
ok: true,
|
|
626
|
-
accountId: listAccountId,
|
|
627
|
-
chatId: history.chatId ?? listParams.target,
|
|
628
|
-
count: history.messages.length,
|
|
629
|
-
truncated: history.truncated,
|
|
630
|
-
messages: history.messages,
|
|
631
|
-
});
|
|
632
|
-
}
|
|
633
|
-
// The attachment on a message that is already in a chat.
|
|
634
|
-
//
|
|
635
|
-
// `read` says a photo exists; it does not fetch it, and the inbound
|
|
636
|
-
// path only ever reads what arrives while the agent is being addressed.
|
|
637
|
-
// Everything else — a screenshot posted an hour ago, a diagram in a
|
|
638
|
-
// chat the agent reads but was not tagged in — was visible to the
|
|
639
|
-
// channel and unreachable to the agent. Same `readChats` scope as
|
|
640
|
-
// history: this must not become a way to pull bytes out of a chat the
|
|
641
|
-
// account was never allowed to read.
|
|
642
|
-
if (canonical === "fetch-media") {
|
|
643
|
-
const fetchParams = (0, fetch_media_1.parseFetchMediaParams)(params);
|
|
644
|
-
const fetchAccountId = resolveRuntimeAccountId(cfg, accountId);
|
|
645
|
-
if (!fetchAccountId) {
|
|
646
|
-
throw new Error("clawgram: no configured account found");
|
|
647
|
-
}
|
|
648
|
-
if (!(0, history_1.isChatReadable)(fetchParams.target, resolveAccountReadChats(cfg, fetchAccountId))) {
|
|
649
|
-
actionLog.warn("clawgram fetch-media refused: chat outside read scope", {
|
|
650
|
-
accountId: fetchAccountId,
|
|
651
|
-
target: fetchParams.target,
|
|
652
|
-
});
|
|
653
|
-
throw new Error(`clawgram: not-allowed-chat ${fetchParams.target}`);
|
|
654
|
-
}
|
|
655
|
-
const fetchGram = requireRuntimeFor(fetchAccountId);
|
|
656
|
-
// Fetching is a read: a dry run answers for real, the same way `read`
|
|
657
|
-
// does. Nothing leaves the machine — the file lands in a temp
|
|
658
|
-
// directory this channel prunes — so a rehearsal that reported
|
|
659
|
-
// "would fetch" would only teach the agent to ask twice.
|
|
660
|
-
const found = await fetchGram.getMessageById(fetchParams.target, fetchParams.messageId);
|
|
661
|
-
const fetchChatId = found.chatId ?? fetchParams.target;
|
|
662
|
-
if (!found.message) {
|
|
663
|
-
actionLog.info("clawgram fetch-media found no message", {
|
|
664
|
-
accountId: fetchAccountId,
|
|
665
|
-
chatId: fetchChatId,
|
|
666
|
-
messageId: fetchParams.messageId,
|
|
667
|
-
});
|
|
668
|
-
return (0, core_1.jsonResult)({
|
|
669
|
-
ok: false,
|
|
670
|
-
accountId: fetchAccountId,
|
|
671
|
-
chatId: fetchChatId,
|
|
672
|
-
messageId: String(fetchParams.messageId),
|
|
673
|
-
error: "message-not-found",
|
|
674
|
-
});
|
|
675
|
-
}
|
|
676
|
-
// `read` throws the file away, so it gets a directory of its own —
|
|
677
|
-
// the shared directory is keyed by chat and message, and deleting
|
|
678
|
-
// that path would pull the file out from under an earlier `both`
|
|
679
|
-
// fetch of the same message that handed the caller a path.
|
|
680
|
-
// Не общий /tmp: там файлы видит каждый локальный пользователь, а на
|
|
681
|
-
// этом хосте живёт ещё и раннер деплоя. Каталог состояния OpenClaw
|
|
682
|
-
// принадлежит агенту; если он не задан, остаётся /tmp — но права
|
|
683
|
-
// 0700/0600 ставятся в любом случае (A5-13).
|
|
684
|
-
// Каталог состояния принадлежит агенту; при явно заданном
|
|
685
|
-
// OPENCLAW_STATE_DIR вложения не покидают его.
|
|
686
|
-
const mediaRoot = process.env.OPENCLAW_STATE_DIR?.trim()
|
|
687
|
-
? node_path_1.default.join((0, state_dir_1.resolveStateDir)(), "tmp")
|
|
688
|
-
: node_os_1.default.tmpdir();
|
|
689
|
-
const sharedFetchDir = node_path_1.default.join(mediaRoot, "clawgram-fetched");
|
|
690
|
-
let fetchDir = sharedFetchDir;
|
|
691
|
-
if (fetchParams.mode === "read") {
|
|
692
|
-
const { mkdtemp, mkdir } = await import("node:fs/promises");
|
|
693
|
-
await mkdir(mediaRoot, { recursive: true, mode: 0o700 });
|
|
694
|
-
fetchDir = await mkdtemp(node_path_1.default.join(mediaRoot, "clawgram-media-"));
|
|
695
|
-
}
|
|
696
|
-
else {
|
|
697
|
-
await (0, media_1.pruneFetchedMedia)(sharedFetchDir, FETCHED_MEDIA_TTL_MS, Date.now());
|
|
698
|
-
}
|
|
699
|
-
const downloaded = await (0, media_1.downloadMessageMediaToFile)({
|
|
700
|
-
client: fetchGram.getClient(),
|
|
701
|
-
message: found.message,
|
|
702
|
-
maxBytes: attachments_1.INBOUND_MEDIA_MAX_BYTES,
|
|
703
|
-
dir: fetchDir,
|
|
704
|
-
fileNameFor: ({ media, extension }) => (0, fetch_media_1.fetchedMediaFileName)({
|
|
705
|
-
chatId: fetchChatId,
|
|
706
|
-
messageId: fetchParams.messageId,
|
|
707
|
-
extension,
|
|
708
|
-
fileName: media.fileName,
|
|
709
|
-
}),
|
|
710
|
-
});
|
|
711
|
-
if (!downloaded) {
|
|
712
|
-
// Three different nothings, and the agent has to be able to tell
|
|
713
|
-
// them apart: a message with no attachment, an attachment this
|
|
714
|
-
// channel does not read (a video, a spreadsheet), and one too
|
|
715
|
-
// large to be worth the transfer. Saying "could not fetch" to all
|
|
716
|
-
// three is how "she ignored the picture" starts.
|
|
717
|
-
const described = (0, media_1.describeMedia)(found.message?.media);
|
|
718
|
-
const tooLarge = typeof described?.size === "number" && described.size > attachments_1.INBOUND_MEDIA_MAX_BYTES;
|
|
719
|
-
const error = !described
|
|
720
|
-
? "no-media"
|
|
721
|
-
: tooLarge
|
|
722
|
-
? "media-too-large"
|
|
723
|
-
: "unsupported-media";
|
|
724
|
-
actionLog.info("clawgram fetch-media returned nothing", {
|
|
725
|
-
accountId: fetchAccountId,
|
|
726
|
-
chatId: fetchChatId,
|
|
727
|
-
messageId: fetchParams.messageId,
|
|
728
|
-
kind: described?.kind ?? null,
|
|
729
|
-
error,
|
|
730
|
-
});
|
|
731
|
-
return (0, core_1.jsonResult)({
|
|
732
|
-
ok: false,
|
|
733
|
-
accountId: fetchAccountId,
|
|
734
|
-
chatId: fetchChatId,
|
|
735
|
-
messageId: String(fetchParams.messageId),
|
|
736
|
-
media: described ?? null,
|
|
737
|
-
error,
|
|
738
|
-
});
|
|
739
|
-
}
|
|
740
|
-
let read;
|
|
741
|
-
let readError;
|
|
742
|
-
if (fetchParams.mode !== "file") {
|
|
743
|
-
try {
|
|
744
|
-
read = await (0, attachments_1.understandAttachmentFile)({
|
|
745
|
-
runtime: pluginRuntime,
|
|
746
|
-
cfg,
|
|
747
|
-
filePath: downloaded.path,
|
|
748
|
-
mimeType: downloaded.mimeType,
|
|
749
|
-
understanding: downloaded.understanding,
|
|
750
|
-
});
|
|
751
|
-
if (!read) {
|
|
752
|
-
readError = "read-empty";
|
|
753
|
-
}
|
|
754
|
-
}
|
|
755
|
-
catch (err) {
|
|
756
|
-
// The bytes are already here. A failed reading is worth
|
|
757
|
-
// reporting, but it does not undo a successful fetch: the file
|
|
758
|
-
// still exists and can still be forwarded.
|
|
759
|
-
readError = String(err);
|
|
760
|
-
}
|
|
761
|
-
}
|
|
762
|
-
// `read` mode is the inbound contract — the words, not the file — so
|
|
763
|
-
// the bytes go away with the answer. Any other mode keeps them:
|
|
764
|
-
// that is the whole point of asking for a path.
|
|
765
|
-
if (fetchParams.mode === "read") {
|
|
766
|
-
try {
|
|
767
|
-
const { rm } = await import("node:fs/promises");
|
|
768
|
-
await rm(fetchDir, { recursive: true, force: true });
|
|
769
|
-
}
|
|
770
|
-
catch {
|
|
771
|
-
// A file left behind is pruned within a day; failing the call
|
|
772
|
-
// over it would throw away a reading that already succeeded.
|
|
773
|
-
}
|
|
774
|
-
}
|
|
775
|
-
actionLog.info("clawgram fetch-media completed", {
|
|
776
|
-
accountId: fetchAccountId,
|
|
777
|
-
chatId: fetchChatId,
|
|
778
|
-
messageId: fetchParams.messageId,
|
|
779
|
-
mode: fetchParams.mode,
|
|
780
|
-
kind: downloaded.media.kind,
|
|
781
|
-
understanding: downloaded.understanding,
|
|
782
|
-
characters: read?.length ?? 0,
|
|
783
|
-
readError: readError ?? null,
|
|
784
|
-
});
|
|
785
|
-
return (0, core_1.jsonResult)({
|
|
786
|
-
ok: true,
|
|
787
|
-
accountId: fetchAccountId,
|
|
788
|
-
chatId: fetchChatId,
|
|
789
|
-
messageId: String(fetchParams.messageId),
|
|
790
|
-
mode: fetchParams.mode,
|
|
791
|
-
media: downloaded.media,
|
|
792
|
-
understanding: downloaded.understanding,
|
|
793
|
-
filePath: fetchParams.mode === "read" ? undefined : downloaded.path,
|
|
794
|
-
text: read,
|
|
795
|
-
readError,
|
|
796
|
-
});
|
|
797
|
-
}
|
|
798
|
-
/**
|
|
799
|
-
* The scaffold every chat-shaped read shares.
|
|
800
|
-
*
|
|
801
|
-
* `participants`, `topics`, `dialogs`, `joins` and `chatInfo` each
|
|
802
|
-
* spelled out the same sequence: parse, resolve the account, check a
|
|
803
|
-
* scope, fetch the runtime, call it, log counts, answer. Roughly
|
|
804
|
-
* forty lines apiece, differing in four places — which is how a new
|
|
805
|
-
* action came to cost sixty lines of scaffold and how the two gates
|
|
806
|
-
* drifted apart (finding A6-11).
|
|
807
|
-
*
|
|
808
|
-
* The gate follows from the shape rather than being restated: an
|
|
809
|
-
* action that names a chat is gated by `readChats`, `dialogs` has its
|
|
810
|
-
* own discovery gate precisely because its point is to find chats
|
|
811
|
-
* that are not in scope yet, and `joins` has none — the journal only
|
|
812
|
-
* ever holds chats this account was put into.
|
|
813
|
-
*
|
|
814
|
-
* The runtime is a getter, not a value: `joins` reads a file and must
|
|
815
|
-
* not fail merely because no runtime is connected.
|
|
816
|
-
*/
|
|
817
|
-
const runRead = async (spec) => {
|
|
818
|
-
const parsed = spec.parse();
|
|
819
|
-
const readAccountId = resolveRuntimeAccountId(cfg, accountId);
|
|
820
|
-
if (!readAccountId) {
|
|
821
|
-
throw new Error("clawgram: no configured account found");
|
|
822
|
-
}
|
|
823
|
-
const target = spec.target?.(parsed);
|
|
824
|
-
if (target !== undefined) {
|
|
825
|
-
if (!(0, history_1.isChatReadable)(target, resolveAccountReadChats(cfg, readAccountId))) {
|
|
826
|
-
actionLog.warn(`clawgram ${spec.name} refused: chat outside read scope`, {
|
|
827
|
-
accountId: readAccountId,
|
|
828
|
-
target,
|
|
829
|
-
});
|
|
830
|
-
throw new Error(`clawgram: not-allowed-chat ${target}`);
|
|
831
|
-
}
|
|
832
|
-
}
|
|
833
|
-
else if (spec.discovery) {
|
|
834
|
-
if (!(0, dialogs_1.isChatDiscoveryEnabled)(resolveAccountDiscoverChats(cfg, readAccountId))) {
|
|
835
|
-
actionLog.warn(`clawgram ${spec.name} refused: chat-discovery is not enabled`, {
|
|
836
|
-
accountId: readAccountId,
|
|
837
|
-
});
|
|
838
|
-
throw new Error("clawgram: chat-discovery is not enabled");
|
|
839
|
-
}
|
|
840
|
-
}
|
|
841
|
-
const gram = () => requireRuntimeFor(readAccountId);
|
|
842
|
-
const result = await spec.run({ parsed, accountId: readAccountId, gram });
|
|
843
|
-
actionLog.info(`clawgram handleAction ${spec.name} completed`, {
|
|
844
|
-
accountId: readAccountId,
|
|
845
|
-
...spec.after(parsed, result),
|
|
846
|
-
});
|
|
847
|
-
return (0, core_1.jsonResult)({ ok: true, accountId: readAccountId, ...spec.result(parsed, result) });
|
|
512
|
+
const context = {
|
|
513
|
+
action, canonical, params, cfg, accountId, dryRun, toolContext,
|
|
514
|
+
allowedMediaRoots, readMedia, pluginRuntime,
|
|
515
|
+
resolveRuntimeAccountId, requireRuntimeFor,
|
|
848
516
|
};
|
|
849
|
-
//
|
|
850
|
-
//
|
|
851
|
-
//
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
parse: () => (0, history_1.parseListParticipantsParams)(params),
|
|
856
|
-
target: (p) => p.target,
|
|
857
|
-
run: ({ parsed, gram }) => gram().listParticipants(parsed),
|
|
858
|
-
// Counts only. Member ids are personal data and have no business in
|
|
859
|
-
// a log that is read while debugging something else.
|
|
860
|
-
after: (p, m) => ({
|
|
861
|
-
target: p.target,
|
|
862
|
-
limit: p.limit,
|
|
863
|
-
returned: m.participants.length,
|
|
864
|
-
truncated: m.truncated,
|
|
865
|
-
}),
|
|
866
|
-
result: (p, m) => ({
|
|
867
|
-
chatId: m.chatId ?? p.target,
|
|
868
|
-
count: m.participants.length,
|
|
869
|
-
truncated: m.truncated,
|
|
870
|
-
participants: m.participants,
|
|
871
|
-
}),
|
|
872
|
-
});
|
|
873
|
-
}
|
|
874
|
-
// Topic names. A forum chat is addressed by topic id, and until now an
|
|
875
|
-
// id could only be lifted off an inbound message — so a topic nobody had
|
|
876
|
-
// written in yet was unreachable, and one named in words was unfindable.
|
|
877
|
-
// Titles say what a chat is working on, so the read scope gates them.
|
|
878
|
-
if (canonical === "topics") {
|
|
879
|
-
return await runRead({
|
|
880
|
-
name: "topics",
|
|
881
|
-
parse: () => (0, topics_1.parseTopicsParams)(params),
|
|
882
|
-
target: (p) => p.target,
|
|
883
|
-
run: ({ parsed, gram }) => gram().listTopics(parsed),
|
|
884
|
-
after: (p, f) => ({
|
|
885
|
-
target: p.target,
|
|
886
|
-
limit: p.limit,
|
|
887
|
-
returned: f.topics.length,
|
|
888
|
-
truncated: f.truncated,
|
|
889
|
-
}),
|
|
890
|
-
result: (p, f) => ({
|
|
891
|
-
chatId: f.chatId ?? p.target,
|
|
892
|
-
count: f.topics.length,
|
|
893
|
-
truncated: f.truncated,
|
|
894
|
-
topics: f.topics,
|
|
895
|
-
}),
|
|
896
|
-
});
|
|
897
|
-
}
|
|
898
|
-
// Which chats this account is in. Not gated by `readChats` — the whole
|
|
899
|
-
// point is to find chats that are not in it yet — so it has a gate of
|
|
900
|
-
// its own, is metadata only, and never reports direct chats.
|
|
901
|
-
if (canonical === "dialogs") {
|
|
902
|
-
return await runRead({
|
|
903
|
-
name: "dialogs",
|
|
904
|
-
parse: () => (0, dialogs_1.parseDialogsParams)(params),
|
|
905
|
-
discovery: true,
|
|
906
|
-
run: ({ parsed, gram }) => gram().listDialogs(parsed),
|
|
907
|
-
// Counts only: which chats a person's account sits in is exactly
|
|
908
|
-
// the kind of thing that should not be sitting in a log.
|
|
909
|
-
after: (p, f) => ({ limit: p.limit, returned: f.dialogs.length, truncated: f.truncated }),
|
|
910
|
-
result: (_p, f) => ({ count: f.dialogs.length, truncated: f.truncated, dialogs: f.dialogs }),
|
|
911
|
-
});
|
|
912
|
-
}
|
|
913
|
-
// Where this account was recently added, and by whom. Reading the journal
|
|
914
|
-
// has no scope check of its own: it only ever contains chats this account
|
|
915
|
-
// was put into, which is exactly what the caller is allowed to learn.
|
|
916
|
-
if (canonical === "joins") {
|
|
917
|
-
return await runRead({
|
|
918
|
-
name: "joins",
|
|
919
|
-
parse: () => (0, joins_1.parseJoinsParams)(params),
|
|
920
|
-
// No runtime: this reads a file, and must answer with none connected.
|
|
921
|
-
run: async ({ parsed, accountId: joinsAccountId }) => (0, joins_1.selectJoinRecords)((0, joins_1.readJoinRecords)((0, joins_1.resolveJoinsJournalPath)(cfg?.channels?.["clawgram"]?.accounts?.[joinsAccountId], joinsAccountId)), parsed),
|
|
922
|
-
after: (p, selected) => ({
|
|
923
|
-
since: p.since ?? null,
|
|
924
|
-
limit: p.limit,
|
|
925
|
-
returned: selected.length,
|
|
926
|
-
}),
|
|
927
|
-
result: (_p, selected) => ({ count: selected.length, joins: selected }),
|
|
928
|
-
});
|
|
929
|
-
}
|
|
930
|
-
// Describing a chat is a read, so the same `readChats` scope that gates
|
|
931
|
-
// history gates it too — this must not become a way to learn the title
|
|
932
|
-
// and size of a chat the account was never allowed to read.
|
|
933
|
-
if (canonical === "chatInfo") {
|
|
934
|
-
return await runRead({
|
|
935
|
-
name: "chatInfo",
|
|
936
|
-
parse: () => (0, chat_info_1.parseChatInfoParams)(params, toolContext),
|
|
937
|
-
target: (p) => p.target,
|
|
938
|
-
run: async ({ parsed, gram }) => {
|
|
939
|
-
const { entity, full } = await gram().getChatInfo(parsed.target);
|
|
940
|
-
return (0, chat_info_1.describeChat)(entity, full);
|
|
941
|
-
},
|
|
942
|
-
// Type and size only. The title of a private chat is as personal as
|
|
943
|
-
// its contents and has no business in a debugging log.
|
|
944
|
-
after: (_p, info) => ({
|
|
945
|
-
type: info.type,
|
|
946
|
-
memberCount: info.memberCount ?? null,
|
|
947
|
-
isForum: info.isForum ?? null,
|
|
948
|
-
}),
|
|
949
|
-
result: (p, info) => ({ chat: { ...info, chatId: info.chatId ?? p.target } }),
|
|
950
|
-
});
|
|
951
|
-
}
|
|
952
|
-
// A reaction is an outbound act on someone else's message, so it is
|
|
953
|
-
// gated like sending rather than like reading — and it respects
|
|
954
|
-
// `dryRun`, which reading does not need to.
|
|
955
|
-
if (canonical === "react") {
|
|
956
|
-
const reactionParams = (0, reactions_1.parseReactionParams)(params, toolContext);
|
|
957
|
-
const reactionAccountId = resolveRuntimeAccountId(cfg, accountId);
|
|
958
|
-
if (!reactionAccountId) {
|
|
959
|
-
throw new Error("clawgram: no configured account found");
|
|
960
|
-
}
|
|
961
|
-
// Реакция — видимое действие от имени владельца в чужом чате, и
|
|
962
|
-
// адресуется она так же, как сообщение: та же область (A5-12).
|
|
963
|
-
if (!(0, send_scope_1.isChatSendable)(reactionParams.target, resolveAccountSendChats(cfg, reactionAccountId))) {
|
|
964
|
-
refuseOutboundOutsideScope("react", reactionAccountId, String(reactionParams.target));
|
|
965
|
-
}
|
|
966
|
-
actionLog.info("clawgram handleAction react", {
|
|
967
|
-
accountId: reactionAccountId,
|
|
968
|
-
dryRun: dryRun === true,
|
|
969
|
-
target: reactionParams.target,
|
|
970
|
-
messageId: reactionParams.messageId,
|
|
971
|
-
remove: reactionParams.remove,
|
|
972
|
-
});
|
|
973
|
-
if (dryRun === true) {
|
|
974
|
-
return (0, core_1.jsonResult)({
|
|
975
|
-
ok: true,
|
|
976
|
-
dryRun: true,
|
|
977
|
-
accountId: reactionAccountId,
|
|
978
|
-
chatId: reactionParams.target,
|
|
979
|
-
messageId: reactionParams.messageId,
|
|
980
|
-
removed: reactionParams.remove,
|
|
981
|
-
});
|
|
982
|
-
}
|
|
983
|
-
const reactionGram = requireRuntimeFor(reactionAccountId);
|
|
984
|
-
await reactionGram.sendReaction(reactionParams);
|
|
985
|
-
return (0, core_1.jsonResult)({
|
|
986
|
-
ok: true,
|
|
987
|
-
accountId: reactionAccountId,
|
|
988
|
-
chatId: reactionParams.target,
|
|
989
|
-
messageId: reactionParams.messageId,
|
|
990
|
-
removed: reactionParams.remove,
|
|
991
|
-
});
|
|
992
|
-
}
|
|
993
|
-
// ---- Chat management (2.12.0) ----
|
|
994
|
-
//
|
|
995
|
-
// Assembling a chat rather than speaking in it: create a supergroup,
|
|
996
|
-
// add and remove people, appoint admins, hand the chat over, issue an
|
|
997
|
-
// invite link. All of it is possible only because this is a personal
|
|
998
|
-
// MTProto account — a bot could do almost none of this.
|
|
999
|
-
//
|
|
1000
|
-
// Every branch is gated by the account's `manageChats` scope, which is
|
|
1001
|
-
// opt-in (absent = deny, see manage.ts) — these are the first actions
|
|
1002
|
-
// that change a chat rather than write into it. Parsing runs before
|
|
1003
|
-
// the gate so a malformed call fails on its own shape, and `dryRun`
|
|
1004
|
-
// returns after the gate so a dry run exercises the same refusals a
|
|
1005
|
-
// real call would hit. People's ids stay out of the logs throughout;
|
|
1006
|
-
// the JSON result carries them to the caller, the journal does not.
|
|
1007
|
-
const manageAction = actions_1.MANAGE_ACTIONS.has(canonical) ? canonical : undefined;
|
|
1008
|
-
if (manageAction) {
|
|
1009
|
-
const manageAccountId = resolveRuntimeAccountId(cfg, accountId);
|
|
1010
|
-
if (!manageAccountId) {
|
|
1011
|
-
throw new Error("clawgram: no configured account found");
|
|
1012
|
-
}
|
|
1013
|
-
const manageScope = resolveAccountManageChats(cfg, manageAccountId);
|
|
1014
|
-
const requireRuntime = () => requireRuntimeFor(manageAccountId);
|
|
1015
|
-
/**
|
|
1016
|
-
* The scaffold every management action shares.
|
|
1017
|
-
*
|
|
1018
|
-
* Six actions used to spell it out one after another: resolve the
|
|
1019
|
-
* account, check the scope, log, answer a dry run, call the
|
|
1020
|
-
* runtime, log again, build the result. A change to any of those —
|
|
1021
|
-
* the dry-run contract, say — was a six-place edit in the plugin's
|
|
1022
|
-
* largest file, and the one deliberate exception (createGroup does
|
|
1023
|
-
* not check a chat scope, because the chat does not exist yet) was
|
|
1024
|
-
* invisible among the copies (finding A12-06).
|
|
1025
|
-
*
|
|
1026
|
-
* The differences stay written at each call site: what to parse,
|
|
1027
|
-
* what to log, what to run, what to answer. Only the scaffold moved.
|
|
1028
|
-
*/
|
|
1029
|
-
const runManage = async (spec) => {
|
|
1030
|
-
const parsed = spec.parse();
|
|
1031
|
-
const target = spec.target(parsed);
|
|
1032
|
-
if (target === undefined) {
|
|
1033
|
-
// Nothing to check a scope against yet, so the gate is coarser:
|
|
1034
|
-
// management must be enabled at all for this account.
|
|
1035
|
-
if (!(0, manage_1.isManagementEnabled)(manageScope)) {
|
|
1036
|
-
actionLog.warn(`clawgram ${spec.name} refused: management is not enabled`, {
|
|
1037
|
-
accountId: manageAccountId,
|
|
1038
|
-
});
|
|
1039
|
-
throw new Error("clawgram: chat management is not enabled for this account — "
|
|
1040
|
-
+ `set channels.clawgram.accounts.${manageAccountId}.manageChats`);
|
|
1041
|
-
}
|
|
1042
|
-
}
|
|
1043
|
-
else if (!(0, manage_1.isChatManageable)(target, manageScope)) {
|
|
1044
|
-
actionLog.warn("clawgram management refused: chat outside manage scope", {
|
|
1045
|
-
accountId: manageAccountId,
|
|
1046
|
-
action: manageAction,
|
|
1047
|
-
target,
|
|
1048
|
-
});
|
|
1049
|
-
throw new Error(`clawgram: not-managed-chat ${target}`);
|
|
1050
|
-
}
|
|
1051
|
-
actionLog.info(`clawgram handleAction ${spec.name}`, {
|
|
1052
|
-
accountId: manageAccountId,
|
|
1053
|
-
dryRun: dryRun === true,
|
|
1054
|
-
...spec.before(parsed),
|
|
1055
|
-
});
|
|
1056
|
-
if (dryRun === true) {
|
|
1057
|
-
return (0, core_1.jsonResult)({
|
|
1058
|
-
ok: true,
|
|
1059
|
-
dryRun: true,
|
|
1060
|
-
accountId: manageAccountId,
|
|
1061
|
-
...(target === undefined ? {} : { chatId: target }),
|
|
1062
|
-
});
|
|
1063
|
-
}
|
|
1064
|
-
const gram = requireRuntime();
|
|
1065
|
-
spec.precondition?.(gram);
|
|
1066
|
-
const result = await spec.run(gram, parsed);
|
|
1067
|
-
actionLog.info(`clawgram handleAction ${spec.name} completed`, {
|
|
1068
|
-
accountId: manageAccountId,
|
|
1069
|
-
...spec.after(parsed, result),
|
|
1070
|
-
});
|
|
1071
|
-
return (0, core_1.jsonResult)({ ok: true, accountId: manageAccountId, ...spec.result(parsed, result) });
|
|
1072
|
-
};
|
|
1073
|
-
if (manageAction === "createGroup") {
|
|
1074
|
-
return await runManage({
|
|
1075
|
-
name: "createGroup",
|
|
1076
|
-
parse: () => (0, manage_1.parseCreateGroupParams)(params),
|
|
1077
|
-
// A group being created is not in any scope yet.
|
|
1078
|
-
target: () => undefined,
|
|
1079
|
-
before: (p) => ({ users: p.users.length, hasAbout: Boolean(p.about) }),
|
|
1080
|
-
run: (gram, p) => gram.createGroup(p),
|
|
1081
|
-
after: (_p, created) => ({ chatId: created.chatId ?? null, missing: created.missing.length }),
|
|
1082
|
-
result: (_p, created) => ({ chatId: created.chatId, missing: created.missing }),
|
|
1083
|
-
});
|
|
1084
|
-
}
|
|
1085
|
-
if (manageAction === "addMembers") {
|
|
1086
|
-
return await runManage({
|
|
1087
|
-
name: "addMembers",
|
|
1088
|
-
parse: () => (0, manage_1.parseAddMembersParams)(params, toolContext),
|
|
1089
|
-
target: (p) => p.target,
|
|
1090
|
-
before: (p) => ({ target: p.target, users: p.users.length }),
|
|
1091
|
-
run: (gram, p) => gram.addChatMembers(p),
|
|
1092
|
-
after: (p, added) => ({
|
|
1093
|
-
target: p.target,
|
|
1094
|
-
requested: p.users.length,
|
|
1095
|
-
missing: added.missing.length,
|
|
1096
|
-
}),
|
|
1097
|
-
result: (p, added) => ({
|
|
1098
|
-
chatId: added.chatId ?? p.target,
|
|
1099
|
-
requested: p.users.length,
|
|
1100
|
-
// Telegram refuses silently-restricted invites per user; the
|
|
1101
|
-
// caller gets the ids so it can hand them an invite link.
|
|
1102
|
-
missing: added.missing,
|
|
1103
|
-
}),
|
|
1104
|
-
});
|
|
1105
|
-
}
|
|
1106
|
-
if (manageAction === "removeMember") {
|
|
1107
|
-
return await runManage({
|
|
1108
|
-
name: "removeMember",
|
|
1109
|
-
parse: () => (0, manage_1.parseRemoveMemberParams)(params, toolContext),
|
|
1110
|
-
target: (p) => p.target,
|
|
1111
|
-
before: (p) => ({ target: p.target, ban: p.ban }),
|
|
1112
|
-
run: (gram, p) => gram.removeChatMember(p),
|
|
1113
|
-
after: (p) => ({ target: p.target, ban: p.ban }),
|
|
1114
|
-
result: (p) => ({ chatId: p.target, user: p.user, banned: p.ban }),
|
|
1115
|
-
});
|
|
1116
|
-
}
|
|
1117
|
-
if (manageAction === "promoteAdmin" || manageAction === "demoteAdmin") {
|
|
1118
|
-
const promote = manageAction === "promoteAdmin";
|
|
1119
|
-
return await runManage({
|
|
1120
|
-
// Both spellings log as `setAdmin`, as they always have.
|
|
1121
|
-
name: "setAdmin",
|
|
1122
|
-
parse: () => (promote
|
|
1123
|
-
? (0, manage_1.parsePromoteAdminParams)(params, toolContext)
|
|
1124
|
-
: (0, manage_1.parseDemoteAdminParams)(params, toolContext)),
|
|
1125
|
-
target: (p) => p.target,
|
|
1126
|
-
before: (p) => ({ target: p.target, isAdmin: p.isAdmin, hasRank: Boolean(p.rank) }),
|
|
1127
|
-
run: (gram, p) => gram.setChatAdmin(p),
|
|
1128
|
-
after: (p) => ({ target: p.target, isAdmin: p.isAdmin }),
|
|
1129
|
-
result: (p) => ({
|
|
1130
|
-
chatId: p.target,
|
|
1131
|
-
user: p.user,
|
|
1132
|
-
isAdmin: p.isAdmin,
|
|
1133
|
-
...(p.rank ? { rank: p.rank } : {}),
|
|
1134
|
-
}),
|
|
1135
|
-
});
|
|
1136
|
-
}
|
|
1137
|
-
if (manageAction === "transferOwnership") {
|
|
1138
|
-
return await runManage({
|
|
1139
|
-
name: "transferOwnership",
|
|
1140
|
-
parse: () => (0, manage_1.parseTransferOwnershipParams)(params, toolContext),
|
|
1141
|
-
target: (p) => p.target,
|
|
1142
|
-
before: (p) => ({ target: p.target }),
|
|
1143
|
-
// The password stays inside the runtime: it is read from the
|
|
1144
|
-
// account config at start-up and never travels through dispatch
|
|
1145
|
-
// arguments, which are one log call away from the journal.
|
|
1146
|
-
precondition: (gram) => {
|
|
1147
|
-
if (!gram.twoFaPassword) {
|
|
1148
|
-
throw new Error("clawgram: ownership transfer requires twoFaPassword in the account config "
|
|
1149
|
-
+ "(the account's Telegram 2FA password, as a literal or a SecretRef)");
|
|
1150
|
-
}
|
|
1151
|
-
},
|
|
1152
|
-
run: (gram, p) => gram.transferChatOwnership(p),
|
|
1153
|
-
after: (p) => ({ target: p.target }),
|
|
1154
|
-
result: (p) => ({ chatId: p.target, newOwner: p.user }),
|
|
1155
|
-
});
|
|
1156
|
-
}
|
|
1157
|
-
// inviteLink — the only management action left.
|
|
1158
|
-
return await runManage({
|
|
1159
|
-
name: "inviteLink",
|
|
1160
|
-
parse: () => (0, manage_1.parseInviteLinkParams)(params, toolContext),
|
|
1161
|
-
target: (p) => p.target,
|
|
1162
|
-
before: (p) => ({
|
|
1163
|
-
target: p.target,
|
|
1164
|
-
hasExpiry: p.expireDate !== undefined,
|
|
1165
|
-
usageLimit: p.usageLimit ?? null,
|
|
1166
|
-
requestNeeded: p.requestNeeded,
|
|
1167
|
-
}),
|
|
1168
|
-
run: (gram, p) => gram.exportChatInviteLink(p),
|
|
1169
|
-
after: (p, exported) => ({ target: p.target, hasLink: Boolean(exported.link) }),
|
|
1170
|
-
result: (p, exported) => ({ chatId: p.target, link: exported.link }),
|
|
1171
|
-
});
|
|
1172
|
-
}
|
|
1173
|
-
// Core normalizes whichever of these it filled in to a local path (see
|
|
1174
|
-
// `mediaSourceParams` above); `mediaUrl` stays a URL, which GramJS
|
|
1175
|
-
// accepts as well.
|
|
1176
|
-
const attachedFile = (0, param_readers_1.readStringParam)(params, "filePath")
|
|
1177
|
-
?? (0, param_readers_1.readStringParam)(params, "path")
|
|
1178
|
-
?? (0, param_readers_1.readStringParam)(params, "media")
|
|
1179
|
-
?? (0, param_readers_1.readStringParam)(params, "mediaUrl");
|
|
1180
|
-
// Core dispatches `upload-file`; `sendAttachment` is its legacy alias
|
|
1181
|
-
// and arrives from older callers. A plain `send` carrying a file lands
|
|
1182
|
-
// here too — `openclaw message send --media` does exactly that, and
|
|
1183
|
-
// routing it to the text path dropped the file without a word.
|
|
1184
|
-
if (canonical === "upload-file" || (canonical === "send" && attachedFile)) {
|
|
1185
|
-
const rawUploadTo = (0, helpers_1.resolveActionTarget)(params, toolContext);
|
|
1186
|
-
const uploadTo = (0, helpers_1.normalizeOutboundTarget)(rawUploadTo);
|
|
1187
|
-
const uploadAccountId = resolveRuntimeAccountId(cfg, accountId);
|
|
1188
|
-
if (!uploadAccountId) {
|
|
1189
|
-
throw new Error("clawgram: no configured account found");
|
|
1190
|
-
}
|
|
1191
|
-
// Та же граница, что у `send`: файл наружу — такое же исходящее.
|
|
1192
|
-
if (!(0, send_scope_1.isChatSendable)(uploadTo, resolveAccountSendChats(cfg, uploadAccountId))) {
|
|
1193
|
-
refuseOutboundOutsideScope("upload-file", uploadAccountId, uploadTo);
|
|
1194
|
-
}
|
|
1195
|
-
if (!attachedFile) {
|
|
1196
|
-
throw new Error("clawgram: upload-file requires filePath, path, media, or mediaUrl");
|
|
1197
|
-
}
|
|
1198
|
-
// Before anything else about the message is considered: an
|
|
1199
|
-
// out-of-scope path is refused, not sent and then regretted.
|
|
1200
|
-
(0, media_1.assertLocalMediaWithinRoots)(attachedFile, allowedMediaRoots);
|
|
1201
|
-
const captionText = (0, helpers_1.readMessageText)(params) || ((0, param_readers_1.readStringParam)(params, "caption") ?? "");
|
|
1202
|
-
// A caption is optional, but the silent-reply sentinel must never
|
|
1203
|
-
// reach Telegram as one — same reasoning as the `send` path below.
|
|
1204
|
-
const caption = captionText.trim() && (0, helpers_1.isSilentReplyText)(captionText)
|
|
1205
|
-
? ""
|
|
1206
|
-
: captionText.replaceAll("\\n", "\n");
|
|
1207
|
-
const uploadReplyToId = (0, param_readers_1.readStringOrNumberParam)(params, "replyToId") ?? (0, param_readers_1.readStringOrNumberParam)(params, "replyTo");
|
|
1208
|
-
const uploadThreadId = (0, param_readers_1.readStringOrNumberParam)(params, "threadId");
|
|
1209
|
-
const asVoice = (0, helpers_1.readVoiceNoteFlag)(params);
|
|
1210
|
-
actionLog.info("clawgram handleAction upload-file", {
|
|
1211
|
-
accountId: uploadAccountId,
|
|
1212
|
-
dryRun: dryRun === true,
|
|
1213
|
-
to: uploadTo,
|
|
1214
|
-
hasCaption: Boolean(caption),
|
|
1215
|
-
replyToId: uploadReplyToId ?? null,
|
|
1216
|
-
threadId: uploadThreadId ?? null,
|
|
1217
|
-
asVoice,
|
|
1218
|
-
});
|
|
1219
|
-
if (dryRun === true) {
|
|
1220
|
-
return (0, core_1.jsonResult)({
|
|
1221
|
-
ok: true,
|
|
1222
|
-
dryRun: true,
|
|
1223
|
-
to: uploadTo,
|
|
1224
|
-
accountId: uploadAccountId,
|
|
1225
|
-
});
|
|
1226
|
-
}
|
|
1227
|
-
const uploadGram = requireRuntimeFor(uploadAccountId);
|
|
1228
|
-
// Read last, through core's scoped reader when it gave one: a dry
|
|
1229
|
-
// run or a refusal above must not open the file.
|
|
1230
|
-
const file = await (0, media_1.loadOutboundMedia)(attachedFile, allowedMediaRoots, readMedia);
|
|
1231
|
-
const uploaded = await uploadGram.sendMedia({
|
|
1232
|
-
target: uploadTo,
|
|
1233
|
-
file,
|
|
1234
|
-
caption: caption || undefined,
|
|
1235
|
-
// Same resolution as the text `send`: per-call value wins, an
|
|
1236
|
-
// omitted one inherits the account format (2.15.0). A caption is
|
|
1237
|
-
// the same prose as a message and renders identically.
|
|
1238
|
-
parseMode: (0, helpers_1.resolveOutboundParseMode)(params, cfg, uploadAccountId),
|
|
1239
|
-
replyToMessageId: (0, helpers_1.resolveReplyToMessageIdForTarget)(rawUploadTo, uploadReplyToId),
|
|
1240
|
-
messageThreadId: (0, helpers_1.parseOptionalThreadId)(uploadThreadId),
|
|
1241
|
-
asVoice,
|
|
1242
|
-
});
|
|
1243
|
-
actionLog.info("clawgram handleAction upload-file completed", {
|
|
1244
|
-
accountId: uploadAccountId,
|
|
1245
|
-
to: uploadTo,
|
|
1246
|
-
sentMessageId: String(uploaded?.id ?? ""),
|
|
1247
|
-
});
|
|
1248
|
-
return (0, core_1.jsonResult)({
|
|
1249
|
-
ok: true,
|
|
1250
|
-
to: uploadTo,
|
|
1251
|
-
accountId: uploadAccountId,
|
|
1252
|
-
messageId: String(uploaded?.id ?? ""),
|
|
1253
|
-
});
|
|
1254
|
-
}
|
|
1255
|
-
if (action !== "send") {
|
|
1256
|
-
throw new Error(`clawgram: unsupported message action ${action}`);
|
|
1257
|
-
}
|
|
1258
|
-
const rawTo = (0, helpers_1.resolveActionTarget)(params, toolContext);
|
|
1259
|
-
const targetKind = (0, helpers_1.inferOutboundTargetKind)(rawTo);
|
|
1260
|
-
const to = (0, helpers_1.normalizeOutboundTarget)(rawTo);
|
|
1261
|
-
const replyToId = (0, param_readers_1.readStringOrNumberParam)(params, "replyToId") ?? (0, param_readers_1.readStringOrNumberParam)(params, "replyTo");
|
|
1262
|
-
const threadId = (0, param_readers_1.readStringOrNumberParam)(params, "threadId");
|
|
1263
|
-
const messageThreadId = (0, helpers_1.parseOptionalThreadId)(threadId);
|
|
1264
|
-
// Omitting parseMode inherits the account's configured mode rather
|
|
1265
|
-
// than falling back to plain text (2.13.0): an account set to `html`
|
|
1266
|
-
// used to render replies as HTML and these sends as raw markup.
|
|
1267
|
-
const parseMode = (0, helpers_1.resolveOutboundParseMode)(params, cfg, (0, helpers_1.resolveConfiguredAccountId)(cfg, accountId) ?? accountId ?? "default");
|
|
1268
|
-
actionLog.info("clawgram handleAction send", {
|
|
1269
|
-
requestedAccountId: accountId,
|
|
1270
|
-
dryRun: dryRun === true,
|
|
1271
|
-
rawTo,
|
|
1272
|
-
to,
|
|
1273
|
-
targetKind,
|
|
1274
|
-
replyToId: replyToId ?? null,
|
|
1275
|
-
threadId: threadId ?? null,
|
|
1276
|
-
parseMode: parseMode ?? null,
|
|
1277
|
-
toolContextCurrentChannelId: toolContext?.currentChannelId ?? null,
|
|
1278
|
-
});
|
|
1279
|
-
const resolvedAccountId = resolveRuntimeAccountId(cfg, accountId);
|
|
1280
|
-
if (!resolvedAccountId) {
|
|
1281
|
-
throw new Error("clawgram: no configured account found");
|
|
1282
|
-
}
|
|
1283
|
-
// Проверка ПОСЛЕ резолва аккаунта и ДО любой доставки: область задаётся
|
|
1284
|
-
// на аккаунт, а отказ должен случиться раньше, чем цель разрешена в
|
|
1285
|
-
// Telegram-сущность — resolve сам по себе виден собеседнику (A5-12).
|
|
1286
|
-
if (!(0, send_scope_1.isChatSendable)(to, resolveAccountSendChats(cfg, resolvedAccountId))) {
|
|
1287
|
-
refuseOutboundOutsideScope("send", resolvedAccountId, to);
|
|
1288
|
-
}
|
|
1289
|
-
const currentChannelId = toolContext?.currentChannelId?.trim() ?? "";
|
|
1290
|
-
const currentMessageId = toolContext?.currentMessageId;
|
|
1291
|
-
const currentChannelTarget = currentChannelId ? (0, helpers_1.normalizeOutboundTarget)(currentChannelId) : "";
|
|
1292
|
-
const sendingToCurrentGroup = Boolean(currentChannelTarget &&
|
|
1293
|
-
currentChannelTarget === to &&
|
|
1294
|
-
targetKind === "group");
|
|
1295
|
-
if (sendingToCurrentGroup &&
|
|
1296
|
-
!replyToId &&
|
|
1297
|
-
currentMessageId !== null &&
|
|
1298
|
-
currentMessageId !== undefined &&
|
|
1299
|
-
(0, group_visible_reply_guard_1.hasRecentVisibleGroupReply)({
|
|
1300
|
-
accountId: resolvedAccountId,
|
|
1301
|
-
chatId: to,
|
|
1302
|
-
currentMessageId,
|
|
1303
|
-
})) {
|
|
1304
|
-
actionLog.warn("clawgram suppressing duplicate visible group reply", {
|
|
1305
|
-
accountId: resolvedAccountId,
|
|
1306
|
-
to,
|
|
1307
|
-
currentMessageId: String(currentMessageId),
|
|
1308
|
-
toolContextCurrentChannelId: currentChannelId || null,
|
|
1309
|
-
});
|
|
1310
|
-
// A dry run reports the suppression instead of impersonating it: the
|
|
1311
|
-
// caller asked what would happen, and what would happen is nothing.
|
|
1312
|
-
return (0, core_1.jsonResult)({
|
|
1313
|
-
ok: true,
|
|
1314
|
-
...(dryRun ? { dryRun: true } : {}),
|
|
1315
|
-
suppressedDuplicate: true,
|
|
1316
|
-
to,
|
|
1317
|
-
accountId: resolvedAccountId,
|
|
1318
|
-
});
|
|
1319
|
-
}
|
|
1320
|
-
// Whom to greet is decided by the message this turn is answering, not
|
|
1321
|
-
// by whoever spoke last. An agent replying to a request rarely passes
|
|
1322
|
-
// `replyToId`, and until 2026-08-10 that fell through to the most
|
|
1323
|
-
// recent sender: in an interleaved chat the owner's report went out
|
|
1324
|
-
// addressed to a colleague who had asked something else entirely.
|
|
1325
|
-
// A dry run peeks: consuming the address here left the real send with
|
|
1326
|
-
// no greeting, so a rehearsal silently changed the message that went
|
|
1327
|
-
// out afterwards.
|
|
1328
|
-
const groupReplyAddress = (dryRun ? group_reply_address_1.peekGroupReplyAddress : group_reply_address_1.consumeGroupReplyAddress)({
|
|
1329
|
-
accountId: resolvedAccountId,
|
|
1330
|
-
chatId: to,
|
|
1331
|
-
replyToId: replyToId ?? currentMessageId,
|
|
1332
|
-
});
|
|
1333
|
-
const requestedText = (0, helpers_1.readMessageText)(params).replaceAll("\\n", "\n");
|
|
1334
|
-
// `NO_REPLY` is OpenClaw's "say nothing" sentinel. The inbound pipeline
|
|
1335
|
-
// and core both strip it, but an explicit `message.action` call is
|
|
1336
|
-
// neither path — and the SDK itself prompts agents to send a message
|
|
1337
|
-
// and *then* answer NO_REPLY, so the two are one slip apart. Posting
|
|
1338
|
-
// the token into a work chat looks like the assistant malfunctioning.
|
|
1339
|
-
//
|
|
1340
|
-
// Checked before the reply-address prefix on purpose: prefixing first
|
|
1341
|
-
// leaves "Name: " behind, which is not empty, and the token goes out.
|
|
1342
|
-
// That is precisely how it once reached the inbound path.
|
|
1343
|
-
if (requestedText.trim() && (0, helpers_1.isSilentReplyText)(requestedText)) {
|
|
1344
|
-
actionLog.info("clawgram suppressing silent send", {
|
|
1345
|
-
accountId: resolvedAccountId,
|
|
1346
|
-
to,
|
|
1347
|
-
});
|
|
1348
|
-
return (0, core_1.jsonResult)({
|
|
1349
|
-
ok: true,
|
|
1350
|
-
skipped: "silent",
|
|
1351
|
-
sent: false,
|
|
1352
|
-
to,
|
|
1353
|
-
accountId: resolvedAccountId,
|
|
1354
|
-
});
|
|
1355
|
-
}
|
|
1356
|
-
const text = (0, helpers_1.prefixReplyTextToAddress)(requestedText, groupReplyAddress);
|
|
1357
|
-
if (!text) {
|
|
1358
|
-
throw new Error("clawgram: message text is required");
|
|
1359
|
-
}
|
|
1360
|
-
if (dryRun) {
|
|
1361
|
-
return (0, core_1.jsonResult)({
|
|
1362
|
-
ok: true,
|
|
1363
|
-
dryRun: true,
|
|
1364
|
-
to,
|
|
1365
|
-
accountId: resolvedAccountId,
|
|
1366
|
-
});
|
|
1367
|
-
}
|
|
1368
|
-
const gram = requireRuntimeFor(resolvedAccountId);
|
|
1369
|
-
const sent = await gram.sendText({
|
|
1370
|
-
target: to,
|
|
1371
|
-
text,
|
|
1372
|
-
targetKind,
|
|
1373
|
-
replyToMessageId: (0, helpers_1.resolveReplyToMessageIdForTarget)(rawTo, replyToId),
|
|
1374
|
-
messageThreadId,
|
|
1375
|
-
parseMode,
|
|
1376
|
-
});
|
|
1377
|
-
if (sendingToCurrentGroup &&
|
|
1378
|
-
!replyToId &&
|
|
1379
|
-
currentMessageId !== null &&
|
|
1380
|
-
currentMessageId !== undefined) {
|
|
1381
|
-
(0, group_visible_reply_guard_1.rememberVisibleGroupReply)({
|
|
1382
|
-
accountId: resolvedAccountId,
|
|
1383
|
-
chatId: to,
|
|
1384
|
-
currentMessageId,
|
|
1385
|
-
});
|
|
1386
|
-
}
|
|
1387
|
-
// The turn has now spoken for itself. Recorded for every send into the
|
|
1388
|
-
// chat this turn came from — with or without an explicit replyToId —
|
|
1389
|
-
// so that core delivering the turn's final text a few seconds later
|
|
1390
|
-
// can be recognised as an echo of this same answer.
|
|
1391
|
-
if (currentMessageId !== null && currentMessageId !== undefined) {
|
|
1392
|
-
(0, group_visible_reply_guard_1.rememberTurnSend)({
|
|
1393
|
-
accountId: resolvedAccountId,
|
|
1394
|
-
chatId: to,
|
|
1395
|
-
currentMessageId,
|
|
1396
|
-
});
|
|
1397
|
-
}
|
|
1398
|
-
actionLog.info("clawgram handleAction send completed", {
|
|
1399
|
-
accountId: resolvedAccountId,
|
|
1400
|
-
to,
|
|
1401
|
-
replyToId: replyToId ?? null,
|
|
1402
|
-
sentMessageId: String(sent?.id ?? ""),
|
|
1403
|
-
});
|
|
1404
|
-
return (0, core_1.jsonResult)({
|
|
1405
|
-
ok: true,
|
|
1406
|
-
to,
|
|
1407
|
-
accountId: resolvedAccountId,
|
|
1408
|
-
messageId: String(sent?.id ?? ""),
|
|
1409
|
-
});
|
|
517
|
+
// Reads first, then management, then the outbound actions — which end
|
|
518
|
+
// with `send` and refuse whatever nobody claimed. Each module answers
|
|
519
|
+
// `undefined` for an action that is not its own (B5-13, part 3).
|
|
520
|
+
return (await (0, actions_read_1.handleReadAction)(context))
|
|
521
|
+
?? (await (0, actions_manage_1.handleManageAction)(context))
|
|
522
|
+
?? (await (0, actions_send_1.handleSendAction)(context));
|
|
1410
523
|
},
|
|
1411
524
|
},
|
|
1412
525
|
outbound: (0, outbound_1.createOutbound)(runtimes),
|