@wirecat/tg-cli 0.99.0 → 0.101.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 (117) hide show
  1. package/README.md +6 -5
  2. package/dist/bin/tg.js +23 -28
  3. package/dist/bundle/adapter-A3VD4Y6Z.js +2790 -0
  4. package/dist/bundle/all-profiles-UPVNHXB2.js +264 -0
  5. package/dist/bundle/anthropic-IRKNWPIB.js +71 -0
  6. package/dist/bundle/bot-api-UNTQG2M5.js +39793 -0
  7. package/dist/bundle/bot-history-V4RTY5K7.js +167 -0
  8. package/dist/bundle/bun-2JZPG2NL.js +169 -0
  9. package/dist/bundle/bun-sqlite-TZHKM225.js +70 -0
  10. package/dist/bundle/chunk-22PQUX72.js +190 -0
  11. package/dist/bundle/chunk-2DGOFLDA.js +58 -0
  12. package/dist/bundle/chunk-2SJOUK6J.js +2 -0
  13. package/dist/bundle/chunk-2XBSVRT2.js +98 -0
  14. package/dist/bundle/chunk-3KHKYYCR.js +24782 -0
  15. package/dist/bundle/chunk-4ZS73HTJ.js +6848 -0
  16. package/dist/bundle/chunk-54R2GDQ3.js +119 -0
  17. package/dist/bundle/chunk-5GKXETRP.js +1345 -0
  18. package/dist/bundle/chunk-5KU4UQBM.js +570 -0
  19. package/dist/bundle/chunk-5TPT2S2Z.js +41 -0
  20. package/dist/bundle/chunk-64DK7S4F.js +76 -0
  21. package/dist/bundle/chunk-6IPY2QRG.js +82 -0
  22. package/dist/bundle/chunk-7BFO3DY6.js +21 -0
  23. package/dist/bundle/chunk-7CBUCTB6.js +1142 -0
  24. package/dist/bundle/chunk-A5JSTZZZ.js +122 -0
  25. package/dist/bundle/chunk-ACGTFLEB.js +1275 -0
  26. package/dist/bundle/chunk-AFV74GK3.js +50 -0
  27. package/dist/bundle/chunk-AVWK4NCW.js +24600 -0
  28. package/dist/bundle/chunk-BJG6JA5U.js +35 -0
  29. package/dist/bundle/chunk-BX6HH4F6.js +215 -0
  30. package/dist/bundle/chunk-BXQS5RCE.js +8170 -0
  31. package/dist/bundle/chunk-CJ6IYCYP.js +583 -0
  32. package/dist/bundle/chunk-DG62L57H.js +2795 -0
  33. package/dist/bundle/chunk-DYNSP6FW.js +33720 -0
  34. package/dist/bundle/chunk-F7TDFWXY.js +82 -0
  35. package/dist/bundle/chunk-G2US6LJB.js +35 -0
  36. package/dist/bundle/chunk-G3ZRY436.js +3077 -0
  37. package/dist/bundle/chunk-G77QOTXE.js +18 -0
  38. package/dist/bundle/chunk-H6OXALTJ.js +45 -0
  39. package/dist/bundle/chunk-LPB2MDUW.js +452 -0
  40. package/dist/bundle/chunk-MLLJ74LM.js +24 -0
  41. package/dist/bundle/chunk-N5UFBWDM.js +166 -0
  42. package/dist/bundle/chunk-NC5WS7OP.js +31 -0
  43. package/dist/bundle/chunk-NKJJJAIJ.js +237 -0
  44. package/dist/bundle/chunk-NMGO6LW6.js +1950 -0
  45. package/dist/bundle/chunk-ODSVNH3H.js +18588 -0
  46. package/dist/bundle/chunk-OEJ5DMCX.js +2374 -0
  47. package/dist/bundle/chunk-OILBDLWL.js +724 -0
  48. package/dist/bundle/chunk-OPBTNQ35.js +1007 -0
  49. package/dist/bundle/chunk-PUBS2F5J.js +35803 -0
  50. package/dist/bundle/chunk-PYTOIDSM.js +153 -0
  51. package/dist/bundle/chunk-QOWSVDPZ.js +3526 -0
  52. package/dist/bundle/chunk-QYVVRQTN.js +73 -0
  53. package/dist/bundle/chunk-RF54YDBB.js +46 -0
  54. package/dist/bundle/chunk-RVCS7Q3A.js +6672 -0
  55. package/dist/bundle/chunk-S2JSZWEC.js +277 -0
  56. package/dist/bundle/chunk-S7ZNLLY5.js +54 -0
  57. package/dist/bundle/chunk-TGREFJVA.js +2315 -0
  58. package/dist/bundle/chunk-U46UNBMT.js +524 -0
  59. package/dist/bundle/chunk-UN6CKIBN.js +285 -0
  60. package/dist/bundle/chunk-VA5YEJS3.js +161 -0
  61. package/dist/bundle/chunk-VCGL2ETF.js +78 -0
  62. package/dist/bundle/chunk-VRSN7VLO.js +63 -0
  63. package/dist/bundle/chunk-VYDTI254.js +3332 -0
  64. package/dist/bundle/chunk-W2336E7Y.js +886 -0
  65. package/dist/bundle/chunk-X4Y2ROJI.js +541 -0
  66. package/dist/bundle/chunk-XCKD54TN.js +100 -0
  67. package/dist/bundle/chunk-ZEOCU24Z.js +738 -0
  68. package/dist/bundle/chunk-ZJVZXJOG.js +71 -0
  69. package/dist/bundle/chunk-ZV24I2UJ.js +25 -0
  70. package/dist/bundle/chunk-ZZLKX62Z.js +928 -0
  71. package/dist/bundle/command-contract-TKDI7E56.js +31 -0
  72. package/dist/bundle/dist-RJMT44PL.js +7577 -0
  73. package/dist/bundle/echarts-QZ6PR3VC.js +42501 -0
  74. package/dist/bundle/embed-UBXCXSRD.js +35 -0
  75. package/dist/bundle/embedder-B4ZTKC23.js +108 -0
  76. package/dist/bundle/entry-BTUTHO5M.js +14 -0
  77. package/dist/bundle/first-run-UC4HRIFV.js +24 -0
  78. package/dist/bundle/first-screen-SMCX6YKY.js +29 -0
  79. package/dist/bundle/identity-QSDEGDH7.js +11 -0
  80. package/dist/bundle/instructions-BBGLZKO3.js +9 -0
  81. package/dist/bundle/mcp-4Y37G2UY.js +165 -0
  82. package/dist/bundle/node-IUL5HSYI.js +2340 -0
  83. package/dist/bundle/node-LZZX22VR.js +176 -0
  84. package/dist/bundle/node-UPPL626U.js +21 -0
  85. package/dist/bundle/node-sqlite-BPGT6T5U.js +46 -0
  86. package/dist/bundle/oauth-XNE2KPKJ.js +18 -0
  87. package/dist/bundle/open-SXGYZLB5.js +20 -0
  88. package/dist/bundle/process-GPUXC4PG.js +91 -0
  89. package/dist/bundle/program-NEXEAL7T.js +1060 -0
  90. package/dist/bundle/prompt-SORGLEYI.js +13 -0
  91. package/dist/bundle/proxy-transport-G4MA6BGU.js +17 -0
  92. package/dist/bundle/recognize-UJBXORVD.js +191 -0
  93. package/dist/bundle/remote-W72AR7KH.js +26 -0
  94. package/dist/bundle/rerank-3Y2VZM3J.js +49 -0
  95. package/dist/bundle/serve-VDZIVOPR.js +196 -0
  96. package/dist/bundle/server-BERXP4GW.js +785 -0
  97. package/dist/bundle/server-ZFHN4GUF.js +178 -0
  98. package/dist/bundle/state-DGR4EE3E.js +34 -0
  99. package/dist/bundle/store-MRCFSCZD.js +121 -0
  100. package/dist/bundle/store-maintenance-command-DCMZDMYS.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 +3 -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/program.js +1 -1
  108. package/dist/program.js.map +1 -1
  109. package/dist/telegram/errors.js +1 -1
  110. package/dist/telegram/errors.js.map +1 -1
  111. package/dist/version.d.ts +1 -1
  112. package/dist/version.d.ts.map +1 -1
  113. package/dist/version.js +1 -1
  114. package/dist/version.js.map +1 -1
  115. package/install/windows.ps1 +1 -1
  116. package/package.json +6 -4
  117. package/skills/{wirecat-tg → tg-cli}/SKILL.md +4 -4
