@uniquedivine/tg-sai 0.0.4 → 0.1.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.
@@ -0,0 +1,417 @@
1
+ import { createHash, randomUUID } from "node:crypto"
2
+ import { mkdir, open, readFile, rename, rm } from "node:fs/promises"
3
+ import { dirname, isAbsolute, join, resolve } from "node:path"
4
+ import type { ChatMember } from "@mtcute/bun"
5
+ import {
6
+ addChatMembers,
7
+ createInviteLink,
8
+ createSupergroup,
9
+ getChatMember,
10
+ getPrimaryInviteLink,
11
+ iterDialogs,
12
+ } from "@mtcute/bun/methods.js"
13
+ import { saiBot } from "./cfg"
14
+ import { createMtcuteClient, promoteTargetAdmin } from "./mtcuteAdapter"
15
+ import { configDir, strictProfileCredentials } from "./profiles"
16
+ import { PROVISIONING_BOT_ID } from "./provisioning"
17
+ import { withTelemetryIdentity } from "./telemetry/middleware"
18
+ import type { ClientTelemetry } from "./telemetry/middleware"
19
+ import type {
20
+ JournalRecord,
21
+ Member,
22
+ ProvisionJournal,
23
+ ProvisionRequest,
24
+ ProvisioningLinks,
25
+ TelegramProvisioner,
26
+ } from "./provisioning"
27
+
28
+ interface PrimaryInvite {
29
+ link: string
30
+ isPrimary: boolean
31
+ isRevoked: boolean
32
+ isMyLink: boolean
33
+ endDate: Date | null
34
+ }
35
+ const COMPLETION_LINK_TIMEOUT_MS = 10_000
36
+
37
+ /** Fetch completion links without creating invitations or sending messages. */
38
+ export async function readProvisioningLinks(
39
+ chatId: number,
40
+ reader: {
41
+ history(
42
+ signal: AbortSignal,
43
+ ): Promise<readonly { id: number; chat: { id: number } }[]>
44
+ primaryInvite(signal: AbortSignal): Promise<PrimaryInvite>
45
+ },
46
+ timeoutMs = COMPLETION_LINK_TIMEOUT_MS,
47
+ ): Promise<ProvisioningLinks> {
48
+ // Bot API supergroup IDs encode the channel ID as -(10^12 + channel ID).
49
+ const channelId = -chatId - 1_000_000_000_000
50
+ if (!Number.isSafeInteger(chatId) || channelId <= 0) return {}
51
+ const bounded = async <T>(
52
+ read: (signal: AbortSignal) => Promise<T>,
53
+ ): Promise<T> => {
54
+ let timer: ReturnType<typeof setTimeout> | undefined
55
+ const controller = new AbortController()
56
+ try {
57
+ return await Promise.race([
58
+ Promise.resolve().then(() => read(controller.signal)),
59
+ new Promise<never>((_, reject) => {
60
+ timer = setTimeout(() => {
61
+ controller.abort()
62
+ reject(new Error("Completion link read timed out"))
63
+ }, timeoutMs)
64
+ }),
65
+ ])
66
+ } finally {
67
+ clearTimeout(timer)
68
+ }
69
+ }
70
+ const [history, invite] = await Promise.allSettled([
71
+ bounded(reader.history),
72
+ bounded(reader.primaryInvite),
73
+ ])
74
+ const result: ProvisioningLinks = {}
75
+ if (history.status === "fulfilled") {
76
+ const message = history.value.find(
77
+ (value) =>
78
+ value.chat.id === chatId &&
79
+ Number.isSafeInteger(value.id) &&
80
+ value.id > 0 &&
81
+ value.id <= 2_147_483_647,
82
+ )
83
+ if (message) result.openGroupUrl = `https://t.me/c/${channelId}/${message.id}`
84
+ }
85
+ if (invite.status === "fulfilled") {
86
+ const link = invite.value
87
+ if (
88
+ link.isPrimary &&
89
+ link.isMyLink &&
90
+ !link.isRevoked &&
91
+ (!link.endDate || link.endDate.getTime() > Date.now()) &&
92
+ /^https:\/\/t\.me\/(?:\+|joinchat\/)[A-Za-z0-9_-]{5,128}$/.test(link.link)
93
+ )
94
+ result.primaryInviteLink = link.link
95
+ }
96
+ return result
97
+ }
98
+
99
+ // Fresh custody sessions do not have access hashes for numeric user IDs yet.
100
+ // Handles discover the peer, but only the pinned numeric ID establishes identity.
101
+ const DEFAULT_MEMBER_HANDLES = new Map<number, string>([
102
+ [1912700300, "uniquedivine"],
103
+ [7930936303, "corinnebernett"],
104
+ [5965882418, "lilnaptime"],
105
+ [472528179, "erickpinos"],
106
+ ])
107
+
108
+ export async function resolveProvisioningPeer(
109
+ getUser: (peer: string | number) => Promise<{ id: number; isBot: boolean }>,
110
+ peer: string | number,
111
+ ): Promise<{ id: number; isBot: boolean }> {
112
+ const normalized = typeof peer === "string" ? peer.replace(/^@/, "") : peer
113
+ const numeric =
114
+ typeof normalized === "number"
115
+ ? normalized
116
+ : /^[0-9]+$/.test(normalized)
117
+ ? Number(normalized)
118
+ : undefined
119
+ const expectedId =
120
+ numeric ??
121
+ [...DEFAULT_MEMBER_HANDLES].find(
122
+ ([, handle]) => handle.toLowerCase() === String(normalized).toLowerCase(),
123
+ )?.[0]
124
+ const lookup =
125
+ expectedId === undefined
126
+ ? normalized
127
+ : (DEFAULT_MEMBER_HANDLES.get(expectedId) ?? expectedId)
128
+ const user = await getUser(lookup)
129
+ if (expectedId !== undefined && user.id !== expectedId)
130
+ throw new Error("Provisioning participant identity mismatch")
131
+ if (
132
+ expectedId !== undefined &&
133
+ DEFAULT_MEMBER_HANDLES.has(expectedId) &&
134
+ user.isBot
135
+ )
136
+ throw new Error("Default provisioning participant must be a user account")
137
+ return { id: user.id, isBot: user.isBot }
138
+ }
139
+
140
+ export function normalizeProvisioningMember(
141
+ value: Pick<ChatMember, "status" | "isMember" | "permissions"> | null,
142
+ ): Member {
143
+ const role =
144
+ value?.status === "creator"
145
+ ? "creator"
146
+ : value?.status === "admin"
147
+ ? "admin"
148
+ : value?.isMember
149
+ ? "member"
150
+ : "absent"
151
+ return {
152
+ role,
153
+ rights: Object.fromEntries(
154
+ Object.entries(value?.permissions ?? {}).filter(
155
+ (entry): entry is [string, boolean] => typeof entry[1] === "boolean",
156
+ ),
157
+ ),
158
+ }
159
+ }
160
+
161
+ /** Separate files and a process lock prevent account/session crossover. */
162
+ export function accountPaths(
163
+ root: string,
164
+ userId: number,
165
+ ): { storage: string; lock: string } {
166
+ if (!Number.isSafeInteger(userId) || userId <= 0)
167
+ throw new Error("Invalid custody user ID")
168
+ const base = resolve(root, "provisioning", "accounts", String(userId))
169
+ return {
170
+ storage: join(base, "mtcute.session"),
171
+ lock: join(base, "worker.lock"),
172
+ }
173
+ }
174
+ export async function withAccountLock<T>(
175
+ lockPath: string,
176
+ operation: () => Promise<T>,
177
+ ): Promise<T> {
178
+ if (!isAbsolute(lockPath))
179
+ throw new Error("Absolute account lock path required")
180
+ await mkdir(dirname(lockPath), { recursive: true, mode: 0o700 })
181
+ // The kernel releases flock when this process dies. Persistent lock metadata
182
+ // never authorizes deleting a live executor's lock or retrying group creation.
183
+ if (!Bun.which("flock"))
184
+ throw new Error("Custody worker requires the Linux flock utility")
185
+ const guard = Bun.spawn(
186
+ [
187
+ "flock",
188
+ "--exclusive",
189
+ "--nonblock",
190
+ lockPath,
191
+ "sh",
192
+ "-c",
193
+ "printf 'locked\\n'; cat >/dev/null",
194
+ ],
195
+ {
196
+ stdin: "pipe",
197
+ stdout: "pipe",
198
+ stderr: "pipe",
199
+ },
200
+ )
201
+ const reader = guard.stdout.getReader()
202
+ const first = await reader.read()
203
+ reader.releaseLock()
204
+ if (first.done || new TextDecoder().decode(first.value).trim() !== "locked") {
205
+ guard.stdin.end()
206
+ await guard.exited
207
+ throw new Error("Custody account is locked; another executor is active")
208
+ }
209
+ try {
210
+ return await operation()
211
+ } finally {
212
+ guard.stdin.end()
213
+ await guard.exited
214
+ }
215
+ }
216
+
217
+ export class FileProvisionJournal implements ProvisionJournal {
218
+ constructor(private root = configDir()) {}
219
+ private path(requestId: string): string {
220
+ return join(
221
+ resolve(this.root),
222
+ "provisioning",
223
+ "receipts",
224
+ `${createHash("sha256").update(requestId).digest("hex")}.json`,
225
+ )
226
+ }
227
+ async read(requestId: string): Promise<JournalRecord | null> {
228
+ try {
229
+ return JSON.parse(
230
+ await readFile(this.path(requestId), "utf8"),
231
+ ) as JournalRecord
232
+ } catch (error) {
233
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null
234
+ throw new Error("Cannot read provisioning recovery receipt")
235
+ }
236
+ }
237
+ async write(requestId: string, record: JournalRecord): Promise<void> {
238
+ const path = this.path(requestId)
239
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 })
240
+ const tmp = `${path}.${randomUUID()}.tmp`
241
+ const file = await open(tmp, "wx", 0o600)
242
+ try {
243
+ await file.writeFile(JSON.stringify(record))
244
+ await file.sync()
245
+ } finally {
246
+ await file.close()
247
+ }
248
+ await rename(tmp, path)
249
+ const directory = await open(dirname(path), "r")
250
+ try {
251
+ await directory.sync()
252
+ } finally {
253
+ await directory.close()
254
+ }
255
+ }
256
+ }
257
+
258
+ /**
259
+ * Runs `operation` with a provisioning adapter for the custody account.
260
+ * When `signal` aborts, the client is destroyed: mtcute aborts its
261
+ * `stopSignal`, which ends in-flight calls and flood-wait sleeps.
262
+ */
263
+ export async function withProvisionTelegram<T>(
264
+ request: ProvisionRequest,
265
+ operation: (telegram: TelegramProvisioner) => Promise<T>,
266
+ telemetry?: ClientTelemetry,
267
+ signal?: AbortSignal,
268
+ ): Promise<T> {
269
+ signal?.throwIfAborted()
270
+ const credentials = await strictProfileCredentials(
271
+ request.custodyProfile,
272
+ request.expectedUserId,
273
+ )
274
+ const paths = accountPaths(configDir(), request.expectedUserId)
275
+ return withAccountLock(paths.lock, async () => {
276
+ const client = await createMtcuteClient({
277
+ apiId: credentials.apiId,
278
+ apiHash: credentials.apiHash,
279
+ session: credentials.sessionString,
280
+ storage: paths.storage,
281
+ // Keys the saved flood-hold guard to the custody account.
282
+ accountId: request.expectedUserId,
283
+ }, withTelemetryIdentity(telemetry, {
284
+ accountId: request.expectedUserId,
285
+ profile: request.custodyProfile,
286
+ }))
287
+ let destroying: Promise<void> | null = null
288
+ const destroy = () => {
289
+ destroying ??= client.destroy().catch(() => {})
290
+ }
291
+ signal?.addEventListener("abort", destroy, { once: true })
292
+ try {
293
+ signal?.throwIfAborted()
294
+ if ((await client.getMe()).id !== request.expectedUserId)
295
+ throw new Error("Custody account identity mismatch")
296
+ const bot = await client.getUser(saiBot.handle)
297
+ if (bot.id !== PROVISIONING_BOT_ID || !bot.isBot)
298
+ throw new Error("Configured Sai bot identity mismatch")
299
+ const member = async (
300
+ chatId: number,
301
+ userId: number,
302
+ ): Promise<Member> => {
303
+ return normalizeProvisioningMember(
304
+ await getChatMember(client, { chatId, userId }),
305
+ )
306
+ }
307
+ const verifyMarker = async (
308
+ chatId: number,
309
+ marker: string,
310
+ ): Promise<boolean> => {
311
+ const chat = await client.getFullChat(chatId)
312
+ return (
313
+ chat.chatType === "supergroup" &&
314
+ !chat.isForum &&
315
+ chat.isCreator &&
316
+ chat.bio === marker
317
+ )
318
+ }
319
+ const linkClient = (abortSignal: AbortSignal) => client.withParams({
320
+ abortSignal,
321
+ timeout: COMPLETION_LINK_TIMEOUT_MS,
322
+ floodSleepThreshold: 0,
323
+ maxRetryCount: 0,
324
+ })
325
+ // Create and add never sleep through a flood wait: the error reaches
326
+ // provisioning, which saves its retry time and releases the worker.
327
+ const writeClient = client.withParams({ floodSleepThreshold: 0 })
328
+ const adapter: TelegramProvisioner = {
329
+ self: async () => (await client.getMe()).id,
330
+ resolve: (peer) =>
331
+ resolveProvisioningPeer((value) => client.getUser(value), peer),
332
+ create: async (title, marker) =>
333
+ (
334
+ await createSupergroup(writeClient, {
335
+ title,
336
+ description: marker,
337
+ forum: false,
338
+ })
339
+ ).id,
340
+ member,
341
+ add: async (chatId, userId) => {
342
+ const missing = await addChatMembers(writeClient, chatId, userId, {
343
+ forwardCount: 0,
344
+ })
345
+ if (missing.length)
346
+ throw Object.assign(new Error("Participant privacy restriction"), {
347
+ text: "USER_PRIVACY_RESTRICTED",
348
+ })
349
+ },
350
+ addMany: async (chatId, userIds) =>
351
+ (
352
+ await addChatMembers(writeClient, chatId, userIds, {
353
+ forwardCount: 0,
354
+ })
355
+ ).map((invitee) => invitee.userId),
356
+ inviteLink: async (chatId) => {
357
+ const expires = new Date(Date.now() + 24 * 60 * 60 * 1000)
358
+ const link = await createInviteLink(client, chatId, {
359
+ expires,
360
+ withApproval: true,
361
+ })
362
+ if (
363
+ !link.isMyLink ||
364
+ link.isRevoked ||
365
+ !link.approvalNeeded ||
366
+ !link.endDate
367
+ ) {
368
+ throw new Error(
369
+ "Controlled invitation properties were not confirmed",
370
+ )
371
+ }
372
+ return {
373
+ inviteLink: link.link,
374
+ expiresAt: link.endDate.toISOString(),
375
+ }
376
+ },
377
+ completionLinks: (chatId) =>
378
+ readProvisioningLinks(chatId, {
379
+ history: (abortSignal) =>
380
+ linkClient(abortSignal).getHistory(chatId, { limit: 1 }),
381
+ primaryInvite: (abortSignal) =>
382
+ getPrimaryInviteLink(linkClient(abortSignal), chatId),
383
+ }),
384
+ // Promotion keeps mtcute's flood sleep, as before.
385
+ promote: async (chatId, userId, rights) =>
386
+ promoteTargetAdmin(
387
+ client,
388
+ { chatId, targetPeer: userId, rights },
389
+ {},
390
+ ),
391
+ verifyMarker,
392
+ candidates: async (marker) => {
393
+ const candidates: number[] = []
394
+ for await (const dialog of iterDialogs(client, {
395
+ limit: 200,
396
+ archived: "keep",
397
+ })) {
398
+ const chat = dialog.peer
399
+ if (
400
+ chat.type !== "chat" ||
401
+ chat.chatType !== "supergroup" ||
402
+ !chat.isCreator
403
+ )
404
+ continue
405
+ if (await verifyMarker(chat.id, marker)) candidates.push(chat.id)
406
+ }
407
+ return candidates
408
+ },
409
+ }
410
+ return await operation(adapter)
411
+ } finally {
412
+ signal?.removeEventListener("abort", destroy)
413
+ if (destroying) await destroying
414
+ else await client.disconnect()
415
+ }
416
+ })
417
+ }
@@ -0,0 +1,4 @@
1
+ declare module "*.wasm" {
2
+ const path: string
3
+ export default path
4
+ }
@@ -0,0 +1,132 @@
1
+ import { createHash } from "node:crypto"
2
+ import { gzipSync, inflateSync } from "node:zlib"
3
+ import { createTelegramCryptoProvider, verifyRuntimeAssets } from "./telegramRuntime"
4
+ import { createMtcuteClient, createMtcuteRuntimeClient } from "./mtcuteAdapter"
5
+ import { mkdtemp, rm } from "node:fs/promises"
6
+ import { tmpdir } from "node:os"
7
+ import { join } from "node:path"
8
+ import { configDir, strictProfileCredentials } from "./profiles"
9
+ import { accountPaths, withAccountLock } from "./provisioningRuntime"
10
+ import { withTelemetryIdentity } from "./telemetry/middleware"
11
+ import type { ClientTelemetry } from "./telemetry/middleware"
12
+
13
+ export const HEALTH_CUSTODY_USER_ID = 8274304175
14
+ export interface RuntimeHealthCheck {
15
+ name: string
16
+ ok: boolean
17
+ reason?: string
18
+ }
19
+ export interface RuntimeHealthResult {
20
+ ok: boolean
21
+ mode: "offline" | "online"
22
+ checks: RuntimeHealthCheck[]
23
+ userId?: number
24
+ }
25
+ export interface RuntimeHealthOptions {
26
+ online?: boolean
27
+ custodyProfile?: string
28
+ timeoutMs?: number
29
+ /** Records the online getMe; identity is filled in for the custody user. */
30
+ telemetry?: ClientTelemetry
31
+ }
32
+
33
+ async function bounded<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
34
+ let timer: ReturnType<typeof setTimeout> | undefined
35
+ try {
36
+ return await Promise.race([
37
+ promise,
38
+ new Promise<never>((_, reject) => {
39
+ timer = setTimeout(() => reject(new Error("Health operation timed out")), timeoutMs)
40
+ }),
41
+ ])
42
+ } finally {
43
+ clearTimeout(timer)
44
+ }
45
+ }
46
+
47
+ /** Initialize the same provider passed to TelegramClient, without credentials or I/O to Telegram. */
48
+ export async function checkOfflineTelegramRuntime(): Promise<RuntimeHealthResult> {
49
+ const checks: RuntimeHealthCheck[] = []
50
+ try {
51
+ await verifyRuntimeAssets()
52
+ const crypto = createTelegramCryptoProvider()
53
+ await crypto.initialize()
54
+ checks.push({ name: "telegram_runtime_assets", ok: true })
55
+ const key = new Uint8Array(32).fill(7)
56
+ const iv = new Uint8Array(32).fill(3)
57
+ const input = Uint8Array.from({ length: 32 }, (_, i) => i)
58
+ const encrypted = crypto.createAesIge(key, iv).encrypt(input)
59
+ const decrypted = crypto.createAesIge(key, iv).decrypt(encrypted)
60
+ if (!Buffer.from(decrypted).equals(Buffer.from(input)) ||
61
+ Buffer.from(encrypted).equals(Buffer.from(input)))
62
+ throw new Error("Telegram crypto roundtrip failed")
63
+ const sample = new TextEncoder().encode("tg-sai compiled runtime readiness")
64
+ if (Buffer.from(crypto.sha256(sample)).toString("hex") !==
65
+ createHash("sha256").update(sample).digest("hex"))
66
+ throw new Error("Telegram hash check failed")
67
+ checks.push({ name: "telegram_crypto", ok: true })
68
+ const compressed = crypto.gzip(sample, 4096)
69
+ if (!compressed || !Buffer.from(inflateSync(compressed)).equals(Buffer.from(sample)) ||
70
+ !Buffer.from(crypto.gunzip(gzipSync(sample))).equals(Buffer.from(sample)))
71
+ throw new Error("Telegram compression check failed")
72
+ checks.push({ name: "telegram_compression", ok: true })
73
+ const directory = await mkdtemp(join(tmpdir(), "tg-sai-runtime-health-"))
74
+ const client = createMtcuteRuntimeClient({ apiId: 1, apiHash: "0".repeat(32),
75
+ storage: join(directory, "session") })
76
+ try {
77
+ // prepare initializes the real client storage and crypto, without connect/getMe.
78
+ await client.prepare()
79
+ checks.push({ name: "telegram_client_prepare", ok: true })
80
+ } finally {
81
+ try { await client.destroy() } finally { await rm(directory, { recursive: true, force: true }) }
82
+ }
83
+ return { ok: true, mode: "offline", checks }
84
+ } catch {
85
+ // Dependency errors can contain paths and imported source. Keep readiness output bounded.
86
+ checks.push({ name: "telegram_runtime", ok: false, reason: "telegram_runtime_initialization_failed" })
87
+ return { ok: false, mode: "offline", checks }
88
+ }
89
+ }
90
+
91
+ /** Explicit online mode checks only the pinned custody identity under the worker's account lock. */
92
+ export async function checkTelegramRuntimeHealth(
93
+ options: RuntimeHealthOptions = {},
94
+ ): Promise<RuntimeHealthResult> {
95
+ const offline = await checkOfflineTelegramRuntime()
96
+ if (!offline.ok || !options.online) return offline
97
+ const result: RuntimeHealthResult = { ...offline, mode: "online" }
98
+ if (!options.custodyProfile?.trim()) {
99
+ result.ok = false
100
+ result.checks.push({ name: "custody_identity", ok: false, reason: "explicit_custody_profile_required" })
101
+ return result
102
+ }
103
+ const timeoutMs = options.timeoutMs ?? 20000
104
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > 60000)
105
+ throw new Error("Health timeout must be 1000 through 60000ms")
106
+ try {
107
+ const credentials = await strictProfileCredentials(options.custodyProfile, HEALTH_CUSTODY_USER_ID)
108
+ const paths = accountPaths(configDir(), HEALTH_CUSTODY_USER_ID)
109
+ await withAccountLock(paths.lock, async () => {
110
+ const client = await createMtcuteClient({ apiId: credentials.apiId,
111
+ apiHash: credentials.apiHash, session: credentials.sessionString, storage: paths.storage,
112
+ accountId: HEALTH_CUSTODY_USER_ID },
113
+ withTelemetryIdentity(options.telemetry, {
114
+ accountId: HEALTH_CUSTODY_USER_ID, profile: options.custodyProfile }))
115
+ try {
116
+ const me = await bounded(client.getMe(), timeoutMs)
117
+ if (me.id !== HEALTH_CUSTODY_USER_ID || me.isBot)
118
+ throw new Error("Custody identity mismatch")
119
+ result.userId = me.id
120
+ } finally {
121
+ await bounded(client.destroy(), 10000)
122
+ }
123
+ })
124
+ result.checks.push({ name: "custody_identity", ok: true })
125
+ return result
126
+ } catch {
127
+ result.ok = false
128
+ result.checks.push({ name: "custody_identity", ok: false,
129
+ reason: "custody_identity_check_failed_or_account_locked" })
130
+ return result
131
+ }
132
+ }
@@ -0,0 +1,48 @@
1
+ import type { Command } from "commander"
2
+ import { checkTelegramRuntimeHealth } from "./runtimeHealth"
3
+ import { activeTelemetryRun } from "./telemetry/run"
4
+
5
+ export function addRuntimeHealthCommands(program: Command, legacyLocal?: () => Promise<void>): void {
6
+ const health = program.command("health")
7
+ .description("Check Telegram runtime readiness; defaults to offline crypto/compression checks")
8
+ .option("--offline", "Initialize the actual Telegram runtime without credentials or network access")
9
+ .option("--online", "Also verify custody getMe under the account lock; no Telegram writes")
10
+ .option("--custody-profile <name>", "Explicit saved custody profile for user 8274304175")
11
+ .option("--timeout-ms <ms>", "Online identity timeout, 1000 through 60000", "20000")
12
+ .option("--json", "Print a machine-readable readiness result")
13
+ .addHelpText("after", `
14
+ Examples:
15
+ tg-sai health
16
+ tg-sai health --offline --json
17
+ tg-sai health --online --custody-profile SaiTeam_AI --json
18
+
19
+ Offline success proves runtime initialization, not Telegram authentication.
20
+ Online mode checks the custody account only and refuses personal-profile fallback.
21
+ `)
22
+ if (legacyLocal)
23
+ health.option("--local", "Run the earlier active-profile and workstation diagnostics, including getMe")
24
+ health.action(async (options: { offline?: boolean; online?: boolean;
25
+ custodyProfile?: string; timeoutMs: string; json?: boolean; local?: boolean }) => {
26
+ if (options.offline && options.online)
27
+ throw new Error("Choose --offline or --online")
28
+ if (options.local) {
29
+ if (options.offline || options.online || options.custodyProfile || options.json)
30
+ throw new Error("--local cannot be combined with runtime health options")
31
+ await legacyLocal!()
32
+ return
33
+ }
34
+ if (options.custodyProfile && !options.online)
35
+ throw new Error("--custody-profile requires explicit --online")
36
+ const result = await checkTelegramRuntimeHealth({ online: options.online,
37
+ custodyProfile: options.custodyProfile, timeoutMs: Number(options.timeoutMs),
38
+ telemetry: activeTelemetryRun()?.client() })
39
+ if (options.json) console.log(JSON.stringify(result))
40
+ else {
41
+ console.log(`mode: ${result.mode}`)
42
+ for (const check of result.checks)
43
+ console.log(`${check.name}: ${check.ok ? "ok" : check.reason ?? "failed"}`)
44
+ console.log(`ready: ${result.ok}`)
45
+ }
46
+ process.exitCode = result.ok ? 0 : 1
47
+ })
48
+ }
@@ -69,6 +69,11 @@ def _parse_args() -> argparse.Namespace:
69
69
  return parser.parse_args()
