fix(node): mirror official Gemini hooks
This commit is contained in:
1 parent
48a830ff4d
commit
2d8111d823
15 files changed
+1999
-144
No files matched your search
@@ -0,0 +1,164 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
interface ParsedArgument {
|
||||
readonly value: string;
|
||||
readonly next: number;
|
||||
}
|
||||
|
||||
export interface GeminiRuntimeReference {
|
||||
readonly agentId: string;
|
||||
readonly scriptPath: string;
|
||||
}
|
||||
|
||||
export function sameGeminiPath(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 sameGeminiAgentId(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.env.SystemRoot;
|
||||
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 `& ${quotePowerShell(windowsPowerShellPath())} -NoLogo -NoProfile -NonInteractive -EncodedCommand ${encoded}`;
|
||||
}
|
||||
|
||||
export function buildGeminiCommand(scriptPath: string): string {
|
||||
if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) {
|
||||
throw new Error('Gemini CLI 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 {
|
||||
if (!command.startsWith('& ')) return undefined;
|
||||
const powershell = readPowerShellArgument(command, 2);
|
||||
if (!powershell
|
||||
|| !path.win32.isAbsolute(powershell.value)
|
||||
|| path.win32.basename(powershell.value).toLowerCase() !== 'powershell.exe') return undefined;
|
||||
const prefix = ' -NoLogo -NoProfile -NonInteractive -EncodedCommand ';
|
||||
if (!command.startsWith(prefix, powershell.next)) return undefined;
|
||||
const encoded = command.slice(powershell.next + prefix.length);
|
||||
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) return undefined;
|
||||
const buffer = Buffer.from(encoded, 'base64');
|
||||
if (buffer.length % 2 !== 0 || buffer.toString('base64') !== encoded) return undefined;
|
||||
return parsePowerShellSource(buffer.toString('utf16le'));
|
||||
}
|
||||
|
||||
function parseLegacyCommand(command: string): readonly [string, string] | undefined {
|
||||
const match = /^node "([^"\r\n]+)"$/.exec(command);
|
||||
return match ? ['node', match[1]] : undefined;
|
||||
}
|
||||
|
||||
function isNodeExecutable(filePath: string): boolean {
|
||||
const basename = path.basename(filePath).toLowerCase();
|
||||
return basename === 'node' || basename === 'node.exe';
|
||||
}
|
||||
|
||||
export function geminiRuntimeReference(
|
||||
command: string,
|
||||
scriptName: string,
|
||||
includeLegacy = false,
|
||||
): GeminiRuntimeReference | undefined {
|
||||
const parsed = parsePosixCommand(command)
|
||||
?? parseWindowsCommand(command)
|
||||
?? (includeLegacy ? parseLegacyCommand(command) : undefined);
|
||||
if (!parsed
|
||||
|| !isNodeExecutable(parsed[0])
|
||||
|| !path.isAbsolute(parsed[1])
|
||||
|| path.basename(parsed[1]) !== scriptName) return undefined;
|
||||
if (parsed[0] !== 'node' && !path.isAbsolute(parsed[0])) return undefined;
|
||||
const agentDirectory = path.dirname(parsed[1]);
|
||||
if (!sameGeminiPath(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] };
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
import {
|
||||
applyEdits,
|
||||
modify,
|
||||
parse,
|
||||
parseTree,
|
||||
printParseErrorCode,
|
||||
type FormattingOptions,
|
||||
type JSONPath,
|
||||
type Node,
|
||||
type ParseError,
|
||||
} from 'jsonc-parser';
|
||||
import {
|
||||
MANAGED_EVENTS,
|
||||
managedGeminiRemovals,
|
||||
readGeminiHookControls,
|
||||
readGeminiHooks,
|
||||
type GeminiGroup,
|
||||
type GeminiHookControls,
|
||||
type GeminiHooks,
|
||||
type ManagedGeminiEvent,
|
||||
} from './gemini-contract.js';
|
||||
import { isObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
export const GEMINI_OWNED_FILE_MARKER = '// Managed by Elydora';
|
||||
|
||||
export interface GeminiDocument {
|
||||
readonly filePath: string;
|
||||
readonly exists: boolean;
|
||||
readonly raw: string;
|
||||
readonly root: JsonObject;
|
||||
readonly hooks: GeminiHooks;
|
||||
readonly hookControls: GeminiHookControls;
|
||||
readonly hasHooksContainer: boolean;
|
||||
readonly ownedFile: boolean;
|
||||
}
|
||||
|
||||
export interface RenderedGeminiDocument {
|
||||
readonly document: GeminiDocument;
|
||||
readonly changed: boolean;
|
||||
readonly next?: string;
|
||||
}
|
||||
|
||||
interface DocumentOptions {
|
||||
readonly exists: boolean;
|
||||
readonly filePath: string;
|
||||
readonly raw: string;
|
||||
}
|
||||
|
||||
function rejectDuplicateKeys(
|
||||
node: Node | undefined,
|
||||
label: string,
|
||||
location: 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 childLocation = [...location, key];
|
||||
if (keys.has(key)) {
|
||||
throw new Error(`${label} contains duplicate field "${childLocation.join('.')}"`);
|
||||
}
|
||||
keys.add(key);
|
||||
rejectDuplicateKeys(property.children?.[1], label, childLocation);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (node.type === 'array') {
|
||||
for (const child of node.children ?? []) rejectDuplicateKeys(child, label, location);
|
||||
}
|
||||
}
|
||||
|
||||
function parseJsoncObject(raw: string, label: string): JsonObject {
|
||||
const errors: ParseError[] = [];
|
||||
const value: unknown = parse(raw, errors, {
|
||||
allowTrailingComma: false,
|
||||
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: false,
|
||||
disallowComments: false,
|
||||
}), label);
|
||||
return value;
|
||||
}
|
||||
|
||||
export function parseGeminiDocument(options: DocumentOptions): GeminiDocument {
|
||||
const label = `Gemini CLI user settings at ${options.filePath}`;
|
||||
const root = parseJsoncObject(options.raw, label);
|
||||
const hasHooksContainer = Object.hasOwn(root, 'hooks');
|
||||
return {
|
||||
...options,
|
||||
root,
|
||||
hooks: readGeminiHooks(root.hooks),
|
||||
hookControls: readGeminiHookControls(root.hooksConfig),
|
||||
hasHooksContainer,
|
||||
ownedFile: options.raw.startsWith(GEMINI_OWNED_FILE_MARKER),
|
||||
};
|
||||
}
|
||||
|
||||
export function createGeminiDocument(filePath: string): GeminiDocument {
|
||||
return parseGeminiDocument({
|
||||
exists: false,
|
||||
filePath,
|
||||
raw: `${GEMINI_OWNED_FILE_MARKER}\n{}\n`,
|
||||
});
|
||||
}
|
||||
|
||||
function formatting(raw: string): FormattingOptions {
|
||||
const indentation = /\r?\n([ \t]+)\S/.exec(raw)?.[1];
|
||||
const insertSpaces = !indentation?.includes('\t');
|
||||
return {
|
||||
eol: raw.includes('\r\n') ? '\r\n' : '\n',
|
||||
insertSpaces,
|
||||
tabSize: insertSpaces ? Math.max(1, indentation?.length ?? 2) : 1,
|
||||
};
|
||||
}
|
||||
|
||||
function change(
|
||||
raw: string,
|
||||
jsonPath: JSONPath,
|
||||
value: unknown,
|
||||
isArrayInsertion = false,
|
||||
): string {
|
||||
return applyEdits(raw, modify(raw, jsonPath, value, {
|
||||
formattingOptions: formatting(raw),
|
||||
isArrayInsertion,
|
||||
}));
|
||||
}
|
||||
|
||||
function currentDocument(document: GeminiDocument, raw: string): GeminiDocument {
|
||||
return parseGeminiDocument({
|
||||
exists: document.exists,
|
||||
filePath: document.filePath,
|
||||
raw,
|
||||
});
|
||||
}
|
||||
|
||||
function removeManagedEntries(
|
||||
document: GeminiDocument,
|
||||
raw: string,
|
||||
agentId?: string,
|
||||
): string {
|
||||
const removals = managedGeminiRemovals(document.hooks, agentId);
|
||||
for (const event of MANAGED_EVENTS) {
|
||||
const eventRemovals = removals
|
||||
.filter((removal) => removal.event === event)
|
||||
.sort((left, right) => right.groupIndex - left.groupIndex);
|
||||
for (const removal of eventRemovals) {
|
||||
const groupPath: JSONPath = ['hooks', event, removal.groupIndex];
|
||||
if (removal.removeGroup) {
|
||||
raw = change(raw, groupPath, undefined);
|
||||
continue;
|
||||
}
|
||||
for (const handlerIndex of [...removal.handlerIndexes].sort(
|
||||
(left, right) => right - left,
|
||||
)) {
|
||||
raw = change(raw, [...groupPath, 'hooks', handlerIndex], undefined);
|
||||
}
|
||||
}
|
||||
if (eventRemovals.length > 0) {
|
||||
const current = currentDocument(document, raw);
|
||||
if ((current.hooks[event] ?? []).length === 0) {
|
||||
raw = change(raw, ['hooks', event], undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
const current = currentDocument(document, raw);
|
||||
if (current.hasHooksContainer && Object.keys(current.hooks).length === 0) {
|
||||
raw = change(raw, ['hooks'], undefined);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function appendGroup(
|
||||
document: GeminiDocument,
|
||||
raw: string,
|
||||
event: ManagedGeminiEvent,
|
||||
group: GeminiGroup,
|
||||
): string {
|
||||
const current = currentDocument(document, raw);
|
||||
if (current.hooks[event]) {
|
||||
return change(raw, ['hooks', event, current.hooks[event].length], group, true);
|
||||
}
|
||||
return change(raw, ['hooks', event], [group]);
|
||||
}
|
||||
|
||||
export function renderGeminiDocument(
|
||||
document: GeminiDocument,
|
||||
agentId: string | undefined,
|
||||
additions: ReadonlyMap<ManagedGeminiEvent, GeminiGroup>,
|
||||
): RenderedGeminiDocument {
|
||||
let raw = removeManagedEntries(document, document.raw, agentId);
|
||||
for (const event of MANAGED_EVENTS) {
|
||||
const group = additions.get(event);
|
||||
if (group) raw = appendGroup(document, raw, event, group);
|
||||
}
|
||||
const current = currentDocument(document, raw);
|
||||
if (additions.size === 0
|
||||
&& document.ownedFile
|
||||
&& Object.keys(current.root).length === 0) {
|
||||
return { document, changed: true, next: undefined };
|
||||
}
|
||||
return { document, changed: raw !== document.raw, next: raw };
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
import {
|
||||
buildGeminiCommand,
|
||||
geminiRuntimeReference,
|
||||
sameGeminiAgentId,
|
||||
type GeminiRuntimeReference,
|
||||
} from './gemini-command.js';
|
||||
import { isObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
export const AGENT_KEY = 'gemini';
|
||||
export const CONFIG_FILE = 'settings.json';
|
||||
export const GUARD_SCRIPT = 'guard.js';
|
||||
export const AUDIT_SCRIPT = 'hook.js';
|
||||
export const GUARD_HOOK_NAME = 'elydora-guard';
|
||||
export const AUDIT_HOOK_NAME = 'elydora-audit';
|
||||
export const HOOK_TIMEOUT_MS = 10_000;
|
||||
export const MANAGED_EVENTS = ['BeforeTool', 'AfterTool'] as const;
|
||||
|
||||
const KNOWN_EVENTS = new Set([
|
||||
'BeforeTool',
|
||||
'AfterTool',
|
||||
'BeforeAgent',
|
||||
'Notification',
|
||||
'AfterAgent',
|
||||
'SessionStart',
|
||||
'SessionEnd',
|
||||
'PreCompress',
|
||||
'BeforeModel',
|
||||
'AfterModel',
|
||||
'BeforeToolSelection',
|
||||
]);
|
||||
|
||||
export type ManagedGeminiEvent = (typeof MANAGED_EVENTS)[number];
|
||||
|
||||
export interface GeminiHandler extends JsonObject {
|
||||
readonly type: 'command';
|
||||
readonly command?: string;
|
||||
readonly name?: string;
|
||||
readonly timeout?: number;
|
||||
}
|
||||
|
||||
export interface GeminiGroup extends JsonObject {
|
||||
readonly matcher?: string;
|
||||
readonly sequential?: boolean;
|
||||
readonly hooks: GeminiHandler[];
|
||||
}
|
||||
|
||||
export type GeminiHooks = Record<string, GeminiGroup[]>;
|
||||
|
||||
export interface GeminiHookControls {
|
||||
readonly enabled: boolean;
|
||||
readonly disabled: readonly string[];
|
||||
}
|
||||
|
||||
export interface GeminiRuntimeContract {
|
||||
readonly agentId: string;
|
||||
readonly guardPath: string;
|
||||
readonly auditPath: string;
|
||||
}
|
||||
|
||||
export interface ManagedRemoval {
|
||||
readonly event: ManagedGeminiEvent;
|
||||
readonly groupIndex: number;
|
||||
readonly handlerIndexes: readonly number[];
|
||||
readonly removeGroup: boolean;
|
||||
}
|
||||
|
||||
function optionalString(value: JsonObject, field: string, label: string): void {
|
||||
if (value[field] !== undefined && typeof value[field] !== 'string') {
|
||||
throw new Error(`${label} field "${field}" must be a string`);
|
||||
}
|
||||
}
|
||||
|
||||
function validateTimeout(value: unknown, label: string): void {
|
||||
if (value === undefined) return;
|
||||
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
|
||||
throw new Error(`${label} timeout must be a non-negative finite number`);
|
||||
}
|
||||
}
|
||||
|
||||
function validateEnvironment(value: unknown, label: string): void {
|
||||
if (value === undefined) return;
|
||||
if (!isObject(value)
|
||||
|| Object.values(value).some((entry) => typeof entry !== 'string')) {
|
||||
throw new Error(`${label} env must map names to strings`);
|
||||
}
|
||||
}
|
||||
|
||||
function validateHandler(
|
||||
value: unknown,
|
||||
event: string,
|
||||
groupIndex: number,
|
||||
handlerIndex: number,
|
||||
): GeminiHandler {
|
||||
const label = `Gemini CLI settings handler hooks.${event}[${groupIndex}].hooks[${handlerIndex}]`;
|
||||
if (!isObject(value)) throw new Error(`${label} must be an object`);
|
||||
if (value.type !== 'command') {
|
||||
throw new Error(`${label} has unsupported type "${String(value.type)}"`);
|
||||
}
|
||||
optionalString(value, 'name', label);
|
||||
optionalString(value, 'description', label);
|
||||
optionalString(value, 'source', label);
|
||||
validateTimeout(value.timeout, label);
|
||||
validateEnvironment(value.env, label);
|
||||
if (typeof value.command !== 'string' || value.command.length === 0) {
|
||||
throw new Error(`${label} requires a non-empty command`);
|
||||
}
|
||||
return value as GeminiHandler;
|
||||
}
|
||||
|
||||
function validateGroup(value: unknown, event: string, groupIndex: number): GeminiGroup {
|
||||
const label = `Gemini CLI settings 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.sequential !== undefined && typeof value.sequential !== 'boolean') {
|
||||
throw new Error(`${label} sequential must be a boolean`);
|
||||
}
|
||||
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 GeminiGroup;
|
||||
}
|
||||
|
||||
export function readGeminiHooks(value: unknown): GeminiHooks {
|
||||
if (value === undefined) return {};
|
||||
if (!isObject(value)) throw new Error('Gemini CLI settings field "hooks" must be an object');
|
||||
const hooks: GeminiHooks = {};
|
||||
for (const [event, groups] of Object.entries(value)) {
|
||||
if (!Array.isArray(groups)) {
|
||||
throw new Error(`Gemini CLI settings field "hooks.${event}" must be an array`);
|
||||
}
|
||||
hooks[event] = KNOWN_EVENTS.has(event)
|
||||
? groups.map((group, index) => validateGroup(group, event, index))
|
||||
: groups as GeminiGroup[];
|
||||
}
|
||||
return hooks;
|
||||
}
|
||||
|
||||
export function readGeminiHookControls(value: unknown): GeminiHookControls {
|
||||
if (value === undefined) return { enabled: true, disabled: [] };
|
||||
if (!isObject(value)) {
|
||||
throw new Error('Gemini CLI settings field "hooksConfig" must be an object');
|
||||
}
|
||||
const supported = new Set(['enabled', 'disabled', 'notifications']);
|
||||
const extra = Object.keys(value).find((field) => !supported.has(field));
|
||||
if (extra) {
|
||||
throw new Error(`Gemini CLI settings field "hooksConfig" contains unsupported field "${extra}"`);
|
||||
}
|
||||
if (value.enabled !== undefined && typeof value.enabled !== 'boolean') {
|
||||
throw new Error('Gemini CLI settings field "hooksConfig.enabled" must be a boolean');
|
||||
}
|
||||
if (value.notifications !== undefined && typeof value.notifications !== 'boolean') {
|
||||
throw new Error('Gemini CLI settings field "hooksConfig.notifications" must be a boolean');
|
||||
}
|
||||
if (value.disabled !== undefined && (
|
||||
!Array.isArray(value.disabled)
|
||||
|| value.disabled.some((item) => typeof item !== 'string')
|
||||
)) {
|
||||
throw new Error('Gemini CLI settings field "hooksConfig.disabled" must be an array of strings');
|
||||
}
|
||||
return {
|
||||
enabled: value.enabled !== false,
|
||||
disabled: value.disabled === undefined ? [] : value.disabled as string[],
|
||||
};
|
||||
}
|
||||
|
||||
export function managedGeminiHooksEnabled(controls: GeminiHookControls): boolean {
|
||||
return controls.enabled
|
||||
&& !controls.disabled.includes(GUARD_HOOK_NAME)
|
||||
&& !controls.disabled.includes(AUDIT_HOOK_NAME);
|
||||
}
|
||||
|
||||
export function disabledManagedGeminiEntries(
|
||||
controls: GeminiHookControls,
|
||||
): readonly string[] {
|
||||
return controls.disabled.filter((entry) => (
|
||||
entry === GUARD_HOOK_NAME
|
||||
|| entry === AUDIT_HOOK_NAME
|
||||
|| geminiRuntimeReference(entry, GUARD_SCRIPT, true) !== undefined
|
||||
|| geminiRuntimeReference(entry, AUDIT_SCRIPT, true) !== undefined
|
||||
));
|
||||
}
|
||||
|
||||
export function buildGeminiGroup(scriptPath: string, name: string): GeminiGroup {
|
||||
return {
|
||||
hooks: [{
|
||||
type: 'command',
|
||||
name,
|
||||
command: buildGeminiCommand(scriptPath),
|
||||
timeout: HOOK_TIMEOUT_MS,
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
function exactManagedGroup(group: GeminiGroup): boolean {
|
||||
return Object.keys(group).length === 1 && Object.hasOwn(group, 'hooks');
|
||||
}
|
||||
|
||||
function currentManagedReference(
|
||||
handler: GeminiHandler,
|
||||
scriptName: string,
|
||||
hookName: string,
|
||||
): GeminiRuntimeReference | undefined {
|
||||
return Object.keys(handler).sort().join('|') === 'command|name|timeout|type'
|
||||
&& handler.type === 'command'
|
||||
&& handler.name === hookName
|
||||
&& handler.timeout === HOOK_TIMEOUT_MS
|
||||
&& typeof handler.command === 'string'
|
||||
? geminiRuntimeReference(handler.command, scriptName)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function legacyManagedReference(
|
||||
handler: GeminiHandler,
|
||||
scriptName: string,
|
||||
): GeminiRuntimeReference | undefined {
|
||||
return Object.keys(handler).sort().join('|') === 'command|type'
|
||||
&& handler.type === 'command'
|
||||
&& typeof handler.command === 'string'
|
||||
? geminiRuntimeReference(handler.command, scriptName, true)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function managedReference(
|
||||
handler: GeminiHandler,
|
||||
scriptName: string,
|
||||
hookName: string,
|
||||
includeLegacy: boolean,
|
||||
): GeminiRuntimeReference | undefined {
|
||||
return currentManagedReference(handler, scriptName, hookName)
|
||||
?? (includeLegacy ? legacyManagedReference(handler, scriptName) : undefined);
|
||||
}
|
||||
|
||||
export function managedGeminiRemovals(
|
||||
hooks: GeminiHooks,
|
||||
agentId?: string,
|
||||
): ManagedRemoval[] {
|
||||
const removals: ManagedRemoval[] = [];
|
||||
for (const [event, scriptName, hookName] of [
|
||||
['BeforeTool', GUARD_SCRIPT, GUARD_HOOK_NAME],
|
||||
['AfterTool', AUDIT_SCRIPT, AUDIT_HOOK_NAME],
|
||||
] as const) {
|
||||
(hooks[event] ?? []).forEach((group, groupIndex) => {
|
||||
const handlerIndexes = group.hooks.flatMap((handler, handlerIndex) => {
|
||||
const reference = managedReference(handler, scriptName, hookName, true);
|
||||
return reference
|
||||
&& (agentId === undefined || sameGeminiAgentId(reference.agentId, agentId))
|
||||
? [handlerIndex]
|
||||
: [];
|
||||
});
|
||||
if (handlerIndexes.length > 0) {
|
||||
removals.push({
|
||||
event,
|
||||
groupIndex,
|
||||
handlerIndexes,
|
||||
removeGroup: exactManagedGroup(group) && handlerIndexes.length === group.hooks.length,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
return removals;
|
||||
}
|
||||
|
||||
function referencesForEvent(
|
||||
groups: readonly GeminiGroup[],
|
||||
scriptName: string,
|
||||
hookName: string,
|
||||
): Map<string, GeminiRuntimeReference[]> {
|
||||
const references = new Map<string, GeminiRuntimeReference[]>();
|
||||
for (const group of groups) {
|
||||
if (!exactManagedGroup(group)) continue;
|
||||
for (const handler of group.hooks) {
|
||||
const reference = currentManagedReference(handler, scriptName, hookName);
|
||||
if (!reference) continue;
|
||||
const key = process.platform === 'win32'
|
||||
? reference.agentId.toLowerCase()
|
||||
: reference.agentId;
|
||||
references.set(key, [...(references.get(key) ?? []), reference]);
|
||||
}
|
||||
}
|
||||
return references;
|
||||
}
|
||||
|
||||
export function geminiRuntimeContracts(hooks: GeminiHooks): GeminiRuntimeContract[] {
|
||||
const guards = referencesForEvent(hooks.BeforeTool ?? [], GUARD_SCRIPT, GUARD_HOOK_NAME);
|
||||
const audits = referencesForEvent(hooks.AfterTool ?? [], AUDIT_SCRIPT, AUDIT_HOOK_NAME);
|
||||
const contracts: GeminiRuntimeContract[] = [];
|
||||
for (const [key, guard] of guards) {
|
||||
const audit = audits.get(key);
|
||||
if (guard.length !== 1 || audit?.length !== 1) continue;
|
||||
contracts.push({
|
||||
agentId: guard[0].agentId,
|
||||
guardPath: guard[0].scriptPath,
|
||||
auditPath: audit[0].scriptPath,
|
||||
});
|
||||
}
|
||||
return contracts;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { InstallConfig } from './base.js';
|
||||
import {
|
||||
AGENT_KEY,
|
||||
AUDIT_SCRIPT,
|
||||
GUARD_SCRIPT,
|
||||
} from './gemini-contract.js';
|
||||
import type { RenderedGeminiDocument } from './gemini-config.js';
|
||||
import {
|
||||
commitManagedInstallation,
|
||||
preflightManagedInstallation,
|
||||
prepareManagedInstallation,
|
||||
type ManagedRuntimePaths,
|
||||
type PreparedManagedInstallation,
|
||||
type RenameFile,
|
||||
} from './managed-installation.js';
|
||||
|
||||
const DISPLAY_NAME = 'Gemini CLI';
|
||||
const SETTINGS_DIRECTORY_LABEL = 'Gemini CLI configuration directory';
|
||||
const SETTINGS_LABEL = 'Gemini CLI user settings';
|
||||
|
||||
export type GeminiRuntimePaths = ManagedRuntimePaths;
|
||||
export type PreparedGeminiInstallation = PreparedManagedInstallation;
|
||||
export type { RenameFile };
|
||||
|
||||
export async function preflightGeminiInstallation(
|
||||
config: InstallConfig,
|
||||
settingsPath: string,
|
||||
): Promise<GeminiRuntimePaths> {
|
||||
return preflightManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
hookLocations: [{ directoryLabel: SETTINGS_DIRECTORY_LABEL, filePath: settingsPath }],
|
||||
config,
|
||||
}, GUARD_SCRIPT, AUDIT_SCRIPT);
|
||||
}
|
||||
|
||||
export async function prepareGeminiInstallation(
|
||||
config: InstallConfig,
|
||||
rendered: RenderedGeminiDocument,
|
||||
): Promise<PreparedGeminiInstallation> {
|
||||
const settingsSource = rendered.next ?? rendered.document.raw;
|
||||
if (settingsSource === undefined) throw new Error('Gemini CLI hook settings are missing');
|
||||
return prepareManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
displayName: DISPLAY_NAME,
|
||||
hookSources: [{
|
||||
directoryLabel: SETTINGS_DIRECTORY_LABEL,
|
||||
label: SETTINGS_LABEL,
|
||||
filePath: rendered.document.filePath,
|
||||
expectedSource: rendered.document.exists ? rendered.document.raw : undefined,
|
||||
source: settingsSource,
|
||||
}],
|
||||
config,
|
||||
guardOptions: { successOutput: '{}\n' },
|
||||
auditOptions: { nativePayload: true, successOutput: '{}\n' },
|
||||
}, GUARD_SCRIPT, AUDIT_SCRIPT);
|
||||
}
|
||||
|
||||
export async function commitGeminiInstallation(
|
||||
prepared: PreparedGeminiInstallation,
|
||||
renameFile?: RenameFile,
|
||||
): Promise<void> {
|
||||
await commitManagedInstallation(prepared, renameFile);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
AGENT_KEY,
|
||||
CONFIG_FILE,
|
||||
type GeminiRuntimeContract,
|
||||
} from './gemini-contract.js';
|
||||
import {
|
||||
createGeminiDocument,
|
||||
parseGeminiDocument,
|
||||
type GeminiDocument,
|
||||
type RenderedGeminiDocument,
|
||||
} from './gemini-config.js';
|
||||
import { sameGeminiAgentId, sameGeminiPath } from './gemini-command.js';
|
||||
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
|
||||
import {
|
||||
commitManagedTransaction,
|
||||
prepareManagedFileChange,
|
||||
} from './managed-transaction.js';
|
||||
import { parseStrictJsonObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
export function geminiConfigurationDirectory(): string {
|
||||
const configuredHome = process.env.GEMINI_CLI_HOME;
|
||||
const home = configuredHome ? configuredHome : os.homedir();
|
||||
return path.join(home, '.gemini');
|
||||
}
|
||||
|
||||
export function geminiSettingsPath(): string {
|
||||
return path.join(geminiConfigurationDirectory(), CONFIG_FILE);
|
||||
}
|
||||
|
||||
export async function readGeminiDocument(): Promise<GeminiDocument> {
|
||||
const filePath = geminiSettingsPath();
|
||||
await inspectPhysicalDirectory(path.dirname(filePath), 'Gemini CLI configuration directory');
|
||||
const snapshot = await readPhysicalFile(filePath, 'Gemini CLI user settings');
|
||||
return snapshot
|
||||
? parseGeminiDocument({
|
||||
exists: true,
|
||||
filePath,
|
||||
raw: snapshot.contents,
|
||||
})
|
||||
: createGeminiDocument(filePath);
|
||||
}
|
||||
|
||||
export async function writeGeminiDocument(rendered: RenderedGeminiDocument): Promise<void> {
|
||||
if (!rendered.changed) return;
|
||||
const change = await prepareManagedFileChange({
|
||||
filePath: rendered.document.filePath,
|
||||
label: 'Gemini CLI user settings',
|
||||
next: rendered.next,
|
||||
mode: 0o600,
|
||||
expectedSource: rendered.document.exists ? rendered.document.raw : undefined,
|
||||
verifyExpectedSource: true,
|
||||
});
|
||||
if (!change) return;
|
||||
await commitManagedTransaction({
|
||||
displayName: 'Gemini CLI',
|
||||
operation: 'uninstall',
|
||||
directories: [{
|
||||
path: path.dirname(rendered.document.filePath),
|
||||
label: 'Gemini CLI configuration directory',
|
||||
}],
|
||||
changes: [change],
|
||||
});
|
||||
}
|
||||
|
||||
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: GeminiRuntimeContract,
|
||||
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 (!sameGeminiAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
|
||||
throw new Error(`Elydora runtime identity does not match Gemini CLI 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: GeminiRuntimeContract): Promise<boolean> {
|
||||
const runtimeRoot = path.join(os.homedir(), '.elydora');
|
||||
const agentDirectory = path.dirname(contract.guardPath);
|
||||
if (!sameGeminiPath(path.dirname(agentDirectory), runtimeRoot)
|
||||
|| !sameGeminiPath(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 geminiRuntimeFilesExist(
|
||||
contracts: readonly GeminiRuntimeContract[],
|
||||
): Promise<boolean> {
|
||||
for (const contract of contracts) {
|
||||
if (await runtimeContractExists(contract)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
+68
-142
@@ -1,169 +1,95 @@
|
||||
import fsp from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import type { AgentPlugin, InstallConfig, PluginStatus } from './base.js';
|
||||
import {
|
||||
AGENT_KEY,
|
||||
AUDIT_HOOK_NAME,
|
||||
GUARD_HOOK_NAME,
|
||||
buildGeminiGroup,
|
||||
disabledManagedGeminiEntries,
|
||||
geminiRuntimeContracts,
|
||||
managedGeminiHooksEnabled,
|
||||
type GeminiGroup,
|
||||
type ManagedGeminiEvent,
|
||||
} from './gemini-contract.js';
|
||||
import { renderGeminiDocument, type GeminiDocument } from './gemini-config.js';
|
||||
import {
|
||||
commitGeminiInstallation,
|
||||
preflightGeminiInstallation,
|
||||
prepareGeminiInstallation,
|
||||
} from './gemini-installation.js';
|
||||
import {
|
||||
geminiRuntimeFilesExist,
|
||||
readGeminiDocument,
|
||||
writeGeminiDocument,
|
||||
} from './gemini-io.js';
|
||||
import { SUPPORTED_AGENTS } from './registry.js';
|
||||
|
||||
const AGENT_KEY = 'gemini';
|
||||
const entry = SUPPORTED_AGENTS.get(AGENT_KEY)!;
|
||||
|
||||
function resolveConfigDir(): string {
|
||||
return entry.configDir.replace(/^~/, os.homedir());
|
||||
}
|
||||
|
||||
function resolveConfigPath(): string {
|
||||
return path.join(resolveConfigDir(), entry.configFile);
|
||||
}
|
||||
|
||||
function buildHookCommand(scriptPath: string): string {
|
||||
return `node "${scriptPath}"`;
|
||||
}
|
||||
|
||||
function isElydoraCommand(cmd: string, agentId?: string): boolean {
|
||||
if (!cmd.includes('elydora')) return false;
|
||||
if (agentId) {
|
||||
return cmd.includes(agentId);
|
||||
function requireEnabledHooks(document: GeminiDocument): void {
|
||||
if (!document.hookControls.enabled) {
|
||||
throw new Error(`Gemini CLI hooks are disabled by hooksConfig.enabled: ${document.filePath}`);
|
||||
}
|
||||
const disabled = disabledManagedGeminiEntries(document.hookControls);
|
||||
if (disabled.length > 0) {
|
||||
throw new Error(
|
||||
`Gemini CLI hooks are disabled by hooksConfig.disabled: ${disabled.join(', ')}`,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function filterElydoraEntries(arr: Array<Record<string, unknown>>, agentId?: string): Array<Record<string, unknown>> {
|
||||
return arr.filter((entry) => {
|
||||
if (Array.isArray(entry.hooks)) {
|
||||
const cmds = entry.hooks as Array<Record<string, unknown>>;
|
||||
return !cmds.some((h) => typeof h.command === 'string' && isElydoraCommand(h.command, agentId));
|
||||
}
|
||||
if (typeof entry.command === 'string') return !isElydoraCommand(entry.command, agentId);
|
||||
return true;
|
||||
});
|
||||
function installedGroups(guardPath: string, auditPath: string): ReadonlyMap<
|
||||
ManagedGeminiEvent,
|
||||
GeminiGroup
|
||||
> {
|
||||
return new Map([
|
||||
['BeforeTool', buildGeminiGroup(guardPath, GUARD_HOOK_NAME)],
|
||||
['AfterTool', buildGeminiGroup(auditPath, AUDIT_HOOK_NAME)],
|
||||
]);
|
||||
}
|
||||
|
||||
export const geminiPlugin: AgentPlugin = {
|
||||
managesRuntime: true,
|
||||
|
||||
async preflightInstall(config: InstallConfig): Promise<void> {
|
||||
const document = await readGeminiDocument();
|
||||
requireEnabledHooks(document);
|
||||
await preflightGeminiInstallation(config, document.filePath);
|
||||
},
|
||||
|
||||
async install(config: InstallConfig): Promise<void> {
|
||||
const configDir = resolveConfigDir();
|
||||
await fsp.mkdir(configDir, { recursive: true });
|
||||
|
||||
const configPath = resolveConfigPath();
|
||||
let settings: Record<string, unknown> = {};
|
||||
|
||||
try {
|
||||
const raw = await fsp.readFile(configPath, 'utf-8');
|
||||
settings = JSON.parse(raw);
|
||||
} catch {
|
||||
// Start fresh
|
||||
}
|
||||
|
||||
if (!settings.hooks || typeof settings.hooks !== 'object') {
|
||||
settings.hooks = {};
|
||||
}
|
||||
const hooks = settings.hooks as Record<string, unknown>;
|
||||
|
||||
// --- BeforeTool (guard — freeze enforcement) ---
|
||||
if (!Array.isArray(hooks.BeforeTool)) {
|
||||
hooks.BeforeTool = [];
|
||||
}
|
||||
const preFiltered = filterElydoraEntries(hooks.BeforeTool as Array<Record<string, unknown>>);
|
||||
preFiltered.push({
|
||||
hooks: [{ type: 'command', command: buildHookCommand(config.guardScriptPath) }],
|
||||
});
|
||||
hooks.BeforeTool = preFiltered;
|
||||
|
||||
// --- AfterTool (audit logging) ---
|
||||
if (!Array.isArray(hooks.AfterTool)) {
|
||||
hooks.AfterTool = [];
|
||||
}
|
||||
const postFiltered = filterElydoraEntries(hooks.AfterTool as Array<Record<string, unknown>>);
|
||||
postFiltered.push({
|
||||
hooks: [{ type: 'command', command: buildHookCommand(config.hookScriptPath) }],
|
||||
});
|
||||
hooks.AfterTool = postFiltered;
|
||||
|
||||
settings.hooks = hooks;
|
||||
await fsp.writeFile(configPath, JSON.stringify(settings, null, 2) + '\n', 'utf-8');
|
||||
const document = await readGeminiDocument();
|
||||
requireEnabledHooks(document);
|
||||
const paths = await preflightGeminiInstallation(config, document.filePath);
|
||||
const rendered = renderGeminiDocument(
|
||||
document,
|
||||
undefined,
|
||||
installedGroups(paths.guardPath, paths.auditPath),
|
||||
);
|
||||
await commitGeminiInstallation(await prepareGeminiInstallation(config, rendered));
|
||||
console.log(` Gemini CLI hooks: ${document.filePath}`);
|
||||
console.log(' Gemini CLI verification: run /hooks list.');
|
||||
},
|
||||
|
||||
async uninstall(agentId?: string): Promise<void> {
|
||||
const configPath = resolveConfigPath();
|
||||
|
||||
let settings: Record<string, unknown>;
|
||||
try {
|
||||
const raw = await fsp.readFile(configPath, 'utf-8');
|
||||
settings = JSON.parse(raw);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const hooks = settings.hooks as Record<string, unknown> | undefined;
|
||||
if (!hooks) return;
|
||||
|
||||
if (Array.isArray(hooks.BeforeTool)) {
|
||||
hooks.BeforeTool = filterElydoraEntries(hooks.BeforeTool as Array<Record<string, unknown>>, agentId);
|
||||
}
|
||||
if (Array.isArray(hooks.AfterTool)) {
|
||||
hooks.AfterTool = filterElydoraEntries(hooks.AfterTool as Array<Record<string, unknown>>, agentId);
|
||||
}
|
||||
|
||||
await fsp.writeFile(configPath, JSON.stringify(settings, null, 2) + '\n', 'utf-8');
|
||||
const document = await readGeminiDocument();
|
||||
await writeGeminiDocument(renderGeminiDocument(document, agentId, new Map()));
|
||||
},
|
||||
|
||||
async status(): Promise<PluginStatus> {
|
||||
const configPath = resolveConfigPath();
|
||||
|
||||
let hookConfigured = false;
|
||||
let hookScriptPath = '';
|
||||
try {
|
||||
const raw = await fsp.readFile(configPath, 'utf-8');
|
||||
const settings = JSON.parse(raw);
|
||||
const hooks = settings.hooks as Record<string, unknown> | undefined;
|
||||
if (hooks) {
|
||||
const checkArr = (arr: unknown) => {
|
||||
if (!Array.isArray(arr)) return false;
|
||||
return (arr as Array<Record<string, unknown>>).some((entry) => {
|
||||
if (Array.isArray(entry.hooks)) {
|
||||
return (entry.hooks as Array<Record<string, unknown>>).some(
|
||||
(h) => typeof h.command === 'string' && h.command.includes('elydora'),
|
||||
);
|
||||
}
|
||||
return typeof entry.command === 'string' && entry.command.includes('elydora');
|
||||
});
|
||||
};
|
||||
hookConfigured = checkArr(hooks.BeforeTool) && checkArr(hooks.AfterTool);
|
||||
|
||||
// Extract hook script path from AfterTool command
|
||||
if (hookConfigured && Array.isArray(hooks.AfterTool)) {
|
||||
for (const e of hooks.AfterTool as Array<Record<string, unknown>>) {
|
||||
if (Array.isArray(e.hooks)) {
|
||||
for (const h of e.hooks as Array<Record<string, unknown>>) {
|
||||
const cmd = h.command as string;
|
||||
if (cmd && cmd.includes('elydora')) {
|
||||
hookScriptPath = cmd.replace(/^node\s+"?/, '').replace(/"?\s*$/, '');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Config not readable
|
||||
}
|
||||
|
||||
let hookScriptExists = false;
|
||||
if (hookScriptPath) {
|
||||
try {
|
||||
await fsp.access(hookScriptPath);
|
||||
hookScriptExists = true;
|
||||
} catch {
|
||||
// File doesn't exist
|
||||
}
|
||||
}
|
||||
|
||||
const document = await readGeminiDocument();
|
||||
const contracts = geminiRuntimeContracts(document.hooks);
|
||||
const hookConfigured = managedGeminiHooksEnabled(document.hookControls)
|
||||
&& contracts.length > 0;
|
||||
const hookScriptExists = hookConfigured
|
||||
? await geminiRuntimeFilesExist(contracts)
|
||||
: false;
|
||||
return {
|
||||
installed: hookConfigured && hookScriptExists,
|
||||
agentName: AGENT_KEY,
|
||||
displayName: entry.name,
|
||||
hookConfigured,
|
||||
hookScriptExists,
|
||||
configPath,
|
||||
configPath: document.filePath,
|
||||
};
|
||||
},
|
||||
};
|
||||
Reference in new issue
Block a user