Files
PrismFacet/plugin/core/router-loader.ts
hzhang 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

96 lines
2.7 KiB
TypeScript

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());
}
/**
* 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 },
});
}