@asabot/core 0.1.0 → 0.2.0
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 +78 -13
- 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 +5 -1
- 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 +10 -10
- package/dist/core/plugin/context.js +20 -18
- package/dist/core/plugin/definition.d.ts +5 -0
- package/dist/core/plugin/execution.d.ts +3 -0
- package/dist/core/plugin/execution.js +3 -0
- package/dist/core/plugin/manager.d.ts +18 -4
- package/dist/core/plugin/manager.js +137 -45
- package/dist/core/plugin/tasks.d.ts +131 -24
- package/dist/core/plugin/tasks.js +517 -117
- package/dist/core/plugin/types.d.ts +3 -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 +13 -5
- 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 +229 -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 +95 -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 +190 -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-BAbj8e7E.css +2 -0
- package/web/dist/assets/index-CMuBy6y5.js +51 -0
- package/web/dist/assets/{markdown-CDlgpI7K.js → markdown-MEN1AImu.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
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type { AdapterDefinition } from './adapter.ts';
|
|
3
|
+
import type { App } from './app.ts';
|
|
4
|
+
export declare const connectionSchema: z.ZodObject<{
|
|
5
|
+
id: z.ZodString;
|
|
6
|
+
name: z.ZodString;
|
|
7
|
+
adapter: z.ZodString;
|
|
8
|
+
enabled: z.ZodDefault<z.ZodBoolean>;
|
|
9
|
+
config: z.ZodUnknown;
|
|
10
|
+
}, z.core.$strict>;
|
|
11
|
+
export type ConnectionConfig = z.output<typeof connectionSchema>;
|
|
12
|
+
export interface ConnectionState {
|
|
13
|
+
id: string;
|
|
14
|
+
name: string;
|
|
15
|
+
adapter: string;
|
|
16
|
+
platform: string;
|
|
17
|
+
enabled: boolean;
|
|
18
|
+
state: 'disabled' | 'connecting' | 'waiting' | 'online' | 'retrying' | 'error' | 'offline' | 'reauthorize';
|
|
19
|
+
changedAt: number;
|
|
20
|
+
lastConnectedAt?: number;
|
|
21
|
+
lastError?: string;
|
|
22
|
+
errorAt?: number;
|
|
23
|
+
nextRetryAt?: number;
|
|
24
|
+
endpoints: string[];
|
|
25
|
+
bots: {
|
|
26
|
+
platform: string;
|
|
27
|
+
selfId: string;
|
|
28
|
+
}[];
|
|
29
|
+
}
|
|
30
|
+
/** 一条持久连接对应一个独立驱动实例;监听连接可登记多台机器人。 */
|
|
31
|
+
export declare class Connections {
|
|
32
|
+
private readonly app;
|
|
33
|
+
private readonly definitions;
|
|
34
|
+
private readonly entries;
|
|
35
|
+
private readonly subscribers;
|
|
36
|
+
private running;
|
|
37
|
+
constructor(app: App);
|
|
38
|
+
register(definition: AdapterDefinition, source: string): void;
|
|
39
|
+
definition(id: string): AdapterDefinition;
|
|
40
|
+
catalog(): ({
|
|
41
|
+
id: string;
|
|
42
|
+
platform: string;
|
|
43
|
+
name: string;
|
|
44
|
+
version: string;
|
|
45
|
+
description: string;
|
|
46
|
+
connectionTypes: string[];
|
|
47
|
+
capabilities: import("./bot.ts").BotCapabilities;
|
|
48
|
+
setup?: {
|
|
49
|
+
kind: "qr";
|
|
50
|
+
} | undefined;
|
|
51
|
+
source: string;
|
|
52
|
+
configSchema: z.core.ZodStandardJSONSchemaPayload<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>> | {
|
|
53
|
+
type: string;
|
|
54
|
+
};
|
|
55
|
+
} | {
|
|
56
|
+
id: string;
|
|
57
|
+
platform: string;
|
|
58
|
+
name: string;
|
|
59
|
+
version: string;
|
|
60
|
+
description: string;
|
|
61
|
+
connectionTypes: string[];
|
|
62
|
+
capabilities: import("./bot.ts").BotCapabilities;
|
|
63
|
+
setup?: {
|
|
64
|
+
kind: "qr";
|
|
65
|
+
} | undefined;
|
|
66
|
+
source: string;
|
|
67
|
+
configSchema: z.core.ZodStandardJSONSchemaPayload<z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>> | {
|
|
68
|
+
type: string;
|
|
69
|
+
};
|
|
70
|
+
})[];
|
|
71
|
+
validate(configs: ConnectionConfig[]): ConnectionConfig[];
|
|
72
|
+
list(): ConnectionState[];
|
|
73
|
+
private binding;
|
|
74
|
+
subscribe(listener: () => void): () => void;
|
|
75
|
+
private publish;
|
|
76
|
+
private error;
|
|
77
|
+
private update;
|
|
78
|
+
apply(configs: ConnectionConfig[]): Promise<void>;
|
|
79
|
+
reconnect(id: string): Promise<void>;
|
|
80
|
+
start(): Promise<void>;
|
|
81
|
+
stop(): Promise<void>;
|
|
82
|
+
private stopEntry;
|
|
83
|
+
private startEntry;
|
|
84
|
+
}
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { ConfigError } from './errors.js';
|
|
5
|
+
import { botIdentitySchema, botKey } from './identity.js';
|
|
6
|
+
import { redactSchemaText } from './utils/redact.js';
|
|
7
|
+
export const connectionSchema = z
|
|
8
|
+
.object({
|
|
9
|
+
id: z.string().regex(/^[a-zA-Z0-9_-]+$/),
|
|
10
|
+
name: z.string().trim().min(1).max(120),
|
|
11
|
+
adapter: z.string().min(1),
|
|
12
|
+
enabled: z.boolean().default(true),
|
|
13
|
+
config: z.unknown(),
|
|
14
|
+
})
|
|
15
|
+
.strict();
|
|
16
|
+
/** 一条持久连接对应一个独立驱动实例;监听连接可登记多台机器人。 */
|
|
17
|
+
export class Connections {
|
|
18
|
+
app;
|
|
19
|
+
definitions = new Map();
|
|
20
|
+
entries = new Map();
|
|
21
|
+
subscribers = new Set();
|
|
22
|
+
running = false;
|
|
23
|
+
constructor(app) {
|
|
24
|
+
this.app = app;
|
|
25
|
+
}
|
|
26
|
+
register(definition, source) {
|
|
27
|
+
if (this.definitions.has(definition.id))
|
|
28
|
+
throw new ConfigError(`Duplicate adapter "${definition.id}"`);
|
|
29
|
+
this.definitions.set(definition.id, { definition, source });
|
|
30
|
+
}
|
|
31
|
+
definition(id) {
|
|
32
|
+
const item = this.definitions.get(id);
|
|
33
|
+
if (!item)
|
|
34
|
+
throw new ConfigError(`Unknown adapter "${id}"`);
|
|
35
|
+
return item.definition;
|
|
36
|
+
}
|
|
37
|
+
catalog() {
|
|
38
|
+
return [...this.definitions.values()].map(({ definition, source }) => {
|
|
39
|
+
const { create: _create, configSchema, setup, accountId: _accountId, botBinding: _botBinding, ...metadata } = definition;
|
|
40
|
+
return {
|
|
41
|
+
...metadata,
|
|
42
|
+
...(setup && { setup: { kind: setup.kind } }),
|
|
43
|
+
source,
|
|
44
|
+
configSchema: setup
|
|
45
|
+
? { type: 'object' }
|
|
46
|
+
: z.toJSONSchema(configSchema, { io: 'input', unrepresentable: 'any' }),
|
|
47
|
+
};
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
validate(configs) {
|
|
51
|
+
const ids = new Set();
|
|
52
|
+
const accounts = new Set();
|
|
53
|
+
return configs.map((config) => {
|
|
54
|
+
if (ids.has(config.id))
|
|
55
|
+
throw new ConfigError(`Duplicate connection ID "${config.id}"`);
|
|
56
|
+
ids.add(config.id);
|
|
57
|
+
const definition = this.definition(config.adapter);
|
|
58
|
+
const result = definition.configSchema.safeParse(config.config);
|
|
59
|
+
if (!result.success)
|
|
60
|
+
throw new ConfigError(`connections.${config.id}.config: ${this.error(config, result.error)}`);
|
|
61
|
+
if (definition.accountId) {
|
|
62
|
+
const selfId = definition.accountId(result.data);
|
|
63
|
+
if (!botIdentitySchema.shape.selfId.safeParse(selfId).success)
|
|
64
|
+
throw new ConfigError(`connections.${config.id}: invalid Bot ID`);
|
|
65
|
+
const key = botKey({ platform: definition.platform, selfId });
|
|
66
|
+
if (accounts.has(key))
|
|
67
|
+
throw new ConfigError(`Bot ${definition.platform}:${selfId} 已绑定到另一条连接`);
|
|
68
|
+
accounts.add(key);
|
|
69
|
+
}
|
|
70
|
+
return { ...config, config: result.data };
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
list() {
|
|
74
|
+
const accounts = this.app.botAccounts.list();
|
|
75
|
+
return [...this.entries.values()].map((entry) => {
|
|
76
|
+
const bots = accounts.filter((bot) => bot.connectionId === entry.config.id);
|
|
77
|
+
const lastOnlineAt = Math.max(0, ...bots.map((bot) => bot.lastOnlineAt ?? 0));
|
|
78
|
+
return {
|
|
79
|
+
...entry.state,
|
|
80
|
+
lastConnectedAt: entry.state.lastConnectedAt ?? (lastOnlineAt || undefined),
|
|
81
|
+
endpoints: [...entry.state.endpoints],
|
|
82
|
+
bots: bots.map(({ platform, selfId }) => ({ platform, selfId })),
|
|
83
|
+
};
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
binding(config) {
|
|
87
|
+
const definition = this.definition(config.adapter);
|
|
88
|
+
const account = definition.accountId?.(config.config);
|
|
89
|
+
const remote = definition.botBinding?.(config.config);
|
|
90
|
+
const key = createHash('sha256')
|
|
91
|
+
.update(JSON.stringify([definition.id, account, remote?.key]))
|
|
92
|
+
.digest('hex');
|
|
93
|
+
return { id: config.id, key, multiple: account === undefined && (remote?.multiple ?? !remote) };
|
|
94
|
+
}
|
|
95
|
+
subscribe(listener) {
|
|
96
|
+
this.subscribers.add(listener);
|
|
97
|
+
return () => this.subscribers.delete(listener);
|
|
98
|
+
}
|
|
99
|
+
publish() {
|
|
100
|
+
for (const listener of this.subscribers) {
|
|
101
|
+
try {
|
|
102
|
+
listener();
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
this.app.logger.error({ err: error }, 'Connection subscriber failed');
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
error(config, error) {
|
|
110
|
+
return redactSchemaText(error instanceof Error ? error.message : String(error), config.config, z.toJSONSchema(this.definition(config.adapter).configSchema, { io: 'input', unrepresentable: 'any' }));
|
|
111
|
+
}
|
|
112
|
+
update(entry, state) {
|
|
113
|
+
const changed = state.state !== undefined && state.state !== entry.state.state;
|
|
114
|
+
Object.assign(entry.state, state, changed ? { changedAt: Date.now() } : {});
|
|
115
|
+
if (state.state === 'online') {
|
|
116
|
+
if (changed)
|
|
117
|
+
entry.state.lastConnectedAt = Date.now();
|
|
118
|
+
entry.state.nextRetryAt = undefined;
|
|
119
|
+
}
|
|
120
|
+
this.publish();
|
|
121
|
+
}
|
|
122
|
+
async apply(configs) {
|
|
123
|
+
const parsed = this.validate(configs).map((config) => ({ config, binding: this.binding(config) }));
|
|
124
|
+
const bindings = new Map(parsed.map(({ config, binding }) => [config.id, binding]));
|
|
125
|
+
for (const [id, entry] of this.entries) {
|
|
126
|
+
if (!bindings.has(id)) {
|
|
127
|
+
await this.stopEntry(entry);
|
|
128
|
+
this.entries.delete(id);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
this.app.botAccounts.pruneBindings(bindings);
|
|
132
|
+
for (const { config, binding } of parsed) {
|
|
133
|
+
let entry = this.entries.get(config.id);
|
|
134
|
+
if (entry && isDeepStrictEqual(entry.config, config))
|
|
135
|
+
continue;
|
|
136
|
+
const { accountId } = this.definition(config.adapter);
|
|
137
|
+
const replaced = entry &&
|
|
138
|
+
(entry.config.adapter !== config.adapter ||
|
|
139
|
+
(accountId && accountId(entry.config.config) !== accountId(config.config)));
|
|
140
|
+
const bindingChanged = entry && entry.binding.key !== binding.key;
|
|
141
|
+
if (entry?.adapter && !replaced && entry.config.enabled && config.enabled) {
|
|
142
|
+
const changed = !isDeepStrictEqual(entry.config.config, config.config);
|
|
143
|
+
entry.config = config;
|
|
144
|
+
entry.binding = binding;
|
|
145
|
+
entry.state.name = config.name;
|
|
146
|
+
if (bindingChanged)
|
|
147
|
+
Object.assign(entry.state, { lastConnectedAt: undefined, lastError: undefined, errorAt: undefined });
|
|
148
|
+
if (changed) {
|
|
149
|
+
this.update(entry, { state: 'connecting', nextRetryAt: undefined });
|
|
150
|
+
try {
|
|
151
|
+
await entry.adapter.reconfigure(config.config);
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
this.update(entry, { state: 'error', lastError: this.error(config, error), errorAt: Date.now() });
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
if (entry)
|
|
160
|
+
await this.stopEntry(entry);
|
|
161
|
+
if (!entry) {
|
|
162
|
+
entry = {
|
|
163
|
+
config,
|
|
164
|
+
generation: 0,
|
|
165
|
+
bots: new Map(),
|
|
166
|
+
binding,
|
|
167
|
+
state: {
|
|
168
|
+
id: config.id,
|
|
169
|
+
name: config.name,
|
|
170
|
+
adapter: config.adapter,
|
|
171
|
+
platform: this.definition(config.adapter).platform,
|
|
172
|
+
enabled: config.enabled,
|
|
173
|
+
state: 'disabled',
|
|
174
|
+
changedAt: Date.now(),
|
|
175
|
+
endpoints: [],
|
|
176
|
+
bots: [],
|
|
177
|
+
},
|
|
178
|
+
};
|
|
179
|
+
this.entries.set(config.id, entry);
|
|
180
|
+
}
|
|
181
|
+
if (bindingChanged) {
|
|
182
|
+
Object.assign(entry.state, { lastConnectedAt: undefined, lastError: undefined, errorAt: undefined });
|
|
183
|
+
}
|
|
184
|
+
entry.binding = binding;
|
|
185
|
+
entry.config = config;
|
|
186
|
+
Object.assign(entry.state, {
|
|
187
|
+
name: config.name,
|
|
188
|
+
adapter: config.adapter,
|
|
189
|
+
platform: this.definition(config.adapter).platform,
|
|
190
|
+
enabled: config.enabled,
|
|
191
|
+
});
|
|
192
|
+
if (this.running && config.enabled)
|
|
193
|
+
await this.startEntry(entry);
|
|
194
|
+
else
|
|
195
|
+
this.update(entry, { state: config.enabled ? 'offline' : 'disabled' });
|
|
196
|
+
}
|
|
197
|
+
this.publish();
|
|
198
|
+
}
|
|
199
|
+
async reconnect(id) {
|
|
200
|
+
const entry = this.entries.get(id);
|
|
201
|
+
if (!entry)
|
|
202
|
+
throw new ConfigError('Connection not found');
|
|
203
|
+
if (!entry.config.enabled)
|
|
204
|
+
throw new ConfigError('Connection is disabled');
|
|
205
|
+
await this.stopEntry(entry);
|
|
206
|
+
await this.startEntry(entry);
|
|
207
|
+
}
|
|
208
|
+
async start() {
|
|
209
|
+
this.running = true;
|
|
210
|
+
await this.apply(this.app.config.connections);
|
|
211
|
+
}
|
|
212
|
+
async stop() {
|
|
213
|
+
this.running = false;
|
|
214
|
+
for (const entry of this.entries.values())
|
|
215
|
+
await this.stopEntry(entry);
|
|
216
|
+
}
|
|
217
|
+
async stopEntry(entry) {
|
|
218
|
+
entry.generation++;
|
|
219
|
+
await entry.adapter?.stop();
|
|
220
|
+
entry.adapter = undefined;
|
|
221
|
+
for (const bot of entry.bots.values())
|
|
222
|
+
this.app.unregisterBot(bot);
|
|
223
|
+
entry.bots.clear();
|
|
224
|
+
this.update(entry, {
|
|
225
|
+
state: entry.config.enabled ? 'offline' : 'disabled',
|
|
226
|
+
endpoints: [],
|
|
227
|
+
nextRetryAt: undefined,
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
async startEntry(entry) {
|
|
231
|
+
const generation = ++entry.generation;
|
|
232
|
+
this.update(entry, { state: 'connecting', nextRetryAt: undefined });
|
|
233
|
+
const app = this.app;
|
|
234
|
+
const current = () => generation === entry.generation;
|
|
235
|
+
const { config } = entry;
|
|
236
|
+
const definition = this.definition(config.adapter);
|
|
237
|
+
const store = app.storage.store(`@adapter:${JSON.stringify([config.adapter, config.id, definition.accountId?.(config.config)])}`, () => {
|
|
238
|
+
if (!current())
|
|
239
|
+
throw new Error('Connection is stopped');
|
|
240
|
+
});
|
|
241
|
+
const host = {
|
|
242
|
+
connection: {
|
|
243
|
+
id: config.id,
|
|
244
|
+
store,
|
|
245
|
+
update: ({ error, ...state }) => {
|
|
246
|
+
if (!current())
|
|
247
|
+
return;
|
|
248
|
+
this.update(entry, {
|
|
249
|
+
...state,
|
|
250
|
+
...(error ? { lastError: this.error(entry.config, error), errorAt: Date.now() } : {}),
|
|
251
|
+
});
|
|
252
|
+
},
|
|
253
|
+
},
|
|
254
|
+
logger: app.logger.child({ connectionId: entry.config.id }),
|
|
255
|
+
sessionServices: app.sessionServices,
|
|
256
|
+
get ignoreSelf() {
|
|
257
|
+
return app.ignoreSelf;
|
|
258
|
+
},
|
|
259
|
+
emit: (event) => {
|
|
260
|
+
if (!current())
|
|
261
|
+
return;
|
|
262
|
+
if (event.name === 'bot.online')
|
|
263
|
+
this.update(entry, { state: 'online' });
|
|
264
|
+
if (event.name === 'bot.offline')
|
|
265
|
+
this.update(entry, {
|
|
266
|
+
state: [...entry.bots.values()].some((bot) => bot.status === 'online')
|
|
267
|
+
? 'online'
|
|
268
|
+
: entry.state.endpoints.length > 0
|
|
269
|
+
? 'waiting'
|
|
270
|
+
: 'offline',
|
|
271
|
+
});
|
|
272
|
+
app.emit(event);
|
|
273
|
+
},
|
|
274
|
+
registerBot: (bot) => {
|
|
275
|
+
if (!current())
|
|
276
|
+
return;
|
|
277
|
+
const existing = app.bots.get(bot.platform, bot.selfId);
|
|
278
|
+
if (existing && existing !== bot && existing.status === 'online')
|
|
279
|
+
throw new Error(`Bot ${bot.platform}:${bot.selfId} already belongs to another connection`);
|
|
280
|
+
app.registerBot(bot, entry.binding);
|
|
281
|
+
entry.bots.set(botKey(bot), bot);
|
|
282
|
+
app.setBotInfo(bot, { connection: entry.config.adapter, connectionId: entry.config.id });
|
|
283
|
+
this.publish();
|
|
284
|
+
},
|
|
285
|
+
unregisterBot: (bot) => {
|
|
286
|
+
if (current()) {
|
|
287
|
+
app.unregisterBot(bot);
|
|
288
|
+
if (entry.bots.get(botKey(bot)) === bot)
|
|
289
|
+
entry.bots.delete(botKey(bot));
|
|
290
|
+
this.publish();
|
|
291
|
+
}
|
|
292
|
+
},
|
|
293
|
+
setBotInfo: (bot, info) => {
|
|
294
|
+
if (current())
|
|
295
|
+
app.setBotInfo(bot, { ...info, connectionId: entry.config.id });
|
|
296
|
+
},
|
|
297
|
+
registerUpgrade: (path, handler) => {
|
|
298
|
+
const endpoint = `/connections/${encodeURIComponent(entry.config.id)}${path}`;
|
|
299
|
+
const remove = app.registerUpgrade(endpoint, handler);
|
|
300
|
+
entry.state.endpoints.push(endpoint);
|
|
301
|
+
this.publish();
|
|
302
|
+
return () => {
|
|
303
|
+
remove();
|
|
304
|
+
if (current()) {
|
|
305
|
+
entry.state.endpoints = entry.state.endpoints.filter((item) => item !== endpoint);
|
|
306
|
+
this.publish();
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
},
|
|
310
|
+
whenIdle: () => app.whenIdle(),
|
|
311
|
+
isSuperuser: (actor) => app.isSuperuser(actor),
|
|
312
|
+
isBotAdmin: (actor) => app.isBotAdmin(actor),
|
|
313
|
+
prepareOutgoing: (input) => app.prepareOutgoing(input),
|
|
314
|
+
invokeApi: (call, execute) => app.invokeApi(call, execute),
|
|
315
|
+
};
|
|
316
|
+
try {
|
|
317
|
+
entry.adapter = definition.create(config.config, host);
|
|
318
|
+
await entry.adapter.start();
|
|
319
|
+
}
|
|
320
|
+
catch (error) {
|
|
321
|
+
const lastError = this.error(entry.config, error);
|
|
322
|
+
this.update(entry, { state: 'error', lastError, errorAt: Date.now() });
|
|
323
|
+
app.logger.error({ connectionId: entry.config.id, reason: lastError }, 'Connection failed');
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { MessageTarget, SendResult } from './bot.ts';
|
|
2
|
+
import type { BotIdentity } from './identity.ts';
|
|
3
|
+
import type { Target } from './target.ts';
|
|
4
|
+
declare const messages: {
|
|
5
|
+
readonly NO_BOT_ONLINE: '没有匹配的在线机器人';
|
|
6
|
+
readonly RATE_LIMITED: '发送受限,请稍后重试';
|
|
7
|
+
readonly CONVERSATION_UNAVAILABLE: '目标会话不可用';
|
|
8
|
+
readonly DELIVERY_TIMEOUT: '等待发送回执超时,消息可能已送达';
|
|
9
|
+
readonly DELIVERY_UNCONFIRMED: '未能确认消息是否送达';
|
|
10
|
+
readonly DELIVERY_REJECTED: '平台拒绝了消息';
|
|
11
|
+
readonly DELIVERY_UNSUPPORTED: '此机器人不支持该发送方式';
|
|
12
|
+
readonly DELIVERY_BLOCKED: '消息被发送规则拦截';
|
|
13
|
+
readonly DELIVERY_PREPARATION_FAILED: '消息准备失败,请检查内容或附件';
|
|
14
|
+
};
|
|
15
|
+
export type DeliveryCode = keyof typeof messages;
|
|
16
|
+
export type DeliveryOutcome = 'not_sent' | 'unknown' | 'partial';
|
|
17
|
+
export interface DeliveryFailure {
|
|
18
|
+
code: DeliveryCode;
|
|
19
|
+
outcome: DeliveryOutcome;
|
|
20
|
+
target: Target;
|
|
21
|
+
platformCode?: number;
|
|
22
|
+
confirmedMessageIds?: readonly string[];
|
|
23
|
+
}
|
|
24
|
+
interface DeliveryIssue {
|
|
25
|
+
code: DeliveryCode;
|
|
26
|
+
outcome?: DeliveryOutcome;
|
|
27
|
+
/** For adapter-authored guidance only; never pass a raw platform response. */
|
|
28
|
+
message?: string;
|
|
29
|
+
platformCode?: number;
|
|
30
|
+
confirmedMessageIds?: readonly string[];
|
|
31
|
+
}
|
|
32
|
+
/** A failed send with enough information to decide whether repeating it is safe. */
|
|
33
|
+
export declare class DeliveryError extends Error implements DeliveryFailure {
|
|
34
|
+
readonly code: DeliveryCode;
|
|
35
|
+
readonly outcome: DeliveryOutcome;
|
|
36
|
+
readonly target: Target;
|
|
37
|
+
readonly platformCode?: number;
|
|
38
|
+
readonly confirmedMessageIds?: readonly string[];
|
|
39
|
+
constructor(target: Target, issue: DeliveryIssue);
|
|
40
|
+
failure(): DeliveryFailure;
|
|
41
|
+
publicFailure(config: unknown): DeliveryFailure;
|
|
42
|
+
}
|
|
43
|
+
/** Tracks confirmations within one logical send, including sends split by an adapter or hook. */
|
|
44
|
+
export declare class DeliveryAttempt {
|
|
45
|
+
readonly target: Target;
|
|
46
|
+
private readonly confirmed;
|
|
47
|
+
constructor(bot: BotIdentity, target: MessageTarget);
|
|
48
|
+
confirm<T extends SendResult>(sent: T): T;
|
|
49
|
+
run<T>(work: () => Promise<T>, fallback?: DeliveryCode): Promise<T>;
|
|
50
|
+
/** Protocol boundary: an unclassified failure after starting a request has an unknown result. */
|
|
51
|
+
request<T>(work: () => Promise<T>, classify?: (error: unknown) => DeliveryIssue | undefined): Promise<T>;
|
|
52
|
+
}
|
|
53
|
+
export {};
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { ApiTimeoutError, NotConnectedError, PluginError, SendBlockedError, SendQueueFullError, UnsupportedError, } from './errors.js';
|
|
2
|
+
import { redactText } from './utils/redact.js';
|
|
3
|
+
const messages = {
|
|
4
|
+
NO_BOT_ONLINE: '没有匹配的在线机器人',
|
|
5
|
+
RATE_LIMITED: '发送受限,请稍后重试',
|
|
6
|
+
CONVERSATION_UNAVAILABLE: '目标会话不可用',
|
|
7
|
+
DELIVERY_TIMEOUT: '等待发送回执超时,消息可能已送达',
|
|
8
|
+
DELIVERY_UNCONFIRMED: '未能确认消息是否送达',
|
|
9
|
+
DELIVERY_REJECTED: '平台拒绝了消息',
|
|
10
|
+
DELIVERY_UNSUPPORTED: '此机器人不支持该发送方式',
|
|
11
|
+
DELIVERY_BLOCKED: '消息被发送规则拦截',
|
|
12
|
+
DELIVERY_PREPARATION_FAILED: '消息准备失败,请检查内容或附件',
|
|
13
|
+
};
|
|
14
|
+
/** A failed send with enough information to decide whether repeating it is safe. */
|
|
15
|
+
export class DeliveryError extends Error {
|
|
16
|
+
code;
|
|
17
|
+
outcome;
|
|
18
|
+
target;
|
|
19
|
+
platformCode;
|
|
20
|
+
confirmedMessageIds;
|
|
21
|
+
constructor(target, issue) {
|
|
22
|
+
super(issue.outcome === 'partial'
|
|
23
|
+
? '消息已部分送达,请核对后再重试'
|
|
24
|
+
: (issue.message ?? messages[issue.code]));
|
|
25
|
+
this.name = 'DeliveryError';
|
|
26
|
+
this.code = issue.code;
|
|
27
|
+
this.outcome =
|
|
28
|
+
issue.outcome ??
|
|
29
|
+
(issue.code === 'DELIVERY_TIMEOUT' || issue.code === 'DELIVERY_UNCONFIRMED' ? 'unknown' : 'not_sent');
|
|
30
|
+
this.target = {
|
|
31
|
+
platform: target.platform,
|
|
32
|
+
selfId: target.selfId,
|
|
33
|
+
type: target.type,
|
|
34
|
+
id: target.id,
|
|
35
|
+
thread: target.thread,
|
|
36
|
+
};
|
|
37
|
+
this.platformCode = issue.platformCode;
|
|
38
|
+
this.confirmedMessageIds = issue.confirmedMessageIds;
|
|
39
|
+
}
|
|
40
|
+
failure() {
|
|
41
|
+
const { code, outcome, target, platformCode, confirmedMessageIds } = this;
|
|
42
|
+
return { code, outcome, target, platformCode, confirmedMessageIds };
|
|
43
|
+
}
|
|
44
|
+
publicFailure(config) {
|
|
45
|
+
const { platform, selfId, id, type, thread } = this.target;
|
|
46
|
+
const redact = (value) => redactText(value, config);
|
|
47
|
+
return {
|
|
48
|
+
...this.failure(),
|
|
49
|
+
target: {
|
|
50
|
+
platform: redact(platform),
|
|
51
|
+
selfId: selfId === undefined ? undefined : redact(selfId),
|
|
52
|
+
id: redact(id),
|
|
53
|
+
type,
|
|
54
|
+
thread: thread && { id: redact(thread.id), rootMessageId: redact(thread.rootMessageId) },
|
|
55
|
+
},
|
|
56
|
+
confirmedMessageIds: this.confirmedMessageIds?.map(redact),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
function commonIssue(error) {
|
|
61
|
+
if (error instanceof NotConnectedError)
|
|
62
|
+
return { code: 'NO_BOT_ONLINE' };
|
|
63
|
+
if (error instanceof ApiTimeoutError)
|
|
64
|
+
return { code: 'DELIVERY_TIMEOUT' };
|
|
65
|
+
if (error instanceof SendQueueFullError)
|
|
66
|
+
return { code: 'RATE_LIMITED' };
|
|
67
|
+
if (error instanceof SendBlockedError)
|
|
68
|
+
return { code: 'DELIVERY_BLOCKED' };
|
|
69
|
+
if (error instanceof UnsupportedError)
|
|
70
|
+
return { code: 'DELIVERY_UNSUPPORTED' };
|
|
71
|
+
}
|
|
72
|
+
/** Tracks confirmations within one logical send, including sends split by an adapter or hook. */
|
|
73
|
+
export class DeliveryAttempt {
|
|
74
|
+
target;
|
|
75
|
+
confirmed = [];
|
|
76
|
+
constructor(bot, target) {
|
|
77
|
+
this.target = { ...target, platform: bot.platform, selfId: bot.selfId };
|
|
78
|
+
}
|
|
79
|
+
confirm(sent) {
|
|
80
|
+
this.confirmed.push(sent.messageId);
|
|
81
|
+
return sent;
|
|
82
|
+
}
|
|
83
|
+
async run(work, fallback = 'DELIVERY_PREPARATION_FAILED') {
|
|
84
|
+
try {
|
|
85
|
+
return await work();
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
// A plugin policy failure is independent of delivery, unless earlier parts have already been sent.
|
|
89
|
+
if (!this.confirmed.length && error instanceof PluginError)
|
|
90
|
+
throw error;
|
|
91
|
+
const failure = error instanceof DeliveryError
|
|
92
|
+
? error
|
|
93
|
+
: new DeliveryError(this.target, commonIssue(error) ?? { code: fallback });
|
|
94
|
+
if (!this.confirmed.length)
|
|
95
|
+
throw failure;
|
|
96
|
+
throw new DeliveryError(failure.target, {
|
|
97
|
+
...failure.failure(),
|
|
98
|
+
message: failure.message,
|
|
99
|
+
outcome: 'partial',
|
|
100
|
+
confirmedMessageIds: [...new Set([...this.confirmed, ...(failure.confirmedMessageIds ?? [])])],
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/** Protocol boundary: an unclassified failure after starting a request has an unknown result. */
|
|
105
|
+
async request(work, classify) {
|
|
106
|
+
try {
|
|
107
|
+
return await work();
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
if (error instanceof DeliveryError || error instanceof PluginError)
|
|
111
|
+
throw error;
|
|
112
|
+
throw new DeliveryError(this.target, classify?.(error) ?? commonIssue(error) ?? { code: 'DELIVERY_UNCONFIRMED' });
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
@@ -11,7 +11,9 @@ export declare class ApiInterceptors {
|
|
|
11
11
|
private readonly interceptors;
|
|
12
12
|
private readonly inInterceptor;
|
|
13
13
|
private readonly wrapped;
|
|
14
|
-
|
|
14
|
+
check: (call: ApiCall) => void;
|
|
15
|
+
enabled: (owner: string, bot: Bot) => boolean;
|
|
16
|
+
add(handler: ApiInterceptor, priority: number, owner?: string): () => void;
|
|
15
17
|
wrap(bot: Bot): void;
|
|
16
18
|
invoke(call: ApiCall, execute: (args: unknown[]) => Promise<unknown>): Promise<unknown>;
|
|
17
19
|
}
|
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
2
|
import { botActions } from '../bot.js';
|
|
3
3
|
import { UnsupportedError } from '../errors.js';
|
|
4
|
+
import { pluginExecution } from '../plugin/execution.js';
|
|
4
5
|
export class ApiInterceptors {
|
|
5
6
|
interceptors = [];
|
|
6
7
|
inInterceptor = new AsyncLocalStorage();
|
|
7
8
|
wrapped = new WeakSet();
|
|
8
|
-
|
|
9
|
-
|
|
9
|
+
check = () => { };
|
|
10
|
+
enabled = () => true;
|
|
11
|
+
add(handler, priority, owner) {
|
|
12
|
+
const interceptor = { handler, priority, owner };
|
|
10
13
|
this.interceptors.push(interceptor);
|
|
11
14
|
return () => {
|
|
12
15
|
const index = this.interceptors.indexOf(interceptor);
|
|
@@ -18,8 +21,10 @@ export class ApiInterceptors {
|
|
|
18
21
|
if (this.wrapped.has(bot))
|
|
19
22
|
return;
|
|
20
23
|
this.wrapped.add(bot);
|
|
21
|
-
for (const method of botActions) {
|
|
24
|
+
for (const method of [...botActions, 'sendThread']) {
|
|
22
25
|
const original = bot[method];
|
|
26
|
+
if (original === undefined)
|
|
27
|
+
continue;
|
|
23
28
|
Object.defineProperty(bot, method, {
|
|
24
29
|
configurable: true,
|
|
25
30
|
writable: true,
|
|
@@ -32,6 +37,7 @@ export class ApiInterceptors {
|
|
|
32
37
|
}
|
|
33
38
|
}
|
|
34
39
|
async invoke(call, execute) {
|
|
40
|
+
this.check(call);
|
|
35
41
|
if (this.inInterceptor.getStore())
|
|
36
42
|
return execute(call.args);
|
|
37
43
|
const interceptors = [...this.interceptors].sort((a, b) => b.priority - a.priority);
|
|
@@ -39,9 +45,10 @@ export class ApiInterceptors {
|
|
|
39
45
|
const interceptor = interceptors[index];
|
|
40
46
|
if (!interceptor)
|
|
41
47
|
return execute(call.args);
|
|
42
|
-
if (!this.interceptors.includes(interceptor)
|
|
48
|
+
if (!this.interceptors.includes(interceptor) ||
|
|
49
|
+
(interceptor.owner !== undefined && !this.enabled(interceptor.owner, call.bot)))
|
|
43
50
|
return dispatch(index + 1);
|
|
44
|
-
return interceptor.handler(call, () => dispatch(index + 1));
|
|
51
|
+
return pluginExecution.run(interceptor.owner ?? 'core', () => interceptor.handler(call, () => dispatch(index + 1)));
|
|
45
52
|
};
|
|
46
53
|
return this.inInterceptor.run(true, () => dispatch(0));
|
|
47
54
|
}
|