From 652bafd75ab5904162d33c2144172ae927b53bfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=89=8B=E7=93=9C=E4=B8=80=E5=8D=81=E9=9B=AA?= Date: Wed, 27 May 2026 12:27:13 +0800 Subject: [PATCH] Extract bridge transport into @snowluma/bridge Move transport-layer bridge code out of @snowluma/core into a dedicated @snowluma/bridge package and introduce a clear account layer in core. Adds Bridge, BridgeInterface, InjectBridge, ProtocolBridge (stub), adapters, and manager files under packages/bridge and updates package.json exports. In @snowluma/core the former bridge surface is replaced by Account, AccountContext, AccountInterface and AccountManager; apis were moved/renamed to account/apis and now consume AccountContext. Adjustments include packet handling plumbing (use deliverPacket / setPacketHandler), updated sendRawPacket wiring, uploaded-file cache and lifecycle changes (InjectBridge.dispose, ProtocolBridge returns a structured not-implemented result). Tests and imports were updated accordingly. --- packages/bridge/package.json | 32 ++++ .../src/bridge => bridge/src}/adapter.ts | 0 packages/bridge/src/bridge-interface.ts | 70 ++++++++ packages/bridge/src/bridge.ts | 57 +++++++ packages/bridge/src/index.ts | 17 ++ .../bridge => bridge/src}/inject-adapter.ts | 4 +- .../bridge => bridge/src}/inject-bridge.ts | 47 +++--- .../src/bridge => bridge/src}/manager.ts | 0 .../bridge => bridge/src}/protocol-adapter.ts | 0 packages/bridge/src/protocol-bridge.ts | 41 +++++ packages/core/package.json | 48 ++---- packages/core/src/account/account-context.ts | 25 +++ .../core/src/account/account-interface.ts | 34 ++++ packages/core/src/account/account-manager.ts | 100 ++++++++++++ .../{bridge/bridge.ts => account/account.ts} | 152 +++++++----------- .../src/{bridge => account}/apis/contacts.ts | 20 ++- .../src/{bridge => account}/apis/extras.ts | 4 +- .../src/{bridge => account}/apis/forward.ts | 14 +- .../src/{bridge => account}/apis/friend.ts | 4 +- .../{bridge => account}/apis/group-admin.ts | 4 +- .../{bridge => account}/apis/group-album.ts | 4 +- .../{bridge => account}/apis/group-file.ts | 17 +- .../src/{bridge => account}/apis/index.ts | 17 +- .../{bridge => account}/apis/interaction.ts | 4 +- .../src/{bridge => account}/apis/message.ts | 31 ++-- .../core/src/{bridge => account}/apis/misc.ts | 4 +- .../src/{bridge => account}/apis/profile.ts | 11 +- .../src/{bridge => account}/apis/shared.ts | 5 +- .../core/src/{bridge => account}/apis/web.ts | 38 +++-- packages/core/src/bridge/bridge-context.ts | 8 - packages/core/src/bridge/bridge-interface.ts | 43 ----- packages/core/src/bridge/protocol-bridge.ts | 52 ------ packages/core/src/index.ts | 16 +- ...est.ts => account-member-identity.test.ts} | 73 ++++----- ...est.ts => account-private-routing.test.ts} | 116 +++++++------ packages/core/tests/actions/extras.test.ts | 6 +- .../core/tests/actions/forward-file.test.ts | 6 +- .../core/tests/actions/forward-nested.test.ts | 12 +- packages/core/tests/actions/forward.test.ts | 6 +- packages/core/tests/actions/friend.test.ts | 6 +- .../core/tests/actions/group-admin.test.ts | 10 +- .../core/tests/actions/group-file.test.ts | 10 +- .../core/tests/actions/group-message.test.ts | 4 +- .../core/tests/actions/interaction.test.ts | 6 +- packages/core/tests/actions/misc.test.ts | 8 +- packages/core/tests/actions/profile.test.ts | 26 +-- packages/onebot/package.json | 1 + packages/onebot/src/api-handler.ts | 4 +- packages/onebot/src/instance-context.ts | 7 +- packages/onebot/src/instance-rkey.ts | 14 +- packages/onebot/src/instance.ts | 6 +- packages/onebot/src/manager.ts | 16 +- packages/onebot/src/media-url-resolver.ts | 4 +- .../onebot/src/modules/contact-actions.ts | 22 +-- packages/onebot/src/modules/media-actions.ts | 4 +- .../onebot/src/modules/message-actions.ts | 6 +- .../onebot/src/modules/request-actions.ts | 4 +- pnpm-lock.yaml | 3 + 58 files changed, 780 insertions(+), 523 deletions(-) rename packages/{core/src/bridge => bridge/src}/adapter.ts (100%) create mode 100644 packages/bridge/src/bridge-interface.ts create mode 100644 packages/bridge/src/bridge.ts rename packages/{core/src/bridge => bridge/src}/inject-adapter.ts (99%) rename packages/{core/src/bridge => bridge/src}/inject-bridge.ts (55%) rename packages/{core/src/bridge => bridge/src}/manager.ts (100%) rename packages/{core/src/bridge => bridge/src}/protocol-adapter.ts (100%) create mode 100644 packages/bridge/src/protocol-bridge.ts create mode 100644 packages/core/src/account/account-context.ts create mode 100644 packages/core/src/account/account-interface.ts create mode 100644 packages/core/src/account/account-manager.ts rename packages/core/src/{bridge/bridge.ts => account/account.ts} (58%) rename packages/core/src/{bridge => account}/apis/contacts.ts (92%) rename packages/core/src/{bridge => account}/apis/extras.ts (96%) rename packages/core/src/{bridge => account}/apis/forward.ts (98%) rename packages/core/src/{bridge => account}/apis/friend.ts (90%) rename packages/core/src/{bridge => account}/apis/group-admin.ts (96%) rename packages/core/src/{bridge => account}/apis/group-album.ts (98%) rename packages/core/src/{bridge => account}/apis/group-file.ts (98%) rename packages/core/src/{bridge => account}/apis/index.ts (86%) rename packages/core/src/{bridge => account}/apis/interaction.ts (96%) rename packages/core/src/{bridge => account}/apis/message.ts (94%) rename packages/core/src/{bridge => account}/apis/misc.ts (95%) rename packages/core/src/{bridge => account}/apis/profile.ts (94%) rename packages/core/src/{bridge => account}/apis/shared.ts (93%) rename packages/core/src/{bridge => account}/apis/web.ts (90%) delete mode 100644 packages/core/src/bridge/bridge-context.ts delete mode 100644 packages/core/src/bridge/bridge-interface.ts delete mode 100644 packages/core/src/bridge/protocol-bridge.ts rename packages/core/tests/{bridge-member-identity.test.ts => account-member-identity.test.ts} (60%) rename packages/core/tests/{bridge-private-routing.test.ts => account-private-routing.test.ts} (59%) diff --git a/packages/bridge/package.json b/packages/bridge/package.json index df0e8a04..23a1f480 100644 --- a/packages/bridge/package.json +++ b/packages/bridge/package.json @@ -42,6 +42,38 @@ "./types": { "types": "./src/types.ts", "default": "./src/types.ts" + }, + "./bridge": { + "types": "./src/bridge.ts", + "default": "./src/bridge.ts" + }, + "./bridge-interface": { + "types": "./src/bridge-interface.ts", + "default": "./src/bridge-interface.ts" + }, + "./inject-bridge": { + "types": "./src/inject-bridge.ts", + "default": "./src/inject-bridge.ts" + }, + "./protocol-bridge": { + "types": "./src/protocol-bridge.ts", + "default": "./src/protocol-bridge.ts" + }, + "./adapter": { + "types": "./src/adapter.ts", + "default": "./src/adapter.ts" + }, + "./inject-adapter": { + "types": "./src/inject-adapter.ts", + "default": "./src/inject-adapter.ts" + }, + "./protocol-adapter": { + "types": "./src/protocol-adapter.ts", + "default": "./src/protocol-adapter.ts" + }, + "./manager": { + "types": "./src/manager.ts", + "default": "./src/manager.ts" } }, "scripts": { diff --git a/packages/core/src/bridge/adapter.ts b/packages/bridge/src/adapter.ts similarity index 100% rename from packages/core/src/bridge/adapter.ts rename to packages/bridge/src/adapter.ts diff --git a/packages/bridge/src/bridge-interface.ts b/packages/bridge/src/bridge-interface.ts new file mode 100644 index 00000000..f450841d --- /dev/null +++ b/packages/bridge/src/bridge-interface.ts @@ -0,0 +1,70 @@ +import type { SendPacketResult } from '@snowluma/common/packet-sender'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; + +/** + * Discriminator for the two bridge transport implementations: + * + * - `'inject'` — backed by an in-process NTQQ hook (one or more + * QQ.exe processes injected with the SnowLuma DLL, + * talking over named pipes). + * - `'protocol'` — backed by a direct protocol client (no QQ.exe, + * no hook). Reserved for the future pure-protocol + * runtime; `ProtocolBridge` is a stub until then. + * + * Mirrored on `AccountInterface` so account-level consumers can + * branch on transport without `instanceof` checks against a concrete + * subclass when they genuinely have to (diagnostics, kind-specific + * WebUI panels, …). + */ +export type BridgeKind = 'inject' | 'protocol'; + +/** + * `BridgeInterface` — **strictly transport**. A bridge owns one wire- + * level connection to QQ for a given UIN: it sends opaque packets out + * and surfaces received packets to whoever subscribed via + * `setPacketHandler`. + * + * It deliberately knows nothing about identity caches, the event bus, + * the api hub, or the cmd-dispatch pipeline — that machinery lives on + * the `Account` layer (`@snowluma/core/account-interface`) that wraps + * a `Bridge` to expose a business-level API to OneBot and friends. + * + * Direct consumers are limited to: + * - `BridgeAdapter` implementations (they create / dispose bridges, + * and pump received packets through `deliverPacket`), + * - `BridgeManager` (multi-account host, indexes bridges by uin), + * - `Account` (the only thing that calls `setPacketHandler` and the + * one that exposes the rich surface to OneBot). + * + * OneBot and api modules should NEVER import `BridgeInterface`; they + * import `AccountInterface` instead. + */ +export interface BridgeInterface { + /** Transport family backing this bridge. */ + readonly kind: BridgeKind; + /** Stable, unique-per-live-bridge id inside `BridgeManager` + * (e.g. `'inject:3161592748'`). */ + readonly id: string; + /** QQ number this transport carries. */ + readonly uin: string; + + /** Wire-level send. The only escape hatch the apis layer eventually + * routes through (via `Account.sendRawPacket`). */ + sendRawPacket( + serviceCmd: string, + body: Uint8Array, + timeoutMs?: number, + ): Promise; + + /** Subscribe to inbound packets. Called once by `Account` when it + * attaches to this transport. Passing `null` detaches. */ + setPacketHandler(handler: ((pkt: PacketInfo) => void) | null): void; + + /** Adapter-side hook: feed a freshly-received packet into the + * current subscriber (if any). Called by `BridgeAdapter`s when + * their underlying runtime delivers a frame. */ + deliverPacket(pkt: PacketInfo): void; + + /** Release transport-side resources. Idempotent. */ + dispose(): void; +} diff --git a/packages/bridge/src/bridge.ts b/packages/bridge/src/bridge.ts new file mode 100644 index 00000000..e0a30757 --- /dev/null +++ b/packages/bridge/src/bridge.ts @@ -0,0 +1,57 @@ +import type { SendPacketResult } from '@snowluma/common/packet-sender'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; +import type { BridgeInterface, BridgeKind } from './bridge-interface'; + +/** + * Abstract base for every concrete bridge transport (`InjectBridge`, + * `ProtocolBridge`, …). Strictly transport: knows about wire-level + * send, packet delivery to a single subscriber, and lifecycle. + * + * Subclasses provide: + * + * 1. `kind` / `id` / `uin` — discriminators used by `BridgeManager` + * to index live transports. + * 2. `sendRawPacket` — the actual outbound wire path. `InjectBridge` + * forwards through a `PacketSender` (named-pipe to QQ.exe); + * `ProtocolBridge` will eventually drive a long-lived TCP login + * session. + * + * Inbound packets are routed via the `packetHandler_` slot: an + * `Account` calls `setPacketHandler(...)` to subscribe, and the + * owning `BridgeAdapter` calls `deliverPacket(pkt)` for every frame + * the underlying runtime hands it. + * + * `Bridge` knows NOTHING about identity caches, the event bus, the + * api hub, or the cmd-dispatch pipeline. That entire account-layer + * machinery lives on `Account` (`@snowluma/core/account`). + */ +export abstract class Bridge implements BridgeInterface { + abstract readonly kind: BridgeKind; + abstract readonly id: string; + abstract readonly uin: string; + + abstract sendRawPacket( + serviceCmd: string, + body: Uint8Array, + timeoutMs?: number, + ): Promise; + + private packetHandler_: ((pkt: PacketInfo) => void) | null = null; + private disposed_ = false; + + setPacketHandler(handler: ((pkt: PacketInfo) => void) | null): void { + this.packetHandler_ = handler; + } + + deliverPacket(pkt: PacketInfo): void { + this.packetHandler_?.(pkt); + } + + get isDisposed(): boolean { return this.disposed_; } + + dispose(): void { + if (this.disposed_) return; + this.disposed_ = true; + this.packetHandler_ = null; + } +} diff --git a/packages/bridge/src/index.ts b/packages/bridge/src/index.ts index 4f7a4378..c8074f6e 100644 --- a/packages/bridge/src/index.ts +++ b/packages/bridge/src/index.ts @@ -1,5 +1,22 @@ +// ─── Hook runtime (existing) ─────────────────────────────────────── export { HookManager, type BridgeManagerSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo, type HookProcessStatus, type QqPortLoginInfo } from './hook-manager'; +// ─── Transport layer (Bridge + concrete InjectBridge / ProtocolBridge) ── +export { Bridge } from './bridge'; +export { type BridgeInterface, type BridgeKind } from './bridge-interface'; +export { InjectBridge } from './inject-bridge'; +export { ProtocolBridge } from './protocol-bridge'; + +// ─── Adapter pattern ─────────────────────────────────────────────── +export { type BridgeAdapter, type BridgeAdapterHost } from './adapter'; +export { InjectBridgeAdapter, type InjectBridgeAdapterOptions } from './inject-adapter'; +export { ProtocolBridgeAdapter } from './protocol-adapter'; + +// ─── Multi-account host ──────────────────────────────────────────── +export { + BridgeManager, type SessionClosedCallback, type SessionStartedCallback +} from './manager'; + diff --git a/packages/core/src/bridge/inject-adapter.ts b/packages/bridge/src/inject-adapter.ts similarity index 99% rename from packages/core/src/bridge/inject-adapter.ts rename to packages/bridge/src/inject-adapter.ts index 467e2283..c3cae2ad 100644 --- a/packages/core/src/bridge/inject-adapter.ts +++ b/packages/bridge/src/inject-adapter.ts @@ -1,7 +1,7 @@ -import { HookManager, type BridgeManagerSink, type HookManagerDeps } from '@snowluma/bridge'; import type { PacketSender } from '@snowluma/common/packet-sender'; import type { PacketInfo } from '@snowluma/common/protocol-types'; import type { BridgeAdapter, BridgeAdapterHost } from './adapter'; +import { HookManager, type BridgeManagerSink, type HookManagerDeps } from './hook-manager'; import { InjectBridge } from './inject-bridge'; /** Subset of `HookManagerDeps` the operator is allowed to forward @@ -117,7 +117,7 @@ export class InjectBridgeAdapter implements BridgeAdapter, BridgeManagerSink { } } - bridge.onPacket(pkt); + bridge.deliverPacket(pkt); } onPidDisconnected(pid: number): void { diff --git a/packages/core/src/bridge/inject-bridge.ts b/packages/bridge/src/inject-bridge.ts similarity index 55% rename from packages/core/src/bridge/inject-bridge.ts rename to packages/bridge/src/inject-bridge.ts index b8e8c411..8cdc157b 100644 --- a/packages/core/src/bridge/inject-bridge.ts +++ b/packages/bridge/src/inject-bridge.ts @@ -1,43 +1,34 @@ import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender'; -import { IdentityService } from '@snowluma/protocol/identity-service'; import { Bridge } from './bridge'; /** - * `InjectBridge` — the concrete account bridge backed by the in-process - * NTQQ hook (one or more QQ.exe processes injected with the SnowLuma - * DLL talking over named pipes). + * `InjectBridge` — concrete transport backed by the in-process NTQQ + * hook. One UIN may be served simultaneously by several injected + * processes; the bridge therefore tracks an unordered set of PIDs and + * keeps a single live `PacketSender` (the most recently logged-in + * pipe) for outbound traffic. * - * One UIN may be served simultaneously by several injected processes; - * the bridge therefore tracks an unordered set of PIDs and keeps a - * single live `PacketSender` (the most recently logged-in pipe) for - * outbound traffic. PID bookkeeping is intentionally kept here rather - * than on the abstract `Bridge` so the protocol-only runtime never - * sees the concept. + * PID bookkeeping is scoped to this transport because the protocol- + * only runtime never has the concept; quarantining it here keeps the + * abstract `Bridge` and the `BridgeManager` free of pid awareness. * - * The owning `InjectBridgeAdapter` is responsible for: - * - calling `attachPid(pid, sender)` on every successful hook login, - * - calling `detachPid(pid)` when the watcher reports a pipe drop, - * - calling `dispose()` when the last PID drops. + * The owning `InjectBridgeAdapter` is responsible for calling + * `attachPid(pid, sender)` on every successful hook login, + * `detachPid(pid)` when the watcher reports a pipe drop, and tearing + * the bridge down once `isEmpty` returns true. */ export class InjectBridge extends Bridge { readonly kind = 'inject' as const; + readonly uin: string; private readonly pids_ = new Set(); private packetClient_: PacketSender | null = null; - /** - * @param uin QQ number this bridge represents. - * @param identity Optional pre-built `IdentityService`. The default - * opens the on-disk SQLite store at - * `data//snowluma_identity.db`; tests usually - * pass `IdentityService.memory(uin)` to avoid touching - * the filesystem. - */ - constructor(uin: string, identity: IdentityService = IdentityService.openForUin(uin)) { - super(identity); + constructor(uin: string) { + super(); + this.uin = uin; } - /** Stable, unique-per-account id used by `BridgeManager`. */ get id(): string { return `inject:${this.uin}`; } /** PIDs currently routing packets into this bridge. Read-only view @@ -82,4 +73,10 @@ export class InjectBridge extends Bridge { } return client.sendPacket(serviceCmd, Buffer.from(body), timeoutMs); } + + override dispose(): void { + super.dispose(); + this.packetClient_ = null; + this.pids_.clear(); + } } diff --git a/packages/core/src/bridge/manager.ts b/packages/bridge/src/manager.ts similarity index 100% rename from packages/core/src/bridge/manager.ts rename to packages/bridge/src/manager.ts diff --git a/packages/core/src/bridge/protocol-adapter.ts b/packages/bridge/src/protocol-adapter.ts similarity index 100% rename from packages/core/src/bridge/protocol-adapter.ts rename to packages/bridge/src/protocol-adapter.ts diff --git a/packages/bridge/src/protocol-bridge.ts b/packages/bridge/src/protocol-bridge.ts new file mode 100644 index 00000000..a12d5035 --- /dev/null +++ b/packages/bridge/src/protocol-bridge.ts @@ -0,0 +1,41 @@ +import type { SendPacketResult } from '@snowluma/common/packet-sender'; +import { Bridge } from './bridge'; + +/** + * `ProtocolBridge` — placeholder transport for the future pure- + * protocol runtime (no QQ.exe, no hook). It already participates in + * `BridgeManager` so the wider architecture (BridgeAdapter pool → + * AccountManager → OneBot) is exercised end-to-end today; once a real + * `ProtocolClient` lands the transport will gain a constructor + * argument and `sendRawPacket` will route through it. + * + * Until then `sendRawPacket` returns a structured "not implemented" + * failure rather than throwing, so the surrounding code treats it as + * a regular transport-down result. + */ +export class ProtocolBridge extends Bridge { + readonly kind = 'protocol' as const; + readonly uin: string; + + constructor(uin: string) { + super(); + this.uin = uin; + } + + get id(): string { return `protocol:${this.uin}`; } + + override async sendRawPacket( + serviceCmd: string, + body: Uint8Array, + timeoutMs?: number, + ): Promise { + void serviceCmd; void body; void timeoutMs; + return { + success: false, + gotResponse: false, + errorCode: -1, + errorMessage: 'protocol bridge transport is not yet implemented', + responseData: null, + }; + } +} diff --git a/packages/core/package.json b/packages/core/package.json index 24b5932b..5922bfe0 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -10,45 +10,25 @@ "types": "./src/index.ts", "default": "../../dist/index.mjs" }, - "./bridge": { - "types": "./src/bridge/bridge.ts", - "default": "./src/bridge/bridge.ts" + "./account": { + "types": "./src/account/account.ts", + "default": "./src/account/account.ts" }, - "./inject-bridge": { - "types": "./src/bridge/inject-bridge.ts", - "default": "./src/bridge/inject-bridge.ts" + "./account-context": { + "types": "./src/account/account-context.ts", + "default": "./src/account/account-context.ts" }, - "./protocol-bridge": { - "types": "./src/bridge/protocol-bridge.ts", - "default": "./src/bridge/protocol-bridge.ts" + "./account-interface": { + "types": "./src/account/account-interface.ts", + "default": "./src/account/account-interface.ts" }, - "./bridge-interface": { - "types": "./src/bridge/bridge-interface.ts", - "default": "./src/bridge/bridge-interface.ts" - }, - "./bridge-context": { - "types": "./src/bridge/bridge-context.ts", - "default": "./src/bridge/bridge-context.ts" - }, - "./manager": { - "types": "./src/bridge/manager.ts", - "default": "./src/bridge/manager.ts" - }, - "./adapter": { - "types": "./src/bridge/adapter.ts", - "default": "./src/bridge/adapter.ts" - }, - "./inject-adapter": { - "types": "./src/bridge/inject-adapter.ts", - "default": "./src/bridge/inject-adapter.ts" - }, - "./protocol-adapter": { - "types": "./src/bridge/protocol-adapter.ts", - "default": "./src/bridge/protocol-adapter.ts" + "./account-manager": { + "types": "./src/account/account-manager.ts", + "default": "./src/account/account-manager.ts" }, "./apis": { - "types": "./src/bridge/apis/index.ts", - "default": "./src/bridge/apis/index.ts" + "types": "./src/account/apis/index.ts", + "default": "./src/account/apis/index.ts" } }, "scripts": { diff --git a/packages/core/src/account/account-context.ts b/packages/core/src/account/account-context.ts new file mode 100644 index 00000000..aa587531 --- /dev/null +++ b/packages/core/src/account/account-context.ts @@ -0,0 +1,25 @@ +import type { BridgeContext as ProtocolBridgeContext } from '@snowluma/protocol/bridge-context'; +import type { ApiHub } from './apis'; + +/** + * `AccountContext` — the **account-layer** context that Api wrappers + * (`apis/*`) consume. + * + * It extends the protocol-layer `BridgeContext` with one extra slot: + * `apis: ApiHub`. The protocol layer can't mention `ApiHub` because + * the apis live in @snowluma/core, so the shared surface is layered: + * + * - `@snowluma/protocol/bridge-context.BridgeContext` — identity, + * events, raw packet I/O, sequences, file cache. Consumed by + * `element-builder`, highway uploaders, msg-push decoders. + * - `@snowluma/core/account/account-context.AccountContext` — adds + * `apis`. Consumed by everything inside `apis/*` and by tests that + * stub the surface for OneBot-side unit tests. + * + * The concrete `Account` class implements this extended interface. + */ +export interface AccountContext extends ProtocolBridgeContext { + readonly apis: ApiHub; +} + +export type { UploadedFileMeta } from '@snowluma/protocol/bridge-context'; diff --git a/packages/core/src/account/account-interface.ts b/packages/core/src/account/account-interface.ts new file mode 100644 index 00000000..4c2b718d --- /dev/null +++ b/packages/core/src/account/account-interface.ts @@ -0,0 +1,34 @@ +import type { BridgeKind } from '@snowluma/bridge'; +import type { AccountContext } from './account-context'; + +/** + * `AccountInterface` — the public surface every QQ account exposes to + * the rest of the system (OneBot, future MCP clients, WebUI status + * panels). Replaces the old `BridgeInterface`, which conflated the + * transport (`Bridge`) and the account-level wrapper. + * + * Reading this type is the right starting point when wiring a new + * consumer: + * + * - `identity` / `events` / `apis` / sequence helpers / file cache + * are inherited from `AccountContext`. + * - `kind` / `id` / `uin` mirror the underlying transport's identity + * so consumers can branch on transport kind when they really need + * to (e.g. WebUI diagnostics) without `instanceof` checks. + * - `dispose()` is the lifecycle hook; `AccountManager` calls it + * when the underlying bridge disappears. + * + * Day-to-day consumers should stay kind-agnostic — that's the entire + * point of the abstraction. + */ +export interface AccountInterface extends AccountContext { + /** Transport family backing this account. */ + readonly kind: BridgeKind; + /** Stable, unique-per-account id (mirrors the transport's id). */ + readonly id: string; + /** QQ number this account represents. Mirrors `identity.uin`. */ + readonly uin: string; + /** Release identity DB handles, event subscribers, and any + * account-level resources. Idempotent. */ + dispose(): void; +} diff --git a/packages/core/src/account/account-manager.ts b/packages/core/src/account/account-manager.ts new file mode 100644 index 00000000..aa2ab5c3 --- /dev/null +++ b/packages/core/src/account/account-manager.ts @@ -0,0 +1,100 @@ +import type { BridgeInterface, BridgeManager } from '@snowluma/bridge'; +import { createLogger } from '@snowluma/common/logger'; +import { Account } from './account'; +import type { AccountInterface } from './account-interface'; + +export type AccountStartedCallback = (uin: string, account: AccountInterface) => void; +export type AccountClosedCallback = (uin: string) => void; + +const log = createLogger('Account'); + +/** + * `AccountManager` — the layer that turns transport-level bridges into + * full-fledged `Account`s. + * + * It subscribes to `BridgeManager`'s primary-bridge availability + * callbacks (`sessionStarted` / `sessionClosed`), wraps each newly- + * available `Bridge` in a fresh `Account`, and re-emits its own + * `accountStarted` / `accountClosed` events for downstream consumers + * (OneBot, future MCP runtimes, WebUI). + * + * One `Account` per UIN at a time. If `BridgeManager` swaps the + * primary bridge under a UIN (e.g. protocol overtakes inject) the + * manager already issues close→start in that order, which we faithfully + * propagate: the old `Account` is disposed and a brand-new one is + * built around the new primary bridge. + */ +export class AccountManager { + private readonly accounts_ = new Map(); + private onAccountStarted_: AccountStartedCallback | null = null; + private onAccountClosed_: AccountClosedCallback | null = null; + + /** Subscribe to a `BridgeManager` so this AccountManager learns + * about primary-bridge availability and tears down accounts on + * the way out. Idempotent. Call before `bridgeManager.start()`. */ + bind(bridgeManager: BridgeManager): void { + bridgeManager.setSessionStartedCallback((uin, bridge) => { + this.onBridgeAvailable(uin, bridge); + }); + bridgeManager.setSessionClosedCallback((uin) => { + this.onBridgeUnavailable(uin); + }); + } + + /** Notified when an `Account` is published — typically once per UIN + * going online (and once more on a primary-bridge swap). */ + setAccountStartedCallback(cb: AccountStartedCallback): void { this.onAccountStarted_ = cb; } + /** Notified when an `Account` is torn down — the UIN may either be + * fully offline OR getting a fresh account on a new transport. */ + setAccountClosedCallback(cb: AccountClosedCallback): void { this.onAccountClosed_ = cb; } + + /** Currently online accounts, keyed by UIN. */ + getAccount(uin: string): AccountInterface | null { + return this.accounts_.get(uin) ?? null; + } + + getAccounts(): readonly AccountInterface[] { + return [...this.accounts_.values()]; + } + + /** Tear down every live account. Safe to call from a shutdown + * handler; idempotent. */ + dispose(): void { + for (const account of this.accounts_.values()) { + try { account.dispose(); } catch (err) { + log.debug('account.dispose() threw: %s', err instanceof Error ? err.message : String(err)); + } + } + this.accounts_.clear(); + } + + // ─── BridgeManager session-callback handlers ─────────────────── + + private onBridgeAvailable(uin: string, bridge: BridgeInterface): void { + // Defensive: a stuck old account on the same UIN means + // BridgeManager fired closed→started but we missed the closed. + // Tear it down before publishing a fresh one to avoid dangling + // identity DB handles. + const stale = this.accounts_.get(uin); + if (stale) { + log.warn('rebuilding account: UIN=%s stale=%s', uin, stale.id); + try { stale.dispose(); } catch { /* ignore */ } + this.accounts_.delete(uin); + } + + const account = new Account(bridge); + this.accounts_.set(uin, account); + log.debug('account started: UIN=%s id=%s', uin, account.id); + this.onAccountStarted_?.(uin, account); + } + + private onBridgeUnavailable(uin: string): void { + const account = this.accounts_.get(uin); + if (!account) return; + this.accounts_.delete(uin); + log.debug('account closed: UIN=%s id=%s', uin, account.id); + try { this.onAccountClosed_?.(uin); } finally { + try { account.dispose(); } catch { /* ignore */ } + } + } +} diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/account/account.ts similarity index 58% rename from packages/core/src/bridge/bridge.ts rename to packages/core/src/account/account.ts index a627f3d7..57747cd3 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/account/account.ts @@ -1,68 +1,75 @@ +import type { BridgeInterface, BridgeKind } from '@snowluma/bridge'; import type { SendPacketResult } from '@snowluma/common/packet-sender'; import type { PacketInfo } from '@snowluma/common/protocol-types'; +import type { UploadedFileMeta } from '@snowluma/protocol/bridge-context'; import { BridgeEventBus } from '@snowluma/protocol/event-bus'; import { IdentityService } from '@snowluma/protocol/identity-service'; import { MSG_PUSH_CMD, parseMsgPush } from '@snowluma/protocol/msg-push'; import { IncomingPacketPipeline, type CmdParser } from '@snowluma/protocol/packet-pipeline'; +import type { AccountInterface } from './account-interface'; import { buildApiHub, type ApiHub } from './apis'; -import { - AiVoiceChatType, - type AiVoiceCategory, - type StrangerStatus, -} from './apis/extras'; -import type { BridgeInterface, BridgeKind } from './bridge-interface'; /** - * Abstract base for every concrete account bridge (`InjectBridge`, - * `ProtocolBridge`, …). Owns everything that is transport-agnostic: + * `Account` — the QQ-account-level concept that sits on top of a low- + * level `Bridge` transport. Owns everything OneBot, the apis, and the + * msg-push pipeline care about: * - * - the per-account `IdentityService` (friend/group/uid cache + DB), - * - the typed `BridgeEventBus` (per-kind subscribers), + * - `identity` (per-uin SQLite-backed roster + uid↔uin index), + * - the typed `BridgeEventBus` (subscribe to bridge events by kind), * - the `ApiHub` (typed wrappers around `sendRawPacket`), - * - the `IncomingPacketPipeline` (cmd → decoder dispatch), - * - the uploaded-file cache shared between `upload_*_file` and - * `send_msg`, + * - the `IncomingPacketPipeline` (cmd → decoder → emit on bus), + * - the uploaded-file cache (shared between `upload_*_file` and + * `send_msg`), * - the monotonic `clientSequence` / `messageRandom` counters. * - * Subclasses only have to provide: + * The transport is opaque: `Account` only calls `bridge.sendRawPacket` + * and registers a single `setPacketHandler` so all incoming packets + * flow into its pipeline. Swap the transport (hook → protocol) and + * everything above keeps working unchanged. * - * 1. `kind` / `id` — discriminators for `BridgeManager` bookkeeping - * and diagnostics. - * 2. `sendRawPacket` — the actual wire-level transport. `InjectBridge` - * forwards to a `PacketSender` (the hook named-pipe client); - * `ProtocolBridge` will eventually forward to a long-lived TCP - * protocol client. - * - * The base class is intentionally abstract: callers never write - * `new Bridge(...)`. Tests that want to exercise the common - * pipeline / identity logic subclass `Bridge` (supplying the two - * abstract members) or instantiate `InjectBridge` directly. + * Lifecycle is managed by `AccountManager`: the manager subscribes to + * `BridgeManager` add/remove callbacks, materialises an `Account` on + * the way up, and calls `dispose()` on the way down. OneBot consumers + * see `AccountInterface`; never `Account` itself. */ -export abstract class Bridge implements BridgeInterface { - abstract readonly kind: BridgeKind; - abstract readonly id: string; - +export class Account implements AccountInterface { + readonly kind: BridgeKind; + readonly id: string; readonly uin: string; readonly identity: IdentityService; readonly events = new BridgeEventBus(); readonly apis: ApiHub; - private readonly pipeline: IncomingPacketPipeline; + private readonly transport_: BridgeInterface; + private readonly pipeline_: IncomingPacketPipeline; private static readonly UPLOADED_FILE_CACHE_MAX = 1024; private readonly uploadedFileMeta_ = new Map(); private clientSeq_ = 100000000 + (Date.now() % 1000000000); private msgRandom_ = (Date.now() & 0xFFFFFFFF) >>> 0; private disposed_ = false; - constructor(identity: IdentityService) { + /** + * @param bridge The low-level transport this account rides on top + * of. `Account` calls `bridge.sendRawPacket` and + * subscribes via `bridge.setPacketHandler`. + * @param identity Optional pre-built `IdentityService`. The default + * opens the on-disk SQLite store at + * `data//snowluma_identity.db`; tests usually + * pass `IdentityService.memory(uin)` to avoid touching + * the filesystem. + */ + constructor(bridge: BridgeInterface, identity: IdentityService = IdentityService.openForUin(bridge.uin)) { + this.transport_ = bridge; + this.kind = bridge.kind; + this.id = bridge.id; + this.uin = bridge.uin; this.identity = identity; - this.uin = identity.uin; this.apis = buildApiHub(this); this.identity.setFetcher({ fetchProfile: (uin) => this.apis.contacts.fetchUserProfile(uin), fetchGroupMemberList: (gid) => this.apis.contacts.fetchGroupMemberList(gid), }); - this.pipeline = new IncomingPacketPipeline({ + this.pipeline_ = new IncomingPacketPipeline({ identity: this.identity, events: this.events, refreshMemberCache: (groupId, refreshGroupList, forceMemberList) => @@ -90,43 +97,47 @@ export abstract class Bridge implements BridgeInterface { } }, }); - this.pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush); + this.pipeline_.registerCmd(MSG_PUSH_CMD, parseMsgPush); + + // Subscribe to inbound packets from the transport. `Bridge` only + // ever supports a single subscriber (us); the `BridgeAdapter` + // pumps packets through `bridge.deliverPacket`. + bridge.setPacketHandler((pkt: PacketInfo) => this.pipeline_.process(pkt)); } - // ─── BridgeInterface plumbing ────────────────────────────── - - onPacket(packet: PacketInfo): void { - this.pipeline.process(packet); - } + // ─── AccountInterface plumbing ───────────────────────────────── dispose(): void { if (this.disposed_) return; this.disposed_ = true; + this.transport_.setPacketHandler(null); this.identity.close(); this.events.clear(); } get isDisposed(): boolean { return this.disposed_; } - // ─── Transport (abstract — implemented per-subclass) ──────────── + // ─── Transport (proxied to the underlying Bridge) ────────────── - abstract sendRawPacket( + async sendRawPacket( serviceCmd: string, body: Uint8Array, timeoutMs?: number, - ): Promise; + ): Promise { + return this.transport_.sendRawPacket(serviceCmd, body, timeoutMs); + } - // ─── Pipeline registration (used by tests + extra cmd modules) ────── + // ─── Pipeline registration (used by tests + extra cmd modules) ─ registerCmd(cmd: string, parser: CmdParser): void { - this.pipeline.registerCmd(cmd, parser); + this.pipeline_.registerCmd(cmd, parser); } handlesCmd(cmd: string): boolean { - return this.pipeline.handlesCmd(cmd); + return this.pipeline_.handlesCmd(cmd); } - // ─── Send-side protocol helpers (shared sequence generators) ──────── + // ─── Send-side protocol helpers (shared sequence generators) ─── nextClientSequence(): number { return ++this.clientSeq_; @@ -137,11 +148,11 @@ export abstract class Bridge implements BridgeInterface { return this.msgRandom_ & 0x7FFFFFFF; } - // ─── Uploaded-file cache ────────────────────────────────── + // ─── Uploaded-file cache ─────────────────────────────────────── rememberUploadedFile(meta: UploadedFileMeta): void { if (!meta.fileId) return; - if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) { + if (this.uploadedFileMeta_.size >= Account.UPLOADED_FILE_CACHE_MAX) { // Map iteration order is insertion order — drop the oldest. const oldest = this.uploadedFileMeta_.keys().next().value; if (oldest !== undefined) this.uploadedFileMeta_.delete(oldest); @@ -154,13 +165,13 @@ export abstract class Bridge implements BridgeInterface { return this.uploadedFileMeta_.get(fileId); } - // ─── Identity convenience ────────────────────────────────── + // ─── Identity convenience ────────────────────────────────────── async resolveUserUid(uin: number, groupId?: number): Promise { return this.identity.resolveUid(uin, groupId); } - // ─── Internal helpers ───────────────────────────────────── + // ─── Internal helpers ────────────────────────────────────────── private async refreshMemberCache( groupId: number, @@ -175,44 +186,3 @@ export abstract class Bridge implements BridgeInterface { return true; } } -export interface SendMessageReceipt { - messageId: number; - sequence: number; - clientSequence: number; - random: number; - timestamp: number; -} - -export interface UploadedFileMeta { - fileId: string; - scope: 'group' | 'private'; - /** Group id if scope='group', else `undefined`. */ - groupId?: number; - /** Friend uin if scope='private', else `undefined`. */ - userId?: number; - fileName: string; - fileSize: number; - fileMd5: Uint8Array; - fileSha1: Uint8Array; - /** Server-issued hash returned alongside the upload (private only). */ - fileHash?: string; - /** Insert time — used to evict the oldest entry when the cache fills. */ - rememberedAt: number; -} - -export interface DownloadRKeyInfo { - rkey: string; - ttlSeconds: number; - storeId: number; - createTime: number; - type: number; -} - -export interface ClientKeyInfo { - clientKey: string; - expireTime: string; - keyIndex: string -} -export { AiVoiceChatType }; -export type { AiVoiceCategory, StrangerStatus }; - diff --git a/packages/core/src/bridge/apis/contacts.ts b/packages/core/src/account/apis/contacts.ts similarity index 92% rename from packages/core/src/bridge/apis/contacts.ts rename to packages/core/src/account/apis/contacts.ts index 6ae4f411..9798c9a4 100644 --- a/packages/core/src/bridge/apis/contacts.ts +++ b/packages/core/src/account/apis/contacts.ts @@ -12,8 +12,22 @@ import type { QQGroupInfo, UserProfileInfo, } from '@snowluma/protocol/qq-info'; -import type { DownloadRKeyInfo } from '../bridge'; -import type { BridgeContext } from '../bridge-context'; +import type { AccountContext } from '../account-context'; + +/** + * One row of an `OidbSvcTrpcTcp.0x9067_202` (download rkey) response. + * Cached for the duration of `ttlSeconds` and consumed by the OneBot + * media-URL resolver / message converter when a download URL must be + * minted on the fly. Lives at the apis layer (not on `Bridge`) because + * only `apis.contacts.fetchDownloadRKeys` materialises these rows. + */ +export interface DownloadRKeyInfo { + rkey: string; + ttlSeconds: number; + storeId: number; + createTime: number; + type: number; +} // ─── Helpers (previously in bridge-contacts.ts) ─────────────────── @@ -63,7 +77,7 @@ export class ContactsApi { private memberListInflight = new Map>(); private memberListLastFetch = new Map(); - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: AccountContext) { } async fetchFriendList(): Promise { const friends: FriendInfo[] = []; diff --git a/packages/core/src/bridge/apis/extras.ts b/packages/core/src/account/apis/extras.ts similarity index 96% rename from packages/core/src/bridge/apis/extras.ts rename to packages/core/src/account/apis/extras.ts index cd78f577..54a64759 100644 --- a/packages/core/src/bridge/apis/extras.ts +++ b/packages/core/src/account/apis/extras.ts @@ -5,7 +5,7 @@ import { } from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list'; import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status'; import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo'; -import type { BridgeContext } from '../bridge-context'; +import type { AccountContext } from '../account-context'; import type { MediaIndexNode } from './shared'; // ─────────────── public types (re-exported from bridge.ts as before) ─── @@ -27,7 +27,7 @@ export interface AiVoiceItem { } export class ExtrasApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: AccountContext) { } // ─────────────── Group todo (0xF90) ─────────────── diff --git a/packages/core/src/bridge/apis/forward.ts b/packages/core/src/account/apis/forward.ts similarity index 98% rename from packages/core/src/bridge/apis/forward.ts rename to packages/core/src/account/apis/forward.ts index 86d0b9da..f03b8c1f 100644 --- a/packages/core/src/bridge/apis/forward.ts +++ b/packages/core/src/account/apis/forward.ts @@ -7,18 +7,16 @@ import type { SendLongMsgResp, } from '@snowluma/proto-defs/longmsg'; import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message'; +import type { BridgeContext } from '@snowluma/protocol/bridge-context'; import { buildSendElems } from '@snowluma/protocol/element-builder'; import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events'; import { parseMsgPush } from '@snowluma/protocol/msg-push'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import { randomUUID } from 'crypto'; import { gunzipSync, gzipSync } from 'zlib'; -import type { Bridge } from '../bridge'; -import type { BridgeContext } from '../bridge-context'; +import type { AccountContext } from '../account-context'; import { resolveSelfUid, toInt } from './shared'; -function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } - // Module-scoped cache, keyed by res_id. Survives only for the lifetime // of the process — that's enough because OneBot clients typically // resolve a forward immediately after receiving the parent message. @@ -62,7 +60,7 @@ function hexToBytesLocal(hex: string): Uint8Array { } async function buildForwardPushBody( - bridge: Bridge, + bridge: BridgeContext, node: ForwardNodePayload, groupId?: number, userUid?: string, @@ -203,7 +201,7 @@ function previewFromElements(elements: MessageElement[]): string { } export class ForwardApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: AccountContext) { } async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise { const { resId } = await this.uploadRecursive(nodes, groupId, userId); @@ -233,7 +231,7 @@ export class ForwardApi { throw new Error('forward nodes are required'); } - const bridge = asBridge(this.ctx); + const bridge = this.ctx; // For a private forward to `userId`, any image/record/video inside a node // needs the recipient's uid as upload scene. Resolve it once up-front, @@ -378,7 +376,7 @@ export class ForwardApi { } async fetch(resId: string): Promise { - const bridge = asBridge(this.ctx); + const bridge = this.ctx; const cached = forwardResCache.get(resId); if (cached) { return cached.map(node => ({ diff --git a/packages/core/src/bridge/apis/friend.ts b/packages/core/src/account/apis/friend.ts similarity index 90% rename from packages/core/src/bridge/apis/friend.ts rename to packages/core/src/account/apis/friend.ts index 98208352..e1a541bf 100644 --- a/packages/core/src/bridge/apis/friend.ts +++ b/packages/core/src/account/apis/friend.ts @@ -1,10 +1,10 @@ import { DeleteFriend } from '@snowluma/protocol/oidb-services/friend/delete-friend'; import { HandleFriendRequest } from '@snowluma/protocol/oidb-services/friend/handle-friend-request'; import { SetFriendRemark } from '@snowluma/protocol/oidb-services/friend/set-friend-remark'; -import type { BridgeContext } from '../bridge-context'; +import type { AccountContext } from '../account-context'; export class FriendApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: AccountContext) { } /** * Accept or reject an inbound friend request. `uidOrFlag` is either a diff --git a/packages/core/src/bridge/apis/group-admin.ts b/packages/core/src/account/apis/group-admin.ts similarity index 96% rename from packages/core/src/bridge/apis/group-admin.ts rename to packages/core/src/account/apis/group-admin.ts index 9951ddec..de8b5e04 100644 --- a/packages/core/src/bridge/apis/group-admin.ts +++ b/packages/core/src/account/apis/group-admin.ts @@ -12,10 +12,10 @@ import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card'; import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search'; import { SetSpecialTitle } from '@snowluma/protocol/oidb-services/group-admin/set-special-title'; -import type { BridgeContext } from '../bridge-context'; +import type { AccountContext } from '../account-context'; export class GroupAdminApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: AccountContext) { } muteMember(groupId: number, userId: number, duration: number): Promise { return MuteMember.invoke(this.ctx, { groupId, userId, duration }); diff --git a/packages/core/src/bridge/apis/group-album.ts b/packages/core/src/account/apis/group-album.ts similarity index 98% rename from packages/core/src/bridge/apis/group-album.ts rename to packages/core/src/account/apis/group-album.ts index 7a8b1205..84a0067a 100644 --- a/packages/core/src/bridge/apis/group-album.ts +++ b/packages/core/src/account/apis/group-album.ts @@ -12,7 +12,7 @@ import type { } from '@snowluma/proto-defs/oidb-actions/group-album'; import { getGroupAlbumList, uploadImageToGroupAlbum } from '@snowluma/protocol/web/group-album'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import type { BridgeContext } from '../bridge-context'; +import type { AccountContext } from '../account-context'; function convertBigIntToString(obj: unknown): JsonValue { @@ -31,7 +31,7 @@ function convertBigIntToString(obj: unknown): JsonValue { } export class GroupAlbumApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: AccountContext) { } // 列出群相册(基于 qzone.qq.com 的 HTTP Cookie)。 async list(groupId: number): Promise { diff --git a/packages/core/src/bridge/apis/group-file.ts b/packages/core/src/account/apis/group-file.ts similarity index 98% rename from packages/core/src/bridge/apis/group-file.ts rename to packages/core/src/account/apis/group-file.ts index 86920988..07d7e470 100644 --- a/packages/core/src/bridge/apis/group-file.ts +++ b/packages/core/src/account/apis/group-file.ts @@ -4,8 +4,7 @@ import type { FileUploadExt } from '@snowluma/proto-defs/highway'; import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway'; import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '@snowluma/protocol/highway/utils'; import { protobuf_encode } from '@snowluma/proton'; -import type { Bridge } from '../bridge'; -import type { BridgeContext } from '../bridge-context'; +import type { AccountContext } from '../account-context'; import { resolveSelfUid, toInt, type MediaIndexNode } from './shared'; import { CreateGroupFolder } from '@snowluma/protocol/oidb-services/group-file/create-group-folder'; @@ -28,8 +27,6 @@ import { ensureRetCodeZero } from '@snowluma/protocol/oidb-services/shared'; const log = createLogger('GroupFile'); -function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } - // ─────────────── public result types ─────────────── export interface GroupFileInfo { @@ -217,7 +214,7 @@ function buildPrivateFileUploadExt( } export class GroupFileApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: AccountContext) { } // ─────────────── publish (group file → chat) ─────────────── @@ -241,7 +238,7 @@ export class GroupFileApi { folderId = '/', uploadFile = true, ): Promise { - const bridge = asBridge(this.ctx); + const bridge = this.ctx; // Group/private files may legitimately be up to 4 GiB on QQ's wire, // so override the default 1 GiB cap with the protocol ceiling. const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES); @@ -341,7 +338,7 @@ export class GroupFileApi { name = '', uploadFile = true, ): Promise { - const bridge = asBridge(this.ctx); + const bridge = this.ctx; const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES); if (!loaded.bytes.length) throw new Error('private file is empty'); @@ -580,7 +577,7 @@ export class GroupFileApi { } async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise { - const bridge = asBridge(this.ctx); + const bridge = this.ctx; const selfUid = await resolveSelfUid(bridge); void userId; const result = await GetPrivateFileUrl.invoke(this.ctx, { selfUid, fileId, fileHash }); @@ -627,7 +624,7 @@ export class GroupFileApi { } async getPrivatePttUrl(node: MediaIndexNode): Promise { - const bridge = asBridge(this.ctx); + const bridge = this.ctx; const selfUid = await resolveSelfUid(bridge); return GetPrivatePttUrl.invoke(this.ctx, { selfUid, node }); } @@ -637,7 +634,7 @@ export class GroupFileApi { } async getPrivateVideoUrl(node: MediaIndexNode): Promise { - const bridge = asBridge(this.ctx); + const bridge = this.ctx; const selfUid = await resolveSelfUid(bridge); return GetPrivateVideoUrl.invoke(this.ctx, { selfUid, node }); } diff --git a/packages/core/src/bridge/apis/index.ts b/packages/core/src/account/apis/index.ts similarity index 86% rename from packages/core/src/bridge/apis/index.ts rename to packages/core/src/account/apis/index.ts index 831b223b..048c1da3 100644 --- a/packages/core/src/bridge/apis/index.ts +++ b/packages/core/src/account/apis/index.ts @@ -1,4 +1,4 @@ -import type { BridgeContext } from '../bridge-context'; +import type { AccountContext } from '../account-context'; import { ContactsApi } from './contacts'; import { ExtrasApi } from './extras'; import { ForwardApi } from './forward'; @@ -47,7 +47,7 @@ export interface ApiHub { * runtime-mutated `apis.xxx` slots, neither of which is worth the * complexity for ~13 small classes. */ -export function buildApiHub(ctx: BridgeContext): ApiHub { +export function buildApiHub(ctx: AccountContext): ApiHub { return { message: new MessageApi(ctx), contacts: new ContactsApi(ctx), @@ -67,16 +67,21 @@ export function buildApiHub(ctx: BridgeContext): ApiHub { // Re-export the Api classes themselves so callers can write // `import type { MessageApi } from '@snowluma/core/.../apis'` for // signature use. Concrete instances always come from `bridge.apis.*`. -export { ContactsApi } from './contacts'; -export { ExtrasApi } from './extras'; +export { ContactsApi, type DownloadRKeyInfo } from './contacts'; +export { + AiVoiceChatType, ExtrasApi, type AiVoiceCategory, + type AiVoiceItem, + type StrangerStatus +} from './extras'; export { ForwardApi } from './forward'; export { FriendApi } from './friend'; export { GroupAdminApi } from './group-admin'; export { GroupAlbumApi } from './group-album'; export { GroupFileApi } from './group-file'; export { InteractionApi } from './interaction'; -export { MessageApi } from './message'; +export { MessageApi, type SendMessageReceipt } from './message'; export { MiscApi } from './misc'; export { ProfileApi } from './profile'; -export { WebApi } from './web'; +export { type MediaIndexNode } from './shared'; +export { WebApi, type ClientKeyInfo, type WebHonorInfo, type WebNoticeInfo } from './web'; diff --git a/packages/core/src/bridge/apis/interaction.ts b/packages/core/src/account/apis/interaction.ts similarity index 96% rename from packages/core/src/bridge/apis/interaction.ts rename to packages/core/src/account/apis/interaction.ts index 4ace0f61..45958d74 100644 --- a/packages/core/src/bridge/apis/interaction.ts +++ b/packages/core/src/account/apis/interaction.ts @@ -12,10 +12,10 @@ import { SetEssence } from '@snowluma/protocol/oidb-services/interaction/set-ess import { FetchReactionSummary } from '@snowluma/protocol/oidb-services/reaction/fetch-reaction-summary'; import { GetEmojiLikes } from '@snowluma/protocol/oidb-services/reaction/get-emoji-likes'; import { SetReaction } from '@snowluma/protocol/oidb-services/reaction/set-reaction'; -import type { BridgeContext } from '../bridge-context'; +import type { AccountContext } from '../account-context'; export class InteractionApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: AccountContext) { } sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise { return SendPoke.invoke(this.ctx, { isGroup, peerUin, targetUin }); diff --git a/packages/core/src/bridge/apis/message.ts b/packages/core/src/account/apis/message.ts similarity index 94% rename from packages/core/src/bridge/apis/message.ts rename to packages/core/src/account/apis/message.ts index 7b7cbc9b..7cf26baf 100644 --- a/packages/core/src/bridge/apis/message.ts +++ b/packages/core/src/account/apis/message.ts @@ -11,21 +11,26 @@ import type { import { buildSendElems } from '@snowluma/protocol/element-builder'; import type { MessageElement } from '@snowluma/protocol/events'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import type { BridgeContext } from '../bridge-context'; -// `Bridge` is imported as a type only so we can narrow `ctx` back to -// the concrete Bridge instance when passing it to `buildSendElems` -// (which still takes `Bridge` because the highway upload helpers it -// transitively calls each take `Bridge` — refactoring those is a -// separate concern that doesn't need to land alongside the Api split). -// -// At runtime `ctx` IS the Bridge instance that constructed this -// MessageApi — `buildApiHub(ctx)` passes the Bridge itself. -import type { Bridge, SendMessageReceipt } from '../bridge'; +import type { AccountContext } from '../account-context'; + +/** + * Receipt returned by every typed `send*Message` call. The OneBot + * adapter feeds these into its `MessageStore` so later `recall_msg` + * actions can resolve the wire-level coordinates (sequence + random) + * from the `message_id` it previously emitted. + */ +export interface SendMessageReceipt { + messageId: number; + sequence: number; + clientSequence: number; + random: number; + timestamp: number; +} const SEND_MSG_CMD = 'MessageSvc.PbSendMsg'; export class MessageApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: AccountContext) { } /** * Send a message to a QQ group. @@ -41,7 +46,7 @@ export class MessageApi { async sendGroup(groupId: number, elements: MessageElement[]): Promise { if (elements.length === 0) throw new Error('message is empty'); - const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, groupId }); + const protoElems = await buildSendElems(elements, { bridge: this.ctx, groupId }); const random = this.ctx.nextMessageRandom(); const request = protobuf_encode({ @@ -97,7 +102,7 @@ export class MessageApi { userUid = await this.ctx.resolveUserUid(userUin); } - const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, userUid }); + const protoElems = await buildSendElems(elements, { bridge: this.ctx, userUid }); const random = this.ctx.nextMessageRandom(); const clientSeq = this.ctx.nextClientSequence(); diff --git a/packages/core/src/bridge/apis/misc.ts b/packages/core/src/account/apis/misc.ts similarity index 95% rename from packages/core/src/bridge/apis/misc.ts rename to packages/core/src/account/apis/misc.ts index 0e78432e..4ab2dc97 100644 --- a/packages/core/src/bridge/apis/misc.ts +++ b/packages/core/src/account/apis/misc.ts @@ -4,14 +4,14 @@ import type { MiniAppShareResp, } from '@snowluma/proto-defs/oidb-actions/base'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import type { BridgeContext } from '../bridge-context'; // Migrated OIDB cmds — facade methods are one-line forwarders. import { ClickInlineKeyboardButton } from '@snowluma/protocol/oidb-services/misc/click-inline-keyboard-button'; import { SendGroupSign } from '@snowluma/protocol/oidb-services/misc/send-group-sign'; import { TranslateEnToZh } from '@snowluma/protocol/oidb-services/misc/translate-en-to-zh'; +import type { AccountContext } from '../account-context'; export class MiscApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: AccountContext) { } translateEn2Zh(words: string[]): Promise { return TranslateEnToZh.invoke(this.ctx, { words }); diff --git a/packages/core/src/bridge/apis/profile.ts b/packages/core/src/account/apis/profile.ts similarity index 94% rename from packages/core/src/bridge/apis/profile.ts rename to packages/core/src/account/apis/profile.ts index 309b717e..0315e713 100644 --- a/packages/core/src/bridge/apis/profile.ts +++ b/packages/core/src/account/apis/profile.ts @@ -13,13 +13,10 @@ import { SetInputStatus } from '@snowluma/protocol/oidb-services/profile/set-inp import { SetProfile } from '@snowluma/protocol/oidb-services/profile/set-profile'; import { SetSelfLongNick } from '@snowluma/protocol/oidb-services/profile/set-self-long-nick'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import type { Bridge } from '../bridge'; -import type { BridgeContext } from '../bridge-context'; - -function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } +import type { AccountContext } from '../account-context'; export class ProfileApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: AccountContext) { } // ─────────────── status / profile setters ─────────────── @@ -82,7 +79,7 @@ export class ProfileApi { } async setAvatar(source: string): Promise { - const bridge = asBridge(this.ctx); + const bridge = this.ctx; const loaded = await loadBinarySource(source, 'avatar'); if (!loaded.bytes.length) throw new Error('avatar file is empty'); @@ -102,7 +99,7 @@ export class ProfileApi { * Source ref: Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs#GroupSetAvatar. */ async setGroupAvatar(groupId: number, source: string): Promise { - const bridge = asBridge(this.ctx); + const bridge = this.ctx; const loaded = await loadBinarySource(source, 'group-avatar'); if (!loaded.bytes.length) throw new Error('group avatar file is empty'); diff --git a/packages/core/src/bridge/apis/shared.ts b/packages/core/src/account/apis/shared.ts similarity index 93% rename from packages/core/src/bridge/apis/shared.ts rename to packages/core/src/account/apis/shared.ts index 09ff7b8d..7bbcb9bb 100644 --- a/packages/core/src/bridge/apis/shared.ts +++ b/packages/core/src/account/apis/shared.ts @@ -1,4 +1,5 @@ -import type { Bridge } from '../bridge'; + +import type { BridgeContext } from '@snowluma/protocol/bridge-context'; export function toInt(value: unknown): number { if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value); @@ -31,7 +32,7 @@ export function ensureRetCodeZero(operation: string, code: unknown, msg: unknown * `selfProfile`; forward/profile actions need this fast path before * warmup completes. */ -export async function resolveSelfUid(bridge: Bridge): Promise { +export async function resolveSelfUid(bridge: BridgeContext): Promise { let selfUid = bridge.identity.selfUid; if (selfUid) return selfUid; diff --git a/packages/core/src/bridge/apis/web.ts b/packages/core/src/account/apis/web.ts similarity index 90% rename from packages/core/src/bridge/apis/web.ts rename to packages/core/src/account/apis/web.ts index 6198f924..ed3388c9 100644 --- a/packages/core/src/bridge/apis/web.ts +++ b/packages/core/src/account/apis/web.ts @@ -1,3 +1,4 @@ +import type { BridgeContext } from '@snowluma/protocol/bridge-context'; import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key'; import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey'; import { getGroupEssenceMsg, getGroupEssenceMsgAll, type GroupEssenceMsgRet } from '@snowluma/protocol/web/group-essence'; @@ -10,10 +11,7 @@ import { type SetNoticeRetSuccess, } from '@snowluma/protocol/web/group-notice'; import { RequestUtil } from '@snowluma/protocol/web/request-util'; -import type { Bridge } from '../bridge'; -import type { BridgeContext } from '../bridge-context'; - -function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } +import type { AccountContext } from '../account-context'; export type ClientKeyInfo = NamespaceClientKeyInfo; @@ -44,15 +42,15 @@ export interface WebNoticeInfo { // ─────────────── private helpers (cookie acquisition) ─────────────── -function forceFetchClientKeyInner(bridge: Bridge): Promise { +function forceFetchClientKeyInner(bridge: BridgeContext): Promise { return ForceFetchClientKey.invoke(bridge); } -function getPSkey(bridge: Bridge, domainList: string[]): Promise<{ domainPskeyMap: Map }> { +function getPSkey(bridge: BridgeContext, domainList: string[]): Promise<{ domainPskeyMap: Map }> { return GetPskey.invoke(bridge, { domainList }); } -async function getCookies(bridge: Bridge, domain: string): Promise> { +async function getCookies(bridge: BridgeContext, domain: string): Promise> { const ClientKeyData = await forceFetchClientKeyInner(bridge); // Build the ptlogin2 jump URL: this is the canonical way for the @@ -82,7 +80,7 @@ async function getCookies(bridge: Bridge, domain: string): Promise { +async function getSKey(bridge: BridgeContext): Promise { const ClientKeyData = await forceFetchClientKeyInner(bridge); if (!ClientKeyData.clientKey) { @@ -119,23 +117,23 @@ function getBknFromSKey(skey: string): number { } export class WebApi { - constructor(private readonly ctx: BridgeContext) { } + constructor(private readonly ctx: AccountContext) { } // ─────────────── cookie / token primitives ─────────────── async forceFetchClientKey(): Promise { - return forceFetchClientKeyInner(asBridge(this.ctx)); + return forceFetchClientKeyInner(this.ctx); } /** Fetch the cookie jar for a `qq.com` subdomain. Used by GroupAlbumApi * (qzone.qq.com) and by every other web helper here. */ async getCookies(domain: string): Promise> { - return getCookies(asBridge(this.ctx), domain); + return getCookies(this.ctx, domain); } /** Cookies for `domain` joined into the canonical "k=v; k=v" header form. */ async getCookiesStr(domain: string): Promise { - const cookieObject = await getCookies(asBridge(this.ctx), domain); + const cookieObject = await getCookies(this.ctx, domain); return Object.entries(cookieObject) .map(([key, value]) => `${key}=${value}`) .join('; '); @@ -143,7 +141,7 @@ export class WebApi { /** CSRF token == bkn(skey) — used by qzone / qun web APIs. */ async getCsrfToken(): Promise { - const skey = await getSKey(asBridge(this.ctx)); + const skey = await getSKey(this.ctx); if (!skey) { throw new Error('SKey is Empty'); } @@ -152,7 +150,7 @@ export class WebApi { /** Returns the OneBot `get_credentials` payload (cookie string + bkn). */ async getCredentials(domain: string): Promise<{ cookies: string; token: number; csrf_token: number }> { - const cookieObject = await getCookies(asBridge(this.ctx), domain); + const cookieObject = await getCookies(this.ctx, domain); const cookiesStr = Object.entries(cookieObject) .map(([key, value]) => `${key}=${value}`) .join('; '); @@ -171,7 +169,7 @@ export class WebApi { /** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */ async getEssence(groupId: number, pageStart = 0, pageLimit = 50): Promise { - const bridge = asBridge(this.ctx); + const bridge = this.ctx; const groupCode = groupId.toString(); const cookieObject = await getCookies(bridge, 'qun.qq.com'); const essenceData = await getGroupEssenceMsg(cookieObject, groupCode, pageStart, pageLimit); @@ -180,7 +178,7 @@ export class WebApi { /** Walks every page and returns the concatenated result. */ async getEssenceAll(groupId: number): Promise { - const bridge = asBridge(this.ctx); + const bridge = this.ctx; const groupCode = groupId.toString(); const cookieObject = await getCookies(bridge, 'qun.qq.com'); return await getGroupEssenceMsgAll(cookieObject, groupCode); @@ -189,7 +187,7 @@ export class WebApi { // ─────────────── group honor ─────────────── async getHonorInfo(groupId: number, type: WebHonorType | string): Promise { - const bridge = asBridge(this.ctx); + const bridge = this.ctx; const groupCode = groupId.toString(); const cookieObject = await getCookies(bridge, 'qun.qq.com'); @@ -238,7 +236,7 @@ export class WebApi { confirm_required?: number; }, ): Promise { - const bridge = asBridge(this.ctx); + const bridge = this.ctx; const groupCode = groupId.toString(); const cookieObject = await getCookies(bridge, 'qun.qq.com'); @@ -288,7 +286,7 @@ export class WebApi { } async getNotice(groupId: number): Promise { - const bridge = asBridge(this.ctx); + const bridge = this.ctx; const groupCode = groupId.toString(); const cookieObject = await getCookies(bridge, 'qun.qq.com'); @@ -329,7 +327,7 @@ export class WebApi { } async deleteNotice(groupId: number, fid: string): Promise { - const bridge = asBridge(this.ctx); + const bridge = this.ctx; const groupCode = groupId.toString(); const cookieObject = await getCookies(bridge, 'qun.qq.com'); return await deleteGroupNoticeHttp(cookieObject, groupCode, fid); diff --git a/packages/core/src/bridge/bridge-context.ts b/packages/core/src/bridge/bridge-context.ts deleted file mode 100644 index ef146e85..00000000 --- a/packages/core/src/bridge/bridge-context.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { BridgeContext as BaseBridgeContext } from '@snowluma/protocol/bridge-context'; -import type { ApiHub } from './apis'; - -export interface BridgeContext extends BaseBridgeContext { - readonly apis: ApiHub; -} -export type { UploadedFileMeta } from '@snowluma/protocol/bridge-context'; - diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts deleted file mode 100644 index b208ea15..00000000 --- a/packages/core/src/bridge/bridge-interface.ts +++ /dev/null @@ -1,43 +0,0 @@ -import type { PacketInfo } from '@snowluma/common/protocol-types'; -import type { BridgeContext } from './bridge-context'; - -/** - * Discriminator for the two bridge implementations: - * - * - `'inject'` — backed by an in-process NTQQ hook (one or more - * QQ.exe processes injected with the SnowLuma DLL, - * talking over named pipes). - * - `'protocol'` — backed by a direct protocol client (no QQ.exe, - * no hook). Reserved for the future pure-protocol - * runtime; the concrete `ProtocolBridge` is a stub - * until that runtime lands. - * - * The kind is part of `BridgeInterface` so any consumer that genuinely - * needs to branch on transport (diagnostics, runtime-specific WebUI - * panels, …) can do so without `instanceof` checks against a concrete - * subclass. Day-to-day callers (OneBot, protocol APIs) MUST stay kind- - * agnostic — that's the whole point of the abstraction. - */ -export type BridgeKind = 'inject' | 'protocol'; - -/** - * The public surface every concrete bridge exposes. OneBot, protocol - * APIs and tests all consume this — never the concrete `Bridge` class - * — so swapping in a `ProtocolBridge` later is a transport change, not - * a business-logic change. - */ -export interface BridgeInterface extends BridgeContext { - /** Transport family this bridge is backed by. */ - readonly kind: BridgeKind; - /** Stable identity of the bridge inside `BridgeManager` (e.g. - * `'inject:3161592748'`). Unique per live bridge. */ - readonly id: string; - /** QQ number this bridge represents. Mirrors `identity.uin`. */ - readonly uin: string; - /** Inject a freshly received packet into the per-cmd dispatch - * pipeline. Called by the owning `BridgeAdapter`; never by OneBot. */ - onPacket(packet: PacketInfo): void; - /** Release identity DB handles, event subscribers, and any - * transport-side resources. Idempotent. */ - dispose(): void; -} diff --git a/packages/core/src/bridge/protocol-bridge.ts b/packages/core/src/bridge/protocol-bridge.ts deleted file mode 100644 index a37534ea..00000000 --- a/packages/core/src/bridge/protocol-bridge.ts +++ /dev/null @@ -1,52 +0,0 @@ -import type { SendPacketResult } from '@snowluma/common/packet-sender'; -import { IdentityService } from '@snowluma/protocol/identity-service'; -import { Bridge } from './bridge'; - -/** - * `ProtocolBridge` — the placeholder concrete bridge for the future - * pure-protocol runtime (no QQ.exe, no hook). It already participates - * in `BridgeManager` and `BridgeInterface` so the rest of the system - * (OneBot, protocol APIs, WebUI) can be wired against the abstract - * surface today and gain real protocol traffic later without further - * refactor. - * - * Until a `ProtocolClient` is wired in, `sendRawPacket` returns a - * structured "not implemented" failure rather than throwing, so the - * surrounding code still treats it as a regular transport-down result. - * - * NOTE: kept deliberately small. When the real protocol runtime lands, - * the constructor will accept a `ProtocolClient` (or similar transport - * handle), `sendRawPacket` will forward to it, and an inbound packet - * dispatcher will pump received frames through the inherited - * `onPacket` pipeline. - */ -export class ProtocolBridge extends Bridge { - readonly kind = 'protocol' as const; - - /** - * @param uin QQ number this bridge represents. - * @param identity Optional pre-built `IdentityService`. Defaults to - * the on-disk SQLite store keyed by `uin`. - */ - constructor(uin: string, identity: IdentityService = IdentityService.openForUin(uin)) { - super(identity); - } - - /** Stable, unique-per-account id used by `BridgeManager`. */ - get id(): string { return `protocol:${this.uin}`; } - - override async sendRawPacket( - serviceCmd: string, - body: Uint8Array, - timeoutMs?: number, - ): Promise { - void serviceCmd; void body; void timeoutMs; - return { - success: false, - gotResponse: false, - errorCode: -1, - errorMessage: 'protocol bridge transport is not yet implemented', - responseData: null, - }; - } -} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index a192db85..49bec39c 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,9 +1,8 @@ +import { BridgeManager, InjectBridgeAdapter, ProtocolBridgeAdapter } from '@snowluma/bridge'; import { closeLogger, createLogger } from '@snowluma/common/logger'; import { loadRuntimeConfig } from '@snowluma/common/runtime'; import { OneBotManager } from '@snowluma/onebot/manager'; -import { InjectBridgeAdapter } from './bridge/inject-adapter'; -import { BridgeManager } from './bridge/manager'; -import { ProtocolBridgeAdapter } from './bridge/protocol-adapter'; +import { AccountManager } from './account/account-manager'; const runtimeConfig = loadRuntimeConfig(); const log = createLogger('App'); @@ -18,6 +17,7 @@ async function main() { // so the architecture is exercised end-to-end). Both must be // registered BEFORE bridgeManager.start(). const bridgeManager = new BridgeManager(); + const accountManager = new AccountManager(); const oneBotManager = new OneBotManager(); const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad); @@ -28,9 +28,12 @@ async function main() { bridgeManager.registerAdapter(injectAdapter); bridgeManager.registerAdapter(new ProtocolBridgeAdapter()); - // OneBot subscribes to BridgeManager session events; bind before - // start() so the very first login is delivered. - oneBotManager.bind(bridgeManager); + // Layer chain: BridgeManager (transport pool) → AccountManager + // (wraps each primary bridge in an Account) → OneBotManager (one + // OneBotInstance per Account). Bind before start() so the very + // first login is delivered down the chain. + accountManager.bind(bridgeManager); + oneBotManager.bind(accountManager); await bridgeManager.start(); @@ -55,6 +58,7 @@ async function main() { const shutdown = (signal: string) => async () => { log.warn(`Shutting down (${signal})...`); oneBotManager.dispose(); + accountManager.dispose(); await bridgeManager.dispose(); await closeLogger(); process.exit(0); diff --git a/packages/core/tests/bridge-member-identity.test.ts b/packages/core/tests/account-member-identity.test.ts similarity index 60% rename from packages/core/tests/bridge-member-identity.test.ts rename to packages/core/tests/account-member-identity.test.ts index 58250bfb..5eec620c 100644 --- a/packages/core/tests/bridge-member-identity.test.ts +++ b/packages/core/tests/account-member-identity.test.ts @@ -1,9 +1,10 @@ +import { InjectBridge } from '@snowluma/bridge'; import type { PacketInfo } from '@snowluma/common/protocol-types'; import type { GroupMemberJoin, QQEventVariant } from '@snowluma/protocol/events'; import { IdentityService } from '@snowluma/protocol/identity-service'; import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info'; import { describe, expect, it } from 'vitest'; -import { InjectBridge } from '../src/bridge/inject-bridge'; +import { Account } from '../src/account/account'; const SELF_UIN = '10001'; const GROUP_ID = 123456789; @@ -34,28 +35,27 @@ function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo { }; } -class RefreshingBridge extends InjectBridge { - readonly memberFetches: Array<{ groupId: number; force: boolean }> = []; - - constructor(identity: IdentityService, private readonly refreshedMembers: GroupMemberInfo[]) { - super(identity.uin, identity); - // `fetchGroupMemberList` moved from Bridge onto `apis.contacts` - // under the #6 refactor — patch the method on the constructed - // ContactsApi instance to intercept calls + record them for - // assertions. (Direct property assignment works because the - // method is just an own property on the Api instance, not on - // its prototype.) - this.apis.contacts.fetchGroupMemberList = async ( - groupId: number, - options: { force?: boolean } = {}, - ): Promise => { - this.memberFetches.push({ groupId, force: Boolean(options.force) }); - for (const member of this.refreshedMembers) { - this.identity.updateGroupMember(groupId, member); - } - return this.refreshedMembers; - }; - } +/** + * `Account` wired up with a member-list interceptor. The interceptor + * lives on `account.apis.contacts.fetchGroupMemberList`; direct + * property assignment is enough because the ApiHub holds own-property + * methods, not prototype ones. + */ +function buildAccount(identity: IdentityService, refreshedMembers: GroupMemberInfo[]) { + const bridge = new InjectBridge(identity.uin); + const account = new Account(bridge, identity); + const memberFetches: Array<{ groupId: number; force: boolean }> = []; + account.apis.contacts.fetchGroupMemberList = async ( + groupId: number, + options: { force?: boolean } = {}, + ): Promise => { + memberFetches.push({ groupId, force: Boolean(options.force) }); + for (const member of refreshedMembers) { + account.identity.updateGroupMember(groupId, member); + } + return refreshedMembers; + }; + return { account, bridge, memberFetches }; } function makePacket(): PacketInfo { @@ -85,15 +85,15 @@ async function waitForEvent(events: GroupMemberJoin[]): Promise throw new Error('timed out waiting for group_member_join'); } -describe('Bridge group member identity refresh', () => { +describe('Account group member identity refresh', () => { it('forces a fresh member list before dispatching an unresolved join event', async () => { const member = makeGroupMember(22222, 'u_new_member'); const identity = IdentityService.memory(SELF_UIN); identity.rememberGroups([makeGroup()]); - const bridge = new RefreshingBridge(identity, [member]); + const { account, bridge, memberFetches } = buildAccount(identity, [member]); const seen: GroupMemberJoin[] = []; - bridge.registerCmd('test.member_join', () => [{ + account.registerCmd('test.member_join', () => [{ kind: 'group_member_join', time: 1710000000, selfUin: Number(SELF_UIN), @@ -103,20 +103,21 @@ describe('Bridge group member identity refresh', () => { userUid: member.uid, operatorUid: member.uid, }]); - bridge.events.on('group_member_join', (event) => { + account.events.on('group_member_join', (event) => { seen.push(event); }); - bridge.onPacket(makePacket()); + bridge.deliverPacket(makePacket()); const event = await waitForEvent(seen); - expect(bridge.memberFetches).toEqual([{ groupId: GROUP_ID, force: true }]); + expect(memberFetches).toEqual([{ groupId: GROUP_ID, force: true }]); expect(event.userUin).toBe(member.uin); expect(event.operatorUin).toBe(member.uin); }); it('remembers UID mappings from realtime request events', () => { - const bridge = new InjectBridge(SELF_UIN, IdentityService.memory(SELF_UIN)); + const bridge = new InjectBridge(SELF_UIN); + const account = new Account(bridge, IdentityService.memory(SELF_UIN)); const events: QQEventVariant[] = [ { kind: 'friend_request', @@ -140,12 +141,12 @@ describe('Bridge group member identity refresh', () => { }, ]; - bridge.registerCmd('test.request_identity', () => events); - bridge.onPacket(makeRequestPacket()); + account.registerCmd('test.request_identity', () => events); + bridge.deliverPacket(makeRequestPacket()); - expect(bridge.identity.findUidByUin(55555)).toBe('u_friend_request'); - expect(bridge.identity.findUidByUin(66666)).toBe('u_group_request'); - expect(bridge.identity.findUinByUid('u_friend_request')).toBe(55555); - expect(bridge.identity.findUinByUid('u_group_request')).toBe(66666); + expect(account.identity.findUidByUin(55555)).toBe('u_friend_request'); + expect(account.identity.findUidByUin(66666)).toBe('u_group_request'); + expect(account.identity.findUinByUid('u_friend_request')).toBe(55555); + expect(account.identity.findUinByUid('u_group_request')).toBe(66666); }); }); diff --git a/packages/core/tests/bridge-private-routing.test.ts b/packages/core/tests/account-private-routing.test.ts similarity index 59% rename from packages/core/tests/bridge-private-routing.test.ts rename to packages/core/tests/account-private-routing.test.ts index 42e57015..5611eccb 100644 --- a/packages/core/tests/bridge-private-routing.test.ts +++ b/packages/core/tests/account-private-routing.test.ts @@ -1,48 +1,80 @@ +import type { BridgeInterface } from '@snowluma/bridge'; import type { SendPacketResult } from '@snowluma/common/packet-sender'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action'; import type { FileExtra } from '@snowluma/proto-defs/message'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import { describe, expect, it, vi } from 'vitest'; +import { Account } from '../src/account/account'; vi.mock('@snowluma/protocol/element-builder', () => ({ buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]), })); -describe('Bridge private media routing', () => { +/** + * Thin fake transport — implements `BridgeInterface` directly without + * inheriting from `Bridge`, so each test gets a clean slate plus a + * single capture slot for the outbound body. The `Account` under test + * proxies `sendRawPacket` straight through. + */ +class FakeBridge implements BridgeInterface { + readonly kind = 'inject' as const; + readonly id = 'inject:test'; + capturedBody: Uint8Array | null = null; + private response_: SendPacketResult = { + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.from(protobuf_encode({ + result: 0, + errMsg: '', + privateSequence: 88, + timestamp1: 1710000000, + })), + }; + + constructor(public readonly uin: string) { } + + setResponse(resp: SendPacketResult): void { this.response_ = resp; } + + async sendRawPacket(_cmd: string, body: Uint8Array): Promise { + this.capturedBody = body; + return this.response_; + } + + setPacketHandler(_handler: ((pkt: PacketInfo) => void) | null): void { /* unused */ } + deliverPacket(_pkt: PacketInfo): void { /* unused */ } + dispose(): void { /* unused */ } +} + +describe('Account private media routing', () => { it('includes resolved uid in the final c2c send request for media messages', async () => { - const { Bridge } = await import('../src/bridge/bridge'); const { IdentityService } = await import('@snowluma/protocol/identity-service'); - class TestBridge extends Bridge { - readonly kind = 'inject' as const; - readonly id = 'inject:test'; - capturedBody: Uint8Array | null = null; + const bridge = new FakeBridge('10000'); + bridge.setResponse({ + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.from(protobuf_encode({ + result: 0, + errMsg: '', + privateSequence: 88, + timestamp1: 1710000000, + })), + }); - override async resolveUserUid(uin: number): Promise { - expect(uin).toBe(12345); - return 'u_peer_12345'; - } + const account = new Account(bridge, IdentityService.memory('10000')); + // resolveUserUid lookup needs an explicit override since the + // identity store has no mapping for the test peer. + account.resolveUserUid = vi.fn(async (uin: number) => { + expect(uin).toBe(12345); + return 'u_peer_12345'; + }); - override async sendRawPacket(serviceCmd: string, body: Uint8Array): Promise { - expect(serviceCmd).toBe('MessageSvc.PbSendMsg'); - this.capturedBody = body; - return { - success: true, - gotResponse: true, - errorCode: 0, - errorMessage: '', - responseData: Buffer.from(protobuf_encode({ - result: 0, - errMsg: '', - privateSequence: 88, - timestamp1: 1710000000, - })), - }; - } - } - - const bridge = new TestBridge(IdentityService.memory('10000')); - await bridge.apis.message.sendPrivate(12345, [{ type: 'video', url: 'file:///tmp/clip.mp4' } as any]); + await account.apis.message.sendPrivate(12345, [{ type: 'video', url: 'file:///tmp/clip.mp4' } as any]); expect(bridge.capturedBody).toBeInstanceOf(Uint8Array); const request = protobuf_decode(bridge.capturedBody as Uint8Array); @@ -61,27 +93,13 @@ describe('Bridge private media routing', () => { // BuildPacketBase` + `FileEntity.PackMessageContent`. Previous // implementation wrote c2c routing + richText.notOnlineFile + // c2cCmd=11 — the QQ-NT server rejected every c2c file send. - const { Bridge } = await import('../src/bridge/bridge'); const { IdentityService } = await import('@snowluma/protocol/identity-service'); - class TestBridge extends Bridge { - readonly kind = 'inject' as const; - readonly id = 'inject:test'; - capturedBody: Uint8Array | null = null; - override async sendRawPacket(_cmd: string, body: Uint8Array): Promise { - this.capturedBody = body; - return { - success: true, gotResponse: true, errorCode: 0, errorMessage: '', - responseData: Buffer.from(protobuf_encode({ - result: 0, errMsg: '', privateSequence: 88, timestamp1: 1710000000, - })), - }; - } - } - const bridge = new TestBridge(IdentityService.memory('10000')); + const bridge = new FakeBridge('10000'); + const account = new Account(bridge, IdentityService.memory('10000')); const fileMd5 = new Uint8Array([0xde, 0xad, 0xbe, 0xef]); - await bridge.apis.message.sendC2cFile(67890, 'u_peer_xyz', { + await account.apis.message.sendC2cFile(67890, 'u_peer_xyz', { fileId: 'uuid-abc-123', fileName: 'doc.txt', fileSize: 1024, @@ -113,10 +131,6 @@ describe('Bridge private media routing', () => { fileSize: 1024n, fileHash: 'hash-xyz', subcmd: 1, // server-required intake validator field - // dangerEvel and fileType are 0 — proto3 omits zero values on - // the wire, so they're not asserted here (matches Lagrange's - // behaviour: it sets `DangerEvel = 0` but protobuf-net also - // skips serialising default ints). }); expect(fileExtra?.file?.fileMd5).toEqual(fileMd5); // expireTime is now+7d; just sanity-check it landed (non-zero, plausible) diff --git a/packages/core/tests/actions/extras.test.ts b/packages/core/tests/actions/extras.test.ts index d062345f..ef25d64d 100644 --- a/packages/core/tests/actions/extras.test.ts +++ b/packages/core/tests/actions/extras.test.ts @@ -1,5 +1,3 @@ -import { describe, it, expect } from 'vitest'; -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { OidbGroupTodo, @@ -12,11 +10,13 @@ import type { OidbAiVoiceReq, OidbAiVoiceResp, } from '@snowluma/proto-defs/oidb-actions/media'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { describe, expect, it } from 'vitest'; // Post-namespace migration: ExtrasApi forwards 6 OIDB cmds through // namespaces under @snowluma/protocol/oidb-services/extras. Tests assert // against bridge.sendRawPacket directly. -import { ExtrasApi, AiVoiceChatType } from '../../src/bridge/apis/extras'; +import { AiVoiceChatType, ExtrasApi } from '../../src/account/apis/extras'; import { mockBridge } from './_helpers'; function packResponse(body: Uint8Array) { diff --git a/packages/core/tests/actions/forward-file.test.ts b/packages/core/tests/actions/forward-file.test.ts index dc67a058..c3e424e9 100644 --- a/packages/core/tests/actions/forward-file.test.ts +++ b/packages/core/tests/actions/forward-file.test.ts @@ -23,7 +23,7 @@ // Mirrors NapCat's `PacketMsgFileElement.{buildElement,buildContent}` // split. -import { describe, it, expect, vi } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; vi.mock('@snowluma/protocol/bridge-oidb', () => ({ runOidb: vi.fn(async () => new Uint8Array()), @@ -44,9 +44,9 @@ vi.mock('@snowluma/protocol/element-builder', () => ({ buildSendElems: buildSendElemsMock, })); -import { protobuf_encode } from '@snowluma/proton'; import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg'; -import { ForwardApi } from '../../src/bridge/apis/forward'; +import { protobuf_encode } from '@snowluma/proton'; +import { ForwardApi } from '../../src/account/apis/forward'; import { mockBridge } from './_helpers'; function uploadResponseWithResId(resId: string) { diff --git a/packages/core/tests/actions/forward-nested.test.ts b/packages/core/tests/actions/forward-nested.test.ts index 1d2c97d1..316a542d 100644 --- a/packages/core/tests/actions/forward-nested.test.ts +++ b/packages/core/tests/actions/forward-nested.test.ts @@ -16,12 +16,12 @@ // dev/Lagrange.Core/.../Message/Entity/MultiMsgEntity.cs:43-115 // dev/NapCatQQ/.../helper/forward-msg-builder.ts:52-122 -import { describe, it, expect, vi } from 'vitest'; -import { gunzipSync, inflateSync } from 'zlib'; -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import type { SendLongMsgReq, SendLongMsgResp, LongMsgResult } from '@snowluma/proto-defs/longmsg'; -import type { PushMsgBody } from '@snowluma/proto-defs/message'; import type { Elem } from '@snowluma/proto-defs/element'; +import type { LongMsgResult, SendLongMsgReq, SendLongMsgResp } from '@snowluma/proto-defs/longmsg'; +import type { PushMsgBody } from '@snowluma/proto-defs/message'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { describe, expect, it, vi } from 'vitest'; +import { gunzipSync, inflateSync } from 'zlib'; // Don't mock element-builder — we WANT the real forward preview // element to land in the encoded wire bytes so we can verify the @@ -39,7 +39,7 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({ uploadVideoMsgInfo: vi.fn(async () => new Uint8Array()), })); -import { ForwardApi } from '../../src/bridge/apis/forward'; +import { ForwardApi } from '../../src/account/apis/forward'; import { mockBridge } from './_helpers'; function uploadResponseWithResId(resId: string) { diff --git a/packages/core/tests/actions/forward.test.ts b/packages/core/tests/actions/forward.test.ts index fa424d0b..f39e8cff 100644 --- a/packages/core/tests/actions/forward.test.ts +++ b/packages/core/tests/actions/forward.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, vi } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; vi.mock('@snowluma/protocol/bridge-oidb', () => ({ runOidb: vi.fn(async () => new Uint8Array()), @@ -14,9 +14,9 @@ vi.mock('@snowluma/protocol/element-builder', () => ({ buildSendElems: vi.fn(async () => []), })); -import { protobuf_encode } from '@snowluma/proton'; import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg'; -import { ForwardApi } from '../../src/bridge/apis/forward'; +import { protobuf_encode } from '@snowluma/proton'; +import { ForwardApi } from '../../src/account/apis/forward'; import { mockBridge } from './_helpers'; function uploadResponseWithResId(resId: string) { diff --git a/packages/core/tests/actions/friend.test.ts b/packages/core/tests/actions/friend.test.ts index 2dba2c47..7e9af8eb 100644 --- a/packages/core/tests/actions/friend.test.ts +++ b/packages/core/tests/actions/friend.test.ts @@ -1,17 +1,17 @@ -import { describe, it, expect, vi } from 'vitest'; -import { protobuf_decode } from '@snowluma/proton'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { OidbDeleteFriend, OidbFriendRequestAction, OidbSetFriendRemark, } from '@snowluma/proto-defs/oidb-actions/base'; +import { protobuf_decode } from '@snowluma/proton'; +import { describe, expect, it, vi } from 'vitest'; // Post-namespace migration: FriendApi is a thin facade over the // namespaces under @snowluma/protocol/oidb-services/friend. Tests assert // against the bridge mock's sendRawPacket directly — no need for // module-level bridge-oidb mocks anymore. -import { FriendApi } from '../../src/bridge/apis/friend'; +import { FriendApi } from '../../src/account/apis/friend'; import { mockBridge } from './_helpers'; describe('apis/friend', () => { diff --git a/packages/core/tests/actions/group-admin.test.ts b/packages/core/tests/actions/group-admin.test.ts index 008d6fe8..407781bd 100644 --- a/packages/core/tests/actions/group-admin.test.ts +++ b/packages/core/tests/actions/group-admin.test.ts @@ -1,11 +1,9 @@ -import { describe, it, expect, vi } from 'vitest'; -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { - Oidb0x8a0Req, - Oidb0x8a7Resp, Oidb0x89a_0AddOption, Oidb0x89a_0Search, + Oidb0x8a0Req, + Oidb0x8a7Resp, Oidb0xf16Req, OidbGroupRequestAction, OidbKickMember, @@ -17,11 +15,13 @@ import type { OidbSetAdmin, OidbSpecialTitle, } from '@snowluma/proto-defs/oidb-actions/base'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { describe, expect, it, vi } from 'vitest'; // Post-namespace migration: GroupAdminApi forwards through namespaces // under @snowluma/protocol/oidb-services/group-admin. Tests assert // against bridge.sendRawPacket directly — no module-level mocks. -import { GroupAdminApi } from '../../src/bridge/apis/group-admin'; +import { GroupAdminApi } from '../../src/account/apis/group-admin'; import { mockBridge } from './_helpers'; function packResponse(body: Uint8Array) { diff --git a/packages/core/tests/actions/group-file.test.ts b/packages/core/tests/actions/group-file.test.ts index 2894ffa8..5ca4c330 100644 --- a/packages/core/tests/actions/group-file.test.ts +++ b/packages/core/tests/actions/group-file.test.ts @@ -1,18 +1,18 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { OidbGroupFileCountViewResp, + OidbGroupFileFolderResp, OidbGroupFileReq, OidbGroupFileResp, OidbGroupFileViewResp, - OidbGroupFileFolderResp, OidbGroupSendFileReq, } from '@snowluma/proto-defs/oidb-actions/group-file'; import type { - OidbPrivateFileUploadResp, NTV2RichMediaResp, + OidbPrivateFileUploadResp, } from '@snowluma/proto-defs/oidb-actions/media'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; // Post-namespace migration: GroupFileApi forwards single-OIDB methods // through namespaces under @snowluma/protocol/oidb-services/group-file. @@ -38,7 +38,7 @@ vi.mock('@snowluma/protocol/highway/utils', () => ({ })); import * as highwayClient from '@snowluma/protocol/highway'; -import { GroupFileApi } from '../../src/bridge/apis/group-file'; +import { GroupFileApi } from '../../src/account/apis/group-file'; import { mockBridge } from './_helpers'; function packResponse(body: Uint8Array) { diff --git a/packages/core/tests/actions/group-message.test.ts b/packages/core/tests/actions/group-message.test.ts index a607dedb..d09a0257 100644 --- a/packages/core/tests/actions/group-message.test.ts +++ b/packages/core/tests/actions/group-message.test.ts @@ -4,7 +4,7 @@ // after #6 commit 1 moved the recall + markRead helpers onto MessageApi // and #6 commit 6 absorbed setEssence into InteractionApi. -import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; vi.mock('@snowluma/protocol/bridge-oidb', () => ({ runOidb: vi.fn(async () => new Uint8Array()), @@ -13,7 +13,7 @@ vi.mock('@snowluma/protocol/bridge-oidb', () => ({ decodeOidbEnv: vi.fn(() => ({ body: {} })), })); -import { MessageApi } from '../../src/bridge/apis/message'; +import { MessageApi } from '../../src/account/apis/message'; import { mockBridge } from './_helpers'; describe('apis/message — recall + markRead', () => { diff --git a/packages/core/tests/actions/interaction.test.ts b/packages/core/tests/actions/interaction.test.ts index a2d6dc65..810883c5 100644 --- a/packages/core/tests/actions/interaction.test.ts +++ b/packages/core/tests/actions/interaction.test.ts @@ -1,14 +1,14 @@ -import { describe, it, expect } from 'vitest'; -import { protobuf_encode } from '@snowluma/proton'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { Oidb0x9083Resp } from '@snowluma/proto-defs/oidb-actions/base'; +import { protobuf_encode } from '@snowluma/proton'; +import { describe, expect, it } from 'vitest'; // Post-namespace-migration: InteractionApi is a thin facade and // production code routes through the namespace path (sender → // sendRawPacket). Tests now assert against the bridge mock's // sendRawPacket directly — no need for module-level mocks on the // bridge-oidb internals. -import { InteractionApi } from '../../src/bridge/apis/interaction'; +import { InteractionApi } from '../../src/account/apis/interaction'; import { mockBridge } from './_helpers'; describe('apis/interaction', () => { diff --git a/packages/core/tests/actions/misc.test.ts b/packages/core/tests/actions/misc.test.ts index d60483d6..52ac1bbe 100644 --- a/packages/core/tests/actions/misc.test.ts +++ b/packages/core/tests/actions/misc.test.ts @@ -1,16 +1,16 @@ -import { describe, it, expect, vi } from 'vitest'; -import { protobuf_encode } from '@snowluma/proton'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { - Oidb0x990Resp, Oidb0x112eResp, + Oidb0x990Resp, } from '@snowluma/proto-defs/oidb-actions/base'; +import { protobuf_encode } from '@snowluma/proton'; +import { describe, expect, it, vi } from 'vitest'; // Post-namespace migration: MiscApi forwards 3 OIDB cmds through // @snowluma/protocol/oidb-services/misc namespaces. The non-OIDB // `getMiniAppArk` (LightAppSvc) stays inline on the facade. Tests // hit bridge.sendRawPacket directly. -import { MiscApi } from '../../src/bridge/apis/misc'; +import { MiscApi } from '../../src/account/apis/misc'; import { mockBridge } from './_helpers'; function packResponse(body: Uint8Array) { diff --git a/packages/core/tests/actions/profile.test.ts b/packages/core/tests/actions/profile.test.ts index f33901b1..d83a1029 100644 --- a/packages/core/tests/actions/profile.test.ts +++ b/packages/core/tests/actions/profile.test.ts @@ -1,5 +1,3 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { GroupAvatarExtra, @@ -8,6 +6,8 @@ import type { SetStatusReq, SetStatusResp, } from '@snowluma/proto-defs/oidb-actions/base'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; // `encodeOidbEnv` / `decodeOidbEnv` are proton-bound pass-through wrappers // (substituted at the call site with the inlined codec). Mocking them on @@ -38,7 +38,7 @@ vi.mock('@snowluma/protocol/highway/utils', () => ({ import * as oidb from '@snowluma/protocol/bridge-oidb'; import * as highwayClient from '@snowluma/protocol/highway'; -import { ProfileApi } from '../../src/bridge/apis/profile'; +import { ProfileApi } from '../../src/account/apis/profile'; import { mockBridge } from './_helpers'; describe('apis/profile', () => { @@ -52,14 +52,14 @@ describe('apis/profile', () => { it('setOnlineStatus sends to status_svc.SetStatus and accepts an empty response', async () => { const bridge = mockBridge(); - await new ProfileApi(bridge as any).setOnlineStatus( 11, 0, 100); + await new ProfileApi(bridge as any).setOnlineStatus(11, 0, 100); const [serviceCmd] = bridge.sendRawPacket.mock.calls[0]!; expect(serviceCmd).toBe('trpc.qq_new_tech.status_svc.StatusService.SetStatus'); }); it('setOnlineStatus does NOT include the customExt field 4 (varint 0x22 absent in body)', async () => { const bridge = mockBridge(); - await new ProfileApi(bridge as any).setOnlineStatus( 11, 0, 100); + await new ProfileApi(bridge as any).setOnlineStatus(11, 0, 100); const [, body] = bridge.sendRawPacket.mock.calls[0]!; // proto field 4 length-delimited tag = (4 << 3) | 2 = 0x22. The // body should not contain that byte; if encoder ever leaks an @@ -69,7 +69,7 @@ describe('apis/profile', () => { it('setDiyOnlineStatus hardcodes status=10 / extStatus=2000 and packs faceId+wording+faceType into customExt', async () => { const bridge = mockBridge(); - await new ProfileApi(bridge as any).setDiyOnlineStatus( 1234, '摸鱼中', 2); + await new ProfileApi(bridge as any).setDiyOnlineStatus(1234, '摸鱼中', 2); const [serviceCmd, body] = bridge.sendRawPacket.mock.calls[0]!; expect(serviceCmd).toBe('trpc.qq_new_tech.status_svc.StatusService.SetStatus'); // Decode the wire bytes back through the same schema to assert @@ -90,7 +90,7 @@ describe('apis/profile', () => { bridge.sendRawPacket.mockResolvedValueOnce({ success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: respBuf, } as any); - await expect(new ProfileApi(bridge as any).setDiyOnlineStatus( 1, 't', 1)).rejects.toThrow(/denied/); + await expect(new ProfileApi(bridge as any).setDiyOnlineStatus(1, 't', 1)).rejects.toThrow(/denied/); }); it('setDiyOnlineStatus rejects when the transport itself fails', async () => { @@ -98,7 +98,7 @@ describe('apis/profile', () => { bridge.sendRawPacket.mockResolvedValueOnce({ success: false, gotResponse: false, errorCode: -1, errorMessage: 'pipe closed', responseData: null, } as any); - await expect(new ProfileApi(bridge as any).setDiyOnlineStatus( 1, 't', 1)).rejects.toThrow(/pipe closed/); + await expect(new ProfileApi(bridge as any).setDiyOnlineStatus(1, 't', 1)).rejects.toThrow(/pipe closed/); }); it('setProfile is a no-op when both arguments are undefined', async () => { @@ -117,20 +117,20 @@ describe('apis/profile', () => { it('setSelfLongNick targets 0x112a_2 wire cmd', async () => { const bridge = mockBridge(); - await new ProfileApi(bridge as any).setSelfLongNick( 'hello world'); + await new ProfileApi(bridge as any).setSelfLongNick('hello world'); expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x112a_2'); }); it('setInputStatus resolves UID first and sends 0xcd4_1', async () => { const bridge = mockBridge(); - await new ProfileApi(bridge as any).setInputStatus( 10001, 1); + await new ProfileApi(bridge as any).setInputStatus(10001, 1); expect(bridge.resolveUserUid).toHaveBeenCalledWith(10001); expect(bridge.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0xcd4_1'); }); it('setAvatar loads bytes and pushes through the highway upload path (cmd 90)', async () => { const bridge = mockBridge(); - await new ProfileApi(bridge as any).setAvatar( '/some/avatar.png'); + await new ProfileApi(bridge as any).setAvatar('/some/avatar.png'); expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce(); expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); const [, , cmdId, , , extend] = vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]!; @@ -140,7 +140,7 @@ describe('apis/profile', () => { it('setGroupAvatar uses cmdId 3000 and packs the Lagrange GroupAvatarExtra constants', async () => { const bridge = mockBridge(); - await new ProfileApi(bridge as any).setGroupAvatar( 12345, '/some/group-avatar.png'); + await new ProfileApi(bridge as any).setGroupAvatar(12345, '/some/group-avatar.png'); expect(highwayClient.fetchHighwaySession).toHaveBeenCalledOnce(); expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); const [, , cmdId, , , extend] = vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]!; @@ -163,7 +163,7 @@ describe('apis/profile', () => { vi.mocked(loadBinarySource).mockResolvedValueOnce({ bytes: new Uint8Array(0), fileName: 'empty.png', } as any); - await expect(new ProfileApi(bridge as any).setGroupAvatar( 1, 'empty.png')).rejects.toThrow(/empty/); + await expect(new ProfileApi(bridge as any).setGroupAvatar(1, 'empty.png')).rejects.toThrow(/empty/); expect(highwayClient.fetchHighwaySession).not.toHaveBeenCalled(); }); diff --git a/packages/onebot/package.json b/packages/onebot/package.json index ede164a4..73797e4e 100644 --- a/packages/onebot/package.json +++ b/packages/onebot/package.json @@ -86,6 +86,7 @@ "typecheck": "tsc --noEmit" }, "dependencies": { + "@snowluma/bridge": "workspace:*", "@snowluma/common": "workspace:*", "@snowluma/core": "workspace:*", "@snowluma/proto-defs": "workspace:*", diff --git a/packages/onebot/src/api-handler.ts b/packages/onebot/src/api-handler.ts index 7a9546f7..df97851a 100644 --- a/packages/onebot/src/api-handler.ts +++ b/packages/onebot/src/api-handler.ts @@ -1,6 +1,6 @@ import { summarizeParams } from '@snowluma/common/log-summary'; import { createLogger, type Logger } from '@snowluma/common/logger'; -import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { AccountInterface } from '@snowluma/core/account-interface'; import { register as registerExtended } from './actions/extended'; import { register as registerFriend } from './actions/friend'; import { register as registerGroupAdmin } from './actions/group-admin'; @@ -33,7 +33,7 @@ export interface GroupEssenceMsgRet { } export interface ApiActionContext { - bridge: BridgeInterface; + bridge: AccountInterface; getLoginInfo: () => { userId: number; nickname: string }; isOnline: () => boolean; getMessage: (messageId: number) => JsonObject | null; diff --git a/packages/onebot/src/instance-context.ts b/packages/onebot/src/instance-context.ts index e32fecfc..053cfe04 100644 --- a/packages/onebot/src/instance-context.ts +++ b/packages/onebot/src/instance-context.ts @@ -1,5 +1,4 @@ -import type { Bridge } from '@snowluma/core/bridge'; -import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { AccountInterface } from '@snowluma/core/account-interface'; import type { WebHonorType } from '@snowluma/protocol/web/group-honor'; import type { ApiActionContext } from './api-handler'; import type { ConverterContext } from './event-converter'; @@ -41,7 +40,7 @@ import type { JsonObject, MessageMeta, OneBotConfig } from './types'; export interface OneBotInstanceContext { uin: string; selfId: number; - bridge: BridgeInterface; + bridge: AccountInterface; messageStore: MessageStore; mediaStore: MediaStore; reactionStore: ReactionStore; @@ -119,5 +118,5 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { }; } -export type { Bridge, WebHonorType }; +export type { WebHonorType }; diff --git a/packages/onebot/src/instance-rkey.ts b/packages/onebot/src/instance-rkey.ts index b713537c..a10df495 100644 --- a/packages/onebot/src/instance-rkey.ts +++ b/packages/onebot/src/instance-rkey.ts @@ -1,6 +1,6 @@ import { createLogger } from '@snowluma/common/logger'; -import type { DownloadRKeyInfo } from '@snowluma/core/bridge'; -import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { AccountInterface } from '@snowluma/core/account-interface'; +import type { DownloadRKeyInfo } from '@snowluma/core/apis'; import type { MessageElement } from '@snowluma/protocol/events'; const log = createLogger('OneBot'); @@ -27,7 +27,7 @@ export class RKeyCache { private cache = new Map(); private lastRefreshAttempt = 0; - warmUp(bridge: BridgeInterface, uin: string): void { + warmUp(bridge: AccountInterface, uin: string): void { bridge.apis.contacts.fetchDownloadRKeys().then( (rkeys) => { this.updateCache(rkeys); @@ -39,7 +39,7 @@ export class RKeyCache { ); } - resolveImageUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string { + resolveImageUrl(bridge: AccountInterface, element: MessageElement, isGroup: boolean): string { const url = element.imageUrl ?? ''; if (!urlNeedsRKey(url)) return url; @@ -50,7 +50,7 @@ export class RKeyCache { const separator = url.includes('?') ? '&rkey=' : '?rkey='; return url + separator + encodeURIComponent(cleanRKey); } - resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string { + resolveMediaUrl(bridge: AccountInterface, element: MessageElement, isGroup: boolean): string { const url = element.url ?? ''; if (!url || !urlNeedsRKey(url)) return url; @@ -89,12 +89,12 @@ export class RKeyCache { } } - private findRKey(bridge: BridgeInterface, isGroup: boolean): string | null { + private findRKey(bridge: AccountInterface, isGroup: boolean): string | null { const primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE; return this.findRKeyForType(bridge, primaryType); } - private findRKeyForType(bridge: BridgeInterface, primaryType: number): string | null { + private findRKeyForType(bridge: AccountInterface, primaryType: number): string | null { const now = Math.floor(Date.now() / 1000); const tryFind = (type: number): string | null => { diff --git a/packages/onebot/src/instance.ts b/packages/onebot/src/instance.ts index 92d3d3e6..2259c063 100644 --- a/packages/onebot/src/instance.ts +++ b/packages/onebot/src/instance.ts @@ -1,5 +1,5 @@ import { createLogger, type Logger } from '@snowluma/common/logger'; -import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { AccountInterface } from '@snowluma/core/account-interface'; import { formatGroup, formatMessageSegments, formatReply, formatUser } from '@snowluma/protocol/format'; import path from 'path'; import { ApiHandler } from './api-handler'; @@ -28,7 +28,7 @@ const moduleLog = createLogger('Event'); export class OneBotInstance { readonly uin: string; - private readonly bridge: BridgeInterface; + private readonly bridge: AccountInterface; private readonly apiHandler: ApiHandler; private readonly converterCtx: ConverterContext; private readonly messageStore: MessageStore; @@ -45,7 +45,7 @@ export class OneBotInstance { get nickname(): string { return this.bridge.identity.nickname; } - constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) { + constructor(uin: string, bridge: AccountInterface, config: OneBotConfig) { this.uin = uin; this.bridge = bridge; const uinNum = Number.parseInt(uin, 10); diff --git a/packages/onebot/src/manager.ts b/packages/onebot/src/manager.ts index 8d1d7d54..b077c8eb 100644 --- a/packages/onebot/src/manager.ts +++ b/packages/onebot/src/manager.ts @@ -1,6 +1,6 @@ import { createLogger } from '@snowluma/common/logger'; -import type { BridgeInterface } from '@snowluma/core/bridge-interface'; -import type { BridgeManager } from '@snowluma/core/manager'; +import type { AccountInterface } from '@snowluma/core/account-interface'; +import type { AccountManager } from '@snowluma/core/account-manager'; import { loadOneBotConfig } from './config'; import { OneBotInstance } from './instance'; @@ -10,12 +10,12 @@ const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1'; export class OneBotManager { private readonly instances = new Map(); - bind(bridgeManager: BridgeManager): void { - bridgeManager.setSessionStartedCallback((uin, bridge) => { - this.onSessionStarted(uin, bridge); + bind(accountManager: AccountManager): void { + accountManager.setAccountStartedCallback((uin, account) => { + this.onSessionStarted(uin, account); }); - bridgeManager.setSessionClosedCallback((uin) => { + accountManager.setAccountClosedCallback((uin) => { this.onSessionClosed(uin); }); } @@ -45,7 +45,7 @@ export class OneBotManager { this.instances.clear(); } - private onSessionStarted(uin: string, bridge: BridgeInterface): void { + private onSessionStarted(uin: string, bridge: AccountInterface): void { if (this.instances.has(uin)) return; const config = loadOneBotConfig(uin, { persistDefaults: true }); @@ -71,7 +71,7 @@ export class OneBotManager { } -async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise { +async function warmUpBridgeState(uin: string, bridge: AccountInterface): Promise { const selfUin = parseInt(uin, 10) || 0; let selfResolved = false; diff --git a/packages/onebot/src/media-url-resolver.ts b/packages/onebot/src/media-url-resolver.ts index a2cf4c1f..87b6923d 100644 --- a/packages/onebot/src/media-url-resolver.ts +++ b/packages/onebot/src/media-url-resolver.ts @@ -1,10 +1,10 @@ -import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { AccountInterface } from '@snowluma/core/account-interface'; import type { MessageElement } from '@snowluma/protocol/events'; import type { RKeyCache } from './instance-rkey'; export class MediaUrlResolver { constructor( - private readonly bridge: BridgeInterface, + private readonly bridge: AccountInterface, private readonly rkeyCache: RKeyCache, ) { } diff --git a/packages/onebot/src/modules/contact-actions.ts b/packages/onebot/src/modules/contact-actions.ts index 62e44a67..6ec6a861 100644 --- a/packages/onebot/src/modules/contact-actions.ts +++ b/packages/onebot/src/modules/contact-actions.ts @@ -1,4 +1,4 @@ -import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { AccountInterface } from '@snowluma/core/account-interface'; import type { IdentityService } from '@snowluma/protocol/identity-service'; import type { OneBotInstanceContext } from '../instance-context'; import type { JsonObject } from '../types'; @@ -9,7 +9,7 @@ export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nick return { userId, nickname }; } -async function refreshSingleGroupMembers(bridge: BridgeInterface, groupId: number): Promise { +async function refreshSingleGroupMembers(bridge: AccountInterface, groupId: number): Promise { try { await bridge.apis.contacts.fetchGroupMemberList(groupId); } catch { @@ -17,7 +17,7 @@ async function refreshSingleGroupMembers(bridge: BridgeInterface, groupId: numbe } } -export async function getFriendList(bridge: BridgeInterface): Promise { +export async function getFriendList(bridge: AccountInterface): Promise { try { const friends = await bridge.apis.contacts.fetchFriendList(); return friends.map(f => ({ @@ -35,7 +35,7 @@ export async function getFriendList(bridge: BridgeInterface): Promise { try { @@ -54,7 +54,7 @@ export async function getGroupList( } export async function getGroupInfo( - bridge: BridgeInterface, + bridge: AccountInterface, groupId: number, noCache?: boolean, ): Promise { @@ -76,7 +76,7 @@ export async function getGroupInfo( } export async function getGroupMemberList( - bridge: BridgeInterface, + bridge: AccountInterface, groupId: number, noCache?: boolean, ): Promise { @@ -94,7 +94,7 @@ export async function getGroupMemberList( } export async function getGroupMemberInfo( - bridge: BridgeInterface, + bridge: AccountInterface, groupId: number, userId: number, noCache?: boolean, @@ -108,7 +108,7 @@ export async function getGroupMemberInfo( } export async function getGroupFiles( - bridge: BridgeInterface, + bridge: AccountInterface, groupId: number, folderId?: string, ): Promise { @@ -140,7 +140,7 @@ export async function getGroupFiles( } export async function getStrangerInfo( - bridge: BridgeInterface, + bridge: AccountInterface, userId: number, ): Promise { try { @@ -167,7 +167,7 @@ export async function getStrangerInfo( } } -export async function getGroupSystemMessages(bridge: BridgeInterface): Promise { +export async function getGroupSystemMessages(bridge: AccountInterface): Promise { try { const reqs = await bridge.apis.contacts.fetchGroupRequests(); return reqs.map(r => ({ @@ -184,7 +184,7 @@ export async function getGroupSystemMessages(bridge: BridgeInterface): Promise { +export async function getDownloadRKeys(bridge: AccountInterface): Promise { try { const rkeys = await bridge.apis.contacts.fetchDownloadRKeys(); return rkeys.map(r => ({ diff --git a/packages/onebot/src/modules/media-actions.ts b/packages/onebot/src/modules/media-actions.ts index 08ee1fe5..b5ca7da7 100644 --- a/packages/onebot/src/modules/media-actions.ts +++ b/packages/onebot/src/modules/media-actions.ts @@ -1,5 +1,5 @@ import { createLogger } from '@snowluma/common/logger'; -import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { AccountInterface } from '@snowluma/core/account-interface'; import type { MediaStore } from '../media-store'; import type { JsonObject } from '../types'; @@ -21,7 +21,7 @@ export async function getImageInfo( } export async function getRecordInfo( - bridge: BridgeInterface, + bridge: AccountInterface, mediaStore: MediaStore, file: string, ): Promise { diff --git a/packages/onebot/src/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts index 8b80c5e8..955be71c 100644 --- a/packages/onebot/src/modules/message-actions.ts +++ b/packages/onebot/src/modules/message-actions.ts @@ -1,5 +1,5 @@ import { createLogger } from '@snowluma/common/logger'; -import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { AccountInterface } from '@snowluma/core/account-interface'; import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events'; import type { MessageSendResult } from '../api-handler'; import { elementsToOneBotSegments } from '../event-converter'; @@ -64,7 +64,7 @@ export async function getFriendMsgHistory( .map(sanitizeMessageEventForApi); } -export async function deleteMessage(bridge: BridgeInterface, meta: MessageMeta): Promise { +export async function deleteMessage(bridge: AccountInterface, meta: MessageMeta): Promise { if (meta.isGroup) { await bridge.apis.message.recallGroup(meta.targetId, meta.sequence); } else { @@ -79,7 +79,7 @@ export async function deleteMessage(bridge: BridgeInterface, meta: MessageMeta): } export async function setEssenceMessage( - bridge: BridgeInterface, + bridge: AccountInterface, messageStore: MessageStore, messageId: number, enable: boolean, diff --git a/packages/onebot/src/modules/request-actions.ts b/packages/onebot/src/modules/request-actions.ts index 29954e2b..547c74b8 100644 --- a/packages/onebot/src/modules/request-actions.ts +++ b/packages/onebot/src/modules/request-actions.ts @@ -1,7 +1,7 @@ -import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { AccountInterface } from '@snowluma/core/account-interface'; export async function handleGroupAddRequest( - bridge: BridgeInterface, + bridge: AccountInterface, flag: string, approve: boolean, reason: string, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2715a2c4..8d15eb1f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -139,6 +139,9 @@ importers: packages/onebot: dependencies: + '@snowluma/bridge': + specifier: workspace:* + version: link:../bridge '@snowluma/common': specifier: workspace:* version: link:../common