Compare commits

...

81 Commits
dev2 ... v1.9.7

Author SHA1 Message Date
snowluma-bot[bot]
cc27cd1f43 Merge pull request #89 from SnowLuma/dev
chore: promote dev → main (515bac4)
2026-06-07 14:30:05 +00:00
DrSmoothl
515bac4b3c chore(release): v1.9.7 2026-06-07 22:29:37 +08:00
DrSmoothl
6a2fd9e8f3 fix(bridge): don't crash the daemon when the hook pipe closes mid-send
When the control pipe drops while a send() is awaiting its ack,
rejectControlPending() rejects both the ack and the reply deferreds. The
reply is only awaited after the ack, so an ack-first rejection leaves the
reply promise rejected with NO awaiter — an unhandled rejection that, under
Node's default policy, kills the process. In Docker supervisor restarts it
(every session drops for ~1s); on a bare Windows run it just dies, surfacing
as "connection pipe closed" with the bot offline after hours of uptime.

Attach a no-op .catch() to each deferred at creation so a rejection can never
go unhandled (the real await still observes the value/rejection). Add a
regression test that drops the pipe mid-send and asserts no unhandled
rejection escapes — it fails without the guard.

Also install last-resort process guards (unhandledRejection / uncaughtException)
in the app entry: log and keep serving instead of exiting, so any other stray
rejection cannot take the daemon down and its stack is captured. The bridge's
watcher reconnects the dropped pipe on the next tick.
2026-06-07 22:15:07 +08:00
snowluma-bot[bot]
40c65c87bd Merge pull request #88 from SnowLuma/dev
chore: promote dev → main (174150c)
2026-06-07 13:20:48 +00:00
墨梓柒
ac39d04170 Merge branch 'main' into dev 2026-06-07 21:20:39 +08:00
DrSmoothl
174150c5e1 chore(release): v1.9.6 2026-06-07 21:19:00 +08:00
DrSmoothl
56dc934106 feat(webui): notify when a newer release is available
Advisory, read-only update check: the core polls GitHub's latest stable release, compares it against the running build, and surfaces a notice in the sidebar footer plus a detailed card (changelog + download link + platform-matched asset hint) in Settings → About.

SnowLuma never downloads or applies anything itself — cross-platform self-update is a minefield (Windows locks loaded .node/.dll, Docker bakes the app into image layers, bare installs have no supervisor), so the user downloads and applies manually.

The backend caches results for 6h to stay under GitHub's unauthenticated rate limit, degrades silently on failure, and can be disabled via SNOWLUMA_UPDATE_CHECK=0.
2026-06-05 16:08:38 +08:00
DrSmoothl
28db1d1079 fix(onebot): distinguish group disband from kick_me (#87)
group_decrease collapsed GroupChange.decreaseType into a single isKick boolean, so a group disband (decreaseType 129) was indistinguishable from the bot being kicked — both surfaced as kick_me.

Preserve the protocol reason as a leaveType discriminator (leave | kick | disband) on GroupMemberLeave: decreaseType 129 -> disband, 0/130 -> leave, otherwise kick. The OneBot converter emits disband, or splits kick into kick/kick_me by selfId as before. leave/kick/kick_me are unchanged.
2026-06-05 11:49:14 +08:00
DrSmoothl
966855469d ci: run the full test suite on pull requests
The repo had no PR test gate, so broken tests landed on dev unnoticed. Add a
pull_request workflow that runs `pnpm -r --no-bail --if-present test` across all
packages on ubuntu-latest (pnpm 10.28.0, Node 22), with per-PR concurrency.
2026-06-04 23:36:33 +08:00
DrSmoothl
9374b8ac64 fix(protocol): invokeOidb rejects on packet send failure (success=false)
invokeOidb only threw on success=false when an OIDB errorCode was set (the
block added in #69); a send failure with no errorCode silently resolved with an
undecoded result. Surface it — throw errorMessage || 'packet send failed',
matching runOidb and the oidb-service tests that were already red on dev.
2026-06-04 23:36:22 +08:00
ikun两年半
34ea2ce438 refactor(webui): 移除冗余的手动保存按钮喵,通用设置改为 debounce 自动保存喵 (#83)
* refactor(webui): 移除冗余的手动保存按钮喵,通用设置改为 debounce 自动保存喵

* fix(webui): 修复保存按钮状态喵,允许在自动保存时手动触发喵
2026-06-04 18:03:17 +08:00
墨梓柒
9dedcf93a8 Dev (#82)
* test(sdk): remove obsolete actions-sync guard

c49ae1c removed the SDK's hardcoded action-name list (src/actions.ts / SNOWLUMA_ACTIONS) and updated exports, but left the test that guarded it. The test imports SNOWLUMA_ACTIONS from ../src -- now undefined ("not iterable") -- and its registerAction('...') enumeration of onebot is itself stale after the declarative action-kit migration. Nothing else references SNOWLUMA_ACTIONS; the list it kept in sync no longer exists, so the guard is dead. Removing it makes the sdk suite green (16 tests).

* fix(mcp): add repository metadata so the provenance publish validates

npm publish --provenance rejected @snowluma/mcp@1.9.5 with E422 because package.json had no repository.url to match the GitHub repo asserted in the provenance statement. Add repository/homepage/bugs (mirroring @snowluma/sdk and @snowluma/ui, directory packages/mcp) and refresh the now-inaccurate 'read-only' description. 1.9.5 was never successfully published, so re-running the publish workflow will ship it.
2026-06-03 22:19:31 +08:00
DrSmoothl
0cc7ef2f30 fix(mcp): add repository metadata so the provenance publish validates
npm publish --provenance rejected @snowluma/mcp@1.9.5 with E422 because package.json had no repository.url to match the GitHub repo asserted in the provenance statement. Add repository/homepage/bugs (mirroring @snowluma/sdk and @snowluma/ui, directory packages/mcp) and refresh the now-inaccurate 'read-only' description. 1.9.5 was never successfully published, so re-running the publish workflow will ship it.
2026-06-03 22:17:58 +08:00
DrSmoothl
d2097f77c8 test(sdk): remove obsolete actions-sync guard
c49ae1c removed the SDK's hardcoded action-name list (src/actions.ts / SNOWLUMA_ACTIONS) and updated exports, but left the test that guarded it. The test imports SNOWLUMA_ACTIONS from ../src -- now undefined ("not iterable") -- and its registerAction('...') enumeration of onebot is itself stale after the declarative action-kit migration. Nothing else references SNOWLUMA_ACTIONS; the list it kept in sync no longer exists, so the guard is dead. Removing it makes the sdk suite green (16 tests).
2026-06-03 22:17:58 +08:00
snowluma-bot[bot]
46cbd29956 Merge pull request #81 from SnowLuma/dev
chore: promote dev → main (4fcaba2)
2026-06-03 13:56:10 +00:00
DrSmoothl
4fcaba2f3e chore(release): v1.9.5 2026-06-03 21:55:37 +08:00
DrSmoothl
4427ecd569 docs(mcp): document execution mode (modes, env, read/write safety)
Covers the docs vs execution split, the four SNOWLUMA_MCP_* env vars, the query_action / invoke_action tools, read/write-mode example client configs, and the per-action safety model (default-write classification, the enforced mode gate, unknown-action rejection, envelope passthrough, and the readOnly/destructive annotations).
2026-06-03 21:55:05 +08:00
DrSmoothl
6d92a28e2b feat(mcp): execution mode — query/invoke OneBot actions with a read/write safety gate
@snowluma/mcp gains execution alongside the read-only catalog: when SNOWLUMA_MCP_ENDPOINT is set it exposes query_action (read-only actions, readOnlyHint) and, in write mode, invoke_action (any known action, destructiveHint), proxied to a running OneBot instance over HTTP. Without an endpoint it degrades to docs-only. SNOWLUMA_MCP_MODE (docs|read|write) gates tool visibility AND is re-checked in execute(), so an unlisted tool cannot be called; unknown/legacy actions are non-invokable.

Read vs write is classified precisely at the source: defineAction/preset gain readOnly (default false = write, the safe default), flowed through describe() into the generated catalog snapshot. 58 actions are marked read-only by what their run() actually does -- name-traps like get_ai_record (publishes to the group), request_decrypt_key (returns a DB key), and download_file (arbitrary URL + disk write) stay writes.

The HTTP call is a ~20-line fetch bridge rather than @snowluma/sdk: the SDK's published dist is bundler-only ESM (extensionless imports) that native node cannot load, and the bin stays a plain tsc build.

onebot 332 tests pass (readOnly is metadata-only, no behavior change); mcp gains 21 tests for mode gating / read-write routing / envelope passthrough / error mapping. Full workspace typecheck clean; native node smoke verified.
2026-06-03 21:53:02 +08:00
DrSmoothl
18f7d847ac refactor(onebot): lift the network adapter reload state machine into the base class
The four NetworkAdapters each carried a byte-identical reload() state machine (sigChanged/wasEnabled -> Reopened/Closed/Opened/Normal). Lift it into IOneBotNetworkAdapter as a template method; per-adapter variation is now expressed via three hooks: bindingSignature(), willEnable() (default enabled!==false; clients add && !!url), and onConfigReplaced() (post-swap side effects).

Also delete four redundant 'override get isActive()' (identical to the base getter), lift the duplicated uin-logger setup into the base ctor, and drop http-post's now-redundant signature_ cache.

NetworkReloadType is a test-observability seam -- the sole production caller (instance.applyConfigDiff) discards it -- so a new base-level test exercises all transitions directly. Behaviour-preserving: +94/-157 in src, full workspace typecheck clean, 332 onebot tests pass.
2026-06-03 20:53:36 +08:00
游手好闲的言柒
d3092a1806 fix(onebot): support inline file url/path in send_group/private_msg (#80)
file 段现接受 file/url/path(无需先 upload_group_file/upload_private_file);群走 groupFile.upload()、私聊走 uploadPrivate()(内部已 publish/sendC2c),file_id 老路径不变。含 parser 与群/私聊文件发送测试。
2026-06-03 20:00:58 +08:00
DrSmoothl
69c8960ea9 feat(mcp): @snowluma/mcp — read-only MCP server for the OneBot action catalog
A new published package that exposes every OneBot action's docs + a ready-to-use
JSON Schema to LLM clients over stdio. Tools: list_actions / get_action /
search_actions / list_categories, plus the whole catalog as a resource.

The catalog is a build-time snapshot generated from @snowluma/onebot's live
action specs (collectActionDocs()) — so it auto-tracks action add/remove and the
published package carries zero runtime dependency on the private onebot package.

action-kit enrichment (the data source):
- Field.toJsonSchema() per coercer (uint→integer/minimum:1, messageId→integer/
  not-const-0, int→min/max, string→minLength/maxLength, array→items, enum→enum).
- describe() composes a per-action inputSchema; ActionDoc gains inputSchema +
  category. action-docs.ts tags each doc with its domain category.

Wiring: onebot exports ./action-kit + ./action-docs; root build:all includes mcp;
mcp-npm-publish.yml mirrors the sdk/ui publish workflows (triggers on changes
under packages/mcp/** or packages/onebot/**, since the catalog derives from it).

onebot typecheck + 318 tests green; mcp typecheck/build/smoke green; the 142
registered OneBot action names are unchanged.
2026-06-02 22:45:30 +08:00
DrSmoothl
fc21d87a9b feat(onebot): fetch_ptt_text via async 0x210/61 result push (#79)
Live testing showed the voice-to-text text is delivered by an async push
(Event 0x210 subType 61), not the request response — so the previous
poll-by-resend never got it. Captured a real push and decoded its protobuf:
outer { f1, f2:item }; the item echoes the request msgId at field 1 (the
correlation key) and the recognised text at field 8.

- proto-defs: PttTransPush / PttTransPushItem (live-verified).
- protocol: Event0x210SubType.PttTransResult = 61 + decoder → internal
  `ptt_trans_result` event { msgId, text } (replaces the temp hex dump).
- core: translatePttToText now sends ONE trigger and returns the inline text
  only if present (already-transcribed); empty = pending.
- onebot: ptt-trans-waiter (keyed by selfUin:msgId), event-pipeline subscribes
  `ptt_trans_result` to resolve it; fetch_ptt_text registers the waiter,
  fires the trigger, and awaits the push (20s timeout).

Decoded one real push as text "12311123。" end to end.
2026-06-02 22:01:07 +08:00
DrSmoothl
e036e70acc chore(protocol): temp-dump 0x210 subType-61 ptt-trans push body (#79)
Live testing showed the voice-to-text text is delivered via an async push
Event 0x210 subType 61 (0x3D), not the sync pttTrans.TransC2CPttReq response
(which is a fixed ~137B ack). That push has no static sys_msg_0x210_0x3d
handler — its protobuf is registered dynamically by the ptt-trans subsystem,
so RE through the std::function callback chain is impractical.

Dump the raw subType-61 body (fromUin + len + hex) once so the wire format
can be decoded from ground truth, then implement the real decoder +
request/await correlation. Temporary — to be replaced by the actual decoder.
2026-06-02 21:28:44 +08:00
DrSmoothl
92cfaf24b8 feat(log): trace the inbound receive chain (symmetric to outbound)
Sending got full-chain trace via the api-handler chokepoint; receiving had
none. Wrap convertAndDispatch — the single path every inbound message/notice
takes (decode → convert → dispatch) — as the receive-side mirror:

- When trace is live, run the chain inside a request id so the whole receive
  (incl. any rkey-fetch packets the conversion triggers) is correlated under
  one [req#N]; otherwise skip the wrap entirely (zero overhead).
- trace the raw inbound event on entry (deep render) and the converted
  post_type + elapsed on exit (or "dropped").

Reuses the existing trace/ALS/renderParamsVerbose machinery; no new mechanism.
2026-06-02 21:15:12 +08:00
DrSmoothl
15e4e261c5 feat(log): memory-only trace level + request correlation + chokepoint tracing
Debugging from user-supplied logs was impossible: a successful action left
one terse, over-summarized debug line and nothing about what it sent QQ or
what QQ returned. Add full-chain tracing that stays off disk so it scales to
hundreds of groups.

common:
- New `trace` level (below debug). Never written to file — it lives only in
  an in-memory ring + the WebUI stream, so the high-volume full chain costs no
  disk. `emit` early-returns for trace before format/render (and before any
  lazy producer) when trace isn't active → ~free at the default level.
- Dedicated O(1) circular ring for trace (default 5000, SNOWLUMA_TRACE_BUFFER),
  separate from the normal 1000-entry buffer (also switched off array .shift);
  getRecentLogs merges both by id.
- request-context.ts: AsyncLocalStorage request id. The logger auto-stamps
  `[req#N]` on every line in a request's async chain — across packages, zero
  signature threading — and records it on the entry.
- log-summary.renderParamsVerbose: deep render of params (nested structure,
  per-string cap, total budget, token/password/secret redaction).

chokepoints (auto-cover every action without touching 100+ handlers):
- onebot api-handler: wrap each action in a request id (only when trace is
  live); trace the full params on entry and status+elapsed on exit; the terse
  debug breadcrumb still persists to file, failures still warn.
- core bridge.sendRawPacket: trace on success (cmd, sizes, elapsed); warn on
  errorCode!=0 / no response (cmd, code, message) so disk keeps real problems.
- protocol highway: fold the bare console.log lines into the logger (trace).

webui: trace as the lowest filterable level; render the `[req#N]` tag and let
search match it. Server needs no change — LOG_LEVELS, getRecentLogs and the
SSE stream carry it through.
2026-06-02 21:01:19 +08:00
DrSmoothl
7336352cd3 feat(onebot): voice-to-text action fetch_ptt_text (#79)
Adds NapCat-compatible voice-to-text. New `fetch_ptt_text` action (aliases
`get_ptt_text` / `get_record_text`) takes a message_id, resolves the cached
`record` fingerprint (uuid + md5 + duration/size/format), drives QQ's native
`pttTrans.TransC2CPttReq` / `pttTrans.TransGroupPttReq`, and returns { text }.

The response carries the text inline once transcription is done; an empty
text means the server is still transcribing (there is no dedicated push
command — confirmed via RE), so the bridge re-sends with a short backoff
until the text lands, mirroring NapCat's fire-then-re-read shape.

Layers:
- proto-defs/ptt-trans: PttTransReq/Resp + per-scene items.
- core ExtrasApi.translatePttToText: encode -> sendRawPacket -> decode -> poll.
- onebot media-actions.fetchPttText + api-handler/instance-context wiring.
- onebot extended: register the action + aliases.

The commands + request/response field tags were reverse-engineered from
QQ-NT wrapper.node (im_core/msg/ptt/ptt_trans_worker.cc). The numeric tags
are solid; the length-delimited fields (uuid/md5) and the response text tag
are RE-derived and want one live capture to confirm before relying on them.
2026-06-02 20:47:06 +08:00
DrSmoothl
9b92f3825d refactor(onebot): declarative action-kit for param coercion + validation
Introduce packages/onebot/src/action-kit.ts — a zero-dependency,
type-inferring declarative layer for OneBot action params. Each action
declares its param contract (f.* coercers + optional cross-field rules)
and a `run` handler that receives typed, already-validated params.
Validation failures now return BAD_REQUEST naming the offending field
instead of falling through to ApiHandler's INTERNAL_ERROR catch.

- 141/142 actions migrated to defineAction/groupAction/groupUserAction
  across info/message/friend/group-*/request/extended; only
  .handle_quick_operation stays legacy (it needs the ApiHandler instance,
  which run() does not receive).
- f.messageId() distinguishes signed/non-zero message ids from positive
  group/user ids (f.uint()); int({min:0}).default(1800) fixes duration=0
  (unmute), which the old `|| 1800` silently swallowed.
- run(p, ctx, raw) exposes the raw params as an escape hatch for the
  irregular tail (alias-key fallbacks, arbitrary objects).
- action-docs.ts renders self-generated API docs from describe().
- ApiHandler dispatch / try-catch / response-wrapping unchanged (narrow seam).

Registered action name set is byte-identical before/after (142, verified
by runtime enumeration). Typecheck clean; onebot suite green (the
pre-existing websocket native-addon test failure is unrelated).
2026-06-02 15:21:46 +08:00
snowluma-bot[bot]
74c727b9e3 Merge pull request #77 from SnowLuma/dev
chore: promote dev → main (a1f372b)
2026-06-01 08:22:22 +00:00
DrSmoothl
a1f372bc9d chore(release): v1.9.4 2026-06-01 16:21:54 +08:00
DrSmoothl
b23607d51d feat(webui): add About tab to settings with Star CTA
New "关于" mini-tab in the settings page showcasing SnowLuma: logo +
name + version badge (__APP_VERSION__) + tagline, a short blurb, and a
prominent GitHub Star call-to-action linking to SnowLuma/SnowLuma, plus
secondary links (repo / releases / issues).

Static CTA — no GitHub API fetch, so no rate-limit / loading state.
Reuses /logo.png (same asset as sidebar/login) and the existing Card +
motion + accent-color design language; responsive centered layout.
2026-06-01 16:07:49 +08:00
墨梓柒
a51bf60d9a Merge pull request #76 from tt-P607/fix/highway-multi-chunk-keepalive
fix(protocol): one TCP connection per highway chunk
2026-06-01 15:04:05 +08:00
DrSmoothl
003e8c2deb feat(onebot): built-in #sl status command (toggleable, non-plugin)
A hardcoded `#sl` status command — deliberately NOT a plugin system.
Matched at the instance dispatch choke point: a pure-text message equal
to `#sl` (exact, trimmed, case-insensitive — no startsWith) replies with
SnowLuma version / platform / uptime in the same conversation.

- Anyone can trigger; the per-UIN `statusCommand.enabled` toggle is the
  only gate (default on). Per-conversation cooldown (default 5s,
  configurable) prevents flood/风控 from repeated triggers.
- `swallow` (default false / pass-through): when set, a matched `#sl` is
  not forwarded to downstream adapters — still cached, logged, replied.
- Config on OneBotConfig.statusCommand (per-UIN): defaulted + clamped in
  config.ts, mirrored/normalized in the WebUI; edits hot-reload via the
  shared instance context.
- WebUI: a "内置命令" section in the 通用设置 tab (enable / swallow /
  cooldown). Node enable toggle extracted into a shared ui/ToggleSwitch.

Pure matcher / cooldown / uptime / text helpers live in
modules/status-command with unit tests; config defaults + clamp covered.
2026-06-01 14:58:13 +08:00
tt-P607
118bcbe83c fix(protocol): one TCP connection per highway chunk
Highway 上传超过 1 MiB 的载荷(多 chunk 场景)会失败,OneBot 侧表现
为 retcode=1200 / `connection closed before response`。

根因:`uploadHighwayHttp` 用同一个 TCP socket,靠 HTTP keep-alive 把
每个 1 MiB chunk 依次 POST 出去。但 QQ highway 的边缘节点(以及链
路上的代理/NAT)经常在第一次响应之后立刻 FIN 关闭连接,第二个 chunk
的 POST 写到一个已被对端 close 的 socket 上,`readHttpResponseBody`
立刻收到 `close` 事件并抛出 `connection closed before response`。

为什么之前看起来像网络问题:≤1 MiB 的载荷(文本、PTT、小图)只发一
次 POST,永远不会触发;但凡跨过 `HIGHWAY_BLOCK_SIZE = 1 MiB`,第二
个 chunk 路径必然失败。改 Clash MTU、关 TUN、加直连规则都没用,因
为问题不在网络层。

改动:
- `uploadHighwayHttp`:每个 chunk 都新开一个 TCP 连接,`finally` 里
  `destroy()`。建连开销相对 1 MiB chunk 的传输时间可以忽略,行为也
  和 NapCat / Lagrange 在大文件上传时的连接生命周期一致。
- `readHttpResponseBody`:报错信息带上 `received=NB, headerSeen=
  true|false`,方便后续区分 “连接刚握手就被关” 和 “响应读到一半被
  截断” 两种情况。

测试:`packages/core/tests/highway/highway-client.test.ts` 三个用例
(0.5 MiB 单 chunk / 1.5 MiB 两 chunk —— 即本次 bug 复现 / 2.5 MiB
三 chunk),断言 `net.createConnection` 被调用的次数等于
`ceil(size / HIGHWAY_BLOCK_SIZE)`,并且每个用过的 socket 在下一次
建连之前都被 destroy。

线上验证:之前每次发 1 MB 以上图片必出 retcode=1200 的账号,打补丁
后通过 OneBot HTTP 已能正常发出图片。
2026-06-01 14:35:57 +08:00
DrSmoothl
0d63bf7415 fix(onebot): sign forward-msg media + pick image rkey by appid (#74)
/get_forward_msg returned raw, rkey-less image/media URLs because
getForwardMessage converted forward nodes WITHOUT the URL resolvers the
normal receive path (to-message.ts) uses. Wire imageUrlResolver +
mediaUrlResolver into it so forwarded images/voice/video get signed
download URLs — exactly issue #74 (image url 缺少 rkey).

Also derive the image rkey scene from the appid baked into the URL
(1406 -> private, 1407 -> group) instead of the carrying message's
group/private context, falling back to isGroup only when the URL has no
recognised appid. A c2c image forwarded into a group keeps its original
c2c appid, so the old isGroup-based pick signed it with the group rkey ->
`invalid rkey` on download. Mirrors NapCat's getImageUrlFromParsedUrl;
Lagrange/NapCat both reuse one unified converter so this never drifts.

Fix the self-contradictory `c2c images` rkey test (its fixture used the
group appid 1407) and add cross-tests asserting appid outranks isGroup
both ways, plus the no-appid fallback.
2026-05-31 23:50:08 +08:00
DrSmoothl
f9252fb26d fix(bridge): type Ptlogin probe + de-magic process threshold (PR #73 follow-up)
PR #73's login-state probe shipped with issues:
- `fetchPtlogin` returned `Promise<any[]>`, tripping the repo's
  `@typescript-eslint/no-explicit-any` (error) and breaking `pnpm lint`.
  Modelled the read fields as a `PtloginUin` interface and cast the parsed
  JSONP to it.
- `tryPtloginMethod` had a dead `if` whose two branches both returned
  'fallback'; collapsed to a single return with a comment.
- The `< 6` QQ-process-count heuristic was a bare magic number (one copy
  annotated only with "13579 5个端口全部用光"). Extracted to
  `LOGGED_OUT_PROCESS_COUNT_MAX` with an explanation and reused in all three
  sites (incl. the error fallback).

Behaviour-preserving: the probing logic (Ptlogin parse, deep-link fallback,
PID port discovery) is unchanged — only typing and the magic constant.
2026-05-31 22:33:22 +08:00
墨梓柒
e821080ca8 Merge pull request #73 from H3CoF6/fix/detect
New implement for QQ status detection
2026-05-31 15:43:19 +08:00
H3CoF6
b3749560c8 New implement for QQ status detection 2026-05-31 04:51:54 +08:00
DrSmoothl
c3803e4ba8 feat(proto): implement deflated payload for JSON and XML elements in message builder 2026-05-30 22:52:15 +08:00
snowluma-bot[bot]
f2840c7074 Merge pull request #71 from SnowLuma/dev
chore: promote dev → main (ad081e2)
2026-05-30 12:54:09 +00:00
DrSmoothl
ad081e2149 chore(release): v1.9.3 2026-05-30 20:53:45 +08:00
DrSmoothl
0e4b881f76 feat(webui): add live connection status for OneBot adapters in dashboard 2026-05-30 18:02:01 +08:00
DrSmoothl
90f26ca4f4 fix(proto): emit state=0 on whole-ban unmute via new pb_optional marker
set_group_whole_ban false (unmute) failed with `OIDB error 1007` while
enabling worked (issue #70). OIDB (0x89A, 0) is shared by several commands
(SetSearch / SetAddOption / mute-all) disambiguated by body shape. Unmute
sends muteState.state=0, but proton omits zero scalars (proto3), leaving an
empty `muteState` the server can't classify. Enable sends 0xFFFFFFFF, which
is non-zero and survives — hence the asymmetry.

Add a `pb_optional<N, T>` marker (proto3 explicit presence): a scalar so
marked serialises even at its zero/default value. It is opt-in per field via
a NEW `explicitPresence` flag set ONLY by this marker — never reused from the
TS-`?`-derived `isOptional` (true for nearly every field). The encoder routes
explicit-presence scalars to a dedicated block; every `pb<>` / `pb_repeated<>`
field takes the untouched branches, so existing wire output is byte-identical
(proton's 99 existing tests, incl. byte-level round-trips, stay green).

Mark OidbMuteAllState.state `pb_optional<17, uint_32>` so unmute now puts
field 17 (=0) on the wire. New tests: proton pb_optional encode/round-trip
(incl. that sibling pb<> fields still omit zero), and a byte-level assertion
that mute-all unmute carries the state field.

Note: proton ships as a built Vite plugin (dist, gitignored); rebuild it
(`pnpm --filter @snowluma/proton build`) for the change to reach consumers.
2026-05-30 17:55:23 +08:00
DrSmoothl
c4413dabb5 fix(proto): correct 0x8FC body/targetName field tags (set_group_card)
set_group_card always failed with `OIDB error 1007 on 0x8fc_3` (issue #70).
The 0x8FC request protos put the body wrapper at tag 2 and the member card
name at tag 2, but QQ-NT expects body at tag 3 and targetName at tag 8, so
the server found neither and rejected the request.

Cross-checked byte-for-byte against two working references:
  - Lagrange.Core OidbSvcTrpcTcp0x8FC: Body=ProtoMember(3), TargetName=8
  - NapCat Oidb.0x8FC_2: body=ProtoField(3), targetName=8

Fixes OidbRenameMember (0x8FC_3 set card) and the same latent bug in
OidbSpecialTitle (0x8FC_2 set special title), whose body was also at tag 2.
Send-only protos (empty deserialize); existing tests assert the command
name, not field tags, so they're unaffected.
2026-05-30 17:29:17 +08:00
DrSmoothl
71be3ae2e1 feat(webui): split overview into a processes page + mobile/ultrawide pass
The homepage was doing double duty — monitoring + injection control. Split it:

- New /processes page ("进程注入", sidebar #2) owns the QQ-process control
  surface (load / unload / refresh / probe-login + its dialogs). Overview is
  now a read-only dashboard: stats, host metrics, online accounts, plus a
  read-only injection-summary tile (online / loadable, links to /processes)
  and a first-run CTA that points at /processes while nothing is online.
  Route + AppPath + nav item wired; state/polling stay layout-owned.

Responsive + a11y pass:
- Mobile sidebar Sheet gets an sr-only title + description, fixing the Radix
  "DialogContent requires a DialogTitle" accessibility error.
- Log rows stack on phones (meta line + full-width message) instead of a
  ~40px column that broke every few chars; time parses defensively so a
  non-ISO value never renders "Invalid Date".
- Process cards stack on phones (info row + actions row) so name / PID / path
  stop collapsing to "Q.."; the status badge no longer wraps.
- Config tab strip scrolls horizontally on phones instead of wrapping to
  three rows; account strip defaults collapsed ≤lg; header buttons wrap.
- Dialogs keep a 1rem gutter on tiny screens via w-[calc(100vw-2rem)].
- Content widens to 1600px on ≥2xl; account/process grids gain a column at
  2xl so >1700px screens aren't mostly empty gutter.
2026-05-30 16:56:34 +08:00
手瓜一十雪
3cfac51811 Add SVG logo and update README
Add a new animated SVG logo at .github/logo.svg and embed it in README.md. Update the README content: refresh badges, simplify and translate the project intro and feature list into Chinese, add concise quickstart steps, adjust links (Releases → 发布版, RoadMap), and replace long/duplicated sections with a shorter overview and contributor badge. Overall this cleans up and modernizes the README and adds a branded logo for the project.
2026-05-30 16:06:29 +08:00
DrSmoothl
76c6ebc700 feat(webui): settings tabs, password dialog, instant node save, error pages
Five WebUI changes:

1. Settings page rebuilt around mini tabs (外观 / 数据刷新 / 账号安全)
   instead of three stacked cards; content and behaviour unchanged.

2. "修改访问密码" now opens an independent ChangePasswordDialog modal
   rather than swapping the whole page for the forced-change screen. The
   form is extracted to a shared ChangePasswordForm used by both the modal
   and the forced full-screen ChangePasswordPage — behaviour identical.

3. Node config: creating / editing / deleting / enable-toggling an
   HTTP/WS endpoint now persists immediately — clicking 保存 in the editor
   dialog IS the save. Previously it only marked the config dirty until you
   also hit the top-right 保存, which silently cost many users their token
   edits. `save()` takes an explicit config so it persists the freshly
   computed value, not the stale closed-over state. The general-settings
   tab keeps its explicit top-right save.

4. Forced first-time change-password no longer renders an old-password
   field: it carries the password the user just logged in with. Browsers
   (Edge/Chrome) were autofilling that field on upgrade, so users thought
   the old password was pre-filled correctly and could never save. A
   returning already-authed session (no fresh login) still shows the field.

5. Added default error + 404 screens (status-screens.tsx), wired into the
   TanStack router via defaultErrorComponent / defaultNotFoundComponent.
2026-05-30 13:34:41 +08:00
DrSmoothl
74b6fe97e5 build(core): externalize node:sqlite instead of SSR-bundling
Addresses MliKiowa's review on PR #68 ("单独排除 sqlite 就行了"). That PR
fixed the `DatabaseSync is not a constructor` crash by switching the core
bundle to SSR mode (build.ssr + ssr.noExternal + target node22 + a
catch-all isNodeBuiltin external fn). The root cause was narrower: on
Node 22.x `node:sqlite` is experimental and absent from `builtinModules`,
so the `nodeModules` sweep didn't externalize it and Vite swapped in a
browser shell. The SSR switch also self-inflicted the @hono/node-server
MODULE_NOT_FOUND it then had to paper over with noExternal — the original
config already bundled all non-builtin deps.

Revert vite.config.ts to the pre-PR state and just add 'node:sqlite'
(+ bare 'sqlite') to the external list. Verified: `SNOWLUMA_TARGET=linux-x64
vite build` succeeds and dist/index.mjs now carries a real
`import { DatabaseSync } from "node:sqlite"` rather than a shimmed shell.
2026-05-29 20:22:06 +08:00
DrSmoothl
4a0626f00b fix(onebot): re-sign image rkey on get_image / get_msg lookups
get_image and get_msg returned the URL baked into the message store when
the message first arrived. That URL's rkey expires, so a client fetching
it later (or re-querying after the original push) got
`{"retcode":-5503010,"retmsg":"invalid rkey"}`.

Re-sign at lookup time from the raw unsigned `imageUrl` the media store
already keeps alongside the signed `url` (plus `isGroup`): getImageInfo
now takes the image rkey resolver and mints a current rkey, and get_msg
walks its segment array refreshing each image URL through it. Both are
best-effort — a resolver miss/throw or a non-array message body falls
back to the stored URL untouched. Mirrors NapCat re-signing on every
getImageUrl call instead of handing back a stale baked URL.

The resolver is reused from converterCtx (no new rkeyCache wiring); a
cache-hit re-sign is a string concat, only an expired rkey awaits the
already-deduped/cooled-down/timeout-bounded refresh.
2026-05-29 20:14:21 +08:00
墨梓柒
ba19cee07d Merge pull request #68 from H3CoF6/Dev
Fix SSR bundle and node:sqlite resolution in Vite config
2026-05-29 20:14:11 +08:00
DrSmoothl
624959f099 fix(onebot): await a fresh rkey before signing media URLs
Image/video/record download URLs are signed at receive-time with an rkey
(OIDB 0x9067_202, TTL-bounded). RKeyCache resolved synchronously: on a
cache miss or inside the expiry skew it returned the URL *without* an
rkey and only kicked off a fire-and-forget refresh (plus a 30s cooldown).
So during the expire→refresh window — and whenever the OIDB hiccuped —
SnowLuma emitted unsigned URLs, which the CDN rejects with
`{"retcode":-5503010,"retmsg":"invalid rkey"}`. Intermittent by nature.

Mirror NapCat's getImageUrl (`if (isExpired()) await refreshRkey()`):
make resolveImageUrl/resolveMediaUrl async and block on one refresh when
the cache can't serve a still-valid rkey. The refresh coalesces
concurrent callers onto a single OIDB round-trip, backs off for 30s after
a failure, and is bounded by a 5s timeout so a stuck packet send never
wedges message conversion (it degrades to whatever the cache holds).

Widen ImageUrlResolver to `string | Promise<string>` and await it in
to-segment so the image path can resolve asynchronously like media.
2026-05-29 17:56:39 +08:00
DrSmoothl
0110b71dd3 fix(protocol): send browser UA + Referer retry on media downloads
loadBinarySource issued a header-less fetch(source) for remote media.
Anti-hotlink / anti-bot front-ends reset such requests, surfacing as
undici `TypeError: fetch failed` (not a clean 403) — so quoting a
command and sending an image/GIF whose source is a guarded URL bounced
with send_group_msg retcode 1200 "fetch failed".

Mirror NapCat's download path: send a browser User-Agent on every
request and retry once with a Referer pointing at the resource when the
first attempt is refused (network error or 403/4xx). Size-limit
rejections are tagged noRetry so an oversized body isn't re-downloaded.
Also route set_group_notice's image fetch through loadBinarySource so it
inherits the same hardening (plus http/file/base64 handling).
2026-05-29 17:37:10 +08:00
H3CoF6
00ca582f1a feat(protocol): implement OIDB 0xcde_2 (RequestDbKey) (#69) 2026-05-28 15:18:06 +08:00
H3CoF6
bf932477dd build(core): fix SSR bundle and node:sqlite resolution in Vite config 2026-05-28 02:02:29 +08:00
手瓜一十雪
f2b7ef0056 Switch from @snowluma/sqlite to node:sqlite (sync)
Remove the in-tree @snowluma/sqlite wrapper and vendored better-sqlite3 prebuilts; migrate consumers to node:sqlite's synchronous API. Replaced imports and types (Database/Statement -> DatabaseSync/StatementSync), updated PRAGMA calls to use exec, and adjusted code in onebot (media/message/reaction stores) and protocol (identity service). Vite config no longer bundles sqlite native binaries and references to the sqlite workspace were removed. Also delete the packages/sqlite package and its native prebuild artifacts, and add a couple of unrelated AST improvements in proton: use a module-level shared wrapper cache and add an inheritance cache to avoid repeated scans. Minor import reordering/cleanup applied where needed.
2026-05-27 20:02:40 +08:00
snowluma-bot[bot]
54c4641a0e Merge pull request #66 from SnowLuma/dev
chore: promote dev → main (5924346)
2026-05-24 10:02:15 +00:00
snowluma-bot[bot]
08b7ab7f15 Merge pull request #63 from SnowLuma/dev
chore: promote dev → main (ee0f159)
2026-05-21 09:50:31 +00:00
snowluma-bot[bot]
4a92dd71ad Merge pull request #62 from SnowLuma/dev
chore: promote dev → main (607a7b3)
2026-05-21 09:34:03 +00:00
snowluma-bot[bot]
1bd0cbc359 Merge pull request #57 from SnowLuma/dev
chore: promote dev → main (2de1ff4)
2026-05-20 06:21:32 +00:00
snowluma-bot[bot]
fe567caeec Merge pull request #50 from SnowLuma/dev
chore: promote dev → main (941e60d)
2026-05-18 07:04:16 +00:00
snowluma-bot[bot]
231d60411b Merge pull request #48 from SnowLuma/dev
chore: promote dev → main (b94775c)
2026-05-18 05:31:37 +00:00
snowluma-bot[bot]
bee1e67c60 Merge pull request #46 from SnowLuma/dev
chore: promote dev → main (c6f4d5c)
2026-05-17 16:11:03 +00:00
snowluma-bot[bot]
71b0bda8f4 Merge pull request #44 from SnowLuma/dev
chore: promote dev → main (90884df)
2026-05-17 11:29:18 +00:00
墨梓柒
133cfc0c0e Merge pull request #40 from SnowLuma/revert/pr-38-c2c-video-sceneType
Revert "fix(send): keep c2c video compatQMsgSceneType at 2 (#38)"
2026-05-16 16:44:38 +08:00
DrSmoothl
b959783ded Revert "fix(send): keep c2c video compatQMsgSceneType at 2 (#38)"
This reverts commit 463e0ffb5d.
2026-05-16 14:54:56 +08:00
时瑾
463e0ffb5d fix(send): keep c2c video compatQMsgSceneType at 2 (#38)
Commit 29f28d6 changed c2c video `compatQmsgSceneType` from 2 to 1
as a "symmetric asymmetry" cleanup, matching the image/ptt convention
where the field tracks the upload's sceneType (c2c=1, group=2). For
video this is wrong.

Image and ptt have *different* legacy compat elements per scene
(notOnlineImage vs customFace; ptt c2c vs group), so the server needs
to know which scene shape to emit. The legacy `videoFile` element
(packet element type 19) has no scene split — fromChatType /
toChatType live inside the element itself — so the QQ NT server
emits a single group-shaped compat payload regardless. NapCat
hardcodes `compatQMsgSceneType: 2` for *both* UploadGroupVideo and
UploadPrivateVideo for exactly this reason.

Setting it to 1 on c2c made the server emit a c2c-scene shaped
compat blob that older QQ clients failed to resolve, showing the
message as "视频已过期" on those receivers. Newer clients only read
the commonElem(48, 11) and displayed fine — which is why only "some
devices" saw the breakage.

Keep `commonElem.businessType = isGroup ? 21 : 11` untouched — that
piece of 29f28d6 is still correct and is what fixed PbSendMsg
result=79.
2026-05-16 14:22:49 +08:00
snowluma-bot[bot]
9d55e86b1c Merge pull request #37 from SnowLuma/dev
chore: promote dev → main (7da52bc)
2026-05-15 23:18:33 +08:00
snowluma-bot[bot]
07449788c6 Merge pull request #36 from SnowLuma/dev
chore: promote dev → main (85b59bc)
2026-05-15 01:48:08 +08:00
snowluma-bot[bot]
fe4af70562 Merge pull request #34 from SnowLuma/dev
chore: promote dev → main (564eec2)
2026-05-14 20:50:46 +08:00
snowluma-bot[bot]
545a732385 Merge pull request #30 from SnowLuma/dev
chore: promote dev → main (ada591b)
2026-05-13 16:55:55 +08:00
snowluma-bot[bot]
c2f22d8daf Merge pull request #29 from SnowLuma/dev
chore: promote dev → main (6abde40)
2026-05-13 16:23:42 +08:00
snowluma-bot[bot]
9216b54427 Merge pull request #28 from SnowLuma/dev
chore: promote dev → main (1b2dd83)
2026-05-12 22:06:52 +08:00
snowluma-bot[bot]
fd9a239241 Merge pull request #27 from SnowLuma/dev
chore: promote dev → main (8636222)
2026-05-11 15:32:46 +00:00
snowluma-bot[bot]
5a4028d5dc Merge pull request #25 from SnowLuma/dev
chore: promote dev → main (6f6ce11)
2026-05-10 10:17:23 +08:00
snowluma-bot[bot]
d02e7cc3ab Merge pull request #23 from SnowLuma/dev
chore: promote dev → main (bec23c4)
2026-05-10 01:32:20 +08:00
snowluma-bot[bot]
9938545788 Merge pull request #21 from SnowLuma/dev
chore: promote dev → main (a7b3809)
2026-05-09 19:40:04 +08:00
snowluma-bot[bot]
7149bc8689 Merge pull request #20 from SnowLuma/dev
chore: promote dev → main (c39b3f5)
2026-05-09 19:33:40 +08:00
snowluma-bot[bot]
9802128421 Merge pull request #19 from SnowLuma/dev
chore: promote dev → main (2af273b)
2026-05-09 16:40:37 +08:00
墨梓柒
a572d05c25 Merge pull request #18 from SnowLuma/dependabot/npm_and_yarn/hono-4.12.18
build(deps-dev): bump hono from 4.12.14 to 4.12.18
2026-05-09 16:03:21 +08:00
dependabot[bot]
cb06624d12 build(deps-dev): bump hono from 4.12.14 to 4.12.18
Bumps [hono](https://github.com/honojs/hono) from 4.12.14 to 4.12.18.
- [Release notes](https://github.com/honojs/hono/releases)
- [Commits](https://github.com/honojs/hono/compare/v4.12.14...v4.12.18)

---
updated-dependencies:
- dependency-name: hono
  dependency-version: 4.12.18
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-09 08:01:11 +00:00
snowluma-bot[bot]
7b93839186 Merge pull request #17 from SnowLuma/dev
chore: promote dev → main (1565749)
2026-05-09 15:37:22 +08:00
snowluma-bot[bot]
d0085ec052 Merge pull request #15 from SnowLuma/dev
chore: promote dev → main (c3b328f)
2026-05-09 15:04:19 +08:00
159 changed files with 15640 additions and 3574 deletions

40
.github/logo.svg vendored Normal file
View File

@@ -0,0 +1,40 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 120" width="100%" height="100%" style="background-color: transparent;">
<defs>
<style>
@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@800&amp;display=swap');
.title-font {
font-family: 'Plus Jakarta Sans', sans-serif;
font-size: 48px;
font-weight: 800;
letter-spacing: -0.02em;
text-anchor: middle;
}
.star-fx {
animation: floatAnimation 4s ease-in-out infinite;
}
.star-top { transform-origin: 265px 25px; fill: #cec1e6; }
.star-bottom { transform-origin: 45px 95px; animation-delay: 0.5s; fill: #fad6e6; }
@keyframes floatAnimation {
0% { transform: translateY(0px) rotate(0deg); opacity: 0.9; }
50% { transform: translateY(-8px) rotate(10deg); opacity: 1; }
100% { transform: translateY(0px) rotate(0deg); opacity: 0.9; }
}
</style>
</defs>
<g transform="translate(160, 75)">
<text class="title-font" dx="2" dy="2">
<tspan fill="#f9d5e7">Snow</tspan><tspan fill="#a5c9ff">Luma</tspan>
</text>
<text class="title-font" dx="0" dy="0">
<tspan fill="#a5c9ff">Snow</tspan><tspan fill="#cec1e6">Luma</tspan>
</text>
</g>
<path class="star-fx star-top" d="M265,13 L267.8,21.1 L276,24 L267.8,26.9 L265,35 L262.2,26.9 L254,24 L262.2,21.1 Z"/>
<path class="star-fx star-bottom" d="M45,84 L47.1,90.2 L53.5,92.2 L47.1,94.2 L45,100 L42.9,94.2 L36.5,92.2 L42.9,90.2 Z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

43
.github/workflows/ci.yml vendored Normal file
View File

@@ -0,0 +1,43 @@
# Run the full workspace test suite on every pull request.
#
# The repo previously had no PR test gate, so broken tests could land on `dev`
# unnoticed — and did (protocol's oidb-service rejection path, plus an external
# contributor PR). This gates every PR on the whole suite.
#
# `pnpm -r --no-bail --if-present test` runs each package's `test` script
# (skipping packages without one); --no-bail means one failing package still
# reports the rest, and the run as a whole still fails if any package fails.
name: CI
on:
pull_request:
permissions:
contents: read
# Cancel an in-flight run when the PR gets new commits.
concurrency:
group: ci-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: pnpm/action-setup@v6
with:
version: 10.28.0
run_install: false
- uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'pnpm'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Run all package tests
run: pnpm -r --no-bail --if-present test

109
.github/workflows/mcp-npm-publish.yml vendored Normal file
View File

@@ -0,0 +1,109 @@
name: Publish MCP to npm
on:
push:
branches: [main]
paths:
- 'packages/mcp/**'
# The action catalog is generated from @snowluma/onebot's specs, so an
# action change must republish the MCP snapshot.
- 'packages/onebot/**'
- 'package.json'
- 'pnpm-lock.yaml'
- 'pnpm-workspace.yaml'
- 'tsconfig.base.json'
workflow_dispatch:
permissions:
contents: read
id-token: write
concurrency:
group: mcp-npm-publish-${{ github.ref }}
cancel-in-progress: false
jobs:
publish:
name: Build, test, and publish MCP
runs-on: ubuntu-latest
environment: SnowLuma
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Type check MCP
run: pnpm --filter @snowluma/mcp typecheck
- name: Test MCP (regenerates + validates the action catalog)
run: pnpm --filter @snowluma/mcp test
- name: Build MCP
run: pnpm --filter @snowluma/mcp build
- name: Check npm package version
id: npm
working-directory: packages/mcp
shell: bash
run: |
set -euo pipefail
package_name="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).name)")"
package_version="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).version)")"
{
echo "package_name=${package_name}"
echo "package_version=${package_version}"
} >> "${GITHUB_OUTPUT}"
if npm view "${package_name}@${package_version}" version >/dev/null 2>&1; then
echo "already_published=true" >> "${GITHUB_OUTPUT}"
echo "::notice::${package_name}@${package_version} already exists on npm; skipping publish."
else
echo "already_published=false" >> "${GITHUB_OUTPUT}"
fi
- name: Validate npm token
if: steps.npm.outputs.already_published != 'true'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
if [ -z "${NODE_AUTH_TOKEN}" ]; then
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
exit 1
fi
- name: Publish MCP to npm
if: steps.npm.outputs.already_published != 'true'
working-directory: packages/mcp
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npm publish --access public --provenance
- name: Summary
shell: bash
run: |
{
echo "## MCP npm publish"
echo
echo "| Key | Value |"
echo "| --- | --- |"
echo "| Package | \`${{ steps.npm.outputs.package_name }}\` |"
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
echo "| Environment | \`SnowLuma\` |"
} >> "${GITHUB_STEP_SUMMARY}"

117
README.md
View File

@@ -1,4 +1,6 @@
<h1 align="center">❄️ SnowLuma</h1>
<h1 align="center">
<img src=".github/logo.svg" width="100%" alt="SnowLuma" />
</h1>
<p align="center">
<i>Next Remote Protocol Framework.</i>
@@ -7,8 +9,7 @@
<p align="center">
<a href="https://github.com/SnowLuma/SnowLuma/releases"><img alt="Release" src="https://img.shields.io/github/v/release/SnowLuma/SnowLuma?label=release&style=flat-square"></a>
<a href="https://github.com/SnowLuma/SnowLuma/actions"><img alt="Build" src="https://img.shields.io/github/actions/workflow/status/SnowLuma/SnowLuma/release.yml?branch=main&style=flat-square&label=build"></a>
<a href="https://www.npmjs.com/package/@snowluma/sdk"><img alt="@snowluma/sdk" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=%40snowluma%2Fsdk&color=cb3837"></a>
<a href="https://www.npmjs.com/package/@snowluma/ui"><img alt="@snowluma/ui" src="https://img.shields.io/npm/v/%40snowluma%2Fui?style=flat-square&label=%40snowluma%2Fui&color=cb3837"></a>
<a href="https://www.npmjs.com/package/@snowluma/sdk"><img alt="NPM" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=sdk&color=cb3837"></a>
<a href="https://github.com/SnowLuma/SnowLuma/stargazers"><img alt="Stars" src="https://img.shields.io/github/stars/SnowLuma/SnowLuma?style=flat-square"></a>
</p>
@@ -21,111 +22,29 @@
---
## 简介
SnowLuma 在 QQ 客户端与生态侧之间承担协议转换工作,向上以 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准协议暴露能力。Bridge 层负责会话与事件枢纽,再通过 WebSocket / HTTP / WebUI 等多种适配器对外提供接入。
项目持续迭代中,稳定版本通过 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 发布。
SnowLuma 是一个基于 TypeScript 的协议转换框架,旨在为 QQ 客户端提供 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准接口,支持 WebSocket/HTTP 适配、多账号并行及 WebUI 管理。
## 特性
- **OneBot v11 兼容** —— 涵盖文本、图片、视频、语音、合并转发、戳一戳、Markdown、JSON、XML 等常用消息段。
- **多账号并行** —— 同一进程可同时托管多个 QQ 账号,会话彼此独立。
- **多种适配器** —— WebSocket Server / WebSocket Client / HTTP Server / HTTP Post,HTTP 服务端同时支持 `application/json` 与 `application/x-www-form-urlencoded`。
- **WebUI 管理面板** —— 浏览器登录、密码强度校验、登录限流、SSE 实时日志、配置热更新。
- **TypeScript 全链路** —— Bridge / OneBot / SDK / UI 均使用 TypeScript,发布到 npm 的 `@snowluma/sdk` 与 `@snowluma/ui` 可直接供下游应用消费。
- **数据持久化** —— 好友、群、群成员等关系数据落 SQLite,跨重启可用。
- **OneBot v11 兼容**:支持文本、音视频、Markdown、JSON 等消息格式。
- **高性能架构**:TypeScript 全栈,基于 pnpm monorepo 管理,核心逻辑分离。
- **现代化管理**:内置 WebUI 面板,支持实时日志、密码热更、多账号管理。
- **多适配器支持**:WebSocket (Server/Client)、HTTP (Server/Post)。
- **数据持久化**:使用 SQLite 存储好友、群组等关系数据。
## 快速开始
下载预构建发布包:
```bash
# 从 Releases 下载 zip,解压到任意目录
./launcher.bat # Windows
```
或从源码开发:
```bash
git clone https://github.com/SnowLuma/SnowLuma.git
cd SnowLuma
pnpm install
pnpm build
pnpm start
```
WebUI 默认监听 `5099` 端口。首次启动会在控制台打印 `initial credentials: user=admin password=<...>`,登录后请立即修改。
若未完成首次改密就关闭进程,下次启动会自动重新生成一个新的随机密码。
## 工作区
本仓库使用 pnpm monorepo 管理,各包职责如下:
| 包 | 说明 |
| --- | --- |
| [`@snowluma/core`](packages/core) | 核心:协议层 / Bridge / OneBot / WebUI 全部在此。 |
| [`@snowluma/sdk`](packages/sdk) | OneBot HTTP & WebSocket TypeScript SDK,发布到 npm。 |
| [`@snowluma/ui`](packages/ui) | Tailwind 4 共享组件库(shadcn 风格),发布到 npm。 |
| [`@snowluma/websocket`](packages/websocket) | OneBot WebSocket 适配器底层。 |
| [`@snowluma/proton`](packages/proton) | 编译期 protobuf 编/解码器生成器:TS interface 标注 `pb<N, T>`,Vite 插件在构建时把 `protobuf_encode<T>` / `protobuf_decode<T>` 替换为内联 codec,零运行时反射。 |
| [`@snowluma/runtime`](packages/runtime) | 运行时清单与发布包资源。 |
| [`webui`](packages/webui) | Web 管理面板前端。 |
## 架构
```mermaid
flowchart TD
A([QQ 客户端])
B["协议层<br/><sub>packet pipeline · cmd 分派</sub>"]
C["Bridge 层<br/><sub>会话调度 · 花名册缓存 · 消息发送</sub>"]
D["OneBot 层<br/><sub>Event Converter · Action Handler</sub>"]
E([WS / HTTP / WebUI])
A --> B --> C --> D --> E
```
## 文档
- [路线图](RoadMap.md)
- [贡献指南](CONTRIBUTING.md)
- [行为准则](CODE_OF_CONDUCT.md)
## 开发命令
```bash
pnpm dev # 启动 core dev server
pnpm dev:web # 启动 webui dev server
pnpm test # 运行 core 测试
pnpm typecheck # 全仓库 type check
pnpm build:all # 构建 core + sdk + webui
```
1. 从 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载最新发布包并解压。
2. 运行 `./launcher.bat` (Windows) 或 `./launcher.sh` (Linux)。
3. 访问 `http://localhost:5099` (初始账号 `admin`,密码见控制台输出)。
## 鸣谢
- [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) —— Proto 定义参考。
- [NapCatQQ](https://github.com/NapNeko/NapCatQQ) —— Scanner 与 Packet 处理实现参考。
参考了 [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) 的协议定义与 [NapCatQQ](https://github.com/NapNeko/NapCatQQ) 的实现思路。
## 贡献者
---
感谢每一位为 SnowLuma 提交过代码的伙伴。
<p align="center">
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors"><img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" /></a>
</p>
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors">
<img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" alt="Contributors" />
</a>
## Star 趋势
<a href="https://star-history.com/#SnowLuma/SnowLuma&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date" />
</picture>
</a>
## 社区
- QQ 群:[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
- Telegram:[SnowLuma-TG](https://t.me/napcatqq)
- 问题反馈:[GitHub Issues](https://github.com/SnowLuma/SnowLuma/issues)

View File

@@ -1,6 +1,6 @@
{
"name": "snowluma-monorepo",
"version": "1.9.2",
"version": "1.9.7",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
@@ -8,7 +8,8 @@
"build": "pnpm --filter @snowluma/core build",
"build:sdk": "pnpm --filter @snowluma/sdk build",
"build:webui": "pnpm --filter webui build",
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter webui build",
"build:mcp": "pnpm --filter @snowluma/mcp build",
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter @snowluma/mcp build && pnpm --filter webui build",
"dev": "pnpm --filter @snowluma/core dev",
"dev:mode": "cd dist && cross-env SNOWLUMA_DEV_MODE=1 SNOWLUMA_DEV_WEBUI=1 node index.mjs",
"dev:web": "pnpm --filter webui dev",

View File

@@ -1,6 +1,6 @@
{
"name": "@snowluma/bridge",
"version": "1.9.2",
"version": "1.9.7",
"private": true,
"type": "module",
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",

View File

@@ -465,6 +465,12 @@ export class QqHookClient extends EventEmitter {
});
const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>();
// Always attach a handler so a rejection can never become "unhandled" (which
// crashes Node). When the pipe closes, rejectControlPending() rejects every
// pending deferred — but the reply is only `await`ed AFTER the ack, so if the
// ack fails first the reply promise is rejected with NO awaiter. The real
// `await` below still observes the value/rejection (a separate continuation).
ackDeferred.promise.catch(() => { /* observed by the await, or harmless */ });
this.pendingAcks.set(requestId, {
resolve: ackDeferred.resolve,
reject: ackDeferred.reject,
@@ -474,6 +480,7 @@ export class QqHookClient extends EventEmitter {
let replyDeferred: Deferred<QqHookSendReply> | null = null;
if (wantReply) {
replyDeferred = createDeferred<QqHookSendReply>();
replyDeferred.promise.catch(() => { /* see note above — prevents unhandled rejection */ });
this.pendingReplies.set(requestId, replyDeferred);
}

View File

@@ -1,5 +1,6 @@
import { exec } from 'child_process';
import net from 'net';
import https from 'https';
import { promisify } from 'util';
const execAsync = promisify(exec);
@@ -8,6 +9,13 @@ const PORT_RANGE_START = 9210;
const PORT_RANGE_END = 9219;
const PROBE_TIMEOUT_MS = 1000;
const CONNECTION_TIMEOUT_MS = 500;
// QQ's Ptlogin quick-login ports plus its main process mean a single
// logged-in client surfaces roughly this many processes. When no usable
// probe port is found, a count BELOW this implies the target PID is still at
// the login screen; AT/ABOVE it the environment is ambiguous (multiple or
// unrelated `qq` processes), so we fall through to deep-link probing rather
// than guess "logged out".
const LOGGED_OUT_PROCESS_COUNT_MAX = 6;
export interface QqPortLoginInfo {
port: number;
@@ -42,6 +50,7 @@ function decodeJwt(token: string): JwtPayload | null {
}
}
async function probePort(port: number): Promise<QqPortLoginInfo | null> {
return new Promise((resolve) => {
const client = new net.Socket();
@@ -108,6 +117,93 @@ async function probePort(port: number): Promise<QqPortLoginInfo | null> {
});
}
/** One entry of the Ptlogin `pt_get_uins` JSONP array. Only the fields the
* probe reads are modelled; QQ sends more but they're irrelevant here. */
interface PtloginUin {
uin?: string | number;
account?: string | number;
nickname?: string;
}
async function fetchPtlogin(port: number): Promise<PtloginUin[]> {
return new Promise((resolve) => {
const url = `https://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`;
const req = https.get(
url,
{
headers: {
Host: 'localhost.ptlogin2.qq.com',
Referer: 'https://xui.ptlogin2.qq.com/',
Cookie: 'pt_local_token=0',
},
rejectUnauthorized: false, // 忽略本地自签证书报错
timeout: CONNECTION_TIMEOUT_MS,
},
(res) => {
let text = '';
res.on('data', (chunk) => { text += chunk.toString(); });
res.on('end', () => {
try {
// 100% 复刻 Python 切片逻辑:获取两个方括号中间的字符串,再包装成数组
const inner = text.split('[')[1].split(']')[0];
const data = JSON.parse('[' + inner + ']') as PtloginUin[];
resolve(data);
} catch {
resolve([]);
}
});
}
);
req.on('error', () => resolve([]));
req.on('timeout', () => {
req.destroy();
resolve([]);
});
});
}
async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallback'> {
// 抽象的 QQNT
const res1 = await fetchPtlogin(port);
const res2 = await fetchPtlogin(port);
const target = res1.length < res2.length ? res1 : res2;
if (target.length === 1) {
const account = target[0];
return {
port,
uin: String(account.uin || account.account || ''),
nickName: account.nickname || '',
loggedIn: true,
};
}
// Any non-1 result — the 2+0 alternation, both-2, both-empty, etc. — is
// inconclusive; hand off to the deep-link / process-count fallback.
return 'fallback';
}
async function getQqProcessCount(): Promise<number> {
try {
if (process.platform === 'win32') {
const { stdout } = await execAsync('tasklist /fi "imagename eq QQ.exe" /nh');
return stdout.toLowerCase().split('\n').filter(line => line.includes('qq.exe')).length;
} else {
const { stdout } = await execAsync('pgrep -c qq');
return parseInt(stdout.trim(), 10) || 0;
}
} catch {
// On failure report the ambiguous threshold so we never falsely
// conclude "logged out".
return LOGGED_OUT_PROCESS_COUNT_MAX;
}
}
async function getProcessPorts(pid: number): Promise<number[]> {
try {
if (process.platform === 'win32') {
@@ -119,13 +215,11 @@ async function getProcessPorts(pid: number): Promise<number[]> {
if (parts.length < 5) continue;
const owningPid = parts[parts.length - 1];
if (owningPid !== String(pid)) continue;
const localAddr = parts[1];
const portMatch = localAddr.match(/:(\d+)$/);
if (!portMatch) continue;
const port = Number(portMatch[1]);
if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) {
ports.add(port);
}
ports.add(Number(portMatch[1]));
}
return Array.from(ports);
} else {
@@ -135,10 +229,7 @@ async function getProcessPorts(pid: number): Promise<number[]> {
for (const line of lines) {
const match = line.match(/:(\d+)\s/);
if (match) {
const port = Number(match[1]);
if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) {
ports.add(port);
}
ports.add(Number(match[1]));
}
}
return Array.from(ports);
@@ -148,18 +239,41 @@ async function getProcessPorts(pid: number): Promise<number[]> {
}
}
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
const ports = await getProcessPorts(pid);
if (ports.length === 0) {
for (let port = PORT_RANGE_START; port <= PORT_RANGE_END; port++) {
const info = await probePort(port);
if (info) return info;
const totalPids = await getQqProcessCount();
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
return { port: 0, uin: '', loggedIn: false };
}
return null;
}
for (const port of ports) {
const PT_PORTS = [4301, 4303, 4305, 4307, 4309];
const matchedPtPorts = ports.filter(p => PT_PORTS.includes(p));
if (matchedPtPorts.length > 0) {
for (const port of matchedPtPorts) {
const ptResult = await tryPtloginMethod(port);
if (ptResult !== 'fallback') {
return ptResult;
}
}
} else {
const totalPids = await getQqProcessCount();
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
return {
port: ports[0] || 0,
uin: '',
loggedIn: false,
};
}
}
const deepLinkPorts = ports.filter(p => p >= PORT_RANGE_START && p <= PORT_RANGE_END);
for (const port of deepLinkPorts) {
const info = await probePort(port);
if (info) return info;
}

View File

@@ -1,8 +1,9 @@
import net from 'net';
import { mkdtemp, rm, writeFile } from 'fs/promises';
import os from 'os';
import path from 'path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { listLiveLinuxPipePids } from '../src/qq-hook-client';
import { listLiveLinuxPipePids, QqHookClient } from '../src/qq-hook-client';
let tmpDir: string | null = null;
@@ -42,3 +43,66 @@ describe('listLiveLinuxPipePids', () => {
expect(probe).toHaveBeenCalledTimes(2);
});
});
describe.skipIf(process.platform === 'win32')('QqHookClient — pipe close mid-send', () => {
// Regression: when the control pipe closes while a send() is awaiting its
// ack, rejectControlPending() rejects BOTH the ack and reply deferreds. The
// reply is only `await`ed after the ack, so if the ack rejects first the
// reply promise is rejected with NO awaiter — an UNHANDLED rejection that
// crashes the Node process (Docker: supervisor restarts it ~1s later; on
// Windows it just dies → "connection pipe closed", bot down). The .catch()
// guard on each deferred prevents it; without the guard this test trips the
// unhandledRejection assertion below.
it('does not raise an unhandled rejection', async () => {
const dir = await mkdtemp(path.join(os.tmpdir(), 'snowluma-pipe-'));
const prevRuntimeDir = process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
process.env.SNOWLUMA_HOOK_RUNTIME_DIR = dir;
const PID = 778899;
const helloFrame = (): Buffer => {
const h = Buffer.alloc(40);
h.writeUInt32LE(0x31504851, 0); // PIPE_MAGIC
h.writeUInt16LE(1, 4); // PIPE_VERSION
h.writeUInt16LE(1, 6); // PipeOp.hello
h.writeBigUInt64LE(BigInt(PID), 32); // value0 = pid
return h;
};
let controlConn: net.Socket | null = null;
const controlServer = net.createServer((sock) => { controlConn = sock; sock.write(helloFrame()); });
const recvServer = net.createServer((sock) => { sock.write(helloFrame()); });
await new Promise<void>((r) => controlServer.listen(path.join(dir, `mojo.${PID}.control.sock`), () => r()));
await new Promise<void>((r) => recvServer.listen(path.join(dir, `mojo.${PID}.recv.sock`), () => r()));
const unhandled: unknown[] = [];
const onUnhandled = (reason: unknown): void => { unhandled.push(reason); };
process.on('unhandledRejection', onUnhandled);
const client = new QqHookClient(PID);
client.on('error', () => { /* socket reset on destroy — ignore */ });
try {
await client.connectAll({ recv: true });
// Start a reply-expecting send, let it reach the in-flight (awaiting-ack)
// state, then have the "hook" drop the pipe before it answers.
const sent = client.send('noop', null, { wantReply: true, ackTimeoutMs: 1000, replyTimeoutMs: 1000 })
.then(() => 'resolved' as const, (e: unknown) => e);
await new Promise((r) => setTimeout(r, 30));
controlConn?.destroy();
const outcome = await sent;
await new Promise((r) => setTimeout(r, 50)); // let Node surface any unhandled rejection
expect(outcome).toBeInstanceOf(Error);
expect(unhandled, `unhandled rejections leaked: ${unhandled.map(String).join(', ')}`).toHaveLength(0);
} finally {
process.off('unhandledRejection', onUnhandled);
client.close();
await new Promise<void>((r) => controlServer.close(() => r()));
await new Promise<void>((r) => recvServer.close(() => r()));
if (prevRuntimeDir === undefined) delete process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
else process.env.SNOWLUMA_HOOK_RUNTIME_DIR = prevRuntimeDir;
await rm(dir, { recursive: true, force: true });
}
});
});

View File

@@ -1,6 +1,6 @@
{
"name": "@snowluma/common",
"version": "1.9.2",
"version": "1.9.7",
"private": true,
"type": "module",
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",

View File

@@ -49,3 +49,70 @@ export function summarizeParams(params: unknown): string {
}
return out.join(' ');
}
const VERBOSE_STRING_MAX = 200;
const VERBOSE_TOTAL_MAX = 1500;
// Keys whose values must never be rendered — tokens, passwords, secrets.
const REDACT_KEY = /^(.*[-_])?(token|password|passwd|secret|access[-_]?token)([-_].*)?$/i;
/**
* Deep, debug-grade render of a params object for the `trace` level: shows the
* full nested structure (message segments, nested objects) so a reproduction
* is legible — unlike {@link summarizeParams}, which collapses nested values.
*
* Three guards keep it safe and bounded:
* - per-string cap (long values like base64 image data become `"…<N B>"`),
* - total output budget (so a giant payload can't flood the buffer),
* - key-based redaction (token / password / secret → `"***"`).
*/
export function renderParamsVerbose(params: unknown): string {
const seen = new WeakSet<object>();
let budget = VERBOSE_TOTAL_MAX;
const walk = (value: unknown, key?: string): string => {
if (budget <= 0) return '…';
if (key !== undefined && REDACT_KEY.test(key)) return '"***"';
if (value === null) return 'null';
if (value === undefined) return 'undefined';
switch (typeof value) {
case 'string': {
const truncated =
value.length > VERBOSE_STRING_MAX
? `${value.slice(0, VERBOSE_STRING_MAX)}…<${value.length}B>`
: value;
const out = JSON.stringify(truncated);
budget -= out.length;
return out;
}
case 'number':
case 'boolean':
case 'bigint': {
const out = String(value);
budget -= out.length;
return out;
}
case 'object': {
if (seen.has(value as object)) return '"[circular]"';
seen.add(value as object);
const parts: string[] = [];
if (Array.isArray(value)) {
for (const item of value) {
if (budget <= 0) { parts.push('…'); break; }
parts.push(walk(item));
}
return `[${parts.join(',')}]`;
}
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
if (budget <= 0) { parts.push('…'); break; }
parts.push(`${k}:${walk(v, k)}`);
}
return `{${parts.join(',')}}`;
}
default:
return typeof value;
}
};
return walk(params);
}

View File

@@ -1,7 +1,8 @@
import { format } from 'util';
import { getFileTransport } from './log-file-transport';
import { currentRequestId } from './request-context';
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
type LogLevel = 'trace' | 'debug' | 'info' | 'success' | 'warn' | 'error';
export interface LogEntry {
id: number;
@@ -10,6 +11,8 @@ export interface LogEntry {
scope: string;
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
uin?: number;
/** Correlation id, when emitted inside a `runWithRequestId(...)` scope. */
req?: number;
message: string;
line: string;
}
@@ -26,6 +29,7 @@ interface LogOptions {
const UIN_SLOT_WIDTH = 12;
const LEVEL_WEIGHT: Record<LogLevel, number> = {
trace: 5,
debug: 10,
info: 20,
success: 25,
@@ -34,6 +38,7 @@ const LEVEL_WEIGHT: Record<LogLevel, number> = {
};
const LEVEL_LABEL: Record<LogLevel, string> = {
trace: 'TRACE',
debug: 'DEBUG',
info: 'INFO',
success: 'OK',
@@ -42,6 +47,7 @@ const LEVEL_LABEL: Record<LogLevel, string> = {
};
const COLOR_CODE: Record<LogLevel, number> = {
trace: 90,
debug: 90,
info: 36,
success: 32,
@@ -53,13 +59,55 @@ const COLOR_SCOPE = 35;
const COLOR_DIM = 2;
const COLOR_RESET = '\x1b[0m';
const MAX_LOG_ENTRIES = 1000;
const logEntries: LogEntry[] = [];
/** Trace ring cap — env-tunable since trace is the high-volume stream. */
function resolveTraceBufferMax(): number {
const raw = Number.parseInt(process.env.SNOWLUMA_TRACE_BUFFER ?? '', 10);
return Number.isFinite(raw) && raw >= 100 ? raw : 5000;
}
const TRACE_BUFFER_MAX = resolveTraceBufferMax();
/**
* Fixed-capacity circular buffer. O(1) push + eviction (no array `.shift()`),
* so the high-throughput trace stream never pays an O(n) shift per overflow.
*/
class RingBuffer<T> {
private readonly buf: (T | undefined)[];
private start = 0;
private count = 0;
constructor(private readonly cap: number) {
this.buf = new Array<T | undefined>(cap);
}
push(item: T): void {
const end = (this.start + this.count) % this.cap;
this.buf[end] = item;
if (this.count < this.cap) this.count += 1;
else this.start = (this.start + 1) % this.cap; // full → overwrite oldest
}
/** Most recent `n` items, oldest→newest. */
recent(n: number): T[] {
const take = Math.max(0, Math.min(Math.trunc(n), this.count));
const out: T[] = new Array<T>(take);
const first = this.start + (this.count - take);
for (let i = 0; i < take; i += 1) out[i] = this.buf[(first + i) % this.cap]!;
return out;
}
toArray(): T[] {
return this.recent(this.count);
}
get size(): number {
return this.count;
}
}
const logRing = new RingBuffer<LogEntry>(MAX_LOG_ENTRIES);
const traceRing = new RingBuffer<LogEntry>(TRACE_BUFFER_MAX);
const logSubscribers = new Set<(entry: LogEntry) => void>();
let nextLogId = 1;
function resolveMinLevel(): LogLevel {
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
if (raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
if (raw === 'trace' || raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
return raw;
}
return 'info';
@@ -75,7 +123,7 @@ function shouldLog(level: LogLevel): boolean {
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
}
export const LOG_LEVELS: readonly LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
export const LOG_LEVELS: readonly LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
export function getLogLevel(): LogLevel {
return currentLevel;
@@ -110,15 +158,16 @@ function currentTime(): string {
return `${hh}:${mm}:${ss}`;
}
function render(level: LogLevel, options: LogOptions, args: unknown[]): string {
function render(level: LogLevel, options: LogOptions, args: unknown[], reqId?: number): string {
const message = format(...args);
const ts = currentTime();
const label = LEVEL_LABEL[level].padEnd(5, ' ');
const uinTag = options.uin !== undefined ? `[${options.uin}]` : '';
const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH);
const reqTag = reqId !== undefined ? `[req#${reqId}]` : '';
if (!useColor()) {
return `${ts} ${label} ${uinSlot} [${options.scope}] ${message}`;
return `${ts} ${label} ${uinSlot} [${options.scope}] ${reqTag ? `${reqTag} ` : ''}${message}`;
}
const cTs = ansi(COLOR_DIM, ts);
@@ -129,28 +178,46 @@ function render(level: LogLevel, options: LogOptions, args: unknown[]): string {
? ansi(COLOR_DIM, uinTag) + ' '.repeat(UIN_SLOT_WIDTH - uinTag.length)
: ' '.repeat(UIN_SLOT_WIDTH);
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
return `${cTs} ${cLabel} ${cUin} ${cScope} ${message}`;
const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : '';
return `${cTs} ${cLabel} ${cUin} ${cScope} ${cReq}${message}`;
}
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
// Console / subscriber level filter. File output is debug-and-up always;
// see log-file-transport.ts.
const passesConsole = shouldLog(level);
const message = format(...args);
const line = render(level, options, args);
// `trace` never touches disk and is the high-volume full-chain stream. When
// it won't reach the console/memory buffer either (level not dialed to
// trace), bail BEFORE format/render AND before evaluating any lazy producer
// — this is what keeps full-chain tracing ~free at the default level even
// with hundreds of groups.
if (level === 'trace' && !passesConsole) return;
// Lazy trace form: `log.trace(() => ['…', deepRender(x)])`. The producer
// (and its expensive deep render) only runs now that trace is confirmed live.
let realArgs = args;
if (level === 'trace' && args.length === 1 && typeof args[0] === 'function') {
realArgs = (args[0] as () => unknown[])();
}
const reqId = currentRequestId();
const message = format(...realArgs);
const line = render(level, options, realArgs, reqId);
const entry: LogEntry = {
id: nextLogId++,
time: new Date().toISOString(),
level,
scope: options.scope,
...(options.uin !== undefined ? { uin: options.uin } : {}),
...(reqId !== undefined ? { req: reqId } : {}),
message,
line,
};
if (passesConsole) {
logEntries.push(entry);
if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift();
// Trace gets its own ring so its volume never evicts the normal log buffer.
(level === 'trace' ? traceRing : logRing).push(entry);
for (const subscriber of logSubscribers) subscriber(entry);
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
// Strip ASCII control characters before writing to terminal to prevent
@@ -162,10 +229,11 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
stream.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
}
// File transport always sees every level (debug-and-up) for post-mortem
// value; ANSI stripping happens inside the transport. UIN routes the
// line to its per-account sub-file in addition to the shared one.
getFileTransport().write(line, options.uin);
// File transport sees debug-and-up for post-mortem value; `trace` is
// memory / WebUI only (omitted here to avoid huge on-disk volume). ANSI
// stripping happens inside the transport. UIN routes the line to its
// per-account sub-file in addition to the shared one.
if (level !== 'trace') getFileTransport().write(line, options.uin);
}
/**
@@ -179,8 +247,14 @@ export function closeLogger(): Promise<void> {
}
export function getRecentLogs(limit = 300): LogEntry[] {
const n = Math.max(1, Math.min(Math.trunc(limit), MAX_LOG_ENTRIES));
return logEntries.slice(-n);
const n = Math.max(1, Math.trunc(limit));
// Merge the normal + trace rings by id (ids are monotonic, so id order is
// chronological). The trace ring is empty unless trace level is/was active,
// so the common case is just the normal ring with no sort.
const merged = traceRing.size > 0
? [...logRing.toArray(), ...traceRing.toArray()].sort((a, b) => a.id - b.id)
: logRing.toArray();
return merged.slice(-n);
}
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
@@ -191,6 +265,13 @@ export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
}
export interface Logger {
/**
* High-volume, memory-only diagnostic level (never written to disk). Pass a
* lazy producer — `trace(() => ['msg %s', expensiveRender(x)])` — so the
* arguments (and any costly rendering) are built only when trace is active.
* A plain `trace('msg', x)` works too but evaluates its args eagerly.
*/
trace: (...args: unknown[]) => void;
debug: (...args: unknown[]) => void;
info: (...args: unknown[]) => void;
success: (...args: unknown[]) => void;
@@ -207,6 +288,7 @@ export interface Logger {
function makeLogger(opts: LogOptions): Logger {
return {
trace: (...args: unknown[]) => emit('trace', opts, args),
debug: (...args: unknown[]) => emit('debug', opts, args),
info: (...args: unknown[]) => emit('info', opts, args),
success: (...args: unknown[]) => emit('success', opts, args),
@@ -226,3 +308,8 @@ function makeLogger(opts: LogOptions): Logger {
export function createLogger(scope: string): Logger {
return makeLogger({ scope });
}
// Request-correlation helpers live alongside the logger since `[req#N]`
// stamping is a logging concern. Re-exported here so callers import the
// whole logging surface from one place.
export { nextRequestId, runWithRequestId, currentRequestId } from './request-context';

View File

@@ -0,0 +1,35 @@
import { AsyncLocalStorage } from 'async_hooks';
interface RequestStore {
id: number;
}
const storage = new AsyncLocalStorage<RequestStore>();
let counter = 0;
/**
* Allocate the next per-process request id (monotonic). Wraps via uint32 so
* it never overflows to a non-integer; `0` is skipped so "no id" stays
* unambiguous.
*/
export function nextRequestId(): number {
counter = (counter + 1) >>> 0;
if (counter === 0) counter = 1;
return counter;
}
/**
* Run `fn` with `id` bound as the ambient request id for the entire async
* chain it spawns. Any logger call anywhere in that chain — across packages,
* across awaits — picks it up via {@link currentRequestId} with no signature
* threading. Used by the OneBot action handler to correlate a request's whole
* journey (entry → outbound packets → exit) under one `[req#N]` tag.
*/
export function runWithRequestId<T>(id: number, fn: () => T): T {
return storage.run({ id }, fn);
}
/** The request id bound to the current async context, or undefined outside one. */
export function currentRequestId(): number | undefined {
return storage.getStore()?.id;
}

View File

@@ -1,6 +1,6 @@
{
"name": "@snowluma/core",
"version": "1.9.2",
"version": "1.9.7",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
@@ -46,7 +46,6 @@
"@snowluma/protocol": "workspace:*",
"@snowluma/proto-defs": "workspace:*",
"@snowluma/proton": "workspace:*",
"@snowluma/sqlite": "workspace:*",
"@snowluma/websocket": "workspace:*"
},
"devDependencies": {

View File

@@ -5,9 +5,38 @@ 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 { PttTransReq, PttTransResp } from '@snowluma/proto-defs/ptt-trans';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '../bridge-context';
import type { MediaIndexNode } from './shared';
/** Inputs for a voice-to-text request, gathered from the received `record`
* element + its message meta. `uuid`/`md5Hex` come from the cached record;
* the uins + scene from the message meta. */
export interface PttTransInput {
isGroup: boolean;
msgId: number;
senderUin: number;
/** Receiver uin (c2c) or group uin (group). */
peerUin: number;
uuid: string;
md5Hex: string;
duration: number;
size: number;
format: number;
/** Group ptt numeric file id (group only; optional). */
fileId?: number;
}
function hexToBytes(hex: string): Uint8Array {
const s = (hex || '').trim();
if (!s) return new Uint8Array(0);
const len = s.length >> 1;
const out = new Uint8Array(len);
for (let i = 0; i < len; i++) out[i] = parseInt(s.substr(i * 2, 2), 16);
return out;
}
// ─────────────── public types (re-exported from bridge.ts as before) ───
export type StrangerStatus = NamespaceStrangerStatus;
@@ -88,4 +117,44 @@ export class ExtrasApi {
}
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
}
// ─────────────── Voice-to-text (pttTrans.Trans{C2C,Group}PttReq) ───────────────
/**
* Send ONE `pttTrans.Trans{C2C,Group}PttReq` to trigger transcription and
* return the recognised text IF the response carries it inline (the
* already-transcribed case). For a freshly-received voice the response is an
* empty ack and the text is delivered later via the async Event 0x210
* subType-61 push — callers should treat `''` as "pending" and wait for the
* `ptt_trans_result` event (correlated by msgId). Live-verified end to end.
*/
async translatePttToText(input: PttTransInput): Promise<string> {
const md5 = hexToBytes(input.md5Hex);
const req: PttTransReq = input.isGroup
? {
type: 1,
groupItem: {
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), groupUin: BigInt(input.peerUin),
fileId: input.fileId ?? 0, md5, duration: input.duration, size: input.size,
format: input.format, uuid: input.uuid,
},
}
: {
type: 2,
c2cItem: {
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), receiverUin: BigInt(input.peerUin),
uuid: input.uuid, duration: input.duration, size: input.size, format: input.format, md5,
},
};
const cmd = input.isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq';
const result = await this.ctx.sendRawPacket(cmd, protobuf_encode<PttTransReq>(req));
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'ptt translate request failed');
}
const resp = protobuf_decode<PttTransResp>(result.responseData);
const item = input.isGroup ? resp?.groupResult : resp?.c2cResult;
if (item?.errCode) throw new Error(`ptt translate failed: error=${item.errCode}`);
return item?.text ?? ''; // '' = transcribing async; caller awaits the push
}
}

View File

@@ -9,6 +9,7 @@ import type { BridgeContext } from '../bridge-context';
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 { RequestDbKey } from '@snowluma/protocol/oidb-services/misc/request-decrypt-key';
export class MiscApi {
constructor(private readonly ctx: BridgeContext) { }
@@ -75,4 +76,15 @@ export class MiscApi {
sendGroupSign(groupId: number): Promise<void> {
return SendGroupSign.invoke(this.ctx, { groupId });
}
async getDecryptKey(dbSalt: string): Promise<string> {
const result = await RequestDbKey.invoke(this.ctx, { db_salt: dbSalt });
if (!result.success) {
throw new Error(result.errorMsg || `Failed to get decrypt key (code: ${result.errorCode})`);
}
if (!result.dbKey) {
throw new Error('Decrypt key is empty');
}
return result.dbKey;
}
}

View File

@@ -1,3 +1,4 @@
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key';
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
import { getGroupEssenceMsg, getGroupEssenceMsgAll, type GroupEssenceMsgRet } from '@snowluma/protocol/web/group-essence';
@@ -247,16 +248,11 @@ export class WebApi {
let imgHeight = 300;
if (options?.image) {
let imageBuffer: Buffer;
if (options.image.startsWith('http://') || options.image.startsWith('https://')) {
const response = await fetch(options.image);
if (!response.ok) throw new Error(`Failed to download image: ${response.status}`);
imageBuffer = Buffer.from(await response.arrayBuffer());
} else {
const { readFileSync } = await import('fs');
imageBuffer = readFileSync(options.image);
}
// Route through loadBinarySource so the group-notice image download
// gets the same browser-UA + Referer-retry hardening as every other
// media fetch — and http/file/base64 source handling for free.
const loaded = await loadBinarySource(options.image, 'group-notice image');
const imageBuffer = Buffer.from(loaded.bytes);
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
if (picInfo) {

View File

@@ -1,3 +1,4 @@
import { createLogger } from '@snowluma/common/logger';
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
@@ -12,6 +13,7 @@ import {
} from './apis/extras';
import type { BridgeInterface } from './bridge-interface';
const log = createLogger('Bridge');
export class Bridge implements BridgeInterface {
readonly identity: IdentityService;
@@ -129,12 +131,29 @@ export class Bridge implements BridgeInterface {
}
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
if (!this.packetClient_) {
log.warn('packet %s dropped: no packet sender attached', serviceCmd);
return {
success: false, gotResponse: false, errorCode: -1,
errorMessage: 'no packet sender attached', responseData: null,
};
}
return this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
const startedAt = Date.now();
const result = await this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
const elapsed = Date.now() - startedAt;
const respLen = result.responseData ? result.responseData.length : 0;
if (!result.success || result.errorCode !== 0) {
// QQ-side rejection or transport failure — the usual root cause when an
// action misbehaves. Warn (persisted) with cmd + code so a user's log
// shows exactly where the chain broke.
log.warn('packet %s failed: code=%d gotResponse=%s %s (uin=%s, %dB, %dms)',
serviceCmd, result.errorCode, result.gotResponse,
result.errorMessage ?? '', this.identity.uin, body.length, elapsed);
} else {
// Happy path — memory-only trace so the full chain shows under the
// request's [req#N] when debugging, without flooding disk.
log.trace(() => [`packet ${serviceCmd} ok (${body.length}B⇄${respLen}B, ${elapsed}ms)`]);
}
return result;
}
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
return this.identity.resolveUid(uin, groupId);

View File

@@ -7,6 +7,22 @@ import { BridgeManager } from './bridge/manager';
const runtimeConfig = loadRuntimeConfig();
const log = createLogger('App');
// Last-resort process guards. This is a long-running daemon: a hooked QQ pipe
// can drop at any moment, and a stray rejection on a detached callback (or a
// throw that escapes one) must NOT take the whole process down — otherwise
// Docker restarts it (dropping every session) and a bare Windows run just dies
// ("connection pipe closed", bot offline). Log and keep serving; the bridge's
// own watcher reconnects the dropped pipe. Targeted handlers still cover the
// known paths (e.g. the hook-client send deferreds) — these only catch what
// slips through, and surface its stack so the real source can be fixed.
process.on('unhandledRejection', (reason) => {
log.error('unhandledRejection (kept alive): %s',
reason instanceof Error ? (reason.stack ?? reason.message) : String(reason));
});
process.on('uncaughtException', (error) => {
log.error('uncaughtException (kept alive): %s', error.stack ?? error.message);
});
async function main() {
log.info('SnowLuma starting');

View File

@@ -14,6 +14,7 @@ import { fileURLToPath } from 'url';
import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth';
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
import { findAvailablePort } from './port';
import { getUpdateInfo } from './update-check';
const log = createLogger('WebUI');
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -285,6 +286,16 @@ export async function initWebUI(
// ─── Read-only API ───────────────────────────────────────────────────────
app.get('/api/status', (c) => c.json({ status: 'running' }));
// Advisory update check — compares the running build against the latest
// GitHub stable release and links the user to it. Read-only: SnowLuma
// never downloads or applies the update itself. `?force=1` bypasses the
// server-side cache (the "立即检查" button). Never errors out — a failed
// check returns `{ hasUpdate: false, error }` and the UI degrades quietly.
app.get('/api/update/check', async (c) => {
const force = c.req.query('force') === 'true' || c.req.query('force') === '1';
return c.json(await getUpdateInfo(force));
});
// Host system info
let lastCpuTimes: { idle: number; total: number }[] | null = null;
function sampleCpuLoad(): number[] {
@@ -355,6 +366,12 @@ export async function initWebUI(
return c.json({ list });
});
// Live OneBot adapter health per account (listening / connected / client
// counts / last-delivery), powering the dashboard's connection card.
app.get('/api/connections', (c) => {
return c.json({ list: oneBotManager.getConnectionStatuses() });
});
app.get('/api/logs', (c) => {
const limit = Number(c.req.query('limit') ?? 300);
return c.json({ list: getRecentLogs(limit) });

View File

@@ -0,0 +1,163 @@
// Advisory update check against the public GitHub Releases API.
//
// Strictly read-only (T0): SnowLuma never downloads or applies anything
// itself — cross-platform self-update is a minefield (Windows locks loaded
// .node/.dll/node.exe, Docker bakes the app into image layers, bare installs
// have no supervisor). We only tell the WebUI that a newer *stable* release
// exists and link the user to it; they download and apply manually.
//
// The result is cached to stay well under GitHub's 60 req/hr unauthenticated
// rate limit, and every failure degrades silently (the UI just shows
// "无法检查更新" rather than nagging).
import { createLogger } from '@snowluma/common/logger';
const log = createLogger('Update');
const LATEST_RELEASE_URL = 'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest';
const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6h — comfortably under the rate limit
const FETCH_TIMEOUT_MS = 8_000;
const NOTES_MAX = 4_000; // cap the release-body we hand back to the client
export interface UpdateCheckResult {
/** The running build's version (no `v` prefix). */
current: string;
/** Latest stable release version, or null when the check did not complete. */
latest: string | null;
/** True only when `latest` is strictly newer than `current`. */
hasUpdate: boolean;
/** GitHub release page URL for the latest release. */
htmlUrl: string | null;
/** Release notes (markdown), truncated to {@link NOTES_MAX}. */
notes: string | null;
/** ISO timestamp the latest release was published. */
publishedAt: string | null;
/** When this result was produced (epoch ms). */
checkedAt: number;
/** Set when the check was skipped or failed; the UI degrades silently. */
error?: string;
}
interface GithubRelease {
tag_name?: string;
html_url?: string;
body?: string;
published_at?: string;
}
function currentVersion(): string {
return typeof __APP_VERSION__ === 'string' && __APP_VERSION__ ? __APP_VERSION__ : '0.0.0';
}
function isEnabled(): boolean {
const v = (process.env.SNOWLUMA_UPDATE_CHECK ?? '').trim().toLowerCase();
return v !== '0' && v !== 'false' && v !== 'off' && v !== 'no';
}
/**
* Compare two dotted versions. Returns >0 if `a` is newer than `b`, <0 if
* older, 0 if equal. The numeric core (major.minor.patch) compares
* numerically; a prerelease (`-rc.1`) ranks below its release. Good enough
* for "is the latest stable strictly newer than what we run" — and avoids
* pulling in a `semver` runtime dependency (the dist bundle ships none).
*/
export function compareVersions(a: string, b: string): number {
const parse = (v: string) => {
const [core = '', pre = ''] = v.replace(/^v/, '').split('-', 2);
const nums = core.split('.').map((n) => parseInt(n, 10) || 0);
while (nums.length < 3) nums.push(0);
return { nums, pre };
};
const pa = parse(a);
const pb = parse(b);
for (let i = 0; i < 3; i++) {
if (pa.nums[i] !== pb.nums[i]) return pa.nums[i] - pb.nums[i];
}
if (pa.pre === pb.pre) return 0;
if (!pa.pre) return 1; // release > prerelease
if (!pb.pre) return -1;
return pa.pre < pb.pre ? -1 : 1;
}
let cache: UpdateCheckResult | null = null;
let inflight: Promise<UpdateCheckResult> | null = null;
async function fetchLatest(current: string): Promise<UpdateCheckResult> {
const base: UpdateCheckResult = {
current,
latest: null,
hasUpdate: false,
htmlUrl: null,
notes: null,
publishedAt: null,
checkedAt: Date.now(),
};
try {
// `/releases/latest` already excludes drafts and prereleases, so this is
// stable-channel by construction.
const res = await fetch(LATEST_RELEASE_URL, {
headers: {
Accept: 'application/vnd.github+json',
'User-Agent': `SnowLuma/${current}`,
'X-GitHub-Api-Version': '2022-11-28',
},
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!res.ok) return { ...base, error: `github ${res.status}` };
const rel = (await res.json()) as GithubRelease;
const tag = (rel.tag_name ?? '').trim();
if (!tag) return { ...base, error: 'no tag' };
const latest = tag.replace(/^v/, '');
return {
current,
latest,
hasUpdate: compareVersions(latest, current) > 0,
htmlUrl: rel.html_url ?? null,
notes: rel.body ? rel.body.slice(0, NOTES_MAX) : null,
publishedAt: rel.published_at ?? null,
checkedAt: Date.now(),
};
} catch (e) {
return { ...base, error: e instanceof Error ? e.message : 'network error' };
}
}
/**
* Get the update-availability result. Cached for {@link CACHE_TTL_MS}; pass
* `force` to bypass the cache (the WebUI's "立即检查" button). Never throws —
* failures come back as a result with `error` set and `hasUpdate: false`, and
* are not cached so the next check retries.
*/
export async function getUpdateInfo(force = false): Promise<UpdateCheckResult> {
const current = currentVersion();
if (!isEnabled()) {
return { ...emptyResult(current), error: 'disabled' };
}
if (!force && cache && Date.now() - cache.checkedAt < CACHE_TTL_MS) return cache;
if (inflight) return inflight;
inflight = (async () => {
const result = await fetchLatest(current);
if (result.error) {
log.debug('update check failed: %s', result.error);
} else {
cache = result; // only cache good results so transient errors retry
if (result.hasUpdate) log.info('a newer release is available: v%s (running v%s)', result.latest, current);
}
return result;
})().finally(() => {
inflight = null;
});
return inflight;
}
function emptyResult(current: string): UpdateCheckResult {
return {
current,
latest: null,
hasUpdate: false,
htmlUrl: null,
notes: null,
publishedAt: null,
checkedAt: Date.now(),
};
}

View File

@@ -35,6 +35,43 @@ function commonElem(elem: any): { serviceType: number; businessType: number; pbE
return elem.commonElem;
}
function inflatePrefixedPayload(data: Uint8Array): string {
expect(data[0]).toBe(0x01);
return inflateSync(Buffer.from(data.subarray(1))).toString('utf8');
}
describe('element-builder / rich card encoding', () => {
it('encodes json segments as deflated LightApp payloads and preserves non-ASCII text', async () => {
const card = JSON.stringify({
app: 'com.tencent.structmsg',
view: 'music',
prompt: '[音乐]起风了',
meta: { music: { title: '起风了', desc: '买辣椒也用券' } },
});
const [elem] = await buildSendElems(
[{ type: 'json', text: card } as any],
{ bridge: fakeBridge, groupId: 12345 },
);
expect(elem.lightApp).toBeDefined();
expect((elem as any).richMsg).toBeUndefined();
expect(inflatePrefixedPayload(elem.lightApp!.data!)).toBe(card);
});
it('encodes xml richMsg payloads by UTF-8 bytes, not JavaScript string length', async () => {
const xml = '<msg serviceID="35" brief="[分享]中文卡片"></msg>';
const [elem] = await buildSendElems(
[{ type: 'xml', text: xml, subType: 35 } as any],
{ bridge: fakeBridge, groupId: 12345 },
);
expect(elem.richMsg?.serviceId).toBe(35);
expect(inflatePrefixedPayload(elem.richMsg!.template1!)).toBe(xml);
});
});
describe('element-builder / commonElem.businessType per scene', () => {
describe('image', () => {
it('c2c → businessType 10', async () => {
@@ -129,10 +166,7 @@ describe('element-builder / forward preview (com.tencent.multimsg LightApp)', ()
// the outer's LongMsgResult — without uniseq the QQ-NT client has
// no way to walk the tree and has to re-fetch each inner resId.
function decodeLightApp(elem: any): unknown {
const data: Uint8Array = elem.lightApp.data;
expect(data[0]).toBe(0x01); // deflate prefix
const inflated = inflateSync(Buffer.from(data.subarray(1))).toString('utf8');
return JSON.parse(inflated);
return JSON.parse(inflatePrefixedPayload(elem.lightApp.data));
}
it('emits a lightApp.data blob with prefix=0x01 (deflated JSON, not XML/serviceID=35)', async () => {

View File

@@ -99,3 +99,81 @@ describe('loadBinarySource maxBytes enforcement', () => {
).rejects.toThrow(/too large: 128 > 64/);
});
});
describe('loadBinarySource HTTP header hardening', () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
vi.restoreAllMocks();
});
it('sends a browser User-Agent on the first attempt, without a Referer', async () => {
const calls: Array<Record<string, string>> = [];
globalThis.fetch = vi.fn(async (_url: unknown, init?: RequestInit) => {
calls.push((init?.headers ?? {}) as Record<string, string>);
return new Response(new Uint8Array([1, 2, 3]), { status: 200 });
}) as typeof fetch;
await loadBinarySource('https://example.test/a.png', 'image');
expect(calls).toHaveLength(1);
expect(calls[0]['User-Agent']).toMatch(/Mozilla\/5\.0/);
expect(calls[0]['Referer']).toBeUndefined();
});
it('retries with a Referer when the first fetch fails at the network level', async () => {
// Reproduces the reported bug: an anti-bot front-end resets the
// header-less request → undici `TypeError: fetch failed`. The retry
// carries a Referer pointing at the resource itself and succeeds.
const calls: Array<Record<string, string>> = [];
globalThis.fetch = vi.fn(async (_url: unknown, init?: RequestInit) => {
calls.push((init?.headers ?? {}) as Record<string, string>);
if (calls.length === 1) throw new TypeError('fetch failed');
return new Response(new Uint8Array([9, 9]), { status: 200 });
}) as typeof fetch;
const loaded = await loadBinarySource('https://img.example.test/x.gif', 'image');
expect(Array.from(loaded.bytes)).toEqual([9, 9]);
expect(calls).toHaveLength(2);
expect(calls[0]['Referer']).toBeUndefined();
expect(calls[1]['Referer']).toBe('https://img.example.test/x.gif');
});
it('retries with a Referer on a 403 (anti-hotlink)', async () => {
let n = 0;
globalThis.fetch = vi.fn(async () => {
n++;
if (n === 1) return new Response(new Uint8Array(0), { status: 403 });
return new Response(new Uint8Array([7]), { status: 200 });
}) as typeof fetch;
const loaded = await loadBinarySource('https://cdn.example.test/y.jpg', 'image');
expect(Array.from(loaded.bytes)).toEqual([7]);
expect(n).toBe(2);
});
it('does not retry a size-limit rejection (deterministic, no second download)', async () => {
const fetchMock = vi.fn(async () => new Response(new Uint8Array(0), {
status: 200,
headers: { 'content-length': String(10 * 1024 * 1024) },
}));
globalThis.fetch = fetchMock as typeof fetch;
await expect(
loadBinarySource('https://example.test/big.bin', 'image', 1024),
).rejects.toThrow(/too large/);
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('surfaces the first error when the Referer retry also fails', async () => {
let n = 0;
globalThis.fetch = vi.fn(async () => {
n++;
throw new TypeError('fetch failed');
}) as typeof fetch;
await expect(
loadBinarySource('https://example.test/z.png', 'image'),
).rejects.toThrow(/fetch failed/);
expect(n).toBe(2);
});
});

View File

@@ -0,0 +1,161 @@
// highway-client.uploadHighwayHttp 的连接生命周期测试。
//
// 回归覆盖:当上传数据 > HIGHWAY_BLOCK_SIZE (1 MiB) 时,旧实现会复用
// 同一个 TCP socket 在 keep-alive 模式下连续 POST,但 QQ highway 的
// 边缘节点经常在第一次响应后立刻 FIN 关闭,导致第二次 POST 报
// `connection closed before response`。用户上报的 1.19 MB 图片
// (onebot retcode=1200)就是这个分支。
//
// 修复方案:每个 chunk 独立建一个新的 TCP 连接。本测试通过 mock
// `net.createConnection` 计数建连次数,断言每个 chunk 一连接的不变量。
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { EventEmitter } from 'events';
// highway-client 解析响应只关心 errorCode === 0 —— 一个完全空的
// RespDataHighwayHead protobuf 体(0 字节)会被解为 ,errorCode
// 是 undefined,走 falsy 通过分支。
//
// HTTP body 是 highway frame:
// 0x28 | head_len(BE32) | body_len(BE32) | head | body | 0x29
function buildEmptyHighwayResponseFrame(): Buffer {
const frame = Buffer.alloc(10);
frame[0] = 0x28;
frame.writeUInt32BE(0, 1); // head_len
frame.writeUInt32BE(0, 5); // body_len
frame[9] = 0x29;
return frame;
}
function buildHttpResponse(frameBody: Buffer): Buffer {
const headers = [
'HTTP/1.1 200 OK',
`Content-Length: ${frameBody.length}`,
'Connection: close',
'',
'',
].join('\r\n');
return Buffer.concat([Buffer.from(headers, 'ascii'), frameBody]);
}
// FakeSocket 模拟 net.Socket 的最小子集。highway-client 用到:
// - 'data' / 'error' / 'close' 事件
// - .write(data, cb) cb 会被 socketWrite 等待
// - .destroy()
// - .setTimeout / .once / .removeListener (继承自 EventEmitter)
class FakeSocket extends EventEmitter {
destroyed = false;
// 每个 POST = 2 次 write(HTTP header + body)。第二次 write 落地后
// 异步回放响应并立刻 close —— 复现 QQ highway 真实行为:响应一发完
// 就 FIN,旧实现的下一次 POST 必然撞上已关闭的 socket。
private writeCount = 0;
private response: Buffer;
constructor(response: Buffer) {
super();
this.response = response;
}
setTimeout(_ms: number) { /* no-op */ }
write(_data: unknown, cb?: (err?: Error) => void): boolean {
this.writeCount += 1;
if (this.writeCount === 2) {
setImmediate(() => {
this.emit('data', this.response);
this.emit('close');
});
}
if (cb) cb();
return true;
}
destroy() {
this.destroyed = true;
}
}
// vitest 把 vi.mock 工厂 hoist 到文件顶部,所以工厂里不能引用普通的
// 顶层 const —— 那会触发 "Cannot access X before initialization"。
// 用 vi.hoisted 让这两个值跟着 mock 一起被 hoist。
const { createdSockets, createConnectionMock } = vi.hoisted(() => ({
createdSockets: [] as FakeSocket[],
createConnectionMock: vi.fn(),
}));
vi.mock('net', () => ({
default: { createConnection: createConnectionMock },
createConnection: createConnectionMock,
}));
import { uploadHighwayHttp, type HighwaySession } from '@snowluma/protocol/highway';
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
function makeBridge(): BridgeContext {
return {
identity: { uin: '10001' } as unknown,
} as unknown as BridgeContext;
}
function makeSession(): HighwaySession {
return {
sigSession: new Uint8Array([0xAA]),
sessionKey: new Uint8Array([0xBB]),
host: '127.0.0.1',
port: 80,
};
}
describe('uploadHighwayHttp connection lifecycle', () => {
beforeEach(() => {
createdSockets.length = 0;
createConnectionMock.mockReset();
createConnectionMock.mockImplementation((_opts: unknown, listener?: () => void) => {
const sock = new FakeSocket(buildHttpResponse(buildEmptyHighwayResponseFrame()));
createdSockets.push(sock);
// net.createConnection 在握手成功后调用 listener。同步触发即可,
// tcpConnect 的 Promise 会立刻 resolve。
if (listener) setImmediate(listener);
return sock as unknown as ReturnType<typeof createConnectionMock>;
});
});
afterEach(() => {
vi.restoreAllMocks();
});
it('uses a single TCP connection for a sub-block payload', async () => {
// 0.5 MiB → 1 chunk。覆盖 PTT / 小图的常见场景。
const bytes = new Uint8Array(512 * 1024);
await uploadHighwayHttp(
makeBridge(), makeSession(), 1003, bytes, new Uint8Array(16), new Uint8Array(0),
);
expect(createConnectionMock).toHaveBeenCalledTimes(1);
expect(createdSockets[0]!.destroyed).toBe(true);
});
it('uses a fresh TCP connection per chunk for multi-block payloads', async () => {
// 1.5 MiB → ceil(1.5) = 2 chunks。这正是用户上报的 1.19 MB 图片
// 触发的代码路径:旧实现复用 socket 时第二次 POST 撞上 keep-alive
// 关闭,新实现必须为每个 chunk 各开一个 socket。
const bytes = new Uint8Array(Math.floor(1.5 * HIGHWAY_BLOCK_SIZE));
await uploadHighwayHttp(
makeBridge(), makeSession(), 1003, bytes, new Uint8Array(16), new Uint8Array(0),
);
expect(createConnectionMock).toHaveBeenCalledTimes(2);
expect(createdSockets).toHaveLength(2);
for (const sock of createdSockets) {
expect(sock.destroyed).toBe(true);
}
});
it('opens N connections for N chunks (3 chunks here)', async () => {
const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE));
await uploadHighwayHttp(
makeBridge(), makeSession(), 1004, bytes, new Uint8Array(16), new Uint8Array(0),
);
expect(createConnectionMock).toHaveBeenCalledTimes(3);
});
});

View File

@@ -1,10 +1,10 @@
import { defineConfig, PluginOption, UserConfig } from 'vite';
import { fileURLToPath } from 'url';
import fs from 'fs';
import path from 'path';
import { builtinModules } from 'module';
import cp from 'vite-plugin-cp';
import protobufVitePlugin from '@snowluma/proton/vite';
import fs from 'fs';
import { builtinModules } from 'module';
import path from 'path';
import { fileURLToPath } from 'url';
import { defineConfig, PluginOption, UserConfig } from 'vite';
import cp from 'vite-plugin-cp';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '..', '..');
@@ -20,12 +20,16 @@ const rootPkg = JSON.parse(
// vite-plugin-cp consumes globs through globby; on Windows we must use POSIX-style separators.
const toPosix = (p: string) => p.replace(/\\/g, '/');
// `@snowluma/websocket` and `@snowluma/sqlite` are bundled — they're
// in-tree TS workspace wrappers that route their native `.node`
// addons through `dist/native/`. Only Node builtins stay external;
// the actual `better-sqlite3` JS wrapper is pulled in via the
// `@snowluma/sqlite` re-export and bundled into `index.mjs`.
const external: string[] = [];
// `@snowluma/websocket` is bundled — it's an
// in-tree TS workspace wrapper that routes its native `.node`
// addon through `dist/native/`. Only Node builtins stay external.
//
// `node:sqlite` is an experimental builtin that Node 22.x lines don't
// list in `builtinModules`, so the `nodeModules` sweep below misses it.
// Externalise it explicitly — otherwise Vite bundles it and swaps in a
// browser shell, crashing the hook with `DatabaseSync is not a
// constructor` (the bug PR #68 set out to fix).
const external: string[] = ['node:sqlite', 'sqlite'];
const nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`)].flat();
@@ -46,20 +50,8 @@ const runtimeDistFiles = ['package.json',
// Native binaries shipped for the selected target:
// * `snowluma-*.{dll,node,so}` – NTQQ hook (Windows + Linux).
// * `websocket-*.node` – RFC 6455 framing/mask addon (all platforms).
// * `better-sqlite3-v<abi>-*.node` – SQLite native binding consumed
// by @snowluma/sqlite. Two ABIs
// vendored side-by-side
// (v127 = Node 22 LTS, v137 =
// Node 24) so the runtime can
// pick whichever matches the
// host's `process.versions.modules`.
// Vendored via
// `tools/fetch-sqlite-prebuilts.mjs`
// from WiseLibs's prebuild releases.
const SQLITE_ABIS = ['v127', 'v137'];
const nativeFiles = [
`websocket-${targetTriple}.node`,
...SQLITE_ABIS.map((abi) => `better-sqlite3-${abi}-${targetTriple}.node`),
...(targetPlatform === 'win32'
? [`snowluma-${targetTriple}.dll`, `snowluma-${targetTriple}.node`]
: []),

1
packages/mcp/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
dist/

113
packages/mcp/README.md Normal file
View File

@@ -0,0 +1,113 @@
# @snowluma/mcp
An [MCP](https://modelcontextprotocol.io) server for the **SnowLuma OneBot action
catalog**. It runs in two modes from one binary:
- **docs** (default) — read-only: every action's docs, parameters, cross-field
constraints, and a ready-to-use **JSON Schema**, so an LLM can answer "what
params does `set_group_ban` take?" without holding the whole catalog in context.
- **execution** (opt-in) — when pointed at a running OneBot HTTP endpoint, the LLM
can also *call* actions: read-only ones freely, write ones behind a gate.
## Docs only (default)
Add to your MCP client (Claude Desktop, Cline, …) — no endpoint, no execution:
```json
{
"mcpServers": {
"snowluma": { "command": "npx", "args": ["-y", "@snowluma/mcp"] }
}
}
```
### Docs tools
- `list_actions({ category? })` — lightweight index (name / category / summary / aliases / `readOnly`).
- `get_action({ name })` — full doc for one action incl. `inputSchema` and `readOnly` (accepts aliases).
- `search_actions({ query })` — fuzzy match over name / summary / aliases.
- `list_categories()` — categories and their action counts.
Also exposes the whole catalog as a resource: `snowluma://onebot/actions`.
## Execution (opt-in)
Point the server at a running SnowLuma instance's **OneBot HTTP endpoint** (the
`httpServer` network adapter) and it gains two execution tools:
- `query_action({ action, params? })` — calls a **read-only** action (e.g. `get_*`,
`can_*`) and returns the full OneBot response. Annotated `readOnlyHint`. Refuses
write actions (points you to `invoke_action`).
- `invoke_action({ action, params? })` — calls **any known** action, including ones
with side effects (send a message, change a group, …). Annotated `destructiveHint`
+ `openWorldHint`. **Only available in write mode.**
Both pass the OneBot envelope through verbatim — a logical failure (`retcode≠0`)
comes back as data with its `wording`; only a transport failure is an error.
### Configuration (env)
| Variable | Meaning |
| --- | --- |
| `SNOWLUMA_MCP_ENDPOINT` | OneBot HTTP endpoint, e.g. `http://127.0.0.1:3000/`. **Absent → docs-only** (execution tools hidden). |
| `SNOWLUMA_MCP_TOKEN` | Access token (sent as `Authorization: Bearer …`), if the endpoint requires one. |
| `SNOWLUMA_MCP_TIMEOUT_MS` | Per-request timeout (default `30000`). |
| `SNOWLUMA_MCP_MODE` | `docs` \| `read` \| `write`. Default: `read` when an endpoint is set, else `docs`. |
**Read mode** — the LLM can query read-only actions, but cannot perform any write:
```json
{
"mcpServers": {
"snowluma": {
"command": "npx",
"args": ["-y", "@snowluma/mcp"],
"env": {
"SNOWLUMA_MCP_ENDPOINT": "http://127.0.0.1:3000/",
"SNOWLUMA_MCP_TOKEN": "your-access-token"
}
}
}
}
```
**Write mode** — also enables `invoke_action` (the bot can send messages, manage
groups, etc.). Enable deliberately:
```json
{
"mcpServers": {
"snowluma": {
"command": "npx",
"args": ["-y", "@snowluma/mcp"],
"env": {
"SNOWLUMA_MCP_ENDPOINT": "http://127.0.0.1:3000/",
"SNOWLUMA_MCP_TOKEN": "your-access-token",
"SNOWLUMA_MCP_MODE": "write"
}
}
}
}
```
### Safety model
- **Read/write is classified per action** in the source specs (by what the action
actually does, not its name) and baked into the catalog. The default is *write*:
an action is callable via `query_action` **only** if it is explicitly read-only.
- **The mode gate is enforced on every call**, not just by hiding tools — calling
`invoke_action` outside write mode is refused even if a client sends it directly.
- **Unknown actions are rejected** by both tools (only catalog actions are callable),
so typos and non-catalog internal actions can't be driven.
- A well-behaved client can auto-approve `query_action` (read-only) and prompt for
`invoke_action` (destructive) using the MCP tool annotations.
## How it stays in sync
The catalog — including each action's `readOnly` flag — is a **build-time snapshot**
generated from `@snowluma/onebot`'s live action specs (`collectActionDocs()`) on
every build, so it auto-tracks action add/remove and read/write reclassification.
The snapshot is pinned to the SnowLuma version it was built from; a new SnowLuma
release republishes a fresh catalog.
This package is generated; do not hand-edit `src/generated/catalog.ts`.

58
packages/mcp/package.json Normal file
View File

@@ -0,0 +1,58 @@
{
"name": "@snowluma/mcp",
"version": "1.9.7",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",
"url": "git+https://github.com/SnowLuma/SnowLuma.git",
"directory": "packages/mcp"
},
"homepage": "https://github.com/SnowLuma/SnowLuma#readme",
"bugs": {
"url": "https://github.com/SnowLuma/SnowLuma/issues"
},
"type": "module",
"bin": {
"snowluma-mcp": "./dist/server.js"
},
"main": "./dist/server.js",
"types": "./dist/server.d.ts",
"files": [
"dist",
"README.md"
],
"scripts": {
"clean": "node -e \"const fs=require('node:fs');fs.rmSync('dist',{recursive:true,force:true})\"",
"gen": "vitest run scripts/gen-catalog.test.ts",
"prebuild": "pnpm run clean && pnpm run gen",
"build": "tsc -p tsconfig.json",
"prepack": "pnpm run build",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"start": "node dist/server.js"
},
"keywords": [
"mcp",
"model-context-protocol",
"onebot",
"snowluma",
"qq"
],
"dependencies": {
"@modelcontextprotocol/sdk": "^1.0.0"
},
"devDependencies": {
"@snowluma/onebot": "workspace:*",
"@snowluma/proton": "workspace:*",
"@types/node": "^24.12.2",
"typescript": "catalog:",
"vite": "catalog:",
"vitest": "^4.1.4"
},
"engines": {
"node": ">=22"
},
"publishConfig": {
"access": "public"
}
}

View File

@@ -0,0 +1,32 @@
// Catalog generator. Runs under vitest (so @snowluma/onebot/action-docs resolves
// via the proton plugin, exactly as onebot's own tests do) and writes a build-time
// snapshot of the OneBot action catalog into src/generated/catalog.ts.
//
// This is the whole "auto-track Action 增减" mechanic: the snapshot is regenerated
// from the live specs on every build, so it can never describe a stale action set.
import { mkdirSync, writeFileSync } from 'node:fs';
import { it, expect } from 'vitest';
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
it('generates src/generated/catalog.ts from the live action specs', () => {
const actions = collectActionDocs();
const categories = collectCategories();
expect(actions.length).toBeGreaterThan(100);
// every action must carry a composed input schema (the MCP's payoff)
for (const a of actions) {
expect(a.inputSchema).toBeTypeOf('object');
expect(a.name).toBeTruthy();
}
const body =
'// GENERATED by scripts/gen-catalog.test.ts — do not edit. Run `pnpm gen`.\n' +
'/* eslint-disable */\n' +
"import type { CatalogAction, CatalogCategory } from '../types.js';\n\n" +
`export const ACTIONS: CatalogAction[] = ${JSON.stringify(actions, null, 2)};\n\n` +
`export const CATEGORIES: CatalogCategory[] = ${JSON.stringify(categories, null, 2)};\n`;
const dir = new URL('../src/generated/', import.meta.url);
mkdirSync(dir, { recursive: true });
writeFileSync(new URL('../src/generated/catalog.ts', import.meta.url), body);
});

View File

@@ -0,0 +1,69 @@
// Thin HTTP bridge to a running OneBot instance.
//
// The OneBot v11 HTTP action protocol is trivial — POST `{ action, params }` to
// the endpoint, read back the JSON envelope — so the MCP talks to it directly
// with `fetch`. We deliberately do NOT depend on @snowluma/sdk here: its
// published dist is bundler-targeted ESM (extensionless relative imports) that
// native `node` cannot resolve without a bundler, and this package is a plain
// `tsc`-built stdio bin. The wire shape — not a shared client type — is the seam
// (ADR-0005); tests inject a fake `ActionClient` (or a fake `fetch`).
const DEFAULT_TIMEOUT_MS = 30_000;
/** OneBot v11 response envelope, passed through to the LLM verbatim. */
export interface OneBotEnvelope {
status: string;
retcode: number;
data?: unknown;
message?: string;
wording?: string;
echo?: unknown;
[k: string]: unknown;
}
export interface ActionClient {
/** Send one OneBot action; resolves the full envelope (even on retcode≠0),
* rejects only on transport-level failure (timeout / connection / bad body). */
call(action: string, params: Record<string, unknown>): Promise<OneBotEnvelope>;
}
export interface HttpClientOptions {
/** OneBot HTTP endpoint, e.g. http://127.0.0.1:3000/. */
endpoint: string;
accessToken?: string;
timeoutMs?: number;
/** Injectable fetch for tests; defaults to the global fetch. */
fetch?: typeof fetch;
}
export function makeHttpClient(opts: HttpClientOptions): ActionClient {
const fetchImpl = opts.fetch ?? globalThis.fetch;
const timeoutMs = opts.timeoutMs && opts.timeoutMs > 0 ? opts.timeoutMs : DEFAULT_TIMEOUT_MS;
const headers: Record<string, string> = {
'Content-Type': 'application/json',
Accept: 'application/json',
};
if (opts.accessToken) headers.Authorization = `Bearer ${opts.accessToken}`;
return {
async call(action, params) {
const res = await fetchImpl(opts.endpoint, {
method: 'POST',
headers,
body: JSON.stringify({ action, params }),
signal: AbortSignal.timeout(timeoutMs),
});
const text = await res.text();
let parsed: unknown;
try {
parsed = text ? JSON.parse(text) : null;
} catch {
throw new Error(`OneBot returned non-JSON (HTTP ${res.status})`);
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new Error(`OneBot returned an unexpected response (HTTP ${res.status})`);
}
return parsed as OneBotEnvelope;
},
};
}

File diff suppressed because it is too large Load Diff

106
packages/mcp/src/server.ts Normal file
View File

@@ -0,0 +1,106 @@
#!/usr/bin/env node
// @snowluma/mcp — an MCP server for the SnowLuma OneBot action catalog.
//
// Two modes in one binary:
// • docs (default, no endpoint): read-only catalog tools (list/get/search/
// categories) + a catalog resource. Zero contact with any live instance.
// • read / write (when SNOWLUMA_MCP_ENDPOINT is set): the catalog tools PLUS
// execution — query_action (read-only actions) and, in write mode,
// invoke_action (any known action) — proxied to a running OneBot instance
// over HTTP.
//
// Env:
// SNOWLUMA_MCP_ENDPOINT OneBot HTTP endpoint (e.g. http://127.0.0.1:3000/).
// Absent → docs-only (execution tools hidden).
// SNOWLUMA_MCP_TOKEN access token (Bearer) for the endpoint.
// SNOWLUMA_MCP_TIMEOUT_MS per-request timeout (default SDK 30s).
// SNOWLUMA_MCP_MODE docs | read | write. Default: read when an
// endpoint is set, else docs.
//
// NOTE: stdout is the MCP protocol channel — all diagnostics go to stderr.
import { readFileSync } from 'node:fs';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
CallToolRequestSchema,
ListResourcesRequestSchema,
ListToolsRequestSchema,
ReadResourceRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import { ACTIONS, CATEGORIES } from './generated/catalog.js';
import { makeHttpClient, type ActionClient } from './client.js';
import { callTool, computeTools, type Mode } from './tools.js';
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string };
const VERSION = pkg.version;
const RESOURCE_URI = 'snowluma://onebot/actions';
// ── resolve mode + client from the environment ────────────────────────────
function resolveRuntime(): { mode: Mode; client?: ActionClient } {
const endpoint = process.env.SNOWLUMA_MCP_ENDPOINT?.trim();
const token = process.env.SNOWLUMA_MCP_TOKEN?.trim() || undefined;
const timeoutRaw = Number(process.env.SNOWLUMA_MCP_TIMEOUT_MS);
const timeoutMs = Number.isFinite(timeoutRaw) && timeoutRaw > 0 ? timeoutRaw : undefined;
const requested = process.env.SNOWLUMA_MCP_MODE?.trim().toLowerCase();
const validRequest = requested === 'docs' || requested === 'read' || requested === 'write' ? requested : undefined;
if (!endpoint) {
if (validRequest && validRequest !== 'docs') {
console.error(`[snowluma-mcp] SNOWLUMA_MCP_MODE=${validRequest} ignored: no SNOWLUMA_MCP_ENDPOINT set — docs-only.`);
}
return { mode: 'docs' };
}
const mode: Mode = validRequest ?? 'read';
if (mode === 'docs') {
// Endpoint set but operator explicitly wants docs-only — honor it.
return { mode: 'docs' };
}
const client = makeHttpClient({ endpoint, accessToken: token, timeoutMs });
return { mode, client };
}
const { mode, client } = resolveRuntime();
const server = new Server(
{ name: 'snowluma-mcp', version: VERSION },
{ capabilities: { tools: {}, resources: {} } },
);
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: computeTools(mode) }));
server.setRequestHandler(CallToolRequestSchema, async (req) => {
const args = (req.params.arguments ?? {}) as Record<string, unknown>;
return callTool(req.params.name, args, { mode, client });
});
server.setRequestHandler(ListResourcesRequestSchema, async () => ({
resources: [
{
uri: RESOURCE_URI,
name: 'SnowLuma OneBot action catalog',
mimeType: 'application/json',
description: `SnowLuma v${VERSION} 的 ${ACTIONS.length} 个 OneBot action 完整目录(文档 + JSON Schema)。`,
},
],
}));
server.setRequestHandler(ReadResourceRequestSchema, async (req) => {
if (req.params.uri !== RESOURCE_URI) throw new Error(`unknown resource: ${req.params.uri}`);
return {
contents: [
{
uri: RESOURCE_URI,
mimeType: 'application/json',
text: JSON.stringify({ version: VERSION, categories: CATEGORIES, actions: ACTIONS }, null, 2),
},
],
};
});
const transport = new StdioServerTransport();
await server.connect(transport);
const where = client ? ` → ${process.env.SNOWLUMA_MCP_ENDPOINT?.trim()}` : '';
console.error(`[snowluma-mcp] v${VERSION} ready — ${ACTIONS.length} actions, ${CATEGORIES.length} categories, mode=${mode}${where}`);

182
packages/mcp/src/tools.ts Normal file
View File

@@ -0,0 +1,182 @@
// Tool surface for the MCP — kept free of any stdio / transport / env concerns
// so it is directly unit-testable. `server.ts` reads the environment, builds a
// client, and wires `computeTools` / `callTool` into the MCP request handlers.
//
// Two execution tools partition the action space by side-effect:
// • query_action — read-only actions only (readOnlyHint)
// • invoke_action — any known action (destructiveHint, write mode)
// Visibility is gated by `mode`, and `callTool` RE-checks every permission
// (defense in depth: a client may call a tool that was never listed).
import type { CallToolResult, Tool } from '@modelcontextprotocol/sdk/types.js';
import { ACTIONS, CATEGORIES } from './generated/catalog.js';
import type { CatalogAction } from './types.js';
import type { ActionClient } from './client.js';
export type Mode = 'docs' | 'read' | 'write';
// name + every alias → action, so lookups accept aliases too.
const byName = new Map<string, CatalogAction>();
for (const a of ACTIONS) {
for (const n of [a.name, ...a.aliases]) byName.set(n, a);
}
/** Lightweight index entry (keeps list/search payloads small). */
function lite(a: CatalogAction) {
return { name: a.name, category: a.category, summary: a.summary, aliases: a.aliases, readOnly: a.readOnly };
}
const DOCS_TOOLS: Tool[] = [
{
name: 'list_actions',
description: '列出所有 OneBot action(可按 category 过滤)。返回轻量索引(名称/分类/摘要/别名/是否只读)。',
inputSchema: {
type: 'object',
properties: { category: { type: 'string', description: '按分类过滤,如 群管理 / 消息 / 好友' } },
additionalProperties: false,
},
annotations: { readOnlyHint: true, openWorldHint: false },
},
{
name: 'get_action',
description: '获取某个 OneBot action 的完整文档:摘要、参数表、跨字段约束、返回、是否只读,以及可直接用于构造调用的参数 JSON Schema(inputSchema)。',
inputSchema: {
type: 'object',
properties: { name: { type: 'string', description: 'action 名(接受别名)' } },
required: ['name'],
additionalProperties: false,
},
annotations: { readOnlyHint: true, openWorldHint: false },
},
{
name: 'search_actions',
description: '按关键字模糊搜索 action(匹配名称 / 摘要 / 别名)。返回轻量索引。',
inputSchema: {
type: 'object',
properties: { query: { type: 'string', description: '关键字' } },
required: ['query'],
additionalProperties: false,
},
annotations: { readOnlyHint: true, openWorldHint: false },
},
{
name: 'list_categories',
description: '列出所有分类及其 action 数量。',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
annotations: { readOnlyHint: true, openWorldHint: false },
},
];
const EXEC_INPUT_SCHEMA = {
type: 'object' as const,
properties: {
action: { type: 'string', description: 'action 名(接受别名)。先用 get_action 查它的参数 inputSchema。' },
params: { type: 'object', description: '该 action 的参数对象', additionalProperties: true },
},
required: ['action'],
additionalProperties: false,
};
function queryTool(): Tool {
return {
name: 'query_action',
description: '调用一个【只读】OneBot action(如 get_*/can_*)并返回完整响应。仅接受只读 action;写操作请用 invoke_action。',
inputSchema: EXEC_INPUT_SCHEMA,
annotations: { readOnlyHint: true, openWorldHint: true },
};
}
function invokeTool(): Tool {
return {
name: 'invoke_action',
description: '调用一个 OneBot action(可产生副作用:发消息、改群、改资料等)并返回完整响应。仅在写模式可用。',
inputSchema: EXEC_INPUT_SCHEMA,
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
};
}
/** Tools visible for a given mode: docs always; +query in read/write; +invoke in write. */
export function computeTools(mode: Mode): Tool[] {
const tools: Tool[] = [...DOCS_TOOLS];
if (mode === 'read' || mode === 'write') tools.push(queryTool());
if (mode === 'write') tools.push(invokeTool());
return tools;
}
export type ToolResult = CallToolResult;
function asText(data: unknown): ToolResult {
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] };
}
function asError(message: string): ToolResult {
return { content: [{ type: 'text', text: message }], isError: true };
}
export interface CallCtx {
mode: Mode;
client?: ActionClient;
}
export async function callTool(name: string, args: Record<string, unknown>, ctx: CallCtx): Promise<ToolResult> {
switch (name) {
case 'list_actions': {
const category = typeof args.category === 'string' ? args.category : undefined;
const list = ACTIONS.filter((a) => !category || a.category === category).map(lite);
return asText({ count: list.length, actions: list });
}
case 'get_action': {
const q = typeof args.name === 'string' ? args.name : '';
const action = byName.get(q);
if (!action) return asError(`未找到 action: ${JSON.stringify(q)}。用 list_actions / search_actions 查可用项。`);
return asText(action);
}
case 'search_actions': {
const q = (typeof args.query === 'string' ? args.query : '').toLowerCase();
const list = ACTIONS.filter(
(a) =>
a.name.toLowerCase().includes(q) ||
(a.summary ?? '').toLowerCase().includes(q) ||
a.aliases.some((al) => al.toLowerCase().includes(q)),
).map(lite);
return asText({ count: list.length, actions: list });
}
case 'list_categories':
return asText(CATEGORIES);
case 'query_action':
return execute(args, ctx, 'read');
case 'invoke_action':
return execute(args, ctx, 'write');
default:
return asError(`未知工具: ${name}`);
}
}
/** Shared execution path for query_action (read) / invoke_action (write).
* Re-checks mode + readOnly routing regardless of which tools were listed. */
async function execute(args: Record<string, unknown>, ctx: CallCtx, kind: 'read' | 'write'): Promise<ToolResult> {
if (kind === 'write' && ctx.mode !== 'write') {
return asError('写操作未启用:需设置 SNOWLUMA_MCP_MODE=write。');
}
if (kind === 'read' && ctx.mode !== 'read' && ctx.mode !== 'write') {
return asError('执行未启用:需配置 SNOWLUMA_MCP_ENDPOINT。');
}
if (!ctx.client) return asError('未配置 OneBot 端点(SNOWLUMA_MCP_ENDPOINT),无法执行。');
const action = typeof args.action === 'string' ? args.action : '';
const cat = byName.get(action);
if (!cat) return asError(`未知 action: ${JSON.stringify(action)}。用 list_actions / search_actions 查可用项。`);
if (kind === 'read' && !cat.readOnly) {
return asError(`${action} 是写操作,不能用 query_action;请用 invoke_action(需 SNOWLUMA_MCP_MODE=write)。`);
}
const params =
args.params && typeof args.params === 'object' && !Array.isArray(args.params)
? (args.params as Record<string, unknown>)
: {};
try {
const envelope = await ctx.client.call(action, params);
return asText(envelope);
} catch (err) {
return asError(`调用失败: ${err instanceof Error ? err.message : String(err)}`);
}
}

38
packages/mcp/src/types.ts Normal file
View File

@@ -0,0 +1,38 @@
// The MCP's own view of the OneBot action catalog. Mirrors @snowluma/onebot's
// ActionDoc, but is defined HERE so the published package does not couple to
// onebot's internals — the generated `catalog.ts` (a build-time snapshot) is the
// only contract (ADR-0005: the wire/data shape is the seam, not a shared type).
export interface CatalogParam {
name: string;
/** Display type ('uint' | 'int' | 'messageId' | 'string' | 'bool' | 'message' | 'enum' | 'X[]' | 'raw'). */
type: string;
required: boolean;
default?: unknown;
desc?: string;
values?: ReadonlyArray<string | number>;
/** JSON Schema fragment for this single field. */
schema?: Record<string, unknown>;
}
export interface CatalogAction {
name: string;
aliases: string[];
category?: string;
summary?: string;
returns?: string;
/** True only for pure data-fetch actions (no side effects). Drives the
* read/write tool routing: read-only → query_action, else → invoke_action.
* Classified at the source spec by what the action's `run` actually does. */
readOnly: boolean;
params: CatalogParam[];
/** Cross-field invariants, e.g. "exactly one of: message_id | (group_id+user_id)". */
invariants: string[];
/** Composed JSON Schema for the whole params object. */
inputSchema: Record<string, unknown>;
}
export interface CatalogCategory {
category: string;
count: number;
}

View File

@@ -0,0 +1,39 @@
import { describe, it, expect } from 'vitest';
import { makeHttpClient } from '../src/client';
// Verifies the HTTP bridge: a OneBot action becomes a POST of `{ action, params }`
// to the endpoint (with Bearer auth), and the JSON envelope comes back verbatim.
// A fake fetch stands in for the network.
describe('makeHttpClient — OneBot HTTP wiring', () => {
it('POSTs {action, params} to the endpoint and returns the parsed envelope', async () => {
const calls: Array<{ url: string; body: any; auth?: string }> = [];
const fakeFetch = (async (url: unknown, init: any) => {
calls.push({
url: String(url),
body: JSON.parse(init.body as string),
auth: (init.headers as Record<string, string>)?.Authorization,
});
return new Response(JSON.stringify({ status: 'ok', retcode: 0, data: { ok: true } }), {
status: 200,
headers: { 'content-type': 'application/json' },
});
}) as unknown as typeof fetch;
const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', accessToken: 'tok', fetch: fakeFetch });
const env = await client.call('get_status', { x: 1 });
expect(env.status).toBe('ok');
expect(env.retcode).toBe(0);
expect(calls).toHaveLength(1);
expect(calls[0].url).toBe('http://127.0.0.1:9999/');
expect(calls[0].body.action).toBe('get_status');
expect(calls[0].body.params).toEqual({ x: 1 });
expect(calls[0].auth).toBe('Bearer tok');
});
it('propagates a transport failure as a rejection (so the tool layer can map it)', async () => {
const fakeFetch = (async () => { throw new Error('ECONNREFUSED'); }) as unknown as typeof fetch;
const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch });
await expect(client.call('get_status', {})).rejects.toThrow();
});
});

View File

@@ -0,0 +1,138 @@
import { describe, it, expect } from 'vitest';
import { computeTools, callTool } from '../src/tools';
import type { ActionClient, OneBotEnvelope } from '../src/client';
type Res = Awaited<ReturnType<typeof callTool>>;
function text(res: Res): string {
const block = res.content?.[0];
return block && block.type === 'text' ? block.text : '';
}
function parsed(res: Res): any {
return JSON.parse(text(res));
}
/** A fake ActionClient — no transport. Records the last call and returns a
* canned envelope (overridable per test). */
function fakeClient(impl?: (action: string, params: Record<string, unknown>) => OneBotEnvelope): ActionClient {
return {
call: async (action, params) => impl?.(action, params) ?? { status: 'ok', retcode: 0, data: { action, params } },
};
}
describe('computeTools — mode gating', () => {
it('docs mode exposes only the 4 catalog tools', () => {
expect(computeTools('docs').map((t) => t.name)).toEqual([
'list_actions', 'get_action', 'search_actions', 'list_categories',
]);
});
it('read mode adds query_action only (no invoke_action)', () => {
const names = computeTools('read').map((t) => t.name);
expect(names).toContain('query_action');
expect(names).not.toContain('invoke_action');
});
it('write mode adds both query_action and invoke_action', () => {
const names = computeTools('write').map((t) => t.name);
expect(names).toContain('query_action');
expect(names).toContain('invoke_action');
});
it('annotations are honest: query=readOnly, invoke=destructive', () => {
const q = computeTools('write').find((t) => t.name === 'query_action');
const inv = computeTools('write').find((t) => t.name === 'invoke_action');
expect(q?.annotations?.readOnlyHint).toBe(true);
expect(inv?.annotations?.readOnlyHint).toBe(false);
expect(inv?.annotations?.destructiveHint).toBe(true);
});
});
describe('callTool — docs tools (no client needed)', () => {
it('list_actions returns entries that carry readOnly', async () => {
const data = parsed(await callTool('list_actions', {}, { mode: 'docs' }));
expect(data.count).toBeGreaterThan(100);
expect(typeof data.actions[0].readOnly).toBe('boolean');
});
it('get_action resolves a known read-only action', async () => {
const a = parsed(await callTool('get_action', { name: 'get_status' }, { mode: 'docs' }));
expect(a.name).toBe('get_status');
expect(a.readOnly).toBe(true);
});
it('get_action on a write action reports readOnly=false', async () => {
expect(parsed(await callTool('get_action', { name: 'send_group_msg' }, { mode: 'docs' })).readOnly).toBe(false);
});
it('get_action accepts an alias', async () => {
// nc_get_rkey is an alias of get_rkey (read-only).
const a = parsed(await callTool('get_action', { name: 'nc_get_rkey' }, { mode: 'docs' }));
expect(a.name).toBe('get_rkey');
});
});
describe('callTool — query_action (read)', () => {
it('executes a read-only action and passes the envelope through', async () => {
const res = await callTool('query_action', { action: 'get_status', params: {} }, { mode: 'read', client: fakeClient() });
expect(res.isError).toBeFalsy();
expect(parsed(res).retcode).toBe(0);
});
it('refuses a write action and points to invoke_action', async () => {
const res = await callTool('query_action', { action: 'send_group_msg', params: {} }, { mode: 'read', client: fakeClient() });
expect(res.isError).toBe(true);
expect(text(res)).toContain('invoke_action');
});
it('refuses an unknown action', async () => {
const res = await callTool('query_action', { action: 'no_such_action' }, { mode: 'read', client: fakeClient() });
expect(res.isError).toBe(true);
expect(text(res)).toContain('未知 action');
});
it('is blocked in docs mode even when called directly (defense in depth)', async () => {
const res = await callTool('query_action', { action: 'get_status' }, { mode: 'docs' });
expect(res.isError).toBe(true);
});
it('errors clearly when no client is wired', async () => {
const res = await callTool('query_action', { action: 'get_status' }, { mode: 'read' });
expect(res.isError).toBe(true);
expect(text(res)).toContain('未配置');
});
});
describe('callTool — invoke_action (write)', () => {
it('executes a write action in write mode and forwards action+params', async () => {
let seen: { action: string; params: Record<string, unknown> } | null = null;
const client: ActionClient = {
call: async (action, params) => {
seen = { action, params };
return { status: 'ok', retcode: 0, data: { message_id: 42 } };
},
};
const res = await callTool('invoke_action', { action: 'send_group_msg', params: { group_id: 1, message: 'hi' } }, { mode: 'write', client });
expect(res.isError).toBeFalsy();
expect(seen!.action).toBe('send_group_msg');
expect(seen!.params).toEqual({ group_id: 1, message: 'hi' });
expect(parsed(res).data.message_id).toBe(42);
});
it('is blocked in read mode (write gate cannot be bypassed)', async () => {
const res = await callTool('invoke_action', { action: 'send_group_msg', params: {} }, { mode: 'read', client: fakeClient() });
expect(res.isError).toBe(true);
expect(text(res)).toContain('写操作未启用');
});
it('passes a retcode≠0 envelope through as data, NOT isError', async () => {
const client = fakeClient(() => ({ status: 'failed', retcode: 1404, message: 'not found', wording: '未找到' }));
const res = await callTool('invoke_action', { action: 'send_group_msg', params: {} }, { mode: 'write', client });
expect(res.isError).toBeFalsy();
expect(parsed(res).retcode).toBe(1404);
expect(parsed(res).wording).toBe('未找到');
});
it('maps a transport-level throw to isError', async () => {
const client: ActionClient = { call: async () => { throw new Error('connection refused'); } };
const res = await callTool('invoke_action', { action: 'send_group_msg', params: {} }, { mode: 'write', client });
expect(res.isError).toBe(true);
expect(text(res)).toContain('调用失败');
expect(text(res)).toContain('connection refused');
});
it('accepts a read-only action too (invoke is a superset)', async () => {
const res = await callTool('invoke_action', { action: 'get_status', params: {} }, { mode: 'write', client: fakeClient() });
expect(res.isError).toBeFalsy();
});
it('refuses an unknown action (typo safety)', async () => {
const res = await callTool('invoke_action', { action: 'frobnicate' }, { mode: 'write', client: fakeClient() });
expect(res.isError).toBe(true);
expect(text(res)).toContain('未知 action');
});
});

View File

@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"noEmit": false,
"types": ["node"]
},
"include": ["src/**/*"]
}

View File

@@ -0,0 +1,17 @@
// Vitest config — used only to RUN the catalog generator (scripts/gen-catalog.test.ts)
// in an environment where `@snowluma/onebot/action-docs` resolves. The proton
// plugin provides the same bare-specifier resolver @snowluma/onebot's own tests
// use, so importing the action specs works identically here.
import protobufVitePlugin from '@snowluma/proton/vite';
import { defineConfig } from 'vitest/config';
export default defineConfig({
plugins: [protobufVitePlugin()],
test: {
include: ['scripts/**/*.test.ts', 'tests/**/*.test.ts'],
environment: 'node',
env: {
SNOWLUMA_LOG_FILE: '0',
},
},
});

View File

@@ -1,6 +1,6 @@
{
"name": "@snowluma/onebot",
"version": "1.9.2",
"version": "1.9.7",
"private": true,
"type": "module",
"description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
@@ -11,6 +11,14 @@
"types": "./src/index.ts",
"default": "./src/index.ts"
},
"./action-kit": {
"types": "./src/action-kit.ts",
"default": "./src/action-kit.ts"
},
"./action-docs": {
"types": "./src/action-docs.ts",
"default": "./src/action-docs.ts"
},
"./manager": {
"types": "./src/manager.ts",
"default": "./src/manager.ts"
@@ -91,7 +99,6 @@
"@snowluma/proto-defs": "workspace:*",
"@snowluma/proton": "workspace:*",
"@snowluma/protocol": "workspace:*",
"@snowluma/sqlite": "workspace:*",
"@snowluma/websocket": "workspace:*"
},
"devDependencies": {

View File

@@ -0,0 +1,89 @@
// action-docs — self-generated OneBot API docs (D4).
//
// Walks `ActionSpec.describe()` over every declarative action and renders a
// structured doc list + a Markdown view. The metadata is carried on the same
// values that drive runtime validation, so docs cannot drift from behavior.
//
// Coverage note: the ~15 genuinely irregular actions in `actions/extended.ts`
// that remain on the legacy `h.registerAction(...)` path are NOT ActionSpecs
// and so do not appear here — that is the documented irregular tail.
//
// The serving SURFACE (WebUI panel / OpenAPI export / static markdown) is a
// deferred product decision; this module produces format-agnostic data plus a
// Markdown default. Point any renderer at `collectActionDocs()`.
import type { ActionDoc, ActionSpec, Field } from './action-kit';
import { actions as infoActions } from './actions/info';
import { actions as messageActions } from './actions/message';
import { actions as friendActions } from './actions/friend';
import { actions as groupInfoActions } from './actions/group-info';
import { actions as groupAdminActions } from './actions/group-admin';
import { actions as groupFileActions } from './actions/group-file';
import { actions as requestActions } from './actions/request';
import { actions as extendedActions } from './actions/extended';
import { actions as groupAlbumActions } from './actions/group-album';
type AnySpec = ActionSpec<Record<string, Field<unknown>>>;
// Source file = domain category. Each doc is tagged so the MCP / UI can group.
const GROUPS: ReadonlyArray<{ category: string; specs: readonly AnySpec[] }> = [
{ category: '信息', specs: infoActions },
{ category: '消息', specs: messageActions },
{ category: '好友', specs: friendActions },
{ category: '群信息', specs: groupInfoActions },
{ category: '群管理', specs: groupAdminActions },
{ category: '群文件', specs: groupFileActions },
{ category: '请求', specs: requestActions },
{ category: '扩展', specs: extendedActions },
{ category: '群相册', specs: groupAlbumActions },
];
/** Every declarative action's doc (with category), sorted by name. */
export function collectActionDocs(): ActionDoc[] {
return GROUPS
.flatMap(({ category, specs }) => specs.map((s) => ({ ...s.describe(), category })))
.sort((a, b) => a.name.localeCompare(b.name));
}
/** Distinct categories with action counts. */
export function collectCategories(): Array<{ category: string; count: number }> {
return GROUPS.map(({ category, specs }) => ({ category, count: specs.length }));
}
function paramRow(p: ActionDoc['params'][number]): string {
const type = p.values ? p.values.map((v) => JSON.stringify(v)).join(' \\| ') : p.type;
const required = p.required ? '✓' : '–';
const def = !p.required && p.default !== undefined ? `\`${JSON.stringify(p.default)}\`` : '';
return `| \`${p.name}\` | ${type} | ${required} | ${def} | ${p.desc ?? ''} |`;
}
function renderAction(doc: ActionDoc): string {
const lines: string[] = [];
const alias = doc.aliases.length ? ` _(别名: ${doc.aliases.map((a) => `\`${a}\``).join(', ')})_` : '';
const cat = doc.category ? ` · ${doc.category}` : '';
lines.push(`### \`${doc.name}\`${cat}${alias}`);
if (doc.summary) lines.push('', doc.summary);
if (doc.params.length) {
lines.push('', '| 参数 | 类型 | 必填 | 默认 | 说明 |', '| --- | --- | --- | --- | --- |');
for (const p of doc.params) lines.push(paramRow(p));
} else {
lines.push('', '_无参数_');
}
if (doc.invariants.length) lines.push('', `**约束:** ${doc.invariants.map((i) => `\`${i}\``).join(';')}`);
if (doc.returns) lines.push('', `**返回:** \`${doc.returns}\``);
return lines.join('\n');
}
/** Render the full Markdown doc. */
export function renderActionDocsMarkdown(docs: readonly ActionDoc[] = collectActionDocs()): string {
const header = [
'# OneBot Actions',
'',
'> 由 `packages/onebot/src/action-docs.ts` 从各 `ActionSpec.describe()` 自动生成,请勿手改。',
'> 仅覆盖声明式 action;`extended.ts` 中少量走 legacy `registerAction` 的不规则 action 不在此列。',
'',
`共 ${docs.length} 个声明式 action。`,
'',
];
return header.concat(docs.map(renderAction)).join('\n') + '\n';
}

View File

@@ -0,0 +1,483 @@
// action-kit — declarative OneBot Action definitions.
//
// One Action declares its param contract once (a record of `Field`s + optional
// cross-field `rules`) and a `run` handler. The kit owns param coercion +
// validation + the `BAD_REQUEST` shaping (naming the offending field) +
// doc metadata. The handler receives typed, already-validated params.
//
// Narrow seam (ADR-0006): `ApiHandler` keeps dispatch / try-catch / response
// wrapping. `defineAction(...).register(h, ctx)` ultimately registers a plain
// `(params) => Promise<ApiResponse>` via `ApiHandler.registerAction`, exactly
// like the legacy style — so old and new actions coexist during migration.
//
// Zero runtime npm deps (ADR-0004). Type inference via `InferParams` — no
// hand-written param interface. Param contract is intentionally a second
// definition from the SDK's client-side types (ADR-0005).
//
// Guard-rail (ADR-0007): the built-in coercers below are strict. Do NOT add a
// lenient `union`/`refine` escape that re-introduces the silent coercion this
// module exists to remove.
import { RETCODE, failedResponse } from './types';
import type { ApiResponse, JsonObject, JsonValue } from './types';
import type { ApiActionContext, ApiHandler } from './api-handler';
// ─────────────────────────── result currency ───────────────────────────
export type Ok<T> = { ok: true; value: T };
/** `field` is the offending param ('' for a cross-field rule). */
export type Err = { ok: false; field: string; reason: string };
export type CoerceResult<T> = Ok<T> | Err;
const ok = <T>(value: T): Ok<T> => ({ ok: true, value });
const err = (field: string, reason: string): Err => ({ ok: false, field, reason });
/** Only an absent key produces MISSING — this is what lets a present `0` /
* `''` / `false` be distinguished from "not provided". */
const MISSING = Symbol('missing');
type Raw = JsonValue | typeof MISSING;
// ─────────────────────────── Field (param coercer) ───────────────────────────
/** A JSON Schema fragment (loose). Each coercer emits one; `describe()` composes
* them into an action's `inputSchema` (consumed by docs / the MCP). */
export type JsonSchema = Record<string, unknown>;
export interface FieldDoc {
type: string;
required: boolean;
default?: JsonValue;
desc?: string;
values?: readonly (string | number)[];
/** JSON Schema fragment for this field's value (constraints only; presence
* and default are applied at the object level by `describe()`). */
schema?: JsonSchema;
}
export interface Field<T> {
readonly doc: FieldDoc;
/** Coerce the raw value at this field's key (MISSING when the key is absent). */
coerce(raw: Raw, field: string): CoerceResult<T>;
/** Absent ⇒ value is `undefined`; a present value still must coerce. */
optional(): Field<T | undefined>;
/** Absent ⇒ `value`; a present value still must coerce (so `"abc"` for a
* numeric field is an error, not a silent fallback). */
default(value: T): Field<T>;
describe(text: string): Field<T>;
/** Complete JSON Schema for this field's value (constraints + description +
* default). Object-level required-ness is handled by `describe()`. */
toJsonSchema(): JsonSchema;
}
/** Core coerces a PRESENT value (never MISSING). Presence policy is applied
* by the wrapping Field. */
type Core<T> = (raw: JsonValue, field: string) => CoerceResult<T>;
class FieldImpl<T> implements Field<T> {
constructor(
private readonly core: Core<T>,
readonly doc: FieldDoc,
) {}
coerce(raw: Raw, field: string): CoerceResult<T> {
if (raw === MISSING) {
if (this.doc.required) return err(field, 'is required');
return ok(this.doc.default as T); // default value, or undefined when optional
}
return this.core(raw, field);
}
optional(): Field<T | undefined> {
return new FieldImpl<T | undefined>(this.core as Core<T | undefined>, {
...this.doc,
required: false,
default: undefined,
});
}
default(value: T): Field<T> {
return new FieldImpl<T>(this.core, { ...this.doc, required: false, default: value as JsonValue });
}
describe(text: string): Field<T> {
return new FieldImpl<T>(this.core, { ...this.doc, desc: text });
}
toJsonSchema(): JsonSchema {
const out: JsonSchema = { ...(this.doc.schema ?? {}) };
if (this.doc.desc) out.description = this.doc.desc;
if (this.doc.default !== undefined) out.default = this.doc.default;
return out;
}
}
// ─────────────────────────── coercer vocabulary `f` ───────────────────────────
interface IntOpts { min?: number; max?: number; nonZero?: boolean }
/** Accept a number or numeric string, truncate to integer (matches the legacy
* `asNumber`), then apply bounds. Non-numeric / blank ⇒ Err. */
function intCore(typeName: string, opts: IntOpts): Core<number> {
return (raw, field) => {
let n: number;
if (typeof raw === 'number' && Number.isFinite(raw)) n = Math.trunc(raw);
else if (typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))) n = Math.trunc(Number(raw));
else return err(field, `expected ${typeName}`);
if (opts.nonZero && n === 0) return err(field, 'must not be 0');
if (opts.min !== undefined && n < opts.min) return err(field, `must be >= ${opts.min}`);
if (opts.max !== undefined && n > opts.max) return err(field, `must be <= ${opts.max}`);
return ok(n);
};
}
function intSchema(opts: IntOpts): JsonSchema {
const s: JsonSchema = { type: 'integer' };
if (opts.min !== undefined) s.minimum = opts.min;
if (opts.max !== undefined) s.maximum = opts.max;
if (opts.nonZero) s.not = { const: 0 };
return s;
}
interface StrOpts { allowEmpty?: boolean; maxLen?: number }
function strSchema(opts: StrOpts): JsonSchema {
const s: JsonSchema = { type: 'string' };
if (opts.allowEmpty === false) s.minLength = 1;
if (opts.maxLen !== undefined) s.maxLength = opts.maxLen;
return s;
}
function arrayField<E>(el: Field<E>, mustBeNonEmpty: boolean): Field<E[]> & { nonEmpty(): Field<E[]> } {
const core: Core<E[]> = (raw, field) => {
if (!Array.isArray(raw)) return err(field, 'expected an array');
const out: E[] = [];
for (let i = 0; i < raw.length; i++) {
const r = el.coerce(raw[i] as JsonValue, `${field}[${i}]`);
if (!r.ok) return r;
out.push(r.value);
}
if (mustBeNonEmpty && out.length === 0) return err(field, 'must not be empty');
return ok(out);
};
const base = new FieldImpl<E[]>(core, {
type: `${el.doc.type}[]`,
required: true,
schema: { type: 'array', items: el.toJsonSchema(), ...(mustBeNonEmpty ? { minItems: 1 } : {}) },
});
return Object.assign(base, { nonEmpty: () => arrayField(el, true) });
}
export const f = {
/** Positive integer (>0): group_id / user_id / message_id. */
uint(): Field<number> {
return new FieldImpl<number>(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true, schema: intSchema({ min: 1 }) });
},
/** Integer with optional bounds; allows 0 / negatives unless bounded.
* e.g. a duration where 0 is meaningful: `f.int({ min: 0 })`. */
int(opts: IntOpts = {}): Field<number> {
return new FieldImpl<number>(intCore('an integer', opts), { type: 'int', required: true, schema: intSchema(opts) });
},
/** OneBot message id: a non-zero integer. NEGATIVES ARE VALID (ids are a
* signed int32 hash) — do NOT use `uint()` for message_id. */
messageId(): Field<number> {
return new FieldImpl<number>(intCore('a message id', { nonZero: true }), { type: 'messageId', required: true, schema: intSchema({ nonZero: true }) });
},
/** Finite number (fractions allowed). */
number(): Field<number> {
return new FieldImpl<number>((raw, field) => {
if (typeof raw === 'number' && Number.isFinite(raw)) return ok(raw);
if (typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))) return ok(Number(raw));
return err(field, 'expected a number');
}, { type: 'number', required: true, schema: { type: 'number' } });
},
/** String. Numbers/booleans stringify (matches legacy `asString`). Empty
* allowed by default; `{ allowEmpty: false }` rejects ''. */
string(opts: StrOpts = {}): Field<string> {
return new FieldImpl<string>((raw, field) => {
let s: string;
if (typeof raw === 'string') s = raw;
else if (typeof raw === 'number' || typeof raw === 'boolean') s = String(raw);
else return err(field, 'expected a string');
if (opts.allowEmpty === false && s === '') return err(field, 'must not be empty');
if (opts.maxLen !== undefined && s.length > opts.maxLen) return err(field, `must be <= ${opts.maxLen} chars`);
return ok(s);
}, { type: 'string', required: true, schema: strSchema(opts) });
},
/** true/1/yes/on ⇒ true; false/0/no/off ⇒ false (matches legacy `asBoolean`). */
bool(): Field<boolean> {
return new FieldImpl<boolean>((raw, field) => {
if (typeof raw === 'boolean') return ok(raw);
if (typeof raw === 'number') return ok(raw !== 0);
if (typeof raw === 'string') {
const t = raw.trim().toLowerCase();
if (t === 'true' || t === '1' || t === 'yes' || t === 'on') return ok(true);
if (t === 'false' || t === '0' || t === 'no' || t === 'off') return ok(false);
}
return err(field, 'expected a boolean');
}, { type: 'bool', required: true, schema: { type: 'boolean' } });
},
/** OneBot message union: string | segment[] | object. A string that looks
* like a JSON array is parsed (matches legacy `asMessage`); otherwise the
* value passes through. Output stays `JsonValue` — downstream ctx.* accept it. */
message(): Field<JsonValue> {
return new FieldImpl<JsonValue>((raw, _field) => {
if (typeof raw === 'string') {
const t = raw.trim();
if (t.startsWith('[') && t.endsWith(']')) {
try {
const parsed: unknown = JSON.parse(t);
if (Array.isArray(parsed)) return ok(parsed as JsonValue);
} catch {
// fall through to literal text
}
}
}
return ok(raw);
}, { type: 'message', required: true, schema: { description: 'OneBot message: string | segment[] | object' } });
},
/** Homogeneous array; `.nonEmpty()` rejects []. */
array<E>(el: Field<E>): Field<E[]> & { nonEmpty(): Field<E[]> } {
return arrayField(el, false);
},
/** Constrained literal set. */
enum<const V extends readonly (string | number)[]>(...values: V): Field<V[number]> {
return new FieldImpl<V[number]>((raw, field) => {
if ((typeof raw === 'string' || typeof raw === 'number') && (values as readonly (string | number)[]).includes(raw)) {
return ok(raw as V[number]);
}
return err(field, `expected one of: ${values.join(', ')}`);
}, { type: 'enum', required: true, values, schema: { enum: [...values] } });
},
/** Escape hatch — pass the raw value (or undefined) through, validate nothing. */
raw(): Field<JsonValue | undefined> {
return new FieldImpl<JsonValue | undefined>((raw) => ok(raw), { type: 'raw', required: false, default: undefined, schema: {} });
},
};
// ─────────────────────────── type inference ───────────────────────────
type Spec = Record<string, Field<unknown>>;
type FieldType<F> = F extends Field<infer T> ? T : never;
/** Post-validation every key is present; optional/raw fields carry `undefined`
* in their value type. */
export type InferParams<S extends Spec> = { [K in keyof S]: FieldType<S[K]> };
// ─────────────────────────── cross-field rules ───────────────────────────
export interface CrossFieldRule {
readonly doc: string;
check(params: Record<string, unknown>): Err | null;
}
type Key<P> = Extract<keyof P, string>;
type Group<P> = Key<P> | Key<P>[];
export interface RuleBuilders<P> {
/** Exactly one group satisfied. A group is a key, or an array of keys that
* must ALL be present. e.g. `exactlyOneOf('message_id', ['group_id','user_id'])`. */
exactlyOneOf(...groups: Group<P>[]): CrossFieldRule;
atLeastOneOf(...keys: Key<P>[]): CrossFieldRule;
requiredTogether(...keys: Key<P>[]): CrossFieldRule;
mutuallyExclusive(...keys: Key<P>[]): CrossFieldRule;
/** Arbitrary predicate; fails with `doc` as the reason. */
rule(doc: string, ok: (p: P) => boolean): CrossFieldRule;
}
const present = (p: Record<string, unknown>, key: string): boolean => p[key] !== undefined;
const groupOk = (p: Record<string, unknown>, g: string | string[]): boolean =>
Array.isArray(g) ? g.every((k) => present(p, k)) : present(p, g);
const groupLabel = (g: string | string[]): string => (Array.isArray(g) ? `(${g.join('+')})` : g);
const RULES: RuleBuilders<Record<string, unknown>> = {
exactlyOneOf(...groups) {
const doc = `exactly one of: ${groups.map(groupLabel).join(' | ')}`;
return {
doc,
check: (p) => (groups.filter((g) => groupOk(p, g)).length === 1 ? null : err('', doc)),
};
},
atLeastOneOf(...keys) {
const doc = `at least one of: ${keys.join(', ')}`;
return { doc, check: (p) => (keys.some((k) => present(p, k)) ? null : err('', doc)) };
},
requiredTogether(...keys) {
const doc = `all or none of: ${keys.join(', ')}`;
return {
doc,
check: (p) => {
const n = keys.filter((k) => present(p, k)).length;
return n === 0 || n === keys.length ? null : err('', doc);
},
};
},
mutuallyExclusive(...keys) {
const doc = `at most one of: ${keys.join(', ')}`;
return { doc, check: (p) => (keys.filter((k) => present(p, k)).length <= 1 ? null : err('', doc)) };
},
rule(doc, okFn) {
return { doc, check: (p) => (okFn(p as never) ? null : err('', doc)) };
},
};
// ─────────────────────────── defineAction ───────────────────────────
export interface ParamDoc extends FieldDoc {
name: string;
}
export interface ActionDoc {
name: string;
aliases: string[];
/** Domain category (set by the doc collector, e.g. 群管理/消息). */
category?: string;
summary?: string;
returns?: string;
/** True only for pure data-fetch actions (no side effects). Drives the MCP's
* read/write tool routing; defaults to false (treated as a write). */
readOnly: boolean;
params: ParamDoc[];
invariants: string[];
/** Composed JSON Schema for the whole params object (properties + required). */
inputSchema: JsonSchema;
}
type Handler = (params: JsonObject) => Promise<ApiResponse>;
export interface ActionSpec<S extends Spec> {
readonly names: string[];
readonly params: S;
/** Pure: coerce + validate + cross-field, no ctx, no I/O. The test surface. */
parse(raw: JsonObject): CoerceResult<InferParams<S>>;
/** Bind ctx and produce the `(params) => ApiResponse` for `registerAction`. */
toHandler(ctx: ApiActionContext): Handler;
/** Doc metadata (D4); a renderer walks this. */
describe(): ActionDoc;
register(h: ApiHandler, ctx: ApiActionContext): void;
}
interface ActionDef<S extends Spec> {
name: string | readonly [string, ...string[]];
summary?: string;
returns?: string;
/** Mark true ONLY for pure data-fetch actions with no side effects. Default
* false = write. Surfaced via describe() into the catalog for the MCP's
* read/write routing. Classify by what `run` actually does, not the name. */
readOnly?: boolean;
params: S;
rules?: (r: RuleBuilders<InferParams<S>>) => readonly CrossFieldRule[];
/** `raw` is the original untouched params — an escape hatch for the
* irregular tail (alias-key fallbacks, arbitrary nested objects). Declared
* fields in `p` remain the validated path; reach for `raw` only for keys
* the spec can't express. */
run: (p: InferParams<S>, ctx: ApiActionContext, raw: JsonObject) => Promise<ApiResponse> | ApiResponse;
}
const wording = (e: Err): string => (e.field ? `${e.field}: ${e.reason}` : e.reason);
export function defineAction<S extends Spec>(def: ActionDef<S>): ActionSpec<S> {
const names = typeof def.name === 'string' ? [def.name] : [...def.name];
const rules: readonly CrossFieldRule[] = def.rules
? def.rules(RULES as unknown as RuleBuilders<InferParams<S>>)
: [];
const parse = (raw: JsonObject): CoerceResult<InferParams<S>> => {
const out: Record<string, unknown> = {};
for (const key of Object.keys(def.params)) {
const field = def.params[key];
const value = Object.prototype.hasOwnProperty.call(raw, key) ? (raw[key] as JsonValue) : MISSING;
const r = field.coerce(value, key);
if (!r.ok) return r;
out[key] = r.value;
}
for (const rule of rules) {
const e = rule.check(out);
if (e) return e;
}
return ok(out as InferParams<S>);
};
const toHandler = (ctx: ApiActionContext): Handler => async (params: JsonObject) => {
const r = parse(params);
if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r));
return def.run(r.value, ctx, params);
};
return {
names,
params: def.params,
parse,
toHandler,
describe: () => {
const entries = Object.entries(def.params);
const properties: Record<string, JsonSchema> = {};
const required: string[] = [];
for (const [name, field] of entries) {
properties[name] = field.toJsonSchema();
if (field.doc.required) required.push(name);
}
const inputSchema: JsonSchema = {
type: 'object',
properties,
...(required.length ? { required } : {}),
additionalProperties: true,
};
return {
name: names[0],
aliases: names.slice(1),
summary: def.summary,
returns: def.returns,
readOnly: def.readOnly ?? false,
params: entries.map(([name, field]) => ({ name, ...field.doc })),
invariants: rules.map((rule) => rule.doc),
inputSchema,
};
},
register: (h, ctx) => {
const handler = toHandler(ctx);
for (const name of names) h.registerAction(name, handler);
},
};
}
// ─────────────────────────── presets ───────────────────────────
// `group_id` appears in 61/142 actions, `user_id` in 27 — these collapse the
// dominant shape. The injected fields are surfaced in `describe()` so docs
// list them even though the caller never typed them (ADR-0006 trade-off).
type WithGroup<S extends Spec> = S & { group_id: Field<number> };
type WithGroupUser<S extends Spec> = S & { group_id: Field<number>; user_id: Field<number> };
interface PresetDef<S extends Spec, Extra> {
name: string | readonly [string, ...string[]];
summary?: string;
returns?: string;
readOnly?: boolean;
params?: S;
rules?: (r: RuleBuilders<InferParams<S> & Extra>) => readonly CrossFieldRule[];
run: (p: InferParams<S> & Extra, ctx: ApiActionContext, raw: JsonObject) => Promise<ApiResponse> | ApiResponse;
}
/** Pre-seeds `group_id` (uint, required). */
export function groupAction<S extends Spec>(def: PresetDef<S, { group_id: number }>): ActionSpec<WithGroup<S>> {
const params = { group_id: f.uint().describe('群号'), ...(def.params ?? {}) } as WithGroup<S>;
return defineAction({ ...def, params } as unknown as ActionDef<WithGroup<S>>);
}
/** Pre-seeds `group_id` + `user_id` (both uint, required). */
export function groupUserAction<S extends Spec>(
def: PresetDef<S, { group_id: number; user_id: number }>,
): ActionSpec<WithGroupUser<S>> {
const params = {
group_id: f.uint().describe('群号'),
user_id: f.uint().describe('QQ 号'),
...(def.params ?? {}),
} as WithGroupUser<S>;
return defineAction({ ...def, params } as unknown as ActionDef<WithGroupUser<S>>);
}
// ─────────────────────────── registration helper ───────────────────────────
/** Register many specs onto an ApiHandler. Coexists with legacy
* `h.registerAction(name, fn)` in the same `register(h, ctx)`. */
export function registerActions(h: ApiHandler, ctx: ApiActionContext, specs: ReadonlyArray<ActionSpec<Spec>>): void {
for (const spec of specs) spec.register(h, ctx);
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,30 +1,47 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asNumber, asBoolean } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
import { defineAction, registerActions, f } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { okResponse } from '../types';
export const actions = [
defineAction({
name: 'get_friend_list',
summary: '获取好友列表',
readOnly: true,
params: {},
run: async (_p, ctx) => {
if (ctx.getFriendList) {
return okResponse(await ctx.getFriendList());
}
return okResponse([]);
},
}),
defineAction({
name: 'get_stranger_info',
summary: '获取陌生人信息',
readOnly: true,
params: { user_id: f.uint().describe('QQ 号') },
run: async (p, ctx) => {
const userId = p.user_id;
if (ctx.getStrangerInfo) {
const info = await ctx.getStrangerInfo(userId);
return okResponse(info ?? { user_id: userId, nickname: '', sex: 'unknown', age: 0 });
}
return okResponse({ user_id: userId, nickname: '', sex: 'unknown', age: 0 });
},
}),
defineAction({
name: 'delete_friend',
summary: '删除好友',
params: { user_id: f.uint().describe('QQ 号'), block: f.bool().default(false) },
run: async (p, ctx) => {
await ctx.bridge.apis.friend.delete(p.user_id, p.block);
return okResponse();
},
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_friend_list', async () => {
if (ctx.getFriendList) {
return okResponse(await ctx.getFriendList());
}
return okResponse([]);
});
h.registerAction('get_stranger_info', async (params) => {
const userId = asNumber(params.user_id);
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
if (ctx.getStrangerInfo) {
const info = await ctx.getStrangerInfo(userId);
return okResponse(info ?? { user_id: userId, nickname: '', sex: 'unknown', age: 0 });
}
return okResponse({ user_id: userId, nickname: '', sex: 'unknown', age: 0 });
});
h.registerAction('delete_friend', async (params) => {
const userId = asNumber(params.user_id);
const block = asBoolean(params.block, false);
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
await ctx.bridge.apis.friend.delete(userId, block);
return okResponse();
});
registerActions(h, ctx, actions);
}

View File

@@ -1,118 +1,135 @@
import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { asBoolean, asNumber, asString } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('set_group_kick', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const reject = asBoolean(params.reject_add_request, false);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.bridge.apis.groupAdmin.kickMember(groupId, userId, reject);
return okResponse();
});
h.registerAction('set_group_kick_members', async (params) => {
const groupId = asNumber(params.group_id);
const userIds = Array.isArray(params.user_id) ? params.user_id.map(asNumber).filter(Boolean) : [];
const reject = asBoolean(params.reject_add_request, false);
if (!groupId || userIds.length === 0) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id array are required');
await ctx.bridge.apis.groupAdmin.kickMembers(groupId, userIds, reject);
return okResponse();
});
h.registerAction('set_group_ban', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const duration = asNumber(params.duration) || 1800;
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.bridge.apis.groupAdmin.muteMember(groupId, userId, duration);
return okResponse();
});
h.registerAction('set_group_whole_ban', async (params) => {
const groupId = asNumber(params.group_id);
const enable = asBoolean(params.enable, true);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.bridge.apis.groupAdmin.muteAll(groupId, enable);
return okResponse();
});
h.registerAction('set_group_add_option', async (params) => {
const groupId = asNumber(params.group_id);
const addType = asNumber(params.add_type);
if (!groupId || addType === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and add_type are required');
await ctx.bridge.apis.groupAdmin.setAddOption(groupId, addType);
return okResponse();
});
h.registerAction('set_group_search', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.bridge.apis.groupAdmin.setSearch(groupId);
return okResponse();
});
h.registerAction('set_group_admin', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const enable = asBoolean(params.enable, true);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.bridge.apis.groupAdmin.setAdmin(groupId, userId, enable);
return okResponse();
});
h.registerAction('set_group_card', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const card = asString(params.card);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.bridge.apis.groupAdmin.setCard(groupId, userId, card);
return okResponse();
});
h.registerAction('set_group_name', async (params) => {
const groupId = asNumber(params.group_id);
const name = asString(params.group_name);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.bridge.apis.groupAdmin.setName(groupId, name);
return okResponse();
});
h.registerAction('set_group_leave', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.bridge.apis.groupAdmin.leave(groupId);
return okResponse();
});
h.registerAction('set_group_special_title', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const title = asString(params.special_title);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.bridge.apis.groupAdmin.setSpecialTitle(groupId, userId, title);
return okResponse();
});
h.registerAction('set_group_anonymous', async () => {
return okResponse();
});
h.registerAction('set_group_anonymous_ban', async () => {
return okResponse();
});
h.registerAction('set_group_portrait', async (params) => {
const groupId = asNumber(params.group_id);
const file = asString(params.file);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
try {
await ctx.bridge.apis.profile.setGroupAvatar(groupId, file);
export const actions = [
groupUserAction({
name: 'set_group_kick',
summary: '踢出群成员',
params: { reject_add_request: f.bool().default(false) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.kickMember(p.group_id, p.user_id, p.reject_add_request);
return okResponse();
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
});
},
}),
groupAction({
name: 'set_group_kick_members',
summary: '批量踢出群成员',
params: { user_id: f.array(f.uint()).nonEmpty(), reject_add_request: f.bool().default(false) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.kickMembers(p.group_id, p.user_id, p.reject_add_request);
return okResponse();
},
}),
groupUserAction({
name: 'set_group_ban',
summary: '禁言群成员(duration=0 解除)',
params: { duration: f.int({ min: 0 }).default(1800) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.muteMember(p.group_id, p.user_id, p.duration);
return okResponse();
},
}),
groupAction({
name: 'set_group_whole_ban',
summary: '全员禁言开关',
params: { enable: f.bool().default(true) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.muteAll(p.group_id, p.enable);
return okResponse();
},
}),
groupAction({
name: 'set_group_add_option',
summary: '设置加群选项',
params: { add_type: f.int({ min: 0 }).default(0) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setAddOption(p.group_id, p.add_type);
return okResponse();
},
}),
groupAction({
name: 'set_group_search',
summary: '允许群被搜索',
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setSearch(p.group_id);
return okResponse();
},
}),
groupUserAction({
name: 'set_group_admin',
summary: '设置/取消管理员',
params: { enable: f.bool().default(true) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setAdmin(p.group_id, p.user_id, p.enable);
return okResponse();
},
}),
groupUserAction({
name: 'set_group_card',
summary: '设置群名片(空字符串清除)',
params: { card: f.string().default('') },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setCard(p.group_id, p.user_id, p.card);
return okResponse();
},
}),
groupAction({
name: 'set_group_name',
summary: '设置群名',
params: { group_name: f.string().default('') },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setName(p.group_id, p.group_name);
return okResponse();
},
}),
groupAction({
name: 'set_group_leave',
summary: '退群',
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.leave(p.group_id);
return okResponse();
},
}),
groupUserAction({
name: 'set_group_special_title',
summary: '设置群头衔',
params: { special_title: f.string().default('') },
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setSpecialTitle(p.group_id, p.user_id, p.special_title);
return okResponse();
},
}),
// No-op stubs (accept and ignore any params, as before).
defineAction({ name: 'set_group_anonymous', summary: '匿名开关(未实现,返回 ok)', params: {}, run: () => okResponse() }),
defineAction({ name: 'set_group_anonymous_ban', summary: '匿名禁言(未实现,返回 ok)', params: {}, run: () => okResponse() }),
groupAction({
name: 'set_group_portrait',
summary: '设置群头像',
params: { file: f.string({ allowEmpty: false }) },
run: async (p, ctx) => {
try {
await ctx.bridge.apis.profile.setGroupAvatar(p.group_id, p.file);
return okResponse();
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
},
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}

View File

@@ -1,133 +1,132 @@
import { groupAction, registerActions, f } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { asNumber, asString } from '../api-handler';
import type { JsonValue } from '../types';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_group_album_list', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
export const actions = [
groupAction({
name: 'get_group_album_list',
readOnly: true,
run: async (p, ctx) => {
try {
const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id);
return okResponse(albumList);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get group album list';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
},
}),
try {
const albumList = await ctx.bridge.apis.groupAlbum.list(groupId);
return okResponse(albumList);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get group album list';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
groupAction({
name: 'upload_image_to_qun_album',
params: {
album_id: f.string({ allowEmpty: false }),
album_name: f.string({ allowEmpty: false }),
file: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
try {
await ctx.bridge.apis.groupAlbum.upload(p.group_id, p.album_id, p.album_name, p.file);
return okResponse(null);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to upload image to group album';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
},
}),
h.registerAction('upload_image_to_qun_album', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const albumName = asString(params.album_name);
const file = asString(params.file);
groupAction({
name: 'get_group_album_media_list',
readOnly: true,
params: {
album_id: f.string({ allowEmpty: false }),
attach_info: f.string().default(''),
},
run: async (p, ctx) => {
try {
const mediaList = await ctx.bridge.apis.groupAlbum.getMediaList(p.group_id, p.album_id, p.attach_info);
return okResponse(mediaList as unknown as JsonValue);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get group album media list';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
},
}),
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
if (!albumName) return failedResponse(RETCODE.BAD_REQUEST, 'album_name is required');
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
groupAction({
name: 'do_group_album_comment',
params: {
album_id: f.string({ allowEmpty: false }),
lloc: f.string({ allowEmpty: false }),
content: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
try {
const comment = await ctx.bridge.apis.groupAlbum.comment(p.group_id, p.album_id, p.lloc, p.content);
return okResponse(comment as unknown as JsonValue);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to comment on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
},
}),
try {
await ctx.bridge.apis.groupAlbum.upload(groupId, albumId, albumName, file);
return okResponse(null);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to upload image to group album';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('get_group_album_media_list', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const attachInfo = asString(params.attach_info) || '';
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
try {
const mediaList = await ctx.bridge.apis.groupAlbum.getMediaList(groupId, albumId, attachInfo);
return okResponse(mediaList as unknown as JsonValue);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get group album media list';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('do_group_album_comment', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const lloc = asString(params.lloc);
const content = asString(params.content);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
if (!lloc) return failedResponse(RETCODE.BAD_REQUEST, 'lloc is required');
if (!content) return failedResponse(RETCODE.BAD_REQUEST, 'content is required');
try {
const comment = await ctx.bridge.apis.groupAlbum.comment(groupId, albumId, lloc, content);
return okResponse(comment as unknown as JsonValue);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to comment on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('set_group_album_media_like', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const batchId = asString(params.batch_id);
const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数
if (!groupId || !albumId || !batchId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required');
}
try {
const res = await ctx.bridge.apis.groupAlbum.like(groupId, albumId, batchId, lloc, true);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to set like on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
groupAction({
name: 'set_group_album_media_like',
params: {
album_id: f.string({ allowEmpty: false }),
batch_id: f.string({ allowEmpty: false }),
lloc: f.string().optional(), // 可选参数(空串按未传处理)
},
run: async (p, ctx) => {
try {
const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, true);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to set like on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
},
}),
// 取消点赞群相册媒体
h.registerAction('cancel_group_album_media_like', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const batchId = asString(params.batch_id);
const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数
groupAction({
name: 'cancel_group_album_media_like',
params: {
album_id: f.string({ allowEmpty: false }),
batch_id: f.string({ allowEmpty: false }),
lloc: f.string().optional(), // 可选参数(空串按未传处理)
},
run: async (p, ctx) => {
try {
const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, false);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to cancel like on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
},
}),
if (!groupId || !albumId || !batchId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required');
}
groupAction({
name: 'del_group_album_media',
params: {
album_id: f.string({ allowEmpty: false }),
lloc: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
try {
const res = await ctx.bridge.apis.groupAlbum.delete(p.group_id, p.album_id, p.lloc);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to delete album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
},
}),
];
try {
const res = await ctx.bridge.apis.groupAlbum.like(groupId, albumId, batchId, lloc, false);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to cancel like on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('del_group_album_media', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const lloc = asString(params.lloc);
if (!groupId || !albumId || !lloc) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and lloc are required');
}
try {
const res = await ctx.bridge.apis.groupAlbum.delete(groupId, albumId, lloc);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to delete album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}

View File

@@ -1,118 +1,157 @@
import { defineAction, groupAction, registerActions, f } from '../action-kit';
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asBoolean, asNumber, asString } from '../api-handler';
import { RETCODE, failedResponse } from '../types';
import { okResponse } from '../types';
import { RETCODE, failedResponse, okResponse } from '../types';
export const actions = [
groupAction({
name: 'upload_group_file',
summary: '上传群文件',
returns: '{ file_id: string }',
// `folder` / `folder_id` are two aliases for one target dir; the first
// non-empty wins, else '/'. Both default '' so the `||` chain matches the
// legacy `asString(folder) || asString(folder_id) || '/'`.
params: {
file: f.string({ allowEmpty: false }),
name: f.string().default(''),
folder: f.string().default(''),
folder_id: f.string().default(''),
upload_file: f.bool().default(true),
},
run: async (p, ctx) => {
const folderId = p.folder || p.folder_id || '/';
const result = await ctx.bridge.apis.groupFile.upload(p.group_id, p.file, p.name, folderId, p.upload_file);
return okResponse({ file_id: result.fileId });
},
}),
defineAction({
name: 'upload_private_file',
summary: '上传私聊文件',
returns: '{ file_id: string }',
params: {
user_id: f.uint(),
file: f.string({ allowEmpty: false }),
name: f.string().default(''),
upload_file: f.bool().default(true),
},
run: async (p, ctx) => {
const result = await ctx.bridge.apis.groupFile.uploadPrivate(p.user_id, p.file, p.name, p.upload_file);
return okResponse({ file_id: result.fileId });
},
}),
groupAction({
name: 'get_group_file_url',
summary: '获取群文件下载链接',
readOnly: true,
returns: '{ url: string }',
// busid: legacy `asNumber(busid) || 102` mapped absent/0/invalid → 102.
// f.int({min:0}).default(102) keeps absent → 102, but a present 0 now
// stays 0 and a non-numeric busid is now rejected (BAD_REQUEST) instead
// of silently becoming 102.
params: { file_id: f.string({ allowEmpty: false }), busid: f.int({ min: 0 }).default(102) },
run: async (p, ctx) => {
return okResponse({ url: await ctx.bridge.apis.groupFile.getUrl(p.group_id, p.file_id, p.busid) });
},
}),
groupAction({
name: 'get_group_root_files',
summary: '获取群根目录文件列表',
readOnly: true,
run: async (p, ctx) => {
return okResponse(await ctx.getGroupFiles(p.group_id, '/'));
},
}),
groupAction({
name: 'get_group_files_by_folder',
summary: '获取群子目录文件列表',
readOnly: true,
// folder_id / folder are aliases; first non-empty wins, else '/'.
params: { folder_id: f.string().default(''), folder: f.string().default('') },
run: async (p, ctx) => {
const folderId = p.folder_id || p.folder || '/';
return okResponse(await ctx.getGroupFiles(p.group_id, folderId));
},
}),
groupAction({
name: 'delete_group_file',
summary: '删除群文件',
params: { file_id: f.string({ allowEmpty: false }) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupFile.delete(p.group_id, p.file_id);
return okResponse();
},
}),
groupAction({
name: 'move_group_file',
summary: '移动群文件',
params: {
file_id: f.string({ allowEmpty: false }),
parent_directory: f.string({ allowEmpty: false }),
target_directory: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupFile.move(p.group_id, p.file_id, p.parent_directory, p.target_directory);
return okResponse();
},
}),
groupAction({
name: 'create_group_file_folder',
summary: '创建群文件夹',
params: { name: f.string({ allowEmpty: false }), parent_id: f.string().default('/') },
run: async (p, ctx) => {
await ctx.bridge.apis.groupFile.createFolder(p.group_id, p.name, p.parent_id || '/');
return okResponse();
},
}),
groupAction({
name: 'delete_group_file_folder',
summary: '删除群文件夹',
params: { folder_id: f.string({ allowEmpty: false }) },
run: async (p, ctx) => {
await ctx.bridge.apis.groupFile.deleteFolder(p.group_id, p.folder_id);
return okResponse();
},
}),
groupAction({
name: 'rename_group_file_folder',
summary: '重命名群文件夹',
// new_folder_name / name are aliases; first non-empty wins and must be
// non-empty (legacy `asString(new_folder_name) || asString(name)` + `!newName`).
params: { folder_id: f.string({ allowEmpty: false }), new_folder_name: f.string().default(''), name: f.string().default('') },
run: async (p, ctx) => {
const newName = p.new_folder_name || p.name;
if (!newName) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required');
}
await ctx.bridge.apis.groupFile.renameFolder(p.group_id, p.folder_id, newName);
return okResponse();
},
}),
defineAction({
name: 'get_private_file_url',
summary: '获取私聊文件下载链接',
readOnly: true,
returns: '{ url: string }',
params: {
user_id: f.uint(),
file_id: f.string({ allowEmpty: false }),
file_hash: f.string({ allowEmpty: false }),
},
run: async (p, ctx) => {
return okResponse({ url: await ctx.bridge.apis.groupFile.getPrivateUrl(p.user_id, p.file_id, p.file_hash) });
},
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('upload_group_file', async (params) => {
const groupId = asNumber(params.group_id);
const file = asString(params.file);
const name = asString(params.name);
const folderId = asString(params.folder) || asString(params.folder_id) || '/';
const uploadFile = asBoolean(params.upload_file, true);
if (!groupId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file are required');
const result = await ctx.bridge.apis.groupFile.upload(groupId, file, name, folderId, uploadFile);
return okResponse({ file_id: result.fileId });
});
h.registerAction('upload_private_file', async (params) => {
const userId = asNumber(params.user_id);
const file = asString(params.file);
const name = asString(params.name);
const uploadFile = asBoolean(params.upload_file, true);
if (!userId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'user_id and file are required');
const result = await ctx.bridge.apis.groupFile.uploadPrivate(userId, file, name, uploadFile);
return okResponse({ file_id: result.fileId });
});
h.registerAction('get_group_file_url', async (params) => {
const groupId = asNumber(params.group_id);
const fileId = asString(params.file_id);
const busId = asNumber(params.busid) || 102;
if (!groupId || !fileId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
}
return okResponse({ url: await ctx.bridge.apis.groupFile.getUrl(groupId, fileId, busId) });
});
h.registerAction('get_group_root_files', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
return okResponse(await ctx.getGroupFiles(groupId, '/'));
});
h.registerAction('get_group_files_by_folder', async (params) => {
const groupId = asNumber(params.group_id);
const folderId = asString(params.folder_id) || asString(params.folder) || '/';
if (!groupId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
return okResponse(await ctx.getGroupFiles(groupId, folderId));
});
h.registerAction('delete_group_file', async (params) => {
const groupId = asNumber(params.group_id);
const fileId = asString(params.file_id);
if (!groupId || !fileId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
}
await ctx.bridge.apis.groupFile.delete(groupId, fileId);
return okResponse();
});
h.registerAction('move_group_file', async (params) => {
const groupId = asNumber(params.group_id);
const fileId = asString(params.file_id);
const parentDirectory = asString(params.parent_directory);
const targetDirectory = asString(params.target_directory);
if (!groupId || !fileId || !parentDirectory || !targetDirectory) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, file_id, parent_directory and target_directory are required');
}
await ctx.bridge.apis.groupFile.move(groupId, fileId, parentDirectory, targetDirectory);
return okResponse();
});
h.registerAction('create_group_file_folder', async (params) => {
const groupId = asNumber(params.group_id);
const name = asString(params.name);
const parentId = asString(params.parent_id) || '/';
if (!groupId || !name) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and name are required');
}
await ctx.bridge.apis.groupFile.createFolder(groupId, name, parentId);
return okResponse();
});
h.registerAction('delete_group_file_folder', async (params) => {
const groupId = asNumber(params.group_id);
const folderId = asString(params.folder_id);
if (!groupId || !folderId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required');
}
await ctx.bridge.apis.groupFile.deleteFolder(groupId, folderId);
return okResponse();
});
h.registerAction('rename_group_file_folder', async (params) => {
const groupId = asNumber(params.group_id);
const folderId = asString(params.folder_id);
const newName = asString(params.new_folder_name) || asString(params.name);
if (!groupId || !folderId || !newName) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required');
}
await ctx.bridge.apis.groupFile.renameFolder(groupId, folderId, newName);
return okResponse();
});
h.registerAction('get_private_file_url', async (params) => {
const userId = asNumber(params.user_id);
const fileId = asString(params.file_id);
const fileHash = asString(params.file_hash);
if (!userId || !fileId || !fileHash) {
return failedResponse(RETCODE.BAD_REQUEST, 'user_id, file_id and file_hash are required');
}
return okResponse({ url: await ctx.bridge.apis.groupFile.getPrivateUrl(userId, fileId, fileHash) });
});
registerActions(h, ctx, actions);
}

View File

@@ -1,84 +1,120 @@
import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit';
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asNumber, asBoolean, asString } from '../api-handler';
import { asString } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
import { WebHonorType } from '@snowluma/protocol/web/group-honor';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_group_list', async (params) => {
const noCache = asBoolean(params.no_cache, false);
if (ctx.getGroupList) {
return okResponse(await ctx.getGroupList(noCache));
}
return okResponse([]);
});
export const actions = [
defineAction({
name: 'get_group_list',
summary: '获取群列表',
readOnly: true,
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const noCache = p.no_cache;
if (ctx.getGroupList) {
return okResponse(await ctx.getGroupList(noCache));
}
return okResponse([]);
},
}),
h.registerAction('get_group_info', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
const noCache = asBoolean(params.no_cache, false);
if (ctx.getGroupInfo) {
const info = await ctx.getGroupInfo(groupId, noCache);
return okResponse(info ?? { group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
}
return okResponse({ group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
});
groupAction({
name: 'get_group_info',
summary: '获取群信息',
readOnly: true,
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const groupId = p.group_id;
const noCache = p.no_cache;
if (ctx.getGroupInfo) {
const info = await ctx.getGroupInfo(groupId, noCache);
return okResponse(info ?? { group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
}
return okResponse({ group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
},
}),
h.registerAction('get_group_member_list', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
const noCache = asBoolean(params.no_cache, false);
if (ctx.getGroupMemberList) {
return okResponse(await ctx.getGroupMemberList(groupId, noCache));
}
return okResponse([]);
});
groupAction({
name: 'get_group_member_list',
summary: '获取群成员列表',
readOnly: true,
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const groupId = p.group_id;
const noCache = p.no_cache;
if (ctx.getGroupMemberList) {
return okResponse(await ctx.getGroupMemberList(groupId, noCache));
}
return okResponse([]);
},
}),
h.registerAction('get_group_member_info', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
const noCache = asBoolean(params.no_cache, false);
if (ctx.getGroupMemberInfo) {
const info = await ctx.getGroupMemberInfo(groupId, userId, noCache);
return okResponse(info ?? {
groupUserAction({
name: 'get_group_member_info',
summary: '获取群成员信息',
readOnly: true,
params: { no_cache: f.bool().default(false) },
run: async (p, ctx) => {
const groupId = p.group_id;
const userId = p.user_id;
const noCache = p.no_cache;
if (ctx.getGroupMemberInfo) {
const info = await ctx.getGroupMemberInfo(groupId, userId, noCache);
return okResponse(info ?? {
group_id: groupId, user_id: userId, nickname: '', card: '',
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
level: '0', role: 'member', title: '',
});
}
return okResponse({
group_id: groupId, user_id: userId, nickname: '', card: '',
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
level: '0', role: 'member', title: '',
});
}
return okResponse({
group_id: groupId, user_id: userId, nickname: '', card: '',
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
level: '0', role: 'member', title: '',
});
});
},
}),
h.registerAction('get_group_honor_info', async (params) => {
const groupId = asNumber(params.group_id);
const typeStr = asString(params.type) || 'all';
// `type` keeps the legacy `asString(x) || 'all'` semantics (absent / non-string
// / empty-string all collapse to 'all'), which a typed string field can't
// replicate exactly — so it stays a raw param coerced in run().
groupAction({
name: 'get_group_honor_info',
summary: '获取群荣誉信息',
readOnly: true,
params: { type: f.raw() },
run: async (p, ctx) => {
const groupId = p.group_id;
const typeStr = asString(p.type) || 'all';
if (!groupId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
const typeValues = Object.values(WebHonorType) as string[];
if (!typeValues.includes(typeStr)) {
return failedResponse(RETCODE.BAD_REQUEST, `invalid type, must be one of ${typeValues.join(', ')}`);
}
try {
const honorInfo = await ctx.bridge.apis.web.getHonorInfo(groupId, typeStr as WebHonorType);
return okResponse(honorInfo);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`);
}
},
}),
const typeValues = Object.values(WebHonorType) as string[];
if (!typeValues.includes(typeStr)) {
return failedResponse(RETCODE.BAD_REQUEST, `invalid type, must be one of ${typeValues.join(', ')}`);
}
defineAction({
name: 'get_group_system_msg',
summary: '获取群系统消息',
readOnly: true,
params: {},
run: async (_p, ctx) => {
if (ctx.handleGetGroupSystemMsg) {
return okResponse(await ctx.handleGetGroupSystemMsg());
}
return okResponse([]);
},
}),
];
try {
const honorInfo = await ctx.bridge.apis.web.getHonorInfo(groupId, typeStr as WebHonorType);
return okResponse(honorInfo);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`);
}
});
h.registerAction('get_group_system_msg', async () => {
if (ctx.handleGetGroupSystemMsg) {
return okResponse(await ctx.handleGetGroupSystemMsg());
}
return okResponse([]);
});
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}

View File

@@ -1,32 +1,63 @@
import { defineAction, registerActions } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { okResponse } from '../types';
// 后续考虑移动到一个统一的地方构建,避免版本信息分散在各个模块中。
const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev';
export const actions = [
defineAction({
name: 'get_login_info',
readOnly: true,
params: {},
run: (_p, ctx) => {
const login = ctx.getLoginInfo();
return okResponse({ user_id: login.userId, nickname: login.nickname });
},
}),
defineAction({
name: 'get_status',
readOnly: true,
params: {},
run: (_p, ctx) => {
const online = ctx.isOnline();
return okResponse({ online, good: online });
},
}),
defineAction({
name: 'get_version_info',
readOnly: true,
params: {},
run: () => {
return okResponse({
app_name: 'SnowLuma',
app_version: `${appVersion}-node`,
protocol_version: 'v11',
});
},
}),
defineAction({
name: 'can_send_image',
readOnly: true,
params: {},
run: (_p, ctx) => {
return okResponse({ yes: ctx.canSendImage?.() ?? false });
},
}),
defineAction({
name: 'can_send_record',
readOnly: true,
params: {},
run: (_p, ctx) => {
return okResponse({ yes: ctx.canSendRecord?.() ?? false });
},
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_login_info', async () => {
const login = ctx.getLoginInfo();
return okResponse({ user_id: login.userId, nickname: login.nickname });
});
h.registerAction('get_status', async () => {
const online = ctx.isOnline();
return okResponse({ online, good: online });
});
// 后续考虑移动到一个统一的地方构建,避免版本信息分散在各个模块中。
const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev';
h.registerAction('get_version_info', async () => {
return okResponse({
app_name: 'SnowLuma',
app_version: `${appVersion}-node`,
protocol_version: 'v11',
});
});
h.registerAction('can_send_image', async () => {
return okResponse({ yes: ctx.canSendImage?.() ?? false });
});
h.registerAction('can_send_record', async () => {
return okResponse({ yes: ctx.canSendRecord?.() ?? false });
});
registerActions(h, ctx, actions);
}

View File

@@ -1,97 +1,117 @@
import type { JsonObject, JsonValue } from '../types';
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asNumber, asString, asBoolean, asMessage } from '../api-handler';
import { defineAction, groupAction, registerActions, f } from '../action-kit';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('send_msg', async (params) => {
const messageType = asString(params.message_type);
const message = asMessage(params.message);
const autoEscape = asBoolean(params.auto_escape, false);
if (message === undefined) {
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
/**
* Re-sign image URLs in a stored message event at read time. `get_msg`
* returns a copy persisted when the message first arrived, and image rkeys
* expire — so walk the segment array and refresh each image URL through
* `ctx.getImageInfo`, which mints a current rkey. Best-effort and in-place;
* `findEvent` returns a fresh parse, so mutating the array is safe.
*/
async function refreshStoredImageUrls(event: JsonObject, ctx: ApiActionContext): Promise<void> {
const segments = event.message;
if (!Array.isArray(segments)) return;
for (const seg of segments) {
if (!seg || typeof seg !== 'object') continue;
const segment = seg as { type?: unknown; data?: Record<string, JsonValue> };
if (segment.type !== 'image') continue;
const data = segment.data;
if (!data || typeof data !== 'object') continue;
const file = typeof data.file === 'string' ? data.file
: typeof data.file_id === 'string' ? data.file_id
: '';
if (!file) continue;
try {
const info = await ctx.getImageInfo(file);
if (info && typeof info.url === 'string' && info.url) data.url = info.url;
} catch {
// Keep the stored URL when the refresh fails.
}
if (messageType === 'group' || params.group_id !== undefined) {
const groupId = asNumber(params.group_id);
if (!Number.isInteger(groupId) || groupId <= 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
return okResponse({ message_id: result.messageId });
}
const userId = asNumber(params.user_id);
if (!Number.isInteger(userId) || userId <= 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
}
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
return okResponse({ message_id: result.messageId });
});
h.registerAction('send_private_msg', async (params) => {
const userId = asNumber(params.user_id);
const message = asMessage(params.message);
const autoEscape = asBoolean(params.auto_escape, false);
if (!Number.isInteger(userId) || userId <= 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
}
if (message === undefined) {
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
}
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
return okResponse({ message_id: result.messageId });
});
h.registerAction('send_group_msg', async (params) => {
const groupId = asNumber(params.group_id);
const message = asMessage(params.message);
const autoEscape = asBoolean(params.auto_escape, false);
if (!Number.isInteger(groupId) || groupId <= 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
if (message === undefined) {
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
}
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
return okResponse({ message_id: result.messageId });
});
h.registerAction('get_msg', async (params) => {
const messageId = asNumber(params.message_id);
if (!Number.isInteger(messageId) || messageId === 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
}
const data = ctx.getMessage(messageId);
if (!data) {
return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
}
const result: JsonObject = { ...data };
delete result.post_type;
delete result.self_id;
result.real_id = (result.message_id ?? messageId) as JsonValue;
return okResponse(result);
});
h.registerAction('delete_msg', async (params) => {
const messageId = asNumber(params.message_id);
if (!Number.isInteger(messageId) || messageId === 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
}
const meta = ctx.getMessageMeta(messageId);
if (!meta) {
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not retractable');
}
await ctx.deleteMessage(messageId, meta);
return okResponse();
});
}
}
export const actions = [
// send_msg routes on message_type / group_id presence, so the *required*
// id is conditional — that branch stays in run(). The fields themselves
// (message required; group_id/user_id valid uints when present) are
// validated by the spec; message_type is left lenient for parity.
defineAction({
name: 'send_msg',
summary: '发送消息(按 message_type/群号 自动路由群聊或私聊)',
returns: '{ message_id: number }',
params: {
message: f.message(),
message_type: f.string().optional(),
group_id: f.uint().optional(),
user_id: f.uint().optional(),
auto_escape: f.bool().default(false),
},
run: async (p, ctx) => {
if (p.message_type === 'group' || p.group_id !== undefined) {
if (p.group_id === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
const result = await ctx.sendGroupMessage(p.group_id, p.message, p.auto_escape);
return okResponse({ message_id: result.messageId });
}
if (p.user_id === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape);
return okResponse({ message_id: result.messageId });
},
}),
defineAction({
name: 'send_private_msg',
summary: '发送私聊消息',
returns: '{ message_id: number }',
params: { user_id: f.uint(), message: f.message(), auto_escape: f.bool().default(false) },
run: async (p, ctx) => {
const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape);
return okResponse({ message_id: result.messageId });
},
}),
groupAction({
name: 'send_group_msg',
summary: '发送群消息',
returns: '{ message_id: number }',
params: { message: f.message(), auto_escape: f.bool().default(false) },
run: async (p, ctx) => {
const result = await ctx.sendGroupMessage(p.group_id, p.message, p.auto_escape);
return okResponse({ message_id: result.messageId });
},
}),
defineAction({
name: 'get_msg',
summary: '获取消息',
readOnly: true,
params: { message_id: f.messageId() },
run: async (p, ctx) => {
const data = ctx.getMessage(p.message_id);
if (!data) return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
const result: JsonObject = { ...data };
delete result.post_type;
delete result.self_id;
result.real_id = (result.message_id ?? p.message_id) as JsonValue;
await refreshStoredImageUrls(result, ctx);
return okResponse(result);
},
}),
defineAction({
name: 'delete_msg',
summary: '撤回消息',
params: { message_id: f.messageId() },
run: async (p, ctx) => {
const meta = ctx.getMessageMeta(p.message_id);
if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not retractable');
await ctx.deleteMessage(p.message_id, meta);
return okResponse();
},
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}

View File

@@ -1,23 +1,42 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asString, asBoolean } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
import { defineAction, registerActions, f } from '../action-kit';
import type { ApiActionContext, ApiHandler } from '../api-handler';
import { asString } from '../api-handler';
import { okResponse } from '../types';
export const actions = [
defineAction({
name: 'set_friend_add_request',
summary: '处理好友添加请求',
params: {
flag: f.string({ allowEmpty: false }),
approve: f.bool().default(true),
},
run: async (p, ctx) => {
await ctx.bridge.apis.friend.handleRequest(p.flag, p.approve);
return okResponse();
},
}),
defineAction({
name: 'set_group_add_request',
summary: '处理加群请求',
params: {
flag: f.string({ allowEmpty: false }),
// sub_type/type pass through with a nested fallback (sub_type → type → 'add');
// kept raw so the original asString resolution is preserved verbatim.
sub_type: f.raw(),
type: f.raw(),
approve: f.bool().default(true),
reason: f.string().default(''),
},
run: async (p, ctx) => {
const subType = asString(p.sub_type, asString(p.type, 'add'));
await ctx.handleGroupRequest(p.flag, subType, p.approve, p.reason);
return okResponse();
},
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('set_friend_add_request', async (params) => {
const flag = asString(params.flag);
const approve = asBoolean(params.approve, true);
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
await ctx.bridge.apis.friend.handleRequest(flag, approve);
return okResponse();
});
h.registerAction('set_group_add_request', async (params) => {
const flag = asString(params.flag);
const subType = asString(params.sub_type, asString(params.type, 'add'));
const approve = asBoolean(params.approve, true);
const reason = asString(params.reason);
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
await ctx.handleGroupRequest(flag, subType, approve, reason);
return okResponse();
});
registerActions(h, ctx, actions);
}

View File

@@ -1,5 +1,5 @@
import { summarizeParams } from '@snowluma/common/log-summary';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { renderParamsVerbose, summarizeParams } from '@snowluma/common/log-summary';
import { createLogger, getLogLevel, nextRequestId, runWithRequestId, type Logger } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { register as registerExtended } from './actions/extended';
import { register as registerFriend } from './actions/friend';
@@ -76,6 +76,7 @@ export interface ApiActionContext {
}>;
getImageInfo: (file: string) => Promise<JsonObject | null>;
getRecordInfo: (file: string) => Promise<JsonObject | null>;
fetchPttText: (messageId: number) => Promise<{ text: string }>;
}
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
@@ -108,13 +109,33 @@ export class ApiHandler {
return failedResponse(RETCODE.UNKNOWN_ACTION, 'unknown action');
}
// Entry log goes to file always (debug); console only when level is
// dialed down to debug. Caller-perspective summary lets the operator
// grep "what did the bot get asked to do" without scraping wire logs.
this.log.debug('%s params=%s', action, summarizeParams(params));
// Correlate the whole request — entry, every outbound packet it triggers,
// and the exit — under one `[req#N]` tag via AsyncLocalStorage. Only pay
// the wrap + id allocation when trace is actually live, so the default
// path stays allocation-free.
if (getLogLevel() !== 'trace') {
return this.runAction(action, handler, params);
}
return runWithRequestId(nextRequestId(), () => this.runAction(action, handler, params));
}
private async runAction(
action: string,
handler: ActionHandler,
params: JsonObject,
): Promise<import('./types').ApiResponse> {
// Terse breadcrumb to the log file (debug, always persisted): lets the
// operator grep "what did the bot get asked to do" in post-mortems.
this.log.debug('%s params=%s', action, summarizeParams(params));
// Full request shape, memory-only (trace). Lazy producer → the deep render
// only runs when trace is live.
this.log.trace(() => [`${action} ⇐ %s`, renderParamsVerbose(params)]);
const startedAt = Date.now();
try {
return await handler(params);
const response = await handler(params);
this.log.trace(() => [`${action} ⇒ ${response.status} (${Date.now() - startedAt}ms)`]);
return response;
} catch (error) {
// Action failures are almost always param-shape problems coming
// from the OneBot client; warn (not error) is the right level so

View File

@@ -9,6 +9,7 @@ import type {
MessageFormat,
OneBotConfig,
OneBotNetworks,
StatusCommandConfig,
WsClientNetwork,
WsRole,
WsServerNetwork,
@@ -20,6 +21,14 @@ const CONFIG_DIR = 'config';
const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json');
const DEFAULT_ACCESS_TOKEN_BYTES = 32;
const DEFAULT_STATUS_COMMAND: StatusCommandConfig = { enabled: true, swallow: false, cooldownSeconds: 5 };
/** Upper bound on the `#sl` reply cooldown — a year is effectively "off but sane". */
const STATUS_COMMAND_COOLDOWN_MAX = 31_536_000;
function makeDefaultStatusCommand(): StatusCommandConfig {
return { ...DEFAULT_STATUS_COMMAND };
}
export function makeDefaultOneBotConfig(): OneBotConfig {
return {
networks: {
@@ -46,6 +55,7 @@ export function makeDefaultOneBotConfig(): OneBotConfig {
wsClients: [],
},
musicSignUrl: '',
statusCommand: makeDefaultStatusCommand(),
};
}
@@ -98,6 +108,11 @@ function toJsonObject(config: OneBotConfig): JsonObject {
wsClients: nets.wsClients.map(wsClientToJson),
},
musicSignUrl: config.musicSignUrl ?? '',
statusCommand: {
enabled: config.statusCommand.enabled,
swallow: config.statusCommand.swallow,
cooldownSeconds: config.statusCommand.cooldownSeconds,
},
};
}
@@ -181,7 +196,26 @@ function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig {
}
const networks: OneBotNetworks = { httpServers, httpClients, wsServers, wsClients };
return { networks, musicSignUrl };
return { networks, musicSignUrl, statusCommand: parseStatusCommand(sources) };
}
/** Last-write-wins merge of `statusCommand` across config sources, with
* defaults filled and the cooldown clamped to a sane non-negative range. */
function parseStatusCommand(sources: JsonObject[]): StatusCommandConfig {
const out = makeDefaultStatusCommand();
for (const src of sources) {
const raw = src.statusCommand;
if (!isObject(raw)) continue;
if (typeof raw.enabled === 'boolean') out.enabled = raw.enabled;
if (typeof raw.swallow === 'boolean') out.swallow = raw.swallow;
if (raw.cooldownSeconds !== undefined) {
out.cooldownSeconds = Math.min(
STATUS_COMMAND_COOLDOWN_MAX,
asNumber(raw.cooldownSeconds, DEFAULT_STATUS_COMMAND.cooldownSeconds),
);
}
}
return out;
}
function collectByName<T extends { name: string }>(

View File

@@ -25,7 +25,7 @@ import {
} from './to-request';
import { elementsToJson } from './to-segment';
export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string;
export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string | Promise<string>;
export type MediaUrlResolver = (element: MessageElement, isGroup: boolean, sessionId: number) => Promise<string>;
export type MessageIdResolver = (isGroup: boolean, sessionId: number, sequence: number, eventName: string) => number;

View File

@@ -32,10 +32,15 @@ export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMember
export function convertGroupMemberLeave(ctx: ConverterContext, event: GroupMemberLeave): JsonObject {
let subType: string;
if (event.isKick) {
subType = event.userUin === ctx.selfId ? 'kick_me' : 'kick';
} else {
subType = 'leave';
switch (event.leaveType) {
case 'disband':
subType = 'disband';
break;
case 'kick':
subType = event.userUin === ctx.selfId ? 'kick_me' : 'kick';
break;
default:
subType = 'leave';
}
return {
time: event.time,

View File

@@ -45,7 +45,7 @@ async function elementToSegment(
}
if (element.type === 'image') {
const url = imageUrlResolver ? imageUrlResolver(element, isGroup) : (element.imageUrl ?? '');
const url = imageUrlResolver ? await imageUrlResolver(element, isGroup) : (element.imageUrl ?? '');
const data: JsonObject = {
url,
file: element.fileId ?? '',

View File

@@ -1,26 +1,33 @@
import { createLogger, getLogLevel, nextRequestId, runWithRequestId, type Logger } from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
import type { QQEventVariant } from '@snowluma/protocol/events';
import { convertEvent } from './event-converter';
import type { OneBotInstanceContext } from './instance-context';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
import { deliverPttTransText, pttTransKey } from './modules/ptt-trans-waiter';
const moduleLog = createLogger('Event');
export function registerEventPipeline(ctx: OneBotInstanceContext): () => void {
const uinNum = Number.parseInt(ctx.uin, 10);
const log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
const disposers: Array<() => void> = [];
disposers.push(
ctx.bridge.events.on('group_message', async (event) => {
cacheGroupMessageMeta(ctx, event);
await convertAndDispatch(ctx, event);
await convertAndDispatch(ctx, log, event);
}),
);
disposers.push(
ctx.bridge.events.on('friend_message', async (event) => {
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, event.msgId);
await convertAndDispatch(ctx, event);
await convertAndDispatch(ctx, log, event);
}),
);
disposers.push(
ctx.bridge.events.on('temp_message', async (event) => {
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, 0);
await convertAndDispatch(ctx, event);
await convertAndDispatch(ctx, log, event);
}),
);
for (const kind of NOTICE_KINDS) {
@@ -29,10 +36,17 @@ export function registerEventPipeline(ctx: OneBotInstanceContext): () => void {
if (event.kind === 'group_msg_emoji_like') {
cacheReaction(ctx, event);
}
await convertAndDispatch(ctx, event);
await convertAndDispatch(ctx, log, event);
}),
);
}
// Internal-only: voice-to-text result push. Not converted to a OneBot event —
// it just unblocks the fetch_ptt_text call waiting on this msgId.
disposers.push(
ctx.bridge.events.on('ptt_trans_result', (event) => {
deliverPttTransText(pttTransKey(event.selfUin, event.msgId), event.text);
}),
);
return () => {
for (const dispose of disposers) {
@@ -58,10 +72,30 @@ const NOTICE_KINDS = [
'group_msg_emoji_like',
] as const satisfies readonly QQEventVariant['kind'][];
async function convertAndDispatch(ctx: OneBotInstanceContext, event: QQEventVariant): Promise<void> {
async function convertAndDispatch(ctx: OneBotInstanceContext, log: Logger, event: QQEventVariant): Promise<void> {
// Inbound choke point — the receive-side mirror of the outbound api-handler.
// Correlate the whole receive chain (decode → convert, incl. any rkey-fetch
// packets the conversion triggers, → dispatch) under one [req#N]. Only pay
// the AsyncLocalStorage wrap + id when trace is actually live.
if (getLogLevel() !== 'trace') {
await runConvertAndDispatch(ctx, log, event);
return;
}
await runWithRequestId(nextRequestId(), () => runConvertAndDispatch(ctx, log, event));
}
async function runConvertAndDispatch(ctx: OneBotInstanceContext, log: Logger, event: QQEventVariant): Promise<void> {
// Raw inbound event, memory-only (trace). Lazy → the deep render runs only
// when trace is live.
log.trace(() => [`recv ${event.kind} ⇐ %s`, renderParamsVerbose(event)]);
const startedAt = Date.now();
const converted = await convertEvent(ctx.converterCtx, event);
if (!converted) return;
if (!converted) {
log.trace(() => [`recv ${event.kind} ⇒ dropped (${Date.now() - startedAt}ms)`]);
return;
}
ctx.dispatchEvent(converted);
log.trace(() => [`recv ${event.kind} ⇒ ${String(converted.post_type ?? '?')} (${Date.now() - startedAt}ms)`]);
}
function cacheGroupMessageMeta(ctx: OneBotInstanceContext, event: Extract<QQEventVariant, { kind: 'group_message' }>): void {

View File

@@ -18,6 +18,7 @@ import {
getStrangerInfo,
} from './modules/contact-actions';
import {
fetchPttText as fetchPttTextAction,
getImageInfo as getCachedImageInfo,
getRecordInfo as getCachedRecordInfo,
} from './modules/media-actions';
@@ -114,8 +115,9 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
complete: cachedCount >= serverCount,
};
},
getImageInfo: (file) => getCachedImageInfo(mediaStore, file),
getImageInfo: (file) => getCachedImageInfo(mediaStore, file, ref.converterCtx.imageUrlResolver),
getRecordInfo: (file) => getCachedRecordInfo(bridge, mediaStore, file),
fetchPttText: (messageId) => fetchPttTextAction(messageStore, mediaStore, bridge, ref.selfId, messageId),
};
}

View File

@@ -15,6 +15,10 @@ interface CachedRKey {
const RKEY_REFRESH_SKEW = 60;
const RKEY_REFRESH_COOLDOWN = 30;
// Upper bound on how long URL resolution may block on a refresh round-trip.
// A stuck packet send must never wedge message conversion — past this we
// fall back to whatever the cache holds (possibly nothing).
const RKEY_REFRESH_TIMEOUT_MS = 5000;
const PRIVATE_IMAGE_RKEY_TYPE = 10;
const GROUP_IMAGE_RKEY_TYPE = 20;
const PRIVATE_VIDEO_RKEY_TYPE = 12;
@@ -26,31 +30,39 @@ const FALLBACK_IMAGE_RKEY_TYPE = 2;
export class RKeyCache {
private cache = new Map<number, CachedRKey>();
private lastRefreshAttempt = 0;
private refreshInflight: Promise<void> | null = null;
warmUp(bridge: BridgeInterface, uin: string): void {
bridge.apis.contacts.fetchDownloadRKeys().then(
(rkeys) => {
this.updateCache(rkeys);
log.info('rkeys loaded: UIN=%s count=%d', uin, rkeys.length);
},
(err) => {
log.warn('failed to load rkeys for UIN %s: %s', uin, err instanceof Error ? err.message : String(err));
},
this.ensureFresh(bridge).then(
() => log.info('rkeys loaded: UIN=%s count=%d', uin, this.cache.size),
(err) => log.warn('failed to load rkeys for UIN %s: %s', uin, err instanceof Error ? err.message : String(err)),
);
}
resolveImageUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string {
async resolveImageUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): Promise<string> {
const url = element.imageUrl ?? '';
if (!urlNeedsRKey(url)) return url;
const rkey = this.findRKey(bridge, isGroup);
// The rkey scene must follow the IMAGE's own upload context, not the
// message currently carrying it. A c2c image forwarded into a group
// keeps its original c2c fileid/appid (1406); signing it with the
// group rkey just because the forward node looks like a group message
// yields `invalid rkey` on download. So derive the scene from the
// appid baked into the URL, and only fall back to `isGroup` when the
// URL carries no recognised appid (legacy gchat / unknown shapes).
// Mirrors NapCat's getImageUrlFromParsedUrl (appid 1406 → private,
// 1407 → group).
const primaryType = imageRKeyTypeFromUrl(url)
?? (isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE);
const rkey = await this.findRKeyForType(bridge, primaryType);
if (!rkey) return url;
const cleanRKey = stripRKeyPrefix(rkey);
const separator = url.includes('?') ? '&rkey=' : '?rkey=';
return url + separator + encodeURIComponent(cleanRKey);
}
resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string {
async resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): Promise<string> {
const url = element.url ?? '';
if (!url || !urlNeedsRKey(url)) return url;
@@ -65,7 +77,7 @@ export class RKeyCache {
primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
}
const rkey = this.findRKeyForType(bridge, primaryType);
const rkey = await this.findRKeyForType(bridge, primaryType);
if (!rkey) return url;
const cleanRKey = stripRKeyPrefix(rkey);
@@ -89,33 +101,79 @@ export class RKeyCache {
}
}
private findRKey(bridge: BridgeInterface, isGroup: boolean): string | null {
const primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
return this.findRKeyForType(bridge, primaryType);
}
private findRKeyForType(bridge: BridgeInterface, primaryType: number): string | null {
/** Pull a still-valid rkey out of the cache, or null if missing/expiring. */
private findInCache(primaryType: number): string | null {
const now = Math.floor(Date.now() / 1000);
const tryFind = (type: number): string | null => {
const cached = this.cache.get(type);
if (!cached || !cached.value) return null;
if (cached.expiresAt !== 0 && now + RKEY_REFRESH_SKEW >= cached.expiresAt) return null;
return cached.value;
};
let result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
if (result) return result;
if (now - this.lastRefreshAttempt < RKEY_REFRESH_COOLDOWN) return null;
this.lastRefreshAttempt = now;
bridge.apis.contacts.fetchDownloadRKeys().then(
(rkeys) => this.updateCache(rkeys),
() => { /* ignore */ },
);
result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
return result;
return tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
}
private async findRKeyForType(bridge: BridgeInterface, primaryType: number): Promise<string | null> {
const cached = this.findInCache(primaryType);
if (cached) return cached;
// Cache miss or inside the expiry skew: block on a fresh fetch rather
// than hand back a URL with a stale/absent rkey — the CDN rejects those
// with `{"retcode":-5503010,"retmsg":"invalid rkey"}`. Mirrors NapCat's
// getImageUrl path, which does `if (isExpired()) await refreshRkey()`
// before building the URL instead of refreshing in the background.
await this.ensureFresh(bridge);
return this.findInCache(primaryType);
}
/**
* Refresh the rkey cache via OIDB 0x9067_202, coalescing concurrent
* callers onto one in-flight request and backing off for
* RKEY_REFRESH_COOLDOWN after a failed attempt so a persistently
* unreachable server isn't hammered once per inbound image. The await is
* bounded by RKEY_REFRESH_TIMEOUT_MS.
*/
private async ensureFresh(bridge: BridgeInterface): Promise<void> {
if (!this.refreshInflight) {
const now = Math.floor(Date.now() / 1000);
if (now - this.lastRefreshAttempt < RKEY_REFRESH_COOLDOWN) return;
this.lastRefreshAttempt = now;
this.refreshInflight = bridge.apis.contacts.fetchDownloadRKeys()
.then((rkeys) => { this.updateCache(rkeys); })
.catch((err) => {
log.warn('rkey refresh failed: %s', err instanceof Error ? err.message : String(err));
})
.finally(() => { this.refreshInflight = null; });
}
const inflight = this.refreshInflight;
if (!inflight) return;
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<void>((resolve) => { timer = setTimeout(resolve, RKEY_REFRESH_TIMEOUT_MS); });
try {
await Promise.race([inflight, timeout]);
} finally {
if (timer) clearTimeout(timer);
}
}
}
// QQ-NT download appids embedded in the image URL query string. The scene
// they encode is a property of the image (where it was uploaded), so they
// outrank the carrying message's group/private context — see resolveImageUrl.
const APPID_PRIVATE_IMAGE = '1406';
const APPID_GROUP_IMAGE = '1407';
/** Map the `appid` baked into an NT download URL to its rkey type. Returns
* null when the URL carries no recognised appid, leaving the caller to fall
* back to the message's group/private context. */
function imageRKeyTypeFromUrl(url: string): number | null {
const match = url.match(/[?&]appid=(\d+)/);
if (!match) return null;
if (match[1] === APPID_PRIVATE_IMAGE) return PRIVATE_IMAGE_RKEY_TYPE;
if (match[1] === APPID_GROUP_IMAGE) return GROUP_IMAGE_RKEY_TYPE;
return null;
}
function urlNeedsRKey(url: string): boolean {

View File

@@ -12,12 +12,15 @@ import { MediaStore } from './media-store';
import { MediaUrlResolver } from './media-url-resolver';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
import { MessageStore } from './message-store';
import { sendGroupMessage, sendPrivateMessage } from './modules/message-actions';
import { buildStatusText, matchesStatusCommand, statusCooldownElapsed } from './modules/status-command';
import {
HttpPostAdapter,
HttpServerAdapter,
OneBotNetworkManager,
WsClientAdapter,
WsServerAdapter,
type AdapterStatus,
type NetworkAdapterContext,
} from './network';
import { ReactionStore } from './reaction-store';
@@ -36,6 +39,11 @@ export class OneBotInstance {
private readonly reactionStore: ReactionStore;
private readonly networkManager: OneBotNetworkManager;
private readonly rkeyCache: RKeyCache;
private readonly ctx: OneBotInstanceContext;
/** Process-uptime baseline for the `#sl` status reply. */
private readonly startedAt = Date.now();
/** Per-conversation last-reply timestamp for the `#sl` cooldown. */
private readonly statusCommandCooldown = new Map<string, number>();
private disposeEventPipeline: (() => void) | null = null;
private readonly pids = new Set<number>();
@@ -46,6 +54,11 @@ export class OneBotInstance {
get nickname(): string { return this.bridge.identity.nickname; }
/** Live status of this account's OneBot network adapters. */
getConnectionStatuses(): AdapterStatus[] {
return this.networkManager.describeStatuses();
}
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) {
this.uin = uin;
this.bridge = bridge;
@@ -84,6 +97,7 @@ export class OneBotInstance {
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
dispatchEvent: (event) => this.dispatchEvent(event),
};
this.ctx = ctx;
this.apiHandler = new ApiHandler(buildApiContext(ctx), uinNum > 0 ? uinNum : undefined);
this.networkManager = new OneBotNetworkManager();
@@ -98,6 +112,9 @@ export class OneBotInstance {
}
reloadConfig(config: OneBotConfig): void {
// Keep the shared context's config in sync so live readers (e.g. the
// `#sl` handler reading `statusCommand`) pick up edits without a restart.
this.ctx.config = config;
void this.applyConfigDiff(config).catch((err) => {
this.log.warn('applyConfigDiff failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
});
@@ -139,11 +156,53 @@ export class OneBotInstance {
private dispatchEvent(event: JsonObject): void {
this.cacheMessageEvent(event);
this.logReceivedMessage(event);
// Built-in `#sl`: always cache + log first (a swallowed `#sl` is still
// observable locally); only forwarding to downstream adapters is gated.
if (this.handleStatusCommand(event)) return;
void this.networkManager.emitEvent(event).catch((err) => {
this.log.warn('emitEvent failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
});
}
/**
* Built-in `#sl` status command. Returns `true` when the event matched AND
* `swallow` is configured — the caller then skips `emitEvent` so downstream
* adapters never see it. The reply itself is fired async and rate-limited
* per conversation; matching and replying are independent of swallowing.
*/
private handleStatusCommand(event: JsonObject): boolean {
const cfg = this.ctx.config.statusCommand;
if (!cfg.enabled) return false;
const postType = event.post_type;
if (postType !== 'message' && postType !== 'message_sent') return false;
if (!matchesStatusCommand(event.message)) return false;
const isGroup = event.message_type === 'group';
const sessionId = isGroup ? toInt(event.group_id) : toInt(event.user_id);
if (sessionId === 0) return cfg.swallow;
const key = `${isGroup ? 'g' : 'p'}:${sessionId}`;
const now = Date.now();
if (statusCooldownElapsed(this.statusCommandCooldown.get(key), now, cfg.cooldownSeconds)) {
this.statusCommandCooldown.set(key, now);
void this.replyStatus(isGroup, sessionId).catch((err) => {
this.log.warn('status command reply failed: %s', err instanceof Error ? err.message : String(err));
});
}
return cfg.swallow;
}
private async replyStatus(isGroup: boolean, sessionId: number): Promise<void> {
const text = buildStatusText({
version: typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev',
platform: process.platform,
arch: process.arch,
uptimeMs: Date.now() - this.startedAt,
});
if (isGroup) await sendGroupMessage(this.ctx, sessionId, text, true);
else await sendPrivateMessage(this.ctx, sessionId, text, true);
}
private buildNetworkContext(): NetworkAdapterContext {
return {
uin: this.uin,

View File

@@ -3,10 +3,18 @@ import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { BridgeManager } from '@snowluma/core/manager';
import { loadOneBotConfig } from './config';
import { OneBotInstance } from './instance';
import type { AdapterStatus } from './network';
const log = createLogger('OneBot');
const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1';
/** Per-account OneBot connection health, surfaced to the WebUI dashboard. */
export interface AccountConnections {
uin: string;
nickname: string;
adapters: AdapterStatus[];
}
export class OneBotManager {
private readonly instances = new Map<string, OneBotInstance>();
@@ -28,6 +36,15 @@ export class OneBotManager {
return [...this.instances.values()];
}
/** Live OneBot adapter status for every account, for the WebUI dashboard. */
getConnectionStatuses(): AccountConnections[] {
return this.getInstances().map((i) => ({
uin: i.uin,
nickname: i.nickname,
adapters: i.getConnectionStatuses(),
}));
}
reloadConfig(uin: string): boolean {
const instance = this.instances.get(uin);
if (!instance) return false;

View File

@@ -1,6 +1,6 @@
import type { MessageElement } from '@snowluma/protocol/events';
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
import fs from 'fs';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import path from 'path';
export interface CachedImage {
@@ -62,17 +62,17 @@ const TYPE_VIDEO = 'video';
const DEFAULT_KEEP_ENTRIES = 4096;
export class MediaStore {
private readonly db: DatabaseType;
private readonly db: DatabaseSync;
private readonly maxEntriesPerType: number;
// Prepared statements (pay the parsing cost once at startup).
private readonly upsertEntry: Statement;
private readonly upsertKey: Statement;
private readonly findEntryByKey: Statement;
private readonly findEntryByPrimary: Statement;
private readonly evictByType: Statement;
private readonly purgeOrphanKeys: Statement;
private readonly countByType: Statement;
private readonly upsertEntry: StatementSync;
private readonly upsertKey: StatementSync;
private readonly findEntryByKey: StatementSync;
private readonly findEntryByPrimary: StatementSync;
private readonly evictByType: StatementSync;
private readonly purgeOrphanKeys: StatementSync;
private readonly countByType: StatementSync;
constructor(dbPath: string, maxEntriesPerType = DEFAULT_KEEP_ENTRIES) {
this.maxEntriesPerType = Math.max(64, maxEntriesPerType);
@@ -80,9 +80,9 @@ export class MediaStore {
const dir = path.dirname(dbPath);
fs.mkdirSync(dir, { recursive: true });
this.db = new Database(dbPath);
this.db.pragma('journal_mode = WAL');
this.db.pragma('synchronous = NORMAL');
this.db = new DatabaseSync(dbPath);
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('PRAGMA synchronous = NORMAL');
this.initSchema();
this.upsertEntry = this.db.prepare(

View File

@@ -288,8 +288,9 @@ export async function segmentToElement(type: string, data: Record<string, unknow
}
case 'file': {
const fileId = String(data.file_id ?? data.fileId ?? '').trim();
if (!fileId) {
log.warn('[MsgParser] file segment without file_id is unsupported (upload first via upload_group_file / upload_private_file)');
const source = String(data.file ?? data.url ?? data.path ?? '').trim();
if (!fileId && !source) {
log.warn('[MsgParser] file segment without file_id or file/url is unsupported');
return null;
}
const fileName = String(data.name ?? data.filename ?? data.fileName ?? '').trim();
@@ -297,7 +298,7 @@ export async function segmentToElement(type: string, data: Record<string, unknow
const md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim();
const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim();
const fileHash = String(data.file_hash ?? data.fileHash ?? '').trim();
const elem: MessageElement = { type: 'file', fileId };
const elem: MessageElement = fileId ? { type: 'file', fileId } : { type: 'file', url: source };
if (fileName) elem.fileName = fileName;
if (fileSize > 0) elem.fileSize = fileSize;
if (md5Hex) elem.md5Hex = md5Hex;

View File

@@ -1,18 +1,18 @@
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
import fs from 'fs';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import path from 'path';
import type { JsonObject, MessageMeta } from './types';
export class MessageStore {
private readonly db: DatabaseType;
private readonly stmtStoreEvent: Statement;
private readonly stmtStoreMeta: Statement;
private readonly stmtFindEvent: Statement;
private readonly stmtFindMeta: Statement;
private readonly stmtResolveReplyGroup: Statement;
private readonly stmtResolveReplyPrivate: Statement;
private readonly stmtListEventsAnchored: Statement;
private readonly stmtListEventsLatest: Statement;
private readonly db: DatabaseSync;
private readonly stmtStoreEvent: StatementSync;
private readonly stmtStoreMeta: StatementSync;
private readonly stmtFindEvent: StatementSync;
private readonly stmtFindMeta: StatementSync;
private readonly stmtResolveReplyGroup: StatementSync;
private readonly stmtResolveReplyPrivate: StatementSync;
private readonly stmtListEventsAnchored: StatementSync;
private readonly stmtListEventsLatest: StatementSync;
constructor(dbPath: string) {
const dir = path.dirname(dbPath);
@@ -20,9 +20,9 @@ export class MessageStore {
// Replace .json extension with .db if present
const finalPath = dbPath.replace(/\.json$/, '.db');
this.db = new Database(finalPath);
this.db.pragma('journal_mode = WAL');
this.db.pragma('synchronous = NORMAL');
this.db = new DatabaseSync(finalPath);
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('PRAGMA synchronous = NORMAL');
this.initSchema();
// Prepare once. Statements survive for the lifetime of the

View File

@@ -1,17 +1,106 @@
import { createLogger } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { MessageElement } from '@snowluma/protocol/events';
import type { ImageUrlResolver } from '../event-converter';
import type { MediaStore } from '../media-store';
import type { MessageStore } from '../message-store';
import {
deliverPttTransText,
failPttTransWaiter,
pttTransKey,
waitPttTransText,
} from './ptt-trans-waiter';
import type { JsonObject } from '../types';
const log = createLogger('OneBot');
/**
* Voice-to-text for a received ptt (issue #79 / NapCat `fetch_ptt_text`).
* Resolves the message's `record` segment to its cached fingerprint
* (uuid + md5 + duration/size/format), then drives QQ's native
* `pttTrans.Trans{C2C,Group}PttReq` via the bridge and returns the text.
*/
export async function fetchPttText(
messageStore: MessageStore,
mediaStore: MediaStore,
bridge: BridgeInterface,
selfId: number,
messageId: number,
): Promise<{ text: string }> {
const event = messageStore.findEvent(messageId);
if (!event) throw new Error('消息不存在或已被撤回');
const segments = Array.isArray(event.message) ? event.message : [];
let file = '';
for (const seg of segments) {
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
const so = seg as JsonObject;
if (so.type !== 'record') continue;
const data = (typeof so.data === 'object' && so.data !== null && !Array.isArray(so.data)) ? so.data as JsonObject : {};
file = String(data.file ?? data.url ?? '');
break;
}
if (!file) throw new Error('消息中不包含语音');
const cached = mediaStore.findRecord(file);
if (!cached) throw new Error('语音不在缓存中,无法转写');
const isGroup = event.message_type === 'group' || cached.isGroup;
const senderUin = Number(event.user_id) || 0;
// c2c: receiver is self (inbound voice); group: the group uin.
const peerUin = isGroup ? (Number(event.group_id) || cached.sessionId) : selfId;
// Register the waiter BEFORE triggering, so a fast async push can't race
// ahead of us. The trigger response may carry the text inline (already
// transcribed) — settle immediately then; otherwise the Event 0x210
// subType-61 push resolves the waiter via the event-pipeline subscription.
const key = pttTransKey(selfId, messageId);
const waiter = waitPttTransText(key, 20000);
try {
const syncText = await bridge.apis.extras.translatePttToText({
isGroup,
msgId: messageId,
senderUin,
peerUin,
uuid: cached.fileId || '',
md5Hex: cached.md5Hex ?? '',
duration: cached.duration ?? 0,
size: cached.fileSize ?? 0,
format: cached.voiceFormat ?? 0,
});
if (syncText) deliverPttTransText(key, syncText);
} catch (e) {
failPttTransWaiter(key, e instanceof Error ? e : new Error(String(e)));
}
return { text: await waiter };
}
export async function getImageInfo(
mediaStore: MediaStore,
file: string,
imageUrlResolver?: ImageUrlResolver | null,
): Promise<JsonObject | null> {
const cached = mediaStore.findImage(file);
if (!cached) return null;
const url = cached.url || cached.imageUrl || '';
let url = cached.url || cached.imageUrl || '';
// Re-sign with a current rkey at lookup time. The stored `url` was signed
// when the message first arrived and its rkey may have since expired — the
// CDN then rejects the download with
// `{"retcode":-5503010,"retmsg":"invalid rkey"}`. Resolving from the raw
// (unsigned) `imageUrl` mints a fresh rkey, mirroring NapCat which
// re-signs on every getImageUrl call instead of handing back a baked URL.
if (imageUrlResolver && cached.imageUrl) {
try {
const element: MessageElement = { type: 'image', imageUrl: cached.imageUrl, subType: cached.subType };
const fresh = await imageUrlResolver(element, cached.isGroup);
if (fresh) url = fresh;
} catch {
// Best-effort: fall back to the stored URL on any resolver failure.
}
}
return {
file: url || cached.file,
url,

View File

@@ -241,54 +241,40 @@ export async function sendPrivateMessage(
// never mixed with the regular elements. We only need it for file
// here — video/ARK/ptt already go through commonElem so the
// element-builder handles them inline.
const fileElements = elements.filter(e => e.type === 'file' && e.fileId);
// Two sub-paths:
// a) has url/path but no file_id → uploadPrivate() which internally calls sendC2cFile()
// b) has file_id from a prior upload_private_file → sendC2cFile() only
const allFileElements = elements.filter(e => e.type === 'file');
const nonFileElements = elements.filter(e => e.type !== 'file');
if (fileElements.length !== elements.filter(e => e.type === 'file').length) {
log.warn('[OneBot] private file segment without file_id — skipped (upload first via upload_private_file)');
}
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendPrivate>> | undefined;
if (nonFileElements.length > 0) {
lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements);
logSentMessage(false, userId, nonFileElements);
}
if (fileElements.length > 0) {
// C2C file send needs the recipient's UID — resolve once and reuse.
if (allFileElements.length > 0) {
const userUid = await ref.bridge.resolveUserUid(userId);
if (!userUid) {
throw new Error(`c2c file send: could not resolve uid for user ${userId}`);
}
for (const fileEl of fileElements) {
// C2C file send requires fileSize/fileMd5/fileName to ride on the
// wire (NotOnlineFile inside msgContent). The OneBot caller
// usually only echoes the file_id from a previous
// `upload_private_file`, so look up the rest from the upload
// cache. Inline segment fields (md5/size/name) take precedence so
// a caller that already knows everything can bypass the cache.
const cached = ref.bridge.recallUploadedFile(fileEl.fileId!);
const fileMd5 = fileEl.md5Hex
? Buffer.from(fileEl.md5Hex, 'hex')
: (cached?.fileMd5 ?? new Uint8Array(0));
const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0;
// Fall back to a generic name — the QQ server resolves the
// file by fileUuid, not name, so a missing name only affects
// the chat bubble display.
const fileName = fileEl.fileName ?? cached?.fileName ?? 'file';
const fileHash = fileEl.fileHash ?? cached?.fileHash;
if (fileSize === 0 && !cached) {
log.warn(
'[OneBot] c2c file_id=%s sent without fileSize and no upload cache — recipient may see 0 B',
fileEl.fileId,
);
if (!userUid) throw new Error(`c2c file send: could not resolve uid for user ${userId}`);
for (const fileEl of allFileElements) {
if (fileEl.url && !fileEl.fileId) {
// uploadPrivate() already calls sendC2cFile() internally — do NOT call it again.
const name = fileEl.fileName || fileEl.url.split('/').pop() || 'file';
await ref.bridge.apis.groupFile.uploadPrivate(userId, fileEl.url, name, true);
logSentMessage(false, userId, [fileEl]);
if (!lastReceipt) {
lastReceipt = { messageId: 0, sequence: 0, clientSequence: 0, random: 0, timestamp: Math.floor(Date.now() / 1000) };
}
} else if (fileEl.fileId) {
const cached = ref.bridge.recallUploadedFile(fileEl.fileId);
const fileMd5 = fileEl.md5Hex ? Buffer.from(fileEl.md5Hex, 'hex') : (cached?.fileMd5 ?? new Uint8Array(0));
const fileSize = fileEl.fileSize ?? cached?.fileSize ?? 0;
const fileName = fileEl.fileName ?? cached?.fileName ?? 'file';
const fileHash = fileEl.fileHash ?? cached?.fileHash;
lastReceipt = await ref.bridge.apis.message.sendC2cFile(userId, userUid, { fileId: fileEl.fileId, fileName, fileSize, fileMd5, fileHash });
logSentMessage(false, userId, [fileEl]);
} else {
log.warn('[OneBot] private file segment without file_id or url — skipped');
}
lastReceipt = await ref.bridge.apis.message.sendC2cFile(userId, userUid, {
fileId: fileEl.fileId!,
fileName,
fileSize,
fileMd5,
fileHash,
});
logSentMessage(false, userId, [fileEl]);
}
}
if (!lastReceipt) throw new Error('message is empty');
@@ -345,47 +331,37 @@ export async function sendGroupMessage(
});
if (elements.length === 0) throw new Error('message is empty');
// Group `{type:'file', file_id}` segments don't ride on the elems[]
// pipeline either. The QQ-NT server rejects PbSendMsg with a
// transElem(24) file payload (result=79); the correct send path is a
// dedicated OIDB call (`OidbSvcTrpcTcp.0x6d9_4`) that publishes a
// previously-uploaded file id as a chat bubble. Mirrors the c2c-file
// split below (private path) — both must be peeled off before the
// regular sendGroupMessage runs.
const fileElements = elements.filter(e => e.type === 'file' && e.fileId);
// Two sub-paths for group file segments:
// a) has url/path but no file_id → upload() which internally calls publish()
// b) has file_id from a prior upload_group_file → publish() only
const allFileElements = elements.filter(e => e.type === 'file');
const nonFileElements = elements.filter(e => e.type !== 'file');
if (fileElements.length !== elements.filter(e => e.type === 'file').length) {
log.warn('[OneBot] group file segment without file_id — skipped (upload first via upload_group_file)');
}
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendGroup>> | undefined;
if (nonFileElements.length > 0) {
lastReceipt = await ref.bridge.apis.message.sendGroup(groupId, nonFileElements);
logSentMessage(true, groupId, nonFileElements);
}
for (const fileEl of fileElements) {
// Group-file publish has no per-message sequence/random tuple to
// hash a messageId from — OIDB 0x6d9_4 is fire-and-forget on the
// wire. If this is the LAST element we still need a receipt so
// the OneBot caller can cache the id; synthesise one from the
// file_id hash + a fresh timestamp.
await ref.bridge.apis.groupFile.publish(groupId, fileEl.fileId!);
for (const fileEl of allFileElements) {
let fileId: string;
if (fileEl.url && !fileEl.fileId) {
// upload() already calls publish() internally — do NOT call publish() again.
const name = fileEl.fileName || fileEl.url.split('/').pop() || 'file';
const result = await ref.bridge.apis.groupFile.upload(groupId, fileEl.url, name, '/', true);
fileId = result.fileId ?? '';
if (!fileId) { log.warn('[OneBot] group file auto-upload returned no file_id — skipped'); continue; }
} else if (fileEl.fileId) {
fileId = fileEl.fileId;
await ref.bridge.apis.groupFile.publish(groupId, fileId);
} else {
log.warn('[OneBot] group file segment without file_id or url — skipped');
continue;
}
logSentMessage(true, groupId, [fileEl]);
if (!lastReceipt) {
// Use a hash of the fileId as a stable pseudo-id; this gets
// mixed with groupId in `hashMessageIdInt32` below.
let h = 0;
const s = fileEl.fileId ?? '';
for (let i = 0; i < s.length; i++) {
h = ((h << 5) - h + s.charCodeAt(i)) | 0;
}
lastReceipt = {
messageId: 0,
sequence: h & 0x7FFFFFFF,
clientSequence: 0,
random: h & 0x7FFFFFFF,
timestamp: Math.floor(Date.now() / 1000),
};
for (let i = 0; i < fileId.length; i++) h = ((h << 5) - h + fileId.charCodeAt(i)) | 0;
lastReceipt = { messageId: 0, sequence: h & 0x7FFFFFFF, clientSequence: 0, random: h & 0x7FFFFFFF, timestamp: Math.floor(Date.now() / 1000) };
}
}
if (!lastReceipt) throw new Error('message is empty');
@@ -675,7 +651,16 @@ export async function getForwardMessage(
for (const node of nodes) {
const isGroup = node.messageType === 'group' || (node.groupId !== undefined && node.groupId > 0);
const sessionId = isGroup ? (node.groupId ?? 0) : node.userUin;
const segments = await elementsToOneBotSegments(node.elements, isGroup, sessionId);
// Route forward nodes through the SAME resolver-equipped conversion the
// normal receive path uses (to-message.ts). Without the image/media URL
// resolvers the segments come back with raw, rkey-less download URLs —
// exactly issue #74 (`/get_forward_msg` image url 缺少 rkey). Image rkey
// re-signing is scene-aware via the appid in the URL (see instance-rkey).
const segments = await elementsToOneBotSegments(
node.elements, isGroup, sessionId,
ref.converterCtx.imageUrlResolver,
ref.converterCtx.mediaUrlResolver,
);
const sender: JsonObject = {
user_id: node.userUin,

View File

@@ -0,0 +1,56 @@
// Correlates an async voice-to-text result back to the fetch_ptt_text call
// that triggered it. QQ delivers the text via an Event 0x210 subType-61 push
// (decoded into a `ptt_trans_result` event), not in the request response — so
// the action registers a waiter keyed by `${selfUin}:${msgId}`, fires the
// trigger request, and the push subscription resolves the waiter by msgId.
interface Pending {
resolve: (text: string) => void;
reject: (err: Error) => void;
timer: ReturnType<typeof setTimeout>;
}
const pending = new Map<string, Pending>();
export function pttTransKey(selfUin: number, msgId: number): string {
return `${selfUin}:${msgId}`;
}
/**
* Register a waiter for `key`'s transcription. Rejects after `timeoutMs`.
* A new waiter for the same key supersedes (rejects) the previous one.
*/
export function waitPttTransText(key: string, timeoutMs: number): Promise<string> {
const existing = pending.get(key);
if (existing) {
clearTimeout(existing.timer);
pending.delete(key);
existing.reject(new Error('语音转文字请求被新的请求取代'));
}
return new Promise<string>((resolve, reject) => {
const timer = setTimeout(() => {
if (pending.get(key)?.timer === timer) pending.delete(key);
reject(new Error('语音转文字超时(未收到结果推送)'));
}, timeoutMs);
timer.unref?.();
pending.set(key, { resolve, reject, timer });
});
}
/** Resolve a waiting fetch_ptt_text with the recognised text. No-op if none. */
export function deliverPttTransText(key: string, text: string): void {
const p = pending.get(key);
if (!p) return;
clearTimeout(p.timer);
pending.delete(key);
p.resolve(text);
}
/** Reject a waiter (e.g. the trigger request itself failed). No-op if none. */
export function failPttTransWaiter(key: string, err: Error): void {
const p = pending.get(key);
if (!p) return;
clearTimeout(p.timer);
pending.delete(key);
p.reject(err);
}

View File

@@ -0,0 +1,82 @@
import type { JsonObject, JsonValue } from '../types';
/**
* Hardcoded trigger for the built-in status command — exact match,
* case-insensitive, after trimming. Intentionally NOT configurable: the
* `statusCommand.enabled` toggle is the only knob (the gate is on/off, not
* the word).
*/
export const STATUS_COMMAND_TRIGGER = '#sl';
/**
* True iff `message` is exactly the trigger: a single `text` segment (or a
* bare string for string-format adapters) whose trimmed, lowercased content
* equals {@link STATUS_COMMAND_TRIGGER}.
*
* Reads the segment array rather than `raw_message` to avoid CQ-encoding
* ambiguity, and rejects mixed-segment messages (`#sl` + image/at/reply) so
* only a pure `#sl` triggers — no `startsWith`, so `#slogan` never matches.
*/
export function matchesStatusCommand(message: JsonValue | undefined): boolean {
if (typeof message === 'string') {
return normalize(message) === STATUS_COMMAND_TRIGGER;
}
if (!Array.isArray(message) || message.length !== 1) return false;
const seg = message[0];
if (!isObject(seg) || seg.type !== 'text') return false;
const data = isObject(seg.data) ? seg.data : null;
const text = data && typeof data.text === 'string' ? data.text : '';
return normalize(text) === STATUS_COMMAND_TRIGGER;
}
function normalize(s: string): string {
return s.trim().toLowerCase();
}
function isObject(value: unknown): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
/**
* Whether a reply is allowed now given the last reply time + cooldown.
* `cooldownSeconds <= 0` disables the cooldown entirely.
*/
export function statusCooldownElapsed(
lastRepliedAtMs: number | undefined,
nowMs: number,
cooldownSeconds: number,
): boolean {
if (lastRepliedAtMs === undefined) return true;
if (cooldownSeconds <= 0) return true;
return nowMs - lastRepliedAtMs >= cooldownSeconds * 1000;
}
export interface StatusInfo {
version: string;
platform: string;
arch: string;
uptimeMs: number;
}
/** Render the public-safe `#sl` reply: version + platform/arch + uptime. */
export function buildStatusText(info: StatusInfo): string {
return [
'SnowLuma 状态',
`版本: ${info.version}`,
`平台: ${info.platform}-${info.arch}`,
`运行时长: ${formatUptime(info.uptimeMs)}`,
].join('\n');
}
/** Human-readable uptime (zh-CN), dropping leading zero units. */
export function formatUptime(ms: number): string {
const totalSec = Math.max(0, Math.floor(ms / 1000));
const days = Math.floor(totalSec / 86400);
const hours = Math.floor((totalSec % 86400) / 3600);
const minutes = Math.floor((totalSec % 3600) / 60);
const seconds = totalSec % 60;
if (days > 0) return `${days}天 ${hours}小时 ${minutes}分钟`;
if (hours > 0) return `${hours}小时 ${minutes}分钟`;
if (minutes > 0) return `${minutes}分钟 ${seconds}秒`;
return `${seconds}秒`;
}

View File

@@ -1,3 +1,4 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { ApiHandler } from '../api-handler';
import type { DispatchPayload } from '../event-filter';
import type { JsonObject, NetworkBase } from '../types';
@@ -16,16 +17,33 @@ export enum NetworkReloadType {
Opened = 3,
}
export type AdapterStatusLevel = 'ok' | 'warn' | 'down' | 'disabled';
/** Live runtime status of a single network adapter, surfaced to the WebUI
* dashboard (and the per-node config cards) so the gateway's own
* connection health is visible. `detail` is a short human string, e.g.
* "3 个客户端" / "重连中" / "上次推送失败 14:53:01". */
export interface AdapterStatus {
name: string;
kind: 'httpServer' | 'httpClient' | 'wsServer' | 'wsClient';
status: AdapterStatusLevel;
detail: string;
}
export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
readonly name: string;
protected config: C;
protected readonly ctx: NetworkAdapterContext;
protected readonly log: Logger;
protected isEnabled = false;
constructor(name: string, config: C, ctx: NetworkAdapterContext) {
constructor(name: string, config: C, ctx: NetworkAdapterContext, moduleLog?: Logger) {
this.name = name;
this.config = structuredClone(config);
this.ctx = ctx;
const base = moduleLog ?? createLogger('OneBot.Network');
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? base.child({ uin: uinNum }) : base;
}
get isActive(): boolean { return this.isEnabled; }
@@ -34,7 +52,63 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
abstract open(): void | Promise<void>;
abstract close(): void | Promise<void>;
abstract reload(config: C): NetworkReloadType | Promise<NetworkReloadType>;
abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise<void>;
/** Report live connection health for the WebUI dashboard. */
abstract describeStatus(): AdapterStatus;
// ── reload: shared hot-reload state machine (template method) ──────────
//
// All four adapters reconcile a live config swap identically: decide
// whether the binding changed, whether the adapter should be enabled, and
// then open/close to reach the target state. The skeleton lives here; the
// three things that genuinely differ per adapter are the hooks below.
//
// NOTE: the returned `NetworkReloadType` is a *test-observability* seam.
// The sole production caller (`instance.applyConfigDiff`) discards it —
// it exists so tests can assert "which transition did this config cause"
// without poking private state. Behaviour, not the label, is the contract.
/** Stable string identity of the bound resource (host:port / url / token …).
* A change here means the live binding must be torn down and re-opened. */
protected abstract bindingSignature(config: C): string;
/** Whether `config` should result in an enabled adapter. Defaults to the
* `enabled` flag; client adapters also require a target `url`. */
protected willEnable(config: C): boolean {
return config.enabled !== false;
}
/** Refresh derived state after `this.config` has been replaced (report
* options, role, propagation to live connections). Default: nothing. */
protected onConfigReplaced(_next: C): void { /* no-op */ }
async reload(next: C): Promise<NetworkReloadType> {
const prevSig = this.bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = this.willEnable(next);
this.config = structuredClone(next);
this.onConfigReplaced(next);
const sigChanged = prevSig !== this.bindingSignature(next);
if (sigChanged && wasEnabled) {
await this.close();
if (willEnable) {
await this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
await this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
await this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
}

View File

@@ -1,4 +1,4 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import { createLogger } from '@snowluma/common/logger';
import {
pickDispatchJson,
resolveReportOptions,
@@ -6,7 +6,7 @@ import {
type EventReportOptions,
} from '../event-filter';
import type { HttpClientNetwork, JsonObject } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { executeQuickOperation } from './quick-operation';
const moduleLog = createLogger('OneBot.POST');
@@ -14,19 +14,11 @@ const DEFAULT_TIMEOUT_MS = 5000;
export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
private options: EventReportOptions;
private signature_: string;
private readonly log: Logger;
private lastDelivery: { at: number; ok: boolean } | null = null;
constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
super(name, config, ctx, moduleLog);
this.options = resolveReportOptions(config);
this.signature_ = bindingSignature(config);
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
@@ -39,33 +31,25 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
this.isEnabled = false;
}
async reload(next: HttpClientNetwork): Promise<NetworkReloadType> {
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false && !!next.url;
override describeStatus(): AdapterStatus {
if (!this.isEnabled) return { name: this.name, kind: 'httpClient', status: 'disabled', detail: '未启用' };
if (!this.lastDelivery) return { name: this.name, kind: 'httpClient', status: 'ok', detail: '已启用' };
const at = new Date(this.lastDelivery.at).toTimeString().slice(0, 8);
return this.lastDelivery.ok
? { name: this.name, kind: 'httpClient', status: 'ok', detail: `上次推送成功 ${at}` }
: { name: this.name, kind: 'httpClient', status: 'warn', detail: `上次推送失败 ${at}` };
}
this.config = structuredClone(next);
protected override bindingSignature(config: HttpClientNetwork): string {
return `${config.url}#${config.accessToken ?? ''}#${config.timeoutMs ?? DEFAULT_TIMEOUT_MS}`;
}
protected override willEnable(config: HttpClientNetwork): boolean {
return config.enabled !== false && !!config.url;
}
protected override onConfigReplaced(next: HttpClientNetwork): void {
this.options = resolveReportOptions(next);
const newSig = bindingSignature(next);
const sigChanged = newSig !== this.signature_;
this.signature_ = newSig;
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(event: JsonObject, payload: DispatchPayload): void {
@@ -98,6 +82,7 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
signal: AbortSignal.timeout(timeoutMs),
});
if (response.ok) {
this.lastDelivery = { at: Date.now(), ok: true };
const contentType = response.headers.get('content-type') ?? '';
if (contentType.includes('application/json')) {
const body = await response.text();
@@ -106,9 +91,11 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
}
}
} else {
this.lastDelivery = { at: Date.now(), ok: false };
this.log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status);
}
} catch (error) {
this.lastDelivery = { at: Date.now(), ok: false };
if (this.isEnabled) {
this.log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error));
}
@@ -126,10 +113,6 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
}
}
function bindingSignature(net: HttpClientNetwork): string {
return `${net.url}#${net.accessToken ?? ''}#${net.timeoutMs ?? DEFAULT_TIMEOUT_MS}`;
}
async function computeHmacSha1(secret: string, payload: string): Promise<string> {
const { createHmac } = await import('crypto');
return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex');

View File

@@ -1,4 +1,4 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import { createLogger } from '@snowluma/common/logger';
import {
createServer,
type IncomingMessage,
@@ -7,23 +7,17 @@ import {
} from 'http';
import type { DispatchPayload } from '../event-filter';
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath } from './utils';
const moduleLog = createLogger('OneBot.HTTP');
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
private server: Server | null = null;
private readonly log: Logger;
private listening = false;
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
return this.isEnabled;
super(name, config, ctx, moduleLog);
}
open(): void {
@@ -36,35 +30,19 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
close(): void {
if (!this.isEnabled && !this.server) return;
this.isEnabled = false;
this.listening = false;
this.server?.close();
this.server = null;
}
async reload(next: HttpServerNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false;
override describeStatus(): AdapterStatus {
if (!this.isEnabled) return { name: this.name, kind: 'httpServer', status: 'disabled', detail: '未启用' };
if (!this.listening) return { name: this.name, kind: 'httpServer', status: 'down', detail: '未监听(端口被占用?)' };
return { name: this.name, kind: 'httpServer', status: 'ok', detail: '监听中' };
}
this.config = structuredClone(next);
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
protected override bindingSignature(config: HttpServerNetwork): string {
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path ?? '/')}`;
}
onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ }
@@ -76,6 +54,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
this.server = server;
server.on('listening', () => {
this.listening = true;
this.log.success(
'[%s] listening %s:%d%s',
this.name,
@@ -85,6 +64,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
);
});
server.on('error', (err) => {
this.listening = false;
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
});
@@ -213,10 +193,6 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
}
}
function bindingSignature(net: HttpServerNetwork): string {
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path ?? '/')}`;
}
function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];

View File

@@ -1,4 +1,10 @@
export { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
export {
IOneBotNetworkAdapter,
NetworkReloadType,
type AdapterStatus,
type AdapterStatusLevel,
type NetworkAdapterContext,
} from './adapter';
export { HttpPostAdapter } from './http-post-adapter';
export { HttpServerAdapter } from './http-server-adapter';
export { OneBotNetworkManager } from './network-manager';

View File

@@ -1,7 +1,7 @@
import { createLogger } from '@snowluma/common/logger';
import { buildDispatchPayload } from '../event-filter';
import type { JsonObject, NetworkBase } from '../types';
import { IOneBotNetworkAdapter } from './adapter';
import { IOneBotNetworkAdapter, type AdapterStatus } from './adapter';
const log = createLogger('OneBot.Network');
@@ -30,6 +30,11 @@ export class OneBotNetworkManager {
list(): AnyAdapter[] { return [...this.adapters.values()]; }
/** Live status of every registered adapter, for the WebUI dashboard. */
describeStatuses(): AdapterStatus[] {
return this.list().map((a) => a.describeStatus());
}
hasActiveAdapters(): boolean {
for (const a of this.adapters.values()) if (a.isActive) return true;
return false;

View File

@@ -1,5 +1,5 @@
import { WebSocket } from '@snowluma/websocket';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { createLogger } from '@snowluma/common/logger';
import {
pickDispatchJson,
resolveReportOptions,
@@ -8,7 +8,7 @@ import {
type EventReportOptions,
} from '../event-filter';
import type { JsonObject, WsClientNetwork, WsRole } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { rawDataToString, safeClose, safeSend } from './utils';
const moduleLog = createLogger('OneBot.WS-Client');
@@ -16,22 +16,16 @@ const DEFAULT_RECONNECT_INTERVAL_MS = 5000;
export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
private socket: WebSocket | null = null;
private connected = false;
private reconnectTimer: NodeJS.Timeout | null = null;
private options: EventReportOptions;
private role: WsRole;
private explicitlyClosed = false;
private readonly log: Logger;
constructor(name: string, config: WsClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
super(name, config, ctx, moduleLog);
this.options = resolveReportOptions(config);
this.role = config.role ?? 'Universal';
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
@@ -46,6 +40,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
close(): void {
this.explicitlyClosed = true;
this.isEnabled = false;
this.connected = false;
this.cancelReconnect();
if (this.socket) {
safeClose(this.socket);
@@ -53,33 +48,23 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
}
}
async reload(next: WsClientNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false && !!next.url;
override describeStatus(): AdapterStatus {
if (!this.isEnabled) return { name: this.name, kind: 'wsClient', status: 'disabled', detail: '未启用' };
if (this.connected) return { name: this.name, kind: 'wsClient', status: 'ok', detail: '已连接' };
return { name: this.name, kind: 'wsClient', status: 'warn', detail: this.reconnectTimer ? '重连中' : '连接中' };
}
this.config = structuredClone(next);
protected override bindingSignature(config: WsClientNetwork): string {
return `${config.url}#${config.role ?? 'Universal'}#${Math.max(1000, config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${config.accessToken ?? ''}`;
}
protected override willEnable(config: WsClientNetwork): boolean {
return config.enabled !== false && !!config.url;
}
protected override onConfigReplaced(next: WsClientNetwork): void {
this.options = resolveReportOptions(next);
this.role = next.role ?? 'Universal';
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
@@ -108,6 +93,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
this.socket = socket;
socket.on('open', () => {
this.connected = true;
this.log.info('[%s] connected %s', this.name, this.config.url);
this.sendBootstrapMetaEvents(socket);
});
@@ -120,6 +106,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
socket.on('close', () => {
this.socket = null;
this.connected = false;
if (this.explicitlyClosed || !this.isEnabled) return;
this.scheduleReconnect();
});
@@ -171,6 +158,3 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
}
}
function bindingSignature(net: WsClientNetwork): string {
return `${net.url}#${net.role ?? 'Universal'}#${Math.max(1000, net.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${net.accessToken ?? ''}`;
}

View File

@@ -1,6 +1,6 @@
import { WebSocket, WebSocketServer } from '@snowluma/websocket';
import type { IncomingMessage } from 'http';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { createLogger } from '@snowluma/common/logger';
import {
pickDispatchJson,
resolveReportOptions,
@@ -9,7 +9,7 @@ import {
type EventReportOptions,
} from '../event-filter';
import type { JsonObject, WsRole, WsServerNetwork } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend } from './utils';
const moduleLog = createLogger('OneBot.WS-Server');
@@ -22,19 +22,13 @@ interface ForwardConn {
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
private wss: WebSocketServer | null = null;
private listening = false;
private connections = new Map<WebSocket, ForwardConn>();
private options: EventReportOptions;
private readonly log: Logger;
constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
super(name, config, ctx, moduleLog);
this.options = resolveReportOptions(config);
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
@@ -57,39 +51,26 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
}
this.isEnabled = false;
this.listening = false;
for (const ws of [...this.connections.keys()]) safeClose(ws);
this.connections.clear();
this.wss?.close();
this.wss = null;
}
async reload(next: WsServerNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false;
override describeStatus(): AdapterStatus {
if (!this.isEnabled) return { name: this.name, kind: 'wsServer', status: 'disabled', detail: '未启用' };
if (!this.listening) return { name: this.name, kind: 'wsServer', status: 'down', detail: '未监听(端口被占用?)' };
return { name: this.name, kind: 'wsServer', status: 'ok', detail: `${this.connections.size} 个客户端` };
}
this.config = structuredClone(next);
protected override bindingSignature(config: WsServerNetwork): string {
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path)}#${config.role ?? 'auto'}#${config.accessToken ?? ''}`;
}
protected override onConfigReplaced(next: WsServerNetwork): void {
this.options = resolveReportOptions(next);
for (const conn of this.connections.values()) conn.options = this.options;
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
@@ -111,6 +92,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
this.wss = wss;
wss.on('listening', () => {
this.listening = true;
this.log.success(
'[%s] listening %s:%d%s',
this.name,
@@ -121,6 +103,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
});
wss.on('error', (err: Error) => {
this.listening = false;
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
});
@@ -178,7 +161,3 @@ function classifyForwardRole(request: IncomingMessage): WsRole {
if (path.endsWith('/event')) return 'Event';
return 'Universal';
}
function bindingSignature(net: WsServerNetwork): string {
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path)}#${net.role ?? 'auto'}#${net.accessToken ?? ''}`;
}

View File

@@ -1,21 +1,21 @@
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
import fs from 'fs';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import path from 'path';
export class ReactionStore {
private readonly db: DatabaseType;
private readonly stmtUpsert: Statement;
private readonly stmtRemove: Statement;
private readonly stmtList: Statement;
private readonly stmtCount: Statement;
private readonly stmtCountByEmoji: Statement;
private readonly db: DatabaseSync;
private readonly stmtUpsert: StatementSync;
private readonly stmtRemove: StatementSync;
private readonly stmtList: StatementSync;
private readonly stmtCount: StatementSync;
private readonly stmtCountByEmoji: StatementSync;
constructor(dbPath: string) {
const dir = path.dirname(dbPath);
fs.mkdirSync(dir, { recursive: true });
this.db = new Database(dbPath);
this.db.pragma('journal_mode = WAL');
this.db.pragma('synchronous = NORMAL');
this.db = new DatabaseSync(dbPath);
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('PRAGMA synchronous = NORMAL');
this.initSchema();
this.stmtUpsert = this.db.prepare(

View File

@@ -63,11 +63,29 @@ export interface OneBotNetworks {
wsClients: WsClientNetwork[];
}
/**
* Built-in `#sl` status command. The trigger word is hardcoded (`#sl`,
* exact match, case-insensitive); only these toggles are configurable.
*/
export interface StatusCommandConfig {
/** Master on/off. Default `true` — built-in, but freely disableable. */
enabled: boolean;
/**
* When `true`, a matched `#sl` is NOT forwarded to downstream adapters
* (it is still cached, logged, and replied to). Default `false` (pass-through).
*/
swallow: boolean;
/** Per-conversation reply cooldown in seconds. `0` disables it. Default `5`. */
cooldownSeconds: number;
}
/** Per-UIN OneBot configuration. */
export interface OneBotConfig {
networks: OneBotNetworks;
/** Music card signing service URL (optional). */
musicSignUrl?: string;
/** Built-in `#sl` status command settings. Always present after normalization. */
statusCommand: StatusCommandConfig;
}
export interface MessageMeta {

View File

@@ -0,0 +1,31 @@
// Tests the self-generated docs (D4): the describe()-walker aggregates every
// declarative action and renders coherent metadata/markdown.
import { describe, it, expect } from 'vitest';
import { collectActionDocs, renderActionDocsMarkdown } from '../src/action-docs';
describe('action-docs', () => {
const docs = collectActionDocs();
it('covers the migrated declarative actions with unique names', () => {
expect(docs.length).toBeGreaterThanOrEqual(120);
const names = docs.map((d) => d.name);
expect(new Set(names).size).toBe(names.length); // no duplicates
});
it('surfaces preset-injected fields + defaults (set_group_ban)', () => {
const ban = docs.find((d) => d.name === 'set_group_ban');
expect(ban).toBeDefined();
expect(ban!.params.map((p) => p.name)).toEqual(['group_id', 'user_id', 'duration']);
const groupId = ban!.params.find((p) => p.name === 'group_id')!;
expect(groupId).toMatchObject({ type: 'uint', required: true });
const duration = ban!.params.find((p) => p.name === 'duration')!;
expect(duration).toMatchObject({ type: 'int', required: false, default: 1800 });
});
it('renders markdown with header + an action section', () => {
const md = renderActionDocsMarkdown(docs);
expect(md).toContain('# OneBot Actions');
expect(md).toContain('`set_group_ban`');
expect(md).toContain('| 参数 | 类型 | 必填 | 默认 | 说明 |');
});
});

View File

@@ -0,0 +1,220 @@
// Interface tests for action-kit — the deepened param-validation module.
// The interface IS the test surface: we drive `parse()` (pure, no ctx) for
// coercion/validation/cross-field, `describe()` for doc metadata, and
// `toHandler()` for the BAD_REQUEST shaping + ctx threading.
import { describe, it, expect } from 'vitest';
import { f, defineAction, groupUserAction, type CoerceResult } from '../src/action-kit';
import type { ApiActionContext } from '../src/api-handler';
import { RETCODE, okResponse } from '../src/types';
const ctx = {} as unknown as ApiActionContext;
function expectErr<T>(r: CoerceResult<T>): { field: string; reason: string } {
if (r.ok) throw new Error(`expected Err, got Ok(${JSON.stringify(r.value)})`);
return { field: r.field, reason: r.reason };
}
function expectOk<T>(r: CoerceResult<T>): T {
if (!r.ok) throw new Error(`expected Ok, got Err(${r.field}: ${r.reason})`);
return r.value;
}
describe('f.uint — positive integer, missing≠0', () => {
const spec = defineAction({ name: 't', params: { x: f.uint() }, run: () => okResponse() });
it('accepts number and numeric string, truncates', () => {
expect(expectOk(spec.parse({ x: 123 }))).toEqual({ x: 123 });
expect(expectOk(spec.parse({ x: '456' }))).toEqual({ x: 456 });
expect(expectOk(spec.parse({ x: 5.7 }))).toEqual({ x: 5 });
});
it('rejects missing / 0 / negative / garbage, naming the field', () => {
expect(expectErr(spec.parse({})).field).toBe('x');
expect(expectErr(spec.parse({})).reason).toBe('is required');
expect(expectErr(spec.parse({ x: 0 })).field).toBe('x'); // 0 is not a valid id
expect(expectErr(spec.parse({ x: -3 })).field).toBe('x');
expect(expectErr(spec.parse({ x: 'abc' })).field).toBe('x');
});
});
describe('f.int({min:0}).default — the duration / unmute fix', () => {
const spec = defineAction({ name: 't', params: { d: f.int({ min: 0 }).default(1800) }, run: () => okResponse() });
it('missing ⇒ default; present 0 ⇒ 0 (not the default); negative ⇒ err', () => {
expect(expectOk(spec.parse({}))).toEqual({ d: 1800 });
expect(expectOk(spec.parse({ d: 0 }))).toEqual({ d: 0 }); // the bug the old `|| 1800` had
expect(expectErr(spec.parse({ d: -1 })).field).toBe('d');
});
it('present garbage is an error, not a silent fallback', () => {
expect(expectErr(spec.parse({ d: 'abc' })).field).toBe('d');
});
});
describe('f.messageId — non-zero integer, negatives allowed', () => {
const spec = defineAction({ name: 't', params: { id: f.messageId() }, run: () => okResponse() });
it('accepts negative ids (signed int32 hash), rejects 0 and garbage', () => {
expect(expectOk(spec.parse({ id: -2147483648 }))).toEqual({ id: -2147483648 });
expect(expectOk(spec.parse({ id: 123 }))).toEqual({ id: 123 });
expect(expectErr(spec.parse({ id: 0 })).reason).toBe('must not be 0');
expect(expectErr(spec.parse({ id: 'x' })).field).toBe('id');
});
});
describe('f.bool / f.string / f.enum', () => {
it('bool synonyms', () => {
const s = defineAction({ name: 't', params: { b: f.bool() }, run: () => okResponse() });
expect(expectOk(s.parse({ b: 'on' }))).toEqual({ b: true });
expect(expectOk(s.parse({ b: 0 }))).toEqual({ b: false });
expect(expectErr(s.parse({ b: 'maybe' })).field).toBe('b');
});
it('string allowEmpty toggle', () => {
const s = defineAction({ name: 't', params: { c: f.string({ allowEmpty: false }) }, run: () => okResponse() });
expect(expectErr(s.parse({ c: '' })).field).toBe('c');
expect(expectOk(s.parse({ c: 'x' }))).toEqual({ c: 'x' });
});
it('enum literal set', () => {
const s = defineAction({ name: 't', params: { e: f.enum('a', 'b') }, run: () => okResponse() });
expect(expectOk(s.parse({ e: 'a' }))).toEqual({ e: 'a' });
expect(expectErr(s.parse({ e: 'c' })).field).toBe('e');
});
});
describe('f.array(...).nonEmpty — per-element + non-empty', () => {
const spec = defineAction({ name: 't', params: { ids: f.array(f.uint()).nonEmpty() }, run: () => okResponse() });
it('accepts a non-empty uint array', () => {
expect(expectOk(spec.parse({ ids: [1, 2, 3] }))).toEqual({ ids: [1, 2, 3] });
});
it('rejects empty and names the bad element index', () => {
expect(expectErr(spec.parse({ ids: [] })).field).toBe('ids');
expect(expectErr(spec.parse({ ids: [1, 'x'] })).field).toBe('ids[1]');
});
});
describe('f.message — union passthrough + JSON-array string', () => {
const spec = defineAction({ name: 't', params: { m: f.message() }, run: () => okResponse() });
it('parses a JSON-array string, passes plain string / array through', () => {
expect(expectOk(spec.parse({ m: '[{"type":"text","data":{"text":"hi"}}]' })).m).toEqual([
{ type: 'text', data: { text: 'hi' } },
]);
expect(expectOk(spec.parse({ m: 'hello' })).m).toBe('hello');
expect(expectOk(spec.parse({ m: [{ type: 'face' }] })).m).toEqual([{ type: 'face' }]);
});
it('required when missing', () => {
expect(expectErr(spec.parse({})).reason).toBe('is required');
});
});
describe('optional fields', () => {
const spec = defineAction({ name: 't', params: { x: f.uint().optional() }, run: () => okResponse() });
it('missing ⇒ undefined value, present-invalid ⇒ err', () => {
expect(expectOk(spec.parse({}))).toEqual({ x: undefined });
expect(expectErr(spec.parse({ x: 'abc' })).field).toBe('x');
});
});
describe('cross-field rules', () => {
const spec = defineAction({
name: 'set_msg_emoji_like',
params: {
message_id: f.uint().optional(),
group_id: f.uint().optional(),
user_id: f.uint().optional(),
emoji_id: f.uint(),
},
rules: (r) => [r.exactlyOneOf('message_id', ['group_id', 'user_id'])],
run: () => okResponse(),
});
it('passes when exactly one locator group present', () => {
expect(spec.parse({ message_id: 5, emoji_id: 1 }).ok).toBe(true);
expect(spec.parse({ group_id: 9, user_id: 8, emoji_id: 1 }).ok).toBe(true);
});
it('fails when zero or both groups present', () => {
expect(expectErr(spec.parse({ emoji_id: 1 })).reason).toContain('exactly one of');
expect(expectErr(spec.parse({ message_id: 5, group_id: 9, user_id: 8, emoji_id: 1 })).reason).toContain('exactly one of');
});
it('field errors take priority over rule errors (per-field first)', () => {
expect(expectErr(spec.parse({ emoji_id: 0 })).field).toBe('emoji_id');
});
});
describe('toHandler — BAD_REQUEST shaping + ctx threading', () => {
const spec = groupUserAction({
name: 'set_group_ban',
params: { duration: f.int({ min: 0 }).default(1800) },
run: (p) => okResponse({ seen: [p.group_id, p.user_id, p.duration] }),
});
it('success path returns run output with typed/defaulted params', async () => {
const res = await spec.toHandler(ctx)({ group_id: 10, user_id: 20 });
expect(res).toMatchObject({ status: 'ok', retcode: 0, data: { seen: [10, 20, 1800] } });
});
it('bad params ⇒ BAD_REQUEST naming the field (not INTERNAL_ERROR)', async () => {
const res = await spec.toHandler(ctx)({ user_id: 20 }); // missing group_id
expect(res.retcode).toBe(RETCODE.BAD_REQUEST);
expect(res.status).toBe('failed');
expect(res.wording).toContain('group_id');
});
});
describe('run raw escape hatch — original params as 3rd arg', () => {
it('exposes untouched params for undeclared keys (alias fallbacks etc.)', async () => {
const spec = defineAction({
name: 't',
params: { user_id: f.uint() },
run: (_p, _ctx, raw) => okResponse({ extra: (raw.long_nick ?? raw.longNick ?? null) as never }),
});
const res = await spec.toHandler(ctx)({ user_id: 1, longNick: 'hi' });
expect(res).toMatchObject({ status: 'ok', data: { extra: 'hi' } });
});
});
describe('toJsonSchema / inputSchema (for the MCP)', () => {
it('emits a JSON Schema fragment per coercer', () => {
expect(f.uint().toJsonSchema()).toEqual({ type: 'integer', minimum: 1 });
expect(f.messageId().toJsonSchema()).toEqual({ type: 'integer', not: { const: 0 } });
expect(f.int({ min: 0 }).default(1800).toJsonSchema()).toEqual({ type: 'integer', minimum: 0, default: 1800 });
expect(f.string({ allowEmpty: false }).toJsonSchema()).toEqual({ type: 'string', minLength: 1 });
expect(f.bool().toJsonSchema()).toEqual({ type: 'boolean' });
expect(f.enum('a', 'b').toJsonSchema()).toEqual({ enum: ['a', 'b'] });
expect(f.array(f.uint()).nonEmpty().toJsonSchema()).toEqual({
type: 'array',
items: { type: 'integer', minimum: 1 },
minItems: 1,
});
expect(f.uint().describe('群号').toJsonSchema()).toEqual({ type: 'integer', minimum: 1, description: '群号' });
});
it('composes an action inputSchema (object + required + defaults)', () => {
const spec = groupUserAction({
name: 'set_group_ban',
params: { duration: f.int({ min: 0 }).default(1800) },
run: () => okResponse(),
});
const { inputSchema } = spec.describe();
expect(inputSchema).toMatchObject({
type: 'object',
additionalProperties: true,
required: ['group_id', 'user_id'],
properties: {
group_id: { type: 'integer', minimum: 1 },
user_id: { type: 'integer', minimum: 1 },
duration: { type: 'integer', minimum: 0, default: 1800 },
},
});
});
});
describe('describe — doc metadata for self-generated docs (D4)', () => {
const spec = groupUserAction({
name: ['set_group_ban', 'ban'],
summary: 'Mute a member',
params: { duration: f.int({ min: 0 }).default(1800).describe('seconds; 0 unmutes') },
run: () => okResponse(),
});
it('exposes name, aliases, and per-param metadata (incl. preset-injected fields)', () => {
const doc = spec.describe();
expect(doc.name).toBe('set_group_ban');
expect(doc.aliases).toEqual(['ban']);
expect(doc.summary).toBe('Mute a member');
const names = doc.params.map((p) => p.name);
expect(names).toEqual(['group_id', 'user_id', 'duration']); // presets surfaced
const duration = doc.params.find((p) => p.name === 'duration');
expect(duration).toMatchObject({ type: 'int', required: false, default: 1800, desc: 'seconds; 0 unmutes' });
});
});

View File

@@ -0,0 +1,224 @@
// Base-level test for the reload state machine that `IOneBotNetworkAdapter`
// now owns (the template method lifted out of all four concrete adapters).
//
// It imports `../src/network/adapter` DIRECTLY rather than the `../src/network`
// barrel on purpose: the barrel re-exports the ws adapters, which pull in
// `@snowluma/websocket`'s native addon — absent in a plain checkout. The base
// class has no such dependency, so the state machine is testable in isolation.
//
// A `ProbeAdapter` deliberately does NOT override `reload()`: it exercises the
// inherited template, with `open()`/`close()` reduced to call-counters so each
// test can assert exactly which transition the template drove (and that the
// returned `NetworkReloadType` — a test-only observability seam — matches).
import { describe, expect, it } from 'vitest';
import {
IOneBotNetworkAdapter,
NetworkReloadType,
type AdapterStatus,
type NetworkAdapterContext,
} from '../src/network/adapter';
import type { NetworkBase } from '../src/types';
interface ProbeConfig extends NetworkBase {
/** The only field `bindingSignature` reads — lets a test flip the binding
* independently of `enabled` / `url`. */
sig?: string;
/** Present only so the client-style `willEnable` override has something to
* require. */
url?: string;
}
const CTX: NetworkAdapterContext = {
uin: '10001',
api: {} as never,
buildLifecycleEvent: () => ({}),
buildHeartbeatEvent: () => ({}),
};
class ProbeAdapter extends IOneBotNetworkAdapter<ProbeConfig> {
opens = 0;
closes = 0;
configReplaced = 0;
constructor(name: string, config: ProbeConfig, private readonly requireUrl = false) {
super(name, config, CTX);
}
open(): void {
this.opens++;
// Faithful to the real adapters: only actually enable when the config says
// so. The template should only ever call open() when willEnable is true,
// so this doubles as an invariant check.
if (this.willEnable(this.config)) this.isEnabled = true;
}
close(): void {
this.closes++;
this.isEnabled = false;
}
onEvent(): void { /* unused here */ }
describeStatus(): AdapterStatus {
return { name: this.name, kind: 'httpServer', status: this.isEnabled ? 'ok' : 'disabled', detail: '' };
}
protected bindingSignature(config: ProbeConfig): string {
return config.sig ?? 'fixed';
}
// Mirrors the client adapters (ws-client / http-post): also requires a url.
protected override willEnable(config: ProbeConfig): boolean {
return config.enabled !== false && (!this.requireUrl || !!config.url);
}
protected override onConfigReplaced(_next: ProbeConfig): void {
this.configReplaced++;
}
}
function cfg(partial: Partial<ProbeConfig> = {}): ProbeConfig {
return { name: 'probe', enabled: true, sig: 'A', messageFormat: 'array', reportSelfMessage: false, ...partial };
}
/** Build a probe, optionally bring it to the enabled state, then zero the
* counters so a test observes only reload-driven open/close calls. */
function makeProbe(initial: Partial<ProbeConfig>, opts: { requireUrl?: boolean; open?: boolean } = {}): ProbeAdapter {
const a = new ProbeAdapter('probe', cfg(initial), opts.requireUrl);
if (opts.open) a.open();
a.opens = 0;
a.closes = 0;
a.configReplaced = 0;
return a;
}
describe('IOneBotNetworkAdapter.reload — shared state machine', () => {
it('stable enabled, signature unchanged → Normal (no open/close)', async () => {
const a = makeProbe({ sig: 'A' }, { open: true });
expect(a.isActive).toBe(true);
const t = await a.reload(cfg({ sig: 'A' }));
expect(t).toBe(NetworkReloadType.Normal);
expect(a.opens).toBe(0);
expect(a.closes).toBe(0);
expect(a.isActive).toBe(true);
});
it('stable disabled stays disabled → Normal (no open/close)', async () => {
const a = makeProbe({ enabled: false, sig: 'A' }); // not opened → wasEnabled=false
expect(a.isActive).toBe(false);
const t = await a.reload(cfg({ enabled: false, sig: 'A' }));
expect(t).toBe(NetworkReloadType.Normal);
expect(a.opens).toBe(0);
expect(a.closes).toBe(0);
expect(a.isActive).toBe(false);
});
it('disabled → enabled → Opened (open only)', async () => {
const a = makeProbe({ enabled: false, sig: 'A' });
const t = await a.reload(cfg({ enabled: true, sig: 'A' }));
expect(t).toBe(NetworkReloadType.Opened);
expect(a.opens).toBe(1);
expect(a.closes).toBe(0);
expect(a.isActive).toBe(true);
});
it('disabled → enabled even with a changed signature → Opened, NOT Reopened', async () => {
// Reopened requires wasEnabled; a signature change alone must not promote
// an Opened into a Reopened.
const a = makeProbe({ enabled: false, sig: 'A' });
const t = await a.reload(cfg({ enabled: true, sig: 'B' }));
expect(t).toBe(NetworkReloadType.Opened);
expect(a.opens).toBe(1);
expect(a.closes).toBe(0);
});
it('enabled → disabled (enabled:false), signature unchanged → Closed (close only)', async () => {
const a = makeProbe({ sig: 'A' }, { open: true });
const t = await a.reload(cfg({ enabled: false, sig: 'A' }));
expect(t).toBe(NetworkReloadType.Closed);
expect(a.closes).toBe(1);
expect(a.opens).toBe(0);
expect(a.isActive).toBe(false);
});
it('enabled, signature changed, still enabled → Reopened (close + open)', async () => {
const a = makeProbe({ sig: 'A' }, { open: true });
const t = await a.reload(cfg({ sig: 'B' }));
expect(t).toBe(NetworkReloadType.Reopened);
expect(a.closes).toBe(1);
expect(a.opens).toBe(1);
expect(a.isActive).toBe(true);
});
it('enabled, signature changed, will disable → Closed (close only, no reopen)', async () => {
const a = makeProbe({ sig: 'A' }, { open: true });
const t = await a.reload(cfg({ enabled: false, sig: 'B' }));
expect(t).toBe(NetworkReloadType.Closed);
expect(a.closes).toBe(1);
expect(a.opens).toBe(0);
expect(a.isActive).toBe(false);
});
it('onConfigReplaced runs on every reload, and config is swapped before the decision', async () => {
const a = makeProbe({ sig: 'A' }, { open: true });
await a.reload(cfg({ sig: 'A' })); // Normal
await a.reload(cfg({ sig: 'B' })); // Reopened
await a.reload(cfg({ enabled: false, sig: 'B' })); // Closed
expect(a.configReplaced).toBe(3);
expect(a.currentConfig.sig).toBe('B');
expect(a.currentConfig.enabled).toBe(false);
});
describe('willEnable override (client-style: requires url)', () => {
it('enabled:true but no url → willEnable false → stays disabled → Normal', async () => {
const a = makeProbe({ enabled: false, sig: 'A', url: undefined }, { requireUrl: true });
const t = await a.reload(cfg({ enabled: true, sig: 'A', url: undefined }));
expect(t).toBe(NetworkReloadType.Normal);
expect(a.opens).toBe(0);
expect(a.isActive).toBe(false);
});
it('enabled:true with a url → Opened', async () => {
const a = makeProbe({ enabled: false, sig: 'A' }, { requireUrl: true });
const t = await a.reload(cfg({ enabled: true, sig: 'A', url: 'ws://x' }));
expect(t).toBe(NetworkReloadType.Opened);
expect(a.opens).toBe(1);
expect(a.isActive).toBe(true);
});
it('url removed while enabled (signature unchanged) → willEnable false → Closed', async () => {
// Proves the `wasEnabled && !willEnable` branch fires from the predicate
// alone, independent of any binding-signature change.
const a = makeProbe({ sig: 'A', url: 'ws://x' }, { requireUrl: true, open: true });
expect(a.isActive).toBe(true);
const t = await a.reload(cfg({ enabled: true, sig: 'A', url: undefined }));
expect(t).toBe(NetworkReloadType.Closed);
expect(a.closes).toBe(1);
expect(a.opens).toBe(0);
expect(a.isActive).toBe(false);
});
});
});

View File

@@ -25,6 +25,7 @@ describe('makeDefaultOneBotConfig', () => {
expect(config.networks.wsServers[0].reportSelfMessage).toBe(false);
expect(config.networks.wsClients).toEqual([]);
expect(config.musicSignUrl).toBe('');
expect(config.statusCommand).toEqual({ enabled: true, swallow: false, cooldownSeconds: 5 });
});
});
@@ -57,6 +58,26 @@ describe('loadOneBotConfig', () => {
// Legacy keys must not appear in the persisted file.
expect(onDisk.httpServers).toBeUndefined();
expect(onDisk.wsServers).toBeUndefined();
// statusCommand is materialised with defaults on a fresh install.
expect(onDisk.statusCommand).toEqual({ enabled: true, swallow: false, cooldownSeconds: 5 });
});
it('fills statusCommand defaults and clamps a negative cooldown', () => {
const uin = '10042';
const dir = path.join(tempDir, 'config');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
path.join(dir, `onebot_${uin}.json`),
JSON.stringify({
networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] },
statusCommand: { swallow: true, cooldownSeconds: -3 },
}),
);
const config = loadOneBotConfig(uin);
expect(config.statusCommand.enabled).toBe(true); // default filled (absent in file)
expect(config.statusCommand.swallow).toBe(true); // taken from file
expect(config.statusCommand.cooldownSeconds).toBe(0); // negative clamped to 0
});
it('migrates legacy per-type arrays into networks groups', () => {

View File

@@ -144,27 +144,34 @@ describe('convertEvent — notice kinds', () => {
expect(invite!.sub_type).toBe('invite');
});
it('group_member_leave: leave / kick / kick_me', async () => {
it('group_member_leave: leave / kick / kick_me / disband', async () => {
const leave = await convertEvent(bareCtx(), {
kind: 'group_member_leave',
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, operatorUin: 0, isKick: false,
userUin: PEER_UIN, operatorUin: 0, leaveType: 'leave',
} as QQEventVariant);
expect(leave!.sub_type).toBe('leave');
const kick = await convertEvent(bareCtx(), {
kind: 'group_member_leave',
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, operatorUin: 33333, isKick: true,
userUin: PEER_UIN, operatorUin: 33333, leaveType: 'kick',
} as QQEventVariant);
expect(kick!.sub_type).toBe('kick');
const kickMe = await convertEvent(bareCtx(), {
kind: 'group_member_leave',
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: SELF_ID, operatorUin: 33333, isKick: true,
userUin: SELF_ID, operatorUin: 33333, leaveType: 'kick',
} as QQEventVariant);
expect(kickMe!.sub_type).toBe('kick_me');
const disband = await convertEvent(bareCtx(), {
kind: 'group_member_leave',
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: SELF_ID, operatorUin: 33333, leaveType: 'disband',
} as QQEventVariant);
expect(disband!.sub_type).toBe('disband');
});
it('group_mute: ban vs lift_ban driven by duration', async () => {

View File

@@ -0,0 +1,137 @@
import { describe, it, expect, vi } from 'vitest';
import { RKeyCache } from '../src/instance-rkey';
import type { MessageElement } from '@snowluma/protocol/events';
// The screenshot URL: a raw QQ-NT multimedia download link with no rkey yet.
// appid 1407 = group image, 1406 = private/c2c image (see instance-rkey).
const NT_IMAGE_URL = 'https://multimedia.nt.qq.com.cn/download?appid=1407&fileid=ABC';
const NT_PRIVATE_IMAGE_URL = 'https://multimedia.nt.qq.com.cn/download?appid=1406&fileid=XYZ';
const GROUP_IMAGE_TYPE = 20;
const PRIVATE_IMAGE_TYPE = 10;
function nowSec(): number {
return Math.floor(Date.now() / 1000);
}
function makeBridge(fetchImpl: () => Promise<unknown[]>) {
const fetchDownloadRKeys = vi.fn(fetchImpl);
return { bridge: { apis: { contacts: { fetchDownloadRKeys } } }, fetchDownloadRKeys };
}
function freshGroupRkey(value = 'GROUPKEY') {
return [{ rkey: value, type: GROUP_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 }];
}
function freshBothRkeys() {
return [
{ rkey: 'PRIVATEKEY', type: PRIVATE_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 },
{ rkey: 'GROUPKEY', type: GROUP_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 },
];
}
function imageEl(): MessageElement {
return { type: 'image', imageUrl: NT_IMAGE_URL };
}
function privateImageEl(): MessageElement {
return { type: 'image', imageUrl: NT_PRIVATE_IMAGE_URL };
}
describe('RKeyCache.resolveImageUrl', () => {
it('awaits a refresh on a cold cache and appends the rkey', async () => {
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
const cache = new RKeyCache();
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(url).toBe(`${NT_IMAGE_URL}&rkey=GROUPKEY`);
expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1);
});
it('coalesces concurrent cold-cache lookups into a single fetch', async () => {
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
const cache = new RKeyCache();
const urls = await Promise.all([
cache.resolveImageUrl(bridge as never, imageEl(), true),
cache.resolveImageUrl(bridge as never, imageEl(), true),
cache.resolveImageUrl(bridge as never, imageEl(), true),
]);
expect(urls).toEqual(Array(3).fill(`${NT_IMAGE_URL}&rkey=GROUPKEY`));
expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1);
});
it('serves a still-valid rkey from cache without re-fetching', async () => {
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
const cache = new RKeyCache();
await cache.resolveImageUrl(bridge as never, imageEl(), true);
await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1);
});
it('falls back to the unsigned URL (no throw) when the refresh fails', async () => {
const { bridge, fetchDownloadRKeys } = makeBridge(async () => { throw new Error('oidb down'); });
const cache = new RKeyCache();
const url = await cache.resolveImageUrl(bridge as never, imageEl(), true);
expect(url).toBe(NT_IMAGE_URL);
expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1);
});
it('uses the private rkey type for c2c images (appid 1406)', async () => {
const { bridge } = makeBridge(async () => freshBothRkeys());
const cache = new RKeyCache();
const url = await cache.resolveImageUrl(bridge as never, privateImageEl(), false);
expect(url).toBe(`${NT_PRIVATE_IMAGE_URL}&rkey=PRIVATEKEY`);
});
// The scene follows the image's own appid, not the carrying message — the
// crux of `/get_forward_msg` rkey correctness (issue #74): a c2c image
// forwarded into a group must still be signed with the private rkey.
it('signs an appid-1406 image with the private rkey even when isGroup is true', async () => {
const { bridge } = makeBridge(async () => freshBothRkeys());
const cache = new RKeyCache();
const url = await cache.resolveImageUrl(bridge as never, privateImageEl(), true);
expect(url).toBe(`${NT_PRIVATE_IMAGE_URL}&rkey=PRIVATEKEY`);
});
it('signs an appid-1407 image with the group rkey even when isGroup is false', async () => {
const { bridge } = makeBridge(async () => freshBothRkeys());
const cache = new RKeyCache();
const url = await cache.resolveImageUrl(bridge as never, imageEl(), false);
expect(url).toBe(`${NT_IMAGE_URL}&rkey=GROUPKEY`);
});
it('falls back to the isGroup scene when the URL carries no appid', async () => {
const noAppidUrl = 'https://multimedia.nt.qq.com.cn/download?fileid=NOAPPID';
const { bridge } = makeBridge(async () => freshBothRkeys());
const cache = new RKeyCache();
const url = await cache.resolveImageUrl(
bridge as never, { type: 'image', imageUrl: noAppidUrl }, true,
);
expect(url).toBe(`${noAppidUrl}&rkey=GROUPKEY`);
});
it('leaves non-NT URLs untouched and never fetches', async () => {
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
const cache = new RKeyCache();
const el: MessageElement = { type: 'image', imageUrl: 'https://gchat.qpic.cn/foo.jpg' };
const url = await cache.resolveImageUrl(bridge as never, el, true);
expect(url).toBe('https://gchat.qpic.cn/foo.jpg');
expect(fetchDownloadRKeys).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,106 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
createLogger,
currentRequestId,
getLogLevel,
getRecentLogs,
runWithRequestId,
setLogLevel,
} from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
describe('renderParamsVerbose', () => {
it('shows the full nested structure (message segments), unlike the shallow summary', () => {
const out = renderParamsVerbose({
group_id: 123,
message: [{ type: 'text', data: { text: 'hello' } }, { type: 'at', data: { qq: '456' } }],
});
expect(out).toContain('group_id:123');
expect(out).toContain('text');
expect(out).toContain('"hello"');
expect(out).toContain('"456"');
});
it('truncates long strings (e.g. base64) with a size marker', () => {
const big = 'A'.repeat(5000);
const out = renderParamsVerbose({ file: `base64://${big}` });
expect(out).toContain('base64://');
expect(out).toContain('…<'); // truncation marker
expect(out).toContain('B>');
expect(out.length).toBeLessThan(2000); // bounded by the total budget
});
it('redacts sensitive keys at any depth', () => {
const out = renderParamsVerbose({
access_token: 'super-secret-value',
nested: { password: 'hunter2', SECRET: 'x', ok: 'visible' },
});
expect(out).not.toContain('super-secret-value');
expect(out).not.toContain('hunter2');
expect(out).toContain('"***"');
expect(out).toContain('"visible"'); // non-sensitive keys still rendered
});
it('handles circular references without throwing', () => {
const a: Record<string, unknown> = { name: 'a' };
a.self = a;
expect(() => renderParamsVerbose(a)).not.toThrow();
expect(renderParamsVerbose(a)).toContain('[circular]');
});
});
describe('logger trace level + request correlation', () => {
let prevLevel: string;
beforeEach(() => {
prevLevel = getLogLevel();
});
afterEach(() => {
setLogLevel(prevLevel);
});
it('captures trace into the in-memory buffer only when the level is trace', () => {
const log = createLogger('Test.Trace');
const marker = `trace-marker-${Math.trunc(performance.now())}-${getRecentLogs(1).length}`;
setLogLevel('info');
log.trace('off %s', marker);
expect(getRecentLogs(2000).some((e) => e.message.includes(marker))).toBe(false);
setLogLevel('trace');
log.trace('on %s', marker);
const hit = getRecentLogs(2000).find((e) => e.message.includes(marker));
expect(hit).toBeDefined();
expect(hit?.level).toBe('trace');
});
it('does NOT evaluate a lazy producer when trace is off (the efficiency guarantee)', () => {
const log = createLogger('Test.Lazy');
const produce = vi.fn(() => ['lazy payload']);
setLogLevel('info');
log.trace(produce);
expect(produce).not.toHaveBeenCalled();
setLogLevel('trace');
log.trace(produce);
expect(produce).toHaveBeenCalledTimes(1);
});
it('stamps the ambient request id onto entries emitted inside runWithRequestId', () => {
const log = createLogger('Test.Req');
setLogLevel('trace');
const marker = `req-marker-${Math.trunc(performance.now())}`;
expect(currentRequestId()).toBeUndefined();
runWithRequestId(4242, () => {
expect(currentRequestId()).toBe(4242);
log.trace('inside %s', marker);
});
expect(currentRequestId()).toBeUndefined();
const hit = getRecentLogs(2000).find((e) => e.message.includes(marker));
expect(hit?.req).toBe(4242);
expect(hit?.line).toContain('[req#4242]');
});
});

View File

@@ -0,0 +1,63 @@
import { describe, it, expect, vi } from 'vitest';
import type { MessageElement } from '@snowluma/protocol/events';
import { getImageInfo } from '../src/modules/media-actions';
import type { CachedImage, MediaStore } from '../src/media-store';
const RAW = 'https://multimedia.nt.qq.com.cn/download?appid=1407&fileid=ABC';
function fakeStore(image: CachedImage | null): MediaStore {
return { findImage: () => image } as unknown as MediaStore;
}
function cachedImage(overrides: Partial<CachedImage> = {}): CachedImage {
return {
file: 'ABC.jpg',
url: `${RAW}&rkey=STALE`, // signed when the message arrived; now expired
fileSize: 100,
fileName: 'ABC.jpg',
subType: 0,
summary: '',
isGroup: true,
sessionId: 123,
imageUrl: RAW, // raw, unsigned — the basis for re-signing
...overrides,
};
}
describe('getImageInfo — rkey re-signing at lookup time', () => {
it('re-signs from the raw imageUrl via the resolver', async () => {
const resolver = vi.fn(async (el: MessageElement) => `${el.imageUrl}&rkey=FRESH`);
const info = await getImageInfo(fakeStore(cachedImage()), 'ABC.jpg', resolver);
expect(info?.url).toBe(`${RAW}&rkey=FRESH`);
expect(info?.file).toBe(`${RAW}&rkey=FRESH`);
expect(resolver).toHaveBeenCalledWith(
expect.objectContaining({ type: 'image', imageUrl: RAW }),
true, // isGroup carried through
);
});
it('returns the stored URL when no resolver is wired', async () => {
const info = await getImageInfo(fakeStore(cachedImage()), 'ABC.jpg');
expect(info?.url).toBe(`${RAW}&rkey=STALE`);
});
it('falls back to the stored URL when the resolver throws', async () => {
const resolver = vi.fn(async () => { throw new Error('rkey fetch failed'); });
const info = await getImageInfo(fakeStore(cachedImage()), 'ABC.jpg', resolver);
expect(info?.url).toBe(`${RAW}&rkey=STALE`);
});
it('skips re-signing when no raw imageUrl is stored', async () => {
const resolver = vi.fn(async () => 'should-not-be-used');
const info = await getImageInfo(fakeStore(cachedImage({ imageUrl: '' })), 'ABC.jpg', resolver);
expect(resolver).not.toHaveBeenCalled();
expect(info?.url).toBe(`${RAW}&rkey=STALE`);
});
it('returns null when the image is not cached', async () => {
const info = await getImageInfo(fakeStore(null), 'missing.jpg');
expect(info).toBeNull();
});
});

View File

@@ -413,6 +413,33 @@ describe('parseMessage', () => {
const parsed = JSON.parse(result[0].text!);
expect(parsed.meta.contact.type).toBe('group');
});
it('parses signed music cards and buildSendElems preserves non-ASCII JSON', async () => {
const card = JSON.stringify({
app: 'com.tencent.structmsg',
view: 'music',
prompt: '[音乐]风中有朵雨做的云',
meta: { music: { title: '风中有朵雨做的云', desc: '孟庭苇' } },
});
vi.stubGlobal('fetch', vi.fn(async () => ({
ok: true,
text: async () => card,
})));
try {
const result = await parseMessage(
[{ type: 'music', data: { type: '163', id: '123456' } }] as any,
false,
);
expect(result).toEqual([{ type: 'json', text: card }]);
const protoElems = await buildSendElems(result);
expect(protoElems).toHaveLength(1);
expect(protoElems[0].lightApp?.data?.[0]).toBe(0x01);
} finally {
vi.unstubAllGlobals();
}
});
});
describe('single segment object', () => {
@@ -454,16 +481,22 @@ describe('parseMessage', () => {
]);
});
it('drops a file segment with no file_id (upload-first contract)', async () => {
// Path-only segments aren't supported here — callers must
// upload via `upload_group_file` / `upload_private_file` first
// to obtain a file_id. Dropping with a warning is preferable
// to silently kicking off an upload from inside the message
// parser, which can't fail loudly without changing call sites.
it('parses {type:"file", file:"/path"} (no file_id) into a file element with url', async () => {
// Inline file path: the parser now accepts file/url/path and stores
// it in `url`. The send layer (sendGroupMessage / sendPrivateMessage)
// handles the actual upload so the parser stays side-effect-free.
const result = await parseMessage(
[{ type: 'file', data: { file: '/local/path/a.bin' } } as any],
false,
);
expect(result).toEqual([{ type: 'file', url: '/local/path/a.bin' }]);
});
it('drops a file segment with neither file_id nor file/url', async () => {
const result = await parseMessage(
[{ type: 'file', data: {} } as any],
false,
);
expect(result).toEqual([]);
});

View File

@@ -25,7 +25,9 @@ class FakeAdapter extends IOneBotNetworkAdapter<FakeNetworkConfig> {
this.closes++;
this.isEnabled = false;
}
reload(next: FakeNetworkConfig): NetworkReloadType {
// Keeps its own reload — this is a manager test double, not a reload test;
// base.reload became concrete so this is now a genuine override.
override reload(next: FakeNetworkConfig): NetworkReloadType {
this.reloads++;
this.config = structuredClone(next);
if (next.enabled === false && this.isEnabled) {
@@ -38,6 +40,9 @@ class FakeAdapter extends IOneBotNetworkAdapter<FakeNetworkConfig> {
}
return NetworkReloadType.Normal;
}
protected bindingSignature(config: FakeNetworkConfig): string {
return JSON.stringify(config);
}
onEvent(event: JsonObject, payload: DispatchPayload): void {
this.events.push(event);
this.lastPayloads.push(payload);

View File

@@ -105,14 +105,13 @@ describe('send_group_msg with {type:"file"} segment', () => {
});
it('file segment without file_id is skipped (with a warn-level log)', async () => {
// Same upload-by-reference contract as the c2c file path —
// missing file_id means there's nothing to publish.
const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt);
const publish = vi.fn();
const upload = vi.fn();
const bridge = fakeBridge({
apis: {
message: { sendGroup: sendGroupMessage_bridge },
groupFile: { publish },
groupFile: { publish, upload },
} as any,
resolveUserUid: vi.fn(),
} as any);
@@ -120,10 +119,42 @@ describe('send_group_msg with {type:"file"} segment', () => {
await sendGroupMessage(ctx, 12345, [
{ type: 'text', data: { text: 'with bad file segment' } },
{ type: 'file', data: {} }, // no file_id
{ type: 'file', data: {} }, // no file_id and no url
] as any, false);
expect(sendGroupMessage_bridge).toHaveBeenCalledOnce();
expect(publish).not.toHaveBeenCalled();
expect(upload).not.toHaveBeenCalled();
});
it('file segment with url (no file_id) auto-uploads via groupFile.upload (not publish)', async () => {
// Happy path for inline file sending: the bot passes a local path
// directly. upload() internally calls publish(), so we must NOT
// call publish() a second time.
const upload = vi.fn(async (_gid: number, _src: string, _name: string, _folder: string, _doUpload: boolean) =>
({ fileId: 'auto-fid', fileHash: null }));
const publish = vi.fn();
const bridge = fakeBridge({
apis: {
message: { sendGroup: vi.fn() },
groupFile: { upload, publish },
} as any,
resolveUserUid: vi.fn(),
} as any);
const ctx = makeCtx(bridge);
await sendGroupMessage(ctx, 12345, [{
type: 'file', data: { file: '/tmp/audio.wav', name: 'audio.wav' },
}] as any, false);
expect(upload).toHaveBeenCalledOnce();
const [gid, src, name, folder, doUpload] = upload.mock.calls[0]!;
expect(gid).toBe(12345);
expect(src).toBe('/tmp/audio.wav');
expect(name).toBe('audio.wav');
expect(folder).toBe('/');
expect(doUpload).toBe(true);
// publish must NOT be called — upload() already handles it internally
expect(publish).not.toHaveBeenCalled();
});
});

View File

@@ -227,4 +227,33 @@ describe('send_private_msg with {type:"file"} segment', () => {
expect(sendC2cFileMessage).not.toHaveBeenCalled();
});
it('file segment with url (no file_id) auto-uploads via groupFile.uploadPrivate (not sendC2cFile)', async () => {
// uploadPrivate() internally calls sendC2cFile() — must NOT call it again.
const uploadPrivate = vi.fn(async (_uid: number, _src: string, _name: string, _doUpload: boolean) =>
({ fileId: 'auto-fid', fileHash: null }));
const sendC2cFileMessage = vi.fn();
const bridge = fakeBridge({
apis: {
message: { sendPrivate: vi.fn(), sendC2cFile: sendC2cFileMessage },
groupFile: { uploadPrivate },
} as any,
resolveUserUid: vi.fn(async () => 'u_peer'),
recallUploadedFile: vi.fn(() => undefined),
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [{
type: 'file', data: { file: '/tmp/audio.wav', name: 'audio.wav' },
}] as any, false);
expect(uploadPrivate).toHaveBeenCalledOnce();
const [uid, src, name, doUpload] = uploadPrivate.mock.calls[0]!;
expect(uid).toBe(67890);
expect(src).toBe('/tmp/audio.wav');
expect(name).toBe('audio.wav');
expect(doUpload).toBe(true);
// sendC2cFile must NOT be called — uploadPrivate() handles it internally
expect(sendC2cFileMessage).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,103 @@
import { describe, it, expect } from 'vitest';
import {
STATUS_COMMAND_TRIGGER,
buildStatusText,
formatUptime,
matchesStatusCommand,
statusCooldownElapsed,
} from '../src/modules/status-command';
import type { JsonValue } from '../src/types';
function textSeg(text: string): JsonValue {
return [{ type: 'text', data: { text } }] as unknown as JsonValue;
}
describe('matchesStatusCommand', () => {
it('matches a single text segment equal to the trigger', () => {
expect(matchesStatusCommand(textSeg('#sl'))).toBe(true);
});
it('is case-insensitive and trims surrounding whitespace', () => {
expect(matchesStatusCommand(textSeg('#SL'))).toBe(true);
expect(matchesStatusCommand(textSeg(' #Sl '))).toBe(true);
});
it('matches a bare string (string-format adapters)', () => {
expect(matchesStatusCommand('#sl' as unknown as JsonValue)).toBe(true);
expect(matchesStatusCommand(' #SL ' as unknown as JsonValue)).toBe(true);
});
it('does NOT match as a prefix — only exact', () => {
expect(matchesStatusCommand(textSeg('#slogan'))).toBe(false);
expect(matchesStatusCommand(textSeg('#sl help'))).toBe(false);
expect(matchesStatusCommand(textSeg('你好 #sl'))).toBe(false);
});
it('rejects mixed-segment messages', () => {
const mixed = [
{ type: 'text', data: { text: '#sl' } },
{ type: 'image', data: { file: 'x.png' } },
] as unknown as JsonValue;
expect(matchesStatusCommand(mixed)).toBe(false);
});
it('rejects non-text leading segments and empty/garbage input', () => {
expect(matchesStatusCommand([{ type: 'at', data: { qq: '1' } }] as unknown as JsonValue)).toBe(false);
expect(matchesStatusCommand([] as unknown as JsonValue)).toBe(false);
expect(matchesStatusCommand(undefined)).toBe(false);
expect(matchesStatusCommand(123 as unknown as JsonValue)).toBe(false);
});
it('exposes the hardcoded trigger', () => {
expect(STATUS_COMMAND_TRIGGER).toBe('#sl');
});
});
describe('statusCooldownElapsed', () => {
it('allows the first reply (no prior timestamp)', () => {
expect(statusCooldownElapsed(undefined, 1_000, 5)).toBe(true);
});
it('ignores the cooldown when set to 0 or negative', () => {
expect(statusCooldownElapsed(1_000, 1_500, 0)).toBe(true);
expect(statusCooldownElapsed(1_000, 1_000, -1)).toBe(true);
});
it('blocks within the window and allows once elapsed', () => {
const last = 10_000;
expect(statusCooldownElapsed(last, last + 4_999, 5)).toBe(false);
expect(statusCooldownElapsed(last, last + 5_000, 5)).toBe(true);
expect(statusCooldownElapsed(last, last + 9_999, 5)).toBe(true);
});
});
describe('formatUptime', () => {
it('drops leading zero units', () => {
expect(formatUptime(0)).toBe('0秒');
expect(formatUptime(45_000)).toBe('45秒');
expect(formatUptime(90_000)).toBe('1分钟 30秒');
expect(formatUptime(3_600_000)).toBe('1小时 0分钟');
expect(formatUptime((26 * 3600 + 12 * 60) * 1000)).toBe('1天 2小时 12分钟');
});
it('never goes negative', () => {
expect(formatUptime(-5_000)).toBe('0秒');
});
});
describe('buildStatusText', () => {
it('renders version / platform / uptime, no leaked uin or topology', () => {
const text = buildStatusText({
version: '1.9.3-node',
platform: 'linux',
arch: 'x64',
uptimeMs: 90_000,
});
expect(text).toContain('SnowLuma');
expect(text).toContain('版本: 1.9.3-node');
expect(text).toContain('平台: linux-x64');
expect(text).toContain('运行时长: 1分钟 30秒');
// public-safe: must not echo a uin or connection count
expect(text).not.toMatch(/uin|连接|adapter/i);
});
});

View File

@@ -1,6 +1,6 @@
{
"name": "@snowluma/proto-defs",
"version": "1.9.2",
"version": "1.9.7",
"private": true,
"type": "module",
"description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb<N, T>` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).",
@@ -35,6 +35,10 @@
"types": "./src/notify.ts",
"default": "./src/notify.ts"
},
"./ptt-trans": {
"types": "./src/ptt-trans.ts",
"default": "./src/ptt-trans.ts"
},
"./oidb": {
"types": "./src/oidb.ts",
"default": "./src/oidb.ts"

View File

@@ -1,4 +1,4 @@
import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton';
import type { pb, pb_optional, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton';
// Re-exported from the legacy oidb-action module while large protocol groups
// are split into focused files.
@@ -13,7 +13,11 @@ export interface OidbMuteMember {
body?: pb<3, OidbMuteMemberBody>;
}
export interface OidbMuteAllState {
state?: pb<17, uint_32>;
// Explicit presence: the unmute request sends state=0, which proto3 would
// otherwise omit — leaving an empty `muteState` the server can't tell apart
// from the other commands sharing OIDB (0x89A, 0) (SetSearch / SetAddOption,
// disambiguated by body shape). pb_optional forces the 0 onto the wire.
state?: pb_optional<17, uint_32>;
}
export interface OidbMuteAll {
groupUin?: pb<1, uint_32>;
@@ -90,13 +94,19 @@ export interface OidbSetAdmin {
uid?: pb<2, string>;
isAdmin?: pb<3, bool>;
}
// 0x8FC_3 (set member card) shares its wire shape with 0x8FC_2 (special
// title): the body wrapper sits at tag 3, and the card name at tag 8 —
// NOT tags 2/2. Sending body@2 / targetName@2 makes the server miss both
// and reject with `OIDB error 1007`. Cross-checked byte-for-byte against:
// dev/Lagrange.Core/…/Request/OidbSvcTrpcTcp0x8FC.cs (Body=3, TargetName=8)
// dev/napcatQQInside/…/proto/oidb/Oidb.0x8FC_2.ts (body=3, targetName=8)
export interface OidbRenameMemberBody {
targetUid?: pb<1, string>;
targetName?: pb<2, string>;
targetName?: pb<8, string>;
}
export interface OidbRenameMember {
groupUin?: pb<1, uint_32>;
body?: pb<2, OidbRenameMemberBody>;
body?: pb<3, OidbRenameMemberBody>;
}
export interface OidbRenameGroupBody {
targetName?: pb<1, string>;
@@ -112,7 +122,8 @@ export interface OidbSpecialTitleBody {
}
export interface OidbSpecialTitle {
groupUin?: pb<1, uint_32>;
body?: pb<2, OidbSpecialTitleBody>;
// Same family as 0x8FC_3 above — body wrapper is tag 3, not 2.
body?: pb<3, OidbSpecialTitleBody>;
}
// 0x7E5_104 (FriendLike) request body. Field numbers 11/12/13 (NOT
// 1/2/3) — the server reads `targetUid` from tag 11 and rejects with
@@ -657,4 +668,22 @@ export interface GroupAvatarExtra {
field3?: pb<3, GroupAvatarExtraField3>;
field5?: pb<5, uint_32>;
field6?: pb<6, uint_32>;
}
}
export interface Oidb0xcdeReqBodyInfo {
db_salt?: pb<1, string>;
}
export interface Oidb0xcdeReq {
info?: pb<2, Oidb0xcdeReqBodyInfo>;
sessionData?: pb<10, bytes>;
}
export interface Oidb0xcdeRespBodyInfo {
dbKey?: pb<1, string>;
}
export interface Oidb0xcdeResp {
info?: pb<2, Oidb0xcdeRespBodyInfo>;
}

View File

@@ -0,0 +1,97 @@
import type { pb, uint_32, uint_64, bytes } from '@snowluma/proton';
/**
* Voice-to-text (语音转文字) request/response protobufs for the
* `pttTrans.TransC2CPttReq` / `pttTrans.TransGroupPttReq` SSO commands.
*
* Reverse-engineered from QQ-NT `wrapper.node` (macOS 9.9.x) —
* `im_core/msg/ptt/ptt_trans_worker.cc` (`EncodeC2CPtt` / `EncodeTroopPtt`
* build the request, `OnTranslateResp` decodes the response). The wire shape
* here is RE-derived and NOT yet verified against a live server: the numeric
* field tags are read straight from the encoder, but the length-delimited
* fields (uuid / md5) and the response `text` tag should be confirmed with a
* single live capture before relying on them.
*
* Flow: send Trans{C2C,Group}PttReq → response carries the text inline when
* transcription is already done; when it's empty the server transcribes
* asynchronously (no dedicated push command exists — see NotifyTransUpdate),
* so the caller re-sends with backoff until the text arrives or it times out.
*/
/** Source ptt-element field (NT internal tag) noted in the comment after each. */
export interface C2CPttTransItem {
msgId?: pb<1, uint_64>;
senderUin?: pb<2, uint_64>;
receiverUin?: pb<3, uint_64>;
uuid?: pb<4, string>; // element 45503 (c2c ptt uuid)
duration?: pb<5, uint_32>; // element 45906 (seconds)
size?: pb<6, uint_32>; // element 45405 (bytes)
format?: pb<7, uint_32>; // element 45907 (voice codec)
eventType?: pb<8, uint_32>; // element 45921
md5?: pb<9, bytes>; // element 45406 (raw 16-byte md5)
}
export interface GroupPttTransItem {
msgId?: pb<1, uint_64>;
senderUin?: pb<2, uint_64>;
groupUin?: pb<3, uint_64>;
fileId?: pb<4, uint_32>; // element 45903 (group ptt numeric file id)
md5?: pb<5, bytes>; // element 45406
duration?: pb<6, uint_32>; // element 45906
size?: pb<7, uint_32>; // element 45405
format?: pb<8, uint_32>; // element 45907
uuid?: pb<9, string>; // element 45503
eventType?: pb<10, uint_32>; // element 45921
ext?: pb<11, uint_32>; // element 49202 (optional)
}
/**
* Outer request. `type` selects the scene (1 = group, 2 = c2c) and only the
* matching item is populated — group at field 2, c2c at field 3.
*/
export interface PttTransReq {
type?: pb<1, uint_32>;
groupItem?: pb<2, GroupPttTransItem>;
c2cItem?: pb<3, C2CPttTransItem>;
}
/** Per-scene result. `errCode` 0 = ok; `text` carries the recognised speech. */
export interface C2CPttTransResult {
errCode?: pb<2, uint_32>;
text?: pb<8, string>; // VERIFY LIVE: text tag from OnTranslateResp
}
export interface GroupPttTransResult {
errCode?: pb<2, uint_32>;
text?: pb<9, string>; // VERIFY LIVE: text tag from OnTranslateResp
}
/**
* Outer response. `type` echoes the scene; result is at field 2 (group) /
* field 3 (c2c). An empty `text` with `errCode == 0` means "transcribing,
* retry later".
*/
export interface PttTransResp {
type?: pb<1, uint_32>;
groupResult?: pb<2, GroupPttTransResult>;
c2cResult?: pb<3, C2CPttTransResult>;
}
/**
* Async result push (Event 0x210 subType 61), sent after the request once the
* server finishes transcribing. **Live-verified** against a real push: the
* outer carries a single result item at field 2; the item echoes the request
* `msgId` at field 1 (the correlation key) and the recognised text at field 8.
*/
export interface PttTransPushItem {
msgId?: pb<1, uint_64>; // echoes the request msgId — correlation key
text?: pb<8, string>; // recognised text
senderUin?: pb<9, uint_64>;
receiverUin?: pb<10, uint_64>;
uuid?: pb<13, string>;
}
export interface PttTransPush {
field1?: pb<1, uint_32>;
item?: pb<2, PttTransPushItem>;
}

View File

@@ -1,6 +1,6 @@
{
"name": "@snowluma/protocol",
"version": "1.9.2",
"version": "1.9.7",
"private": true,
"type": "module",
"description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/<x>'` collapses to `import { … } from '@snowluma/protocol/<x>'`.",
@@ -107,6 +107,10 @@
"types": "./src/oidb-services/misc/send-group-sign.ts",
"default": "./src/oidb-services/misc/send-group-sign.ts"
},
"./oidb-services/misc/request-decrypt-key": {
"types": "./src/oidb-services/misc/request-decrypt-key.ts",
"default": "./src/oidb-services/misc/request-decrypt-key.ts"
},
"./oidb-services/web/force-fetch-client-key": {
"types": "./src/oidb-services/web/force-fetch-client-key.ts",
"default": "./src/oidb-services/web/force-fetch-client-key.ts"
@@ -368,8 +372,7 @@
"dependencies": {
"@snowluma/common": "workspace:*",
"@snowluma/proto-defs": "workspace:*",
"@snowluma/proton": "workspace:*",
"@snowluma/sqlite": "workspace:*"
"@snowluma/proton": "workspace:*"
},
"devDependencies": {
"@types/node": "^24.12.2",

View File

@@ -105,32 +105,31 @@ function makeReplyElem(element: MessageElement): ProtoElem {
return { srcMsg };
}
function makeDeflatedPayload(content: string): Uint8Array {
const deflated = deflateSync(Buffer.from(content, 'utf8'));
const payload = new Uint8Array(deflated.length + 1);
payload[0] = 0x01;
payload.set(deflated, 1);
return payload;
}
function makeJsonElem(element: MessageElement): ProtoElem {
const content = element.text ?? '';
const payload = new Uint8Array(content.length + 1);
payload[0] = 0x00;
const encoded = new TextEncoder().encode(content);
payload.set(encoded, 1);
return {
richMsg: {
serviceId: 1,
template1: payload,
lightApp: {
data: makeDeflatedPayload(content),
},
};
}
function makeXmlElem(element: MessageElement): ProtoElem {
const content = element.text ?? '';
const payload = new Uint8Array(content.length + 1);
payload[0] = 0x00;
const encoded = new TextEncoder().encode(content);
payload.set(encoded, 1);
return {
richMsg: {
serviceId: element.subType === 0 ? 35 : (element.subType ?? 35),
template1: payload,
template1: makeDeflatedPayload(content),
},
};
}
@@ -208,14 +207,9 @@ function makeForwardElem(element: MessageElement): ProtoElem {
};
const json = JSON.stringify(lightApp);
const deflated = deflateSync(Buffer.from(json, 'utf8'));
const payload = new Uint8Array(deflated.length + 1);
payload[0] = 0x01; // 0x01 prefix = deflated JSON (vs 0x00 = uncompressed XML)
payload.set(deflated, 1);
return {
lightApp: {
data: payload,
data: makeDeflatedPayload(json),
},
};
}

View File

@@ -153,7 +153,12 @@ export interface GroupMemberLeave extends QQEvent {
operatorUin: number;
userUid?: string;
operatorUid?: string;
isKick: boolean;
/**
* Protocol-level reason the member left, derived from
* GroupChange.decreaseType. `kick` is split into kick / kick_me
* downstream (OneBot converter) by comparing against selfId.
*/
leaveType: 'leave' | 'kick' | 'disband';
}
export interface GroupMuteEvent extends QQEvent {
@@ -263,6 +268,18 @@ export interface GroupMsgEmojiLikeEvent extends QQEvent {
isAdd: boolean;
}
/**
* Async voice-to-text result, pushed by the server (Event 0x210 subType 61)
* after a `pttTrans.Trans{C2C,Group}PttReq`. `msgId` echoes the request's
* msgId — the correlation key a pending `fetch_ptt_text` waits on. Internal
* (not surfaced to OneBot clients).
*/
export interface PttTransResultEvent extends QQEvent {
kind: 'ptt_trans_result';
msgId: number;
text: string;
}
export type QQEventVariant =
| FriendMessage
| GroupMessage
@@ -280,4 +297,5 @@ export type QQEventVariant =
| GroupEssenceEvent
| GroupFileUploadEvent
| FriendAddEvent
| GroupMsgEmojiLikeEvent;
| GroupMsgEmojiLikeEvent
| PttTransResultEvent;

View File

@@ -182,8 +182,10 @@ export function formatEvent(identity: IdentityService, event: QQEventVariant): s
return `私聊撤回 ${formatUser(identity, undefined, event.userUin)} 撤回了消息`;
case 'group_member_join':
return `入群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} 加入 ${formatGroup(identity, event.groupId)}`;
case 'group_member_leave':
return `退群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} ${event.isKick ? '被踢出' : '退出'} ${formatGroup(identity, event.groupId)}`;
case 'group_member_leave': {
const leaveAction = event.leaveType === 'disband' ? '随群解散' : event.leaveType === 'kick' ? '被踢出' : '退出';
return `退群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} ${leaveAction} ${formatGroup(identity, event.groupId)}`;
}
case 'group_mute':
return `禁言 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} ${event.duration}秒`;
case 'group_admin':

View File

@@ -8,11 +8,13 @@ import type {
ReqDataHighwayHead,
RespDataHighwayHead,
} from '@snowluma/proto-defs/highway';
import { createLogger } from '@snowluma/common/logger';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import net from 'net';
import type { BridgeContext } from '../bridge-context';
import { computeMd5, packHighwayFrame, unpackHighwayFrame } from './utils';
const log = createLogger('Highway');
const HIGHWAY_APP_ID = 1600001604;
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
@@ -69,7 +71,7 @@ export async function fetchHighwaySession(bridge: BridgeContext): Promise<Highwa
}
}
console.log(`[Highway] session: ${session.host}:${session.port} sig=${(session.sigSession as Uint8Array).length}B`);
log.trace('session %s:%d sig=%dB', session.host, session.port, (session.sigSession as Uint8Array).length);
return session;
}
@@ -202,7 +204,14 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
const onClose = () => finish(() => {
const buf = Buffer.concat(chunks);
if (headerEnd >= 0) resolve(new Uint8Array(buf.subarray(headerEnd)));
else reject(new Error('connection closed before response'));
// QQ 的 highway 边缘节点对单连接多 POST 的 keep-alive 支持不稳定:
// 第一次 POST 拿到响应后服务器经常立刻 FIN 关闭,下一次写入的请求体
// 走到一个已被对端 close 的 socket 上,触发这里。诊断信息把已收到的
// 字节数和是否解析到 header 一起带出来,便于区分 “连接刚握手就被关”
// 和 “响应读到一半被截断” 两种情况。
else reject(new Error(
`connection closed before response (received=${buf.length}B, headerSeen=${headerEnd >= 0})`
));
});
socket.on('data', onData);
@@ -225,42 +234,60 @@ export async function uploadHighwayHttp(
bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array,
): Promise<void> {
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`;
const socket = await tcpConnect(session.host, session.port);
try {
let offset = 0;
while (offset < bytes.length) {
const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, bytes.length - offset);
const chunk = bytes.subarray(offset, offset + chunkSize);
const chunkMd5 = computeMd5(chunk);
const head = makeHighwayHead(
bridge.identity.uin, commandId, bytes.length, offset, chunkSize,
chunkMd5, fileMd5, session.sigSession, extend,
);
const frame = packHighwayFrame(head, chunk);
const responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
const { head: respHead } = unpackHighwayFrame(responseBody);
const resp = protobuf_decode<RespDataHighwayHead>(respHead);
if (resp?.errorCode && resp.errorCode !== 0) {
// Surface every diagnostic the highway response carries so
// user reports of `error_code=921` and friends include the
// server-side context (segHead.retCode, chunk size, file md5)
// — without these we can't tell apart a malformed-payload
// reject, a session-ticket mismatch, or a per-account rate-
// limit.
const segRetCode = resp.msgSegHead?.retCode ?? 0;
const fileMd5Hex = Buffer.from(fileMd5).toString('hex');
throw new Error(
`highway upload error_code=${resp.errorCode}` +
` (cmdId=${commandId} chunk=${chunkSize}/${bytes.length}` +
` offset=${offset} segRetCode=${segRetCode}` +
` fileMd5=${fileMd5Hex.slice(0, 16)}…)`,
);
}
offset += chunkSize;
console.log(`[Highway] uploaded ${offset}/${bytes.length} bytes`);
// 每个 chunk 一个独立的 TCP 连接。
//
// 旧实现整个文件复用同一个 socket,依赖 `Connection: keep-alive` 跑多次
// POST。但 QQ highway 边缘节点(以及链路上的代理/NAT)经常在第一次响应
// 之后立刻 FIN 关闭连接,导致第二个 chunk 写入一个已被对端关闭的 socket,
// `readHttpResponseBody` 立刻收到 `close` 事件并抛 `connection closed
// before response`。
//
// 现象上的体现:≤1 MB 的图片/PTT 因为只发一个 chunk,不会触发;超过 1 MB
// 的图片或视频(HIGHWAY_BLOCK_SIZE = 1 MiB)必然失败。
//
// 改成每 chunk 一连接代价可忽略:
// - 单个 1 MB chunk 的传输时间远大于 TCP 建连开销;
// - QQ 服务端反正也不希望客户端长时间占用连接;
// - 与 NapCat / Lagrange 在大文件上传时的连接生命周期一致。
let offset = 0;
while (offset < bytes.length) {
const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, bytes.length - offset);
const chunk = bytes.subarray(offset, offset + chunkSize);
const chunkMd5 = computeMd5(chunk);
const head = makeHighwayHead(
bridge.identity.uin, commandId, bytes.length, offset, chunkSize,
chunkMd5, fileMd5, session.sigSession, extend,
);
const frame = packHighwayFrame(head, chunk);
const socket = await tcpConnect(session.host, session.port);
let responseBody: Uint8Array;
try {
responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
} finally {
socket.destroy();
}
} finally {
socket.destroy();
const { head: respHead } = unpackHighwayFrame(responseBody);
const resp = protobuf_decode<RespDataHighwayHead>(respHead);
if (resp?.errorCode && resp.errorCode !== 0) {
// Surface every diagnostic the highway response carries so
// user reports of `error_code=921` and friends include the
// server-side context (segHead.retCode, chunk size, file md5)
// — without these we can't tell apart a malformed-payload
// reject, a session-ticket mismatch, or a per-account rate-
// limit.
const segRetCode = resp.msgSegHead?.retCode ?? 0;
const fileMd5Hex = Buffer.from(fileMd5).toString('hex');
throw new Error(
`highway upload error_code=${resp.errorCode}` +
` (cmdId=${commandId} chunk=${chunkSize}/${bytes.length}` +
` offset=${offset} segRetCode=${segRetCode}` +
` fileMd5=${fileMd5Hex.slice(0, 16)}…)`,
);
}
offset += chunkSize;
log.trace('uploaded %d/%d bytes', offset, bytes.length);
}
}

View File

@@ -22,6 +22,19 @@ const DEFAULT_MAX_BINARY_SIZE = 1024 * 1024 * 1024; // 1 GiB
export const FILE_UPLOAD_MAX_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB
const FETCH_TIMEOUT_MS = 60_000;
/**
* Browser-like User-Agent for remote media downloads. Many image / CDN
* hosts (and anti-hotlink front-ends) reject or RST a header-less,
* non-browser request — which surfaces as undici `TypeError: fetch
* failed` rather than a clean 403. Sending a normal browser UA on every
* request (and retrying with a Referer when the first try is refused) is
* what lets NapCat fetch sources our bare `fetch(source)` couldn't.
* Cross-checked against
* `dev/napcatQQInside/packages/napcat-common/src/file.ts:101-142,359-369`.
*/
const DOWNLOAD_USER_AGENT =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';
export interface ImageHashes {
md5: Uint8Array;
sha1: Uint8Array;
@@ -65,6 +78,14 @@ export function resolveLocalFilePath(source: string): string | null {
return filePath;
}
/**
* Tag a size-limit error so the HTTP retry path leaves it alone — retrying
* a too-large response just re-downloads the same oversized body.
*/
function tooLarge(message: string): Error {
return Object.assign(new Error(message), { noRetry: true });
}
export async function loadBinarySource(
source: string,
resourceName: string,
@@ -81,49 +102,79 @@ export async function loadBinarySource(
}
if (/^https?:\/\//i.test(source)) {
const resp = await fetch(source, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
const declared = Number(resp.headers.get('content-length') ?? '0');
if (Number.isFinite(declared) && declared > maxBytes) {
throw new Error(`${resourceName} too large: ${declared} > ${maxBytes}`);
}
const fileName = guessFileNameFromUrl(source);
// Stream the body incrementally so a server that omits or
// understates Content-Length can't make us buffer a chunked response
// past maxBytes — `await resp.arrayBuffer()` would happily allocate
// the entire payload before we get a chance to length-check it.
const reader = resp.body?.getReader();
if (!reader) {
const bytes = new Uint8Array(await resp.arrayBuffer());
if (bytes.length > maxBytes) {
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
// A single fetch attempt with the given headers. Streams the body
// incrementally so a server that omits or understates Content-Length
// can't make us buffer a chunked response past maxBytes — `await
// resp.arrayBuffer()` would happily allocate the entire payload before
// we get a chance to length-check it. Size-limit rejections are tagged
// `noRetry` so the outer retry doesn't re-download an oversized body.
const attempt = async (headers: Record<string, string>): Promise<LoadedBinary> => {
const resp = await fetch(source, {
headers,
redirect: 'follow',
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
const declared = Number(resp.headers.get('content-length') ?? '0');
if (Number.isFinite(declared) && declared > maxBytes) {
throw tooLarge(`${resourceName} too large: ${declared} > ${maxBytes}`);
}
const reader = resp.body?.getReader();
if (!reader) {
const bytes = new Uint8Array(await resp.arrayBuffer());
if (bytes.length > maxBytes) {
throw tooLarge(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
}
return { bytes, fileName };
}
const chunks: Uint8Array[] = [];
let total = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (!value) continue;
total += value.byteLength;
if (total > maxBytes) {
await reader.cancel().catch(() => { /* ignore */ });
throw tooLarge(`${resourceName} too large: > ${maxBytes}`);
}
chunks.push(value);
}
} finally {
reader.releaseLock();
}
const bytes = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
return { bytes, fileName };
}
const chunks: Uint8Array[] = [];
let total = 0;
};
// First try with a browser UA only. On any non-size failure — a
// network-level `fetch failed` (connection reset by an anti-bot
// front-end) or a 403/4xx from anti-hotlink — retry once with a
// Referer pointing at the resource itself, the common bypass for
// same-origin hotlink checks. Mirrors NapCat's with/without-Referer
// strategy.
const baseHeaders: Record<string, string> = {
'User-Agent': DOWNLOAD_USER_AGENT,
Accept: '*/*',
};
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (!value) continue;
total += value.byteLength;
if (total > maxBytes) {
await reader.cancel().catch(() => { /* ignore */ });
throw new Error(`${resourceName} too large: > ${maxBytes}`);
}
chunks.push(value);
return await attempt(baseHeaders);
} catch (err) {
if ((err as { noRetry?: boolean } | null)?.noRetry) throw err;
try {
return await attempt({ ...baseHeaders, Referer: source });
} catch {
throw err;
}
} finally {
reader.releaseLock();
}
const bytes = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
return { bytes, fileName };
}
const filePath = resolveLocalFilePath(source);

View File

@@ -1,12 +1,14 @@
import fs from 'fs';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import path from 'path';
import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite';
import type {
FriendInfo, GroupMemberInfo, QQGroupInfo,
UserProfileInfo, GroupRequestInfo,
} from './qq-info';
import { createLogger, type Logger } from '@snowluma/common/logger';
import type {
FriendInfo, GroupMemberInfo,
GroupRequestInfo,
QQGroupInfo,
UserProfileInfo,
} from './qq-info';
const moduleLogger = createLogger('Identity');
@@ -109,14 +111,14 @@ export class IdentityService {
private readonly uidByUin = new Map<number, string>();
// ─── Persistence + fetcher ───
private readonly db: DatabaseType | null;
private readonly db: DatabaseSync | null;
// Prepared-statement cache. Every `.prepare(sql)` call in this
// service re-parses the SQL — that's the SQLite anti-pattern
// RoadMap #5 is fixing. We memoize by the SQL string itself so the
// call sites stay readable (no need to enumerate 20+ named fields
// upfront); the Map lookup is O(1) hash + string-eq, which is
// negligible next to the SQL parse it replaces.
private readonly stmtCache_ = new Map<string, Statement>();
private readonly stmtCache_ = new Map<string, StatementSync>();
private inTransaction = false;
private fetcher: IdentityFetcher | null = null;
private readonly log: Logger;
@@ -134,16 +136,16 @@ export class IdentityService {
}
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
this.db = new Database(dbPath);
this.db.pragma('journal_mode = WAL');
this.db.pragma('synchronous = NORMAL');
this.db = new DatabaseSync(dbPath);
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('PRAGMA synchronous = NORMAL');
this.initSchema();
this.loadSnapshot();
}
/** Cached `prepare(sql)`. First call per unique SQL parses; later
* calls reuse the same `Statement` object. See `stmtCache_`. */
private pstmt(sql: string): Statement {
private pstmt(sql: string): StatementSync {
let cached = this.stmtCache_.get(sql);
if (cached !== undefined) return cached;
cached = this.db!.prepare(sql);

View File

@@ -12,6 +12,7 @@ import type {
GeneralGrayTipInfo,
NewFriend,
} from '@snowluma/proto-defs/notify';
import type { PttTransPush } from '@snowluma/proto-defs/ptt-trans';
import type { MsgPushContext } from '../context';
import { Event0x210SubType } from '../enums';
import {
@@ -28,6 +29,7 @@ const unknownLog = createLogger('MsgPush.Unknown');
export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
switch (ctx.head.subType as Event0x210SubType) {
case Event0x210SubType.FriendRequestNotice: return decodeFriendRequest(ctx);
case Event0x210SubType.PttTransResult: return decodePttTransResult(ctx);
// 138 (other-recalled) and 139 (self-recalled) share the same
// FriendRecall wire shape; the helper picks the right uid side
// based on the subType.
@@ -58,6 +60,20 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
return [];
};
// Voice-to-text async result push. Wire shape (live-verified):
// { f1: uint, f2: { f1 = msgId (echoes the request), f8 = text, ... } }
// `msgId` is the correlation key a pending fetch_ptt_text waits on; we surface
// it + the recognised text as an internal `ptt_trans_result` event.
function decodePttTransResult(ctx: MsgPushContext): QQEventVariant[] {
const push = protobuf_decode<PttTransPush>(ctx.content);
const item = push?.item;
if (!item) return [];
const msgId = Number(item.msgId ?? 0n);
const text = item.text ?? '';
if (!msgId || !text) return [];
return [{ kind: 'ptt_trans_result', time: ctx.head.timestamp, selfUin: ctx.selfUin, msgId, text }];
}
function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] {
const request = protobuf_decode<FriendRequest>(ctx.content);
if (!request?.info) return [];

Some files were not shown because too many files have changed in this diff Show More