@asabot/core 0.2.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/README.md +15 -1
- package/dist/core/logger.js +4 -1
- package/dist/core/message/segment.js +3 -13
- package/dist/core/plugin/context.d.ts +7 -1
- package/dist/core/plugin/context.js +28 -3
- package/dist/core/plugin/definition.d.ts +2 -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 +8 -3
- package/dist/core/plugin/manager.js +42 -11
- package/dist/core/plugin/packages.d.ts +4 -0
- package/dist/core/plugin/packages.js +39 -9
- package/dist/core/plugin/types.d.ts +11 -0
- package/dist/index.d.ts +1 -1
- package/dist/server/index.js +1 -0
- package/dist/server/views.d.ts +2 -0
- package/docs/DEPLOY.md +22 -1
- package/package.json +1 -1
- package/web/dist/assets/index-ogXTSYEt.css +2 -0
- package/web/dist/assets/index-r9XycpMd.js +51 -0
- package/web/dist/assets/{markdown-MEN1AImu.js → markdown-CIohfKSa.js} +1 -1
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-BAbj8e7E.css +0 -2
- package/web/dist/assets/index-CMuBy6y5.js +0 -51
package/README.md
CHANGED
|
@@ -77,6 +77,8 @@ npm run dev
|
|
|
77
77
|
|
|
78
78
|
## 官方插件
|
|
79
79
|
|
|
80
|
+
`@asabot/plugin-ai` 为业务插件提供统一的对话、生图、语音合成和结构化决策服务。启用后,从「插件页面 → AI 管理」配置 API 渠道、模型、默认分配和白名单,查看来源、请求及用量。用法及本地构建见 [AI 插件文档](packages/plugin-ai/README.md)。
|
|
81
|
+
|
|
80
82
|
`@asabot/plugin-render` 将文本、Markdown 和 satori HTML 渲染为 PNG,也可通过配置 Chrome 或 Edge 使用网页截图。可在插件市场安装,或由超管发送 `/plugin install @asabot/plugin-render`。在插件中声明 `inject: ['render']` 后即可使用:
|
|
81
83
|
|
|
82
84
|
```ts
|
|
@@ -148,6 +150,16 @@ curl -X POST http://127.0.0.1:5140/api/v1/send \
|
|
|
148
150
|
|
|
149
151
|
发布前将 TypeScript 编译成 JS 并附带 `.d.ts`,因为 Node 不会剥离 `node_modules` 中的 TypeScript。插件入口使用 `import { definePlugin } from '@asabot/core'`;运行时会连接当前框架实例。也可以运行 `npm create @asabot@latest -- --template plugin` 创建带构建和测试配置的插件项目。
|
|
150
152
|
|
|
153
|
+
要让插件市场和安装后的管理界面显示自定义图标,在 `package.json` 的 `keywords` 里加一条 `asabot-icon:` 声明,指向可公开访问的 HTTPS 图片(如 SVG 或 PNG):
|
|
154
|
+
|
|
155
|
+
```json
|
|
156
|
+
{
|
|
157
|
+
"keywords": ["asabot-plugin", "asabot-icon:https://assets.example.com/my-plugin.svg"]
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
两处使用同一条声明。没有声明、地址无效或图片加载失败时,面板显示默认的 `Package` 图标。
|
|
162
|
+
|
|
151
163
|
## 开发插件
|
|
152
164
|
|
|
153
165
|
### 最小插件
|
|
@@ -170,6 +182,8 @@ export default definePlugin({
|
|
|
170
182
|
|
|
171
183
|
默认发现 `plugins/<name>.ts` 和 `plugins/<name>/index.ts`;文件默认导出 `definePlugin(...)` 的结果。顶层以 `_` 或 `.` 开头的文件和目录,以及 `*.test.*`、`*.spec.*`、`*.d.ts` 均被忽略。`name` 由小写英文字母、数字、`-` 和 `_` 组成且必须全局唯一,`core` 是保留名。插件可声明 `version`、`description`、`depends: ['其他插件名']` 和 zod 配置 schema;从 `@asabot/core` 导入 `z`。脚手架生成的 `plugins/hello.ts` 包含配置和命令示例。
|
|
172
184
|
|
|
185
|
+
文件插件可直接在 `definePlugin()` 中声明 `iconUrl: 'https://assets.example.com/my-plugin.svg'`。
|
|
186
|
+
|
|
173
187
|
### Context 一览
|
|
174
188
|
|
|
175
189
|
| API | 用途 |
|
|
@@ -188,7 +202,7 @@ export default definePlugin({
|
|
|
188
202
|
| `ctx.bot(selfId?)`、`ctx.bots` | 查找在线 Bot、列出 Bot;找不到在线 Bot 时 `ctx.bot()` 抛错 |
|
|
189
203
|
| `ctx.send`、`ctx.broadcast` | 向指定平台和会话主动发送或批量发送 |
|
|
190
204
|
| `ctx.beforeSend`、`ctx.interceptApi` | 处理出站消息或拦截 Bot API 调用 |
|
|
191
|
-
| `ctx.provide`、`ctx.inject`、`ctx.injectOptional` |
|
|
205
|
+
| `ctx.provide`、`ctx.provideScoped`、`ctx.inject`、`ctx.injectOptional` | 提供共享或按调用方绑定的服务,或注入已声明的服务 |
|
|
192
206
|
| `ctx.dataDir`、`ctx.signal`、`ctx.onDispose(fn)` | 插件数据目录、卸载信号、自定义清理函数 |
|
|
193
207
|
|
|
194
208
|
观察者、命令、中间件、匹配器和定时任务随插件卸载自动回收。事件处理器应配合 `signal` 取消耗时操作;插件代码仍运行在主进程中。
|
package/dist/core/logger.js
CHANGED
|
@@ -94,7 +94,10 @@ class RotatingFile {
|
|
|
94
94
|
const { path, maxSize, maxFiles } = this.options;
|
|
95
95
|
if (!this.initialized) {
|
|
96
96
|
mkdirSync(dirname(path), { recursive: true });
|
|
97
|
-
|
|
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;
|
|
98
101
|
this.initialized = true;
|
|
99
102
|
}
|
|
100
103
|
const length = Buffer.byteLength(chunk);
|
|
@@ -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
|
}
|
|
@@ -16,7 +16,7 @@ import { type Target } from '../target.ts';
|
|
|
16
16
|
import { type Duration } from '../utils/duration.ts';
|
|
17
17
|
import { type PluginDefinition } from './definition.ts';
|
|
18
18
|
import { type TaskHandle, type TaskHandler, type TaskRegistrationOptions } from './tasks.ts';
|
|
19
|
-
import type { PanelPageOptions, PluginStateEvent } from './types.ts';
|
|
19
|
+
import type { PanelPageOptions, PluginStateEvent, ServiceConsumer } from './types.ts';
|
|
20
20
|
type Listener = (event: AnyEvent | PluginStateEvent, signal: AbortSignal) => unknown | Promise<unknown>;
|
|
21
21
|
type Cleanup = () => void | Promise<void>;
|
|
22
22
|
/** 按事件过滤的上下文,可继续注册处理器或叠加过滤条件。 */
|
|
@@ -34,6 +34,7 @@ export declare class Context<Config = undefined> {
|
|
|
34
34
|
private readonly tasks;
|
|
35
35
|
private readonly cleanups;
|
|
36
36
|
private readonly dependencies;
|
|
37
|
+
private readonly consumer;
|
|
37
38
|
private routeApp?;
|
|
38
39
|
private panelRouteApp?;
|
|
39
40
|
private disposed;
|
|
@@ -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。 */
|
|
@@ -2,6 +2,7 @@ import { mkdirSync } from 'node:fs';
|
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { fileURLToPath } from 'node:url';
|
|
4
4
|
import { Hono } from 'hono';
|
|
5
|
+
import { dispatchContext } from '../dispatch/trace.js';
|
|
5
6
|
import { NoBotOnlineError, PluginError } from '../errors.js';
|
|
6
7
|
import { Scheduler } from '../scheduler.js';
|
|
7
8
|
import { targetSchema } from '../target.js';
|
|
@@ -22,6 +23,7 @@ export class Context {
|
|
|
22
23
|
tasks;
|
|
23
24
|
cleanups = [];
|
|
24
25
|
dependencies;
|
|
26
|
+
consumer;
|
|
25
27
|
routeApp;
|
|
26
28
|
panelRouteApp;
|
|
27
29
|
disposed = false;
|
|
@@ -64,6 +66,17 @@ export class Context {
|
|
|
64
66
|
this.owner = name;
|
|
65
67
|
this.value = config;
|
|
66
68
|
this.dependencies = serviceDependencies(dependencies);
|
|
69
|
+
this.consumer = Object.freeze({
|
|
70
|
+
plugin: name,
|
|
71
|
+
signal: this.controller.signal,
|
|
72
|
+
event() {
|
|
73
|
+
const current = dispatchContext.getStore();
|
|
74
|
+
if (current?.plugin !== name || !current.active.value)
|
|
75
|
+
return undefined;
|
|
76
|
+
const { eventId, platform, selfId } = current.trace;
|
|
77
|
+
return { eventId, platform, selfId };
|
|
78
|
+
},
|
|
79
|
+
});
|
|
67
80
|
this.childLogger = app.logger.child({ plugin: name });
|
|
68
81
|
this.scope = { owner: name, signal: this.controller.signal };
|
|
69
82
|
this.scheduler = new Scheduler(this.childLogger, this.controller.signal, app.config.timezone);
|
|
@@ -161,7 +174,19 @@ export class Context {
|
|
|
161
174
|
/** 按名称提供插件服务并返回撤销函数;同名服务已存在时抛错。 */
|
|
162
175
|
provide(name, service) {
|
|
163
176
|
this.assertActive();
|
|
164
|
-
|
|
177
|
+
return this.disposeService(this.app.plugins.provide(this.owner, name, service));
|
|
178
|
+
}
|
|
179
|
+
/** 提供按使用方上下文创建的服务,服务可获取插件身份和卸载信号。 */
|
|
180
|
+
provideScoped(name, factory) {
|
|
181
|
+
this.assertActive();
|
|
182
|
+
return this.disposeService(this.app.plugins.provideScoped(this.owner, name, factory));
|
|
183
|
+
}
|
|
184
|
+
/** 列出声明依赖指定服务的已发现插件,包括未启用的插件。 */
|
|
185
|
+
serviceConsumers(name) {
|
|
186
|
+
this.assertActive();
|
|
187
|
+
return this.app.plugins.serviceConsumers(name);
|
|
188
|
+
}
|
|
189
|
+
disposeService(dispose) {
|
|
165
190
|
this.controller.signal.addEventListener('abort', dispose, { once: true });
|
|
166
191
|
return () => {
|
|
167
192
|
this.controller.signal.removeEventListener('abort', dispose);
|
|
@@ -173,14 +198,14 @@ export class Context {
|
|
|
173
198
|
this.assertActive();
|
|
174
199
|
if (!this.dependencies.required.includes(name))
|
|
175
200
|
throw new PluginError(`插件 "${this.owner}" 未声明服务 ${name}`);
|
|
176
|
-
return this.app.plugins.inject(name);
|
|
201
|
+
return this.app.plugins.inject(name, this.consumer);
|
|
177
202
|
}
|
|
178
203
|
/** 获取已声明的可选服务;服务缺失返回 undefined,未声明时抛出 PluginError。 */
|
|
179
204
|
injectOptional(name) {
|
|
180
205
|
this.assertActive();
|
|
181
206
|
if (!this.dependencies.optional.includes(name))
|
|
182
207
|
throw new PluginError(`插件 "${this.owner}" 未声明可选服务 ${name}`);
|
|
183
|
-
return this.app.plugins.injectOptional(name);
|
|
208
|
+
return this.app.plugins.injectOptional(name, this.consumer);
|
|
184
209
|
}
|
|
185
210
|
on(name, listener) {
|
|
186
211
|
this.assertActive();
|
|
@@ -9,6 +9,8 @@ export interface PluginDefinition<Schema extends z.ZodType | undefined = z.ZodTy
|
|
|
9
9
|
version?: string;
|
|
10
10
|
/** 插件说明,用于展示。 */
|
|
11
11
|
description?: string;
|
|
12
|
+
/** 内置和文件插件的 HTTPS 图标 URL;npm 插件在 keywords 中声明 asabot-icon:<URL>。 */
|
|
13
|
+
iconUrl?: string;
|
|
12
14
|
/** 安装时用于初始化「新机器人默认启用」;不声明时为 false。 */
|
|
13
15
|
defaultOnNewBots?: boolean;
|
|
14
16
|
/** 校验配置并推导 ctx.config 类型的 zod schema。 */
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export function parsePluginIconUrl(value) {
|
|
2
|
+
if (typeof value !== 'string' || value.length > 2048)
|
|
3
|
+
return undefined;
|
|
4
|
+
const url = URL.parse(value);
|
|
5
|
+
if (url?.protocol === 'https:' && !url.username && !url.password)
|
|
6
|
+
return url.href;
|
|
7
|
+
}
|
|
8
|
+
export function pluginIconFromKeywords(keywords) {
|
|
9
|
+
if (!Array.isArray(keywords))
|
|
10
|
+
return undefined;
|
|
11
|
+
const prefix = 'asabot-icon:';
|
|
12
|
+
const keyword = keywords.find((value) => typeof value === 'string' && value.startsWith(prefix));
|
|
13
|
+
return parsePluginIconUrl(keyword?.slice(prefix.length));
|
|
14
|
+
}
|
|
@@ -2,7 +2,7 @@ import type { App } from '../app.ts';
|
|
|
2
2
|
import { type BotIdentity } from '../identity.ts';
|
|
3
3
|
import { type PluginDefinition } from './definition.ts';
|
|
4
4
|
import { type PackageOptions, PackageService } from './packages.ts';
|
|
5
|
-
import type { PluginState } from './types.ts';
|
|
5
|
+
import type { PluginState, ServiceConsumer } from './types.ts';
|
|
6
6
|
/** 管理插件注册、依赖协调、启停、重载和服务。 */
|
|
7
7
|
export declare class PluginManager {
|
|
8
8
|
private readonly app;
|
|
@@ -28,8 +28,12 @@ export declare class PluginManager {
|
|
|
28
28
|
list(): PluginState[];
|
|
29
29
|
get(name: string): PluginState | undefined;
|
|
30
30
|
provide(plugin: string, name: string, value: unknown): () => void;
|
|
31
|
-
|
|
32
|
-
|
|
31
|
+
provideScoped(plugin: string, name: string, factory: (consumer: ServiceConsumer) => unknown): () => void;
|
|
32
|
+
serviceConsumers(name: string): string[];
|
|
33
|
+
private registerService;
|
|
34
|
+
inject(name: string, consumer?: ServiceConsumer): unknown;
|
|
35
|
+
injectOptional(name: string, consumer?: ServiceConsumer): unknown;
|
|
36
|
+
private serviceValue;
|
|
33
37
|
getConfig(name: string): unknown;
|
|
34
38
|
getGroupConfig(name: string, groupKey: string): Record<string, unknown> | undefined;
|
|
35
39
|
setGroupConfig(name: string, groupKey: string, override: Record<string, unknown> | null): void;
|
|
@@ -58,6 +62,7 @@ export declare class PluginManager {
|
|
|
58
62
|
upload(filename: string, content: string, overwrite?: boolean): Promise<PluginState>;
|
|
59
63
|
uninstall(name: string, purge?: boolean): Promise<void>;
|
|
60
64
|
packageInfo(name: string): import("./packages.ts").PackageInfo | undefined;
|
|
65
|
+
packageReadme(name: string): Promise<string | undefined>;
|
|
61
66
|
subscribePackageUpdates(subscriber: (state: PluginState) => void): () => void;
|
|
62
67
|
updateConfig(name: string, value: unknown): Promise<void>;
|
|
63
68
|
setDefaultOnNewBots(name: string, enabled: boolean): Promise<void>;
|
|
@@ -12,6 +12,7 @@ import { mergeConfig } from '../utils/merge.js';
|
|
|
12
12
|
import { Context } from './context.js';
|
|
13
13
|
import { serviceDependencies } from './definition.js';
|
|
14
14
|
import { pluginExecution } from './execution.js';
|
|
15
|
+
import { parsePluginIconUrl, pluginIconFromKeywords } from './icon.js';
|
|
15
16
|
import { importPlugin, registerPluginRoots } from './loader.js';
|
|
16
17
|
import { PackageService, redact } from './packages.js';
|
|
17
18
|
import { ManagementError, uploadContents } from './upload.js';
|
|
@@ -122,10 +123,22 @@ export class PluginManager {
|
|
|
122
123
|
return state && { ...state };
|
|
123
124
|
}
|
|
124
125
|
provide(plugin, name, value) {
|
|
126
|
+
return this.registerService(name, { plugin, kind: 'shared', value });
|
|
127
|
+
}
|
|
128
|
+
provideScoped(plugin, name, factory) {
|
|
129
|
+
return this.registerService(name, { plugin, kind: 'scoped', factory, instances: new WeakMap() });
|
|
130
|
+
}
|
|
131
|
+
serviceConsumers(name) {
|
|
132
|
+
return [...this.entries.values()]
|
|
133
|
+
.filter(({ state }) => state.inject.some((item) => item.name === name))
|
|
134
|
+
.map(({ state }) => state.name)
|
|
135
|
+
.sort();
|
|
136
|
+
}
|
|
137
|
+
registerService(name, service) {
|
|
138
|
+
const { plugin } = service;
|
|
125
139
|
const existing = this.services.get(name);
|
|
126
140
|
if (existing)
|
|
127
141
|
throw new PluginError(`服务 ${name} 冲突:插件 "${existing.plugin}" 已提供,插件 "${plugin}" 无法重复提供`);
|
|
128
|
-
const service = { plugin, value };
|
|
129
142
|
this.services.set(name, service);
|
|
130
143
|
this.serviceProviders.set(name, plugin);
|
|
131
144
|
const entry = this.require(plugin);
|
|
@@ -143,14 +156,24 @@ export class PluginManager {
|
|
|
143
156
|
this.requestReconcile();
|
|
144
157
|
};
|
|
145
158
|
}
|
|
146
|
-
inject(name) {
|
|
159
|
+
inject(name, consumer) {
|
|
147
160
|
const service = this.services.get(name);
|
|
148
161
|
if (!service)
|
|
149
162
|
throw new PluginError(`服务 ${name} 不可用`);
|
|
150
|
-
return service
|
|
163
|
+
return this.serviceValue(name, service, consumer);
|
|
151
164
|
}
|
|
152
|
-
injectOptional(name) {
|
|
153
|
-
|
|
165
|
+
injectOptional(name, consumer) {
|
|
166
|
+
const service = this.services.get(name);
|
|
167
|
+
return service && this.serviceValue(name, service, consumer);
|
|
168
|
+
}
|
|
169
|
+
serviceValue(name, service, consumer) {
|
|
170
|
+
if (service.kind === 'shared')
|
|
171
|
+
return service.value;
|
|
172
|
+
if (!consumer)
|
|
173
|
+
throw new PluginError(`服务 ${name} 必须在插件上下文中注入`);
|
|
174
|
+
if (!service.instances.has(consumer))
|
|
175
|
+
service.instances.set(consumer, service.factory(consumer));
|
|
176
|
+
return service.instances.get(consumer);
|
|
154
177
|
}
|
|
155
178
|
getConfig(name) {
|
|
156
179
|
const entry = this.entries.get(name);
|
|
@@ -290,6 +313,7 @@ export class PluginManager {
|
|
|
290
313
|
pluginName = `${base}-${suffix++}`;
|
|
291
314
|
const state = {
|
|
292
315
|
name: pluginName,
|
|
316
|
+
iconUrl: pluginIconFromKeywords(manifest.keywords),
|
|
293
317
|
source: 'package',
|
|
294
318
|
state: 'failed',
|
|
295
319
|
enabled: this.app.config.plugins[pluginName]?.enabled ?? true,
|
|
@@ -508,6 +532,12 @@ export class PluginManager {
|
|
|
508
532
|
const manifest = this.entries.get(name)?.manifest;
|
|
509
533
|
return manifest ? this.packages.info(manifest) : undefined;
|
|
510
534
|
}
|
|
535
|
+
packageReadme(name) {
|
|
536
|
+
const manifest = this.entries.get(name)?.manifest;
|
|
537
|
+
if (!manifest)
|
|
538
|
+
throw new ManagementError(404, 'Plugin package is not installed');
|
|
539
|
+
return this.packages.installedReadme(manifest);
|
|
540
|
+
}
|
|
511
541
|
subscribePackageUpdates(subscriber) {
|
|
512
542
|
this.packageUpdateSubscribers.add(subscriber);
|
|
513
543
|
return () => this.packageUpdateSubscribers.delete(subscriber);
|
|
@@ -598,7 +628,7 @@ export class PluginManager {
|
|
|
598
628
|
else
|
|
599
629
|
this.app.logger.debug({ plugin: name, field }, 'Plugin configuration changed in memory only');
|
|
600
630
|
}
|
|
601
|
-
add(definition, source, path, files = new Set(), release) {
|
|
631
|
+
add(definition, source, path, files = new Set(), release, manifest) {
|
|
602
632
|
const name = definition.name;
|
|
603
633
|
const state = {
|
|
604
634
|
name,
|
|
@@ -610,7 +640,7 @@ export class PluginManager {
|
|
|
610
640
|
inject: [],
|
|
611
641
|
capabilities: definition.capabilities,
|
|
612
642
|
};
|
|
613
|
-
const entry = { state, definition, files, release };
|
|
643
|
+
const entry = { state, definition, files, release, manifest };
|
|
614
644
|
this.metadata(entry);
|
|
615
645
|
if (this.entries.has(name)) {
|
|
616
646
|
entry.failure = 'duplicate';
|
|
@@ -631,6 +661,9 @@ export class PluginManager {
|
|
|
631
661
|
entry.state.capabilities = definition.capabilities;
|
|
632
662
|
entry.state.version = definition.version;
|
|
633
663
|
entry.state.description = definition.description;
|
|
664
|
+
entry.state.iconUrl = entry.manifest
|
|
665
|
+
? pluginIconFromKeywords(entry.manifest.keywords)
|
|
666
|
+
: parsePluginIconUrl(definition.iconUrl);
|
|
634
667
|
entry.state.depends = definition.depends;
|
|
635
668
|
const dependencies = serviceDependencies(definition.inject);
|
|
636
669
|
entry.state.inject = [
|
|
@@ -824,7 +857,7 @@ export class PluginManager {
|
|
|
824
857
|
const target = manifest.exports === undefined ? (manifest.main ?? 'index.js') : select(exports);
|
|
825
858
|
if (!target || !/\.(?:js|mjs)$/.test(target))
|
|
826
859
|
throw new ManagementError(400, 'Plugin package entry must be JavaScript');
|
|
827
|
-
const root =
|
|
860
|
+
const root = this.packages.packageRoot(manifest.name);
|
|
828
861
|
const path = resolve(root, target);
|
|
829
862
|
this.ensureInside(root, path);
|
|
830
863
|
await this.ensureRealInside(root, path);
|
|
@@ -842,9 +875,7 @@ export class PluginManager {
|
|
|
842
875
|
throw new ManagementError(409, 'Updated package changed its plugin name');
|
|
843
876
|
if (!existing) {
|
|
844
877
|
await this.initializeDefaultOnNewBots(definition);
|
|
845
|
-
|
|
846
|
-
entry.manifest = manifest;
|
|
847
|
-
return entry;
|
|
878
|
+
return this.add(definition, 'package', path, imported.files, imported.release, manifest);
|
|
848
879
|
}
|
|
849
880
|
const oldPath = existing.state.path;
|
|
850
881
|
const oldManifest = existing.manifest;
|
|
@@ -35,6 +35,7 @@ export interface PackageSearchItem {
|
|
|
35
35
|
name: string;
|
|
36
36
|
version: string;
|
|
37
37
|
description?: string;
|
|
38
|
+
iconUrl?: string;
|
|
38
39
|
author?: string;
|
|
39
40
|
date?: string;
|
|
40
41
|
links: {
|
|
@@ -147,7 +148,9 @@ export declare class PackageService {
|
|
|
147
148
|
}, host: PackageHost, options?: PackageOptions);
|
|
148
149
|
init(): Promise<void>;
|
|
149
150
|
dependencies(): Promise<Record<string, string>>;
|
|
151
|
+
packageRoot(name: string): string;
|
|
150
152
|
manifest(name: string): Promise<PackageManifest>;
|
|
153
|
+
installedReadme(manifest: PackageManifest): Promise<string | undefined>;
|
|
151
154
|
info(manifest: PackageManifest): PackageInfo;
|
|
152
155
|
private refreshLatest;
|
|
153
156
|
ensureLatest(): Promise<void>;
|
|
@@ -174,6 +177,7 @@ export declare class PackageService {
|
|
|
174
177
|
installed?: string | undefined;
|
|
175
178
|
versions: {
|
|
176
179
|
version: string;
|
|
180
|
+
iconUrl: string | undefined;
|
|
177
181
|
date?: string | undefined;
|
|
178
182
|
peerRange?: string | undefined;
|
|
179
183
|
compatible: boolean;
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
|
-
import {
|
|
3
|
+
import { createReadStream } from 'node:fs';
|
|
4
|
+
import { access, mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
|
|
4
5
|
import { delimiter, isAbsolute, join, resolve } from 'node:path';
|
|
5
6
|
import { fileURLToPath } from 'node:url';
|
|
6
7
|
import { gunzipSync } from 'fflate';
|
|
7
8
|
import { maxSatisfying, rcompare, satisfies, valid, validRange } from 'semver';
|
|
8
9
|
import { z } from 'zod';
|
|
10
|
+
import { pluginIconFromKeywords } from './icon.js';
|
|
9
11
|
import { ManagementError } from './upload.js';
|
|
10
12
|
const manifestSchema = z.object({
|
|
11
13
|
name: z.string(),
|
|
@@ -83,7 +85,13 @@ export function redact(value) {
|
|
|
83
85
|
return result;
|
|
84
86
|
}
|
|
85
87
|
const maxTarballBytes = 5 * 1024 * 1024;
|
|
86
|
-
const
|
|
88
|
+
const maxReadmeBytes = 200 * 1024;
|
|
89
|
+
const readmeFilename = /^readme(?:\.(?:md|markdown|txt))?$/i;
|
|
90
|
+
function decodeReadme(bytes) {
|
|
91
|
+
return new TextDecoder().decode(bytes.subarray(0, maxReadmeBytes), {
|
|
92
|
+
stream: bytes.length > maxReadmeBytes,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
87
95
|
/** The top-level README of an npm tarball (gzipped ustar), or undefined when there is none. */
|
|
88
96
|
export function readmeFromTarball(tgz) {
|
|
89
97
|
const tar = gunzipSync(tgz);
|
|
@@ -104,7 +112,8 @@ export function readmeFromTarball(tgz) {
|
|
|
104
112
|
const prefix = field(offset + 345, 155);
|
|
105
113
|
const path = prefix ? `${prefix}/${name}` : name;
|
|
106
114
|
const start = offset + 512;
|
|
107
|
-
|
|
115
|
+
const slash = path.indexOf('/');
|
|
116
|
+
if ((type === '' || type === '0') && slash > 0 && readmeFilename.test(path.slice(slash + 1)))
|
|
108
117
|
return decoder.decode(tar.subarray(start, start + size));
|
|
109
118
|
offset = start + Math.ceil(size / 512) * 512;
|
|
110
119
|
}
|
|
@@ -165,6 +174,7 @@ export class FetchRegistry {
|
|
|
165
174
|
name: item.name,
|
|
166
175
|
version: item.version,
|
|
167
176
|
...(item.description === undefined ? {} : { description: item.description }),
|
|
177
|
+
iconUrl: pluginIconFromKeywords(item.keywords),
|
|
168
178
|
...(item.author === undefined
|
|
169
179
|
? {}
|
|
170
180
|
: { author: typeof item.author === 'string' ? item.author : item.author.name }),
|
|
@@ -291,15 +301,35 @@ export class PackageService {
|
|
|
291
301
|
const data = JSON.parse(await readFile(join(this.dir, 'package.json'), 'utf8'));
|
|
292
302
|
return data.dependencies ?? {};
|
|
293
303
|
}
|
|
304
|
+
packageRoot(name) {
|
|
305
|
+
return join(this.dir, 'node_modules', ...name.split('/'));
|
|
306
|
+
}
|
|
294
307
|
async manifest(name) {
|
|
295
308
|
if (!validPackageName(name))
|
|
296
309
|
throw new ManagementError(400, 'Invalid package name');
|
|
297
|
-
const data = JSON.parse(await readFile(join(this.
|
|
310
|
+
const data = JSON.parse(await readFile(join(this.packageRoot(name), 'package.json'), 'utf8'));
|
|
298
311
|
const parsed = manifestSchema.safeParse(data);
|
|
299
312
|
if (!parsed.success || parsed.data.name !== name || !valid(parsed.data.version))
|
|
300
313
|
throw new ManagementError(400, 'Invalid installed package metadata');
|
|
301
314
|
return parsed.data;
|
|
302
315
|
}
|
|
316
|
+
async installedReadme(manifest) {
|
|
317
|
+
const root = this.packageRoot(manifest.name);
|
|
318
|
+
try {
|
|
319
|
+
const files = await readdir(root, { withFileTypes: true });
|
|
320
|
+
const readme = files.find((file) => file.isFile() && readmeFilename.test(file.name));
|
|
321
|
+
if (!readme)
|
|
322
|
+
return undefined;
|
|
323
|
+
const stream = createReadStream(join(root, readme.name), { end: maxReadmeBytes });
|
|
324
|
+
const chunks = await stream.toArray();
|
|
325
|
+
return decodeReadme(Buffer.concat(chunks));
|
|
326
|
+
}
|
|
327
|
+
catch (error) {
|
|
328
|
+
if (error.code === 'ENOENT')
|
|
329
|
+
return undefined;
|
|
330
|
+
throw error;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
303
333
|
info(manifest) {
|
|
304
334
|
const peerRange = manifest.peerDependencies?.['@asabot/core'];
|
|
305
335
|
const cached = this.latestCache.get(manifest.name);
|
|
@@ -411,10 +441,7 @@ export class PackageService {
|
|
|
411
441
|
const data = cached.value;
|
|
412
442
|
const installed = this.host.installedPackages().get(name)?.manifest.version;
|
|
413
443
|
const repository = typeof data.repository === 'string' ? data.repository : data.repository?.url;
|
|
414
|
-
const
|
|
415
|
-
const readme = bytes && bytes.length > 200 * 1024
|
|
416
|
-
? new TextDecoder().decode(bytes.subarray(0, 200 * 1024), { stream: true })
|
|
417
|
-
: data.readme;
|
|
444
|
+
const readme = data.readme === undefined ? undefined : decodeReadme(Buffer.from(data.readme, 'utf8'));
|
|
418
445
|
const versions = Object.keys(data.versions)
|
|
419
446
|
.filter((version) => valid(version))
|
|
420
447
|
.sort(rcompare)
|
|
@@ -424,6 +451,7 @@ export class PackageService {
|
|
|
424
451
|
.object({
|
|
425
452
|
peerDependencies: z.record(z.string(), z.string()).optional(),
|
|
426
453
|
deprecated: z.string().optional(),
|
|
454
|
+
keywords: z.unknown().optional(),
|
|
427
455
|
})
|
|
428
456
|
.safeParse(data.versions[version]);
|
|
429
457
|
const peerRange = value.success ? value.data.peerDependencies?.['@asabot/core'] : undefined;
|
|
@@ -431,6 +459,7 @@ export class PackageService {
|
|
|
431
459
|
const date = data.time?.[version];
|
|
432
460
|
return {
|
|
433
461
|
version,
|
|
462
|
+
iconUrl: value.success ? pluginIconFromKeywords(value.data.keywords) : undefined,
|
|
434
463
|
...(date === undefined ? {} : { date }),
|
|
435
464
|
...(peerRange === undefined ? {} : { peerRange }),
|
|
436
465
|
compatible: !!peerRange && !!validRange(peerRange) && satisfies(frameworkVersion, peerRange),
|
|
@@ -459,7 +488,8 @@ export class PackageService {
|
|
|
459
488
|
(version !== undefined &&
|
|
460
489
|
(version.length > 256 || (!validRange(version) && !/^[a-zA-Z0-9][a-zA-Z0-9._+-]*$/.test(version)))))
|
|
461
490
|
throw new ManagementError(400, 'Invalid package name or version');
|
|
462
|
-
|
|
491
|
+
// The abbreviated npm packument omits keywords from version manifests.
|
|
492
|
+
const metadata = await this.registry.fullMetadata(name);
|
|
463
493
|
this.latestCache.set(name, { value: metadata['dist-tags']?.latest, expires: Date.now() + 3_600_000 });
|
|
464
494
|
const selected = version === undefined
|
|
465
495
|
? metadata['dist-tags']?.latest
|
|
@@ -14,11 +14,22 @@ export interface PanelPage {
|
|
|
14
14
|
root: string;
|
|
15
15
|
entry: string;
|
|
16
16
|
}
|
|
17
|
+
/** 由框架绑定的服务使用方;事件信息只在该插件的分发处理期间可用。 */
|
|
18
|
+
export interface ServiceConsumer {
|
|
19
|
+
readonly plugin: string;
|
|
20
|
+
readonly signal: AbortSignal;
|
|
21
|
+
event(): {
|
|
22
|
+
eventId: string;
|
|
23
|
+
platform: string;
|
|
24
|
+
selfId: string;
|
|
25
|
+
} | undefined;
|
|
26
|
+
}
|
|
17
27
|
/** 插件的来源、运行状态、依赖服务及可选错误信息。 */
|
|
18
28
|
export interface PluginState {
|
|
19
29
|
name: string;
|
|
20
30
|
version?: string;
|
|
21
31
|
description?: string;
|
|
32
|
+
iconUrl?: string;
|
|
22
33
|
depends?: string[];
|
|
23
34
|
source: 'builtin' | 'file' | 'package';
|
|
24
35
|
path?: string;
|
package/dist/index.d.ts
CHANGED
|
@@ -41,7 +41,7 @@ export { definePlugin, type PluginDefinition } from './core/plugin/definition.ts
|
|
|
41
41
|
export { PluginManager } from './core/plugin/manager.ts';
|
|
42
42
|
export type { TaskAttempt, TaskHandle, TaskHandler, TaskOptions, TaskOutcome, TaskPolicy, TaskQuery, TaskRecord, TaskRegistrationOptions, TaskState, } from './core/plugin/tasks.ts';
|
|
43
43
|
export { TaskConflictError } from './core/plugin/tasks.ts';
|
|
44
|
-
export type { PanelPageOptions, PluginState, PluginStateEvent } from './core/plugin/types.ts';
|
|
44
|
+
export type { PanelPageOptions, PluginState, PluginStateEvent, ServiceConsumer } from './core/plugin/types.ts';
|
|
45
45
|
export type { CooldownScope } from './core/ratelimit.ts';
|
|
46
46
|
export { type AccessEntry, type AccessList, type AccessSubject, KVStore, Storage, } from './core/storage/index.ts';
|
|
47
47
|
export { formatTarget, parseTarget, type Target, targetSchema } from './core/target.ts';
|
package/dist/server/index.js
CHANGED
|
@@ -635,6 +635,7 @@ export class HttpServer {
|
|
|
635
635
|
});
|
|
636
636
|
panel.post('/send', async (c) => c.json(await this.send(await body(c, sendSchema))));
|
|
637
637
|
panel.get('/plugins', (c) => c.json(this.app.plugins.list().map((plugin) => pluginView(this.app, plugin))));
|
|
638
|
+
panel.get('/plugins/:name/readme', async (c) => c.json({ readme: await this.app.plugins.packageReadme(c.req.param('name')) }));
|
|
638
639
|
panel.post('/plugins/rescan', async (c) => {
|
|
639
640
|
const result = await this.app.plugins.rescan();
|
|
640
641
|
return c.json({
|
package/dist/server/views.d.ts
CHANGED
|
@@ -35,6 +35,7 @@ export declare function pluginView(app: App, state: PluginState): {
|
|
|
35
35
|
name: string;
|
|
36
36
|
version?: string;
|
|
37
37
|
description?: string;
|
|
38
|
+
iconUrl?: string;
|
|
38
39
|
depends?: string[];
|
|
39
40
|
source: 'builtin' | 'file' | 'package';
|
|
40
41
|
path?: string;
|
|
@@ -140,6 +141,7 @@ export declare function botPluginView(app: App, bot: BotAccount, name: string):
|
|
|
140
141
|
name: string;
|
|
141
142
|
version?: string;
|
|
142
143
|
description?: string;
|
|
144
|
+
iconUrl?: string;
|
|
143
145
|
depends?: string[];
|
|
144
146
|
source: 'builtin' | 'file' | 'package';
|
|
145
147
|
path?: string;
|
package/docs/DEPLOY.md
CHANGED
|
@@ -54,6 +54,27 @@ curl http://127.0.0.1:5140/healthz
|
|
|
54
54
|
|
|
55
55
|
Compose 只启动 AsaBot;OneBot 服务需要自行准备。`/healthz` 检查 HTTP 服务是否运行,Bot 离线时也会返回成功,可结合响应中的 `bots.online` 查看连接状态。停止服务使用 `docker compose stop`。
|
|
56
56
|
|
|
57
|
+
### 使用 GHCR 镜像
|
|
58
|
+
|
|
59
|
+
Linux x86-64 服务器可以直接拉取预构建镜像。在 `compose.yaml` 同目录下的 `compose.override.yaml` 中为 `asabot` 服务设置以下两项(已有端口、网络等配置可继续保留):
|
|
60
|
+
|
|
61
|
+
```yaml
|
|
62
|
+
services:
|
|
63
|
+
asabot:
|
|
64
|
+
build: !reset null
|
|
65
|
+
image: ghcr.io/isyuah/asabot:latest
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`!reset` 清除主配置里的本地构建配置,需要 Docker Compose 2.24.4 或更新版本。初始化配置和目录后,首次启动和后续拉取新版使用同一条命令:
|
|
69
|
+
|
|
70
|
+
```sh
|
|
71
|
+
docker compose up -d --pull always --wait asabot
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Compose 会先拉取镜像,再根据变更重建 AsaBot 容器,沿用宿主机上的 `config`、`data` 和 `plugins`。`latest` 会在发布时更新,已经运行的容器要在执行上述命令后才会换用新镜像。也可以指定版本号或 `sha-<完整 Git 提交哈希>` 标签来固定部署版本。
|
|
75
|
+
|
|
76
|
+
维护者推送 `vX.Y.Z` 格式的 Git 标签后,[Publish container image](https://github.com/isyuah/AsaBot/actions/workflows/container.yml) 会发布 `X.Y.Z`、`sha-<完整 Git 提交哈希>` 和 `latest`。也可在 Actions 中对默认分支手动运行该工作流,更新 `latest` 和提交标签。[公开镜像](https://github.com/isyuah/AsaBot/pkgs/container/asabot)可以匿名拉取。
|
|
77
|
+
|
|
57
78
|
也可直接构建和运行容器(示例为 Linux/macOS shell):
|
|
58
79
|
|
|
59
80
|
```sh
|
|
@@ -150,7 +171,7 @@ server {
|
|
|
150
171
|
|
|
151
172
|
数据目录包含 `asabot.db`、SQLite 的 WAL 文件以及插件数据。备份前先停止 AsaBot,再备份整个数据目录、用户插件和实际使用的配置文件;环境变量和 `.env` 应单独安全保存。恢复时使用对应的数据、插件和配置,并确保容器用户有正确的读写权限。
|
|
152
173
|
|
|
153
|
-
|
|
174
|
+
升级前先停止服务并完成备份。直接运行方式在更新仓库代码后执行 `pnpm install --frozen-lockfile` 和 `pnpm --filter web build` 再启动;Compose 按部署方式构建源码或[拉取 GHCR 镜像](#使用-ghcr-镜像)。升级后检查日志、`/healthz`、面板和 OneBot 连接。升级时保留原有数据挂载,不要清理数据卷。
|
|
154
175
|
|
|
155
176
|
### 从 0.1.x 迁移群规则
|
|
156
177
|
|