@wirecat/tg-cli 0.99.0 → 0.100.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.
Files changed (112) hide show
  1. package/README.md +3 -2
  2. package/dist/bin/tg.js +23 -28
  3. package/dist/bundle/adapter-2LVPMFKF.js +2790 -0
  4. package/dist/bundle/all-profiles-BLTK2AAB.js +255 -0
  5. package/dist/bundle/anthropic-RJE4XEOO.js +71 -0
  6. package/dist/bundle/bot-api-4XM3NVWG.js +39793 -0
  7. package/dist/bundle/bot-history-WVM5GEQN.js +167 -0
  8. package/dist/bundle/bun-UZXO2LRQ.js +169 -0
  9. package/dist/bundle/bun-sqlite-GJLGSQIT.js +70 -0
  10. package/dist/bundle/chunk-2IM4M7Q2.js +98 -0
  11. package/dist/bundle/chunk-2MXQ2EUN.js +1344 -0
  12. package/dist/bundle/chunk-2XUGPE5W.js +73 -0
  13. package/dist/bundle/chunk-3KHKYYCR.js +24782 -0
  14. package/dist/bundle/chunk-3MVHRZWR.js +2 -0
  15. package/dist/bundle/chunk-3N6LXAPE.js +724 -0
  16. package/dist/bundle/chunk-3QDPV34J.js +6668 -0
  17. package/dist/bundle/chunk-3S5CL55R.js +100 -0
  18. package/dist/bundle/chunk-4U7QOFDA.js +33511 -0
  19. package/dist/bundle/chunk-4VBDVZNE.js +524 -0
  20. package/dist/bundle/chunk-4YCLWWZ3.js +277 -0
  21. package/dist/bundle/chunk-66E5QDLH.js +24 -0
  22. package/dist/bundle/chunk-6VEOR6GD.js +166 -0
  23. package/dist/bundle/chunk-6YLT4YVJ.js +45 -0
  24. package/dist/bundle/chunk-7BFO3DY6.js +21 -0
  25. package/dist/bundle/chunk-A7OBVRJV.js +738 -0
  26. package/dist/bundle/chunk-AFV74GK3.js +50 -0
  27. package/dist/bundle/chunk-ASDZHG5I.js +25 -0
  28. package/dist/bundle/chunk-ATZ44Z77.js +3253 -0
  29. package/dist/bundle/chunk-AVWK4NCW.js +24600 -0
  30. package/dist/bundle/chunk-BAIZAZ6Q.js +82 -0
  31. package/dist/bundle/chunk-BJG6JA5U.js +35 -0
  32. package/dist/bundle/chunk-BL36RR34.js +285 -0
  33. package/dist/bundle/chunk-BZANDKWT.js +71 -0
  34. package/dist/bundle/chunk-CV5ASHTW.js +8170 -0
  35. package/dist/bundle/chunk-DN4QUTWU.js +78 -0
  36. package/dist/bundle/chunk-DVOUKGFK.js +1950 -0
  37. package/dist/bundle/chunk-GTURDJJD.js +570 -0
  38. package/dist/bundle/chunk-GYEOQS2D.js +2795 -0
  39. package/dist/bundle/chunk-H3X5LS6U.js +153 -0
  40. package/dist/bundle/chunk-HKT5EOT5.js +6848 -0
  41. package/dist/bundle/chunk-HXTTDIL7.js +82 -0
  42. package/dist/bundle/chunk-I6WZJVRT.js +1123 -0
  43. package/dist/bundle/chunk-JFJVS5JC.js +41 -0
  44. package/dist/bundle/chunk-JSKT5UZX.js +2315 -0
  45. package/dist/bundle/chunk-KE6L2UEG.js +3068 -0
  46. package/dist/bundle/chunk-LI7TXFLS.js +122 -0
  47. package/dist/bundle/chunk-MQNFEVAH.js +58 -0
  48. package/dist/bundle/chunk-MUEXF4ME.js +582 -0
  49. package/dist/bundle/chunk-OOOV3JBZ.js +35527 -0
  50. package/dist/bundle/chunk-OW3COBN5.js +1275 -0
  51. package/dist/bundle/chunk-P26LWFNZ.js +35 -0
  52. package/dist/bundle/chunk-Q26JMPBP.js +215 -0
  53. package/dist/bundle/chunk-QU2FJMFB.js +18282 -0
  54. package/dist/bundle/chunk-QY3YOOTP.js +18 -0
  55. package/dist/bundle/chunk-RDQMV6EU.js +46 -0
  56. package/dist/bundle/chunk-RER6DAHP.js +3514 -0
  57. package/dist/bundle/chunk-SGJYU3SB.js +54 -0
  58. package/dist/bundle/chunk-SMJTL5U7.js +117 -0
  59. package/dist/bundle/chunk-SYPL4PHV.js +76 -0
  60. package/dist/bundle/chunk-THVNP6S6.js +31 -0
  61. package/dist/bundle/chunk-U7LXA4SO.js +1007 -0
  62. package/dist/bundle/chunk-UD4DOZCN.js +886 -0
  63. package/dist/bundle/chunk-UMLPXNJI.js +63 -0
  64. package/dist/bundle/chunk-V4JSVH4M.js +190 -0
  65. package/dist/bundle/chunk-WE3LBRMB.js +2374 -0
  66. package/dist/bundle/chunk-WKOY3POD.js +452 -0
  67. package/dist/bundle/chunk-X4Y2ROJI.js +541 -0
  68. package/dist/bundle/chunk-YG7PNCSW.js +230 -0
  69. package/dist/bundle/chunk-Z2FHEIXN.js +63 -0
  70. package/dist/bundle/chunk-ZZLKX62Z.js +928 -0
  71. package/dist/bundle/command-contract-AIVKJYIR.js +31 -0
  72. package/dist/bundle/dist-RJMT44PL.js +7577 -0
  73. package/dist/bundle/echarts-YHSYUWLY.js +42501 -0
  74. package/dist/bundle/embed-3HGI2XIW.js +35 -0
  75. package/dist/bundle/embedder-2CJMZETJ.js +108 -0
  76. package/dist/bundle/entry-UVE53OV3.js +14 -0
  77. package/dist/bundle/first-run-6GYC2QS3.js +24 -0
  78. package/dist/bundle/first-screen-HRRLVLOG.js +29 -0
  79. package/dist/bundle/identity-HEV5E57G.js +11 -0
  80. package/dist/bundle/instructions-5UVAXSQV.js +9 -0
  81. package/dist/bundle/mcp-NWXBVNUA.js +165 -0
  82. package/dist/bundle/node-IUL5HSYI.js +2340 -0
  83. package/dist/bundle/node-UPPL626U.js +21 -0
  84. package/dist/bundle/node-YHYEGYVE.js +176 -0
  85. package/dist/bundle/node-sqlite-CQ33A3R2.js +46 -0
  86. package/dist/bundle/oauth-OB3JFAD7.js +18 -0
  87. package/dist/bundle/open-JHGZIXU2.js +20 -0
  88. package/dist/bundle/process-PSKS3N5B.js +91 -0
  89. package/dist/bundle/program-RPYVPNRX.js +1060 -0
  90. package/dist/bundle/prompt-7BXUMJGG.js +13 -0
  91. package/dist/bundle/proxy-transport-3EEMW2HW.js +17 -0
  92. package/dist/bundle/recognize-YMZPL47R.js +191 -0
  93. package/dist/bundle/remote-LQ3Q22NG.js +26 -0
  94. package/dist/bundle/rerank-SM7IYVXJ.js +49 -0
  95. package/dist/bundle/serve-GHUEP5H5.js +181 -0
  96. package/dist/bundle/server-A45HVXQY.js +178 -0
  97. package/dist/bundle/server-K2BQPPHN.js +785 -0
  98. package/dist/bundle/state-WIOL52GZ.js +30 -0
  99. package/dist/bundle/store-XE5AKUJZ.js +121 -0
  100. package/dist/bundle/store-maintenance-command-YS5E7VUN.js +46 -0
  101. package/dist/bundle/tg.js +40 -0
  102. package/dist/commands/context.d.ts.map +1 -1
  103. package/dist/commands/context.js +1 -1
  104. package/dist/commands/context.js.map +1 -1
  105. package/dist/install/postinstall.js +1 -1
  106. package/dist/install/postinstall.js.map +1 -1
  107. package/dist/version.d.ts +1 -1
  108. package/dist/version.d.ts.map +1 -1
  109. package/dist/version.js +1 -1
  110. package/dist/version.js.map +1 -1
  111. package/package.json +4 -2
  112. /package/skills/{wirecat-tg → tg-cli}/SKILL.md +0 -0
