From 9b92f3825d7e53457febf79c108b3d0494f66bea Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 2 Jun 2026 15:21:46 +0800 Subject: [PATCH 01/12] refactor(onebot): declarative action-kit for param coercion + validation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Introduce packages/onebot/src/action-kit.ts — a zero-dependency, type-inferring declarative layer for OneBot action params. Each action declares its param contract (f.* coercers + optional cross-field rules) and a `run` handler that receives typed, already-validated params. Validation failures now return BAD_REQUEST naming the offending field instead of falling through to ApiHandler's INTERNAL_ERROR catch. - 141/142 actions migrated to defineAction/groupAction/groupUserAction across info/message/friend/group-*/request/extended; only .handle_quick_operation stays legacy (it needs the ApiHandler instance, which run() does not receive). - f.messageId() distinguishes signed/non-zero message ids from positive group/user ids (f.uint()); int({min:0}).default(1800) fixes duration=0 (unmute), which the old `|| 1800` silently swallowed. - run(p, ctx, raw) exposes the raw params as an escape hatch for the irregular tail (alias-key fallbacks, arbitrary objects). - action-docs.ts renders self-generated API docs from describe(). - ApiHandler dispatch / try-catch / response-wrapping unchanged (narrow seam). Registered action name set is byte-identical before/after (142, verified by runtime enumeration). Typecheck clean; onebot suite green (the pre-existing websocket native-addon test failure is unrelated). --- packages/onebot/src/action-docs.ts | 80 + packages/onebot/src/action-kit.ts | 418 ++++ packages/onebot/src/actions/extended.ts | 2391 +++++++++++--------- packages/onebot/src/actions/friend.ts | 69 +- packages/onebot/src/actions/group-admin.ts | 243 +- packages/onebot/src/actions/group-album.ts | 237 +- packages/onebot/src/actions/group-file.ts | 263 ++- packages/onebot/src/actions/group-info.ts | 164 +- packages/onebot/src/actions/info.ts | 80 +- packages/onebot/src/actions/message.ts | 161 +- packages/onebot/src/actions/request.ts | 59 +- packages/onebot/tests/action-docs.test.ts | 31 + packages/onebot/tests/action-kit.test.ts | 184 ++ 13 files changed, 2729 insertions(+), 1651 deletions(-) create mode 100644 packages/onebot/src/action-docs.ts create mode 100644 packages/onebot/src/action-kit.ts create mode 100644 packages/onebot/tests/action-docs.test.ts create mode 100644 packages/onebot/tests/action-kit.test.ts diff --git a/packages/onebot/src/action-docs.ts b/packages/onebot/src/action-docs.ts new file mode 100644 index 00000000..0d89e09b --- /dev/null +++ b/packages/onebot/src/action-docs.ts @@ -0,0 +1,80 @@ +// 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>>; + +const ALL_SPECS: readonly AnySpec[] = [ + ...infoActions, + ...messageActions, + ...friendActions, + ...groupInfoActions, + ...groupAdminActions, + ...groupFileActions, + ...requestActions, + ...extendedActions, + ...groupAlbumActions, +]; + +/** Every declarative action's doc, sorted by name. */ +export function collectActionDocs(specs: readonly AnySpec[] = ALL_SPECS): ActionDoc[] { + return specs.map((s) => s.describe()).sort((a, b) => a.name.localeCompare(b.name)); +} + +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(', ')})_` : ''; + lines.push(`### \`${doc.name}\`${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'; +} diff --git a/packages/onebot/src/action-kit.ts b/packages/onebot/src/action-kit.ts new file mode 100644 index 00000000..644686a0 --- /dev/null +++ b/packages/onebot/src/action-kit.ts @@ -0,0 +1,418 @@ +// 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` 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 = { 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 = Ok | Err; + +const ok = (value: T): Ok => ({ 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) ─────────────────────────── + +export interface FieldDoc { + type: string; + required: boolean; + default?: JsonValue; + desc?: string; + values?: readonly (string | number)[]; +} + +export interface Field { + readonly doc: FieldDoc; + /** Coerce the raw value at this field's key (MISSING when the key is absent). */ + coerce(raw: Raw, field: string): CoerceResult; + /** Absent ⇒ value is `undefined`; a present value still must coerce. */ + optional(): Field; + /** 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; + describe(text: string): Field; +} + +/** Core coerces a PRESENT value (never MISSING). Presence policy is applied + * by the wrapping Field. */ +type Core = (raw: JsonValue, field: string) => CoerceResult; + +class FieldImpl implements Field { + constructor( + private readonly core: Core, + readonly doc: FieldDoc, + ) {} + + coerce(raw: Raw, field: string): CoerceResult { + 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 { + return new FieldImpl(this.core as Core, { + ...this.doc, + required: false, + default: undefined, + }); + } + + default(value: T): Field { + return new FieldImpl(this.core, { ...this.doc, required: false, default: value as JsonValue }); + } + + describe(text: string): Field { + return new FieldImpl(this.core, { ...this.doc, desc: text }); + } +} + +// ─────────────────────────── 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 { + 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); + }; +} + +interface StrOpts { allowEmpty?: boolean; maxLen?: number } + +function arrayField(el: Field, mustBeNonEmpty: boolean): Field & { nonEmpty(): Field } { + const core: Core = (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(core, { type: `${el.doc.type}[]`, required: true }); + return Object.assign(base, { nonEmpty: () => arrayField(el, true) }); +} + +export const f = { + /** Positive integer (>0): group_id / user_id / message_id. */ + uint(): Field { + return new FieldImpl(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true }); + }, + /** 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 { + return new FieldImpl(intCore('an integer', opts), { type: 'int', required: true }); + }, + /** 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 { + return new FieldImpl(intCore('a message id', { nonZero: true }), { type: 'messageId', required: true }); + }, + /** Finite number (fractions allowed). */ + number(): Field { + return new FieldImpl((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 }); + }, + /** String. Numbers/booleans stringify (matches legacy `asString`). Empty + * allowed by default; `{ allowEmpty: false }` rejects ''. */ + string(opts: StrOpts = {}): Field { + return new FieldImpl((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 }); + }, + /** true/1/yes/on ⇒ true; false/0/no/off ⇒ false (matches legacy `asBoolean`). */ + bool(): Field { + return new FieldImpl((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 }); + }, + /** 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 { + return new FieldImpl((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 }); + }, + /** Homogeneous array; `.nonEmpty()` rejects []. */ + array(el: Field): Field & { nonEmpty(): Field } { + return arrayField(el, false); + }, + /** Constrained literal set. */ + enum(...values: V): Field { + return new FieldImpl((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 }); + }, + /** Escape hatch — pass the raw value (or undefined) through, validate nothing. */ + raw(): Field { + return new FieldImpl((raw) => ok(raw), { type: 'raw', required: false, default: undefined }); + }, +}; + +// ─────────────────────────── type inference ─────────────────────────── + +type Spec = Record>; +type FieldType = F extends Field ? T : never; +/** Post-validation every key is present; optional/raw fields carry `undefined` + * in their value type. */ +export type InferParams = { [K in keyof S]: FieldType }; + +// ─────────────────────────── cross-field rules ─────────────────────────── + +export interface CrossFieldRule { + readonly doc: string; + check(params: Record): Err | null; +} + +type Key

= Extract; +type Group

= Key

| Key

[]; + +export interface RuleBuilders

