import { Client, parseGroupMessageId, type Config as NativeIcqqClientConfig, type FileElem, type PttElem, type Sendable, type ShareElem, type VideoElem, } from '@icqqjs/icqq'; import { inspect } from 'node:util'; import { AsyncLocalStorage } from 'node:async_hooks'; import { createEndpointSpecification, endpointSpec, type Endpoint, type EndpointSpecification, type EndpointControl, type EndpointManagement, type EndpointPendingRequest, type EndpointSendRequest, type EndpointTransportState, type AdapterOutageNotifier, createEndpointOperation, type EndpointManagementRequest, type EndpointGroupRequest, type EndpointApproveRequest, type EndpointRejectRequest, type EndpointMemberRequest, type EndpointMuteRequest, type EndpointAdminRequest, type EndpointUserRequest, type EndpointGroupNoticeRequest, } from 'zhin.js/adapter'; import type { EndpointContentPort } from '@zhin.js/adapter'; import { receiveOneBotLikeSideEvent } from '@zhin.js/adapter-onebot-events'; import { buildSystem, toCanonicalSegments, type LoginAssist, type LoginAssistEndpointIdentity, type LoginFlowSnapshot, type PendingLoginTask, type OutboundMediaFetcher } from '@zhin.js/core'; import { EndpointDeliveryError, type EndpointSendPart, type EndpointSendResult, type MessageRef } from '@zhin.js/im-contract'; import { formatCompact, getAdapterLogger, truncatePreview } from '@zhin.js/logger'; import type { CapabilityId } from 'zhin.js'; import type { IcqqLoginControl } from './icqq-login-control.js'; import { IcqqLoginDriver, icqqLinkHost, type IcqqChallengeKind } from './icqq-login-assist.js'; import { messages as t } from './i18n.js'; import { bridgeIcqqSdkLogger } from './sdk-logger.js'; import { sanitizeIcqqLoginMessage } from './icqq-login-errors.js'; import { IcqqContentResolver } from './content-resolver.js'; import { InboundMessageDeduper, findIcqqNestedMessageSource, isIcqqBotMentioned, isIcqqMessagePostType, normalizeIcqqInboundMessage, messageLookupFromIcqqSource, resolveIcqqQuoteIdFromEvent, resolveIcqqInboundMedia, resolveIcqqSelfUserId, shouldSkipSelfInboundMessage, type IcqqMessageEvent, } from './icqq-inbound.js'; import { icqqNoticeDedupeKey, isIcqqNoticePayload, isIcqqRequestPayload, } from './icqq-inbox.js'; import { IcqqGuildCatalog, normalizeIcqqGuildInboundMessage, } from './icqq-guild.js'; import { fetchIcqqRemoteMedia, prepareIcqqOutboundMedia, resolveIcqqOutboundMediaMode, } from './outbound-media.js'; import { formatInboundContent, formatOutboundMessageParts, normalizeIcqqImageMedia, icqqInboundConversation, icqqOutboundTarget, type IcqqInboundMessage, type ResolvedIcqqConfig, } from './protocol.js'; import type { SystemMessage as IcqqSystemMessage } from './types.js'; import { ManagedIcqqClient, type IcqqBackgroundOperation } from './managed-client.js'; import { createIcqqActionPorts } from './group-actions.js'; import { inspectGroupMember, moderateGroupMember } from './group-moderation.js'; import { inspectGroupMemberProfile, inspectGroupScene, inspectSelfStanding } from './group-scene.js'; import { createIcqqSelfProfile } from './self-profile.js'; export interface IcqqEndpointOptions { readonly id: CapabilityId; readonly config: ResolvedIcqqConfig; readonly signal?: AbortSignal; readonly endpointIdentity?: LoginAssistEndpointIdentity; readonly loginAssist: LoginAssist; readonly locale?: import('zhin.js/i18n').Locale; /** Out-of-band outage notifier; absent in tests/hosts without outbound. */ readonly notifier?: AdapterOutageNotifier; /** Downloads outbound media URLs on this host; defaults to core `fetchOutboundMedia` (tests inject one). */ readonly fetchMedia?: OutboundMediaFetcher; } const BOUND_EVENTS = [ 'message.private', 'message.group', 'message.guild', 'request.friend', 'request.group', 'notice.friend', 'notice.group', 'system.online', 'system.offline', 'system.offline.network', 'system.offline.kickoff', 'system.login.qrcode', 'system.login.device', 'system.login.slider', 'system.login.error', 'system.login.auth', ] as const; /** * Log level of an ICQQ `system.*` event by meaning: coming online and login challenges waiting for * the person (QR code, device lock, slider, identity check) are normal progress (`info`); only * failures (login errors, going offline) are `warn`, so a routine login stays out of the warnings. */ export function icqqSystemEventLogLevel(type: string): 'info' | 'warn' { return type === 'online' || type.startsWith('login.') && type !== 'login.error' ? 'info' : 'warn'; } export class IcqqEndpoint extends ManagedIcqqClient implements Endpoint { readonly [endpointSpec]: EndpointSpecification; readonly #logger: ReturnType; readonly #options: IcqqEndpointOptions; readonly endpointName: string; readonly #guildCatalog = new IcqqGuildCatalog(); readonly #inboundDeduper = new InboundMessageDeduper(); readonly #sideEventDeduper = new InboundMessageDeduper(); readonly #loginAssistOwner = Object.freeze({}); #open = false; #retiring = false; #started = false; #stopped = false; #everOnline = false; #retirementEpoch = 0; #retirementArmed = false; #disposeNativeEvents?: () => void; #disposeQrcodeError?: () => void; #resolveStartOnline?: () => void; #heldInbound: IcqqInboundMessage[] = []; readonly #inflightInbound = new Set>(); readonly #inboundOwner = new AsyncLocalStorage(); readonly #contentResolver: IcqqContentResolver; readonly #content: EndpointContentPort; readonly loginControl: IcqqLoginControl; #reloginTimer?: ReturnType; #reloginAttempts = 0; /** Error code of the failure the automatic relogin is retrying (reported when it gives up). */ #lastAutoFailure: 'network' | 'unknown' = 'network'; #reloginInFlight?: Promise; /** * Login flow of this Endpoint instance (ADR 0058). While a person answers a challenge no * automatic relogin runs: a relogin starts a new SDK login, which issues a new challenge and * voids the URL / ticket the operator is working on. */ readonly #login: IcqqLoginDriver; #offlineNoticeAt = 0; #challengeNoticeAt = 0; readonly #management: EndpointManagement = Object.freeze({ inspectGroupMember: request => inspectGroupMember(this, request), inspectGroupScene: request => inspectGroupScene(this, request), inspectGroupMemberProfile: request => inspectGroupMemberProfile(this, request), inspectSelfStanding: request => inspectSelfStanding(this, request), moderateGroupMember: request => moderateGroupMember({ client: this, isActive: () => this.#open && !this.#retiring && !this.#stopped }, request), listFriends: async (request: EndpointManagementRequest = {}) => createEndpointOperation(request).run(() => Array.from(this.fl.values()).map((f) => ({ user_id: f.user_id, nickname: f.nickname, remark: f.remark ?? '', }))), listGroups: async (request: EndpointManagementRequest = {}) => createEndpointOperation(request).run(() => Array.from(this.gl.values()).map((g) => ({ group_id: g.group_id, name: g.group_name, }))), listChannels: async (request: EndpointManagementRequest = {}) => { const operation = createEndpointOperation(request); await operation.run(() => this.#guildCatalog.syncAll(this)); return operation.run(() => this.#guildCatalog.getGuildChannelList()); }, listGroupMembers: async ({ groupId, signal }: EndpointGroupRequest) => Array.from((await createEndpointOperation({ signal }).run(() => this.getGroupMemberList(Number(groupId)))).values()), listRequests: (request: EndpointManagementRequest = {}) => createEndpointOperation(request).run(() => this.#listPendingRequests()), approveRequest: request => this.#approveRequest(request), rejectRequest: request => this.#rejectRequest(request), kickGroupMember: async ({ groupId, userId, signal }: EndpointMemberRequest) => { const operation = createEndpointOperation({ signal }); await operation.run(() => this.setGroupKick(Number(groupId), Number(userId))); }, muteGroupMember: async ({ groupId, userId, durationSeconds: duration, signal }: EndpointMuteRequest) => { const operation = createEndpointOperation({ signal }); await operation.run(() => this.setGroupBan(Number(groupId), Number(userId), duration)); }, setGroupAdmin: async ({ groupId, userId, enabled, signal }: EndpointAdminRequest) => { const operation = createEndpointOperation({ signal }); await operation.run(() => this.setGroupAdmin(Number(groupId), Number(userId), enabled)); }, deleteFriend: async ({ userId, signal }: EndpointUserRequest) => { const operation = createEndpointOperation({ signal }); await operation.run(() => this.deleteFriend(Number(userId))); }, sendGroupNotice: async ({ groupId, content, signal }: EndpointGroupNoticeRequest) => { const operation = createEndpointOperation({ signal }); if (await operation.run(() => this.sendGroupNotice(Number(groupId), content)) === false) { throw new Error('QQ did not confirm the group notice'); } }, ...createIcqqActionPorts(() => this), }); readonly #control: EndpointControl = Object.freeze({ recall: async ({ message, signal }) => { if (!message.id || message.id.startsWith('outbound:')) return; if (!await createEndpointOperation({ signal }).run(() => this.deleteMsg(message.id))) throw new Error('QQ did not confirm message recall'); }, addReaction: async ({ message, emoji, signal }) => { const target = resolveIcqqGroupReactionTarget(message); if (!target) return null; try { // Do not await protocol ACK — packet timeout must not stall the AI reply. await createEndpointOperation({ signal }).run(() => { this.#ignoreReactionAck('add', this.pickGroup(target.groupId).setReaction(target.seq, emoji)); }); } catch (error) { if (error instanceof EndpointDeliveryError && error.code === 'endpoint_inactive') throw error; this.#logger.debug(formatCompact({ op: 'reaction_add_failed', error: error instanceof Error ? error.message : String(error), })); } return emoji; }, removeReaction: async ({ message, reactionId, signal }) => { const target = resolveIcqqGroupReactionTarget(message); if (!target) return; try { await createEndpointOperation({ signal }).run(() => { this.#ignoreReactionAck('remove', this.pickGroup(target.groupId).delReaction(target.seq, reactionId)); }); } catch (error) { if (error instanceof EndpointDeliveryError && error.code === 'endpoint_inactive') throw error; this.#logger.debug(formatCompact({ op: 'reaction_remove_failed', error: error instanceof Error ? error.message : String(error), })); } }, }); constructor(options: IcqqEndpointOptions) { super(Number(options.config.id), resolveNativeClientConfig(options.config), (operation, error) => this.#handleBackgroundFailure(operation, error)); const name = () => this.endpointName; const state = () => this.#transportState; const content = () => this.#content; this[endpointSpec] = createEndpointSpecification(this, { start: signal => this.#startFramework(signal), open: () => this.#openFramework(), close: () => this.#closeFramework(), stop: () => this.#stopFramework(), send: request => this.#sendFramework(request), get name() { return name(); }, get transportState() { return state(); }, management: this.#management, control: this.#control, profile: createIcqqSelfProfile(this), get content() { return content(); }, login: { // The lease signal aborts on stop / retirement: never let a slow SDK call block it. relogin: async ({ signal }) => { await (signal ? raceAbort(this.relogin(), signal) : this.relogin()); }, refreshChallenge: async ({ signal }) => { await (signal ? raceAbort(this.refreshLoginChallenge(), signal) : this.refreshLoginChallenge()); }, }, }); this.#logger = getAdapterLogger('icqq', options.config.id); // The SDK's own log4js output is replaced by a bridge into this Zhin logger (#1250): one format, // no ANSI off a terminal, `logLevel` (default warn), chat text only at debug and escaped onto one // line, verification links (sid / sig) and phone numbers redacted. if (this.logger) this.logger = bridgeIcqqSdkLogger(this.#logger, options.config.logLevel) as unknown as typeof this.logger; this.#contentResolver = new IcqqContentResolver(this); this.#content = this.#contentResolver.port; this.#options = options; this.endpointName = options.config.id; this.#login = new IcqqLoginDriver({ assist: options.loginAssist, client: this, endpointKey: this.endpointName, owner: this.#loginAssistOwner, ...(options.signal ? { signal: options.signal } : {}), ...(options.endpointIdentity ? { endpointIdentity: options.endpointIdentity } : {}), logger: this.#logger, ...(options.locale ? { locale: options.locale } : {}), }); this.loginControl = Object.freeze({ endpointId: this.endpointName, state: () => ({ endpointId: this.endpointName, transportState: this.#transportState, online: this.isOnline(), pending: this.#pendingLoginTasks(), }), pending: () => this.#pendingLoginTasks(), flow: () => this.#loginFlow(), relogin: async () => { this.#options.signal?.throwIfAborted(); await this.relogin(); }, submit: (taskId: string, value: string | Record) => !this.#options.signal?.aborted && this.#options.loginAssist.submit(taskId, value, this.#options.endpointIdentity), cancel: (taskId: string, reason?: string) => !this.#options.signal?.aborted && this.#options.loginAssist.cancel(taskId, reason, this.#options.endpointIdentity), }); } #handleBackgroundFailure(operation: IcqqBackgroundOperation, error: unknown): void { if (!this.#started || this.#stopped || this.#retiring) return; this.#logger.warn(formatCompact({ op: `icqq_${operation}_failed`, endpoint: this.endpointName, error: error instanceof Error ? error.message : error && typeof error === 'object' && 'message' in error && typeof error.message === 'string' ? error.message : typeof error === 'string' ? error : 'Unknown ICQQ SDK background failure', ...(error && typeof error === 'object' && 'code' in error && typeof error.code === 'number' ? { code: error.code } : {}), })); if (operation === 'sso-heartbeat' && !this.isOnline()) return; if (operation === 'login' && !this.#everOnline) return; // Delegate to the SDK's existing transport termination, offline event and // reconn_interval policy. No account-level logout or second retry timer. this.emit('internal.error.network', -2, `ICQQ ${operation} failed`); } /** Force a login attempt (Console「重新登录」, recovery command): a new login flow. */ relogin(): Promise { return this.#startRelogin(true); } /** * Console「刷新二维码」: a new QR code in place while a QR challenge is shown; any other * challenge cannot be refreshed alone, so this logs in again. */ async refreshLoginChallenge(): Promise { if (this.#stopped || this.#retiring || this.#options.signal?.aborted) throw new Error('ICQQ endpoint 已停止'); if (await this.#login.refresh()) return; await this.relogin(); } #startRelogin(resetAttempts: boolean): Promise { if (this.#stopped || this.#retiring) { return Promise.reject(new Error('ICQQ endpoint 已停止')); } if (this.#reloginInFlight) return this.#reloginInFlight; if (resetAttempts) this.#reloginAttempts = 0; const task = this.#performRelogin(resetAttempts); this.#reloginInFlight = task; void task.catch(() => undefined).finally(() => { if (this.#reloginInFlight === task) this.#reloginInFlight = undefined; if (this.#started && !this.#stopped && !this.#retiring && !this.isOnline()) { this.#scheduleRelogin('relogin_failed'); } }); return task; } async #performRelogin(manual: boolean): Promise { this.#clearReloginTimer(); this.cancelReconnect(); this.#logger.info(formatCompact({ op: 'icqq_relogin', endpoint: this.endpointName, manual })); // A requested relogin is a new attempt; an automatic retry continues the current timeline. if (manual) this.#login.begin(t(this.#options.locale, 'loginReconnecting')); else this.#login.connect(t(this.#options.locale, 'loginReconnecting')); try { await this.login(this.#options.config.password); } catch (error) { this.#logger.warn(formatCompact({ op: 'icqq_relogin_failed', endpoint: this.endpointName, error: error instanceof Error ? error.message : String(error), })); throw error; } } /** * Automatic backoff relogin, only for failures that need no verification (network drop, kicked, * a plain login that did not finish). Never while a person answers a challenge (ADR 0058 §6). */ #scheduleRelogin(reason: 'kickoff' | 'login_network' | 'login_failed' | 'relogin_failed'): void { if (!this.#options.config.autoReconnect || this.#stopped || this.#retiring) return; if (this.#login.busy) return; // A failed verification or an expired challenge waits for the person (next: relogin / refresh). if (reason === 'relogin_failed' && this.#login.awaitingPerson) return; if (this.#reloginTimer || this.#reloginInFlight) return; if (this.#reloginAttempts >= ICQQ_RELOGIN_ATTEMPTS) { // Exhausted: the attempt ends and waits for the person. if (!this.#login.awaitingPerson) { const message = t(this.#options.locale, 'loginRetryExhausted', { attempts: ICQQ_RELOGIN_ATTEMPTS }); this.#login.fail(this.#lastAutoFailure, message, 'relogin'); this.#notifyOffline('relogin_exhausted', false, true); } return; } const attempt = this.#reloginAttempts++; const delayMs = Math.min(300_000, 5_000 * (2 ** Math.min(attempt, 5))); const locale = this.#options.locale; this.#login.info(t(locale, 'loginRetryScheduled', { reason: t(locale, reason === 'kickoff' ? 'loginReasonKickoff' : reason === 'login_network' ? 'loginReasonNetwork' : 'loginReasonFailed'), seconds: Math.round(delayMs / 1000), attempt: attempt + 1, })); this.#logger.info(formatCompact({ op: 'icqq_relogin_scheduled', endpoint: this.endpointName, reason, attempt: attempt + 1, delay_ms: delayMs, })); this.#reloginTimer = setTimeout(() => { this.#reloginTimer = undefined; void this.#startRelogin(false).catch(() => { // #performRelogin already scheduled the next attempt. }); }, delayMs); this.#reloginTimer.unref?.(); } #clearReloginTimer(): void { if (!this.#reloginTimer) return; clearTimeout(this.#reloginTimer); this.#reloginTimer = undefined; } /** This incarnation's latest login flow (snapshot, including the active challenge's material). */ #loginFlow(): LoginFlowSnapshot | undefined { if (this.#options.signal?.aborted) return undefined; const flow = this.#options.loginAssist.getFlow('icqq', this.endpointName); const identity = this.#options.endpointIdentity; if (!flow || !identity) return flow; const own = flow.endpointIdentity; return own && own.canonicalId === identity.canonicalId && own.instanceId === identity.instanceId && own.epoch === identity.epoch && own.incarnationId === identity.incarnationId ? flow : undefined; } #pendingLoginTasks(): readonly PendingLoginTask[] { if (this.#options.signal?.aborted) return []; return this.#options.loginAssist.listPending() .filter((task) => task.adapter === 'icqq' && (this.#options.endpointIdentity ? task.endpointIdentity?.canonicalId === this.#options.endpointIdentity.canonicalId && task.endpointIdentity.instanceId === this.#options.endpointIdentity.instanceId && task.endpointIdentity.epoch === this.#options.endpointIdentity.epoch && task.endpointIdentity.incarnationId === this.#options.endpointIdentity.incarnationId : task.endpointKey === this.endpointName)); } #notifyOffline(reason: string, willRetry: boolean, force = false): void { const notifier = this.#options.notifier; if (!notifier?.configured) return; const now = Date.now(); if (!force && now - this.#offlineNoticeAt < 60_000) return; this.#offlineNoticeAt = now; const recovery = willRetry ? '已开始自动重新登录。' : '请手动重新登录。'; const qrCommand = `icqq login qr ${this.endpointName}`; const confirmCommand = `icqq login confirm ${this.endpointName}`; const codeCommand = `icqq login code ${this.endpointName} <内容>`; const text = `[Zhin] ICQQ ${this.endpointName} 掉线(${reason})。${recovery}\n` + `恢复:在 QQ 回复 \`${qrCommand}\` 获取二维码,扫码后回复 \`${confirmCommand}\`;` + `滑块/短信验证请回复 \`${codeCommand}\`。也可以打开 Console 的 ICQQ 页面完成登录。`; void notifier.send(text).then((sent) => { if (sent) return; this.#logger.warn(formatCompact({ op: 'icqq_notify_failed', endpoint: this.endpointName, reason, })); }); } #notifyChallenge(step: IcqqChallengeKind): void { const notifier = this.#options.notifier; if (!notifier?.configured) return; const now = Date.now(); if (now - this.#challengeNoticeAt < 30_000) return; this.#challengeNoticeAt = now; const id = this.endpointName; const label = step === 'qrcode' ? '扫码登录' : step === 'slider' ? '滑块验证' : step === 'device' ? '设备锁验证' : step === 'sms' ? '短信验证码' : '身份验证'; const next = step === 'qrcode' ? `在 QQ 回复 \`icqq login qr ${id}\` 获取二维码,用手机 QQ 扫码并在手机上确认,登录会自动继续;没有继续时回复 \`icqq login confirm ${id}\`。` : step === 'slider' ? `打开 Console 的 ICQQ 页面,用验证码辅助页完成滑块即可;也可以回复 \`icqq login status ${id}\` 查看滑块链接,再用 \`icqq login code ${id} \` 提交。` : step === 'device' ? `回复 \`icqq login status ${id}\` 查看验证链接,用手机完成验证后回复 \`icqq login confirm ${id}\`;改用短信验证码请回复 \`icqq login code ${id} sms\`。` : step === 'sms' ? `收到短信后回复 \`icqq login code ${id} <6 位验证码>\`。` : `需要复制设备信息到验证页,请打开 Console 的 ICQQ 页面按步骤完成;完成后点「已完成,继续登录」或回复 \`icqq login confirm ${id}\`。`; void notifier.send(`[Zhin] ICQQ ${id} 需要${label}。\n${next}`).then((sent) => { if (sent) return; this.#logger.warn(formatCompact({ op: 'icqq_notify_failed', endpoint: this.endpointName, reason: `login_${step}`, })); }); } #notifyRecovered(): void { const notifier = this.#options.notifier; const hadOfflineNotice = this.#offlineNoticeAt > 0; this.#offlineNoticeAt = 0; this.#challengeNoticeAt = 0; if (!notifier?.configured || !hadOfflineNotice) return; void notifier.send(`[Zhin] ICQQ ${this.endpointName} 已重新上线。`).then((sent) => { if (sent) return; this.#logger.warn(formatCompact({ op: 'icqq_notify_failed', endpoint: this.endpointName, reason: 'recovered' })); }); } #ignoreReactionAck(action: 'add' | 'remove', task: Promise | unknown): void { void Promise.resolve(task).catch((error) => { this.#logger.debug(formatCompact({ op: `reaction_${action}_failed`, error: error instanceof Error ? error.message : String(error), })); }); } get #transportState(): EndpointTransportState { if (this.#stopped || this.#retiring) return 'stopped'; if (!this.#started) return 'idle'; if (this.isOnline()) return 'open'; if (!this.#everOnline) return 'connecting'; return this.#options.config.autoReconnect ? 'reconnecting' : 'closed'; } async #startFramework(signal: AbortSignal): Promise { if (this.#started) return; signal.throwIfAborted(); this.#stopped = false; // Invalidate a guard left by a prior lifecycle epoch before admitting a // new login attempt on this endpoint instance. this.#retirementEpoch += 1; this.#retirementArmed = false; this.#retiring = false; this.off('system.online'); this.#started = true; let resolveOnline!: () => void; const onlineReady = new Promise((resolve) => { resolveOnline = resolve; }); const onAbort = () => resolveOnline(); this.#resolveStartOnline = resolveOnline; signal.addEventListener('abort', onAbort, { once: true }); try { this.#bindClientEvents(); this.#login.begin(); await raceAbort(Promise.resolve(this.login(this.#options.config.password)), signal); await onlineReady; signal.throwIfAborted(); await this.#pullPendingSystemMessages(signal); signal.throwIfAborted(); this.#logger.info( `connected (direct) | friends: ${this.fl.size} | groups: ${this.gl.size}`, ); } catch (error) { this.#notifyOffline('start_failed', false); await this.#stopFramework(); this.#logger.debug(`Failed to connect ICQQ client: ${error instanceof Error ? error.stack ?? error.message : String(error)}`); throw error; } finally { signal.removeEventListener('abort', onAbort); if (this.#resolveStartOnline === resolveOnline) this.#resolveStartOnline = undefined; } } #openFramework(): void { if (this.#retirementArmed) { this.#retirementEpoch += 1; this.#retirementArmed = false; this.off('system.online'); this.#bindSystemOnlineEvent(); } this.#retiring = false; this.#open = true; const held = this.#heldInbound.splice(0); for (const msg of held) { void this.admit(msg).catch((error) => { this.#logInboundHandlerFailure('held', error); }); } } async #closeFramework(): Promise { this.#assertExternalLifecycle('close'); this.#armRetirementFence(); await Promise.allSettled([...this.#inflightInbound]); } async #stopFramework(): Promise { this.#assertExternalLifecycle('stop'); this.#stopped = true; this.#clearReloginTimer(); this.#login.invalidate(); this.#armRetirementFence(); await Promise.allSettled([...this.#inflightInbound]); this.#resolveStartOnline?.(); this.#options.loginAssist.cancelOwned(this.#loginAssistOwner, 'endpoint_stopped'); this.#heldInbound.length = 0; this.#disposeNativeEvents?.(); this.#disposeNativeEvents = undefined; this.#disposeQrcodeError?.(); this.#disposeQrcodeError = undefined; for (const event of BOUND_EVENTS) { // The retirement guard owns this matcher until a late login handshake // has finished. start()/open() replace it with the normal listener. if (event !== 'system.online') this.off(event); } // `Client.logout()` sends an account-level unregister packet before it // closes this transport. During config HMR the replacement endpoint for // the same UIN is already online, so unregistering the retiring generation // also closes the replacement session. Endpoint ownership is transport // scoped: retire only this Client's TCP connection. try { this.terminate(); } catch { /* ignore */ } this.#inboundDeduper.clear(); this.#sideEventDeduper.clear(); this.#guildCatalog.clear(); this.#started = false; this.#logger.debug(formatCompact({ op: 'disconnect' })); } #armRetirementFence(): void { this.#retiring = true; this.#open = false; if (this.#retirementArmed) return; this.#retirementArmed = true; const retirementEpoch = ++this.#retirementEpoch; // ICQQ owns reconnect through this per-Client timer. Clear it before any // asynchronous drain so a queued callback cannot enter while close waits. this.cancelReconnect(); // A login callback may already be inside the SDK handshake, which has no // abort API. Replace the normal online listener with an epoch-owned guard // before draining inbound work. Transport termination is account-local; // logout would also unregister an HMR replacement using the same UIN. this.off('system.online'); this.on('system.online', () => { if (this.#retirementEpoch !== retirementEpoch || !this.#retiring) return; try { this.terminate(); } catch { /* already closed */ } }); } async #sendFramework({ conversation, payload, signal }: EndpointSendRequest): Promise { if (!this.#started) throw new EndpointDeliveryError('endpoint_disconnected', 'icqq endpoint 未连接', 'not_sent'); const operation = createEndpointOperation({ signal }); const mediaMode = resolveIcqqOutboundMediaMode(this.#options.config); const prepared = await operation.prepare(async () => isIcqqSegmentPayload(payload) ? prepareIcqqOutboundMedia(normalizeIcqqImageMedia(await fetchIcqqRemoteMedia(payload, { ...(signal ? { signal } : {}), ...(this.#options.fetchMedia ? { fetchMedia: this.#options.fetchMedia } : {}), })), mediaMode) : { content: payload, dispose() {} }); // Cancellation ends our wait, not the SDK's use of temporary media. The actual native // promises own that resource until they settle, including a late rejection after cancellation. const pendingSends = new Set>(); const sendNative = (target: ReturnType, message: Sendable) => { const task = this.#sendNative(target, message); pendingSends.add(task); const settled = () => { pendingSends.delete(task); }; void task.then(settled, settled); return task; }; try { // Standalone elements (share / file / …) are split into ordered messages. const messages = formatOutboundMessageParts(prepared.content); const parsed = icqqOutboundTarget(conversation); const parts: EndpointSendPart[] = []; for (const [index, { message, sourceIndices }] of messages.entries()) { const preview = formatIcqqSendablePreview(message); let result: { message_id?: unknown }; try { result = await operation.run(() => sendNative(parsed, message)); } catch (error) { this.#logger.warn(formatCompact({ op: 'icqq_send_failed', target: `${conversation.kind}:${conversation.id}`, part: messages.length > 1 ? `${index + 1}/${messages.length}` : undefined, error: describeUnknownError(error), preview: truncatePreview(preview, 120), })); if (index === 0) throw error; // Earlier sends completed; retrying can duplicate accepted messages, even without ids. throw new EndpointDeliveryError('partial_delivery', `ICQQ completed ${index} of ${messages.length} message sends`, 'unknown', { cause: error, parts }); } const rawId = result?.message_id; const id = (typeof rawId === 'string' || (typeof rawId === 'number' && Number.isFinite(rawId))) && String(rawId).trim() !== '' ? String(rawId) : undefined; parts.push({ ...(id ? { messageId: id } : {}), ...(sourceIndices ? { sourceIndices } : {}) }); this.#logger.info( `send ${conversation.kind}:${conversation.id} | id: ${id ?? '-'} | ${truncatePreview(preview, 80)}`, ); } // A resolved share/file call has no message identity; retain that unknown slot in the batch. if (!parts.some(part => part.messageId)) { throw new EndpointDeliveryError('delivery_unconfirmed', 'Message delivery is unconfirmed: ICQQ returned no message_id', 'unknown', { parts }); } return { parts }; } finally { const disposeMedia = () => { try { prepared.dispose(); } catch (error) { // Temporary-file cleanup cannot change an observed send result. this.#logger.warn(formatCompact({ op: 'icqq_media_cleanup_failed', error: describeUnknownError(error) })); } }; if (pendingSends.size) void Promise.allSettled([...pendingSends]).then(disposeMedia); else disposeMedia(); } } async #sendNative( target: ReturnType, message: Sendable, ): Promise<{ message_id?: unknown }> { if (isIcqqShareElement(message)) { switch (target.kind) { case 'private': { const friend = this.pickFriend(target.userId); await friend.share(message); return {}; } case 'group': { const group = this.pickGroup(target.groupId); await group.share(message); return {}; } case 'temp': await this.pickMember(target.groupId, target.userId).share(message); return {}; case 'channel': { const channel = this.pickGuild(target.guildId).channels.get(target.channelId); if (!channel) { throw new TypeError(`ICQQ guild channel is unavailable: ${target.guildId}/${target.channelId}`); } await channel.share(message); return {}; } } } if (isIcqqFileElement(message)) { switch (target.kind) { case 'private': { await this.pickFriend(target.userId).sendFile(message.file, message.name); return {}; } case 'group': { await this.pickGroup(target.groupId).sendFile(message.file, '/', message.name); return {}; } case 'temp': case 'channel': throw new TypeError(`ICQQ ${target.kind} conversation does not support file delivery`); } } switch (target.kind) { case 'private': return this.sendPrivateMsg(target.userId, message); case 'group': return this.sendGroupMsg(target.groupId, message); case 'temp': return this.sendTempMsg(target.groupId, target.userId, message); case 'channel': return this.sendGuildMsg(target.guildId, target.channelId, message) as unknown as { message_id?: unknown }; } } admit(msg: IcqqInboundMessage): Promise { return this.#trackInbound(() => this.#deliverInbound(msg)); } #trackInbound(run: () => Promise): Promise { const owner = Symbol('icqq-inbound'); let settle!: () => void; const settlement = new Promise((resolve) => { settle = resolve; }); this.#inflightInbound.add(settlement); let operation: Promise; try { operation = this.#inboundOwner.run(owner, () => this[endpointSpec].events.run(run)); } catch (error) { this.#inflightInbound.delete(settlement); settle(); return Promise.reject(error); } return operation.finally(() => { this.#inflightInbound.delete(settlement); settle(); }); } #assertExternalLifecycle(operation: 'close' | 'stop'): void { if (!this.#inboundOwner.getStore()) return; throw new Error( `ICQQ endpoint ${operation} cannot run inside its own inbound receive; invoke it from the owning lifecycle`, ); } async #deliverInbound(msg: IcqqInboundMessage, admittedBeforeRetire = false): Promise { const conversation = msg.conversation; if (!this.#open && !admittedBeforeRetire) { if (this.#retiring) return; if (this.#heldInbound.length >= INBOUND_HOLD_LIMIT) { const dropped = this.#heldInbound.shift(); this.#logger.warn(formatCompact({ op: 'icqq_inbound_hold_drop', endpoint: this.endpointName, id: dropped?.id, target: dropped ? `${dropped.conversation.kind}:${dropped.conversation.id}` : undefined, limit: INBOUND_HOLD_LIMIT, })); } this.#heldInbound.push(msg); this.#logger.info( `hold ${conversation.kind}:${conversation.id}` + (msg.sender ? ` from ${msg.sender.name ?? msg.sender.id}` : '') + ` until open | ${truncatePreview(msg.content, 80)}`, ); return; } const mentioned = isIcqqBotMentioned({ uin: this.endpointName, content: msg.segments, rawMessage: msg.content, }); this.#logger.info( `recv ${conversation.kind}:${conversation.id}` + (msg.sender ? ` from ${msg.sender.name ?? msg.sender.id}` : '') + (mentioned ? ' (mentioned)' : '') + ` | ${truncatePreview(msg.content, 80)}`, ); await this[endpointSpec].events.emit('message.receive', { event: msg.event, platformSentAt: Number.isFinite(msg.platformSentAt) ? msg.platformSentAt : undefined, conversation, message: { conversation, id: msg.id }, content: msg.content, ...(msg.segments ? { segments: msg.segments } : {}), sender: msg.sender, endpointId: this.endpointName, ...(mentioned ? { mentioned: true } : {}), ...(msg.replyTo ? { replyTo: msg.replyTo } : {}), metadata: Object.freeze({ channelType: msg.channelType, ...(msg.metadata ?? {}), }), }).catch((err) => { this.#logger.warn(formatCompact({ op: 'recv', endpoint: this.endpointName, target: `${conversation.kind}:${conversation.id}`, ok: false, error: err instanceof Error ? err.message : String(err), })); }); } #bindClientEvents(): void { this.#bindNativeEvents(); const safe = (label: string, fn: () => void): void => { void this[endpointSpec].events.run(fn).catch(() => { this.#logger.debug(formatCompact({ op: 'icqq_event_not_admitted', endpoint: this.endpointName, event: label })); }); }; this.on('message.private', (event) => { this.#startMessageEvent('message.private', event); }); this.on('message.group', (event) => { this.#startMessageEvent('message.group', event); }); this.on('message.guild', (event) => { void this.#trackInbound(() => this.#handleGuildEvent(event)).catch((error) => { this.#logInboundHandlerFailure('message.guild', error); }); }); this.on('request.friend', (event) => safe('request.friend', () => { this.#onRequestEvent(serializeIcqqEvent(event)); })); this.on('request.group', (event) => safe('request.group', () => { this.#onRequestEvent(serializeIcqqEvent(event)); })); this.on('notice.friend', (event) => safe('notice.friend', () => { this.#onNoticeEvent(serializeIcqqEvent(event)); })); this.on('notice.group', (event) => safe('notice.group', () => { this.#onNoticeEvent(serializeIcqqEvent(event)); })); this.#bindSystemOnlineEvent(); this.on('system.offline', (event) => { this.#logSystemEvent('offline', event); this.#notifyOffline('offline', this.#options.config.autoReconnect); }); this.on('system.offline.network', (event) => { this.#logSystemEvent('offline.network', event); this.#notifyOffline('network', this.#options.config.autoReconnect); }); this.on('system.offline.kickoff', (event) => { this.#logSystemEvent('offline.kickoff', event); this.#notifyOffline('kickoff', this.#options.config.autoReconnect); this.#scheduleRelogin('kickoff'); }); this.on('system.login.qrcode', (event) => { this.#logger.info('icqq 收到二维码登录事件,等待扫码(Console / 终端 / QQ 命令)'); this.#handleLoginChallenge('qrcode', event); }); this.on('system.login.device', (event) => { this.#handleLoginChallenge('device', event); }); this.on('system.login.slider', (event) => { this.#handleLoginChallenge('slider', event); }); this.on('system.login.error', (event) => { const raw = event && typeof event === 'object' ? event as { code?: unknown; message?: unknown } : {}; this.#logSystemEvent('login.error', event, { ...(typeof raw.code === 'number' ? { code: raw.code } : {}), message: sanitizeIcqqLoginMessage(raw.message), }); if (this.#retiring || this.#stopped || this.#options.signal?.aborted) return; this.#handleLoginError(event); }); // The SDK's second scan query (inside qrcodeLogin) failed: report it instead of verifying forever. // Only our listener is removed on stop (the SDK has its own one on this internal event). this.#disposeQrcodeError?.(); const disposeQrcodeError = this.on('internal.error.qrcode', (code: unknown, message: unknown) => { if (this.#retiring || this.#stopped || this.#options.signal?.aborted) return; this.#login.qrcodeError(code, message); }); this.#disposeQrcodeError = () => { disposeQrcodeError(); }; this.on('system.login.auth', (event) => { this.#handleLoginChallenge('auth', event); }); } #bindSystemOnlineEvent(): void { this.on('system.online', (event) => { if (this.#retiring) return; this.#everOnline = true; this.#login.online(); this.#clearReloginTimer(); this.#reloginAttempts = 0; this.#notifyRecovered(); try { this.#resolveStartOnline?.(); try { // transport 重连不清除(账号不变);stop/retire 由基类撤销登记。上报失败不影响上线流程。 this[endpointSpec].reportSelfUserId(resolveIcqqSelfUserId(this)); } catch (error) { this.#logger.warn(formatCompact({ op: 'icqq_report_self_user_id_failed', endpoint: this.endpointName, error: error instanceof Error ? error.message : String(error), })); } this.#logSystemEvent('online', event); } catch (error) { this.#logger.warn(formatCompact({ op: 'icqq_event_handler', endpoint: this.endpointName, event: 'system.online', error: error instanceof Error ? error.message : String(error), })); } }); } /** Forward every public SDK event, including protocol extensions unknown to Zhin. */ #bindNativeEvents(): void { this.#disposeNativeEvents?.(); let matchedName: string | undefined; const registration = this.on( (eventName: unknown) => { matchedName = typeof eventName === 'string' && !eventName.startsWith('internal.') ? eventName : undefined; return matchedName !== undefined; }, (event: unknown) => { const name = matchedName; if (name) this.#emitNativeEvent(name, event); }, ); this.#disposeNativeEvents = () => registration(); } #emitNativeEvent(name: string, event: unknown): void { void this[endpointSpec].events.platform(name, event).catch((error) => { this.#logger.warn(formatCompact({ op: 'icqq_platform_event_failed', endpoint: this.endpointName, event: name, error: error instanceof Error ? error.message : String(error), })); }); } #handleLoginChallenge(step: Exclude, event: unknown): void { if (this.#retiring || this.#stopped || this.#options.signal?.aborted) return; const payload = serializeIcqqEvent(event) ?? (event && typeof event === 'object' ? event as Record : null); // Verification links carry a session id (sid / sig): logs get the challenge kind and host only. this.#logSystemEvent(`login.${step}`, event, loginChallengeLogLine(step, payload)); this.#clearReloginTimer(); this.#notifyChallenge(step); // The QR image is a Buffer, which serialization drops; the driver reads the raw event. const raw = event && typeof event === 'object' ? event as Record : {}; this.#login.challenge(step, { ...(payload ?? {}), ...raw }); } /** * `system.login.error` (ADR 0058 §5–6): a wrong code stays on its challenge; a verification * failure ends the attempt and waits for the person (`next`). Only a plain login that failed on * the network or for an unknown reason, without any challenge, keeps the automatic backoff. */ #handleLoginError(event: unknown): void { const { mapping, hadChallenge, retrying } = this.#login.loginError(event); this.#logger.warn(formatCompact({ op: 'icqq_login_error', endpoint: this.endpointName, code: mapping.code, ...(mapping.platformCode !== undefined ? { platform_code: mapping.platformCode } : {}), })); if (retrying) return; const autoRetry = this.#options.config.autoReconnect && (mapping.code === 'network' || (mapping.code === 'unknown' && !hadChallenge)); this.#notifyOffline('login_error', autoRetry); if (autoRetry) { this.#login.outcome({ result: 'rejected', code: mapping.code, message: mapping.message, next: 'wait' }); this.#lastAutoFailure = mapping.code === 'network' ? 'network' : 'unknown'; this.#scheduleRelogin(mapping.code === 'network' ? 'login_network' : 'login_failed'); return; } this.#clearReloginTimer(); this.#login.fail(mapping.code, mapping.message, mapping.next); } /** * `safe` replaces the payload in the log line and the `system.receive` side event (login * challenges keep only kind and host: links carry a sid, plus phone / device / QR image). */ #logSystemEvent(type: string, event: unknown, safe?: Record | null): void { const payload = safe === undefined ? serializeIcqqEvent(event) : safe; const line = payload; this.#logger[icqqSystemEventLogLevel(type)](formatCompact({ op: `system.${type}`, endpoint: this.endpointName, ...(line ? { event: JSON.stringify(line) } : {}), })); this.#dispatchIcqqSystemSideEvent(type, payload); } #dispatchIcqqSideEvent(payload: Record): void { const postType = String(payload.post_type ?? ''); const isRequest = postType === 'request' || postType.startsWith('request.'); const flag = payload.flag != null ? String(payload.flag) : ''; void receiveOneBotLikeSideEvent((name, payload) => this[endpointSpec].events.emit(name, payload), { adapter: 'icqq', endpointKey: this.endpointName, platform: 'icqq', raw: payload, ...(isRequest ? { approve: (id, remark) => this.#approveRequest({ requestId: flag || id, remark }), reject: (id, reason) => this.#rejectRequest({ requestId: flag || id, reason }), } : {}), }).catch((err) => { this.#logger.warn(formatCompact({ op: 'icqq_side_event_failed', endpoint: this.endpointName, post_type: postType || undefined, error: err instanceof Error ? err.message : String(err), })); }); } #dispatchIcqqSystemSideEvent(type: string, payload: Record | null): void { void this[endpointSpec].events.emit('system.receive', buildSystem(payload ?? {}, { id: `system:${this.endpointName}:${type}:${Date.now()}`, clientAdapter: 'icqq', endpointId: this.endpointName, type: 'system', name: `system.${type}`, timestamp: Date.now(), })).catch((err) => { this.#logger.warn(formatCompact({ op: 'icqq_system_side_event_failed', endpoint: this.endpointName, type, error: err instanceof Error ? err.message : String(err), })); }); } async #handleMessageEvent(eventName: 'message.private' | 'message.group', event: unknown): Promise { if (this.#retiring) return; const admittedBeforeRetire = this.#open; const payload = serializeIcqqEvent(event); if (!payload || !isIcqqMessagePostType(payload)) { this.#logger.debug(formatCompact({ op: 'icqq_inbound_skip', reason: payload ? 'not_message_post' : 'serialize_failed', endpoint: this.endpointName, event: eventName, })); return; } const data = payload as IcqqMessageEvent; if (shouldSkipSelfInboundMessage(data)) { this.#logger.debug(formatCompact({ op: 'icqq_inbound_skip', reason: 'self', endpoint: this.endpointName, user_id: data.user_id, self_id: data.self_id, })); return; } const contact = this.#resolveInboundContact(data); if (contact) { await resolveIcqqInboundMedia(data.message, { getPttUrl: (element) => contact.getPttUrl(element as PttElem), getVideoUrl: (element) => contact.getVideoUrl(element as VideoElem), }); if (!this.#started) return; } const normalized = normalizeIcqqInboundMessage(data); if (!normalized) { this.#logger.debug(formatCompact({ op: 'icqq_inbound_skip', reason: 'normalize_failed', endpoint: this.endpointName, event: eventName, message_id: data.message_id, })); return; } if (!this.#inboundDeduper.shouldProcess(normalized.messageId)) { this.#logger.debug(formatCompact({ op: 'icqq_inbound_skip', reason: 'dedupe', endpoint: this.endpointName, id: normalized.messageId, })); return; } const conversation = icqqInboundConversation(String(this.#options.id), { channelType: normalized.channelType, channelId: normalized.channelId, channelParentGroupId: normalized.channelParentGroupId, name: normalized.groupName, }); const quoteId = resolveIcqqQuoteIdFromEvent(data); const quoted = messageLookupFromIcqqSource(findIcqqNestedMessageSource(data)); if (quoteId && quoted) { this.#contentResolver.remember(quoteId, Object.freeze({ ref: Object.freeze({ conversation, id: quoteId }), ...(quoted.sender?.id ? { actor: Object.freeze({ id: quoted.sender.id, ...(quoted.sender.name ? { displayName: quoted.sender.name } : {}), }) } : {}), segments: Object.freeze(toCanonicalSegments( Array.isArray(quoted.content) ? quoted.content : [{ type: 'text', data: { text: quoted.content } }], )), timestamp: quoted.time ? quoted.time * (quoted.time < 1e12 ? 1000 : 1) : Date.now(), })); } await this.#deliverInbound({ event, platformSentAt: normalized.timestampMs, id: normalized.messageId, conversation, content: formatInboundContent(normalized.rawMessage), segments: normalized.content, sender: { id: normalized.userId, name: normalized.nickname || undefined, ...(normalized.senderRole ? { platform: { standing: normalized.senderRole } } : {}), }, channelType: normalized.channelType, ...(quoteId ? { replyTo: { id: quoteId } } : {}), metadata: { nickname: normalized.nickname, senderRole: normalized.senderRole, platformSentAt: normalized.timestampMs, }, }, admittedBeforeRetire); } #startMessageEvent(eventName: 'message.private' | 'message.group', event: unknown): void { const operation = this.#trackInbound(() => this.#handleMessageEvent(eventName, event)); void operation.catch((error) => { this.#logInboundHandlerFailure(eventName, error); }); } #resolveInboundContact(data: IcqqMessageEvent) { const userId = Number(data.user_id ?? data.from_id); if (!Number.isFinite(userId) || userId <= 0) return null; if (data.message_type === 'group' || data.group_id != null) { const groupId = Number(data.group_id); return Number.isFinite(groupId) && groupId > 0 ? this.pickGroup(groupId) : null; } const sourceGroupId = Number(data.sender?.group_id); if (Number.isFinite(sourceGroupId) && sourceGroupId > 0) { return this.pickMember(sourceGroupId, userId); } return this.pickFriend(userId); } #logInboundHandlerFailure(event: string, error: unknown): void { this.#logger.warn(formatCompact({ op: 'icqq_inbound_handler_failed', endpoint: this.endpointName, event, error: describeUnknownError(error), })); } async #handleGuildEvent(event: unknown): Promise { const payload = serializeIcqqEvent(event); if (!payload || typeof payload !== 'object') return; const normalized = normalizeIcqqGuildInboundMessage( payload as Parameters[0], ); if (!normalized) { this.#logger.debug(formatCompact({ op: 'icqq_inbound_skip', reason: 'guild_normalize_failed', endpoint: this.endpointName, })); return; } this.#guildCatalog.upsertFromInbound(normalized.raw); if (!this.#inboundDeduper.shouldProcess(`guild:${normalized.messageId}`)) { this.#logger.debug(formatCompact({ op: 'icqq_inbound_skip', reason: 'dedupe', endpoint: this.endpointName, id: `guild:${normalized.messageId}`, })); return; } await this.admit({ event, platformSentAt: typeof normalized.raw.time === 'number' && Number.isFinite(normalized.raw.time) ? normalized.timestampMs : undefined, id: normalized.messageId, conversation: icqqInboundConversation(String(this.#options.id), { channelType: 'channel', channelId: normalized.channelId, guildId: normalized.guildId, }), content: formatInboundContent(normalized.rawMessage), segments: normalized.content, sender: { id: normalized.userId, name: normalized.nickname || undefined }, channelType: 'channel', metadata: { guildId: normalized.guildId, nickname: normalized.nickname, }, }); } #onRequestEvent(payload: Record | null): void { if (!payload || !isIcqqRequestPayload(payload)) return; const flag = payload.flag != null ? String(payload.flag) : (payload.seq != null ? String(payload.seq) : ''); if (flag && !this.#sideEventDeduper.shouldProcess(`request:${flag}`)) return; this.#dispatchIcqqSideEvent(payload); } #onNoticeEvent(payload: Record | null): void { if (!payload || !isIcqqNoticePayload(payload)) return; if (!this.#sideEventDeduper.shouldProcess(icqqNoticeDedupeKey(payload))) return; this.#dispatchIcqqSideEvent(payload); } async #listPendingRequests(): Promise { const messages = await this.getSystemMsg(); const rows: EndpointPendingRequest[] = []; for (const raw of messages) { const msg = raw as unknown as IcqqSystemMessage & { request_type?: string }; const kind = msg.request_type === 'friend' ? 'friend' : 'group'; const platformRequestId = (msg.flag && String(msg.flag).trim()) || (msg.seq != null ? String(msg.seq) : ''); if (!platformRequestId || msg.user_id == null) continue; const createdAt = Number(msg.time); rows.push(Object.freeze({ platform_request_id: platformRequestId, type: kind, scene_type: kind === 'group' ? 'group' : null, scene_id: String(kind === 'group' ? (msg.group_id ?? msg.user_id) : msg.user_id), sub_type: kind === 'group' ? (msg.type != null ? String(msg.type) : null) : null, actor_id: String(msg.user_id), actor_name: msg.nickname != null ? String(msg.nickname) : null, comment: msg.comment != null ? String(msg.comment) : null, created_at: Number.isFinite(createdAt) && createdAt > 0 ? (createdAt < 1e12 ? createdAt * 1000 : createdAt) : Date.now(), })); } return Object.freeze(rows); } async #pullPendingSystemMessages(signal: AbortSignal): Promise { try { const messages = await raceAbort(Promise.resolve(this.getSystemMsg()), signal); for (const raw of messages) { signal.throwIfAborted(); const msg = raw as unknown as IcqqSystemMessage & { request_type?: string }; const kind = msg.request_type === 'friend' ? 'friend' : 'group'; const flag = msg.flag != null ? String(msg.flag) : (msg.seq != null ? String(msg.seq) : ''); if (!flag || !this.#sideEventDeduper.shouldProcess(`request:${flag}`)) continue; this.#dispatchIcqqSideEvent({ post_type: 'request', request_type: kind, flag: msg.flag, user_id: msg.user_id, group_id: msg.group_id, comment: msg.comment, time: msg.time, sub_type: msg.type, }); } } catch (error) { if (signal.aborted) throw signal.reason ?? error; this.#logger.debug(formatCompact({ op: 'side_event_pull_system_msg', endpoint: this.endpointName, error: error instanceof Error ? error.message : String(error), })); } } async #approveRequest({ requestId: id, remark, signal }: EndpointApproveRequest): Promise { const operation = createEndpointOperation({ signal }); const messages = await operation.run(() => this.getSystemMsg()); const target = messages.find((m) => { const msg = m as unknown as IcqqSystemMessage; return msg.flag === id || (msg.seq != null && String(msg.seq) === id); }) as unknown as IcqqSystemMessage | undefined; if (!target?.flag) { throw new Error(`icqq 未找到待处理请求: ${id}`); } const flag = target.flag; if ((target as { request_type?: string }).request_type === 'friend') { await operation.run(() => this.setFriendAddRequest(flag, true, remark)); } else { await operation.run(() => this.setGroupAddRequest(flag, true)); } } async #rejectRequest({ requestId: id, reason, signal }: EndpointRejectRequest): Promise { const operation = createEndpointOperation({ signal }); const messages = await operation.run(() => this.getSystemMsg()); const target = messages.find((m) => { const msg = m as unknown as IcqqSystemMessage; return msg.flag === id || (msg.seq != null && String(msg.seq) === id); }) as unknown as IcqqSystemMessage | undefined; if (!target?.flag) { throw new Error(`icqq 未找到待处理请求: ${id}`); } const flag = target.flag; if ((target as { request_type?: string }).request_type === 'friend') { await operation.run(() => this.setFriendAddRequest(flag, false)); } else { await operation.run(() => this.setGroupAddRequest(flag, false, reason)); } } } function isIcqqShareElement(message: Sendable): message is ShareElem { return !Array.isArray(message) && typeof message === 'object' && message !== null && message.type === 'share'; } function formatIcqqSendablePreview(message: Sendable): string { if (typeof message === 'string') return message; try { return JSON.stringify(message, (_key, value) => Buffer.isBuffer(value) ? '' : value); } catch { return '[ICQQ Sendable]'; } } function isIcqqSegmentPayload(payload: unknown): payload is import('zhin.js').SendContent { if (Array.isArray(payload)) return true; return typeof payload === 'object' && payload !== null && typeof (payload as { type?: unknown }).type === 'string'; } function isIcqqFileElement(message: Sendable): message is FileElem { return !Array.isArray(message) && typeof message !== 'string' && message.type === 'file'; } async function raceAbort(operation: Promise, signal: AbortSignal): Promise { signal.throwIfAborted(); let rejectAbort!: (reason: unknown) => void; const aborted = new Promise((_resolve, reject) => { rejectAbort = reject; }); const onAbort = () => rejectAbort(signal.reason ?? new Error('ICQQ operation aborted')); signal.addEventListener('abort', onAbort, { once: true }); try { return await Promise.race([operation, aborted]); } finally { signal.removeEventListener('abort', onAbort); } } function describeUnknownError(error: unknown): string { if (error instanceof Error) return error.stack ?? error.message; if (error && typeof error === 'object') { try { return JSON.stringify(error); } catch { return inspect(error, { depth: 4, breakLength: 120 }); } } return String(error); } function resolveIcqqGroupReactionTarget( message: MessageRef, ): { groupId: number; seq: number } | null { if (message.conversation.kind !== 'group') return null; const groupId = Number(message.conversation.id); if (!Number.isFinite(groupId) || groupId <= 0) return null; const raw = message.id?.trim(); if (!raw || raw.startsWith('outbound:')) return null; if (/^[1-9]\d*$/.test(raw)) return { groupId, seq: Number(raw) }; try { const parsed = parseGroupMessageId(raw); if (parsed.seq > 0) return { groupId: parsed.group_id || groupId, seq: parsed.seq }; } catch { // not a cqhttp group message id } return null; } function resolveNativeClientConfig(config: ResolvedIcqqConfig): NativeIcqqClientConfig { return { log_level: config.logLevel, platform: config.platform, ...(config.ver ? { ver: config.ver } : {}), ...(config.dataDir ? { data_dir: config.dataDir } : {}), ...(config.signApiAddr ? { sign_api_addr: config.signApiAddr } : {}), ...(config.ignoreSelf != null ? { ignore_self: config.ignoreSelf } : {}), ...(config.resend != null ? { resend: config.resend } : {}), ...(config.cacheGroupMember != null ? { cache_group_member: config.cacheGroupMember } : {}), ...(config.autoServer != null ? { auto_server: config.autoServer } : {}), ...(config.qqnt != null ? { QQNT: config.qqnt } : {}), ...(config.ntLogin != null ? { NTLogin: config.ntLogin } : {}), reconn_interval: config.autoReconnect ? 5 : 0, }; } /** Log line of a login challenge: its kind and the link's host, never the link, image or device. */ export function loginChallengeLogLine(kind: string, payload: Record | null): Record { const host = icqqLinkHost(payload?.url); return { kind, ...(host ? { host } : {}) }; } function serializeIcqqEvent(event: unknown): Record | null { if (!event || typeof event !== 'object') return null; const nativeToJSON = (event as { toJSON?: (keys: string[]) => unknown }).toJSON; if (typeof nativeToJSON === 'function') { try { const json = nativeToJSON.call(event, [...ICQQ_SERIALIZE_SKIP]); if (json && typeof json === 'object' && !Array.isArray(json)) { return json as Record; } } catch { /* JSON.stringify 也会无参调 toJSON,不能当回退 */ } } const out: Record = {}; for (const [key, value] of Object.entries(event as Record)) { if (typeof value === 'function' || (ICQQ_SERIALIZE_SKIP as readonly string[]).includes(key)) continue; out[key] = value; } return Object.keys(out).length > 0 ? out : null; } const INBOUND_HOLD_LIMIT = 32; /** Automatic backoff relogins before the attempt fails and waits for the person. */ const ICQQ_RELOGIN_ATTEMPTS = 8; const ICQQ_SERIALIZE_SKIP = ['group', 'member', 'friend', 'discuss', 'client'] as const;