feat: add native Cline hook integration

This commit is contained in:
ZacharyZhang-NY committed 2026-07-19 09:31:31 -04:00
1 parent a69545d50f
commit 66c5ab00a9
9 files changed
+1042 -5

No files matched your search

+2
View File
@@ -16,6 +16,7 @@ import { opencodePlugin } from './plugins/opencode.js';
import { copilotPlugin } from './plugins/copilot.js';
import { lettaPlugin } from './plugins/letta.js';
import { codexPlugin } from './plugins/codex.js';
import { clinePlugin } from './plugins/cline.js';
import { kimiPlugin } from './plugins/kimi.js';
import { grokPlugin } from './plugins/grok.js';
@@ -32,6 +33,7 @@ const PLUGINS: ReadonlyMap<string, AgentPlugin> = new Map([
['copilot', copilotPlugin],
['letta', lettaPlugin],
['codex', codexPlugin],
['cline', clinePlugin],
['kimi', kimiPlugin],
['grok', grokPlugin],
]);
+232
View File
@@ -0,0 +1,232 @@
import os from 'node:os';
import path from 'node:path';
export const AGENT_KEY = 'cline';
export const GUARD_FILE_NAME = 'PreToolUse.mjs';
export const AUDIT_FILE_NAME = 'PostToolUse.mjs';
const METADATA_MARKER = '// @elydora-cline-hook ';
const METADATA_VERSION = 1;
export type ClineHookKind = 'guard' | 'audit';
export interface ClineHookMetadata {
readonly version: 1;
readonly kind: ClineHookKind;
readonly agentId: string;
readonly runtimePath: string;
}
export interface ClineHookFile {
readonly exists: boolean;
readonly filePath: string;
readonly source?: string;
readonly metadata?: ClineHookMetadata;
}
export interface ClineRuntimeContract {
readonly agentId: string;
readonly agentDirectory: string;
readonly guardPath: string;
readonly auditPath: string;
}
type JsonObject = Record<string, unknown>;
function isObject(value: unknown): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
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 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;
}
export function sameAgentId(left: string, right: string): boolean {
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
}
export function resolveHooksDirectory(): string {
const configuredDirectory = process.env.CLINE_DIR?.trim();
const clineDirectory = configuredDirectory
? path.resolve(configuredDirectory)
: path.join(os.homedir(), '.cline');
return path.join(clineDirectory, 'hooks');
}
export function resolveHookFiles(): {
readonly hooksDirectory: string;
readonly guardPath: string;
readonly auditPath: string;
} {
const hooksDirectory = resolveHooksDirectory();
return {
hooksDirectory,
guardPath: path.join(hooksDirectory, GUARD_FILE_NAME),
auditPath: path.join(hooksDirectory, AUDIT_FILE_NAME),
};
}
export function buildMetadata(
kind: ClineHookKind,
agentId: string,
runtimePath: string,
): ClineHookMetadata {
if (!agentId) throw new Error('agentId is required');
if (!path.isAbsolute(runtimePath)) throw new Error(`Cline ${kind} runtime path must be absolute`);
return { version: METADATA_VERSION, kind, agentId, runtimePath };
}
function encodeMetadata(metadata: ClineHookMetadata): string {
return Buffer.from(JSON.stringify(metadata), 'utf-8').toString('base64url');
}
export function buildWrapper(metadata: ClineHookMetadata): string {
return `#!/usr/bin/env node
${METADATA_MARKER}${encodeMetadata(metadata)}
import { spawn } from 'node:child_process';
const hookKind = ${JSON.stringify(metadata.kind)};
const runtimePath = ${JSON.stringify(metadata.runtimePath)};
function runRuntime(input) {
return new Promise((resolve, reject) => {
const child = spawn(process.execPath, [runtimePath], {
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
});
const stdout = [];
const stderr = [];
let stdinError;
child.stdout.on('data', (chunk) => stdout.push(chunk));
child.stderr.on('data', (chunk) => stderr.push(chunk));
child.stdin.on('error', (error) => {
if (error?.code !== 'EPIPE') stdinError = error;
});
child.once('error', reject);
child.once('close', (code, signal) => {
if (stdinError) {
reject(stdinError);
return;
}
resolve({
code,
signal,
stdout: Buffer.concat(stdout).toString('utf-8'),
stderr: Buffer.concat(stderr).toString('utf-8'),
});
});
child.stdin.end(input);
});
}
async function main() {
const chunks = [];
for await (const chunk of process.stdin) chunks.push(chunk);
const result = await runRuntime(Buffer.concat(chunks));
if (result.stdout) process.stderr.write(result.stdout);
if (result.stderr) process.stderr.write(result.stderr);
if (hookKind === 'guard' && result.code === 2) {
const errorMessage = result.stderr.trim() || 'Agent is frozen by Elydora.';
process.stdout.write('HOOK_CONTROL\\t' + JSON.stringify({ cancel: true, errorMessage }) + '\\n');
return;
}
if (result.signal) throw new Error('runtime terminated by signal ' + result.signal);
if (result.code !== 0) throw new Error('runtime exited with code ' + result.code);
}
main().catch((error) => {
const message = error instanceof Error ? error.stack || error.message : String(error);
process.stderr.write('Elydora Cline ' + hookKind + ' wrapper failed: ' + message + '\\n');
process.exitCode = 1;
});
`;
}
function validateMetadata(value: unknown): ClineHookMetadata {
if (!isObject(value)) throw new Error('metadata must be an object');
const keys = Object.keys(value).sort();
if (keys.join(',') !== 'agentId,kind,runtimePath,version') {
throw new Error('metadata contains an unexpected field set');
}
if (value.version !== METADATA_VERSION) throw new Error('metadata version must be 1');
if (value.kind !== 'guard' && value.kind !== 'audit') {
throw new Error('metadata kind must be "guard" or "audit"');
}
if (typeof value.agentId !== 'string' || value.agentId.length === 0) {
throw new Error('metadata agentId must be a non-empty string');
}
if (typeof value.runtimePath !== 'string' || !path.isAbsolute(value.runtimePath)) {
throw new Error('metadata runtimePath must be an absolute path');
}
return value as unknown as ClineHookMetadata;
}
export function parseMetadata(filePath: string, source: string): ClineHookMetadata | undefined {
const markerLine = source.split(/\r?\n/, 3)[1];
if (!markerLine?.startsWith(METADATA_MARKER)) return undefined;
try {
const encoded = markerLine.slice(METADATA_MARKER.length);
const decoded = Buffer.from(encoded, 'base64url').toString('utf-8');
return validateMetadata(JSON.parse(decoded));
} catch (error) {
throw new Error(`Failed to parse Elydora Cline hook metadata at ${filePath}: ${errorMessage(error)}`, {
cause: asError(error),
});
}
}
export function assertWrapperIntegrity(file: ClineHookFile): void {
if (!file.metadata || file.source === undefined) return;
if (file.source !== buildWrapper(file.metadata)) {
throw new Error(`Elydora Cline hook at ${file.filePath} does not match the managed template`);
}
}
function validateAgentSegment(agentId: string): void {
if (agentId === '.' || agentId === '..' || path.basename(agentId) !== agentId) {
throw new Error('Elydora Cline hook metadata contains an invalid agentId');
}
}
export function runtimeContract(
guardFile: ClineHookFile,
auditFile: ClineHookFile,
): ClineRuntimeContract | undefined {
if (!guardFile.metadata || !auditFile.metadata) return undefined;
assertWrapperIntegrity(guardFile);
assertWrapperIntegrity(auditFile);
const guard = guardFile.metadata;
const audit = auditFile.metadata;
if (guard.kind !== 'guard' || audit.kind !== 'audit') {
throw new Error('Elydora Cline hook files contain mismatched event metadata');
}
if (!sameAgentId(guard.agentId, audit.agentId)) {
throw new Error('Elydora Cline hook files reference different agents');
}
validateAgentSegment(guard.agentId);
const agentDirectory = path.join(os.homedir(), '.elydora', guard.agentId);
const expectedGuard = path.join(agentDirectory, 'guard.js');
const expectedAudit = path.join(agentDirectory, 'hook.js');
if (!samePath(guard.runtimePath, expectedGuard) || !samePath(audit.runtimePath, expectedAudit)) {
throw new Error('Elydora Cline hook metadata references an unexpected runtime path');
}
return {
agentId: guard.agentId,
agentDirectory,
guardPath: expectedGuard,
auditPath: expectedAudit,
};
}
+249
View File
@@ -0,0 +1,249 @@
import { randomUUID } from 'node:crypto';
import fsp from 'node:fs/promises';
import type { FileHandle } from 'node:fs/promises';
import path from 'node:path';
import {
AGENT_KEY,
type ClineHookFile,
type ClineRuntimeContract,
parseMetadata,
sameAgentId,
} from './cline-contract.js';
type JsonObject = Record<string, unknown>;
interface StagedFile {
readonly state: ClineHookFile;
readonly tempPath: string;
}
function isObject(value: unknown): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function hasErrorCode(error: unknown, code: string): boolean {
return isObject(error) && error.code === code;
}
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));
}
export async function readHookFile(filePath: string): Promise<ClineHookFile> {
let source: string;
try {
source = await fsp.readFile(filePath, 'utf-8');
} catch (error) {
if (hasErrorCode(error, 'ENOENT')) return { exists: false, filePath };
throw new Error(`Read Cline hook at ${filePath}: ${errorMessage(error)}`, {
cause: asError(error),
});
}
return {
exists: true,
filePath,
source,
metadata: parseMetadata(filePath, source),
};
}
export function requireAvailableHookFile(file: ClineHookFile): void {
if (file.exists && !file.metadata) {
throw new Error(`Cline hook at ${file.filePath} already exists and is owned by another integration`);
}
}
async function removeTemporary(tempPath: string): Promise<void> {
try {
await fsp.unlink(tempPath);
} catch (error) {
if (!hasErrorCode(error, 'ENOENT')) throw error;
}
}
async function failStage(
handle: FileHandle | undefined,
tempPath: string,
cause: unknown,
): Promise<never> {
const errors = [asError(cause)];
if (handle) {
try {
await handle.close();
} catch (error) {
errors.push(asError(error));
}
}
try {
await removeTemporary(tempPath);
} catch (error) {
errors.push(asError(error));
}
const message = `Stage Cline hook at ${tempPath}: ${errorMessage(cause)}`;
if (errors.length > 1) throw new AggregateError(errors, message);
throw new Error(message, { cause: errors[0] });
}
async function stageFile(state: ClineHookFile, source: string): Promise<StagedFile> {
const directory = path.dirname(state.filePath);
await fsp.mkdir(directory, { recursive: true, mode: 0o700 });
const tempPath = path.join(directory, `.${path.basename(state.filePath)}.${randomUUID()}.tmp`);
let handle: FileHandle | undefined;
try {
handle = await fsp.open(tempPath, 'wx', 0o700);
await handle.writeFile(source, 'utf-8');
await handle.sync();
await handle.close();
handle = undefined;
return { state, tempPath };
} catch (error) {
return failStage(handle, tempPath, error);
}
}
async function writeAtomic(filePath: string, source: string): Promise<void> {
const staged = await stageFile({ exists: false, filePath }, source);
try {
await fsp.rename(staged.tempPath, filePath);
} catch (error) {
const errors = [asError(error)];
try {
await removeTemporary(staged.tempPath);
} catch (cleanupError) {
errors.push(asError(cleanupError));
}
throw new AggregateError(errors, `Restore Cline hook at ${filePath}: ${errorMessage(error)}`);
}
}
async function rollbackFile(state: ClineHookFile): Promise<void> {
if (state.exists) {
await writeAtomic(state.filePath, state.source!);
return;
}
try {
await fsp.unlink(state.filePath);
} catch (error) {
if (!hasErrorCode(error, 'ENOENT')) throw error;
}
}
export async function writeHookPair(
guard: { readonly state: ClineHookFile; readonly source: string },
audit: { readonly state: ClineHookFile; readonly source: string },
): Promise<void> {
const staged: StagedFile[] = [];
try {
staged.push(await stageFile(guard.state, guard.source));
staged.push(await stageFile(audit.state, audit.source));
} catch (error) {
const errors = [asError(error)];
for (const item of staged) {
try {
await removeTemporary(item.tempPath);
} catch (cleanupError) {
errors.push(asError(cleanupError));
}
}
throw new AggregateError(errors, `Stage Cline hook pair: ${errorMessage(error)}`);
}
const committed: StagedFile[] = [];
try {
for (const item of staged) {
await fsp.rename(item.tempPath, item.state.filePath);
committed.push(item);
}
} catch (error) {
const errors = [asError(error)];
for (const item of [...committed].reverse()) {
try {
await rollbackFile(item.state);
} catch (rollbackError) {
errors.push(asError(rollbackError));
}
}
for (const item of staged.slice(committed.length)) {
try {
await removeTemporary(item.tempPath);
} catch (cleanupError) {
errors.push(asError(cleanupError));
}
}
throw new AggregateError(errors, `Write Cline hook pair: ${errorMessage(error)}`);
}
}
export async function removeOwnedHooks(
files: readonly ClineHookFile[],
agentId?: string,
): Promise<void> {
for (const file of files) {
const ownedAgentId = file.metadata?.agentId;
if (!ownedAgentId || (agentId && !sameAgentId(ownedAgentId, agentId))) continue;
try {
await fsp.unlink(file.filePath);
} catch (error) {
if (hasErrorCode(error, 'ENOENT')) continue;
throw new Error(`Remove Cline hook at ${file.filePath}: ${errorMessage(error)}`, {
cause: asError(error),
});
}
}
}
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> {
let raw: string;
try {
raw = await fsp.readFile(filePath, 'utf-8');
} catch (error) {
if (hasErrorCode(error, 'ENOENT')) return undefined;
throw new Error(`Read Elydora runtime config at ${filePath}: ${errorMessage(error)}`, {
cause: asError(error),
});
}
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 be a JSON object`);
return value;
}
export async function runtimeFilesExist(contract: ClineRuntimeContract): Promise<boolean> {
const configPath = path.join(contract.agentDirectory, 'config.json');
const config = await readRuntimeConfig(configPath);
if (!config
|| config.agent_name !== AGENT_KEY
|| typeof config.agent_id !== 'string'
|| !sameAgentId(config.agent_id, contract.agentId)) return false;
const existence = await Promise.all([
regularFileExists(contract.guardPath, 'Elydora guard runtime'),
regularFileExists(contract.auditPath, 'Elydora audit runtime'),
]);
return existence.every(Boolean);
}
+70
View File
@@ -0,0 +1,70 @@
import type { AgentPlugin, InstallConfig, PluginStatus } from './base.js';
import {
AGENT_KEY,
buildMetadata,
buildWrapper,
resolveHookFiles,
runtimeContract,
} from './cline-contract.js';
import {
readHookFile,
removeOwnedHooks,
requireAvailableHookFile,
requireRuntime,
runtimeFilesExist,
writeHookPair,
} from './cline-io.js';
import { SUPPORTED_AGENTS } from './registry.js';
const entry = SUPPORTED_AGENTS.get(AGENT_KEY)!;
export const clinePlugin: AgentPlugin = {
async install(config: InstallConfig): Promise<void> {
if (!config.agentId) throw new Error('agentId is required');
const paths = resolveHookFiles();
const guardState = await readHookFile(paths.guardPath);
const auditState = await readHookFile(paths.auditPath);
requireAvailableHookFile(guardState);
requireAvailableHookFile(auditState);
await requireRuntime(config.guardScriptPath, 'Elydora guard runtime');
await requireRuntime(config.hookScriptPath, 'Elydora audit runtime');
const guardMetadata = buildMetadata('guard', config.agentId, config.guardScriptPath);
const auditMetadata = buildMetadata('audit', config.agentId, config.hookScriptPath);
const guardSource = buildWrapper(guardMetadata);
const auditSource = buildWrapper(auditMetadata);
runtimeContract(
{ exists: true, filePath: paths.guardPath, source: guardSource, metadata: guardMetadata },
{ exists: true, filePath: paths.auditPath, source: auditSource, metadata: auditMetadata },
);
await writeHookPair(
{ state: guardState, source: guardSource },
{ state: auditState, source: auditSource },
);
console.log(' Cline: user-level PreToolUse and PostToolUse hooks installed.');
},
async uninstall(agentId?: string): Promise<void> {
const paths = resolveHookFiles();
const guardState = await readHookFile(paths.guardPath);
const auditState = await readHookFile(paths.auditPath);
await removeOwnedHooks([guardState, auditState], agentId);
},
async status(): Promise<PluginStatus> {
const paths = resolveHookFiles();
const guardState = await readHookFile(paths.guardPath);
const auditState = await readHookFile(paths.auditPath);
const contract = runtimeContract(guardState, auditState);
const hookConfigured = contract !== undefined;
const hookScriptExists = contract ? await runtimeFilesExist(contract) : false;
return {
installed: hookConfigured && hookScriptExists,
agentName: AGENT_KEY,
displayName: entry.name,
hookConfigured,
hookScriptExists,
configPath: paths.hooksDirectory,
};
},
};
+14 -5
View File
@@ -180,11 +180,20 @@ async function main() {
return;
}
// Extract tool_name and tool_input from hook data
// Different agents may pass data in different shapes
const toolName = hookData.tool_name || hookData.toolName || hookData.name || 'unknown';
const toolInput = hookData.tool_input || hookData.toolInput || hookData.input || hookData.parameters || {};
const sessionId = hookData.session_id || hookData.sessionId || hookData.session || 'unknown';
// Extract provider-native tool fields without reshaping the hook input.
const clineToolEvent =
hookData.tool_result && typeof hookData.tool_result === 'object'
? hookData.tool_result
: hookData.tool_call && typeof hookData.tool_call === 'object'
? hookData.tool_call
: {};
const toolName =
hookData.tool_name || hookData.toolName || hookData.name || clineToolEvent.name || 'unknown';
const toolInput =
hookData.tool_input || hookData.toolInput || hookData.input || hookData.parameters ||
clineToolEvent.input || {};
const sessionId =
hookData.session_id || hookData.sessionId || hookData.session || hookData.taskId || 'unknown';
// Read agent config and private key
let config;
+1
View File
@@ -15,6 +15,7 @@ export const SUPPORTED_AGENTS: ReadonlyMap<string, AgentRegistryEntry> = new Map
['copilot', { name: 'Copilot CLI', configDir: '.github/hooks', configFile: 'hooks.json' }],
['letta', { name: 'Letta Code', configDir: '~/.letta', configFile: 'settings.json' }],
['codex', { name: 'OpenAI Codex', configDir: '~/.codex', configFile: 'hooks.json' }],
['cline', { name: 'Cline', configDir: '~/.cline/hooks', configFile: 'PreToolUse.mjs' }],
['kimi', { name: 'Kimi Code', configDir: '~/.kimi-code', configFile: 'config.toml' }],
['grok', { name: 'Grok Build', configDir: '~/.grok/hooks', configFile: 'elydora-audit.json' }],
]);