70
70
 
71
71
 
72
+ def _is_wrapper_mode(args: argparse.Namespace) -> bool:
73
+ """Return True when tg-sai is calling this helper internally."""
74
+ return bool(args.session_output and args.no_env_write)
75
+
76
+
72
77
  def _render_qr(qr) -> None:
73
78
  import qrcode
74
79
 
@@ -149,6 +154,7 @@ def _phone_login(client: TelegramClient) -> None:
149
154
 
150
155
  def main() -> None:
151
156
  args = _parse_args()
157
+ wrapper_mode = _is_wrapper_mode(args)
152
158
 
153
159
  api_id = os.getenv("TELEGRAM_API_ID")
154
160
  api_hash = os.getenv("TELEGRAM_API_HASH")
@@ -164,16 +170,20 @@ def main() -> None:
164
170
  print("Error: TELEGRAM_API_ID must be an integer")
165
171
  sys.exit(1)
166
172
 
167
- print("\n----- Telegram Session String Generator -----\n")
168
- print("This script will generate a session string for your Telegram account.")
169
- print("The generated session string can be added to your tg-sai profile.")
170
- print("\nYour credentials are only used for local Telegram authentication.\n")
173
+ if not wrapper_mode:
174
+ print("\n----- Telegram Session String Generator -----\n")
175
+ print("This script will generate a session string for your Telegram account.")
176
+ print("The generated session string can be added to your tg-sai profile.")
177
+ print("\nYour credentials are only used for local Telegram authentication.\n")
171
178
 
