refactor: restructure PrismFacet per OpenClaw plugin spec

- plugin/ directory structure: hooks/, tools/, core/
- export default { id, name, register } entry format
- globalThis state management with lifecycle protection
- WeakSet dedup on before_prompt_build hook
- Tool uses inputSchema + execute (not parameters + handler)
- additionalProperties: false in config schema
- Core logic in plugin/core/ (no plugin-sdk dependency)
- Install/uninstall script (scripts/install.mjs)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
zhi
2026-04-18 17:22:17 +00:00
parent c4a72b13c0
commit d5c057a3f9
17 changed files with 502 additions and 306 deletions

View File

@@ -0,0 +1,41 @@
import { readFileSync } from "node:fs";
import { getRouters } from "./router-loader.js";
import { getRule } from "./rule-store.js";
import type { RouterContext } from "./router-loader.js";
export interface InjectionResult {
appendSystemContext?: string;
}
export async function resolveInjection(
ctx: RouterContext,
log: { info(msg: string): void; warn(msg: string): void }
): Promise<InjectionResult> {
const routers = getRouters();
const segments: string[] = [];
for (const router of routers) {
try {
const key = await router.module.resolve(ctx);
if (!key) continue;
const promptFile = getRule(router.name, key);
if (!promptFile) continue;
try {
const content = readFileSync(promptFile, "utf8").trim();
if (content) {
segments.push(content);
log.info(`[prism-facet] injecting ${router.name}:${key}${promptFile}`);
}
} catch (err) {
log.warn(`[prism-facet] cannot read ${promptFile}: ${String(err)}`);
}
} catch (err) {
log.warn(`[prism-facet] router ${router.name} failed: ${String(err)}`);
}
}
if (segments.length === 0) return {};
return { appendSystemContext: segments.join("\n\n---\n\n") };
}

View File

@@ -0,0 +1,77 @@
import { readdirSync } from "node:fs";
import path from "node:path";
export interface RouterContext {
agentId: string;
}
export interface RouterModule {
resolve(ctx: RouterContext): string | Promise<string>;
}
export interface LoadedRouter {
name: string;
filePath: string;
module: RouterModule;
}
const _G = globalThis as Record<string, unknown>;
const ROUTERS_KEY = "_prismFacetRouters";
const LOAD_COUNTER_KEY = "_prismFacetLoadCounter";
function getRouterMap(): Map<string, LoadedRouter> {
if (!(_G[ROUTERS_KEY] instanceof Map)) {
_G[ROUTERS_KEY] = new Map<string, LoadedRouter>();
}
return _G[ROUTERS_KEY] as Map<string, LoadedRouter>;
}
function routerNameFromFile(filename: string): string {
return filename.replace(/\.(ts|js|mjs)$/, "");
}
export async function loadRouters(
routersDir: string,
log: { info(msg: string): void; warn(msg: string): void }
): Promise<void> {
const map = getRouterMap();
map.clear();
if (typeof _G[LOAD_COUNTER_KEY] !== "number") _G[LOAD_COUNTER_KEY] = 0;
(_G[LOAD_COUNTER_KEY] as number)++;
const counter = _G[LOAD_COUNTER_KEY] as number;
let files: string[];
try {
files = readdirSync(routersDir).filter(
(f) => /\.(ts|js|mjs)$/.test(f) && !f.startsWith(".")
);
} catch {
log.warn(`[prism-facet] routers directory not found: ${routersDir}`);
return;
}
for (const file of files) {
const name = routerNameFromFile(file);
const filePath = path.resolve(routersDir, file);
try {
const mod = (await import(`${filePath}?v=${counter}`)) as RouterModule;
if (typeof mod.resolve !== "function") {
log.warn(`[prism-facet] router ${name}: no resolve() export, skipping`);
continue;
}
map.set(name, { name, filePath, module: mod });
log.info(`[prism-facet] router loaded: ${name}`);
} catch (err) {
log.warn(`[prism-facet] router ${name}: failed to load — ${String(err)}`);
}
}
}
export function getRouters(): LoadedRouter[] {
return Array.from(getRouterMap().values());
}
export function getRouterNames(): string[] {
return Array.from(getRouterMap().keys());
}

56
plugin/core/rule-store.ts Normal file
View File

