@asabot/core 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/README.md +93 -14
- package/asabot.config.example.yaml +47 -29
- package/dist/adapters/feishu/adapter.d.ts +19 -0
- package/dist/adapters/feishu/adapter.js +621 -0
- package/dist/adapters/feishu/api.d.ts +142 -0
- package/dist/adapters/feishu/api.js +306 -0
- package/dist/adapters/feishu/bot.d.ts +95 -0
- package/dist/adapters/feishu/bot.js +539 -0
- package/dist/adapters/feishu/cards.d.ts +93 -0
- package/dist/adapters/feishu/cards.js +106 -0
- package/dist/adapters/feishu/config.d.ts +13 -0
- package/dist/adapters/feishu/config.js +36 -0
- package/dist/adapters/feishu/events.d.ts +33 -0
- package/dist/adapters/feishu/events.js +14 -0
- package/dist/adapters/feishu/index.d.ts +8 -0
- package/dist/adapters/feishu/index.js +5 -0
- package/dist/adapters/feishu/message.d.ts +64 -0
- package/dist/adapters/feishu/message.js +197 -0
- package/dist/adapters/feishu/transport.d.ts +34 -0
- package/dist/adapters/feishu/transport.js +110 -0
- package/dist/adapters/index.d.ts +1 -7
- package/dist/adapters/index.js +75 -6
- package/dist/adapters/loader.d.ts +6 -0
- package/dist/adapters/loader.js +73 -0
- package/dist/adapters/media-source.d.ts +7 -0
- package/dist/adapters/media-source.js +137 -0
- package/dist/adapters/onebot11/adapter.d.ts +5 -0
- package/dist/adapters/onebot11/adapter.js +23 -11
- package/dist/adapters/onebot11/api.d.ts +4 -1
- package/dist/adapters/onebot11/api.js +21 -8
- package/dist/adapters/onebot11/errors.d.ts +3 -0
- package/dist/adapters/onebot11/errors.js +6 -0
- package/dist/adapters/virtual/index.js +7 -1
- package/dist/adapters/wecom/adapter.d.ts +14 -0
- package/dist/adapters/wecom/adapter.js +220 -0
- package/dist/adapters/wecom/bot.d.ts +71 -0
- package/dist/adapters/wecom/bot.js +312 -0
- package/dist/adapters/wecom/cards.d.ts +37 -0
- package/dist/adapters/wecom/cards.js +30 -0
- package/dist/adapters/wecom/config.d.ts +8 -0
- package/dist/adapters/wecom/config.js +10 -0
- package/dist/adapters/wecom/events.d.ts +93 -0
- package/dist/adapters/wecom/events.js +46 -0
- package/dist/adapters/wecom/index.d.ts +7 -0
- package/dist/adapters/wecom/index.js +21 -0
- package/dist/adapters/wecom/media.d.ts +50 -0
- package/dist/adapters/wecom/media.js +149 -0
- package/dist/adapters/wecom/message.d.ts +151 -0
- package/dist/adapters/wecom/message.js +116 -0
- package/dist/adapters/wecom/transport.d.ts +39 -0
- package/dist/adapters/wecom/transport.js +116 -0
- package/dist/adapters/weixin-clawbot/adapter.d.ts +16 -0
- package/dist/adapters/weixin-clawbot/adapter.js +173 -0
- package/dist/adapters/weixin-clawbot/bot.d.ts +41 -0
- package/dist/adapters/weixin-clawbot/bot.js +254 -0
- package/dist/adapters/weixin-clawbot/index.d.ts +2 -0
- package/dist/adapters/weixin-clawbot/index.js +19 -0
- package/dist/adapters/weixin-clawbot/media.d.ts +57 -0
- package/dist/adapters/weixin-clawbot/media.js +196 -0
- package/dist/adapters/weixin-clawbot/message.d.ts +12 -0
- package/dist/adapters/weixin-clawbot/message.js +79 -0
- package/dist/adapters/weixin-clawbot/protocol.d.ts +145 -0
- package/dist/adapters/weixin-clawbot/protocol.js +178 -0
- package/dist/adapters/weixin-clawbot/setup.d.ts +2 -0
- package/dist/adapters/weixin-clawbot/setup.js +121 -0
- package/dist/bootstrap.d.ts +5 -0
- package/dist/bootstrap.js +5 -20
- package/dist/cli.js +9 -3
- package/dist/core/adapter.d.ts +69 -3
- package/dist/core/adapter.js +11 -1
- package/dist/core/app.d.ts +12 -9
- package/dist/core/app.js +50 -51
- package/dist/core/bot-accounts.d.ts +28 -0
- package/dist/core/bot-accounts.js +78 -0
- package/dist/core/bot-policies.d.ts +30 -0
- package/dist/core/bot-policies.js +112 -0
- package/dist/core/bot.d.ts +19 -1
- package/dist/core/bot.js +13 -0
- package/dist/core/capabilities.d.ts +54 -0
- package/dist/core/capabilities.js +25 -0
- package/dist/core/config/schema.d.ts +61 -8
- package/dist/core/config/schema.js +15 -3
- package/dist/core/config/write.js +5 -1
- package/dist/core/connections.d.ts +84 -0
- package/dist/core/connections.js +326 -0
- package/dist/core/delivery.d.ts +53 -0
- package/dist/core/delivery.js +115 -0
- package/dist/core/dispatch/api.d.ts +3 -1
- package/dist/core/dispatch/api.js +12 -5
- package/dist/core/dispatch/dispatcher.d.ts +1 -0
- package/dist/core/dispatch/dispatcher.js +35 -15
- package/dist/core/dispatch/outgoing.d.ts +1 -0
- package/dist/core/dispatch/outgoing.js +5 -3
- package/dist/core/dispatch/trace.d.ts +2 -0
- package/dist/core/dispatch/types.d.ts +6 -0
- package/dist/core/dispatch/types.js +1 -2
- package/dist/core/errors.d.ts +4 -1
- package/dist/core/errors.js +7 -1
- package/dist/core/event/session.d.ts +3 -1
- package/dist/core/event/session.js +7 -4
- package/dist/core/event/types.d.ts +5 -1
- package/dist/core/identity.d.ts +18 -0
- package/dist/core/identity.js +31 -0
- package/dist/core/logger.js +9 -2
- package/dist/core/message/segment.js +3 -13
- package/dist/core/message/types.d.ts +2 -0
- package/dist/core/permission.d.ts +2 -1
- package/dist/core/permission.js +7 -2
- package/dist/core/plugin/context.d.ts +17 -11
- package/dist/core/plugin/context.js +48 -21
- package/dist/core/plugin/definition.d.ts +7 -0
- package/dist/core/plugin/execution.d.ts +3 -0
- package/dist/core/plugin/execution.js +3 -0
- package/dist/core/plugin/icon.d.ts +2 -0
- package/dist/core/plugin/icon.js +14 -0
- package/dist/core/plugin/manager.d.ts +26 -7
- package/dist/core/plugin/manager.js +179 -56
- package/dist/core/plugin/packages.d.ts +4 -0
- package/dist/core/plugin/packages.js +39 -9
- package/dist/core/plugin/tasks.d.ts +131 -24
- package/dist/core/plugin/tasks.js +517 -117
- package/dist/core/plugin/types.d.ts +14 -0
- package/dist/core/ratelimit.js +6 -1
- package/dist/core/storage/index.d.ts +3 -1
- package/dist/core/storage/index.js +52 -2
- package/dist/core/target.d.ts +24 -6
- package/dist/core/target.js +26 -6
- package/dist/core/utils/merge.d.ts +3 -0
- package/dist/core/utils/merge.js +18 -0
- package/dist/core/utils/redact.d.ts +6 -0
- package/dist/core/utils/redact.js +76 -0
- package/dist/index.d.ts +14 -6
- package/dist/index.js +7 -2
- package/dist/plugins/admin.js +30 -3
- package/dist/plugins/help.js +1 -0
- package/dist/plugins/history.d.ts +4 -0
- package/dist/plugins/history.js +13 -3
- package/dist/plugins/http.js +1 -0
- package/dist/plugins/long-message.js +20 -12
- package/dist/plugins/status.js +1 -0
- package/dist/server/auth.d.ts +5 -1
- package/dist/server/auth.js +11 -7
- package/dist/server/connection-setups.d.ts +126 -0
- package/dist/server/connection-setups.js +188 -0
- package/dist/server/groups.d.ts +1 -0
- package/dist/server/groups.js +8 -8
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +230 -29
- package/dist/server/schemas.d.ts +6 -2
- package/dist/server/settings.d.ts +66 -20
- package/dist/server/settings.js +158 -61
- package/dist/server/views.d.ts +97 -17
- package/dist/server/views.js +48 -13
- package/dist/testing/create-test-app.js +2 -2
- package/dist/testing/dispatch-fixture.js +2 -1
- package/dist/testing/fake-bot.d.ts +2 -1
- package/dist/testing/fake-bot.js +4 -1
- package/docs/DEPLOY.md +211 -0
- package/docs/FEISHU.md +170 -0
- package/docs/WECOM.md +107 -0
- package/docs/WEIXIN-CLAWBOT.md +56 -0
- package/package.json +29 -3
- package/web/dist/assets/index-ogXTSYEt.css +2 -0
- package/web/dist/assets/index-r9XycpMd.js +51 -0
- package/web/dist/assets/{markdown-CDlgpI7K.js → markdown-CIohfKSa.js} +3 -3
- package/web/dist/index.html +2 -2
- package/web/dist/plugin-pages/_sdk.js +26 -1
- package/web/dist/assets/index-BI5GCpiI.css +0 -2
- package/web/dist/assets/index-C-rshHwD.js +0 -51
|
@@ -2,11 +2,14 @@ import { randomUUID } from 'node:crypto';
|
|
|
2
2
|
import { CommandBuilder } from '../command/builder.js';
|
|
3
3
|
import { formatUsage, parseArguments } from '../command/parse.js';
|
|
4
4
|
import { tokenize } from '../command/tokenizer.js';
|
|
5
|
+
import { DeliveryError } from '../delivery.js';
|
|
5
6
|
import { CommandConflictError, SendBlockedError } from '../errors.js';
|
|
6
7
|
import { dialogueMethods, stripLeadingMention } from '../event/index.js';
|
|
7
8
|
import { isSegment } from '../message/index.js';
|
|
8
9
|
import { resolvePermission } from '../permission.js';
|
|
10
|
+
import { pluginExecution } from '../plugin/execution.js';
|
|
9
11
|
import { RateLimiter } from '../ratelimit.js';
|
|
12
|
+
import { redactText } from '../utils/redact.js';
|
|
10
13
|
import { ActivityTracker, trackPrompt } from './activity.js';
|
|
11
14
|
import { messages } from './messages.js';
|
|
12
15
|
import { PromptManager } from './prompt.js';
|
|
@@ -279,7 +282,11 @@ export class Dispatcher {
|
|
|
279
282
|
if (('userId' in event || 'groupId' in event) &&
|
|
280
283
|
!(event.kind === 'message'
|
|
281
284
|
? event.isSuperuser
|
|
282
|
-
: 'userId' in event &&
|
|
285
|
+
: 'userId' in event &&
|
|
286
|
+
event.userId !== undefined &&
|
|
287
|
+
this.config.superusers.some((actor) => actor.platform === event.platform &&
|
|
288
|
+
actor.selfId === event.selfId &&
|
|
289
|
+
actor.userId === event.userId)) &&
|
|
283
290
|
!this.accessFilter(event)) {
|
|
284
291
|
const step = this.traceStep('filter', undefined, 'blocked');
|
|
285
292
|
if (step)
|
|
@@ -573,10 +580,8 @@ export class Dispatcher {
|
|
|
573
580
|
await session.send(messages.suggest(`${prefix ?? this.config.command.prefixes[0] ?? ''}${results[0]}`));
|
|
574
581
|
}
|
|
575
582
|
catch (error) {
|
|
576
|
-
if (step)
|
|
577
|
-
step
|
|
578
|
-
step.error = error instanceof Error ? error.message : String(error);
|
|
579
|
-
}
|
|
583
|
+
if (step)
|
|
584
|
+
this.traceFailure(step, error);
|
|
580
585
|
throw error;
|
|
581
586
|
}
|
|
582
587
|
finally {
|
|
@@ -612,6 +617,12 @@ export class Dispatcher {
|
|
|
612
617
|
};
|
|
613
618
|
return view;
|
|
614
619
|
}
|
|
620
|
+
traceFailure(step, error) {
|
|
621
|
+
step.outcome = 'error';
|
|
622
|
+
step.error = redactText(error instanceof Error ? error.message : String(error), this.config);
|
|
623
|
+
if (error instanceof DeliveryError)
|
|
624
|
+
step.deliveryFailure = error.publicFailure(this.config);
|
|
625
|
+
}
|
|
615
626
|
async invoke(scope, event, handler, message, command, onError, setActivity, parent, stage) {
|
|
616
627
|
if (scope.signal?.aborted || this.shutdown.aborted)
|
|
617
628
|
return;
|
|
@@ -644,8 +655,14 @@ export class Dispatcher {
|
|
|
644
655
|
const current = dispatchContext.getStore();
|
|
645
656
|
const handlerContext = current ? { ...current, plugin: scope.owner, parent: current } : undefined;
|
|
646
657
|
const logError = (error) => {
|
|
647
|
-
|
|
648
|
-
|
|
658
|
+
const delivery = error instanceof DeliveryError ? error : undefined;
|
|
659
|
+
this.logger[error instanceof SendBlockedError || delivery?.code === 'DELIVERY_BLOCKED' ? 'info' : 'error']({
|
|
660
|
+
...(delivery
|
|
661
|
+
? {
|
|
662
|
+
deliveryFailure: delivery.publicFailure(this.config),
|
|
663
|
+
error: redactText(delivery.message, this.config),
|
|
664
|
+
}
|
|
665
|
+
: { err: error }),
|
|
649
666
|
plugin: scope.owner,
|
|
650
667
|
event: event.name,
|
|
651
668
|
eventId: handlerContext?.active.value ? handlerContext.eventId : event.id,
|
|
@@ -656,8 +673,8 @@ export class Dispatcher {
|
|
|
656
673
|
const work = Promise.resolve().then(() => {
|
|
657
674
|
signal.throwIfAborted();
|
|
658
675
|
return handlerContext
|
|
659
|
-
? dispatchContext.run(handlerContext, () => handler(view, signal, step, record))
|
|
660
|
-
: handler(view, signal, step, record);
|
|
676
|
+
? pluginExecution.run(scope.owner, () => dispatchContext.run(handlerContext, () => handler(view, signal, step, record)))
|
|
677
|
+
: pluginExecution.run(scope.owner, () => handler(view, signal, step, record));
|
|
661
678
|
});
|
|
662
679
|
void work.catch((error) => {
|
|
663
680
|
if (finished && !isCancellation(error, signal))
|
|
@@ -675,18 +692,21 @@ export class Dispatcher {
|
|
|
675
692
|
}
|
|
676
693
|
}
|
|
677
694
|
else {
|
|
678
|
-
if (step)
|
|
679
|
-
step
|
|
680
|
-
step.error = error instanceof Error ? error.message : String(error);
|
|
681
|
-
}
|
|
695
|
+
if (step)
|
|
696
|
+
this.traceFailure(step, error);
|
|
682
697
|
logError(error);
|
|
683
|
-
if (onError !== undefined &&
|
|
698
|
+
if (onError !== undefined &&
|
|
699
|
+
!(error instanceof SendBlockedError) &&
|
|
700
|
+
!(error instanceof DeliveryError)) {
|
|
684
701
|
try {
|
|
685
702
|
await dispatchContext.run(handlerContext, () => onError(view));
|
|
686
703
|
}
|
|
687
704
|
catch (replyError) {
|
|
705
|
+
const deliveryFailure = replyError instanceof DeliveryError ? replyError.publicFailure(this.config) : undefined;
|
|
706
|
+
if (step && deliveryFailure)
|
|
707
|
+
step.deliveryFailure = deliveryFailure;
|
|
688
708
|
this.logger[replyError instanceof SendBlockedError ? 'info' : 'error']({
|
|
689
|
-
err: replyError,
|
|
709
|
+
...(deliveryFailure ? { deliveryFailure } : { err: replyError }),
|
|
690
710
|
plugin: scope.owner,
|
|
691
711
|
event: event.name,
|
|
692
712
|
eventId: handlerContext?.eventId ?? event.id,
|
|
@@ -7,6 +7,7 @@ export declare class OutgoingHooks {
|
|
|
7
7
|
private readonly inHook;
|
|
8
8
|
private readonly logger;
|
|
9
9
|
constructor(logger: Logger);
|
|
10
|
+
enabled: (owner: string, input: OutgoingMessage) => boolean;
|
|
10
11
|
add(plugin: string, handler: BeforeSend, priority: number): () => void;
|
|
11
12
|
prepare(input: OutgoingMessage): Promise<Message | Delivery>;
|
|
12
13
|
/** Runs a hook's delivery; its own sends skip the hooks (they already decided) like any send made inside a hook. */
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
2
|
import { SendBlockedError } from '../errors.js';
|
|
3
|
+
import { pluginExecution } from '../plugin/execution.js';
|
|
3
4
|
export class OutgoingHooks {
|
|
4
5
|
hooks = [];
|
|
5
6
|
inHook = new AsyncLocalStorage();
|
|
@@ -7,6 +8,7 @@ export class OutgoingHooks {
|
|
|
7
8
|
constructor(logger) {
|
|
8
9
|
this.logger = logger;
|
|
9
10
|
}
|
|
11
|
+
enabled = () => true;
|
|
10
12
|
add(plugin, handler, priority) {
|
|
11
13
|
const hook = { plugin, handler, priority };
|
|
12
14
|
this.hooks.push(hook);
|
|
@@ -21,7 +23,7 @@ export class OutgoingHooks {
|
|
|
21
23
|
return input.message;
|
|
22
24
|
let message = input.message;
|
|
23
25
|
for (const hook of [...this.hooks].sort((a, b) => b.priority - a.priority)) {
|
|
24
|
-
if (!this.hooks.includes(hook))
|
|
26
|
+
if (!this.hooks.includes(hook) || !this.enabled(hook.plugin, input))
|
|
25
27
|
continue;
|
|
26
28
|
let timer;
|
|
27
29
|
let blocked = false;
|
|
@@ -29,7 +31,7 @@ export class OutgoingHooks {
|
|
|
29
31
|
const timeout = Symbol('timeout');
|
|
30
32
|
try {
|
|
31
33
|
const inputMessage = message.map((segment) => ({ ...segment, data: { ...segment.data } }));
|
|
32
|
-
const work = this.inHook.run(true, () => Promise.resolve().then(() => hook.handler({ ...input, message: inputMessage })));
|
|
34
|
+
const work = this.inHook.run(true, () => pluginExecution.run(hook.plugin, () => Promise.resolve().then(() => hook.handler({ ...input, message: inputMessage }))));
|
|
33
35
|
void work.catch((error) => {
|
|
34
36
|
if (timedOut)
|
|
35
37
|
this.logger.error({ err: error, plugin: hook.plugin }, 'Before-send hook failed');
|
|
@@ -48,7 +50,7 @@ export class OutgoingHooks {
|
|
|
48
50
|
blocked = true;
|
|
49
51
|
else if (result !== undefined) {
|
|
50
52
|
if (!Array.isArray(result))
|
|
51
|
-
return result;
|
|
53
|
+
return { deliver: () => pluginExecution.run(hook.plugin, () => result.deliver()) };
|
|
52
54
|
message = result;
|
|
53
55
|
}
|
|
54
56
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import type { DeliveryFailure } from '../delivery.ts';
|
|
2
3
|
/** 一次事件分发中单个阶段的处理结果及耗时。 */
|
|
3
4
|
export interface TraceStep {
|
|
4
5
|
stage: 'filter' | 'observer' | 'middleware' | 'prompt' | 'command' | 'matcher' | 'suggest';
|
|
@@ -7,6 +8,7 @@ export interface TraceStep {
|
|
|
7
8
|
outcome: 'handled' | 'passed' | 'blocked' | 'denied' | 'cooldown' | 'invalid' | 'error' | 'timeout';
|
|
8
9
|
duration: number;
|
|
9
10
|
error?: string;
|
|
11
|
+
deliveryFailure?: DeliveryFailure;
|
|
10
12
|
}
|
|
11
13
|
/** 事件的完整分发阶段、耗时和发送消息 ID。 */
|
|
12
14
|
export interface DispatchTrace {
|
|
@@ -12,6 +12,12 @@ export interface Scope {
|
|
|
12
12
|
/** 由平台和群 ID 生成群标识;没有群 ID 时返回 undefined。 */
|
|
13
13
|
export declare function groupKeyOf(event: {
|
|
14
14
|
platform: string;
|
|
15
|
+
selfId: string;
|
|
16
|
+
groupId: string;
|
|
17
|
+
}): string;
|
|
18
|
+
export declare function groupKeyOf(event: {
|
|
19
|
+
platform: string;
|
|
20
|
+
selfId: string;
|
|
15
21
|
groupId?: string;
|
|
16
22
|
}): string | undefined;
|
|
17
23
|
/** 调用后注销对应资源的函数。 */
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
/** 由平台和群 ID 生成群标识;没有群 ID 时返回 undefined。 */
|
|
2
1
|
export function groupKeyOf(event) {
|
|
3
|
-
return event.groupId === undefined ? undefined : `${event.platform}:${event.groupId}`;
|
|
2
|
+
return event.groupId === undefined ? undefined : `${event.platform}:${event.selfId}:group:${event.groupId}`;
|
|
4
3
|
}
|
package/dist/core/errors.d.ts
CHANGED
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
export declare class ConfigError extends Error {
|
|
3
3
|
constructor(message: string, options?: ErrorOptions);
|
|
4
4
|
}
|
|
5
|
+
export declare class QrSetupError extends Error {
|
|
6
|
+
constructor(message: string);
|
|
7
|
+
}
|
|
5
8
|
/** 平台不支持请求的操作。 */
|
|
6
9
|
export declare class UnsupportedError extends Error {
|
|
7
10
|
readonly platform: string;
|
|
@@ -27,7 +30,7 @@ export declare class NotConnectedError extends Error {
|
|
|
27
30
|
export declare class SendQueueFullError extends Error {
|
|
28
31
|
constructor();
|
|
29
32
|
}
|
|
30
|
-
/**
|
|
33
|
+
/** 没有符合查询条件的在线机器人。 */
|
|
31
34
|
export declare class NoBotOnlineError extends Error {
|
|
32
35
|
constructor();
|
|
33
36
|
}
|
package/dist/core/errors.js
CHANGED
|
@@ -5,6 +5,12 @@ export class ConfigError extends Error {
|
|
|
5
5
|
this.name = 'ConfigError';
|
|
6
6
|
}
|
|
7
7
|
}
|
|
8
|
+
export class QrSetupError extends Error {
|
|
9
|
+
constructor(message) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = 'QrSetupError';
|
|
12
|
+
}
|
|
13
|
+
}
|
|
8
14
|
/** 平台不支持请求的操作。 */
|
|
9
15
|
export class UnsupportedError extends Error {
|
|
10
16
|
platform;
|
|
@@ -50,7 +56,7 @@ export class SendQueueFullError extends Error {
|
|
|
50
56
|
this.name = 'SendQueueFullError';
|
|
51
57
|
}
|
|
52
58
|
}
|
|
53
|
-
/**
|
|
59
|
+
/** 没有符合查询条件的在线机器人。 */
|
|
54
60
|
export class NoBotOnlineError extends Error {
|
|
55
61
|
constructor() {
|
|
56
62
|
super('No bot is online');
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type Bot, type MessageThread } from '../bot.ts';
|
|
2
2
|
import type { Message, Sendable } from '../message/index.ts';
|
|
3
3
|
import type { LruSet } from '../utils/lru.ts';
|
|
4
4
|
import type { PromptOptions, Session, SessionServices } from './types.ts';
|
|
@@ -16,9 +16,11 @@ interface SessionFields {
|
|
|
16
16
|
bot: Bot;
|
|
17
17
|
messageId: string;
|
|
18
18
|
userId: string;
|
|
19
|
+
thread?: MessageThread;
|
|
19
20
|
message: Message;
|
|
20
21
|
sender: Session['sender'];
|
|
21
22
|
isSuperuser: boolean;
|
|
23
|
+
isBotAdmin: boolean;
|
|
22
24
|
sentMessageIds?: LruSet<string>;
|
|
23
25
|
}
|
|
24
26
|
export type SessionInit = SessionFields & ({
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { sendTo } from '../bot.js';
|
|
2
|
+
import { DeliveryAttempt } from '../delivery.js';
|
|
1
3
|
import { isSegment, normalizeSendable, plainText, seg } from '../message/index.js';
|
|
2
4
|
import { formatTarget } from '../target.js';
|
|
3
5
|
export function dialogueMethods(run) {
|
|
@@ -102,6 +104,7 @@ export function createSession(init, services) {
|
|
|
102
104
|
selfId: init.selfId,
|
|
103
105
|
type: init.messageType,
|
|
104
106
|
id: init.groupId ?? init.userId,
|
|
107
|
+
...(init.thread === undefined ? {} : { thread: init.thread }),
|
|
105
108
|
};
|
|
106
109
|
const session = {
|
|
107
110
|
id: init.id,
|
|
@@ -116,6 +119,7 @@ export function createSession(init, services) {
|
|
|
116
119
|
messageId: init.messageId,
|
|
117
120
|
userId: init.userId,
|
|
118
121
|
...(init.groupId === undefined ? {} : { groupId: init.groupId }),
|
|
122
|
+
...(init.thread === undefined ? {} : { thread: init.thread }),
|
|
119
123
|
channelKey: formatTarget(target),
|
|
120
124
|
target,
|
|
121
125
|
message: init.message,
|
|
@@ -123,10 +127,9 @@ export function createSession(init, services) {
|
|
|
123
127
|
sender: init.sender,
|
|
124
128
|
toMe,
|
|
125
129
|
isSuperuser: init.isSuperuser,
|
|
130
|
+
isBotAdmin: init.isBotAdmin,
|
|
126
131
|
async send(content) {
|
|
127
|
-
return init.
|
|
128
|
-
? init.bot.sendGroup(init.groupId, content)
|
|
129
|
-
: init.bot.sendPrivate(init.userId, content);
|
|
132
|
+
return sendTo(init.bot, target, content);
|
|
130
133
|
},
|
|
131
134
|
async reply(content, options = {}) {
|
|
132
135
|
const quote = options.quote ?? true;
|
|
@@ -141,7 +144,7 @@ export function createSession(init, services) {
|
|
|
141
144
|
return session.send([...prefix, ...normalizeSendable(content)]);
|
|
142
145
|
},
|
|
143
146
|
async sendForward(nodes) {
|
|
144
|
-
return init.bot
|
|
147
|
+
return new DeliveryAttempt(init.bot, target).request(() => init.bot.sendForward(target, nodes));
|
|
145
148
|
},
|
|
146
149
|
...dialogueMethods((work) => work((text, options) => services.prompt(session, text, options))),
|
|
147
150
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Bot, ForwardNode, SendResult } from '../bot.ts';
|
|
1
|
+
import type { Bot, ForwardNode, MessageThread, SendResult } from '../bot.ts';
|
|
2
2
|
import type { DispatchTrace } from '../dispatch/trace.ts';
|
|
3
3
|
import type { Message, Sendable } from '../message/index.ts';
|
|
4
4
|
import type { Target } from '../target.ts';
|
|
@@ -47,6 +47,8 @@ export interface Session extends BaseEvent {
|
|
|
47
47
|
readonly userId: string;
|
|
48
48
|
/** 群消息的群 ID;私聊中不存在。 */
|
|
49
49
|
readonly groupId?: string;
|
|
50
|
+
/** 消息所属话题;群 ID 仍然指向所在群。 */
|
|
51
|
+
readonly thread?: MessageThread;
|
|
50
52
|
/** 包含平台、机器人账号、会话类型和 ID 的目标字符串。 */
|
|
51
53
|
readonly channelKey: string;
|
|
52
54
|
/** 可用于主动发送的当前会话目标。 */
|
|
@@ -66,6 +68,7 @@ export interface Session extends BaseEvent {
|
|
|
66
68
|
readonly toMe: boolean;
|
|
67
69
|
/** 发送者是否为配置的超管。 */
|
|
68
70
|
readonly isSuperuser: boolean;
|
|
71
|
+
readonly isBotAdmin: boolean;
|
|
69
72
|
/** 向当前会话发送内容;发送失败时 Promise 拒绝。 */
|
|
70
73
|
send(content: Sendable): Promise<SendResult>;
|
|
71
74
|
/** 回复当前消息;默认引用原消息,at 为 true 时在群内提及发送者。 */
|
|
@@ -218,6 +221,7 @@ export interface MessageSentEvent extends BaseEvent {
|
|
|
218
221
|
readonly messageType: 'private' | 'group';
|
|
219
222
|
readonly userId?: string;
|
|
220
223
|
readonly groupId?: string;
|
|
224
|
+
readonly thread?: MessageThread;
|
|
221
225
|
readonly message: Message;
|
|
222
226
|
}
|
|
223
227
|
/** 一次事件处理结束后的分发追踪事件。 */
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const botIdentitySchema: z.ZodObject<{
|
|
3
|
+
platform: z.ZodString;
|
|
4
|
+
selfId: z.ZodString;
|
|
5
|
+
}, z.core.$strict>;
|
|
6
|
+
export declare const actorIdentitySchema: z.ZodObject<{
|
|
7
|
+
platform: z.ZodString;
|
|
8
|
+
selfId: z.ZodString;
|
|
9
|
+
userId: z.ZodString;
|
|
10
|
+
}, z.core.$strict>;
|
|
11
|
+
export type BotIdentity = z.infer<typeof botIdentitySchema>;
|
|
12
|
+
export type ActorIdentity = z.infer<typeof actorIdentitySchema>;
|
|
13
|
+
export declare const botKey: (bot: BotIdentity) => string;
|
|
14
|
+
export declare const sameBot: (a: BotIdentity, b: BotIdentity) => boolean;
|
|
15
|
+
/** 群规则始终隶属于一台机器人。 */
|
|
16
|
+
export declare function groupIdentity(key: string): BotIdentity & {
|
|
17
|
+
groupId: string;
|
|
18
|
+
};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export const botIdentitySchema = z
|
|
3
|
+
.object({
|
|
4
|
+
platform: z
|
|
5
|
+
.string()
|
|
6
|
+
.min(1)
|
|
7
|
+
.regex(/^[^:\s]+$/)
|
|
8
|
+
.meta({ title: '平台' }),
|
|
9
|
+
selfId: z
|
|
10
|
+
.string()
|
|
11
|
+
.min(1)
|
|
12
|
+
.regex(/^[^:\s]+$/)
|
|
13
|
+
.meta({ title: '机器人 ID' }),
|
|
14
|
+
})
|
|
15
|
+
.strict();
|
|
16
|
+
export const actorIdentitySchema = botIdentitySchema
|
|
17
|
+
.extend({
|
|
18
|
+
userId: z.string().min(1).meta({ title: '用户 ID' }),
|
|
19
|
+
})
|
|
20
|
+
.strict();
|
|
21
|
+
export const botKey = (bot) => JSON.stringify([bot.platform, bot.selfId]);
|
|
22
|
+
export const sameBot = (a, b) => a.platform === b.platform && a.selfId === b.selfId;
|
|
23
|
+
/** 群规则始终隶属于一台机器人。 */
|
|
24
|
+
export function groupIdentity(key) {
|
|
25
|
+
const match = /^([^:\s]+):([^:\s]+):group:(\S+)$/.exec(key);
|
|
26
|
+
if (!match)
|
|
27
|
+
throw new Error('Invalid bot-scoped group key');
|
|
28
|
+
return botIdentitySchema
|
|
29
|
+
.extend({ groupId: z.string().min(1) })
|
|
30
|
+
.parse({ platform: match[1], selfId: match[2], groupId: match[3] });
|
|
31
|
+
}
|
package/dist/core/logger.js
CHANGED
|
@@ -10,10 +10,12 @@ const redactedFields = [
|
|
|
10
10
|
'token',
|
|
11
11
|
'password',
|
|
12
12
|
'apiToken',
|
|
13
|
+
'appSecret',
|
|
13
14
|
'*.accessToken',
|
|
14
15
|
'*.token',
|
|
15
16
|
'*.password',
|
|
16
17
|
'*.apiToken',
|
|
18
|
+
'*.appSecret',
|
|
17
19
|
];
|
|
18
20
|
// A subscriber failure cannot be sent through the same ring buffer without recursing.
|
|
19
21
|
const subscriberErrorLogger = pino({ redact: { paths: redactedFields, censor: '[Redacted]' } }, process.stderr);
|
|
@@ -92,7 +94,10 @@ class RotatingFile {
|
|
|
92
94
|
const { path, maxSize, maxFiles } = this.options;
|
|
93
95
|
if (!this.initialized) {
|
|
94
96
|
mkdirSync(dirname(path), { recursive: true });
|
|
95
|
-
|
|
97
|
+
const existing = statSync(path, { throwIfNoEntry: false });
|
|
98
|
+
if (existing && !existing.isFile())
|
|
99
|
+
throw new Error('Log path must point to a regular file');
|
|
100
|
+
this.size = existing?.size ?? 0;
|
|
96
101
|
this.initialized = true;
|
|
97
102
|
}
|
|
98
103
|
const length = Buffer.byteLength(chunk);
|
|
@@ -146,7 +151,9 @@ export function createLogger(options = {}) {
|
|
|
146
151
|
redact: { paths: redactedFields, censor: '[Redacted]' },
|
|
147
152
|
mixin: () => {
|
|
148
153
|
const context = dispatchContext.getStore();
|
|
149
|
-
return context?.active.value
|
|
154
|
+
return context?.active.value
|
|
155
|
+
? { eventId: context.eventId, platform: context.trace.platform, selfId: context.trace.selfId }
|
|
156
|
+
: {};
|
|
150
157
|
},
|
|
151
158
|
}, pino.multistream(streams));
|
|
152
159
|
return result;
|
|
@@ -13,20 +13,10 @@ function mediaSource(source) {
|
|
|
13
13
|
if (/^(?:https?|base64|file):\/\//i.test(source)) {
|
|
14
14
|
return source;
|
|
15
15
|
}
|
|
16
|
-
if (isAbsolute(source)
|
|
17
|
-
if (process.platform !== 'win32' && win32.isAbsolute(source)) {
|
|
18
|
-
const normalized = source.replaceAll('\\', '/');
|
|
19
|
-
if (normalized.startsWith('//')) {
|
|
20
|
-
const [host, ...parts] = normalized.slice(2).split('/');
|
|
21
|
-
return `file://${host}/${parts.map(encodeURIComponent).join('/')}`;
|
|
22
|
-
}
|
|
23
|
-
return `file:///${normalized
|
|
24
|
-
.split('/')
|
|
25
|
-
.map((part, index) => (index === 0 ? part : encodeURIComponent(part)))
|
|
26
|
-
.join('/')}`;
|
|
27
|
-
}
|
|
16
|
+
if (isAbsolute(source) && !source.startsWith('//'))
|
|
28
17
|
return pathToFileURL(source).href;
|
|
29
|
-
|
|
18
|
+
if (win32.isAbsolute(source))
|
|
19
|
+
return pathToFileURL(source, { windows: true }).href;
|
|
30
20
|
if (/^\.\.?\//.test(source)) {
|
|
31
21
|
throw new TypeError('请使用 new URL(..., import.meta.url) 或绝对路径指定本地文件');
|
|
32
22
|
}
|
|
@@ -2,10 +2,11 @@ import type { Session } from './event/index.ts';
|
|
|
2
2
|
/** 根据 Session 判断权限的同步或异步函数。 */
|
|
3
3
|
export type Rule = (session: Session) => boolean | Promise<boolean>;
|
|
4
4
|
/** 内置权限名称或自定义权限判断函数。 */
|
|
5
|
-
export type Permission = Rule | 'superuser' | 'group.owner' | 'group.admin';
|
|
5
|
+
export type Permission = Rule | 'superuser' | 'bot.admin' | 'group.owner' | 'group.admin';
|
|
6
6
|
/** 内置权限规则及 and、or、not 组合器。 */
|
|
7
7
|
export declare const perm: {
|
|
8
8
|
superuser: Rule;
|
|
9
|
+
botAdmin: Rule;
|
|
9
10
|
groupOwner: Rule;
|
|
10
11
|
groupAdmin: Rule;
|
|
11
12
|
group: Rule;
|
package/dist/core/permission.js
CHANGED
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
const superuser = (session) => session.isSuperuser;
|
|
2
|
-
const
|
|
2
|
+
const botAdmin = (session) => session.isSuperuser || session.isBotAdmin;
|
|
3
|
+
const groupOwner = (session) => session.isSuperuser ||
|
|
4
|
+
session.isBotAdmin ||
|
|
5
|
+
(session.messageType === 'group' && session.sender.role === 'owner');
|
|
3
6
|
const groupAdmin = (session) => session.isSuperuser ||
|
|
7
|
+
session.isBotAdmin ||
|
|
4
8
|
(session.messageType === 'group' && (session.sender.role === 'owner' || session.sender.role === 'admin'));
|
|
5
9
|
const group = (session) => session.messageType === 'group';
|
|
6
10
|
const privateRule = (session) => session.messageType === 'private';
|
|
7
11
|
/** 内置权限规则及 and、or、not 组合器。 */
|
|
8
12
|
export const perm = {
|
|
9
13
|
superuser,
|
|
14
|
+
botAdmin,
|
|
10
15
|
groupOwner,
|
|
11
16
|
groupAdmin,
|
|
12
17
|
group,
|
|
@@ -28,5 +33,5 @@ export const perm = {
|
|
|
28
33
|
export function resolvePermission(permission) {
|
|
29
34
|
if (typeof permission === 'function')
|
|
30
35
|
return permission;
|
|
31
|
-
return { superuser, 'group.owner': groupOwner, 'group.admin': groupAdmin }[permission];
|
|
36
|
+
return { superuser, 'bot.admin': botAdmin, 'group.owner': groupOwner, 'group.admin': groupAdmin }[permission];
|
|
32
37
|
}
|
|
@@ -7,15 +7,16 @@ import type { App } from '../app.ts';
|
|
|
7
7
|
import type { Bot, SendResult } from '../bot.ts';
|
|
8
8
|
import type { CommandBuilder } from '../command/builder.ts';
|
|
9
9
|
import type { ApiInterceptor } from '../dispatch/api.ts';
|
|
10
|
-
import {
|
|
10
|
+
import type { DispatchEvent, Disposer, MatchHandler, MatchPattern, Middleware } from '../dispatch/types.ts';
|
|
11
11
|
import type { AnyEvent, EventMap, KnownEventMap, MetaEvent, PlatformNoticeEvent, RequestEvent } from '../event/index.ts';
|
|
12
|
+
import type { BotIdentity } from '../identity.ts';
|
|
12
13
|
import type { Sendable } from '../message/index.ts';
|
|
13
14
|
import type { KVStore } from '../storage/index.ts';
|
|
14
15
|
import { type Target } from '../target.ts';
|
|
15
16
|
import { type Duration } from '../utils/duration.ts';
|
|
16
17
|
import { type PluginDefinition } from './definition.ts';
|
|
17
|
-
import { type TaskHandle, type TaskHandler } from './tasks.ts';
|
|
18
|
-
import type { PanelPageOptions, PluginStateEvent } from './types.ts';
|
|
18
|
+
import { type TaskHandle, type TaskHandler, type TaskRegistrationOptions } from './tasks.ts';
|
|
19
|
+
import type { PanelPageOptions, PluginStateEvent, ServiceConsumer } from './types.ts';
|
|
19
20
|
type Listener = (event: AnyEvent | PluginStateEvent, signal: AbortSignal) => unknown | Promise<unknown>;
|
|
20
21
|
type Cleanup = () => void | Promise<void>;
|
|
21
22
|
/** 按事件过滤的上下文,可继续注册处理器或叠加过滤条件。 */
|
|
@@ -33,6 +34,7 @@ export declare class Context<Config = undefined> {
|
|
|
33
34
|
private readonly tasks;
|
|
34
35
|
private readonly cleanups;
|
|
35
36
|
private readonly dependencies;
|
|
37
|
+
private readonly consumer;
|
|
36
38
|
private routeApp?;
|
|
37
39
|
private panelRouteApp?;
|
|
38
40
|
private disposed;
|
|
@@ -51,11 +53,10 @@ export declare class Context<Config = undefined> {
|
|
|
51
53
|
get name(): string;
|
|
52
54
|
/** 经过插件 schema 校验的全局配置。 */
|
|
53
55
|
get config(): Readonly<Config>;
|
|
54
|
-
/**
|
|
55
|
-
configFor(target: string | {
|
|
56
|
-
platform: string;
|
|
56
|
+
/** 获取目标机器人或群组合并覆盖项后的有效配置。 */
|
|
57
|
+
configFor(target: string | (BotIdentity & {
|
|
57
58
|
groupId?: string;
|
|
58
|
-
}): Readonly<Config>;
|
|
59
|
+
})): Readonly<Config>;
|
|
59
60
|
/** 自动附带插件名的日志记录器。 */
|
|
60
61
|
get logger(): Logger;
|
|
61
62
|
/** 插件卸载时中止的信号,可传给异步任务。 */
|
|
@@ -69,7 +70,7 @@ export declare class Context<Config = undefined> {
|
|
|
69
70
|
/** 创建并返回当前插件的数据目录;文件系统操作失败时抛错。 */
|
|
70
71
|
get dataDir(): string;
|
|
71
72
|
/** 按账号 ID 查找在线机器人,省略时取第一个;找不到时抛出 NoBotOnlineError。 */
|
|
72
|
-
bot(
|
|
73
|
+
bot(identity?: BotIdentity): Bot;
|
|
73
74
|
/** 向指定目标发送内容;目标无效、无在线机器人或发送失败时拒绝。 */
|
|
74
75
|
send(target: Target | string, content: Sendable): Promise<SendResult>;
|
|
75
76
|
/** 顺序向多个目标发送,interval 是发送间隔;单个发送失败写入对应结果的 error。 */
|
|
@@ -84,6 +85,11 @@ export declare class Context<Config = undefined> {
|
|
|
84
85
|
migrate(steps: string[]): void;
|
|
85
86
|
/** 按名称提供插件服务并返回撤销函数;同名服务已存在时抛错。 */
|
|
86
87
|
provide<K extends string>(name: K, service: K extends keyof Services ? Services[K] : unknown): Disposer;
|
|
88
|
+
/** 提供按使用方上下文创建的服务,服务可获取插件身份和卸载信号。 */
|
|
89
|
+
provideScoped<K extends string>(name: K, factory: (consumer: ServiceConsumer) => K extends keyof Services ? Services[K] : unknown): Disposer;
|
|
90
|
+
/** 列出声明依赖指定服务的已发现插件,包括未启用的插件。 */
|
|
91
|
+
serviceConsumers(name: string): string[];
|
|
92
|
+
private disposeService;
|
|
87
93
|
/** 获取已声明的必需服务;未声明或服务不可用时抛出 PluginError。 */
|
|
88
94
|
inject<K extends string>(name: K): K extends keyof Services ? Services[K] : unknown;
|
|
89
95
|
/** 获取已声明的可选服务;服务缺失返回 undefined,未声明时抛出 PluginError。 */
|
|
@@ -135,9 +141,9 @@ export declare class Context<Config = undefined> {
|
|
|
135
141
|
/** 注册一次性延迟任务并返回停止函数;duration 是毫秒数或时长字符串。 */
|
|
136
142
|
timeout(duration: string | number, fn: (signal: AbortSignal) => unknown | Promise<unknown>): Disposer;
|
|
137
143
|
/** 注册可持久化任务并恢复待执行项;同名任务重复注册时抛错。 */
|
|
138
|
-
task<T>(name: string, handler: TaskHandler<T
|
|
139
|
-
/**
|
|
140
|
-
|
|
144
|
+
task<T>(name: string, handler: TaskHandler<T>, options?: TaskRegistrationOptions): TaskHandle<T>;
|
|
145
|
+
/** 在插件 setup 成功后激活持久化任务。 */
|
|
146
|
+
activateTasks(): void;
|
|
141
147
|
/** 注册插件卸载时的清理函数,并返回取消注册函数。 */
|
|
142
148
|
onDispose(fn: Cleanup): Disposer;
|
|
143
149
|
/** 中止插件资源并逆序执行清理函数;重复调用无影响。 */
|