fix(node): mirror Factory Droid 0.175 hooks

This commit is contained in:
ZacharyZhang-NY committed 2026-07-20 13:45:33 -04:00
1 parent 42a7653a77
commit 47ef2cc691
12 files changed
+1855 -932

No files matched your search

+157 -109
View File
@@ -1,51 +1,50 @@
import {
applyEdits,
modify,
parse,
parseTree,
printParseErrorCode,
type FormattingOptions,
type JSONPath,
type Node,
type ParseError,
} from 'jsonc-parser';
import type { FileSnapshot } from './managed-files.js';
import type { DroidPolicyState } from './droid-policy.js';
import {
TOOL_EVENTS,
type DroidGroup,
type DroidHookSettings,
type JsonObject,
type DroidHookMap,
type ToolEvent,
hasOwn,
isObject,
managedRemovals,
readHookSettings,
readHookMap,
} from './droid-contract.js';
import {
isObject,
parseStrictJsoncObject,
type JsonObject,
} from './strict-json.js';
export const OWNED_FILE_MARKER = '// Managed by Elydora';
export type DroidDocumentKind = 'hooks' | 'legacy' | 'settings';
export type DroidDocumentKind = 'hooks' | 'legacy' | 'settings' | 'local-settings';
export interface DroidDocument {
readonly kind: DroidDocumentKind;
readonly filePath: string;
readonly exists: boolean;
readonly raw: string;
readonly snapshot?: FileSnapshot;
readonly root: JsonObject;
readonly hooks: DroidHookSettings;
readonly hooks: DroidHookMap;
readonly basePath: JSONPath;
readonly hasHooksContainer: boolean;
readonly hooksDisabled?: boolean;
readonly showHookOutput?: boolean;
readonly ownedFile: boolean;
}
export interface DroidSources {
readonly rootPath: string;
readonly primary?: DroidDocument;
readonly root: DroidDocument;
readonly legacy: DroidDocument;
readonly settings: DroidDocument;
}
export interface InstallationTargets {
readonly targets: ReadonlyMap<ToolEvent, DroidDocument>;
readonly createdRoot?: DroidDocument;
readonly localSettings: DroidDocument;
readonly policy: DroidPolicyState;
}
export interface RenderedDocument {
@@ -59,59 +58,48 @@ interface DocumentOptions {
readonly filePath: string;
readonly kind: DroidDocumentKind;
readonly raw: string;
readonly snapshot?: FileSnapshot;
}
function rejectDuplicateKeys(node: Node | undefined, label: string, path: string[] = []): void {
if (!node) return;
if (node.type === 'object') {
const keys = new Set<string>();
for (const property of node.children ?? []) {
const key = String(property.children?.[0]?.value);
const location = [...path, key];
if (keys.has(key)) throw new Error(`${label} contains duplicate field "${location.join('.')}"`);
keys.add(key);
rejectDuplicateKeys(property.children?.[1], label, location);
}
return;
}
if (node.type === 'array') {
for (const child of node.children ?? []) rejectDuplicateKeys(child, label, path);
}
}
function parseJsoncObject(raw: string, label: string): JsonObject {
const errors: ParseError[] = [];
const value: unknown = parse(raw, errors, {
allowTrailingComma: true,
disallowComments: false,
});
if (errors.length > 0) {
const details = errors
.map((error) => `${printParseErrorCode(error.error)} at offset ${error.offset}`)
.join(', ');
throw new Error(`Failed to parse ${label}: ${details}`);
}
if (!isObject(value)) throw new Error(`${label} must contain a JSON object`);
rejectDuplicateKeys(parseTree(raw, [], {
allowTrailingComma: true,
disallowComments: false,
}), label);
return value;
function hasOwn(value: JsonObject, key: string): boolean {
return Object.prototype.hasOwnProperty.call(value, key);
}
function labelFor(kind: DroidDocumentKind, filePath: string): string {
if (kind === 'settings') return `Factory Droid settings at ${filePath}`;
if (kind === 'local-settings') return `Factory Droid local settings at ${filePath}`;
if (kind === 'legacy') return `Factory Droid legacy hooks at ${filePath}`;
return `Factory Droid hooks at ${filePath}`;
}
function optionalBoolean(root: JsonObject, field: string, label: string): boolean | undefined {
const value = root[field];
if (value !== undefined && typeof value !== 'boolean') {
throw new Error(`${label} field "${field}" must be a boolean`);
}
return value as boolean | undefined;
}
function legacyDirectHooks(root: JsonObject, label: string): {
readonly hooks: DroidHookMap;
readonly hooksDisabled?: boolean;
readonly showHookOutput?: boolean;
} {
const hooksDisabled = optionalBoolean(root, 'hooksDisabled', label);
const showHookOutput = optionalBoolean(root, 'showHookOutput', label);
const hookEntries = Object.fromEntries(
Object.entries(root).filter(([key]) => key !== 'hooksDisabled' && key !== 'showHookOutput'),
);
return { hooks: readHookMap(hookEntries, label), hooksDisabled, showHookOutput };
}
export function parseDocument(options: DocumentOptions): DroidDocument {
const label = labelFor(options.kind, options.filePath);
const root = parseJsoncObject(options.raw, label);
if (options.kind === 'settings') {
const root = parseStrictJsoncObject(options.raw, label);
if (options.kind === 'settings' || options.kind === 'local-settings') {
const hasHooksContainer = hasOwn(root, 'hooks');
const hooks = hasHooksContainer
? readHookSettings(root.hooks, `${label} field "hooks"`)
? readHookMap(root.hooks, `${label} field "hooks"`)
: {};
return {
...options,
@@ -119,21 +107,42 @@ export function parseDocument(options: DocumentOptions): DroidDocument {
hooks,
basePath: ['hooks'],
hasHooksContainer,
hooksDisabled: optionalBoolean(root, 'hooksDisabled', label),
showHookOutput: optionalBoolean(root, 'showHookOutput', label),
ownedFile: false,
};
}
if (hasOwn(root, 'hooks')) {
if (!isObject(root.hooks)) throw new Error(`${label} field "hooks" must be an object`);
return {
...options,
root,
hooks: readHookMap(root.hooks, `${label} field "hooks"`),
basePath: ['hooks'],
hasHooksContainer: true,
ownedFile: options.raw.startsWith(OWNED_FILE_MARKER),
};
}
const legacy = legacyDirectHooks(root, label);
return {
...options,
root,
hooks: readHookSettings(root, label),
...legacy,
basePath: [],
hasHooksContainer: true,
hasHooksContainer: false,
ownedFile: options.raw.startsWith(OWNED_FILE_MARKER),
};
}
export function createSettingsDocument(filePath: string): DroidDocument {
return parseDocument({ exists: false, filePath, kind: 'settings', raw: '{}\n' });
export function createSettingsDocument(
filePath: string,
kind: 'settings' | 'local-settings' = 'settings',
): DroidDocument {
return parseDocument({ exists: false, filePath, kind, raw: '{}\n' });
}
export function createLegacyHookDocument(filePath: string): DroidDocument {
return parseDocument({ exists: false, filePath, kind: 'legacy', raw: '{}\n' });
}
export function createOwnedHookDocument(filePath: string): DroidDocument {
@@ -141,7 +150,7 @@ export function createOwnedHookDocument(filePath: string): DroidDocument {
exists: false,
filePath,
kind: 'hooks',
raw: `${OWNED_FILE_MARKER}\n{}\n`,
raw: `${OWNED_FILE_MARKER}\n{\n "hooks": {}\n}\n`,
});
}
@@ -159,12 +168,7 @@ function formatting(raw: string): FormattingOptions {
};
}
function change(
raw: string,
path: JSONPath,
value: unknown,
isArrayInsertion = false,
): string {
function change(raw: string, path: JSONPath, value: unknown, isArrayInsertion = false): string {
return applyEdits(raw, modify(raw, path, value, {
formattingOptions: formatting(raw),
isArrayInsertion,
@@ -177,20 +181,16 @@ function currentDocument(document: DroidDocument, raw: string): DroidDocument {
filePath: document.filePath,
kind: document.kind,
raw,
snapshot: document.snapshot,
});
}
function removeManagedEntries(
document: DroidDocument,
raw: string,
agentId?: string,
): string {
function removeManagedEntries(document: DroidDocument, raw: string, agentId?: string): string {
const removals = managedRemovals(document.hooks, agentId);
for (const event of TOOL_EVENTS) {
const eventRemovals = removals
.filter((removal) => removal.event === event)
.sort((left, right) => right.groupIndex - left.groupIndex);
if (eventRemovals.length === 0) continue;
for (const removal of eventRemovals) {
const groupPath = [...eventPath(document, event), removal.groupIndex];
if (removal.removeGroup) {
@@ -201,9 +201,11 @@ function removeManagedEntries(
raw = change(raw, [...groupPath, 'hooks', handlerIndex], undefined);
}
}
const current = currentDocument(document, raw);
if ((current.hooks[event] ?? []).length === 0) {
raw = change(raw, eventPath(document, event), undefined);
if (eventRemovals.length > 0) {
const current = currentDocument(document, raw);
if ((current.hooks[event] ?? []).length === 0) {
raw = change(raw, eventPath(document, event), undefined);
}
}
}
return raw;
@@ -216,7 +218,7 @@ function appendGroup(
group: DroidGroup,
): string {
const current = currentDocument(document, raw);
if (hasOwn(current.hooks, event)) {
if (Object.prototype.hasOwnProperty.call(current.hooks, event)) {
const groups = current.hooks[event] ?? [];
return change(raw, [...eventPath(document, event), groups.length], group, true);
}
@@ -224,8 +226,10 @@ function appendGroup(
}
function hookFileIsEmpty(document: DroidDocument, raw: string): boolean {
if (document.kind === 'settings') return false;
return Object.keys(currentDocument(document, raw).hooks).length === 0;
if (document.kind === 'settings' || document.kind === 'local-settings') return false;
const current = currentDocument(document, raw);
const remainingRootFields = Object.keys(current.root).filter((key) => key !== 'hooks');
return Object.keys(current.hooks).length === 0 && remainingRootFields.length === 0;
}
export function renderDocument(
@@ -239,45 +243,89 @@ export function renderDocument(
if (group) raw = appendGroup(document, raw, event, group);
}
currentDocument(document, raw);
if (additions.size === 0 && document.ownedFile && hookFileIsEmpty(document, raw)) {
if (additions.size === 0
&& document.exists
&& document.ownedFile
&& hookFileIsEmpty(document, raw)) {
return { document, changed: true, next: undefined };
}
return { document, changed: raw !== document.raw, next: raw };
}
function eventTarget(
event: ToolEvent,
sources: DroidSources,
createdRoot: () => DroidDocument,
): DroidDocument {
if (sources.primary && hasOwn(sources.primary.hooks, event)) return sources.primary;
if (sources.settings.hasHooksContainer && hasOwn(sources.settings.hooks, event)) {
return sources.settings;
}
if (sources.primary) return sources.primary;
export function activeDocument(sources: DroidSources): DroidDocument {
if (sources.root.exists) return sources.root;
if (sources.legacy.exists) return sources.legacy;
if (sources.localSettings.hasHooksContainer) return sources.localSettings;
if (sources.settings.hasHooksContainer) return sources.settings;
return createdRoot();
return sources.root;
}
export function installationTargets(sources: DroidSources): InstallationTargets {
let root: DroidDocument | undefined;
const createdRoot = (): DroidDocument => {
root ??= createOwnedHookDocument(sources.rootPath);
return root;
};
const targets = new Map<ToolEvent, DroidDocument>();
for (const event of TOOL_EVENTS) targets.set(event, eventTarget(event, sources, createdRoot));
return { targets, createdRoot: root };
export function effectiveHooks(sources: DroidSources): DroidHookMap {
return activeDocument(sources).hooks;
}
export function additionsFor(
export interface DroidHookBlock {
readonly field: 'allowManagedHooksOnly' | 'hooksDisabled';
readonly filePath: string;
readonly label: string;
}
export function hookBlock(sources: DroidSources): DroidHookBlock | undefined {
if (sources.policy.allowManagedHooksOnlyBy) {
return {
field: 'allowManagedHooksOnly',
...sources.policy.allowManagedHooksOnlyBy,
};
}
if (sources.policy.hooksDisabled !== undefined) {
return sources.policy.hooksDisabled ? {
field: 'hooksDisabled',
...sources.policy.hooksDisabledBy!,
} : undefined;
}
const selected = sources.localSettings.hooksDisabled !== undefined
? sources.localSettings
: sources.settings;
if (selected.hooksDisabled === true) {
return {
field: 'hooksDisabled',
filePath: selected.filePath,
label: labelFor(selected.kind, selected.filePath),
};
}
const active = activeDocument(sources);
return active.hooksDisabled === true
? {
field: 'hooksDisabled',
filePath: active.filePath,
label: labelFor(active.kind, active.filePath),
}
: undefined;
}
export function sourceDocuments(sources: DroidSources): DroidDocument[] {
return [sources.root, sources.legacy, sources.settings, sources.localSettings];
}
export function installationDocuments(sources: DroidSources): DroidDocument[] {
const target = activeDocument(sources);
const documents = [
sources.root.exists || target === sources.root ? sources.root : undefined,
sources.legacy.exists ? sources.legacy : undefined,
sources.settings.hasHooksContainer ? sources.settings : undefined,
sources.localSettings.hasHooksContainer ? sources.localSettings : undefined,
];
const unique = new Map<string, DroidDocument>();
for (const document of documents) {
if (document) unique.set(document.filePath, document);
}
return [...unique.values()];
}
export function additionsForTarget(
document: DroidDocument,
targets: ReadonlyMap<ToolEvent, DroidDocument>,
target: DroidDocument,
groups: ReadonlyMap<ToolEvent, DroidGroup>,
): ReadonlyMap<ToolEvent, DroidGroup> {
const additions = new Map<ToolEvent, DroidGroup>();
for (const event of TOOL_EVENTS) {
if (targets.get(event) === document) additions.set(event, groups.get(event)!);
}
return additions;
return document === target ? groups : new Map();
}
+114 -96
View File
@@ -1,5 +1,6 @@
import os from 'node:os';
import path from 'node:path';
import type { JsonObject } from './strict-json.js';
export const AGENT_KEY = 'droid';
export const GUARD_SCRIPT = 'guard.js';
@@ -7,22 +8,10 @@ export const AUDIT_SCRIPT = 'hook.js';
export const HOOK_TIMEOUT_SECONDS = 10;
export const TOOL_EVENTS = ['PreToolUse', 'PostToolUse'] as const;
const EVENT_NAMES = new Set([
'PreToolUse',
'PostToolUse',
'Notification',
'UserPromptSubmit',
'Stop',
'SubagentStop',
'PreCompact',
'SessionStart',
'SessionEnd',
]);
const FLAG_NAMES = new Set(['hooksDisabled', 'showHookOutput']);
const HANDLER_KEYS = ['command', 'timeout', 'type'];
const GROUP_KEYS = ['hooks', 'matcher'];
const WINDOWS_EXIT_SUFFIX = '; exit $LASTEXITCODE';
export type JsonObject = Record<string, unknown>;
export type ToolEvent = typeof TOOL_EVENTS[number];
export interface DroidHandler extends JsonObject {
@@ -37,11 +26,9 @@ export interface DroidGroup extends JsonObject {
readonly hooks: DroidHandler[];
}
export interface DroidHookSettings extends JsonObject {
export interface DroidHookMap extends JsonObject {
readonly PreToolUse?: DroidGroup[];
readonly PostToolUse?: DroidGroup[];
readonly hooksDisabled?: boolean;
readonly showHookOutput?: boolean;
}
export interface RuntimeContract {
@@ -51,7 +38,7 @@ export interface RuntimeContract {
}
export interface ManagedRemoval {
readonly event: string;
readonly event: ToolEvent;
readonly groupIndex: number;
readonly handlerIndexes: number[];
readonly removeGroup: boolean;
@@ -62,25 +49,21 @@ interface ParsedArgument {
readonly next: number;
}
export function isObject(value: unknown): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
export function hasOwn(value: JsonObject, key: string): boolean {
return Object.prototype.hasOwnProperty.call(value, key);
}
function quotePosix(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}
function quoteWindows(value: string): string {
return `"${value.replaceAll('"', '\\"')}"`;
function quotePowerShell(value: string): string {
return `'${value.replaceAll("'", "''")}'`;
}
export function buildCommand(scriptPath: string): string {
const quote = process.platform === 'win32' ? quoteWindows : quotePosix;
return `${quote(process.execPath)} ${quote(scriptPath)}`;
if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) {
throw new Error('Factory Droid hook commands require absolute executable and script paths');
}
return process.platform === 'win32'
? `& ${quotePowerShell(process.execPath)} ${quotePowerShell(scriptPath)}${WINDOWS_EXIT_SUFFIX}`
: `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`;
}
export function buildGroup(scriptPath: string): DroidGroup {
@@ -111,65 +94,76 @@ function validateHandler(
handlerIndex: number,
): DroidHandler {
const location = `${label}[${groupIndex}].hooks[${handlerIndex}]`;
if (!isObject(value)) throw new Error(`${location} must be an object`);
if (value.type !== 'command') throw new Error(`${location} type must be "command"`);
if (typeof value.command !== 'string') throw new Error(`${location} command must be a string`);
if (value.timeout !== undefined
&& (typeof value.timeout !== 'number'
|| !Number.isFinite(value.timeout))) {
throw new Error(`${location} timeout must be a finite number`);
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throw new Error(`${location} must be an object`);
}
return value as DroidHandler;
const handler = value as JsonObject;
if (handler.type !== 'command') throw new Error(`${location} type must be "command"`);
if (typeof handler.command !== 'string' || handler.command.trim().length === 0) {
throw new Error(`${location} command must be a non-empty string`);
}
if (handler.timeout !== undefined
&& (typeof handler.timeout !== 'number'
|| !Number.isFinite(handler.timeout)
|| handler.timeout <= 0)) {
throw new Error(`${location} timeout must be a positive finite number`);
}
return handler as DroidHandler;
}
function validateGroup(value: unknown, label: string, groupIndex: number): DroidGroup {
const location = `${label}[${groupIndex}]`;
if (!isObject(value)) throw new Error(`${location} must be an object`);
if (value.matcher !== undefined) {
if (typeof value.matcher !== 'string') throw new Error(`${location} matcher must be a string`);
validateRegex(value.matcher, `${location} matcher`, true);
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throw new Error(`${location} must be an object`);
}
if (value.commandRegex !== undefined) {
if (typeof value.commandRegex !== 'string') {
const group = value as JsonObject;
if (group.matcher !== undefined) {
if (typeof group.matcher !== 'string') throw new Error(`${location} matcher must be a string`);
validateRegex(group.matcher, `${location} matcher`, true);
}
if (group.commandRegex !== undefined) {
if (typeof group.commandRegex !== 'string') {
throw new Error(`${location} commandRegex must be a string`);
}
validateRegex(value.commandRegex, `${location} commandRegex`, false);
validateRegex(group.commandRegex, `${location} commandRegex`, false);
}
if (!Array.isArray(value.hooks)) throw new Error(`${location} must contain a hooks array`);
const handlers = value.hooks.map(
(handler, handlerIndex) => validateHandler(handler, label, groupIndex, handlerIndex),
);
return { ...value, hooks: handlers } as DroidGroup;
if (!Array.isArray(group.hooks)) throw new Error(`${location} must contain a hooks array`);
return {
...group,
hooks: group.hooks.map(
(handler, handlerIndex) => validateHandler(handler, label, groupIndex, handlerIndex),
),
} as DroidGroup;
}
export function readHookSettings(value: unknown, label: string): DroidHookSettings {
if (!isObject(value)) throw new Error(`${label} must contain a JSON object`);
const settings: DroidHookSettings = { ...value };
for (const [key, item] of Object.entries(value)) {
if (FLAG_NAMES.has(key)) {
if (typeof item !== 'boolean') throw new Error(`${label} field "${key}" must be a boolean`);
continue;
}
if (!EVENT_NAMES.has(key)) throw new Error(`${label} contains unsupported field "${key}"`);
if (!Array.isArray(item)) throw new Error(`${label} field "${key}" must be an array`);
settings[key] = item.map(
(group, groupIndex) => validateGroup(group, `${label} field "${key}"`, groupIndex),
export function readHookMap(value: unknown, label: string): DroidHookMap {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throw new Error(`${label} must contain a JSON object`);
}
const hooks: DroidHookMap = {};
for (const [event, groups] of Object.entries(value)) {
if (!Array.isArray(groups)) throw new Error(`${label} field "${event}" must be an array`);
hooks[event] = groups.map(
(group, groupIndex) => validateGroup(group, `${label} field "${event}"`, groupIndex),
);
}
return settings;
return hooks;
}
function readWindowsArgument(command: string, start: number): ParsedArgument | undefined {
if (command[start] !== '"') return undefined;
function readPowerShellArgument(command: string, start: number): ParsedArgument | undefined {
if (command[start] !== "'") return undefined;
let value = '';
for (let index = start + 1; index < command.length; index += 1) {
if (command[index] === '\\' && command[index + 1] === '"') {
value += '"';
if (command[index] !== "'") {
value += command[index];
continue;
}
if (command[index + 1] === "'") {
value += "'";
index += 1;
continue;
}
if (command[index] === '"') return { value, next: index + 1 };
value += command[index];
return { value, next: index + 1 };
}
return undefined;
}
@@ -192,16 +186,45 @@ function readPosixArgument(command: string, start: number): ParsedArgument | und
return undefined;
}
function parseGeneratedCommand(command: string): readonly [string, string] | undefined {
const readArgument = process.platform === 'win32' ? readWindowsArgument : readPosixArgument;
const executable = readArgument(command, 0);
function parseTwoArguments(
command: string,
start: number,
readArgument: (command: string, start: number) => ParsedArgument | undefined,
): readonly [string, string] | undefined {
const executable = readArgument(command, start);
if (!executable || command[executable.next] !== ' ') return undefined;
const script = readArgument(command, executable.next + 1);
if (!script || script.next !== command.length || !executable.value || !script.value) return undefined;
return [executable.value, script.value];
}
function samePath(left: string, right: string): boolean {
function parseLegacyWindowsCommand(command: string): readonly [string, string] | undefined {
const match = /^"([^"\r\n]+)" "([^"\r\n]+)"$/.exec(command);
return match ? [match[1], match[2]] : undefined;
}
function parsePowerShellCommand(command: string): readonly [string, string] | undefined {
if (!command.startsWith('& ')) return undefined;
const executable = readPowerShellArgument(command, 2);
if (!executable || command[executable.next] !== ' ') return undefined;
const script = readPowerShellArgument(command, executable.next + 1);
if (!script
|| command.slice(script.next) !== WINDOWS_EXIT_SUFFIX
|| !executable.value
|| !script.value) return undefined;
return [executable.value, script.value];
}
function parseGeneratedCommand(
command: string,
includeLegacy: boolean,
): readonly [string, string] | undefined {
if (process.platform !== 'win32') return parseTwoArguments(command, 0, readPosixArgument);
const current = parsePowerShellCommand(command);
return current ?? (includeLegacy ? parseLegacyWindowsCommand(command) : undefined);
}
export function samePath(left: string, right: string): boolean {
const normalizedLeft = path.resolve(left);
const normalizedRight = path.resolve(right);
return process.platform === 'win32'
@@ -209,15 +232,19 @@ function samePath(left: string, right: string): boolean {
: normalizedLeft === normalizedRight;
}
function sameAgentId(left: string, right: string): boolean {
export function sameAgentId(left: string, right: string): boolean {
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
}
export function managedAgentId(handler: DroidHandler, scriptName: string): string | undefined {
export function managedAgentId(
handler: DroidHandler,
scriptName: string,
includeLegacy = false,
): string | undefined {
if (Object.keys(handler).sort().join('\0') !== HANDLER_KEYS.join('\0')
|| handler.type !== 'command'
|| handler.timeout !== HOOK_TIMEOUT_SECONDS) return undefined;
const parsed = parseGeneratedCommand(handler.command);
const parsed = parseGeneratedCommand(handler.command, includeLegacy);
if (!parsed || !samePath(parsed[0], process.execPath)) return undefined;
const scriptPath = parsed[1];
if (path.basename(scriptPath) !== scriptName) return undefined;
@@ -234,19 +261,16 @@ function exactOwnedGroup(group: DroidGroup, managedIndexes: number[]): boolean {
&& managedIndexes.length === group.hooks.length;
}
export function managedRemovals(
settings: DroidHookSettings,
agentId?: string,
): ManagedRemoval[] {
export function managedRemovals(hooks: DroidHookMap, agentId?: string): ManagedRemoval[] {
const removals: ManagedRemoval[] = [];
for (const [event, scriptName] of [
['PreToolUse', GUARD_SCRIPT],
['PostToolUse', AUDIT_SCRIPT],
] as const) {
const groups = settings[event] ?? [];
const groups = hooks[event] ?? [];
groups.forEach((group, groupIndex) => {
const handlerIndexes = group.hooks.flatMap((handler, handlerIndex) => {
const managedId = managedAgentId(handler, scriptName);
const managedId = managedAgentId(handler, scriptName, true);
return managedId && (agentId === undefined || sameAgentId(managedId, agentId))
? [handlerIndex]
: [];
@@ -264,20 +288,21 @@ export function managedRemovals(
return removals;
}
function managedIds(groups: DroidGroup[], scriptName: string): Set<string> {
function configuredIds(groups: DroidGroup[], scriptName: string): Set<string> {
const ids = new Set<string>();
for (const group of groups) {
for (const handler of group.hooks) {
const agentId = managedAgentId(handler, scriptName);
if (agentId) ids.add(agentId);
}
if (Object.keys(group).sort().join('\0') !== GROUP_KEYS.join('\0')
|| group.matcher !== '*'
|| group.hooks.length !== 1) continue;
const agentId = managedAgentId(group.hooks[0], scriptName);
if (agentId) ids.add(agentId);
}
return ids;
}
export function runtimeContracts(settings: DroidHookSettings): RuntimeContract[] {
const guards = managedIds(settings.PreToolUse ?? [], GUARD_SCRIPT);
const audits = managedIds(settings.PostToolUse ?? [], AUDIT_SCRIPT);
export function runtimeContracts(hooks: DroidHookMap): RuntimeContract[] {
const guards = configuredIds(hooks.PreToolUse ?? [], GUARD_SCRIPT);
const audits = configuredIds(hooks.PostToolUse ?? [], AUDIT_SCRIPT);
const root = path.join(os.homedir(), '.elydora');
return [...guards]
.filter((agentId) => [...audits].some((auditId) => sameAgentId(auditId, agentId)))
@@ -287,10 +312,3 @@ export function runtimeContracts(settings: DroidHookSettings): RuntimeContract[]
auditPath: path.join(root, agentId, AUDIT_SCRIPT),
}));
}
export function mergeHookSettings(
primary: DroidHookSettings | undefined,
fallback: DroidHookSettings | undefined,
): DroidHookSettings {
return { ...(fallback ?? {}), ...(primary ?? {}) };
}
+172
View File
@@ -0,0 +1,172 @@
import path from 'node:path';
import type { InstallConfig } from './base.js';
import {
AGENT_KEY,
AUDIT_SCRIPT,
GUARD_SCRIPT,
samePath,
} from './droid-contract.js';
import {
activeDocument,
installationDocuments,
sourceDocuments,
type DroidDocument,
type DroidSources,
type RenderedDocument,
} from './droid-config.js';
import { requireHooksEnabled } from './droid-io.js';
import {
commitManagedInstallation,
preflightManagedInstallation,
prepareManagedInstallation,
type ManagedRuntimePaths,
type PreparedManagedInstallation,
type RenameFile,
} from './managed-installation.js';
import {
commitManagedTransaction,
prepareManagedFileChange,
type PreparedManagedTransaction,
} from './managed-transaction.js';
const DISPLAY_NAME = 'Factory Droid';
const DIRECTORY_LABEL = 'Factory Droid user configuration directory';
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
export type DroidRuntimePaths = ManagedRuntimePaths;
export type PreparedDroidInstallation = PreparedManagedInstallation;
export type { RenameFile };
function sourceLabel(document: DroidDocument): string {
if (document.kind === 'settings') return 'Factory Droid user settings';
if (document.kind === 'local-settings') return 'Factory Droid local settings';
if (document.kind === 'legacy') return 'Factory Droid legacy hooks';
return 'Factory Droid user hooks';
}
function hookLocations(sources: DroidSources) {
return installationDocuments(sources).map((document) => ({
directoryLabel: document.kind === 'legacy'
? 'Factory Droid legacy hooks directory'
: DIRECTORY_LABEL,
filePath: document.filePath,
}));
}
export async function preflightDroidInstallation(
config: InstallConfig,
sources: DroidSources,
): Promise<DroidRuntimePaths> {
requireHooksEnabled(sources);
return preflightManagedInstallation({
agentKey: AGENT_KEY,
hookLocations: hookLocations(sources),
config,
}, GUARD_SCRIPT, AUDIT_SCRIPT);
}
function installationChanges(
sources: DroidSources,
rendered: readonly RenderedDocument[],
): readonly RenderedDocument[] {
const target = activeDocument(sources);
return rendered.filter((item) => item.changed || item.document === target);
}
function sourcePreconditions(
sources: DroidSources,
changed: readonly RenderedDocument[],
) {
const changedPaths = changed.map((item) => item.document.filePath);
return sourceDocuments(sources)
.filter((document) => !changedPaths.some((filePath) => samePath(filePath, document.filePath)))
.map((document) => ({
filePath: document.filePath,
label: sourceLabel(document),
maximumBytes: MAX_SOURCE_BYTES,
original: document.snapshot,
}));
}
export async function prepareDroidInstallation(
config: InstallConfig,
sources: DroidSources,
rendered: readonly RenderedDocument[],
): Promise<PreparedDroidInstallation> {
await preflightDroidInstallation(config, sources);
const changed = installationChanges(sources, rendered);
const prepared = await prepareManagedInstallation({
agentKey: AGENT_KEY,
displayName: DISPLAY_NAME,
hookSources: changed.map((item) => ({
directoryLabel: item.document.kind === 'legacy'
? 'Factory Droid legacy hooks directory'
: DIRECTORY_LABEL,
label: sourceLabel(item.document),
filePath: item.document.filePath,
expectedSource: item.document.exists ? item.document.raw : undefined,
expectedSnapshot: item.document.snapshot,
source: item.changed ? item.next : item.document.raw,
})),
config,
auditOptions: { nativePayload: true },
}, GUARD_SCRIPT, AUDIT_SCRIPT);
return {
...prepared,
transaction: {
...prepared.transaction,
preconditions: [
...sourcePreconditions(sources, changed),
...sources.policy.preconditions,
],
},
};
}
export async function commitDroidInstallation(
prepared: PreparedDroidInstallation,
renameFile?: RenameFile,
): Promise<void> {
await commitManagedInstallation(prepared, renameFile);
}
export async function prepareDroidUninstall(
rendered: readonly RenderedDocument[],
): Promise<PreparedManagedTransaction> {
const changed = rendered.filter((item) => item.changed);
const changes = await Promise.all(changed.map((item) => prepareManagedFileChange({
filePath: item.document.filePath,
label: sourceLabel(item.document),
next: item.next,
mode: 0o600,
expectedSource: item.document.raw,
expectedSnapshot: item.document.snapshot,
verifyExpectedSource: true,
})));
return {
displayName: DISPLAY_NAME,
operation: 'uninstall',
directories: changed.map((item) => ({
path: path.dirname(item.document.filePath),
label: item.document.kind === 'legacy'
? 'Factory Droid legacy hooks directory'
: DIRECTORY_LABEL,
})),
changes: changes.filter((change) => change !== undefined),
preconditions: rendered
.filter((item) => !item.changed)
.map((item) => ({
filePath: item.document.filePath,
label: sourceLabel(item.document),
maximumBytes: MAX_SOURCE_BYTES,
original: item.document.snapshot,
})),
};
}
export async function commitDroidUninstall(
prepared: PreparedManagedTransaction,
renameFile?: RenameFile,
): Promise<void> {
await commitManagedTransaction(prepared, renameFile);
}
+137 -262
View File
@@ -1,310 +1,185 @@
import { randomUUID } from 'node:crypto';
import fsp from 'node:fs/promises';
import type { FileHandle } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import {
AGENT_KEY,
type JsonObject,
AUDIT_SCRIPT,
GUARD_SCRIPT,
type RuntimeContract,
isObject,
sameAgentId,
samePath,
} from './droid-contract.js';
import {
type DroidSources,
type RenderedDocument,
activeDocument,
createLegacyHookDocument,
createOwnedHookDocument,
createSettingsDocument,
hookBlock,
parseDocument,
type DroidDocument,
type DroidDocumentKind,
type DroidSources,
} from './droid-config.js';
import { generateGuardScript } from './guard-template.js';
import { generateHookScript } from './hook-template.js';
import { readDroidPolicy } from './droid-policy.js';
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
import { parseStrictJsonObject, type JsonObject } from './strict-json.js';
interface FileChange {
readonly filePath: string;
readonly label: string;
readonly original?: string;
readonly next?: string;
}
const MAX_SECRET_BYTES = 64 * 1024;
const MAX_CONFIG_BYTES = 512 * 1024;
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
interface StagedChange {
readonly change: FileChange;
readonly tempPath?: string;
readonly rollbackPath?: string;
committed: boolean;
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function asError(error: unknown): Error {
return error instanceof Error ? error : new Error(String(error));
}
function hasErrorCode(error: unknown, code: string): boolean {
return isObject(error) && error.code === code;
}
function factoryPaths(): {
interface FactoryPaths {
readonly directory: string;
readonly root: string;
readonly legacyDirectory: string;
readonly legacy: string;
readonly settings: string;
} {
readonly localSettings: string;
}
function factoryPaths(): FactoryPaths {
const directory = path.join(os.homedir(), '.factory');
const legacyDirectory = path.join(directory, 'hooks');
return {
directory,
root: path.join(directory, 'hooks.json'),
legacy: path.join(directory, 'hooks', 'hooks.json'),
legacyDirectory,
legacy: path.join(legacyDirectory, 'hooks.json'),
settings: path.join(directory, 'settings.json'),
localSettings: path.join(directory, 'settings.local.json'),
};
}
async function readOptional(filePath: string, label: string): Promise<string | undefined> {
try {
return await fsp.readFile(filePath, 'utf-8');
} catch (error) {
if (hasErrorCode(error, 'ENOENT')) return undefined;
throw new Error(`Read ${label} at ${filePath}: ${errorMessage(error)}`, {
cause: asError(error),
});
}
async function readDocument(
filePath: string,
kind: DroidDocumentKind,
label: string,
): Promise<DroidDocument | undefined> {
const snapshot = await readPhysicalFile(filePath, label, MAX_SOURCE_BYTES);
return snapshot ? parseDocument({
exists: true,
filePath,
kind,
raw: snapshot.contents,
snapshot,
}) : undefined;
}
export async function readSources(): Promise<DroidSources> {
const paths = factoryPaths();
const [rootRaw, settingsRaw] = await Promise.all([
readOptional(paths.root, 'Factory Droid hooks'),
readOptional(paths.settings, 'Factory Droid settings'),
await inspectPhysicalDirectory(paths.directory, 'Factory Droid user configuration directory');
await inspectPhysicalDirectory(paths.legacyDirectory, 'Factory Droid legacy hooks directory');
const [root, legacy, settings, localSettings, policy] = await Promise.all([
readDocument(paths.root, 'hooks', 'Factory Droid user hooks'),
readDocument(paths.legacy, 'legacy', 'Factory Droid legacy hooks'),
readDocument(paths.settings, 'settings', 'Factory Droid user settings'),
readDocument(paths.localSettings, 'local-settings', 'Factory Droid local settings'),
readDroidPolicy(),
]);
let primary;
if (rootRaw !== undefined) {
primary = parseDocument({
exists: true,
filePath: paths.root,
kind: 'hooks',
raw: rootRaw,
});
} else {
const legacyRaw = await readOptional(paths.legacy, 'Factory Droid legacy hooks');
if (legacyRaw !== undefined) {
primary = parseDocument({
exists: true,
filePath: paths.legacy,
kind: 'legacy',
raw: legacyRaw,
});
}
}
const settings = settingsRaw === undefined
? createSettingsDocument(paths.settings)
: parseDocument({
exists: true,
filePath: paths.settings,
kind: 'settings',
raw: settingsRaw,
});
return { rootPath: paths.root, primary, settings };
}
function labelFor(rendered: RenderedDocument): string {
if (rendered.document.kind === 'settings') return 'Factory Droid settings';
if (rendered.document.kind === 'legacy') return 'Factory Droid legacy hooks';
return 'Factory Droid hooks';
}
function fileChange(rendered: RenderedDocument): FileChange | undefined {
if (!rendered.changed) return undefined;
return {
filePath: rendered.document.filePath,
label: labelFor(rendered),
original: rendered.document.exists ? rendered.document.raw : undefined,
next: rendered.next,
root: root ?? createOwnedHookDocument(paths.root),
legacy: legacy ?? createLegacyHookDocument(paths.legacy),
settings: settings ?? createSettingsDocument(paths.settings),
localSettings: localSettings
?? createSettingsDocument(paths.localSettings, 'local-settings'),
policy,
};
}
async function unlinkOptional(filePath: string): Promise<void> {
try {
await fsp.unlink(filePath);
} catch (error) {
if (!hasErrorCode(error, 'ENOENT')) throw error;
export function requireHooksEnabled(sources: DroidSources): void {
const blocked = hookBlock(sources);
if (blocked) {
throw new Error(
`Factory Droid user hooks are disabled by ${blocked.field} in ${blocked.label} at ${blocked.filePath}`,
);
}
}
async function writeExclusive(filePath: string, contents: string, label: string): Promise<void> {
let handle: FileHandle | undefined;
try {
handle = await fsp.open(filePath, 'wx', 0o600);
await handle.writeFile(contents, 'utf-8');
await handle.sync();
await handle.close();
} catch (error) {
const failures = [asError(error)];
if (handle) {
try {
await handle.close();
} catch (closeError) {
failures.push(asError(closeError));
}
}
try {
await unlinkOptional(filePath);
} catch (cleanupError) {
failures.push(asError(cleanupError));
}
if (failures.length > 1) {
throw new AggregateError(failures, `Stage ${label} at ${filePath}`);
}
throw new Error(`Stage ${label} at ${filePath}: ${errorMessage(error)}`, {
cause: failures[0],
});
function requireString(value: unknown, field: string, configPath: string): string {
if (typeof value !== 'string' || value.trim().length === 0) {
throw new Error(`Elydora runtime config ${field} is invalid: ${configPath}`);
}
}
async function assertUnchanged(change: FileChange): Promise<void> {
const current = await readOptional(change.filePath, change.label);
if (current !== change.original) {
throw new Error(`${change.label} changed during installation: ${change.filePath}`);
}
}
async function stage(change: FileChange): Promise<StagedChange> {
await assertUnchanged(change);
const directory = path.dirname(change.filePath);
await fsp.mkdir(directory, { recursive: true, mode: 0o700 });
const token = randomUUID();
const tempPath = change.next === undefined
? undefined
: path.join(directory, `.${path.basename(change.filePath)}.${token}.tmp`);
const rollbackPath = change.original === undefined
? undefined
: path.join(directory, `.${path.basename(change.filePath)}.${token}.rollback`);
try {
if (tempPath) await writeExclusive(tempPath, change.next!, change.label);
if (rollbackPath && change.next !== undefined) {
await writeExclusive(rollbackPath, change.original!, `${change.label} rollback`);
}
} catch (error) {
const failures = [asError(error)];
for (const stagedPath of [tempPath, rollbackPath]) {
if (!stagedPath) continue;
try {
await unlinkOptional(stagedPath);
} catch (cleanupError) {
failures.push(asError(cleanupError));
}
}
if (failures.length > 1) throw new AggregateError(failures, `Stage ${change.label}`);
throw error;
}
return { change, tempPath, rollbackPath, committed: false };
}
async function commit(staged: StagedChange): Promise<void> {
await assertUnchanged(staged.change);
if (staged.change.next === undefined) {
if (!staged.rollbackPath) throw new Error(`Missing rollback path for ${staged.change.label}`);
await fsp.rename(staged.change.filePath, staged.rollbackPath);
} else {
if (!staged.tempPath) throw new Error(`Missing staged file for ${staged.change.label}`);
await fsp.rename(staged.tempPath, staged.change.filePath);
}
staged.committed = true;
}
async function rollback(staged: StagedChange): Promise<void> {
if (!staged.committed) return;
if (staged.change.original === undefined) {
await unlinkOptional(staged.change.filePath);
return;
}
if (!staged.rollbackPath) throw new Error(`Missing rollback data for ${staged.change.label}`);
await fsp.rename(staged.rollbackPath, staged.change.filePath);
}
async function cleanup(staged: StagedChange): Promise<void> {
const paths = [staged.tempPath, staged.rollbackPath].filter(
(filePath): filePath is string => filePath !== undefined,
);
await Promise.all(paths.map(unlinkOptional));
}
export async function writeDocuments(rendered: RenderedDocument[]): Promise<void> {
const changes = rendered.flatMap((item) => {
const next = fileChange(item);
return next ? [next] : [];
});
if (changes.length === 0) return;
const staged: StagedChange[] = [];
try {
for (const change of changes) staged.push(await stage(change));
for (const item of staged) await commit(item);
} catch (error) {
const failures = [asError(error)];
for (const item of [...staged].reverse()) {
try {
await rollback(item);
} catch (rollbackError) {
failures.push(asError(rollbackError));
}
}
for (const item of staged) {
try {
await cleanup(item);
} catch (cleanupError) {
failures.push(asError(cleanupError));
}
}
if (failures.length > 1) throw new AggregateError(failures, 'Write Factory Droid hook sources');
throw new Error(`Write Factory Droid hook sources: ${errorMessage(error)}`, {
cause: failures[0],
});
}
await Promise.all(staged.map(cleanup));
}
export async function regularFileExists(filePath: string, label: string): Promise<boolean> {
try {
return (await fsp.stat(filePath)).isFile();
} catch (error) {
if (hasErrorCode(error, 'ENOENT') || hasErrorCode(error, 'ENOTDIR')) return false;
throw new Error(`Read ${label} at ${filePath}: ${errorMessage(error)}`, {
cause: asError(error),
});
}
}
export async function requireRuntime(filePath: string, label: string): Promise<void> {
if (!filePath) throw new Error(`${label} path is required`);
if (!await regularFileExists(filePath, label)) throw new Error(`${label} is missing: ${filePath}`);
}
async function readRuntimeConfig(filePath: string): Promise<JsonObject | undefined> {
const raw = await readOptional(filePath, 'Elydora runtime config');
if (raw === undefined) return undefined;
let value: unknown;
try {
value = JSON.parse(raw);
} catch (error) {
throw new Error(`Failed to parse Elydora runtime config at ${filePath}: ${errorMessage(error)}`, {
cause: asError(error),
});
}
if (!isObject(value)) throw new Error(`Elydora runtime config at ${filePath} must contain a JSON object`);
return value;
}
function validateRuntimeConfig(
config: JsonObject,
contract: RuntimeContract,
configPath: string,
): void {
const supported = new Set(['org_id', 'agent_id', 'kid', 'base_url', 'token', 'agent_name']);
const extra = Object.keys(config).find((key) => !supported.has(key));
if (extra) throw new Error(`Elydora runtime config has unsupported field "${extra}": ${configPath}`);
requireString(config.org_id, 'org_id', configPath);
requireString(config.kid, 'kid', configPath);
const agentId = requireString(config.agent_id, 'agent_id', configPath);
if (!sameAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
throw new Error(`Elydora runtime identity does not match Factory Droid hooks: ${configPath}`);
}
if (config.token !== undefined) requireString(config.token, 'token', configPath);
const rawBaseUrl = requireString(config.base_url, 'base_url', configPath);
let baseUrl: URL;
try {
baseUrl = new URL(rawBaseUrl);
} catch (error) {
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`, {
cause: error instanceof Error ? error : new Error(String(error)),
});
}
if (!['http:', 'https:'].includes(baseUrl.protocol)
|| !baseUrl.hostname
|| baseUrl.username
|| baseUrl.password
|| baseUrl.search
|| baseUrl.hash) {
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`);
}
}
function validatePrivateKey(contents: string, keyPath: string): void {
const bytes = Buffer.from(contents, 'base64url');
if (bytes.length !== 32 || bytes.toString('base64url') !== contents) {
throw new Error(`Elydora private key is invalid: ${keyPath}`);
}
}
function validContractPaths(contract: RuntimeContract): boolean {
const agentDirectory = path.dirname(contract.guardPath);
return samePath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))
&& samePath(contract.guardPath, path.join(agentDirectory, GUARD_SCRIPT))
&& samePath(contract.auditPath, path.join(agentDirectory, AUDIT_SCRIPT));
}
export async function runtimeFilesExist(contracts: RuntimeContract[]): Promise<boolean> {
for (const contract of contracts) {
if (!validContractPaths(contract)) continue;
const runtimeRoot = path.join(os.homedir(), '.elydora');
const agentDirectory = path.dirname(contract.guardPath);
const runtimeConfig = await readRuntimeConfig(path.join(agentDirectory, 'config.json'));
if (!runtimeConfig || runtimeConfig.agent_name !== AGENT_KEY) continue;
const files = await Promise.all([
regularFileExists(contract.guardPath, 'Elydora guard runtime'),
regularFileExists(contract.auditPath, 'Elydora audit runtime'),
if (!await inspectPhysicalDirectory(runtimeRoot, 'Elydora runtime directory')) continue;
if (!await inspectPhysicalDirectory(agentDirectory, 'Elydora agent runtime directory')) continue;
const configPath = path.join(agentDirectory, 'config.json');
const keyPath = path.join(agentDirectory, 'private.key');
const [config, key, guard, audit] = await Promise.all([
readPhysicalFile(configPath, 'Elydora runtime config', MAX_CONFIG_BYTES),
readPhysicalFile(keyPath, 'Elydora private key', MAX_SECRET_BYTES),
readPhysicalFile(contract.guardPath, 'Elydora guard runtime'),
readPhysicalFile(contract.auditPath, 'Elydora audit runtime'),
]);
if (files.every(Boolean)) return true;
if (!config || !key || !guard || !audit) continue;
const parsed = parseStrictJsonObject(config.contents, `Elydora runtime config at ${configPath}`);
validateRuntimeConfig(parsed, contract, configPath);
validatePrivateKey(key.contents, keyPath);
if (guard.contents === generateGuardScript(AGENT_KEY, contract.agentId)
&& audit.contents === generateHookScript(
AGENT_KEY,
contract.agentId,
{ nativePayload: true },
)) return true;
}
return false;
}
export function displayConfigPath(sources: DroidSources): string {
if (sources.primary) return sources.primary.filePath;
if (sources.settings.exists && sources.settings.hasHooksContainer) return sources.settings.filePath;
return sources.rootPath;
return activeDocument(sources).filePath;
}
+157
View File
@@ -0,0 +1,157 @@
import fsp from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { inspectPhysicalDirectory, readPhysicalFile, type FileSnapshot } from './managed-files.js';
import { parseStrictJsoncObject, type JsonObject } from './strict-json.js';
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
interface PolicyLocation {
readonly filePath: string;
readonly label: string;
}
interface PolicyLayer extends PolicyLocation {
readonly snapshot?: FileSnapshot;
readonly hooksDisabled?: boolean;
readonly allowManagedHooksOnly?: boolean;
readonly showHookOutput?: boolean;
}
export interface DroidPolicyPrecondition {
readonly filePath: string;
readonly label: string;
readonly maximumBytes: number;
readonly original?: FileSnapshot;
}
export interface DroidPolicyOrigin {
readonly filePath: string;
readonly label: string;
}
export interface DroidPolicyState {
readonly allowManagedHooksOnlyBy?: DroidPolicyOrigin;
readonly hooksDisabled?: boolean;
readonly hooksDisabledBy?: DroidPolicyOrigin;
readonly preconditions: readonly DroidPolicyPrecondition[];
}
function hasCode(error: unknown, code: string): boolean {
return typeof error === 'object' && error !== null && 'code' in error && error.code === code;
}
function optionalBoolean(root: JsonObject, field: string, label: string): boolean | undefined {
const value = root[field];
if (value !== undefined && typeof value !== 'boolean') {
throw new Error(`${label} field "${field}" must be a boolean`);
}
return value as boolean | undefined;
}
function managedSettingsPath(): string {
if (process.platform === 'darwin') {
return '/Library/Application Support/Factory/settings.json';
}
if (process.platform === 'win32') {
return path.join(process.env.ProgramFiles ?? 'C:\\Program Files', 'Factory', 'settings.json');
}
return '/etc/factory/settings.json';
}
async function readLayer(location: PolicyLocation): Promise<PolicyLayer> {
await inspectPhysicalDirectory(path.dirname(location.filePath), `${location.label} directory`);
const snapshot = await readPhysicalFile(location.filePath, location.label, MAX_SOURCE_BYTES);
if (!snapshot) return location;
const root = parseStrictJsoncObject(snapshot.contents, `${location.label} at ${location.filePath}`);
return {
...location,
snapshot,
hooksDisabled: optionalBoolean(root, 'hooksDisabled', location.label),
allowManagedHooksOnly: optionalBoolean(root, 'allowManagedHooksOnly', location.label),
showHookOutput: optionalBoolean(root, 'showHookOutput', location.label),
};
}
async function gitRoot(start: string): Promise<string | undefined> {
let current = path.resolve(start);
for (;;) {
const marker = path.join(current, '.git');
try {
const metadata = await fsp.lstat(marker);
if (metadata.isSymbolicLink() || (!metadata.isDirectory() && !metadata.isFile())) {
throw new Error(`Factory Droid project marker is not physical: ${marker}`);
}
return current;
} catch (error) {
if (!hasCode(error, 'ENOENT') && !hasCode(error, 'ENOTDIR')) throw error;
}
const parent = path.dirname(current);
if (parent === current) return undefined;
current = parent;
}
}
function projectDirectories(root: string, current: string): string[] {
const directories = [root];
const relative = path.relative(root, current);
if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return directories;
let directory = root;
for (const segment of relative.split(path.sep).filter(Boolean)) {
directory = path.join(directory, segment);
directories.push(directory);
}
return directories;
}
async function projectLocations(): Promise<PolicyLocation[][]> {
const current = path.resolve(process.cwd());
const root = await gitRoot(current) ?? current;
return projectDirectories(root, current).map((directory, index) => {
const factory = path.join(directory, '.factory');
const scope = index === 0 ? 'project' : `folder ${directory}`;
return [{
filePath: path.join(factory, 'settings.json'),
label: `Factory Droid ${scope} settings`,
}, {
filePath: path.join(factory, 'settings.local.json'),
label: `Factory Droid ${scope} local settings`,
}];
});
}
function scopeValue(layers: readonly PolicyLayer[], field: 'hooksDisabled'): PolicyLayer | undefined {
const [settings, local] = layers;
return local[field] !== undefined ? local : settings[field] !== undefined ? settings : undefined;
}
export async function readDroidPolicy(): Promise<DroidPolicyState> {
const managedLocation: PolicyLocation = {
filePath: managedSettingsPath(),
label: 'Factory Droid system-managed settings',
};
const scopes = await projectLocations();
const [managed, ...projectLayers] = await Promise.all([
readLayer(managedLocation),
...scopes.map(async (scope) => Promise.all(scope.map(readLayer))),
]);
const flattened = [managed, ...projectLayers.flat()];
const allowManagedHooksOnlyBy = managed.allowManagedHooksOnly === true
? { filePath: managed.filePath, label: managed.label }
: undefined;
const selected = [managed, ...projectLayers.map((scope) => scopeValue(scope, 'hooksDisabled'))]
.find((layer) => layer?.hooksDisabled !== undefined);
return {
allowManagedHooksOnlyBy,
hooksDisabled: selected?.hooksDisabled,
hooksDisabledBy: selected
? { filePath: selected.filePath, label: selected.label }
: undefined,
preconditions: flattened.map((layer) => ({
filePath: layer.filePath,
label: layer.label,
maximumBytes: MAX_SOURCE_BYTES,
original: layer.snapshot,
})),
};
}
+54 -56
View File
@@ -1,88 +1,86 @@
import type { AgentPlugin, InstallConfig, PluginStatus } from './base.js';
import {
AGENT_KEY,
TOOL_EVENTS,
buildGroup,
mergeHookSettings,
runtimeContracts,
type DroidGroup,
type ToolEvent,
} from './droid-contract.js';
import {
additionsFor,
installationTargets,
activeDocument,
additionsForTarget,
effectiveHooks,
hookBlock,
installationDocuments,
renderDocument,
type DroidDocument,
sourceDocuments,
type DroidSources,
type RenderedDocument,
} from './droid-config.js';
import {
displayConfigPath,
readSources,
requireRuntime,
runtimeFilesExist,
writeDocuments,
} from './droid-io.js';
commitDroidInstallation,
commitDroidUninstall,
preflightDroidInstallation,
prepareDroidInstallation,
prepareDroidUninstall,
} from './droid-installation.js';
import { displayConfigPath, readSources, runtimeFilesExist } from './droid-io.js';
import { SUPPORTED_AGENTS } from './registry.js';
const entry = SUPPORTED_AGENTS.get(AGENT_KEY)!;
function uniqueDocuments(documents: Array<DroidDocument | undefined>): DroidDocument[] {
const unique = new Map<string, DroidDocument>();
for (const document of documents) {
if (document) unique.set(document.filePath, document);
}
return [...unique.values()];
function renderInstallation(
sources: DroidSources,
guardPath: string,
auditPath: string,
): RenderedDocument[] {
const target = activeDocument(sources);
const groups = new Map<ToolEvent, DroidGroup>([
['PreToolUse', buildGroup(guardPath)],
['PostToolUse', buildGroup(auditPath)],
]);
return installationDocuments(sources).map((document) => renderDocument(
document,
undefined,
additionsForTarget(document, target, groups),
));
}
function renderUninstall(sources: DroidSources, agentId?: string): RenderedDocument[] {
return sourceDocuments(sources).map(
(document) => renderDocument(document, agentId, new Map()),
);
}
export const droidPlugin: AgentPlugin = {
async install(config: InstallConfig): Promise<void> {
if (!config.agentId) throw new Error('agentId is required');
const sources = await readSources();
await requireRuntime(config.guardScriptPath, 'Elydora guard runtime');
await requireRuntime(config.hookScriptPath, 'Elydora audit runtime');
managesRuntime: true,
const selected = installationTargets(sources);
const groups = new Map<ToolEvent, DroidGroup>([
['PreToolUse', buildGroup(config.guardScriptPath)],
['PostToolUse', buildGroup(config.hookScriptPath)],
]);
const documents = uniqueDocuments([
sources.primary,
sources.settings.hasHooksContainer ? sources.settings : undefined,
...TOOL_EVENTS.map((event) => selected.targets.get(event)),
]);
const rendered = documents.map((document) => renderDocument(
document,
undefined,
additionsFor(document, selected.targets, groups),
));
await writeDocuments(rendered);
const locations = TOOL_EVENTS
.map((event) => `${event}: ${selected.targets.get(event)!.filePath}`)
.join(', ');
console.log(` Factory Droid: ${locations}`);
async preflightInstall(config: InstallConfig): Promise<void> {
const sources = await readSources();
await preflightDroidInstallation(config, sources);
},
async install(config: InstallConfig): Promise<void> {
const sources = await readSources();
const paths = await preflightDroidInstallation(config, sources);
const rendered = renderInstallation(sources, paths.guardPath, paths.auditPath);
const prepared = await prepareDroidInstallation(config, sources, rendered);
await commitDroidInstallation(prepared);
console.log(` Factory Droid hooks: ${activeDocument(sources).filePath}`);
console.log(' Factory Droid: run /hooks to review the Elydora hook changes.');
},
async uninstall(agentId?: string): Promise<void> {
const sources = await readSources();
const documents = uniqueDocuments([
sources.primary,
sources.settings.hasHooksContainer ? sources.settings : undefined,
]);
const rendered = documents.map((document) => renderDocument(
document,
agentId,
new Map(),
));
await writeDocuments(rendered);
const prepared = await prepareDroidUninstall(renderUninstall(sources, agentId));
await commitDroidUninstall(prepared);
},
async status(): Promise<PluginStatus> {
const sources = await readSources();
const effective = mergeHookSettings(sources.primary?.hooks, sources.settings.hooks);
const contracts = runtimeContracts(effective);
const hookConfigured = effective.hooksDisabled !== true && contracts.length > 0;
const hookScriptExists = hookConfigured ? await runtimeFilesExist(contracts) : false;
const contracts = runtimeContracts(effectiveHooks(sources));
const hookConfigured = hookBlock(sources) === undefined && contracts.length > 0;
const hookScriptExists = hookConfigured && await runtimeFilesExist(contracts);
return {
installed: hookConfigured && hookScriptExists,
agentName: AGENT_KEY,