Merge pull request #81 from SnowLuma/dev

chore: promote dev → main (4fcaba2)
This commit is contained in:
snowluma-bot[bot] authored and GitHub committed 2026-06-03 13:56:10 +00:00
commit 46cbd29956
71 files changed
+11608 -1942

No files matched your search

+109
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}"
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "snowluma-monorepo",
"version": "1.9.4",
"version": "1.9.5",
"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",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/bridge",
"version": "1.9.4",
"version": "1.9.5",
"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).",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/common",
"version": "1.9.4",
"version": "1.9.5",
"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).",
+67
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);
}
+104 -17
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';
+35
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;
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/core",
"version": "1.9.4",
"version": "1.9.5",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
+69
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
}
}
+20 -1
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);
+1
View File
@@ -0,0 +1 @@
dist/
+113
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`.
+49
View File
@@ -0,0 +1,49 @@
{
"name": "@snowluma/mcp",
"version": "1.9.5",
"description": "MCP server exposing the SnowLuma OneBot action catalog (read-only docs + JSON Schemas) to LLM clients.",
"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"
}
}
+32
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);
});
+69
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
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
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
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;
}
+39
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();
});
});
+138
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');
});
});
+13
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/**/*"]
}
+17
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',
},
},
});
+9 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/onebot",
"version": "1.9.4",
"version": "1.9.5",
"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"
+89
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';
}
+483
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
+44 -27
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);
}
+130 -113
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);
}
+119 -120
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);
}
+153 -114
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);
}
+103 -67
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);
}
+58 -27
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);
}
+76 -86
View File
@@ -1,6 +1,6 @@
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';
/**
@@ -32,96 +32,86 @@ async function refreshStoredImageUrls(event: JsonObject, ctx: ApiActionContext):
}
}
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');
}
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');
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 });
}
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
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 });
}
},
}),
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 });
});
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 });
},
}),
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);
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 });
},
}),
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');
}
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);
},
}),
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
return okResponse({ message_id: result.messageId });
});
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();
},
}),
];
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;
await refreshStoredImageUrls(result, ctx);
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 function register(h: ApiHandler, ctx: ApiActionContext): void {
registerActions(h, ctx, actions);
}
+39 -20
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);
}
+28 -7
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
+40 -6
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 {
+2
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';
@@ -116,6 +117,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
},
getImageInfo: (file) => getCachedImageInfo(mediaStore, file, ref.converterCtx.imageUrlResolver),
getRecordInfo: (file) => getCachedRecordInfo(bridge, mediaStore, file),
fetchPttText: (messageId) => fetchPttTextAction(messageStore, mediaStore, bridge, ref.selfId, messageId),
};
}
+4 -3
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;
@@ -3,10 +3,78 @@ 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,
+46 -70
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');
@@ -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);
}
+60 -2
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';
@@ -33,12 +34,16 @@ 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; }
@@ -47,10 +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;
}
}
@@ -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 AdapterStatus, type NetworkAdapterContext } from './adapter';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { executeQuickOperation } from './quick-operation';
const moduleLog = createLogger('OneBot.POST');
@@ -14,20 +14,11 @@ const DEFAULT_TIMEOUT_MS = 5000;
export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
private options: EventReportOptions;
private signature_: string;
private lastDelivery: { at: number; ok: boolean } | null = null;
private readonly log: Logger;
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 {
@@ -49,33 +40,16 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
: { name: this.name, kind: 'httpClient', status: 'warn', detail: `上次推送失败 ${at}` };
}
async reload(next: HttpClientNetwork): Promise<NetworkReloadType> {
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false && !!next.url;
protected override bindingSignature(config: HttpClientNetwork): string {
return `${config.url}#${config.accessToken ?? ''}#${config.timeoutMs ?? DEFAULT_TIMEOUT_MS}`;
}
this.config = structuredClone(next);
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 {
@@ -139,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');
@@ -1,4 +1,4 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import { createLogger } from '@snowluma/common/logger';
import {
createServer,
type IncomingMessage,
@@ -7,7 +7,7 @@ import {
} from 'http';
import type { DispatchPayload } from '../event-filter';
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath } from './utils';
const moduleLog = createLogger('OneBot.HTTP');
@@ -15,16 +15,9 @@ const moduleLog = createLogger('OneBot.HTTP');
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
private server: Server | null = null;
private listening = false;
private readonly log: Logger;
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 {
@@ -48,31 +41,8 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
return { name: this.name, kind: 'httpServer', status: 'ok', detail: '监听中' };
}
async reload(next: HttpServerNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false;
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 */ }
@@ -223,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[] = [];
@@ -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 AdapterStatus, type NetworkAdapterContext } from './adapter';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { rawDataToString, safeClose, safeSend } from './utils';
const moduleLog = createLogger('OneBot.WS-Client');
@@ -21,18 +21,11 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
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 {
@@ -61,33 +54,17 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
return { name: this.name, kind: 'wsClient', status: 'warn', detail: this.reconnectTimer ? '重连中' : '连接中' };
}
async reload(next: WsClientNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false && !!next.url;
protected override bindingSignature(config: WsClientNetwork): string {
return `${config.url}#${config.role ?? 'Universal'}#${Math.max(1000, config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${config.accessToken ?? ''}`;
}
this.config = structuredClone(next);
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 {
@@ -181,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 ?? ''}`;
}
@@ -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 AdapterStatus, 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');
@@ -25,17 +25,10 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
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 {
@@ -71,33 +64,13 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
return { name: this.name, kind: 'wsServer', status: 'ok', detail: `${this.connections.size} 个客户端` };
}
async reload(next: WsServerNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false;
protected override bindingSignature(config: WsServerNetwork): string {
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path)}#${config.role ?? 'auto'}#${config.accessToken ?? ''}`;
}
this.config = structuredClone(next);
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 {
@@ -188,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 ?? ''}`;
}
+31
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('| 参数 | 类型 | 必填 | 默认 | 说明 |');
});
});
+220
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' });
});
});
@@ -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);
});
});
});
+106
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]');
});
});
+12 -6
View File
@@ -481,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([]);
});
@@ -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);
+35 -4
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();
});
});
@@ -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();
});
});
+5 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/proto-defs",
"version": "1.9.4",
"version": "1.9.5",
"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"
+97
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>;
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/protocol",
"version": "1.9.4",
"version": "1.9.5",
"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>'`.",
+14 -1
View File
@@ -263,6 +263,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 +292,5 @@ export type QQEventVariant =
| GroupEssenceEvent
| GroupFileUploadEvent
| FriendAddEvent
| GroupMsgEmojiLikeEvent;
| GroupMsgEmojiLikeEvent
| PttTransResultEvent;
@@ -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;
}
@@ -286,6 +288,6 @@ export async function uploadHighwayHttp(
);
}
offset += chunkSize;
console.log(`[Highway] uploaded ${offset}/${bytes.length} bytes`);
log.trace('uploaded %d/%d bytes', offset, bytes.length);
}
}
@@ -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 [];
+8
View File
@@ -36,6 +36,14 @@ export enum Event0x2DCSubType {
export enum Event0x210SubType {
FriendRequestNotice = 35,
/**
* Voice-to-text (语音转文字) async result push, fired after a
* `pttTrans.Trans{C2C,Group}PttReq` once the server finishes transcribing.
* Live-verified body: `{ f1:uint, f2:{ f1=msgId, f8=text, ... } }`. There's
* no static sys_msg_0x210_0x3d handler — the ptt-trans subsystem registers
* it dynamically; we decode it into an internal `ptt_trans_result` event.
*/
PttTransResult = 61,
/**
* Outgoing friend-message recall — bot recalled its own message that
* was sent to a friend. Same `FriendRecall` wire shape as 138; the
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/proton",
"version": "1.9.4",
"version": "1.9.5",
"private": true,
"type": "module",
"description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/runtime",
"version": "1.9.4",
"version": "1.9.5",
"private": true,
"type": "module",
"main": "index.mjs",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "[email protected]"
},
"version": "1.9.4",
"version": "1.9.5",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "[email protected]"
},
"version": "1.9.4",
"version": "1.9.5",
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
"keywords": [
"snowluma",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/websocket",
"version": "1.9.4",
"version": "1.9.5",
"private": true,
"type": "module",
"main": "./src/index.ts",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "webui",
"private": true,
"version": "1.9.4",
"version": "1.9.5",
"type": "module",
"scripts": {
"dev": "vite",
@@ -12,6 +12,7 @@ import type { LogEntry, LogLevel } from '@/types';
import { useApi } from '@/lib/api';
const levelClass: Record<LogLevel, string> = {
trace: 'text-muted-foreground/60',
debug: 'text-muted-foreground',
info: 'text-primary',
success: 'text-success',
@@ -19,7 +20,7 @@ const levelClass: Record<LogLevel, string> = {
error: 'text-destructive',
};
const LEVELS: LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
const LEVELS: LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
/** Show a locale time when the backend sends an ISO timestamp (it does);
* fall back to the raw string otherwise so we never render "Invalid Date". */
@@ -98,7 +99,8 @@ export function LogsPage() {
return (
l.message.toLowerCase().includes(f) ||
l.scope.toLowerCase().includes(f) ||
l.level.toLowerCase().includes(f)
l.level.toLowerCase().includes(f) ||
(l.req !== undefined && String(l.req).includes(f))
);
});
}, [logs, filter, enabledLevels]);
@@ -223,6 +225,11 @@ export function LogsPage() {
{log.level.toUpperCase()}
</span>
<span className="min-w-0 truncate text-muted-foreground sm:w-28">[{log.scope}]</span>
{log.req !== undefined && (
<span className="shrink-0 rounded bg-primary/10 px-1 text-[10px] text-primary tabular-nums" title="请求关联号">
#{log.req}
</span>
)}
</div>
<span className="min-w-0 whitespace-pre-wrap break-all">{log.message}</span>
</motion.div>
+3 -1
View File
@@ -124,7 +124,7 @@ export interface SystemInfo {
};
}
export type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
export type LogLevel = 'trace' | 'debug' | 'info' | 'success' | 'warn' | 'error';
export interface LogEntry {
id: number;
@@ -132,6 +132,8 @@ export interface LogEntry {
level: LogLevel;
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
uin?: number;
/** Request correlation id, when emitted inside a request scope. */
req?: number;
scope: string;
message: string;
line: string;
+675
View File
File diff suppressed because it is too large. Load diff