@@ -0,0 +1,56 @@
import { readFileSync, writeFileSync } from "node:fs";
export type RuleStore = Record<string, string>; // "router:key" → prompt file path
const _G = globalThis as Record<string, unknown>;
const RULES_KEY = "_prismFacetRules";
const RULES_PATH_KEY = "_prismFacetRulesPath";
function getRules(): RuleStore {
if (!_G[RULES_KEY] || typeof _G[RULES_KEY] !== "object") {
_G[RULES_KEY] = {};
}
return _G[RULES_KEY] as RuleStore;
}
function getRulesPath(): string {
return (_G[RULES_PATH_KEY] as string) || "";
}
function save(): void {
const p = getRulesPath();
if (!p) return;
writeFileSync(p, JSON.stringify(getRules(), null, 2) + "\n", "utf8");
}
export function initRuleStore(filePath: string): void {
_G[RULES_PATH_KEY] = filePath;
try {
const raw = readFileSync(filePath, "utf8");
_G[RULES_KEY] = JSON.parse(raw) as RuleStore;
} catch {
_G[RULES_KEY] = {};
}
}
export function addRule(router: string, key: string, promptFile: string): void {
getRules()[`${router}:${key}`] = promptFile;
save();
}
export function removeRule(router: string, key: string): boolean {
const rules = getRules();
const ruleKey = `${router}:${key}`;
if (!(ruleKey in rules)) return false;
delete rules[ruleKey];
save();
return true;
}
export function getRule(router: string, key: string): string | undefined {
return getRules()[`${router}:${key}`];
}
export function listRules(): Record<string, string> {
return { ...getRules() };
}

View File

@@ -0,0 +1,25 @@
import { resolveInjection } from "../core/prompt-injector.js";
const _G = globalThis as Record<string, unknown>;
const DEDUP_KEY = "_prismFacetBPBDedup";
export function registerBeforePromptBuild(api: {
on(hook: string, handler: (...args: any[]) => any): void;
logger: { info(msg: string): void; warn(msg: string): void };
}): void {
if (!(_G[DEDUP_KEY] instanceof WeakSet)) _G[DEDUP_KEY] = new WeakSet<object>();
const dedup = _G[DEDUP_KEY] as WeakSet<object>;
api.on("before_prompt_build", async (event: unknown, ctx: { agentId?: string }) => {
if (dedup.has(event as object)) return;
dedup.add(event as object);
const agentId = ctx.agentId || "";
if (!agentId) return;
const result = await resolveInjection({ agentId }, api.logger);
if (result.appendSystemContext) {
return { appendSystemContext: result.appendSystemContext };
}
});
}

66
plugin/index.ts Normal file
View File

@@ -0,0 +1,66 @@
import path from "node:path";
import { loadRouters } from "./core/router-loader.js";
import { initRuleStore } from "./core/rule-store.js";
import { registerBeforePromptBuild } from "./hooks/before-prompt-build.js";
import { registerPromptRulesTool } from "./tools/prompt-rules.js";
interface PluginConfig {
routersDir?: string;
rulesFile?: string;
}
interface OpenClawPluginApi {
logger: {
info(msg: string): void;
warn(msg: string): void;
error(msg: string): void;
};
on(hook: string, handler: (...args: any[]) => any): void;
registerTool(def: any): void;
config?: PluginConfig;
}
const _G = globalThis as Record<string, unknown>;
const LIFECYCLE_KEY = "_prismFacetGatewayLifecycleRegistered";
function normalizeConfig(api: OpenClawPluginApi): PluginConfig {
const raw = (api as any).config ?? {};
return {
routersDir: typeof raw.routersDir === "string" ? raw.routersDir : undefined,
rulesFile: typeof raw.rulesFile === "string" ? raw.rulesFile : undefined,
};
}
export default {
id: "prism-facet",
name: "PrismFacet",
register(api: OpenClawPluginApi) {
const config = normalizeConfig(api);
const pluginDir = path.dirname(new URL(import.meta.url).pathname);
const routersDir = config.routersDir || path.resolve(pluginDir, "..", "routers");
const rulesFile = config.rulesFile || path.resolve(pluginDir, "..", "rules.json");
// Gateway lifecycle: init once
if (!_G[LIFECYCLE_KEY]) {
_G[LIFECYCLE_KEY] = true;
initRuleStore(rulesFile);
loadRouters(routersDir, api.logger).catch((err) => {
api.logger.error(`[prism-facet] failed to load routers: ${String(err)}`);
});
api.on("gateway_stop", () => {
_G[LIFECYCLE_KEY] = false;
});
}
// Agent session hooks: register every time (dedup inside handler)
registerBeforePromptBuild(api);
// Tools
registerPromptRulesTool(api, routersDir);
api.logger.info("[prism-facet] plugin registered");
},
};

