fix(grok): implement official hook contract

This commit is contained in:
ZacharyZhang-NY committed 2026-07-20 05:16:35 -04:00
1 parent d8d4e8d336
commit e2d8351f36
14 files changed
+1623 -839

No files matched your search

+1
View File
@@ -64,6 +64,7 @@ export async function prepareCursorInstallation(
guardOptions: {
failClosed: true,
successOutput: '{"permission":"allow"}\n',
denyProtocol: 'cursor',
},
auditOptions: {
failClosed: true,
+159
View File
@@ -0,0 +1,159 @@
import os from 'node:os';
import path from 'node:path';
interface ParsedArgument {
readonly value: string;
readonly next: number;
}
export interface GrokRuntimeReference {
readonly agentId: string;
readonly scriptPath: string;
}
export function sameGrokPath(left: string, right: string): boolean {
const normalizedLeft = path.resolve(left);
const normalizedRight = path.resolve(right);
return process.platform === 'win32'
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
: normalizedLeft === normalizedRight;
}
export function sameGrokAgentId(left: string, right: string): boolean {
return process.platform === 'win32'
? left.toLowerCase() === right.toLowerCase()
: left === right;
}
function quotePosix(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}
function quotePowerShell(value: string): string {
return `'${value.replaceAll("'", "''")}'`;
}
function windowsPowerShellPath(): string {
const configuredRoot = process.platform === 'win32' ? process.env.SystemRoot : undefined;
const systemRoot = configuredRoot
&& path.win32.isAbsolute(configuredRoot)
&& !/["%\r\n]/.test(configuredRoot)
? configuredRoot
: 'C:\\Windows';
return path.win32.join(
systemRoot,
'System32',
'WindowsPowerShell',
'v1.0',
'powershell.exe',
);
}
function windowsCommand(scriptPath: string): string {
const source = `& ${quotePowerShell(process.execPath)} ${quotePowerShell(scriptPath)}; exit $LASTEXITCODE`;
const encoded = Buffer.from(source, 'utf16le').toString('base64');
return `"${windowsPowerShellPath()}" -NoLogo -NoProfile -NonInteractive -EncodedCommand ${encoded}`;
}
export function buildGrokCommand(scriptPath: string): string {
if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) {
throw new Error('Grok hook commands require absolute executable and script paths');
}
return process.platform === 'win32'
? windowsCommand(scriptPath)
: `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`;
}
function readPosixArgument(command: string, start: number): ParsedArgument | undefined {
if (command[start] !== "'") return undefined;
const apostrophe = `'"'"'`;
let value = '';
for (let index = start + 1; index < command.length;) {
if (command.startsWith(apostrophe, index)) {
value += "'";
index += apostrophe.length;
continue;
}
if (command[index] === "'") return { value, next: index + 1 };
value += command[index];
index += 1;
}
return undefined;
}
function parsePosixCommand(command: string): readonly [string, string] | undefined {
const executable = readPosixArgument(command, 0);
if (!executable || command[executable.next] !== ' ') return undefined;
const script = readPosixArgument(command, executable.next + 1);
if (!script || script.next !== command.length) return undefined;
return [executable.value, script.value];
}
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] !== "'") {
value += command[index];
continue;
}
if (command[index + 1] === "'") {
value += "'";
index += 1;
continue;
}
return { value, next: index + 1 };
}
return undefined;
}
function parsePowerShellSource(source: string): readonly [string, string] | undefined {
if (!source.startsWith('& ')) return undefined;
const executable = readPowerShellArgument(source, 2);
if (!executable || source[executable.next] !== ' ') return undefined;
const script = readPowerShellArgument(source, executable.next + 1);
if (!script || source.slice(script.next) !== '; exit $LASTEXITCODE') return undefined;
return [executable.value, script.value];
}
function parseWindowsCommand(command: string): readonly [string, string] | undefined {
const match = /^"([^"\r\n]+)" -NoLogo -NoProfile -NonInteractive -EncodedCommand ([A-Za-z0-9+/]+={0,2})$/.exec(command);
if (!match
|| !path.win32.isAbsolute(match[1])
|| path.win32.basename(match[1]).toLowerCase() !== 'powershell.exe') return undefined;
const encoded = match[2];
const buffer = Buffer.from(encoded, 'base64');
if (buffer.length % 2 !== 0 || buffer.toString('base64') !== encoded) return undefined;
return parsePowerShellSource(buffer.toString('utf16le'));
}
function parseLegacyWindowsCommand(command: string): readonly [string, string] | undefined {
const match = /^"([^"\r\n]+)" "([^"\r\n]+)"$/.exec(command);
return match ? [match[1], match[2]] : undefined;
}
function isNodeExecutable(filePath: string): boolean {
const basename = path.basename(filePath).toLowerCase();
return basename === 'node' || basename === 'node.exe';
}
export function grokRuntimeReference(
command: string,
scriptName: string,
): GrokRuntimeReference | undefined {
const parsed = parsePosixCommand(command)
?? parseWindowsCommand(command)
?? parseLegacyWindowsCommand(command);
if (!parsed
|| !path.isAbsolute(parsed[0])
|| !path.isAbsolute(parsed[1])
|| !isNodeExecutable(parsed[0])
|| path.basename(parsed[1]) !== scriptName) return undefined;
const agentDirectory = path.dirname(parsed[1]);
if (!sameGrokPath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))) {
return undefined;
}
const agentId = path.basename(agentDirectory);
if (!agentId || agentId === '.' || agentId === '..') return undefined;
return { agentId, scriptPath: parsed[1] };
}
+276
View File
@@ -0,0 +1,276 @@
import {
buildGrokCommand,
grokRuntimeReference,
sameGrokAgentId,
type GrokRuntimeReference,
} from './grok-command.js';
import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js';
export const AGENT_KEY = 'grok';
export const GUARD_SCRIPT = 'guard.js';
export const AUDIT_SCRIPT = 'hook.js';
export const HOOK_TIMEOUT_SECONDS = 10;
const MATCHER_REJECTING_EVENTS = new Set([
'SessionStart',
'SessionEnd',
'Stop',
'UserPromptSubmit',
]);
export type ManagedGrokEvent = 'PreToolUse' | 'PostToolUse' | 'PostToolUseFailure';
export interface GrokHandler extends JsonObject {
readonly type: 'command' | 'http';
readonly command?: string;
readonly url?: string;
readonly timeout?: number;
}
export interface GrokGroup extends JsonObject {
readonly matcher?: string;
readonly hooks: GrokHandler[];
}
export type GrokHooks = Record<string, GrokGroup[]>;
export interface GrokDocument {
readonly exists: boolean;
readonly filePath: string;
readonly root: JsonObject;
readonly hooks: GrokHooks;
readonly raw?: string;
}
export interface RenderedGrokDocument {
readonly document: GrokDocument;
readonly changed: boolean;
readonly next?: string;
}
export interface GrokRuntimeContract {
readonly agentId: string;
readonly guardPath: string;
readonly auditPath: string;
}
function validateTimeout(value: unknown, label: string): void {
if (value === undefined) return;
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new Error(`${label} timeout must be a non-negative integer`);
}
}
function validateHandler(
value: unknown,
event: string,
groupIndex: number,
handlerIndex: number,
): GrokHandler {
const label = `Grok user hooks handler hooks.${event}[${groupIndex}].hooks[${handlerIndex}]`;
if (!isObject(value)) throw new Error(`${label} must be an object`);
if (value.type !== 'command' && value.type !== 'http') {
throw new Error(`${label} has unsupported type "${String(value.type)}"`);
}
if (value.type === 'command' && (typeof value.command !== 'string' || !value.command)) {
throw new Error(`${label} requires a non-empty command`);
}
if (value.type === 'http' && (typeof value.url !== 'string' || !value.url)) {
throw new Error(`${label} requires a non-empty url`);
}
validateTimeout(value.timeout, label);
if (value.env !== undefined) {
if (!isObject(value.env)
|| Object.values(value.env).some((item) => typeof item !== 'string')) {
throw new Error(`${label} env must map names to strings`);
}
}
return value as GrokHandler;
}
function validateGroup(value: unknown, event: string, groupIndex: number): GrokGroup {
const label = `Grok user hooks group hooks.${event}[${groupIndex}]`;
if (!isObject(value)) throw new Error(`${label} must be an object`);
if (value.matcher !== undefined && typeof value.matcher !== 'string') {
throw new Error(`${label} matcher must be a string`);
}
if (value.matcher !== undefined && MATCHER_REJECTING_EVENTS.has(event)) {
throw new Error(`${label} cannot declare a matcher for ${event}`);
}
if (!Array.isArray(value.hooks)) throw new Error(`${label} must contain a hooks array`);
return {
...value,
hooks: value.hooks.map(
(handler, handlerIndex) => validateHandler(handler, event, groupIndex, handlerIndex),
),
} as GrokGroup;
}
function readHooks(value: unknown): GrokHooks {
if (value === undefined) return {};
if (!isObject(value)) throw new Error('Grok user hooks field "hooks" must be an object');
const hooks: GrokHooks = {};
for (const [event, candidate] of Object.entries(value)) {
if (!Array.isArray(candidate)) {
throw new Error(`Grok user hooks field "hooks.${event}" must be an array`);
}
hooks[event] = candidate.map((group, index) => validateGroup(group, event, index));
}
return hooks;
}
export function parseGrokDocument(filePath: string, raw: string): GrokDocument {
const root = parseStrictJsonObject(raw, `Grok user hooks at ${filePath}`);
return { exists: true, filePath, root, hooks: readHooks(root.hooks), raw };
}
export function createGrokDocument(filePath: string): GrokDocument {
return { exists: false, filePath, root: {}, hooks: {} };
}
export function buildGrokGroup(scriptPath: string): GrokGroup {
return {
hooks: [{
type: 'command',
command: buildGrokCommand(scriptPath),
timeout: HOOK_TIMEOUT_SECONDS,
}],
};
}
function exactManagedGroup(group: GrokGroup): boolean {
return Object.keys(group).length === 1 && Object.hasOwn(group, 'hooks');
}
function exactManagedHandler(handler: GrokHandler): boolean {
return Object.keys(handler).sort().join('|') === 'command|timeout|type'
&& handler.type === 'command'
&& handler.timeout === HOOK_TIMEOUT_SECONDS
&& typeof handler.command === 'string';
}
function managedReference(
handler: GrokHandler,
scriptName: string,
): GrokRuntimeReference | undefined {
if (!exactManagedHandler(handler)) return undefined;
return grokRuntimeReference(handler.command as string, scriptName);
}
function removeFromGroups(
groups: readonly GrokGroup[],
scriptName: string,
agentId?: string,
): GrokGroup[] {
const result: GrokGroup[] = [];
for (const group of groups) {
if (!exactManagedGroup(group)) {
result.push(group);
continue;
}
const handlers = group.hooks.filter((handler) => {
const reference = managedReference(handler, scriptName);
return !reference
|| (agentId !== undefined && !sameGrokAgentId(reference.agentId, agentId));
});
if (handlers.length > 0) result.push({ hooks: handlers });
}
return result;
}
function managedEvent(event: string): readonly [ManagedGrokEvent, string] | undefined {
if (event === 'PreToolUse') return ['PreToolUse', GUARD_SCRIPT];
if (event === 'PostToolUse') return ['PostToolUse', AUDIT_SCRIPT];
if (event === 'PostToolUseFailure') return ['PostToolUseFailure', AUDIT_SCRIPT];
return undefined;
}
export function removeManagedGrokHooks(hooks: GrokHooks, agentId?: string): GrokHooks {
const next: GrokHooks = Object.fromEntries(
Object.entries(hooks).map(([event, groups]) => [event, [...groups]]),
);
for (const [event, scriptName] of [
['PreToolUse', GUARD_SCRIPT],
['PostToolUse', AUDIT_SCRIPT],
['PostToolUseFailure', AUDIT_SCRIPT],
] as const) {
const groups = removeFromGroups(next[event] ?? [], scriptName, agentId);
if (groups.length > 0) next[event] = groups;
else delete next[event];
}
return next;
}
function entirelyManaged(document: GrokDocument): boolean {
if (!document.exists || !Object.keys(document.root).every((key) => key === 'hooks')) return false;
const events = Object.entries(document.hooks);
if (events.length === 0) return false;
let handlerCount = 0;
for (const [event, groups] of events) {
const contract = managedEvent(event);
if (!contract || groups.length === 0) return false;
for (const group of groups) {
if (!exactManagedGroup(group)
|| group.hooks.length === 0
|| group.hooks.some((handler) => !managedReference(handler, contract[1]))) return false;
handlerCount += group.hooks.length;
}
}
return handlerCount > 0;
}
export function renderGrokDocument(
document: GrokDocument,
hooks: GrokHooks,
): RenderedGrokDocument {
if (!document.exists && Object.keys(hooks).length === 0) {
return { document, changed: false };
}
if (Object.keys(hooks).length === 0 && entirelyManaged(document)) {
return { document, changed: true };
}
const root: JsonObject = { ...document.root };
if (Object.keys(hooks).length > 0) root.hooks = hooks;
else delete root.hooks;
const next = `${JSON.stringify(root, null, 2)}\n`;
return { document, changed: next !== document.raw, next };
}
function referencesForEvent(
groups: readonly GrokGroup[],
scriptName: string,
): Map<string, GrokRuntimeReference[]> {
const result = new Map<string, GrokRuntimeReference[]>();
for (const group of groups) {
if (!exactManagedGroup(group)) continue;
for (const handler of group.hooks) {
const reference = managedReference(handler, scriptName);
if (!reference) continue;
const key = process.platform === 'win32'
? reference.agentId.toLowerCase()
: reference.agentId;
const entries = result.get(key) ?? [];
entries.push(reference);
result.set(key, entries);
}
}
return result;
}
export function grokRuntimeContracts(hooks: GrokHooks): GrokRuntimeContract[] {
const guards = referencesForEvent(hooks.PreToolUse ?? [], GUARD_SCRIPT);
const successes = referencesForEvent(hooks.PostToolUse ?? [], AUDIT_SCRIPT);
const failures = referencesForEvent(hooks.PostToolUseFailure ?? [], AUDIT_SCRIPT);
const contracts: GrokRuntimeContract[] = [];
for (const [key, guard] of guards) {
const success = successes.get(key);
const failure = failures.get(key);
if (guard.length !== 1 || success?.length !== 1 || failure?.length !== 1) continue;
contracts.push({
agentId: guard[0].agentId,
guardPath: guard[0].scriptPath,
auditPath: success[0].scriptPath,
});
}
return contracts;
}
+116
View File
@@ -0,0 +1,116 @@
import path from 'node:path';
import type { InstallConfig } from './base.js';
import {
AGENT_KEY,
AUDIT_SCRIPT,
GUARD_SCRIPT,
type RenderedGrokDocument,
} from './grok-contract.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 = 'Grok Build';
const HOOKS_DIRECTORY_LABEL = 'Grok hooks directory';
const HOOKS_LABEL = 'Grok user hooks';
export type GrokRuntimePaths = ManagedRuntimePaths;
export type PreparedGrokInstallation = PreparedManagedInstallation;
export type { RenameFile };
export async function preflightGrokInstallation(
config: InstallConfig,
hooksPath: string,
): Promise<GrokRuntimePaths> {
return preflightManagedInstallation({
agentKey: AGENT_KEY,
hookLocations: [{ directoryLabel: HOOKS_DIRECTORY_LABEL, filePath: hooksPath }],
config,
}, GUARD_SCRIPT, AUDIT_SCRIPT);
}
export async function prepareGrokInstallation(
config: InstallConfig,
rendered: RenderedGrokDocument,
): Promise<PreparedGrokInstallation> {
const hooksSource = rendered.next ?? rendered.document.raw;
if (hooksSource === undefined) throw new Error('Grok hook configuration is missing');
const prepared = await prepareManagedInstallation({
agentKey: AGENT_KEY,
displayName: DISPLAY_NAME,
hookSources: [{
directoryLabel: HOOKS_DIRECTORY_LABEL,
label: HOOKS_LABEL,
filePath: rendered.document.filePath,
expectedSource: rendered.document.raw,
source: hooksSource,
}],
config,
guardOptions: { denyProtocol: 'grok' },
auditOptions: { nativePayload: true },
}, GUARD_SCRIPT, AUDIT_SCRIPT);
const hooksDirectory = path.dirname(rendered.document.filePath);
return {
...prepared,
transaction: {
...prepared.transaction,
directories: [
{ path: path.dirname(hooksDirectory), label: 'Grok home directory' },
...prepared.transaction.directories,
],
},
};
}
export async function commitGrokInstallation(
prepared: PreparedGrokInstallation,
renameFile?: RenameFile,
): Promise<void> {
await commitManagedInstallation(prepared, renameFile);
}
export async function prepareGrokUninstall(
rendered: RenderedGrokDocument,
): Promise<PreparedManagedTransaction> {
const change = rendered.changed
? await prepareManagedFileChange({
filePath: rendered.document.filePath,
label: HOOKS_LABEL,
next: rendered.next,
mode: 0o600,
expectedSource: rendered.document.raw,
verifyExpectedSource: true,
})
: undefined;
return {
displayName: DISPLAY_NAME,
operation: 'uninstall',
directories: rendered.changed
? [
{
path: path.dirname(path.dirname(rendered.document.filePath)),
label: 'Grok home directory',
},
{ path: path.dirname(rendered.document.filePath), label: HOOKS_DIRECTORY_LABEL },
]
: [],
changes: change ? [change] : [],
};
}
export async function commitGrokUninstall(
prepared: PreparedManagedTransaction,
renameFile?: RenameFile,
): Promise<void> {
await commitManagedTransaction(prepared, renameFile);
}
+112
View File
@@ -0,0 +1,112 @@
import os from 'node:os';
import path from 'node:path';
import {
AGENT_KEY,
createGrokDocument,
parseGrokDocument,
type GrokDocument,
type GrokRuntimeContract,
} from './grok-contract.js';
import { sameGrokAgentId, sameGrokPath } from './grok-command.js';
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
import { parseStrictJsonObject, type JsonObject } from './strict-json.js';
const CONFIG_FILE = 'elydora-audit.json';
export function grokConfigPath(): string {
const configured = process.env.GROK_HOME;
const grokHome = configured === undefined || configured === ''
? path.join(os.homedir(), '.grok')
: path.resolve(configured);
return path.join(grokHome, 'hooks', CONFIG_FILE);
}
export async function readGrokDocument(): Promise<GrokDocument> {
const filePath = grokConfigPath();
await inspectPhysicalDirectory(path.dirname(path.dirname(filePath)), 'Grok home directory');
await inspectPhysicalDirectory(path.dirname(filePath), 'Grok hooks directory');
const snapshot = await readPhysicalFile(filePath, 'Grok user hooks');
return snapshot
? parseGrokDocument(filePath, snapshot.contents)
: createGrokDocument(filePath);
}
function requireNonEmptyString(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}`);
}
return value;
}
function validateRuntimeConfig(
config: JsonObject,
contract: GrokRuntimeContract,
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}`);
requireNonEmptyString(config.org_id, 'org_id', configPath);
requireNonEmptyString(config.kid, 'kid', configPath);
const agentId = requireNonEmptyString(config.agent_id, 'agent_id', configPath);
if (!sameGrokAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
throw new Error(`Elydora runtime identity does not match Grok hooks: ${configPath}`);
}
if (config.token !== undefined) requireNonEmptyString(config.token, 'token', configPath);
const rawBaseUrl = requireNonEmptyString(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}`);
}
}
async function runtimeContractExists(contract: GrokRuntimeContract): Promise<boolean> {
const runtimeRoot = path.join(os.homedir(), '.elydora');
const agentDirectory = path.dirname(contract.guardPath);
if (!sameGrokPath(path.dirname(agentDirectory), runtimeRoot)
|| !sameGrokPath(contract.auditPath, path.join(agentDirectory, 'hook.js'))) return false;
if (!await inspectPhysicalDirectory(runtimeRoot, 'Elydora runtime directory')) return false;
if (!await inspectPhysicalDirectory(agentDirectory, 'Elydora agent runtime directory')) return false;
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'),
readPhysicalFile(keyPath, 'Elydora private key'),
readPhysicalFile(contract.guardPath, 'Elydora guard runtime'),
readPhysicalFile(contract.auditPath, 'Elydora audit runtime'),
]);
if (!config || !key || !guard || !audit) return false;
const parsed = parseStrictJsonObject(config.contents, `Elydora runtime config at ${configPath}`);
validateRuntimeConfig(parsed, contract, configPath);
validatePrivateKey(key.contents, keyPath);
return guard.contents.length > 0 && audit.contents.length > 0;
}
export async function grokRuntimeFilesExist(
contracts: readonly GrokRuntimeContract[],
): Promise<boolean> {
for (const contract of contracts) {
if (await runtimeContractExists(contract)) return true;
}
return false;
}
+56 -431
View File
@@ -1,458 +1,83 @@
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 type { AgentPlugin, InstallConfig, PluginStatus } from './base.js';
import {
AGENT_KEY,
buildGrokGroup,
grokRuntimeContracts,
removeManagedGrokHooks,
renderGrokDocument,
type GrokHooks,
} from './grok-contract.js';
import {
commitGrokInstallation,
commitGrokUninstall,
preflightGrokInstallation,
prepareGrokInstallation,
prepareGrokUninstall,
} from './grok-installation.js';
import { grokRuntimeFilesExist, readGrokDocument } from './grok-io.js';
import { SUPPORTED_AGENTS } from './registry.js';
const AGENT_KEY = 'grok';
const GUARD_SCRIPT = 'guard.js';
const AUDIT_SCRIPT = 'hook.js';
const HOOK_TIMEOUT_SECONDS = 10;
const entry = SUPPORTED_AGENTS.get(AGENT_KEY)!;
type JsonObject = Record<string, unknown>;
interface GrokHandler extends JsonObject {
readonly type: 'command' | 'http';
readonly command?: string;
readonly url?: string;
readonly timeout?: number;
}
interface GrokGroup extends JsonObject {
readonly matcher?: string;
readonly hooks: GrokHandler[];
}
type GrokHooks = Record<string, GrokGroup[]>;
interface GrokDocument {
readonly exists: boolean;
readonly configPath: string;
readonly root: JsonObject;
readonly hooks: GrokHooks;
}
interface ParsedArgument {
readonly value: string;
readonly next: number;
}
interface RuntimeContract {
readonly agentId: string;
readonly guardPath: string;
readonly auditPath: string;
}
function isObject(value: unknown): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function hasOwn(value: JsonObject, key: string): boolean {
return Object.prototype.hasOwnProperty.call(value, key);
}
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 resolveConfigPath(): string {
const grokHome = process.env.GROK_HOME || path.join(os.homedir(), '.grok');
return path.join(grokHome, 'hooks', entry.configFile);
}
function quotePosix(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}
function quoteWindows(value: string): string {
return `"${value.replaceAll('"', '\\"')}"`;
}
function buildCommand(scriptPath: string): string {
const quote = process.platform === 'win32' ? quoteWindows : quotePosix;
return `${quote(process.execPath)} ${quote(scriptPath)}`;
}
function buildHandler(scriptPath: string): GrokHandler {
function installedHooks(
hooks: GrokHooks,
guardPath: string,
auditPath: string,
): GrokHooks {
const cleaned = removeManagedGrokHooks(hooks);
return {
type: 'command',
command: buildCommand(scriptPath),
timeout: HOOK_TIMEOUT_SECONDS,
...cleaned,
PreToolUse: [...(cleaned.PreToolUse ?? []), buildGrokGroup(guardPath)],
PostToolUse: [...(cleaned.PostToolUse ?? []), buildGrokGroup(auditPath)],
PostToolUseFailure: [
...(cleaned.PostToolUseFailure ?? []),
buildGrokGroup(auditPath),
],
};
}
function readWindowsArgument(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 += '"';
index += 1;
continue;
}
if (command[index] === '"') return { value, next: index + 1 };
value += command[index];
}
return undefined;
}
const POSIX_APOSTROPHE = `'"'"'`;
function readPosixArgument(command: string, start: number): ParsedArgument | undefined {
if (command[start] !== "'") return undefined;
let value = '';
for (let index = start + 1; index < command.length;) {
if (command.startsWith(POSIX_APOSTROPHE, index)) {
value += "'";
index += POSIX_APOSTROPHE.length;
continue;
}
if (command[index] === "'") return { value, next: index + 1 };
value += command[index];
index += 1;
}
return undefined;
}
function parseGeneratedCommand(command: string): readonly [string, string] | undefined {
const readArgument = process.platform === 'win32' ? readWindowsArgument : readPosixArgument;
const executable = readArgument(command, 0);
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 {
const normalizedLeft = path.resolve(left);
const normalizedRight = path.resolve(right);
return process.platform === 'win32'
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
: normalizedLeft === normalizedRight;
}
function sameAgentId(left: string, right: string): boolean {
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
}
function managedAgentId(handler: GrokHandler, scriptName: string): string | undefined {
if (handler.type !== 'command'
|| handler.timeout !== HOOK_TIMEOUT_SECONDS
|| typeof handler.command !== 'string') return undefined;
const parsed = parseGeneratedCommand(handler.command);
if (!parsed) return undefined;
const scriptPath = parsed[1];
if (path.basename(scriptPath) !== scriptName) return undefined;
const agentDirectory = path.dirname(scriptPath);
const runtimeRoot = path.join(os.homedir(), '.elydora');
if (!samePath(path.dirname(agentDirectory), runtimeRoot)) return undefined;
const agentId = path.basename(agentDirectory);
return agentId && agentId !== '.' && agentId !== '..' ? agentId : undefined;
}
function validateHandler(value: unknown, event: string, groupIndex: number, handlerIndex: number): GrokHandler {
const label = `Grok hooks config handler hooks.${event}[${groupIndex}].hooks[${handlerIndex}]`;
if (!isObject(value)) throw new Error(`${label} must be an object`);
if (value.type !== 'command' && value.type !== 'http') {
throw new Error(`${label} has unsupported type "${String(value.type)}"`);
}
if (value.type === 'command' && (typeof value.command !== 'string' || value.command.length === 0)) {
throw new Error(`${label} requires a non-empty command`);
}
if (value.type === 'http' && (typeof value.url !== 'string' || value.url.length === 0)) {
throw new Error(`${label} requires a non-empty url`);
}
if (value.timeout !== undefined
&& (typeof value.timeout !== 'number' || !Number.isFinite(value.timeout) || value.timeout <= 0)) {
throw new Error(`${label} timeout must be a positive finite number`);
}
return value as GrokHandler;
}
function validateGroup(value: unknown, event: string, groupIndex: number): GrokGroup {
const label = `Grok hooks config group hooks.${event}[${groupIndex}]`;
if (!isObject(value)) throw new Error(`${label} must be an object`);
if (value.matcher !== undefined && typeof value.matcher !== 'string') {
throw new Error(`${label} matcher must be a string`);
}
if (!Array.isArray(value.hooks)) throw new Error(`${label} must contain a hooks array`);
const handlers = value.hooks.map(
(handler, handlerIndex) => validateHandler(handler, event, groupIndex, handlerIndex),
);
return { ...value, hooks: handlers } as GrokGroup;
}
function readHooks(root: JsonObject): GrokHooks {
if (root.hooks === undefined) return {};
if (!isObject(root.hooks)) throw new Error('Grok hooks config field "hooks" must be an object');
const hooks: GrokHooks = {};
for (const [event, value] of Object.entries(root.hooks)) {
if (!Array.isArray(value)) {
throw new Error(`Grok hooks config field "hooks.${event}" must be an array`);
}
hooks[event] = value.map((group, index) => validateGroup(group, event, index));
}
return hooks;
}
async function readConfig(): Promise<GrokDocument> {
const configPath = resolveConfigPath();
let raw: string;
try {
raw = await fsp.readFile(configPath, 'utf-8');
} catch (error) {
if (hasErrorCode(error, 'ENOENT')) return { exists: false, configPath, root: {}, hooks: {} };
throw new Error(`Read Grok hooks config at ${configPath}: ${errorMessage(error)}`, {
cause: asError(error),
});
}
let root: unknown;
try {
root = JSON.parse(raw);
} catch (error) {
throw new Error(`Failed to parse Grok hooks config at ${configPath}: ${errorMessage(error)}`, {
cause: asError(error),
});
}
if (!isObject(root)) throw new Error(`Grok hooks config at ${configPath} must contain a JSON object`);
return { exists: true, configPath, root, hooks: readHooks(root) };
}
function removeManaged(
groups: GrokGroup[],
scriptName: string,
agentId?: string,
): { readonly groups: GrokGroup[]; readonly changed: boolean } {
let changed = false;
const result: GrokGroup[] = [];
for (const group of groups) {
if (hasOwn(group, 'matcher')) {
result.push(group);
continue;
}
let groupChanged = false;
const handlers = group.hooks.filter((handler) => {
const managedId = managedAgentId(handler, scriptName);
const remove = managedId !== undefined
&& (agentId === undefined || sameAgentId(managedId, agentId));
if (remove) {
changed = true;
groupChanged = true;
}
return !remove;
});
if (!groupChanged) result.push(group);
else if (handlers.length > 0) result.push({ ...group, hooks: handlers });
}
return { groups: result, changed };
}
function removeManagedHooks(hooks: GrokHooks, agentId?: string): {
readonly hooks: GrokHooks;
readonly changed: boolean;
} {
const next = { ...hooks };
let changed = false;
for (const [event, scriptName] of [
['PreToolUse', GUARD_SCRIPT],
['PostToolUse', AUDIT_SCRIPT],
] as const) {
const result = removeManaged(next[event] ?? [], scriptName, agentId);
if (!result.changed) continue;
changed = true;
if (result.groups.length > 0) next[event] = result.groups;
else delete next[event];
}
return { hooks: next, changed };
}
async function failWrite(
handle: FileHandle | undefined,
tempPath: string,
configPath: string,
cause: unknown,
): Promise<never> {
const errors = [asError(cause)];
if (handle) {
try {
await handle.close();
} catch (error) {
errors.push(asError(error));
}
}
try {
await fsp.unlink(tempPath);
} catch (error) {
if (!hasErrorCode(error, 'ENOENT')) errors.push(asError(error));
}
const message = `Write Grok hooks config at ${configPath}: ${errorMessage(cause)}`;
if (errors.length > 1) throw new AggregateError(errors, message);
throw new Error(message, { cause: errors[0] });
}
async function writeConfig(configPath: string, root: JsonObject): Promise<void> {
const directory = path.dirname(configPath);
await fsp.mkdir(directory, { recursive: true, mode: 0o700 });
const tempPath = path.join(directory, `.${path.basename(configPath)}.${randomUUID()}.tmp`);
let handle: FileHandle | undefined;
try {
handle = await fsp.open(tempPath, 'wx', 0o600);
await handle.writeFile(JSON.stringify(root, null, 2) + '\n', 'utf-8');
await handle.sync();
await handle.close();
handle = undefined;
await fsp.rename(tempPath, configPath);
} catch (error) {
await failWrite(handle, tempPath, configPath, error);
}
}
async function removeConfig(configPath: string): Promise<void> {
try {
await fsp.unlink(configPath);
} catch (error) {
if (hasErrorCode(error, 'ENOENT')) return;
throw new Error(`Remove Grok hooks config at ${configPath}: ${errorMessage(error)}`, {
cause: asError(error),
});
}
}
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) });
}
}
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 readJsonObject(filePath: string, label: string): Promise<JsonObject | undefined> {
let raw: string;
try {
raw = 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) });
}
let value: unknown;
try {
value = JSON.parse(raw);
} catch (error) {
throw new Error(`Failed to parse ${label} at ${filePath}: ${errorMessage(error)}`, {
cause: asError(error),
});
}
if (!isObject(value)) throw new Error(`${label} at ${filePath} must contain a JSON object`);
return value;
}
function managedIds(groups: GrokGroup[], scriptName: string): Set<string> {
const ids = new Set<string>();
for (const group of groups) {
if (hasOwn(group, 'matcher')) continue;
for (const handler of group.hooks) {
const agentId = managedAgentId(handler, scriptName);
if (agentId) ids.add(agentId);
}
}
return ids;
}
function runtimeContracts(hooks: GrokHooks): RuntimeContract[] {
const guards = managedIds(hooks.PreToolUse ?? [], GUARD_SCRIPT);
const audits = managedIds(hooks.PostToolUse ?? [], AUDIT_SCRIPT);
const root = path.join(os.homedir(), '.elydora');
return [...guards]
.filter((agentId) => audits.has(agentId))
.map((agentId) => ({
agentId,
guardPath: path.join(root, agentId, GUARD_SCRIPT),
auditPath: path.join(root, agentId, AUDIT_SCRIPT),
}));
}
async function runtimeScriptsExist(contracts: RuntimeContract[]): Promise<boolean> {
const root = path.join(os.homedir(), '.elydora');
let entries: Array<{ isDirectory(): boolean; name: string }>;
try {
entries = await fsp.readdir(root, { withFileTypes: true });
} catch (error) {
if (hasErrorCode(error, 'ENOENT')) return false;
throw new Error(`Read Elydora runtime directory at ${root}: ${errorMessage(error)}`, {
cause: asError(error),
});
}
for (const contract of contracts) {
if (!entries.some((item) => item.isDirectory() && sameAgentId(item.name, contract.agentId))) continue;
const runtimeConfigPath = path.join(root, contract.agentId, 'config.json');
const runtimeConfig = await readJsonObject(runtimeConfigPath, 'Elydora runtime config');
if (!runtimeConfig || runtimeConfig.agent_name !== AGENT_KEY) continue;
const [guardExists, auditExists] = await Promise.all([
regularFileExists(contract.guardPath, 'Elydora guard runtime'),
regularFileExists(contract.auditPath, 'Elydora audit runtime'),
]);
if (guardExists && auditExists) return true;
}
return false;
}
export const grokPlugin: AgentPlugin = {
managesRuntime: true,
async preflightInstall(config: InstallConfig): Promise<void> {
const document = await readGrokDocument();
await preflightGrokInstallation(config, document.filePath);
},
async install(config: InstallConfig): Promise<void> {
if (!config.agentId) throw new Error('agentId is required');
const document = await readConfig();
await requireRuntime(config.guardScriptPath, 'Elydora guard runtime');
await requireRuntime(config.hookScriptPath, 'Elydora audit runtime');
const cleaned = removeManagedHooks(document.hooks).hooks;
const hooks: GrokHooks = {
...cleaned,
PreToolUse: [...(cleaned.PreToolUse ?? []), { hooks: [buildHandler(config.guardScriptPath)] }],
PostToolUse: [...(cleaned.PostToolUse ?? []), { hooks: [buildHandler(config.hookScriptPath)] }],
};
await writeConfig(document.configPath, { ...document.root, hooks });
console.log(' Grok Build: global PreToolUse and PostToolUse hooks installed.');
const document = await readGrokDocument();
const paths = await preflightGrokInstallation(config, document.filePath);
const rendered = renderGrokDocument(
document,
installedHooks(document.hooks, paths.guardPath, paths.auditPath),
);
await commitGrokInstallation(await prepareGrokInstallation(config, rendered));
console.log(
' Grok Build: global PreToolUse, PostToolUse, and PostToolUseFailure hooks installed.',
);
},
async uninstall(agentId?: string): Promise<void> {
const document = await readConfig();
if (!document.exists) return;
const result = removeManagedHooks(document.hooks, agentId);
if (!result.changed) return;
const root = { ...document.root };
if (Object.keys(result.hooks).length > 0) root.hooks = result.hooks;
else delete root.hooks;
if (Object.keys(root).length === 0) await removeConfig(document.configPath);
else await writeConfig(document.configPath, root);
const document = await readGrokDocument();
const rendered = renderGrokDocument(
document,
removeManagedGrokHooks(document.hooks, agentId),
);
await commitGrokUninstall(await prepareGrokUninstall(rendered));
},
async status(): Promise<PluginStatus> {
const document = await readConfig();
const contracts = runtimeContracts(document.hooks);
const document = await readGrokDocument();
const contracts = grokRuntimeContracts(document.hooks);
const hookConfigured = contracts.length > 0;
const hookScriptExists = hookConfigured ? await runtimeScriptsExist(contracts) : false;
const hookScriptExists = hookConfigured && await grokRuntimeFilesExist(contracts);
return {
installed: hookConfigured && hookScriptExists,
agentName: AGENT_KEY,
displayName: entry.name,
hookConfigured,
hookScriptExists,
configPath: document.configPath,
configPath: document.filePath,
};
},
};
+6 -1
View File
@@ -3,6 +3,7 @@ import { PROTECTED_RUNTIME_READER } from './runtime-reader-template.js';
export interface GuardScriptOptions {
readonly failClosed?: boolean;
readonly successOutput?: string;
readonly denyProtocol?: 'cursor' | 'grok';
}
export function generateGuardScript(
@@ -12,6 +13,7 @@ export function generateGuardScript(
): string {
const failClosed = options.failClosed ?? false;
const successOutput = options.successOutput ?? '';
const denyProtocol = options.denyProtocol ?? '';
return `#!/usr/bin/env node
'use strict';
@@ -25,6 +27,7 @@ const AGENT_NAME = ${JSON.stringify(agentName)};
const AGENT_ID = ${JSON.stringify(agentId)};
const SUCCESS_OUTPUT = ${JSON.stringify(successOutput)};
const FAIL_CLOSED = ${JSON.stringify(failClosed)};
const DENY_PROTOCOL = ${JSON.stringify(denyProtocol)};
const ELYDORA_DIR = path.join(os.homedir(), '.elydora');
const CONFIG_PATH = path.join(ELYDORA_DIR, AGENT_ID, 'config.json');
const STATUS_CACHE_PATH = path.join(ELYDORA_DIR, AGENT_ID, 'status-cache.json');
@@ -42,12 +45,14 @@ function validateStatus(value, source) {
function blockAgent(status) {
const state = status === 'frozen' ? 'frozen' : 'revoked';
const message = 'Agent "' + AGENT_NAME + '" is ' + state + ' in Elydora.';
if (SUCCESS_OUTPUT) {
if (DENY_PROTOCOL === 'cursor') {
process.stdout.write(JSON.stringify({
permission: 'deny',
userMessage: message,
agentMessage: message + ' Tool execution is blocked.',
}) + '\\n');
} else if (DENY_PROTOCOL === 'grok') {
process.stdout.write(JSON.stringify({ decision: 'deny', reason: message }) + '\\n');
}
process.stderr.write('[Elydora guard] ' + message + ' Tool execution blocked.\\n');
process.exitCode = 2;