@celljs/ta-bots 0.0.0-stage → 4.9.1
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/README.en.md +46 -0
- package/README.md +45 -2
- package/extension/index.mjs +629 -0
- package/host/index.mjs +2313 -0
- package/package.json +53 -4
- package/web/index.js +1241 -0
|
@@ -0,0 +1,629 @@
|
|
|
1
|
+
// ../ta-protocol/esm/common/access-protocol.js
|
|
2
|
+
var TaAccessServer = Symbol("TaAccessServer");
|
|
3
|
+
// ../ta-protocol/esm/common/auth-protocol.js
|
|
4
|
+
var TaAuthServer = Symbol("TaAuthServer");
|
|
5
|
+
// ../ta-protocol/esm/common/gateway-protocol.js
|
|
6
|
+
var TaGatewayServer = Symbol("TaGatewayServer");
|
|
7
|
+
// ../ta-protocol/esm/common/location.js
|
|
8
|
+
var TaLocation;
|
|
9
|
+
(function(TaLocation2) {
|
|
10
|
+
TaLocation2.SSH = "ssh://";
|
|
11
|
+
const HOST = /^(?!-)[\w.@:%+[\]-]+$/;
|
|
12
|
+
function isRemote(location) {
|
|
13
|
+
return location.startsWith(TaLocation2.SSH);
|
|
14
|
+
}
|
|
15
|
+
TaLocation2.isRemote = isRemote;
|
|
16
|
+
function parse(location) {
|
|
17
|
+
if (!isRemote(location)) {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
const rest = location.slice(TaLocation2.SSH.length);
|
|
21
|
+
const slash = rest.indexOf("/");
|
|
22
|
+
const host2 = slash < 0 ? rest : rest.slice(0, slash);
|
|
23
|
+
const path2 = slash < 0 ? "" : normalize(rest.slice(slash));
|
|
24
|
+
if (!isHost(host2)) {
|
|
25
|
+
throw new Error(`${JSON.stringify(location)} names no host: write ssh://<host>/<path>, the host as ssh takes it.`);
|
|
26
|
+
}
|
|
27
|
+
return { host: host2, path: path2 };
|
|
28
|
+
}
|
|
29
|
+
TaLocation2.parse = parse;
|
|
30
|
+
function isHost(host2) {
|
|
31
|
+
return HOST.test(host2);
|
|
32
|
+
}
|
|
33
|
+
TaLocation2.isHost = isHost;
|
|
34
|
+
const FLAGS = /^-[46AaCfGgKkMNnqsTtVvXxYy]+$/;
|
|
35
|
+
function readHost(input) {
|
|
36
|
+
const words = input.trim().split(/\s+/).filter(Boolean);
|
|
37
|
+
if (words[0] === "ssh") {
|
|
38
|
+
words.shift();
|
|
39
|
+
}
|
|
40
|
+
let destination;
|
|
41
|
+
let port;
|
|
42
|
+
let user;
|
|
43
|
+
const options = [];
|
|
44
|
+
for (let i = 0;i < words.length; i++) {
|
|
45
|
+
const word = words[i];
|
|
46
|
+
const glued = /^-([pl])(.+)$/.exec(word);
|
|
47
|
+
if (word === "-p" || word === "-l" || glued) {
|
|
48
|
+
const value = glued ? glued[2] : words[++i];
|
|
49
|
+
if (value === undefined) {
|
|
50
|
+
return { error: "invalid" };
|
|
51
|
+
}
|
|
52
|
+
if ((glued ? glued[1] : word[1]) === "p") {
|
|
53
|
+
port = value;
|
|
54
|
+
} else {
|
|
55
|
+
user = value;
|
|
56
|
+
}
|
|
57
|
+
} else if (word === "-o" || word.startsWith("-o")) {
|
|
58
|
+
const value = word === "-o" ? words[++i] : word.slice(2);
|
|
59
|
+
const option = /^(port|user)\s*=?\s*(.+)$/i.exec(value !== null && value !== undefined ? value : "");
|
|
60
|
+
if (!option) {
|
|
61
|
+
options.push(`-o ${value !== null && value !== undefined ? value : ""}`.trim());
|
|
62
|
+
} else if (option[1].toLowerCase() === "port") {
|
|
63
|
+
port = option[2];
|
|
64
|
+
} else {
|
|
65
|
+
user = option[2];
|
|
66
|
+
}
|
|
67
|
+
} else if (FLAGS.test(word)) {} else if (word.startsWith("-")) {
|
|
68
|
+
options.push(/^-[bBcDeEFiIJLmOQRSwW]$/.test(word) && words[i + 1] !== undefined ? `${word} ${words[++i]}` : word);
|
|
69
|
+
} else if (destination === undefined) {
|
|
70
|
+
destination = word;
|
|
71
|
+
} else {
|
|
72
|
+
return { error: "invalid" };
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (options.length > 0) {
|
|
76
|
+
return { error: "options", options };
|
|
77
|
+
}
|
|
78
|
+
if (!destination) {
|
|
79
|
+
return { error: "empty" };
|
|
80
|
+
}
|
|
81
|
+
let host2 = destination.replace(/^ssh:\/\//, "").replace(/\/.*$/, "");
|
|
82
|
+
if (user && !host2.includes("@")) {
|
|
83
|
+
host2 = `${user}@${host2}`;
|
|
84
|
+
}
|
|
85
|
+
if (port) {
|
|
86
|
+
if (!/^\d{1,5}$/.test(port) || /:\d+$/.test(host2)) {
|
|
87
|
+
return { error: "invalid" };
|
|
88
|
+
}
|
|
89
|
+
host2 = port === "22" ? host2 : `${host2}:${port}`;
|
|
90
|
+
}
|
|
91
|
+
return isHost(host2) ? { host: host2 } : { error: "invalid" };
|
|
92
|
+
}
|
|
93
|
+
TaLocation2.readHost = readHost;
|
|
94
|
+
function ssh(host2, path2 = "") {
|
|
95
|
+
return `${TaLocation2.SSH}${host2}${path2 ? normalize(path2) : ""}`;
|
|
96
|
+
}
|
|
97
|
+
TaLocation2.ssh = ssh;
|
|
98
|
+
function hostLabel(host2) {
|
|
99
|
+
const name = host2.replace(/^[^@]*@/, "").replace(/^\[(.*)\](?::\d+)?$/, "$1").replace(/^([^:]*):\d+$/, "$1");
|
|
100
|
+
return /^[\d.]+$/.test(name) || name.includes(":") ? name : name.split(".")[0] || name;
|
|
101
|
+
}
|
|
102
|
+
TaLocation2.hostLabel = hostLabel;
|
|
103
|
+
function host(location) {
|
|
104
|
+
var _a;
|
|
105
|
+
return isRemote(location) ? (_a = parse(location)) === null || _a === undefined ? undefined : _a.host : undefined;
|
|
106
|
+
}
|
|
107
|
+
TaLocation2.host = host;
|
|
108
|
+
function path(location) {
|
|
109
|
+
var _a;
|
|
110
|
+
var _b;
|
|
111
|
+
return (_b = (_a = parse(location)) === null || _a === undefined ? undefined : _a.path) !== null && _b !== undefined ? _b : location;
|
|
112
|
+
}
|
|
113
|
+
TaLocation2.path = path;
|
|
114
|
+
function parent(location) {
|
|
115
|
+
const remote = parse(location);
|
|
116
|
+
if (remote) {
|
|
117
|
+
const above = remote.path ? parentPath(remote.path) : undefined;
|
|
118
|
+
return above === undefined ? undefined : ssh(remote.host, above);
|
|
119
|
+
}
|
|
120
|
+
return parentPath(location);
|
|
121
|
+
}
|
|
122
|
+
TaLocation2.parent = parent;
|
|
123
|
+
function child(location, name) {
|
|
124
|
+
const remote = parse(location);
|
|
125
|
+
if (remote) {
|
|
126
|
+
return ssh(remote.host, childPath(remote.path || "/", name));
|
|
127
|
+
}
|
|
128
|
+
return childPath(location, name);
|
|
129
|
+
}
|
|
130
|
+
TaLocation2.child = child;
|
|
131
|
+
function basename(location) {
|
|
132
|
+
const remote = parse(location);
|
|
133
|
+
const path2 = (remote ? remote.path : location).replace(/[\\/]+$/, "");
|
|
134
|
+
const name = path2.slice(Math.max(path2.lastIndexOf("/"), path2.lastIndexOf("\\")) + 1);
|
|
135
|
+
return name || (remote === null || remote === undefined ? undefined : remote.host) || location;
|
|
136
|
+
}
|
|
137
|
+
TaLocation2.basename = basename;
|
|
138
|
+
function parentPath(path2) {
|
|
139
|
+
const trimmed = path2.replace(/[\\/]+$/, "");
|
|
140
|
+
const at = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
|
|
141
|
+
if (at < 0) {
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const head = trimmed.slice(0, at);
|
|
145
|
+
return head === "" || /^[A-Za-z]:$/.test(head) ? head + trimmed[at] : head;
|
|
146
|
+
}
|
|
147
|
+
function childPath(path2, name) {
|
|
148
|
+
const separator = path2.includes("/") || !path2.includes("\\") ? "/" : "\\";
|
|
149
|
+
return path2.endsWith(separator) ? path2 + name : path2 + separator + name;
|
|
150
|
+
}
|
|
151
|
+
function normalize(path2) {
|
|
152
|
+
const squeezed = `/${path2}`.replace(/\/+/g, "/");
|
|
153
|
+
return squeezed.length > 1 ? squeezed.replace(/\/$/, "") : squeezed;
|
|
154
|
+
}
|
|
155
|
+
})(TaLocation || (TaLocation = {}));
|
|
156
|
+
// ../ta-protocol/esm/common/package-protocol.js
|
|
157
|
+
var TaPackageServer = Symbol("TaPackageServer");
|
|
158
|
+
var TaPackageTextUtil;
|
|
159
|
+
(function(TaPackageTextUtil2) {
|
|
160
|
+
function pick(text, language) {
|
|
161
|
+
var _a, _b, _c, _d;
|
|
162
|
+
if (text === undefined || typeof text === "string") {
|
|
163
|
+
return text;
|
|
164
|
+
}
|
|
165
|
+
return (_d = (_c = (_b = (_a = text[language]) !== null && _a !== undefined ? _a : text[language.split("-")[0]]) !== null && _b !== undefined ? _b : text.en) !== null && _c !== undefined ? _c : text["en-US"]) !== null && _d !== undefined ? _d : Object.values(text)[0];
|
|
166
|
+
}
|
|
167
|
+
TaPackageTextUtil2.pick = pick;
|
|
168
|
+
})(TaPackageTextUtil || (TaPackageTextUtil = {}));
|
|
169
|
+
// ../ta-protocol/esm/common/relay-protocol.js
|
|
170
|
+
var TaRelayServer = Symbol("TaRelayServer");
|
|
171
|
+
// ../ta-protocol/esm/common/remote-protocol.js
|
|
172
|
+
var TaRemoteServer = Symbol("TaRemoteServer");
|
|
173
|
+
// ../ta-protocol/esm/common/settings-protocol.js
|
|
174
|
+
var TaSettingsServer = Symbol("TaSettingsServer");
|
|
175
|
+
// ../ta-protocol/esm/common/ta-extension-host.js
|
|
176
|
+
var TA_HOST_EVENT = "ta:host";
|
|
177
|
+
// ../ta-protocol/esm/common/ta-protocol.js
|
|
178
|
+
var TaServer = Symbol("TaServer");
|
|
179
|
+
var TaClient = Symbol("TaClient");
|
|
180
|
+
var TaErrorUtil;
|
|
181
|
+
(function(TaErrorUtil2) {
|
|
182
|
+
function code(error) {
|
|
183
|
+
var _a;
|
|
184
|
+
var _b;
|
|
185
|
+
const failure = error;
|
|
186
|
+
const code2 = (_b = failure === null || failure === undefined ? undefined : failure.code) !== null && _b !== undefined ? _b : (_a = failure === null || failure === undefined ? undefined : failure.data) === null || _a === undefined ? undefined : _a.code;
|
|
187
|
+
return typeof code2 === "string" ? code2 : undefined;
|
|
188
|
+
}
|
|
189
|
+
TaErrorUtil2.code = code;
|
|
190
|
+
})(TaErrorUtil || (TaErrorUtil = {}));
|
|
191
|
+
var TaMessageContext;
|
|
192
|
+
(function(TaMessageContext2) {
|
|
193
|
+
const BLOCK = /^<context>\n?[\s\S]*?\n?<\/context>\n?/;
|
|
194
|
+
function wrap(context, message) {
|
|
195
|
+
return `<context>
|
|
196
|
+
${context}
|
|
197
|
+
</context>
|
|
198
|
+
${message}`;
|
|
199
|
+
}
|
|
200
|
+
TaMessageContext2.wrap = wrap;
|
|
201
|
+
function strip(message) {
|
|
202
|
+
return message.replace(BLOCK, "");
|
|
203
|
+
}
|
|
204
|
+
TaMessageContext2.strip = strip;
|
|
205
|
+
})(TaMessageContext || (TaMessageContext = {}));
|
|
206
|
+
var TaSkillUse;
|
|
207
|
+
(function(TaSkillUse2) {
|
|
208
|
+
const BLOCK = /^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;
|
|
209
|
+
function parse(message) {
|
|
210
|
+
var _a;
|
|
211
|
+
const match = BLOCK.exec(message);
|
|
212
|
+
if (!match) {
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
return { name: match[1], location: match[2], content: match[3], message: ((_a = match[4]) === null || _a === undefined ? undefined : _a.trim()) || undefined };
|
|
216
|
+
}
|
|
217
|
+
TaSkillUse2.parse = parse;
|
|
218
|
+
function command(use) {
|
|
219
|
+
return use.message ? `/skill:${use.name} ${use.message}` : `/skill:${use.name}`;
|
|
220
|
+
}
|
|
221
|
+
TaSkillUse2.command = command;
|
|
222
|
+
})(TaSkillUse || (TaSkillUse = {}));
|
|
223
|
+
// ../ta-protocol/esm/common/workspace-protocol.js
|
|
224
|
+
var TaWorkspaceServer = Symbol("TaWorkspaceServer");
|
|
225
|
+
var TaTerminalServer = Symbol("TaTerminalServer");
|
|
226
|
+
var TaExcludedFiles;
|
|
227
|
+
(function(TaExcludedFiles2) {
|
|
228
|
+
TaExcludedFiles2.NAMES = [".git", ".svn", ".hg", ".DS_Store", "Thumbs.db"];
|
|
229
|
+
function has(name) {
|
|
230
|
+
return TaExcludedFiles2.NAMES.includes(name);
|
|
231
|
+
}
|
|
232
|
+
TaExcludedFiles2.has = has;
|
|
233
|
+
function filter(entries) {
|
|
234
|
+
return entries.filter((entry) => !has(entry.name));
|
|
235
|
+
}
|
|
236
|
+
TaExcludedFiles2.filter = filter;
|
|
237
|
+
})(TaExcludedFiles || (TaExcludedFiles = {}));
|
|
238
|
+
var TA_UPLOAD_PART_BYTES = 4 * 1024 * 1024;
|
|
239
|
+
// web-src/bots-protocol.ts
|
|
240
|
+
var NAME = "@celljs/ta-bots";
|
|
241
|
+
var Keys;
|
|
242
|
+
((Keys) => {
|
|
243
|
+
Keys.BOTS = "bots";
|
|
244
|
+
Keys.STATUS = "status";
|
|
245
|
+
})(Keys ||= {});
|
|
246
|
+
var INBOUND_TYPE = "ta-bots";
|
|
247
|
+
var SENT_TYPE = "ta-bots-sent";
|
|
248
|
+
var BotTargetUtil;
|
|
249
|
+
((BotTargetUtil) => {
|
|
250
|
+
function same(a, b) {
|
|
251
|
+
if (!a || !b || a.kind !== b.kind) {
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
return a.kind === "double" || b.kind === "session" && a.sessionFile === b.sessionFile;
|
|
255
|
+
}
|
|
256
|
+
BotTargetUtil.same = same;
|
|
257
|
+
function parse(value) {
|
|
258
|
+
if (!value || typeof value !== "object") {
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
const target = value;
|
|
262
|
+
if (target.kind === "double") {
|
|
263
|
+
return { kind: "double" };
|
|
264
|
+
}
|
|
265
|
+
if (target.kind === "session" && typeof target.sessionFile === "string" && target.sessionFile) {
|
|
266
|
+
const text = (key) => typeof target[key] === "string" && target[key] ? { [key]: target[key] } : {};
|
|
267
|
+
return { kind: "session", sessionFile: target.sessionFile, ...text("cwd"), ...text("title"), ...text("group") };
|
|
268
|
+
}
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
BotTargetUtil.parse = parse;
|
|
272
|
+
})(BotTargetUtil ||= {});
|
|
273
|
+
|
|
274
|
+
// web-src/server-texts.ts
|
|
275
|
+
var BotServerTexts;
|
|
276
|
+
((BotServerTexts) => {
|
|
277
|
+
function zh(env = process.env) {
|
|
278
|
+
return /^zh/i.test(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG || "");
|
|
279
|
+
}
|
|
280
|
+
BotServerTexts.zh = zh;
|
|
281
|
+
function unbound() {
|
|
282
|
+
return zh() ? "这个机器人还没有连接到 Ta 的任何对话。在 Ta 里打开一个对话,点输入框左侧的 +,选“机器人”连接它。" : "This bot is not connected to a conversation of Ta yet. Open one in Ta, click + left of the message box and pick it under Bots.";
|
|
283
|
+
}
|
|
284
|
+
BotServerTexts.unbound = unbound;
|
|
285
|
+
function noDouble() {
|
|
286
|
+
return zh() ? "Ta 的分身还没有对话:先在 Ta 里打开一次分身。" : "The double of Ta has no conversation yet: open it once in Ta.";
|
|
287
|
+
}
|
|
288
|
+
BotServerTexts.noDouble = noDouble;
|
|
289
|
+
function failed(reason) {
|
|
290
|
+
return zh() ? `没能交给 Ta:${reason}` : `Ta did not get it: ${reason}`;
|
|
291
|
+
}
|
|
292
|
+
BotServerTexts.failed = failed;
|
|
293
|
+
function stopped() {
|
|
294
|
+
return zh() ? "(Ta 停下了,没有回复)" : "(Ta stopped without an answer)";
|
|
295
|
+
}
|
|
296
|
+
BotServerTexts.stopped = stopped;
|
|
297
|
+
function error(reason) {
|
|
298
|
+
return zh() ? `Ta 出错了:${reason}` : `Ta failed: ${reason}`;
|
|
299
|
+
}
|
|
300
|
+
BotServerTexts.error = error;
|
|
301
|
+
function defaultName(kind, taken = []) {
|
|
302
|
+
const base = kind === "weixin" ? zh() ? "我的微信" : "My WeChat" : zh() ? "企业微信机器人" : "WeCom bot";
|
|
303
|
+
for (let n = 1;; n++) {
|
|
304
|
+
const name = n === 1 ? base : `${base} ${n}`;
|
|
305
|
+
if (!taken.includes(name)) {
|
|
306
|
+
return name;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
BotServerTexts.defaultName = defaultName;
|
|
311
|
+
})(BotServerTexts ||= {});
|
|
312
|
+
|
|
313
|
+
// web-src/text-util.ts
|
|
314
|
+
var MIME = {
|
|
315
|
+
jpg: "image/jpeg",
|
|
316
|
+
jpeg: "image/jpeg",
|
|
317
|
+
png: "image/png",
|
|
318
|
+
gif: "image/gif",
|
|
319
|
+
webp: "image/webp",
|
|
320
|
+
bmp: "image/bmp",
|
|
321
|
+
mp4: "video/mp4",
|
|
322
|
+
mov: "video/quicktime",
|
|
323
|
+
webm: "video/webm",
|
|
324
|
+
mp3: "audio/mpeg",
|
|
325
|
+
wav: "audio/wav",
|
|
326
|
+
amr: "audio/amr",
|
|
327
|
+
silk: "audio/silk",
|
|
328
|
+
pdf: "application/pdf",
|
|
329
|
+
txt: "text/plain",
|
|
330
|
+
md: "text/markdown",
|
|
331
|
+
json: "application/json",
|
|
332
|
+
zip: "application/zip",
|
|
333
|
+
csv: "text/csv",
|
|
334
|
+
html: "text/html",
|
|
335
|
+
doc: "application/msword",
|
|
336
|
+
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
337
|
+
xls: "application/vnd.ms-excel",
|
|
338
|
+
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
339
|
+
ppt: "application/vnd.ms-powerpoint",
|
|
340
|
+
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
|
|
341
|
+
};
|
|
342
|
+
var BotText;
|
|
343
|
+
((BotText) => {
|
|
344
|
+
function mimeOf(name) {
|
|
345
|
+
const ext = /\.([a-z0-9]+)$/i.exec(name)?.[1]?.toLowerCase();
|
|
346
|
+
return ext && MIME[ext] || "application/octet-stream";
|
|
347
|
+
}
|
|
348
|
+
BotText.mimeOf = mimeOf;
|
|
349
|
+
function extensionOf(data) {
|
|
350
|
+
const hex = Array.from(data.subarray(0, 12), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
351
|
+
if (hex.startsWith("ffd8ff")) {
|
|
352
|
+
return ".jpg";
|
|
353
|
+
}
|
|
354
|
+
if (hex.startsWith("89504e47")) {
|
|
355
|
+
return ".png";
|
|
356
|
+
}
|
|
357
|
+
if (hex.startsWith("47494638")) {
|
|
358
|
+
return ".gif";
|
|
359
|
+
}
|
|
360
|
+
if (hex.startsWith("52494646") && hex.slice(16, 24) === "57454250") {
|
|
361
|
+
return ".webp";
|
|
362
|
+
}
|
|
363
|
+
if (hex.slice(8, 16) === "66747970") {
|
|
364
|
+
return ".mp4";
|
|
365
|
+
}
|
|
366
|
+
return "";
|
|
367
|
+
}
|
|
368
|
+
BotText.extensionOf = extensionOf;
|
|
369
|
+
function fileName(name, fallback) {
|
|
370
|
+
const clean = (name.split(/[\\/]/).pop() ?? "").replace(/[\\/:*?"<>|]+/g, "_").replace(/\p{Cc}+/gu, "_").replace(/^\.+/, "").trim().slice(0, 120);
|
|
371
|
+
return clean || fallback;
|
|
372
|
+
}
|
|
373
|
+
BotText.fileName = fileName;
|
|
374
|
+
function plain(markdown) {
|
|
375
|
+
const lines = [];
|
|
376
|
+
let fenced = false;
|
|
377
|
+
for (const line of markdown.replace(/\r\n/g, `
|
|
378
|
+
`).split(`
|
|
379
|
+
`)) {
|
|
380
|
+
if (/^\s*(```|~~~)/.test(line)) {
|
|
381
|
+
fenced = !fenced;
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
if (fenced) {
|
|
385
|
+
lines.push(line);
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
const text = line.replace(/^\s{0,3}#{1,6}\s+/, "").replace(/^\s{0,3}>\s?/, "│ ").replace(/^(\s*)[-*+]\s+\[( |x)\]\s+/i, (_, indent, mark) => `${indent}${mark.trim() ? "☑" : "☐"} `).replace(/^(\s*)[-*+]\s+/, "$1• ").replace(/^\s*([-*_])\s*\1\s*\1[\s\-*_]*$/, "──────").replace(/!\[([^\]]*)\]\(([^)\s]+)[^)]*\)/g, (_, alt, url) => alt ? `${alt} ${url}` : url).replace(/\[([^\]]+)\]\(([^)\s]+)[^)]*\)/g, (_, label, url) => label === url ? url : `${label} (${url})`).replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g, "$2").replace(/(^|[^*\w])\*(?=\S)([^*]*?\S)\*(?!\w)/g, "$1$2").replace(/~~(?=\S)([\s\S]*?\S)~~/g, "$1").replace(/`([^`]+)`/g, "$1").replace(/^\|(.*)\|\s*$/, (_, cells) => /^[\s|:-]+$/.test(cells) ? "" : cells.split("|").map((cell) => cell.trim()).join(" "));
|
|
389
|
+
lines.push(text);
|
|
390
|
+
}
|
|
391
|
+
return lines.join(`
|
|
392
|
+
`).replace(/\n{3,}/g, `
|
|
393
|
+
|
|
394
|
+
`).trim();
|
|
395
|
+
}
|
|
396
|
+
BotText.plain = plain;
|
|
397
|
+
function split(text, max) {
|
|
398
|
+
const encoder = new TextEncoder;
|
|
399
|
+
const pieces = [];
|
|
400
|
+
let rest = text;
|
|
401
|
+
while (encoder.encode(rest).length > max) {
|
|
402
|
+
let end = fit(rest, max, encoder);
|
|
403
|
+
const window = rest.slice(0, end);
|
|
404
|
+
const cut = Math.max(window.lastIndexOf(`
|
|
405
|
+
|
|
406
|
+
`), window.lastIndexOf(`
|
|
407
|
+
`));
|
|
408
|
+
const space = window.lastIndexOf(" ");
|
|
409
|
+
if (cut > end / 2) {
|
|
410
|
+
end = cut;
|
|
411
|
+
} else if (space > end / 2) {
|
|
412
|
+
end = space;
|
|
413
|
+
}
|
|
414
|
+
pieces.push(rest.slice(0, end).trimEnd());
|
|
415
|
+
rest = rest.slice(end).replace(/^\s+/, "");
|
|
416
|
+
}
|
|
417
|
+
if (rest) {
|
|
418
|
+
pieces.push(rest);
|
|
419
|
+
}
|
|
420
|
+
return pieces;
|
|
421
|
+
}
|
|
422
|
+
BotText.split = split;
|
|
423
|
+
function fit(text, max, encoder) {
|
|
424
|
+
let low = 0;
|
|
425
|
+
let high = text.length;
|
|
426
|
+
while (low < high) {
|
|
427
|
+
const middle = Math.ceil((low + high) / 2);
|
|
428
|
+
if (encoder.encode(text.slice(0, middle)).length <= max) {
|
|
429
|
+
low = middle;
|
|
430
|
+
} else {
|
|
431
|
+
high = middle - 1;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
const code = text.charCodeAt(low - 1);
|
|
435
|
+
return code >= 55296 && code <= 56319 ? low - 1 : Math.max(1, low);
|
|
436
|
+
}
|
|
437
|
+
})(BotText ||= {});
|
|
438
|
+
|
|
439
|
+
// web-src/extension.ts
|
|
440
|
+
var HOST_WAIT_MS = 1000;
|
|
441
|
+
var INBOX = ".ta/inbox";
|
|
442
|
+
var IMAGE_BYTES = 5 * 1024 * 1024;
|
|
443
|
+
var MODEL_IMAGES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
|
|
444
|
+
var TOOL = "bot_send_file";
|
|
445
|
+
var KIND = { weixin: "WeChat", wecom: "WeCom" };
|
|
446
|
+
function inboundText(details) {
|
|
447
|
+
const who = details.from.name || details.from.id;
|
|
448
|
+
const head = `[${KIND[details.kind]} · ${details.botName}${details.group ? " · group" : ""}] ${who}:`;
|
|
449
|
+
const files = details.attachments.map((file) => file.path ? `[${file.kind}: ${file.path}]` : `[${file.kind}: ${file.name}, not saved]`);
|
|
450
|
+
return [head, details.text, ...files].filter(Boolean).join(`
|
|
451
|
+
`);
|
|
452
|
+
}
|
|
453
|
+
function botNote(details) {
|
|
454
|
+
return `
|
|
455
|
+
|
|
456
|
+
This message came from ${KIND[details.kind]} through the bot "${details.botName}" of Ta. The person reads your final answer there, as ${details.kind === "weixin" ? "plain text without Markdown" : "Markdown"}, on a phone: answer in a few short paragraphs, and say what you did rather than showing long output. Files they sent are saved under ${INBOX}/. To send them a file, a picture or a video, call ${TOOL} with its path.`;
|
|
457
|
+
}
|
|
458
|
+
function activate(pi) {
|
|
459
|
+
let reached;
|
|
460
|
+
let detach;
|
|
461
|
+
let origins = [];
|
|
462
|
+
let answer = "";
|
|
463
|
+
let failure;
|
|
464
|
+
let stopped = false;
|
|
465
|
+
let sessionFile = () => {
|
|
466
|
+
return;
|
|
467
|
+
};
|
|
468
|
+
const reach = () => reached ??= new Promise((resolve) => {
|
|
469
|
+
const timer = setTimeout(() => resolve(undefined), HOST_WAIT_MS);
|
|
470
|
+
pi.events.emit(TA_HOST_EVENT, {
|
|
471
|
+
name: NAME,
|
|
472
|
+
resolve: (found) => {
|
|
473
|
+
clearTimeout(timer);
|
|
474
|
+
resolve(found.service && found.files ? { service: found.service, files: found.files } : undefined);
|
|
475
|
+
}
|
|
476
|
+
});
|
|
477
|
+
});
|
|
478
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
479
|
+
const found = await reach();
|
|
480
|
+
if (!found) {
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
sessionFile = () => ctx.sessionManager.getSessionFile();
|
|
484
|
+
detach?.();
|
|
485
|
+
detach = found.service.attach(ctx.sessionManager.getSessionId(), { deliver: (delivery) => void deliver(found, delivery) });
|
|
486
|
+
});
|
|
487
|
+
pi.on("session_shutdown", () => {
|
|
488
|
+
detach?.();
|
|
489
|
+
detach = undefined;
|
|
490
|
+
});
|
|
491
|
+
pi.on("before_agent_start", async (event) => {
|
|
492
|
+
const found = await reach();
|
|
493
|
+
if (found) {
|
|
494
|
+
const bound = (await found.service.boundTo(sessionFile())).length > 0;
|
|
495
|
+
const active = pi.getActiveTools();
|
|
496
|
+
if (bound !== active.includes(TOOL)) {
|
|
497
|
+
pi.setActiveTools(bound ? [...active, TOOL] : active.filter((name) => name !== TOOL));
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
if (event.messageType === "custom" && event.message?.customType === INBOUND_TYPE) {
|
|
501
|
+
return { systemPrompt: event.systemPrompt + botNote(event.message.details) };
|
|
502
|
+
}
|
|
503
|
+
return;
|
|
504
|
+
});
|
|
505
|
+
pi.on("message_end", (event) => {
|
|
506
|
+
const message = event.message;
|
|
507
|
+
if (message.role === "custom" && message.customType === INBOUND_TYPE) {
|
|
508
|
+
const origin = message.details?.origin;
|
|
509
|
+
if (origin) {
|
|
510
|
+
origins.push(origin);
|
|
511
|
+
}
|
|
512
|
+
} else if (message.role === "assistant" && origins.length > 0 && message.stopReason !== "toolUse") {
|
|
513
|
+
const text = textOf(message.content);
|
|
514
|
+
answer = text || answer;
|
|
515
|
+
failure = message.stopReason === "error" ? message.errorMessage || "error" : undefined;
|
|
516
|
+
stopped = message.stopReason === "aborted";
|
|
517
|
+
}
|
|
518
|
+
});
|
|
519
|
+
pi.on("agent_settled", async () => {
|
|
520
|
+
if (origins.length === 0) {
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
const asked = origins;
|
|
524
|
+
const text = answer || (failure ? BotServerTexts.error(failure) : stopped ? BotServerTexts.stopped() : "");
|
|
525
|
+
origins = [];
|
|
526
|
+
answer = "";
|
|
527
|
+
failure = undefined;
|
|
528
|
+
stopped = false;
|
|
529
|
+
const found = await reach();
|
|
530
|
+
if (found) {
|
|
531
|
+
const sent = await found.service.replied(asked, text);
|
|
532
|
+
post({ sent });
|
|
533
|
+
}
|
|
534
|
+
});
|
|
535
|
+
pi.on("context", (event) => {
|
|
536
|
+
const messages = event.messages.filter((message) => !(message.role === "custom" && message.customType === SENT_TYPE));
|
|
537
|
+
return messages.length === event.messages.length ? undefined : { messages };
|
|
538
|
+
});
|
|
539
|
+
pi.registerTool({
|
|
540
|
+
name: TOOL,
|
|
541
|
+
label: "Send to the bot",
|
|
542
|
+
description: "Send a file, picture or video to the WeChat or WeCom chat whose message you are answering (the bots connected to this conversation). Your final answer is sent as text by itself; use this only for files.",
|
|
543
|
+
promptSnippet: "Send a file to the WeChat or WeCom chat of the message being answered",
|
|
544
|
+
parameters: {
|
|
545
|
+
type: "object",
|
|
546
|
+
properties: { path: { type: "string", description: "The file, relative to the working directory or absolute." } },
|
|
547
|
+
required: ["path"]
|
|
548
|
+
},
|
|
549
|
+
execute: async (_id, params) => {
|
|
550
|
+
const found = await reach();
|
|
551
|
+
const path = typeof params?.path === "string" ? params.path.trim() : "";
|
|
552
|
+
if (!found || !path) {
|
|
553
|
+
throw new Error(found ? "Give the path of the file." : "Bots need the Ta service.");
|
|
554
|
+
}
|
|
555
|
+
const to = origins.length > 0 ? origins : found.service.lastChats(await found.service.boundTo(sessionFile()));
|
|
556
|
+
if (to.length === 0) {
|
|
557
|
+
throw new Error("No chat of a bot is waiting for an answer in this conversation.");
|
|
558
|
+
}
|
|
559
|
+
const data = await found.files.read(found.files.resolve(path));
|
|
560
|
+
if (!data) {
|
|
561
|
+
throw new Error(`There is no file at ${path}.`);
|
|
562
|
+
}
|
|
563
|
+
const name = path.split(/[\\/]/).pop() || "file";
|
|
564
|
+
const mimeType = BotText.mimeOf(name);
|
|
565
|
+
const kind = mimeType.startsWith("image/") ? "image" : mimeType.startsWith("video/") ? "video" : "file";
|
|
566
|
+
const sent = await found.service.sendFile(to, { kind, name, mimeType, data });
|
|
567
|
+
post({ sent });
|
|
568
|
+
const failed = sent.filter((item) => item.error);
|
|
569
|
+
if (failed.length === sent.length) {
|
|
570
|
+
throw new Error(failed.map((item) => `${item.botName}: ${item.error}`).join("; "));
|
|
571
|
+
}
|
|
572
|
+
return {
|
|
573
|
+
content: [
|
|
574
|
+
{
|
|
575
|
+
type: "text",
|
|
576
|
+
text: `Sent ${name} to ${sent.filter((item) => !item.error).map((item) => item.botName).join(", ")}.`
|
|
577
|
+
}
|
|
578
|
+
],
|
|
579
|
+
details: undefined
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
});
|
|
583
|
+
function post(message) {
|
|
584
|
+
if (message.sent.length > 0) {
|
|
585
|
+
const summary = message.sent.map((item) => `${item.botName}: ${item.error ?? "sent"}`).join(`
|
|
586
|
+
`);
|
|
587
|
+
pi.sendMessage({ customType: SENT_TYPE, content: summary, display: true, details: message });
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
async function deliver(found, delivery) {
|
|
591
|
+
const attachments = [];
|
|
592
|
+
const images = [];
|
|
593
|
+
if (delivery.files.length > 0) {
|
|
594
|
+
await found.files.write(found.files.resolve(`${INBOX}/.gitignore`), new TextEncoder().encode(`*
|
|
595
|
+
`)).catch(() => {
|
|
596
|
+
return;
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
for (const file of delivery.files) {
|
|
600
|
+
const path = `${INBOX}/${stamp(new Date(delivery.details.at))}-${file.name}`;
|
|
601
|
+
const saved = await found.files.write(found.files.resolve(path), file.data).then(() => true, () => false);
|
|
602
|
+
attachments.push({ kind: file.kind, name: file.name, size: file.data.length, ...saved ? { path } : {} });
|
|
603
|
+
if (file.kind === "image" && MODEL_IMAGES.has(file.mimeType) && file.data.length <= IMAGE_BYTES) {
|
|
604
|
+
images.push({ type: "image", data: Buffer.from(file.data).toString("base64"), mimeType: file.mimeType });
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
const details = { ...delivery.details, attachments };
|
|
608
|
+
pi.sendMessage({ customType: INBOUND_TYPE, content: [{ type: "text", text: inboundText(details) }, ...images], display: true, details }, { triggerTurn: true, deliverAs: "followUp" });
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
function textOf(content) {
|
|
612
|
+
if (typeof content === "string") {
|
|
613
|
+
return content.trim();
|
|
614
|
+
}
|
|
615
|
+
return Array.isArray(content) ? content.filter((block) => block?.type === "text" && block.text).map((block) => block.text).join(`
|
|
616
|
+
|
|
617
|
+
`).trim() : "";
|
|
618
|
+
}
|
|
619
|
+
function stamp(date) {
|
|
620
|
+
const two = (value) => String(value).padStart(2, "0");
|
|
621
|
+
return `${date.getFullYear()}${two(date.getMonth() + 1)}${two(date.getDate())}-${two(date.getHours())}${two(date.getMinutes())}${two(date.getSeconds())}`;
|
|
622
|
+
}
|
|
623
|
+
export {
|
|
624
|
+
inboundText,
|
|
625
|
+
activate as default,
|
|
626
|
+
botNote,
|
|
627
|
+
TOOL,
|
|
628
|
+
INBOX
|
|
629
|
+
};
|