@mushinjs/core 0.3.0 → 0.4.0-next.20261124175848
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/dist/actions.d.ts +18 -9
- package/dist/actions.js +15 -3
- package/dist/actions.js.map +1 -1
- package/dist/env.js +1 -1
- package/dist/env.js.map +1 -1
- package/dist/errors.d.ts +1 -1
- package/dist/errors.js +1 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/manager.d.ts +69 -2
- package/dist/manager.js +200 -6
- package/dist/manager.js.map +1 -1
- package/dist/manifest.d.ts +4 -1
- package/dist/manifest.js.map +1 -1
- package/dist/message.d.ts +1 -1
- package/dist/message.js.map +1 -1
- package/dist/utils.d.ts +1 -1
- package/dist/utils.js +6 -2
- package/dist/utils.js.map +1 -1
- package/package.json +1 -1
package/dist/actions.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Context, Service } from "cordis";
|
|
1
|
+
import { Context, Fiber, Service } from "cordis";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
declare module 'cordis' {
|
|
4
4
|
interface Context {
|
|
@@ -15,8 +15,8 @@ declare module 'cordis' {
|
|
|
15
15
|
}
|
|
16
16
|
export type Risk = 'read' | 'write' | 'dangerous';
|
|
17
17
|
export interface ActionCaller {
|
|
18
|
-
kind: 'api' | '
|
|
19
|
-
/**
|
|
18
|
+
kind: 'api' | 'fairy' | 'mcp' | 'internal';
|
|
19
|
+
/** Fairy session id, when Fairy made the call. */
|
|
20
20
|
session?: string;
|
|
21
21
|
/** Dashboard connection id, used to route client actions back to the right tab. */
|
|
22
22
|
client?: string;
|
|
@@ -24,7 +24,7 @@ export interface ActionCaller {
|
|
|
24
24
|
export interface ActionDefinition<S extends z.ZodType = z.ZodType, R = unknown> {
|
|
25
25
|
/** Dotted lowercase name, such as `bots.create`. */
|
|
26
26
|
name: string;
|
|
27
|
-
/** Written for
|
|
27
|
+
/** Written for Fairy: what the action does and what it returns. */
|
|
28
28
|
description: string;
|
|
29
29
|
input: S;
|
|
30
30
|
/** JSON Schema shown instead of the one made from `input`, for tools described elsewhere (such as MCP tools). */
|
|
@@ -33,10 +33,15 @@ export interface ActionDefinition<S extends z.ZodType = z.ZodType, R = unknown>
|
|
|
33
33
|
/** Client actions run in the dashboard; the server relays them to the caller's tab. */
|
|
34
34
|
client?: boolean;
|
|
35
35
|
/**
|
|
36
|
-
* False keeps the action away from
|
|
36
|
+
* False keeps the action away from Fairy: dashboard plumbing (editor previews, debugger
|
|
37
37
|
* controls) that only makes sense next to a screen and would only distract the model.
|
|
38
38
|
*/
|
|
39
|
-
|
|
39
|
+
fairy?: false;
|
|
40
|
+
/**
|
|
41
|
+
* Whether Fairy asks before a call with this input, when the user set no policy for the action; undefined goes by
|
|
42
|
+
* the risk (dangerous asks). Lets an action ask only for some inputs, such as a command that changes something.
|
|
43
|
+
*/
|
|
44
|
+
approval?: (input: z.output<S>) => 'auto' | 'confirm' | undefined;
|
|
40
45
|
handler?: (input: z.output<S>, caller: ActionCaller) => R | Promise<R>;
|
|
41
46
|
}
|
|
42
47
|
export interface ActionInfo {
|
|
@@ -44,8 +49,8 @@ export interface ActionInfo {
|
|
|
44
49
|
description: string;
|
|
45
50
|
risk: Risk;
|
|
46
51
|
client: boolean;
|
|
47
|
-
/** False when
|
|
48
|
-
|
|
52
|
+
/** False when Fairy never sees the action; see `ActionDefinition.fairy`. */
|
|
53
|
+
fairy: boolean;
|
|
49
54
|
plugin: string;
|
|
50
55
|
inputSchema: JsonSchema;
|
|
51
56
|
}
|
|
@@ -61,7 +66,7 @@ export type ClientRelay = (name: string, input: unknown, caller: ActionCaller) =
|
|
|
61
66
|
/** Converts a zod schema to the JSON Schema shown to LLMs and dashboard forms. */
|
|
62
67
|
export declare function toJsonSchema(schema: z.ZodType): JsonSchema;
|
|
63
68
|
/**
|
|
64
|
-
* The registry of typed operations. The HTTP API and
|
|
69
|
+
* The registry of typed operations. The HTTP API and Fairy both call actions,
|
|
65
70
|
* so a feature a plugin exposes here is reachable from the dashboard and by conversation.
|
|
66
71
|
*/
|
|
67
72
|
export declare class Actions extends Service {
|
|
@@ -73,6 +78,10 @@ export declare class Actions extends Service {
|
|
|
73
78
|
/** Lets the console relay client actions to dashboard tabs. */
|
|
74
79
|
setClientRelay(relay: ClientRelay): import("cordis").Disposable<Promise<void>>;
|
|
75
80
|
has(name: string): boolean;
|
|
81
|
+
/** Whether Fairy should ask before this call, as the action decides from the input; see `ActionDefinition.approval`. */
|
|
82
|
+
approval(name: string, input: unknown): 'auto' | 'confirm' | undefined;
|
|
83
|
+
/** The context that defined an action; `manager.packageOf` names its plugin. */
|
|
84
|
+
fiberOf(name: string): Fiber | undefined;
|
|
76
85
|
get(name: string): ActionInfo | undefined;
|
|
77
86
|
list(): ActionInfo[];
|
|
78
87
|
private info;
|
package/dist/actions.js
CHANGED
|
@@ -12,7 +12,7 @@ function toJsonSchema(schema) {
|
|
|
12
12
|
}
|
|
13
13
|
const namePattern = /^[a-z][a-zA-Z0-9]*(\.[a-z][a-zA-Z0-9]*)+$/;
|
|
14
14
|
/**
|
|
15
|
-
* The registry of typed operations. The HTTP API and
|
|
15
|
+
* The registry of typed operations. The HTTP API and Fairy both call actions,
|
|
16
16
|
* so a feature a plugin exposes here is reachable from the dashboard and by conversation.
|
|
17
17
|
*/
|
|
18
18
|
var Actions = class extends Service {
|
|
@@ -30,7 +30,8 @@ var Actions = class extends Service {
|
|
|
30
30
|
if (this.store.has(definition.name)) throw new Error(`action "${definition.name}" is already defined`);
|
|
31
31
|
this.store.set(definition.name, {
|
|
32
32
|
...definition,
|
|
33
|
-
plugin: ctx.fiber.name
|
|
33
|
+
plugin: ctx.fiber.name,
|
|
34
|
+
fiber: ctx.fiber
|
|
34
35
|
});
|
|
35
36
|
ctx.emit("actions/changed");
|
|
36
37
|
return () => {
|
|
@@ -51,6 +52,17 @@ var Actions = class extends Service {
|
|
|
51
52
|
has(name) {
|
|
52
53
|
return this.store.has(name);
|
|
53
54
|
}
|
|
55
|
+
/** Whether Fairy should ask before this call, as the action decides from the input; see `ActionDefinition.approval`. */
|
|
56
|
+
approval(name, input) {
|
|
57
|
+
const action = this.store.get(name);
|
|
58
|
+
if (!action?.approval) return;
|
|
59
|
+
const parsed = action.input.safeParse(input ?? {});
|
|
60
|
+
return parsed.success ? action.approval(parsed.data) : void 0;
|
|
61
|
+
}
|
|
62
|
+
/** The context that defined an action; `manager.packageOf` names its plugin. */
|
|
63
|
+
fiberOf(name) {
|
|
64
|
+
return this.store.get(name)?.fiber;
|
|
65
|
+
}
|
|
54
66
|
get(name) {
|
|
55
67
|
const action = this.store.get(name);
|
|
56
68
|
return action && this.info(action);
|
|
@@ -65,7 +77,7 @@ var Actions = class extends Service {
|
|
|
65
77
|
description: action.description,
|
|
66
78
|
risk: action.risk,
|
|
67
79
|
client: !!action.client,
|
|
68
|
-
|
|
80
|
+
fairy: action.fairy !== false,
|
|
69
81
|
plugin: action.plugin,
|
|
70
82
|
inputSchema: action.schema
|
|
71
83
|
};
|
package/dist/actions.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"actions.js","names":[],"sources":["../src/actions.ts"],"sourcesContent":["import { Context, Service } from 'cordis'\nimport { z } from 'zod'\nimport { MushinError } from './errors'\n\ndeclare module 'cordis' {\n interface Context {\n actions: Actions\n /** The instance directory: config file, data and local plugins live here. */\n baseDir: string\n /** Set by `mushin test`: bots stay offline and nothing reaches the outside. The launcher always sets it. */\n offline: boolean\n }\n\n interface Events {\n 'actions/changed'(): void\n 'actions/called'(record: ActionCallRecord): void\n }\n}\n\nexport type Risk = 'read' | 'write' | 'dangerous'\n\nexport interface ActionCaller {\n kind: 'api' | 'agent' | 'mcp' | 'internal'\n /** Agent session id, when the Agent made the call. */\n session?: string\n /** Dashboard connection id, used to route client actions back to the right tab. */\n client?: string\n}\n\nexport interface ActionDefinition<S extends z.ZodType = z.ZodType, R = unknown> {\n /** Dotted lowercase name, such as `bots.create`. */\n name: string\n /** Written for the Agent: what the action does and what it returns. */\n description: string\n input: S\n /** JSON Schema shown instead of the one made from `input`, for tools described elsewhere (such as MCP tools). */\n inputSchema?: JsonSchema\n risk: Risk\n /** Client actions run in the dashboard; the server relays them to the caller's tab. */\n client?: boolean\n /**\n * False keeps the action away from the Agent: dashboard plumbing (editor previews, debugger\n * controls) that only makes sense next to a screen and would only distract the model.\n */\n agent?: false\n handler?: (input: z.output<S>, caller: ActionCaller) => R | Promise<R>\n}\n\nexport interface ActionInfo {\n name: string\n description: string\n risk: Risk\n client: boolean\n /** False when the Agent never sees the action; see `ActionDefinition.agent`. */\n agent: boolean\n plugin: string\n inputSchema: JsonSchema\n}\n\nexport interface ActionCallRecord {\n name: string\n caller: ActionCaller\n ok: boolean\n durationMs: number\n error?: string\n}\n\nexport type JsonSchema = Record<string, any>\n\nexport type ClientRelay = (name: string, input: unknown, caller: ActionCaller) => Promise<unknown>\n\ninterface StoredAction extends ActionDefinition {\n plugin: string\n schema?: JsonSchema\n}\n\n/** Converts a zod schema to the JSON Schema shown to LLMs and dashboard forms. */\nexport function toJsonSchema(schema: z.ZodType): JsonSchema {\n const { $schema, ...rest } = z.toJSONSchema(schema, { io: 'input', unrepresentable: 'any' }) as JsonSchema\n return rest\n}\n\nconst namePattern = /^[a-z][a-zA-Z0-9]*(\\.[a-z][a-zA-Z0-9]*)+$/\n\n/**\n * The registry of typed operations. The HTTP API and the Agent both call actions,\n * so a feature a plugin exposes here is reachable from the dashboard and by conversation.\n */\nexport class Actions extends Service {\n private store = new Map<string, StoredAction>()\n private relay?: ClientRelay\n\n constructor(ctx: Context) {\n super(ctx, 'actions')\n }\n\n /** Registers an action. It is removed when the calling plugin unloads. */\n define<S extends z.ZodType, R>(definition: ActionDefinition<S, R>) {\n if (!namePattern.test(definition.name)) {\n throw new Error(`invalid action name \"${definition.name}\", expected a dotted name such as \"bots.create\"`)\n }\n if (!definition.client && !definition.handler) {\n throw new Error(`action \"${definition.name}\" needs a handler`)\n }\n const ctx = this.ctx\n return ctx.effect(() => {\n if (this.store.has(definition.name)) {\n throw new Error(`action \"${definition.name}\" is already defined`)\n }\n this.store.set(definition.name, { ...(definition as ActionDefinition), plugin: ctx.fiber.name })\n ctx.emit('actions/changed')\n return () => {\n this.store.delete(definition.name)\n ctx.emit('actions/changed')\n }\n }, `actions.define(${definition.name})`)\n }\n\n /** Lets the console relay client actions to dashboard tabs. */\n setClientRelay(relay: ClientRelay) {\n return this.ctx.effect(() => {\n this.relay = relay\n return () => {\n if (this.relay === relay) this.relay = undefined\n }\n }, 'actions.setClientRelay()')\n }\n\n has(name: string) {\n return this.store.has(name)\n }\n\n get(name: string): ActionInfo | undefined {\n const action = this.store.get(name)\n return action && this.info(action)\n }\n\n list(): ActionInfo[] {\n return [...this.store.values()].map((action) => this.info(action)).sort((a, b) => a.name.localeCompare(b.name))\n }\n\n private info(action: StoredAction): ActionInfo {\n action.schema ??= action.inputSchema ?? toJsonSchema(action.input)\n return {\n name: action.name,\n description: action.description,\n risk: action.risk,\n client: !!action.client,\n agent: action.agent !== false,\n plugin: action.plugin,\n inputSchema: action.schema,\n }\n }\n\n async call(name: string, input: unknown, caller: ActionCaller = { kind: 'internal' }): Promise<unknown> {\n const action = this.store.get(name)\n if (!action) throw new MushinError('not_found', `Unknown action: ${name}`)\n const parsed = action.input.safeParse(input ?? {})\n if (!parsed.success) {\n throw new MushinError('invalid_input', z.prettifyError(parsed.error), parsed.error.issues)\n }\n const start = Date.now()\n try {\n let result: unknown\n if (action.client) {\n if (!this.relay) throw new MushinError('unavailable', 'No dashboard is connected to run this action')\n result = await this.relay(name, parsed.data, caller)\n } else {\n result = await action.handler!(parsed.data, caller)\n }\n this.ctx.emit('actions/called', { name, caller, ok: true, durationMs: Date.now() - start })\n return result\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n this.ctx.emit('actions/called', { name, caller, ok: false, durationMs: Date.now() - start, error: message })\n throw error\n }\n }\n}\n\n/** OpenAI tool names allow only letters, digits, `_` and `-`, so dots become double underscores. */\nexport function toToolName(action: string) {\n return action.replaceAll('.', '__')\n}\n\nexport function fromToolName(tool: string) {\n return tool.replaceAll('__', '.')\n}\n"],"mappings":";;;;;AA6EA,SAAgB,aAAa,QAA+B;CAC1D,MAAM,EAAE,SAAS,GAAG,SAAS,EAAE,aAAa,QAAQ;EAAE,IAAI;EAAS,iBAAiB;CAAM,CAAC;CAC3F,OAAO;AACT;AAEA,MAAM,cAAc;;;;;AAMpB,IAAa,UAAb,cAA6B,QAAQ;CACnC,wBAAgB,IAAI,IAA0B;CAC9C;CAEA,YAAY,KAAc;EACxB,MAAM,KAAK,SAAS;CACtB;;CAGA,OAA+B,YAAoC;EACjE,IAAI,CAAC,YAAY,KAAK,WAAW,IAAI,GACnC,MAAM,IAAI,MAAM,wBAAwB,WAAW,KAAK,gDAAgD;EAE1G,IAAI,CAAC,WAAW,UAAU,CAAC,WAAW,SACpC,MAAM,IAAI,MAAM,WAAW,WAAW,KAAK,kBAAkB;EAE/D,MAAM,MAAM,KAAK;EACjB,OAAO,IAAI,aAAa;GACtB,IAAI,KAAK,MAAM,IAAI,WAAW,IAAI,GAChC,MAAM,IAAI,MAAM,WAAW,WAAW,KAAK,qBAAqB;GAElE,KAAK,MAAM,IAAI,WAAW,MAAM;IAAE,GAAI;IAAiC,QAAQ,IAAI,MAAM;GAAK,CAAC;GAC/F,IAAI,KAAK,iBAAiB;GAC1B,aAAa;IACX,KAAK,MAAM,OAAO,WAAW,IAAI;IACjC,IAAI,KAAK,iBAAiB;GAC5B;EACF,GAAG,kBAAkB,WAAW,KAAK,EAAE;CACzC;;CAGA,eAAe,OAAoB;EACjC,OAAO,KAAK,IAAI,aAAa;GAC3B,KAAK,QAAQ;GACb,aAAa;IACX,IAAI,KAAK,UAAU,OAAO,KAAK,QAAQ,KAAA;GACzC;EACF,GAAG,0BAA0B;CAC/B;CAEA,IAAI,MAAc;EAChB,OAAO,KAAK,MAAM,IAAI,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S,OAAO;GACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACrE,KAAK,IAAI,KAAK,kBAAkB;IAAE;IAAM;IAAQ,IAAI;IAAO,YAAY,KAAK,IAAI,IAAI;IAAO,OAAO;GAAQ,CAAC;GAC3G,MAAM;EACR;CACF;AACF;;AAGA,SAAgB,WAAW,QAAgB;CACzC,OAAO,OAAO,WAAW,KAAK,IAAI;AACpC;AAEA,SAAgB,aAAa,MAAc;CACzC,OAAO,KAAK,WAAW,MAAM,GAAG;AAClC"}
|
|
1
|
+
{"version":3,"file":"actions.js","names":[],"sources":["../src/actions.ts"],"sourcesContent":["import { Context, type Fiber, Service } from 'cordis'\nimport { z } from 'zod'\nimport { MushinError } from './errors'\n\ndeclare module 'cordis' {\n interface Context {\n actions: Actions\n /** The instance directory: config file, data and local plugins live here. */\n baseDir: string\n /** Set by `mushin test`: bots stay offline and nothing reaches the outside. The launcher always sets it. */\n offline: boolean\n }\n\n interface Events {\n 'actions/changed'(): void\n 'actions/called'(record: ActionCallRecord): void\n }\n}\n\nexport type Risk = 'read' | 'write' | 'dangerous'\n\nexport interface ActionCaller {\n kind: 'api' | 'fairy' | 'mcp' | 'internal'\n /** Fairy session id, when Fairy made the call. */\n session?: string\n /** Dashboard connection id, used to route client actions back to the right tab. */\n client?: string\n}\n\nexport interface ActionDefinition<S extends z.ZodType = z.ZodType, R = unknown> {\n /** Dotted lowercase name, such as `bots.create`. */\n name: string\n /** Written for Fairy: what the action does and what it returns. */\n description: string\n input: S\n /** JSON Schema shown instead of the one made from `input`, for tools described elsewhere (such as MCP tools). */\n inputSchema?: JsonSchema\n risk: Risk\n /** Client actions run in the dashboard; the server relays them to the caller's tab. */\n client?: boolean\n /**\n * False keeps the action away from Fairy: dashboard plumbing (editor previews, debugger\n * controls) that only makes sense next to a screen and would only distract the model.\n */\n fairy?: false\n /**\n * Whether Fairy asks before a call with this input, when the user set no policy for the action; undefined goes by\n * the risk (dangerous asks). Lets an action ask only for some inputs, such as a command that changes something.\n */\n approval?: (input: z.output<S>) => 'auto' | 'confirm' | undefined\n handler?: (input: z.output<S>, caller: ActionCaller) => R | Promise<R>\n}\n\nexport interface ActionInfo {\n name: string\n description: string\n risk: Risk\n client: boolean\n /** False when Fairy never sees the action; see `ActionDefinition.fairy`. */\n fairy: boolean\n plugin: string\n inputSchema: JsonSchema\n}\n\nexport interface ActionCallRecord {\n name: string\n caller: ActionCaller\n ok: boolean\n durationMs: number\n error?: string\n}\n\nexport type JsonSchema = Record<string, any>\n\nexport type ClientRelay = (name: string, input: unknown, caller: ActionCaller) => Promise<unknown>\n\ninterface StoredAction extends ActionDefinition {\n plugin: string\n /** The context that defined it, to tell which installed plugin it belongs to. */\n fiber: Fiber\n schema?: JsonSchema\n}\n\n/** Converts a zod schema to the JSON Schema shown to LLMs and dashboard forms. */\nexport function toJsonSchema(schema: z.ZodType): JsonSchema {\n const { $schema, ...rest } = z.toJSONSchema(schema, { io: 'input', unrepresentable: 'any' }) as JsonSchema\n return rest\n}\n\nconst namePattern = /^[a-z][a-zA-Z0-9]*(\\.[a-z][a-zA-Z0-9]*)+$/\n\n/**\n * The registry of typed operations. The HTTP API and Fairy both call actions,\n * so a feature a plugin exposes here is reachable from the dashboard and by conversation.\n */\nexport class Actions extends Service {\n private store = new Map<string, StoredAction>()\n private relay?: ClientRelay\n\n constructor(ctx: Context) {\n super(ctx, 'actions')\n }\n\n /** Registers an action. It is removed when the calling plugin unloads. */\n define<S extends z.ZodType, R>(definition: ActionDefinition<S, R>) {\n if (!namePattern.test(definition.name)) {\n throw new Error(`invalid action name \"${definition.name}\", expected a dotted name such as \"bots.create\"`)\n }\n if (!definition.client && !definition.handler) {\n throw new Error(`action \"${definition.name}\" needs a handler`)\n }\n const ctx = this.ctx\n return ctx.effect(() => {\n if (this.store.has(definition.name)) {\n throw new Error(`action \"${definition.name}\" is already defined`)\n }\n this.store.set(definition.name, { ...(definition as ActionDefinition), plugin: ctx.fiber.name, fiber: ctx.fiber })\n ctx.emit('actions/changed')\n return () => {\n this.store.delete(definition.name)\n ctx.emit('actions/changed')\n }\n }, `actions.define(${definition.name})`)\n }\n\n /** Lets the console relay client actions to dashboard tabs. */\n setClientRelay(relay: ClientRelay) {\n return this.ctx.effect(() => {\n this.relay = relay\n return () => {\n if (this.relay === relay) this.relay = undefined\n }\n }, 'actions.setClientRelay()')\n }\n\n has(name: string) {\n return this.store.has(name)\n }\n\n /** Whether Fairy should ask before this call, as the action decides from the input; see `ActionDefinition.approval`. */\n approval(name: string, input: unknown): 'auto' | 'confirm' | undefined {\n const action = this.store.get(name)\n if (!action?.approval) return\n const parsed = action.input.safeParse(input ?? {})\n return parsed.success ? action.approval(parsed.data) : undefined\n }\n\n /** The context that defined an action; `manager.packageOf` names its plugin. */\n fiberOf(name: string): Fiber | undefined {\n return this.store.get(name)?.fiber\n }\n\n get(name: string): ActionInfo | undefined {\n const action = this.store.get(name)\n return action && this.info(action)\n }\n\n list(): ActionInfo[] {\n return [...this.store.values()].map((action) => this.info(action)).sort((a, b) => a.name.localeCompare(b.name))\n }\n\n private info(action: StoredAction): ActionInfo {\n action.schema ??= action.inputSchema ?? toJsonSchema(action.input)\n return {\n name: action.name,\n description: action.description,\n risk: action.risk,\n client: !!action.client,\n fairy: action.fairy !== false,\n plugin: action.plugin,\n inputSchema: action.schema,\n }\n }\n\n async call(name: string, input: unknown, caller: ActionCaller = { kind: 'internal' }): Promise<unknown> {\n const action = this.store.get(name)\n if (!action) throw new MushinError('not_found', `Unknown action: ${name}`)\n const parsed = action.input.safeParse(input ?? {})\n if (!parsed.success) {\n throw new MushinError('invalid_input', z.prettifyError(parsed.error), parsed.error.issues)\n }\n const start = Date.now()\n try {\n let result: unknown\n if (action.client) {\n if (!this.relay) throw new MushinError('unavailable', 'No dashboard is connected to run this action')\n result = await this.relay(name, parsed.data, caller)\n } else {\n result = await action.handler!(parsed.data, caller)\n }\n this.ctx.emit('actions/called', { name, caller, ok: true, durationMs: Date.now() - start })\n return result\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n this.ctx.emit('actions/called', { name, caller, ok: false, durationMs: Date.now() - start, error: message })\n throw error\n }\n }\n}\n\n/** OpenAI tool names allow only letters, digits, `_` and `-`, so dots become double underscores. */\nexport function toToolName(action: string) {\n return action.replaceAll('.', '__')\n}\n\nexport function fromToolName(tool: string) {\n return tool.replaceAll('__', '.')\n}\n"],"mappings":";;;;;AAoFA,SAAgB,aAAa,QAA+B;CAC1D,MAAM,EAAE,SAAS,GAAG,SAAS,EAAE,aAAa,QAAQ;EAAE,IAAI;EAAS,iBAAiB;CAAM,CAAC;CAC3F,OAAO;AACT;AAEA,MAAM,cAAc;;;;;AAMpB,IAAa,UAAb,cAA6B,QAAQ;CACnC,wBAAgB,IAAI,IAA0B;CAC9C;CAEA,YAAY,KAAc;EACxB,MAAM,KAAK,SAAS;CACtB;;CAGA,OAA+B,YAAoC;EACjE,IAAI,CAAC,YAAY,KAAK,WAAW,IAAI,GACnC,MAAM,IAAI,MAAM,wBAAwB,WAAW,KAAK,gDAAgD;EAE1G,IAAI,CAAC,WAAW,UAAU,CAAC,WAAW,SACpC,MAAM,IAAI,MAAM,WAAW,WAAW,KAAK,kBAAkB;EAE/D,MAAM,MAAM,KAAK;EACjB,OAAO,IAAI,aAAa;GACtB,IAAI,KAAK,MAAM,IAAI,WAAW,IAAI,GAChC,MAAM,IAAI,MAAM,WAAW,WAAW,KAAK,qBAAqB;GAElE,KAAK,MAAM,IAAI,WAAW,MAAM;IAAE,GAAI;IAAiC,QAAQ,IAAI,MAAM;IAAM,OAAO,IAAI;GAAM,CAAC;GACjH,IAAI,KAAK,iBAAiB;GAC1B,aAAa;IACX,KAAK,MAAM,OAAO,WAAW,IAAI;IACjC,IAAI,KAAK,iBAAiB;GAC5B;EACF,GAAG,kBAAkB,WAAW,KAAK,EAAE;CACzC;;CAGA,eAAe,OAAoB;EACjC,OAAO,KAAK,IAAI,aAAa;GAC3B,KAAK,QAAQ;GACb,a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,iBAAiB,EAAE,cAAc,OAAO,KAAK,GAAG,OAAO,MAAM,MAAM;EAE3F,MAAM,QAAQ,KAAK,IAAI;EACvB,IAAI;GACF,IAAI;GACJ,IAAI,OAAO,QAAQ;IACjB,IAAI,CAAC,KAAK,OAAO,MAAM,IAAI,YAAY,eAAe,8CAA8C;IACpG,SAAS,MAAM,KAAK,MAAM,MAAM,OAAO,MAAM,MAAM;GACrD,OACE,SAAS,MAAM,OAAO,QAAS,OAAO,MAAM,MAAM;GAEpD,KAAK,IAAI,KAAK,kBAAkB;IAAE;IAAM;IAAQ,IAAI;IAAM,YAAY,KAAK,IAAI,IAAI;GAAM,CAAC;GAC1F,OAAO;EACT,SAAS,OAAO;GACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACrE,KAAK,IAAI,KAAK,kBAAkB;IAAE;IAAM;IAAQ,IAAI;IAAO,YAAY,KAAK,IAAI,IAAI;IAAO,OAAO;GAAQ,CAAC;GAC3G,MAAM;EACR;CACF;AACF;;AAGA,SAAgB,WAAW,QAAgB;CACzC,OAAO,OAAO,WAAW,KAAK,IAAI;AACpC;AAEA,SAAgB,aAAa,MAAc;CACzC,OAAO,KAAK,WAAW,MAAM,GAAG;AAClC"}
|
package/dist/env.js
CHANGED
|
@@ -4,7 +4,7 @@ import { readFile } from "node:fs/promises";
|
|
|
4
4
|
// src/env.ts
|
|
5
5
|
/**
|
|
6
6
|
* Secrets live in the instance's `.env` file. Configuration refers to them as `${NAME}`: the whole
|
|
7
|
-
* value of a field, so `mushin.config.json`, `data/` and anything shown to
|
|
7
|
+
* value of a field, so `mushin.config.json`, `data/` and anything shown to Fairy hold only names.
|
|
8
8
|
*/
|
|
9
9
|
const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
10
10
|
const REFERENCE = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/;
|
package/dist/env.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"env.js","names":[],"sources":["../src/env.ts"],"sourcesContent":["import { readFileSync } from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport { isMasked, writeTextAtomic } from './utils'\n\n/**\n * Secrets live in the instance's `.env` file. Configuration refers to them as `${NAME}`: the whole\n * value of a field, so `mushin.config.json`, `data/` and anything shown to the Agent hold only names.\n */\n\nconst NAME = /^[A-Za-z_][A-Za-z0-9_]*$/\nconst REFERENCE = /^\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}$/\n\n/** The variable a value refers to: `${DEEPSEEK_API_KEY}` gives `DEEPSEEK_API_KEY`. */\nexport function envReference(value: unknown) {\n return typeof value === 'string' ? REFERENCE.exec(value)?.[1] : undefined\n}\n\nexport function isEnvName(name: string) {\n return NAME.test(name)\n}\n\n/** A variable name made from words, such as a provider's name and a key: `DeepSeek`, `apiKey` gives `DEEPSEEK_API_KEY`. */\nexport function envName(...parts: string[]) {\n const words = parts\n // A camelCase key (`apiKey`) is split into words; a name such as `DeepSeek` stays one word.\n .map((part) => (/^[a-z]/.test(part) ? part.replace(/([a-z0-9])([A-Z])/g, '$1_$2') : part).normalize('NFKD').replace(/[^A-Za-z0-9]+/g, '_'))\n .join('_')\n .replace(/_+/g, '_')\n .replace(/^_|_$/g, '')\n .toUpperCase()\n return /^[A-Z_]/.test(words) ? words : `MUSHIN_${words}`\n}\n\n/** Parses `.env` text: `NAME=value` lines, `#` comments, single or double quotes, an optional `export`. */\nexport function parseEnv(text: string) {\n const values: Record<string, string> = {}\n for (const raw of text.split(/\\r?\\n/)) {\n const line = raw.trim()\n if (!line || line.startsWith('#')) continue\n const match = /^(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*(.*)$/.exec(line)\n if (!match) continue\n const [, name, rest] = match as unknown as [string, string, string]\n let value: string\n if (rest.startsWith('\"')) {\n const end = closingQuote(rest)\n value = rest.slice(1, end).replace(/\\\\([nr\"\\\\])/g, (_, char: string) => ({ n: '\\n', r: '\\r' })[char as 'n'] ?? char)\n } else if (rest.startsWith('\\'')) {\n const end = rest.indexOf('\\'', 1)\n value = rest.slice(1, end < 0 ? undefined : end)\n } else {\n value = rest.replace(/\\s+#.*$/, '').trim()\n }\n values[name] = value\n }\n return values\n}\n\nfunction closingQuote(text: string) {\n for (let i = 1; i < text.length; i++) {\n if (text[i] === '\\\\') i++\n else if (text[i] === '\"') return i\n }\n return text.length\n}\n\nfunction serialize(value: string) {\n if (/^[\\w.\\-+/=:@~,%]*$/.test(value)) return value\n return `\"${value.replace(/[\\\\\"]/g, '\\\\$&').replace(/\\n/g, '\\\\n').replace(/\\r/g, '\\\\r')}\"`\n}\n\n/** `.env` text with one variable set (or removed, for `undefined`), keeping every other line as it was. */\nexport function updateEnvText(text: string, name: string, value: string | undefined) {\n if (!isEnvName(name)) throw new Error(`\"${name}\" is not a valid environment variable name`)\n const lines = text ? text.replace(/\\r?\\n$/, '').split(/\\r?\\n/) : []\n const pattern = new RegExp(`^\\\\s*(?:export\\\\s+)?${name}\\\\s*=`)\n const at = lines.findIndex((line) => pattern.test(line))\n const next = lines.filter((line, index) => index === at || !pattern.test(line))\n const index = next.findIndex((line) => pattern.test(line))\n if (value === undefined) {\n if (index >= 0) next.splice(index, 1)\n } else if (index >= 0) {\n next[index] = `${name}=${serialize(value)}`\n } else {\n next.push(`${name}=${serialize(value)}`)\n }\n return next.length ? next.join('\\n') + '\\n' : ''\n}\n\n/** Names that some `.env` file put into `process.env`, so a later load may replace them. Everything else came from the shell. */\nconst loaded = new Set<string>()\n\n/**\n * One instance's `.env` file. Loading it copies its variables into `process.env`, where plugins,\n * MCP servers and terminal commands find them; a variable already set by the shell wins.\n */\nexport class EnvFile {\n private values: Record<string, string> = {}\n\n constructor(readonly path: string) {}\n\n /** Reads the file and copies its variables into `process.env`. A missing file is an empty one. */\n loadSync() {\n let text = ''\n try {\n text = readFileSync(this.path, 'utf8')\n } catch (error: any) {\n if (error?.code !== 'ENOENT') throw error\n }\n this.apply(parseEnv(text))\n return this\n }\n\n /** Reads the file again, for changes made by another process such as `mushin token reset`. */\n async reload() {\n const text = await readFile(this.path, 'utf8').catch((error) => {\n if (error?.code === 'ENOENT') return ''\n throw error\n })\n this.apply(parseEnv(text))\n }\n\n private apply(values: Record<string, string>) {\n this.values = values\n for (const [name, value] of Object.entries(values)) {\n if (process.env[name] === undefined || loaded.has(name)) {\n process.env[name] = value\n loaded.add(name)\n }\n }\n }\n\n /** True when the shell set the variable, so it overrides the file. */\n fromShell(name: string) {\n return process.env[name] !== undefined && !loaded.has(name)\n }\n\n /** The value of a variable: the shell's, else this file's. */\n get(name: string): string | undefined {\n return this.fromShell(name) ? process.env[name] : this.values[name]\n }\n\n /** Names this file defines. */\n names() {\n return Object.keys(this.values)\n }\n\n /** The value a field means: a `${NAME}` reference is looked up, anything else is itself. A missing variable is ''. */\n resolve<T>(value: T): T | string {\n const name = envReference(value)\n return name === undefined ? value : this.get(name) ?? ''\n }\n\n /** Sets a variable in the file and in `process.env`, unless the shell set it. */\n async set(name: string, value: string) {\n await this.write(name, value)\n }\n\n async delete(name: string) {\n await this.write(name, undefined)\n }\n\n /**\n * Puts a secret into the file under a name derived from `preferred` and returns its `${NAME}` reference.\n * A name already holding another value is not reused: `_2`, `_3` and so on are tried.\n */\n async store(preferred: string, value: string) {\n await this.reload()\n let name = preferred\n for (let n = 2; this.values[name] !== undefined && this.values[name] !== value; n++) name = `${preferred}_${n}`\n if (this.values[name] !== value) await this.set(name, value)\n return `\\${${name}}`\n }\n\n /**\n * Moves the plain values of `keys` in a config into the file and returns the config with `${NAME}`\n * references in their place. A value that replaces a reference in `previous` takes over that name;\n * other names are made from `name` and the key. Empty values, references and masked values\n * (`sk-…1234`, which the caller replaces) are left as they are.\n */\n async moveIn<T extends Record<string, any>>(config: T, options: { keys: Iterable<string>; name: string[]; previous?: Record<string, any> }): Promise<{ config: T; moved: string[] }> {\n const next: Record<string, any> = { ...config }\n const moved: string[] = []\n for (const key of options.keys) {\n const value = next[key]\n if (typeof value !== 'string' || !value || envReference(value) !== undefined || isMasked(value)) continue\n const taken = envReference(options.previous?.[key])\n if (taken !== undefined && !this.fromShell(taken)) {\n await this.set(taken, value)\n next[key] = `\\${${taken}}`\n } else {\n next[key] = await this.store(envName(...options.name, key), value)\n }\n moved.push(key)\n }\n return { config: next as T, moved }\n }\n\n /** A copy of a config with the `${NAME}` references of `keys` (all keys when omitted) replaced by their values. */\n resolveAll<T extends Record<string, any>>(config: T, keys?: Iterable<string>): T {\n const next: Record<string, any> = { ...config }\n for (const key of keys ?? Object.keys(next)) {\n if (key in next) next[key] = this.resolve(next[key])\n }\n return next as T\n }\n\n private async write(name: string, value: string | undefined) {\n let values: Record<string, string> = {}\n await writeTextAtomic(this.path, async () => {\n const text = await readFile(this.path, 'utf8').catch(() => '')\n const next = updateEnvText(text, name, value)\n values = parseEnv(next)\n return next\n }, { mode: 0o600 })\n this.values = values\n if (!this.fromShell(name)) {\n if (value === undefined) {\n delete process.env[name]\n loaded.delete(name)\n } else {\n process.env[name] = value\n loaded.add(name)\n }\n }\n }\n}\n\n/**\n * Replaces `${NAME}` values anywhere in a JSON-like value with the variables' values from `process.env`,\n * for plugin settings in `mushin.config.json`. The input is not changed.\n */\nexport function resolveEnvReferences<T>(value: T, env: NodeJS.ProcessEnv = process.env): T {\n const name = envReference(value)\n if (name !== undefined) return (env[name] ?? '') as T\n if (Array.isArray(value)) return value.map((item) => resolveEnvReferences(item, env)) as T\n if (value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype) {\n return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, resolveEnvReferences(item, env)])) as T\n }\n return value\n}\n"],"mappings":";;;;;;;;AASA,MAAM,OAAO;AACb,MAAM,YAAY;;AAGlB,SAAgB,aAAa,OAAgB;CAC3C,OAAO,OAAO,UAAU,WAAW,UAAU,KAAK,KAAK,CAAC,GAAG,KAAK,KAAA;AAClE;AAEA,SAAgB,UAAU,MAAc;CACtC,OAAO,KAAK,KAAK,IAAI;AACvB;;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AI,QAAQ;IACpB,OAAO,IAAI,IAAI;GACjB;EACF;CACF;AACF;;;;;AAMA,SAAgB,qBAAwB,OAAU,MAAyB,QAAQ,KAAQ;CACzF,MAAM,OAAO,aAAa,KAAK;CAC/B,IAAI,SAAS,KAAA,GAAW,OAAQ,IAAI,SAAS;CAC7C,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,KAAK,SAAS,qBAAqB,MAAM,GAAG,CAAC;CACpF,IAAI,SAAS,OAAO,UAAU,YAAY,OAAO,eAAe,KAAK,MAAM,OAAO,WAChF,OAAO,OAAO,YAAY,OAAO,QAAQ,KAAK,CAAC,CAAC,KAAK,CAAC,KAAK,UAAU,CAAC,KAAK,qBAAqB,MAAM,GAAG,CAAC,CAAC,CAAC;CAE9G,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"env.js","names":[],"sources":["../src/env.ts"],"sourcesContent":["import { readFileSync } from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport { isMasked, writeTextAtomic } from './utils'\n\n/**\n * Secrets live in the instance's `.env` file. Configuration refers to them as `${NAME}`: the whole\n * value of a field, so `mushin.config.json`, `data/` and anything shown to Fairy hold only names.\n */\n\nconst NAME = /^[A-Za-z_][A-Za-z0-9_]*$/\nconst REFERENCE = /^\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}$/\n\n/** The variable a value refers to: `${DEEPSEEK_API_KEY}` gives `DEEPSEEK_API_KEY`. */\nexport function envReference(value: unknown) {\n return typeof value === 'string' ? REFERENCE.exec(value)?.[1] : undefined\n}\n\nexport function isEnvName(name: string) {\n return NAME.test(name)\n}\n\n/** A variable name made from words, such as a provider's name and a key: `DeepSeek`, `apiKey` gives `DEEPSEEK_API_KEY`. */\nexport function envName(...parts: string[]) {\n const words = parts\n // A camelCase key (`apiKey`) is split into words; a name such as `DeepSeek` stays one word.\n .map((part) => (/^[a-z]/.test(part) ? part.replace(/([a-z0-9])([A-Z])/g, '$1_$2') : part).normalize('NFKD').replace(/[^A-Za-z0-9]+/g, '_'))\n .join('_')\n .replace(/_+/g, '_')\n .replace(/^_|_$/g, '')\n .toUpperCase()\n return /^[A-Z_]/.test(words) ? words : `MUSHIN_${words}`\n}\n\n/** Parses `.env` text: `NAME=value` lines, `#` comments, single or double quotes, an optional `export`. */\nexport function parseEnv(text: string) {\n const values: Record<string, string> = {}\n for (const raw of text.split(/\\r?\\n/)) {\n const line = raw.trim()\n if (!line || line.startsWith('#')) continue\n const match = /^(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*(.*)$/.exec(line)\n if (!match) continue\n const [, name, rest] = match as unknown as [string, string, string]\n let value: string\n if (rest.startsWith('\"')) {\n const end = closingQuote(rest)\n value = rest.slice(1, end).replace(/\\\\([nr\"\\\\])/g, (_, char: string) => ({ n: '\\n', r: '\\r' })[char as 'n'] ?? char)\n } else if (rest.startsWith('\\'')) {\n const end = rest.indexOf('\\'', 1)\n value = rest.slice(1, end < 0 ? undefined : end)\n } else {\n value = rest.replace(/\\s+#.*$/, '').trim()\n }\n values[name] = value\n }\n return values\n}\n\nfunction closingQuote(text: string) {\n for (let i = 1; i < text.length; i++) {\n if (text[i] === '\\\\') i++\n else if (text[i] === '\"') return i\n }\n return text.length\n}\n\nfunction serialize(value: string) {\n if (/^[\\w.\\-+/=:@~,%]*$/.test(value)) return value\n return `\"${value.replace(/[\\\\\"]/g, '\\\\$&').replace(/\\n/g, '\\\\n').replace(/\\r/g, '\\\\r')}\"`\n}\n\n/** `.env` text with one variable set (or removed, for `undefined`), keeping every other line as it was. */\nexport function updateEnvText(text: string, name: string, value: string | undefined) {\n if (!isEnvName(name)) throw new Error(`\"${name}\" is not a valid environment variable name`)\n const lines = text ? text.replace(/\\r?\\n$/, '').split(/\\r?\\n/) : []\n const pattern = new RegExp(`^\\\\s*(?:export\\\\s+)?${name}\\\\s*=`)\n const at = lines.findIndex((line) => pattern.test(line))\n const next = lines.filter((line, index) => index === at || !pattern.test(line))\n const index = next.findIndex((line) => pattern.test(line))\n if (value === undefined) {\n if (index >= 0) next.splice(index, 1)\n } else if (index >= 0) {\n next[index] = `${name}=${serialize(value)}`\n } else {\n next.push(`${name}=${serialize(value)}`)\n }\n return next.length ? next.join('\\n') + '\\n' : ''\n}\n\n/** Names that some `.env` file put into `process.env`, so a later load may replace them. Everything else came from the shell. */\nconst loaded = new Set<string>()\n\n/**\n * One instance's `.env` file. Loading it copies its variables into `process.env`, where plugins,\n * MCP servers and terminal commands find them; a variable already set by the shell wins.\n */\nexport class EnvFile {\n private values: Record<string, string> = {}\n\n constructor(readonly path: string) {}\n\n /** Reads the file and copies its variables into `process.env`. A missing file is an empty one. */\n loadSync() {\n let text = ''\n try {\n text = readFileSync(this.path, 'utf8')\n } catch (error: any) {\n if (error?.code !== 'ENOENT') throw error\n }\n this.apply(parseEnv(text))\n return this\n }\n\n /** Reads the file again, for changes made by another process such as `mushin token reset`. */\n async reload() {\n const text = await readFile(this.path, 'utf8').catch((error) => {\n if (error?.code === 'ENOENT') return ''\n throw error\n })\n this.apply(parseEnv(text))\n }\n\n private apply(values: Record<string, string>) {\n this.values = values\n for (const [name, value] of Object.entries(values)) {\n if (process.env[name] === undefined || loaded.has(name)) {\n process.env[name] = value\n loaded.add(name)\n }\n }\n }\n\n /** True when the shell set the variable, so it overrides the file. */\n fromShell(name: string) {\n return process.env[name] !== undefined && !loaded.has(name)\n }\n\n /** The value of a variable: the shell's, else this file's. */\n get(name: string): string | undefined {\n return this.fromShell(name) ? process.env[name] : this.values[name]\n }\n\n /** Names this file defines. */\n names() {\n return Object.keys(this.values)\n }\n\n /** The value a field means: a `${NAME}` reference is looked up, anything else is itself. A missing variable is ''. */\n resolve<T>(value: T): T | string {\n const name = envReference(value)\n return name === undefined ? value : this.get(name) ?? ''\n }\n\n /** Sets a variable in the file and in `process.env`, unless the shell set it. */\n async set(name: string, value: string) {\n await this.write(name, value)\n }\n\n async delete(name: string) {\n await this.write(name, undefined)\n }\n\n /**\n * Puts a secret into the file under a name derived from `preferred` and returns its `${NAME}` reference.\n * A name already holding another value is not reused: `_2`, `_3` and so on are tried.\n */\n async store(preferred: string, value: string) {\n await this.reload()\n let name = preferred\n for (let n = 2; this.values[name] !== undefined && this.values[name] !== value; n++) name = `${preferred}_${n}`\n if (this.values[name] !== value) await this.set(name, value)\n return `\\${${name}}`\n }\n\n /**\n * Moves the plain values of `keys` in a config into the file and returns the config with `${NAME}`\n * references in their place. A value that replaces a reference in `previous` takes over that name;\n * other names are made from `name` and the key. Empty values, references and masked values\n * (`sk-…1234`, which the caller replaces) are left as they are.\n */\n async moveIn<T extends Record<string, any>>(config: T, options: { keys: Iterable<string>; name: string[]; previous?: Record<string, any> }): Promise<{ config: T; moved: string[] }> {\n const next: Record<string, any> = { ...config }\n const moved: string[] = []\n for (const key of options.keys) {\n const value = next[key]\n if (typeof value !== 'string' || !value || envReference(value) !== undefined || isMasked(value)) continue\n const taken = envReference(options.previous?.[key])\n if (taken !== undefined && !this.fromShell(taken)) {\n await this.set(taken, value)\n next[key] = `\\${${taken}}`\n } else {\n next[key] = await this.store(envName(...options.name, key), value)\n }\n moved.push(key)\n }\n return { config: next as T, moved }\n }\n\n /** A copy of a config with the `${NAME}` references of `keys` (all keys when omitted) replaced by their values. */\n resolveAll<T extends Record<string, any>>(config: T, keys?: Iterable<string>): T {\n const next: Record<string, any> = { ...config }\n for (const key of keys ?? Object.keys(next)) {\n if (key in next) next[key] = this.resolve(next[key])\n }\n return next as T\n }\n\n private async write(name: string, value: string | undefined) {\n let values: Record<string, string> = {}\n await writeTextAtomic(this.path, async () => {\n const text = await readFile(this.path, 'utf8').catch(() => '')\n const next = updateEnvText(text, name, value)\n values = parseEnv(next)\n return next\n }, { mode: 0o600 })\n this.values = values\n if (!this.fromShell(name)) {\n if (value === undefined) {\n delete process.env[name]\n loaded.delete(name)\n } else {\n process.env[name] = value\n loaded.add(name)\n }\n }\n }\n}\n\n/**\n * Replaces `${NAME}` values anywhere in a JSON-like value with the variables' values from `process.env`,\n * for plugin settings in `mushin.config.json`. The input is not changed.\n */\nexport function resolveEnvReferences<T>(value: T, env: NodeJS.ProcessEnv = process.env): T {\n const name = envReference(value)\n if (name !== undefined) return (env[name] ?? '') as T\n if (Array.isArray(value)) return value.map((item) => resolveEnvReferences(item, env)) as T\n if (value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype) {\n return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, resolveEnvReferences(item, env)])) as T\n }\n return value\n}\n"],"mappings":";;;;;;;;AASA,MAAM,OAAO;AACb,MAAM,YAAY;;AAGlB,SAAgB,aAAa,OAAgB;CAC3C,OAAO,OAAO,UAAU,WAAW,UAAU,KAAK,KAAK,CAAC,GAAG,KAAK,KAAA;AAClE;AAEA,SAAgB,UAAU,MAAc;CACtC,OAAO,KAAK,KAAK,IAAI;AACvB;;AAGA,SAAgB,QAAQ,GAAG,OAAiB;CAC1C,MAAM,QAAQ,MAEX,KAAK,UAAU,SAAS,KAAK,IAAI,IAAI,KAAK,QAAQ,sBAAsB,OAAO,IAAI,KAAA,CAAM,UAAU,MAAM,CAAC,CAAC,QAAQ,kBAAkB,GAAG,CAAC,CAAC,CAC1I,KAAK,GAAG,CAAC,CACT,QAAQ,OAAO,GAAG,CAAC,CACnB,QAAQ,UAAU,EAAE,CAAC,CACrB,YAAY;CACf,OAAO,UAAU,KAAK,KAAK,IAAI,QAAQ,UAAU;AACnD;;AAGA,SAAgB,SAAS,MAAc;CACrC,MAAM,SAAiC,CAAC;CACxC,KAAK,MAAM,OAAO,KAAK,MAAM,OAAO,GAAG;EACrC,MAAM,OAAO,IAAI,KAAK;EACtB,IAAI,CAAC,QAAQ,KAAK,WAAW,GAAG,GAAG;EACnC,MAAM,QAAQ,sDAAsD,KAAK,IAAI;EAC7E,IAAI,CAAC,OAAO;EACZ,MAAM,GAAG,MAAM,QAAQ;EACvB,IAAI;EACJ,IAAI,KAAK,WAAW,IAAG,GAAG;GACxB,MAAM,MAAM,aAAa,IAAI;GAC7B,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AK,IAAI,GACxC,IAAI,OAAO,MAAM,KAAK,OAAO,KAAK,QAAQ,KAAK,IAAI;EAErD,OAAO;CACT;CAEA,MAAc,MAAM,MAAc,OAA2B;EAC3D,IAAI,SAAiC,CAAC;EACtC,MAAM,gBAAgB,KAAK,MAAM,YAAY;GAE3C,MAAM,OAAO,cAAc,MADR,SAAS,KAAK,MAAM,MAAM,CAAC,CAAC,YAAY,EAAE,GAC5B,MAAM,KAAK;GAC5C,SAAS,SAAS,IAAI;GACtB,OAAO;EACT,GAAG,EAAE,MAAM,IAAM,CAAC;EAClB,KAAK,SAAS;EACd,IAAI,CAAC,KAAK,UAAU,IAAI,GAAG;GACzB,IAAI,UAAU,KAAA,GAAW;IACvB,OAAO,QAAQ,IAAI;IACnB,OAAO,OAAO,IAAI;GACpB,OAAO;IACL,QAAQ,IAAI,QAAQ;IACpB,OAAO,IAAI,IAAI;GACjB;EACF;CACF;AACF;;;;;AAMA,SAAgB,qBAAwB,OAAU,MAAyB,QAAQ,KAAQ;CACzF,MAAM,OAAO,aAAa,KAAK;CAC/B,IAAI,SAAS,KAAA,GAAW,OAAQ,IAAI,SAAS;CAC7C,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,KAAK,SAAS,qBAAqB,MAAM,GAAG,CAAC;CACpF,IAAI,SAAS,OAAO,UAAU,YAAY,OAAO,eAAe,KAAK,MAAM,OAAO,WAChF,OAAO,OAAO,YAAY,OAAO,QAAQ,KAAK,CAAC,CAAC,KAAK,CAAC,KAAK,UAAU,CAAC,KAAK,qBAAqB,MAAM,GAAG,CAAC,CAAC,CAAC;CAE9G,OAAO;AACT"}
|
package/dist/errors.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export type ErrorCode = 'not_found' | 'invalid_input' | 'conflict' | 'forbidden' | 'unauthorized' | 'unavailable' | 'failed';
|
|
2
|
-
/** An error whose message is safe to show to users and to
|
|
2
|
+
/** An error whose message is safe to show to users and to Fairy. */
|
|
3
3
|
export declare class MushinError extends Error {
|
|
4
4
|
code: ErrorCode;
|
|
5
5
|
details?: unknown | undefined;
|
package/dist/errors.js
CHANGED
|
@@ -8,7 +8,7 @@ const statusCodes = {
|
|
|
8
8
|
unavailable: 503,
|
|
9
9
|
failed: 500
|
|
10
10
|
};
|
|
11
|
-
/** An error whose message is safe to show to users and to
|
|
11
|
+
/** An error whose message is safe to show to users and to Fairy. */
|
|
12
12
|
var MushinError = class extends Error {
|
|
13
13
|
code;
|
|
14
14
|
details;
|
package/dist/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["export type ErrorCode =\n | 'not_found'\n | 'invalid_input'\n | 'conflict'\n | 'forbidden'\n | 'unauthorized'\n | 'unavailable'\n | 'failed'\n\nconst statusCodes: Record<ErrorCode, number> = {\n not_found: 404,\n invalid_input: 400,\n conflict: 409,\n forbidden: 403,\n unauthorized: 401,\n unavailable: 503,\n failed: 500,\n}\n\n/** An error whose message is safe to show to users and to
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["export type ErrorCode =\n | 'not_found'\n | 'invalid_input'\n | 'conflict'\n | 'forbidden'\n | 'unauthorized'\n | 'unavailable'\n | 'failed'\n\nconst statusCodes: Record<ErrorCode, number> = {\n not_found: 404,\n invalid_input: 400,\n conflict: 409,\n forbidden: 403,\n unauthorized: 401,\n unavailable: 503,\n failed: 500,\n}\n\n/** An error whose message is safe to show to users and to Fairy. */\nexport class MushinError extends Error {\n name = 'MushinError'\n\n constructor(public code: ErrorCode, message: string, public details?: unknown) {\n super(message)\n }\n\n get status() {\n return statusCodes[this.code]\n }\n\n toJSON() {\n return { code: this.code, message: this.message, details: this.details }\n }\n}\n\nexport function toErrorPayload(error: unknown) {\n if (error instanceof MushinError) return error.toJSON()\n if (error instanceof Error) return { code: 'failed' as const, message: error.message }\n return { code: 'failed' as const, message: String(error) }\n}\n"],"mappings":";AASA,MAAM,cAAyC;CAC7C,WAAW;CACX,eAAe;CACf,UAAU;CACV,WAAW;CACX,cAAc;CACd,aAAa;CACb,QAAQ;AACV;;AAGA,IAAa,cAAb,cAAiC,MAAM;CAGlB;CAAyC;CAF5D,OAAO;CAEP,YAAY,MAAwB,SAAiB,SAA0B;EAC7E,MAAM,OAAO;EADI,KAAA,OAAA;EAAyC,KAAA,UAAA;CAE5D;CAEA,IAAI,SAAS;EACX,OAAO,YAAY,KAAK;CAC1B;CAEA,SAAS;EACP,OAAO;GAAE,MAAM,KAAK;GAAM,SAAS,KAAK;GAAS,SAAS,KAAK;EAAQ;CACzE;AACF;AAEA,SAAgB,eAAe,OAAgB;CAC7C,IAAI,iBAAiB,aAAa,OAAO,MAAM,OAAO;CACtD,IAAI,iBAAiB,OAAO,OAAO;EAAE,MAAM;EAAmB,SAAS,MAAM;CAAQ;CACrF,OAAO;EAAE,MAAM;EAAmB,SAAS,OAAO,KAAK;CAAE;AAC3D"}
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { ActionCallRecord, ActionCaller, ActionDefinition, ActionInfo, Actions,
|
|
|
2
2
|
import { DependencyGraph, DependencyProblem, DependencyReport, DependencyState, DependentState, DisablePlan, EnablePlan, EntryLike, dependencyReport, injectedServices, loadOrder, planDisable, planEnable, providerOf, undeclaredServices, unmet } from "./dependencies.js";
|
|
3
3
|
import { EnvFile, envName, envReference, isEnvName, parseEnv, resolveEnvReferences, updateEnvText } from "./env.js";
|
|
4
4
|
import { ErrorCode, MushinError, toErrorPayload } from "./errors.js";
|
|
5
|
-
import { InstanceConfig, ManagerOptions, MissingDependency, PluginEntry, PluginManager, PluginStatus, describeMissing, fiberError, fiberStatus, knownManifest, maskSecrets, pluginSchema, restoreMasked, secretFields, unwrapPlugin, validatePluginConfig } from "./manager.js";
|
|
5
|
+
import { InstanceConfig, ManagerOptions, MissingDependency, PluginEntry, PluginManager, PluginProvides, PluginStatus, ProvidedItem, ProvidesSource, describeMissing, fiberError, fiberStatus, knownManifest, maskSecrets, pluginSchema, restoreMasked, secretFields, unwrapPlugin, validatePluginConfig } from "./manager.js";
|
|
6
6
|
import { CatalogEntry, DependencySpec, LocalizedText, MUSHIN_VERSION, PluginManifest, currentPackageName, dependencyPlugins, manifestProblems, readPackageJson, resolvePackageEntry, scanCatalog } from "./manifest.js";
|
|
7
7
|
import { ChannelInfo, Content, KnowledgeSource, MessageRecord, MessageType, Provenance, Segment, UserInfo, messageType, seg, segmentsToText, toSegments } from "./message.js";
|
|
8
8
|
import { compareVersions, parseVersion, satisfies, validRange } from "./semver.js";
|
|
@@ -10,4 +10,4 @@ import { FieldDisplay, FieldText, LOG_TAGS, LogTag, field, isMasked, localize, l
|
|
|
10
10
|
import { UsageEvent, UsageScope, usage } from "./usage.js";
|
|
11
11
|
import { z } from "zod";
|
|
12
12
|
export * from "cordis";
|
|
13
|
-
export { ActionCallRecord, ActionCaller, ActionDefinition, ActionInfo, Actions, CatalogEntry, ChannelInfo, ClientRelay, Content, DependencyGraph, DependencyProblem, DependencyReport, DependencySpec, DependencyState, DependentState, DisablePlan, EnablePlan, EntryLike, EnvFile, ErrorCode, FieldDisplay, FieldText, InstanceConfig, JsonSchema, KnowledgeSource, LOG_TAGS, LocalizedText, LogTag, MUSHIN_VERSION, ManagerOptions, MessageRecord, MessageType, MissingDependency, MushinError, PluginEntry, PluginManager, PluginManifest, PluginStatus, Provenance, Risk, Segment, UsageEvent, UsageScope, UserInfo, compareVersions, currentPackageName, dependencyPlugins, dependencyReport, describeMissing, envName, envReference, fiberError, fiberStatus, field, fromToolName, injectedServices, isEnvName, isMasked, knownManifest, loadOrder, localize, logTag, manifestProblems, mask, maskSecrets, messageType, parseEnv, parseVersion, planDisable, planEnable, pluginSchema, providerOf, randomId, readJson, readPackageJson, resolveEnvReferences, resolvePackageEntry, restoreMasked, satisfies, scanCatalog, secretFields, seg, segmentsToText, toErrorPayload, toJsonSchema, toSegments, toToolName, undeclaredServices, unmet, unwrapPlugin, updateEnvText, usage, validRange, validatePluginConfig, writeJsonAtomic, writeTextAtomic, z };
|
|
13
|
+
export { ActionCallRecord, ActionCaller, ActionDefinition, ActionInfo, Actions, CatalogEntry, ChannelInfo, ClientRelay, Content, DependencyGraph, DependencyProblem, DependencyReport, DependencySpec, DependencyState, DependentState, DisablePlan, EnablePlan, EntryLike, EnvFile, ErrorCode, FieldDisplay, FieldText, InstanceConfig, JsonSchema, KnowledgeSource, LOG_TAGS, LocalizedText, LogTag, MUSHIN_VERSION, ManagerOptions, MessageRecord, MessageType, MissingDependency, MushinError, PluginEntry, PluginManager, PluginManifest, PluginProvides, PluginStatus, Provenance, ProvidedItem, ProvidesSource, Risk, Segment, UsageEvent, UsageScope, UserInfo, compareVersions, currentPackageName, dependencyPlugins, dependencyReport, describeMissing, envName, envReference, fiberError, fiberStatus, field, fromToolName, injectedServices, isEnvName, isMasked, knownManifest, loadOrder, localize, logTag, manifestProblems, mask, maskSecrets, messageType, parseEnv, parseVersion, planDisable, planEnable, pluginSchema, providerOf, randomId, readJson, readPackageJson, resolveEnvReferences, resolvePackageEntry, restoreMasked, satisfies, scanCatalog, secretFields, seg, segmentsToText, toErrorPayload, toJsonSchema, toSegments, toToolName, undeclaredServices, unmet, unwrapPlugin, updateEnvText, usage, validRange, validatePluginConfig, writeJsonAtomic, writeTextAtomic, z };
|
package/dist/manager.d.ts
CHANGED
|
@@ -18,14 +18,21 @@ export interface PluginEntry {
|
|
|
18
18
|
}
|
|
19
19
|
export interface InstanceConfig {
|
|
20
20
|
plugins: PluginEntry[];
|
|
21
|
+
/**
|
|
22
|
+
* Folders besides the app's plugins/ that hold local plugin folders, such as one a development copy and an
|
|
23
|
+
* instance share. Relative paths start at the app folder; `~` is the home folder.
|
|
24
|
+
*/
|
|
25
|
+
pluginDirs?: string[];
|
|
21
26
|
}
|
|
22
27
|
export interface ManagerOptions {
|
|
23
28
|
configPath: string;
|
|
24
29
|
config: InstanceConfig;
|
|
25
30
|
/** `node_modules` directories searched for plugin packages. */
|
|
26
31
|
nodeModules: string[];
|
|
27
|
-
/** Directories holding local plugin folders. */
|
|
32
|
+
/** Directories holding local plugin folders; the config's `pluginDirs` come after them. */
|
|
28
33
|
localDirs: string[];
|
|
34
|
+
/** The app folder, where relative `pluginDirs` start; the config file's folder by default. */
|
|
35
|
+
baseDir?: string;
|
|
29
36
|
/** Imports a module by specifier; supplied by the launcher so bare names resolve from its location. */
|
|
30
37
|
importer: (specifier: string) => Promise<any>;
|
|
31
38
|
}
|
|
@@ -42,6 +49,24 @@ export interface MissingDependency {
|
|
|
42
49
|
}
|
|
43
50
|
export declare function fiberStatus(fiber: Fiber | undefined): PluginStatus;
|
|
44
51
|
export declare function fiberError(fiber: Fiber | undefined): string | undefined;
|
|
52
|
+
/** Something a running plugin adds besides actions: a chat command, a flow node or a bot adapter. */
|
|
53
|
+
export interface ProvidedItem {
|
|
54
|
+
kind: 'command' | 'node' | 'adapter';
|
|
55
|
+
name: string;
|
|
56
|
+
/** The context that added it; `packageOf` finds its plugin from there. */
|
|
57
|
+
fiber?: Fiber;
|
|
58
|
+
/** The package, when the source knows it better than the context does (a bot plugin runs inside the bots plugin). */
|
|
59
|
+
package?: string;
|
|
60
|
+
}
|
|
61
|
+
/** Lists what running plugins add; see `PluginManager.defineProvides`. */
|
|
62
|
+
export type ProvidesSource = () => Iterable<ProvidedItem>;
|
|
63
|
+
/** What one plugin adds, by name: tools are the actions Fairy and the API can call. */
|
|
64
|
+
export interface PluginProvides {
|
|
65
|
+
commands: string[];
|
|
66
|
+
nodes: string[];
|
|
67
|
+
tools: string[];
|
|
68
|
+
adapters: string[];
|
|
69
|
+
}
|
|
45
70
|
/** Picks the plugin out of a module: a default export, or the module namespace itself. */
|
|
46
71
|
export declare function unwrapPlugin(mod: any): Plugin;
|
|
47
72
|
/** JSON Schema of a plugin's zod `Config`, if it has one. */
|
|
@@ -69,6 +94,11 @@ export declare class PluginManager extends Service {
|
|
|
69
94
|
private catalogList;
|
|
70
95
|
/** Entries that were not started because a dependency is missing or they form a cycle. */
|
|
71
96
|
private blocked;
|
|
97
|
+
/** Entries whose package could not be imported, such as one that is no longer installed. */
|
|
98
|
+
private loadErrors;
|
|
99
|
+
/** The version of each local plugin folder's files, so a reload after an edit imports them afresh. */
|
|
100
|
+
private versions;
|
|
101
|
+
private providesSources;
|
|
72
102
|
constructor(ctx: Context, options: ManagerOptions);
|
|
73
103
|
private envFile?;
|
|
74
104
|
/** The instance's `.env`, where secret config fields are kept. */
|
|
@@ -79,6 +109,8 @@ export declare class PluginManager extends Service {
|
|
|
79
109
|
private get logger();
|
|
80
110
|
get entries(): PluginEntry[];
|
|
81
111
|
[Service.init](): AsyncGenerator<import("cordis").Disposable<Promise<void>> | (() => boolean), void, unknown>;
|
|
112
|
+
/** Every folder local plugins load from: the launcher's, then the config's `pluginDirs`. */
|
|
113
|
+
get localDirs(): string[];
|
|
82
114
|
catalog(refresh?: boolean): Promise<CatalogEntry[]>;
|
|
83
115
|
/** The installed packages as last scanned, without waiting for a rescan. */
|
|
84
116
|
get catalogSnapshot(): readonly CatalogEntry[];
|
|
@@ -87,6 +119,12 @@ export declare class PluginManager extends Service {
|
|
|
87
119
|
/** The catalog and entries, for dependency questions. */
|
|
88
120
|
graph(refresh?: boolean): Promise<DependencyGraph>;
|
|
89
121
|
private graphNow;
|
|
122
|
+
/** The package of the app plugin a context belongs to, found by walking up from it to an entry's context. */
|
|
123
|
+
packageOf(fiber: Fiber | undefined): string | undefined;
|
|
124
|
+
/** Lists what plugins add besides actions (flow nodes, chat commands, adapters), for `plugins.provides`. Removed when the caller unloads. */
|
|
125
|
+
defineProvides(source: ProvidesSource): import("cordis").Disposable<Promise<void>>;
|
|
126
|
+
/** What each running plugin adds, by package: its chat commands, flow nodes, tools (actions) and adapters. */
|
|
127
|
+
provides(): Record<string, PluginProvides>;
|
|
90
128
|
/** Dependencies, dependents and what enabling or disabling the package would take. */
|
|
91
129
|
dependencies(name: string): Promise<{
|
|
92
130
|
missing?: MissingDependency[] | undefined;
|
|
@@ -103,8 +141,27 @@ export declare class PluginManager extends Service {
|
|
|
103
141
|
dependents: DependentState[];
|
|
104
142
|
}>;
|
|
105
143
|
findPackage(name: string): Promise<CatalogEntry | undefined>;
|
|
106
|
-
/**
|
|
144
|
+
/**
|
|
145
|
+
* Imports a plugin package. Catalogued packages load from their own directory. A local one carries the version of
|
|
146
|
+
* its files in the URL (`?mushin-v=<n>`), which goes up when a file changed, so loading it again runs the new code.
|
|
147
|
+
*/
|
|
107
148
|
loadPlugin(name: string): Promise<Plugin>;
|
|
149
|
+
/** The local plugin folders, each with the plugins found in it. */
|
|
150
|
+
folders(): Promise<{
|
|
151
|
+
path: string;
|
|
152
|
+
/** From the config's pluginDirs, rather than the app's own plugins/ folder. */
|
|
153
|
+
extra: boolean;
|
|
154
|
+
exists: boolean;
|
|
155
|
+
plugins: string[];
|
|
156
|
+
}[]>;
|
|
157
|
+
/** Sets the config's `pluginDirs`, rescans, and starts enabled entries whose package turned up. */
|
|
158
|
+
setFolders(dirs: string[]): Promise<{
|
|
159
|
+
path: string;
|
|
160
|
+
/** From the config's pluginDirs, rather than the app's own plugins/ folder. */
|
|
161
|
+
extra: boolean;
|
|
162
|
+
exists: boolean;
|
|
163
|
+
plugins: string[];
|
|
164
|
+
}[]>;
|
|
108
165
|
get(id: string): PluginEntry | undefined;
|
|
109
166
|
status(id: string): {
|
|
110
167
|
status: PluginStatus;
|
|
@@ -136,6 +193,16 @@ export declare class PluginManager extends Service {
|
|
|
136
193
|
}): Promise<PluginEntry>;
|
|
137
194
|
private assertNotEssential;
|
|
138
195
|
private disableOne;
|
|
196
|
+
/**
|
|
197
|
+
* Takes an entry out of the config, with its settings. An enabled entry is disabled first, under the same
|
|
198
|
+
* rules as `disable`: essential plugins stay, and plugins that require it are refused unless `cascade` is set.
|
|
199
|
+
*/
|
|
200
|
+
remove(id: string, options?: {
|
|
201
|
+
cascade?: boolean;
|
|
202
|
+
}): Promise<{
|
|
203
|
+
id: string;
|
|
204
|
+
package: string;
|
|
205
|
+
}>;
|
|
139
206
|
/** Starts entries that were held back for a missing dependency, once it is there. */
|
|
140
207
|
private retryBlocked;
|
|
141
208
|
configure(id: string, input: Record<string, any>): Promise<PluginEntry>;
|
package/dist/manager.js
CHANGED
|
@@ -6,7 +6,9 @@ import { MUSHIN_VERSION, manifestProblems, readPackageJson, resolvePackageEntry,
|
|
|
6
6
|
import { isMasked, mask, writeJsonAtomic } from "./utils.js";
|
|
7
7
|
import { Service } from "cordis";
|
|
8
8
|
import { z } from "zod";
|
|
9
|
-
import {
|
|
9
|
+
import { readdir, stat } from "node:fs/promises";
|
|
10
|
+
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
11
|
+
import { homedir } from "node:os";
|
|
10
12
|
import { pathToFileURL } from "node:url";
|
|
11
13
|
// src/manager.ts
|
|
12
14
|
const fiberStates = [
|
|
@@ -26,6 +28,11 @@ function fiberError(fiber) {
|
|
|
26
28
|
if (!error) return;
|
|
27
29
|
return error instanceof Error ? error.message : String(error);
|
|
28
30
|
}
|
|
31
|
+
const PROVIDES_KEY = {
|
|
32
|
+
command: "commands",
|
|
33
|
+
node: "nodes",
|
|
34
|
+
adapter: "adapters"
|
|
35
|
+
};
|
|
29
36
|
/** Picks the plugin out of a module: a default export, or the module namespace itself. */
|
|
30
37
|
function unwrapPlugin(mod) {
|
|
31
38
|
const value = mod?.default;
|
|
@@ -97,6 +104,11 @@ var PluginManager = class extends Service {
|
|
|
97
104
|
catalogList = [];
|
|
98
105
|
/** Entries that were not started because a dependency is missing or they form a cycle. */
|
|
99
106
|
blocked = /* @__PURE__ */ new Map();
|
|
107
|
+
/** Entries whose package could not be imported, such as one that is no longer installed. */
|
|
108
|
+
loadErrors = /* @__PURE__ */ new Map();
|
|
109
|
+
/** The version of each local plugin folder's files, so a reload after an edit imports them afresh. */
|
|
110
|
+
versions = /* @__PURE__ */ new Map();
|
|
111
|
+
providesSources = /* @__PURE__ */ new Set();
|
|
100
112
|
constructor(ctx, options) {
|
|
101
113
|
super(ctx, "manager");
|
|
102
114
|
this.options = options;
|
|
@@ -149,9 +161,15 @@ var PluginManager = class extends Service {
|
|
|
149
161
|
this.logger.error("failed to load %s: %s", entry.package, error);
|
|
150
162
|
});
|
|
151
163
|
}
|
|
164
|
+
/** Every folder local plugins load from: the launcher's, then the config's `pluginDirs`. */
|
|
165
|
+
get localDirs() {
|
|
166
|
+
const base = this.options.baseDir ?? dirname(this.options.configPath);
|
|
167
|
+
const extra = (this.options.config.pluginDirs ?? []).filter(Boolean).map((dir) => resolve(base, dir.replace(/^~(?=$|[\\/])/, homedir())));
|
|
168
|
+
return [.../* @__PURE__ */ new Set([...this.options.localDirs, ...extra])];
|
|
169
|
+
}
|
|
152
170
|
catalog(refresh = false) {
|
|
153
171
|
if (refresh || !this.catalogCache) {
|
|
154
|
-
this.catalogCache = scanCatalog(this.options.nodeModules, this.
|
|
172
|
+
this.catalogCache = scanCatalog(this.options.nodeModules, this.localDirs);
|
|
155
173
|
this.catalogCache.then((list) => this.catalogList = list, () => {});
|
|
156
174
|
}
|
|
157
175
|
return this.catalogCache;
|
|
@@ -176,6 +194,53 @@ var PluginManager = class extends Service {
|
|
|
176
194
|
known: knownManifest
|
|
177
195
|
};
|
|
178
196
|
}
|
|
197
|
+
/** The package of the app plugin a context belongs to, found by walking up from it to an entry's context. */
|
|
198
|
+
packageOf(fiber) {
|
|
199
|
+
if (!fiber) return;
|
|
200
|
+
const owners = /* @__PURE__ */ new Map();
|
|
201
|
+
for (const [id, tracked] of this.fibers) {
|
|
202
|
+
const entry = this.entries.find((item) => item.id === id);
|
|
203
|
+
if (entry) owners.set(tracked.ctx.fiber, entry.package);
|
|
204
|
+
}
|
|
205
|
+
let current = fiber;
|
|
206
|
+
while (current) {
|
|
207
|
+
const found = owners.get(current);
|
|
208
|
+
if (found) return found;
|
|
209
|
+
const parent = current.parent?.fiber;
|
|
210
|
+
if (!parent || parent === current) return;
|
|
211
|
+
current = parent;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
/** Lists what plugins add besides actions (flow nodes, chat commands, adapters), for `plugins.provides`. Removed when the caller unloads. */
|
|
215
|
+
defineProvides(source) {
|
|
216
|
+
return this.ctx.effect(() => {
|
|
217
|
+
this.providesSources.add(source);
|
|
218
|
+
return () => this.providesSources.delete(source);
|
|
219
|
+
}, "manager.defineProvides()");
|
|
220
|
+
}
|
|
221
|
+
/** What each running plugin adds, by package: its chat commands, flow nodes, tools (actions) and adapters. */
|
|
222
|
+
provides() {
|
|
223
|
+
const result = {};
|
|
224
|
+
const add = (pkg, key, name) => {
|
|
225
|
+
if (!pkg) return;
|
|
226
|
+
const item = result[pkg] ??= {
|
|
227
|
+
commands: [],
|
|
228
|
+
nodes: [],
|
|
229
|
+
tools: [],
|
|
230
|
+
adapters: []
|
|
231
|
+
};
|
|
232
|
+
if (!item[key].includes(name)) item[key].push(name);
|
|
233
|
+
};
|
|
234
|
+
const actions = this.home.actions;
|
|
235
|
+
for (const action of actions.list()) if (action.fairy) add(this.packageOf(actions.fiberOf(action.name)), "tools", action.name);
|
|
236
|
+
for (const source of this.providesSources) try {
|
|
237
|
+
for (const item of source()) add(item.package ?? this.packageOf(item.fiber), PROVIDES_KEY[item.kind], item.name);
|
|
238
|
+
} catch (error) {
|
|
239
|
+
this.logger.debug("listing what plugins provide failed: %s", error);
|
|
240
|
+
}
|
|
241
|
+
for (const item of Object.values(result)) for (const list of Object.values(item)) list.sort();
|
|
242
|
+
return result;
|
|
243
|
+
}
|
|
179
244
|
/** Dependencies, dependents and what enabling or disabling the package would take. */
|
|
180
245
|
async dependencies(name) {
|
|
181
246
|
const graph = await this.graph();
|
|
@@ -190,13 +255,53 @@ var PluginManager = class extends Service {
|
|
|
190
255
|
async findPackage(name) {
|
|
191
256
|
return (await this.catalog()).find((entry) => entry.package === name);
|
|
192
257
|
}
|
|
193
|
-
/**
|
|
258
|
+
/**
|
|
259
|
+
* Imports a plugin package. Catalogued packages load from their own directory. A local one carries the version of
|
|
260
|
+
* its files in the URL (`?mushin-v=<n>`), which goes up when a file changed, so loading it again runs the new code.
|
|
261
|
+
*/
|
|
194
262
|
async loadPlugin(name) {
|
|
195
263
|
const entry = await this.findPackage(name);
|
|
196
264
|
if (!entry) return unwrapPlugin(await this.options.importer(name));
|
|
197
265
|
const pkg = await readPackageJson(entry.path);
|
|
198
266
|
const file = resolvePackageEntry(entry.path, pkg ?? {});
|
|
199
|
-
|
|
267
|
+
const url = pathToFileURL(file).href;
|
|
268
|
+
if (!entry.local) return unwrapPlugin(await this.options.importer(url));
|
|
269
|
+
const stamp = await folderStamp(entry.path);
|
|
270
|
+
const known = this.versions.get(entry.path);
|
|
271
|
+
const version = !known ? 0 : known.stamp === stamp ? known.version : known.version + 1;
|
|
272
|
+
this.versions.set(entry.path, {
|
|
273
|
+
stamp,
|
|
274
|
+
version
|
|
275
|
+
});
|
|
276
|
+
return unwrapPlugin(await this.options.importer(`${url}?mushin-v=${version}`));
|
|
277
|
+
}
|
|
278
|
+
/** The local plugin folders, each with the plugins found in it. */
|
|
279
|
+
async folders() {
|
|
280
|
+
const catalog = await this.catalog(true);
|
|
281
|
+
return Promise.all(this.localDirs.map(async (path) => ({
|
|
282
|
+
path,
|
|
283
|
+
/** From the config's pluginDirs, rather than the app's own plugins/ folder. */
|
|
284
|
+
extra: !this.options.localDirs.includes(path),
|
|
285
|
+
exists: await stat(path).then((info) => info.isDirectory(), () => false),
|
|
286
|
+
plugins: catalog.filter((item) => item.local && isInside(path, item.path)).map((item) => item.package)
|
|
287
|
+
})));
|
|
288
|
+
}
|
|
289
|
+
/** Sets the config's `pluginDirs`, rescans, and starts enabled entries whose package turned up. */
|
|
290
|
+
async setFolders(dirs) {
|
|
291
|
+
const list = [...new Set(dirs.map((dir) => dir.trim()).filter(Boolean))];
|
|
292
|
+
if (list.length) this.options.config.pluginDirs = list;
|
|
293
|
+
else delete this.options.config.pluginDirs;
|
|
294
|
+
await this.save();
|
|
295
|
+
this.logger.info("plugin folders: %s", this.localDirs.join(", "));
|
|
296
|
+
await this.graph(true);
|
|
297
|
+
for (const entry of this.entries) {
|
|
298
|
+
if (entry.enabled === false || this.fibers.has(entry.id) || !(this.loadErrors.has(entry.id) || this.blocked.has(entry.id))) continue;
|
|
299
|
+
if (!this.catalogList.some((item) => item.package === entry.package)) continue;
|
|
300
|
+
await this.start(entry).catch((error) => this.logger.error("failed to load %s: %s", entry.package, error));
|
|
301
|
+
}
|
|
302
|
+
await this.retryBlocked();
|
|
303
|
+
this.home.emit("manager/changed", "");
|
|
304
|
+
return this.folders();
|
|
200
305
|
}
|
|
201
306
|
get(id) {
|
|
202
307
|
return this.entries.find((entry) => entry.id === id);
|
|
@@ -209,6 +314,11 @@ var PluginManager = class extends Service {
|
|
|
209
314
|
missing: blocked
|
|
210
315
|
};
|
|
211
316
|
const fiber = this.fibers.get(id);
|
|
317
|
+
const loadError = this.loadErrors.get(id);
|
|
318
|
+
if (loadError && !fiber) return {
|
|
319
|
+
status: "failed",
|
|
320
|
+
error: loadError
|
|
321
|
+
};
|
|
212
322
|
const status = fiberStatus(fiber);
|
|
213
323
|
const entry = this.get(id);
|
|
214
324
|
if (status === "pending" && entry) {
|
|
@@ -289,7 +399,15 @@ var PluginManager = class extends Service {
|
|
|
289
399
|
return;
|
|
290
400
|
}
|
|
291
401
|
this.blocked.delete(entry.id);
|
|
292
|
-
|
|
402
|
+
let plugin;
|
|
403
|
+
try {
|
|
404
|
+
plugin = await this.loadPlugin(entry.package);
|
|
405
|
+
this.loadErrors.delete(entry.id);
|
|
406
|
+
} catch (error) {
|
|
407
|
+
this.loadErrors.set(entry.id, loadErrorMessage(entry.package, error));
|
|
408
|
+
this.home.emit("manager/changed", entry.id);
|
|
409
|
+
throw error;
|
|
410
|
+
}
|
|
293
411
|
if (entry.config) {
|
|
294
412
|
const secured = await this.secure(entry, plugin, entry.config, entry.config);
|
|
295
413
|
if (secured !== entry.config && JSON.stringify(secured) !== JSON.stringify(entry.config)) {
|
|
@@ -310,7 +428,8 @@ var PluginManager = class extends Service {
|
|
|
310
428
|
}
|
|
311
429
|
async stop(id) {
|
|
312
430
|
const fiber = this.fibers.get(id);
|
|
313
|
-
|
|
431
|
+
const cleared = this.loadErrors.delete(id);
|
|
432
|
+
if (this.blocked.delete(id) || cleared) this.home.emit("manager/changed", id);
|
|
314
433
|
if (!fiber) return;
|
|
315
434
|
this.fibers.delete(id);
|
|
316
435
|
await fiber.dispose();
|
|
@@ -388,6 +507,24 @@ var PluginManager = class extends Service {
|
|
|
388
507
|
await this.stop(id);
|
|
389
508
|
return entry;
|
|
390
509
|
}
|
|
510
|
+
/**
|
|
511
|
+
* Takes an entry out of the config, with its settings. An enabled entry is disabled first, under the same
|
|
512
|
+
* rules as `disable`: essential plugins stay, and plugins that require it are refused unless `cascade` is set.
|
|
513
|
+
*/
|
|
514
|
+
async remove(id, options = {}) {
|
|
515
|
+
const entry = this.require(id);
|
|
516
|
+
if (entry.enabled !== false) await this.disable(id, options);
|
|
517
|
+
else await this.assertNotEssential(entry);
|
|
518
|
+
await this.stop(id);
|
|
519
|
+
this.entries.splice(this.entries.indexOf(entry), 1);
|
|
520
|
+
await this.save();
|
|
521
|
+
this.logger.info("removed %s (%s)", id, entry.package);
|
|
522
|
+
this.home.emit("manager/changed", id);
|
|
523
|
+
return {
|
|
524
|
+
id,
|
|
525
|
+
package: entry.package
|
|
526
|
+
};
|
|
527
|
+
}
|
|
391
528
|
/** Starts entries that were held back for a missing dependency, once it is there. */
|
|
392
529
|
async retryBlocked() {
|
|
393
530
|
for (const id of [...this.blocked.keys()]) {
|
|
@@ -476,6 +613,27 @@ var PluginManager = class extends Service {
|
|
|
476
613
|
input: z.object({}),
|
|
477
614
|
handler: () => Promise.all(this.entries.map((entry) => this.describe(entry)))
|
|
478
615
|
});
|
|
616
|
+
yield actions.define({
|
|
617
|
+
name: "plugins.provides",
|
|
618
|
+
description: "What each running plugin adds, by package: chat commands, flow node types, tools (actions) and bot adapters. Disabled plugins add nothing.",
|
|
619
|
+
risk: "read",
|
|
620
|
+
input: z.object({}),
|
|
621
|
+
handler: () => this.provides()
|
|
622
|
+
});
|
|
623
|
+
yield actions.define({
|
|
624
|
+
name: "plugins.folders",
|
|
625
|
+
description: "The folders local plugins load from (the app's plugins/ folder, then the extra ones in pluginDirs of mushin.config.json), with whether each exists and the plugin packages found in it.",
|
|
626
|
+
risk: "read",
|
|
627
|
+
input: z.object({}),
|
|
628
|
+
handler: () => this.folders()
|
|
629
|
+
});
|
|
630
|
+
yield actions.define({
|
|
631
|
+
name: "plugins.folders.set",
|
|
632
|
+
description: "Set the extra folders local plugins load from, besides the app's plugins/ folder (pluginDirs in mushin.config.json), for example one folder that a development copy and an instance share. Replaces the list; an empty list removes them. Relative paths start at the app folder. The code in these folders runs as part of Mushin.js.",
|
|
633
|
+
risk: "dangerous",
|
|
634
|
+
input: z.object({ dirs: z.array(z.string().min(1)).max(20) }),
|
|
635
|
+
handler: ({ dirs }) => this.setFolders(dirs)
|
|
636
|
+
});
|
|
479
637
|
yield actions.define({
|
|
480
638
|
name: "plugins.dependencies",
|
|
481
639
|
description: "What a plugin package needs and what needs it: required and optional plugins with whether each is installed, fits the version range and is enabled; the plugins that depend on it; the app plugins enabling it would also enable; and the ones disabling it would also disable. Read this before enabling or disabling a plugin.",
|
|
@@ -501,6 +659,13 @@ var PluginManager = class extends Service {
|
|
|
501
659
|
input: entryInput.extend({ cascade: z.boolean().optional().describe("Also disable the plugins that require it") }),
|
|
502
660
|
handler: async ({ id, cascade }) => this.describe(await this.disable(id, { cascade }))
|
|
503
661
|
});
|
|
662
|
+
yield actions.define({
|
|
663
|
+
name: "plugins.remove",
|
|
664
|
+
description: "Remove an app plugin entry from the config, settings included, for example one whose package is no longer installed. An enabled entry is disabled first, under the same rules as plugins.disable (essential plugins stay; plugins that require it need cascade). The package stays installed and can be enabled again with default settings.",
|
|
665
|
+
risk: "dangerous",
|
|
666
|
+
input: entryInput.extend({ cascade: z.boolean().optional().describe("Also disable the plugins that require it") }),
|
|
667
|
+
handler: ({ id, cascade }) => this.remove(id, { cascade })
|
|
668
|
+
});
|
|
504
669
|
yield actions.define({
|
|
505
670
|
name: "plugins.configure",
|
|
506
671
|
description: "Replace the config of an app plugin entry and restart it.",
|
|
@@ -517,6 +682,35 @@ var PluginManager = class extends Service {
|
|
|
517
682
|
});
|
|
518
683
|
}
|
|
519
684
|
};
|
|
685
|
+
const isInside = (root, path) => {
|
|
686
|
+
const rel = relative(root, path);
|
|
687
|
+
return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
|
|
688
|
+
};
|
|
689
|
+
const SKIP_STAMP = /* @__PURE__ */ new Set(["node_modules", ".git"]);
|
|
690
|
+
/** When the files of a folder last changed, as one string: file count, newest modification time and total size. */
|
|
691
|
+
async function folderStamp(root) {
|
|
692
|
+
let count = 0;
|
|
693
|
+
let newest = 0;
|
|
694
|
+
let size = 0;
|
|
695
|
+
const walk = async (dir, depth) => {
|
|
696
|
+
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) if (entry.isDirectory()) {
|
|
697
|
+
if (depth < 8 && !SKIP_STAMP.has(entry.name)) await walk(join(dir, entry.name), depth + 1);
|
|
698
|
+
} else if (entry.isFile()) {
|
|
699
|
+
const info = await stat(join(dir, entry.name)).catch(() => void 0);
|
|
700
|
+
if (!info) continue;
|
|
701
|
+
count++;
|
|
702
|
+
size += info.size;
|
|
703
|
+
newest = Math.max(newest, info.mtimeMs);
|
|
704
|
+
}
|
|
705
|
+
};
|
|
706
|
+
await walk(root, 0);
|
|
707
|
+
return `${count}:${newest}:${size}`;
|
|
708
|
+
}
|
|
709
|
+
/** Why a package could not be imported, in one line: a missing package says so plainly. */
|
|
710
|
+
function loadErrorMessage(name, error) {
|
|
711
|
+
if (error?.code === "ERR_MODULE_NOT_FOUND" && String(error.message).includes(`'${name}'`)) return `${name} is not installed`;
|
|
712
|
+
return error instanceof Error ? error.message : String(error);
|
|
713
|
+
}
|
|
520
714
|
/** One line naming what keeps a plugin from running, for logs and status tooltips. */
|
|
521
715
|
function describeMissing(missing) {
|
|
522
716
|
return "Missing dependencies: " + missing.map((item) => {
|
package/dist/manager.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.js","names":[],"sources":["../src/manager.ts"],"sourcesContent":["import { dirname, join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { Context, type Fiber, type Plugin, Service } from 'cordis'\nimport { z } from 'zod'\nimport { toJsonSchema, type JsonSchema } from './actions'\nimport {\n type DependencyGraph, dependencyReport, type DependencyState, loadOrder, planDisable, planEnable, providerOf, undeclaredServices, unmet,\n injectedServices,\n} from './dependencies'\nimport { MushinError } from './errors'\nimport { EnvFile, envReference, resolveEnvReferences } from './env'\nimport { type CatalogEntry, manifestProblems, MUSHIN_VERSION, type PluginManifest, readPackageJson, resolvePackageEntry, scanCatalog } from './manifest'\nimport { isMasked, mask, writeJsonAtomic } from './utils'\n\ndeclare module 'cordis' {\n interface Context {\n manager: PluginManager\n }\n\n interface Events {\n 'manager/changed'(id: string): void\n }\n}\n\nexport interface PluginEntry {\n id: string\n package: string\n enabled?: boolean\n config?: Record<string, any>\n}\n\nexport interface InstanceConfig {\n plugins: PluginEntry[]\n}\n\nexport interface ManagerOptions {\n configPath: string\n config: InstanceConfig\n /** `node_modules` directories searched for plugin packages. */\n nodeModules: string[]\n /** Directories holding local plugin folders. */\n localDirs: string[]\n /** Imports a module by specifier; supplied by the launcher so bare names resolve from its location. */\n importer: (specifier: string) => Promise<any>\n}\n\n/** `missing`: waiting for a dependency that is not installed, not enabled or not running. */\nexport type PluginStatus = 'disabled' | 'pending' | 'loading' | 'active' | 'failed' | 'unloading' | 'missing'\n\n/** A required dependency that keeps a plugin from running, or a service nothing provides yet. */\nexport interface MissingDependency {\n package?: string\n service?: string\n range?: string\n /** `inactive`: enabled, but not running yet (or failed). */\n reason: 'not-installed' | 'version' | 'disabled' | 'inactive' | 'mushin' | 'cycle'\n version?: string\n}\n\n// Mirrors cordis FiberState, a const enum that cannot be imported under isolatedModules.\nconst fiberStates: PluginStatus[] = ['pending', 'loading', 'active', 'failed', 'disabled', 'unloading']\n\nexport function fiberStatus(fiber: Fiber | undefined): PluginStatus {\n if (!fiber) return 'disabled'\n return fiberStates[fiber.state] ?? 'pending'\n}\n\nexport function fiberError(fiber: Fiber | undefined): string | undefined {\n // Cordis keeps the failure on a private field; it is the only way to show why a plugin failed.\n const error = (fiber as any)?._error\n if (!error) return\n return error instanceof Error ? error.message : String(error)\n}\n\n/** Picks the plugin out of a module: a default export, or the module namespace itself. */\nexport function unwrapPlugin(mod: any): Plugin {\n const value = mod?.default\n if (value && (typeof value === 'function' || typeof value.apply === 'function')) return value\n if (typeof mod?.apply === 'function') return mod\n throw new Error('module does not export a Cordis plugin')\n}\n\n/** JSON Schema of a plugin's zod `Config`, if it has one. */\nexport function pluginSchema(plugin: Plugin): JsonSchema | undefined {\n const config = (plugin as any).Config\n if (config && typeof config === 'object' && '_zod' in config) return toJsonSchema(config)\n}\n\n/** The top-level config fields a plugin marks as secret, with `field(…, { secret: true })`. */\nexport function secretFields(plugin: Plugin): string[] {\n const properties: Record<string, JsonSchema> = pluginSchema(plugin)?.properties ?? {}\n return Object.keys(properties).filter((key) => properties[key]?.['x-secret'] === true)\n}\n\n/** A config with the plain values of `keys` masked, for lists. `${NAME}` references show where the value is. */\nexport function maskSecrets<T extends Record<string, any>>(config: T, keys: string[]): T {\n if (!keys.length) return config\n const next: Record<string, any> = { ...config }\n for (const key of keys) {\n if (typeof next[key] === 'string' && next[key] && envReference(next[key]) === undefined) next[key] = mask(next[key])\n }\n return next as T\n}\n\n/** A config sent back from a form: masked values keep what was saved before. */\nexport function restoreMasked<T extends Record<string, any>>(config: T, previous: Record<string, any> | undefined, keys: string[]): T {\n if (!keys.length) return config\n const next: Record<string, any> = { ...config }\n for (const key of keys) {\n if (isMasked(next[key])) next[key] = previous?.[key]\n }\n return next as T\n}\n\nexport function validatePluginConfig(plugin: Plugin, config: unknown) {\n const schema = (plugin as any).Config\n if (!schema || typeof schema !== 'object' || !('_zod' in schema)) return config\n const result = (schema as z.ZodType).safeParse(resolveEnvReferences(config ?? {}))\n if (!result.success) throw new MushinError('invalid_input', z.prettifyError(result.error), result.error.issues)\n return config\n}\n\nconst entryInput = z.object({ id: z.string().describe('Plugin entry id from plugins.list') })\n\n/** Manifests for Cordis plugins that Mushin.js uses but that do not ship a `mushin` field. */\nconst knownManifests: Record<string, PluginManifest> = {\n '@cordisjs/plugin-server': {\n kind: 'app',\n essential: true,\n provides: ['server'],\n displayName: { en: 'HTTP server', 'zh-CN': 'HTTP 服务器' },\n description: { en: 'Serves the dashboard, the API and OneBot reverse connections', 'zh-CN': '提供控制台、API 和 OneBot 反向连接' },\n },\n}\n\nexport function knownManifest(name: string) {\n return knownManifests[name]\n}\n\n/**\n * Loads app plugins listed in mushin.config.json and keeps the file in sync\n * when plugins are enabled, disabled or reconfigured at runtime.\n */\nexport class PluginManager extends Service {\n static inject = ['actions']\n\n /** The manager's own context; plugins load here, never under a caller's context. */\n private home: Context\n private fibers = new Map<string, Fiber>()\n private catalogCache?: Promise<CatalogEntry[]>\n /** The last catalog read, for status checks that cannot wait. */\n private catalogList: CatalogEntry[] = []\n /** Entries that were not started because a dependency is missing or they form a cycle. */\n private blocked = new Map<string, MissingDependency[]>()\n\n constructor(ctx: Context, public options: ManagerOptions) {\n super(ctx, 'manager')\n this.home = ctx\n }\n\n private envFile?: EnvFile\n\n /** The instance's `.env`, where secret config fields are kept. */\n private get env() {\n return this.envFile ??= new EnvFile(join(dirname(this.options.configPath), '.env')).loadSync()\n }\n\n /** Moves the plain values of an entry's secret fields into `.env`, leaving `${NAME}` references. */\n private async secure(entry: PluginEntry, plugin: Plugin, config: Record<string, any>, previous?: Record<string, any>) {\n const keys = secretFields(plugin)\n if (!keys.length) return config\n return (await this.env.moveIn(config, { keys, name: [entry.id], previous })).config\n }\n\n /** Plugin lifecycle lines, tagged `plugin` in the dashboard. */\n private get logger() {\n return this.home.logger('plugin')\n }\n\n get entries() {\n return this.options.config.plugins\n }\n\n async *[Service.init]() {\n yield this.home.on('internal/status', (fiber) => {\n for (const [id, tracked] of this.fibers) {\n if (tracked.ctx.fiber !== fiber) continue\n const status = fiberStatus(fiber)\n if (status === 'active') this.logger.info('%s is active', id)\n else if (status === 'failed') this.logger.error('%s failed: %s', id, fiberError(fiber) ?? 'no details')\n this.home.emit('manager/changed', id)\n }\n })\n yield* this.defineActions()\n const graph = await this.graph()\n for (const entry of this.catalogList) {\n for (const problem of manifestProblems(entry.manifest)) this.logger.warn('%s: %s in its package.json \"mushin\" field', entry.package, problem)\n }\n // Dependencies first, so a plugin finds what it needs already loading.\n const { order, cycles } = loadOrder(graph, this.entries.filter((entry) => entry.enabled !== false))\n for (const cycle of cycles) {\n this.logger.error('dependency cycle: %s; these plugins do not start', cycle.chain.join(' → '))\n for (const entry of cycle.entries) this.blocked.set(entry.id, [{ reason: 'cycle', package: cycle.chain.join(' → ') }])\n }\n for (const entry of order) {\n await this.start(entry).catch((error) => {\n this.logger.error('failed to load %s: %s', entry.package, error)\n })\n }\n }\n\n catalog(refresh = false) {\n if (refresh || !this.catalogCache) {\n this.catalogCache = scanCatalog(this.options.nodeModules, this.options.localDirs)\n this.catalogCache.then((list) => (this.catalogList = list), () => {})\n }\n return this.catalogCache\n }\n\n /** The installed packages as last scanned, without waiting for a rescan. */\n get catalogSnapshot(): readonly CatalogEntry[] {\n return this.catalogList\n }\n\n /** The package whose manifest says it adds this flow node type, e.g. `onebot.*` covers `onebot.kick`. */\n packageForNode(type: string) {\n return this.catalogList.find((entry) => entry.manifest.nodes?.some((pattern) => (pattern.endsWith('*') ? type.startsWith(pattern.slice(0, -1)) : pattern === type)))\n }\n\n /** The catalog and entries, for dependency questions. */\n async graph(refresh = false): Promise<DependencyGraph> {\n this.catalogList = await this.catalog(refresh)\n return this.graphNow()\n }\n\n private graphNow(): DependencyGraph {\n return { catalog: this.catalogList, entries: this.entries, known: knownManifest }\n }\n\n /** Dependencies, dependents and what enabling or disabling the package would take. */\n async dependencies(name: string) {\n const graph = await this.graph()\n const entry = this.entries.find((item) => item.package === name)\n return {\n ...dependencyReport(graph, name),\n enable: planEnable(graph, name),\n disable: planDisable(graph, name),\n ...(entry ? { missing: this.missingOf(entry) } : {}),\n }\n }\n async findPackage(name: string) {\n return (await this.catalog()).find((entry) => entry.package === name)\n }\n\n /** Imports a plugin package. Catalogued packages load from their own directory. */\n async loadPlugin(name: string): Promise<Plugin> {\n const entry = await this.findPackage(name)\n if (!entry) return unwrapPlugin(await this.options.importer(name))\n const pkg = await readPackageJson(entry.path)\n const file = resolvePackageEntry(entry.path, pkg ?? {})\n return unwrapPlugin(await this.options.importer(pathToFileURL(file).href))\n }\n\n get(id: string) {\n return this.entries.find((entry) => entry.id === id)\n }\n\n status(id: string): { status: PluginStatus; error?: string; missing?: MissingDependency[] } {\n const blocked = this.blocked.get(id)\n if (blocked) return { status: 'missing', error: describeMissing(blocked), missing: blocked }\n const fiber = this.fibers.get(id)\n const status = fiberStatus(fiber)\n const entry = this.get(id)\n if (status === 'pending' && entry) {\n const missing = this.missingOf(entry)\n if (missing.length) return { status: 'missing', error: describeMissing(missing), missing }\n }\n return { status, error: fiberError(fiber) }\n }\n\n /** What keeps an enabled entry from running: required plugins that are absent or stopped, and injected services nobody provides. */\n private missingOf(entry: PluginEntry): MissingDependency[] {\n const graph = this.graphNow()\n const missing: MissingDependency[] = []\n for (const dep of dependencyReport(graph, entry.package).requires) {\n if (dep.kind === 'bot') continue\n const reason = this.depReason(dep)\n if (reason) missing.push({ package: dep.package, range: dep.range, reason, ...(dep.version ? { version: dep.version } : {}) })\n }\n const fiber = this.fibers.get(entry.id)\n for (const service of injectedServices({ inject: fiber?.inject }).required) {\n if (this.home.get(service as any) !== undefined) continue\n const provider = providerOf(graph, service)\n if (provider && missing.some((item) => item.package === provider)) continue\n const providerEntry = provider ? this.entries.find((item) => item.package === provider) : undefined\n missing.push({\n service,\n ...(provider ? { package: provider } : {}),\n reason: !provider ? 'not-installed' : !providerEntry || providerEntry.enabled === false ? 'disabled' : 'inactive',\n })\n }\n return missing\n }\n\n private depReason(dep: DependencyState): MissingDependency['reason'] | undefined {\n if (dep.problem === 'not-installed' || dep.problem === 'version' || dep.problem === 'disabled') return dep.problem\n if (dep.entry && fiberStatus(this.fibers.get(dep.entry)) !== 'active' && !knownManifest(dep.package)) return 'inactive'\n }\n\n /** Requirements checked before starting: the Mushin.js version and required plugins that are installed, fit and enabled. */\n private async preflight(entry: PluginEntry): Promise<MissingDependency[]> {\n const graph = await this.graph()\n const report = dependencyReport(graph, entry.package)\n const missing: MissingDependency[] = []\n if (report.mushin && !report.mushin.ok) missing.push({ reason: 'mushin', range: report.mushin.range, version: MUSHIN_VERSION })\n for (const dep of report.requires) {\n if (dep.kind === 'bot') continue\n if (dep.problem === 'not-installed' || dep.problem === 'version' || dep.problem === 'disabled') {\n missing.push({ package: dep.package, range: dep.range, reason: dep.problem, ...(dep.version ? { version: dep.version } : {}) })\n }\n }\n return missing\n }\n\n private async start(entry: PluginEntry) {\n this.logger.debug('starting %s (%s)', entry.id, entry.package)\n const missing = await this.preflight(entry)\n if (missing.length) {\n await this.fibers.get(entry.id)?.dispose()\n this.fibers.delete(entry.id)\n this.blocked.set(entry.id, missing)\n this.logger.warn('%s does not start: %s', entry.id, describeMissing(missing))\n this.home.emit('manager/changed', entry.id)\n return\n }\n this.blocked.delete(entry.id)\n const plugin = await this.loadPlugin(entry.package)\n // A key typed into mushin.config.json by hand moves to .env on the next start.\n if (entry.config) {\n const secured = await this.secure(entry, plugin, entry.config, entry.config)\n if (secured !== entry.config && JSON.stringify(secured) !== JSON.stringify(entry.config)) {\n entry.config = secured\n await this.save()\n this.logger.info('moved the secret settings of %s to .env', entry.id)\n }\n }\n for (const { service, provider } of undeclaredServices(this.graphNow(), entry.package, plugin)) {\n const local = this.catalogList.find((item) => item.package === entry.package)?.local\n // Mostly useful to plugin authors, whose plugins are usually local while they work on them.\n this.logger[local ? 'warn' : 'debug']('%s injects \"%s\" but does not declare %s in its manifest\\'s requires or optional', entry.package, service, provider)\n }\n // Let the old instance release its resources (e.g. the server's port) before the new one starts.\n await this.fibers.get(entry.id)?.dispose()\n // `${NAME}` values come from the instance's .env file.\n const fiber = this.home.plugin(plugin, resolveEnvReferences(entry.config ?? {}))\n this.fibers.set(entry.id, fiber)\n this.home.emit('manager/changed', entry.id)\n return fiber\n }\n\n private async stop(id: string) {\n const fiber = this.fibers.get(id)\n if (this.blocked.delete(id)) this.home.emit('manager/changed', id)\n if (!fiber) return\n this.fibers.delete(id)\n await fiber.dispose()\n this.logger.info('%s stopped', id)\n this.home.emit('manager/changed', id)\n }\n\n save() {\n return writeJsonAtomic(this.options.configPath, this.options.config)\n }\n\n /**\n * Enables a plugin. Required plugins that are installed but disabled are refused unless\n * `cascade` is set, in which case they are enabled first; missing or mismatched ones always are.\n */\n async enable(name: string, id?: string, options: { cascade?: boolean } = {}) {\n const plan = planEnable(await this.graph(), name)\n if (plan.mushin.length) {\n const item = plan.mushin[0]\n throw new MushinError('unavailable', `${item.package} needs Mushin.js ${item.range}; this is ${item.version}`, { plan })\n }\n if (plan.blocked.length) {\n const list = plan.blocked.map((dep) => (dep.problem === 'version' ? `${dep.package}@${dep.range} (installed: ${dep.version})` : `${dep.package} (not installed)`))\n throw new MushinError('unavailable', `${name} needs ${list.join(', ')}`, { plan })\n }\n if (plan.enable.length && !options.cascade) {\n throw new MushinError('conflict', `${name} needs ${plan.enable.join(', ')}, which ${plan.enable.length > 1 ? 'are' : 'is'} disabled; enable ${plan.enable.length > 1 ? 'them' : 'it'} too with cascade: true`, { plan })\n }\n for (const dep of plan.enable) await this.enableOne(dep)\n const entry = await this.enableOne(name, id)\n await this.retryBlocked()\n return entry\n }\n\n private async enableOne(name: string, id?: string) {\n let entry = id ? this.get(id) : this.entries.find((item) => item.package === name)\n if (!entry) {\n const base = id ?? name.replace(/^@[^/]+\\//, '').replace(/^(mushin-)?plugin-/, '')\n let unique = base\n for (let i = 2; this.get(unique); i++) unique = `${base}-${i}`\n entry = { id: unique, package: name, enabled: true, config: {} }\n this.entries.push(entry)\n }\n entry.enabled = true\n await this.save()\n this.logger.info('enabled %s (%s)', entry.id, entry.package)\n await this.start(entry)\n return entry\n }\n\n /**\n * Disables a plugin. Enabled plugins that require it are refused unless `cascade` is set, in\n * which case they are disabled first.\n */\n async disable(id: string, options: { cascade?: boolean } = {}) {\n const entry = this.require(id)\n await this.assertNotEssential(entry)\n // Another enabled entry of the same package keeps its dependents running.\n const twin = this.entries.some((item) => item !== entry && item.package === entry.package && item.enabled !== false)\n const plan = twin ? { disable: [], botPlugins: [], degraded: [] } : planDisable(await this.graph(), entry.package)\n if (plan.disable.length && !options.cascade) {\n throw new MushinError('conflict', `${plan.disable.map((item) => item.package).join(', ')} need${plan.disable.length > 1 ? '' : 's'} ${entry.package}; disable ${plan.disable.length > 1 ? 'them' : 'it'} too with cascade: true`, { plan })\n }\n for (const item of plan.disable) await this.assertNotEssential(this.require(item.id))\n for (const item of plan.disable) await this.disableOne(this.require(item.id))\n return this.disableOne(entry)\n }\n\n private async assertNotEssential(entry: PluginEntry) {\n const manifest = (await this.findPackage(entry.package))?.manifest ?? knownManifests[entry.package]\n if (manifest?.essential) {\n throw new MushinError('forbidden', `${entry.package} is essential and cannot be disabled`)\n }\n }\n\n private async disableOne(entry: PluginEntry) {\n const id = entry.id\n entry.enabled = false\n await this.save()\n this.logger.info('disabled %s', id)\n await this.stop(id)\n return entry\n }\n\n /** Starts entries that were held back for a missing dependency, once it is there. */\n private async retryBlocked() {\n for (const id of [...this.blocked.keys()]) {\n const entry = this.get(id)\n if (!entry || entry.enabled === false || this.blocked.get(id)?.some((item) => item.reason === 'cycle')) continue\n if ((await this.preflight(entry)).length) continue\n await this.start(entry).catch((error) => this.logger.error('failed to load %s: %s', entry.package, error))\n }\n }\n\n async configure(id: string, input: Record<string, any>) {\n const entry = this.require(id)\n const plugin = await this.loadPlugin(entry.package)\n const config = restoreMasked(input, entry.config, secretFields(plugin))\n validatePluginConfig(plugin, config)\n entry.config = await this.secure(entry, plugin, config, entry.config)\n await this.save()\n this.logger.info('config of %s changed', id)\n if (entry.enabled !== false) await this.start(entry)\n return entry\n }\n\n async reload(id: string) {\n const entry = this.require(id)\n if (entry.enabled === false) throw new MushinError('conflict', `${id} is disabled`)\n this.logger.info('reloading %s', id)\n await this.stop(id)\n await this.start(entry)\n return entry\n }\n\n private require(id: string) {\n const entry = this.get(id)\n if (!entry) throw new MushinError('not_found', `No app plugin entry with id \"${id}\"`)\n return entry\n }\n\n async describe(entry: PluginEntry) {\n const catalog = await this.findPackage(entry.package)\n let configSchema: JsonSchema | undefined\n let secrets: string[] = []\n try {\n const plugin = await this.loadPlugin(entry.package)\n configSchema = pluginSchema(plugin)\n secrets = secretFields(plugin)\n } catch {}\n const report = dependencyReport(this.graphNow(), entry.package)\n return {\n id: entry.id,\n package: entry.package,\n enabled: entry.enabled !== false,\n config: maskSecrets(entry.config ?? {}, secrets),\n configSchema,\n manifest: catalog?.manifest ?? knownManifests[entry.package],\n version: catalog?.version,\n dependencies: { requires: report.requires, optional: report.optional, dependents: report.dependents, ...(report.mushin ? { mushin: report.mushin } : {}) },\n ...this.status(entry.id),\n }\n }\n\n private *defineActions() {\n const actions = this.home.actions\n\n yield actions.define({\n name: 'plugins.catalog',\n description: 'List installed plugin packages, both app plugins and bot plugins. Optionally filter by kind or a search query.',\n risk: 'read',\n input: z.object({\n kind: z.enum(['app', 'bot']).optional(),\n query: z.string().optional().describe('Case-insensitive text matched against names and descriptions'),\n refresh: z.boolean().optional().describe('Rescan the disk for newly added packages'),\n }),\n handler: async ({ kind, query, refresh }) => {\n let list = await this.catalog(refresh)\n if (kind) list = list.filter((entry) => entry.manifest.kind === kind)\n if (query) {\n const needle = query.toLowerCase()\n list = list.filter((entry) => JSON.stringify([entry.package, entry.manifest]).toLowerCase().includes(needle))\n }\n return list.map(({ path, ...rest }) => rest)\n },\n })\n\n yield actions.define({\n name: 'plugins.list',\n description: 'List app plugin entries with their status (active, pending, failed, disabled) and config.',\n risk: 'read',\n input: z.object({}),\n handler: () => Promise.all(this.entries.map((entry) => this.describe(entry))),\n })\n\n yield actions.define({\n name: 'plugins.dependencies',\n description: 'What a plugin package needs and what needs it: required and optional plugins with whether each is installed, fits the version range and is enabled; the plugins that depend on it; the app plugins enabling it would also enable; and the ones disabling it would also disable. Read this before enabling or disabling a plugin.',\n risk: 'read',\n input: z.object({ package: z.string().describe('Package name, e.g. @mushinjs/plugin-flows') }),\n handler: ({ package: name }) => this.dependencies(name),\n })\n\n yield actions.define({\n name: 'plugins.enable',\n description: 'Enable an app plugin by package name. Adds it to the config if it is not there yet. If it requires plugins that are disabled, this fails and names them unless cascade is true, which enables them first; tell the user which ones before doing that.',\n risk: 'write',\n input: z.object({ package: z.string(), id: z.string().optional(), cascade: z.boolean().optional().describe('Also enable the disabled plugins it requires') }),\n handler: async (input) => this.describe(await this.enable(input.package, input.id, { cascade: input.cascade })),\n })\n\n yield actions.define({\n name: 'plugins.disable',\n description: 'Disable an app plugin entry. Essential plugins cannot be disabled. If enabled plugins require it, this fails and names them unless cascade is true, which disables them too; tell the user which ones before doing that.',\n risk: 'write',\n input: entryInput.extend({ cascade: z.boolean().optional().describe('Also disable the plugins that require it') }),\n handler: async ({ id, cascade }) => this.describe(await this.disable(id, { cascade })),\n })\n\n yield actions.define({\n name: 'plugins.configure',\n description: 'Replace the config of an app plugin entry and restart it.',\n risk: 'write',\n input: entryInput.extend({ config: z.record(z.string(), z.any()) }),\n handler: async ({ id, config }) => this.describe(await this.configure(id, config)),\n })\n\n yield actions.define({\n name: 'plugins.reload',\n description: 'Restart an app plugin entry.',\n risk: 'write',\n input: entryInput,\n handler: async ({ id }) => this.describe(await this.reload(id)),\n })\n }\n}\n\n/** One line naming what keeps a plugin from running, for logs and status tooltips. */\nexport function describeMissing(missing: MissingDependency[]) {\n return 'Missing dependencies: ' + missing.map((item) => {\n const name = item.package ?? `service \"${item.service}\"`\n switch (item.reason) {\n case 'not-installed': return item.package ? `${name} (not installed)` : `${name} (no installed plugin provides it)`\n case 'version': return `${name}@${item.range} (installed: ${item.version})`\n case 'disabled': return `${name} (disabled)`\n case 'inactive': return `${name} (not running)`\n case 'mushin': return `Mushin.js ${item.range} (this is ${item.version})`\n case 'cycle': return `a dependency cycle: ${item.package}`\n }\n }).join(', ')\n}\n"],"mappings":";;;;;;;;;;;AA4DA,MAAM,cAA8B;CAAC;CAAW;CAAW;CAAU;CAAU;CAAY;AAAW;AAEtG,SAAgB,YAAY,OAAwC;CAClE,IAAI,CAAC,OAAO,OAAO;CACnB,OAAO,YAAY,MAAM,UAAU;AACrC;AAEA,SAAgB,WAAW,OAA8C;CAEvE,MAAM,QAAS,OAAe;CAC9B,IAAI,CAAC,OAAO;CACZ,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;;AAGA,SAAgB,aAAa,KAAkB;CAC7C,MAAM,QAAQ,KAAK;CACnB,IAAI,UAAU,OAAO,UAAU,cAAc,OAAO,MAAM,UAAU,aAAa,OAAO;CACxF,IAAI,OAAO,KAAK,UAAU,YAAY,OAAO;CAC7C,MAAM,IAAI,MAAM,wCAAwC;AAC1D;;AAGA,SAAgB,aAAa,QAAwC;CACnE,MAAM,SAAU,OAAe;CAC/B,IAAI,UAAU,OAAO,WAAW,YAAY,UAAU,QAAQ,OAAO,aAAa,MAAM;AAC1F;;AAGA,SAAgB,aAAa,QAA0B;CACrD,MAAM,aAAyC,aAAa,MAAM,CAAC,EAAE,cAAc,CAAC;CACpF,OAAO,OAAO,KAAK,UAAU,CAAC,CAAC,QAAQ,QAAQ,WAAW,IAAI,GAAG,gBAAgB,IAAI;AACvF;;AAGA,SAAgB,YAA2C,QAAW,MAAmB;CACvF,IAAI,CAAC,KAAK,QAAQ,OAAO;CACzB,MAAM,OAA4B,EAAE,GAAG,OAAO;CAC9C,KAAK,MAAM,OAAO,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ACN,OAAO;GACP,SAAS,OAAO,EAAE,SAAS,KAAK,SAAS,MAAM,KAAK,OAAO,EAAE,CAAC;EAChE,CAAC;CACH;AACF;;AAGA,SAAgB,gBAAgB,SAA8B;CAC5D,OAAO,2BAA2B,QAAQ,KAAK,SAAS;EACtD,MAAM,OAAO,KAAK,WAAW,YAAY,KAAK,QAAQ;EACtD,QAAQ,KAAK,QAAb;GACE,KAAK,iBAAiB,OAAO,KAAK,UAAU,GAAG,KAAK,oBAAoB,GAAG,KAAK;GAChF,KAAK,WAAW,OAAO,GAAG,KAAK,GAAG,KAAK,MAAM,eAAe,KAAK,QAAQ;GACzE,KAAK,YAAY,OAAO,GAAG,KAAK;GAChC,KAAK,YAAY,OAAO,GAAG,KAAK;GAChC,KAAK,UAAU,OAAO,aAAa,KAAK,MAAM,YAAY,KAAK,QAAQ;GACvE,KAAK,SAAS,OAAO,uBAAuB,KAAK;EACnD;CACF,CAAC,CAAC,CAAC,KAAK,IAAI;AACd"}
|
|
1
|
+
{"version":3,"file":"manager.js","names":[],"sources":["../src/manager.ts"],"sourcesContent":["import { readdir, stat } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { Context, type Fiber, type Plugin, Service } from 'cordis'\nimport { z } from 'zod'\nimport { toJsonSchema, type JsonSchema } from './actions'\nimport {\n type DependencyGraph, dependencyReport, type DependencyState, loadOrder, planDisable, planEnable, providerOf, undeclaredServices, unmet,\n injectedServices,\n} from './dependencies'\nimport { MushinError } from './errors'\nimport { EnvFile, envReference, resolveEnvReferences } from './env'\nimport { type CatalogEntry, manifestProblems, MUSHIN_VERSION, type PluginManifest, readPackageJson, resolvePackageEntry, scanCatalog } from './manifest'\nimport { isMasked, mask, writeJsonAtomic } from './utils'\n\ndeclare module 'cordis' {\n interface Context {\n manager: PluginManager\n }\n\n interface Events {\n 'manager/changed'(id: string): void\n }\n}\n\nexport interface PluginEntry {\n id: string\n package: string\n enabled?: boolean\n config?: Record<string, any>\n}\n\nexport interface InstanceConfig {\n plugins: PluginEntry[]\n /**\n * Folders besides the app's plugins/ that hold local plugin folders, such as one a development copy and an\n * instance share. Relative paths start at the app folder; `~` is the home folder.\n */\n pluginDirs?: string[]\n}\n\nexport interface ManagerOptions {\n configPath: string\n config: InstanceConfig\n /** `node_modules` directories searched for plugin packages. */\n nodeModules: string[]\n /** Directories holding local plugin folders; the config's `pluginDirs` come after them. */\n localDirs: string[]\n /** The app folder, where relative `pluginDirs` start; the config file's folder by default. */\n baseDir?: string\n /** Imports a module by specifier; supplied by the launcher so bare names resolve from its location. */\n importer: (specifier: string) => Promise<any>\n}\n\n/** `missing`: waiting for a dependency that is not installed, not enabled or not running. */\nexport type PluginStatus = 'disabled' | 'pending' | 'loading' | 'active' | 'failed' | 'unloading' | 'missing'\n\n/** A required dependency that keeps a plugin from running, or a service nothing provides yet. */\nexport interface MissingDependency {\n package?: string\n service?: string\n range?: string\n /** `inactive`: enabled, but not running yet (or failed). */\n reason: 'not-installed' | 'version' | 'disabled' | 'inactive' | 'mushin' | 'cycle'\n version?: string\n}\n\n// Mirrors cordis FiberState, a const enum that cannot be imported under isolatedModules.\nconst fiberStates: PluginStatus[] = ['pending', 'loading', 'active', 'failed', 'disabled', 'unloading']\n\nexport function fiberStatus(fiber: Fiber | undefined): PluginStatus {\n if (!fiber) return 'disabled'\n return fiberStates[fiber.state] ?? 'pending'\n}\n\nexport function fiberError(fiber: Fiber | undefined): string | undefined {\n // Cordis keeps the failure on a private field; it is the only way to show why a plugin failed.\n const error = (fiber as any)?._error\n if (!error) return\n return error instanceof Error ? error.message : String(error)\n}\n\n/** Something a running plugin adds besides actions: a chat command, a flow node or a bot adapter. */\nexport interface ProvidedItem {\n kind: 'command' | 'node' | 'adapter'\n name: string\n /** The context that added it; `packageOf` finds its plugin from there. */\n fiber?: Fiber\n /** The package, when the source knows it better than the context does (a bot plugin runs inside the bots plugin). */\n package?: string\n}\n\n/** Lists what running plugins add; see `PluginManager.defineProvides`. */\nexport type ProvidesSource = () => Iterable<ProvidedItem>\n\n/** What one plugin adds, by name: tools are the actions Fairy and the API can call. */\nexport interface PluginProvides {\n commands: string[]\n nodes: string[]\n tools: string[]\n adapters: string[]\n}\n\nconst PROVIDES_KEY = { command: 'commands', node: 'nodes', adapter: 'adapters' } as const\n\n/** Picks the plugin out of a module: a default export, or the module namespace itself. */\nexport function unwrapPlugin(mod: any): Plugin {\n const value = mod?.default\n if (value && (typeof value === 'function' || typeof value.apply === 'function')) return value\n if (typeof mod?.apply === 'function') return mod\n throw new Error('module does not export a Cordis plugin')\n}\n\n/** JSON Schema of a plugin's zod `Config`, if it has one. */\nexport function pluginSchema(plugin: Plugin): JsonSchema | undefined {\n const config = (plugin as any).Config\n if (config && typeof config === 'object' && '_zod' in config) return toJsonSchema(config)\n}\n\n/** The top-level config fields a plugin marks as secret, with `field(…, { secret: true })`. */\nexport function secretFields(plugin: Plugin): string[] {\n const properties: Record<string, JsonSchema> = pluginSchema(plugin)?.properties ?? {}\n return Object.keys(properties).filter((key) => properties[key]?.['x-secret'] === true)\n}\n\n/** A config with the plain values of `keys` masked, for lists. `${NAME}` references show where the value is. */\nexport function maskSecrets<T extends Record<string, any>>(config: T, keys: string[]): T {\n if (!keys.length) return config\n const next: Record<string, any> = { ...config }\n for (const key of keys) {\n if (typeof next[key] === 'string' && next[key] && envReference(next[key]) === undefined) next[key] = mask(next[key])\n }\n return next as T\n}\n\n/** A config sent back from a form: masked values keep what was saved before. */\nexport function restoreMasked<T extends Record<string, any>>(config: T, previous: Record<string, any> | undefined, keys: string[]): T {\n if (!keys.length) return config\n const next: Record<string, any> = { ...config }\n for (const key of keys) {\n if (isMasked(next[key])) next[key] = previous?.[key]\n }\n return next as T\n}\n\nexport function validatePluginConfig(plugin: Plugin, config: unknown) {\n const schema = (plugin as any).Config\n if (!schema || typeof schema !== 'object' || !('_zod' in schema)) return config\n const result = (schema as z.ZodType).safeParse(resolveEnvReferences(config ?? {}))\n if (!result.success) throw new MushinError('invalid_input', z.prettifyError(result.error), result.error.issues)\n return config\n}\n\nconst entryInput = z.object({ id: z.string().describe('Plugin entry id from plugins.list') })\n\n/** Manifests for Cordis plugins that Mushin.js uses but that do not ship a `mushin` field. */\nconst knownManifests: Record<string, PluginManifest> = {\n '@cordisjs/plugin-server': {\n kind: 'app',\n essential: true,\n provides: ['server'],\n displayName: { en: 'HTTP server', 'zh-CN': 'HTTP 服务器' },\n description: { en: 'Serves the dashboard, the API and OneBot reverse connections', 'zh-CN': '提供控制台、API 和 OneBot 反向连接' },\n },\n}\n\nexport function knownManifest(name: string) {\n return knownManifests[name]\n}\n\n/**\n * Loads app plugins listed in mushin.config.json and keeps the file in sync\n * when plugins are enabled, disabled or reconfigured at runtime.\n */\nexport class PluginManager extends Service {\n static inject = ['actions']\n\n /** The manager's own context; plugins load here, never under a caller's context. */\n private home: Context\n private fibers = new Map<string, Fiber>()\n private catalogCache?: Promise<CatalogEntry[]>\n /** The last catalog read, for status checks that cannot wait. */\n private catalogList: CatalogEntry[] = []\n /** Entries that were not started because a dependency is missing or they form a cycle. */\n private blocked = new Map<string, MissingDependency[]>()\n /** Entries whose package could not be imported, such as one that is no longer installed. */\n private loadErrors = new Map<string, string>()\n /** The version of each local plugin folder's files, so a reload after an edit imports them afresh. */\n private versions = new Map<string, { stamp: string; version: number }>()\n private providesSources = new Set<ProvidesSource>()\n\n constructor(ctx: Context, public options: ManagerOptions) {\n super(ctx, 'manager')\n this.home = ctx\n }\n\n private envFile?: EnvFile\n\n /** The instance's `.env`, where secret config fields are kept. */\n private get env() {\n return this.envFile ??= new EnvFile(join(dirname(this.options.configPath), '.env')).loadSync()\n }\n\n /** Moves the plain values of an entry's secret fields into `.env`, leaving `${NAME}` references. */\n private async secure(entry: PluginEntry, plugin: Plugin, config: Record<string, any>, previous?: Record<string, any>) {\n const keys = secretFields(plugin)\n if (!keys.length) return config\n return (await this.env.moveIn(config, { keys, name: [entry.id], previous })).config\n }\n\n /** Plugin lifecycle lines, tagged `plugin` in the dashboard. */\n private get logger() {\n return this.home.logger('plugin')\n }\n\n get entries() {\n return this.options.config.plugins\n }\n\n async *[Service.init]() {\n yield this.home.on('internal/status', (fiber) => {\n for (const [id, tracked] of this.fibers) {\n if (tracked.ctx.fiber !== fiber) continue\n const status = fiberStatus(fiber)\n if (status === 'active') this.logger.info('%s is active', id)\n else if (status === 'failed') this.logger.error('%s failed: %s', id, fiberError(fiber) ?? 'no details')\n this.home.emit('manager/changed', id)\n }\n })\n yield* this.defineActions()\n const graph = await this.graph()\n for (const entry of this.catalogList) {\n for (const problem of manifestProblems(entry.manifest)) this.logger.warn('%s: %s in its package.json \"mushin\" field', entry.package, problem)\n }\n // Dependencies first, so a plugin finds what it needs already loading.\n const { order, cycles } = loadOrder(graph, this.entries.filter((entry) => entry.enabled !== false))\n for (const cycle of cycles) {\n this.logger.error('dependency cycle: %s; these plugins do not start', cycle.chain.join(' → '))\n for (const entry of cycle.entries) this.blocked.set(entry.id, [{ reason: 'cycle', package: cycle.chain.join(' → ') }])\n }\n for (const entry of order) {\n await this.start(entry).catch((error) => {\n this.logger.error('failed to load %s: %s', entry.package, error)\n })\n }\n }\n\n /** Every folder local plugins load from: the launcher's, then the config's `pluginDirs`. */\n get localDirs() {\n const base = this.options.baseDir ?? dirname(this.options.configPath)\n const extra = (this.options.config.pluginDirs ?? []).filter(Boolean).map((dir) => resolve(base, dir.replace(/^~(?=$|[\\\\/])/, homedir())))\n return [...new Set([...this.options.localDirs, ...extra])]\n }\n\n catalog(refresh = false) {\n if (refresh || !this.catalogCache) {\n this.catalogCache = scanCatalog(this.options.nodeModules, this.localDirs)\n this.catalogCache.then((list) => (this.catalogList = list), () => {})\n }\n return this.catalogCache\n }\n\n /** The installed packages as last scanned, without waiting for a rescan. */\n get catalogSnapshot(): readonly CatalogEntry[] {\n return this.catalogList\n }\n\n /** The package whose manifest says it adds this flow node type, e.g. `onebot.*` covers `onebot.kick`. */\n packageForNode(type: string) {\n return this.catalogList.find((entry) => entry.manifest.nodes?.some((pattern) => (pattern.endsWith('*') ? type.startsWith(pattern.slice(0, -1)) : pattern === type)))\n }\n\n /** The catalog and entries, for dependency questions. */\n async graph(refresh = false): Promise<DependencyGraph> {\n this.catalogList = await this.catalog(refresh)\n return this.graphNow()\n }\n\n private graphNow(): DependencyGraph {\n return { catalog: this.catalogList, entries: this.entries, known: knownManifest }\n }\n\n /** The package of the app plugin a context belongs to, found by walking up from it to an entry's context. */\n packageOf(fiber: Fiber | undefined): string | undefined {\n if (!fiber) return\n const owners = new Map<Fiber, string>()\n for (const [id, tracked] of this.fibers) {\n const entry = this.entries.find((item) => item.id === id)\n if (entry) owners.set(tracked.ctx.fiber, entry.package)\n }\n let current: Fiber | undefined = fiber\n while (current) {\n const found = owners.get(current)\n if (found) return found\n const parent: Fiber | undefined = current.parent?.fiber\n if (!parent || parent === current) return\n current = parent\n }\n }\n\n /** Lists what plugins add besides actions (flow nodes, chat commands, adapters), for `plugins.provides`. Removed when the caller unloads. */\n defineProvides(source: ProvidesSource) {\n return this.ctx.effect(() => {\n this.providesSources.add(source)\n return () => this.providesSources.delete(source)\n }, 'manager.defineProvides()')\n }\n\n /** What each running plugin adds, by package: its chat commands, flow nodes, tools (actions) and adapters. */\n provides(): Record<string, PluginProvides> {\n const result: Record<string, PluginProvides> = {}\n const add = (pkg: string | undefined, key: keyof PluginProvides, name: string) => {\n if (!pkg) return\n const item = result[pkg] ??= { commands: [], nodes: [], tools: [], adapters: [] }\n if (!item[key].includes(name)) item[key].push(name)\n }\n const actions = this.home.actions\n for (const action of actions.list()) {\n if (action.fairy) add(this.packageOf(actions.fiberOf(action.name)), 'tools', action.name)\n }\n for (const source of this.providesSources) {\n try {\n for (const item of source()) add(item.package ?? this.packageOf(item.fiber), PROVIDES_KEY[item.kind], item.name)\n } catch (error) {\n this.logger.debug('listing what plugins provide failed: %s', error)\n }\n }\n for (const item of Object.values(result)) for (const list of Object.values(item)) list.sort()\n return result\n }\n\n /** Dependencies, dependents and what enabling or disabling the package would take. */\n async dependencies(name: string) {\n const graph = await this.graph()\n const entry = this.entries.find((item) => item.package === name)\n return {\n ...dependencyReport(graph, name),\n enable: planEnable(graph, name),\n disable: planDisable(graph, name),\n ...(entry ? { missing: this.missingOf(entry) } : {}),\n }\n }\n async findPackage(name: string) {\n return (await this.catalog()).find((entry) => entry.package === name)\n }\n\n /**\n * Imports a plugin package. Catalogued packages load from their own directory. A local one carries the version of\n * its files in the URL (`?mushin-v=<n>`), which goes up when a file changed, so loading it again runs the new code.\n */\n async loadPlugin(name: string): Promise<Plugin> {\n const entry = await this.findPackage(name)\n if (!entry) return unwrapPlugin(await this.options.importer(name))\n const pkg = await readPackageJson(entry.path)\n const file = resolvePackageEntry(entry.path, pkg ?? {})\n const url = pathToFileURL(file).href\n if (!entry.local) return unwrapPlugin(await this.options.importer(url))\n const stamp = await folderStamp(entry.path)\n const known = this.versions.get(entry.path)\n const version = !known ? 0 : known.stamp === stamp ? known.version : known.version + 1\n this.versions.set(entry.path, { stamp, version })\n return unwrapPlugin(await this.options.importer(`${url}?mushin-v=${version}`))\n }\n\n /** The local plugin folders, each with the plugins found in it. */\n async folders() {\n const catalog = await this.catalog(true)\n return Promise.all(this.localDirs.map(async (path) => ({\n path,\n /** From the config's pluginDirs, rather than the app's own plugins/ folder. */\n extra: !this.options.localDirs.includes(path),\n exists: await stat(path).then((info) => info.isDirectory(), () => false),\n plugins: catalog.filter((item) => item.local && isInside(path, item.path)).map((item) => item.package),\n })))\n }\n\n /** Sets the config's `pluginDirs`, rescans, and starts enabled entries whose package turned up. */\n async setFolders(dirs: string[]) {\n const list = [...new Set(dirs.map((dir) => dir.trim()).filter(Boolean))]\n if (list.length) this.options.config.pluginDirs = list\n else delete this.options.config.pluginDirs\n await this.save()\n this.logger.info('plugin folders: %s', this.localDirs.join(', '))\n await this.graph(true)\n for (const entry of this.entries) {\n if (entry.enabled === false || this.fibers.has(entry.id) || !(this.loadErrors.has(entry.id) || this.blocked.has(entry.id))) continue\n if (!this.catalogList.some((item) => item.package === entry.package)) continue\n await this.start(entry).catch((error) => this.logger.error('failed to load %s: %s', entry.package, error))\n }\n await this.retryBlocked()\n this.home.emit('manager/changed', '')\n return this.folders()\n }\n\n get(id: string) {\n return this.entries.find((entry) => entry.id === id)\n }\n\n status(id: string): { status: PluginStatus; error?: string; missing?: MissingDependency[] } {\n const blocked = this.blocked.get(id)\n if (blocked) return { status: 'missing', error: describeMissing(blocked), missing: blocked }\n const fiber = this.fibers.get(id)\n const loadError = this.loadErrors.get(id)\n if (loadError && !fiber) return { status: 'failed', error: loadError }\n const status = fiberStatus(fiber)\n const entry = this.get(id)\n if (status === 'pending' && entry) {\n const missing = this.missingOf(entry)\n if (missing.length) return { status: 'missing', error: describeMissing(missing), missing }\n }\n return { status, error: fiberError(fiber) }\n }\n\n /** What keeps an enabled entry from running: required plugins that are absent or stopped, and injected services nobody provides. */\n private missingOf(entry: PluginEntry): MissingDependency[] {\n const graph = this.graphNow()\n const missing: MissingDependency[] = []\n for (const dep of dependencyReport(graph, entry.package).requires) {\n if (dep.kind === 'bot') continue\n const reason = this.depReason(dep)\n if (reason) missing.push({ package: dep.package, range: dep.range, reason, ...(dep.version ? { version: dep.version } : {}) })\n }\n const fiber = this.fibers.get(entry.id)\n for (const service of injectedServices({ inject: fiber?.inject }).required) {\n if (this.home.get(service as any) !== undefined) continue\n const provider = providerOf(graph, service)\n if (provider && missing.some((item) => item.package === provider)) continue\n const providerEntry = provider ? this.entries.find((item) => item.package === provider) : undefined\n missing.push({\n service,\n ...(provider ? { package: provider } : {}),\n reason: !provider ? 'not-installed' : !providerEntry || providerEntry.enabled === false ? 'disabled' : 'inactive',\n })\n }\n return missing\n }\n\n private depReason(dep: DependencyState): MissingDependency['reason'] | undefined {\n if (dep.problem === 'not-installed' || dep.problem === 'version' || dep.problem === 'disabled') return dep.problem\n if (dep.entry && fiberStatus(this.fibers.get(dep.entry)) !== 'active' && !knownManifest(dep.package)) return 'inactive'\n }\n\n /** Requirements checked before starting: the Mushin.js version and required plugins that are installed, fit and enabled. */\n private async preflight(entry: PluginEntry): Promise<MissingDependency[]> {\n const graph = await this.graph()\n const report = dependencyReport(graph, entry.package)\n const missing: MissingDependency[] = []\n if (report.mushin && !report.mushin.ok) missing.push({ reason: 'mushin', range: report.mushin.range, version: MUSHIN_VERSION })\n for (const dep of report.requires) {\n if (dep.kind === 'bot') continue\n if (dep.problem === 'not-installed' || dep.problem === 'version' || dep.problem === 'disabled') {\n missing.push({ package: dep.package, range: dep.range, reason: dep.problem, ...(dep.version ? { version: dep.version } : {}) })\n }\n }\n return missing\n }\n\n private async start(entry: PluginEntry) {\n this.logger.debug('starting %s (%s)', entry.id, entry.package)\n const missing = await this.preflight(entry)\n if (missing.length) {\n await this.fibers.get(entry.id)?.dispose()\n this.fibers.delete(entry.id)\n this.blocked.set(entry.id, missing)\n this.logger.warn('%s does not start: %s', entry.id, describeMissing(missing))\n this.home.emit('manager/changed', entry.id)\n return\n }\n this.blocked.delete(entry.id)\n let plugin: Plugin\n try {\n plugin = await this.loadPlugin(entry.package)\n this.loadErrors.delete(entry.id)\n } catch (error) {\n this.loadErrors.set(entry.id, loadErrorMessage(entry.package, error))\n this.home.emit('manager/changed', entry.id)\n throw error\n }\n // A key typed into mushin.config.json by hand moves to .env on the next start.\n if (entry.config) {\n const secured = await this.secure(entry, plugin, entry.config, entry.config)\n if (secured !== entry.config && JSON.stringify(secured) !== JSON.stringify(entry.config)) {\n entry.config = secured\n await this.save()\n this.logger.info('moved the secret settings of %s to .env', entry.id)\n }\n }\n for (const { service, provider } of undeclaredServices(this.graphNow(), entry.package, plugin)) {\n const local = this.catalogList.find((item) => item.package === entry.package)?.local\n // Mostly useful to plugin authors, whose plugins are usually local while they work on them.\n this.logger[local ? 'warn' : 'debug']('%s injects \"%s\" but does not declare %s in its manifest\\'s requires or optional', entry.package, service, provider)\n }\n // Let the old instance release its resources (e.g. the server's port) before the new one starts.\n await this.fibers.get(entry.id)?.dispose()\n // `${NAME}` values come from the instance's .env file.\n const fiber = this.home.plugin(plugin, resolveEnvReferences(entry.config ?? {}))\n this.fibers.set(entry.id, fiber)\n this.home.emit('manager/changed', entry.id)\n return fiber\n }\n\n private async stop(id: string) {\n const fiber = this.fibers.get(id)\n const cleared = this.loadErrors.delete(id)\n if (this.blocked.delete(id) || cleared) this.home.emit('manager/changed', id)\n if (!fiber) return\n this.fibers.delete(id)\n await fiber.dispose()\n this.logger.info('%s stopped', id)\n this.home.emit('manager/changed', id)\n }\n\n save() {\n return writeJsonAtomic(this.options.configPath, this.options.config)\n }\n\n /**\n * Enables a plugin. Required plugins that are installed but disabled are refused unless\n * `cascade` is set, in which case they are enabled first; missing or mismatched ones always are.\n */\n async enable(name: string, id?: string, options: { cascade?: boolean } = {}) {\n const plan = planEnable(await this.graph(), name)\n if (plan.mushin.length) {\n const item = plan.mushin[0]\n throw new MushinError('unavailable', `${item.package} needs Mushin.js ${item.range}; this is ${item.version}`, { plan })\n }\n if (plan.blocked.length) {\n const list = plan.blocked.map((dep) => (dep.problem === 'version' ? `${dep.package}@${dep.range} (installed: ${dep.version})` : `${dep.package} (not installed)`))\n throw new MushinError('unavailable', `${name} needs ${list.join(', ')}`, { plan })\n }\n if (plan.enable.length && !options.cascade) {\n throw new MushinError('conflict', `${name} needs ${plan.enable.join(', ')}, which ${plan.enable.length > 1 ? 'are' : 'is'} disabled; enable ${plan.enable.length > 1 ? 'them' : 'it'} too with cascade: true`, { plan })\n }\n for (const dep of plan.enable) await this.enableOne(dep)\n const entry = await this.enableOne(name, id)\n await this.retryBlocked()\n return entry\n }\n\n private async enableOne(name: string, id?: string) {\n let entry = id ? this.get(id) : this.entries.find((item) => item.package === name)\n if (!entry) {\n const base = id ?? name.replace(/^@[^/]+\\//, '').replace(/^(mushin-)?plugin-/, '')\n let unique = base\n for (let i = 2; this.get(unique); i++) unique = `${base}-${i}`\n entry = { id: unique, package: name, enabled: true, config: {} }\n this.entries.push(entry)\n }\n entry.enabled = true\n await this.save()\n this.logger.info('enabled %s (%s)', entry.id, entry.package)\n await this.start(entry)\n return entry\n }\n\n /**\n * Disables a plugin. Enabled plugins that require it are refused unless `cascade` is set, in\n * which case they are disabled first.\n */\n async disable(id: string, options: { cascade?: boolean } = {}) {\n const entry = this.require(id)\n await this.assertNotEssential(entry)\n // Another enabled entry of the same package keeps its dependents running.\n const twin = this.entries.some((item) => item !== entry && item.package === entry.package && item.enabled !== false)\n const plan = twin ? { disable: [], botPlugins: [], degraded: [] } : planDisable(await this.graph(), entry.package)\n if (plan.disable.length && !options.cascade) {\n throw new MushinError('conflict', `${plan.disable.map((item) => item.package).join(', ')} need${plan.disable.length > 1 ? '' : 's'} ${entry.package}; disable ${plan.disable.length > 1 ? 'them' : 'it'} too with cascade: true`, { plan })\n }\n for (const item of plan.disable) await this.assertNotEssential(this.require(item.id))\n for (const item of plan.disable) await this.disableOne(this.require(item.id))\n return this.disableOne(entry)\n }\n\n private async assertNotEssential(entry: PluginEntry) {\n const manifest = (await this.findPackage(entry.package))?.manifest ?? knownManifests[entry.package]\n if (manifest?.essential) {\n throw new MushinError('forbidden', `${entry.package} is essential and cannot be disabled`)\n }\n }\n\n private async disableOne(entry: PluginEntry) {\n const id = entry.id\n entry.enabled = false\n await this.save()\n this.logger.info('disabled %s', id)\n await this.stop(id)\n return entry\n }\n\n /**\n * Takes an entry out of the config, with its settings. An enabled entry is disabled first, under the same\n * rules as `disable`: essential plugins stay, and plugins that require it are refused unless `cascade` is set.\n */\n async remove(id: string, options: { cascade?: boolean } = {}) {\n const entry = this.require(id)\n if (entry.enabled !== false) await this.disable(id, options)\n else await this.assertNotEssential(entry)\n await this.stop(id)\n this.entries.splice(this.entries.indexOf(entry), 1)\n await this.save()\n this.logger.info('removed %s (%s)', id, entry.package)\n this.home.emit('manager/changed', id)\n return { id, package: entry.package }\n }\n\n /** Starts entries that were held back for a missing dependency, once it is there. */\n private async retryBlocked() {\n for (const id of [...this.blocked.keys()]) {\n const entry = this.get(id)\n if (!entry || entry.enabled === false || this.blocked.get(id)?.some((item) => item.reason === 'cycle')) continue\n if ((await this.preflight(entry)).length) continue\n await this.start(entry).catch((error) => this.logger.error('failed to load %s: %s', entry.package, error))\n }\n }\n\n async configure(id: string, input: Record<string, any>) {\n const entry = this.require(id)\n const plugin = await this.loadPlugin(entry.package)\n const config = restoreMasked(input, entry.config, secretFields(plugin))\n validatePluginConfig(plugin, config)\n entry.config = await this.secure(entry, plugin, config, entry.config)\n await this.save()\n this.logger.info('config of %s changed', id)\n if (entry.enabled !== false) await this.start(entry)\n return entry\n }\n\n async reload(id: string) {\n const entry = this.require(id)\n if (entry.enabled === false) throw new MushinError('conflict', `${id} is disabled`)\n this.logger.info('reloading %s', id)\n await this.stop(id)\n await this.start(entry)\n return entry\n }\n\n private require(id: string) {\n const entry = this.get(id)\n if (!entry) throw new MushinError('not_found', `No app plugin entry with id \"${id}\"`)\n return entry\n }\n\n async describe(entry: PluginEntry) {\n const catalog = await this.findPackage(entry.package)\n let configSchema: JsonSchema | undefined\n let secrets: string[] = []\n try {\n const plugin = await this.loadPlugin(entry.package)\n configSchema = pluginSchema(plugin)\n secrets = secretFields(plugin)\n } catch {}\n const report = dependencyReport(this.graphNow(), entry.package)\n return {\n id: entry.id,\n package: entry.package,\n enabled: entry.enabled !== false,\n config: maskSecrets(entry.config ?? {}, secrets),\n configSchema,\n manifest: catalog?.manifest ?? knownManifests[entry.package],\n version: catalog?.version,\n dependencies: { requires: report.requires, optional: report.optional, dependents: report.dependents, ...(report.mushin ? { mushin: report.mushin } : {}) },\n ...this.status(entry.id),\n }\n }\n\n private *defineActions() {\n const actions = this.home.actions\n\n yield actions.define({\n name: 'plugins.catalog',\n description: 'List installed plugin packages, both app plugins and bot plugins. Optionally filter by kind or a search query.',\n risk: 'read',\n input: z.object({\n kind: z.enum(['app', 'bot']).optional(),\n query: z.string().optional().describe('Case-insensitive text matched against names and descriptions'),\n refresh: z.boolean().optional().describe('Rescan the disk for newly added packages'),\n }),\n handler: async ({ kind, query, refresh }) => {\n let list = await this.catalog(refresh)\n if (kind) list = list.filter((entry) => entry.manifest.kind === kind)\n if (query) {\n const needle = query.toLowerCase()\n list = list.filter((entry) => JSON.stringify([entry.package, entry.manifest]).toLowerCase().includes(needle))\n }\n return list.map(({ path, ...rest }) => rest)\n },\n })\n\n yield actions.define({\n name: 'plugins.list',\n description: 'List app plugin entries with their status (active, pending, failed, disabled) and config.',\n risk: 'read',\n input: z.object({}),\n handler: () => Promise.all(this.entries.map((entry) => this.describe(entry))),\n })\n\n yield actions.define({\n name: 'plugins.provides',\n description: 'What each running plugin adds, by package: chat commands, flow node types, tools (actions) and bot adapters. Disabled plugins add nothing.',\n risk: 'read',\n input: z.object({}),\n handler: () => this.provides(),\n })\n\n yield actions.define({\n name: 'plugins.folders',\n description: 'The folders local plugins load from (the app\\'s plugins/ folder, then the extra ones in pluginDirs of mushin.config.json), with whether each exists and the plugin packages found in it.',\n risk: 'read',\n input: z.object({}),\n handler: () => this.folders(),\n })\n\n yield actions.define({\n name: 'plugins.folders.set',\n description: 'Set the extra folders local plugins load from, besides the app\\'s plugins/ folder (pluginDirs in mushin.config.json), for example one folder that a development copy and an instance share. Replaces the list; an empty list removes them. Relative paths start at the app folder. The code in these folders runs as part of Mushin.js.',\n risk: 'dangerous',\n input: z.object({ dirs: z.array(z.string().min(1)).max(20) }),\n handler: ({ dirs }) => this.setFolders(dirs),\n })\n\n yield actions.define({\n name: 'plugins.dependencies',\n description: 'What a plugin package needs and what needs it: required and optional plugins with whether each is installed, fits the version range and is enabled; the plugins that depend on it; the app plugins enabling it would also enable; and the ones disabling it would also disable. Read this before enabling or disabling a plugin.',\n risk: 'read',\n input: z.object({ package: z.string().describe('Package name, e.g. @mushinjs/plugin-flows') }),\n handler: ({ package: name }) => this.dependencies(name),\n })\n\n yield actions.define({\n name: 'plugins.enable',\n description: 'Enable an app plugin by package name. Adds it to the config if it is not there yet. If it requires plugins that are disabled, this fails and names them unless cascade is true, which enables them first; tell the user which ones before doing that.',\n risk: 'write',\n input: z.object({ package: z.string(), id: z.string().optional(), cascade: z.boolean().optional().describe('Also enable the disabled plugins it requires') }),\n handler: async (input) => this.describe(await this.enable(input.package, input.id, { cascade: input.cascade })),\n })\n\n yield actions.define({\n name: 'plugins.disable',\n description: 'Disable an app plugin entry. Essential plugins cannot be disabled. If enabled plugins require it, this fails and names them unless cascade is true, which disables them too; tell the user which ones before doing that.',\n risk: 'write',\n input: entryInput.extend({ cascade: z.boolean().optional().describe('Also disable the plugins that require it') }),\n handler: async ({ id, cascade }) => this.describe(await this.disable(id, { cascade })),\n })\n\n yield actions.define({\n name: 'plugins.remove',\n description: 'Remove an app plugin entry from the config, settings included, for example one whose package is no longer installed. An enabled entry is disabled first, under the same rules as plugins.disable (essential plugins stay; plugins that require it need cascade). The package stays installed and can be enabled again with default settings.',\n risk: 'dangerous',\n input: entryInput.extend({ cascade: z.boolean().optional().describe('Also disable the plugins that require it') }),\n handler: ({ id, cascade }) => this.remove(id, { cascade }),\n })\n\n yield actions.define({\n name: 'plugins.configure',\n description: 'Replace the config of an app plugin entry and restart it.',\n risk: 'write',\n input: entryInput.extend({ config: z.record(z.string(), z.any()) }),\n handler: async ({ id, config }) => this.describe(await this.configure(id, config)),\n })\n\n yield actions.define({\n name: 'plugins.reload',\n description: 'Restart an app plugin entry.',\n risk: 'write',\n input: entryInput,\n handler: async ({ id }) => this.describe(await this.reload(id)),\n })\n }\n}\n\nconst isInside = (root: string, path: string) => {\n const rel = relative(root, path)\n return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))\n}\n\nconst SKIP_STAMP = new Set(['node_modules', '.git'])\n\n/** When the files of a folder last changed, as one string: file count, newest modification time and total size. */\nasync function folderStamp(root: string) {\n let count = 0\n let newest = 0\n let size = 0\n const walk = async (dir: string, depth: number) => {\n for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {\n if (entry.isDirectory()) {\n if (depth < 8 && !SKIP_STAMP.has(entry.name)) await walk(join(dir, entry.name), depth + 1)\n } else if (entry.isFile()) {\n const info = await stat(join(dir, entry.name)).catch(() => undefined)\n if (!info) continue\n count++\n size += info.size\n newest = Math.max(newest, info.mtimeMs)\n }\n }\n }\n await walk(root, 0)\n return `${count}:${newest}:${size}`\n}\n\n/** Why a package could not be imported, in one line: a missing package says so plainly. */\nfunction loadErrorMessage(name: string, error: unknown) {\n if ((error as any)?.code === 'ERR_MODULE_NOT_FOUND' && String((error as Error).message).includes(`'${name}'`)) return `${name} is not installed`\n return error instanceof Error ? error.message : String(error)\n}\n\n/** One line naming what keeps a plugin from running, for logs and status tooltips. */\nexport function describeMissing(missing: MissingDependency[]) {\n return 'Missing dependencies: ' + missing.map((item) => {\n const name = item.package ?? `service \"${item.service}\"`\n switch (item.reason) {\n case 'not-installed': return item.package ? `${name} (not installed)` : `${name} (no installed plugin provides it)`\n case 'version': return `${name}@${item.range} (installed: ${item.version})`\n case 'disabled': return `${name} (disabled)`\n case 'inactive': return `${name} (not running)`\n case 'mushin': return `Mushin.js ${item.range} (this is ${item.version})`\n case 'cycle': return `a dependency cycle: ${item.package}`\n }\n }).join(', ')\n}\n"],"mappings":";;;;;;;;;;;;;AAqEA,MAAM,cAA8B;CAAC;CAAW;CAAW;CAAU;CAAU;CAAY;AAAW;AAEtG,SAAgB,YAAY,OAAwC;CAClE,IAAI,CAAC,OAAO,OAAO;CACnB,OAAO,YAAY,MAAM,UAAU;AACrC;AAEA,SAAgB,WAAW,OAA8C;CAEvE,MAAM,QAAS,OAAe;CAC9B,IAAI,CAAC,OAAO;CACZ,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAuBA,MAAM,eAAe;CAAE,SAAS;CAAY,MAAM;CAAS,SAAS;AAAW;;AAG/E,SAAgB,aAAa,KAAkB;CAC7C,MAAM,QAAQ,KAAK;CACnB,IAAI,UAAU,OAAO,UAAU,cAAc,OAAO,MAAM,UAAU,aAAa,OAAO;CACxF,I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KAAK,KAAK,KAAK,MAAM,IAAI,CAAC,CAAC,CAAC,YAAY,KAAA,CAAS;GACpE,IAAI,CAAC,MAAM;GACX;GACA,QAAQ,KAAK;GACb,SAAS,KAAK,IAAI,QAAQ,KAAK,OAAO;EACxC;CAEJ;CACA,MAAM,KAAK,MAAM,CAAC;CAClB,OAAO,GAAG,MAAM,GAAG,OAAO,GAAG;AAC/B;;AAGA,SAAS,iBAAiB,MAAc,OAAgB;CACtD,IAAK,OAAe,SAAS,0BAA0B,OAAQ,MAAgB,OAAO,CAAC,CAAC,SAAS,IAAI,KAAK,EAAE,GAAG,OAAO,GAAG,KAAK;CAC9H,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;;AAGA,SAAgB,gBAAgB,SAA8B;CAC5D,OAAO,2BAA2B,QAAQ,KAAK,SAAS;EACtD,MAAM,OAAO,KAAK,WAAW,YAAY,KAAK,QAAQ;EACtD,QAAQ,KAAK,QAAb;GACE,KAAK,iBAAiB,OAAO,KAAK,UAAU,GAAG,KAAK,oBAAoB,GAAG,KAAK;GAChF,KAAK,WAAW,OAAO,GAAG,KAAK,GAAG,KAAK,MAAM,eAAe,KAAK,QAAQ;GACzE,KAAK,YAAY,OAAO,GAAG,KAAK;GAChC,KAAK,YAAY,OAAO,GAAG,KAAK;GAChC,KAAK,UAAU,OAAO,aAAa,KAAK,MAAM,YAAY,KAAK,QAAQ;GACvE,KAAK,SAAS,OAAO,uBAAuB,KAAK;EACnD;CACF,CAAC,CAAC,CAAC,KAAK,IAAI;AACd"}
|
package/dist/manifest.d.ts
CHANGED
|
@@ -4,7 +4,10 @@ export interface PluginManifest {
|
|
|
4
4
|
kind: 'app' | 'bot';
|
|
5
5
|
displayName?: LocalizedText;
|
|
6
6
|
description?: LocalizedText;
|
|
7
|
-
/**
|
|
7
|
+
/**
|
|
8
|
+
* Essential app plugins cannot be disabled from the dashboard or by Fairy. An essential bot plugin cannot be turned
|
|
9
|
+
* off for the whole project, only on each bot (the flows runner, which the Flows plugin turns on where flows run).
|
|
10
|
+
*/
|
|
8
11
|
essential?: boolean;
|
|
9
12
|
platforms?: string[];
|
|
10
13
|
category?: string;
|
package/dist/manifest.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manifest.js","names":[],"sources":["../src/manifest.ts"],"sourcesContent":["import { readFileSync } from 'node:fs'\nimport { readdir, readFile, stat } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport { validRange } from './semver'\n\nexport type LocalizedText = string | Record<string, string>\n\n/** The `mushin` field in a plugin's package.json. */\nexport interface PluginManifest {\n kind: 'app' | 'bot'\n displayName?: LocalizedText\n description?: LocalizedText\n
|
|
1
|
+
{"version":3,"file":"manifest.js","names":[],"sources":["../src/manifest.ts"],"sourcesContent":["import { readFileSync } from 'node:fs'\nimport { readdir, readFile, stat } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport { validRange } from './semver'\n\nexport type LocalizedText = string | Record<string, string>\n\n/** The `mushin` field in a plugin's package.json. */\nexport interface PluginManifest {\n kind: 'app' | 'bot'\n displayName?: LocalizedText\n description?: LocalizedText\n /**\n * Essential app plugins cannot be disabled from the dashboard or by Fairy. An essential bot plugin cannot be turned\n * off for the whole project, only on each bot (the flows runner, which the Flows plugin turns on where flows run).\n */\n essential?: boolean\n platforms?: string[]\n category?: string\n /** Service names this plugin provides, such as `flows`; maps `inject` names to packages. */\n provides?: string[]\n /** Needed to run: without them the plugin cannot be enabled. */\n requires?: DependencySpec\n /** Used when present: without them the plugin runs, and the features that need them say so. */\n optional?: DependencySpec\n /** Flow node types this plugin adds, such as `logic.permission` or `onebot.*`, so the editor can say which plugin to enable for an unknown node. */\n nodes?: string[]\n}\n\nexport interface DependencySpec {\n /** A version range of Mushin.js, such as `>=0.2.0`. */\n mushin?: string\n /** Package name → version range, such as `{ \"@mushinjs/plugin-bots\": \"*\" }`. */\n plugins?: Record<string, string>\n}\n\n/**\n * The official packages moved from the `@mushin` scope to `@mushinjs` before the first npm release.\n * Names saved by older instances (in mushin.config.json and bot records) are read through this.\n */\nexport function currentPackageName(name: string) {\n return name.startsWith('@mushin/') ? `@mushinjs/${name.slice('@mushin/'.length)}` : name\n}\n\n/** The running Mushin.js version: the version of `@mushinjs/core`. */\nexport const MUSHIN_VERSION: string = (() => {\n try {\n return JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version ?? '0.0.0'\n } catch {\n return '0.0.0'\n }\n})()\n\n/** Problems with the dependency fields of a manifest, in words a plugin author can act on. */\nexport function manifestProblems(manifest: PluginManifest): string[] {\n const problems: string[] = []\n if (manifest.provides !== undefined && (!Array.isArray(manifest.provides) || manifest.provides.some((item) => typeof item !== 'string'))) {\n problems.push('\"provides\" should be a list of service names')\n }\n for (const key of ['requires', 'optional'] as const) {\n const spec = manifest[key]\n if (spec === undefined) continue\n if (!spec || typeof spec !== 'object' || Array.isArray(spec)) {\n problems.push(`\"${key}\" should be an object with \"mushin\" and \"plugins\"`)\n continue\n }\n if (spec.mushin !== undefined && (typeof spec.mushin !== 'string' || !validRange(spec.mushin))) {\n problems.push(`\"${key}.mushin\" is not a version range: ${JSON.stringify(spec.mushin)}`)\n }\n if (spec.plugins !== undefined) {\n if (!spec.plugins || typeof spec.plugins !== 'object' || Array.isArray(spec.plugins)) {\n problems.push(`\"${key}.plugins\" should map package names to version ranges`)\n continue\n }\n for (const [name, range] of Object.entries(spec.plugins)) {\n if (typeof range !== 'string' || !validRange(range)) problems.push(`\"${key}.plugins.${name}\" is not a version range: ${JSON.stringify(range)}`)\n }\n }\n }\n return problems\n}\n\n/** Package name → range of the plugins a manifest lists under `requires` or `optional`. */\nexport function dependencyPlugins(manifest: PluginManifest | undefined, key: 'requires' | 'optional'): [string, string][] {\n const plugins = manifest?.[key]?.plugins\n if (!plugins || typeof plugins !== 'object') return []\n return Object.entries(plugins).filter(([, range]) => typeof range === 'string')\n}\n\nexport interface CatalogEntry {\n package: string\n version: string\n /** Absolute path of the package directory. */\n path: string\n local: boolean\n manifest: PluginManifest\n}\n\ninterface PackageJson {\n name?: string\n version?: string\n description?: string\n main?: string\n module?: string\n exports?: any\n mushin?: PluginManifest\n}\n\nexport async function readPackageJson(dir: string): Promise<PackageJson | undefined> {\n try {\n return JSON.parse(await readFile(join(dir, 'package.json'), 'utf8'))\n } catch {\n return undefined\n }\n}\n\n/** Resolves the file a package's `import` entry points to. */\nexport function resolvePackageEntry(dir: string, pkg: PackageJson) {\n let entry = pkg.exports?.['.'] ?? pkg.exports ?? pkg.module ?? pkg.main ?? 'index.js'\n while (entry && typeof entry === 'object') {\n entry = entry.import ?? entry.node ?? entry.default ?? entry.require\n }\n return resolve(dir, typeof entry === 'string' ? entry : 'index.js')\n}\n\nasync function isDirectory(path: string) {\n try {\n return (await stat(path)).isDirectory()\n } catch {\n return false\n }\n}\n\nasync function listPackageDirs(nodeModules: string) {\n const dirs: string[] = []\n let names: string[]\n try {\n names = await readdir(nodeModules)\n } catch {\n return dirs\n }\n for (const name of names) {\n if (name.startsWith('.')) continue\n const full = join(nodeModules, name)\n if (name.startsWith('@')) {\n for (const sub of await readdir(full).catch(() => [] as string[])) {\n dirs.push(join(full, sub))\n }\n } else {\n dirs.push(full)\n }\n }\n return dirs\n}\n\n/** Finds installed packages that carry a `mushin` manifest. Earlier directories win on duplicates. */\nexport async function scanCatalog(nodeModulesDirs: string[], localDirs: string[]) {\n const found = new Map<string, CatalogEntry>()\n const add = async (dir: string, local: boolean) => {\n const pkg = await readPackageJson(dir)\n if (!pkg?.name || !pkg.mushin || found.has(pkg.name)) return\n found.set(pkg.name, { package: pkg.name, version: pkg.version ?? '0.0.0', path: dir, local, manifest: pkg.mushin })\n }\n for (const localDir of localDirs) {\n for (const name of await readdir(localDir).catch(() => [] as string[])) {\n const dir = join(localDir, name)\n if (await isDirectory(dir)) await add(dir, true)\n }\n }\n for (const nodeModules of nodeModulesDirs) {\n for (const dir of await listPackageDirs(nodeModules)) await add(dir, false)\n }\n return [...found.values()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ACT;;AAGA,eAAsB,YAAY,iBAA2B,WAAqB;CAChF,MAAM,wBAAQ,IAAI,IAA0B;CAC5C,MAAM,MAAM,OAAO,KAAa,UAAmB;EACjD,MAAM,MAAM,MAAM,gBAAgB,GAAG;EACrC,IAAI,CAAC,KAAK,QAAQ,CAAC,IAAI,UAAU,MAAM,IAAI,IAAI,IAAI,GAAG;EACtD,MAAM,IAAI,IAAI,MAAM;GAAE,SAAS,IAAI;GAAM,SAAS,IAAI,WAAW;GAAS,MAAM;GAAK;GAAO,UAAU,IAAI;EAAO,CAAC;CACpH;CACA,KAAK,MAAM,YAAY,WACrB,KAAK,MAAM,QAAQ,MAAM,QAAQ,QAAQ,CAAC,CAAC,YAAY,CAAC,CAAa,GAAG;EACtE,MAAM,MAAM,KAAK,UAAU,IAAI;EAC/B,IAAI,MAAM,YAAY,GAAG,GAAG,MAAM,IAAI,KAAK,IAAI;CACjD;CAEF,KAAK,MAAM,eAAe,iBACxB,KAAK,MAAM,OAAO,MAAM,gBAAgB,WAAW,GAAG,MAAM,IAAI,KAAK,KAAK;CAE5E,OAAO,CAAC,GAAG,MAAM,OAAO,CAAC,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,QAAQ,cAAc,EAAE,OAAO,CAAC;AAC9E"}
|
package/dist/message.d.ts
CHANGED
package/dist/message.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message.js","names":[],"sources":["../src/message.ts"],"sourcesContent":["/**\n * Message segments follow OneBot v11 segments, because OneBot is the first adapter.\n * Other adapters convert to and from this shape.\n */\nexport interface Segment {\n type: string\n data: Record<string, any>\n}\n\nexport const seg = {\n text: (text: string): Segment => ({ type: 'text', data: { text } }),\n at: (id: string, name?: string): Segment => ({ type: 'at', data: { qq: id, ...(name ? { name } : {}) } }),\n image: (file: string): Segment => ({ type: 'image', data: { file } }),\n reply: (id: string): Segment => ({ type: 'reply', data: { id } }),\n face: (id: string): Segment => ({ type: 'face', data: { id } }),\n}\n\nexport type Content = string | Segment | Segment[]\n\nexport function toSegments(content: Content): Segment[] {\n if (typeof content === 'string') return [seg.text(content)]\n if (Array.isArray(content)) return content\n return [content]\n}\n\n/** Plain text of a message: text segments joined, other segments as short placeholders. */\nexport function segmentsToText(segments: Segment[], placeholders = true) {\n return segments.map((s) => {\n if (s.type === 'text') return s.data.text ?? ''\n if (!placeholders) return ''\n if (s.type === 'at') return `@${s.data.name ?? s.data.qq}`\n if (s.type === 'face') return '[face]'\n if (s.type === 'reply') return ''\n return `[${s.type}]`\n }).join('')\n}\n\nexport type MessageType = 'text' | 'image' | 'voice' | 'video' | 'file' | 'card' | 'forward' | 'mixed'\n\nconst segmentKinds: Record<string, MessageType> = {\n text: 'text', at: 'text', face: 'text', reply: 'text',\n image: 'image', mface: 'image',\n record: 'voice',\n video: 'video',\n file: 'file',\n json: 'card', xml: 'card', markdown: 'card', ark: 'card',\n forward: 'forward', node: 'forward',\n}\n\n/** One kind of content gives that type; text plus anything else, or two other kinds, give `mixed`. */\nexport function messageType(segments: Segment[]): MessageType {\n const kinds = new Set(segments.map((s) => segmentKinds[s.type] ?? 'mixed'))\n if (kinds.size === 0) return 'text'\n if (kinds.size === 1) return [...kinds][0]\n return 'mixed'\n}\n\n/** A knowledge base passage a reply was written from. */\nexport interface KnowledgeSource {\n base: string\n doc: string\n chunk: string\n title: string\n}\n\nexport type Provenance =\n | { kind: 'user' }\n | { kind: 'plugin'; plugin: string }\n | { kind: 'llm'; plugin?: string; provider: string; model: string; latencyMs: number; tokens?: number; persona?: string }\n | { kind: 'flow'; flow: string; node: string; provider?: string; model?: string; persona?: string; knowledge?: KnowledgeSource[] }\n | { kind: '
|
|
1
|
+
{"version":3,"file":"message.js","names":[],"sources":["../src/message.ts"],"sourcesContent":["/**\n * Message segments follow OneBot v11 segments, because OneBot is the first adapter.\n * Other adapters convert to and from this shape.\n */\nexport interface Segment {\n type: string\n data: Record<string, any>\n}\n\nexport const seg = {\n text: (text: string): Segment => ({ type: 'text', data: { text } }),\n at: (id: string, name?: string): Segment => ({ type: 'at', data: { qq: id, ...(name ? { name } : {}) } }),\n image: (file: string): Segment => ({ type: 'image', data: { file } }),\n reply: (id: string): Segment => ({ type: 'reply', data: { id } }),\n face: (id: string): Segment => ({ type: 'face', data: { id } }),\n}\n\nexport type Content = string | Segment | Segment[]\n\nexport function toSegments(content: Content): Segment[] {\n if (typeof content === 'string') return [seg.text(content)]\n if (Array.isArray(content)) return content\n return [content]\n}\n\n/** Plain text of a message: text segments joined, other segments as short placeholders. */\nexport function segmentsToText(segments: Segment[], placeholders = true) {\n return segments.map((s) => {\n if (s.type === 'text') return s.data.text ?? ''\n if (!placeholders) return ''\n if (s.type === 'at') return `@${s.data.name ?? s.data.qq}`\n if (s.type === 'face') return '[face]'\n if (s.type === 'reply') return ''\n return `[${s.type}]`\n }).join('')\n}\n\nexport type MessageType = 'text' | 'image' | 'voice' | 'video' | 'file' | 'card' | 'forward' | 'mixed'\n\nconst segmentKinds: Record<string, MessageType> = {\n text: 'text', at: 'text', face: 'text', reply: 'text',\n image: 'image', mface: 'image',\n record: 'voice',\n video: 'video',\n file: 'file',\n json: 'card', xml: 'card', markdown: 'card', ark: 'card',\n forward: 'forward', node: 'forward',\n}\n\n/** One kind of content gives that type; text plus anything else, or two other kinds, give `mixed`. */\nexport function messageType(segments: Segment[]): MessageType {\n const kinds = new Set(segments.map((s) => segmentKinds[s.type] ?? 'mixed'))\n if (kinds.size === 0) return 'text'\n if (kinds.size === 1) return [...kinds][0]\n return 'mixed'\n}\n\n/** A knowledge base passage a reply was written from. */\nexport interface KnowledgeSource {\n base: string\n doc: string\n chunk: string\n title: string\n}\n\nexport type Provenance =\n | { kind: 'user' }\n | { kind: 'plugin'; plugin: string }\n | { kind: 'llm'; plugin?: string; provider: string; model: string; latencyMs: number; tokens?: number; persona?: string }\n | { kind: 'flow'; flow: string; node: string; provider?: string; model?: string; persona?: string; knowledge?: KnowledgeSource[] }\n | { kind: 'fairy'; session: string }\n | { kind: 'manual' }\n\nexport interface ChannelInfo {\n type: 'group' | 'private'\n id: string\n name?: string\n /** For a private chat started from a group (a temporary chat): that group's id. */\n fromGroup?: string\n}\n\nexport interface UserInfo {\n id: string\n name?: string\n /** The sender's role in a group chat, when the platform reports it. */\n role?: 'owner' | 'admin' | 'member'\n}\n\nexport interface MessageRecord {\n id: string\n botId: string\n /** Platform message id, when the platform returned one. */\n messageId?: string\n direction: 'in' | 'out'\n channel: ChannelInfo\n user: UserInfo\n segments: Segment[]\n timestamp: number\n replyTo?: string\n type: MessageType\n /** Adapters that can render every segment of this message. */\n platforms: string[]\n source: Provenance\n}\n"],"mappings":";AASA,MAAa,MAAM;CACjB,OAAO,UAA2B;EAAE,MAAM;EAAQ,MAAM,EAAE,KAAK;CAAE;CACjE,KAAK,IAAY,UAA4B;EAAE,MAAM;EAAM,MAAM;GAAE,IAAI;GAAI,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;EAAG;CAAE;CACvG,QAAQ,UAA2B;EAAE,MAAM;EAAS,MAAM,EAAE,KAAK;CAAE;CACnE,QAAQ,QAAyB;EAAE,MAAM;EAAS,MAAM,EAAE,GAAG;CAAE;CAC/D,OAAO,QAAyB;EAAE,MAAM;EAAQ,MAAM,EAAE,GAAG;CAAE;AAC/D;AAIA,SAAgB,WAAW,SAA6B;CACtD,IAAI,OAAO,YAAY,UAAU,OAAO,CAAC,IAAI,KAAK,OAAO,CAAC;CAC1D,IAAI,MAAM,QAAQ,OAAO,GAAG,OAAO;CACnC,OAAO,CAAC,OAAO;AACjB;;AAGA,SAAgB,eAAe,UAAqB,eAAe,MAAM;CACvE,OAAO,SAAS,KAAK,MAAM;EACzB,IAAI,EAAE,SAAS,QAAQ,OAAO,EAAE,KAAK,QAAQ;EAC7C,IAAI,CAAC,cAAc,OAAO;EAC1B,IAAI,EAAE,SAAS,MAAM,OAAO,IAAI,EAAE,KAAK,QAAQ,EAAE,KAAK;EACtD,IAAI,EAAE,SAAS,QAAQ,OAAO;EAC9B,IAAI,EAAE,SAAS,SAAS,OAAO;EAC/B,OAAO,IAAI,EAAE,KAAK;CACpB,CAAC,CAAC,CAAC,KAAK,EAAE;AACZ;AAIA,MAAM,eAA4C;CAChD,MAAM;CAAQ,IAAI;CAAQ,MAAM;CAAQ,OAAO;CAC/C,OAAO;CAAS,OAAO;CACvB,QAAQ;CACR,OAAO;CACP,MAAM;CACN,MAAM;CAAQ,KAAK;CAAQ,UAAU;CAAQ,KAAK;CAClD,SAAS;CAAW,MAAM;AAC5B;;AAGA,SAAgB,YAAY,UAAkC;CAC5D,MAAM,QAAQ,IAAI,IAAI,SAAS,KAAK,MAAM,aAAa,EAAE,SAAS,OAAO,CAAC;CAC1E,IAAI,MAAM,SAAS,GAAG,OAAO;CAC7B,IAAI,MAAM,SAAS,GAAG,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC;CACxC,OAAO;AACT"}
|
package/dist/utils.d.ts
CHANGED
|
@@ -60,7 +60,7 @@ export declare function field(title: string, description?: string, translations?
|
|
|
60
60
|
title: string;
|
|
61
61
|
};
|
|
62
62
|
/** Source category of a log line, for quick filters in the dashboard. */
|
|
63
|
-
export declare const LOG_TAGS: readonly ["message", "plugin", "bot", "adapter", "flow", "provider", "
|
|
63
|
+
export declare const LOG_TAGS: readonly ["message", "plugin", "bot", "adapter", "flow", "provider", "fairy", "system", "other"];
|
|
64
64
|
export type LogTag = typeof LOG_TAGS[number];
|
|
65
65
|
/** The tag of a logger name; `provider:openai` and `provider` share one. */
|
|
66
66
|
export declare function logTag(name: string): LogTag;
|
package/dist/utils.js
CHANGED
|
@@ -95,7 +95,7 @@ const LOG_TAGS = [
|
|
|
95
95
|
"adapter",
|
|
96
96
|
"flow",
|
|
97
97
|
"provider",
|
|
98
|
-
"
|
|
98
|
+
"fairy",
|
|
99
99
|
"system",
|
|
100
100
|
"other"
|
|
101
101
|
];
|
|
@@ -107,12 +107,16 @@ const logTags = {
|
|
|
107
107
|
bot: "bot",
|
|
108
108
|
bots: "bot",
|
|
109
109
|
onebot: "adapter",
|
|
110
|
+
qq: "adapter",
|
|
111
|
+
discord: "adapter",
|
|
112
|
+
telegram: "adapter",
|
|
113
|
+
kook: "adapter",
|
|
110
114
|
flow: "flow",
|
|
111
115
|
flows: "flow",
|
|
112
116
|
provider: "provider",
|
|
113
117
|
providers: "provider",
|
|
114
118
|
llm: "provider",
|
|
115
|
-
|
|
119
|
+
fairy: "fairy",
|
|
116
120
|
app: "system",
|
|
117
121
|
console: "system",
|
|
118
122
|
server: "system",
|
package/dist/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto'\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\n\nexport function randomId(bytes = 6) {\n return randomBytes(bytes).toString('base64url')\n}\n\n/** Masks a secret for display: `sk-abcdef123456` becomes `sk-…3456`. */\nexport function mask(secret: string | undefined | null) {\n if (!secret) return ''\n if (secret.length <= 8) return '••••'\n return `${secret.slice(0, 3)}…${secret.slice(-4)}`\n}\n\nexport function isMasked(value: unknown) {\n return typeof value === 'string' && (value === '••••' || /^.{0,3}….{4}$/.test(value))\n}\n\nexport async function readJson<T>(path: string): Promise<T | undefined> {\n try {\n return JSON.parse(await readFile(path, 'utf8'))\n } catch (error: any) {\n if (error?.code === 'ENOENT') return undefined\n throw error\n }\n}\n\nconst writeQueues = new Map<string, Promise<void>>()\n\n/**\n * Writes JSON through a temp file and a rename, so a crash never leaves a half-written file.\n * Writes to the same path are serialized.\n */\nexport function writeJsonAtomic(path: string, value: unknown) {\n return writeTextAtomic(path, () => JSON.stringify(value, null, 2) + '\\n')\n}\n\n/**\n * Writes a text file through a temp file and a rename. Writes to the same path are serialized;\n * a function is called when the write's turn comes, so it can build on what the last write left.\n */\nexport function writeTextAtomic(path: string, text: string | (() => string | Promise<string>), options: { mode?: number } = {}) {\n const previous = writeQueues.get(path) ?? Promise.resolve()\n const task = previous.catch(() => {}).then(async () => {\n const content = typeof text === 'function' ? await text() : text\n await mkdir(dirname(path), { recursive: true })\n const temp = `${path}.${randomId(4)}.tmp`\n await writeFile(temp, content, { encoding: 'utf8', mode: options.mode })\n await renameWithRetry(temp, path)\n })\n writeQueues.set(path, task)\n task.finally(() => {\n if (writeQueues.get(path) === task) writeQueues.delete(path)\n }).catch(() => {})\n return task\n}\n\n// Windows can briefly lock a file (antivirus, indexer); retry the rename a few times.\nasync function renameWithRetry(from: string, to: string) {\n for (let attempt = 0; ; attempt++) {\n try {\n return await rename(from, to)\n } catch (error: any) {\n if (attempt >= 5 || !['EPERM', 'EACCES', 'EBUSY'].includes(error?.code)) {\n await rm(from, { force: true })\n throw error\n }\n await new Promise((resolve) => setTimeout(resolve, 20 * 2 ** attempt))\n }\n }\n}\n\nexport function localize(text: string | Record<string, string> | undefined, locale = 'en') {\n if (!text) return ''\n if (typeof text === 'string') return text\n return text[locale] ?? text.en ?? Object.values(text)[0] ?? ''\n}\n\nexport interface FieldText {\n title?: string\n description?: string\n /** Labels of an enum's values, by value. */\n options?: Record<string, string>\n}\n\nexport interface FieldDisplay {\n /** English labels of an enum's values, by value; translations go in `translations[locale].options`. */\n options?: Record<string, string>\n /**\n * How compact forms (the flow editor) show a field: for booleans a checkbox (default) or a\n * switch, for settings that change behavior; otherwise the name of an editor the dashboard\n * provides, such as `commandArgs` (a command's argument list), `people` (users or groups) or\n * `json` (JSON text that may hold references, checked as it is typed).\n */\n widget?: 'checkbox' | 'switch' | 'commandArgs' | 'people' | 'prompt' | 'message' | 'json'\n /** Compact forms fold descriptions into a hint icon; `inline` keeps this one visible. */\n hint?: 'inline'\n /**\n * A read action that lists the values a text field can take, as `{ value, label }[]`, such as\n * `personas.choices`. Forms show a searchable select that still accepts other text.\n */\n choices?: string\n /**\n * A key, token or password. Its value is kept in the instance's `.env` and the config holds a `${NAME}`\n * reference; forms show a password input, and lists show the value masked. Only top-level fields.\n */\n secret?: boolean\n}\n\n/**\n * Metadata for a config field, shown by dashboard forms: an English title and description,\n * plus translations keyed by locale. Use with zod's `.meta()`.\n */\nexport function field(title: string, description?: string, translations: Record<string, FieldText> = {}, display: FieldDisplay = {}) {\n return {\n title,\n ...(description ? { description } : {}),\n 'x-i18n': translations,\n ...(display.options ? { 'x-options': display.options } : {}),\n ...(display.widget ? { 'x-widget': display.widget } : {}),\n ...(display.hint ? { 'x-hint': display.hint } : {}),\n ...(display.choices ? { 'x-choices': display.choices } : {}),\n ...(display.secret ? { 'x-secret': true } : {}),\n }\n}\n\n/** Source category of a log line, for quick filters in the dashboard. */\nexport const LOG_TAGS = ['message', 'plugin', 'bot', 'adapter', 'flow', 'provider', '
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto'\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\n\nexport function randomId(bytes = 6) {\n return randomBytes(bytes).toString('base64url')\n}\n\n/** Masks a secret for display: `sk-abcdef123456` becomes `sk-…3456`. */\nexport function mask(secret: string | undefined | null) {\n if (!secret) return ''\n if (secret.length <= 8) return '••••'\n return `${secret.slice(0, 3)}…${secret.slice(-4)}`\n}\n\nexport function isMasked(value: unknown) {\n return typeof value === 'string' && (value === '••••' || /^.{0,3}….{4}$/.test(value))\n}\n\nexport async function readJson<T>(path: string): Promise<T | undefined> {\n try {\n return JSON.parse(await readFile(path, 'utf8'))\n } catch (error: any) {\n if (error?.code === 'ENOENT') return undefined\n throw error\n }\n}\n\nconst writeQueues = new Map<string, Promise<void>>()\n\n/**\n * Writes JSON through a temp file and a rename, so a crash never leaves a half-written file.\n * Writes to the same path are serialized.\n */\nexport function writeJsonAtomic(path: string, value: unknown) {\n return writeTextAtomic(path, () => JSON.stringify(value, null, 2) + '\\n')\n}\n\n/**\n * Writes a text file through a temp file and a rename. Writes to the same path are serialized;\n * a function is called when the write's turn comes, so it can build on what the last write left.\n */\nexport function writeTextAtomic(path: string, text: string | (() => string | Promise<string>), options: { mode?: number } = {}) {\n const previous = writeQueues.get(path) ?? Promise.resolve()\n const task = previous.catch(() => {}).then(async () => {\n const content = typeof text === 'function' ? await text() : text\n await mkdir(dirname(path), { recursive: true })\n const temp = `${path}.${randomId(4)}.tmp`\n await writeFile(temp, content, { encoding: 'utf8', mode: options.mode })\n await renameWithRetry(temp, path)\n })\n writeQueues.set(path, task)\n task.finally(() => {\n if (writeQueues.get(path) === task) writeQueues.delete(path)\n }).catch(() => {})\n return task\n}\n\n// Windows can briefly lock a file (antivirus, indexer); retry the rename a few times.\nasync function renameWithRetry(from: string, to: string) {\n for (let attempt = 0; ; attempt++) {\n try {\n return await rename(from, to)\n } catch (error: any) {\n if (attempt >= 5 || !['EPERM', 'EACCES', 'EBUSY'].includes(error?.code)) {\n await rm(from, { force: true })\n throw error\n }\n await new Promise((resolve) => setTimeout(resolve, 20 * 2 ** attempt))\n }\n }\n}\n\nexport function localize(text: string | Record<string, string> | undefined, locale = 'en') {\n if (!text) return ''\n if (typeof text === 'string') return text\n return text[locale] ?? text.en ?? Object.values(text)[0] ?? ''\n}\n\nexport interface FieldText {\n title?: string\n description?: string\n /** Labels of an enum's values, by value. */\n options?: Record<string, string>\n}\n\nexport interface FieldDisplay {\n /** English labels of an enum's values, by value; translations go in `translations[locale].options`. */\n options?: Record<string, string>\n /**\n * How compact forms (the flow editor) show a field: for booleans a checkbox (default) or a\n * switch, for settings that change behavior; otherwise the name of an editor the dashboard\n * provides, such as `commandArgs` (a command's argument list), `people` (users or groups) or\n * `json` (JSON text that may hold references, checked as it is typed).\n */\n widget?: 'checkbox' | 'switch' | 'commandArgs' | 'people' | 'prompt' | 'message' | 'json'\n /** Compact forms fold descriptions into a hint icon; `inline` keeps this one visible. */\n hint?: 'inline'\n /**\n * A read action that lists the values a text field can take, as `{ value, label }[]`, such as\n * `personas.choices`. Forms show a searchable select that still accepts other text.\n */\n choices?: string\n /**\n * A key, token or password. Its value is kept in the instance's `.env` and the config holds a `${NAME}`\n * reference; forms show a password input, and lists show the value masked. Only top-level fields.\n */\n secret?: boolean\n}\n\n/**\n * Metadata for a config field, shown by dashboard forms: an English title and description,\n * plus translations keyed by locale. Use with zod's `.meta()`.\n */\nexport function field(title: string, description?: string, translations: Record<string, FieldText> = {}, display: FieldDisplay = {}) {\n return {\n title,\n ...(description ? { description } : {}),\n 'x-i18n': translations,\n ...(display.options ? { 'x-options': display.options } : {}),\n ...(display.widget ? { 'x-widget': display.widget } : {}),\n ...(display.hint ? { 'x-hint': display.hint } : {}),\n ...(display.choices ? { 'x-choices': display.choices } : {}),\n ...(display.secret ? { 'x-secret': true } : {}),\n }\n}\n\n/** Source category of a log line, for quick filters in the dashboard. */\nexport const LOG_TAGS = ['message', 'plugin', 'bot', 'adapter', 'flow', 'provider', 'fairy', 'system', 'other'] as const\n\nexport type LogTag = typeof LOG_TAGS[number]\n\nconst logTags: Record<string, LogTag> = {\n plugin: 'plugin',\n manager: 'plugin',\n 'llm-chat': 'plugin',\n message: 'message',\n bot: 'bot',\n bots: 'bot',\n onebot: 'adapter',\n qq: 'adapter',\n discord: 'adapter',\n telegram: 'adapter',\n kook: 'adapter',\n flow: 'flow',\n flows: 'flow',\n provider: 'provider',\n providers: 'provider',\n llm: 'provider',\n fairy: 'fairy',\n app: 'system',\n console: 'system',\n server: 'system',\n storage: 'system',\n}\n\n/** The tag of a logger name; `provider:openai` and `provider` share one. */\nexport function logTag(name: string): LogTag {\n return logTags[name.split(':')[0]] ?? 'other'\n}\n"],"mappings":";;;;AAIA,SAAgB,SAAS,QAAQ,GAAG;CAClC,OAAO,YAAY,KAAK,CAAC,CAAC,SAAS,WAAW;AAChD;;AAGA,SAAgB,KAAK,QAAmC;CACtD,IAAI,CAAC,QAAQ,OAAO;CACpB,IAAI,OAAO,UAAU,GAAG,OAAO;CAC/B,OAAO,GAAG,OAAO,MAAM,GAAG,CAAC,EAAE,GAAG,OAAO,MAAM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