172
- label = (
173
- input("Account label (optional, e.g. 'work', 'personal'; leave empty for default): ")
174
- .strip()
175
- .lower()
176
- )
179
+ if wrapper_mode:
180
+ label = ""
181
+ else:
182
+ label = (
183
+ input("Account label (optional, e.g. 'work', 'personal'; leave empty for default): ")
184
+ .strip()
185
+ .lower()
186
+ )
177
187
 
178
188
  if args.qr:
179
189
  method = "1"
@@ -207,25 +217,27 @@ def main() -> None:
207
217
  else:
208
218
  env_var = "TELEGRAM_SESSION_STRING"
209
219
 
210
- print("\nAuthentication successful!")
211
- print("\n----- Your Session String -----")
212
- print(f"\n{session_string}\n")
213
- print("Save this in tg-sai with:")
214
- print(
215
- "just tg-sai profile add "
216
- "--name <name> "
217
- f"--api-id {api_id_int} "
218
- f"--api-hash {api_hash} "
219
- "--session-string '<session string>'"
220
- )
221
- print("\nOr add this to an .env file as:")
222
- print(f"{env_var}={session_string}")
223
- print("\nIMPORTANT: Keep this string private and never share it with anyone!")
224
-
225
220
  if args.session_output:
226
221
  with open(args.session_output, "w", encoding="utf-8") as file:
227
222
  file.write(f"{session_string}\n")
228
223
 
224
+ if wrapper_mode:
225
+ print("\nAuthentication successful. Session captured by tg-sai.")
226
+ else:
227
+ print("\nAuthentication successful!")
228
+ print("\n----- Your Session String -----")
229
+ print(f"\n{session_string}\n")
230
+ print("Save this in tg-sai with:")
231
+ print(
232
+ "tg-sai profile add "
233
+ f"--api-id {api_id_int} "
234
+ f"--api-hash {api_hash} "
235
+ "--session-string '<session string>'"
236
+ )
237
+ print("\nOr add this to an .env file as:")
238
+ print(f"{env_var}={session_string}")
239
+ print("\nIMPORTANT: Keep this string private and never share it with anyone!")
240
+
229
241
  if args.no_env_write:
230
242
  choice = "n"
231
243
  else: