@uniquedivine/tg-sai 0.0.5 → 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.
package/provisioning.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { createHash } from "node:crypto"
2
2
 
3
+ import { holdUntil, PEER_FLOOD_WAIT_S } from "./state/holds"
4
+
3
5
  export const PROVISIONING_BOT_ID = 8983431101
4
6
  export type Peer = number | string
5
7
  export interface ProvisionRequest {
@@ -48,6 +50,11 @@ export interface TelegramProvisioner {
48
50
  create(title: string, marker: string): Promise<number>
49
51
  member(chatId: number, userId: number): Promise<Member>
50
52
  add(chatId: number, userId: number): Promise<void>
53
+ /**
54
+ * Adds several users in one call. Resolves to the IDs Telegram reports as
55
+ * not invited (privacy); throws for errors that refuse the whole call.
56
+ */
57
+ addMany?(chatId: number, userIds: number[]): Promise<number[]>
51
58
  inviteLink?(
52
59
  chatId: number,
53
60
  userId: number,
@@ -300,10 +307,17 @@ export async function bindRequest(
300
307
  /** Only explicit server rejection proves creation did not happen. Transport failures remain unknown. */
301
308
  export function definiteCreateRejection(error: unknown): boolean {
302
309
  const e = error as { text?: string; code?: number }
310
+ if (typeof e?.text !== "string") return false
311
+ // The local hold guard refuses before sending, so the call never reached
312
+ // Telegram: a hold (420) or an unreadable hold store (500).
313
+ if (
314
+ (e.code === 420 && /^TG_SAI_HOLD_\d+$/.test(e.text)) ||
315
+ (e.code === 500 && e.text === HOLD_STATE_UNAVAILABLE)
316
+ )
317
+ return true
303
318
  return (
304
- [400, 401, 403, 420].includes(e?.code ?? 0) &&
305
- typeof e.text === "string" &&
306
- /^(?:FLOOD_WAIT|CHANNELS_TOO_MUCH|USER_RESTRICTED|CHAT_TITLE_EMPTY|CHAT_ABOUT_TOO_LONG|AUTH_KEY_UNREGISTERED|SESSION_REVOKED)(?:_%d|_\d+)?$/.test(
319
+ [400, 401, 403, 420].includes(e.code ?? 0) &&
320
+ /^(?:FLOOD_WAIT|FLOOD_PREMIUM_WAIT|PEER_FLOOD|CHANNELS_TOO_MUCH|USER_RESTRICTED|CHAT_TITLE_EMPTY|CHAT_ABOUT_TOO_LONG|AUTH_KEY_UNREGISTERED|SESSION_REVOKED)(?:_%d|_\d+)?$/.test(
307
321
  e.text,
308
322
  )
309
323
  )
@@ -318,7 +332,7 @@ export function safeProvisionError(error: unknown): string {
318
332
  String(Number.isSafeInteger(e.seconds) ? e.seconds : "UNKNOWN"),
319
333
  )
320
334
  : ""
321
- return /^(?:FLOOD(?:_PREMIUM)?_WAIT_(?:\d{1,10}|UNKNOWN)|USER_PRIVACY_RESTRICTED|USER_NOT_MUTUAL_CONTACTS?|USER_NOT_PARTICIPANT|USER_CHANNELS_TOO_MUCH|USER_BOT|USER_ID_INVALID|PEER_ID_INVALID|CHAT_ID_INVALID|CHANNEL_INVALID|CHANNEL_PRIVATE|CHAT_ADMIN_REQUIRED|CHAT_WRITE_FORBIDDEN|USER_ADMIN_INVALID|USER_CREATOR|ADMINS_TOO_MUCH|BOTS_TOO_MUCH|BOT_GROUPS_BLOCKED|RIGHT_FORBIDDEN|USER_RESTRICTED|USER_DEACTIVATED|INPUT_USER_DEACTIVATED|CHANNELS_TOO_MUCH|USERS_TOO_MUCH|AUTH_KEY_UNREGISTERED|SESSION_REVOKED|INVITE_HASH_EXPIRED|INVITE_HASH_INVALID|INVITE_REQUEST_SENT)$/.test(
335
+ return /^(?:FLOOD(?:_PREMIUM)?_WAIT_(?:\d{1,10}|UNKNOWN)|PEER_FLOOD|TG_SAI_HOLD_\d{1,10}|TG_SAI_HOLD_STATE_UNAVAILABLE|USER_PRIVACY_RESTRICTED|USER_NOT_MUTUAL_CONTACTS?|USER_NOT_PARTICIPANT|USER_CHANNELS_TOO_MUCH|USER_BOT|USER_ID_INVALID|PEER_ID_INVALID|CHAT_ID_INVALID|CHANNEL_INVALID|CHANNEL_PRIVATE|CHAT_ADMIN_REQUIRED|CHAT_WRITE_FORBIDDEN|USER_ADMIN_INVALID|USER_CREATOR|ADMINS_TOO_MUCH|BOTS_TOO_MUCH|BOT_GROUPS_BLOCKED|RIGHT_FORBIDDEN|USER_RESTRICTED|USER_DEACTIVATED|INPUT_USER_DEACTIVATED|CHANNELS_TOO_MUCH|USERS_TOO_MUCH|AUTH_KEY_UNREGISTERED|SESSION_REVOKED|INVITE_HASH_EXPIRED|INVITE_HASH_INVALID|INVITE_REQUEST_SENT)$/.test(
322
336
  normalized,
323
337
  )
324
338
  ? normalized
@@ -348,6 +362,24 @@ export function safeProvisionDiagnostic(
348
362
  return `${step}:${safeProvisionError(error)}`
349
363
  }
350
364
 
365
+ /**
366
+ * Whether a refused add concerns only the user(s) being added, so the other
367
+ * users can still be tried one by one: privacy refusals, and 400 errors
368
+ * named `USER_*`, `CHAT_*`, or `BOT_GROUPS_BLOCKED` (e.g.
369
+ * `USER_CHANNELS_TOO_MUCH`). Flood waits, `PEER_FLOOD`, and local holds
370
+ * are never per-user.
371
+ */
372
+ export function isPerUserAddError(error: unknown): boolean {
373
+ if (isPrivacyRestriction(error)) return true
374
+ const e = error as { text?: unknown; errorMessage?: unknown; code?: unknown }
375
+ const text = typeof e?.text === "string" ? e.text : e?.errorMessage
376
+ return (
377
+ e?.code === 400 &&
378
+ typeof text === "string" &&
379
+ /^(?:USER_[A-Z0-9_]+|CHAT_[A-Z0-9_]+|BOT_GROUPS_BLOCKED)$/.test(text)
380
+ )
381
+ }
382
+
351
383
  export function isPrivacyRestriction(error: unknown): boolean {
352
384
  const e = error as { text?: string; errorMessage?: string; code?: number }
353
385
  return [e?.text, e?.errorMessage].some(
@@ -358,17 +390,68 @@ export function isPrivacyRestriction(error: unknown): boolean {
358
390
  ),
359
391
  )
360
392
  }
393
+ /** Text of `HoldStoreUnavailableError` (state/holds.ts). */
394
+ export const HOLD_STATE_UNAVAILABLE = "TG_SAI_HOLD_STATE_UNAVAILABLE"
395
+ /** Retry delay while the hold store cannot be read. */
396
+ export const HOLD_STATE_UNAVAILABLE_RETRY_MS = 5 * 60 * 1000
397
+ /** Telegram gives no duration for `PEER_FLOOD`; holds use 24 h. */
398
+ export const PEER_FLOOD_RETRY_MS = PEER_FLOOD_WAIT_S * 1000
399
+ /**
400
+ * Least lead a cloud `retryAt` gets over now, so Deal Desk never rejects
401
+ * it as not in the future after clock skew or a slow request.
402
+ */
403
+ export const MIN_CLOUD_RETRY_MS = 30_000
404
+ const MAX_RETRY_MS = 31_536_000 * 1000
405
+
406
+ /**
407
+ * Cloud `retryAt` for a local hold ending at `untilMs`: that time, or
408
+ * `MIN_CLOUD_RETRY_MS` from now when later. Never before the hold ends.
409
+ * `null` when the time is not finite or more than a year out.
410
+ */
411
+ export function cloudRetryAt(untilMs: number, now = Date.now()): string | null {
412
+ if (!Number.isFinite(untilMs)) return null
413
+ const at = Math.max(Math.ceil(untilMs), now + MIN_CLOUD_RETRY_MS)
414
+ return at - now <= MAX_RETRY_MS ? new Date(at).toISOString() : null
415
+ }
416
+
417
+ /**
418
+ * When a flood or hold error allows an unattended retry: `FLOOD_WAIT_N`
419
+ * (also mtcute's `FLOOD_WAIT_%d` with `seconds`), `FLOOD_PREMIUM_WAIT_N`,
420
+ * `PEER_FLOOD` (24 h), `TG_SAI_HOLD_N` (the hold's `untilMs` when present),
421
+ * and `TG_SAI_HOLD_STATE_UNAVAILABLE` (5 min). Telegram waits get the same
422
+ * margin as the local hold (`holdUntil`), and every time is at least
423
+ * `MIN_CLOUD_RETRY_MS` out (`cloudRetryAt`). `null` for anything else.
424
+ */
361
425
  export function provisionRetryAt(
362
426
  error: unknown,
363
427
  now = Date.now(),
364
428
  ): string | null {
365
- const e = error as { text?: string; errorMessage?: string; seconds?: number }
429
+ const e = error as {
430
+ text?: string
431
+ errorMessage?: string
432
+ seconds?: number
433
+ untilMs?: number
434
+ }
366
435
  const code = e?.text ?? e?.errorMessage ?? ""
367
- const match = /^FLOOD_WAIT_(\d+|%d)$/.exec(code)
436
+ const after = (waitS: number): string | null =>
437
+ Number.isSafeInteger(waitS) && waitS > 0
438
+ ? cloudRetryAt(holdUntil(now, waitS), now)
439
+ : null
440
+ if (code === "PEER_FLOOD") return after(PEER_FLOOD_WAIT_S)
441
+ if (code === HOLD_STATE_UNAVAILABLE)
442
+ return cloudRetryAt(now + HOLD_STATE_UNAVAILABLE_RETRY_MS, now)
443
+ const hold = /^TG_SAI_HOLD_(\d+)$/.exec(code)
444
+ if (hold) {
445
+ if (Number.isSafeInteger(e.untilMs) && e.untilMs! > now)
446
+ return cloudRetryAt(e.untilMs!, now)
447
+ const seconds = Number(hold[1])
448
+ return Number.isSafeInteger(seconds) && seconds > 0
449
+ ? cloudRetryAt(now + seconds * 1000, now)
450
+ : null
451
+ }
452
+ const match = /^FLOOD(?:_PREMIUM)?_WAIT_(\d+|%d)$/.exec(code)
368
453
  const seconds = match ? Number(match[1] === "%d" ? e.seconds : match[1]) : NaN
369
- return Number.isSafeInteger(seconds) && seconds > 0 && seconds <= 31_536_000
370
- ? new Date(now + seconds * 1000).toISOString()
371
- : null
454
+ return after(seconds)
372
455
  }
373
456
 
374
457
  /** The cloud is authoritative. The journal only recovers a result not yet acknowledged by cloud. */
@@ -517,8 +600,10 @@ export async function provisionSetup(params: {
517
600
  ...(rejected ? { creationRejected: true } : {}),
518
601
  retryAt: provisionRetryAt(error),
519
602
  })
603
+ // `cause` lets the CLI map a hold refusal to exit 75.
520
604
  throw new Error(
521
605
  "Group creation failed; inspect authoritative setup state before resuming",
606
+ { cause: error },
522
607
  )
523
608
  }
524
609
  // Persist immediately, before another network call or cloud acknowledgement.
@@ -539,6 +624,8 @@ export async function provisionSetup(params: {
539
624
  throw new Error("Chat marker or custody owner verification failed")
540
625
  step = "save_configuring"
541
626
  await save({ state: "configuring", chatId, binding })
627
+ // One membership read per user, then one batched add for everyone absent.
628
+ const absent: number[] = []
542
629
  for (const userId of [...binding.participants, PROVISIONING_BOT_ID]) {
543
630
  step = "read_member"
544
631
  const member = await telegram.member(chatId, userId)
@@ -548,48 +635,91 @@ export async function provisionSetup(params: {
548
635
  )
549
636
  continue
550
637
  }
638
+ absent.push(userId)
639
+ }
640
+ // Per-user refusals (privacy, USER_*/CHAT_* 400s) never stop the other
641
+ // users: a refused batch falls back to one add per user. Flood and hold
642
+ // errors refuse the whole batch and propagate with their retry time.
643
+ const failures = new Map<number, { error: unknown; step: ProvisionStep }>()
644
+ const addEach = async (userIds: number[]): Promise<void> => {
645
+ for (const userId of userIds) {
646
+ try {
647
+ step = "add_member"
648
+ await telegram.add(chatId, userId)
649
+ } catch (error) {
650
+ if (!isPerUserAddError(error)) throw error
651
+ failures.set(userId, { error, step: "add_member" })
652
+ }
653
+ }
654
+ }
655
+ if (absent.length && telegram.addMany) {
656
+ step = "add_member"
551
657
  try {
552
- step = "add_member"
553
- await telegram.add(chatId, userId)
554
- step = "verify_added_member"
555
- if ((await telegram.member(chatId, userId)).role === "absent")
556
- throw new Error("Participant invitation incomplete")
658
+ const missing = new Set(await telegram.addMany(chatId, absent))
659
+ for (const userId of absent)
660
+ if (missing.has(userId))
661
+ failures.set(userId, {
662
+ error: { text: "USER_PRIVACY_RESTRICTED" },
663
+ step: "add_member",
664
+ })
557
665
  } catch (error) {
666
+ if (!isPerUserAddError(error)) throw error
667
+ await addEach(absent)
668
+ }
669
+ } else await addEach(absent)
670
+ for (const userId of absent) {
671
+ if (failures.has(userId)) continue
672
+ step = "verify_added_member"
673
+ if ((await telegram.member(chatId, userId)).role === "absent")
674
+ failures.set(userId, {
675
+ error: new Error("Participant invitation incomplete"),
676
+ step: "verify_added_member",
677
+ })
678
+ }
679
+ let fatal: { error: unknown; step: ProvisionStep } | undefined
680
+ for (const userId of absent) {
681
+ const failure = failures.get(userId)
682
+ if (!failure) continue
683
+ if (
684
+ !binding.optionalParticipants?.includes(userId) ||
685
+ !isPrivacyRestriction(failure.error) ||
686
+ !telegram.inviteLink
687
+ ) {
688
+ fatal ??= failure
689
+ continue
690
+ }
691
+ let invite = pendingInvitations.find(
692
+ (i) =>
693
+ i.userId === String(userId) && Date.parse(i.expiresAt) > Date.now(),
694
+ )
695
+ if (!invite) {
696
+ step = "create_invitation"
697
+ const link = await telegram.inviteLink(chatId, userId)
558
698
  if (
559
- !binding.optionalParticipants?.includes(userId) ||
560
- !isPrivacyRestriction(error) ||
561
- !telegram.inviteLink
562
- )
563
- throw error
564
- let invite = pendingInvitations.find(
565
- (i) =>
566
- i.userId === String(userId) && Date.parse(i.expiresAt) > Date.now(),
699
+ !/^https:\/\/t\.me\/(?:\+|joinchat\/)[A-Za-z0-9_-]+$/.test(
700
+ link.inviteLink,
701
+ ) ||
702
+ !Number.isFinite(Date.parse(link.expiresAt)) ||
703
+ Date.parse(link.expiresAt) <= Date.now()
567
704
  )
568
- if (!invite) {
569
- step = "create_invitation"
570
- const link = await telegram.inviteLink(chatId, userId)
571
- if (
572
- !/^https:\/\/t\.me\/(?:\+|joinchat\/)[A-Za-z0-9_-]+$/.test(
573
- link.inviteLink,
574
- ) ||
575
- !Number.isFinite(Date.parse(link.expiresAt)) ||
576
- Date.parse(link.expiresAt) <= Date.now()
577
- )
578
- throw new Error("Invalid controlled invitation link")
579
- invite = {
580
- userId: String(userId),
581
- ...link,
582
- reason: "privacy_restricted",
583
- }
584
- pendingInvitations = [
585
- ...pendingInvitations.filter((i) => i.userId !== invite!.userId),
586
- invite,
587
- ]
588
- step = "save_invitation"
589
- await save({ state: "configuring", chatId, binding })
705
+ throw new Error("Invalid controlled invitation link")
706
+ invite = {
707
+ userId: String(userId),
708
+ ...link,
709
+ reason: "privacy_restricted",
590
710
  }
711
+ pendingInvitations = [
712
+ ...pendingInvitations.filter((i) => i.userId !== invite!.userId),
713
+ invite,
714
+ ]
715
+ step = "save_invitation"
716
+ await save({ state: "configuring", chatId, binding })
591
717
  }
592
718
  }
719
+ if (fatal) {
720
+ step = fatal.step
721
+ throw fatal.error
722
+ }
593
723
  for (const userId of binding.admins) {
594
724
  step = "read_admin"
595
725
  if (
@@ -669,6 +799,7 @@ export async function provisionSetup(params: {
669
799
  })
670
800
  throw new Error(
671
801
  "Setup incomplete; inspect status and resume the same request",
802
+ { cause: error },
672
803
  )
673
804
  }
674
805
  }
@@ -14,6 +14,12 @@ import {
14
14
  FileProvisionJournal,
15
15
  withProvisionTelegram,
16
16
  } from "./provisioningRuntime"
17
+ import { activeTelemetryRun } from "./telemetry/run"
18
+
19
+ /** Telegram telemetry for this CLI run, if the entry point started one. */
20
+ function cliTelemetry() {
21
+ return activeTelemetryRun()?.client()
22
+ }
17
23
 
18
24
  function print(value: unknown): void {
19
25
  console.log(
@@ -88,6 +94,7 @@ export function addProvisionCommands(program: Command): void {
88
94
  journal: new FileProvisionJournal(),
89
95
  workerId: `${hostname()}:${process.pid}:${randomUUID()}`,
90
96
  }),
97
+ cliTelemetry(),
91
98
  ),
92
99
  )
93
100
  })
@@ -133,7 +140,7 @@ export function addProvisionCommands(program: Command): void {
133
140
  "Resolution chat does not match custody owner and request marker",
134
141
  )
135
142
  return cloud.resolve(setup.requestId, options.chat, options.reason)
136
- }),
143
+ }, cliTelemetry()),
137
144
  )
138
145
  },
139
146
  )
@@ -14,6 +14,8 @@ import { saiBot } from "./cfg"
14
14
  import { createMtcuteClient, promoteTargetAdmin } from "./mtcuteAdapter"
15
15
  import { configDir, strictProfileCredentials } from "./profiles"
16
16
  import { PROVISIONING_BOT_ID } from "./provisioning"
17
+ import { withTelemetryIdentity } from "./telemetry/middleware"
18
+ import type { ClientTelemetry } from "./telemetry/middleware"
17
19
  import type {
18
20
  JournalRecord,
19
21
  Member,
@@ -253,10 +255,18 @@ export class FileProvisionJournal implements ProvisionJournal {
253
255
  }
254
256
  }
255
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
+ */
256
263
  export async function withProvisionTelegram<T>(
257
264
  request: ProvisionRequest,
258
265
  operation: (telegram: TelegramProvisioner) => Promise<T>,
266
+ telemetry?: ClientTelemetry,
267
+ signal?: AbortSignal,
259
268
  ): Promise<T> {
269
+ signal?.throwIfAborted()
260
270
  const credentials = await strictProfileCredentials(
261
271
  request.custodyProfile,
262
272
  request.expectedUserId,
@@ -268,8 +278,19 @@ export async function withProvisionTelegram<T>(
268
278
  apiHash: credentials.apiHash,
269
279
  session: credentials.sessionString,
270
280
  storage: paths.storage,
271
- })
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 })
272
292
  try {
293
+ signal?.throwIfAborted()
273
294
  if ((await client.getMe()).id !== request.expectedUserId)
274
295
  throw new Error("Custody account identity mismatch")
275
296
  const bot = await client.getUser(saiBot.handle)
@@ -301,13 +322,16 @@ export async function withProvisionTelegram<T>(
301
322
  floodSleepThreshold: 0,
302
323
  maxRetryCount: 0,
303
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 })
304
328
  const adapter: TelegramProvisioner = {
305
329
  self: async () => (await client.getMe()).id,
306
330
  resolve: (peer) =>
307
331
  resolveProvisioningPeer((value) => client.getUser(value), peer),
308
332
  create: async (title, marker) =>
309
333
  (
310
- await createSupergroup(client, {
334
+ await createSupergroup(writeClient, {
311
335
  title,
312
336
  description: marker,
313
337
  forum: false,
@@ -315,7 +339,7 @@ export async function withProvisionTelegram<T>(
315
339
  ).id,
316
340
  member,
317
341
  add: async (chatId, userId) => {
318
- const missing = await addChatMembers(client, chatId, userId, {
342
+ const missing = await addChatMembers(writeClient, chatId, userId, {
319
343
  forwardCount: 0,
320
344
  })
321
345
  if (missing.length)
@@ -323,6 +347,12 @@ export async function withProvisionTelegram<T>(
323
347
  text: "USER_PRIVACY_RESTRICTED",
324
348
  })
325
349
  },
350
+ addMany: async (chatId, userIds) =>
351
+ (
352
+ await addChatMembers(writeClient, chatId, userIds, {
353
+ forwardCount: 0,
354
+ })
355
+ ).map((invitee) => invitee.userId),
326
356
  inviteLink: async (chatId) => {
327
357
  const expires = new Date(Date.now() + 24 * 60 * 60 * 1000)
328
358
  const link = await createInviteLink(client, chatId, {
@@ -351,8 +381,13 @@ export async function withProvisionTelegram<T>(
351
381
  primaryInvite: (abortSignal) =>
352
382
  getPrimaryInviteLink(linkClient(abortSignal), chatId),
353
383
  }),
384
+ // Promotion keeps mtcute's flood sleep, as before.
354
385
  promote: async (chatId, userId, rights) =>
355
- promoteTargetAdmin(client, { chatId, targetPeer: userId, rights }),
386
+ promoteTargetAdmin(
387
+ client,
388
+ { chatId, targetPeer: userId, rights },
389
+ {},
390
+ ),
356
391
  verifyMarker,
357
392
  candidates: async (marker) => {
358
393
  const candidates: number[] = []
@@ -374,7 +409,9 @@ export async function withProvisionTelegram<T>(
374
409
  }
375
410
  return await operation(adapter)
376
411
  } finally {
377
- await client.disconnect()
412
+ signal?.removeEventListener("abort", destroy)
413
+ if (destroying) await destroying
414
+ else await client.disconnect()
378
415
  }
379
416
  })
380
417
  }
package/runtimeHealth.ts CHANGED
@@ -7,6 +7,8 @@ import { tmpdir } from "node:os"
7
7
  import { join } from "node:path"
8
8
  import { configDir, strictProfileCredentials } from "./profiles"
9
9
  import { accountPaths, withAccountLock } from "./provisioningRuntime"
10
+ import { withTelemetryIdentity } from "./telemetry/middleware"
11
+ import type { ClientTelemetry } from "./telemetry/middleware"
10
12
 
11
13
  export const HEALTH_CUSTODY_USER_ID = 8274304175
12
14
  export interface RuntimeHealthCheck {
@@ -24,6 +26,8 @@ export interface RuntimeHealthOptions {
24
26
  online?: boolean
25
27
  custodyProfile?: string
26
28
  timeoutMs?: number
29
+ /** Records the online getMe; identity is filled in for the custody user. */
30
+ telemetry?: ClientTelemetry
27
31
  }
28
32
 
29
33
  async function bounded<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
@@ -104,7 +108,10 @@ export async function checkTelegramRuntimeHealth(
104
108
  const paths = accountPaths(configDir(), HEALTH_CUSTODY_USER_ID)
105
109
  await withAccountLock(paths.lock, async () => {
106
110
  const client = await createMtcuteClient({ apiId: credentials.apiId,
107
- apiHash: credentials.apiHash, session: credentials.sessionString, storage: paths.storage })
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 }))
108
115
  try {
109
116
  const me = await bounded(client.getMe(), timeoutMs)
110
117
  if (me.id !== HEALTH_CUSTODY_USER_ID || me.isBot)
@@ -1,5 +1,6 @@
1
1
  import type { Command } from "commander"
2
2
  import { checkTelegramRuntimeHealth } from "./runtimeHealth"
3
+ import { activeTelemetryRun } from "./telemetry/run"
3
4
 
4
5
  export function addRuntimeHealthCommands(program: Command, legacyLocal?: () => Promise<void>): void {
5
6
  const health = program.command("health")
@@ -33,7 +34,8 @@ Online mode checks the custody account only and refuses personal-profile fallbac
33
34
  if (options.custodyProfile && !options.online)
34
35
  throw new Error("--custody-profile requires explicit --online")
35
36
  const result = await checkTelegramRuntimeHealth({ online: options.online,
36
- custodyProfile: options.custodyProfile, timeoutMs: Number(options.timeoutMs) })
37
+ custodyProfile: options.custodyProfile, timeoutMs: Number(options.timeoutMs),
38
+ telemetry: activeTelemetryRun()?.client() })
37
39
  if (options.json) console.log(JSON.stringify(result))
38
40
  else {
39
41
  console.log(`mode: ${result.mode}`)