@mushinjs/core 0.2.0 → 0.3.0-next.20261122141505
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 +1 -1
- package/dist/actions.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/manager.d.ts +12 -1
- package/dist/manager.js +56 -8
- package/dist/manager.js.map +1 -1
- package/dist/utils.d.ts +6 -0
- package/dist/utils.js +2 -1
- package/dist/utils.js.map +1 -1
- package/package.json +1 -1
package/dist/actions.d.ts
CHANGED
|
@@ -15,7 +15,7 @@ declare module 'cordis' {
|
|
|
15
15
|
}
|
|
16
16
|
export type Risk = 'read' | 'write' | 'dangerous';
|
|
17
17
|
export interface ActionCaller {
|
|
18
|
-
kind: 'api' | 'agent' | 'internal';
|
|
18
|
+
kind: 'api' | 'agent' | 'mcp' | 'internal';
|
|
19
19
|
/** Agent session id, when the Agent made the call. */
|
|
20
20
|
session?: string;
|
|
21
21
|
/** Dashboard connection id, used to route client actions back to the right tab. */
|
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' | '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,IAAI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AO;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, 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,IAA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ANGED
|
@@ -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, pluginSchema, unwrapPlugin, validatePluginConfig } from "./manager.js";
|
|
5
|
+
import { InstanceConfig, ManagerOptions, MissingDependency, PluginEntry, PluginManager, PluginStatus, 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, messageType, parseEnv, parseVersion, planDisable, planEnable, pluginSchema, providerOf, randomId, readJson, readPackageJson, resolveEnvReferences, resolvePackageEntry, satisfies, scanCatalog, 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, 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 };
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import { Actions, fromToolName, toJsonSchema, toToolName } from "./actions.js";
|
|
|
2
2
|
import { 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 { MushinError, toErrorPayload } from "./errors.js";
|
|
5
|
-
import { PluginManager, describeMissing, fiberError, fiberStatus, knownManifest, pluginSchema, unwrapPlugin, validatePluginConfig } from "./manager.js";
|
|
5
|
+
import { PluginManager, describeMissing, fiberError, fiberStatus, knownManifest, maskSecrets, pluginSchema, restoreMasked, secretFields, unwrapPlugin, validatePluginConfig } from "./manager.js";
|
|
6
6
|
import { MUSHIN_VERSION, currentPackageName, dependencyPlugins, manifestProblems, readPackageJson, resolvePackageEntry, scanCatalog } from "./manifest.js";
|
|
7
7
|
import { messageType, seg, segmentsToText, toSegments } from "./message.js";
|
|
8
8
|
import { compareVersions, parseVersion, satisfies, validRange } from "./semver.js";
|
|
@@ -10,4 +10,4 @@ import { LOG_TAGS, field, isMasked, localize, logTag, mask, randomId, readJson,
|
|
|
10
10
|
import { usage } from "./usage.js";
|
|
11
11
|
import { z } from "zod";
|
|
12
12
|
export * from "cordis";
|
|
13
|
-
export { Actions, EnvFile, LOG_TAGS, MUSHIN_VERSION, MushinError, PluginManager, compareVersions, currentPackageName, dependencyPlugins, dependencyReport, describeMissing, envName, envReference, fiberError, fiberStatus, field, fromToolName, injectedServices, isEnvName, isMasked, knownManifest, loadOrder, localize, logTag, manifestProblems, mask, messageType, parseEnv, parseVersion, planDisable, planEnable, pluginSchema, providerOf, randomId, readJson, readPackageJson, resolveEnvReferences, resolvePackageEntry, satisfies, scanCatalog, seg, segmentsToText, toErrorPayload, toJsonSchema, toSegments, toToolName, undeclaredServices, unmet, unwrapPlugin, updateEnvText, usage, validRange, validatePluginConfig, writeJsonAtomic, writeTextAtomic, z };
|
|
13
|
+
export { Actions, EnvFile, LOG_TAGS, MUSHIN_VERSION, MushinError, PluginManager, 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
|
@@ -46,6 +46,12 @@ export declare function fiberError(fiber: Fiber | undefined): string | undefined
|
|
|
46
46
|
export declare function unwrapPlugin(mod: any): Plugin;
|
|
47
47
|
/** JSON Schema of a plugin's zod `Config`, if it has one. */
|
|
48
48
|
export declare function pluginSchema(plugin: Plugin): JsonSchema | undefined;
|
|
49
|
+
/** The top-level config fields a plugin marks as secret, with `field(…, { secret: true })`. */
|
|
50
|
+
export declare function secretFields(plugin: Plugin): string[];
|
|
51
|
+
/** A config with the plain values of `keys` masked, for lists. `${NAME}` references show where the value is. */
|
|
52
|
+
export declare function maskSecrets<T extends Record<string, any>>(config: T, keys: string[]): T;
|
|
53
|
+
/** A config sent back from a form: masked values keep what was saved before. */
|
|
54
|
+
export declare function restoreMasked<T extends Record<string, any>>(config: T, previous: Record<string, any> | undefined, keys: string[]): T;
|
|
49
55
|
export declare function validatePluginConfig(plugin: Plugin, config: unknown): unknown;
|
|
50
56
|
export declare function knownManifest(name: string): PluginManifest;
|
|
51
57
|
/**
|
|
@@ -64,6 +70,11 @@ export declare class PluginManager extends Service {
|
|
|
64
70
|
/** Entries that were not started because a dependency is missing or they form a cycle. */
|
|
65
71
|
private blocked;
|
|
66
72
|
constructor(ctx: Context, options: ManagerOptions);
|
|
73
|
+
private envFile?;
|
|
74
|
+
/** The instance's `.env`, where secret config fields are kept. */
|
|
75
|
+
private get env();
|
|
76
|
+
/** Moves the plain values of an entry's secret fields into `.env`, leaving `${NAME}` references. */
|
|
77
|
+
private secure;
|
|
67
78
|
/** Plugin lifecycle lines, tagged `plugin` in the dashboard. */
|
|
68
79
|
private get logger();
|
|
69
80
|
get entries(): PluginEntry[];
|
|
@@ -127,7 +138,7 @@ export declare class PluginManager extends Service {
|
|
|
127
138
|
private disableOne;
|
|
128
139
|
/** Starts entries that were held back for a missing dependency, once it is there. */
|
|
129
140
|
private retryBlocked;
|
|
130
|
-
configure(id: string,
|
|
141
|
+
configure(id: string, input: Record<string, any>): Promise<PluginEntry>;
|
|
131
142
|
reload(id: string): Promise<PluginEntry>;
|
|
132
143
|
private require;
|
|
133
144
|
describe(entry: PluginEntry): Promise<{
|
package/dist/manager.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { toJsonSchema } from "./actions.js";
|
|
2
2
|
import { dependencyReport, injectedServices, loadOrder, planDisable, planEnable, providerOf, undeclaredServices } from "./dependencies.js";
|
|
3
3
|
import { MushinError } from "./errors.js";
|
|
4
|
-
import { resolveEnvReferences } from "./env.js";
|
|
4
|
+
import { EnvFile, envReference, resolveEnvReferences } from "./env.js";
|
|
5
5
|
import { MUSHIN_VERSION, manifestProblems, readPackageJson, resolvePackageEntry, scanCatalog } from "./manifest.js";
|
|
6
|
-
import { writeJsonAtomic } from "./utils.js";
|
|
6
|
+
import { isMasked, mask, writeJsonAtomic } from "./utils.js";
|
|
7
7
|
import { Service } from "cordis";
|
|
8
8
|
import { z } from "zod";
|
|
9
|
+
import { dirname, join } from "node:path";
|
|
9
10
|
import { pathToFileURL } from "node:url";
|
|
10
11
|
// src/manager.ts
|
|
11
12
|
const fiberStates = [
|
|
@@ -37,6 +38,25 @@ function pluginSchema(plugin) {
|
|
|
37
38
|
const config = plugin.Config;
|
|
38
39
|
if (config && typeof config === "object" && "_zod" in config) return toJsonSchema(config);
|
|
39
40
|
}
|
|
41
|
+
/** The top-level config fields a plugin marks as secret, with `field(…, { secret: true })`. */
|
|
42
|
+
function secretFields(plugin) {
|
|
43
|
+
const properties = pluginSchema(plugin)?.properties ?? {};
|
|
44
|
+
return Object.keys(properties).filter((key) => properties[key]?.["x-secret"] === true);
|
|
45
|
+
}
|
|
46
|
+
/** A config with the plain values of `keys` masked, for lists. `${NAME}` references show where the value is. */
|
|
47
|
+
function maskSecrets(config, keys) {
|
|
48
|
+
if (!keys.length) return config;
|
|
49
|
+
const next = { ...config };
|
|
50
|
+
for (const key of keys) if (typeof next[key] === "string" && next[key] && envReference(next[key]) === void 0) next[key] = mask(next[key]);
|
|
51
|
+
return next;
|
|
52
|
+
}
|
|
53
|
+
/** A config sent back from a form: masked values keep what was saved before. */
|
|
54
|
+
function restoreMasked(config, previous, keys) {
|
|
55
|
+
if (!keys.length) return config;
|
|
56
|
+
const next = { ...config };
|
|
57
|
+
for (const key of keys) if (isMasked(next[key])) next[key] = previous?.[key];
|
|
58
|
+
return next;
|
|
59
|
+
}
|
|
40
60
|
function validatePluginConfig(plugin, config) {
|
|
41
61
|
const schema = plugin.Config;
|
|
42
62
|
if (!schema || typeof schema !== "object" || !("_zod" in schema)) return config;
|
|
@@ -82,6 +102,21 @@ var PluginManager = class extends Service {
|
|
|
82
102
|
this.options = options;
|
|
83
103
|
this.home = ctx;
|
|
84
104
|
}
|
|
105
|
+
envFile;
|
|
106
|
+
/** The instance's `.env`, where secret config fields are kept. */
|
|
107
|
+
get env() {
|
|
108
|
+
return this.envFile ??= new EnvFile(join(dirname(this.options.configPath), ".env")).loadSync();
|
|
109
|
+
}
|
|
110
|
+
/** Moves the plain values of an entry's secret fields into `.env`, leaving `${NAME}` references. */
|
|
111
|
+
async secure(entry, plugin, config, previous) {
|
|
112
|
+
const keys = secretFields(plugin);
|
|
113
|
+
if (!keys.length) return config;
|
|
114
|
+
return (await this.env.moveIn(config, {
|
|
115
|
+
keys,
|
|
116
|
+
name: [entry.id],
|
|
117
|
+
previous
|
|
118
|
+
})).config;
|
|
119
|
+
}
|
|
85
120
|
/** Plugin lifecycle lines, tagged `plugin` in the dashboard. */
|
|
86
121
|
get logger() {
|
|
87
122
|
return this.home.logger("plugin");
|
|
@@ -255,6 +290,14 @@ var PluginManager = class extends Service {
|
|
|
255
290
|
}
|
|
256
291
|
this.blocked.delete(entry.id);
|
|
257
292
|
const plugin = await this.loadPlugin(entry.package);
|
|
293
|
+
if (entry.config) {
|
|
294
|
+
const secured = await this.secure(entry, plugin, entry.config, entry.config);
|
|
295
|
+
if (secured !== entry.config && JSON.stringify(secured) !== JSON.stringify(entry.config)) {
|
|
296
|
+
entry.config = secured;
|
|
297
|
+
await this.save();
|
|
298
|
+
this.logger.info("moved the secret settings of %s to .env", entry.id);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
258
301
|
for (const { service, provider } of undeclaredServices(this.graphNow(), entry.package, plugin)) {
|
|
259
302
|
const local = this.catalogList.find((item) => item.package === entry.package)?.local;
|
|
260
303
|
this.logger[local ? "warn" : "debug"]("%s injects \"%s\" but does not declare %s in its manifest's requires or optional", entry.package, service, provider);
|
|
@@ -354,10 +397,12 @@ var PluginManager = class extends Service {
|
|
|
354
397
|
await this.start(entry).catch((error) => this.logger.error("failed to load %s: %s", entry.package, error));
|
|
355
398
|
}
|
|
356
399
|
}
|
|
357
|
-
async configure(id,
|
|
400
|
+
async configure(id, input) {
|
|
358
401
|
const entry = this.require(id);
|
|
359
|
-
|
|
360
|
-
|
|
402
|
+
const plugin = await this.loadPlugin(entry.package);
|
|
403
|
+
const config = restoreMasked(input, entry.config, secretFields(plugin));
|
|
404
|
+
validatePluginConfig(plugin, config);
|
|
405
|
+
entry.config = await this.secure(entry, plugin, config, entry.config);
|
|
361
406
|
await this.save();
|
|
362
407
|
this.logger.info("config of %s changed", id);
|
|
363
408
|
if (entry.enabled !== false) await this.start(entry);
|
|
@@ -379,15 +424,18 @@ var PluginManager = class extends Service {
|
|
|
379
424
|
async describe(entry) {
|
|
380
425
|
const catalog = await this.findPackage(entry.package);
|
|
381
426
|
let configSchema;
|
|
427
|
+
let secrets = [];
|
|
382
428
|
try {
|
|
383
|
-
|
|
429
|
+
const plugin = await this.loadPlugin(entry.package);
|
|
430
|
+
configSchema = pluginSchema(plugin);
|
|
431
|
+
secrets = secretFields(plugin);
|
|
384
432
|
} catch {}
|
|
385
433
|
const report = dependencyReport(this.graphNow(), entry.package);
|
|
386
434
|
return {
|
|
387
435
|
id: entry.id,
|
|
388
436
|
package: entry.package,
|
|
389
437
|
enabled: entry.enabled !== false,
|
|
390
|
-
config: entry.config ?? {},
|
|
438
|
+
config: maskSecrets(entry.config ?? {}, secrets),
|
|
391
439
|
configSchema,
|
|
392
440
|
manifest: catalog?.manifest ?? knownManifests[entry.package],
|
|
393
441
|
version: catalog?.version,
|
|
@@ -483,6 +531,6 @@ function describeMissing(missing) {
|
|
|
483
531
|
}
|
|
484
532
|
}).join(", ");
|
|
485
533
|
}
|
|
486
|
-
export { PluginManager, describeMissing, fiberError, fiberStatus, knownManifest, pluginSchema, unwrapPlugin, validatePluginConfig };
|
|
534
|
+
export { PluginManager, describeMissing, fiberError, fiberStatus, knownManifest, maskSecrets, pluginSchema, restoreMasked, secretFields, unwrapPlugin, validatePluginConfig };
|
|
487
535
|
|
|
488
536
|
//# sourceMappingURL=manager.js.map
|
package/dist/manager.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.js","names":[],"sources":["../src/manager.ts"],"sourcesContent":["import { 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 { resolveEnvReferences } from './env'\nimport { type CatalogEntry, manifestProblems, MUSHIN_VERSION, type PluginManifest, readPackageJson, resolvePackageEntry, scanCatalog } from './manifest'\nimport { 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\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 /** 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 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, config: Record<string, any>) {\n const entry = this.require(id)\n const plugin = await this.loadPlugin(entry.package)\n validatePluginConfig(plugin, config)\n entry.config = 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 try {\n configSchema = pluginSchema(await this.loadPlugin(entry.package))\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: entry.config ?? {},\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":";;;;;;;;;;AA2DA,MAAM,cAA8B;CAAC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+
{"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,MAChB,IAAI,OAAO,KAAK,SAAS,YAAY,KAAK,QAAQ,aAAa,KAAK,IAAI,MAAM,KAAA,GAAW,KAAK,OAAO,KAAK,KAAK,IAAI;CAErH,OAAO;AACT;;AAGA,SAAgB,cAA6C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,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/utils.d.ts
CHANGED
|
@@ -39,12 +39,18 @@ export interface FieldDisplay {
|
|
|
39
39
|
* `personas.choices`. Forms show a searchable select that still accepts other text.
|
|
40
40
|
*/
|
|
41
41
|
choices?: string;
|
|
42
|
+
/**
|
|
43
|
+
* A key, token or password. Its value is kept in the instance's `.env` and the config holds a `${NAME}`
|
|
44
|
+
* reference; forms show a password input, and lists show the value masked. Only top-level fields.
|
|
45
|
+
*/
|
|
46
|
+
secret?: boolean;
|
|
42
47
|
}
|
|
43
48
|
/**
|
|
44
49
|
* Metadata for a config field, shown by dashboard forms: an English title and description,
|
|
45
50
|
* plus translations keyed by locale. Use with zod's `.meta()`.
|
|
46
51
|
*/
|
|
47
52
|
export declare function field(title: string, description?: string, translations?: Record<string, FieldText>, display?: FieldDisplay): {
|
|
53
|
+
'x-secret'?: boolean | undefined;
|
|
48
54
|
'x-choices'?: string | undefined;
|
|
49
55
|
'x-hint'?: "inline" | undefined;
|
|
50
56
|
'x-widget'?: "message" | "checkbox" | "switch" | "commandArgs" | "people" | "prompt" | "json" | undefined;
|
package/dist/utils.js
CHANGED
|
@@ -83,7 +83,8 @@ function field(title, description, translations = {}, display = {}) {
|
|
|
83
83
|
...display.options ? { "x-options": display.options } : {},
|
|
84
84
|
...display.widget ? { "x-widget": display.widget } : {},
|
|
85
85
|
...display.hint ? { "x-hint": display.hint } : {},
|
|
86
|
-
...display.choices ? { "x-choices": display.choices } : {}
|
|
86
|
+
...display.choices ? { "x-choices": display.choices } : {},
|
|
87
|
+
...display.secret ? { "x-secret": true } : {}
|
|
87
88
|
};
|
|
88
89
|
}
|
|
89
90
|
/** Source category of a log line, for quick filters in the dashboard. */
|
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\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 }\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', 'agent', '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 flow: 'flow',\n flows: 'flow',\n provider: 'provider',\n providers: 'provider',\n llm: 'provider',\n agent: 'agent',\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,EAAE;AACjD;AAEA,SAAgB,SAAS,OAAgB;CACvC,OAAO,OAAO,UAAU,aAAa,UAAU,UAAU,gBAAgB,KAAK,KAAK;AACrF;AAEA,eAAsB,SAAY,MAAsC;CACtE,IAAI;EACF,OAAO,KAAK,MAAM,MAAM,SAAS,MAAM,MAAM,CAAC;CAChD,SAAS,OAAY;EACnB,IAAI,OAAO,SAAS,UAAU,OAAO,KAAA;EACrC,MAAM;CACR;AACF;AAEA,MAAM,8BAAc,IAAI,IAA2B;;;;;AAMnD,S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MAAM,OAAO,OAAO,IAAI,CAAC,CAAC,MAAM;AAC9D;;;;;
|
|
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', 'agent', '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 flow: 'flow',\n flows: 'flow',\n provider: 'provider',\n providers: 'provider',\n llm: 'provider',\n agent: 'agent',\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,EAAE;AACjD;AAEA,SAAgB,SAAS,OAAgB;CACvC,OAAO,OAAO,UAAU,aAAa,UAAU,UAAU,gBAAgB,KAAK,KAAK;AACrF;AAEA,eAAsB,SAAY,MAAsC;CACtE,IAAI;EACF,OAAO,KAAK,MAAM,MAAM,SAAS,MAAM,MAAM,CAAC;CAChD,SAAS,OAAY;EACnB,IAAI,OAAO,SAAS,UAAU,OAAO,KAAA;EACrC,MAAM;CACR;AACF;AAEA,MAAM,8BAAc,IAAI,IAA2B;;;;;AAMnD,SAAgB,gBAAgB,MAAc,OAAgB;CAC5D,OAAO,gBAAgB,YAAY,KAAK,UAAU,OAAO,MAAM,CAAC,IAAI,IAAI;AAC1E;;;;;AAMA,SAAgB,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