View File

@@ -0,0 +1,21 @@
{
"id": "prism-facet",
"name": "PrismFacet",
"version": "0.1.0",
"description": "Dynamic system prompt injection via routers and rules",
"main": "index.js",
"configSchema": {
"type": "object",
"additionalProperties": false,
"properties": {
"routersDir": {
"type": "string",
"description": "Directory containing router .ts/.js files (default: {pluginDir}/routers)"
},
"rulesFile": {
"type": "string",
"description": "Path to rules.json (default: {pluginDir}/rules.json)"
}
}
}
}

6
plugin/package.json Normal file
View File

@@ -0,0 +1,6 @@
{
"name": "prism-facet",
"version": "0.1.0",
"type": "module",
"main": "index.js"
}

View File

@@ -0,0 +1,106 @@
import { addRule, removeRule, listRules } from "../core/rule-store.js";
import { loadRouters, getRouterNames } from "../core/router-loader.js";
import { resolveInjection } from "../core/prompt-injector.js";
export function registerPromptRulesTool(
api: {
registerTool(def: any): void;
logger: { info(msg: string): void; warn(msg: string): void };
},
routersDir: string
): void {
api.registerTool({
name: "prompt_rules",
description:
"Manage PrismFacet prompt injection rules. " +
"Actions: add (register a rule mapping router:key to a prompt file), " +
"remove (delete a rule), list (show all rules), " +
"test (preview which prompts would be injected for an agent), " +
"reload-routers (hot-reload all router functions), " +
"list-routers (show loaded routers).",
inputSchema: {
type: "object",
properties: {
action: {
type: "string",
enum: ["add", "remove", "list", "test", "reload-routers", "list-routers"],
description: "The action to perform",
},
router: {
type: "string",
description: "Router name (for add/remove)",
},
key: {
type: "string",
description: "Rule key (for add/remove)",
},
file: {
type: "string",
description: "Absolute path to prompt file (for add)",
},
agent: {
type: "string",
description: "Agent ID to test (for test)",
},
},
required: ["action"],
},
execute: async (_toolCallId: string, params: Record<string, unknown>) => {
const action = params.action as string;
const router = params.router as string | undefined;
const key = params.key as string | undefined;
const file = params.file as string | undefined;
const agent = params.agent as string | undefined;
switch (action) {
case "add": {
if (!router || !key || !file) {
return { result: "Error: add requires router, key, and file" };
}
addRule(router, key, file);
return { result: `Rule added: ${router}:${key}${file}` };
}
case "remove": {
if (!router || !key) {
return { result: "Error: remove requires router and key" };
}
const removed = removeRule(router, key);
return {
result: removed
? `Rule removed: ${router}:${key}`
: `Rule not found: ${router}:${key}`,
};
}
case "list": {
const rules = listRules();
const entries = Object.entries(rules);
if (entries.length === 0) return { result: "No rules registered." };
return { result: entries.map(([k, v]) => `${k}${v}`).join("\n") };
}
case "test": {
if (!agent) return { result: "Error: test requires agent" };
const result = await resolveInjection({ agentId: agent }, api.logger);
if (!result.appendSystemContext) {
return { result: `No prompts matched for agent: ${agent}` };
}
return { result: `Matched prompts for ${agent}:\n\n${result.appendSystemContext}` };
}
case "reload-routers": {
await loadRouters(routersDir, api.logger);
const names = getRouterNames();
return { result: `Routers reloaded: ${names.join(", ") || "(none)"}` };
}
case "list-routers": {
const names = getRouterNames();
return {
result: names.length > 0
? `Loaded routers: ${names.join(", ")}`
: "No routers loaded.",
};
}
default:
return { result: `Unknown action: ${action}` };
}
},
});
}