@@ -0,0 +1,1060 @@
1
+ import { createRequire as __tgRequire } from "node:module";
2
+ const require = __tgRequire(import.meta.url);
3
+ import {
4
+ AGENTS,
5
+ CONFIG,
6
+ MEMO_SCENARIOS,
7
+ SKILL,
8
+ TELEGRAM,
9
+ TELEGRAM_BOT,
10
+ accountCommand,
11
+ agentFor,
12
+ answerStdinOption,
13
+ attachmentsCommand,
14
+ botCommand,
15
+ botMcp,
16
+ chatsCommand,
17
+ commandsCommand,
18
+ completeCommand,
19
+ configCommand,
20
+ contactsCommand,
21
+ conversationsCommand,
22
+ doctorCommand,
23
+ floodCommand,
24
+ forCommand,
25
+ guideCommand,
26
+ imagesCommand,
27
+ inboxCommand,
28
+ mcpCommand,
29
+ mentionsCommand,
30
+ messagesCommand,
31
+ metadataCommand,
32
+ modelsCommand,
33
+ parseApiHash,
34
+ parseApiId,
35
+ pathsFor,
36
+ pollsCommand,
37
+ proxiedFetch,
38
+ proxySecrets,
39
+ reactionsCommand,
40
+ recipientsCommand,
41
+ repliesCommand,
42
+ resolveSettings,
43
+ restartServers,
44
+ reviewCommand,
45
+ run,
46
+ runsCommand,
47
+ scheduleCommand,
48
+ screenFor,
49
+ searchCommand,
50
+ searchesCommand,
51
+ sendsCommand,
52
+ serveCommand,
53
+ serverCommand,
54
+ sharedCommandTemplate,
55
+ signInSteps,
56
+ skillCommand,
57
+ statsCommand,
58
+ storeCommand,
59
+ tagsCommand,
60
+ tasksCommand,
61
+ topicsCommand,
62
+ upgradeCommand,
63
+ watchCommand
64
+ } from "./chunk-ODSVNH3H.js";
65
+ import {
66
+ atTerminal,
67
+ loginQr
68
+ } from "./chunk-NMGO6LW6.js";
69
+ import {
70
+ parseProxy,
71
+ proxyLabel
72
+ } from "./chunk-2XBSVRT2.js";
73
+ import "./chunk-VCGL2ETF.js";
74
+ import "./chunk-7CBUCTB6.js";
75
+ import "./chunk-MLLJ74LM.js";
76
+ import {
77
+ installSkill
78
+ } from "./chunk-U46UNBMT.js";
79
+ import "./chunk-NKJJJAIJ.js";
80
+ import "./chunk-BXQS5RCE.js";
81
+ import "./chunk-22PQUX72.js";
82
+ import "./chunk-5GKXETRP.js";
83
+ import "./chunk-CJ6IYCYP.js";
84
+ import "./chunk-DYNSP6FW.js";
85
+ import "./chunk-OILBDLWL.js";
86
+ import "./chunk-RF54YDBB.js";
87
+ import {
88
+ inSection
89
+ } from "./chunk-LPB2MDUW.js";
90
+ import "./chunk-ZZLKX62Z.js";
91
+ import "./chunk-N5UFBWDM.js";
92
+ import "./chunk-QOWSVDPZ.js";
93
+ import {
94
+ Argument,
95
+ Command,
96
+ Option,
97
+ REMOTE_WRITE,
98
+ annotate,
99
+ asFirstWord,
100
+ commandWords,
101
+ customizeSharedCommand,
102
+ environmentOf,
103
+ logsInOrOut,
104
+ outputFor,
105
+ overrideSharedContract,
106
+ printItem,
107
+ refuseCommandName,
108
+ rememberAccount,
109
+ rootOf,
110
+ secretInputOf,
111
+ withDeadline
112
+ } from "./chunk-RVCS7Q3A.js";
113
+ import {
114
+ levelFor,
115
+ runtime
116
+ } from "./chunk-OPBTNQ35.js";
117
+ import "./chunk-54R2GDQ3.js";
118
+ import "./chunk-BX6HH4F6.js";
119
+ import {
120
+ installerOf,
121
+ latestVersion,
122
+ runUpdate,
123
+ updateNotice
124
+ } from "./chunk-PYTOIDSM.js";
125
+ import "./chunk-5KU4UQBM.js";
126
+ import "./chunk-S7ZNLLY5.js";
127
+ import "./chunk-S2JSZWEC.js";
128
+ import "./chunk-ZV24I2UJ.js";
129
+ import {
130
+ TG,
131
+ VERSION
132
+ } from "./chunk-5TPT2S2Z.js";
133
+ import "./chunk-VA5YEJS3.js";
134
+ import {
135
+ servingProfiles
136
+ } from "./chunk-QYVVRQTN.js";
137
+ import "./chunk-VRSN7VLO.js";
138
+ import "./chunk-NC5WS7OP.js";
139
+ import "./chunk-H6OXALTJ.js";
140
+ import "./chunk-A5JSTZZZ.js";
141
+ import "./chunk-ACGTFLEB.js";
142
+ import "./chunk-PUBS2F5J.js";
143
+ import {
144
+ timezoneOf
145
+ } from "./chunk-G3ZRY436.js";
146
+ import "./chunk-TGREFJVA.js";
147
+ import "./chunk-W2336E7Y.js";
148
+ import "./chunk-2SJOUK6J.js";
149
+ import "./chunk-G77QOTXE.js";
150
+ import "./chunk-XCKD54TN.js";
151
+ import "./chunk-4ZS73HTJ.js";
152
+ import {
153
+ readSecret
154
+ } from "./chunk-F7TDFWXY.js";
155
+ import "./chunk-6IPY2QRG.js";
156
+ import {
157
+ configFilePath,
158
+ exitCodeFor,
159
+ indent,
160
+ processStreams,
161
+ renderPretty,
162
+ resolvePaths,
163
+ singleLine
164
+ } from "./chunk-DG62L57H.js";
165
+ import {
166
+ CliError,
167
+ isCliError
168
+ } from "./chunk-OEJ5DMCX.js";
169
+ import "./chunk-BJG6JA5U.js";
170
+ import {
171
+ __name
172
+ } from "./chunk-AFV74GK3.js";
173
+
174
+ // dist/program.js
175
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
176
+
177
+ // dist/bot-api-need.js
178
+ import { readFileSync } from "node:fs";
179
+ var WHOLE_TREE = /* @__PURE__ */ new Set(["commands", "complete", "help", "mcp", "doctor", "config", "serve", "server", "schedule"]);
180
+ var BOT_WITHOUT_API = /* @__PURE__ */ new Set([
181
+ "auth",
182
+ "list",
183
+ "chats",
184
+ "messages",
185
+ "search",
186
+ "recipients",
187
+ "sends",
188
+ "watch",
189
+ "callbacks",
190
+ "webhooks",
191
+ "contacts",
192
+ "me"
193
+ ]);
194
+ var savedBotApiKey = /* @__PURE__ */ __name((env) => {
195
+ try {
196
+ const path = configFilePath(resolvePaths({ appName: TG.appName, prefix: TG.envPrefix, env }).config);
197
+ return readFileSync(path, "utf8").includes("bot.api");
198
+ } catch {
199
+ return false;
200
+ }
201
+ }, "savedBotApiKey");
202
+ var needsBotApi = /* @__PURE__ */ __name((argv, env) => {
203
+ const end = argv.indexOf("--");
204
+ const words = end < 0 ? argv : argv.slice(0, end);
205
+ if (words.some((word) => word.includes("bot.api")))
206
+ return true;
207
+ if (words.some((word) => WHOLE_TREE.has(word)))
208
+ return true;
209
+ const bot2 = words.indexOf("bot");
210
+ if (bot2 >= 0) {
211
+ const next = words.slice(bot2 + 1).find((word) => !word.startsWith("-"));
212
+ if (next === void 0 || !BOT_WITHOUT_API.has(next))
213
+ return true;
214
+ }
215
+ return savedBotApiKey(env);
216
+ }, "needsBotApi");
217
+
218
+ // dist/commands/proxy-config.js
219
+ var withProxySecrets = /* @__PURE__ */ __name((config) => {
220
+ let pending;
221
+ config.hook("preAction", async (_self, action) => {
222
+ pending = void 0;
223
+ const [setting, value] = action.processedArgs;
224
+ if (setting !== "proxy" || !["set", "unset"].includes(action.name()))
225
+ return;
226
+ const { bot: bot2, personal } = action.opts();
227
+ if (bot2 || personal)
228
+ throw new CliError("validation_error", "proxy is one setting for the profile's account and its bot alike \u2014 drop --bot and --personal");
229
+ const { env = process.env, keyring, stdin = process.stdin } = environmentOf(action);
230
+ const secrets = proxySecrets({ env, ...keyring ? { keyring } : {} });
231
+ const scope = action.opts().defaults ? void 0 : CONFIG.resolveSettings(action.optsWithGlobals(), { env }).profile;
232
+ if (action.name() === "unset") {
233
+ pending = /* @__PURE__ */ __name(() => secrets.remove(scope), "pending");
234
+ return;
235
+ }
236
+ const typed = value === "-";
237
+ const text = typed ? await readSecret("proxy URL, hidden as you type: ", { input: stdin }) : String(value);
238
+ const proxy = asValidation(() => parseProxy(text, "proxy"));
239
+ if (!typed && proxy.secret !== void 0)
240
+ throw new CliError("validation_error", "a proxy password or MTProxy secret never goes on the command line \u2014 run `tg config set proxy -` and paste the URL");
241
+ if (proxy.kind === "mtproxy" && proxy.secret === void 0)
242
+ throw new CliError("validation_error", "an MTProxy link needs its secret \u2014 run `tg config set proxy -` and paste the whole link");
243
+ const { checkProxy } = await import("./proxy-transport-G4MA6BGU.js");
244
+ asValidation(() => checkProxy(proxy));
245
+ const label = proxyLabel(proxy);
246
+ action.processedArgs[1] = label;
247
+ pending = /* @__PURE__ */ __name(() => {
248
+ if (proxy.secret === void 0)
249
+ secrets.remove(scope);
250
+ else
251
+ secrets.write(scope, proxy.secret);
252
+ }, "pending");
253
+ });
254
+ config.hook("postAction", () => {
255
+ pending?.();
256
+ pending = void 0;
257
+ });
258
+ return config;
259
+ }, "withProxySecrets");
260
+ var asValidation = /* @__PURE__ */ __name((work) => {
261
+ try {
262
+ return work();
263
+ } catch (error) {
264
+ throw isCliError(error) ? new CliError("validation_error", error.message) : error;
265
+ }
266
+ }, "asValidation");
267
+
268
+ // dist/commands/session.js
269
+ import { existsSync, rmSync } from "node:fs";
270
+
271
+ // dist/browser.js
272
+ import { spawn } from "node:child_process";
273
+ var openInBrowser = /* @__PURE__ */ __name((url, platform = process.platform) => {
274
+ const [command, ...args] = platform === "darwin" ? ["open", url] : platform === "win32" ? ["cmd", "/c", "start", "", url] : ["xdg-open", url];
275
+ try {
276
+ const child = spawn(command ?? "xdg-open", args, { detached: true, stdio: "ignore" });
277
+ child.on("error", () => {
278
+ });
279
+ child.unref();
280
+ return true;
281
+ } catch {
282
+ return false;
283
+ }
284
+ }, "openInBrowser");
285
+
286
+ // dist/contract-overrides.js
287
+ var SHELL_OVERRIDES = {
288
+ setup: [
289
+ {
290
+ command: ["setup"],
291
+ field: "description",
292
+ before: "set up the account and connect an agent",
293
+ after: "set up Telegram and connect your agent",
294
+ reason: "This provider binds its own account linking protocol, credential flow and typed receipt to the shared setup lifecycle."
295
+ },
296
+ {
297
+ command: ["setup"],
298
+ field: "mcp",
299
+ before: false,
300
+ after: null,
301
+ reason: "This provider binds its own account linking protocol, credential flow and typed receipt to the shared setup lifecycle."
302
+ },
303
+ {
304
+ command: ["setup"],
305
+ field: "options",
306
+ before: [
307
+ {
308
+ flags: "--agent <agent>",
309
+ description: "install instructions for this agent",
310
+ takes_value: true,
311
+ mandatory: false
312
+ },
313
+ {
314
+ flags: "--method <method>",
315
+ description: "login method",
316
+ takes_value: true,
317
+ mandatory: false
318
+ }
319
+ ],
320
+ after: [
321
+ {
322
+ flags: "--agent <agent>",
323
+ description: "install the skill for this agent; asks at a terminal, otherwise none",
324
+ takes_value: true,
325
+ mandatory: false,
326
+ choices: ["none", "codex", "cursor", "claude", "gemini", "all"]
327
+ },
328
+ {
329
+ flags: "--app <how>",
330
+ description: "how to get your Telegram app credentials the first time",
331
+ takes_value: true,
332
+ mandatory: false,
333
+ choices: ["auto", "browser"],
334
+ default: "auto"
335
+ },
336
+ {
337
+ flags: "--method <method>",
338
+ description: "how to log in when there is no session",
339
+ takes_value: true,
340
+ mandatory: false,
341
+ choices: ["qr", "phone"],
342
+ default: "qr"
343
+ }
344
+ ],
345
+ reason: "This provider binds its own account linking protocol, credential flow and typed receipt to the shared setup lifecycle."
346
+ }
347
+ ],
348
+ session: [
349
+ {
350
+ command: ["session"],
351
+ field: "description",
352
+ before: "link this account, or end its login",
353
+ after: "log this profile in to Telegram, or out",
354
+ reason: "This provider binds its own account linking protocol, credential flow and typed receipt to the shared session lifecycle."
355
+ },
356
+ {
357
+ command: ["session"],
358
+ field: "effects",
359
+ before: {
360
+ remote: "none",
361
+ local: "none"
362
+ },
363
+ after: null,
364
+ reason: "This provider binds its own account linking protocol, credential flow and typed receipt to the shared session lifecycle."
365
+ },
366
+ {
367
+ command: ["session", "start"],
368
+ field: "description",
369
+ before: "link this account",
370
+ after: "log in by QR code (default) or by phone number, code and 2FA password",
371
+ reason: "This provider binds its own account linking protocol, credential flow and typed receipt to the shared session lifecycle."
372
+ },
373
+ {
374
+ command: ["session", "start"],
375
+ field: "arguments",
376
+ before: [
377
+ {
378
+ name: "method",
379
+ required: false,
380
+ variadic: false,
381
+ description: "login method"
382
+ }
383
+ ],
384
+ after: [
385
+ {
386
+ name: "method",
387
+ required: false,
388
+ variadic: false,
389
+ description: "how to log in",
390
+ choices: ["qr", "phone"],
391
+ default: "qr"
392
+ }
393
+ ],
394
+ reason: "This provider binds its own account linking protocol, credential flow and typed receipt to the shared session lifecycle."
395
+ },
396
+ {
397
+ command: ["session", "start"],
398
+ field: "options",
399
+ before: [],
400
+ after: [
401
+ {
402
+ flags: "--app <how>",
403
+ description: "the first time only: how to get this profile's app from my.telegram.org",
404
+ takes_value: true,
405
+ mandatory: false,
406
+ choices: ["browser", "auto"],
407
+ default: "browser"
408
+ },
409
+ {
410
+ flags: "--sms",
411
+ description: "phone login: ask Telegram to send the code by SMS, not to the app; Telegram may still refuse",
412
+ takes_value: false,
413
+ mandatory: false
414
+ },
415
+ {
416
+ flags: "--answer-stdin",
417
+ description: "with --json and no terminal: print each question as a `needs` line on stderr and read its answer, one line, from stdin",
418
+ takes_value: false,
419
+ mandatory: false
420
+ }
421
+ ],
422
+ reason: "This provider binds its own account linking protocol, credential flow and typed receipt to the shared session lifecycle."
423
+ },
424
+ {
425
+ command: ["session", "end"],
426
+ field: "description",
427
+ before: "end this account's login",
428
+ after: "log this profile out on Telegram's side and forget the session here",
429
+ reason: "This provider binds its own account linking protocol, credential flow and typed receipt to the shared session lifecycle."
430
+ }
431
+ ]
432
+ };
433
+
434
+ // dist/telegram/registration.js
435
+ import { randomBytes } from "node:crypto";
436
+ var MY_TELEGRAM = "https://my.telegram.org";
437
+ var registerApp = /* @__PURE__ */ __name(async (prompts, { fetch: request = fetch, shortName = randomShortName(), signal } = {}) => {
438
+ const cookies = /* @__PURE__ */ new Map();
439
+ const call = /* @__PURE__ */ __name(async (path, form) => {
440
+ const response = await request(`${MY_TELEGRAM}${path}`, {
441
+ method: form ? "POST" : "GET",
442
+ headers: {
443
+ ...form ? { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" } : {},
444
+ "X-Requested-With": "XMLHttpRequest",
445
+ Origin: MY_TELEGRAM,
446
+ Referer: `${MY_TELEGRAM}${path.startsWith("/apps") ? "/apps" : "/auth"}`,
447
+ ...cookies.size > 0 ? { Cookie: [...cookies].map(([name, value]) => `${name}=${value}`).join("; ") } : {}
448
+ },
449
+ ...form ? { body: new URLSearchParams(form).toString() } : {},
450
+ redirect: "manual",
451
+ ...signal === void 0 ? {} : { signal }
452
+ });
453
+ for (const line of response.headers.getSetCookie()) {
454
+ const [pair] = line.split(";");
455
+ const at = pair?.indexOf("=") ?? -1;
456
+ if (pair && at > 0)
457
+ cookies.set(pair.slice(0, at).trim(), pair.slice(at + 1).trim());
458
+ }
459
+ return { status: response.status, text: await response.text() };
460
+ }, "call");
461
+ const phone = (await prompts.phone()).trim();
462
+ const sent = await call("/auth/send_password", { phone });
463
+ const randomHash = parseRandomHash(sent.text);
464
+ prompts.note("my.telegram.org sent a code as a message from Telegram \u2014 open the Telegram app to read it");
465
+ const login = await call("/auth/login", { phone, random_hash: randomHash, password: (await prompts.code()).trim() });
466
+ if (login.text.trim() !== "true") {
467
+ const said = siteSays(login.text);
468
+ throw new CliError(/too many/i.test(said) ? "rate_limited" : "authentication_error", `my.telegram.org refused the code: ${said}`);
469
+ }
470
+ const page = await call("/apps");
471
+ if (page.status === 401 || page.status >= 300 && page.status < 400) {
472
+ throw new CliError("authentication_error", "my.telegram.org did not keep the login \u2014 try again in a minute");
473
+ }
474
+ const existing = readApp(page.text);
475
+ if (existing)
476
+ return { ...existing, created: false };
477
+ const hash = creationHash(page.text);
478
+ const created = await call("/apps/create", {
479
+ hash,
480
+ app_title: "tg-cli",
481
+ app_shortname: shortName,
482
+ app_url: "https://github.com/WireCatLabs/tg-cli",
483
+ app_platform: "desktop",
484
+ app_desc: "A command line interface for my own account"
485
+ });
486
+ if (created.status >= 300 || isPage(created.text)) {
487
+ throw new CliError("provider_error", `my.telegram.org did not create the app: ${siteSays(created.text)}`);
488
+ }
489
+ const app = readApp((await call("/apps")).text);
490
+ if (!app)
491
+ throw new CliError("invalid_response", "my.telegram.org says the app was created, but its page shows none");
492
+ return { ...app, created: true };
493
+ }, "registerApp");
494
+ var parseRandomHash = /* @__PURE__ */ __name((text) => {
495
+ try {
496
+ const hash = JSON.parse(text).random_hash;
497
+ if (typeof hash === "string" && hash !== "")
498
+ return hash;
499
+ } catch {
500
+ }
501
+ const said = siteSays(text);
502
+ throw new CliError(/too many/i.test(said) ? "rate_limited" : "provider_error", `my.telegram.org: ${said}`);
503
+ }, "parseRandomHash");
504
+ var readApp = /* @__PURE__ */ __name((html) => {
505
+ const text = pageText(html);
506
+ const attributes = [...html.matchAll(/\bdata-(?:value|copy)="([^"]*)"/gi)].map(([, value]) => value ?? "");
507
+ const near = /* @__PURE__ */ __name((label, value) => new RegExp(`${label.source}[\\s\\S]{0,1500}?\\bdata-(?:value|copy)="(${value.source})"`, "i").exec(html)?.[1], "near");
508
+ const only = /* @__PURE__ */ __name((value) => {
509
+ const found = new Set(attributes.filter((candidate) => new RegExp(`^${value.source}$`, "i").test(candidate)));
510
+ return found.size === 1 && isAppPage(html) ? [...found][0] : void 0;
511
+ }, "only");
512
+ const id = /api_id:?\s*(\d+)/i.exec(text)?.[1] ?? near(/api_id/, /\d+/) ?? only(/\d+/);
513
+ const hash = /api_hash:?\s*([a-f0-9]{32})\b/i.exec(text)?.[1] ?? near(/api_hash/, /[a-f0-9]{32}/) ?? only(/[a-f0-9]{32}/);
514
+ return id && hash ? { id: Number(id), hash } : void 0;
515
+ }, "readApp");
516
+ var isAppPage = /* @__PURE__ */ __name((html) => titleOf(html) === "App configuration" || /id="app_edit_form"/.test(html), "isAppPage");
517
+ var creationHash = /* @__PURE__ */ __name((html) => {
518
+ const title = titleOf(html);
519
+ const hash = [...html.matchAll(/<input\b[^>]*>/gi)].map(([tag]) => tag).filter((tag) => /\bname="hash"/i.test(tag)).map((tag) => /\bvalue="([a-fA-F0-9]+)"/i.exec(tag)?.[1]).find(Boolean);
520
+ if (hash && (title === "Create new application" || /id="app_create_form"/.test(html)))
521
+ return hash;
522
+ if (isAppPage(html)) {
523
+ throw new CliError("invalid_response", "found your app on my.telegram.org but could not read its keys \u2014 get them with --app browser");
524
+ }
525
+ throw new CliError("invalid_response", `my.telegram.org showed a page this does not know (${title ?? "no title"}) \u2014 create the app by hand with --app browser`);
526
+ }, "creationHash");
527
+ var titleOf = /* @__PURE__ */ __name((html) => {
528
+ const title = /<title>([^<]*)<\/title>/i.exec(html)?.[1];
529
+ return title === void 0 ? void 0 : singleLine(title.trim());
530
+ }, "titleOf");
531
+ var pageText = /* @__PURE__ */ __name((html) => html.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/gi, " ").replace(/<[^>]+>/g, " ").replace(/\\x0a|&nbsp;/gi, " ").replace(/\s+/g, " ").trim(), "pageText");
532
+ var randomShortName = /* @__PURE__ */ __name(() => (
533
+ // biome-ignore lint/security/noSecrets: short-name alphabet, not a key
534
+ `tgcli${[...randomBytes(6)].map((byte) => "abcdefghijklmnopqrstuvwxyz0123456789"[byte % 36]).join("")}`
535
+ ), "randomShortName");
536
+ var siteSays = /* @__PURE__ */ __name((text) => {
537
+ if (isPage(text))
538
+ return `it answered with the page "${titleOf(text) ?? "untitled"}"`;
539
+ return singleLine(pageText(jsonText(text) ?? text)).slice(0, 200) || "(empty answer)";
540
+ }, "siteSays");
541
+ var isPage = /* @__PURE__ */ __name((text) => /<html|<title/i.test(text), "isPage");
542
+ var jsonText = /* @__PURE__ */ __name((text) => {
543
+ try {
544
+ const said = JSON.parse(text).text;
545
+ return typeof said === "string" ? said : void 0;
546
+ } catch {
547
+ return void 0;
548
+ }
549
+ }, "jsonText");
550
+
551
+ // dist/commands/session.js
552
+ var appCredentials = /* @__PURE__ */ __name(async (context, how, command, ask, steps, phone, signal) => {
553
+ if (how === "auto") {
554
+ let app;
555
+ const through = context.proxy();
556
+ const fetch2 = through ? proxiedFetch(through.proxy) : void 0;
557
+ try {
558
+ app = await registerApp({
559
+ phone,
560
+ code: /* @__PURE__ */ __name(() => ask("code from Telegram for my.telegram.org (app registration): ", true, "code"), "code"),
561
+ note: context.renderer.note
562
+ }, { ...signal === void 0 ? {} : { signal }, ...fetch2 ? { fetch: fetch2 } : {} });
563
+ } catch (error) {
564
+ context.renderer.note(`The Telegram application step did not finish. Rerun as \`${command} --app browser\` to copy your app keys from the site yourself.`);
565
+ throw error;
566
+ }
567
+ context.renderer.note(app.created ? "registered a new app on my.telegram.org" : "found the app already registered on my.telegram.org");
568
+ return { id: app.id, hash: app.hash };
569
+ }
570
+ const url = `${MY_TELEGRAM}/apps`;
571
+ const opened = openInBrowser(url);
572
+ if (steps.answers)
573
+ steps.openUrl(url, "Log in with your phone number; the site sends its code in the Telegram app. Open API development tools (if no app exists, fill App title and Short name, choose Desktop, and create it), then copy App api_id and App api_hash.");
574
+ else
575
+ context.renderer.note(`${opened ? "opened" : "open"} ${url}
576
+ 1. Log in with your phone number; the site sends its code in the Telegram app.
577
+ 2. Open API development tools. If no app exists, fill App title and Short name, choose Desktop, and create it.
578
+ 3. Copy App api_id and App api_hash into this terminal. The hash is hidden as you type.
579
+ Or rerun with --app auto to have the application step done for you.`);
580
+ return {
581
+ id: parseApiId(await ask("App api_id: ", true, "api_id")),
582
+ hash: parseApiHash(await ask("App api_hash (not shown): ", false, "api_hash"))
583
+ };
584
+ }, "appCredentials");
585
+ var clockTime = /* @__PURE__ */ __name((time) => {
586
+ const zone = timezoneOf();
587
+ return `${time.toLocaleTimeString("en-GB", { timeZone: zone })} ${zone}`;
588
+ }, "clockTime");
589
+ var KEYS_IN = {
590
+ environment: "from TG_API_ID and TG_API_HASH",
591
+ keyring: "in the keyring",
592
+ file: "in a file beside the config, where there is no keyring"
593
+ };
594
+ var loggedIn = /* @__PURE__ */ __name(({ profile, account, session, appKeys, alreadyLoggedIn }, env) => {
595
+ const who = [account.username ? `@${account.username}` : void 0, `id ${account.id}`].filter(Boolean).join(", ");
596
+ const home = (env.HOME ?? env.USERPROFILE)?.replaceAll("\\", "/");
597
+ const portable = session.replaceAll("\\", "/");
598
+ const shown = home && portable.startsWith(`${home}/`) ? `~${portable.slice(home.length)}` : session;
599
+ return [
600
+ alreadyLoggedIn ? `Already logged in as ${account.name ?? "you"} (${who}) \u2014 profile ${profile}; nothing was asked. \`tg ${asFirstWord(profile)}session end\` first to log in again.` : `Logged in as ${account.name ?? "you"} (${who}) \u2014 profile ${profile}.`,
601
+ `Session: ${shown}`,
602
+ `App keys: ${appKeys ? KEYS_IN[appKeys] : "not stored"}`,
603
+ `Next: tg ${asFirstWord(profile)}chats list \xB7 tg ${asFirstWord(profile)}server install to keep the archive current`
604
+ ].join("\n");
605
+ }, "loggedIn");
606
+ var startSession = /* @__PURE__ */ __name(async (context, { method, app, sms, answers = false, command = "tg session start", progress, signal, indent: pad = 0 }) => {
607
+ if (sms && method !== "phone")
608
+ throw new CliError("validation_error", "--sms is for a phone login");
609
+ const input = context.stdin;
610
+ const terminal = atTerminal(input);
611
+ const stored = context.credentials.read();
612
+ const steps = signInSteps({
613
+ diagnostic: context.streams.diagnostic,
614
+ json: context.format !== "pretty",
615
+ answers,
616
+ input
617
+ });
618
+ if (!terminal && !answers && (method === "phone" || !stored))
619
+ throw new CliError("validation_error", `${command} asks questions \u2014 run it in a terminal${method === "qr" ? "; without one it needs stored app keys" : ""}`);
620
+ const ask = /* @__PURE__ */ __name((prompt, echo, field) => {
621
+ signal?.throwIfAborted();
622
+ if (answers)
623
+ return steps.ask({ field, secret: !echo, prompt: prompt.replace(/:\s*$/, "") }, signal);
624
+ if (!atTerminal(input)) {
625
+ throw new CliError("validation_error", `\`${command}\` needs a terminal to ask for the ${prompt.trim()}`);
626
+ }
627
+ return readSecret(`${" ".repeat(pad)}${prompt}`, { input, echo, ...signal === void 0 ? {} : { signal } });
628
+ }, "ask");
629
+ const qr = loginQr({
630
+ diagnostic: context.streams.diagnostic,
631
+ note: context.renderer.note,
632
+ indent: pad,
633
+ terminal,
634
+ json: context.format !== "pretty"
635
+ });
636
+ let typedPhone;
637
+ let asked = false;
638
+ const phone = /* @__PURE__ */ __name(async () => {
639
+ asked = true;
640
+ typedPhone ??= await ask("phone number, international format: ", true, "phone");
641
+ return typedPhone;
642
+ }, "phone");
643
+ progress?.("app");
644
+ const typed = stored ? void 0 : await appCredentials(context, app, command, ask, steps, phone, signal);
645
+ progress?.("login");
646
+ const telegram = await context.open(stored ?? typed);
647
+ context.track(telegram);
648
+ try {
649
+ const account = await telegram.login({
650
+ method,
651
+ ...sms ? { forceSms: true } : {},
652
+ showQr: /* @__PURE__ */ __name((url, expires) => {
653
+ asked = true;
654
+ qr.show(url, `scan in Telegram \u2192 Settings \u2192 Devices \u2192 Link Desktop Device (valid until ${clockTime(expires)})`, expires);
655
+ }, "showQr"),
656
+ phone,
657
+ code: /* @__PURE__ */ __name(() => {
658
+ asked = true;
659
+ return ask("login code: ", true, "code");
660
+ }, "code"),
661
+ password: /* @__PURE__ */ __name(() => {
662
+ asked = true;
663
+ return ask("2FA password (not shown): ", false, "password");
664
+ }, "password"),
665
+ note: context.renderer.note
666
+ });
667
+ signal?.throwIfAborted();
668
+ if (typed)
669
+ context.credentials.write(typed);
670
+ rememberAccount(TG, context.profile, account.id, context.env);
671
+ const appKeys = context.credentials.source() ?? null;
672
+ return { profile: context.profile, account, session: context.sessionPath, appKeys, alreadyLoggedIn: !asked };
673
+ } finally {
674
+ await telegram.close();
675
+ }
676
+ }, "startSession");
677
+ var sessionCommandDefinition = /* @__PURE__ */ __name(() => {
678
+ const session = annotate(new Command("session"), { mcp: false }).description("log this profile in to Telegram, or out");
679
+ logsInOrOut(annotate(session.command("start"), { effects: REMOTE_WRITE, lifetime: "interactive" })).description("log in by QR code (default) or by phone number, code and 2FA password").addArgument(new Argument("[method]", "how to log in").choices(["qr", "phone"]).default("qr")).addOption(new Option("--app <how>", "the first time only: how to get this profile's app from my.telegram.org").choices(["browser", "auto"]).default("browser")).option("--sms", "phone login: ask Telegram to send the code by SMS, not to the app; Telegram may still refuse").addOption(answerStdinOption()).addHelpText("after", '\nFirst time? Use `tg personal setup` for login, a check of five chats and an agent skill.\n\nExamples:\n tg personal session start QR login; app registration opens in your browser\n tg personal session start --app auto Obtain app ID/hash automatically\n tg personal session start phone Phone number, login code and optional 2FA password\n tg personal session start phone --sms The same, with the code by SMS if Telegram agrees\n tg work session start Log in to the work profile\n\nScan in Telegram: Settings > Devices > Link Desktop Device.\nFor an interrupted or expired session, finish this login, then rerun `tg <profile> setup`.\nAgents: read `tg skill show`. Run `tg <profile> session start qr` in the background (it waits for\nthe scan, and a shell tool shows nothing until it exits), read its output and paste the QR text block\ninto the chat as a code block, exactly as printed. When a new block is printed, paste it and say the old one expired. With\n--json each code is also a stderr line {"event":"qr","qr":{"text","expires_at","scan"}}. Without a\nterminal this needs stored app keys and no 2FA; phone login needs a terminal. Login is not an MCP tool.\n').action(async function(method) {
680
+ const context = forCommand(this);
681
+ refuseCommandName(context.profile, commandWords(rootOf(this)), "tg");
682
+ const { app, sms, answerStdin } = this.opts();
683
+ const answer = await startSession(context, {
684
+ command: `tg ${asFirstWord(context.profile)}session start`,
685
+ method,
686
+ app,
687
+ ...sms ? { sms } : {},
688
+ answers: answerStdin === true
689
+ });
690
+ if (context.format === "pretty")
691
+ context.streams.data(loggedIn(answer, context.env));
692
+ else {
693
+ const { appKeys, alreadyLoggedIn, account, ...rest } = answer;
694
+ printItem(context, {
695
+ ...rest,
696
+ account: { id: account.id, name: account.name, username: account.username },
697
+ app_keys: appKeys,
698
+ already_logged_in: alreadyLoggedIn
699
+ });
700
+ }
701
+ });
702
+ logsInOrOut(annotate(session.command("end"), { effects: REMOTE_WRITE })).description("log this profile out on Telegram's side and forget the session here").action(async function() {
703
+ const context = forCommand(this);
704
+ if (servingProfiles(TG, context.env).includes(context.profile))
705
+ throw new CliError("validation_error", `tg serve is running for ${context.profile} \u2014 \`tg ${asFirstWord(context.profile)}server stop\` first`);
706
+ if (!existsSync(context.sessionPath)) {
707
+ printItem(context, { profile: context.profile, ended: false });
708
+ return;
709
+ }
710
+ await context.withTelegram((telegram) => telegram.logout());
711
+ for (const suffix of ["", "-wal", "-shm"])
712
+ rmSync(`${context.sessionPath}${suffix}`, { force: true });
713
+ printItem(context, { profile: context.profile, ended: true });
714
+ });
715
+ return session;
716
+ }, "sessionCommandDefinition");
717
+ var sessionCommand = /* @__PURE__ */ __name((...args) => customizeSharedCommand(sharedCommandTemplate(TG, "session"), "This provider binds its own account linking protocol, credential flow and typed receipt to the shared session lifecycle.", () => sessionCommandDefinition(...args), SHELL_OVERRIDES.session), "sessionCommand");
718
+
719
+ // dist/commands/setup.js
720
+ import { accessSync, constants, existsSync as existsSync2, mkdirSync } from "node:fs";
721
+
722
+ // dist/update.js
723
+ import { join } from "node:path";
724
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
725
+
726
+ // node_modules/.pnpm/@wirecat+cli-core@0.466.0_@napi-rs+canvas@1.0.13_@wirecat+cli-base@0.64.0_commander@15._f7e4048410ccbe1e801fd184c043d197/node_modules/@wirecat/cli-core/dist/update/index.js
727
+ import { realpathSync } from "node:fs";
728
+ import { fileURLToPath } from "node:url";
729
+ var QUIET_WORDS = [
730
+ "--help",
731
+ "-h",
732
+ "--version",
733
+ "-V",
734
+ "--json",
735
+ "--jsonl",
736
+ "--dry-run",
737
+ "--timeout",
738
+ "commands"
739
+ ];
740
+ var appUpdate = /* @__PURE__ */ __name((app) => {
741
+ const quietWords = app.quietWords ?? QUIET_WORDS;
742
+ const installer2 = /* @__PURE__ */ __name(({ scriptPath } = {}) => installerOf(scriptPath ?? realpathSync(fileURLToPath(app.entry))), "installer");
743
+ const enabled = /* @__PURE__ */ __name((env) => {
744
+ try {
745
+ return app.enabled(env);
746
+ } catch {
747
+ return false;
748
+ }
749
+ }, "enabled");
750
+ return {
751
+ installer: installer2,
752
+ latest: /* @__PURE__ */ __name((environment = {}) => latestVersion(app.packageName, environment.fetch ?? fetch, { timeoutMs: 3e3 }), "latest"),
753
+ /** The package manager's output goes to stderr, so stdout stays one result. */
754
+ runUpdate: /* @__PURE__ */ __name((argv, environment = {}) => environment.spawn ? environment.spawn(argv) : runUpdate(argv), "runUpdate"),
755
+ /**
756
+ * The daily "a newer version exists" line, or `undefined`. Started beside the command and awaited
757
+ * after it, so asking npm costs the command nothing; any failure is silence, never an error.
758
+ */
759
+ updateNotice: /* @__PURE__ */ __name((argv, { tty, environment = {}, env = process.env } = {}) => {
760
+ try {
761
+ const delimiter = argv.indexOf("--");
762
+ const options = argv.slice(0, delimiter < 0 ? void 0 : delimiter);
763
+ const quiet = options.some((word) => quietWords.some((quietWord) => word === quietWord || word.startsWith(`${quietWord}=`)));
764
+ if (quiet)
765
+ return Promise.resolve(void 0);
766
+ const pretty = !argv.includes("--json") && !argv.includes("--jsonl") && (tty ?? process.stdout.isTTY === true);
767
+ return updateNotice({
768
+ argv,
769
+ packageName: app.packageName,
770
+ command: app.command,
771
+ version: app.version,
772
+ statePath: app.statePath(env),
773
+ fetch: environment.fetch ?? fetch,
774
+ ...environment.now ? { now: environment.now } : {},
775
+ format: pretty ? "pretty" : "json",
776
+ stderrIsTTY: environment.stderrIsTTY ?? process.stderr.isTTY === true,
777
+ quiet: argv.includes("--quiet"),
778
+ enabled: enabled(env),
779
+ installer: installer2(environment),
780
+ env,
781
+ offVariables: app.offVariables
782
+ });
783
+ } catch {
784
+ return Promise.resolve(void 0);
785
+ }
786
+ }, "updateNotice")
787
+ };
788
+ }, "appUpdate");
789
+
790
+ // dist/update.js
791
+ var PACKAGE = "@wirecat/tg-cli";
792
+ var { installer, latest, runUpdate: runUpdate2, updateNotice: updateNotice2 } = appUpdate({
793
+ packageName: PACKAGE,
794
+ command: "tg",
795
+ version: VERSION,
796
+ entry: new URL("../update.js", import.meta.url).href,
797
+ statePath: /* @__PURE__ */ __name((env) => join(pathsFor(env).state, "update-check.json"), "statePath"),
798
+ enabled: /* @__PURE__ */ __name((env) => resolveSettings({}, { env, needsProfile: false }).updateCheck, "enabled"),
799
+ offVariables: ["TG_NO_UPDATE_CHECK"]
800
+ });
801
+ var tgScript = /* @__PURE__ */ __name(() => fileURLToPath2(new URL("./bin/tg.js", new URL("../update.js", import.meta.url).href)), "tgScript");
802
+
803
+ // dist/commands/setup.js
804
+ var STEPS = 5;
805
+ var chatCount = /* @__PURE__ */ __name((count) => `${count} ${count === 1 ? "chat" : "chats"}`, "chatCount");
806
+ var setupCommandDefinition = /* @__PURE__ */ __name(() => logsInOrOut(annotate(new Command("setup"), { effects: REMOTE_WRITE, lifetime: "interactive" })).description("set up Telegram and connect your agent").configureHelp({ showGlobalOptions: true }).addHelpText("after", "\nExamples:\n tg personal setup Guided setup of profile personal in your local terminal\n tg personal setup --agent codex Install the skill for Codex\n tg work setup --agent claude Set up a separate work profile\n tg personal setup --app browser Get app ID/hash through my.telegram.org\n tg personal setup --method phone Use a phone login instead of QR\n\nThe first word names the profile; every later command names it too.\n\nAllow about 5 minutes. App registration and account login are separate steps.\nScan the QR in Telegram: Settings > Devices > Link Desktop Device.\nEnter codes, app hashes and passwords only in the terminal.\n\nAgents: read `tg skill show` first. With stored app keys and no 2FA, an agent can run\n tg personal setup --agent codex --json\nin the background and paste the QR text block it prints into the chat, exactly as printed.\nOtherwise the first login needs a local terminal. Machine mode skips agent installation\nunless --agent is given. Existing sessions are checked without another login.\n\nSetup checks five chats. Choose a chat and an amount of history before:\n tg personal messages sync <chat> --last 100\n\nWindows: use tg.cmd or npm.cmd if PowerShell blocks scripts. Without PATH:\n npm.cmd exec --yes --package=@wirecat/tg-cli -- tg personal setup\n").addOption(new Option("--agent <agent>", "install the skill for this agent; asks at a terminal, otherwise none").choices(AGENTS)).addOption(new Option("--app <how>", "how to get your Telegram app credentials the first time").choices(["auto", "browser"]).default("auto")).addOption(new Option("--method <method>", "how to log in when there is no session").choices(["qr", "phone"]).default("qr")).action(async function() {
807
+ const context = forCommand(this);
808
+ refuseCommandName(context.profile, commandWords(rootOf(this)), "tg");
809
+ const options = this.opts();
810
+ if (context.settings.offline)
811
+ throw new CliError("validation_error", "tg setup verifies Telegram \u2014 remove --offline");
812
+ for (const permission of ["account.show", "chats.list"]) {
813
+ if (levelFor(context.settings.permissions, permission).level === "deny")
814
+ throw new CliError("permission_error", `profile ${context.profile} denies ${permission} \u2014 setup cannot verify it`, { permission });
815
+ }
816
+ const reused = existsSync2(context.sessionPath);
817
+ if (!reused && !atTerminal(context.stdin) && (options.method === "phone" || !context.credentials.read()))
818
+ throw new CliError("validation_error", "tg setup needs a terminal for the first login \u2014 run it locally; without one it logs in only by QR, with stored app credentials");
819
+ const prefix = `tg ${asFirstWord(context.profile)}`;
820
+ const command = installer(environmentOf(this).update) === "npx" ? `npm${process.platform === "win32" ? ".cmd" : ""} exec --yes --package=@wirecat/tg-cli -- ${prefix}` : prefix;
821
+ const cancellation = new AbortController();
822
+ const closeables = [
823
+ {
824
+ close: /* @__PURE__ */ __name(async () => {
825
+ cancellation.abort();
826
+ }, "close")
827
+ }
828
+ ];
829
+ const screen = screenFor(context, this.optsWithGlobals().quiet === true, STEPS);
830
+ const loginContext = {
831
+ ...context,
832
+ renderer: { ...context.renderer, note: screen.detail },
833
+ open: /* @__PURE__ */ __name(async (credentials) => {
834
+ cancellation.signal.throwIfAborted();
835
+ const telegram = await context.open(credentials);
836
+ if (cancellation.signal.aborted) {
837
+ await telegram.close();
838
+ cancellation.signal.throwIfAborted();
839
+ }
840
+ closeables.push(telegram);
841
+ return telegram;
842
+ }, "open")
843
+ };
844
+ const answer = await withDeadline(context.settings.commandTimeoutMs, closeables, async () => {
845
+ screen.title(`Telegram setup \u2014 profile ${context.profile}. Allow about 5 minutes; downloading chat history is a separate step.`);
846
+ screen.step(1, "This computer");
847
+ const paths = pathsFor(context.env);
848
+ for (const path of [paths.config, paths.state, paths.cache]) {
849
+ mkdirSync(path, { recursive: true });
850
+ accessSync(path, constants.W_OK);
851
+ }
852
+ screen.detail("\u2713 local directories ready");
853
+ if (process.platform === "win32")
854
+ screen.detail("Windows: use tg.cmd or npm.cmd if PowerShell blocks scripts. Open a new terminal after installing Node.js.");
855
+ if (reused) {
856
+ screen.step(2, "Telegram app ID and hash");
857
+ screen.detail("\u2713 stored credentials");
858
+ screen.step(3, "Link this device");
859
+ screen.detail("\u2713 existing session, no new login");
860
+ } else {
861
+ await context.run(async () => {
862
+ await startSession(loginContext, {
863
+ signal: cancellation.signal,
864
+ method: options.method,
865
+ app: options.app,
866
+ command: `${prefix}setup`,
867
+ indent: screen.indent,
868
+ progress: /* @__PURE__ */ __name((step) => step === "app" ? screen.step(2, "Telegram app ID and hash") : screen.step(3, "Link this device"), "progress")
869
+ });
870
+ });
871
+ }
872
+ screen.step(4, "Account");
873
+ const { account, chats: chats2 } = await context.withTelegram(async (telegram) => {
874
+ closeables.push(telegram);
875
+ cancellation.signal.throwIfAborted();
876
+ if (!telegram.chats)
877
+ throw new CliError("provider_error", "Telegram connection cannot list chats");
878
+ return { account: await telegram.me(), chats: await telegram.chats({ limit: 5, offset: 0 }) };
879
+ });
880
+ screen.detail(`\u2713 verified, ${chatCount(chats2.items.length)} read`);
881
+ screen.step(5, "Agent");
882
+ const agent2 = await agentFor(context, options.agent, screen.indent, {
883
+ ...secretInputOf(this),
884
+ input: context.stdin,
885
+ signal: cancellation.signal
886
+ });
887
+ screen.detail(agent2 === "none" ? "\u2713 no agent skill installed" : `\u2713 ${agent2}`);
888
+ const targets = agent2 === "all" ? ["claude", "agents"] : [agent2 === "claude" ? "claude" : "agents"];
889
+ cancellation.signal.throwIfAborted();
890
+ const written = agent2 === "none" ? [] : installSkill(TG, SKILL, { targets, env: context.env });
891
+ const commands2 = {
892
+ instructions: `${command}skill show`,
893
+ inbox: `${command}inbox --limit 5`,
894
+ chats: `${command}chats list --limit 5`,
895
+ history: `${command}messages sync <chat> --last 100`,
896
+ history_status: `${command}store status`,
897
+ ...agent2 === "none" ? { skill: `${command}skill install`, mcp: `${command}mcp config` } : {}
898
+ };
899
+ const answer2 = {
900
+ profile: context.profile,
901
+ runtime: runtime(),
902
+ paths,
903
+ session: { path: context.sessionPath, reused },
904
+ account: { id: account.id, name: account.name, username: account.username },
905
+ chats: { checked: chats2.items.length, has_more: chats2.hasMore },
906
+ agent: { name: agent2, written },
907
+ commands: commands2
908
+ };
909
+ return answer2;
910
+ });
911
+ const { agent, commands, chats } = answer;
912
+ if (context.format !== "pretty")
913
+ printItem(context, answer);
914
+ else {
915
+ const rows = {
916
+ "Try now": commands.inbox,
917
+ History: `${commands.history} (choose the chat and the amount first)`,
918
+ "Agent skill": agent.name === "none" ? `skipped \u2014 install later: ${commands.skill}` : `installed for ${agent.name}; start a new agent session if it is not found`,
919
+ "For an agent": commands.instructions
920
+ };
921
+ context.streams.data(`
922
+ \u2713 Telegram is ready \u2014 profile ${context.profile}, ${chatCount(chats.checked)} checked
923
+
924
+ ` + indent(renderPretty(rows, { color: context.color }), 2));
925
+ }
926
+ }), "setupCommandDefinition");
927
+ var setupCommand = /* @__PURE__ */ __name((...args) => customizeSharedCommand(sharedCommandTemplate(TG, "setup"), "This provider binds its own account linking protocol, credential flow and typed receipt to the shared setup lifecycle.", () => setupCommandDefinition(...args), SHELL_OVERRIDES.setup), "setupCommand");
928
+
929
+ // dist/commands/update.js
930
+ var upgradeCommand2 = /* @__PURE__ */ __name(() => upgradeCommand(TG, PACKAGE, (command) => {
931
+ const context = environmentOf(command);
932
+ const environment = context.update ?? {};
933
+ const env = context.env ?? process.env;
934
+ return {
935
+ ...outputFor(command),
936
+ installer: /* @__PURE__ */ __name(() => installer(environment), "installer"),
937
+ latest: /* @__PURE__ */ __name(() => latest(environment), "latest"),
938
+ install: /* @__PURE__ */ __name((argv) => runUpdate2(argv, environment), "install"),
939
+ afterUpdate: /* @__PURE__ */ __name(() => restartServers(TG, tgScript(), env, environment.spawn), "afterUpdate")
940
+ };
941
+ }), "upgradeCommand");
942
+
943
+ // dist/program.js
944
+ var NO_RESTART_ON = [exitCodeFor("authentication_error")];
945
+ var botApi;
946
+ var useBotApi = /* @__PURE__ */ __name((group) => {
947
+ botApi = group;
948
+ }, "useBotApi");
949
+ var bot = /* @__PURE__ */ __name(() => {
950
+ const command = botCommand({ ...TELEGRAM_BOT, mcp: botMcp(run2) });
951
+ return botApi ? command.addCommand(botApi()) : command;
952
+ }, "bot");
953
+ var definition = {
954
+ app: TG,
955
+ configuration: CONFIG,
956
+ firstScreen: {
957
+ pitch: "your Telegram account for agents and scripts. What it reads stays on your computer; search, review and tasks work offline.",
958
+ can: [
959
+ { command: "review 'date>1d'", does: "what changed in every chat since yesterday" },
960
+ { command: "tasks agenda", does: "tasks due, replies you owe, replies you wait for" },
961
+ { command: "inbox --transcribe", does: "unread in every chat, voice as text; marks nothing read by default" },
962
+ { command: "search all invoice", does: "messages and notes, from the local store and Telegram's server" },
963
+ { command: "attachments extract", does: "text of PDFs and documents, ready for search" },
964
+ { command: "schedule agent \u2026", does: "an agent on a timer; it runs read-only and can never send" },
965
+ { command: "mcp serve --permission \u2026", does: "your account in any agent, with messages.send=deny" },
966
+ { command: "TG_READ_ONLY=1 tg \u2026", does: "a run that can read and sync but never send, edit or delete" }
967
+ ]
968
+ },
969
+ configure: /* @__PURE__ */ __name((program) => {
970
+ program.commands.find((command) => command.name() === "skill")?.addHelpText("after", "\nBefore the first login, an agent can read `tg skill show`; no session is needed.\nRun `tg personal setup --agent codex` for guided login and skill installation.\nTo install instructions separately: `tg skill install --for all`.\n");
971
+ const contacts = program.commands.find((command) => command.name() === "contacts");
972
+ const check = contacts?.commands.find((command) => command.name() === "check");
973
+ const registries = check?.options.find((option) => option.long === "--no-registries");
974
+ if (registries && check)
975
+ overrideSharedContract(check, "Telegram can query its profile and photos independently of the public ban registries.", () => {
976
+ registries.description = "skip public ban lists; still ask Telegram for the profile and photos unless --offline";
977
+ });
978
+ const contactContext = contacts?.commands.find((command) => command.name() === "context");
979
+ if (contactContext)
980
+ overrideSharedContract(contactContext, "Telegram's contact context stays local unless the caller explicitly asks to sync.", (command) => {
981
+ command.description("what the local store holds about a person; --chat --sync-first explicitly asks Telegram first");
982
+ });
983
+ const membersCheck = program.commands.find((command) => command.name() === "chats")?.commands.find((command) => command.name() === "members")?.commands.find((command) => command.name() === "check");
984
+ if (membersCheck)
985
+ overrideSharedContract(membersCheck, "Telegram supports an explicit deep member check with bounded profile and history reads.", (command) => {
986
+ command.description("members that look like bots, each with its reasons, from the member list and local store; --deep checks selected people individually; removes nobody");
987
+ });
988
+ const deep = membersCheck?.options.find((option) => option.long === "--deep");
989
+ if (deep && membersCheck)
990
+ overrideSharedContract(membersCheck, "Telegram's deep check describes its provider-specific disclosure and request pace.", () => {
991
+ deep.description = "also check the top n profiles, oldest photos, up to 1,000 stored messages each and public ban lists, which are sent their ids \u2014 one person a second";
992
+ });
993
+ }, "configure"),
994
+ commands: /* @__PURE__ */ __name(() => [
995
+ inSection(sessionCommand(), "setup"),
996
+ inSection(setupCommand(), "setup"),
997
+ accountCommand(TELEGRAM),
998
+ chatsCommand(TELEGRAM),
999
+ contactsCommand(TELEGRAM),
1000
+ messagesCommand(TELEGRAM),
1001
+ reactionsCommand(TELEGRAM),
1002
+ pollsCommand(TELEGRAM),
1003
+ modelsCommand(TELEGRAM),
1004
+ inboxCommand(TELEGRAM),
1005
+ reviewCommand(TELEGRAM),
1006
+ topicsCommand(TELEGRAM),
1007
+ watchCommand(TELEGRAM),
1008
+ serveCommand(TELEGRAM),
1009
+ serverCommand(TELEGRAM, { unit: { noRestartOn: NO_RESTART_ON } }),
1010
+ scheduleCommand(TELEGRAM),
1011
+ storeCommand(TELEGRAM),
1012
+ conversationsCommand(TELEGRAM),
1013
+ attachmentsCommand(TELEGRAM),
1014
+ tagsCommand(TELEGRAM),
1015
+ mentionsCommand(TELEGRAM),
1016
+ imagesCommand(TELEGRAM),
1017
+ metadataCommand(TELEGRAM),
1018
+ statsCommand(TELEGRAM),
1019
+ tasksCommand(TELEGRAM),
1020
+ searchCommand(TELEGRAM, { topics: true }),
1021
+ searchesCommand(TELEGRAM),
1022
+ floodCommand(TELEGRAM),
1023
+ repliesCommand(TELEGRAM),
1024
+ recipientsCommand(TELEGRAM),
1025
+ sendsCommand(TELEGRAM),
1026
+ runsCommand(TG),
1027
+ withProxySecrets(configCommand(TG, CONFIG)),
1028
+ doctorCommand(TELEGRAM),
1029
+ commandsCommand(TG),
1030
+ completeCommand(TELEGRAM, CONFIG),
1031
+ upgradeCommand2(),
1032
+ mcpCommand(TELEGRAM),
1033
+ bot(),
1034
+ skillCommand(TG, SKILL),
1035
+ guideCommand(TG, {
1036
+ directory: fileURLToPath3(new URL("../scenarios", new URL("../program.js", import.meta.url).href)),
1037
+ worksWith: [MEMO_SCENARIOS.personBrief]
1038
+ })
1039
+ ], "commands")
1040
+ };
1041
+ var run2 = /* @__PURE__ */ __name(async (argv, environment = {}) => {
1042
+ if (!botApi && needsBotApi(argv, environment.env ?? process.env))
1043
+ useBotApi((await import("./bot-api-UNTQG2M5.js")).telegramBotApiCommand);
1044
+ const notice = updateNotice2(argv, {
1045
+ ...environment.tty === void 0 ? {} : { tty: environment.tty },
1046
+ ...environment.update ? { environment: environment.update } : {},
1047
+ ...environment.env ? { env: environment.env } : {}
1048
+ });
1049
+ const code = await run(argv, definition, environment);
1050
+ const line = await notice;
1051
+ if (line && code === 0)
1052
+ (environment.streams ?? processStreams).diagnostic(line);
1053
+ return code;
1054
+ }, "run");
1055
+ export {
1056
+ NO_RESTART_ON,
1057
+ definition,
1058
+ run2 as run,
1059
+ useBotApi
1060
+ };