From af8d5ab06be33aac6fb000805204cf5781ca7a18 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 14:11:45 +0800 Subject: [PATCH] =?UTF-8?q?Split=20channel=20packages=20and=20rename=20Acc?= =?UTF-8?q?ount=E2=86=92Core?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reorganize package layout and rename core/account types: - Move channel hook & socket sources/tests into packages/channel-hook and packages/channel-socket (many files renamed). - Remove ChannelManager from packages/channel and drop its export from package.json (multi-account host folded into Hub). - Update tests to use HookSink instead of BridgeManagerSink. - In @snowluma/core: move account/apis/* up to src/apis, rename account-context→core-context, account-interface→core-ctx, account→core, and add hub.ts; delete AccountManager. - Update constructors and type usages to accept CoreContext/CoreCtx and adapt identifiers accordingly. This is a refactor to clarify responsibilities (split transport implementations, fold multi-account manager into Hub, and rebrand the account layer as Core). --- packages/channel-hook/package.json | 69 ++++ .../src/hook-adapter.ts | 2 +- .../src/hook-channel.ts | 2 +- .../src/hook-manager.ts | 0 .../src/hook-packet-client.ts | 0 .../src/hook-session.ts | 0 packages/channel-hook/src/index.ts | 15 + .../{channel => channel-hook}/src/injector.ts | 0 .../src/pipe-watcher.ts | 0 .../src/qq-hook-client.ts | 0 .../src/qq-port-probe.ts | 0 .../{channel => channel-hook}/src/types.ts | 0 .../tests/hook-manager.test.ts | 8 +- .../tests/hook-reconnect-no-login-e2e.test.ts | 14 +- .../tests/hook-reconnect-no-login.test.ts | 0 .../tests/hook-session.test.ts | 0 .../tests/pipe-watcher.test.ts | 0 .../tests/qq-hook-client.test.ts | 0 packages/channel-hook/tsconfig.json | 16 + packages/channel-hook/vitest.config.ts | 8 + packages/channel-socket/package.json | 34 ++ packages/channel-socket/src/index.ts | 8 + .../src/socket-adapter.ts | 2 +- .../src/socket-channel.ts | 2 +- packages/channel-socket/tsconfig.json | 15 + packages/channel/package.json | 54 +-- packages/channel/src/index.ts | 28 +- packages/channel/src/manager.ts | 277 -------------- packages/core/package.json | 30 +- packages/core/src/account/account-manager.ts | 100 ------ .../core/src/{account => }/apis/contacts.ts | 4 +- .../core/src/{account => }/apis/extras.ts | 4 +- .../core/src/{account => }/apis/forward.ts | 4 +- .../core/src/{account => }/apis/friend.ts | 4 +- .../src/{account => }/apis/group-admin.ts | 4 +- .../src/{account => }/apis/group-album.ts | 4 +- .../core/src/{account => }/apis/group-file.ts | 4 +- packages/core/src/{account => }/apis/index.ts | 4 +- .../src/{account => }/apis/interaction.ts | 4 +- .../core/src/{account => }/apis/message.ts | 4 +- packages/core/src/{account => }/apis/misc.ts | 4 +- .../core/src/{account => }/apis/profile.ts | 4 +- .../core/src/{account => }/apis/shared.ts | 0 packages/core/src/{account => }/apis/web.ts | 4 +- .../account-context.ts => core-context.ts} | 13 +- .../account-interface.ts => core-ctx.ts} | 22 +- .../core/src/{account/account.ts => core.ts} | 79 ++-- packages/core/src/hub.ts | 340 ++++++++++++++++++ packages/core/src/index.ts | 38 +- packages/core/src/webui/server.ts | 2 +- .../tests/account-member-identity.test.ts | 52 +-- .../tests/account-private-routing.test.ts | 88 ++--- packages/core/tests/actions/extras.test.ts | 2 +- .../core/tests/actions/forward-file.test.ts | 2 +- .../core/tests/actions/forward-nested.test.ts | 2 +- packages/core/tests/actions/forward.test.ts | 2 +- packages/core/tests/actions/friend.test.ts | 2 +- .../core/tests/actions/group-admin.test.ts | 2 +- .../core/tests/actions/group-file.test.ts | 2 +- .../core/tests/actions/group-message.test.ts | 2 +- .../core/tests/actions/interaction.test.ts | 2 +- packages/core/tests/actions/misc.test.ts | 2 +- packages/core/tests/actions/profile.test.ts | 2 +- packages/onebot/src/api-handler.ts | 4 +- packages/onebot/src/instance-context.ts | 4 +- packages/onebot/src/instance-rkey.ts | 12 +- 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 | 44 +++ 74 files changed, 813 insertions(+), 705 deletions(-) create mode 100644 packages/channel-hook/package.json rename packages/{channel => channel-hook}/src/hook-adapter.ts (98%) rename packages/{channel => channel-hook}/src/hook-channel.ts (98%) rename packages/{channel => channel-hook}/src/hook-manager.ts (100%) rename packages/{channel => channel-hook}/src/hook-packet-client.ts (100%) rename packages/{channel => channel-hook}/src/hook-session.ts (100%) create mode 100644 packages/channel-hook/src/index.ts rename packages/{channel => channel-hook}/src/injector.ts (100%) rename packages/{channel => channel-hook}/src/pipe-watcher.ts (100%) rename packages/{channel => channel-hook}/src/qq-hook-client.ts (100%) rename packages/{channel => channel-hook}/src/qq-port-probe.ts (100%) rename packages/{channel => channel-hook}/src/types.ts (100%) rename packages/{channel => channel-hook}/tests/hook-manager.test.ts (98%) rename packages/{channel => channel-hook}/tests/hook-reconnect-no-login-e2e.test.ts (90%) rename packages/{channel => channel-hook}/tests/hook-reconnect-no-login.test.ts (100%) rename packages/{channel => channel-hook}/tests/hook-session.test.ts (100%) rename packages/{channel => channel-hook}/tests/pipe-watcher.test.ts (100%) rename packages/{channel => channel-hook}/tests/qq-hook-client.test.ts (100%) create mode 100644 packages/channel-hook/tsconfig.json create mode 100644 packages/channel-hook/vitest.config.ts create mode 100644 packages/channel-socket/package.json create mode 100644 packages/channel-socket/src/index.ts rename packages/{channel => channel-socket}/src/socket-adapter.ts (93%) rename packages/{channel => channel-socket}/src/socket-channel.ts (96%) create mode 100644 packages/channel-socket/tsconfig.json delete mode 100644 packages/channel/src/manager.ts delete mode 100644 packages/core/src/account/account-manager.ts rename packages/core/src/{account => }/apis/contacts.ts (98%) rename packages/core/src/{account => }/apis/extras.ts (96%) rename packages/core/src/{account => }/apis/forward.ts (99%) rename packages/core/src/{account => }/apis/friend.ts (90%) rename packages/core/src/{account => }/apis/group-admin.ts (96%) rename packages/core/src/{account => }/apis/group-album.ts (98%) rename packages/core/src/{account => }/apis/group-file.ts (99%) rename packages/core/src/{account => }/apis/index.ts (96%) rename packages/core/src/{account => }/apis/interaction.ts (96%) rename packages/core/src/{account => }/apis/message.ts (99%) rename packages/core/src/{account => }/apis/misc.ts (95%) rename packages/core/src/{account => }/apis/profile.ts (98%) rename packages/core/src/{account => }/apis/shared.ts (100%) rename packages/core/src/{account => }/apis/web.ts (98%) rename packages/core/src/{account/account-context.ts => core-context.ts} (60%) rename packages/core/src/{account/account-interface.ts => core-ctx.ts} (53%) rename packages/core/src/{account/account.ts => core.ts} (67%) create mode 100644 packages/core/src/hub.ts diff --git a/packages/channel-hook/package.json b/packages/channel-hook/package.json new file mode 100644 index 00000000..7c1ea666 --- /dev/null +++ b/packages/channel-hook/package.json @@ -0,0 +1,69 @@ +{ + "name": "@snowluma/channel-hook", + "version": "1.9.2", + "private": true, + "type": "module", + "description": "SnowLuma `inject` channel implementation — in-process NTQQ hook runtime. Bundles HookManager / HookSession / pipe-watcher / injector / qq-hook-client plus the `HookChannel` and `HookAdapter` that `Hub` (in @snowluma/core) registers as the primary transport on Windows. Depends on `@snowluma/channel` for the abstract `Channel` + `ChannelAdapter` contracts.", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./hook-channel": { + "types": "./src/hook-channel.ts", + "default": "./src/hook-channel.ts" + }, + "./hook-adapter": { + "types": "./src/hook-adapter.ts", + "default": "./src/hook-adapter.ts" + }, + "./hook-manager": { + "types": "./src/hook-manager.ts", + "default": "./src/hook-manager.ts" + }, + "./hook-session": { + "types": "./src/hook-session.ts", + "default": "./src/hook-session.ts" + }, + "./hook-packet-client": { + "types": "./src/hook-packet-client.ts", + "default": "./src/hook-packet-client.ts" + }, + "./injector": { + "types": "./src/injector.ts", + "default": "./src/injector.ts" + }, + "./pipe-watcher": { + "types": "./src/pipe-watcher.ts", + "default": "./src/pipe-watcher.ts" + }, + "./qq-hook-client": { + "types": "./src/qq-hook-client.ts", + "default": "./src/qq-hook-client.ts" + }, + "./qq-port-probe": { + "types": "./src/qq-port-probe.ts", + "default": "./src/qq-port-probe.ts" + }, + "./types": { + "types": "./src/types.ts", + "default": "./src/types.ts" + } + }, + "scripts": { + "test": "vitest run", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@snowluma/channel": "workspace:*", + "@snowluma/common": "workspace:*" + }, + "devDependencies": { + "@types/node": "^24.12.2", + "typescript": "catalog:", + "vite": "catalog:", + "vitest": "^4.1.4" + } +} diff --git a/packages/channel/src/hook-adapter.ts b/packages/channel-hook/src/hook-adapter.ts similarity index 98% rename from packages/channel/src/hook-adapter.ts rename to packages/channel-hook/src/hook-adapter.ts index 7c070f6b..1dfba861 100644 --- a/packages/channel/src/hook-adapter.ts +++ b/packages/channel-hook/src/hook-adapter.ts @@ -1,6 +1,6 @@ +import type { ChannelAdapter, ChannelAdapterHost } from '@snowluma/channel'; import type { PacketSender } from '@snowluma/common/packet-sender'; import type { PacketInfo } from '@snowluma/common/protocol-types'; -import type { ChannelAdapter, ChannelAdapterHost } from './adapter'; import { HookChannel } from './hook-channel'; import { HookManager, type HookManagerDeps, type HookSink } from './hook-manager'; diff --git a/packages/channel/src/hook-channel.ts b/packages/channel-hook/src/hook-channel.ts similarity index 98% rename from packages/channel/src/hook-channel.ts rename to packages/channel-hook/src/hook-channel.ts index 0c991524..68070205 100644 --- a/packages/channel/src/hook-channel.ts +++ b/packages/channel-hook/src/hook-channel.ts @@ -1,5 +1,5 @@ +import { Channel } from '@snowluma/channel'; import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender'; -import { Channel } from './channel'; /** * `HookChannel` — concrete transport backed by the in-process NTQQ diff --git a/packages/channel/src/hook-manager.ts b/packages/channel-hook/src/hook-manager.ts similarity index 100% rename from packages/channel/src/hook-manager.ts rename to packages/channel-hook/src/hook-manager.ts diff --git a/packages/channel/src/hook-packet-client.ts b/packages/channel-hook/src/hook-packet-client.ts similarity index 100% rename from packages/channel/src/hook-packet-client.ts rename to packages/channel-hook/src/hook-packet-client.ts diff --git a/packages/channel/src/hook-session.ts b/packages/channel-hook/src/hook-session.ts similarity index 100% rename from packages/channel/src/hook-session.ts rename to packages/channel-hook/src/hook-session.ts diff --git a/packages/channel-hook/src/index.ts b/packages/channel-hook/src/index.ts new file mode 100644 index 00000000..30575c0b --- /dev/null +++ b/packages/channel-hook/src/index.ts @@ -0,0 +1,15 @@ +// `@snowluma/channel-hook` — the `inject` channel implementation +// (NTQQ in-process hook). Registered with `Hub` from `@snowluma/core` +// as a `ChannelAdapter` of kind `'inject'`. Everything pid-related is +// scoped to this package — neither `@snowluma/channel` nor anything +// downstream knows about it. + +// ─── Hook runtime ────────────────────────────────────────────────── +export { + HookManager, type HookSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo, + type HookProcessStatus, type QqPortLoginInfo +} from './hook-manager'; + +// ─── Concrete Channel + Adapter ──────────────────────────────────── +export { HookChannel } from './hook-channel'; +export { HookAdapter, type HookAdapterOptions } from './hook-adapter'; diff --git a/packages/channel/src/injector.ts b/packages/channel-hook/src/injector.ts similarity index 100% rename from packages/channel/src/injector.ts rename to packages/channel-hook/src/injector.ts diff --git a/packages/channel/src/pipe-watcher.ts b/packages/channel-hook/src/pipe-watcher.ts similarity index 100% rename from packages/channel/src/pipe-watcher.ts rename to packages/channel-hook/src/pipe-watcher.ts diff --git a/packages/channel/src/qq-hook-client.ts b/packages/channel-hook/src/qq-hook-client.ts similarity index 100% rename from packages/channel/src/qq-hook-client.ts rename to packages/channel-hook/src/qq-hook-client.ts diff --git a/packages/channel/src/qq-port-probe.ts b/packages/channel-hook/src/qq-port-probe.ts similarity index 100% rename from packages/channel/src/qq-port-probe.ts rename to packages/channel-hook/src/qq-port-probe.ts diff --git a/packages/channel/src/types.ts b/packages/channel-hook/src/types.ts similarity index 100% rename from packages/channel/src/types.ts rename to packages/channel-hook/src/types.ts diff --git a/packages/channel/tests/hook-manager.test.ts b/packages/channel-hook/tests/hook-manager.test.ts similarity index 98% rename from packages/channel/tests/hook-manager.test.ts rename to packages/channel-hook/tests/hook-manager.test.ts index 7274b05a..e0982e72 100644 --- a/packages/channel/tests/hook-manager.test.ts +++ b/packages/channel-hook/tests/hook-manager.test.ts @@ -6,7 +6,7 @@ import path from 'path'; import { HookManager, shouldAutoLoadPid } from '../src/hook-manager'; import { PipeWatcher } from '../src/pipe-watcher'; import type { ManualMapHandle } from '../src/injector'; -import type { BridgeManagerSink } from '../src/hook-manager'; +import type { HookSink } from '../src/hook-manager'; import type { QqHookClient } from '../src/qq-hook-client'; import { createLogger } from '@snowluma/common/logger'; @@ -37,13 +37,13 @@ function makeManager(opts: { (c as any).close = () => { (c as any).isClosed = true; }; return c as unknown as QqHookClient; }); - const bridgeManager = { + const sink = { onPacket: vi.fn(), onHookLogin: vi.fn(), onPidDisconnected: vi.fn(), - } as unknown as BridgeManagerSink; + } as unknown as HookSink; const manager = new HookManager({ - bridgeManager, + sink, pipeWatcher, injector: { inject, unload }, makeClient, diff --git a/packages/channel/tests/hook-reconnect-no-login-e2e.test.ts b/packages/channel-hook/tests/hook-reconnect-no-login-e2e.test.ts similarity index 90% rename from packages/channel/tests/hook-reconnect-no-login-e2e.test.ts rename to packages/channel-hook/tests/hook-reconnect-no-login-e2e.test.ts index 61ef7d08..50c1744a 100644 --- a/packages/channel/tests/hook-reconnect-no-login-e2e.test.ts +++ b/packages/channel-hook/tests/hook-reconnect-no-login-e2e.test.ts @@ -9,7 +9,7 @@ import { EventEmitter } from 'events'; import { HookManager } from '../src/hook-manager'; import { PipeWatcher } from '../src/pipe-watcher'; import type { ManualMapHandle } from '../src/injector'; -import type { BridgeManagerSink } from '../src/hook-manager'; +import type { HookSink } from '../src/hook-manager'; import type { QqHookClient } from '../src/qq-hook-client'; const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 }; @@ -41,14 +41,14 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => { intervalMs: 60_000, // manual ticks only }); - const bridgeManager = { + const sink = { onPacket: vi.fn(), onHookLogin: vi.fn(), onPidDisconnected: vi.fn(), - } as unknown as BridgeManagerSink; + } as unknown as HookSink; const manager = new HookManager({ - bridgeManager, + sink, pipeWatcher, injector: { inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), @@ -82,9 +82,9 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => { // The "QQ never logs in" hypothesis: BridgeManager should never have // been told about a login or a disconnect. - expect(bridgeManager.onHookLogin).not.toHaveBeenCalled(); - expect(bridgeManager.onPidDisconnected).not.toHaveBeenCalled(); - expect(bridgeManager.onPacket).not.toHaveBeenCalled(); + expect(sink.onHookLogin).not.toHaveBeenCalled(); + expect(sink.onPidDisconnected).not.toHaveBeenCalled(); + expect(sink.onPacket).not.toHaveBeenCalled(); // Hook layer should hold at most one live client. const alive = clients.filter(c => !c.isClosed); diff --git a/packages/channel/tests/hook-reconnect-no-login.test.ts b/packages/channel-hook/tests/hook-reconnect-no-login.test.ts similarity index 100% rename from packages/channel/tests/hook-reconnect-no-login.test.ts rename to packages/channel-hook/tests/hook-reconnect-no-login.test.ts diff --git a/packages/channel/tests/hook-session.test.ts b/packages/channel-hook/tests/hook-session.test.ts similarity index 100% rename from packages/channel/tests/hook-session.test.ts rename to packages/channel-hook/tests/hook-session.test.ts diff --git a/packages/channel/tests/pipe-watcher.test.ts b/packages/channel-hook/tests/pipe-watcher.test.ts similarity index 100% rename from packages/channel/tests/pipe-watcher.test.ts rename to packages/channel-hook/tests/pipe-watcher.test.ts diff --git a/packages/channel/tests/qq-hook-client.test.ts b/packages/channel-hook/tests/qq-hook-client.test.ts similarity index 100% rename from packages/channel/tests/qq-hook-client.test.ts rename to packages/channel-hook/tests/qq-hook-client.test.ts diff --git a/packages/channel-hook/tsconfig.json b/packages/channel-hook/tsconfig.json new file mode 100644 index 00000000..ebe23b84 --- /dev/null +++ b/packages/channel-hook/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": [ + "node" + ], + "noEmit": true + }, + "include": [ + "src/**/*", + "tests" + ], + "exclude": [ + "node_modules" + ] +} diff --git a/packages/channel-hook/vitest.config.ts b/packages/channel-hook/vitest.config.ts new file mode 100644 index 00000000..b0e95a5a --- /dev/null +++ b/packages/channel-hook/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + include: ['tests/**/*.test.ts'], + environment: 'node', + }, +}); diff --git a/packages/channel-socket/package.json b/packages/channel-socket/package.json new file mode 100644 index 00000000..6fb1029f --- /dev/null +++ b/packages/channel-socket/package.json @@ -0,0 +1,34 @@ +{ + "name": "@snowluma/channel-socket", + "version": "1.9.2", + "private": true, + "type": "module", + "description": "SnowLuma `socket` channel implementation — placeholder for the future pure-socket runtime (no QQ.exe, no hook). Today registers as a no-op `ChannelAdapter` so the Hub-adapter architecture is exercised end-to-end. Will gain a `SocketClient` long-lived TCP login session when the protocol runtime lands.", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./socket-channel": { + "types": "./src/socket-channel.ts", + "default": "./src/socket-channel.ts" + }, + "./socket-adapter": { + "types": "./src/socket-adapter.ts", + "default": "./src/socket-adapter.ts" + } + }, + "scripts": { + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@snowluma/channel": "workspace:*", + "@snowluma/common": "workspace:*" + }, + "devDependencies": { + "@types/node": "^24.12.2", + "typescript": "catalog:" + } +} diff --git a/packages/channel-socket/src/index.ts b/packages/channel-socket/src/index.ts new file mode 100644 index 00000000..2f0f8861 --- /dev/null +++ b/packages/channel-socket/src/index.ts @@ -0,0 +1,8 @@ +// `@snowluma/channel-socket` — future pure-socket transport (no +// QQ.exe, no hook). Today an empty stub so `Hub` can register it as a +// `ChannelAdapter` of kind `'socket'` and exercise the adapter pool +// end-to-end. Will materialise a real `SocketChannel` once the +// pure-socket login client lands. + +export { SocketChannel } from './socket-channel'; +export { SocketAdapter } from './socket-adapter'; diff --git a/packages/channel/src/socket-adapter.ts b/packages/channel-socket/src/socket-adapter.ts similarity index 93% rename from packages/channel/src/socket-adapter.ts rename to packages/channel-socket/src/socket-adapter.ts index cb12202b..db865be6 100644 --- a/packages/channel/src/socket-adapter.ts +++ b/packages/channel-socket/src/socket-adapter.ts @@ -1,4 +1,4 @@ -import type { ChannelAdapter, ChannelAdapterHost } from './adapter'; +import type { ChannelAdapter, ChannelAdapterHost } from '@snowluma/channel'; /** * `SocketAdapter` — placeholder for the future pure-socket runtime. diff --git a/packages/channel/src/socket-channel.ts b/packages/channel-socket/src/socket-channel.ts similarity index 96% rename from packages/channel/src/socket-channel.ts rename to packages/channel-socket/src/socket-channel.ts index 28736bc5..02451df1 100644 --- a/packages/channel/src/socket-channel.ts +++ b/packages/channel-socket/src/socket-channel.ts @@ -1,5 +1,5 @@ +import { Channel } from '@snowluma/channel'; import type { SendPacketResult } from '@snowluma/common/packet-sender'; -import { Channel } from './channel'; /** * `SocketChannel` — placeholder transport for the future pure-socket diff --git a/packages/channel-socket/tsconfig.json b/packages/channel-socket/tsconfig.json new file mode 100644 index 00000000..9ed06e74 --- /dev/null +++ b/packages/channel-socket/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": [ + "node" + ], + "noEmit": true + }, + "include": [ + "src/**/*" + ], + "exclude": [ + "node_modules" + ] +} diff --git a/packages/channel/package.json b/packages/channel/package.json index 4d089c6c..732b74c2 100644 --- a/packages/channel/package.json +++ b/packages/channel/package.json @@ -3,7 +3,7 @@ "version": "1.9.2", "private": true, "type": "module", - "description": "SnowLuma transport layer (v3 rename of @snowluma/bridge). Defines the abstract `Channel` + `ChannelCtx` capability POJO + `ChannelAdapter` port that the Hub in @snowluma/core consumes, plus the in-process NTQQ hook runtime (HookManager / HookSession / pipe-watcher / injector / HookChannel / HookAdapter). The future `channel-socket` package will provide an alternative ChannelAdapter implementation.", + "description": "SnowLuma transport abstract layer. Defines the `Channel` abstract base + `ChannelCtx` capability POJO + `ChannelAdapter` port that `Hub` (in @snowluma/core) consumes. Concrete transports live in `@snowluma/channel-hook` (in-process NTQQ hook) and `@snowluma/channel-socket` (future pure-socket).", "main": "./src/index.ts", "types": "./src/index.ts", "exports": { @@ -26,58 +26,6 @@ "./adapter": { "types": "./src/adapter.ts", "default": "./src/adapter.ts" - }, - "./manager": { - "types": "./src/manager.ts", - "default": "./src/manager.ts" - }, - "./hook-channel": { - "types": "./src/hook-channel.ts", - "default": "./src/hook-channel.ts" - }, - "./hook-adapter": { - "types": "./src/hook-adapter.ts", - "default": "./src/hook-adapter.ts" - }, - "./socket-channel": { - "types": "./src/socket-channel.ts", - "default": "./src/socket-channel.ts" - }, - "./socket-adapter": { - "types": "./src/socket-adapter.ts", - "default": "./src/socket-adapter.ts" - }, - "./hook-manager": { - "types": "./src/hook-manager.ts", - "default": "./src/hook-manager.ts" - }, - "./hook-session": { - "types": "./src/hook-session.ts", - "default": "./src/hook-session.ts" - }, - "./hook-packet-client": { - "types": "./src/hook-packet-client.ts", - "default": "./src/hook-packet-client.ts" - }, - "./injector": { - "types": "./src/injector.ts", - "default": "./src/injector.ts" - }, - "./pipe-watcher": { - "types": "./src/pipe-watcher.ts", - "default": "./src/pipe-watcher.ts" - }, - "./qq-hook-client": { - "types": "./src/qq-hook-client.ts", - "default": "./src/qq-hook-client.ts" - }, - "./qq-port-probe": { - "types": "./src/qq-port-probe.ts", - "default": "./src/qq-port-probe.ts" - }, - "./types": { - "types": "./src/types.ts", - "default": "./src/types.ts" } }, "scripts": { diff --git a/packages/channel/src/index.ts b/packages/channel/src/index.ts index ac14ac6b..4358439f 100644 --- a/packages/channel/src/index.ts +++ b/packages/channel/src/index.ts @@ -1,25 +1,17 @@ -// ─── Hook runtime ────────────────────────────────────────────────── -export { - HookManager, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo, - type HookProcessStatus, type HookSink, type QqPortLoginInfo -} from './hook-manager'; +// `@snowluma/channel` — the abstract transport layer + capability POJO +// + adapter port. Concrete transports (HookChannel / SocketChannel) +// and their adapters live in dedicated packages +// (`@snowluma/channel-hook`, `@snowluma/channel-socket`); the +// multi-account host lives in `@snowluma/core` as `Hub`. Nothing in +// this package depends on a runtime — it's pure interfaces and the +// `Channel` abstract base. -// ─── Transport layer (abstract Channel + concrete HookChannel / SocketChannel) ── +// ─── Transport abstract base ─────────────────────────────────────── export { Channel } from './channel'; export { type ChannelInterface, type ChannelKind } from './channel-interface'; -export { HookChannel } from './hook-channel'; -export { SocketChannel } from './socket-channel'; -// ─── Channel capability POJO (handed to Core in @snowluma/core) ──── +// ─── Capability POJO (handed to Core in @snowluma/core) ──────────── export { makeChannelCtx, type ChannelCtx } from './channel-ctx'; -// ─── Adapter pattern ─────────────────────────────────────────────── +// ─── Adapter port ────────────────────────────────────────────────── export { type ChannelAdapter, type ChannelAdapterHost } from './adapter'; -export { HookAdapter, type HookAdapterOptions } from './hook-adapter'; -export { SocketAdapter } from './socket-adapter'; - -// ─── Multi-account host (v3 intermediate; folds into Hub later) ──── -export { - ChannelManager, type SessionClosedCallback, type SessionStartedCallback -} from './manager'; - diff --git a/packages/channel/src/manager.ts b/packages/channel/src/manager.ts deleted file mode 100644 index 6674caf2..00000000 --- a/packages/channel/src/manager.ts +++ /dev/null @@ -1,277 +0,0 @@ -import { createLogger } from '@snowluma/common/logger'; -import type { ChannelAdapter, ChannelAdapterHost } from './adapter'; -import type { Channel } from './channel'; -import type { ChannelKind } from './channel-interface'; - -export type SessionStartedCallback = (uin: string, channel: Channel) => void; -export type SessionClosedCallback = (uin: string) => void; - -const log = createLogger('Channel'); - -/** - * `ChannelManager` — multi-account host that wires channel **adapters** - * (transport sources) up to channel **consumers** (currently `Hub` in - * `@snowluma/core`; eventually OneBot indirectly). - * - * NOTE: this class is a temporary v3 intermediate. The migration plan - * folds it into `Hub` (in `@snowluma/core`) so the same object owns - * both the channel pool AND the `Core` instances bound to each - * channel. Until that move lands, `ChannelManager` retains the v2 - * session-callback API. - * - * The manager is intentionally transport-agnostic: it knows nothing - * about PIDs, named pipes, or future socket clients. Each adapter - * (`HookAdapter`, `SocketAdapter`, …) translates its own runtime into - * `addChannel` / `removeChannel` calls; the manager just keeps the - * `channelId → Channel` and `uin → channelId[]` indices up to date and - * fires the session callbacks consumers subscribe to. - * - * Multiple channels per UIN are explicitly supported (e.g. hook + pure - * socket on the same account). The primary channel for a UIN is the - * one that wins `primaryPriority`, which currently prefers `inject` - * over `socket` (operators trust the in-process hook more than the - * stand-alone socket client today). OneBot sees the primary; non- - * primary channels still receive packets normally but their events are - * dropped at the manager level so the user never sees duplicates. - */ -export class ChannelManager { - private readonly adapters_ = new Map(); - private readonly channelsById_ = new Map(); - private readonly channelsByUin_ = new Map>(); - private readonly primaryByUin_ = new Map(); - - private onSessionStarted_: SessionStartedCallback | null = null; - private onSessionClosed_: SessionClosedCallback | null = null; - - private started_ = false; - private disposed_ = false; - - // ─── callback wiring (consumed by OneBotManager) ───────────────── - - setSessionStartedCallback(cb: SessionStartedCallback): void { this.onSessionStarted_ = cb; } - setSessionClosedCallback(cb: SessionClosedCallback): void { this.onSessionClosed_ = cb; } - - // ─── adapter registration ──────────────────────────────────────── - - /** - * Register an adapter. Adapters may only be registered before - * `start()` is called; we surface a clear error otherwise so a - * mis-ordered bootstrap fails fast in dev. - * - * The manager enforces at most one adapter per `kind` — adapters are - * the singleton runtime owners (one hook runtime, one protocol - * runtime, …); multiple instances would race on the same login - * source. - */ - registerAdapter(adapter: ChannelAdapter): void { - if (this.started_) { - throw new Error('ChannelManager: cannot register adapters after start()'); - } - if (this.adapters_.has(adapter.kind)) { - throw new Error(`ChannelManager: adapter of kind '${adapter.kind}' is already registered`); - } - this.adapters_.set(adapter.kind, adapter); - } - - /** Look up an adapter by kind; returns `null` when not registered. */ - getAdapter(kind: ChannelKind): ChannelAdapter | null { - return this.adapters_.get(kind) ?? null; - } - - // ─── lifecycle ─────────────────────────────────────────────────── - - /** Start every registered adapter, passing each one its scoped - * `ChannelAdapterHost`. Idempotent. */ - async start(): Promise { - if (this.started_) return; - this.started_ = true; - for (const [kind, adapter] of this.adapters_) { - const host = this.makeHost(kind); - try { - await adapter.start(host); - } catch (err) { - log.warn( - 'adapter [%s] failed to start: %s', - kind, - err instanceof Error ? (err.stack ?? err.message) : String(err), - ); - } - } - } - - /** Dispose every adapter (which removes their channels via the host), - * then dispose any channels that somehow remain. Idempotent. */ - async dispose(): Promise { - if (this.disposed_) return; - this.disposed_ = true; - for (const [kind, adapter] of this.adapters_) { - try { - await adapter.dispose(); - } catch (err) { - log.warn( - 'adapter [%s] failed to dispose: %s', - kind, - err instanceof Error ? err.message : String(err), - ); - } - } - for (const channel of this.channelsById_.values()) { - try { channel.dispose(); } catch { /* ignore */ } - } - this.channelsById_.clear(); - this.channelsByUin_.clear(); - this.primaryByUin_.clear(); - } - - // ─── queries (used by WebUI / OneBot lookups) ──────────────────── - - /** Primary channel for a UIN (the one OneBot is bound to), or `null` - * if the UIN is currently offline. */ - getChannel(uin: string): Channel | null { - const id = this.primaryByUin_.get(uin); - return id ? this.channelsById_.get(id) ?? null : null; - } - - /** Every live channel across every adapter. Iteration order is - * insertion order. */ - getChannels(): readonly Channel[] { - return [...this.channelsById_.values()]; - } - - /** All channels currently servicing a given UIN (one per adapter - * kind at most). The primary is `getChannel(uin)`. */ - getChannelsForUin(uin: string): readonly Channel[] { - const ids = this.channelsByUin_.get(uin); - if (!ids) return []; - const out: Channel[] = []; - for (const id of ids) { - const channel = this.channelsById_.get(id); - if (channel) out.push(channel); - } - return out; - } - - /** UINs currently online (at least one channel). */ - getOnlineUins(): readonly string[] { - return [...this.channelsByUin_.keys()]; - } - - // ─── ChannelAdapterHost implementation (per-adapter) ───────────── - - private makeHost(kind: ChannelKind): ChannelAdapterHost { - const adapterLog = log.child({ adapter: kind }); - return { - log: adapterLog, - addChannel: (channel) => this.addChannel(channel, adapterLog), - removeChannel: (id) => this.removeChannel(id, adapterLog), - }; - } - - private addChannel(channel: Channel, adapterLog: { warn: (msg: string, ...args: unknown[]) => void }): void { - if (this.disposed_) return; - if (this.channelsById_.has(channel.id)) { - adapterLog.warn('addChannel: channel id=%s is already registered, ignoring', channel.id); - return; - } - this.channelsById_.set(channel.id, channel); - - let ids = this.channelsByUin_.get(channel.uin); - if (!ids) { - ids = new Set(); - this.channelsByUin_.set(channel.uin, ids); - } - ids.add(channel.id); - - const prevPrimaryId = this.primaryByUin_.get(channel.uin); - const newPrimary = this.pickPrimary(channel.uin); - if (!newPrimary) return; - this.primaryByUin_.set(channel.uin, newPrimary.id); - - const isFirst = prevPrimaryId === undefined; - const primaryChanged = !isFirst && prevPrimaryId !== newPrimary.id; - - if (isFirst) { - log.debug('session started: UIN=%s via %s', channel.uin, newPrimary.id); - this.onSessionStarted_?.(channel.uin, newPrimary); - } else if (primaryChanged) { - // A higher-priority transport (e.g. socket overtaking inject) - // came online. Treat it as restart-in-place: notify closed for - // the old primary, then started for the new one. OneBot already - // tears down + rebuilds its instance on closed→started, which - // is the only safe way to swap a channel under it today. - log.debug('primary switched: UIN=%s %s → %s', - channel.uin, prevPrimaryId, newPrimary.id); - this.onSessionClosed_?.(channel.uin); - this.onSessionStarted_?.(channel.uin, newPrimary); - } - } - - private removeChannel(id: string, adapterLog: { debug: (msg: string, ...args: unknown[]) => void }): void { - const channel = this.channelsById_.get(id); - if (!channel) return; - this.channelsById_.delete(id); - - const ids = this.channelsByUin_.get(channel.uin); - if (ids) { - ids.delete(id); - if (ids.size === 0) this.channelsByUin_.delete(channel.uin); - } - - const wasPrimary = this.primaryByUin_.get(channel.uin) === id; - if (wasPrimary) this.primaryByUin_.delete(channel.uin); - - const replacement = this.pickPrimary(channel.uin); - if (replacement) { - // Another transport is still online for this UIN. Update primary - // and, if we just demoted the previously-primary, notify - // consumers so OneBot rebinds to the survivor. - this.primaryByUin_.set(channel.uin, replacement.id); - if (wasPrimary) { - adapterLog.debug('primary failover: UIN=%s %s → %s', - channel.uin, id, replacement.id); - this.onSessionClosed_?.(channel.uin); - this.onSessionStarted_?.(channel.uin, replacement); - } - } else if (wasPrimary) { - // Last channel for this UIN is gone — session truly closed. - log.debug('session closed: UIN=%s', channel.uin); - this.onSessionClosed_?.(channel.uin); - } - - try { channel.dispose(); } catch (err) { - adapterLog.debug('channel.dispose() threw: %s', err instanceof Error ? err.message : String(err)); - } - } - - private pickPrimary(uin: string): Channel | null { - const ids = this.channelsByUin_.get(uin); - if (!ids || ids.size === 0) return null; - - let best: Channel | null = null; - let bestRank = -Infinity; - for (const id of ids) { - const channel = this.channelsById_.get(id); - if (!channel) continue; - const rank = primaryPriority(channel.kind); - if (rank > bestRank) { - best = channel; - bestRank = rank; - } - } - return best; - } -} - -/** - * Higher wins. Today we prefer the in-process hook over the future - * pure-socket runtime — operators with QQ.exe running tend to trust - * the hook path more, and the socket runtime is unproven. This single - * function is the only knob to flip later (or to surface as config) - * when the socket runtime is hardened. - */ -function primaryPriority(kind: ChannelKind): number { - switch (kind) { - case 'inject': return 100; - case 'socket': return 50; - } -} diff --git a/packages/core/package.json b/packages/core/package.json index 9b5e608f..dab25479 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -10,25 +10,25 @@ "types": "./src/index.ts", "default": "../../dist/index.mjs" }, - "./account": { - "types": "./src/account/account.ts", - "default": "./src/account/account.ts" + "./core": { + "types": "./src/core.ts", + "default": "./src/core.ts" }, - "./account-context": { - "types": "./src/account/account-context.ts", - "default": "./src/account/account-context.ts" + "./core-context": { + "types": "./src/core-context.ts", + "default": "./src/core-context.ts" }, - "./account-interface": { - "types": "./src/account/account-interface.ts", - "default": "./src/account/account-interface.ts" + "./core-ctx": { + "types": "./src/core-ctx.ts", + "default": "./src/core-ctx.ts" }, - "./account-manager": { - "types": "./src/account/account-manager.ts", - "default": "./src/account/account-manager.ts" + "./hub": { + "types": "./src/hub.ts", + "default": "./src/hub.ts" }, "./apis": { - "types": "./src/account/apis/index.ts", - "default": "./src/account/apis/index.ts" + "types": "./src/apis/index.ts", + "default": "./src/apis/index.ts" } }, "scripts": { @@ -41,6 +41,8 @@ }, "dependencies": { "@snowluma/channel": "workspace:*", + "@snowluma/channel-hook": "workspace:*", + "@snowluma/channel-socket": "workspace:*", "@snowluma/common": "workspace:*", "@snowluma/onebot": "workspace:*", "@snowluma/protocol": "workspace:*", diff --git a/packages/core/src/account/account-manager.ts b/packages/core/src/account/account-manager.ts deleted file mode 100644 index 09a25499..00000000 --- a/packages/core/src/account/account-manager.ts +++ /dev/null @@ -1,100 +0,0 @@ -import type { ChannelInterface, ChannelManager } from '@snowluma/channel'; -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(channelManager: ChannelManager): void { - channelManager.setSessionStartedCallback((uin: string, channel: ChannelInterface) => { - this.onChannelAvailable(uin, channel); - }); - channelManager.setSessionClosedCallback((uin: string) => { - this.onChannelUnavailable(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(); - } - - // ─── ChannelManager session-callback handlers ────────────────── - - private onChannelAvailable(uin: string, channel: ChannelInterface): void { - // Defensive: a stuck old account on the same UIN means - // ChannelManager 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(channel); - this.accounts_.set(uin, account); - log.debug('account started: UIN=%s id=%s', uin, account.id); - this.onAccountStarted_?.(uin, account); - } - - private onChannelUnavailable(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/account/apis/contacts.ts b/packages/core/src/apis/contacts.ts similarity index 98% rename from packages/core/src/account/apis/contacts.ts rename to packages/core/src/apis/contacts.ts index 9798c9a4..50c7b086 100644 --- a/packages/core/src/account/apis/contacts.ts +++ b/packages/core/src/apis/contacts.ts @@ -12,7 +12,7 @@ import type { QQGroupInfo, UserProfileInfo, } from '@snowluma/protocol/qq-info'; -import type { AccountContext } from '../account-context'; +import type { CoreContext } from '../core-context'; /** * One row of an `OidbSvcTrpcTcp.0x9067_202` (download rkey) response. @@ -77,7 +77,7 @@ export class ContactsApi { private memberListInflight = new Map>(); private memberListLastFetch = new Map(); - constructor(private readonly ctx: AccountContext) { } + constructor(private readonly ctx: CoreContext) { } async fetchFriendList(): Promise { const friends: FriendInfo[] = []; diff --git a/packages/core/src/account/apis/extras.ts b/packages/core/src/apis/extras.ts similarity index 96% rename from packages/core/src/account/apis/extras.ts rename to packages/core/src/apis/extras.ts index 54a64759..6a888e61 100644 --- a/packages/core/src/account/apis/extras.ts +++ b/packages/core/src/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 { AccountContext } from '../account-context'; +import type { CoreContext } from '../core-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: AccountContext) { } + constructor(private readonly ctx: CoreContext) { } // ─────────────── Group todo (0xF90) ─────────────── diff --git a/packages/core/src/account/apis/forward.ts b/packages/core/src/apis/forward.ts similarity index 99% rename from packages/core/src/account/apis/forward.ts rename to packages/core/src/apis/forward.ts index f03b8c1f..4e0dcb70 100644 --- a/packages/core/src/account/apis/forward.ts +++ b/packages/core/src/apis/forward.ts @@ -14,7 +14,7 @@ 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 { AccountContext } from '../account-context'; +import type { CoreContext } from '../core-context'; import { resolveSelfUid, toInt } from './shared'; // Module-scoped cache, keyed by res_id. Survives only for the lifetime @@ -201,7 +201,7 @@ function previewFromElements(elements: MessageElement[]): string { } export class ForwardApi { - constructor(private readonly ctx: AccountContext) { } + constructor(private readonly ctx: CoreContext) { } async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise { const { resId } = await this.uploadRecursive(nodes, groupId, userId); diff --git a/packages/core/src/account/apis/friend.ts b/packages/core/src/apis/friend.ts similarity index 90% rename from packages/core/src/account/apis/friend.ts rename to packages/core/src/apis/friend.ts index e1a541bf..9447d1d1 100644 --- a/packages/core/src/account/apis/friend.ts +++ b/packages/core/src/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 { AccountContext } from '../account-context'; +import type { CoreContext } from '../core-context'; export class FriendApi { - constructor(private readonly ctx: AccountContext) { } + constructor(private readonly ctx: CoreContext) { } /** * Accept or reject an inbound friend request. `uidOrFlag` is either a diff --git a/packages/core/src/account/apis/group-admin.ts b/packages/core/src/apis/group-admin.ts similarity index 96% rename from packages/core/src/account/apis/group-admin.ts rename to packages/core/src/apis/group-admin.ts index de8b5e04..4012d2fb 100644 --- a/packages/core/src/account/apis/group-admin.ts +++ b/packages/core/src/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 { AccountContext } from '../account-context'; +import type { CoreContext } from '../core-context'; export class GroupAdminApi { - constructor(private readonly ctx: AccountContext) { } + constructor(private readonly ctx: CoreContext) { } muteMember(groupId: number, userId: number, duration: number): Promise { return MuteMember.invoke(this.ctx, { groupId, userId, duration }); diff --git a/packages/core/src/account/apis/group-album.ts b/packages/core/src/apis/group-album.ts similarity index 98% rename from packages/core/src/account/apis/group-album.ts rename to packages/core/src/apis/group-album.ts index 84a0067a..101837b5 100644 --- a/packages/core/src/account/apis/group-album.ts +++ b/packages/core/src/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 { AccountContext } from '../account-context'; +import type { CoreContext } from '../core-context'; function convertBigIntToString(obj: unknown): JsonValue { @@ -31,7 +31,7 @@ function convertBigIntToString(obj: unknown): JsonValue { } export class GroupAlbumApi { - constructor(private readonly ctx: AccountContext) { } + constructor(private readonly ctx: CoreContext) { } // 列出群相册(基于 qzone.qq.com 的 HTTP Cookie)。 async list(groupId: number): Promise { diff --git a/packages/core/src/account/apis/group-file.ts b/packages/core/src/apis/group-file.ts similarity index 99% rename from packages/core/src/account/apis/group-file.ts rename to packages/core/src/apis/group-file.ts index 07d7e470..fb920e58 100644 --- a/packages/core/src/account/apis/group-file.ts +++ b/packages/core/src/apis/group-file.ts @@ -4,7 +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 { AccountContext } from '../account-context'; +import type { CoreContext } from '../core-context'; import { resolveSelfUid, toInt, type MediaIndexNode } from './shared'; import { CreateGroupFolder } from '@snowluma/protocol/oidb-services/group-file/create-group-folder'; @@ -214,7 +214,7 @@ function buildPrivateFileUploadExt( } export class GroupFileApi { - constructor(private readonly ctx: AccountContext) { } + constructor(private readonly ctx: CoreContext) { } // ─────────────── publish (group file → chat) ─────────────── diff --git a/packages/core/src/account/apis/index.ts b/packages/core/src/apis/index.ts similarity index 96% rename from packages/core/src/account/apis/index.ts rename to packages/core/src/apis/index.ts index 048c1da3..141d17b6 100644 --- a/packages/core/src/account/apis/index.ts +++ b/packages/core/src/apis/index.ts @@ -1,4 +1,4 @@ -import type { AccountContext } from '../account-context'; +import type { CoreContext } from '../core-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: AccountContext): ApiHub { +export function buildApiHub(ctx: CoreContext): ApiHub { return { message: new MessageApi(ctx), contacts: new ContactsApi(ctx), diff --git a/packages/core/src/account/apis/interaction.ts b/packages/core/src/apis/interaction.ts similarity index 96% rename from packages/core/src/account/apis/interaction.ts rename to packages/core/src/apis/interaction.ts index 45958d74..e89b0af7 100644 --- a/packages/core/src/account/apis/interaction.ts +++ b/packages/core/src/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 { AccountContext } from '../account-context'; +import type { CoreContext } from '../core-context'; export class InteractionApi { - constructor(private readonly ctx: AccountContext) { } + constructor(private readonly ctx: CoreContext) { } sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise { return SendPoke.invoke(this.ctx, { isGroup, peerUin, targetUin }); diff --git a/packages/core/src/account/apis/message.ts b/packages/core/src/apis/message.ts similarity index 99% rename from packages/core/src/account/apis/message.ts rename to packages/core/src/apis/message.ts index 7cf26baf..d5d3e25b 100644 --- a/packages/core/src/account/apis/message.ts +++ b/packages/core/src/apis/message.ts @@ -11,7 +11,7 @@ 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 { AccountContext } from '../account-context'; +import type { CoreContext } from '../core-context'; /** * Receipt returned by every typed `send*Message` call. The OneBot @@ -30,7 +30,7 @@ export interface SendMessageReceipt { const SEND_MSG_CMD = 'MessageSvc.PbSendMsg'; export class MessageApi { - constructor(private readonly ctx: AccountContext) { } + constructor(private readonly ctx: CoreContext) { } /** * Send a message to a QQ group. diff --git a/packages/core/src/account/apis/misc.ts b/packages/core/src/apis/misc.ts similarity index 95% rename from packages/core/src/account/apis/misc.ts rename to packages/core/src/apis/misc.ts index 4ab2dc97..91e5e683 100644 --- a/packages/core/src/account/apis/misc.ts +++ b/packages/core/src/apis/misc.ts @@ -8,10 +8,10 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; 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'; +import type { CoreContext } from '../core-context'; export class MiscApi { - constructor(private readonly ctx: AccountContext) { } + constructor(private readonly ctx: CoreContext) { } translateEn2Zh(words: string[]): Promise { return TranslateEnToZh.invoke(this.ctx, { words }); diff --git a/packages/core/src/account/apis/profile.ts b/packages/core/src/apis/profile.ts similarity index 98% rename from packages/core/src/account/apis/profile.ts rename to packages/core/src/apis/profile.ts index 0315e713..7f17ea84 100644 --- a/packages/core/src/account/apis/profile.ts +++ b/packages/core/src/apis/profile.ts @@ -13,10 +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 { AccountContext } from '../account-context'; +import type { CoreContext } from '../core-context'; export class ProfileApi { - constructor(private readonly ctx: AccountContext) { } + constructor(private readonly ctx: CoreContext) { } // ─────────────── status / profile setters ─────────────── diff --git a/packages/core/src/account/apis/shared.ts b/packages/core/src/apis/shared.ts similarity index 100% rename from packages/core/src/account/apis/shared.ts rename to packages/core/src/apis/shared.ts diff --git a/packages/core/src/account/apis/web.ts b/packages/core/src/apis/web.ts similarity index 98% rename from packages/core/src/account/apis/web.ts rename to packages/core/src/apis/web.ts index ed3388c9..77f01901 100644 --- a/packages/core/src/account/apis/web.ts +++ b/packages/core/src/apis/web.ts @@ -11,7 +11,7 @@ import { type SetNoticeRetSuccess, } from '@snowluma/protocol/web/group-notice'; import { RequestUtil } from '@snowluma/protocol/web/request-util'; -import type { AccountContext } from '../account-context'; +import type { CoreContext } from '../core-context'; export type ClientKeyInfo = NamespaceClientKeyInfo; @@ -117,7 +117,7 @@ function getBknFromSKey(skey: string): number { } export class WebApi { - constructor(private readonly ctx: AccountContext) { } + constructor(private readonly ctx: CoreContext) { } // ─────────────── cookie / token primitives ─────────────── diff --git a/packages/core/src/account/account-context.ts b/packages/core/src/core-context.ts similarity index 60% rename from packages/core/src/account/account-context.ts rename to packages/core/src/core-context.ts index aa587531..c6230dde 100644 --- a/packages/core/src/account/account-context.ts +++ b/packages/core/src/core-context.ts @@ -2,8 +2,9 @@ import type { BridgeContext as ProtocolBridgeContext } from '@snowluma/protocol/ import type { ApiHub } from './apis'; /** - * `AccountContext` — the **account-layer** context that Api wrappers - * (`apis/*`) consume. + * `CoreContext` — the internal context that Api wrappers (`apis/*`) + * consume. Only used inside `@snowluma/core`; OneBot and other inbound + * adapters consume the narrower `CoreCtx` projection instead. * * It extends the protocol-layer `BridgeContext` with one extra slot: * `apis: ApiHub`. The protocol layer can't mention `ApiHub` because @@ -12,13 +13,13 @@ import type { ApiHub } from './apis'; * - `@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 + * - `@snowluma/core/core-context.CoreContext` — 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. + * The concrete `Core` class implements this extended interface. */ -export interface AccountContext extends ProtocolBridgeContext { +export interface CoreContext extends ProtocolBridgeContext { readonly apis: ApiHub; } diff --git a/packages/core/src/account/account-interface.ts b/packages/core/src/core-ctx.ts similarity index 53% rename from packages/core/src/account/account-interface.ts rename to packages/core/src/core-ctx.ts index 5e9a9d27..a21be5a3 100644 --- a/packages/core/src/account/account-interface.ts +++ b/packages/core/src/core-ctx.ts @@ -1,30 +1,30 @@ import type { ChannelKind } from '@snowluma/channel'; -import type { AccountContext } from './account-context'; +import type { CoreContext } from './core-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. + * `CoreCtx` — the public surface every QQ account exposes to the rest + * of the system (OneBot, future MCP clients, WebUI status panels). It + * is the structural projection of a `Core` instance that consumers + * receive via `Hub.events.on('core-online', ...)`. * * 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 + * are inherited from `CoreContext`. + * - `kind` / `id` / `uin` mirror the underlying channel'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. + * - `dispose()` is the lifecycle hook; `Hub` calls it when the + * underlying channel disappears. * * Day-to-day consumers should stay kind-agnostic — that's the entire * point of the abstraction. */ -export interface AccountInterface extends AccountContext { +export interface CoreCtx extends CoreContext { /** Transport family backing this account. */ readonly kind: ChannelKind; - /** Stable, unique-per-account id (mirrors the transport's id). */ + /** Stable, unique-per-account id (mirrors the channel's id). */ readonly id: string; /** QQ number this account represents. Mirrors `identity.uin`. */ readonly uin: string; diff --git a/packages/core/src/account/account.ts b/packages/core/src/core.ts similarity index 67% rename from packages/core/src/account/account.ts rename to packages/core/src/core.ts index 824466fa..13b3d3ea 100644 --- a/packages/core/src/account/account.ts +++ b/packages/core/src/core.ts @@ -1,4 +1,4 @@ -import type { ChannelInterface, ChannelKind } from '@snowluma/channel'; +import type { ChannelCtx, ChannelKind } from '@snowluma/channel'; import type { SendPacketResult } from '@snowluma/common/packet-sender'; import type { PacketInfo } from '@snowluma/common/protocol-types'; import type { UploadedFileMeta } from '@snowluma/protocol/bridge-context'; @@ -6,33 +6,36 @@ 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 type { CoreCtx } from './core-ctx'; /** - * `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: + * `Core` — the QQ-account-level business object that sits on top of a + * `Channel` transport (consumed indirectly via a `ChannelCtx` + * capability POJO). Owns everything OneBot, the apis, and the msg-push + * pipeline care about: * * - `identity` (per-uin SQLite-backed roster + uid↔uin index), - * - the typed `BridgeEventBus` (subscribe to bridge events by kind), + * - the typed `BridgeEventBus` (subscribe to per-account events by kind), * - the `ApiHub` (typed wrappers around `sendRawPacket`), * - the `IncomingPacketPipeline` (cmd → decoder → emit on bus), * - the uploaded-file cache (shared between `upload_*_file` and * `send_msg`), * - the monotonic `clientSequence` / `messageRandom` counters. * - * 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. + * The transport is opaque: `Core` only calls `channelCtx.sendRawPacket` + * and subscribes via `channelCtx.onPacket` so all incoming packets flow + * into its pipeline. Swap the transport (hook → socket) and everything + * above keeps working unchanged because `Core` never holds the `Channel` + * itself — only the capability POJO. * - * 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. + * Lifecycle is managed by `Hub`: the hub registers `ChannelAdapter`s, + * builds a `ChannelCtx` from each freshly-available channel, materialises + * a `Core` on the way up, and calls `dispose()` on the way down. OneBot + * consumers see `CoreCtx` (the structural projection); never `Core` + * itself. */ -export class Account implements AccountInterface { +export class Core implements CoreCtx { readonly kind: ChannelKind; readonly id: string; readonly uin: string; @@ -40,7 +43,7 @@ export class Account implements AccountInterface { readonly events = new BridgeEventBus(); readonly apis: ApiHub; - private readonly transport_: ChannelInterface; + private readonly channelCtx_: ChannelCtx; private readonly pipeline_: IncomingPacketPipeline; private static readonly UPLOADED_FILE_CACHE_MAX = 1024; private readonly uploadedFileMeta_ = new Map(); @@ -49,20 +52,21 @@ export class Account implements AccountInterface { private disposed_ = false; /** - * @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. + * @param channelCtx The capability POJO this core rides on top of. + * `Core` calls `channelCtx.sendRawPacket` and + * subscribes via `channelCtx.onPacket`. Built by + * `Hub` from a concrete `Channel` via `makeChannelCtx`. + * @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: ChannelInterface, identity: IdentityService = IdentityService.openForUin(bridge.uin)) { - this.transport_ = bridge; - this.kind = bridge.kind; - this.id = bridge.id; - this.uin = bridge.uin; + constructor(channelCtx: ChannelCtx, identity: IdentityService = IdentityService.openForUin(channelCtx.uin)) { + this.channelCtx_ = channelCtx; + this.kind = channelCtx.kind; + this.id = `${channelCtx.kind}:${channelCtx.uin}`; + this.uin = channelCtx.uin; this.identity = identity; this.apis = buildApiHub(this); this.identity.setFetcher({ @@ -99,18 +103,19 @@ export class Account implements AccountInterface { }); 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)); + // Subscribe to inbound packets from the channel. The underlying + // `Channel` only supports a single subscriber (us); the + // `ChannelAdapter` pumps packets through `channel.deliverPacket`, + // which `Hub` wires into us via `channelCtx.onPacket`. + channelCtx.onPacket((pkt: PacketInfo) => this.pipeline_.process(pkt)); } - // ─── AccountInterface plumbing ───────────────────────────────── + // ─── CoreCtx plumbing ──────────────────────────────────────────── dispose(): void { if (this.disposed_) return; this.disposed_ = true; - this.transport_.setPacketHandler(null); + this.channelCtx_.onPacket(null); this.identity.close(); this.events.clear(); } @@ -124,7 +129,7 @@ export class Account implements AccountInterface { body: Uint8Array, timeoutMs?: number, ): Promise { - return this.transport_.sendRawPacket(serviceCmd, body, timeoutMs); + return this.channelCtx_.sendRawPacket(serviceCmd, body, timeoutMs); } // ─── Pipeline registration (used by tests + extra cmd modules) ─ @@ -152,7 +157,7 @@ export class Account implements AccountInterface { rememberUploadedFile(meta: UploadedFileMeta): void { if (!meta.fileId) return; - if (this.uploadedFileMeta_.size >= Account.UPLOADED_FILE_CACHE_MAX) { + if (this.uploadedFileMeta_.size >= Core.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); diff --git a/packages/core/src/hub.ts b/packages/core/src/hub.ts new file mode 100644 index 00000000..90d5d13c --- /dev/null +++ b/packages/core/src/hub.ts @@ -0,0 +1,340 @@ +import { + makeChannelCtx, + type Channel, + type ChannelAdapter, + type ChannelAdapterHost, + type ChannelKind, +} from '@snowluma/channel'; +import { createLogger, type Logger } from '@snowluma/common/logger'; +import { Core } from './core'; +import type { CoreCtx } from './core-ctx'; + +const log = createLogger('Hub'); + +/** + * Top-level lifecycle events fired by `Hub`. Inbound consumers (OneBot, + * WebUI backend, future MCP) subscribe via `hub.events.on(...)`. + */ +export type HubEventMap = { + /** Fired whenever a fresh `Core` is online for a UIN. Either the + * account just came up, OR the primary channel was swapped under it + * (in which case `'core-offline'` for the same UIN fired first). */ + 'core-online': CoreCtx; + /** Fired when an account goes offline OR right before a primary- + * channel swap rebuilds its `Core`. */ + 'core-offline': { uin: string }; +}; + +export type HubEventHandler = (payload: HubEventMap[K]) => void; +export type HubEventDisposer = () => void; + +/** + * Tiny typed event emitter scoped to `Hub`'s lifecycle events. Kept + * inline rather than reaching for `@snowluma/protocol/event-bus` + * (which is hard-typed to QQ event variants) or a generic dependency. + * + * Subscriber errors are swallowed with a warning so one bad consumer + * never blocks the rest. + */ +class HubEvents { + private readonly listeners_ = new Map void>>(); + + on(event: K, handler: HubEventHandler): HubEventDisposer { + let set = this.listeners_.get(event); + if (!set) { + set = new Set(); + this.listeners_.set(event, set); + } + const wrapped = handler as (p: unknown) => void; + set.add(wrapped); + return () => set!.delete(wrapped); + } + + emit(event: K, payload: HubEventMap[K]): void { + const set = this.listeners_.get(event); + if (!set || set.size === 0) return; + for (const handler of [...set]) { + try { + (handler as HubEventHandler)(payload); + } catch (err) { + log.warn('hub listener (%s) threw: %s', event, err instanceof Error ? err.message : String(err)); + } + } + } + + clear(): void { + this.listeners_.clear(); + } +} + +/** + * `Hub` — the single multi-account entry point and **owner of all + * channels and cores**. Replaces the v2 split between + * `ChannelManager` (transport pool, lived in `@snowluma/channel`) and + * `AccountManager` (account wrapper, lived in `@snowluma/core`). + * + * Responsibilities (folded from both predecessors): + * + * 1. Register one `ChannelAdapter` per transport kind (hook, + * socket, …). Adapters publish/withdraw `Channel`s through the + * `ChannelAdapterHost` interface that Hub implements per-adapter. + * 2. Track every live channel (`channelsById_` / `channelsByUin_`) + * and pick a primary per UIN (`primaryByUin_`) by adapter rank + * (`primaryPriority`: inject > socket today). + * 3. Build a `ChannelCtx` capability POJO from each primary channel + * and materialise a `Core` on top. + * 4. Emit two top-level lifecycle events: `'core-online'` (with the + * `CoreCtx` projection) and `'core-offline'` (with `{ uin }`). + * Inbound consumers (OneBot, WebUI) only see these two events; + * they never touch the underlying `Channel` / `Core` classes. + * + * Single-owner invariant: every `Channel` and every `Core` instance + * is referenced exactly once — from inside `Hub`. External consumers + * hold only `CoreCtx` projections, which become stale when `Core` + * is disposed (handlers should unsubscribe in their `'core-offline'` + * handler). + */ +export class Hub { + // ─── adapter / channel pool (was ChannelManager) ────────────────── + private readonly adapters_ = new Map(); + private readonly channelsById_ = new Map(); + private readonly channelsByUin_ = new Map>(); + private readonly primaryByUin_ = new Map(); + + // ─── core pool (was AccountManager) ────────────────────────────── + private readonly cores_ = new Map(); + + // ─── lifecycle event bus ────────────────────────────────────────── + readonly events = new HubEvents(); + + private started_ = false; + private disposed_ = false; + + // ─── adapter registration ──────────────────────────────────────── + + /** + * Register a channel adapter. Must be called BEFORE `start()`; the + * hub enforces at most one adapter per `kind`. + */ + registerAdapter(adapter: ChannelAdapter): void { + if (this.started_) { + throw new Error('Hub: cannot register adapters after start()'); + } + if (this.adapters_.has(adapter.kind)) { + throw new Error(`Hub: adapter of kind '${adapter.kind}' is already registered`); + } + this.adapters_.set(adapter.kind, adapter); + } + + getAdapter(kind: ChannelKind): ChannelAdapter | null { + return this.adapters_.get(kind) ?? null; + } + + // ─── lifecycle ─────────────────────────────────────────────────── + + /** Start every registered adapter. Idempotent. */ + async start(): Promise { + if (this.started_) return; + this.started_ = true; + for (const [kind, adapter] of this.adapters_) { + const host = this.makeHost(kind); + try { + await adapter.start(host); + } catch (err) { + log.warn('adapter [%s] failed to start: %s', kind, + err instanceof Error ? (err.stack ?? err.message) : String(err)); + } + } + } + + /** Dispose every adapter (which removes their channels via the + * host), then dispose any cores/channels that somehow remain. + * Idempotent. */ + async dispose(): Promise { + if (this.disposed_) return; + this.disposed_ = true; + for (const [kind, adapter] of this.adapters_) { + try { + await adapter.dispose(); + } catch (err) { + log.warn('adapter [%s] failed to dispose: %s', kind, + err instanceof Error ? err.message : String(err)); + } + } + for (const core of this.cores_.values()) { + try { core.dispose(); } catch { /* ignore */ } + } + for (const channel of this.channelsById_.values()) { + try { channel.dispose(); } catch { /* ignore */ } + } + this.cores_.clear(); + this.channelsById_.clear(); + this.channelsByUin_.clear(); + this.primaryByUin_.clear(); + this.events.clear(); + } + + // ─── queries ───────────────────────────────────────────────────── + + /** The `Core` (full business object) for a UIN, or `null` if no + * account is online. Internal-ish — callers typically work with + * `CoreCtx` received from the `'core-online'` event instead. */ + getCore(uin: string): Core | null { + return this.cores_.get(uin) ?? null; + } + + getCores(): readonly Core[] { + return [...this.cores_.values()]; + } + + /** Primary channel for a UIN (the one driving the current `Core`), + * or `null` if the UIN is offline. */ + getChannel(uin: string): Channel | null { + const id = this.primaryByUin_.get(uin); + return id ? this.channelsById_.get(id) ?? null : null; + } + + getOnlineUins(): readonly string[] { + return [...this.channelsByUin_.keys()]; + } + + // ─── ChannelAdapterHost implementation (per-adapter) ───────────── + + private makeHost(kind: ChannelKind): ChannelAdapterHost { + const adapterLog = log.child({ adapter: kind }); + return { + log: adapterLog, + addChannel: (channel) => this.addChannel(channel, adapterLog), + removeChannel: (id) => this.removeChannel(id, adapterLog), + }; + } + + private addChannel(channel: Channel, adapterLog: Logger): void { + if (this.disposed_) return; + if (this.channelsById_.has(channel.id)) { + adapterLog.warn('addChannel: id=%s already registered, ignoring', channel.id); + return; + } + this.channelsById_.set(channel.id, channel); + + let ids = this.channelsByUin_.get(channel.uin); + if (!ids) { + ids = new Set(); + this.channelsByUin_.set(channel.uin, ids); + } + ids.add(channel.id); + + const prevPrimaryId = this.primaryByUin_.get(channel.uin); + const newPrimary = this.pickPrimary(channel.uin); + if (!newPrimary) return; + this.primaryByUin_.set(channel.uin, newPrimary.id); + + const isFirst = prevPrimaryId === undefined; + const primaryChanged = !isFirst && prevPrimaryId !== newPrimary.id; + + if (isFirst) { + log.debug('account online: UIN=%s via %s', channel.uin, newPrimary.id); + this.bringCoreOnline(channel.uin, newPrimary); + } else if (primaryChanged) { + // A higher-priority transport (e.g. socket overtakes inject) + // came online. Tear down the old core and rebuild around the + // new primary so apis/identity stay consistent with the active + // transport. OneBot already tears down + rebuilds its instance + // on offline→online; we faithfully drive that. + log.debug('primary switched: UIN=%s %s → %s', + channel.uin, prevPrimaryId, newPrimary.id); + this.bringCoreOffline(channel.uin); + this.bringCoreOnline(channel.uin, newPrimary); + } + } + + private removeChannel(id: string, adapterLog: Logger): void { + const channel = this.channelsById_.get(id); + if (!channel) return; + this.channelsById_.delete(id); + + const ids = this.channelsByUin_.get(channel.uin); + if (ids) { + ids.delete(id); + if (ids.size === 0) this.channelsByUin_.delete(channel.uin); + } + + const wasPrimary = this.primaryByUin_.get(channel.uin) === id; + if (wasPrimary) this.primaryByUin_.delete(channel.uin); + + const replacement = this.pickPrimary(channel.uin); + if (replacement) { + this.primaryByUin_.set(channel.uin, replacement.id); + if (wasPrimary) { + adapterLog.debug('primary failover: UIN=%s %s → %s', + channel.uin, id, replacement.id); + this.bringCoreOffline(channel.uin); + this.bringCoreOnline(channel.uin, replacement); + } + } else if (wasPrimary) { + log.debug('account offline: UIN=%s', channel.uin); + this.bringCoreOffline(channel.uin); + } + + try { channel.dispose(); } catch (err) { + adapterLog.debug('channel.dispose() threw: %s', + err instanceof Error ? err.message : String(err)); + } + } + + private bringCoreOnline(uin: string, channel: Channel): void { + // Defensive: stale core on the same UIN means we missed the + // offline event. Tear it down first so identity DB handles don't + // leak. + const stale = this.cores_.get(uin); + if (stale) { + log.warn('replacing stale core: UIN=%s id=%s', uin, stale.id); + try { stale.dispose(); } catch { /* ignore */ } + this.cores_.delete(uin); + } + const core = new Core(makeChannelCtx(channel)); + this.cores_.set(uin, core); + this.events.emit('core-online', core); + } + + private bringCoreOffline(uin: string): void { + const core = this.cores_.get(uin); + if (!core) return; + this.cores_.delete(uin); + this.events.emit('core-offline', { uin }); + try { core.dispose(); } catch (err) { + log.debug('core.dispose() threw: %s', err instanceof Error ? err.message : String(err)); + } + } + + private pickPrimary(uin: string): Channel | null { + const ids = this.channelsByUin_.get(uin); + if (!ids || ids.size === 0) return null; + + let best: Channel | null = null; + let bestRank = -Infinity; + for (const id of ids) { + const channel = this.channelsById_.get(id); + if (!channel) continue; + const rank = primaryPriority(channel.kind); + if (rank > bestRank) { + best = channel; + bestRank = rank; + } + } + return best; + } +} + +/** + * Higher wins. Today we prefer the in-process hook over the future + * pure-socket runtime — operators with QQ.exe running trust the hook + * path more, and the socket runtime is unproven. Single knob to flip + * (or surface as config) once the socket runtime is hardened. + */ +function primaryPriority(kind: ChannelKind): number { + switch (kind) { + case 'inject': return 100; + case 'socket': return 50; + } +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 495460a6..92093654 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,8 +1,9 @@ -import { ChannelManager, HookAdapter, SocketAdapter } from '@snowluma/channel'; +import { HookAdapter } from '@snowluma/channel-hook'; +import { SocketAdapter } from '@snowluma/channel-socket'; import { closeLogger, createLogger } from '@snowluma/common/logger'; import { loadRuntimeConfig } from '@snowluma/common/runtime'; import { OneBotManager } from '@snowluma/onebot/manager'; -import { AccountManager } from './account/account-manager'; +import { Hub } from './hub'; const runtimeConfig = loadRuntimeConfig(); const log = createLogger('App'); @@ -10,14 +11,11 @@ const log = createLogger('App'); async function main() { log.info('SnowLuma starting'); - // ChannelManager is a transport-agnostic host: it learns about live - // accounts only through registered ChannelAdapters. Today we have - // two adapters — `hook` (NTQQ in-process hook, fully wired) and - // `socket` (future pure-socket runtime, registered as a stub so the - // architecture is exercised end-to-end). Both must be registered - // BEFORE channelManager.start(). - const channelManager = new ChannelManager(); - const accountManager = new AccountManager(); + // `Hub` is the single multi-account entry point — it owns channel + // adapters (hook, socket), the per-uin `Core` map, and the + // `core-online` / `core-offline` lifecycle event bus. Adapters + // must be registered BEFORE hub.start(). + const hub = new Hub(); const oneBotManager = new OneBotManager(); const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad); @@ -25,17 +23,16 @@ async function main() { log.info('hook auto-load enabled: every discovered QQ process will be injected'); } const hookAdapter = new HookAdapter({ autoLoadOnDiscovery }); - channelManager.registerAdapter(hookAdapter); - channelManager.registerAdapter(new SocketAdapter()); + hub.registerAdapter(hookAdapter); + hub.registerAdapter(new SocketAdapter()); - // Layer chain: ChannelManager (transport pool) → AccountManager - // (wraps each primary channel in an Account) → OneBotManager (one - // OneBotInstance per Account). Bind before start() so the very - // first login is delivered down the chain. - accountManager.bind(channelManager); - oneBotManager.bind(accountManager); + // OneBot subscribes to Hub's two lifecycle events (`core-online` / + // `core-offline`) to materialise / tear down its per-account + // instances. Bind before start() so the very first login is + // delivered to OneBot. + oneBotManager.bind(hub); - await channelManager.start(); + await hub.start(); if ( (typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) || @@ -58,8 +55,7 @@ async function main() { const shutdown = (signal: string) => async () => { log.warn(`Shutting down (${signal})...`); oneBotManager.dispose(); - accountManager.dispose(); - await channelManager.dispose(); + await hub.dispose(); await closeLogger(); process.exit(0); }; diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 0e033cb9..fc82efa9 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -1,6 +1,6 @@ import { serve } from '@hono/node-server'; import { serveStatic } from '@hono/node-server/serve-static'; -import type { HookManager, HookProcessInfo } from '@snowluma/channel'; +import type { HookManager, HookProcessInfo } from '@snowluma/channel-hook'; import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger'; import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config'; import type { OneBotManager } from '@snowluma/onebot/manager'; diff --git a/packages/core/tests/account-member-identity.test.ts b/packages/core/tests/account-member-identity.test.ts index 1ee2020f..2dc5b93b 100644 --- a/packages/core/tests/account-member-identity.test.ts +++ b/packages/core/tests/account-member-identity.test.ts @@ -1,10 +1,11 @@ -import { HookChannel } from '@snowluma/channel'; +import { makeChannelCtx } from '@snowluma/channel'; +import { HookChannel } from '@snowluma/channel-hook'; 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 { Account } from '../src/account/account'; +import { Core } from '../src/core'; const SELF_UIN = '10001'; const GROUP_ID = 123456789; @@ -36,26 +37,27 @@ function makeGroup(members: GroupMemberInfo[] = []): QQGroupInfo { } /** - * `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. + * `Core` wired up with a member-list interceptor. The interceptor + * lives on `core.apis.contacts.fetchGroupMemberList`; direct property + * assignment is enough because the ApiHub holds own-property methods, + * not prototype ones. The underlying `HookChannel` is exposed so tests + * can drive `deliverPacket` directly. */ -function buildAccount(identity: IdentityService, refreshedMembers: GroupMemberInfo[]) { - const bridge = new HookChannel(identity.uin); - const account = new Account(bridge, identity); +function buildCore(identity: IdentityService, refreshedMembers: GroupMemberInfo[]) { + const channel = new HookChannel(identity.uin); + const core = new Core(makeChannelCtx(channel), identity); const memberFetches: Array<{ groupId: number; force: boolean }> = []; - account.apis.contacts.fetchGroupMemberList = async ( + core.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); + core.identity.updateGroupMember(groupId, member); } return refreshedMembers; }; - return { account, bridge, memberFetches }; + return { core, channel, memberFetches }; } function makePacket(): PacketInfo { @@ -85,15 +87,15 @@ async function waitForEvent(events: GroupMemberJoin[]): Promise throw new Error('timed out waiting for group_member_join'); } -describe('Account group member identity refresh', () => { +describe('Core 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 { account, bridge, memberFetches } = buildAccount(identity, [member]); + const { core, channel, memberFetches } = buildCore(identity, [member]); const seen: GroupMemberJoin[] = []; - account.registerCmd('test.member_join', () => [{ + core.registerCmd('test.member_join', () => [{ kind: 'group_member_join', time: 1710000000, selfUin: Number(SELF_UIN), @@ -103,11 +105,11 @@ describe('Account group member identity refresh', () => { userUid: member.uid, operatorUid: member.uid, }]); - account.events.on('group_member_join', (event) => { + core.events.on('group_member_join', (event: GroupMemberJoin) => { seen.push(event); }); - bridge.deliverPacket(makePacket()); + channel.deliverPacket(makePacket()); const event = await waitForEvent(seen); expect(memberFetches).toEqual([{ groupId: GROUP_ID, force: true }]); @@ -116,8 +118,8 @@ describe('Account group member identity refresh', () => { }); it('remembers UID mappings from realtime request events', () => { - const bridge = new HookChannel(SELF_UIN); - const account = new Account(bridge, IdentityService.memory(SELF_UIN)); + const channel = new HookChannel(SELF_UIN); + const core = new Core(makeChannelCtx(channel), IdentityService.memory(SELF_UIN)); const events: QQEventVariant[] = [ { kind: 'friend_request', @@ -141,12 +143,12 @@ describe('Account group member identity refresh', () => { }, ]; - account.registerCmd('test.request_identity', () => events); - bridge.deliverPacket(makeRequestPacket()); + core.registerCmd('test.request_identity', () => events); + channel.deliverPacket(makeRequestPacket()); - 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); + expect(core.identity.findUidByUin(55555)).toBe('u_friend_request'); + expect(core.identity.findUidByUin(66666)).toBe('u_group_request'); + expect(core.identity.findUinByUid('u_friend_request')).toBe(55555); + expect(core.identity.findUinByUid('u_group_request')).toBe(66666); }); }); diff --git a/packages/core/tests/account-private-routing.test.ts b/packages/core/tests/account-private-routing.test.ts index a657c522..a9eb402c 100644 --- a/packages/core/tests/account-private-routing.test.ts +++ b/packages/core/tests/account-private-routing.test.ts @@ -1,27 +1,28 @@ -import type { ChannelInterface } from '@snowluma/channel'; +import type { ChannelCtx } from '@snowluma/channel'; 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'; +import { Core } from '../src/core'; vi.mock('@snowluma/protocol/element-builder', () => ({ buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]), })); /** - * Thin fake transport — implements `ChannelInterface` 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. + * Build a fake `ChannelCtx` POJO that captures the outbound packet + * body for assertions. The `Core` under test consumes this ctx exactly + * the way `Hub` would in production — via `sendRawPacket` and + * `onPacket` only. */ -class FakeBridge implements ChannelInterface { - readonly kind = 'inject' as const; - readonly id = 'inject:test'; - capturedBody: Uint8Array | null = null; - private response_: SendPacketResult = { +function makeFakeCtx(uin: string): { + ctx: ChannelCtx; + getCapturedBody: () => Uint8Array | null; + setResponse: (resp: SendPacketResult) => void; +} { + let capturedBody: Uint8Array | null = null; + let response: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, @@ -33,51 +34,40 @@ class FakeBridge implements ChannelInterface { 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 */ } + const ctx: ChannelCtx = { + uin, + kind: 'inject', + sendRawPacket: async (_cmd, body) => { + capturedBody = body; + return response; + }, + onPacket: () => { /* unused */ }, + dispose: () => { /* unused */ }, + }; + return { + ctx, + getCapturedBody: () => capturedBody, + setResponse: (resp) => { response = resp; }, + }; } -describe('Account private media routing', () => { +describe('Core private media routing', () => { it('includes resolved uid in the final c2c send request for media messages', async () => { const { IdentityService } = await import('@snowluma/protocol/identity-service'); - 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, - })), - }); - - const account = new Account(bridge, IdentityService.memory('10000')); + const fake = makeFakeCtx('10000'); + const core = new Core(fake.ctx, 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) => { + core.resolveUserUid = vi.fn(async (uin: number) => { expect(uin).toBe(12345); return 'u_peer_12345'; }); - await account.apis.message.sendPrivate(12345, [{ type: 'video', url: 'file:///tmp/clip.mp4' } as any]); + await core.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); + expect(fake.getCapturedBody()).toBeInstanceOf(Uint8Array); + const request = protobuf_decode(fake.getCapturedBody() as Uint8Array); expect(request?.routingHead?.c2c).toMatchObject({ uin: 12345, uid: 'u_peer_12345', @@ -95,11 +85,11 @@ describe('Account private media routing', () => { // c2cCmd=11 — the QQ-NT server rejected every c2c file send. const { IdentityService } = await import('@snowluma/protocol/identity-service'); - const bridge = new FakeBridge('10000'); - const account = new Account(bridge, IdentityService.memory('10000')); + const fake = makeFakeCtx('10000'); + const core = new Core(fake.ctx, IdentityService.memory('10000')); const fileMd5 = new Uint8Array([0xde, 0xad, 0xbe, 0xef]); - await account.apis.message.sendC2cFile(67890, 'u_peer_xyz', { + await core.apis.message.sendC2cFile(67890, 'u_peer_xyz', { fileId: 'uuid-abc-123', fileName: 'doc.txt', fileSize: 1024, @@ -107,7 +97,7 @@ describe('Account private media routing', () => { fileHash: 'hash-xyz', }); - const request = protobuf_decode(bridge.capturedBody as Uint8Array); + const request = protobuf_decode(fake.getCapturedBody() as Uint8Array); // Routing: must be trans0x211 with ccCmd=4 + uid, no c2c slot. expect(request?.routingHead?.trans0x211).toMatchObject({ diff --git a/packages/core/tests/actions/extras.test.ts b/packages/core/tests/actions/extras.test.ts index ef25d64d..04fed5ac 100644 --- a/packages/core/tests/actions/extras.test.ts +++ b/packages/core/tests/actions/extras.test.ts @@ -16,7 +16,7 @@ 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 { AiVoiceChatType, ExtrasApi } from '../../src/account/apis/extras'; +import { AiVoiceChatType, ExtrasApi } from '../../src/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 c3e424e9..f3f2d079 100644 --- a/packages/core/tests/actions/forward-file.test.ts +++ b/packages/core/tests/actions/forward-file.test.ts @@ -46,7 +46,7 @@ vi.mock('@snowluma/protocol/element-builder', () => ({ import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg'; import { protobuf_encode } from '@snowluma/proton'; -import { ForwardApi } from '../../src/account/apis/forward'; +import { ForwardApi } from '../../src/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 316a542d..ccc1768c 100644 --- a/packages/core/tests/actions/forward-nested.test.ts +++ b/packages/core/tests/actions/forward-nested.test.ts @@ -39,7 +39,7 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({ uploadVideoMsgInfo: vi.fn(async () => new Uint8Array()), })); -import { ForwardApi } from '../../src/account/apis/forward'; +import { ForwardApi } from '../../src/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 f39e8cff..57fdb7c7 100644 --- a/packages/core/tests/actions/forward.test.ts +++ b/packages/core/tests/actions/forward.test.ts @@ -16,7 +16,7 @@ vi.mock('@snowluma/protocol/element-builder', () => ({ import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg'; import { protobuf_encode } from '@snowluma/proton'; -import { ForwardApi } from '../../src/account/apis/forward'; +import { ForwardApi } from '../../src/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 7e9af8eb..9c5a8fc7 100644 --- a/packages/core/tests/actions/friend.test.ts +++ b/packages/core/tests/actions/friend.test.ts @@ -11,7 +11,7 @@ import { describe, expect, it, vi } from 'vitest'; // 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/account/apis/friend'; +import { FriendApi } from '../../src/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 407781bd..fa654027 100644 --- a/packages/core/tests/actions/group-admin.test.ts +++ b/packages/core/tests/actions/group-admin.test.ts @@ -21,7 +21,7 @@ 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/account/apis/group-admin'; +import { GroupAdminApi } from '../../src/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 5ca4c330..b9df8bd3 100644 --- a/packages/core/tests/actions/group-file.test.ts +++ b/packages/core/tests/actions/group-file.test.ts @@ -38,7 +38,7 @@ vi.mock('@snowluma/protocol/highway/utils', () => ({ })); import * as highwayClient from '@snowluma/protocol/highway'; -import { GroupFileApi } from '../../src/account/apis/group-file'; +import { GroupFileApi } from '../../src/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 d09a0257..d1ebe48e 100644 --- a/packages/core/tests/actions/group-message.test.ts +++ b/packages/core/tests/actions/group-message.test.ts @@ -13,7 +13,7 @@ vi.mock('@snowluma/protocol/bridge-oidb', () => ({ decodeOidbEnv: vi.fn(() => ({ body: {} })), })); -import { MessageApi } from '../../src/account/apis/message'; +import { MessageApi } from '../../src/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 810883c5..31fe8755 100644 --- a/packages/core/tests/actions/interaction.test.ts +++ b/packages/core/tests/actions/interaction.test.ts @@ -8,7 +8,7 @@ import { describe, expect, it } from 'vitest'; // 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/account/apis/interaction'; +import { InteractionApi } from '../../src/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 52ac1bbe..a526b840 100644 --- a/packages/core/tests/actions/misc.test.ts +++ b/packages/core/tests/actions/misc.test.ts @@ -10,7 +10,7 @@ import { describe, expect, it, vi } from 'vitest'; // @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/account/apis/misc'; +import { MiscApi } from '../../src/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 d83a1029..2fe936d4 100644 --- a/packages/core/tests/actions/profile.test.ts +++ b/packages/core/tests/actions/profile.test.ts @@ -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/account/apis/profile'; +import { ProfileApi } from '../../src/apis/profile'; import { mockBridge } from './_helpers'; describe('apis/profile', () => { diff --git a/packages/onebot/src/api-handler.ts b/packages/onebot/src/api-handler.ts index df97851a..0d9d08fd 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 { AccountInterface } from '@snowluma/core/account-interface'; +import type { CoreCtx } from '@snowluma/core/core-ctx'; 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: AccountInterface; + bridge: CoreCtx; 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 053cfe04..940c4271 100644 --- a/packages/onebot/src/instance-context.ts +++ b/packages/onebot/src/instance-context.ts @@ -1,4 +1,4 @@ -import type { AccountInterface } from '@snowluma/core/account-interface'; +import type { CoreCtx } from '@snowluma/core/core-ctx'; import type { WebHonorType } from '@snowluma/protocol/web/group-honor'; import type { ApiActionContext } from './api-handler'; import type { ConverterContext } from './event-converter'; @@ -40,7 +40,7 @@ import type { JsonObject, MessageMeta, OneBotConfig } from './types'; export interface OneBotInstanceContext { uin: string; selfId: number; - bridge: AccountInterface; + bridge: CoreCtx; messageStore: MessageStore; mediaStore: MediaStore; reactionStore: ReactionStore; diff --git a/packages/onebot/src/instance-rkey.ts b/packages/onebot/src/instance-rkey.ts index a10df495..33a8efc8 100644 --- a/packages/onebot/src/instance-rkey.ts +++ b/packages/onebot/src/instance-rkey.ts @@ -1,5 +1,5 @@ import { createLogger } from '@snowluma/common/logger'; -import type { AccountInterface } from '@snowluma/core/account-interface'; +import type { CoreCtx } from '@snowluma/core/core-ctx'; import type { DownloadRKeyInfo } from '@snowluma/core/apis'; import type { MessageElement } from '@snowluma/protocol/events'; @@ -27,7 +27,7 @@ export class RKeyCache { private cache = new Map(); private lastRefreshAttempt = 0; - warmUp(bridge: AccountInterface, uin: string): void { + warmUp(bridge: CoreCtx, uin: string): void { bridge.apis.contacts.fetchDownloadRKeys().then( (rkeys) => { this.updateCache(rkeys); @@ -39,7 +39,7 @@ export class RKeyCache { ); } - resolveImageUrl(bridge: AccountInterface, element: MessageElement, isGroup: boolean): string { + resolveImageUrl(bridge: CoreCtx, 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: AccountInterface, element: MessageElement, isGroup: boolean): string { + resolveMediaUrl(bridge: CoreCtx, 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: AccountInterface, isGroup: boolean): string | null { + private findRKey(bridge: CoreCtx, isGroup: boolean): string | null { const primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE; return this.findRKeyForType(bridge, primaryType); } - private findRKeyForType(bridge: AccountInterface, primaryType: number): string | null { + private findRKeyForType(bridge: CoreCtx, 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 2259c063..63a965c1 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 { AccountInterface } from '@snowluma/core/account-interface'; +import type { CoreCtx } from '@snowluma/core/core-ctx'; 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: AccountInterface; + private readonly bridge: CoreCtx; 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: AccountInterface, config: OneBotConfig) { + constructor(uin: string, bridge: CoreCtx, 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 b077c8eb..2d292539 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 { AccountInterface } from '@snowluma/core/account-interface'; -import type { AccountManager } from '@snowluma/core/account-manager'; +import type { CoreCtx } from '@snowluma/core/core-ctx'; +import type { Hub } from '@snowluma/core/hub'; 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(accountManager: AccountManager): void { - accountManager.setAccountStartedCallback((uin, account) => { - this.onSessionStarted(uin, account); + bind(hub: Hub): void { + hub.events.on('core-online', (ctx) => { + this.onSessionStarted(ctx.uin, ctx); }); - accountManager.setAccountClosedCallback((uin) => { + hub.events.on('core-offline', ({ uin }) => { this.onSessionClosed(uin); }); } @@ -45,7 +45,7 @@ export class OneBotManager { this.instances.clear(); } - private onSessionStarted(uin: string, bridge: AccountInterface): void { + private onSessionStarted(uin: string, bridge: CoreCtx): 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: AccountInterface): Promise { +async function warmUpBridgeState(uin: string, bridge: CoreCtx): 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 87b6923d..4935feaf 100644 --- a/packages/onebot/src/media-url-resolver.ts +++ b/packages/onebot/src/media-url-resolver.ts @@ -1,10 +1,10 @@ -import type { AccountInterface } from '@snowluma/core/account-interface'; +import type { CoreCtx } from '@snowluma/core/core-ctx'; import type { MessageElement } from '@snowluma/protocol/events'; import type { RKeyCache } from './instance-rkey'; export class MediaUrlResolver { constructor( - private readonly bridge: AccountInterface, + private readonly bridge: CoreCtx, private readonly rkeyCache: RKeyCache, ) { } diff --git a/packages/onebot/src/modules/contact-actions.ts b/packages/onebot/src/modules/contact-actions.ts index 6ec6a861..6ef009bc 100644 --- a/packages/onebot/src/modules/contact-actions.ts +++ b/packages/onebot/src/modules/contact-actions.ts @@ -1,4 +1,4 @@ -import type { AccountInterface } from '@snowluma/core/account-interface'; +import type { CoreCtx } from '@snowluma/core/core-ctx'; 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: AccountInterface, groupId: number): Promise { +async function refreshSingleGroupMembers(bridge: CoreCtx, groupId: number): Promise { try { await bridge.apis.contacts.fetchGroupMemberList(groupId); } catch { @@ -17,7 +17,7 @@ async function refreshSingleGroupMembers(bridge: AccountInterface, groupId: numb } } -export async function getFriendList(bridge: AccountInterface): Promise { +export async function getFriendList(bridge: CoreCtx): Promise { try { const friends = await bridge.apis.contacts.fetchFriendList(); return friends.map(f => ({ @@ -35,7 +35,7 @@ export async function getFriendList(bridge: AccountInterface): Promise { try { @@ -54,7 +54,7 @@ export async function getGroupList( } export async function getGroupInfo( - bridge: AccountInterface, + bridge: CoreCtx, groupId: number, noCache?: boolean, ): Promise { @@ -76,7 +76,7 @@ export async function getGroupInfo( } export async function getGroupMemberList( - bridge: AccountInterface, + bridge: CoreCtx, groupId: number, noCache?: boolean, ): Promise { @@ -94,7 +94,7 @@ export async function getGroupMemberList( } export async function getGroupMemberInfo( - bridge: AccountInterface, + bridge: CoreCtx, groupId: number, userId: number, noCache?: boolean, @@ -108,7 +108,7 @@ export async function getGroupMemberInfo( } export async function getGroupFiles( - bridge: AccountInterface, + bridge: CoreCtx, groupId: number, folderId?: string, ): Promise { @@ -140,7 +140,7 @@ export async function getGroupFiles( } export async function getStrangerInfo( - bridge: AccountInterface, + bridge: CoreCtx, userId: number, ): Promise { try { @@ -167,7 +167,7 @@ export async function getStrangerInfo( } } -export async function getGroupSystemMessages(bridge: AccountInterface): Promise { +export async function getGroupSystemMessages(bridge: CoreCtx): Promise { try { const reqs = await bridge.apis.contacts.fetchGroupRequests(); return reqs.map(r => ({ @@ -184,7 +184,7 @@ export async function getGroupSystemMessages(bridge: AccountInterface): Promise< } } -export async function getDownloadRKeys(bridge: AccountInterface): Promise { +export async function getDownloadRKeys(bridge: CoreCtx): 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 b5ca7da7..891bb8b6 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 { AccountInterface } from '@snowluma/core/account-interface'; +import type { CoreCtx } from '@snowluma/core/core-ctx'; import type { MediaStore } from '../media-store'; import type { JsonObject } from '../types'; @@ -21,7 +21,7 @@ export async function getImageInfo( } export async function getRecordInfo( - bridge: AccountInterface, + bridge: CoreCtx, mediaStore: MediaStore, file: string, ): Promise { diff --git a/packages/onebot/src/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts index 955be71c..86235cd3 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 { AccountInterface } from '@snowluma/core/account-interface'; +import type { CoreCtx } from '@snowluma/core/core-ctx'; 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: AccountInterface, meta: MessageMeta): Promise { +export async function deleteMessage(bridge: CoreCtx, 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: AccountInterface, meta: MessageMeta) } export async function setEssenceMessage( - bridge: AccountInterface, + bridge: CoreCtx, 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 547c74b8..d60c8d2d 100644 --- a/packages/onebot/src/modules/request-actions.ts +++ b/packages/onebot/src/modules/request-actions.ts @@ -1,7 +1,7 @@ -import type { AccountInterface } from '@snowluma/core/account-interface'; +import type { CoreCtx } from '@snowluma/core/core-ctx'; export async function handleGroupAddRequest( - bridge: AccountInterface, + bridge: CoreCtx, flag: string, approve: boolean, reason: string, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5ef51186..c72fdab1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -73,6 +73,44 @@ importers: specifier: ^4.1.4 version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + packages/channel-hook: + dependencies: + '@snowluma/channel': + specifier: workspace:* + version: link:../channel + '@snowluma/common': + specifier: workspace:* + version: link:../common + devDependencies: + '@types/node': + specifier: ^24.12.2 + version: 24.12.2 + typescript: + specifier: 'catalog:' + version: 6.0.2 + vite: + specifier: 'catalog:' + version: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + vitest: + specifier: ^4.1.4 + version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + + packages/channel-socket: + dependencies: + '@snowluma/channel': + specifier: workspace:* + version: link:../channel + '@snowluma/common': + specifier: workspace:* + version: link:../common + devDependencies: + '@types/node': + specifier: ^24.12.2 + version: 24.12.2 + typescript: + specifier: 'catalog:' + version: 6.0.2 + packages/common: devDependencies: '@types/node': @@ -87,6 +125,12 @@ importers: '@snowluma/channel': specifier: workspace:* version: link:../channel + '@snowluma/channel-hook': + specifier: workspace:* + version: link:../channel-hook + '@snowluma/channel-socket': + specifier: workspace:* + version: link:../channel-socket '@snowluma/common': specifier: workspace:* version: link:../common