{ + /** 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

[]): CrossFieldRule; + atLeastOneOf(...keys: Key

[]): CrossFieldRule; + requiredTogether(...keys: Key

[]): CrossFieldRule; + mutuallyExclusive(...keys: Key

[]): CrossFieldRule; + /** Arbitrary predicate; fails with `doc` as the reason. */ + rule(doc: string, ok: (p: P) => boolean): CrossFieldRule; +} + +const present = (p: Record, key: string): boolean => p[key] !== undefined; +const groupOk = (p: Record, 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> = { + 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[]; + summary?: string; + returns?: string; + params: ParamDoc[]; + invariants: string[]; +} + +type Handler = (params: JsonObject) => Promise; + +export interface ActionSpec { + readonly names: string[]; + readonly params: S; + /** Pure: coerce + validate + cross-field, no ctx, no I/O. The test surface. */ + parse(raw: JsonObject): CoerceResult>; + /** 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 { + name: string | readonly [string, ...string[]]; + summary?: string; + returns?: string; + params: S; + rules?: (r: RuleBuilders>) => 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, ctx: ApiActionContext, raw: JsonObject) => Promise | ApiResponse; +} + +const wording = (e: Err): string => (e.field ? `${e.field}: ${e.reason}` : e.reason); + +export function defineAction(def: ActionDef): ActionSpec { + const names = typeof def.name === 'string' ? [def.name] : [...def.name]; + const rules: readonly CrossFieldRule[] = def.rules + ? def.rules(RULES as unknown as RuleBuilders>) + : []; + + const parse = (raw: JsonObject): CoerceResult> => { + const out: Record = {}; + 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); + }; + + 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: () => ({ + name: names[0], + aliases: names.slice(1), + summary: def.summary, + returns: def.returns, + params: Object.entries(def.params).map(([name, field]) => ({ name, ...field.doc })), + invariants: rules.map((rule) => rule.doc), + }), + 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 & { group_id: Field }; +type WithGroupUser = S & { group_id: Field; user_id: Field }; + +interface PresetDef { + name: string | readonly [string, ...string[]]; + summary?: string; + returns?: string; + params?: S; + rules?: (r: RuleBuilders & Extra>) => readonly CrossFieldRule[]; + run: (p: InferParams & Extra, ctx: ApiActionContext, raw: JsonObject) => Promise | ApiResponse; +} + +/** Pre-seeds `group_id` (uint, required). */ +export function groupAction(def: PresetDef): ActionSpec> { + const params = { group_id: f.uint().describe('群号'), ...(def.params ?? {}) } as WithGroup; + return defineAction({ ...def, params } as unknown as ActionDef>); +} + +/** Pre-seeds `group_id` + `user_id` (both uint, required). */ +export function groupUserAction( + def: PresetDef, +): ActionSpec> { + const params = { + group_id: f.uint().describe('群号'), + user_id: f.uint().describe('QQ 号'), + ...(def.params ?? {}), + } as WithGroupUser; + return defineAction({ ...def, params } as unknown as ActionDef>); +} + +// ─────────────────────────── 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>): void { + for (const spec of specs) spec.register(h, ctx); +} diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 2a7ad844..2dd846af 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -1,8 +1,9 @@ import { readFile } from 'node:fs/promises'; import type { ApiActionContext, ApiHandler } from '../api-handler'; -import { asBoolean, asMessage, asNumber, asString } from '../api-handler'; +import { asNumber, asString } from '../api-handler'; import type { ForwardPreviewMeta } from '../modules/message-actions'; import { JsonObject, RETCODE, failedResponse, okResponse } from '../types'; +import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit'; const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB const DOWNLOAD_FILE_TIMEOUT_MS = 60_000; @@ -75,1136 +76,1372 @@ function readForwardPreviewMeta(params: Record): ForwardPreview return { source, summary, prompt, news }; } -export function register(h: ApiHandler, ctx: ApiActionContext): void { +// 群待办三动作(set/complete/cancel)共享:按 message_id 查消息元数据 → 校验归属 → 执行 op。 +async function groupTodoRun( + p: { group_id: number; message_id: number }, + ctx: ApiActionContext, + op: (groupId: number, msgSeq: bigint) => Promise, +) { + const meta = ctx.getMessageMeta(p.message_id); + if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found'); + if (!meta.isGroup || meta.targetId !== p.group_id) { + return failedResponse(RETCODE.ACTION_FAILED, 'message does not belong to this group'); + } + try { + await op(p.group_id, BigInt(meta.sequence)); + return okResponse(); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } +} + +export const actions = [ // 赞 - h.registerAction('send_like', async (params) => { - const userId = asNumber(params.user_id); - const times = asNumber(params.times) || 1; - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - await ctx.bridge.apis.interaction.sendLike(userId, times); - return okResponse(); - }); + defineAction({ + name: 'send_like', + summary: '点赞', + params: { + user_id: f.uint(), + // 原实现用 `asNumber(times) || 1`,present 0 会被当作缺省 1。 + times: f.int({ min: 0 }).default(1), + }, + run: async (p, ctx) => { + await ctx.bridge.apis.interaction.sendLike(p.user_id, p.times); + return okResponse(); + }, + }), // 拍一拍 - h.registerAction('friend_poke', async (params) => { - const userId = asNumber(params.user_id); - const targetId = asNumber(params.target_id) || undefined; - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - await ctx.bridge.apis.interaction.sendPoke(false, userId, targetId); - return okResponse(); - }); + defineAction({ + name: 'friend_poke', + summary: '好友拍一拍', + params: { + user_id: f.uint(), + target_id: f.uint().optional(), + }, + run: async (p, ctx) => { + await ctx.bridge.apis.interaction.sendPoke(false, p.user_id, p.target_id); + return okResponse(); + }, + }), - h.registerAction('group_poke', 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'); - await ctx.bridge.apis.interaction.sendPoke(true, groupId, userId); - return okResponse(); - }); + groupUserAction({ + name: 'group_poke', + summary: '群拍一拍', + run: async (p, ctx) => { + await ctx.bridge.apis.interaction.sendPoke(true, p.group_id, p.user_id); + return okResponse(); + }, + }), - h.registerAction('send_poke', async (params) => { - const groupId = asNumber(params.group_id); - const userId = asNumber(params.user_id); - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - if (groupId) { - await ctx.bridge.apis.interaction.sendPoke(true, groupId, userId); - } else { - await ctx.bridge.apis.interaction.sendPoke(false, userId); - } - return okResponse(); - }); + defineAction({ + name: 'send_poke', + summary: '拍一拍(群聊/私聊自动路由)', + params: { + user_id: f.uint(), + group_id: f.uint().optional(), + }, + run: async (p, ctx) => { + if (p.group_id) { + await ctx.bridge.apis.interaction.sendPoke(true, p.group_id, p.user_id); + } else { + await ctx.bridge.apis.interaction.sendPoke(false, p.user_id); + } + return okResponse(); + }, + }), // 精华消息 - h.registerAction('set_essence_msg', async (params) => { - const messageId = asNumber(params.message_id); - if (!Number.isInteger(messageId) || messageId === 0) { - return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); - } - await ctx.setEssenceMsg(messageId); - return okResponse(); - }); + defineAction({ + name: 'set_essence_msg', + summary: '设置精华消息', + params: { message_id: f.messageId() }, + run: async (p, ctx) => { + await ctx.setEssenceMsg(p.message_id); + return okResponse(); + }, + }), - h.registerAction('delete_essence_msg', async (params) => { - const messageId = asNumber(params.message_id); - if (!Number.isInteger(messageId) || messageId === 0) { - return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); - } - await ctx.deleteEssenceMsg(messageId); - return okResponse(); - }); + defineAction({ + name: 'delete_essence_msg', + summary: '移除精华消息', + params: { message_id: f.messageId() }, + run: async (p, ctx) => { + await ctx.deleteEssenceMsg(p.message_id); + return okResponse(); + }, + }), - h.registerAction('get_essence_msg_list', async (params) => { - const groupId = asNumber(params.group_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + groupAction({ + name: 'get_essence_msg_list', + summary: '获取精华消息列表', + run: async (p, ctx) => { + try { + const essenceDataAll = await ctx.bridge.apis.web.getEssenceAll(p.group_id); + const allMsgs = essenceDataAll.flatMap((res) => res.data?.msg_list || []); - try { - const essenceDataAll = await ctx.bridge.apis.web.getEssenceAll(groupId); - - const allMsgs = essenceDataAll.flatMap((res) => res.data?.msg_list || []); - - return okResponse(allMsgs); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, `获取精华消息失败: ${e}`); - } - }); + return okResponse(allMsgs); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, `获取精华消息失败: ${e}`); + } + }, + }), // 群聊表情回应 - h.registerAction('set_group_reaction', async (params) => { - const groupId = asNumber(params.group_id); - const messageId = asNumber(params.message_id); - const code = asString(params.code); - const isSet = asBoolean(params.is_set, true); + defineAction({ + name: 'set_group_reaction', + summary: '群聊表情回应', + params: { + group_id: f.uint().optional(), + message_id: f.messageId(), + code: f.string({ allowEmpty: false }), + is_set: f.bool().default(true), + }, + run: async (p, ctx) => { + const meta = ctx.getMessageMeta(p.message_id); + if (!meta || !meta.isGroup) { + return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a group message'); + } - if (!Number.isInteger(messageId) || messageId === 0 || !code) { - return failedResponse(RETCODE.BAD_REQUEST, 'message_id and code are required'); - } + if (p.group_id && p.group_id !== meta.targetId) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session'); + } - const meta = ctx.getMessageMeta(messageId); - if (!meta || !meta.isGroup) { - return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a group message'); - } - - if (groupId && groupId !== meta.targetId) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session'); - } - - await ctx.bridge.apis.interaction.setReaction(meta.targetId, meta.sequence, code, isSet); - return okResponse(); - }); + await ctx.bridge.apis.interaction.setReaction(meta.targetId, meta.sequence, p.code, p.is_set); + return okResponse(); + }, + }), // 消息历史 - h.registerAction('get_group_msg_history', async (params) => { - const groupId = asNumber(params.group_id); - const messageId = asNumber(params.message_id) || 0; - const count = asNumber(params.count) || 20; - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - const messages = await ctx.getGroupMsgHistory(groupId, messageId, count); - return okResponse({ messages }); - }); + groupAction({ + name: 'get_group_msg_history', + summary: '获取群消息历史', + params: { + // 原实现用 `asNumber(message_id) || 0`,present 0 也映射为 0。 + message_id: f.int({ min: 0 }).default(0), + count: f.int({ min: 0 }).default(20), + }, + run: async (p, ctx) => { + const messages = await ctx.getGroupMsgHistory(p.group_id, p.message_id, p.count); + return okResponse({ messages }); + }, + }), - h.registerAction('get_friend_msg_history', async (params) => { - const userId = asNumber(params.user_id); - const messageId = asNumber(params.message_id) || 0; - const count = asNumber(params.count) || 20; - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - const messages = await ctx.getFriendMsgHistory(userId, messageId, count); - return okResponse({ messages }); - }); + defineAction({ + name: 'get_friend_msg_history', + summary: '获取好友消息历史', + params: { + user_id: f.uint(), + message_id: f.int({ min: 0 }).default(0), + count: f.int({ min: 0 }).default(20), + }, + run: async (p, ctx) => { + const messages = await ctx.getFriendMsgHistory(p.user_id, p.message_id, p.count); + return okResponse({ messages }); + }, + }), // 标记消息已读 - h.registerAction('mark_group_msg_as_read', async (params) => { - const messageId = asNumber(params.message_id); - const groupId = asNumber(params.group_id); + defineAction({ + name: 'mark_group_msg_as_read', + summary: '标记群消息已读', + params: { + message_id: f.messageId(), + group_id: f.uint().optional(), + }, + run: async (p, ctx) => { + const meta = ctx.getMessageMeta(p.message_id); + if (!meta || !meta.isGroup) { + return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a group message'); + } - if (!Number.isInteger(messageId) || messageId === 0) { - return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); - } - const meta = ctx.getMessageMeta(messageId); - if (!meta || !meta.isGroup) { - return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a group message'); - } + if (p.group_id && p.group_id !== meta.targetId) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session'); + } - if (groupId && groupId !== meta.targetId) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session'); - } - - await ctx.bridge.apis.message.markGroupRead(meta.targetId, meta.sequence); - return okResponse(); - }); - - h.registerAction('mark_private_msg_as_read', async (params) => { - const messageId = asNumber(params.message_id); - const userId = asNumber(params.user_id); - - if (!Number.isInteger(messageId) || messageId === 0) { - return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); - } - const meta = ctx.getMessageMeta(messageId); - if (!meta || meta.isGroup) { - return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a private message'); - } - - if (userId && userId !== meta.targetId) { - return failedResponse(RETCODE.BAD_REQUEST, 'user_id does not match message session'); - } - - await ctx.bridge.apis.message.markPrivateRead(meta.targetId, meta.sequence); - return okResponse(); - }); - - h.registerAction('mark_msg_as_read', async (params) => { - const messageId = asNumber(params.message_id); - const targetId = asNumber(params.target_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'); - - if (targetId && targetId !== meta.targetId) { - return failedResponse(RETCODE.BAD_REQUEST, 'target_id does not match message session'); - } - - if (meta.isGroup) { await ctx.bridge.apis.message.markGroupRead(meta.targetId, meta.sequence); - } else { + return okResponse(); + }, + }), + + defineAction({ + name: 'mark_private_msg_as_read', + summary: '标记私聊消息已读', + params: { + message_id: f.messageId(), + user_id: f.uint().optional(), + }, + run: async (p, ctx) => { + const meta = ctx.getMessageMeta(p.message_id); + if (!meta || meta.isGroup) { + return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a private message'); + } + + if (p.user_id && p.user_id !== meta.targetId) { + return failedResponse(RETCODE.BAD_REQUEST, 'user_id does not match message session'); + } + await ctx.bridge.apis.message.markPrivateRead(meta.targetId, meta.sequence); - } - return okResponse(); - }); + return okResponse(); + }, + }), + defineAction({ + name: 'mark_msg_as_read', + summary: '标记消息已读(群聊/私聊自动路由)', + params: { + message_id: f.messageId(), + target_id: f.uint().optional(), + }, + run: async (p, ctx) => { + const meta = ctx.getMessageMeta(p.message_id); + if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found'); - // 下载密钥 - const handleGetRkey = async () => { - if (ctx.getDownloadRKeys) { - return okResponse(await ctx.getDownloadRKeys()); - } - return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); - }; - h.registerAction('get_rkey', handleGetRkey); - h.registerAction('nc_get_rkey', handleGetRkey); + if (p.target_id && p.target_id !== meta.targetId) { + return failedResponse(RETCODE.BAD_REQUEST, 'target_id does not match message session'); + } - // OCR 兜底未实现。 - - h.registerAction('ocr_image', async () => { - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); - }); - - h.registerAction('.ocr_image', async () => { - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); - }); + if (meta.isGroup) { + await ctx.bridge.apis.message.markGroupRead(meta.targetId, meta.sequence); + } else { + await ctx.bridge.apis.message.markPrivateRead(meta.targetId, meta.sequence); + } + return okResponse(); + }, + }), // 群公告 - h.registerAction('_send_group_notice', async (params) => { - const groupId = asNumber(params.group_id); - const content = asString(params.content); - const image = asString(params.image); + groupAction({ + name: '_send_group_notice', + summary: '发送群公告', + params: { + content: f.string({ allowEmpty: false }), + image: f.string().default(''), + pinned: f.raw(), + type: f.raw(), + confirm_required: f.raw(), + }, + run: async (p, ctx) => { + try { + const options = { + image: p.image || undefined, + pinned: p.pinned !== undefined ? Number(p.pinned) : 0, + type: p.type !== undefined ? Number(p.type) : 1, + confirm_required: p.confirm_required !== undefined ? Number(p.confirm_required) : 1, + }; - if (!groupId || !content) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id and content are required'); - } - - - try { - const options = { - image: image || undefined, - pinned: params.pinned !== undefined ? Number(params.pinned) : 0, - type: params.type !== undefined ? Number(params.type) : 1, - confirm_required: params.confirm_required !== undefined ? Number(params.confirm_required) : 1, - }; - - await ctx.bridge.apis.web.sendNotice(groupId, content, options); - return okResponse(); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('_get_group_notice', async (params) => { - const groupId = asNumber(params.group_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - - - try { - const notices = await ctx.bridge.apis.web.getNotice(groupId); - return okResponse(notices); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('_del_group_notice', async (params) => { - const groupId = asNumber(params.group_id); - const fid = asString(params.fid) || asString(params.notice_id); - - if (!groupId || !fid) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id and fid/notice_id are required'); - } - - - try { - const success = await ctx.bridge.apis.web.deleteNotice(groupId, fid); - if (success) { + await ctx.bridge.apis.web.sendNotice(p.group_id, p.content, options); return okResponse(); - } else { - return failedResponse(RETCODE.ACTION_FAILED, 'delete failed'); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); } - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); + }, + }), - // 转发消息。 - h.registerAction('upload_forward_msg', async (params) => { - const messages = asMessage(params.messages ?? params.message); - const groupId = asNumber(params.group_id); - if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); - // 群聊和私聊转发消息的 resId 是分开的(前者是 type=3+groupUin,后者是 type=1+selfUid), - const result = await ctx.sendForwardMsg(messages, groupId > 0 ? groupId : undefined); - const data: Record = { - res_id: result.forwardId, - forward_id: result.forwardId, - message_id: 0, - }; - if (groupId > 0) data.group_id = groupId; - return okResponse(data as import('../types').JsonObject); - }); - - h.registerAction('upload_foward_msg', async (params) => { - const messages = asMessage(params.messages ?? params.message); - const groupId = asNumber(params.group_id); - if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); - const result = await ctx.sendForwardMsg(messages, groupId > 0 ? groupId : undefined); - return okResponse({ res_id: result.forwardId, forward_id: result.forwardId, message_id: 0 }); - }); - - h.registerAction('send_forward_msg', async (params) => { - const messageType = asString(params.message_type); - const groupId = asNumber(params.group_id); - const userId = asNumber(params.user_id); - const messages = asMessage(params.messages ?? params.message); - const meta = readForwardPreviewMeta(params); - - if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); - - if ((messageType === 'group' || groupId > 0) && ctx.sendGroupForwardMsg) { - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - const result = await ctx.sendGroupForwardMsg(groupId, messages, meta); - return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); - } - - if ((messageType === 'private' || userId > 0) && ctx.sendPrivateForwardMsg) { - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - const result = await ctx.sendPrivateForwardMsg(userId, messages, meta); - return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); - } - - const result = await ctx.sendForwardMsg(messages); - return okResponse({ message_id: 0, res_id: result.forwardId, forward_id: result.forwardId }); - }); - - h.registerAction('send_group_forward_msg', async (params) => { - const groupId = asNumber(params.group_id); - const messages = asMessage(params.messages ?? params.message); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); - - const result = await ctx.sendGroupForwardMsg(groupId, messages, readForwardPreviewMeta(params)); - return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); - }); - - h.registerAction('send_private_forward_msg', async (params) => { - const userId = asNumber(params.user_id); - const messages = asMessage(params.messages ?? params.message); - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); - - const result = await ctx.sendPrivateForwardMsg(userId, messages, readForwardPreviewMeta(params)); - return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); - }); - - h.registerAction('get_forward_msg', async (params) => { - let id = asString(params.id); - if (!id) { - const rawMessageId = params.message_id; - const numericMessageId = asNumber(rawMessageId); - if (numericMessageId > 0) { - const event = ctx.getMessage(numericMessageId); - const segments = Array.isArray(event?.message) ? event.message : []; - for (const seg of segments) { - if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue; - const so = seg as Record; - if (String(so.type ?? '') !== 'forward') continue; - const data = (typeof so.data === 'object' && so.data !== null && !Array.isArray(so.data)) - ? so.data as Record - : null; - const candidate = asString(data?.id) || asString(data?.res_id) || asString(data?.forward_id); - if (candidate) { - id = candidate; - break; - } - } + groupAction({ + name: '_get_group_notice', + summary: '获取群公告', + run: async (p, ctx) => { + try { + const notices = await ctx.bridge.apis.web.getNotice(p.group_id); + return okResponse(notices); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); } + }, + }), - if (!id) { - id = asString(rawMessageId); - } - } + // 转发消息。messages/message 互为别名键,两者皆缺省视为未提供。 + defineAction({ + name: 'upload_forward_msg', + summary: '上传转发消息', + params: { + messages: f.message().optional(), + message: f.message().optional(), + group_id: f.uint().optional(), + }, + run: async (p, ctx) => { + const messages = p.messages ?? p.message; + const groupId = p.group_id ?? 0; + if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); + // 群聊和私聊转发消息的 resId 是分开的(前者是 type=3+groupUin,后者是 type=1+selfUid), + const result = await ctx.sendForwardMsg(messages, groupId > 0 ? groupId : undefined); + const data: Record = { + res_id: result.forwardId, + forward_id: result.forwardId, + message_id: 0, + }; + if (groupId > 0) data.group_id = groupId; + return okResponse(data as import('../types').JsonObject); + }, + }), - if (!id) return failedResponse(RETCODE.BAD_REQUEST, 'id or message_id is required'); - - const messages = await ctx.getForwardMsg(id); - return okResponse({ messages }); - }); + defineAction({ + name: 'upload_foward_msg', + summary: '上传转发消息(别名拼写)', + params: { + messages: f.message().optional(), + message: f.message().optional(), + group_id: f.uint().optional(), + }, + run: async (p, ctx) => { + const messages = p.messages ?? p.message; + const groupId = p.group_id ?? 0; + if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); + const result = await ctx.sendForwardMsg(messages, groupId > 0 ? groupId : undefined); + return okResponse({ res_id: result.forwardId, forward_id: result.forwardId, message_id: 0 }); + }, + }), // 文件信息 + defineAction({ + name: 'get_image', + summary: '获取图片信息', + params: { + file: f.string().default(''), + file_id: f.string().default(''), + }, + run: async (p, ctx) => { + const file = p.file || p.file_id; + if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required'); + const info = await ctx.getImageInfo(file); + if (info) return okResponse(info); + return failedResponse(RETCODE.ACTION_FAILED, 'image not found in cache'); + }, + }), - h.registerAction('get_image', async (params) => { - const file = asString(params.file) || asString(params.file_id); - if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required'); - const info = await ctx.getImageInfo(file); - if (info) return okResponse(info); - return failedResponse(RETCODE.ACTION_FAILED, 'image not found in cache'); - }); - - h.registerAction('get_record', async (params) => { - const file = asString(params.file) || asString(params.file_id); - if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required'); - const info = await ctx.getRecordInfo(file); - if (info) return okResponse(info); - return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache'); - }); + defineAction({ + name: 'get_record', + summary: '获取语音信息', + params: { + file: f.string().default(''), + file_id: f.string().default(''), + }, + run: async (p, ctx) => { + const file = p.file || p.file_id; + if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required'); + const info = await ctx.getRecordInfo(file); + if (info) return okResponse(info); + return failedResponse(RETCODE.ACTION_FAILED, 'record not found in cache'); + }, + }), // Cookie、CSRF 令牌和账号信息 + defineAction({ + name: 'get_cookies', + summary: '获取 Cookies', + params: { domain: f.string().default('qun.qq.com') }, + run: async (p, ctx) => { + try { + const cookies = await ctx.bridge.apis.web.getCookiesStr(p.domain || 'qun.qq.com'); + return okResponse({ cookies }); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), - h.registerAction('get_cookies', async (params) => { - const domain = asString(params.domain) || 'qun.qq.com'; + defineAction({ + name: 'get_csrf_token', + summary: '获取 CSRF 令牌', + params: {}, + run: async (_p, ctx) => { + try { + const token = await ctx.bridge.apis.web.getCsrfToken(); + return okResponse({ token }); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + defineAction({ + name: 'get_credentials', + summary: '获取凭证', + params: { domain: f.string().default('qun.qq.com') }, + run: async (p, ctx) => { + try { + const creds = await ctx.bridge.apis.web.getCredentials(p.domain || 'qun.qq.com'); + return okResponse(creds); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), - try { - const cookies = await ctx.bridge.apis.web.getCookiesStr(domain); - return okResponse({ cookies }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('get_csrf_token', async () => { - - try { - const token = await ctx.bridge.apis.web.getCsrfToken(); - return okResponse({ token }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('get_credentials', async (params) => { - const domain = asString(params.domain) || 'qun.qq.com'; - - - try { - const creds = await ctx.bridge.apis.web.getCredentials(domain); - return okResponse(creds); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); // 重启和清理缓存 + defineAction({ + name: 'set_restart', + summary: '重启(不支持)', + params: {}, + run: async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not supported'); + }, + }), - h.registerAction('set_restart', async () => { - return failedResponse(RETCODE.ACTION_FAILED, 'not supported'); - }); + defineAction({ + name: 'clean_cache', + summary: '清理缓存', + params: {}, + run: async () => { + return okResponse(); + }, + }), - h.registerAction('clean_cache', async () => { - return okResponse(); - }); + // 以下接口在方便用户迁移和兼容现有的 OneBot/NapCat 客户端。 + defineAction({ + name: 'set_friend_remark', + summary: '设置好友备注', + params: { + user_id: f.uint(), + remark: f.string(), + }, + run: async (p, ctx) => { + await ctx.bridge.apis.friend.setRemark(p.user_id, p.remark); + return okResponse(); + }, + }), + defineAction({ + name: 'set_group_remark', + summary: '设置群备注', + params: { + group_id: f.uint(), + remark: f.string(), + }, + run: async (p, ctx) => { + await ctx.bridge.apis.groupAdmin.setRemark(p.group_id, p.remark); + return okResponse(); + }, + }), + + defineAction({ + name: 'set_msg_emoji_like', + summary: '设置消息表情回应', + params: { + message_id: f.messageId(), + emoji_id: f.string({ allowEmpty: false }), + set: f.bool().default(true), + }, + run: async (p, ctx) => { + await ctx.setMsgEmojiLike(p.message_id, p.emoji_id, p.set); + return okResponse(); + }, + }), + + defineAction({ + name: '_mark_all_as_read', + summary: '标记全部已读', + params: {}, + run: async () => { + return okResponse(); + }, + }), + + groupAction({ + name: 'get_group_file_system_info', + summary: '获取群文件系统信息', + run: async (p, ctx) => { + const info = await ctx.bridge.apis.groupFile.getCount(p.group_id); + return okResponse({ + file_count: info.fileCount, + limit_count: info.maxCount, + used_space: 0, + total_space: 10737418240, + }); + }, + }), + + defineAction({ + name: 'check_url_safely', + summary: '检查链接安全性', + params: {}, + run: async () => { + return okResponse({ level: 1 }); + }, + }), + + defineAction({ + name: 'set_qq_profile', + summary: '设置 QQ 资料', + params: { + nickname: f.string().optional(), + personal_note: f.string().optional(), + }, + run: async (p, ctx) => { + const nickname = p.nickname; + const personalNote = p.personal_note; + + try { + await ctx.bridge.apis.profile.setProfile(nickname, personalNote); + return okResponse(); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'set_online_status', + summary: '设置在线状态', + params: { + // 原实现用 asNumber+`status===0` 拒绝,等价于必填非零整数。 + status: f.int({ nonZero: true }), + ext_status: f.int({ min: 0 }).default(0), + battery_status: f.int({ min: 0 }).default(100), + }, + run: async (p, ctx) => { + try { + await ctx.bridge.apis.profile.setOnlineStatus(p.status, p.ext_status, p.battery_status); + return okResponse(); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + // 自定义在线状态:与 set_online_status 使用相同的网络包。 + // 这里只填充 customExt 子消息,并将 status/extStatus 强制设为 QQ 定义的“我有自定义状态”取值(10 / 2000)。 + // face_id 和 face_type 可接受数字或数字字符串,以兼容 NapCat;wording 是图标旁展示的可读文本。 + defineAction({ + name: 'set_diy_online_status', + summary: '设置自定义在线状态', + params: { + face_id: f.uint(), + // 原实现用 `asNumber(face_type) || 1`,present 0 会被当作缺省 1。 + face_type: f.int({ min: 0 }).default(1), + wording: f.string().default(''), + }, + run: async (p, ctx) => { + try { + await ctx.bridge.apis.profile.setDiyOnlineStatus(p.face_id, p.wording, p.face_type); + return okResponse(); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }, + }), + + defineAction({ + name: 'get_group_ignored_notifies', + summary: '获取被过滤的入群请求', + params: {}, + run: async (_p, ctx) => { + const reqs = await fetchFilteredGroupRequests(ctx); + return okResponse(reqs.map((r) => ({ + group_id: r.groupId, + group_name: r.groupName, + request_id: r.sequence, + requester_uin: r.targetUin, + requester_nick: r.targetName, + message: r.comment, + checked: r.state !== 1, + actor: r.operatorUin, + invitor_uin: r.invitorUin, + invitor_nick: r.invitorName, + flag: `${r.eventType}:${r.groupId}:${r.targetUid}:filtered`, + }))); + }, + }), + + // NapCat 对“被忽略通知中属于入群请求的子集”的命名(notify type == 7)。 + // 这里把经过过滤的 0x10c8_2 每一项映射成 NapCat 结构。 + // eventType 已经在当前流水线中编码了请求类别。 + defineAction({ + name: 'get_group_ignore_add_request', + summary: '获取被忽略的入群请求(NapCat)', + params: {}, + run: async (_p, ctx) => { + const reqs = await fetchFilteredGroupRequests(ctx); + return okResponse(reqs.map((r) => ({ + request_id: r.sequence, + invitor_uin: r.invitorUin, + invitor_nick: r.invitorName, + group_id: r.groupId, + message: r.comment, + group_name: r.groupName, + checked: r.state !== 1, + actor: r.operatorUin, + requester_nick: r.targetName, + }))); + }, + }), + + // get_group_shut_list 依赖尚未封装的 oidb。 + // 这里遵循 NapCat 约定返回空列表,避免调用方出错。 + defineAction({ + name: 'get_group_shut_list', + summary: '获取群禁言列表(占位)', + params: {}, + run: async () => { + return okResponse([]); + }, + }), + + defineAction({ + name: 'forward_friend_single_msg', + summary: '转发单条消息给好友', + params: { + message_id: f.messageId(), + user_id: f.uint(), + }, + run: async (p, ctx) => { + try { + const result = await ctx.forwardSingleMsg(p.message_id, { userId: p.user_id }); + return okResponse({ message_id: result.messageId }); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }, + }), + + defineAction({ + name: 'forward_group_single_msg', + summary: '转发单条消息到群', + params: { + message_id: f.messageId(), + group_id: f.uint(), + }, + run: async (p, ctx) => { + try { + const result = await ctx.forwardSingleMsg(p.message_id, { groupId: p.group_id }); + return okResponse({ message_id: result.messageId }); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }, + }), + + defineAction({ + name: 'get_profile_like', + summary: '获取资料点赞', + params: { + // 原实现 user_id 经 asNumber,无校验(0 也透传)。 + user_id: f.int({ min: 0 }).default(0), + start: f.int({ min: 0 }).default(0), + count: f.int({ min: 0 }).default(10), + }, + run: async (p, ctx) => { + try { + const data = await ctx.bridge.apis.profile.getLike(p.user_id, p.start, p.count); + return okResponse(data); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'fetch_custom_face', + summary: '获取自定义表情', + params: { count: f.int({ min: 0 }).default(10) }, + run: async (p, ctx) => { + try { + const urls = await ctx.bridge.apis.profile.fetchCustomFace(p.count); + return okResponse(urls); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'get_emoji_likes', + summary: '获取表情回应用户', + params: { + message_id: f.messageId(), + emoji_id: f.string({ allowEmpty: false }), + }, + run: async (p, ctx) => { + try { + const result = await ctx.fetchEmojiLikeUsers(p.message_id, p.emoji_id, 1000); + return okResponse({ + emoji_like_list: result.users.map(u => ({ user_id: String(u.uin), nick_name: '' })), + }); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'fetch_emoji_like', + summary: '获取表情回应用户(NapCat 分页)', + params: { + message_id: f.messageId(), + emojiId: f.string({ allowEmpty: false }), + count: f.int({ min: 0 }).default(10), + cookie: f.string().default(''), + }, + run: async (p, ctx) => { + try { + const offset = p.cookie ? Number.parseInt(p.cookie, 10) || 0 : 0; + const result = await ctx.fetchEmojiLikeUsers(p.message_id, p.emojiId, p.count, offset); + const nextOffset = offset + result.users.length; + const isLastPage = nextOffset >= result.cachedCount; + return okResponse({ + result: 0, + errMsg: '', + emojiLikesList: result.users.map(u => ({ tinyId: String(u.uin), nickName: '', headUrl: '' })), + cookie: isLastPage ? '' : String(nextOffset), + isLastPage, + isFirstPage: offset === 0, + }); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'get_friends_with_category', + summary: '获取分组好友列表', + params: {}, + run: async (_p, ctx) => { + if (ctx.getFriendList) { + return okResponse(await ctx.getFriendList()); + } + return okResponse([]); + }, + }), + + // NapCat 似乎也用不了,暂时不处理。 + defineAction({ + name: 'get_online_clients', + summary: '获取在线客户端(占位)', + params: {}, + run: async () => { + return okResponse({ clients: [] }); + }, + }), + + defineAction({ + name: '_get_model_show', + summary: '获取机型展示(占位)', + params: {}, + run: async () => { + return okResponse({ variants: [] }); + }, + }), + + defineAction({ + name: '_set_model_show', + summary: '设置机型展示(占位)', + params: {}, + run: async () => { + return okResponse(); + }, + }), + + groupAction({ + name: 'get_group_at_all_remain', + summary: '获取群 @全体成员 剩余次数', + run: async (p, ctx) => { + try { + const data = await ctx.bridge.apis.groupAdmin.getAtAllRemain(p.group_id); + return okResponse(data); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'get_unidirectional_friend_list', + summary: '获取单向好友列表', + params: {}, + run: async (_p, ctx) => { + try { + const data = await ctx.bridge.apis.profile.getUnidirectionalFriendList(); + return okResponse(data); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'get_clientkey', + summary: '获取 clientkey', + params: {}, + run: async (_p, ctx) => { + const clientKeyInfo = await ctx.bridge.apis.web.forceFetchClientKey(); + if (!clientKeyInfo.clientKey) { + return failedResponse(RETCODE.ACTION_FAILED, 'get clientkey error'); + } + return okResponse({ ...clientKeyInfo }); + }, + }), + + defineAction({ + name: 'get_collection_list', + summary: '获取收藏列表(占位)', + params: {}, + run: async () => { + return okResponse([]); + }, + }), + + defineAction({ + name: 'create_collection', + summary: '创建收藏(未实现)', + params: {}, + run: async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }, + }), + + defineAction({ + name: '.get_word_slices', + summary: '分词(未实现)', + params: {}, + run: async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }, + }), + + defineAction({ + name: 'set_qq_avatar', + summary: '设置 QQ 头像', + params: { file: f.string({ allowEmpty: false }) }, + run: async (p, ctx) => { + try { + await ctx.bridge.apis.profile.setAvatar(p.file); + return okResponse(); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'set_input_status', + summary: '设置输入状态', + params: { + user_id: f.uint(), + // event_type 可能为 0(取消输入状态);缺省也按 0 处理(与旧 asNumber 行为一致)。 + event_type: f.int().default(0), + }, + run: async (p, ctx) => { + try { + await ctx.bridge.apis.profile.setInputStatus(p.user_id, p.event_type); + return okResponse({}); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'get_group_info_ex', + summary: '获取群信息(扩展)', + params: { group_id: f.uint() }, + run: async (p, ctx) => { + if (ctx.getGroupInfo) { + return okResponse(await ctx.getGroupInfo(p.group_id)); + } + return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + }, + }), + + defineAction({ + name: 'get_group_detail_info', + summary: '获取群详细信息', + params: { group_id: f.uint() }, + run: async (p, ctx) => { + if (ctx.getGroupInfo) { + return okResponse(await ctx.getGroupInfo(p.group_id)); + } + return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); + }, + }), + + defineAction({ + name: 'trans_group_file', + summary: '转存群文件(未实现)', + params: {}, + run: async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }, + }), + + defineAction({ + name: 'rename_group_file', + summary: '重命名群文件(未实现)', + params: {}, + run: async () => { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }, + }), + + defineAction({ + name: 'get_file', + summary: '获取文件(未实现)', + params: { + file_id: f.string().default(''), + file: f.string().default(''), + }, + run: async (p) => { + const fileId = p.file_id || p.file; + if (!fileId) return failedResponse(RETCODE.BAD_REQUEST, 'file_id is required'); + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + }, + }), + + // 机器人生命周期(兼容 NapCat)。 + defineAction({ + name: 'bot_exit', + summary: '退出机器人', + params: {}, + run: async () => { + setTimeout(() => process.exit(0), 50); + return okResponse(); + }, + }), + + defineAction({ + name: 'nc_get_packet_status', + summary: '获取 packet 状态(占位)', + params: {}, + run: async () => { + return okResponse(null); + }, + }), + + // NapCat 暴露 delete_group_folder。 + // SnowLuma 现有的 delete_group_file_folder 是相同操作。 + // 添加别名以便遵循 NapCat 文档的客户端无需重写载荷。 + groupAction({ + name: 'delete_group_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(); + }, + }), + + // 用户在线/扩展状态(NapCat:nc_get_user_status)。 + defineAction({ + name: 'nc_get_user_status', + summary: '获取用户在线/扩展状态', + params: { user_id: f.uint() }, + run: async (p, ctx) => { + const status = await ctx.bridge.apis.extras.getStrangerStatus(p.user_id); + if (!status) return failedResponse(RETCODE.ACTION_FAILED, 'failed to fetch user status'); + return okResponse({ ...status }); + }, + }), + + // AI 语音(oidb 0x929D / 0x929B)。 + groupAction({ + name: 'get_ai_characters', + summary: '获取 AI 语音角色', + params: { chat_type: f.int({ min: 0 }).default(1) }, + run: async (p, ctx) => { + try { + const list = await ctx.bridge.apis.extras.fetchAiVoiceList(p.group_id, p.chat_type); + return okResponse(list.map((cat) => ({ + type: cat.category, + characters: cat.voices.map((v) => ({ + character_id: v.voiceId, + character_name: v.voiceDisplayName, + preview_url: v.voiceExampleUrl, + })), + }))); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }, + }), + + groupAction({ + name: 'get_ai_record', + summary: '生成 AI 语音', + params: { + character: f.string({ allowEmpty: false }), + text: f.string({ allowEmpty: false }), + chat_type: f.int({ min: 0 }).default(1), + }, + run: async (p, ctx) => { + try { + const node = await ctx.bridge.apis.extras.fetchAiVoice(p.group_id, p.character, p.text, p.chat_type); + const url = await ctx.bridge.apis.groupFile.getPttUrl(p.group_id, node); + return okResponse(url); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }, + }), + + // NapCat 的 send_group_ai_record 是仅产生副作用的调用。 + // 调用 fetchAiVoice 会把语音发布到群里。 + // 返回的 message_id 始终为 0,因为 oidb 调用不会回显消息 ID。 + groupAction({ + name: 'send_group_ai_record', + summary: '发送 AI 语音到群', + params: { + character: f.string({ allowEmpty: false }), + text: f.string({ allowEmpty: false }), + chat_type: f.int({ min: 0 }).default(1), + }, + run: async (p, ctx) => { + try { + await ctx.bridge.apis.extras.fetchAiVoice(p.group_id, p.character, p.text, p.chat_type); + return okResponse({ message_id: 0 }); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }, + }), + + defineAction({ + name: 'request_decrypt_key', + summary: '请求数据库解密密钥', + params: { db_path: f.string({ allowEmpty: false }) }, + run: async (p, ctx) => { + try { + const buffer = Buffer.alloc(128); + const fileHandle = await readFile(p.db_path); + + if (fileHandle.length < 0xaf) { + return failedResponse(RETCODE.ACTION_FAILED, 'Database file too short'); + } + + fileHandle.copy(buffer, 0, 0x2f, 0xaf); + const dbSalt = buffer.toString('utf8'); + + if (!/^[0-9a-fA-F]{128}$/.test(dbSalt)) { + return failedResponse(RETCODE.ACTION_FAILED, 'Invalid db_salt: not a valid 128-character hex string'); + } + + const dbKey = await ctx.bridge.apis.misc.getDecryptKey(dbSalt.toLowerCase()); + + return okResponse({ db_key: dbKey }); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }, + }), + + // ===== 原 legacy registerAction,现并入 kit(ctx 调用与逻辑逐字保留; + // 别名键 / 原始参数透传 / 任意对象经 run 第三参 raw 或 f.raw() 表达)===== + + defineAction({ + name: ['get_rkey', 'nc_get_rkey'], + summary: '获取下载 rkey', + params: {}, + run: async (_p, ctx) => + ctx.getDownloadRKeys + ? okResponse(await ctx.getDownloadRKeys()) + : failedResponse(RETCODE.ACTION_FAILED, 'not implemented'), + }), + + defineAction({ + name: ['ocr_image', '.ocr_image'], + summary: 'OCR 图片(未实现)', + params: {}, + run: () => failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'), + }), + + groupAction({ + name: '_del_group_notice', + summary: '删除群公告(fid 或 notice_id 二选一)', + params: { fid: f.string().optional(), notice_id: f.string().optional() }, + run: async (p, ctx) => { + const fid = p.fid || p.notice_id; + if (!fid) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and fid/notice_id are required'); + try { + const success = await ctx.bridge.apis.web.deleteNotice(p.group_id, fid); + return success ? okResponse() : failedResponse(RETCODE.ACTION_FAILED, 'delete failed'); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'send_forward_msg', + summary: '发送合并转发(按 message_type/群号自动路由)', + returns: '{ message_id, res_id, forward_id }', + // group_id/user_id 是“路由提示”而非身份字段:原实现用 asNumber + `>0` 判断, + // 占位的 0 表示“该分支不适用”、不应报错。故从 raw 读取(保持旧语义), + // 只声明 messages/message。 + params: { messages: f.message().optional(), message: f.message().optional() }, + run: async (p, ctx, raw) => { + const messageType = asString(raw.message_type); + const groupId = asNumber(raw.group_id); + const userId = asNumber(raw.user_id); + const messages = p.messages ?? p.message; + const meta = readForwardPreviewMeta(raw); + if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); + if ((messageType === 'group' || groupId > 0) && ctx.sendGroupForwardMsg) { + if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + const result = await ctx.sendGroupForwardMsg(groupId, messages, meta); + return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); + } + if ((messageType === 'private' || userId > 0) && ctx.sendPrivateForwardMsg) { + if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); + const result = await ctx.sendPrivateForwardMsg(userId, messages, meta); + return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); + } + const result = await ctx.sendForwardMsg(messages); + return okResponse({ message_id: 0, res_id: result.forwardId, forward_id: result.forwardId }); + }, + }), + + groupAction({ + name: 'send_group_forward_msg', + summary: '发送群合并转发', + returns: '{ message_id, res_id, forward_id }', + params: { messages: f.message().optional(), message: f.message().optional() }, + run: async (p, ctx, raw) => { + const messages = p.messages ?? p.message; + if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); + const result = await ctx.sendGroupForwardMsg(p.group_id, messages, readForwardPreviewMeta(raw)); + return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); + }, + }), + + defineAction({ + name: 'send_private_forward_msg', + summary: '发送私聊合并转发', + returns: '{ message_id, res_id, forward_id }', + params: { user_id: f.uint(), messages: f.message().optional(), message: f.message().optional() }, + run: async (p, ctx, raw) => { + const messages = p.messages ?? p.message; + if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); + const result = await ctx.sendPrivateForwardMsg(p.user_id, messages, readForwardPreviewMeta(raw)); + return okResponse({ message_id: result.messageId, res_id: result.forwardId, forward_id: result.forwardId }); + }, + }), + + defineAction({ + name: 'get_forward_msg', + summary: '获取合并转发消息(id 或 message_id)', + returns: '{ messages }', + params: { id: f.string().optional() }, + run: async (p, ctx, raw) => { + let id = p.id || ''; + if (!id) { + const rawMessageId = raw.message_id; + const numericMessageId = asNumber(rawMessageId); + if (numericMessageId > 0) { + const event = ctx.getMessage(numericMessageId); + const segments = Array.isArray(event?.message) ? event.message : []; + for (const seg of segments) { + if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue; + const so = seg as Record; + if (String(so.type ?? '') !== 'forward') continue; + const data = (typeof so.data === 'object' && so.data !== null && !Array.isArray(so.data)) + ? so.data as Record + : null; + const candidate = asString(data?.id) || asString(data?.res_id) || asString(data?.forward_id); + if (candidate) { id = candidate; break; } + } + } + if (!id) id = asString(rawMessageId); + } + if (!id) return failedResponse(RETCODE.BAD_REQUEST, 'id or message_id is required'); + const messages = await ctx.getForwardMsg(id); + return okResponse({ messages }); + }, + }), + + defineAction({ + name: 'download_file', + summary: '下载文件(url 或 base64)到 data/downloads', + returns: '{ file }', + params: { url: f.string().default(''), base64: f.string().default(''), name: f.string().default('') }, + run: async (p, _ctx, raw) => { + const url = p.url; + const base64 = p.base64; + const name = p.name; + if (!url && !base64) return failedResponse(RETCODE.BAD_REQUEST, 'url or base64 is required'); + const fs = await import('fs'); + const pathMod = await import('path'); + const cryptoMod = await import('crypto'); + const tempDir = pathMod.resolve('data', 'downloads'); + if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true }); + const resolveSafePath = (preferredName: string, fallbackBuf: Buffer): string | null => { + const rawName = preferredName || cryptoMod.createHash('md5').update(fallbackBuf).digest('hex'); + const safeName = pathMod.basename(rawName); + if (!safeName || safeName === '.' || safeName === '..' || /[\\/]/.test(safeName)) return null; + const resolved = pathMod.resolve(tempDir, safeName); + const rel = pathMod.relative(tempDir, resolved); + if (rel.startsWith('..') || pathMod.isAbsolute(rel)) return null; + return resolved; + }; + let buf: Buffer; + if (base64) { + const upperBound = Math.floor((base64.length * 3) / 4); + if (upperBound > DOWNLOAD_FILE_MAX_BYTES) return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: > ${DOWNLOAD_FILE_MAX_BYTES} bytes`); + buf = Buffer.from(base64, 'base64'); + if (buf.length > DOWNLOAD_FILE_MAX_BYTES) return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: ${buf.length} > ${DOWNLOAD_FILE_MAX_BYTES} bytes`); + } else { + try { + buf = await fetchDownloadFile(url, parseDownloadHeaders(raw.headers), DOWNLOAD_FILE_MAX_BYTES, DOWNLOAD_FILE_TIMEOUT_MS); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + } + const safe = resolveSafePath(name, buf); + if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name'); + await fs.promises.writeFile(safe, buf); + return okResponse({ file: safe }); + }, + }), + + defineAction({ + name: 'translate_en2zh', + summary: '英译中', + returns: '{ words }', + params: { words: f.raw() }, + run: async (p, ctx) => { + const rawWords = p.words; + if (!Array.isArray(rawWords)) return failedResponse(RETCODE.BAD_REQUEST, 'invalid words array'); + const words = rawWords.map((w) => String(w)); + try { + const translated = await ctx.bridge.apis.misc.translateEn2Zh(words); + return okResponse({ words: translated }); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'set_self_longnick', + summary: '设置个性签名(longNick/long_nick,严格 string)', + params: { longNick: f.raw(), long_nick: f.raw() }, + run: async (p, ctx) => { + const longNick = p.longNick || p.long_nick; + if (typeof longNick !== 'string') return failedResponse(RETCODE.BAD_REQUEST, 'invalid longNick'); + try { + await ctx.bridge.apis.profile.setSelfLongNick(longNick); + return okResponse({}); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: 'get_mini_app_ark', + summary: '获取小程序卡片 ark', + params: {}, + run: async (_p, ctx, raw) => { + const type = raw.type || 'bili'; + const title = raw.title || ''; + const desc = raw.desc || ''; + const picUrl = raw.picUrl || raw.pic_url || ''; + const jumpUrl = raw.jumpUrl || raw.jump_url || ''; + try { + const data = await ctx.bridge.apis.misc.getMiniAppArk(String(type), String(title), String(desc), String(picUrl), String(jumpUrl)); + return okResponse(data); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + groupAction({ + name: 'click_inline_keyboard_button', + summary: '点击内联键盘按钮', + params: { bot_appid: f.uint(), msg_seq: f.uint() }, + run: async (p, ctx, raw) => { + const buttonId = raw.button_id; + const callbackData = raw.callback_data || ''; + if (!buttonId) return failedResponse(RETCODE.BAD_REQUEST, 'missing required parameters'); + try { + const data = await ctx.bridge.apis.misc.clickInlineKeyboardButton(p.group_id, p.bot_appid, String(buttonId), String(callbackData), p.msg_seq); + return okResponse(data); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + groupAction({ + name: ['set_group_sign', 'send_group_sign'], + summary: '群签到', + run: async (p, ctx) => { + try { + await ctx.bridge.apis.misc.sendGroupSign(p.group_id); + return okResponse({}); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, String(e)); + } + }, + }), + + defineAction({ + name: ['send_packet', '.send_packet'], + summary: '发送原始 SSO 包(cmd + hex data)', + params: { cmd: f.string({ allowEmpty: false }), data: f.string().default(''), rsp: f.bool().default(true) }, + run: async (p, ctx) => { + if (!/^[0-9a-fA-F]*$/.test(p.data) || p.data.length % 2 !== 0) { + return failedResponse(RETCODE.BAD_REQUEST, 'data must be a hex string of even length'); + } + try { + const body = hexToBytes(p.data); + const result = await ctx.bridge.sendRawPacket(p.cmd, body); + if (!result.success) return failedResponse(RETCODE.ACTION_FAILED, result.errorMessage || 'send failed'); + if (!p.rsp) return okResponse(null); + const respHex = result.responseData ? bytesToHex(result.responseData) : ''; + return okResponse(respHex); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }, + }), + + groupAction({ + name: 'set_group_todo', + summary: '设置群待办', + params: { message_id: f.messageId() }, + run: (p, ctx) => groupTodoRun(p, ctx, (g, s) => ctx.bridge.apis.extras.setGroupTodo(g, s)), + }), + + groupAction({ + name: 'complete_group_todo', + summary: '完成群待办', + params: { message_id: f.messageId() }, + run: (p, ctx) => groupTodoRun(p, ctx, (g, s) => ctx.bridge.apis.extras.completeGroupTodo(g, s)), + }), + + groupAction({ + name: 'cancel_group_todo', + summary: '取消群待办', + params: { message_id: f.messageId() }, + run: (p, ctx) => groupTodoRun(p, ctx, (g, s) => ctx.bridge.apis.extras.cancelGroupTodo(g, s)), + }), +]; + +// 已过滤(机器人/被忽略)的入群请求。 +// SnowLuma 已通过 fetchGroupRequests 实现底层 oidb 0x10c8_2 拉取。 +// 这几个动作只是为实际使用中的 OneBot 方言客户端重命名并投影相同数据。 +async function fetchFilteredGroupRequests(ctx: ApiActionContext) { + try { + return await ctx.bridge.apis.contacts.fetchGroupRequests(true); + } catch { + return []; + } +} + +export function register(h: ApiHandler, ctx: ApiActionContext): void { + registerActions(h, ctx, actions); + + // .handle_quick_operation 仍保留 legacy:它需要把 ApiHandler 本身 (h) 交给 + // executeQuickOperation 去回灌动作,而 action-kit 的 run 只提供 (p, ctx, raw)、不含 h。 h.registerAction('.handle_quick_operation', async (params) => { - const context = params.context as import('../types').JsonObject | undefined; + const context = params.context as JsonObject | undefined; const operation = params.operation as Record | undefined; if (!context || !operation) return failedResponse(RETCODE.BAD_REQUEST, 'context and operation are required'); const { executeQuickOperation } = await import('../network/quick-operation'); await executeQuickOperation(context, operation, h); return okResponse(); }); - - // 以下接口在方便用户迁移和兼容现有的 OneBot/NapCat 客户端。 - h.registerAction('set_friend_remark', async (params) => { - const userId = asNumber(params.user_id); - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - if (params.remark === undefined) { - return failedResponse(RETCODE.BAD_REQUEST, 'remark is required (pass an empty string to clear)'); - } - await ctx.bridge.apis.friend.setRemark(userId, asString(params.remark)); - return okResponse(); - }); - - h.registerAction('set_group_remark', async (params) => { - const groupId = asNumber(params.group_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - if (params.remark === undefined) { - return failedResponse(RETCODE.BAD_REQUEST, 'remark is required (pass an empty string to clear)'); - } - await ctx.bridge.apis.groupAdmin.setRemark(groupId, asString(params.remark)); - return okResponse(); - }); - - h.registerAction('set_msg_emoji_like', async (params) => { - const messageId = asNumber(params.message_id); - const emojiId = asString(params.emoji_id); - const set = asBoolean(params.set, true); - if (!Number.isInteger(messageId) || messageId === 0 || !emojiId) { - return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emoji_id are required'); - } - await ctx.setMsgEmojiLike(messageId, emojiId, set); - return okResponse(); - }); - - - h.registerAction('_mark_all_as_read', async () => { - return okResponse(); - }); - - h.registerAction('get_group_file_system_info', async (params) => { - const groupId = asNumber(params.group_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - const info = await ctx.bridge.apis.groupFile.getCount(groupId); - return okResponse({ - file_count: info.fileCount, - limit_count: info.maxCount, - used_space: 0, - total_space: 10737418240, - }); - }); - - h.registerAction('check_url_safely', async () => { - return okResponse({ level: 1 }); - }); - - h.registerAction('download_file', async (params) => { - const url = asString(params.url); - const base64 = asString(params.base64); - const name = asString(params.name); - if (!url && !base64) return failedResponse(RETCODE.BAD_REQUEST, 'url or base64 is required'); - - const fs = await import('fs'); - const pathMod = await import('path'); - const cryptoMod = await import('crypto'); - const tempDir = pathMod.resolve('data', 'downloads'); - if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true }); - - // 清理文件名:移除所有路径部分,并拒绝任何会解析到 tempDir 外部的路径。 - // 如果没有这个保护,name = "../../config/onebot_x.json" 会让已认证的 OneBot 客户端覆盖工作目录下的任意文件。 - // 例如 config、dist、node_modules 等目录中的文件。 - const resolveSafePath = (preferredName: string, fallbackBuf: Buffer): string | null => { - const raw = preferredName || cryptoMod.createHash('md5').update(fallbackBuf).digest('hex'); - const safeName = pathMod.basename(raw); - if (!safeName || safeName === '.' || safeName === '..' || /[\\/]/.test(safeName)) return null; - const resolved = pathMod.resolve(tempDir, safeName); - const rel = pathMod.relative(tempDir, resolved); - if (rel.startsWith('..') || pathMod.isAbsolute(rel)) return null; - return resolved; - }; - - let buf: Buffer; - if (base64) { - // 每 4 个 base64 字符最多解码成 3 个字节。 - // 在 Buffer.from 分配内存前先拒绝过大的载荷,避免最终也无法通过解码后检查的大载荷导致内存溢出。 - const upperBound = Math.floor((base64.length * 3) / 4); - if (upperBound > DOWNLOAD_FILE_MAX_BYTES) { - return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: > ${DOWNLOAD_FILE_MAX_BYTES} bytes`); - } - buf = Buffer.from(base64, 'base64'); - if (buf.length > DOWNLOAD_FILE_MAX_BYTES) { - return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: ${buf.length} > ${DOWNLOAD_FILE_MAX_BYTES} bytes`); - } - } else { - try { - buf = await fetchDownloadFile( - url!, - parseDownloadHeaders(params.headers), - DOWNLOAD_FILE_MAX_BYTES, - DOWNLOAD_FILE_TIMEOUT_MS, - ); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - } - - const safe = resolveSafePath(name, buf); - if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name'); - // 使用异步写入,避免 GiB 级下载阻塞事件循环。 - // 之前的 writeFileSync 会在运行期间卡住其他所有机器人动作。 - await fs.promises.writeFile(safe, buf); - return okResponse({ file: safe }); - }); - - h.registerAction('set_qq_profile', async (params) => { - - const nickname = params.nickname !== undefined ? asString(params.nickname) : undefined; - const personalNote = params.personal_note !== undefined ? asString(params.personal_note) : undefined; - - - try { - await ctx.bridge.apis.profile.setProfile(nickname, personalNote); - return okResponse(); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('set_online_status', async (params) => { - const status = asNumber(params.status); - const extStatus = asNumber(params.ext_status) || 0; - const batteryStatus = asNumber(params.battery_status) || 100; - - // 参数校验 - if (status === undefined || status === 0) { - return failedResponse(RETCODE.BAD_REQUEST, 'status is required'); - } - - - try { - await ctx.bridge.apis.profile.setOnlineStatus(status, extStatus, batteryStatus); - return okResponse(); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - // 自定义在线状态:与 set_online_status 使用相同的网络包。 - // 这里只填充 customExt 子消息,并将 status/extStatus 强制设为 QQ 定义的“我有自定义状态”取值(10 / 2000)。 - // face_id 和 face_type 可接受数字或数字字符串,以兼容 NapCat;wording 是图标旁展示的可读文本。 - h.registerAction('set_diy_online_status', async (params) => { - const faceId = asNumber(params.face_id); - const faceType = asNumber(params.face_type) || 1; - const wording = asString(params.wording); - if (!faceId) return failedResponse(RETCODE.BAD_REQUEST, 'face_id is required'); - try { - await ctx.bridge.apis.profile.setDiyOnlineStatus(faceId, wording, faceType); - return okResponse(); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - }); - - // 已过滤(机器人/被忽略)的入群请求。 - // SnowLuma 已通过 fetchGroupRequests 实现底层 oidb 0x10c8_2 拉取。 - // 这几个动作只是为实际使用中的 OneBot 方言客户端重命名并投影相同数据。 - const fetchFilteredGroupRequests = async () => { - try { - return await ctx.bridge.apis.contacts.fetchGroupRequests(true); - } catch { - return []; - } - }; - - h.registerAction('get_group_ignored_notifies', async () => { - const reqs = await fetchFilteredGroupRequests(); - return okResponse(reqs.map((r) => ({ - group_id: r.groupId, - group_name: r.groupName, - request_id: r.sequence, - requester_uin: r.targetUin, - requester_nick: r.targetName, - message: r.comment, - checked: r.state !== 1, - actor: r.operatorUin, - invitor_uin: r.invitorUin, - invitor_nick: r.invitorName, - flag: `${r.eventType}:${r.groupId}:${r.targetUid}:filtered`, - }))); - }); - - // NapCat 对“被忽略通知中属于入群请求的子集”的命名(notify type == 7)。 - // 这里把经过过滤的 0x10c8_2 每一项映射成 NapCat 结构。 - // eventType 已经在当前流水线中编码了请求类别。 - h.registerAction('get_group_ignore_add_request', async () => { - const reqs = await fetchFilteredGroupRequests(); - return okResponse(reqs.map((r) => ({ - request_id: r.sequence, - invitor_uin: r.invitorUin, - invitor_nick: r.invitorName, - group_id: r.groupId, - message: r.comment, - group_name: r.groupName, - checked: r.state !== 1, - actor: r.operatorUin, - requester_nick: r.targetName, - }))); - }); - - // get_group_shut_list 依赖尚未封装的 oidb。 - // 这里遵循 NapCat 约定返回空列表,避免调用方出错。 - h.registerAction('get_group_shut_list', async () => { - return okResponse([]); - }); - - h.registerAction('forward_friend_single_msg', async (params) => { - const messageId = asNumber(params.message_id); - const userId = asNumber(params.user_id); - if (!messageId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - try { - const result = await ctx.forwardSingleMsg(messageId, { userId }); - return okResponse({ message_id: result.messageId }); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - }); - - h.registerAction('forward_group_single_msg', async (params) => { - const messageId = asNumber(params.message_id); - const groupId = asNumber(params.group_id); - if (!messageId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - try { - const result = await ctx.forwardSingleMsg(messageId, { groupId }); - return okResponse({ message_id: result.messageId }); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - }); - - h.registerAction('get_profile_like', async (params) => { - const userId = asNumber(params.user_id); - const start = asNumber(params.start) || 0; - const count = asNumber(params.count) || 10; - try { - const data = await ctx.bridge.apis.profile.getLike(userId, start, count); - return okResponse(data); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('fetch_custom_face', async (params) => { - const count = asNumber(params.count) || 10; - try { - const urls = await ctx.bridge.apis.profile.fetchCustomFace(count); - return okResponse(urls); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('get_emoji_likes', async (params) => { - const messageId = asNumber(params.message_id); - const emojiId = asString(params.emoji_id) || ''; - if (!messageId || !emojiId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emoji_id are required'); - try { - const result = await ctx.fetchEmojiLikeUsers(messageId, emojiId, 1000); - return okResponse({ - emoji_like_list: result.users.map(u => ({ user_id: String(u.uin), nick_name: '' })), - }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('fetch_emoji_like', async (params) => { - const messageId = asNumber(params.message_id); - const emojiId = asString(params.emojiId) || ''; - const count = asNumber(params.count) || 10; - const cookie = asString(params.cookie) || ''; - if (!messageId || !emojiId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id and emojiId are required'); - try { - const offset = cookie ? Number.parseInt(cookie, 10) || 0 : 0; - const result = await ctx.fetchEmojiLikeUsers(messageId, emojiId, count, offset); - const nextOffset = offset + result.users.length; - const isLastPage = nextOffset >= result.cachedCount; - return okResponse({ - result: 0, - errMsg: '', - emojiLikesList: result.users.map(u => ({ tinyId: String(u.uin), nickName: '', headUrl: '' })), - cookie: isLastPage ? '' : String(nextOffset), - isLastPage, - isFirstPage: offset === 0, - }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('get_friends_with_category', async () => { - if (ctx.getFriendList) { - return okResponse(await ctx.getFriendList()); - } - return okResponse([]); - }); - - // NapCat 似乎也用不了,暂时不处理。 - h.registerAction('get_online_clients', async () => { - return okResponse({ clients: [] }); - }); - - h.registerAction('_get_model_show', async () => { - return okResponse({ variants: [] }); - }); - - h.registerAction('_set_model_show', async () => { - return okResponse(); - }); - - h.registerAction('.get_word_slices', async () => { - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); - }); - - h.registerAction('get_group_at_all_remain', async (params) => { - const groupId = asNumber(params.group_id); - - if (!groupId) { - return failedResponse(RETCODE.BAD_REQUEST, 'invalid group_id'); - } - try { - const data = await ctx.bridge.apis.groupAdmin.getAtAllRemain(groupId); - return okResponse(data); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('get_unidirectional_friend_list', async () => { - - try { - const data = await ctx.bridge.apis.profile.getUnidirectionalFriendList(); - return okResponse(data); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('set_self_longnick', async (params) => { - const longNick = params.longNick || params.long_nick; - - if (typeof longNick !== 'string') { - return failedResponse(RETCODE.BAD_REQUEST, 'invalid longNick'); - } - try { - await ctx.bridge.apis.profile.setSelfLongNick(longNick); - return okResponse({}); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('get_collection_list', async () => { - return okResponse([]); - }); - - h.registerAction('create_collection', async () => { - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); - }); - - h.registerAction('set_qq_avatar', async (params) => { - const file = asString(params.file); - if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required'); - - - try { - await ctx.bridge.apis.profile.setAvatar(file); - return okResponse(); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('set_input_status', async (params) => { - const userId = asNumber(params.user_id); - const eventType = asNumber(params.event_type); - - if (!userId) { - return failedResponse(RETCODE.BAD_REQUEST, 'invalid user_id'); - } - - // event_type 有可能是 0 (取消输入状态),所以这里严格判断 undefined 或 isNaN - if (eventType === undefined || isNaN(eventType)) { - return failedResponse(RETCODE.BAD_REQUEST, 'invalid event_type'); - } - - try { - await ctx.bridge.apis.profile.setInputStatus(userId, eventType); - return okResponse({}); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('translate_en2zh', async (params) => { - const rawWords = params.words; - - if (!Array.isArray(rawWords)) { - return failedResponse(RETCODE.BAD_REQUEST, 'invalid words array'); - } - - const words = rawWords.map(w => String(w)); - - - try { - const translated = await ctx.bridge.apis.misc.translateEn2Zh(words); - return okResponse({ words: translated }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('get_clientkey', async () => { - const clientKeyInfo = await ctx.bridge.apis.web.forceFetchClientKey(); - if (!clientKeyInfo.clientKey) { - return failedResponse(RETCODE.ACTION_FAILED, 'get clientkey error'); - } - return okResponse({ ...clientKeyInfo }); - }); - - h.registerAction('get_mini_app_ark', async (params) => { - const type = params.type || 'bili'; - const title = params.title || ''; - const desc = params.desc || ''; - const picUrl = params.picUrl || params.pic_url || ''; - const jumpUrl = params.jumpUrl || params.jump_url || ''; - - - try { - const data = await ctx.bridge.apis.misc.getMiniAppArk( - String(type), - String(title), - String(desc), - String(picUrl), - String(jumpUrl) - ); - return okResponse(data); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - h.registerAction('click_inline_keyboard_button', async (params) => { - const groupId = asNumber(params.group_id); - const botAppid = asNumber(params.bot_appid); - const buttonId = params.button_id; - const callbackData = params.callback_data || ''; - const msgSeq = asNumber(params.msg_seq); - - if (!groupId || !botAppid || !buttonId || !msgSeq) { - return failedResponse(RETCODE.BAD_REQUEST, 'missing required parameters'); - } - - - try { - const data = await ctx.bridge.apis.misc.clickInlineKeyboardButton( - groupId, - botAppid, - String(buttonId), - String(callbackData), - msgSeq - ); - return okResponse(data); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }); - - const handleGroupSign = async (params: import('../types').JsonObject) => { - const groupId = asNumber(params.group_id); - - if (!groupId) { - return failedResponse(RETCODE.BAD_REQUEST, 'invalid group_id'); - } - - - try { - await ctx.bridge.apis.misc.sendGroupSign(groupId); - return okResponse({}); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } - }; - - h.registerAction('set_group_sign', handleGroupSign); - h.registerAction('send_group_sign', handleGroupSign); - - h.registerAction('get_group_info_ex', async (params) => { - const groupId = asNumber(params.group_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - if (ctx.getGroupInfo) { - return okResponse(await ctx.getGroupInfo(groupId)); - } - return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); - }); - - h.registerAction('get_group_detail_info', async (params) => { - const groupId = asNumber(params.group_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - if (ctx.getGroupInfo) { - return okResponse(await ctx.getGroupInfo(groupId)); - } - return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); - }); - - h.registerAction('trans_group_file', async () => { - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); - }); - - h.registerAction('rename_group_file', async () => { - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); - }); - - h.registerAction('get_file', async (params) => { - const fileId = asString(params.file_id) || asString(params.file); - if (!fileId) return failedResponse(RETCODE.BAD_REQUEST, 'file_id is required'); - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); - }); - - const handleSendPacket = async (params: JsonObject) => { - const cmd = asString(params.cmd); - const dataHex = asString(params.data); - const rsp = asBoolean(params.rsp, true); - if (!cmd) return failedResponse(RETCODE.BAD_REQUEST, 'cmd is required'); - if (!/^[0-9a-fA-F]*$/.test(dataHex) || dataHex.length % 2 !== 0) { - return failedResponse(RETCODE.BAD_REQUEST, 'data must be a hex string of even length'); - } - try { - const body = hexToBytes(dataHex); - const result = await ctx.bridge.sendRawPacket(cmd, body); - if (!result.success) { - return failedResponse(RETCODE.ACTION_FAILED, result.errorMessage || 'send failed'); - } - if (!rsp) return okResponse(null); - const respHex = result.responseData ? bytesToHex(result.responseData) : ''; - return okResponse(respHex); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - }; - h.registerAction('send_packet', handleSendPacket); - h.registerAction('.send_packet', handleSendPacket); - - // 机器人生命周期(兼容 NapCat)。 - h.registerAction('bot_exit', async () => { - setTimeout(() => process.exit(0), 50); - return okResponse(); - }); - - h.registerAction('nc_get_packet_status', async () => { - return okResponse(null); - }); - - // NapCat 暴露 delete_group_folder。 - // SnowLuma 现有的 delete_group_file_folder 是相同操作。 - // 添加别名以便遵循 NapCat 文档的客户端无需重写载荷。 - h.registerAction('delete_group_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(); - }); - - // 群待办(oidb 0xF90)。 - // 三个子命令共享相同载荷(群号 + msgSeq)。 - // 这里统一提取一次,并按动作名称分发。 - // msgSeq 来自消息元数据缓存;设置、完成、取消总是指向机器人见过的真实消息。 - type GroupTodoOp = (groupId: number, msgSeq: bigint | number | string) => Promise; - const handleGroupTodo = (op: GroupTodoOp) => async (params: import('../types').JsonObject) => { - const groupId = asNumber(params.group_id); - const messageId = asNumber(params.message_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - if (!messageId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); - const meta = ctx.getMessageMeta(messageId); - if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found'); - if (!meta.isGroup || meta.targetId !== groupId) { - return failedResponse(RETCODE.ACTION_FAILED, 'message does not belong to this group'); - } - try { - await op(groupId, BigInt(meta.sequence)); - return okResponse(); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - }; - h.registerAction('set_group_todo', handleGroupTodo((g, s) => ctx.bridge.apis.extras.setGroupTodo(g, BigInt(s)))); - h.registerAction('complete_group_todo', handleGroupTodo((g, s) => ctx.bridge.apis.extras.completeGroupTodo(g, BigInt(s)))); - h.registerAction('cancel_group_todo', handleGroupTodo((g, s) => ctx.bridge.apis.extras.cancelGroupTodo(g, BigInt(s)))); - - // 用户在线/扩展状态(NapCat:nc_get_user_status)。 - - h.registerAction('nc_get_user_status', async (params) => { - const userId = asNumber(params.user_id); - if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - const status = await ctx.bridge.apis.extras.getStrangerStatus(userId); - if (!status) return failedResponse(RETCODE.ACTION_FAILED, 'failed to fetch user status'); - return okResponse({ ...status }); - }); - - // AI 语音(oidb 0x929D / 0x929B)。 - - h.registerAction('get_ai_characters', async (params) => { - const groupId = asNumber(params.group_id); - const chatType = asNumber(params.chat_type) || 1; - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - try { - const list = await ctx.bridge.apis.extras.fetchAiVoiceList(groupId, chatType); - return okResponse(list.map((cat) => ({ - type: cat.category, - characters: cat.voices.map((v) => ({ - character_id: v.voiceId, - character_name: v.voiceDisplayName, - preview_url: v.voiceExampleUrl, - })), - }))); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - }); - - h.registerAction('get_ai_record', async (params) => { - const groupId = asNumber(params.group_id); - const character = asString(params.character); - const text = asString(params.text); - const chatType = asNumber(params.chat_type) || 1; - if (!groupId || !character || !text) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id, character and text are required'); - } - try { - const node = await ctx.bridge.apis.extras.fetchAiVoice(groupId, character, text, chatType); - const url = await ctx.bridge.apis.groupFile.getPttUrl(groupId, node); - return okResponse(url); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - }); - - // NapCat 的 send_group_ai_record 是仅产生副作用的调用。 - // 调用 fetchAiVoice 会把语音发布到群里。 - // 返回的 message_id 始终为 0,因为 oidb 调用不会回显消息 ID。 - h.registerAction('send_group_ai_record', async (params) => { - const groupId = asNumber(params.group_id); - const character = asString(params.character); - const text = asString(params.text); - const chatType = asNumber(params.chat_type) || 1; - if (!groupId || !character || !text) { - return failedResponse(RETCODE.BAD_REQUEST, 'group_id, character and text are required'); - } - try { - await ctx.bridge.apis.extras.fetchAiVoice(groupId, character, text, chatType); - return okResponse({ message_id: 0 }); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - }); - - h.registerAction('request_decrypt_key', async (params) => { - const dbPath = asString(params.db_path); - if (!dbPath) { - return failedResponse(RETCODE.BAD_REQUEST, 'db_path is required'); - } - - try { - const buffer = Buffer.alloc(128); - const fileHandle = await readFile(dbPath); - - if (fileHandle.length < 0xaf) { - return failedResponse(RETCODE.ACTION_FAILED, 'Database file too short'); - } - - fileHandle.copy(buffer, 0, 0x2f, 0xaf); - const dbSalt = buffer.toString('utf8'); - - if (!/^[0-9a-fA-F]{128}$/.test(dbSalt)) { - return failedResponse(RETCODE.ACTION_FAILED, 'Invalid db_salt: not a valid 128-character hex string'); - } - - const dbKey = await ctx.bridge.apis.misc.getDecryptKey(dbSalt.toLowerCase()); - - return okResponse({ db_key: dbKey }); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } - }); } function hexToBytes(hex: string): Uint8Array { diff --git a/packages/onebot/src/actions/friend.ts b/packages/onebot/src/actions/friend.ts index 7e638c99..f1ca2b02 100644 --- a/packages/onebot/src/actions/friend.ts +++ b/packages/onebot/src/actions/friend.ts @@ -1,30 +1,45 @@ -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: '获取好友列表', + params: {}, + run: async (_p, ctx) => { + if (ctx.getFriendList) { + return okResponse(await ctx.getFriendList()); + } + return okResponse([]); + }, + }), + + defineAction({ + name: 'get_stranger_info', + summary: '获取陌生人信息', + 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); } diff --git a/packages/onebot/src/actions/group-admin.ts b/packages/onebot/src/actions/group-admin.ts index 2eda8977..19441311 100644 --- a/packages/onebot/src/actions/group-admin.ts +++ b/packages/onebot/src/actions/group-admin.ts @@ -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); } diff --git a/packages/onebot/src/actions/group-album.ts b/packages/onebot/src/actions/group-album.ts index 80628ded..fa646639 100644 --- a/packages/onebot/src/actions/group-album.ts +++ b/packages/onebot/src/actions/group-album.ts @@ -1,133 +1,130 @@ +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', + 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', + 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); } diff --git a/packages/onebot/src/actions/group-file.ts b/packages/onebot/src/actions/group-file.ts index 4f459099..7792ec4e 100644 --- a/packages/onebot/src/actions/group-file.ts +++ b/packages/onebot/src/actions/group-file.ts @@ -1,118 +1,153 @@ +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: '获取群文件下载链接', + 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: '获取群根目录文件列表', + run: async (p, ctx) => { + return okResponse(await ctx.getGroupFiles(p.group_id, '/')); + }, + }), + + groupAction({ + name: 'get_group_files_by_folder', + summary: '获取群子目录文件列表', + // 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: '获取私聊文件下载链接', + 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); } diff --git a/packages/onebot/src/actions/group-info.ts b/packages/onebot/src/actions/group-info.ts index 0e4d7eee..15c89d84 100644 --- a/packages/onebot/src/actions/group-info.ts +++ b/packages/onebot/src/actions/group-info.ts @@ -1,84 +1,114 @@ +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: '获取群列表', + 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: '获取群信息', + 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: '获取群成员列表', + 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: '获取群成员信息', + 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: '获取群荣誉信息', + 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: '获取群系统消息', + 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); } diff --git a/packages/onebot/src/actions/info.ts b/packages/onebot/src/actions/info.ts index ee8457e1..1b9657c3 100644 --- a/packages/onebot/src/actions/info.ts +++ b/packages/onebot/src/actions/info.ts @@ -1,32 +1,58 @@ +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', + params: {}, + run: (_p, ctx) => { + const login = ctx.getLoginInfo(); + return okResponse({ user_id: login.userId, nickname: login.nickname }); + }, + }), + + defineAction({ + name: 'get_status', + params: {}, + run: (_p, ctx) => { + const online = ctx.isOnline(); + return okResponse({ online, good: online }); + }, + }), + + defineAction({ + name: 'get_version_info', + params: {}, + run: () => { + return okResponse({ + app_name: 'SnowLuma', + app_version: `${appVersion}-node`, + protocol_version: 'v11', + }); + }, + }), + + defineAction({ + name: 'can_send_image', + params: {}, + run: (_p, ctx) => { + return okResponse({ yes: ctx.canSendImage?.() ?? false }); + }, + }), + + defineAction({ + name: 'can_send_record', + 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); } diff --git a/packages/onebot/src/actions/message.ts b/packages/onebot/src/actions/message.ts index b2fbe754..73fd711f 100644 --- a/packages/onebot/src/actions/message.ts +++ b/packages/onebot/src/actions/message.ts @@ -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,85 @@ 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: '获取消息', + 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); } diff --git a/packages/onebot/src/actions/request.ts b/packages/onebot/src/actions/request.ts index e76bade9..18348c76 100644 --- a/packages/onebot/src/actions/request.ts +++ b/packages/onebot/src/actions/request.ts @@ -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); } diff --git a/packages/onebot/tests/action-docs.test.ts b/packages/onebot/tests/action-docs.test.ts new file mode 100644 index 00000000..9f9170a5 --- /dev/null +++ b/packages/onebot/tests/action-docs.test.ts @@ -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('| 参数 | 类型 | 必填 | 默认 | 说明 |'); + }); +}); diff --git a/packages/onebot/tests/action-kit.test.ts b/packages/onebot/tests/action-kit.test.ts new file mode 100644 index 00000000..6ddf74d6 --- /dev/null +++ b/packages/onebot/tests/action-kit.test.ts @@ -0,0 +1,184 @@ +// 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(r: CoerceResult): { 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(r: CoerceResult): 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('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' }); + }); +}); From 7336352cd31583fb5a2f974fc058664fba4ba195 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 2 Jun 2026 20:47:06 +0800 Subject: [PATCH 02/12] feat(onebot): voice-to-text action fetch_ptt_text (#79) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds NapCat-compatible voice-to-text. New `fetch_ptt_text` action (aliases `get_ptt_text` / `get_record_text`) takes a message_id, resolves the cached `record` fingerprint (uuid + md5 + duration/size/format), drives QQ's native `pttTrans.TransC2CPttReq` / `pttTrans.TransGroupPttReq`, and returns { text }. The response carries the text inline once transcription is done; an empty text means the server is still transcribing (there is no dedicated push command — confirmed via RE), so the bridge re-sends with a short backoff until the text lands, mirroring NapCat's fire-then-re-read shape. Layers: - proto-defs/ptt-trans: PttTransReq/Resp + per-scene items. - core ExtrasApi.translatePttToText: encode -> sendRawPacket -> decode -> poll. - onebot media-actions.fetchPttText + api-handler/instance-context wiring. - onebot extended: register the action + aliases. The commands + request/response field tags were reverse-engineered from QQ-NT wrapper.node (im_core/msg/ptt/ptt_trans_worker.cc). The numeric tags are solid; the length-delimited fields (uuid/md5) and the response text tag are RE-derived and want one live capture to confirm before relying on them. --- packages/core/src/bridge/apis/extras.ts | 82 ++++++++++++++++++++ packages/onebot/src/actions/extended.ts | 19 +++++ packages/onebot/src/api-handler.ts | 1 + packages/onebot/src/instance-context.ts | 2 + packages/onebot/src/modules/media-actions.ts | 51 ++++++++++++ packages/proto-defs/package.json | 4 + packages/proto-defs/src/ptt-trans.ts | 78 +++++++++++++++++++ 7 files changed, 237 insertions(+) create mode 100644 packages/proto-defs/src/ptt-trans.ts diff --git a/packages/core/src/bridge/apis/extras.ts b/packages/core/src/bridge/apis/extras.ts index cd78f577..f0aa4a11 100644 --- a/packages/core/src/bridge/apis/extras.ts +++ b/packages/core/src/bridge/apis/extras.ts @@ -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,57 @@ export class ExtrasApi { } throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`); } + + // ─────────────── Voice-to-text (pttTrans.Trans{C2C,Group}PttReq) ─────────────── + + /** + * Trigger QQ's native voice-to-text on a received ptt and return the text. + * + * Sends `pttTrans.TransC2CPttReq` / `pttTrans.TransGroupPttReq` (RE'd from + * wrapper.node). The response carries the text inline when transcription is + * already done; an empty text + errCode 0 means the server is transcribing + * asynchronously (there is no dedicated push command), so we re-send with a + * short backoff until the text lands or the retry budget is spent — the same + * "fire then re-read" shape NapCat uses. + * + * NOTE: the wire field tags here are reverse-engineered and not yet verified + * against a live server; confirm with one capture before trusting failures. + */ + async translatePttToText(input: PttTransInput, maxRetries = 5, retryDelayMs = 1000): Promise { + 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'; + + for (let attempt = 0; attempt < maxRetries; attempt++) { + const result = await this.ctx.sendRawPacket(cmd, protobuf_encode(req)); + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'ptt translate request failed'); + } + const resp = protobuf_decode(result.responseData); + const item = input.isGroup ? resp?.groupResult : resp?.c2cResult; + if (item?.errCode) throw new Error(`ptt translate failed: error=${item.errCode}`); + const text = item?.text ?? ''; + if (text) return text; + // Empty → still transcribing; back off and retry. + if (attempt < maxRetries - 1) { + await new Promise((resolve) => setTimeout(resolve, retryDelayMs)); + } + } + throw new Error('ptt translate timed out (no text returned)'); + } } diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 2dd846af..f2818d4b 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -426,6 +426,25 @@ export const actions = [ }, }), + defineAction({ + // Primary name matches NapCat for drop-in migration; the rest are aliases. + name: ['fetch_ptt_text', 'get_ptt_text', 'get_record_text'], + summary: '获取语音转文字结果', + params: { + message_id: f.string().default(''), + }, + // `raw` so message_id works whether the client sends a number or a string. + run: async (_p, ctx, raw) => { + const messageId = asNumber(raw.message_id); + if (!messageId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); + try { + return okResponse(await ctx.fetchPttText(messageId)); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : '获取语音转文字结果失败'); + } + }, + }), + // Cookie、CSRF 令牌和账号信息 defineAction({ name: 'get_cookies', diff --git a/packages/onebot/src/api-handler.ts b/packages/onebot/src/api-handler.ts index 7a9546f7..105f89b8 100644 --- a/packages/onebot/src/api-handler.ts +++ b/packages/onebot/src/api-handler.ts @@ -76,6 +76,7 @@ export interface ApiActionContext { }>; getImageInfo: (file: string) => Promise; getRecordInfo: (file: string) => Promise; + fetchPttText: (messageId: number) => Promise<{ text: string }>; } type ActionHandler = (params: JsonObject) => Promise; diff --git a/packages/onebot/src/instance-context.ts b/packages/onebot/src/instance-context.ts index 50ccb3d3..e0047947 100644 --- a/packages/onebot/src/instance-context.ts +++ b/packages/onebot/src/instance-context.ts @@ -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), }; } diff --git a/packages/onebot/src/modules/media-actions.ts b/packages/onebot/src/modules/media-actions.ts index 156885b2..0903ae17 100644 --- a/packages/onebot/src/modules/media-actions.ts +++ b/packages/onebot/src/modules/media-actions.ts @@ -3,10 +3,61 @@ 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 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; + + const text = 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, + }); + return { text }; +} + export async function getImageInfo( mediaStore: MediaStore, file: string, diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index 43416896..ff3b5a33 100644 --- a/packages/proto-defs/package.json +++ b/packages/proto-defs/package.json @@ -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" diff --git a/packages/proto-defs/src/ptt-trans.ts b/packages/proto-defs/src/ptt-trans.ts new file mode 100644 index 00000000..497ddbc7 --- /dev/null +++ b/packages/proto-defs/src/ptt-trans.ts @@ -0,0 +1,78 @@ +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>; +} From 15e4e261c59f6a342aeb9ab7ef9e5514433ee52c Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 2 Jun 2026 21:01:19 +0800 Subject: [PATCH 03/12] feat(log): memory-only trace level + request correlation + chokepoint tracing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Debugging from user-supplied logs was impossible: a successful action left one terse, over-summarized debug line and nothing about what it sent QQ or what QQ returned. Add full-chain tracing that stays off disk so it scales to hundreds of groups. common: - New `trace` level (below debug). Never written to file — it lives only in an in-memory ring + the WebUI stream, so the high-volume full chain costs no disk. `emit` early-returns for trace before format/render (and before any lazy producer) when trace isn't active → ~free at the default level. - Dedicated O(1) circular ring for trace (default 5000, SNOWLUMA_TRACE_BUFFER), separate from the normal 1000-entry buffer (also switched off array .shift); getRecentLogs merges both by id. - request-context.ts: AsyncLocalStorage request id. The logger auto-stamps `[req#N]` on every line in a request's async chain — across packages, zero signature threading — and records it on the entry. - log-summary.renderParamsVerbose: deep render of params (nested structure, per-string cap, total budget, token/password/secret redaction). chokepoints (auto-cover every action without touching 100+ handlers): - onebot api-handler: wrap each action in a request id (only when trace is live); trace the full params on entry and status+elapsed on exit; the terse debug breadcrumb still persists to file, failures still warn. - core bridge.sendRawPacket: trace on success (cmd, sizes, elapsed); warn on errorCode!=0 / no response (cmd, code, message) so disk keeps real problems. - protocol highway: fold the bare console.log lines into the logger (trace). webui: trace as the lowest filterable level; render the `[req#N]` tag and let search match it. Server needs no change — LOG_LEVELS, getRecentLogs and the SSE stream carry it through. --- packages/common/src/log-summary.ts | 67 ++++++++++ packages/common/src/logger.ts | 121 +++++++++++++++--- packages/common/src/request-context.ts | 35 +++++ packages/core/src/bridge/bridge.ts | 21 ++- packages/onebot/src/api-handler.ts | 34 ++++- packages/onebot/tests/logging.test.ts | 106 +++++++++++++++ .../protocol/src/highway/highway-client.ts | 6 +- .../webui/src/components/pages/logs-page.tsx | 11 +- packages/webui/src/types.ts | 4 +- 9 files changed, 375 insertions(+), 30 deletions(-) create mode 100644 packages/common/src/request-context.ts create mode 100644 packages/onebot/tests/logging.test.ts diff --git a/packages/common/src/log-summary.ts b/packages/common/src/log-summary.ts index dcec49d6..8b0ff1bb 100644 --- a/packages/common/src/log-summary.ts +++ b/packages/common/src/log-summary.ts @@ -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 `"…"`), + * - 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(); + 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)) { + if (budget <= 0) { parts.push('…'); break; } + parts.push(`${k}:${walk(v, k)}`); + } + return `{${parts.join(',')}}`; + } + default: + return typeof value; + } + }; + + return walk(params); +} diff --git a/packages/common/src/logger.ts b/packages/common/src/logger.ts index d5eabc93..fb29dca4 100644 --- a/packages/common/src/logger.ts +++ b/packages/common/src/logger.ts @@ -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 = { + trace: 5, debug: 10, info: 20, success: 25, @@ -34,6 +38,7 @@ const LEVEL_WEIGHT: Record = { }; const LEVEL_LABEL: Record = { + trace: 'TRACE', debug: 'DEBUG', info: 'INFO', success: 'OK', @@ -42,6 +47,7 @@ const LEVEL_LABEL: Record = { }; const COLOR_CODE: Record = { + 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 { + private readonly buf: (T | undefined)[]; + private start = 0; + private count = 0; + constructor(private readonly cap: number) { + this.buf = new Array(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(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(MAX_LOG_ENTRIES); +const traceRing = new RingBuffer(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 { } 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'; diff --git a/packages/common/src/request-context.ts b/packages/common/src/request-context.ts new file mode 100644 index 00000000..963800c6 --- /dev/null +++ b/packages/common/src/request-context.ts @@ -0,0 +1,35 @@ +import { AsyncLocalStorage } from 'async_hooks'; + +interface RequestStore { + id: number; +} + +const storage = new AsyncLocalStorage(); +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(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; +} diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index f4e560a8..ff9fa610 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -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 { 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 { return this.identity.resolveUid(uin, groupId); diff --git a/packages/onebot/src/api-handler.ts b/packages/onebot/src/api-handler.ts index 105f89b8..cba2a727 100644 --- a/packages/onebot/src/api-handler.ts +++ b/packages/onebot/src/api-handler.ts @@ -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'; @@ -109,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 { + // 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 diff --git a/packages/onebot/tests/logging.test.ts b/packages/onebot/tests/logging.test.ts new file mode 100644 index 00000000..52e6ed3c --- /dev/null +++ b/packages/onebot/tests/logging.test.ts @@ -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 = { 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]'); + }); +}); diff --git a/packages/protocol/src/highway/highway-client.ts b/packages/protocol/src/highway/highway-client.ts index b307cc57..7455e08a 100644 --- a/packages/protocol/src/highway/highway-client.ts +++ b/packages/protocol/src/highway/highway-client.ts @@ -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 = { + trace: 'text-muted-foreground/60', debug: 'text-muted-foreground', info: 'text-primary', success: 'text-success', @@ -19,7 +20,7 @@ const levelClass: Record = { 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()} [{log.scope}] + {log.req !== undefined && ( + + #{log.req} + + )} {log.message} diff --git a/packages/webui/src/types.ts b/packages/webui/src/types.ts index 58efeef2..0f65ab15 100644 --- a/packages/webui/src/types.ts +++ b/packages/webui/src/types.ts @@ -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; From 92cfaf24b82dd55cebf19392be60da3d1054f000 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 2 Jun 2026 21:15:12 +0800 Subject: [PATCH 04/12] feat(log): trace the inbound receive chain (symmetric to outbound) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sending got full-chain trace via the api-handler chokepoint; receiving had none. Wrap convertAndDispatch — the single path every inbound message/notice takes (decode → convert → dispatch) — as the receive-side mirror: - When trace is live, run the chain inside a request id so the whole receive (incl. any rkey-fetch packets the conversion triggers) is correlated under one [req#N]; otherwise skip the wrap entirely (zero overhead). - trace the raw inbound event on entry (deep render) and the converted post_type + elapsed on exit (or "dropped"). Reuses the existing trace/ALS/renderParamsVerbose machinery; no new mechanism. --- packages/onebot/src/event-pipeline.ts | 38 ++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/packages/onebot/src/event-pipeline.ts b/packages/onebot/src/event-pipeline.ts index a6a637f7..77b57049 100644 --- a/packages/onebot/src/event-pipeline.ts +++ b/packages/onebot/src/event-pipeline.ts @@ -1,26 +1,32 @@ +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'; +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,7 +35,7 @@ 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); }), ); } @@ -58,10 +64,30 @@ const NOTICE_KINDS = [ 'group_msg_emoji_like', ] as const satisfies readonly QQEventVariant['kind'][]; -async function convertAndDispatch(ctx: OneBotInstanceContext, event: QQEventVariant): Promise { +async function convertAndDispatch(ctx: OneBotInstanceContext, log: Logger, event: QQEventVariant): Promise { + // 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 { + // 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): void { From e036e70acc83491d03817e5b9a66e52da82edfb0 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 2 Jun 2026 21:28:44 +0800 Subject: [PATCH 05/12] chore(protocol): temp-dump 0x210 subType-61 ptt-trans push body (#79) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Live testing showed the voice-to-text text is delivered via an async push Event 0x210 subType 61 (0x3D), not the sync pttTrans.TransC2CPttReq response (which is a fixed ~137B ack). That push has no static sys_msg_0x210_0x3d handler — its protobuf is registered dynamically by the ptt-trans subsystem, so RE through the std::function callback chain is impractical. Dump the raw subType-61 body (fromUin + len + hex) once so the wire format can be decoded from ground truth, then implement the real decoder + request/await correlation. Temporary — to be replaced by the actual decoder. --- .../protocol/src/msg-push/decoders/event-0x210.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/protocol/src/msg-push/decoders/event-0x210.ts b/packages/protocol/src/msg-push/decoders/event-0x210.ts index 31d94e56..ad6071af 100644 --- a/packages/protocol/src/msg-push/decoders/event-0x210.ts +++ b/packages/protocol/src/msg-push/decoders/event-0x210.ts @@ -54,6 +54,20 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => { // until someone maps the schema. return []; } + if (ctx.head.subType === 61) { + // TEMP capture aid (#79 语音转文字): subType 61 (0x3D) is QQ-NT's ptt + // voice-to-text result push. Its protobuf wire shape is registered + // dynamically by the ptt-trans subsystem (no static sys_msg_0x210_0x3d + // handler), so we dump the raw body once to decode it from ground truth. + // Replace with a proper decoder + correlation once mapped. + unknownLog.info( + 'Event0x210 ptt-trans(subType=61) fromUin=%s len=%d hex=%s', + String(ctx.fromUin ?? ''), + ctx.content?.length ?? 0, + ctx.content ? Buffer.from(ctx.content).toString('hex') : '', + ); + return []; + } unknownLog.debug('Event0x210 unknown subType=%d', ctx.head.subType); return []; }; From fc21d87a9bf95c6bd2eb2e043574f592cedc3fcc Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 2 Jun 2026 22:01:07 +0800 Subject: [PATCH 06/12] feat(onebot): fetch_ptt_text via async 0x210/61 result push (#79) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Live testing showed the voice-to-text text is delivered by an async push (Event 0x210 subType 61), not the request response — so the previous poll-by-resend never got it. Captured a real push and decoded its protobuf: outer { f1, f2:item }; the item echoes the request msgId at field 1 (the correlation key) and the recognised text at field 8. - proto-defs: PttTransPush / PttTransPushItem (live-verified). - protocol: Event0x210SubType.PttTransResult = 61 + decoder → internal `ptt_trans_result` event { msgId, text } (replaces the temp hex dump). - core: translatePttToText now sends ONE trigger and returns the inline text only if present (already-transcribed); empty = pending. - onebot: ptt-trans-waiter (keyed by selfUin:msgId), event-pipeline subscribes `ptt_trans_result` to resolve it; fetch_ptt_text registers the waiter, fires the trigger, and awaits the push (20s timeout). Decoded one real push as text "12311123。" end to end. --- packages/core/src/bridge/apis/extras.ts | 41 +++++--------- packages/onebot/src/event-pipeline.ts | 8 +++ packages/onebot/src/modules/media-actions.ts | 41 ++++++++++---- .../onebot/src/modules/ptt-trans-waiter.ts | 56 +++++++++++++++++++ packages/proto-defs/src/ptt-trans.ts | 19 +++++++ packages/protocol/src/events.ts | 15 ++++- .../src/msg-push/decoders/event-0x210.ts | 30 +++++----- packages/protocol/src/msg-push/enums.ts | 8 +++ 8 files changed, 164 insertions(+), 54 deletions(-) create mode 100644 packages/onebot/src/modules/ptt-trans-waiter.ts diff --git a/packages/core/src/bridge/apis/extras.ts b/packages/core/src/bridge/apis/extras.ts index f0aa4a11..557a088a 100644 --- a/packages/core/src/bridge/apis/extras.ts +++ b/packages/core/src/bridge/apis/extras.ts @@ -121,19 +121,14 @@ export class ExtrasApi { // ─────────────── Voice-to-text (pttTrans.Trans{C2C,Group}PttReq) ─────────────── /** - * Trigger QQ's native voice-to-text on a received ptt and return the text. - * - * Sends `pttTrans.TransC2CPttReq` / `pttTrans.TransGroupPttReq` (RE'd from - * wrapper.node). The response carries the text inline when transcription is - * already done; an empty text + errCode 0 means the server is transcribing - * asynchronously (there is no dedicated push command), so we re-send with a - * short backoff until the text lands or the retry budget is spent — the same - * "fire then re-read" shape NapCat uses. - * - * NOTE: the wire field tags here are reverse-engineered and not yet verified - * against a live server; confirm with one capture before trusting failures. + * 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, maxRetries = 5, retryDelayMs = 1000): Promise { + async translatePttToText(input: PttTransInput): Promise { const md5 = hexToBytes(input.md5Hex); const req: PttTransReq = input.isGroup ? { @@ -153,21 +148,13 @@ export class ExtrasApi { }; const cmd = input.isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq'; - for (let attempt = 0; attempt < maxRetries; attempt++) { - const result = await this.ctx.sendRawPacket(cmd, protobuf_encode(req)); - if (!result.success || !result.gotResponse || !result.responseData) { - throw new Error(result.errorMessage || 'ptt translate request failed'); - } - const resp = protobuf_decode(result.responseData); - const item = input.isGroup ? resp?.groupResult : resp?.c2cResult; - if (item?.errCode) throw new Error(`ptt translate failed: error=${item.errCode}`); - const text = item?.text ?? ''; - if (text) return text; - // Empty → still transcribing; back off and retry. - if (attempt < maxRetries - 1) { - await new Promise((resolve) => setTimeout(resolve, retryDelayMs)); - } + const result = await this.ctx.sendRawPacket(cmd, protobuf_encode(req)); + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(result.errorMessage || 'ptt translate request failed'); } - throw new Error('ptt translate timed out (no text returned)'); + const resp = protobuf_decode(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 } } diff --git a/packages/onebot/src/event-pipeline.ts b/packages/onebot/src/event-pipeline.ts index 77b57049..53fce4e9 100644 --- a/packages/onebot/src/event-pipeline.ts +++ b/packages/onebot/src/event-pipeline.ts @@ -4,6 +4,7 @@ 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'); @@ -39,6 +40,13 @@ export function registerEventPipeline(ctx: OneBotInstanceContext): () => void { }), ); } + // 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) { diff --git a/packages/onebot/src/modules/media-actions.ts b/packages/onebot/src/modules/media-actions.ts index 0903ae17..5d0f7e9a 100644 --- a/packages/onebot/src/modules/media-actions.ts +++ b/packages/onebot/src/modules/media-actions.ts @@ -4,6 +4,12 @@ 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'); @@ -44,18 +50,29 @@ export async function fetchPttText( // c2c: receiver is self (inbound voice); group: the group uin. const peerUin = isGroup ? (Number(event.group_id) || cached.sessionId) : selfId; - const text = 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, - }); - return { text }; + // 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( diff --git a/packages/onebot/src/modules/ptt-trans-waiter.ts b/packages/onebot/src/modules/ptt-trans-waiter.ts new file mode 100644 index 00000000..6b6bebb1 --- /dev/null +++ b/packages/onebot/src/modules/ptt-trans-waiter.ts @@ -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; +} + +const pending = new Map(); + +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 { + const existing = pending.get(key); + if (existing) { + clearTimeout(existing.timer); + pending.delete(key); + existing.reject(new Error('语音转文字请求被新的请求取代')); + } + return new Promise((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); +} diff --git a/packages/proto-defs/src/ptt-trans.ts b/packages/proto-defs/src/ptt-trans.ts index 497ddbc7..3290d581 100644 --- a/packages/proto-defs/src/ptt-trans.ts +++ b/packages/proto-defs/src/ptt-trans.ts @@ -76,3 +76,22 @@ export interface PttTransResp { 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>; +} diff --git a/packages/protocol/src/events.ts b/packages/protocol/src/events.ts index 99a018eb..8eada526 100644 --- a/packages/protocol/src/events.ts +++ b/packages/protocol/src/events.ts @@ -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; diff --git a/packages/protocol/src/msg-push/decoders/event-0x210.ts b/packages/protocol/src/msg-push/decoders/event-0x210.ts index ad6071af..65a922c0 100644 --- a/packages/protocol/src/msg-push/decoders/event-0x210.ts +++ b/packages/protocol/src/msg-push/decoders/event-0x210.ts @@ -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. @@ -54,24 +56,24 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => { // until someone maps the schema. return []; } - if (ctx.head.subType === 61) { - // TEMP capture aid (#79 语音转文字): subType 61 (0x3D) is QQ-NT's ptt - // voice-to-text result push. Its protobuf wire shape is registered - // dynamically by the ptt-trans subsystem (no static sys_msg_0x210_0x3d - // handler), so we dump the raw body once to decode it from ground truth. - // Replace with a proper decoder + correlation once mapped. - unknownLog.info( - 'Event0x210 ptt-trans(subType=61) fromUin=%s len=%d hex=%s', - String(ctx.fromUin ?? ''), - ctx.content?.length ?? 0, - ctx.content ? Buffer.from(ctx.content).toString('hex') : '', - ); - return []; - } unknownLog.debug('Event0x210 unknown subType=%d', ctx.head.subType); 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(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(ctx.content); if (!request?.info) return []; diff --git a/packages/protocol/src/msg-push/enums.ts b/packages/protocol/src/msg-push/enums.ts index 74422733..e94c157c 100644 --- a/packages/protocol/src/msg-push/enums.ts +++ b/packages/protocol/src/msg-push/enums.ts @@ -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 From 69c8960ea949b03f407cd37efc7953be141fbd6b Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 2 Jun 2026 22:45:30 +0800 Subject: [PATCH 07/12] =?UTF-8?q?feat(mcp):=20@snowluma/mcp=20=E2=80=94=20?= =?UTF-8?q?read-only=20MCP=20server=20for=20the=20OneBot=20action=20catalo?= =?UTF-8?q?g?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A new published package that exposes every OneBot action's docs + a ready-to-use JSON Schema to LLM clients over stdio. Tools: list_actions / get_action / search_actions / list_categories, plus the whole catalog as a resource. The catalog is a build-time snapshot generated from @snowluma/onebot's live action specs (collectActionDocs()) — so it auto-tracks action add/remove and the published package carries zero runtime dependency on the private onebot package. action-kit enrichment (the data source): - Field.toJsonSchema() per coercer (uint→integer/minimum:1, messageId→integer/ not-const-0, int→min/max, string→minLength/maxLength, array→items, enum→enum). - describe() composes a per-action inputSchema; ActionDoc gains inputSchema + category. action-docs.ts tags each doc with its domain category. Wiring: onebot exports ./action-kit + ./action-docs; root build:all includes mcp; mcp-npm-publish.yml mirrors the sdk/ui publish workflows (triggers on changes under packages/mcp/** or packages/onebot/**, since the catalog derives from it). onebot typecheck + 318 tests green; mcp typecheck/build/smoke green; the 142 registered OneBot action names are unchanged. --- .github/workflows/mcp-npm-publish.yml | 109 + package.json | 3 +- packages/mcp/.gitignore | 1 + packages/mcp/README.md | 40 + packages/mcp/package.json | 49 + packages/mcp/scripts/gen-catalog.test.ts | 32 + packages/mcp/src/generated/catalog.ts | 5751 ++++++++++++++++++++++ packages/mcp/src/server.ts | 148 + packages/mcp/src/types.ts | 34 + packages/mcp/tsconfig.json | 13 + packages/mcp/vitest.config.ts | 17 + packages/onebot/package.json | 8 + packages/onebot/src/action-docs.ts | 37 +- packages/onebot/src/action-kit.ts | 92 +- packages/onebot/tests/action-kit.test.ts | 36 + pnpm-lock.yaml | 675 +++ 16 files changed, 7012 insertions(+), 33 deletions(-) create mode 100644 .github/workflows/mcp-npm-publish.yml create mode 100644 packages/mcp/.gitignore create mode 100644 packages/mcp/README.md create mode 100644 packages/mcp/package.json create mode 100644 packages/mcp/scripts/gen-catalog.test.ts create mode 100644 packages/mcp/src/generated/catalog.ts create mode 100644 packages/mcp/src/server.ts create mode 100644 packages/mcp/src/types.ts create mode 100644 packages/mcp/tsconfig.json create mode 100644 packages/mcp/vitest.config.ts diff --git a/.github/workflows/mcp-npm-publish.yml b/.github/workflows/mcp-npm-publish.yml new file mode 100644 index 00000000..9f842af6 --- /dev/null +++ b/.github/workflows/mcp-npm-publish.yml @@ -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}" diff --git a/package.json b/package.json index 36790e82..630acf63 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/packages/mcp/.gitignore b/packages/mcp/.gitignore new file mode 100644 index 00000000..849ddff3 --- /dev/null +++ b/packages/mcp/.gitignore @@ -0,0 +1 @@ +dist/ diff --git a/packages/mcp/README.md b/packages/mcp/README.md new file mode 100644 index 00000000..dab67871 --- /dev/null +++ b/packages/mcp/README.md @@ -0,0 +1,40 @@ +# @snowluma/mcp + +A read-only [MCP](https://modelcontextprotocol.io) server that exposes the +**SnowLuma OneBot action catalog** — every action's docs, parameters, cross-field +constraints, and a ready-to-use **JSON Schema** — to LLM clients. + +Point an LLM at it and it can answer "what params does `set_group_ban` take?" or +"which actions send messages?" on demand, without holding the whole catalog in +context. + +## Usage + +Add to your MCP client (Claude Desktop, Cline, …): + +```json +{ + "mcpServers": { + "snowluma": { "command": "npx", "args": ["-y", "@snowluma/mcp"] } + } +} +``` + +## Tools + +- `list_actions({ category? })` — lightweight index (name / category / summary / aliases). +- `get_action({ name })` — full doc for one action incl. `inputSchema` (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`. + +## How it stays in sync + +The catalog 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 the published package carries **zero runtime dependency** on the +private `@snowluma/onebot`. 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`. diff --git a/packages/mcp/package.json b/packages/mcp/package.json new file mode 100644 index 00000000..e2738fd6 --- /dev/null +++ b/packages/mcp/package.json @@ -0,0 +1,49 @@ +{ + "name": "@snowluma/mcp", + "version": "1.9.4", + "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" + } +} diff --git a/packages/mcp/scripts/gen-catalog.test.ts b/packages/mcp/scripts/gen-catalog.test.ts new file mode 100644 index 00000000..292a710b --- /dev/null +++ b/packages/mcp/scripts/gen-catalog.test.ts @@ -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); +}); diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts new file mode 100644 index 00000000..37df0c15 --- /dev/null +++ b/packages/mcp/src/generated/catalog.ts @@ -0,0 +1,5751 @@ +// GENERATED by scripts/gen-catalog.test.ts — do not edit. Run `pnpm gen`. +/* eslint-disable */ +import type { CatalogAction, CatalogCategory } from '../types.js'; + +export const ACTIONS: CatalogAction[] = [ + { + "name": "_del_group_notice", + "aliases": [], + "summary": "删除群公告(fid 或 notice_id 二选一)", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "fid", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "notice_id", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "fid": { + "type": "string" + }, + "notice_id": { + "type": "string" + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "_get_group_notice", + "aliases": [], + "summary": "获取群公告", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "_get_model_show", + "aliases": [], + "summary": "获取机型展示(占位)", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "_mark_all_as_read", + "aliases": [], + "summary": "标记全部已读", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "_send_group_notice", + "aliases": [], + "summary": "发送群公告", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "content", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "image", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + }, + { + "name": "pinned", + "type": "raw", + "required": false, + "schema": {} + }, + { + "name": "type", + "type": "raw", + "required": false, + "schema": {} + }, + { + "name": "confirm_required", + "type": "raw", + "required": false, + "schema": {} + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "content": { + "type": "string", + "minLength": 1 + }, + "image": { + "type": "string", + "default": "" + }, + "pinned": {}, + "type": {}, + "confirm_required": {} + }, + "required": [ + "group_id", + "content" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "_set_model_show", + "aliases": [], + "summary": "设置机型展示(占位)", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": ".get_word_slices", + "aliases": [], + "summary": "分词(未实现)", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "bot_exit", + "aliases": [], + "summary": "退出机器人", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "can_send_image", + "aliases": [], + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "信息" + }, + { + "name": "can_send_record", + "aliases": [], + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "信息" + }, + { + "name": "cancel_group_album_media_like", + "aliases": [], + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "album_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "batch_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "lloc", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "album_id": { + "type": "string", + "minLength": 1 + }, + "batch_id": { + "type": "string", + "minLength": 1 + }, + "lloc": { + "type": "string" + } + }, + "required": [ + "group_id", + "album_id", + "batch_id" + ], + "additionalProperties": true + }, + "category": "群相册" + }, + { + "name": "cancel_group_todo", + "aliases": [], + "summary": "取消群待办", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "message_id", + "type": "messageId", + "required": true, + "schema": { + "type": "integer", + "not": { + "const": 0 + } + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "message_id": { + "type": "integer", + "not": { + "const": 0 + } + } + }, + "required": [ + "group_id", + "message_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "check_url_safely", + "aliases": [], + "summary": "检查链接安全性", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "clean_cache", + "aliases": [], + "summary": "清理缓存", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "click_inline_keyboard_button", + "aliases": [], + "summary": "点击内联键盘按钮", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "bot_appid", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "msg_seq", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "bot_appid": { + "type": "integer", + "minimum": 1 + }, + "msg_seq": { + "type": "integer", + "minimum": 1 + } + }, + "required": [ + "group_id", + "bot_appid", + "msg_seq" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "complete_group_todo", + "aliases": [], + "summary": "完成群待办", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "message_id", + "type": "messageId", + "required": true, + "schema": { + "type": "integer", + "not": { + "const": 0 + } + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "message_id": { + "type": "integer", + "not": { + "const": 0 + } + } + }, + "required": [ + "group_id", + "message_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "create_collection", + "aliases": [], + "summary": "创建收藏(未实现)", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "create_group_file_folder", + "aliases": [], + "summary": "创建群文件夹", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "name", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "parent_id", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "/" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "name": { + "type": "string", + "minLength": 1 + }, + "parent_id": { + "type": "string", + "default": "/" + } + }, + "required": [ + "group_id", + "name" + ], + "additionalProperties": true + }, + "category": "群文件" + }, + { + "name": "del_group_album_media", + "aliases": [], + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "album_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "lloc", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "album_id": { + "type": "string", + "minLength": 1 + }, + "lloc": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "group_id", + "album_id", + "lloc" + ], + "additionalProperties": true + }, + "category": "群相册" + }, + { + "name": "delete_essence_msg", + "aliases": [], + "summary": "移除精华消息", + "params": [ + { + "name": "message_id", + "type": "messageId", + "required": true, + "schema": { + "type": "integer", + "not": { + "const": 0 + } + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "message_id": { + "type": "integer", + "not": { + "const": 0 + } + } + }, + "required": [ + "message_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "delete_friend", + "aliases": [], + "summary": "删除好友", + "params": [ + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "QQ 号" + }, + { + "name": "block", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "user_id": { + "type": "integer", + "minimum": 1, + "description": "QQ 号" + }, + "block": { + "type": "boolean", + "default": false + } + }, + "required": [ + "user_id" + ], + "additionalProperties": true + }, + "category": "好友" + }, + { + "name": "delete_group_file", + "aliases": [], + "summary": "删除群文件", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "file_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "file_id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "group_id", + "file_id" + ], + "additionalProperties": true + }, + "category": "群文件" + }, + { + "name": "delete_group_file_folder", + "aliases": [], + "summary": "删除群文件夹", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "folder_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "folder_id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "group_id", + "folder_id" + ], + "additionalProperties": true + }, + "category": "群文件" + }, + { + "name": "delete_group_folder", + "aliases": [], + "summary": "删除群文件夹", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "folder_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "folder_id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "group_id", + "folder_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "delete_msg", + "aliases": [], + "summary": "撤回消息", + "params": [ + { + "name": "message_id", + "type": "messageId", + "required": true, + "schema": { + "type": "integer", + "not": { + "const": 0 + } + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "message_id": { + "type": "integer", + "not": { + "const": 0 + } + } + }, + "required": [ + "message_id" + ], + "additionalProperties": true + }, + "category": "消息" + }, + { + "name": "do_group_album_comment", + "aliases": [], + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "album_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "lloc", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "content", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "album_id": { + "type": "string", + "minLength": 1 + }, + "lloc": { + "type": "string", + "minLength": 1 + }, + "content": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "group_id", + "album_id", + "lloc", + "content" + ], + "additionalProperties": true + }, + "category": "群相册" + }, + { + "name": "download_file", + "aliases": [], + "summary": "下载文件(url 或 base64)到 data/downloads", + "returns": "{ file }", + "params": [ + { + "name": "url", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + }, + { + "name": "base64", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + }, + { + "name": "name", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "url": { + "type": "string", + "default": "" + }, + "base64": { + "type": "string", + "default": "" + }, + "name": { + "type": "string", + "default": "" + } + }, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "fetch_custom_face", + "aliases": [], + "summary": "获取自定义表情", + "params": [ + { + "name": "count", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 10 + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "count": { + "type": "integer", + "minimum": 0, + "default": 10 + } + }, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "fetch_emoji_like", + "aliases": [], + "summary": "获取表情回应用户(NapCat 分页)", + "params": [ + { + "name": "message_id", + "type": "messageId", + "required": true, + "schema": { + "type": "integer", + "not": { + "const": 0 + } + } + }, + { + "name": "emojiId", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "count", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 10 + }, + { + "name": "cookie", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "message_id": { + "type": "integer", + "not": { + "const": 0 + } + }, + "emojiId": { + "type": "string", + "minLength": 1 + }, + "count": { + "type": "integer", + "minimum": 0, + "default": 10 + }, + "cookie": { + "type": "string", + "default": "" + } + }, + "required": [ + "message_id", + "emojiId" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "fetch_ptt_text", + "aliases": [ + "get_ptt_text", + "get_record_text" + ], + "summary": "获取语音转文字结果", + "params": [ + { + "name": "message_id", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "message_id": { + "type": "string", + "default": "" + } + }, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "forward_friend_single_msg", + "aliases": [], + "summary": "转发单条消息给好友", + "params": [ + { + "name": "message_id", + "type": "messageId", + "required": true, + "schema": { + "type": "integer", + "not": { + "const": 0 + } + } + }, + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "message_id": { + "type": "integer", + "not": { + "const": 0 + } + }, + "user_id": { + "type": "integer", + "minimum": 1 + } + }, + "required": [ + "message_id", + "user_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "forward_group_single_msg", + "aliases": [], + "summary": "转发单条消息到群", + "params": [ + { + "name": "message_id", + "type": "messageId", + "required": true, + "schema": { + "type": "integer", + "not": { + "const": 0 + } + } + }, + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "message_id": { + "type": "integer", + "not": { + "const": 0 + } + }, + "group_id": { + "type": "integer", + "minimum": 1 + } + }, + "required": [ + "message_id", + "group_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "friend_poke", + "aliases": [], + "summary": "好友拍一拍", + "params": [ + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "target_id", + "type": "uint", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "user_id": { + "type": "integer", + "minimum": 1 + }, + "target_id": { + "type": "integer", + "minimum": 1 + } + }, + "required": [ + "user_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_ai_characters", + "aliases": [], + "summary": "获取 AI 语音角色", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "chat_type", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 1 + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "chat_type": { + "type": "integer", + "minimum": 0, + "default": 1 + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_ai_record", + "aliases": [], + "summary": "生成 AI 语音", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "character", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "text", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "chat_type", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 1 + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "character": { + "type": "string", + "minLength": 1 + }, + "text": { + "type": "string", + "minLength": 1 + }, + "chat_type": { + "type": "integer", + "minimum": 0, + "default": 1 + } + }, + "required": [ + "group_id", + "character", + "text" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_clientkey", + "aliases": [], + "summary": "获取 clientkey", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_collection_list", + "aliases": [], + "summary": "获取收藏列表(占位)", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_cookies", + "aliases": [], + "summary": "获取 Cookies", + "params": [ + { + "name": "domain", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "qun.qq.com" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "domain": { + "type": "string", + "default": "qun.qq.com" + } + }, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_credentials", + "aliases": [], + "summary": "获取凭证", + "params": [ + { + "name": "domain", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "qun.qq.com" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "domain": { + "type": "string", + "default": "qun.qq.com" + } + }, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_csrf_token", + "aliases": [], + "summary": "获取 CSRF 令牌", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_emoji_likes", + "aliases": [], + "summary": "获取表情回应用户", + "params": [ + { + "name": "message_id", + "type": "messageId", + "required": true, + "schema": { + "type": "integer", + "not": { + "const": 0 + } + } + }, + { + "name": "emoji_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "message_id": { + "type": "integer", + "not": { + "const": 0 + } + }, + "emoji_id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "message_id", + "emoji_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_essence_msg_list", + "aliases": [], + "summary": "获取精华消息列表", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_file", + "aliases": [], + "summary": "获取文件(未实现)", + "params": [ + { + "name": "file_id", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + }, + { + "name": "file", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "file_id": { + "type": "string", + "default": "" + }, + "file": { + "type": "string", + "default": "" + } + }, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_forward_msg", + "aliases": [], + "summary": "获取合并转发消息(id 或 message_id)", + "returns": "{ messages }", + "params": [ + { + "name": "id", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "id": { + "type": "string" + } + }, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_friend_list", + "aliases": [], + "summary": "获取好友列表", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "好友" + }, + { + "name": "get_friend_msg_history", + "aliases": [], + "summary": "获取好友消息历史", + "params": [ + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "message_id", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 0 + }, + { + "name": "count", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 20 + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "user_id": { + "type": "integer", + "minimum": 1 + }, + "message_id": { + "type": "integer", + "minimum": 0, + "default": 0 + }, + "count": { + "type": "integer", + "minimum": 0, + "default": 20 + } + }, + "required": [ + "user_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_friends_with_category", + "aliases": [], + "summary": "获取分组好友列表", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_group_album_list", + "aliases": [], + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "群相册" + }, + { + "name": "get_group_album_media_list", + "aliases": [], + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "album_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "attach_info", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "album_id": { + "type": "string", + "minLength": 1 + }, + "attach_info": { + "type": "string", + "default": "" + } + }, + "required": [ + "group_id", + "album_id" + ], + "additionalProperties": true + }, + "category": "群相册" + }, + { + "name": "get_group_at_all_remain", + "aliases": [], + "summary": "获取群 @全体成员 剩余次数", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_group_detail_info", + "aliases": [], + "summary": "获取群详细信息", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1 + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_group_file_system_info", + "aliases": [], + "summary": "获取群文件系统信息", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_group_file_url", + "aliases": [], + "summary": "获取群文件下载链接", + "returns": "{ url: string }", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "file_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "busid", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 102 + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "file_id": { + "type": "string", + "minLength": 1 + }, + "busid": { + "type": "integer", + "minimum": 0, + "default": 102 + } + }, + "required": [ + "group_id", + "file_id" + ], + "additionalProperties": true + }, + "category": "群文件" + }, + { + "name": "get_group_files_by_folder", + "aliases": [], + "summary": "获取群子目录文件列表", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "folder_id", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + }, + { + "name": "folder", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "folder_id": { + "type": "string", + "default": "" + }, + "folder": { + "type": "string", + "default": "" + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "群文件" + }, + { + "name": "get_group_honor_info", + "aliases": [], + "summary": "获取群荣誉信息", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "type", + "type": "raw", + "required": false, + "schema": {} + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "type": {} + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "群信息" + }, + { + "name": "get_group_ignore_add_request", + "aliases": [], + "summary": "获取被忽略的入群请求(NapCat)", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_group_ignored_notifies", + "aliases": [], + "summary": "获取被过滤的入群请求", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_group_info", + "aliases": [], + "summary": "获取群信息", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "no_cache", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "no_cache": { + "type": "boolean", + "default": false + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "群信息" + }, + { + "name": "get_group_info_ex", + "aliases": [], + "summary": "获取群信息(扩展)", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1 + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_group_list", + "aliases": [], + "summary": "获取群列表", + "params": [ + { + "name": "no_cache", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "no_cache": { + "type": "boolean", + "default": false + } + }, + "additionalProperties": true + }, + "category": "群信息" + }, + { + "name": "get_group_member_info", + "aliases": [], + "summary": "获取群成员信息", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "QQ 号" + }, + { + "name": "no_cache", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "user_id": { + "type": "integer", + "minimum": 1, + "description": "QQ 号" + }, + "no_cache": { + "type": "boolean", + "default": false + } + }, + "required": [ + "group_id", + "user_id" + ], + "additionalProperties": true + }, + "category": "群信息" + }, + { + "name": "get_group_member_list", + "aliases": [], + "summary": "获取群成员列表", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "no_cache", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "no_cache": { + "type": "boolean", + "default": false + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "群信息" + }, + { + "name": "get_group_msg_history", + "aliases": [], + "summary": "获取群消息历史", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "message_id", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 0 + }, + { + "name": "count", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 20 + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "message_id": { + "type": "integer", + "minimum": 0, + "default": 0 + }, + "count": { + "type": "integer", + "minimum": 0, + "default": 20 + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_group_root_files", + "aliases": [], + "summary": "获取群根目录文件列表", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "群文件" + }, + { + "name": "get_group_shut_list", + "aliases": [], + "summary": "获取群禁言列表(占位)", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_group_system_msg", + "aliases": [], + "summary": "获取群系统消息", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "群信息" + }, + { + "name": "get_image", + "aliases": [], + "summary": "获取图片信息", + "params": [ + { + "name": "file", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + }, + { + "name": "file_id", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "file": { + "type": "string", + "default": "" + }, + "file_id": { + "type": "string", + "default": "" + } + }, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_login_info", + "aliases": [], + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "信息" + }, + { + "name": "get_mini_app_ark", + "aliases": [], + "summary": "获取小程序卡片 ark", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_msg", + "aliases": [], + "summary": "获取消息", + "params": [ + { + "name": "message_id", + "type": "messageId", + "required": true, + "schema": { + "type": "integer", + "not": { + "const": 0 + } + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "message_id": { + "type": "integer", + "not": { + "const": 0 + } + } + }, + "required": [ + "message_id" + ], + "additionalProperties": true + }, + "category": "消息" + }, + { + "name": "get_online_clients", + "aliases": [], + "summary": "获取在线客户端(占位)", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_private_file_url", + "aliases": [], + "summary": "获取私聊文件下载链接", + "returns": "{ url: string }", + "params": [ + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "file_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "file_hash", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "user_id": { + "type": "integer", + "minimum": 1 + }, + "file_id": { + "type": "string", + "minLength": 1 + }, + "file_hash": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "user_id", + "file_id", + "file_hash" + ], + "additionalProperties": true + }, + "category": "群文件" + }, + { + "name": "get_profile_like", + "aliases": [], + "summary": "获取资料点赞", + "params": [ + { + "name": "user_id", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 0 + }, + { + "name": "start", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 0 + }, + { + "name": "count", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 10 + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "user_id": { + "type": "integer", + "minimum": 0, + "default": 0 + }, + "start": { + "type": "integer", + "minimum": 0, + "default": 0 + }, + "count": { + "type": "integer", + "minimum": 0, + "default": 10 + } + }, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_record", + "aliases": [], + "summary": "获取语音信息", + "params": [ + { + "name": "file", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + }, + { + "name": "file_id", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "file": { + "type": "string", + "default": "" + }, + "file_id": { + "type": "string", + "default": "" + } + }, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_rkey", + "aliases": [ + "nc_get_rkey" + ], + "summary": "获取下载 rkey", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_status", + "aliases": [], + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "信息" + }, + { + "name": "get_stranger_info", + "aliases": [], + "summary": "获取陌生人信息", + "params": [ + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "QQ 号" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "user_id": { + "type": "integer", + "minimum": 1, + "description": "QQ 号" + } + }, + "required": [ + "user_id" + ], + "additionalProperties": true + }, + "category": "好友" + }, + { + "name": "get_unidirectional_friend_list", + "aliases": [], + "summary": "获取单向好友列表", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "get_version_info", + "aliases": [], + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "信息" + }, + { + "name": "group_poke", + "aliases": [], + "summary": "群拍一拍", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "QQ 号" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "user_id": { + "type": "integer", + "minimum": 1, + "description": "QQ 号" + } + }, + "required": [ + "group_id", + "user_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "mark_group_msg_as_read", + "aliases": [], + "summary": "标记群消息已读", + "params": [ + { + "name": "message_id", + "type": "messageId", + "required": true, + "schema": { + "type": "integer", + "not": { + "const": 0 + } + } + }, + { + "name": "group_id", + "type": "uint", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "message_id": { + "type": "integer", + "not": { + "const": 0 + } + }, + "group_id": { + "type": "integer", + "minimum": 1 + } + }, + "required": [ + "message_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "mark_msg_as_read", + "aliases": [], + "summary": "标记消息已读(群聊/私聊自动路由)", + "params": [ + { + "name": "message_id", + "type": "messageId", + "required": true, + "schema": { + "type": "integer", + "not": { + "const": 0 + } + } + }, + { + "name": "target_id", + "type": "uint", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "message_id": { + "type": "integer", + "not": { + "const": 0 + } + }, + "target_id": { + "type": "integer", + "minimum": 1 + } + }, + "required": [ + "message_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "mark_private_msg_as_read", + "aliases": [], + "summary": "标记私聊消息已读", + "params": [ + { + "name": "message_id", + "type": "messageId", + "required": true, + "schema": { + "type": "integer", + "not": { + "const": 0 + } + } + }, + { + "name": "user_id", + "type": "uint", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "message_id": { + "type": "integer", + "not": { + "const": 0 + } + }, + "user_id": { + "type": "integer", + "minimum": 1 + } + }, + "required": [ + "message_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "move_group_file", + "aliases": [], + "summary": "移动群文件", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "file_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "parent_directory", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "target_directory", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "file_id": { + "type": "string", + "minLength": 1 + }, + "parent_directory": { + "type": "string", + "minLength": 1 + }, + "target_directory": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "group_id", + "file_id", + "parent_directory", + "target_directory" + ], + "additionalProperties": true + }, + "category": "群文件" + }, + { + "name": "nc_get_packet_status", + "aliases": [], + "summary": "获取 packet 状态(占位)", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "nc_get_user_status", + "aliases": [], + "summary": "获取用户在线/扩展状态", + "params": [ + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "user_id": { + "type": "integer", + "minimum": 1 + } + }, + "required": [ + "user_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "ocr_image", + "aliases": [ + ".ocr_image" + ], + "summary": "OCR 图片(未实现)", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "rename_group_file", + "aliases": [], + "summary": "重命名群文件(未实现)", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "rename_group_file_folder", + "aliases": [], + "summary": "重命名群文件夹", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "folder_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "new_folder_name", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + }, + { + "name": "name", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "folder_id": { + "type": "string", + "minLength": 1 + }, + "new_folder_name": { + "type": "string", + "default": "" + }, + "name": { + "type": "string", + "default": "" + } + }, + "required": [ + "group_id", + "folder_id" + ], + "additionalProperties": true + }, + "category": "群文件" + }, + { + "name": "request_decrypt_key", + "aliases": [], + "summary": "请求数据库解密密钥", + "params": [ + { + "name": "db_path", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "db_path": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "db_path" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "send_forward_msg", + "aliases": [], + "summary": "发送合并转发(按 message_type/群号自动路由)", + "returns": "{ message_id, res_id, forward_id }", + "params": [ + { + "name": "messages", + "type": "message", + "required": false, + "schema": { + "description": "OneBot message: string | segment[] | object" + } + }, + { + "name": "message", + "type": "message", + "required": false, + "schema": { + "description": "OneBot message: string | segment[] | object" + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "messages": { + "description": "OneBot message: string | segment[] | object" + }, + "message": { + "description": "OneBot message: string | segment[] | object" + } + }, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "send_group_ai_record", + "aliases": [], + "summary": "发送 AI 语音到群", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "character", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "text", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "chat_type", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 1 + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "character": { + "type": "string", + "minLength": 1 + }, + "text": { + "type": "string", + "minLength": 1 + }, + "chat_type": { + "type": "integer", + "minimum": 0, + "default": 1 + } + }, + "required": [ + "group_id", + "character", + "text" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "send_group_forward_msg", + "aliases": [], + "summary": "发送群合并转发", + "returns": "{ message_id, res_id, forward_id }", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "messages", + "type": "message", + "required": false, + "schema": { + "description": "OneBot message: string | segment[] | object" + } + }, + { + "name": "message", + "type": "message", + "required": false, + "schema": { + "description": "OneBot message: string | segment[] | object" + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "messages": { + "description": "OneBot message: string | segment[] | object" + }, + "message": { + "description": "OneBot message: string | segment[] | object" + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "send_group_msg", + "aliases": [], + "summary": "发送群消息", + "returns": "{ message_id: number }", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "message", + "type": "message", + "required": true, + "schema": { + "description": "OneBot message: string | segment[] | object" + } + }, + { + "name": "auto_escape", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "message": { + "description": "OneBot message: string | segment[] | object" + }, + "auto_escape": { + "type": "boolean", + "default": false + } + }, + "required": [ + "group_id", + "message" + ], + "additionalProperties": true + }, + "category": "消息" + }, + { + "name": "send_like", + "aliases": [], + "summary": "点赞", + "params": [ + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "times", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 1 + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "user_id": { + "type": "integer", + "minimum": 1 + }, + "times": { + "type": "integer", + "minimum": 0, + "default": 1 + } + }, + "required": [ + "user_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "send_msg", + "aliases": [], + "summary": "发送消息(按 message_type/群号 自动路由群聊或私聊)", + "returns": "{ message_id: number }", + "params": [ + { + "name": "message", + "type": "message", + "required": true, + "schema": { + "description": "OneBot message: string | segment[] | object" + } + }, + { + "name": "message_type", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "group_id", + "type": "uint", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "user_id", + "type": "uint", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "auto_escape", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "message": { + "description": "OneBot message: string | segment[] | object" + }, + "message_type": { + "type": "string" + }, + "group_id": { + "type": "integer", + "minimum": 1 + }, + "user_id": { + "type": "integer", + "minimum": 1 + }, + "auto_escape": { + "type": "boolean", + "default": false + } + }, + "required": [ + "message" + ], + "additionalProperties": true + }, + "category": "消息" + }, + { + "name": "send_packet", + "aliases": [ + ".send_packet" + ], + "summary": "发送原始 SSO 包(cmd + hex data)", + "params": [ + { + "name": "cmd", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "data", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + }, + { + "name": "rsp", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": true + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "cmd": { + "type": "string", + "minLength": 1 + }, + "data": { + "type": "string", + "default": "" + }, + "rsp": { + "type": "boolean", + "default": true + } + }, + "required": [ + "cmd" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "send_poke", + "aliases": [], + "summary": "拍一拍(群聊/私聊自动路由)", + "params": [ + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "group_id", + "type": "uint", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "user_id": { + "type": "integer", + "minimum": 1 + }, + "group_id": { + "type": "integer", + "minimum": 1 + } + }, + "required": [ + "user_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "send_private_forward_msg", + "aliases": [], + "summary": "发送私聊合并转发", + "returns": "{ message_id, res_id, forward_id }", + "params": [ + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "messages", + "type": "message", + "required": false, + "schema": { + "description": "OneBot message: string | segment[] | object" + } + }, + { + "name": "message", + "type": "message", + "required": false, + "schema": { + "description": "OneBot message: string | segment[] | object" + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "user_id": { + "type": "integer", + "minimum": 1 + }, + "messages": { + "description": "OneBot message: string | segment[] | object" + }, + "message": { + "description": "OneBot message: string | segment[] | object" + } + }, + "required": [ + "user_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "send_private_msg", + "aliases": [], + "summary": "发送私聊消息", + "returns": "{ message_id: number }", + "params": [ + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "message", + "type": "message", + "required": true, + "schema": { + "description": "OneBot message: string | segment[] | object" + } + }, + { + "name": "auto_escape", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "user_id": { + "type": "integer", + "minimum": 1 + }, + "message": { + "description": "OneBot message: string | segment[] | object" + }, + "auto_escape": { + "type": "boolean", + "default": false + } + }, + "required": [ + "user_id", + "message" + ], + "additionalProperties": true + }, + "category": "消息" + }, + { + "name": "set_diy_online_status", + "aliases": [], + "summary": "设置自定义在线状态", + "params": [ + { + "name": "face_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "face_type", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 1 + }, + { + "name": "wording", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "face_id": { + "type": "integer", + "minimum": 1 + }, + "face_type": { + "type": "integer", + "minimum": 0, + "default": 1 + }, + "wording": { + "type": "string", + "default": "" + } + }, + "required": [ + "face_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "set_essence_msg", + "aliases": [], + "summary": "设置精华消息", + "params": [ + { + "name": "message_id", + "type": "messageId", + "required": true, + "schema": { + "type": "integer", + "not": { + "const": 0 + } + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "message_id": { + "type": "integer", + "not": { + "const": 0 + } + } + }, + "required": [ + "message_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "set_friend_add_request", + "aliases": [], + "summary": "处理好友添加请求", + "params": [ + { + "name": "flag", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "approve", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": true + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "flag": { + "type": "string", + "minLength": 1 + }, + "approve": { + "type": "boolean", + "default": true + } + }, + "required": [ + "flag" + ], + "additionalProperties": true + }, + "category": "请求" + }, + { + "name": "set_friend_remark", + "aliases": [], + "summary": "设置好友备注", + "params": [ + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "remark", + "type": "string", + "required": true, + "schema": { + "type": "string" + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "user_id": { + "type": "integer", + "minimum": 1 + }, + "remark": { + "type": "string" + } + }, + "required": [ + "user_id", + "remark" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "set_group_add_option", + "aliases": [], + "summary": "设置加群选项", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "add_type", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 0 + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "add_type": { + "type": "integer", + "minimum": 0, + "default": 0 + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "群管理" + }, + { + "name": "set_group_add_request", + "aliases": [], + "summary": "处理加群请求", + "params": [ + { + "name": "flag", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "sub_type", + "type": "raw", + "required": false, + "schema": {} + }, + { + "name": "type", + "type": "raw", + "required": false, + "schema": {} + }, + { + "name": "approve", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": true + }, + { + "name": "reason", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "flag": { + "type": "string", + "minLength": 1 + }, + "sub_type": {}, + "type": {}, + "approve": { + "type": "boolean", + "default": true + }, + "reason": { + "type": "string", + "default": "" + } + }, + "required": [ + "flag" + ], + "additionalProperties": true + }, + "category": "请求" + }, + { + "name": "set_group_admin", + "aliases": [], + "summary": "设置/取消管理员", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "QQ 号" + }, + { + "name": "enable", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": true + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "user_id": { + "type": "integer", + "minimum": 1, + "description": "QQ 号" + }, + "enable": { + "type": "boolean", + "default": true + } + }, + "required": [ + "group_id", + "user_id" + ], + "additionalProperties": true + }, + "category": "群管理" + }, + { + "name": "set_group_album_media_like", + "aliases": [], + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "album_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "batch_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "lloc", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "album_id": { + "type": "string", + "minLength": 1 + }, + "batch_id": { + "type": "string", + "minLength": 1 + }, + "lloc": { + "type": "string" + } + }, + "required": [ + "group_id", + "album_id", + "batch_id" + ], + "additionalProperties": true + }, + "category": "群相册" + }, + { + "name": "set_group_anonymous", + "aliases": [], + "summary": "匿名开关(未实现,返回 ok)", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "群管理" + }, + { + "name": "set_group_anonymous_ban", + "aliases": [], + "summary": "匿名禁言(未实现,返回 ok)", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "群管理" + }, + { + "name": "set_group_ban", + "aliases": [], + "summary": "禁言群成员(duration=0 解除)", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "QQ 号" + }, + { + "name": "duration", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 1800 + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "user_id": { + "type": "integer", + "minimum": 1, + "description": "QQ 号" + }, + "duration": { + "type": "integer", + "minimum": 0, + "default": 1800 + } + }, + "required": [ + "group_id", + "user_id" + ], + "additionalProperties": true + }, + "category": "群管理" + }, + { + "name": "set_group_card", + "aliases": [], + "summary": "设置群名片(空字符串清除)", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "QQ 号" + }, + { + "name": "card", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "user_id": { + "type": "integer", + "minimum": 1, + "description": "QQ 号" + }, + "card": { + "type": "string", + "default": "" + } + }, + "required": [ + "group_id", + "user_id" + ], + "additionalProperties": true + }, + "category": "群管理" + }, + { + "name": "set_group_kick", + "aliases": [], + "summary": "踢出群成员", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "QQ 号" + }, + { + "name": "reject_add_request", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "user_id": { + "type": "integer", + "minimum": 1, + "description": "QQ 号" + }, + "reject_add_request": { + "type": "boolean", + "default": false + } + }, + "required": [ + "group_id", + "user_id" + ], + "additionalProperties": true + }, + "category": "群管理" + }, + { + "name": "set_group_kick_members", + "aliases": [], + "summary": "批量踢出群成员", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "user_id", + "type": "uint[]", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "integer", + "minimum": 1 + }, + "minItems": 1 + } + }, + { + "name": "reject_add_request", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "user_id": { + "type": "array", + "items": { + "type": "integer", + "minimum": 1 + }, + "minItems": 1 + }, + "reject_add_request": { + "type": "boolean", + "default": false + } + }, + "required": [ + "group_id", + "user_id" + ], + "additionalProperties": true + }, + "category": "群管理" + }, + { + "name": "set_group_leave", + "aliases": [], + "summary": "退群", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "群管理" + }, + { + "name": "set_group_name", + "aliases": [], + "summary": "设置群名", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "group_name", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "group_name": { + "type": "string", + "default": "" + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "群管理" + }, + { + "name": "set_group_portrait", + "aliases": [], + "summary": "设置群头像", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "file", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "file": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "group_id", + "file" + ], + "additionalProperties": true + }, + "category": "群管理" + }, + { + "name": "set_group_reaction", + "aliases": [], + "summary": "群聊表情回应", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "message_id", + "type": "messageId", + "required": true, + "schema": { + "type": "integer", + "not": { + "const": 0 + } + } + }, + { + "name": "code", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "is_set", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": true + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1 + }, + "message_id": { + "type": "integer", + "not": { + "const": 0 + } + }, + "code": { + "type": "string", + "minLength": 1 + }, + "is_set": { + "type": "boolean", + "default": true + } + }, + "required": [ + "message_id", + "code" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "set_group_remark", + "aliases": [], + "summary": "设置群备注", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "remark", + "type": "string", + "required": true, + "schema": { + "type": "string" + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1 + }, + "remark": { + "type": "string" + } + }, + "required": [ + "group_id", + "remark" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "set_group_search", + "aliases": [], + "summary": "允许群被搜索", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "群管理" + }, + { + "name": "set_group_sign", + "aliases": [ + "send_group_sign" + ], + "summary": "群签到", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "set_group_special_title", + "aliases": [], + "summary": "设置群头衔", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "QQ 号" + }, + { + "name": "special_title", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "user_id": { + "type": "integer", + "minimum": 1, + "description": "QQ 号" + }, + "special_title": { + "type": "string", + "default": "" + } + }, + "required": [ + "group_id", + "user_id" + ], + "additionalProperties": true + }, + "category": "群管理" + }, + { + "name": "set_group_todo", + "aliases": [], + "summary": "设置群待办", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "message_id", + "type": "messageId", + "required": true, + "schema": { + "type": "integer", + "not": { + "const": 0 + } + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "message_id": { + "type": "integer", + "not": { + "const": 0 + } + } + }, + "required": [ + "group_id", + "message_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "set_group_whole_ban", + "aliases": [], + "summary": "全员禁言开关", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "enable", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": true + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "enable": { + "type": "boolean", + "default": true + } + }, + "required": [ + "group_id" + ], + "additionalProperties": true + }, + "category": "群管理" + }, + { + "name": "set_input_status", + "aliases": [], + "summary": "设置输入状态", + "params": [ + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "event_type", + "type": "int", + "required": false, + "schema": { + "type": "integer" + }, + "default": 0 + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "user_id": { + "type": "integer", + "minimum": 1 + }, + "event_type": { + "type": "integer", + "default": 0 + } + }, + "required": [ + "user_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "set_msg_emoji_like", + "aliases": [], + "summary": "设置消息表情回应", + "params": [ + { + "name": "message_id", + "type": "messageId", + "required": true, + "schema": { + "type": "integer", + "not": { + "const": 0 + } + } + }, + { + "name": "emoji_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "set", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": true + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "message_id": { + "type": "integer", + "not": { + "const": 0 + } + }, + "emoji_id": { + "type": "string", + "minLength": 1 + }, + "set": { + "type": "boolean", + "default": true + } + }, + "required": [ + "message_id", + "emoji_id" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "set_online_status", + "aliases": [], + "summary": "设置在线状态", + "params": [ + { + "name": "status", + "type": "int", + "required": true, + "schema": { + "type": "integer", + "not": { + "const": 0 + } + } + }, + { + "name": "ext_status", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 0 + }, + { + "name": "battery_status", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + }, + "default": 100 + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "status": { + "type": "integer", + "not": { + "const": 0 + } + }, + "ext_status": { + "type": "integer", + "minimum": 0, + "default": 0 + }, + "battery_status": { + "type": "integer", + "minimum": 0, + "default": 100 + } + }, + "required": [ + "status" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "set_qq_avatar", + "aliases": [], + "summary": "设置 QQ 头像", + "params": [ + { + "name": "file", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "file": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "file" + ], + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "set_qq_profile", + "aliases": [], + "summary": "设置 QQ 资料", + "params": [ + { + "name": "nickname", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "personal_note", + "type": "string", + "required": false, + "schema": { + "type": "string" + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "nickname": { + "type": "string" + }, + "personal_note": { + "type": "string" + } + }, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "set_restart", + "aliases": [], + "summary": "重启(不支持)", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "set_self_longnick", + "aliases": [], + "summary": "设置个性签名(longNick/long_nick,严格 string)", + "params": [ + { + "name": "longNick", + "type": "raw", + "required": false, + "schema": {} + }, + { + "name": "long_nick", + "type": "raw", + "required": false, + "schema": {} + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "longNick": {}, + "long_nick": {} + }, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "trans_group_file", + "aliases": [], + "summary": "转存群文件(未实现)", + "params": [], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "translate_en2zh", + "aliases": [], + "summary": "英译中", + "returns": "{ words }", + "params": [ + { + "name": "words", + "type": "raw", + "required": false, + "schema": {} + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "words": {} + }, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "upload_forward_msg", + "aliases": [], + "summary": "上传转发消息", + "params": [ + { + "name": "messages", + "type": "message", + "required": false, + "schema": { + "description": "OneBot message: string | segment[] | object" + } + }, + { + "name": "message", + "type": "message", + "required": false, + "schema": { + "description": "OneBot message: string | segment[] | object" + } + }, + { + "name": "group_id", + "type": "uint", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "messages": { + "description": "OneBot message: string | segment[] | object" + }, + "message": { + "description": "OneBot message: string | segment[] | object" + }, + "group_id": { + "type": "integer", + "minimum": 1 + } + }, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "upload_foward_msg", + "aliases": [], + "summary": "上传转发消息(别名拼写)", + "params": [ + { + "name": "messages", + "type": "message", + "required": false, + "schema": { + "description": "OneBot message: string | segment[] | object" + } + }, + { + "name": "message", + "type": "message", + "required": false, + "schema": { + "description": "OneBot message: string | segment[] | object" + } + }, + { + "name": "group_id", + "type": "uint", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "messages": { + "description": "OneBot message: string | segment[] | object" + }, + "message": { + "description": "OneBot message: string | segment[] | object" + }, + "group_id": { + "type": "integer", + "minimum": 1 + } + }, + "additionalProperties": true + }, + "category": "扩展" + }, + { + "name": "upload_group_file", + "aliases": [], + "summary": "上传群文件", + "returns": "{ file_id: string }", + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "file", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "name", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + }, + { + "name": "folder", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + }, + { + "name": "folder_id", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + }, + { + "name": "upload_file", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": true + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "file": { + "type": "string", + "minLength": 1 + }, + "name": { + "type": "string", + "default": "" + }, + "folder": { + "type": "string", + "default": "" + }, + "folder_id": { + "type": "string", + "default": "" + }, + "upload_file": { + "type": "boolean", + "default": true + } + }, + "required": [ + "group_id", + "file" + ], + "additionalProperties": true + }, + "category": "群文件" + }, + { + "name": "upload_image_to_qun_album", + "aliases": [], + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "群号" + }, + { + "name": "album_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "album_name", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "file", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "minimum": 1, + "description": "群号" + }, + "album_id": { + "type": "string", + "minLength": 1 + }, + "album_name": { + "type": "string", + "minLength": 1 + }, + "file": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "group_id", + "album_id", + "album_name", + "file" + ], + "additionalProperties": true + }, + "category": "群相册" + }, + { + "name": "upload_private_file", + "aliases": [], + "summary": "上传私聊文件", + "returns": "{ file_id: string }", + "params": [ + { + "name": "user_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "file", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "name", + "type": "string", + "required": false, + "schema": { + "type": "string" + }, + "default": "" + }, + { + "name": "upload_file", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": true + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "user_id": { + "type": "integer", + "minimum": 1 + }, + "file": { + "type": "string", + "minLength": 1 + }, + "name": { + "type": "string", + "default": "" + }, + "upload_file": { + "type": "boolean", + "default": true + } + }, + "required": [ + "user_id", + "file" + ], + "additionalProperties": true + }, + "category": "群文件" + } +]; + +export const CATEGORIES: CatalogCategory[] = [ + { + "category": "信息", + "count": 5 + }, + { + "category": "消息", + "count": 5 + }, + { + "category": "好友", + "count": 3 + }, + { + "category": "群信息", + "count": 6 + }, + { + "category": "群管理", + "count": 14 + }, + { + "category": "群文件", + "count": 11 + }, + { + "category": "请求", + "count": 2 + }, + { + "category": "扩展", + "count": 85 + }, + { + "category": "群相册", + "count": 7 + } +]; diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts new file mode 100644 index 00000000..57c92fb1 --- /dev/null +++ b/packages/mcp/src/server.ts @@ -0,0 +1,148 @@ +#!/usr/bin/env node +// @snowluma/mcp — a read-only MCP server that exposes the SnowLuma OneBot action +// catalog (docs + per-action JSON Schemas) to LLM clients over stdio. +// +// The catalog is a build-time snapshot (src/generated/catalog.ts), regenerated +// from @snowluma/onebot's live action specs on every build — so it auto-tracks +// action add/remove and ships zero runtime dependency on onebot. +// +// 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 type { CatalogAction } from './types.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'; + +// name + every alias → the action, so get_action accepts aliases too. +const byName = new Map(); +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 }; +} + +const TOOLS = [ + { + name: 'list_actions', + description: '列出所有 OneBot action(可按 category 过滤)。返回轻量索引(名称/分类/摘要/别名)。', + inputSchema: { + type: 'object', + properties: { category: { type: 'string', description: '按分类过滤,如 群管理 / 消息 / 好友' } }, + additionalProperties: false, + }, + }, + { + name: 'get_action', + description: '获取某个 OneBot action 的完整文档:摘要、参数表、跨字段约束、返回,以及可直接用于构造调用的参数 JSON Schema(inputSchema)。', + inputSchema: { + type: 'object', + properties: { name: { type: 'string', description: 'action 名(接受别名)' } }, + required: ['name'], + additionalProperties: false, + }, + }, + { + name: 'search_actions', + description: '按关键字模糊搜索 action(匹配名称 / 摘要 / 别名)。返回轻量索引。', + inputSchema: { + type: 'object', + properties: { query: { type: 'string', description: '关键字' } }, + required: ['query'], + additionalProperties: false, + }, + }, + { + name: 'list_categories', + description: '列出所有分类及其 action 数量。', + inputSchema: { type: 'object', properties: {}, additionalProperties: false }, + }, +]; + +function asText(data: unknown) { + return { content: [{ type: 'text' as const, text: JSON.stringify(data, null, 2) }] }; +} +function asError(message: string) { + return { content: [{ type: 'text' as const, text: message }], isError: true }; +} + +const server = new Server( + { name: 'snowluma-mcp', version: VERSION }, + { capabilities: { tools: {}, resources: {} } }, +); + +server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS })); + +server.setRequestHandler(CallToolRequestSchema, async (req) => { + const name = req.params.name; + const args = (req.params.arguments ?? {}) as Record; + 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); + default: + return asError(`未知工具: ${name}`); + } +}); + +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); +console.error(`[snowluma-mcp] v${VERSION} ready — ${ACTIONS.length} actions, ${CATEGORIES.length} categories`); diff --git a/packages/mcp/src/types.ts b/packages/mcp/src/types.ts new file mode 100644 index 00000000..92334a01 --- /dev/null +++ b/packages/mcp/src/types.ts @@ -0,0 +1,34 @@ +// 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; + /** JSON Schema fragment for this single field. */ + schema?: Record; +} + +export interface CatalogAction { + name: string; + aliases: string[]; + category?: string; + summary?: string; + returns?: string; + 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; +} + +export interface CatalogCategory { + category: string; + count: number; +} diff --git a/packages/mcp/tsconfig.json b/packages/mcp/tsconfig.json new file mode 100644 index 00000000..b73094e4 --- /dev/null +++ b/packages/mcp/tsconfig.json @@ -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/**/*"] +} diff --git a/packages/mcp/vitest.config.ts b/packages/mcp/vitest.config.ts new file mode 100644 index 00000000..20b7342c --- /dev/null +++ b/packages/mcp/vitest.config.ts @@ -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'], + environment: 'node', + env: { + SNOWLUMA_LOG_FILE: '0', + }, + }, +}); diff --git a/packages/onebot/package.json b/packages/onebot/package.json index b211986d..14b093cb 100644 --- a/packages/onebot/package.json +++ b/packages/onebot/package.json @@ -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" diff --git a/packages/onebot/src/action-docs.ts b/packages/onebot/src/action-docs.ts index 0d89e09b..43982da9 100644 --- a/packages/onebot/src/action-docs.ts +++ b/packages/onebot/src/action-docs.ts @@ -25,21 +25,29 @@ import { actions as groupAlbumActions } from './actions/group-album'; type AnySpec = ActionSpec>>; -const ALL_SPECS: readonly AnySpec[] = [ - ...infoActions, - ...messageActions, - ...friendActions, - ...groupInfoActions, - ...groupAdminActions, - ...groupFileActions, - ...requestActions, - ...extendedActions, - ...groupAlbumActions, +// 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, sorted by name. */ -export function collectActionDocs(specs: readonly AnySpec[] = ALL_SPECS): ActionDoc[] { - return specs.map((s) => s.describe()).sort((a, b) => a.name.localeCompare(b.name)); +/** 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 { @@ -52,7 +60,8 @@ function paramRow(p: ActionDoc['params'][number]): string { function renderAction(doc: ActionDoc): string { const lines: string[] = []; const alias = doc.aliases.length ? ` _(别名: ${doc.aliases.map((a) => `\`${a}\``).join(', ')})_` : ''; - lines.push(`### \`${doc.name}\`${alias}`); + 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('', '| 参数 | 类型 | 必填 | 默认 | 说明 |', '| --- | --- | --- | --- | --- |'); diff --git a/packages/onebot/src/action-kit.ts b/packages/onebot/src/action-kit.ts index 644686a0..d3944431 100644 --- a/packages/onebot/src/action-kit.ts +++ b/packages/onebot/src/action-kit.ts @@ -39,12 +39,19 @@ 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; + 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 { @@ -57,6 +64,9 @@ export interface Field { * numeric field is an error, not a silent fallback). */ default(value: T): Field; describe(text: string): Field; + /** 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 @@ -92,6 +102,13 @@ class FieldImpl implements Field { describe(text: string): Field { return new FieldImpl(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` ─────────────────────────── @@ -113,8 +130,23 @@ function intCore(typeName: string, opts: IntOpts): Core { }; } +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(el: Field, mustBeNonEmpty: boolean): Field & { nonEmpty(): Field } { const core: Core = (raw, field) => { if (!Array.isArray(raw)) return err(field, 'expected an array'); @@ -127,24 +159,28 @@ function arrayField(el: Field, mustBeNonEmpty: boolean): Field & { no if (mustBeNonEmpty && out.length === 0) return err(field, 'must not be empty'); return ok(out); }; - const base = new FieldImpl(core, { type: `${el.doc.type}[]`, required: true }); + const base = new FieldImpl(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 { - return new FieldImpl(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true }); + return new FieldImpl(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 { - return new FieldImpl(intCore('an integer', opts), { type: 'int', required: true }); + return new FieldImpl(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 { - return new FieldImpl(intCore('a message id', { nonZero: true }), { type: 'messageId', required: true }); + return new FieldImpl(intCore('a message id', { nonZero: true }), { type: 'messageId', required: true, schema: intSchema({ nonZero: true }) }); }, /** Finite number (fractions allowed). */ number(): Field { @@ -152,7 +188,7 @@ export const f = { 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 }); + }, { type: 'number', required: true, schema: { type: 'number' } }); }, /** String. Numbers/booleans stringify (matches legacy `asString`). Empty * allowed by default; `{ allowEmpty: false }` rejects ''. */ @@ -165,7 +201,7 @@ export const f = { 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 }); + }, { type: 'string', required: true, schema: strSchema(opts) }); }, /** true/1/yes/on ⇒ true; false/0/no/off ⇒ false (matches legacy `asBoolean`). */ bool(): Field { @@ -178,7 +214,7 @@ export const f = { if (t === 'false' || t === '0' || t === 'no' || t === 'off') return ok(false); } return err(field, 'expected a boolean'); - }, { type: 'bool', required: true }); + }, { 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 @@ -197,7 +233,7 @@ export const f = { } } return ok(raw); - }, { type: 'message', required: true }); + }, { type: 'message', required: true, schema: { description: 'OneBot message: string | segment[] | object' } }); }, /** Homogeneous array; `.nonEmpty()` rejects []. */ array(el: Field): Field & { nonEmpty(): Field } { @@ -210,11 +246,11 @@ export const f = { return ok(raw as V[number]); } return err(field, `expected one of: ${values.join(', ')}`); - }, { type: 'enum', required: true, values }); + }, { type: 'enum', required: true, values, schema: { enum: [...values] } }); }, /** Escape hatch — pass the raw value (or undefined) through, validate nothing. */ raw(): Field { - return new FieldImpl((raw) => ok(raw), { type: 'raw', required: false, default: undefined }); + return new FieldImpl((raw) => ok(raw), { type: 'raw', required: false, default: undefined, schema: {} }); }, }; @@ -291,10 +327,14 @@ export interface ParamDoc extends FieldDoc { export interface ActionDoc { name: string; aliases: string[]; + /** Domain category (set by the doc collector, e.g. 群管理/消息). */ + category?: string; summary?: string; returns?: string; params: ParamDoc[]; invariants: string[]; + /** Composed JSON Schema for the whole params object (properties + required). */ + inputSchema: JsonSchema; } type Handler = (params: JsonObject) => Promise; @@ -359,14 +399,30 @@ export function defineAction(def: ActionDef): ActionSpec { params: def.params, parse, toHandler, - describe: () => ({ - name: names[0], - aliases: names.slice(1), - summary: def.summary, - returns: def.returns, - params: Object.entries(def.params).map(([name, field]) => ({ name, ...field.doc })), - invariants: rules.map((rule) => rule.doc), - }), + describe: () => { + const entries = Object.entries(def.params); + const properties: Record = {}; + 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, + 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); diff --git a/packages/onebot/tests/action-kit.test.ts b/packages/onebot/tests/action-kit.test.ts index 6ddf74d6..02a3d4cb 100644 --- a/packages/onebot/tests/action-kit.test.ts +++ b/packages/onebot/tests/action-kit.test.ts @@ -164,6 +164,42 @@ describe('run raw escape hatch — original params as 3rd arg', () => { }); }); +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'], diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2715a2c4..ce40a072 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -137,6 +137,31 @@ importers: specifier: ^4.1.4 version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + packages/mcp: + dependencies: + '@modelcontextprotocol/sdk': + specifier: ^1.0.0 + version: 1.29.0(zod@4.3.6) + devDependencies: + '@snowluma/onebot': + specifier: workspace:* + version: link:../onebot + '@snowluma/proton': + specifier: workspace:* + version: link:../proton + '@types/node': + specifier: ^24.12.2 + version: 24.12.2 + typescript: + specifier: 'catalog:' + version: 6.0.2 + vite: + specifier: 'catalog:' + version: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0) + vitest: + specifier: ^4.1.4 + version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) + packages/onebot: dependencies: '@snowluma/common': @@ -763,6 +788,16 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@modelcontextprotocol/sdk@1.29.0': + resolution: {integrity: sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==} + engines: {node: '>=18'} + peerDependencies: + '@cfworker/json-schema': ^4.1.1 + zod: ^3.25 || ^4.0 + peerDependenciesMeta: + '@cfworker/json-schema': + optional: true + '@napi-rs/wasm-runtime@1.1.4': resolution: {integrity: sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow==} peerDependencies: @@ -1830,6 +1865,10 @@ packages: '@vitest/utils@4.1.4': resolution: {integrity: sha512-13QMT+eysM5uVGa1rG4kegGYNp6cnQcsTc67ELFbhNLQO+vgsygtYJx2khvdt4gVQqSSpC/KT5FZZxUpP3Oatw==} + accepts@2.0.0: + resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==} + engines: {node: '>= 0.6'} + acorn-jsx@5.3.2: resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} peerDependencies: @@ -1840,9 +1879,20 @@ packages: engines: {node: '>=0.4.0'} hasBin: true + ajv-formats@3.0.1: + resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==} + peerDependencies: + ajv: ^8.0.0 + peerDependenciesMeta: + ajv: + optional: true + ajv@6.14.0: resolution: {integrity: sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==} + ajv@8.20.0: + resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} + any-promise@1.3.0: resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==} @@ -1875,6 +1925,10 @@ packages: blf-debug-appender@1.0.5: resolution: {integrity: sha512-ftNcGiVW2nxzG0WJ8Hcs58CbygPl2vMuLDDSxsfhGZmVl2NFGmZOuXhDDeJifvWmP0FHzP/L8dblxn65eQjgEA==} + body-parser@2.2.2: + resolution: {integrity: sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==} + engines: {node: '>=18'} + brace-expansion@5.0.5: resolution: {integrity: sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==} engines: {node: 18 || 20 || >=22} @@ -1890,10 +1944,22 @@ packages: peerDependencies: esbuild: '>=0.18' + bytes@3.1.2: + resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==} + engines: {node: '>= 0.8'} + cac@6.7.14: resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==} engines: {node: '>=8'} + call-bind-apply-helpers@1.0.2: + resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} + engines: {node: '>= 0.4'} + + call-bound@1.0.4: + resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==} + engines: {node: '>= 0.4'} + caniuse-lite@1.0.30001788: resolution: {integrity: sha512-6q8HFp+lOQtcf7wBK+uEenxymVWkGKkjFpCvw5W25cmMwEDU45p1xQFBQv8JDlMMry7eNxyBaR+qxgmTUZkIRQ==} @@ -1927,12 +1993,36 @@ packages: resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==} engines: {node: ^14.18.0 || >=16.10.0} + content-disposition@1.1.0: + resolution: {integrity: sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==} + engines: {node: '>=18'} + + content-type@1.0.5: + resolution: {integrity: sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==} + engines: {node: '>= 0.6'} + + content-type@2.0.0: + resolution: {integrity: sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==} + engines: {node: '>=18'} + convert-source-map@2.0.0: resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} cookie-es@3.1.1: resolution: {integrity: sha512-UaXxwISYJPTr9hwQxMFYZ7kNhSXboMXP+Z3TRX6f1/NyaGPfuNUZOWP1pUEb75B2HjfklIYLVRfWiFZJyC6Npg==} + cookie-signature@1.2.2: + resolution: {integrity: sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==} + engines: {node: '>=6.6.0'} + + cookie@0.7.2: + resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==} + engines: {node: '>= 0.6'} + + cors@2.8.6: + resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==} + engines: {node: '>= 0.10'} + cross-env@10.1.0: resolution: {integrity: sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==} engines: {node: '>=20'} @@ -1964,6 +2054,10 @@ packages: resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==} engines: {node: '>=0.10.0'} + depd@2.0.0: + resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==} + engines: {node: '>= 0.8'} + detect-libc@2.1.2: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} @@ -1971,13 +2065,28 @@ packages: detect-node-es@1.1.0: resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==} + dunder-proto@1.0.1: + resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} + engines: {node: '>= 0.4'} + + ee-first@1.1.1: + resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} + electron-to-chromium@1.5.339: resolution: {integrity: sha512-Is+0BBHJ4NrdpAYiperrmp53pLywG/yV/6lIMTAnhxvzj/Cmn5Q/ogSHC6AKe7X+8kPLxxFk0cs5oc/3j/fxIg==} + encodeurl@2.0.0: + resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==} + engines: {node: '>= 0.8'} + enhanced-resolve@5.20.1: resolution: {integrity: sha512-Qohcme7V1inbAfvjItgw0EaxVX5q2rdVEZHRBrEQdRZTssLDGsL8Lwrznl8oQ/6kuTJONLaDcGjkNP247XEhcA==} engines: {node: '>=10.13.0'} + es-define-property@1.0.1: + resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} + engines: {node: '>= 0.4'} + es-errors@1.3.0: resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} engines: {node: '>= 0.4'} @@ -1985,6 +2094,10 @@ packages: es-module-lexer@2.0.0: resolution: {integrity: sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw==} + es-object-atoms@1.1.2: + resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==} + engines: {node: '>= 0.4'} + esbuild@0.27.7: resolution: {integrity: sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==} engines: {node: '>=18'} @@ -1994,6 +2107,9 @@ packages: resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} engines: {node: '>=6'} + escape-html@1.0.3: + resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==} + escape-string-regexp@4.0.0: resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} engines: {node: '>=10'} @@ -2057,10 +2173,32 @@ packages: resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} engines: {node: '>=0.10.0'} + etag@1.8.1: + resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} + engines: {node: '>= 0.6'} + + eventsource-parser@3.1.0: + resolution: {integrity: sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==} + engines: {node: '>=18.0.0'} + + eventsource@3.0.7: + resolution: {integrity: sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==} + engines: {node: '>=18.0.0'} + expect-type@1.3.0: resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==} engines: {node: '>=12.0.0'} + express-rate-limit@8.5.2: + resolution: {integrity: sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A==} + engines: {node: '>= 16'} + peerDependencies: + express: '>= 4.11' + + express@5.2.1: + resolution: {integrity: sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==} + engines: {node: '>= 18'} + fast-deep-equal@3.1.3: resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} @@ -2070,6 +2208,9 @@ packages: fast-levenshtein@2.0.6: resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + fast-uri@3.1.2: + resolution: {integrity: sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==} + fdir@6.5.0: resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} engines: {node: '>=12.0.0'} @@ -2088,6 +2229,10 @@ packages: resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==} engines: {node: '>=16.0.0'} + finalhandler@2.1.1: + resolution: {integrity: sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==} + engines: {node: '>= 18.0.0'} + find-up@5.0.0: resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} engines: {node: '>=10'} @@ -2102,6 +2247,10 @@ packages: flatted@3.4.2: resolution: {integrity: sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==} + forwarded@0.2.0: + resolution: {integrity: sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==} + engines: {node: '>= 0.6'} + framer-motion@12.38.0: resolution: {integrity: sha512-rFYkY/pigbcswl1XQSb7q424kSTQ8q6eAC+YUsSKooHQYuLdzdHjrt6uxUC+PRAO++q5IS7+TamgIw1AphxR+g==} peerDependencies: @@ -2116,6 +2265,10 @@ packages: react-dom: optional: true + fresh@2.0.0: + resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==} + engines: {node: '>= 0.8'} + fs-extra@11.3.4: resolution: {integrity: sha512-CTXd6rk/M3/ULNQj8FBqBWHYBVYybQ3VPBw0xGKFe3tuH7ytT6ACnvzpIQ3UZtB8yvUKC2cXn1a+x+5EVQLovA==} engines: {node: '>=14.14'} @@ -2132,10 +2285,18 @@ packages: resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==} engines: {node: '>=6.9.0'} + get-intrinsic@1.3.0: + resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} + engines: {node: '>= 0.4'} + get-nonce@1.0.1: resolution: {integrity: sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==} engines: {node: '>=6'} + get-proto@1.0.1: + resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==} + engines: {node: '>= 0.4'} + get-tsconfig@4.14.0: resolution: {integrity: sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==} @@ -2147,6 +2308,10 @@ packages: resolution: {integrity: sha512-qoV+HK2yFl/366t2/Cb3+xxPUo5BuMynomoDmiaZBIdbs+0pYbjfZU+twLhGKp4uCZ/+NbtpVepH5bGCxRyy2g==} engines: {node: '>=18'} + gopd@1.2.0: + resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} + engines: {node: '>= 0.4'} + graceful-fs@4.2.11: resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} @@ -2154,6 +2319,10 @@ packages: resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} engines: {node: '>=8'} + has-symbols@1.1.0: + resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} + engines: {node: '>= 0.4'} + hasown@2.0.2: resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==} engines: {node: '>= 0.4'} @@ -2171,6 +2340,14 @@ packages: html-escaper@2.0.2: resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==} + http-errors@2.0.1: + resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==} + engines: {node: '>= 0.8'} + + iconv-lite@0.7.2: + resolution: {integrity: sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==} + engines: {node: '>=0.10.0'} + ignore@5.3.2: resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} engines: {node: '>= 4'} @@ -2186,6 +2363,17 @@ packages: resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} engines: {node: '>=0.8.19'} + inherits@2.0.4: + resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} + + ip-address@10.2.0: + resolution: {integrity: sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==} + engines: {node: '>= 12'} + + ipaddr.js@1.9.1: + resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==} + engines: {node: '>= 0.10'} + is-core-module@2.16.1: resolution: {integrity: sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==} engines: {node: '>= 0.4'} @@ -2201,6 +2389,9 @@ packages: is-module@1.0.0: resolution: {integrity: sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==} + is-promise@4.0.0: + resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==} + is-what-type@1.1.4: resolution: {integrity: sha512-120PeT8LdXO7m503rQtOapWA7lHBtWErN+asRxKyxF/SFGeqLEAZhlItjNynNVABHteRMSjomQCdAnxEJldMMQ==} @@ -2227,6 +2418,9 @@ packages: resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==} hasBin: true + jose@6.2.3: + resolution: {integrity: sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==} + joycon@3.1.1: resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==} engines: {node: '>=10'} @@ -2248,6 +2442,12 @@ packages: json-schema-traverse@0.4.1: resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} + json-schema-traverse@1.0.0: + resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==} + + json-schema-typed@8.0.2: + resolution: {integrity: sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==} + json-stable-stringify-without-jsonify@1.0.1: resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} @@ -2373,6 +2573,26 @@ packages: resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==} engines: {node: '>=10'} + math-intrinsics@1.1.0: + resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} + engines: {node: '>= 0.4'} + + media-typer@1.1.0: + resolution: {integrity: sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==} + engines: {node: '>= 0.8'} + + merge-descriptors@2.0.0: + resolution: {integrity: sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==} + engines: {node: '>=18'} + + mime-db@1.54.0: + resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==} + engines: {node: '>= 0.6'} + + mime-types@3.0.2: + resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==} + engines: {node: '>=18'} + minimatch@10.2.5: resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==} engines: {node: 18 || 20 || >=22} @@ -2414,6 +2634,10 @@ packages: natural-compare@1.4.0: resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + negotiator@1.0.0: + resolution: {integrity: sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==} + engines: {node: '>= 0.6'} + node-addon-api@7.1.1: resolution: {integrity: sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==} @@ -2424,9 +2648,20 @@ packages: resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} engines: {node: '>=0.10.0'} + object-inspect@1.13.4: + resolution: {integrity: sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==} + engines: {node: '>= 0.4'} + obug@2.1.1: resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==} + on-finished@2.4.1: + resolution: {integrity: sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==} + engines: {node: '>= 0.8'} + + once@1.4.0: + resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} + optionator@0.9.4: resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} engines: {node: '>= 0.8.0'} @@ -2439,6 +2674,10 @@ packages: resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} engines: {node: '>=10'} + parseurl@1.3.3: + resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==} + engines: {node: '>= 0.8'} + path-exists@4.0.0: resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} engines: {node: '>=8'} @@ -2450,6 +2689,9 @@ packages: path-parse@1.0.7: resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} + path-to-regexp@8.4.2: + resolution: {integrity: sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==} + pathe@2.0.3: resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} @@ -2464,6 +2706,10 @@ packages: resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==} engines: {node: '>= 6'} + pkce-challenge@5.0.1: + resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==} + engines: {node: '>=16.20.0'} + pkg-types@1.3.1: resolution: {integrity: sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==} @@ -2493,10 +2739,26 @@ packages: resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} engines: {node: '>= 0.8.0'} + proxy-addr@2.0.7: + resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==} + engines: {node: '>= 0.10'} + punycode@2.3.1: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} + qs@6.15.2: + resolution: {integrity: sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==} + engines: {node: '>=0.6'} + + range-parser@1.2.1: + resolution: {integrity: sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==} + engines: {node: '>= 0.6'} + + raw-body@3.0.2: + resolution: {integrity: sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==} + engines: {node: '>= 0.10'} + react-dom@19.2.5: resolution: {integrity: sha512-J5bAZz+DXMMwW/wV3xzKke59Af6CHY7G4uYLN1OvBcKEsWOs4pQExj86BBKamxl/Ik5bx9whOrvBlSDfWzgSag==} peerDependencies: @@ -2540,6 +2802,10 @@ packages: resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==} engines: {node: '>= 14.18.0'} + require-from-string@2.0.2: + resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} + engines: {node: '>=0.10.0'} + resolve-from@5.0.0: resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==} engines: {node: '>=8'} @@ -2562,6 +2828,13 @@ packages: engines: {node: '>=18.0.0', npm: '>=8.0.0'} hasBin: true + router@2.2.0: + resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==} + engines: {node: '>= 18'} + + safer-buffer@2.1.2: + resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + sass@1.99.0: resolution: {integrity: sha512-kgW13M54DUB7IsIRM5LvJkNlpH+WhMpooUcaWGFARkF1Tc82v9mIWkCbCYf+MBvpIUBSeSOTilpZjEPr2VYE6Q==} engines: {node: '>=14.0.0'} @@ -2579,6 +2852,10 @@ packages: engines: {node: '>=10'} hasBin: true + send@1.2.1: + resolution: {integrity: sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==} + engines: {node: '>= 18'} + seroval-plugins@1.5.4: resolution: {integrity: sha512-S0xQPhUTefAhNvNWFg0c1J8qJArHt5KdtJ/cFAofo06KD1MVSeFWyl4iiu+ApDIuw0WhjpOfCdgConOfAnLgkw==} engines: {node: '>=10'} @@ -2589,6 +2866,13 @@ packages: resolution: {integrity: sha512-46uFvgrXTVxZcUorgSSRZ4y+ieqLLQRMlG4bnCZKW3qI6BZm7Rg4ntMW4p1mILEEBZWrFlcpp0AyIIlM6jD9iw==} engines: {node: '>=10'} + serve-static@2.2.1: + resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==} + engines: {node: '>= 18'} + + setprototypeof@1.2.0: + resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==} + shebang-command@2.0.0: resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} engines: {node: '>=8'} @@ -2597,6 +2881,22 @@ packages: resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} engines: {node: '>=8'} + side-channel-list@1.0.1: + resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==} + engines: {node: '>= 0.4'} + + side-channel-map@1.0.1: + resolution: {integrity: sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==} + engines: {node: '>= 0.4'} + + side-channel-weakmap@1.0.2: + resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==} + engines: {node: '>= 0.4'} + + side-channel@1.1.0: + resolution: {integrity: sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==} + engines: {node: '>= 0.4'} + siginfo@2.0.0: resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} @@ -2617,6 +2917,10 @@ packages: stackback@0.0.2: resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + statuses@2.0.2: + resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==} + engines: {node: '>= 0.8'} + std-env@4.1.0: resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==} @@ -2668,6 +2972,10 @@ packages: resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==} engines: {node: '>=14.0.0'} + toidentifier@1.0.1: + resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==} + engines: {node: '>=0.6'} + tree-kill@1.2.2: resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==} hasBin: true @@ -2715,6 +3023,10 @@ packages: resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} engines: {node: '>= 0.8.0'} + type-is@2.1.0: + resolution: {integrity: sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==} + engines: {node: '>= 18'} + typescript-eslint@8.58.2: resolution: {integrity: sha512-V8iSng9mRbdZjl54VJ9NKr6ZB+dW0J3TzRXRGcSbLIej9jV86ZRtlYeTKDR/QLxXykocJ5icNzbsl2+5TzIvcQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -2740,6 +3052,10 @@ packages: resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==} engines: {node: '>= 10.0.0'} + unpipe@1.0.0: + resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==} + engines: {node: '>= 0.8'} + update-browserslist-db@1.2.3: resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==} hasBin: true @@ -2774,6 +3090,10 @@ packages: peerDependencies: react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + vary@1.1.2: + resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==} + engines: {node: '>= 0.8'} + vite-plugin-cp@6.0.3: resolution: {integrity: sha512-qxKGH3v9wPwUDbDchJf4IH4mRE1zkLWgzZSxwrl8LapwUWm48IFS7SlbRmcF4NquC/fESA5cHFge9E2Ps+woxg==} engines: {node: '>=14.18.0', vite: '>=3.1.0'} @@ -2880,6 +3200,9 @@ packages: resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} engines: {node: '>=0.10.0'} + wrappy@1.0.2: + resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} @@ -2887,6 +3210,11 @@ packages: resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} engines: {node: '>=10'} + zod-to-json-schema@3.25.2: + resolution: {integrity: sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==} + peerDependencies: + zod: ^3.25.28 || ^4 + zod-validation-error@4.0.2: resolution: {integrity: sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==} engines: {node: '>=18.0.0'} @@ -3187,6 +3515,28 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 + '@modelcontextprotocol/sdk@1.29.0(zod@4.3.6)': + dependencies: + '@hono/node-server': 1.19.14(hono@4.12.18) + ajv: 8.20.0 + ajv-formats: 3.0.1(ajv@8.20.0) + content-type: 1.0.5 + cors: 2.8.6 + cross-spawn: 7.0.6 + eventsource: 3.0.7 + eventsource-parser: 3.1.0 + express: 5.2.1 + express-rate-limit: 8.5.2(express@5.2.1) + hono: 4.12.18 + jose: 6.2.3 + json-schema-typed: 8.0.2 + pkce-challenge: 5.0.1 + raw-body: 3.0.2 + zod: 4.3.6 + zod-to-json-schema: 3.25.2(zod@4.3.6) + transitivePeerDependencies: + - supports-color + '@napi-rs/wasm-runtime@1.1.4(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)': dependencies: '@emnapi/core': 1.9.2 @@ -4140,12 +4490,21 @@ snapshots: convert-source-map: 2.0.0 tinyrainbow: 3.1.0 + accepts@2.0.0: + dependencies: + mime-types: 3.0.2 + negotiator: 1.0.0 + acorn-jsx@5.3.2(acorn@8.16.0): dependencies: acorn: 8.16.0 acorn@8.16.0: {} + ajv-formats@3.0.1(ajv@8.20.0): + optionalDependencies: + ajv: 8.20.0 + ajv@6.14.0: dependencies: fast-deep-equal: 3.1.3 @@ -4153,6 +4512,13 @@ snapshots: json-schema-traverse: 0.4.1 uri-js: 4.4.1 + ajv@8.20.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-uri: 3.1.2 + json-schema-traverse: 1.0.0 + require-from-string: 2.0.2 + any-promise@1.3.0: {} aria-hidden@1.2.6: @@ -4191,6 +4557,20 @@ snapshots: transitivePeerDependencies: - supports-color + body-parser@2.2.2: + dependencies: + bytes: 3.1.2 + content-type: 1.0.5 + debug: 4.4.3 + http-errors: 2.0.1 + iconv-lite: 0.7.2 + on-finished: 2.4.1 + qs: 6.15.2 + raw-body: 3.0.2 + type-is: 2.1.0 + transitivePeerDependencies: + - supports-color + brace-expansion@5.0.5: dependencies: balanced-match: 4.0.4 @@ -4208,8 +4588,20 @@ snapshots: esbuild: 0.27.7 load-tsconfig: 0.2.5 + bytes@3.1.2: {} + cac@6.7.14: {} + call-bind-apply-helpers@1.0.2: + dependencies: + es-errors: 1.3.0 + function-bind: 1.1.2 + + call-bound@1.0.4: + dependencies: + call-bind-apply-helpers: 1.0.2 + get-intrinsic: 1.3.0 + caniuse-lite@1.0.30001788: {} chai@6.2.2: {} @@ -4232,10 +4624,25 @@ snapshots: consola@3.4.2: {} + content-disposition@1.1.0: {} + + content-type@1.0.5: {} + + content-type@2.0.0: {} + convert-source-map@2.0.0: {} cookie-es@3.1.1: {} + cookie-signature@1.2.2: {} + + cookie@0.7.2: {} + + cors@2.8.6: + dependencies: + object-assign: 4.1.1 + vary: 1.1.2 + cross-env@10.1.0: dependencies: '@epic-web/invariant': 1.0.0 @@ -4259,21 +4666,39 @@ snapshots: deepmerge@4.3.1: {} + depd@2.0.0: {} + detect-libc@2.1.2: {} detect-node-es@1.1.0: {} + dunder-proto@1.0.1: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-errors: 1.3.0 + gopd: 1.2.0 + + ee-first@1.1.1: {} + electron-to-chromium@1.5.339: {} + encodeurl@2.0.0: {} + enhanced-resolve@5.20.1: dependencies: graceful-fs: 4.2.11 tapable: 2.3.2 + es-define-property@1.0.1: {} + es-errors@1.3.0: {} es-module-lexer@2.0.0: {} + es-object-atoms@1.1.2: + dependencies: + es-errors: 1.3.0 + esbuild@0.27.7: optionalDependencies: '@esbuild/aix-ppc64': 0.27.7 @@ -4305,6 +4730,8 @@ snapshots: escalade@3.2.0: {} + escape-html@1.0.3: {} + escape-string-regexp@4.0.0: {} eslint-plugin-react-hooks@7.0.1(eslint@10.2.0(jiti@2.6.1)): @@ -4394,14 +4821,62 @@ snapshots: esutils@2.0.3: {} + etag@1.8.1: {} + + eventsource-parser@3.1.0: {} + + eventsource@3.0.7: + dependencies: + eventsource-parser: 3.1.0 + expect-type@1.3.0: {} + express-rate-limit@8.5.2(express@5.2.1): + dependencies: + express: 5.2.1 + ip-address: 10.2.0 + + express@5.2.1: + dependencies: + accepts: 2.0.0 + body-parser: 2.2.2 + content-disposition: 1.1.0 + content-type: 1.0.5 + cookie: 0.7.2 + cookie-signature: 1.2.2 + debug: 4.4.3 + depd: 2.0.0 + encodeurl: 2.0.0 + escape-html: 1.0.3 + etag: 1.8.1 + finalhandler: 2.1.1 + fresh: 2.0.0 + http-errors: 2.0.1 + merge-descriptors: 2.0.0 + mime-types: 3.0.2 + on-finished: 2.4.1 + once: 1.4.0 + parseurl: 1.3.3 + proxy-addr: 2.0.7 + qs: 6.15.2 + range-parser: 1.2.1 + router: 2.2.0 + send: 1.2.1 + serve-static: 2.2.1 + statuses: 2.0.2 + type-is: 2.1.0 + vary: 1.1.2 + transitivePeerDependencies: + - supports-color + fast-deep-equal@3.1.3: {} fast-json-stable-stringify@2.1.0: {} fast-levenshtein@2.0.6: {} + fast-uri@3.1.2: {} + fdir@6.5.0(picomatch@4.0.4): optionalDependencies: picomatch: 4.0.4 @@ -4414,6 +4889,17 @@ snapshots: dependencies: flat-cache: 4.0.1 + finalhandler@2.1.1: + dependencies: + debug: 4.4.3 + encodeurl: 2.0.0 + escape-html: 1.0.3 + on-finished: 2.4.1 + parseurl: 1.3.3 + statuses: 2.0.2 + transitivePeerDependencies: + - supports-color + find-up@5.0.0: dependencies: locate-path: 6.0.0 @@ -4432,6 +4918,8 @@ snapshots: flatted@3.4.2: {} + forwarded@0.2.0: {} + framer-motion@12.38.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5): dependencies: motion-dom: 12.38.0 @@ -4441,6 +4929,8 @@ snapshots: react: 19.2.5 react-dom: 19.2.5(react@19.2.5) + fresh@2.0.0: {} + fs-extra@11.3.4: dependencies: graceful-fs: 4.2.11 @@ -4454,8 +4944,26 @@ snapshots: gensync@1.0.0-beta.2: {} + get-intrinsic@1.3.0: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-define-property: 1.0.1 + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + function-bind: 1.1.2 + get-proto: 1.0.1 + gopd: 1.2.0 + has-symbols: 1.1.0 + hasown: 2.0.2 + math-intrinsics: 1.1.0 + get-nonce@1.0.1: {} + get-proto@1.0.1: + dependencies: + dunder-proto: 1.0.1 + es-object-atoms: 1.1.2 + get-tsconfig@4.14.0: dependencies: resolve-pkg-maps: 1.0.0 @@ -4466,10 +4974,14 @@ snapshots: globals@17.5.0: {} + gopd@1.2.0: {} + graceful-fs@4.2.11: {} has-flag@4.0.0: {} + has-symbols@1.1.0: {} + hasown@2.0.2: dependencies: function-bind: 1.1.2 @@ -4484,6 +4996,18 @@ snapshots: html-escaper@2.0.2: {} + http-errors@2.0.1: + dependencies: + depd: 2.0.0 + inherits: 2.0.4 + setprototypeof: 1.2.0 + statuses: 2.0.2 + toidentifier: 1.0.1 + + iconv-lite@0.7.2: + dependencies: + safer-buffer: 2.1.2 + ignore@5.3.2: {} ignore@7.0.5: {} @@ -4493,6 +5017,12 @@ snapshots: imurmurhash@0.1.4: {} + inherits@2.0.4: {} + + ip-address@10.2.0: {} + + ipaddr.js@1.9.1: {} + is-core-module@2.16.1: dependencies: hasown: 2.0.2 @@ -4505,6 +5035,8 @@ snapshots: is-module@1.0.0: {} + is-promise@4.0.0: {} + is-what-type@1.1.4: {} isbot@5.1.40: {} @@ -4526,6 +5058,8 @@ snapshots: jiti@2.6.1: {} + jose@6.2.3: {} + joycon@3.1.1: {} js-tokens@10.0.0: {} @@ -4538,6 +5072,10 @@ snapshots: json-schema-traverse@0.4.1: {} + json-schema-traverse@1.0.0: {} + + json-schema-typed@8.0.2: {} + json-stable-stringify-without-jsonify@1.0.1: {} json5@2.2.3: {} @@ -4638,6 +5176,18 @@ snapshots: dependencies: semver: 7.7.4 + math-intrinsics@1.1.0: {} + + media-typer@1.1.0: {} + + merge-descriptors@2.0.0: {} + + mime-db@1.54.0: {} + + mime-types@3.0.2: + dependencies: + mime-db: 1.54.0 + minimatch@10.2.5: dependencies: brace-expansion: 5.0.5 @@ -4675,6 +5225,8 @@ snapshots: natural-compare@1.4.0: {} + negotiator@1.0.0: {} + node-addon-api@7.1.1: optional: true @@ -4682,8 +5234,18 @@ snapshots: object-assign@4.1.1: {} + object-inspect@1.13.4: {} + obug@2.1.1: {} + on-finished@2.4.1: + dependencies: + ee-first: 1.1.1 + + once@1.4.0: + dependencies: + wrappy: 1.0.2 + optionator@0.9.4: dependencies: deep-is: 0.1.4 @@ -4701,12 +5263,16 @@ snapshots: dependencies: p-limit: 3.1.0 + parseurl@1.3.3: {} + path-exists@4.0.0: {} path-key@3.1.1: {} path-parse@1.0.7: {} + path-to-regexp@8.4.2: {} + pathe@2.0.3: {} picocolors@1.1.1: {} @@ -4715,6 +5281,8 @@ snapshots: pirates@4.0.7: {} + pkce-challenge@5.0.1: {} + pkg-types@1.3.1: dependencies: confbox: 0.1.8 @@ -4737,8 +5305,26 @@ snapshots: prelude-ls@1.2.1: {} + proxy-addr@2.0.7: + dependencies: + forwarded: 0.2.0 + ipaddr.js: 1.9.1 + punycode@2.3.1: {} + qs@6.15.2: + dependencies: + side-channel: 1.1.0 + + range-parser@1.2.1: {} + + raw-body@3.0.2: + dependencies: + bytes: 3.1.2 + http-errors: 2.0.1 + iconv-lite: 0.7.2 + unpipe: 1.0.0 + react-dom@19.2.5(react@19.2.5): dependencies: react: 19.2.5 @@ -4775,6 +5361,8 @@ snapshots: readdirp@4.1.2: {} + require-from-string@2.0.2: {} + resolve-from@5.0.0: {} resolve-pkg-maps@1.0.0: {} @@ -4838,6 +5426,18 @@ snapshots: '@rollup/rollup-win32-x64-msvc': 4.60.4 fsevents: 2.3.3 + router@2.2.0: + dependencies: + debug: 4.4.3 + depd: 2.0.0 + is-promise: 4.0.0 + parseurl: 1.3.3 + path-to-regexp: 8.4.2 + transitivePeerDependencies: + - supports-color + + safer-buffer@2.1.2: {} + sass@1.99.0: dependencies: chokidar: 4.0.3 @@ -4853,18 +5453,73 @@ snapshots: semver@7.7.4: {} + send@1.2.1: + dependencies: + debug: 4.4.3 + encodeurl: 2.0.0 + escape-html: 1.0.3 + etag: 1.8.1 + fresh: 2.0.0 + http-errors: 2.0.1 + mime-types: 3.0.2 + ms: 2.1.3 + on-finished: 2.4.1 + range-parser: 1.2.1 + statuses: 2.0.2 + transitivePeerDependencies: + - supports-color + seroval-plugins@1.5.4(seroval@1.5.4): dependencies: seroval: 1.5.4 seroval@1.5.4: {} + serve-static@2.2.1: + dependencies: + encodeurl: 2.0.0 + escape-html: 1.0.3 + parseurl: 1.3.3 + send: 1.2.1 + transitivePeerDependencies: + - supports-color + + setprototypeof@1.2.0: {} + shebang-command@2.0.0: dependencies: shebang-regex: 3.0.0 shebang-regex@3.0.0: {} + side-channel-list@1.0.1: + dependencies: + es-errors: 1.3.0 + object-inspect: 1.13.4 + + side-channel-map@1.0.1: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + object-inspect: 1.13.4 + + side-channel-weakmap@1.0.2: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + object-inspect: 1.13.4 + side-channel-map: 1.0.1 + + side-channel@1.1.0: + dependencies: + es-errors: 1.3.0 + object-inspect: 1.13.4 + side-channel-list: 1.0.1 + side-channel-map: 1.0.1 + side-channel-weakmap: 1.0.2 + siginfo@2.0.0: {} sonner@2.0.7(react-dom@19.2.5(react@19.2.5))(react@19.2.5): @@ -4878,6 +5533,8 @@ snapshots: stackback@0.0.2: {} + statuses@2.0.2: {} + std-env@4.1.0: {} sucrase@3.35.1: @@ -4923,6 +5580,8 @@ snapshots: tinyrainbow@3.1.0: {} + toidentifier@1.0.1: {} + tree-kill@1.2.2: {} ts-api-utils@2.5.0(typescript@6.0.2): @@ -4974,6 +5633,12 @@ snapshots: dependencies: prelude-ls: 1.2.1 + type-is@2.1.0: + dependencies: + content-type: 2.0.0 + media-typer: 1.1.0 + mime-types: 3.0.2 + typescript-eslint@8.58.2(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2): dependencies: '@typescript-eslint/eslint-plugin': 8.58.2(@typescript-eslint/parser@8.58.2(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2))(eslint@10.2.0(jiti@2.6.1))(typescript@6.0.2) @@ -4995,6 +5660,8 @@ snapshots: universalify@2.0.1: {} + unpipe@1.0.0: {} + update-browserslist-db@1.2.3(browserslist@4.28.2): dependencies: browserslist: 4.28.2 @@ -5024,6 +5691,8 @@ snapshots: dependencies: react: 19.2.5 + vary@1.1.2: {} + vite-plugin-cp@6.0.3: dependencies: fs-extra: 11.3.4 @@ -5114,10 +5783,16 @@ snapshots: word-wrap@1.2.5: {} + wrappy@1.0.2: {} + yallist@3.1.1: {} yocto-queue@0.1.0: {} + zod-to-json-schema@3.25.2(zod@4.3.6): + dependencies: + zod: 4.3.6 + zod-validation-error@4.0.2(zod@4.3.6): dependencies: zod: 4.3.6 From d3092a1806bd787024d7a8332a350cbc21dbf0db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B8=B8=E6=89=8B=E5=A5=BD=E9=97=B2=E7=9A=84=E8=A8=80?= =?UTF-8?q?=E6=9F=92?= <68868379+tt-P607@users.noreply.github.com> Date: Wed, 3 Jun 2026 20:00:58 +0800 Subject: [PATCH 08/12] fix(onebot): support inline file url/path in send_group/private_msg (#80) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit file 段现接受 file/url/path(无需先 upload_group_file/upload_private_file);群走 groupFile.upload()、私聊走 uploadPrivate()(内部已 publish/sendC2c),file_id 老路径不变。含 parser 与群/私聊文件发送测试。 --- packages/onebot/src/message-parser.ts | 7 +- .../onebot/src/modules/message-actions.ts | 116 +++++++----------- packages/onebot/tests/message-parser.test.ts | 18 ++- packages/onebot/tests/send-group-file.test.ts | 39 +++++- .../tests/send-private-c2c-file.test.ts | 29 +++++ 5 files changed, 126 insertions(+), 83 deletions(-) diff --git a/packages/onebot/src/message-parser.ts b/packages/onebot/src/message-parser.ts index 23f6fe3f..9ddaa897 100644 --- a/packages/onebot/src/message-parser.ts +++ b/packages/onebot/src/message-parser.ts @@ -288,8 +288,9 @@ export async function segmentToElement(type: string, data: Record 0) elem.fileSize = fileSize; if (md5Hex) elem.md5Hex = md5Hex; diff --git a/packages/onebot/src/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts index 77160257..d8db7760 100644 --- a/packages/onebot/src/modules/message-actions.ts +++ b/packages/onebot/src/modules/message-actions.ts @@ -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> | 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> | 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'); diff --git a/packages/onebot/tests/message-parser.test.ts b/packages/onebot/tests/message-parser.test.ts index 945818b4..11f882ae 100644 --- a/packages/onebot/tests/message-parser.test.ts +++ b/packages/onebot/tests/message-parser.test.ts @@ -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([]); }); diff --git a/packages/onebot/tests/send-group-file.test.ts b/packages/onebot/tests/send-group-file.test.ts index 62038289..18745383 100644 --- a/packages/onebot/tests/send-group-file.test.ts +++ b/packages/onebot/tests/send-group-file.test.ts @@ -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(); }); }); diff --git a/packages/onebot/tests/send-private-c2c-file.test.ts b/packages/onebot/tests/send-private-c2c-file.test.ts index fe821cef..fb1e8ab8 100644 --- a/packages/onebot/tests/send-private-c2c-file.test.ts +++ b/packages/onebot/tests/send-private-c2c-file.test.ts @@ -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(); + }); }); From 18f7d847ac1b969003b6c54a34c0d91d894fe5cc Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 3 Jun 2026 20:53:36 +0800 Subject: [PATCH 09/12] refactor(onebot): lift the network adapter reload state machine into the base class The four NetworkAdapters each carried a byte-identical reload() state machine (sigChanged/wasEnabled -> Reopened/Closed/Opened/Normal). Lift it into IOneBotNetworkAdapter as a template method; per-adapter variation is now expressed via three hooks: bindingSignature(), willEnable() (default enabled!==false; clients add && !!url), and onConfigReplaced() (post-swap side effects). Also delete four redundant 'override get isActive()' (identical to the base getter), lift the duplicated uin-logger setup into the base ctor, and drop http-post's now-redundant signature_ cache. NetworkReloadType is a test-observability seam -- the sole production caller (instance.applyConfigDiff) discards it -- so a new base-level test exercises all transitions directly. Behaviour-preserving: +94/-157 in src, full workspace typecheck clean, 332 onebot tests pass. --- packages/onebot/src/network/adapter.ts | 62 ++++- .../onebot/src/network/http-post-adapter.ts | 52 +--- .../onebot/src/network/http-server-adapter.ts | 44 +--- .../onebot/src/network/ws-client-adapter.ts | 48 +--- .../onebot/src/network/ws-server-adapter.ts | 45 +--- .../adapter-reload-state-machine.test.ts | 224 ++++++++++++++++++ packages/onebot/tests/network-manager.test.ts | 7 +- 7 files changed, 324 insertions(+), 158 deletions(-) create mode 100644 packages/onebot/tests/adapter-reload-state-machine.test.ts diff --git a/packages/onebot/src/network/adapter.ts b/packages/onebot/src/network/adapter.ts index 4df2cc32..2c432538 100644 --- a/packages/onebot/src/network/adapter.ts +++ b/packages/onebot/src/network/adapter.ts @@ -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 { 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 { abstract open(): void | Promise; abstract close(): void | Promise; - abstract reload(config: C): NetworkReloadType | Promise; abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise; /** 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 { + 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; + } } diff --git a/packages/onebot/src/network/http-post-adapter.ts b/packages/onebot/src/network/http-post-adapter.ts index 1f650de1..b84deb44 100644 --- a/packages/onebot/src/network/http-post-adapter.ts +++ b/packages/onebot/src/network/http-post-adapter.ts @@ -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 { 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 { : { name: this.name, kind: 'httpClient', status: 'warn', detail: `上次推送失败 ${at}` }; } - async reload(next: HttpClientNetwork): Promise { - 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 { } } -function bindingSignature(net: HttpClientNetwork): string { - return `${net.url}#${net.accessToken ?? ''}#${net.timeoutMs ?? DEFAULT_TIMEOUT_MS}`; -} - async function computeHmacSha1(secret: string, payload: string): Promise { const { createHmac } = await import('crypto'); return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex'); diff --git a/packages/onebot/src/network/http-server-adapter.ts b/packages/onebot/src/network/http-server-adapter.ts index 0374234f..e683d087 100644 --- a/packages/onebot/src/network/http-server-adapter.ts +++ b/packages/onebot/src/network/http-server-adapter.ts @@ -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 { 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 return { name: this.name, kind: 'httpServer', status: 'ok', detail: '监听中' }; } - async reload(next: HttpServerNetwork): Promise { - 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 } } -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 { return new Promise((resolve, reject) => { const chunks: Buffer[] = []; diff --git a/packages/onebot/src/network/ws-client-adapter.ts b/packages/onebot/src/network/ws-client-adapter.ts index bc085bf8..e89397fa 100644 --- a/packages/onebot/src/network/ws-client-adapter.ts +++ b/packages/onebot/src/network/ws-client-adapter.ts @@ -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 { 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 { return { name: this.name, kind: 'wsClient', status: 'warn', detail: this.reconnectTimer ? '重连中' : '连接中' }; } - async reload(next: WsClientNetwork): Promise { - 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 { } } -function bindingSignature(net: WsClientNetwork): string { - return `${net.url}#${net.role ?? 'Universal'}#${Math.max(1000, net.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${net.accessToken ?? ''}`; -} diff --git a/packages/onebot/src/network/ws-server-adapter.ts b/packages/onebot/src/network/ws-server-adapter.ts index 1abb5c80..55c0a285 100644 --- a/packages/onebot/src/network/ws-server-adapter.ts +++ b/packages/onebot/src/network/ws-server-adapter.ts @@ -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 { private listening = false; private connections = new Map(); 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 { return { name: this.name, kind: 'wsServer', status: 'ok', detail: `${this.connections.size} 个客户端` }; } - async reload(next: WsServerNetwork): Promise { - 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 ?? ''}`; -} diff --git a/packages/onebot/tests/adapter-reload-state-machine.test.ts b/packages/onebot/tests/adapter-reload-state-machine.test.ts new file mode 100644 index 00000000..99e33e8b --- /dev/null +++ b/packages/onebot/tests/adapter-reload-state-machine.test.ts @@ -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 { + 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 { + 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, 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); + }); + }); +}); diff --git a/packages/onebot/tests/network-manager.test.ts b/packages/onebot/tests/network-manager.test.ts index 82b2e372..a7de011f 100644 --- a/packages/onebot/tests/network-manager.test.ts +++ b/packages/onebot/tests/network-manager.test.ts @@ -25,7 +25,9 @@ class FakeAdapter extends IOneBotNetworkAdapter { 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 { } 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); From 6d92a28e2b4298b0e9c291877022cb24bdb8f02d Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 3 Jun 2026 21:53:02 +0800 Subject: [PATCH 10/12] =?UTF-8?q?feat(mcp):=20execution=20mode=20=E2=80=94?= =?UTF-8?q?=20query/invoke=20OneBot=20actions=20with=20a=20read/write=20sa?= =?UTF-8?q?fety=20gate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit @snowluma/mcp gains execution alongside the read-only catalog: when SNOWLUMA_MCP_ENDPOINT is set it exposes query_action (read-only actions, readOnlyHint) and, in write mode, invoke_action (any known action, destructiveHint), proxied to a running OneBot instance over HTTP. Without an endpoint it degrades to docs-only. SNOWLUMA_MCP_MODE (docs|read|write) gates tool visibility AND is re-checked in execute(), so an unlisted tool cannot be called; unknown/legacy actions are non-invokable. Read vs write is classified precisely at the source: defineAction/preset gain readOnly (default false = write, the safe default), flowed through describe() into the generated catalog snapshot. 58 actions are marked read-only by what their run() actually does -- name-traps like get_ai_record (publishes to the group), request_decrypt_key (returns a DB key), and download_file (arbitrary URL + disk write) stay writes. The HTTP call is a ~20-line fetch bridge rather than @snowluma/sdk: the SDK's published dist is bundler-only ESM (extensionless imports) that native node cannot load, and the bin stays a plain tsc build. onebot 332 tests pass (readOnly is metadata-only, no behavior change); mcp gains 21 tests for mode gating / read-write routing / envelope passthrough / error mapping. Full workspace typecheck clean; native node smoke verified. --- packages/mcp/src/client.ts | 69 ++++++++ packages/mcp/src/generated/catalog.ts | 138 ++++++++++++++++ packages/mcp/src/server.ts | 134 ++++++--------- packages/mcp/src/tools.ts | 182 +++++++++++++++++++++ packages/mcp/src/types.ts | 4 + packages/mcp/tests/client.test.ts | 39 +++++ packages/mcp/tests/tools.test.ts | 138 ++++++++++++++++ packages/mcp/vitest.config.ts | 2 +- packages/onebot/src/action-kit.ts | 9 + packages/onebot/src/actions/extended.ts | 38 +++++ packages/onebot/src/actions/friend.ts | 2 + packages/onebot/src/actions/group-album.ts | 2 + packages/onebot/src/actions/group-file.ts | 4 + packages/onebot/src/actions/group-info.ts | 6 + packages/onebot/src/actions/info.ts | 5 + packages/onebot/src/actions/message.ts | 1 + 16 files changed, 684 insertions(+), 89 deletions(-) create mode 100644 packages/mcp/src/client.ts create mode 100644 packages/mcp/src/tools.ts create mode 100644 packages/mcp/tests/client.test.ts create mode 100644 packages/mcp/tests/tools.test.ts diff --git a/packages/mcp/src/client.ts b/packages/mcp/src/client.ts new file mode 100644 index 00000000..155a52c1 --- /dev/null +++ b/packages/mcp/src/client.ts @@ -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): Promise; +} + +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 = { + '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; + }, + }; +} diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index 37df0c15..acccda55 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -7,6 +7,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "_del_group_notice", "aliases": [], "summary": "删除群公告(fid 或 notice_id 二选一)", + "readOnly": false, "params": [ { "name": "group_id", @@ -62,6 +63,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "_get_group_notice", "aliases": [], "summary": "获取群公告", + "readOnly": true, "params": [ { "name": "group_id", @@ -95,6 +97,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "_get_model_show", "aliases": [], "summary": "获取机型展示(占位)", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -108,6 +111,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "_mark_all_as_read", "aliases": [], "summary": "标记全部已读", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -121,6 +125,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "_send_group_notice", "aliases": [], "summary": "发送群公告", + "readOnly": false, "params": [ { "name": "group_id", @@ -202,6 +207,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "_set_model_show", "aliases": [], "summary": "设置机型展示(占位)", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -215,6 +221,7 @@ export const ACTIONS: CatalogAction[] = [ "name": ".get_word_slices", "aliases": [], "summary": "分词(未实现)", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -228,6 +235,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "bot_exit", "aliases": [], "summary": "退出机器人", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -240,6 +248,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "can_send_image", "aliases": [], + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -252,6 +261,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "can_send_record", "aliases": [], + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -264,6 +274,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "cancel_group_album_media_like", "aliases": [], + "readOnly": false, "params": [ { "name": "group_id", @@ -336,6 +347,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "cancel_group_todo", "aliases": [], "summary": "取消群待办", + "readOnly": false, "params": [ { "name": "group_id", @@ -387,6 +399,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "check_url_safely", "aliases": [], "summary": "检查链接安全性", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -400,6 +413,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "clean_cache", "aliases": [], "summary": "清理缓存", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -413,6 +427,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "click_inline_keyboard_button", "aliases": [], "summary": "点击内联键盘按钮", + "readOnly": false, "params": [ { "name": "group_id", @@ -474,6 +489,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "complete_group_todo", "aliases": [], "summary": "完成群待办", + "readOnly": false, "params": [ { "name": "group_id", @@ -525,6 +541,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "create_collection", "aliases": [], "summary": "创建收藏(未实现)", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -538,6 +555,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "create_group_file_folder", "aliases": [], "summary": "创建群文件夹", + "readOnly": false, "params": [ { "name": "group_id", @@ -597,6 +615,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "del_group_album_media", "aliases": [], + "readOnly": false, "params": [ { "name": "group_id", @@ -658,6 +677,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "delete_essence_msg", "aliases": [], "summary": "移除精华消息", + "readOnly": false, "params": [ { "name": "message_id", @@ -693,6 +713,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "delete_friend", "aliases": [], "summary": "删除好友", + "readOnly": false, "params": [ { "name": "user_id", @@ -739,6 +760,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "delete_group_file", "aliases": [], "summary": "删除群文件", + "readOnly": false, "params": [ { "name": "group_id", @@ -786,6 +808,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "delete_group_file_folder", "aliases": [], "summary": "删除群文件夹", + "readOnly": false, "params": [ { "name": "group_id", @@ -833,6 +856,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "delete_group_folder", "aliases": [], "summary": "删除群文件夹", + "readOnly": false, "params": [ { "name": "group_id", @@ -880,6 +904,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "delete_msg", "aliases": [], "summary": "撤回消息", + "readOnly": false, "params": [ { "name": "message_id", @@ -914,6 +939,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "do_group_album_comment", "aliases": [], + "readOnly": false, "params": [ { "name": "group_id", @@ -990,6 +1016,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "下载文件(url 或 base64)到 data/downloads", "returns": "{ file }", + "readOnly": false, "params": [ { "name": "url", @@ -1044,6 +1071,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "fetch_custom_face", "aliases": [], "summary": "获取自定义表情", + "readOnly": true, "params": [ { "name": "count", @@ -1074,6 +1102,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "fetch_emoji_like", "aliases": [], "summary": "获取表情回应用户(NapCat 分页)", + "readOnly": true, "params": [ { "name": "message_id", @@ -1154,6 +1183,7 @@ export const ACTIONS: CatalogAction[] = [ "get_record_text" ], "summary": "获取语音转文字结果", + "readOnly": true, "params": [ { "name": "message_id", @@ -1182,6 +1212,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "forward_friend_single_msg", "aliases": [], "summary": "转发单条消息给好友", + "readOnly": false, "params": [ { "name": "message_id", @@ -1231,6 +1262,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "forward_group_single_msg", "aliases": [], "summary": "转发单条消息到群", + "readOnly": false, "params": [ { "name": "message_id", @@ -1280,6 +1312,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "friend_poke", "aliases": [], "summary": "好友拍一拍", + "readOnly": false, "params": [ { "name": "user_id", @@ -1324,6 +1357,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_ai_characters", "aliases": [], "summary": "获取 AI 语音角色", + "readOnly": true, "params": [ { "name": "group_id", @@ -1372,6 +1406,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_ai_record", "aliases": [], "summary": "生成 AI 语音", + "readOnly": false, "params": [ { "name": "group_id", @@ -1448,6 +1483,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_clientkey", "aliases": [], "summary": "获取 clientkey", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -1461,6 +1497,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_collection_list", "aliases": [], "summary": "获取收藏列表(占位)", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -1474,6 +1511,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_cookies", "aliases": [], "summary": "获取 Cookies", + "readOnly": true, "params": [ { "name": "domain", @@ -1502,6 +1540,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_credentials", "aliases": [], "summary": "获取凭证", + "readOnly": true, "params": [ { "name": "domain", @@ -1530,6 +1569,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_csrf_token", "aliases": [], "summary": "获取 CSRF 令牌", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -1543,6 +1583,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_emoji_likes", "aliases": [], "summary": "获取表情回应用户", + "readOnly": true, "params": [ { "name": "message_id", @@ -1592,6 +1633,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_essence_msg_list", "aliases": [], "summary": "获取精华消息列表", + "readOnly": true, "params": [ { "name": "group_id", @@ -1625,6 +1667,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_file", "aliases": [], "summary": "获取文件(未实现)", + "readOnly": true, "params": [ { "name": "file_id", @@ -1667,6 +1710,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "获取合并转发消息(id 或 message_id)", "returns": "{ messages }", + "readOnly": true, "params": [ { "name": "id", @@ -1693,6 +1737,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_friend_list", "aliases": [], "summary": "获取好友列表", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -1706,6 +1751,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_friend_msg_history", "aliases": [], "summary": "获取好友消息历史", + "readOnly": true, "params": [ { "name": "user_id", @@ -1767,6 +1813,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_friends_with_category", "aliases": [], "summary": "获取分组好友列表", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -1779,6 +1826,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "get_group_album_list", "aliases": [], + "readOnly": true, "params": [ { "name": "group_id", @@ -1811,6 +1859,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "get_group_album_media_list", "aliases": [], + "readOnly": true, "params": [ { "name": "group_id", @@ -1871,6 +1920,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_at_all_remain", "aliases": [], "summary": "获取群 @全体成员 剩余次数", + "readOnly": true, "params": [ { "name": "group_id", @@ -1904,6 +1954,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_detail_info", "aliases": [], "summary": "获取群详细信息", + "readOnly": true, "params": [ { "name": "group_id", @@ -1935,6 +1986,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_file_system_info", "aliases": [], "summary": "获取群文件系统信息", + "readOnly": true, "params": [ { "name": "group_id", @@ -1969,6 +2021,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "获取群文件下载链接", "returns": "{ url: string }", + "readOnly": true, "params": [ { "name": "group_id", @@ -2031,6 +2084,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_files_by_folder", "aliases": [], "summary": "获取群子目录文件列表", + "readOnly": true, "params": [ { "name": "group_id", @@ -2090,6 +2144,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_honor_info", "aliases": [], "summary": "获取群荣誉信息", + "readOnly": true, "params": [ { "name": "group_id", @@ -2130,6 +2185,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_ignore_add_request", "aliases": [], "summary": "获取被忽略的入群请求(NapCat)", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2143,6 +2199,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_ignored_notifies", "aliases": [], "summary": "获取被过滤的入群请求", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2156,6 +2213,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_info", "aliases": [], "summary": "获取群信息", + "readOnly": true, "params": [ { "name": "group_id", @@ -2202,6 +2260,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_info_ex", "aliases": [], "summary": "获取群信息(扩展)", + "readOnly": true, "params": [ { "name": "group_id", @@ -2233,6 +2292,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_list", "aliases": [], "summary": "获取群列表", + "readOnly": true, "params": [ { "name": "no_cache", @@ -2261,6 +2321,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_member_info", "aliases": [], "summary": "获取群成员信息", + "readOnly": true, "params": [ { "name": "group_id", @@ -2323,6 +2384,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_member_list", "aliases": [], "summary": "获取群成员列表", + "readOnly": true, "params": [ { "name": "group_id", @@ -2369,6 +2431,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_msg_history", "aliases": [], "summary": "获取群消息历史", + "readOnly": true, "params": [ { "name": "group_id", @@ -2432,6 +2495,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_root_files", "aliases": [], "summary": "获取群根目录文件列表", + "readOnly": true, "params": [ { "name": "group_id", @@ -2465,6 +2529,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_shut_list", "aliases": [], "summary": "获取群禁言列表(占位)", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2478,6 +2543,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_system_msg", "aliases": [], "summary": "获取群系统消息", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2491,6 +2557,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_image", "aliases": [], "summary": "获取图片信息", + "readOnly": true, "params": [ { "name": "file", @@ -2531,6 +2598,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "get_login_info", "aliases": [], + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2544,6 +2612,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_mini_app_ark", "aliases": [], "summary": "获取小程序卡片 ark", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2557,6 +2626,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_msg", "aliases": [], "summary": "获取消息", + "readOnly": true, "params": [ { "name": "message_id", @@ -2592,6 +2662,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_online_clients", "aliases": [], "summary": "获取在线客户端(占位)", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2606,6 +2677,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "获取私聊文件下载链接", "returns": "{ url: string }", + "readOnly": true, "params": [ { "name": "user_id", @@ -2665,6 +2737,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_profile_like", "aliases": [], "summary": "获取资料点赞", + "readOnly": true, "params": [ { "name": "user_id", @@ -2725,6 +2798,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_record", "aliases": [], "summary": "获取语音信息", + "readOnly": true, "params": [ { "name": "file", @@ -2768,6 +2842,7 @@ export const ACTIONS: CatalogAction[] = [ "nc_get_rkey" ], "summary": "获取下载 rkey", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2780,6 +2855,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "get_status", "aliases": [], + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2793,6 +2869,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_stranger_info", "aliases": [], "summary": "获取陌生人信息", + "readOnly": true, "params": [ { "name": "user_id", @@ -2826,6 +2903,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_unidirectional_friend_list", "aliases": [], "summary": "获取单向好友列表", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2838,6 +2916,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "get_version_info", "aliases": [], + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2851,6 +2930,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_poke", "aliases": [], "summary": "群拍一拍", + "readOnly": false, "params": [ { "name": "group_id", @@ -2900,6 +2980,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "mark_group_msg_as_read", "aliases": [], "summary": "标记群消息已读", + "readOnly": false, "params": [ { "name": "message_id", @@ -2948,6 +3029,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "mark_msg_as_read", "aliases": [], "summary": "标记消息已读(群聊/私聊自动路由)", + "readOnly": false, "params": [ { "name": "message_id", @@ -2996,6 +3078,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "mark_private_msg_as_read", "aliases": [], "summary": "标记私聊消息已读", + "readOnly": false, "params": [ { "name": "message_id", @@ -3044,6 +3127,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "move_group_file", "aliases": [], "summary": "移动群文件", + "readOnly": false, "params": [ { "name": "group_id", @@ -3119,6 +3203,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "nc_get_packet_status", "aliases": [], "summary": "获取 packet 状态(占位)", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -3132,6 +3217,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "nc_get_user_status", "aliases": [], "summary": "获取用户在线/扩展状态", + "readOnly": true, "params": [ { "name": "user_id", @@ -3165,6 +3251,7 @@ export const ACTIONS: CatalogAction[] = [ ".ocr_image" ], "summary": "OCR 图片(未实现)", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -3178,6 +3265,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "rename_group_file", "aliases": [], "summary": "重命名群文件(未实现)", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -3191,6 +3279,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "rename_group_file_folder", "aliases": [], "summary": "重命名群文件夹", + "readOnly": false, "params": [ { "name": "group_id", @@ -3264,6 +3353,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "request_decrypt_key", "aliases": [], "summary": "请求数据库解密密钥", + "readOnly": false, "params": [ { "name": "db_path", @@ -3296,6 +3386,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "发送合并转发(按 message_type/群号自动路由)", "returns": "{ message_id, res_id, forward_id }", + "readOnly": false, "params": [ { "name": "messages", @@ -3333,6 +3424,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "send_group_ai_record", "aliases": [], "summary": "发送 AI 语音到群", + "readOnly": false, "params": [ { "name": "group_id", @@ -3410,6 +3502,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "发送群合并转发", "returns": "{ message_id, res_id, forward_id }", + "readOnly": false, "params": [ { "name": "group_id", @@ -3466,6 +3559,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "发送群消息", "returns": "{ message_id: number }", + "readOnly": false, "params": [ { "name": "group_id", @@ -3524,6 +3618,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "send_like", "aliases": [], "summary": "点赞", + "readOnly": false, "params": [ { "name": "user_id", @@ -3571,6 +3666,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "发送消息(按 message_type/群号 自动路由群聊或私聊)", "returns": "{ message_id: number }", + "readOnly": false, "params": [ { "name": "message", @@ -3652,6 +3748,7 @@ export const ACTIONS: CatalogAction[] = [ ".send_packet" ], "summary": "发送原始 SSO 包(cmd + hex data)", + "readOnly": false, "params": [ { "name": "cmd", @@ -3709,6 +3806,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "send_poke", "aliases": [], "summary": "拍一拍(群聊/私聊自动路由)", + "readOnly": false, "params": [ { "name": "user_id", @@ -3754,6 +3852,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "发送私聊合并转发", "returns": "{ message_id, res_id, forward_id }", + "readOnly": false, "params": [ { "name": "user_id", @@ -3808,6 +3907,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "发送私聊消息", "returns": "{ message_id: number }", + "readOnly": false, "params": [ { "name": "user_id", @@ -3864,6 +3964,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_diy_online_status", "aliases": [], "summary": "设置自定义在线状态", + "readOnly": false, "params": [ { "name": "face_id", @@ -3923,6 +4024,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_essence_msg", "aliases": [], "summary": "设置精华消息", + "readOnly": false, "params": [ { "name": "message_id", @@ -3958,6 +4060,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_friend_add_request", "aliases": [], "summary": "处理好友添加请求", + "readOnly": false, "params": [ { "name": "flag", @@ -4002,6 +4105,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_friend_remark", "aliases": [], "summary": "设置好友备注", + "readOnly": false, "params": [ { "name": "user_id", @@ -4045,6 +4149,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_add_option", "aliases": [], "summary": "设置加群选项", + "readOnly": false, "params": [ { "name": "group_id", @@ -4093,6 +4198,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_add_request", "aliases": [], "summary": "处理加群请求", + "readOnly": false, "params": [ { "name": "flag", @@ -4164,6 +4270,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_admin", "aliases": [], "summary": "设置/取消管理员", + "readOnly": false, "params": [ { "name": "group_id", @@ -4225,6 +4332,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "set_group_album_media_like", "aliases": [], + "readOnly": false, "params": [ { "name": "group_id", @@ -4297,6 +4405,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_anonymous", "aliases": [], "summary": "匿名开关(未实现,返回 ok)", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -4310,6 +4419,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_anonymous_ban", "aliases": [], "summary": "匿名禁言(未实现,返回 ok)", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -4323,6 +4433,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_ban", "aliases": [], "summary": "禁言群成员(duration=0 解除)", + "readOnly": false, "params": [ { "name": "group_id", @@ -4387,6 +4498,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_card", "aliases": [], "summary": "设置群名片(空字符串清除)", + "readOnly": false, "params": [ { "name": "group_id", @@ -4449,6 +4561,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_kick", "aliases": [], "summary": "踢出群成员", + "readOnly": false, "params": [ { "name": "group_id", @@ -4511,6 +4624,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_kick_members", "aliases": [], "summary": "批量踢出群成员", + "readOnly": false, "params": [ { "name": "group_id", @@ -4579,6 +4693,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_leave", "aliases": [], "summary": "退群", + "readOnly": false, "params": [ { "name": "group_id", @@ -4612,6 +4727,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_name", "aliases": [], "summary": "设置群名", + "readOnly": false, "params": [ { "name": "group_id", @@ -4658,6 +4774,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_portrait", "aliases": [], "summary": "设置群头像", + "readOnly": false, "params": [ { "name": "group_id", @@ -4705,6 +4822,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_reaction", "aliases": [], "summary": "群聊表情回应", + "readOnly": false, "params": [ { "name": "group_id", @@ -4780,6 +4898,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_remark", "aliases": [], "summary": "设置群备注", + "readOnly": false, "params": [ { "name": "group_id", @@ -4823,6 +4942,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_search", "aliases": [], "summary": "允许群被搜索", + "readOnly": false, "params": [ { "name": "group_id", @@ -4858,6 +4978,7 @@ export const ACTIONS: CatalogAction[] = [ "send_group_sign" ], "summary": "群签到", + "readOnly": false, "params": [ { "name": "group_id", @@ -4891,6 +5012,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_special_title", "aliases": [], "summary": "设置群头衔", + "readOnly": false, "params": [ { "name": "group_id", @@ -4953,6 +5075,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_todo", "aliases": [], "summary": "设置群待办", + "readOnly": false, "params": [ { "name": "group_id", @@ -5004,6 +5127,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_whole_ban", "aliases": [], "summary": "全员禁言开关", + "readOnly": false, "params": [ { "name": "group_id", @@ -5050,6 +5174,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_input_status", "aliases": [], "summary": "设置输入状态", + "readOnly": false, "params": [ { "name": "user_id", @@ -5094,6 +5219,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_msg_emoji_like", "aliases": [], "summary": "设置消息表情回应", + "readOnly": false, "params": [ { "name": "message_id", @@ -5156,6 +5282,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_online_status", "aliases": [], "summary": "设置在线状态", + "readOnly": false, "params": [ { "name": "status", @@ -5221,6 +5348,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_qq_avatar", "aliases": [], "summary": "设置 QQ 头像", + "readOnly": false, "params": [ { "name": "file", @@ -5252,6 +5380,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_qq_profile", "aliases": [], "summary": "设置 QQ 资料", + "readOnly": false, "params": [ { "name": "nickname", @@ -5289,6 +5418,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_restart", "aliases": [], "summary": "重启(不支持)", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -5302,6 +5432,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_self_longnick", "aliases": [], "summary": "设置个性签名(longNick/long_nick,严格 string)", + "readOnly": false, "params": [ { "name": "longNick", @@ -5331,6 +5462,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "trans_group_file", "aliases": [], "summary": "转存群文件(未实现)", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -5345,6 +5477,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "英译中", "returns": "{ words }", + "readOnly": true, "params": [ { "name": "words", @@ -5367,6 +5500,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "upload_forward_msg", "aliases": [], "summary": "上传转发消息", + "readOnly": false, "params": [ { "name": "messages", @@ -5417,6 +5551,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "upload_foward_msg", "aliases": [], "summary": "上传转发消息(别名拼写)", + "readOnly": false, "params": [ { "name": "messages", @@ -5468,6 +5603,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "上传群文件", "returns": "{ file_id: string }", + "readOnly": false, "params": [ { "name": "group_id", @@ -5566,6 +5702,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "upload_image_to_qun_album", "aliases": [], + "readOnly": false, "params": [ { "name": "group_id", @@ -5642,6 +5779,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "上传私聊文件", "returns": "{ file_id: string }", + "readOnly": false, "params": [ { "name": "user_id", diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts index 57c92fb1..93dc5df7 100644 --- a/packages/mcp/src/server.ts +++ b/packages/mcp/src/server.ts @@ -1,10 +1,21 @@ #!/usr/bin/env node -// @snowluma/mcp — a read-only MCP server that exposes the SnowLuma OneBot action -// catalog (docs + per-action JSON Schemas) to LLM clients over stdio. +// @snowluma/mcp — an MCP server for the SnowLuma OneBot action catalog. // -// The catalog is a build-time snapshot (src/generated/catalog.ts), regenerated -// from @snowluma/onebot's live action specs on every build — so it auto-tracks -// action add/remove and ships zero runtime dependency on onebot. +// 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. @@ -18,105 +29,51 @@ import { ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js'; import { ACTIONS, CATEGORIES } from './generated/catalog.js'; -import type { CatalogAction } from './types.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'; -// name + every alias → the action, so get_action accepts aliases too. -const byName = new Map(); -for (const a of ACTIONS) { - for (const n of [a.name, ...a.aliases]) byName.set(n, a); +// ── 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 }; } -/** 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 }; -} - -const TOOLS = [ - { - name: 'list_actions', - description: '列出所有 OneBot action(可按 category 过滤)。返回轻量索引(名称/分类/摘要/别名)。', - inputSchema: { - type: 'object', - properties: { category: { type: 'string', description: '按分类过滤,如 群管理 / 消息 / 好友' } }, - additionalProperties: false, - }, - }, - { - name: 'get_action', - description: '获取某个 OneBot action 的完整文档:摘要、参数表、跨字段约束、返回,以及可直接用于构造调用的参数 JSON Schema(inputSchema)。', - inputSchema: { - type: 'object', - properties: { name: { type: 'string', description: 'action 名(接受别名)' } }, - required: ['name'], - additionalProperties: false, - }, - }, - { - name: 'search_actions', - description: '按关键字模糊搜索 action(匹配名称 / 摘要 / 别名)。返回轻量索引。', - inputSchema: { - type: 'object', - properties: { query: { type: 'string', description: '关键字' } }, - required: ['query'], - additionalProperties: false, - }, - }, - { - name: 'list_categories', - description: '列出所有分类及其 action 数量。', - inputSchema: { type: 'object', properties: {}, additionalProperties: false }, - }, -]; - -function asText(data: unknown) { - return { content: [{ type: 'text' as const, text: JSON.stringify(data, null, 2) }] }; -} -function asError(message: string) { - return { content: [{ type: 'text' as const, text: message }], isError: true }; -} +const { mode, client } = resolveRuntime(); const server = new Server( { name: 'snowluma-mcp', version: VERSION }, { capabilities: { tools: {}, resources: {} } }, ); -server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS })); +server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: computeTools(mode) })); server.setRequestHandler(CallToolRequestSchema, async (req) => { - const name = req.params.name; const args = (req.params.arguments ?? {}) as Record; - 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); - default: - return asError(`未知工具: ${name}`); - } + return callTool(req.params.name, args, { mode, client }); }); server.setRequestHandler(ListResourcesRequestSchema, async () => ({ @@ -145,4 +102,5 @@ server.setRequestHandler(ReadResourceRequestSchema, async (req) => { const transport = new StdioServerTransport(); await server.connect(transport); -console.error(`[snowluma-mcp] v${VERSION} ready — ${ACTIONS.length} actions, ${CATEGORIES.length} categories`); +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}`); diff --git a/packages/mcp/src/tools.ts b/packages/mcp/src/tools.ts new file mode 100644 index 00000000..ca1e21af --- /dev/null +++ b/packages/mcp/src/tools.ts @@ -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(); +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, ctx: CallCtx): Promise { + 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, ctx: CallCtx, kind: 'read' | 'write'): Promise { + 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) + : {}; + try { + const envelope = await ctx.client.call(action, params); + return asText(envelope); + } catch (err) { + return asError(`调用失败: ${err instanceof Error ? err.message : String(err)}`); + } +} diff --git a/packages/mcp/src/types.ts b/packages/mcp/src/types.ts index 92334a01..65c176cb 100644 --- a/packages/mcp/src/types.ts +++ b/packages/mcp/src/types.ts @@ -21,6 +21,10 @@ export interface CatalogAction { 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[]; diff --git a/packages/mcp/tests/client.test.ts b/packages/mcp/tests/client.test.ts new file mode 100644 index 00000000..28994e67 --- /dev/null +++ b/packages/mcp/tests/client.test.ts @@ -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)?.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(); + }); +}); diff --git a/packages/mcp/tests/tools.test.ts b/packages/mcp/tests/tools.test.ts new file mode 100644 index 00000000..800d4c23 --- /dev/null +++ b/packages/mcp/tests/tools.test.ts @@ -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>; +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) => 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 } | 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'); + }); +}); diff --git a/packages/mcp/vitest.config.ts b/packages/mcp/vitest.config.ts index 20b7342c..3a164bb3 100644 --- a/packages/mcp/vitest.config.ts +++ b/packages/mcp/vitest.config.ts @@ -8,7 +8,7 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ plugins: [protobufVitePlugin()], test: { - include: ['scripts/**/*.test.ts'], + include: ['scripts/**/*.test.ts', 'tests/**/*.test.ts'], environment: 'node', env: { SNOWLUMA_LOG_FILE: '0', diff --git a/packages/onebot/src/action-kit.ts b/packages/onebot/src/action-kit.ts index d3944431..04ad724e 100644 --- a/packages/onebot/src/action-kit.ts +++ b/packages/onebot/src/action-kit.ts @@ -331,6 +331,9 @@ export interface ActionDoc { 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). */ @@ -355,6 +358,10 @@ interface ActionDef { 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>) => readonly CrossFieldRule[]; /** `raw` is the original untouched params — an escape hatch for the @@ -418,6 +425,7 @@ export function defineAction(def: ActionDef): ActionSpec { 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, @@ -442,6 +450,7 @@ interface PresetDef { name: string | readonly [string, ...string[]]; summary?: string; returns?: string; + readOnly?: boolean; params?: S; rules?: (r: RuleBuilders & Extra>) => readonly CrossFieldRule[]; run: (p: InferParams & Extra, ctx: ApiActionContext, raw: JsonObject) => Promise | ApiResponse; diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index f2818d4b..d8cb20af 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -174,6 +174,7 @@ export const actions = [ groupAction({ name: 'get_essence_msg_list', summary: '获取精华消息列表', + readOnly: true, run: async (p, ctx) => { try { const essenceDataAll = await ctx.bridge.apis.web.getEssenceAll(p.group_id); @@ -216,6 +217,7 @@ export const actions = [ groupAction({ name: 'get_group_msg_history', summary: '获取群消息历史', + readOnly: true, params: { // 原实现用 `asNumber(message_id) || 0`,present 0 也映射为 0。 message_id: f.int({ min: 0 }).default(0), @@ -230,6 +232,7 @@ export const actions = [ defineAction({ name: 'get_friend_msg_history', summary: '获取好友消息历史', + readOnly: true, params: { user_id: f.uint(), message_id: f.int({ min: 0 }).default(0), @@ -341,6 +344,7 @@ export const actions = [ groupAction({ name: '_get_group_notice', summary: '获取群公告', + readOnly: true, run: async (p, ctx) => { try { const notices = await ctx.bridge.apis.web.getNotice(p.group_id); @@ -397,6 +401,7 @@ export const actions = [ defineAction({ name: 'get_image', summary: '获取图片信息', + readOnly: true, params: { file: f.string().default(''), file_id: f.string().default(''), @@ -413,6 +418,7 @@ export const actions = [ defineAction({ name: 'get_record', summary: '获取语音信息', + readOnly: true, params: { file: f.string().default(''), file_id: f.string().default(''), @@ -430,6 +436,7 @@ export const actions = [ // Primary name matches NapCat for drop-in migration; the rest are aliases. name: ['fetch_ptt_text', 'get_ptt_text', 'get_record_text'], summary: '获取语音转文字结果', + readOnly: true, params: { message_id: f.string().default(''), }, @@ -449,6 +456,7 @@ export const actions = [ defineAction({ name: 'get_cookies', summary: '获取 Cookies', + readOnly: true, params: { domain: f.string().default('qun.qq.com') }, run: async (p, ctx) => { try { @@ -463,6 +471,7 @@ export const actions = [ defineAction({ name: 'get_csrf_token', summary: '获取 CSRF 令牌', + readOnly: true, params: {}, run: async (_p, ctx) => { try { @@ -477,6 +486,7 @@ export const actions = [ defineAction({ name: 'get_credentials', summary: '获取凭证', + readOnly: true, params: { domain: f.string().default('qun.qq.com') }, run: async (p, ctx) => { try { @@ -560,6 +570,7 @@ export const actions = [ groupAction({ name: 'get_group_file_system_info', summary: '获取群文件系统信息', + readOnly: true, run: async (p, ctx) => { const info = await ctx.bridge.apis.groupFile.getCount(p.group_id); return okResponse({ @@ -574,6 +585,7 @@ export const actions = [ defineAction({ name: 'check_url_safely', summary: '检查链接安全性', + readOnly: true, params: {}, run: async () => { return okResponse({ level: 1 }); @@ -644,6 +656,7 @@ export const actions = [ defineAction({ name: 'get_group_ignored_notifies', summary: '获取被过滤的入群请求', + readOnly: true, params: {}, run: async (_p, ctx) => { const reqs = await fetchFilteredGroupRequests(ctx); @@ -669,6 +682,7 @@ export const actions = [ defineAction({ name: 'get_group_ignore_add_request', summary: '获取被忽略的入群请求(NapCat)', + readOnly: true, params: {}, run: async (_p, ctx) => { const reqs = await fetchFilteredGroupRequests(ctx); @@ -691,6 +705,7 @@ export const actions = [ defineAction({ name: 'get_group_shut_list', summary: '获取群禁言列表(占位)', + readOnly: true, params: {}, run: async () => { return okResponse([]); @@ -734,6 +749,7 @@ export const actions = [ defineAction({ name: 'get_profile_like', summary: '获取资料点赞', + readOnly: true, params: { // 原实现 user_id 经 asNumber,无校验(0 也透传)。 user_id: f.int({ min: 0 }).default(0), @@ -753,6 +769,7 @@ export const actions = [ defineAction({ name: 'fetch_custom_face', summary: '获取自定义表情', + readOnly: true, params: { count: f.int({ min: 0 }).default(10) }, run: async (p, ctx) => { try { @@ -767,6 +784,7 @@ export const actions = [ defineAction({ name: 'get_emoji_likes', summary: '获取表情回应用户', + readOnly: true, params: { message_id: f.messageId(), emoji_id: f.string({ allowEmpty: false }), @@ -786,6 +804,7 @@ export const actions = [ defineAction({ name: 'fetch_emoji_like', summary: '获取表情回应用户(NapCat 分页)', + readOnly: true, params: { message_id: f.messageId(), emojiId: f.string({ allowEmpty: false }), @@ -815,6 +834,7 @@ export const actions = [ defineAction({ name: 'get_friends_with_category', summary: '获取分组好友列表', + readOnly: true, params: {}, run: async (_p, ctx) => { if (ctx.getFriendList) { @@ -828,6 +848,7 @@ export const actions = [ defineAction({ name: 'get_online_clients', summary: '获取在线客户端(占位)', + readOnly: true, params: {}, run: async () => { return okResponse({ clients: [] }); @@ -837,6 +858,7 @@ export const actions = [ defineAction({ name: '_get_model_show', summary: '获取机型展示(占位)', + readOnly: true, params: {}, run: async () => { return okResponse({ variants: [] }); @@ -855,6 +877,7 @@ export const actions = [ groupAction({ name: 'get_group_at_all_remain', summary: '获取群 @全体成员 剩余次数', + readOnly: true, run: async (p, ctx) => { try { const data = await ctx.bridge.apis.groupAdmin.getAtAllRemain(p.group_id); @@ -868,6 +891,7 @@ export const actions = [ defineAction({ name: 'get_unidirectional_friend_list', summary: '获取单向好友列表', + readOnly: true, params: {}, run: async (_p, ctx) => { try { @@ -882,6 +906,7 @@ export const actions = [ defineAction({ name: 'get_clientkey', summary: '获取 clientkey', + readOnly: true, params: {}, run: async (_p, ctx) => { const clientKeyInfo = await ctx.bridge.apis.web.forceFetchClientKey(); @@ -895,6 +920,7 @@ export const actions = [ defineAction({ name: 'get_collection_list', summary: '获取收藏列表(占位)', + readOnly: true, params: {}, run: async () => { return okResponse([]); @@ -913,6 +939,7 @@ export const actions = [ defineAction({ name: '.get_word_slices', summary: '分词(未实现)', + readOnly: true, params: {}, run: async () => { return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); @@ -954,6 +981,7 @@ export const actions = [ defineAction({ name: 'get_group_info_ex', summary: '获取群信息(扩展)', + readOnly: true, params: { group_id: f.uint() }, run: async (p, ctx) => { if (ctx.getGroupInfo) { @@ -966,6 +994,7 @@ export const actions = [ defineAction({ name: 'get_group_detail_info', summary: '获取群详细信息', + readOnly: true, params: { group_id: f.uint() }, run: async (p, ctx) => { if (ctx.getGroupInfo) { @@ -996,6 +1025,7 @@ export const actions = [ defineAction({ name: 'get_file', summary: '获取文件(未实现)', + readOnly: true, params: { file_id: f.string().default(''), file: f.string().default(''), @@ -1021,6 +1051,7 @@ export const actions = [ defineAction({ name: 'nc_get_packet_status', summary: '获取 packet 状态(占位)', + readOnly: true, params: {}, run: async () => { return okResponse(null); @@ -1044,6 +1075,7 @@ export const actions = [ defineAction({ name: 'nc_get_user_status', summary: '获取用户在线/扩展状态', + readOnly: true, params: { user_id: f.uint() }, run: async (p, ctx) => { const status = await ctx.bridge.apis.extras.getStrangerStatus(p.user_id); @@ -1056,6 +1088,7 @@ export const actions = [ groupAction({ name: 'get_ai_characters', summary: '获取 AI 语音角色', + readOnly: true, params: { chat_type: f.int({ min: 0 }).default(1) }, run: async (p, ctx) => { try { @@ -1149,6 +1182,7 @@ export const actions = [ defineAction({ name: ['get_rkey', 'nc_get_rkey'], summary: '获取下载 rkey', + readOnly: true, params: {}, run: async (_p, ctx) => ctx.getDownloadRKeys @@ -1159,6 +1193,7 @@ export const actions = [ defineAction({ name: ['ocr_image', '.ocr_image'], summary: 'OCR 图片(未实现)', + readOnly: true, params: {}, run: () => failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'), }), @@ -1238,6 +1273,7 @@ export const actions = [ defineAction({ name: 'get_forward_msg', summary: '获取合并转发消息(id 或 message_id)', + readOnly: true, returns: '{ messages }', params: { id: f.string().optional() }, run: async (p, ctx, raw) => { @@ -1314,6 +1350,7 @@ export const actions = [ defineAction({ name: 'translate_en2zh', summary: '英译中', + readOnly: true, returns: '{ words }', params: { words: f.raw() }, run: async (p, ctx) => { @@ -1348,6 +1385,7 @@ export const actions = [ defineAction({ name: 'get_mini_app_ark', summary: '获取小程序卡片 ark', + readOnly: true, params: {}, run: async (_p, ctx, raw) => { const type = raw.type || 'bili'; diff --git a/packages/onebot/src/actions/friend.ts b/packages/onebot/src/actions/friend.ts index f1ca2b02..93189af2 100644 --- a/packages/onebot/src/actions/friend.ts +++ b/packages/onebot/src/actions/friend.ts @@ -6,6 +6,7 @@ export const actions = [ defineAction({ name: 'get_friend_list', summary: '获取好友列表', + readOnly: true, params: {}, run: async (_p, ctx) => { if (ctx.getFriendList) { @@ -18,6 +19,7 @@ export const actions = [ defineAction({ name: 'get_stranger_info', summary: '获取陌生人信息', + readOnly: true, params: { user_id: f.uint().describe('QQ 号') }, run: async (p, ctx) => { const userId = p.user_id; diff --git a/packages/onebot/src/actions/group-album.ts b/packages/onebot/src/actions/group-album.ts index fa646639..242f7832 100644 --- a/packages/onebot/src/actions/group-album.ts +++ b/packages/onebot/src/actions/group-album.ts @@ -6,6 +6,7 @@ import { RETCODE, failedResponse, okResponse } from '../types'; 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); @@ -37,6 +38,7 @@ export const actions = [ groupAction({ name: 'get_group_album_media_list', + readOnly: true, params: { album_id: f.string({ allowEmpty: false }), attach_info: f.string().default(''), diff --git a/packages/onebot/src/actions/group-file.ts b/packages/onebot/src/actions/group-file.ts index 7792ec4e..16fbd98c 100644 --- a/packages/onebot/src/actions/group-file.ts +++ b/packages/onebot/src/actions/group-file.ts @@ -43,6 +43,7 @@ export const actions = [ 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 @@ -57,6 +58,7 @@ export const actions = [ groupAction({ name: 'get_group_root_files', summary: '获取群根目录文件列表', + readOnly: true, run: async (p, ctx) => { return okResponse(await ctx.getGroupFiles(p.group_id, '/')); }, @@ -65,6 +67,7 @@ export const actions = [ 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) => { @@ -136,6 +139,7 @@ export const actions = [ defineAction({ name: 'get_private_file_url', summary: '获取私聊文件下载链接', + readOnly: true, returns: '{ url: string }', params: { user_id: f.uint(), diff --git a/packages/onebot/src/actions/group-info.ts b/packages/onebot/src/actions/group-info.ts index 15c89d84..7fbb6e26 100644 --- a/packages/onebot/src/actions/group-info.ts +++ b/packages/onebot/src/actions/group-info.ts @@ -8,6 +8,7 @@ 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; @@ -21,6 +22,7 @@ export const actions = [ groupAction({ name: 'get_group_info', summary: '获取群信息', + readOnly: true, params: { no_cache: f.bool().default(false) }, run: async (p, ctx) => { const groupId = p.group_id; @@ -36,6 +38,7 @@ export const actions = [ 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; @@ -50,6 +53,7 @@ export const actions = [ 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; @@ -77,6 +81,7 @@ export const actions = [ groupAction({ name: 'get_group_honor_info', summary: '获取群荣誉信息', + readOnly: true, params: { type: f.raw() }, run: async (p, ctx) => { const groupId = p.group_id; @@ -99,6 +104,7 @@ export const actions = [ defineAction({ name: 'get_group_system_msg', summary: '获取群系统消息', + readOnly: true, params: {}, run: async (_p, ctx) => { if (ctx.handleGetGroupSystemMsg) { diff --git a/packages/onebot/src/actions/info.ts b/packages/onebot/src/actions/info.ts index 1b9657c3..b83cc0f3 100644 --- a/packages/onebot/src/actions/info.ts +++ b/packages/onebot/src/actions/info.ts @@ -8,6 +8,7 @@ const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'd export const actions = [ defineAction({ name: 'get_login_info', + readOnly: true, params: {}, run: (_p, ctx) => { const login = ctx.getLoginInfo(); @@ -17,6 +18,7 @@ export const actions = [ defineAction({ name: 'get_status', + readOnly: true, params: {}, run: (_p, ctx) => { const online = ctx.isOnline(); @@ -26,6 +28,7 @@ export const actions = [ defineAction({ name: 'get_version_info', + readOnly: true, params: {}, run: () => { return okResponse({ @@ -38,6 +41,7 @@ export const actions = [ defineAction({ name: 'can_send_image', + readOnly: true, params: {}, run: (_p, ctx) => { return okResponse({ yes: ctx.canSendImage?.() ?? false }); @@ -46,6 +50,7 @@ export const actions = [ defineAction({ name: 'can_send_record', + readOnly: true, params: {}, run: (_p, ctx) => { return okResponse({ yes: ctx.canSendRecord?.() ?? false }); diff --git a/packages/onebot/src/actions/message.ts b/packages/onebot/src/actions/message.ts index 73fd711f..40e229c6 100644 --- a/packages/onebot/src/actions/message.ts +++ b/packages/onebot/src/actions/message.ts @@ -85,6 +85,7 @@ export const actions = [ defineAction({ name: 'get_msg', summary: '获取消息', + readOnly: true, params: { message_id: f.messageId() }, run: async (p, ctx) => { const data = ctx.getMessage(p.message_id); From 4427ecd569177bfef57adcc1e88c2cd1ef810da9 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 3 Jun 2026 21:55:05 +0800 Subject: [PATCH 11/12] docs(mcp): document execution mode (modes, env, read/write safety) Covers the docs vs execution split, the four SNOWLUMA_MCP_* env vars, the query_action / invoke_action tools, read/write-mode example client configs, and the per-action safety model (default-write classification, the enforced mode gate, unknown-action rejection, envelope passthrough, and the readOnly/destructive annotations). --- packages/mcp/README.md | 105 ++++++++++++++++++++++++++++++++++------- 1 file changed, 89 insertions(+), 16 deletions(-) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index dab67871..91fcda6c 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -1,16 +1,17 @@ # @snowluma/mcp -A read-only [MCP](https://modelcontextprotocol.io) server that exposes the -**SnowLuma OneBot action catalog** — every action's docs, parameters, cross-field -constraints, and a ready-to-use **JSON Schema** — to LLM clients. +An [MCP](https://modelcontextprotocol.io) server for the **SnowLuma OneBot action +catalog**. It runs in two modes from one binary: -Point an LLM at it and it can answer "what params does `set_group_ban` take?" or -"which actions send messages?" on demand, without holding the whole catalog in -context. +- **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. -## Usage +## Docs only (default) -Add to your MCP client (Claude Desktop, Cline, …): +Add to your MCP client (Claude Desktop, Cline, …) — no endpoint, no execution: ```json { @@ -20,21 +21,93 @@ Add to your MCP client (Claude Desktop, Cline, …): } ``` -## Tools +### Docs tools -- `list_actions({ category? })` — lightweight index (name / category / summary / aliases). -- `get_action({ name })` — full doc for one action incl. `inputSchema` (accepts aliases). +- `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 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 the published package carries **zero runtime dependency** on the -private `@snowluma/onebot`. The snapshot is pinned to the SnowLuma version it was -built from; a new SnowLuma release republishes a fresh catalog. +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`. From 4fcaba2f3eb830f631575bf0e8e71ee9e1e45794 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 3 Jun 2026 21:55:37 +0800 Subject: [PATCH 12/12] chore(release): v1.9.5 --- package.json | 2 +- packages/bridge/package.json | 2 +- packages/common/package.json | 2 +- packages/core/package.json | 2 +- packages/mcp/package.json | 2 +- packages/onebot/package.json | 2 +- packages/proto-defs/package.json | 2 +- packages/protocol/package.json | 2 +- packages/proton/package.json | 2 +- packages/runtime/package.json | 2 +- packages/sdk/package.json | 2 +- packages/ui/package.json | 2 +- packages/websocket/package.json | 2 +- packages/webui/package.json | 2 +- 14 files changed, 14 insertions(+), 14 deletions(-) diff --git a/package.json b/package.json index 630acf63..297d86cf 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "snowluma-monorepo", - "version": "1.9.4", + "version": "1.9.5", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", diff --git a/packages/bridge/package.json b/packages/bridge/package.json index 3136c476..56b0c24e 100644 --- a/packages/bridge/package.json +++ b/packages/bridge/package.json @@ -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).", diff --git a/packages/common/package.json b/packages/common/package.json index 1b6d8dbf..9b5e183c 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -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).", diff --git a/packages/core/package.json b/packages/core/package.json index 0a3bdde5..384cb954 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -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", diff --git a/packages/mcp/package.json b/packages/mcp/package.json index e2738fd6..eaa20351 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/mcp", - "version": "1.9.4", + "version": "1.9.5", "description": "MCP server exposing the SnowLuma OneBot action catalog (read-only docs + JSON Schemas) to LLM clients.", "type": "module", "bin": { diff --git a/packages/onebot/package.json b/packages/onebot/package.json index 14b093cb..a78a6630 100644 --- a/packages/onebot/package.json +++ b/packages/onebot/package.json @@ -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..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/'` collapses to `import { … } from '@snowluma/onebot/'`.", diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index ff3b5a33..87b5c8b4 100644 --- a/packages/proto-defs/package.json +++ b/packages/proto-defs/package.json @@ -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` 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).", diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 3530ec7c..a5b29338 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -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/'` collapses to `import { … } from '@snowluma/protocol/'`.", diff --git a/packages/proton/package.json b/packages/proton/package.json index 81faba9b..a45bd15b 100644 --- a/packages/proton/package.json +++ b/packages/proton/package.json @@ -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.", diff --git a/packages/runtime/package.json b/packages/runtime/package.json index aa1e0eda..17678473 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/runtime", - "version": "1.9.4", + "version": "1.9.5", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index aa91410b..42e4d4ae 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.9.4", + "version": "1.9.5", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/ui/package.json b/packages/ui/package.json index 340a0681..3733cfee 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.9.4", + "version": "1.9.5", "description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components", "keywords": [ "snowluma", diff --git a/packages/websocket/package.json b/packages/websocket/package.json index 6ceeef3d..1d5b7e0d 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/websocket", - "version": "1.9.4", + "version": "1.9.5", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/webui/package.json b/packages/webui/package.json index 9dd00cb3..be49cf18 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -1,7 +1,7 @@ { "name": "webui", "private": true, - "version": "1.9.4", + "version": "1.9.5", "type": "module", "scripts": { "dev": "vite",