@@ -0,0 +1,724 @@
1
+ import { createRequire as __tgRequire } from "node:module";
2
+ const require = __tgRequire(import.meta.url);
3
+ import {
4
+ LEVELS
5
+ } from "./chunk-U7LXA4SO.js";
6
+ import {
7
+ storePath,
8
+ wirecatDirectory
9
+ } from "./chunk-QY3YOOTP.js";
10
+ import {
11
+ resolvePaths,
12
+ singleLine,
13
+ visibleControls,
14
+ writeSecurely
15
+ } from "./chunk-GYEOQS2D.js";
16
+ import {
17
+ CliError,
18
+ array,
19
+ getDotPath,
20
+ integer,
21
+ minLength,
22
+ minValue,
23
+ nullable,
24
+ number,
25
+ optional,
26
+ picklist,
27
+ pipe,
28
+ record,
29
+ regex,
30
+ safeParse,
31
+ strictObject,
32
+ string,
33
+ transform,
34
+ unknown
35
+ } from "./chunk-WE3LBRMB.js";
36
+ import {
37
+ __name
38
+ } from "./chunk-AFV74GK3.js";
39
+
40
+ // node_modules/.pnpm/@wirecat+cli-core@0.452.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.63.0_commander@15._e609b9d6c8060966368a91e843fe8bd2/node_modules/@wirecat/cli-core/dist/sends/send-id.js
41
+ import { randomBytes } from "node:crypto";
42
+ var newSendId = /* @__PURE__ */ __name(() => randomBytes(8).readBigInt64BE().toString(), "newSendId");
43
+ var newOperationId = newSendId;
44
+
45
+ // node_modules/.pnpm/@wirecat+cli-core@0.452.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.63.0_commander@15._e609b9d6c8060966368a91e843fe8bd2/node_modules/@wirecat/cli-core/dist/sends/upload.js
46
+ import { openAsBlob, realpathSync } from "node:fs";
47
+ import { open, stat } from "node:fs/promises";
48
+ import { basename, dirname, extname, isAbsolute, relative, resolve, sep } from "node:path";
49
+ var MAX_BUFFERED_UPLOAD_BYTES = 256 * 1024 * 1024;
50
+ var uploadSize = /* @__PURE__ */ __name((source) => source.kind === "file" ? source.size : source.bytes.byteLength, "uploadSize");
51
+ var changed = /* @__PURE__ */ __name(() => new CliError("validation_error", "the file changed after it was checked \u2014 nothing was sent"), "changed");
52
+ var uploadBlob = /* @__PURE__ */ __name(async (source, type) => {
53
+ if (source.kind === "bytes")
54
+ return new Blob([source.bytes], type === void 0 ? {} : { type });
55
+ const blob = await openAsBlob(source.path, type === void 0 ? {} : { type });
56
+ if (blob.size !== source.size)
57
+ throw changed();
58
+ return blob;
59
+ }, "uploadBlob");
60
+ var uploadBytes = /* @__PURE__ */ __name(async (source) => {
61
+ if (source.kind === "bytes")
62
+ return source.bytes;
63
+ if (source.size > MAX_BUFFERED_UPLOAD_BYTES)
64
+ throw new CliError("validation_error", `the file is ${Math.ceil(source.size / 1024 / 1024)} MiB, and this messenger sends at most ${MAX_BUFFERED_UPLOAD_BYTES / 1024 / 1024} MiB from memory \u2014 nothing was sent`);
65
+ const bytes = new Uint8Array(await (await uploadBlob(source)).arrayBuffer());
66
+ if (bytes.byteLength !== source.size)
67
+ throw changed();
68
+ return bytes;
69
+ }, "uploadBytes");
70
+ var PHOTO = /* @__PURE__ */ new Set([".jpg", ".jpeg", ".png", ".webp"]);
71
+ var VOICE = /* @__PURE__ */ new Set([".ogg", ".oga", ".opus"]);
72
+ var JPEG = /* @__PURE__ */ __name((head) => head[0] === 255 && head[1] === 216 && head[2] === 255, "JPEG");
73
+ var SIGNATURES = {
74
+ ".jpg": JPEG,
75
+ ".jpeg": JPEG,
76
+ ".png": /* @__PURE__ */ __name((head) => Buffer.from(head.subarray(0, 8)).toString("latin1") === "\x89PNG\r\n\n", ".png"),
77
+ ".webp": /* @__PURE__ */ __name((head) => {
78
+ const text = Buffer.from(head).toString("latin1");
79
+ return text.startsWith("RIFF") && text.slice(8, 12) === "WEBP";
80
+ }, ".webp")
81
+ };
82
+ var fileHead = /* @__PURE__ */ __name(async (path) => {
83
+ const file2 = await open(path, "r");
84
+ try {
85
+ const head = new Uint8Array(12);
86
+ const { bytesRead } = await file2.read(head, 0, head.length, 0);
87
+ return head.subarray(0, bytesRead);
88
+ } finally {
89
+ await file2.close();
90
+ }
91
+ }, "fileHead");
92
+ var typesText = /* @__PURE__ */ __name((types) => types.length < 2 ? types[0] ?? "" : `${types.slice(0, -1).join(", ")} or ${types.at(-1)}`, "typesText");
93
+ var CREDENTIAL_PARTS = /* @__PURE__ */ new Set([
94
+ ".ssh",
95
+ ".gnupg",
96
+ ".aws",
97
+ ".azure",
98
+ ".kube",
99
+ ".secrets",
100
+ "secrets",
101
+ ".password-store",
102
+ ".mozilla",
103
+ ".env",
104
+ ".npmrc",
105
+ ".pypirc",
106
+ ".netrc",
107
+ "_netrc",
108
+ ".git-credentials",
109
+ "credentials.yml.enc",
110
+ "master.key"
111
+ ]);
112
+ var CREDENTIAL_RUNS = [
113
+ [".config", "autostart"],
114
+ [".config", "git", "credentials"],
115
+ [".config", "gh"],
116
+ [".config", "gcloud"],
117
+ [".config", "google-chrome"],
118
+ [".config", "chromium"],
119
+ [".config", "microsoft-edge"],
120
+ [".config", "BraveSoftware"],
121
+ [".docker", "config.json"],
122
+ [".claude", ".credentials.json"],
123
+ [".codex", "auth.json"],
124
+ [".local", "share", "keyrings"],
125
+ ["Library", "Keychains"],
126
+ ["Library", "Cookies"],
127
+ ["Library", "Safari"],
128
+ ["Library", "Application Support", "Google", "Chrome"],
129
+ ["Library", "Application Support", "Chromium"],
130
+ ["Library", "Application Support", "Microsoft Edge"],
131
+ ["Library", "Application Support", "BraveSoftware"],
132
+ ["Library", "Application Support", "Firefox"],
133
+ ["AppData", "Local", "Google", "Chrome"],
134
+ ["AppData", "Local", "Chromium"],
135
+ ["AppData", "Local", "Microsoft", "Edge"],
136
+ ["AppData", "Local", "BraveSoftware"],
137
+ ["AppData", "Roaming", "Mozilla", "Firefox"],
138
+ ["AppData", "Local", "Microsoft", "Credentials"],
139
+ ["AppData", "Roaming", "Microsoft", "Credentials"],
140
+ ["AppData", "Roaming", "Microsoft", "Protect"],
141
+ ["AppData", "Roaming", "gcloud"],
142
+ ["AppData", "Roaming", "GitHub CLI"]
143
+ ];
144
+ var WIRECAT_APPS = [
145
+ { appName: "max-cli", prefix: "MAX" },
146
+ { appName: "tg-cli", prefix: "TG" },
147
+ { appName: "whatsapp-cli", prefix: "WA" },
148
+ { appName: "cli-memo", prefix: "MEMO" },
149
+ { appName: "drive-cli", prefix: "DRIVE" },
150
+ { appName: "zm", prefix: "ZM" },
151
+ { appName: "cli-messaging", prefix: "MESSAGING" },
152
+ { appName: "cli-common", prefix: "CLI_COMMON" }
153
+ ];
154
+ var refusedPlace = /* @__PURE__ */ __name((path, app, env, platform = process.platform) => {
155
+ const own = [
156
+ ...[{ appName: app.appName, prefix: app.envPrefix }, ...WIRECAT_APPS].flatMap((one) => Object.values(resolvePaths({ ...one, env, platform }))),
157
+ // The shared WireCat folder: the store, its backups beside it, the models.
158
+ wirecatDirectory(env, platform)
159
+ ];
160
+ const store = resolve(storePath(env));
161
+ let ancestor = resolve(path);
162
+ let real = ancestor;
163
+ for (; ; ) {
164
+ try {
165
+ real = resolve(realpathSync(ancestor), relative(ancestor, resolve(path)));
166
+ break;
167
+ } catch {
168
+ const parent = dirname(ancestor);
169
+ if (parent === ancestor)
170
+ break;
171
+ ancestor = parent;
172
+ }
173
+ }
174
+ const folded = platform === "darwin" || platform === "win32";
175
+ const fold = /* @__PURE__ */ __name((text) => folded ? text.toLowerCase() : text, "fold");
176
+ const parts = new Set([...CREDENTIAL_PARTS].map(fold));
177
+ const runs = CREDENTIAL_RUNS.map((run) => run.map(fold));
178
+ const named = /* @__PURE__ */ __name((candidate) => {
179
+ const names = candidate.split(sep).map(fold);
180
+ return names.some((name, index) => parts.has(name) || /^\.env\./.test(name) || runs.some((run) => run.every((part, offset) => names[index + offset] === part)));
181
+ }, "named");
182
+ const same = /* @__PURE__ */ __name((a, b) => fold(a) === fold(b), "same");
183
+ return [resolve(path), real].some((candidate) => named(candidate) || own.some((dir) => inside(fold(candidate), fold(dir))) || [store, `${store}-wal`, `${store}-shm`].some((file2) => same(candidate, file2)));
184
+ }, "refusedPlace");
185
+ var inside = /* @__PURE__ */ __name((path, dir) => {
186
+ const way = relative(resolve(dir), path);
187
+ return way === "" || !way.startsWith("..") && !isAbsolute(way);
188
+ }, "inside");
189
+ var readUpload = /* @__PURE__ */ __name(async (kind, path, { app, env = process.env, anyFile = false, photoTypes }) => {
190
+ const extension = extname(path).toLowerCase();
191
+ if (kind === "photo" && photoTypes !== void 0 && !photoTypes.includes(extension)) {
192
+ throw new CliError("validation_error", `this photo must be a ${typesText(photoTypes)} file, not ${path}`);
193
+ }
194
+ if (kind === "photo" && photoTypes === void 0 && !PHOTO.has(extension)) {
195
+ throw new CliError("validation_error", `a photo is a .jpg, .png or .webp \u2014 send ${path} as a file instead`);
196
+ }
197
+ if (kind === "voice" && !VOICE.has(extension)) {
198
+ throw new CliError("validation_error", `a voice message is Ogg Opus: .ogg, .oga or .opus \u2014 send ${path} as a file`);
199
+ }
200
+ if (!anyFile && refusedPlace(path, app, env)) {
201
+ throw new CliError("validation_error", `cannot send ${path}: known credential files, browser profiles, the WireCat apps' folders and the message store are not sent \u2014 the owner adds --allow-any-file to the command if this file is meant to go`);
202
+ }
203
+ let size;
204
+ let head;
205
+ try {
206
+ const info = await stat(path);
207
+ if (!info.isFile())
208
+ throw Object.assign(new Error("not a file"), { code: "EISDIR" });
209
+ size = info.size;
210
+ if (photoTypes !== void 0 && SIGNATURES[extension] !== void 0)
211
+ head = await fileHead(path);
212
+ } catch (error) {
213
+ const code = error.code;
214
+ const reason = code === "ENOENT" ? "no such file" : code === "EISDIR" ? "it is a folder" : "it cannot be read";
215
+ throw new CliError("validation_error", `cannot send ${path}: ${reason}`);
216
+ }
217
+ if (head !== void 0 && SIGNATURES[extension]?.(head) !== true) {
218
+ throw new CliError("validation_error", `${path} is not a ${typesText(photoTypes ?? [])} image inside`);
219
+ }
220
+ return { kind, name: basename(path), source: { kind: "file", path: resolve(path), size } };
221
+ }, "readUpload");
222
+ var checkFilename = /* @__PURE__ */ __name((filename, files) => {
223
+ if (files.length === 0)
224
+ throw new CliError("validation_error", "--filename names a --file; give one");
225
+ if (files.length > 1)
226
+ throw new CliError("validation_error", "--filename names one --file; an album keeps its names");
227
+ if (filename.trim() === "" || /[/\\\0]/.test(filename) || filename.length > 255)
228
+ throw new CliError("validation_error", "--filename is a name, not a path: no / or \\, at most 255 characters");
229
+ }, "checkFilename");
230
+ var listOf = /* @__PURE__ */ __name((value) => value === void 0 ? [] : typeof value === "string" ? [value] : value, "listOf");
231
+ var readAttachments = /* @__PURE__ */ __name(async ({ photo, file: file2, voice, asFile, filename, text }, read) => {
232
+ const photos = listOf(photo);
233
+ const files = listOf(file2);
234
+ if (voice !== void 0 && (photos.length > 0 || files.length > 0 || (text ?? "").trim() !== "")) {
235
+ throw new CliError("validation_error", "a voice message goes alone \u2014 no text, no file, no photo beside it");
236
+ }
237
+ if (asFile && files.length === 0)
238
+ throw new CliError("validation_error", "--as-file is about a --file; give one");
239
+ if (filename !== void 0)
240
+ checkFilename(filename, files);
241
+ const uploads = [];
242
+ for (const one of photos)
243
+ uploads.push(await readUpload("photo", one, read));
244
+ for (const one of files)
245
+ uploads.push({
246
+ ...await readUpload("file", one, read),
247
+ ...filename === void 0 ? {} : { name: filename },
248
+ ...asFile ? { asFile: true } : {}
249
+ });
250
+ if (voice !== void 0)
251
+ uploads.push(await readUpload("voice", voice, read));
252
+ return uploads;
253
+ }, "readAttachments");
254
+ var readStickerFile = /* @__PURE__ */ __name(async (path, maxBytes, read) => {
255
+ if (extname(path).toLowerCase() !== ".webp")
256
+ throw new CliError("validation_error", `a sticker is a .webp \u2014 send ${path} as a photo or a file instead`);
257
+ const { name, source } = await readUpload("file", path, read);
258
+ if (SIGNATURES[".webp"]?.(await fileHead(path)) !== true)
259
+ throw new CliError("validation_error", `${path} is named .webp but is not a WebP image \u2014 nothing was sent`);
260
+ const size = uploadSize(source);
261
+ if (size > maxBytes)
262
+ throw new CliError("validation_error", `the sticker is ${Math.ceil(size / 1024)} KiB, and this messenger takes at most ${Math.floor(maxBytes / 1024)} KiB \u2014 nothing was sent`);
263
+ return { name, source };
264
+ }, "readStickerFile");
265
+
266
+ // node_modules/.pnpm/@wirecat+cli-core@0.452.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.63.0_commander@15._e609b9d6c8060966368a91e843fe8bd2/node_modules/@wirecat/cli-core/dist/resolve.js
267
+ var isId = /* @__PURE__ */ __name((reference) => /^-?\d+$/.test(reference.trim()), "isId");
268
+ var foldName = /* @__PURE__ */ __name((name) => name.normalize("NFC").replace(/[\uFE0E\uFE0F\u200D]/g, "").toLowerCase(), "foldName");
269
+ var pickChat = /* @__PURE__ */ __name((reference, chats) => {
270
+ const wanted = foldName(reference.trim());
271
+ const matches = chats.filter((chat) => chat.title !== null && foldName(chat.title).includes(wanted));
272
+ if (matches.length === 1 && matches[0])
273
+ return matches[0];
274
+ if (matches.length === 0)
275
+ throw new CliError("not_found", `no chat matches "${reference}"`);
276
+ throw ambiguous(reference, "chats", matches.map((chat) => ({ id: chat.id, title: chat.title })), ({ title }) => singleLine(String(title)));
277
+ }, "pickChat");
278
+ var pickPerson = /* @__PURE__ */ __name((reference, people) => {
279
+ const trimmed = reference.trim();
280
+ const known = people.get(trimmed);
281
+ if (known)
282
+ return known;
283
+ if (isId(trimmed))
284
+ throw new CliError("not_found", `no person ${trimmed} in what this account has seen`);
285
+ const wanted = foldName(trimmed.replace(/^@/, ""));
286
+ const everyone = people.all().toSorted((a, b) => (a.name ?? "").localeCompare(b.name ?? ""));
287
+ const fields = /* @__PURE__ */ __name((person) => [person.alias, person.name, person.username].filter(isPresent).map(foldName), "fields");
288
+ const exact = everyone.filter((person) => fields(person).includes(wanted));
289
+ const matches = exact.length > 0 ? exact : everyone.filter((person) => fields(person).some((one) => one.includes(wanted)));
290
+ if (matches.length === 1 && matches[0])
291
+ return matches[0];
292
+ if (matches.length === 0)
293
+ throw new CliError("not_found", `nobody matches "${reference}"`);
294
+ throw ambiguous(reference, "people", matches.map(({ id, name, username }) => ({ id, name, username })), ({ name, username }) => singleLine([name, username && `@${username}`].filter(isPresent).join(" ")));
295
+ }, "pickPerson");
296
+ var ambiguous = /* @__PURE__ */ __name((reference, what, candidates, label) => {
297
+ const width = Math.max(...candidates.map(({ id }) => id.length));
298
+ const lines = candidates.map((candidate) => ` ${candidate.id.padEnd(width)} ${label(candidate)}`).join("\n");
299
+ return new CliError("validation_error", `"${singleLine(reference)}" matches ${candidates.length} ${what} \u2014 name one by its id:
300
+ ${lines}`, { candidates });
301
+ }, "ambiguous");
302
+ var isPresent = /* @__PURE__ */ __name((value) => value !== null && value !== void 0, "isPresent");
303
+
304
+ // node_modules/.pnpm/@wirecat+cli-core@0.452.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.63.0_commander@15._e609b9d6c8060966368a91e843fe8bd2/node_modules/@wirecat/cli-core/dist/domain/formatting.js
305
+ var invalid = /* @__PURE__ */ __name(() => new CliError("validation_error", "the messenger formatter returned invalid text spans"), "invalid");
306
+ var validateFormattedText = /* @__PURE__ */ __name((formatted) => {
307
+ const { text, spans } = formatted;
308
+ if (typeof text !== "string" || !Array.isArray(spans) || spans.length > 100)
309
+ throw invalid();
310
+ const boundary = /* @__PURE__ */ __name((at) => !(at > 0 && at < text.length && /[\uD800-\uDBFF]/u.test(text[at - 1] ?? "") && /[\uDC00-\uDFFF]/u.test(text[at] ?? "")), "boundary");
311
+ for (const span of spans) {
312
+ if (![
313
+ "bold",
314
+ "italic",
315
+ "strike",
316
+ "underline",
317
+ "code",
318
+ "pre",
319
+ "link",
320
+ "blockquote",
321
+ "spoiler",
322
+ "highlight",
323
+ "heading"
324
+ ].includes(span.type) || !Number.isInteger(span.from) || !Number.isInteger(span.length) || span.from < 0 || span.length <= 0 || span.from + span.length > text.length || !boundary(span.from) || !boundary(span.from + span.length))
325
+ throw invalid();
326
+ if (span.type === "link") {
327
+ if (!span.url || Array.from(span.url).some((char) => char.charCodeAt(0) <= 32 || char.charCodeAt(0) === 127))
328
+ throw new CliError("validation_error", "a Markdown link needs an absolute http, https or mailto URL");
329
+ let url;
330
+ try {
331
+ url = new URL(span.url);
332
+ } catch {
333
+ throw new CliError("validation_error", "a Markdown link needs an absolute http, https or mailto URL");
334
+ }
335
+ if (!["http:", "https:", "mailto:"].includes(url.protocol))
336
+ throw new CliError("validation_error", "Markdown links support http, https and mailto URLs");
337
+ }
338
+ }
339
+ return formatted;
340
+ }, "validateFormattedText");
341
+ var visibleFormattedText = /* @__PURE__ */ __name((formatted) => {
342
+ validateFormattedText(formatted);
343
+ const text = visibleControls(formatted.text);
344
+ const positions = /* @__PURE__ */ new Map([[0, 0]]);
345
+ let original = 0;
346
+ let visible = 0;
347
+ for (const character of formatted.text) {
348
+ const rendered = text.startsWith(character, visible) ? character : visibleControls(character);
349
+ original += character.length;
350
+ visible += rendered.length;
351
+ positions.set(original, visible);
352
+ }
353
+ return {
354
+ text,
355
+ spans: formatted.spans.map((span) => ({
356
+ ...span,
357
+ from: positions.get(span.from),
358
+ length: positions.get(span.from + span.length) - positions.get(span.from),
359
+ ...span.url === void 0 ? {} : { url: visibleControls(span.url) }
360
+ }))
361
+ };
362
+ }, "visibleFormattedText");
363
+
364
+ // node_modules/.pnpm/@wirecat+cli-core@0.452.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.63.0_commander@15._e609b9d6c8060966368a91e843fe8bd2/node_modules/@wirecat/cli-core/dist/moderation/check.js
365
+ var INVITE = /max\.ru\/join\/|(t|telegram)\.me\/(\+|joinchat\/)|tg:\/\/join/i;
366
+ var LINK = /https?:\/\/\S+/i;
367
+ var STRENGTH = { report: 0, delete: 1, remove: 2 };
368
+ var judge = /* @__PURE__ */ __name(({ rules, messages, joined, answerers, service, now, invites }) => {
369
+ const invite = invites ? new RegExp(`${INVITE.source}|${invites.source}`, "i") : INVITE;
370
+ const trusted = new Set(rules.trusted);
371
+ const blocked = /* @__PURE__ */ __name((id, name) => id !== null && rules.blocked.includes(id) || name !== null && rules.blockedNames.some((part) => name.toLocaleLowerCase().includes(part.toLocaleLowerCase())), "blocked");
372
+ const young = /* @__PURE__ */ __name((member) => rules.newAccount.days > 0 && typeof member.registeredAt === "string" && now - Date.parse(member.registeredAt) < rules.newAccount.days * 864e5, "young");
373
+ const found = [];
374
+ const add = /* @__PURE__ */ __name((finding) => {
375
+ if (finding.action === "remove" && found.some((f) => f.action === "remove" && f.personId === finding.personId)) {
376
+ return;
377
+ }
378
+ found.push(finding);
379
+ }, "add");
380
+ for (const member of joined) {
381
+ if (trusted.has(member.id) || answerers.has(member.id))
382
+ continue;
383
+ const person = { kind: "member", personId: member.id, personName: member.name };
384
+ if (blocked(member.id, member.name)) {
385
+ add({ ...person, rule: "blocked", action: rules.blockedPeople === "remove" ? "remove" : "report" });
386
+ } else if (young(member)) {
387
+ add({ ...person, rule: "newAccount", action: rules.newAccount.action });
388
+ }
389
+ }
390
+ const flooding = floodOf(messages, rules.flood);
391
+ for (const message of messages) {
392
+ const id = message.senderId;
393
+ if (id === null || message.outgoing === true || answerers.has(id) || trusted.has(id))
394
+ continue;
395
+ if (service.has(message.id) || message.attachments.some((attachment) => attachment.kind === "control"))
396
+ continue;
397
+ const base = { kind: "message", personId: id, personName: message.senderName, messageId: message.id };
398
+ const text = message.text;
399
+ const broken2 = [];
400
+ if (blocked(id, message.senderName))
401
+ broken2.push(["blocked", rules.blockedPeople]);
402
+ if (invite.test(text))
403
+ broken2.push(["invites", rules.invites]);
404
+ if (LINK.test(text) || message.attachments.some((attachment) => attachment.kind === "share")) {
405
+ broken2.push(["links", rules.links]);
406
+ }
407
+ if (message.forwardedFrom !== null)
408
+ broken2.push(["forwards", rules.forwards]);
409
+ if (flooding.has(message.id))
410
+ broken2.push(["flood", rules.flood.action]);
411
+ const strongest = broken2.reduce((best, rule) => best === void 0 || STRENGTH[rule[1]] > STRENGTH[best[1]] ? rule : best, void 0);
412
+ if (strongest)
413
+ add({ ...base, rule: strongest[0], action: strongest[1] });
414
+ }
415
+ return found;
416
+ }, "judge");
417
+ var floodOf = /* @__PURE__ */ __name((messages, flood) => {
418
+ const window = flood.minutes * 6e4;
419
+ const over = /* @__PURE__ */ new Set();
420
+ const bySender = /* @__PURE__ */ new Map();
421
+ for (const message of messages) {
422
+ if (message.senderId === null)
423
+ continue;
424
+ const times = bySender.get(message.senderId) ?? [];
425
+ const at = Date.parse(message.timestamp);
426
+ times.push(at);
427
+ bySender.set(message.senderId, times);
428
+ if (times.filter((time) => at - time < window).length > flood.messages)
429
+ over.add(message.id);
430
+ }
431
+ return over;
432
+ }, "floodOf");
433
+ var act = /* @__PURE__ */ __name(async (moderator, findings, options) => {
434
+ const { chatId, rules, allowDangerous, dryRun, maxActions, confirm, command } = options;
435
+ const typed = options.commandFor ?? ((chat, finding) => commandFor(command, chat, finding));
436
+ const rows = [];
437
+ let acted = 0;
438
+ let stopped;
439
+ for (const finding of findings) {
440
+ if (finding.action === "report") {
441
+ rows.push({ ...finding, outcome: "reported" });
442
+ continue;
443
+ }
444
+ const consent = finding.action;
445
+ const level2 = rules.consent[consent];
446
+ const row = /* @__PURE__ */ __name((outcome, reason) => ({
447
+ ...finding,
448
+ outcome,
449
+ ...reason ? { reason } : {},
450
+ ...outcome === "done" || outcome === "reported" ? {} : { command: typed(chatId, finding) }
451
+ }), "row");
452
+ if (level2 === "deny") {
453
+ rows.push(row("forbidden", `consent.${consent} is deny`));
454
+ continue;
455
+ }
456
+ if (level2 === "readonly") {
457
+ rows.push(row("reported", `consent.${consent} is readonly`));
458
+ continue;
459
+ }
460
+ if (dryRun) {
461
+ rows.push(row("planned", "--dry-run"));
462
+ continue;
463
+ }
464
+ if (stopped || acted >= maxActions) {
465
+ rows.push(row("skipped", stopped ?? `over the limit of ${maxActions} actions per check`));
466
+ continue;
467
+ }
468
+ if (level2 === "ask" && !allowDangerous) {
469
+ const yes = confirm ? await confirm(finding) : void 0;
470
+ if (yes === void 0) {
471
+ rows.push(row("planned", `consent.${consent} is ask, and nobody is there to answer \u2014 run with --allow-dangerous`));
472
+ continue;
473
+ }
474
+ if (!yes) {
475
+ rows.push(row("declined", "the answer was no"));
476
+ continue;
477
+ }
478
+ }
479
+ acted += 1;
480
+ try {
481
+ if (finding.action === "delete" && finding.messageId) {
482
+ await moderator.deleteMessage(chatId, finding.messageId);
483
+ } else {
484
+ await moderator.removePerson(chatId, finding.personId);
485
+ }
486
+ rows.push(row("done"));
487
+ } catch (error) {
488
+ const failure = asCliError(error);
489
+ if (failure.code === "rate_limited")
490
+ stopped = failure.message;
491
+ const refused = ["rate_limited", "permission_error", "confirmation_required"].includes(failure.code);
492
+ rows.push(row(refused ? "refused" : "failed", failure.message));
493
+ }
494
+ }
495
+ return rows;
496
+ }, "act");
497
+ var asCliError = /* @__PURE__ */ __name((error) => error instanceof CliError ? error : new CliError("provider_error", error instanceof Error ? error.message : String(error)), "asCliError");
498
+ var who = /* @__PURE__ */ __name((finding) => finding.personName ?? finding.personId, "who");
499
+ var describe = /* @__PURE__ */ __name((finding) => finding.action === "delete" ? `delete message ${finding.messageId} from ${who(finding)} for everyone (${finding.rule})` : `remove ${who(finding)} from the group (${finding.rule})`, "describe");
500
+ var commandFor = /* @__PURE__ */ __name((command, chatId, finding) => finding.action === "delete" ? `${command} messages delete ${chatId} ${finding.messageId} --for-everyone --allow-dangerous` : finding.action === "remove" ? `${command} chats members remove ${chatId} ${finding.personId}` : "", "commandFor");
501
+ var CHECK_READS = 1e3;
502
+ var PAGE = 100;
503
+ var gather = /* @__PURE__ */ __name(async (adapter, chatId, since) => {
504
+ const notes = [];
505
+ const historyAfter = adapter.historyAfter;
506
+ if (!historyAfter)
507
+ throw new CliError("validation_error", "this messenger cannot read a chat forward from a time");
508
+ const messages = [];
509
+ let more = true;
510
+ while (more && messages.length < CHECK_READS) {
511
+ const last = messages.at(-1);
512
+ const page = await historyAfter.call(adapter, chatId, {
513
+ limit: PAGE,
514
+ after: last ? { id: last.id } : { time: since }
515
+ });
516
+ messages.push(...page.items);
517
+ more = page.hasMore && page.items.length > 0;
518
+ }
519
+ const scanned = adapter.chatEvents ? (await adapter.chatEvents(chatId, { since })).events : [];
520
+ const until = messages.at(-1)?.timestamp ?? null;
521
+ const events = more && until !== null ? scanned.filter((event) => Date.parse(event.timestamp) <= Date.parse(until)) : scanned;
522
+ if (!adapter.chatEvents)
523
+ notes.push("this messenger does not say who joined, so only messages are judged");
524
+ const joinedIds = new Set(events.filter((one) => one.event === "join" || one.event === "add").flatMap((one) => one.people.length > 0 ? one.people.map((person) => person.id) : one.by.id ? [one.by.id] : []));
525
+ const joined = joinedIds.size === 0 || !adapter.members ? [] : (await adapter.members(chatId, { offset: 0 })).items.filter((member) => joinedIds.has(member.id));
526
+ const admins = adapter.admins ? await adapter.admins(chatId) : null;
527
+ if (admins === null)
528
+ notes.push("the group's admins are not known, so only your own messages are exempt");
529
+ return {
530
+ messages,
531
+ joined,
532
+ answerers: new Set(admins ?? []),
533
+ service: new Set(events.map((one) => one.messageId)),
534
+ until,
535
+ more,
536
+ notes
537
+ };
538
+ }, "gather");
539
+ var MAX_ACTIONS = 10;
540
+ var undone = /* @__PURE__ */ __name((row) => ["planned", "skipped", "failed"].includes(row.outcome), "undone");
541
+ var nextPoint = /* @__PURE__ */ __name((rows, found) => {
542
+ const waiting = rows.filter(undone);
543
+ if (waiting.some((row) => row.messageId === void 0))
544
+ return null;
545
+ const times = waiting.map((row) => found.messages.find((message) => message.id === row.messageId)?.timestamp).filter((time) => time !== void 0).map(Date.parse);
546
+ if (times.length === 0)
547
+ return found.until;
548
+ return new Date(Math.min(...times) - 1).toISOString();
549
+ }, "nextPoint");
550
+ var someUndone = /* @__PURE__ */ __name((rows) => rows.some(undone), "someUndone");
551
+
552
+ // node_modules/.pnpm/@wirecat+cli-core@0.452.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.63.0_commander@15._e609b9d6c8060966368a91e843fe8bd2/node_modules/@wirecat/cli-core/dist/moderation/rules.js
553
+ import { existsSync, readFileSync } from "node:fs";
554
+ import { join } from "node:path";
555
+ var RULE_ACTIONS = ["report", "delete", "remove"];
556
+ var OLD_LEVELS = { forbid: "deny", flag: "ask", confirm: "ask", allow: "allow" };
557
+ var level = pipe(picklist([...LEVELS, ...Object.keys(OLD_LEVELS)]), transform((typed) => OLD_LEVELS[typed] ?? typed));
558
+ var action = picklist(RULE_ACTIONS);
559
+ var personIds = array(pipe(string(), regex(/^-?\d+$/, "a person id is digits")));
560
+ var atLeast = /* @__PURE__ */ __name((min) => pipe(number(), integer(), minValue(min)), "atLeast");
561
+ var groupRules = pipe(strictObject({
562
+ title: nullable(string()),
563
+ trusted: personIds,
564
+ blocked: personIds,
565
+ blockedNames: array(pipe(string(), minLength(1))),
566
+ links: action,
567
+ invites: action,
568
+ forwards: action,
569
+ blockedPeople: action,
570
+ flood: strictObject({ messages: atLeast(1), minutes: atLeast(1), action }),
571
+ /** 0 days turns the rule off. */
572
+ newAccount: strictObject({ days: atLeast(0), action: picklist(["report", "remove"]) }),
573
+ requests: optional(unknown()),
574
+ consent: strictObject({
575
+ delete: level,
576
+ remove: level,
577
+ accept: optional(unknown()),
578
+ decline: optional(unknown())
579
+ })
580
+ }), transform(({ requests: _, consent: { accept: _accept, decline: _decline, ...consent }, ...rules }) => ({
581
+ ...rules,
582
+ consent
583
+ })));
584
+ var file = strictObject({
585
+ groups: record(string(), groupRules),
586
+ /** Where each group's next `chats moderate` starts, ISO 8601. */
587
+ checkedUntil: optional(record(string(), string()))
588
+ });
589
+ var defaultRules = /* @__PURE__ */ __name((title) => ({
590
+ title,
591
+ trusted: [],
592
+ blocked: [],
593
+ blockedNames: [],
594
+ links: "report",
595
+ invites: "report",
596
+ forwards: "report",
597
+ blockedPeople: "report",
598
+ flood: { messages: 5, minutes: 1, action: "report" },
599
+ newAccount: { days: 7, action: "report" },
600
+ consent: { delete: "ask", remove: "ask" }
601
+ }), "defaultRules");
602
+ var list = /* @__PURE__ */ __name((value) => value.split(",").map((item) => item.trim()).filter(Boolean), "list");
603
+ var whole = /* @__PURE__ */ __name((value) => /^\d+$/.test(value.trim()) ? Number(value) : Number.NaN, "whole");
604
+ var KEYS = {
605
+ trusted: { help: "person ids, comma-separated; never acted on", parse: list },
606
+ blocked: { help: "person ids, comma-separated", parse: list },
607
+ blockedNames: { help: "parts of a name, comma-separated, any case", parse: list },
608
+ links: { help: RULE_ACTIONS.join("|"), parse: String },
609
+ invites: { help: RULE_ACTIONS.join("|"), parse: String },
610
+ forwards: { help: RULE_ACTIONS.join("|"), parse: String },
611
+ blockedPeople: { help: RULE_ACTIONS.join("|"), parse: String },
612
+ "flood.messages": { help: "a whole number, 1 or more", parse: whole },
613
+ "flood.minutes": { help: "a whole number, 1 or more", parse: whole },
614
+ "flood.action": { help: RULE_ACTIONS.join("|"), parse: String },
615
+ "newAccount.days": { help: "a whole number; 0 turns it off", parse: whole },
616
+ "newAccount.action": { help: "report|remove", parse: String },
617
+ "consent.delete": { help: LEVELS.join("|"), parse: String },
618
+ "consent.remove": { help: LEVELS.join("|"), parse: String }
619
+ };
620
+ var RULE_KEYS = Object.keys(KEYS);
621
+ var moderationPathFor = /* @__PURE__ */ __name((app, profile, env = process.env) => join(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).state, "profiles", `${profile}.moderation.json`), "moderationPathFor");
622
+ var ModerationRules = class {
623
+ static {
624
+ __name(this, "ModerationRules");
625
+ }
626
+ path;
627
+ constructor(path) {
628
+ this.path = path;
629
+ }
630
+ /** `undefined` when this group has no section yet. */
631
+ read(chatId) {
632
+ return this.#file().groups[chatId];
633
+ }
634
+ /** Writes the group's whole section — the defaults first, if it had none — with one key changed. */
635
+ set(chatId, title, key, value) {
636
+ const known = KEYS[key];
637
+ if (!known)
638
+ throw invalid2(`no rule ${key} \u2014 one of: ${RULE_KEYS.join(", ")}`);
639
+ const current = this.read(chatId) ?? defaultRules(title);
640
+ const checked = safeParse(groupRules, assign(current, key, known.parse(value)));
641
+ if (!checked.success)
642
+ throw invalid2(`${key} ${JSON.stringify(value)} is not valid \u2014 ${known.help}`);
643
+ const saved = this.#file();
644
+ this.#write({ ...saved, groups: { ...saved.groups, [chatId]: checked.output } });
645
+ return checked.output;
646
+ }
647
+ /** Puts one key back to its default. */
648
+ unset(chatId, title, key) {
649
+ if (!KEYS[key])
650
+ throw invalid2(`no rule ${key} \u2014 one of: ${RULE_KEYS.join(", ")}`);
651
+ const current = this.read(chatId) ?? defaultRules(title);
652
+ const changed2 = assign(current, key, lookup(defaultRules(title), key));
653
+ const saved = this.#file();
654
+ this.#write({ ...saved, groups: { ...saved.groups, [chatId]: changed2 } });
655
+ return changed2;
656
+ }
657
+ checkedUntil(chatId) {
658
+ return this.#file().checkedUntil?.[chatId];
659
+ }
660
+ markChecked(chatId, at) {
661
+ const saved = this.#file();
662
+ this.#write({ ...saved, checkedUntil: { ...saved.checkedUntil, [chatId]: at } });
663
+ }
664
+ #file() {
665
+ if (!existsSync(this.path))
666
+ return { groups: {} };
667
+ let parsed;
668
+ try {
669
+ parsed = JSON.parse(readFileSync(this.path, "utf8"));
670
+ } catch (error) {
671
+ throw broken(this.path, error instanceof Error ? error.message : String(error));
672
+ }
673
+ const checked = safeParse(file, parsed);
674
+ if (!checked.success) {
675
+ const problems = checked.issues.map((issue) => `${getDotPath(issue) ?? "file"}: ${issue.message}`);
676
+ throw broken(this.path, problems.join("; "));
677
+ }
678
+ return checked.output;
679
+ }
680
+ #write(content) {
681
+ writeSecurely(this.path, `${JSON.stringify(content, null, 2)}
682
+ `, 384);
683
+ }
684
+ };
685
+ var invalid2 = /* @__PURE__ */ __name((message) => new CliError("validation_error", message), "invalid");
686
+ var broken = /* @__PURE__ */ __name((path, why) => new CliError("configuration_error", `the moderation rules ${path} cannot be read (${why}) \u2014 fix the file`), "broken");
687
+ var lookup = /* @__PURE__ */ __name((rules, key) => key.split(".").reduce((value, part) => value[part], rules), "lookup");
688
+ var assign = /* @__PURE__ */ __name((rules, key, value) => {
689
+ const [head, tail] = key.split(".");
690
+ if (tail === void 0)
691
+ return { ...rules, [head]: value };
692
+ return { ...rules, [head]: { ...rules[head], [tail]: value } };
693
+ }, "assign");
694
+
695
+ export {
696
+ newSendId,
697
+ newOperationId,
698
+ isId,
699
+ foldName,
700
+ pickChat,
701
+ pickPerson,
702
+ uploadSize,
703
+ uploadBlob,
704
+ uploadBytes,
705
+ typesText,
706
+ refusedPlace,
707
+ readUpload,
708
+ readAttachments,
709
+ readStickerFile,
710
+ validateFormattedText,
711
+ visibleFormattedText,
712
+ judge,
713
+ act,
714
+ describe,
715
+ CHECK_READS,
716
+ gather,
717
+ MAX_ACTIONS,
718
+ nextPoint,
719
+ someUndone,
720
+ defaultRules,
721
+ RULE_KEYS,
722
+ moderationPathFor,
723
+ ModerationRules
724
+ };