Compare commits
2 Commits
feat/regis
...
353e19c3ec
| Author | SHA1 | Date | |
|---|---|---|---|
| 353e19c3ec | |||
|
|
108963d1f6 |
@@ -1,110 +0,0 @@
|
|||||||
/**
|
|
||||||
* 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();
|
|
||||||
@@ -35,16 +35,7 @@ export async function loadRouters(
|
|||||||
log: { info(msg: string): void; warn(msg: string): void }
|
log: { info(msg: string): void; warn(msg: string): void }
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const map = getRouterMap();
|
const map = getRouterMap();
|
||||||
// Don't clear() — that would wipe externally-registered routers added
|
map.clear();
|
||||||
// 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;
|
if (typeof _G[LOAD_COUNTER_KEY] !== "number") _G[LOAD_COUNTER_KEY] = 0;
|
||||||
(_G[LOAD_COUNTER_KEY] as number)++;
|
(_G[LOAD_COUNTER_KEY] as number)++;
|
||||||
@@ -57,12 +48,9 @@ export async function loadRouters(
|
|||||||
);
|
);
|
||||||
} catch {
|
} catch {
|
||||||
log.warn(`[prism-facet] routers directory not found: ${routersDir}`);
|
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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const seenThisRun = new Set<string>();
|
|
||||||
for (const file of files) {
|
for (const file of files) {
|
||||||
const name = routerNameFromFile(file);
|
const name = routerNameFromFile(file);
|
||||||
const filePath = path.resolve(routersDir, file);
|
const filePath = path.resolve(routersDir, file);
|
||||||
@@ -73,17 +61,11 @@ export async function loadRouters(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
map.set(name, { name, filePath, module: mod });
|
map.set(name, { name, filePath, module: mod });
|
||||||
seenThisRun.add(name);
|
|
||||||
log.info(`[prism-facet] router loaded: ${name}`);
|
log.info(`[prism-facet] router loaded: ${name}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
log.warn(`[prism-facet] router ${name}: failed to load — ${String(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[] {
|
export function getRouters(): LoadedRouter[] {
|
||||||
@@ -93,21 +75,3 @@ export function getRouters(): LoadedRouter[] {
|
|||||||
export function getRouterNames(): string[] {
|
export function getRouterNames(): string[] {
|
||||||
return Array.from(getRouterMap().keys());
|
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 },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,34 +1,16 @@
|
|||||||
/**
|
|
||||||
* 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";
|
import { readFileSync, writeFileSync } from "node:fs";
|
||||||
|
|
||||||
export type RuleStore = Record<string, string>; // "router:key" → prompt file path
|
export type RuleStore = Record<string, string>; // "router:key" → prompt file path
|
||||||
|
|
||||||
const _G = globalThis as Record<string, unknown>;
|
const _G = globalThis as Record<string, unknown>;
|
||||||
const PERSISTENT_KEY = "_prismFacetRules";
|
const RULES_KEY = "_prismFacetRules";
|
||||||
const EXTERNAL_KEY = "_prismFacetExternalRules";
|
|
||||||
const RULES_PATH_KEY = "_prismFacetRulesPath";
|
const RULES_PATH_KEY = "_prismFacetRulesPath";
|
||||||
|
|
||||||
function getPersistent(): RuleStore {
|
function getRules(): RuleStore {
|
||||||
if (!_G[PERSISTENT_KEY] || typeof _G[PERSISTENT_KEY] !== "object") {
|
if (!_G[RULES_KEY] || typeof _G[RULES_KEY] !== "object") {
|
||||||
_G[PERSISTENT_KEY] = {};
|
_G[RULES_KEY] = {};
|
||||||
}
|
}
|
||||||
return _G[PERSISTENT_KEY] as RuleStore;
|
return _G[RULES_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 {
|
function getRulesPath(): string {
|
||||||
@@ -38,32 +20,26 @@ function getRulesPath(): string {
|
|||||||
function save(): void {
|
function save(): void {
|
||||||
const p = getRulesPath();
|
const p = getRulesPath();
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
writeFileSync(p, JSON.stringify(getPersistent(), null, 2) + "\n", "utf8");
|
writeFileSync(p, JSON.stringify(getRules(), null, 2) + "\n", "utf8");
|
||||||
}
|
}
|
||||||
|
|
||||||
export function initRuleStore(filePath: string): void {
|
export function initRuleStore(filePath: string): void {
|
||||||
_G[RULES_PATH_KEY] = filePath;
|
_G[RULES_PATH_KEY] = filePath;
|
||||||
try {
|
try {
|
||||||
const raw = readFileSync(filePath, "utf8");
|
const raw = readFileSync(filePath, "utf8");
|
||||||
_G[PERSISTENT_KEY] = JSON.parse(raw) as RuleStore;
|
_G[RULES_KEY] = JSON.parse(raw) as RuleStore;
|
||||||
} catch {
|
} catch {
|
||||||
_G[PERSISTENT_KEY] = {};
|
_G[RULES_KEY] = {};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Operator-facing addRule (writes through to rules.json on disk). */
|
|
||||||
export function addRule(router: string, key: string, promptFile: string): void {
|
export function addRule(router: string, key: string, promptFile: string): void {
|
||||||
getPersistent()[`${router}:${key}`] = promptFile;
|
getRules()[`${router}:${key}`] = promptFile;
|
||||||
save();
|
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 {
|
export function removeRule(router: string, key: string): boolean {
|
||||||
const rules = getPersistent();
|
const rules = getRules();
|
||||||
const ruleKey = `${router}:${key}`;
|
const ruleKey = `${router}:${key}`;
|
||||||
if (!(ruleKey in rules)) return false;
|
if (!(ruleKey in rules)) return false;
|
||||||
delete rules[ruleKey];
|
delete rules[ruleKey];
|
||||||
@@ -71,22 +47,10 @@ export function removeRule(router: string, key: string): boolean {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Lookup. Persistent (rules.json) overrides external (plugin defaults). */
|
|
||||||
export function getRule(router: string, key: string): string | undefined {
|
export function getRule(router: string, key: string): string | undefined {
|
||||||
const persistentValue = getPersistent()[`${router}:${key}`];
|
return getRules()[`${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> {
|
export function listRules(): Record<string, string> {
|
||||||
return { ...getExternal(), ...getPersistent() };
|
return { ...getRules() };
|
||||||
}
|
|
||||||
|
|
||||||
/** Admin tool needs to know which tier a rule came from. */
|
|
||||||
export function listRulesTiered(): {
|
|
||||||
persistent: RuleStore;
|
|
||||||
external: RuleStore;
|
|
||||||
} {
|
|
||||||
return { persistent: { ...getPersistent() }, external: { ...getExternal() } };
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,27 +1,4 @@
|
|||||||
/**
|
|
||||||
* 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";
|
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 { loadRouters } from "./core/router-loader.js";
|
||||||
import { initRuleStore } from "./core/rule-store.js";
|
import { initRuleStore } from "./core/rule-store.js";
|
||||||
import { registerBeforePromptBuild } from "./hooks/before-prompt-build.js";
|
import { registerBeforePromptBuild } from "./hooks/before-prompt-build.js";
|
||||||
@@ -84,6 +61,6 @@ export default {
|
|||||||
// Tools
|
// Tools
|
||||||
registerPromptRulesTool(api, routersDir);
|
registerPromptRulesTool(api, routersDir);
|
||||||
|
|
||||||
api.logger.info("[prism-facet] plugin registered (framework only — content via ClawPrompts)");
|
api.logger.info("[prism-facet] plugin registered");
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
{}
|
|
||||||
@@ -1 +1 @@
|
|||||||
{}
|
{}
|
||||||
@@ -130,24 +130,6 @@ function copyDirRecursive(src, dest, excludeExts = []) {
|
|||||||
fs.copyFileSync(srcPath, destPath);
|
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) {
|
switch (action) {
|
||||||
|
|||||||
Reference in New Issue
Block a user