15 Commits

Author SHA1 Message Date
h z
cf03e218af Merge pull request #4 refactor(prism-facet): registration framework + strip content 2026-05-25 09:52:54 +00:00
6dca427187 fix: loadRouters preserves API-registered routers; install.mjs chowns root
Two related fixes:

1. core/router-loader.loadRouters() previously called map.clear() before
   scanning routersDir, which wiped routers registered via
   __prismFacet.addRouter (the cross-plugin API). Now: track which
   entries in the map came from a file vs API (filePath sentinel),
   only delete file-based ones that disappeared between loads. External
   routers are never touched.

2. scripts/install.mjs: chown installed plugin files to root when the
   installer is running as root. openclaw 2026.5+ blocks plugins whose
   files are owned by non-root; rsync/tar from a developer laptop
   silently broke prism-facet on the next gateway restart. Matches the
   Meridian + ClawPrompts install.mjs fix.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 10:31:18 +01:00
cfd2ec445b fix(cross-plugin-api): drain __prismFacetPending queue from early consumers
Plugin load order is undefined. If a consumer (ClawPrompts) loads
before PrismFacet, it can't call __prismFacet.addRouter directly
(slot is undefined). Now it pushes ops onto the well-known
__prismFacetPending array; PrismFacet's installCrossPluginApi()
drains the queue when it runs. Marker __real: true on the installed
API so consumers can tell stub from real.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 10:25:41 +01:00
241cced780 refactor(prism-facet): become a pure registration framework
Strip all Hangman-Lab-specific content out of PrismFacet so it can be
reused by any project. Content (always router, pcexec-convention prompt,
fabric-chat-injector hook) moves to the new sibling plugin ClawPrompts.

Mechanism additions:
- `globalThis.__prismFacet` cross-plugin API installed at module-import
  time (so consumers loaded before PrismFacet can still register):
    .addRouter(name, resolveFn)
    .addRule(router, key, { file })
- core/rule-store: tier rules into `persistent` (rules.json, mutated by
  the prompt-rules admin tool) and `external` (in-memory, registered by
  other plugins via the API). Persistent overrides external on conflict.
- core/router-loader: addExternalRouter() for programmatic registration
  into the same map the file-based loader uses.
- index.ts: drops registerFabricChatInjector wiring, registerBeforePromptBuild
  remains.

Removed (now shipped from ClawPrompts):
- plugin/routers/always.ts
- plugin/hooks/fabric-chat-injector.ts
- plugin/prompts/pcexec-convention.md
- plugin/rules.json: now `{}`; ClawPrompts registers its rule externally

What still lives in PrismFacet:
- before_prompt_build hook (the wiring between routers/rules and the
  agent's system prompt)
- prompt-rules admin tool (lists + mutates persistent rules)
- file-based routersDir / rulesFile scanning (kept for operator ad-hoc
  use; ClawPrompts uses the API instead)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 10:19:39 +01:00
h z
b0fd02c50b Merge pull request '#3 feat(hooks): fabric-chat-injector' into main 2026-05-25 08:56:05 +00:00
33fcd17746 feat(hooks): fabric-chat-injector — suggest chat workflow on channel turns
New before_prompt_build hook that appends a "next action: workflow_start
chat" hint to the system prompt whenever the agent's turn was triggered
by a message in a fabric channel.

If Meridian (`globalThis.__meridian.getChatJournalForChannel`) reports
an existing chat journal for this (agentId, channelId), the hint
includes `from="<journal-id>"` so the agent resumes the conversation
file instead of starting a fresh one each turn.

Activation:
  - ctx.agentId AND ctx.channelId present
  - ctx.messageProvider in {fabric, '' (empty/omitted by gateway)}

TODO(phase-2): once Fabric exposes per-channel type info (DM / group /
triage) via a cross-plugin API, narrow this to xType === 'dm' only.
Today we fire on any fabric channel — chat workflow is a no-op outside
DMs, so the false positives are just prompt-text noise.

Dedup via WeakSet keyed on the event object (same pattern as the
existing before-prompt-build hook) so each turn injects at most once
even when multiple harness call sites trigger the hook.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 09:46:34 +01:00
f3e2e74d36 feat(prism-facet): add 'always' router + Hangman-Lab pcexec convention prompt
The 'always' router resolves to the constant key "always" for every
agent — pair with a rule like 'always:always → some-prompt.md' to
inject a prompt fragment unconditionally (no ego/role/position
lookup needed).

Bundle a site-specific prompt 'pcexec-convention.md' that tells every
agent: Hangman-Lab keeps site binaries at ~/.openclaw/bin (hf,
secret-mgr, ego-mgr, fabric-register, pcguard, lock-mgr, tea) — not
symlinked to /usr/local/bin — so they MUST be invoked via the pcexec
tool, not the codex built-in shell. Without this, agents would call
those CLIs directly and get 'command not found' (observed during the
2026-05-23 hf-wakeup runs on prod t2).

Register the binding in rules.json so it loads at gateway startup.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 08:48:05 +01:00
h z
be5b5f1922 Merge pull request 'fix: declare prompt_rules tool in contracts.tools' (#2) from fix/declare-contracts-tools into main 2026-05-20 14:48:08 +00:00
4d7f7dc6c8 fix: declare prompt_rules tool in contracts.tools
Same class of bug as Meridian (zhi/Meridian#2), HarborForge.OpenclawPlugin
(zhi/HarborForge.OpenclawPlugin#6), and PaddedCell (already fixed in
787d88c). OpenClaw's plugin host requires that any tool registered via
`api.registerTool()` is also declared in `contracts.tools` in the
plugin manifest, or the tool is silently dropped from the agent's
available tool list. plugin doctor was warning:

  prism-facet: plugin must declare contracts.tools before registering
  agent tools

PrismFacet registers exactly one tool, `prompt_rules` (in
tools/prompt-rules.js). Declaring it in the manifest. Verified in sim
that with this change the warning disappears and the tool becomes
visible to agents.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 14:49:42 +01:00
h z
bd851f2b9d Merge pull request 'zhi-2026-04-18' (#1) from zhi-2026-04-18 into main
Reviewed-on: #1
2026-05-01 07:21:25 +00:00
zhi
6a70a68c7e fix: use parameters + content[] format per OpenClaw plugin spec
- inputSchema → parameters
- { result: text } → { content: [{ type: "text", text }] }

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-22 12:04:41 +00:00
zhi
76ac2e959a refactor: remove built-in routers
PrismFacet is a generic framework — routers are registered by
consumers (e.g., ClawRoles), not bundled with the plugin.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-21 10:35:28 +00:00
zhi
bee3dcb84c fix: correct routers/rules path resolution
pluginDir already points to the plugin install root, no need for ..

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-18 19:54:20 +00:00
zhi
d5c057a3f9 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>
2026-04-18 17:22:17 +00:00
zhi
c4a72b13c0 feat: PrismFacet core implementation
- Plugin scaffold: manifest, tsconfig, package.json
- Router loader with dynamic import + cache busting for hot reload
- Rule store: CRUD on rules.json
- Prompt injector: resolve routers → match rules → read files → inject
- MCP tool: prompt_rules (add/remove/list/test/reload-routers/list-routers)
- Built-in routers: agent-id (zero-dep), role, position (ego.json)
- before_prompt_build hook for system prompt injection

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-18 17:12:10 +00:00
18 changed files with 848 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
node_modules/
dist/
plugin/**/*.js
plugin/**/*.js.map

47
package-lock.json generated Normal file
View File

@@ -0,0 +1,47 @@
{
"name": "prism-facet",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "prism-facet",
"version": "0.1.0",
"devDependencies": {
"@types/node": "^25.6.0",
"typescript": "^5.5.0"
}
},
"node_modules/@types/node": {
"version": "25.6.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-25.6.0.tgz",
"integrity": "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~7.19.0"
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "7.19.2",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.19.2.tgz",
"integrity": "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==",
"dev": true,
"license": "MIT"
}
}
}

14
package.json Normal file
View File

@@ -0,0 +1,14 @@
{
"name": "prism-facet",
"version": "0.1.0",
"type": "module",
"scripts": {
"build": "tsc --project tsconfig.plugin.json",
"install-plugin": "node scripts/install.mjs --install",
"uninstall-plugin": "node scripts/install.mjs --uninstall"
},
"devDependencies": {
"@types/node": "^25.6.0",
"typescript": "^5.5.0"
}
}

View File

@@ -0,0 +1,110 @@
/**
* Cross-plugin API: globalThis.__prismFacet
*
* PrismFacet is the registration mechanism (routers, rules, the
* before_prompt_build hook that resolves them); other plugins (notably
* ClawPrompts) supply the actual content by calling into this API at
* their own register() time.
*
* Installation idempotence: safe to call install() multiple times — the
* function attaches the same set of methods to globalThis.__prismFacet
* if not already present. Plugin reload doesn't break consumers.
*
* If a consumer plugin (ClawPrompts) loads BEFORE PrismFacet, the
* `globalThis.__prismFacet` slot will be undefined at the consumer's
* register() time. To make load-order independence work, this module
* pre-creates the slot at module-import time too — consumers can call
* .addRouter / .addRule even if PrismFacet's register() hasn't run yet
* (the registration still lands in the shared maps).
*/
import { addExternalRouter, type RouterContext } from "./router-loader.js";
import { addExternalRule } from "./rule-store.js";
const _G = globalThis as Record<string, unknown>;
export interface PrismFacetCrossPluginApi {
/**
* Register a router programmatically.
* @param name router name (matches the "router:" prefix of rule keys)
* @param resolve function returning a key string for the given context
* (or empty/null to skip this router for this context)
*/
addRouter(
name: string,
resolve: (ctx: RouterContext) => string | Promise<string>,
): void;
/**
* Register a rule programmatically (in-memory; persistent rules.json
* entries set by the prompt-rules tool take precedence on conflict).
* @param routerName router this rule binds to
* @param key value the router must resolve to for this rule to fire
* @param prompt either { file: "/abs/path.md" } or { text: "..." }
*/
addRule(
routerName: string,
key: string,
prompt: { file?: string; text?: string },
): void;
}
type PendingOp =
| { type: "router"; name: string; resolve: (ctx: RouterContext) => string | Promise<string> }
| { type: "rule"; routerName: string; key: string; prompt: { file?: string; text?: string } };
/**
* Idempotent install. Called from PrismFacet's register(). Also runs
* at module-import time below so consumer plugins loading before
* PrismFacet still find a usable API.
*
* Plugin load order is undefined — if ClawPrompts loads before
* PrismFacet, the `_G['__prismFacet']` slot stays at the buffering stub
* created by ClawPrompts (or, if neither has installed yet, missing).
* To make this race-free, we install the real API on first call from
* either side AND drain any queued ops a buffering caller may have
* accumulated via the well-known `__prismFacetPending` array. ClawPrompts
* (and any future consumer) only needs to: push ops onto the pending
* array when `__prismFacet?.addRouter` isn't callable; PrismFacet's
* install() will drain them when it runs.
*/
export function installCrossPluginApi(): PrismFacetCrossPluginApi {
const existing = _G["__prismFacet"] as PrismFacetCrossPluginApi | undefined;
if (existing && typeof existing.addRouter === "function" && (existing as any).__real) return existing;
const api: PrismFacetCrossPluginApi & { __real: true } = {
addRouter(name, resolve) {
addExternalRouter(name, resolve);
},
addRule(routerName, key, prompt) {
if (!prompt.file) {
throw new Error(
"__prismFacet.addRule: only { file: '/abs/path.md' } is supported today; " +
"inline { text } pending injector update",
);
}
addExternalRule(routerName, key, prompt.file);
},
__real: true,
};
_G["__prismFacet"] = api;
// Drain any ops queued by consumer plugins that ran before us.
const pending = _G["__prismFacetPending"] as PendingOp[] | undefined;
if (Array.isArray(pending) && pending.length > 0) {
for (const op of pending) {
try {
if (op.type === "router") api.addRouter(op.name, op.resolve);
else api.addRule(op.routerName, op.key, op.prompt);
} catch {
// Swallow per-op errors so one bad pending entry doesn't block
// the rest. Consumer plugin logs already fired at queue time.
}
}
_G["__prismFacetPending"] = [];
}
return api;
}
// Eager install on module load.
installCrossPluginApi();

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,113 @@
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();
// Don't clear() — that would wipe externally-registered routers added
// by other plugins via __prismFacet.addRouter. Instead, track which
// routers came from the filesystem this run and remove only those
// that disappeared. External routers (filePath sentinel) are never
// touched here.
const FILE_SENTINEL_PREFIX = "<external:";
const fileRoutersBefore = new Set<string>();
for (const [name, r] of map.entries()) {
if (!r.filePath.startsWith(FILE_SENTINEL_PREFIX)) fileRoutersBefore.add(name);
}
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}`);
// No file-based routers this run — drop any leftover file routers.
for (const name of fileRoutersBefore) map.delete(name);
return;
}
const seenThisRun = new Set<string>();
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 });
seenThisRun.add(name);
log.info(`[prism-facet] router loaded: ${name}`);
} catch (err) {
log.warn(`[prism-facet] router ${name}: failed to load — ${String(err)}`);
}
}
// Drop file-based routers that disappeared between loads. Untouched
// routers stay.
for (const stale of fileRoutersBefore) {
if (!seenThisRun.has(stale)) map.delete(stale);
}
}
export function getRouters(): LoadedRouter[] {
return Array.from(getRouterMap().values());
}
export function getRouterNames(): string[] {
return Array.from(getRouterMap().keys());
}
/**
* Cross-plugin API: register a router programmatically. Other plugins
* (e.g. ClawPrompts) call this via globalThis.__prismFacet.addRouter
* to publish a router without dropping a .ts file in PrismFacet's
* routersDir. Replaces any existing router of the same name.
*/
export function addExternalRouter(
name: string,
resolveFn: (ctx: RouterContext) => string | Promise<string>,
): void {
const map = getRouterMap();
map.set(name, {
name,
filePath: `<external: registered via __prismFacet.addRouter>`,
module: { resolve: resolveFn },
});
}

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

@@ -0,0 +1,92 @@
/**
* Two-tier rule store: persistent (operator/admin rules loaded from
* rules.json, mutated by the prompt-rules tool) and external (in-memory
* rules registered by other plugins via the __prismFacet cross-plugin
* API). External rules are NOT saved to disk — they belong to the
* registering plugin and are re-registered on every gateway start.
*
* Lookup precedence: persistent > external (operator wins over plugin
* defaults so an explicit rules.json override is honored).
*/
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 PERSISTENT_KEY = "_prismFacetRules";
const EXTERNAL_KEY = "_prismFacetExternalRules";
const RULES_PATH_KEY = "_prismFacetRulesPath";
function getPersistent(): RuleStore {
if (!_G[PERSISTENT_KEY] || typeof _G[PERSISTENT_KEY] !== "object") {
_G[PERSISTENT_KEY] = {};
}
return _G[PERSISTENT_KEY] as RuleStore;
}
function getExternal(): RuleStore {
if (!_G[EXTERNAL_KEY] || typeof _G[EXTERNAL_KEY] !== "object") {
_G[EXTERNAL_KEY] = {};
}
return _G[EXTERNAL_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(getPersistent(), null, 2) + "\n", "utf8");
}
export function initRuleStore(filePath: string): void {
_G[RULES_PATH_KEY] = filePath;
try {
const raw = readFileSync(filePath, "utf8");
_G[PERSISTENT_KEY] = JSON.parse(raw) as RuleStore;
} catch {
_G[PERSISTENT_KEY] = {};
}
}
/** Operator-facing addRule (writes through to rules.json on disk). */
export function addRule(router: string, key: string, promptFile: string): void {
getPersistent()[`${router}:${key}`] = promptFile;
save();
}
/** Cross-plugin API: register a rule that lives in memory only. */
export function addExternalRule(router: string, key: string, promptFile: string): void {
getExternal()[`${router}:${key}`] = promptFile;
}
export function removeRule(router: string, key: string): boolean {
const rules = getPersistent();
const ruleKey = `${router}:${key}`;
if (!(ruleKey in rules)) return false;
delete rules[ruleKey];
save();
return true;
}
/** Lookup. Persistent (rules.json) overrides external (plugin defaults). */
export function getRule(router: string, key: string): string | undefined {
const persistentValue = getPersistent()[`${router}:${key}`];
if (persistentValue) return persistentValue;
return getExternal()[`${router}:${key}`];
}
/** Merged view for the admin tool. Persistent overrides external. */
export function listRules(): Record<string, string> {
return { ...getExternal(), ...getPersistent() };
}
/** Admin tool needs to know which tier a rule came from. */
export function listRulesTiered(): {
persistent: RuleStore;
external: RuleStore;
} {
return { persistent: { ...getPersistent() }, external: { ...getExternal() } };
}

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 };
}
});
}

89
plugin/index.ts Normal file
View File

@@ -0,0 +1,89 @@
/**
* PrismFacet — prompt-rule registration framework.
*
* Provides:
* - router loader (file-based: routersDir + programmatic: __prismFacet.addRouter)
* - rule store (persistent rules.json + in-memory external rules)
* - before_prompt_build hook that resolves all loaded routers/rules
* and appends the matching prompt fragments to the agent's system
* prompt
* - prompt-rules admin tool to inspect / mutate persistent rules
* - cross-plugin API installed at module load time (globalThis.__prismFacet)
*
* PrismFacet ships NO content of its own — the routers/, prompts/, and
* rules.json directories are empty placeholders. Hangman-Lab-specific
* routers and rules live in the ClawPrompts plugin, which registers
* them at startup via the cross-plugin API.
*/
import path from "node:path";
// Importing core/cross-plugin-api.ts has a side-effect: it installs
// globalThis.__prismFacet at module-import time. Doing this side-effect
// import early — before any other plugin's register() — means a
// consumer plugin (ClawPrompts) loaded before us still finds a working
// __prismFacet to call into.
import "./core/cross-plugin-api.js";
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 (framework only — content via ClawPrompts)");
},
};

View File

@@ -0,0 +1,26 @@
{
"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)"
}
}
},
"contracts": {
"tools": [
"prompt_rules"
]
}
}

6
plugin/package.json Normal file
View File

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

0
plugin/prompts/.gitkeep Normal file
View File

0
plugin/routers/.gitkeep Normal file
View File

1
plugin/rules.json Normal file
View File

@@ -0,0 +1 @@
{}

View File

@@ -0,0 +1,100 @@
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).",
parameters: {
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 { content: [{ type: "text", text: "Error: add requires router, key, and file" }] };
}
addRule(router, key, file);
return { content: [{ type: "text", text: `Rule added: ${router}:${key}${file}` }] };
}
case "remove": {
if (!router || !key) {
return { content: [{ type: "text", text: "Error: remove requires router and key" }] };
}
const removed = removeRule(router, key);
const msg = removed ? `Rule removed: ${router}:${key}` : `Rule not found: ${router}:${key}`;
return { content: [{ type: "text", text: msg }] };
}
case "list": {
const rules = listRules();
const entries = Object.entries(rules);
if (entries.length === 0) return { content: [{ type: "text", text: "No rules registered." }] };
return { content: [{ type: "text", text: entries.map(([k, v]) => `${k}${v}`).join("\n") }] };
}
case "test": {
if (!agent) return { content: [{ type: "text", text: "Error: test requires agent" }] };
const result = await resolveInjection({ agentId: agent }, api.logger);
if (!result.appendSystemContext) {
return { content: [{ type: "text", text: `No prompts matched for agent: ${agent}` }] };
}
return { content: [{ type: "text", text: `Matched prompts for ${agent}:\n\n${result.appendSystemContext}` }] };
}
case "reload-routers": {
await loadRouters(routersDir, api.logger);
const names = getRouterNames();
return { content: [{ type: "text", text: `Routers reloaded: ${names.join(", ") || "(none)"}` }] };
}
case "list-routers": {
const names = getRouterNames();
const msg = names.length > 0 ? `Loaded routers: ${names.join(", ")}` : "No routers loaded.";
return { content: [{ type: "text", text: msg }] };
}
default:
return { content: [{ type: "text", text: `Unknown action: ${action}` }] };
}
},
});
}

1
rules.json Normal file
View File

@@ -0,0 +1 @@
{}

161
scripts/install.mjs Normal file
View File

@@ -0,0 +1,161 @@
#!/usr/bin/env node
import fs from "node:fs";
import path from "node:path";
import { execSync } from "node:child_process";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const projRoot = path.resolve(__dirname, "..");
const pluginSrcDir = path.join(projRoot, "plugin");
const routersSrcDir = path.join(projRoot, "routers");
const PLUGIN_ID = "prism-facet";
const ocDir = path.join(process.env.HOME || "~", ".openclaw");
const pluginsDir = path.join(ocDir, "plugins");
const installDir = path.join(pluginsDir, PLUGIN_ID);
const configPath = path.join(ocDir, "openclaw.json");
const args = process.argv.slice(2);
const action = args[0];
if (!action || !["--install", "--uninstall", "--update"].includes(action)) {
console.log("Usage: node scripts/install.mjs --install | --uninstall | --update");
process.exit(1);
}
function readConfig() {
return JSON.parse(fs.readFileSync(configPath, "utf8"));
}
function writeConfig(cfg) {
fs.writeFileSync(configPath, JSON.stringify(cfg, null, 2) + "\n", "utf8");
}
function setIfMissing(obj, key, value) {
if (obj[key] === undefined || obj[key] === null) {
obj[key] = value;
}
}
function buildPlugin() {
console.log("Building plugin...");
// Compile TypeScript from plugin/ to plugin/ (in-place, JS output)
execSync("npx tsc --project tsconfig.plugin.json", { cwd: projRoot, stdio: "inherit" });
}
function install() {
// 1. Build
buildPlugin();
// 2. Clean and copy plugin to install dir
if (fs.existsSync(installDir)) {
fs.rmSync(installDir, { recursive: true });
}
fs.mkdirSync(installDir, { recursive: true });
// Copy compiled plugin files
copyDirRecursive(pluginSrcDir, installDir, [".ts"]);
// Copy routers alongside plugin
const routersInstallDir = path.join(installDir, "routers");
if (fs.existsSync(routersSrcDir)) {
fs.mkdirSync(routersInstallDir, { recursive: true });
copyDirRecursive(routersSrcDir, routersInstallDir);
}
// Create empty rules.json if not exists
const rulesPath = path.join(installDir, "rules.json");
if (!fs.existsSync(rulesPath)) {
fs.writeFileSync(rulesPath, "{}\n", "utf8");
}
// 3. Update openclaw.json
const cfg = readConfig();
const plugins = cfg.plugins ??= {};
const allow = plugins.allow ??= [];
const loadPaths = (plugins.load ??= {}).paths ??= [];
const entries = plugins.entries ??= {};
if (!allow.includes(PLUGIN_ID)) allow.push(PLUGIN_ID);
if (!loadPaths.includes(installDir)) loadPaths.push(installDir);
const entry = entries[PLUGIN_ID] ??= {};
setIfMissing(entry, "enabled", true);
const hooks = entry.hooks ??= {};
setIfMissing(hooks, "allowPromptInjection", true);
writeConfig(cfg);
console.log(`Installed ${PLUGIN_ID} to ${installDir}`);
console.log("Restart gateway: openclaw gateway restart");
}
function uninstall() {
const cfg = readConfig();
const plugins = cfg.plugins ?? {};
// Remove from allow
if (Array.isArray(plugins.allow)) {
plugins.allow = plugins.allow.filter((id) => id !== PLUGIN_ID);
}
// Remove entry
if (plugins.entries) delete plugins.entries[PLUGIN_ID];
// Remove load path
if (plugins.load?.paths) {
plugins.load.paths = plugins.load.paths.filter((p) => !p.includes(PLUGIN_ID));
}
writeConfig(cfg);
// Remove install dir
if (fs.existsSync(installDir)) {
fs.rmSync(installDir, { recursive: true });
console.log(`Removed ${installDir}`);
}
console.log(`Uninstalled ${PLUGIN_ID}`);
}
function copyDirRecursive(src, dest, excludeExts = []) {
if (!fs.existsSync(dest)) fs.mkdirSync(dest, { recursive: true });
for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
const srcPath = path.join(src, entry.name);
const destPath = path.join(dest, entry.name);
if (entry.isDirectory()) {
if (entry.name === "node_modules") continue;
copyDirRecursive(srcPath, destPath, excludeExts);
} else {
if (excludeExts.some((ext) => entry.name.endsWith(ext))) continue;
fs.copyFileSync(srcPath, destPath);
}
}
// openclaw 2026.5+ refuses to load plugins whose files are owned by
// non-root ("suspicious ownership"). fs.copyFileSync preserves source
// ownership, so rsync/tar from a developer laptop (uid 1000) breaks
// the plugin on next gateway restart. Force chown to root when we
// can (root-only); silently skip otherwise (dev mode under
// unprivileged user — uid checks don't apply there).
try {
if (process.getuid && process.getuid() === 0) chownRecursive(dest);
} catch {}
}
function chownRecursive(dir) {
fs.chownSync(dir, 0, 0);
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, entry.name);
if (entry.isDirectory()) chownRecursive(p);
else fs.chownSync(p, 0, 0);
}
}
switch (action) {
case "--install":
case "--update":
install();
break;
case "--uninstall":
uninstall();
break;
}

18
tsconfig.plugin.json Normal file
View File

@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"outDir": "plugin",
"rootDir": "plugin",
"declaration": false,
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"allowJs": true,
"emitDeclarationOnly": false
},
"include": ["plugin/**/*.ts"],
"exclude": ["plugin/**/*.js"]
}