fix(kirocli): harden v2 and v3 hooks
This commit is contained in:
1 parent
5889b09a09
commit
3f43f4aad5
14 files changed
+1466
-597
No files matched your search
@@ -0,0 +1,416 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
buildKiroIdeCommand,
|
||||
kiroIdeRuntimeReference,
|
||||
sameKiroIdeAgentId,
|
||||
sameKiroIdePath,
|
||||
type KiroIdeRuntimeReference,
|
||||
} from './kiroide-command.js';
|
||||
import {
|
||||
buildKiroIdeHook,
|
||||
kiroIdeRuntimeContracts,
|
||||
renderKiroIdeDocument,
|
||||
type KiroIdeDocument,
|
||||
type KiroIdeHook,
|
||||
type RenderedKiroIdeDocument,
|
||||
type KiroIdeRuntimeContract,
|
||||
} from './kiroide-contract.js';
|
||||
import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
export const AGENT_KEY = 'kirocli';
|
||||
export const AUDIT_SCRIPT = 'hook.js';
|
||||
export const GUARD_SCRIPT = 'guard.js';
|
||||
export const V2_AGENT_NAME = 'elydora-audit';
|
||||
export const V3_CONFIG_FILE = 'elydora-audit.json';
|
||||
export const HOOK_TIMEOUT_MILLISECONDS = 10_000;
|
||||
|
||||
const V2_DESCRIPTION = 'Kiro CLI with Elydora audit and freeze enforcement';
|
||||
const V3_GUARD_NAME = 'elydora-guard';
|
||||
const V3_AUDIT_NAME = 'elydora-audit';
|
||||
const V2_EVENTS = new Set([
|
||||
'agentSpawn',
|
||||
'userPromptSubmit',
|
||||
'preToolUse',
|
||||
'postToolUse',
|
||||
'stop',
|
||||
]);
|
||||
|
||||
export interface KiroCliPaths {
|
||||
readonly homeDirectory: string;
|
||||
readonly kiroDirectory: string;
|
||||
readonly agentsDirectory: string;
|
||||
readonly hooksDirectory: string;
|
||||
readonly v2Path: string;
|
||||
readonly v3Path: string;
|
||||
}
|
||||
|
||||
export interface KiroCliV2Hook extends JsonObject {
|
||||
readonly command: string;
|
||||
readonly matcher?: string;
|
||||
readonly timeout_ms?: number;
|
||||
readonly cache_ttl_seconds?: number;
|
||||
}
|
||||
|
||||
export interface KiroCliV2Document {
|
||||
readonly exists: boolean;
|
||||
readonly filePath: string;
|
||||
readonly root: JsonObject;
|
||||
readonly hooks: JsonObject;
|
||||
readonly raw?: string;
|
||||
}
|
||||
|
||||
export interface RenderedKiroCliV2Document {
|
||||
readonly document: KiroCliV2Document;
|
||||
readonly changed: boolean;
|
||||
readonly next?: string;
|
||||
}
|
||||
|
||||
export function resolveKiroCliPaths(homeDirectory = os.homedir()): KiroCliPaths {
|
||||
const resolvedHome = path.resolve(homeDirectory);
|
||||
const kiroDirectory = path.join(resolvedHome, '.kiro');
|
||||
const agentsDirectory = path.join(kiroDirectory, 'agents');
|
||||
const hooksDirectory = path.join(kiroDirectory, 'hooks');
|
||||
return {
|
||||
homeDirectory: resolvedHome,
|
||||
kiroDirectory,
|
||||
agentsDirectory,
|
||||
hooksDirectory,
|
||||
v2Path: path.join(agentsDirectory, `${V2_AGENT_NAME}.json`),
|
||||
v3Path: path.join(hooksDirectory, V3_CONFIG_FILE),
|
||||
};
|
||||
}
|
||||
|
||||
function validateOptionalInteger(value: unknown, field: string, label: string): void {
|
||||
if (value !== undefined && (!Number.isSafeInteger(value) || (value as number) < 0)) {
|
||||
throw new Error(`${label} ${field} must be a non-negative integer`);
|
||||
}
|
||||
}
|
||||
|
||||
function validateV2Hook(value: unknown, event: string, index: number): KiroCliV2Hook {
|
||||
const label = `Kiro CLI v2 agent hooks.${event}[${index}]`;
|
||||
if (!isObject(value)) throw new Error(`${label} must be an object`);
|
||||
if (typeof value.command !== 'string' || !value.command) {
|
||||
throw new Error(`${label} command must be a non-empty string`);
|
||||
}
|
||||
if (value.matcher !== undefined) {
|
||||
if (!['preToolUse', 'postToolUse'].includes(event)) {
|
||||
throw new Error(`${label} matcher is valid only for tool events`);
|
||||
}
|
||||
if (typeof value.matcher !== 'string' || !value.matcher) {
|
||||
throw new Error(`${label} matcher must be a non-empty string`);
|
||||
}
|
||||
}
|
||||
validateOptionalInteger(value.timeout_ms, 'timeout_ms', label);
|
||||
validateOptionalInteger(value.cache_ttl_seconds, 'cache_ttl_seconds', label);
|
||||
return value as KiroCliV2Hook;
|
||||
}
|
||||
|
||||
function validateV2Hooks(value: unknown, filePath: string): JsonObject {
|
||||
if (value === undefined) return {};
|
||||
if (!isObject(value)) {
|
||||
throw new Error(`Kiro CLI v2 agent field "hooks" must be an object: ${filePath}`);
|
||||
}
|
||||
const hooks: JsonObject = { ...value };
|
||||
for (const [event, entries] of Object.entries(value)) {
|
||||
if (!V2_EVENTS.has(event)) {
|
||||
throw new Error(`Kiro CLI v2 agent has unsupported hook event "${event}": ${filePath}`);
|
||||
}
|
||||
if (!Array.isArray(entries)) {
|
||||
throw new Error(`Kiro CLI v2 agent hooks.${event} must be an array: ${filePath}`);
|
||||
}
|
||||
hooks[event] = entries.map((entry, index) => validateV2Hook(entry, event, index));
|
||||
}
|
||||
return hooks;
|
||||
}
|
||||
|
||||
function validateOptionalV2Fields(root: JsonObject, filePath: string): void {
|
||||
for (const field of ['name', 'description', 'prompt', 'model', 'keyboardShortcut', 'welcomeMessage']) {
|
||||
if (root[field] !== undefined && typeof root[field] !== 'string') {
|
||||
throw new Error(`Kiro CLI v2 agent field "${field}" must be a string: ${filePath}`);
|
||||
}
|
||||
}
|
||||
for (const field of ['tools', 'allowedTools', 'resources']) {
|
||||
const value = root[field];
|
||||
if (value !== undefined
|
||||
&& (!Array.isArray(value) || !value.every((entry) => typeof entry === 'string'))) {
|
||||
throw new Error(`Kiro CLI v2 agent field "${field}" must be an array of strings: ${filePath}`);
|
||||
}
|
||||
}
|
||||
if (root.includeMcpJson !== undefined && typeof root.includeMcpJson !== 'boolean') {
|
||||
throw new Error(`Kiro CLI v2 agent field "includeMcpJson" must be a boolean: ${filePath}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function parseKiroCliV2Document(filePath: string, raw: string): KiroCliV2Document {
|
||||
const root = parseStrictJsonObject(raw, `Kiro CLI v2 agent at ${filePath}`);
|
||||
validateOptionalV2Fields(root, filePath);
|
||||
return {
|
||||
exists: true,
|
||||
filePath,
|
||||
root,
|
||||
hooks: validateV2Hooks(root.hooks, filePath),
|
||||
raw,
|
||||
};
|
||||
}
|
||||
|
||||
export function createKiroCliV2Document(filePath: string): KiroCliV2Document {
|
||||
return { exists: false, filePath, root: {}, hooks: {} };
|
||||
}
|
||||
|
||||
function eventHooks(document: KiroCliV2Document, event: string): readonly KiroCliV2Hook[] {
|
||||
return (document.hooks[event] as readonly KiroCliV2Hook[] | undefined) ?? [];
|
||||
}
|
||||
|
||||
function exactKeys(value: JsonObject, keys: readonly string[]): boolean {
|
||||
return Object.keys(value).sort().join('|') === [...keys].sort().join('|');
|
||||
}
|
||||
|
||||
function legacyWindowsReference(
|
||||
command: unknown,
|
||||
scriptName: string,
|
||||
): KiroIdeRuntimeReference | undefined {
|
||||
if (typeof command !== 'string') return undefined;
|
||||
const match = /^"([^"\r\n]+)" "([^"\r\n]+)"$/.exec(command);
|
||||
if (!match
|
||||
|| !path.isAbsolute(match[1])
|
||||
|| !['node', 'node.exe'].includes(path.basename(match[1]).toLowerCase())
|
||||
|| !path.isAbsolute(match[2])
|
||||
|| path.basename(match[2]) !== scriptName) return undefined;
|
||||
const agentDirectory = path.dirname(match[2]);
|
||||
if (!sameKiroIdePath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))) {
|
||||
return undefined;
|
||||
}
|
||||
const agentId = path.basename(agentDirectory);
|
||||
return agentId ? { agentId, scriptPath: match[2] } : undefined;
|
||||
}
|
||||
|
||||
function ownedReference(command: unknown, scriptName: string): KiroIdeRuntimeReference | undefined {
|
||||
return typeof command === 'string'
|
||||
? kiroIdeRuntimeReference(command, scriptName) ?? legacyWindowsReference(command, scriptName)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function v2OwnedReference(hook: KiroCliV2Hook, event: string) {
|
||||
if (event === 'preToolUse') return ownedReference(hook.command, GUARD_SCRIPT);
|
||||
if (event === 'postToolUse') return ownedReference(hook.command, AUDIT_SCRIPT);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function v2ManagedReference(hook: KiroCliV2Hook, event: string) {
|
||||
const reference = v2OwnedReference(hook, event);
|
||||
if (!reference
|
||||
|| !exactKeys(hook, ['matcher', 'command', 'timeout_ms'])
|
||||
|| hook.matcher !== '*'
|
||||
|| hook.timeout_ms !== HOOK_TIMEOUT_MILLISECONDS) return undefined;
|
||||
return reference;
|
||||
}
|
||||
|
||||
function managedMetadata(root: JsonObject): boolean {
|
||||
return root.name === V2_AGENT_NAME
|
||||
&& root.description === V2_DESCRIPTION
|
||||
&& Array.isArray(root.tools)
|
||||
&& root.tools.length === 1
|
||||
&& root.tools[0] === '*'
|
||||
&& root.includeMcpJson === true;
|
||||
}
|
||||
|
||||
function hasOwnedV2Hooks(document: KiroCliV2Document, agentId?: string): boolean {
|
||||
return ['preToolUse', 'postToolUse'].some((event) => eventHooks(document, event).some((hook) => {
|
||||
const reference = v2OwnedReference(hook, event);
|
||||
return reference !== undefined
|
||||
&& (agentId === undefined || sameKiroIdeAgentId(reference.agentId, agentId));
|
||||
}));
|
||||
}
|
||||
|
||||
export function requireAvailableKiroCliV2Document(document: KiroCliV2Document): void {
|
||||
if (document.exists && !managedMetadata(document.root) && !hasOwnedV2Hooks(document)) {
|
||||
throw new Error(`Kiro CLI v2 agent path conflicts with the Elydora contract: ${document.filePath}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function withoutManagedKiroCliV2Hooks(
|
||||
document: KiroCliV2Document,
|
||||
agentId?: string,
|
||||
): JsonObject {
|
||||
const next = { ...document.hooks };
|
||||
for (const event of ['preToolUse', 'postToolUse']) {
|
||||
const remaining = eventHooks(document, event).filter((hook) => {
|
||||
const reference = v2OwnedReference(hook, event);
|
||||
return !reference || (agentId !== undefined && !sameKiroIdeAgentId(reference.agentId, agentId));
|
||||
});
|
||||
if (remaining.length > 0) next[event] = remaining;
|
||||
else delete next[event];
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function buildV2Hook(scriptPath: string): KiroCliV2Hook {
|
||||
return {
|
||||
matcher: '*',
|
||||
command: buildKiroIdeCommand(scriptPath),
|
||||
timeout_ms: HOOK_TIMEOUT_MILLISECONDS,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildKiroCliV2Hooks(
|
||||
document: KiroCliV2Document,
|
||||
guardPath: string,
|
||||
auditPath: string,
|
||||
): JsonObject {
|
||||
const hooks = withoutManagedKiroCliV2Hooks(document);
|
||||
hooks.preToolUse = [...eventHooks({ ...document, hooks }, 'preToolUse'), buildV2Hook(guardPath)];
|
||||
hooks.postToolUse = [...eventHooks({ ...document, hooks }, 'postToolUse'), buildV2Hook(auditPath)];
|
||||
return hooks;
|
||||
}
|
||||
|
||||
export function renderKiroCliV2Installation(
|
||||
document: KiroCliV2Document,
|
||||
hooks: JsonObject,
|
||||
): RenderedKiroCliV2Document {
|
||||
const next = `${JSON.stringify({
|
||||
...document.root,
|
||||
name: V2_AGENT_NAME,
|
||||
description: V2_DESCRIPTION,
|
||||
tools: ['*'],
|
||||
includeMcpJson: true,
|
||||
hooks,
|
||||
}, null, 2)}\n`;
|
||||
return { document, changed: next !== document.raw, next };
|
||||
}
|
||||
|
||||
function entirelyManagedV2Document(document: KiroCliV2Document, agentId?: string): boolean {
|
||||
if (!document.exists
|
||||
|| !managedMetadata(document.root)
|
||||
|| !exactKeys(document.root, ['name', 'description', 'tools', 'includeMcpJson', 'hooks'])
|
||||
|| !exactKeys(document.hooks, ['preToolUse', 'postToolUse'])) return false;
|
||||
for (const event of ['preToolUse', 'postToolUse']) {
|
||||
const hooks = eventHooks(document, event);
|
||||
if (hooks.length !== 1) return false;
|
||||
const reference = v2OwnedReference(hooks[0], event);
|
||||
if (!reference || (agentId !== undefined && !sameKiroIdeAgentId(reference.agentId, agentId))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function renderKiroCliV2Uninstall(
|
||||
document: KiroCliV2Document,
|
||||
hooks: JsonObject,
|
||||
agentId?: string,
|
||||
): RenderedKiroCliV2Document {
|
||||
if (!hasOwnedV2Hooks(document, agentId)) return { document, changed: false };
|
||||
if (entirelyManagedV2Document(document, agentId) && Object.keys(hooks).length === 0) {
|
||||
return { document, changed: true };
|
||||
}
|
||||
const next = `${JSON.stringify({ ...document.root, hooks }, null, 2)}\n`;
|
||||
return { document, changed: next !== document.raw, next };
|
||||
}
|
||||
|
||||
export function kiroCliV2RuntimeContracts(
|
||||
document: KiroCliV2Document,
|
||||
): KiroIdeRuntimeContract[] {
|
||||
for (const event of ['preToolUse', 'postToolUse']) {
|
||||
if (eventHooks(document, event).some((hook) => (
|
||||
v2OwnedReference(hook, event) !== undefined
|
||||
&& v2ManagedReference(hook, event) === undefined
|
||||
))) return [];
|
||||
}
|
||||
const guards = eventHooks(document, 'preToolUse')
|
||||
.map((hook) => v2ManagedReference(hook, 'preToolUse'))
|
||||
.filter((value): value is KiroIdeRuntimeReference => value !== undefined);
|
||||
const audits = eventHooks(document, 'postToolUse')
|
||||
.map((hook) => v2ManagedReference(hook, 'postToolUse'))
|
||||
.filter((value): value is KiroIdeRuntimeReference => value !== undefined);
|
||||
if (guards.length !== 1 || audits.length !== 1
|
||||
|| !sameKiroIdeAgentId(guards[0].agentId, audits[0].agentId)) return [];
|
||||
return [{ agentId: guards[0].agentId, guardPath: guards[0].scriptPath, auditPath: audits[0].scriptPath }];
|
||||
}
|
||||
|
||||
function v3Specification(name: string) {
|
||||
if (name === V3_GUARD_NAME) return { scriptName: GUARD_SCRIPT };
|
||||
if (name === V3_AUDIT_NAME) return { scriptName: AUDIT_SCRIPT };
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function v3OwnedReference(hook: KiroIdeHook) {
|
||||
const specification = v3Specification(hook.name);
|
||||
return specification && hook.action.type === 'command'
|
||||
? ownedReference(hook.action.command, specification.scriptName)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export function requireAvailableKiroCliV3Hooks(hooks: readonly KiroIdeHook[]): void {
|
||||
for (const hook of hooks) {
|
||||
if (v3Specification(hook.name) && !v3OwnedReference(hook)) {
|
||||
throw new Error(`Kiro CLI v3 hook name "${hook.name}" conflicts with the Elydora contract`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function withoutManagedKiroCliV3Hooks(
|
||||
hooks: readonly KiroIdeHook[],
|
||||
agentId?: string,
|
||||
): KiroIdeHook[] {
|
||||
return hooks.filter((hook) => {
|
||||
const reference = v3OwnedReference(hook);
|
||||
return !reference || (agentId !== undefined && !sameKiroIdeAgentId(reference.agentId, agentId));
|
||||
});
|
||||
}
|
||||
|
||||
function hasOwnedV3Hooks(hooks: readonly KiroIdeHook[], agentId?: string): boolean {
|
||||
return hooks.some((hook) => {
|
||||
const reference = v3OwnedReference(hook);
|
||||
return reference !== undefined
|
||||
&& (agentId === undefined || sameKiroIdeAgentId(reference.agentId, agentId));
|
||||
});
|
||||
}
|
||||
|
||||
function entirelyManagedV3Document(document: KiroIdeDocument, agentId?: string): boolean {
|
||||
return document.exists
|
||||
&& exactKeys(document.root, ['version', 'hooks'])
|
||||
&& document.hooks.length > 0
|
||||
&& document.hooks.every((hook) => {
|
||||
const reference = v3OwnedReference(hook);
|
||||
return reference !== undefined
|
||||
&& (agentId === undefined || sameKiroIdeAgentId(reference.agentId, agentId));
|
||||
});
|
||||
}
|
||||
|
||||
export function renderKiroCliV3Uninstall(
|
||||
document: KiroIdeDocument,
|
||||
hooks: readonly KiroIdeHook[],
|
||||
agentId?: string,
|
||||
): RenderedKiroIdeDocument {
|
||||
if (!hasOwnedV3Hooks(document.hooks, agentId)) return { document, changed: false };
|
||||
if (hooks.length === 0 && entirelyManagedV3Document(document, agentId)) {
|
||||
return { document, changed: true };
|
||||
}
|
||||
return renderKiroIdeDocument(document, hooks);
|
||||
}
|
||||
|
||||
export function buildKiroCliV3Hooks(
|
||||
hooks: readonly KiroIdeHook[],
|
||||
guardPath: string,
|
||||
auditPath: string,
|
||||
): KiroIdeHook[] {
|
||||
return [
|
||||
...withoutManagedKiroCliV3Hooks(hooks),
|
||||
buildKiroIdeHook(V3_GUARD_NAME, guardPath),
|
||||
buildKiroIdeHook(V3_AUDIT_NAME, auditPath),
|
||||
];
|
||||
}
|
||||
|
||||
export function commonKiroCliRuntimeContract(
|
||||
v2Document: KiroCliV2Document,
|
||||
v3Hooks: readonly KiroIdeHook[],
|
||||
): KiroIdeRuntimeContract | undefined {
|
||||
const v2 = kiroCliV2RuntimeContracts(v2Document);
|
||||
const v3 = kiroIdeRuntimeContracts(v3Hooks);
|
||||
if (v2.length !== 1 || v3.length !== 1
|
||||
|| !sameKiroIdeAgentId(v2[0].agentId, v3[0].agentId)
|
||||
|| !sameKiroIdePath(v2[0].guardPath, v3[0].guardPath)
|
||||
|| !sameKiroIdePath(v2[0].auditPath, v3[0].auditPath)) return undefined;
|
||||
return v2[0];
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import path from 'node:path';
|
||||
import type { InstallConfig } from './base.js';
|
||||
import {
|
||||
AGENT_KEY,
|
||||
AUDIT_SCRIPT,
|
||||
GUARD_SCRIPT,
|
||||
type RenderedKiroCliV2Document,
|
||||
} from './kirocli-contract.js';
|
||||
import type { KiroCliSources } from './kirocli-io.js';
|
||||
import type { RenderedKiroIdeDocument } from './kiroide-contract.js';
|
||||
import {
|
||||
commitManagedInstallation,
|
||||
preflightManagedInstallation,
|
||||
prepareManagedInstallation,
|
||||
type ManagedRuntimePaths,
|
||||
type PreparedManagedInstallation,
|
||||
type RenameFile,
|
||||
} from './managed-installation.js';
|
||||
import {
|
||||
commitManagedTransaction,
|
||||
prepareManagedFileChange,
|
||||
type ManagedFileChange,
|
||||
type PreparedManagedTransaction,
|
||||
} from './managed-transaction.js';
|
||||
|
||||
const DISPLAY_NAME = 'Kiro CLI';
|
||||
const V2_DIRECTORY_LABEL = 'Kiro CLI agents directory';
|
||||
const V3_DIRECTORY_LABEL = 'Kiro CLI global hooks directory';
|
||||
|
||||
export type KiroCliRuntimePaths = ManagedRuntimePaths;
|
||||
export type PreparedKiroCliInstallation = PreparedManagedInstallation;
|
||||
export type { RenameFile };
|
||||
|
||||
function hookLocations(sources: KiroCliSources) {
|
||||
return [
|
||||
{ directoryLabel: V2_DIRECTORY_LABEL, filePath: sources.paths.v2Path },
|
||||
{ directoryLabel: V3_DIRECTORY_LABEL, filePath: sources.paths.v3Path },
|
||||
];
|
||||
}
|
||||
|
||||
export async function preflightKiroCliInstallation(
|
||||
config: InstallConfig,
|
||||
sources: KiroCliSources,
|
||||
): Promise<KiroCliRuntimePaths> {
|
||||
return preflightManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
hookLocations: hookLocations(sources),
|
||||
config,
|
||||
}, GUARD_SCRIPT, AUDIT_SCRIPT);
|
||||
}
|
||||
|
||||
export async function prepareKiroCliInstallation(
|
||||
config: InstallConfig,
|
||||
sources: KiroCliSources,
|
||||
v2: RenderedKiroCliV2Document,
|
||||
v3: RenderedKiroIdeDocument,
|
||||
): Promise<PreparedKiroCliInstallation> {
|
||||
if (v2.next === undefined || v3.next === undefined) {
|
||||
throw new Error('Kiro CLI installation requires both v2 and v3 hook documents');
|
||||
}
|
||||
return prepareManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
displayName: DISPLAY_NAME,
|
||||
hookSources: [
|
||||
{
|
||||
directoryLabel: V2_DIRECTORY_LABEL,
|
||||
label: 'Kiro CLI v2 agent config',
|
||||
filePath: sources.paths.v2Path,
|
||||
expectedSource: sources.v2.raw,
|
||||
source: v2.next,
|
||||
},
|
||||
{
|
||||
directoryLabel: V3_DIRECTORY_LABEL,
|
||||
label: 'Kiro CLI v3 global hooks',
|
||||
filePath: sources.paths.v3Path,
|
||||
expectedSource: sources.v3.raw,
|
||||
source: v3.next,
|
||||
},
|
||||
],
|
||||
config,
|
||||
auditOptions: { nativePayload: true },
|
||||
}, GUARD_SCRIPT, AUDIT_SCRIPT);
|
||||
}
|
||||
|
||||
export async function commitKiroCliInstallation(
|
||||
prepared: PreparedKiroCliInstallation,
|
||||
renameFile?: RenameFile,
|
||||
): Promise<void> {
|
||||
await commitManagedInstallation(prepared, renameFile);
|
||||
}
|
||||
|
||||
export async function prepareKiroCliUninstall(
|
||||
sources: KiroCliSources,
|
||||
v2: RenderedKiroCliV2Document,
|
||||
v3: RenderedKiroIdeDocument,
|
||||
): Promise<PreparedManagedTransaction> {
|
||||
const changes: ManagedFileChange[] = [];
|
||||
const directories = [];
|
||||
for (const item of [
|
||||
{ rendered: v2, label: 'Kiro CLI v2 agent config', directoryLabel: V2_DIRECTORY_LABEL },
|
||||
{ rendered: v3, label: 'Kiro CLI v3 global hooks', directoryLabel: V3_DIRECTORY_LABEL },
|
||||
]) {
|
||||
if (!item.rendered.changed) continue;
|
||||
const change = await prepareManagedFileChange({
|
||||
filePath: item.rendered.document.filePath,
|
||||
label: item.label,
|
||||
next: item.rendered.next,
|
||||
mode: 0o600,
|
||||
expectedSource: item.rendered.document.raw,
|
||||
verifyExpectedSource: true,
|
||||
});
|
||||
if (!change) continue;
|
||||
changes.push(change);
|
||||
directories.push({
|
||||
path: path.dirname(item.rendered.document.filePath),
|
||||
label: item.directoryLabel,
|
||||
});
|
||||
}
|
||||
return { displayName: DISPLAY_NAME, operation: 'uninstall', directories, changes };
|
||||
}
|
||||
|
||||
export async function commitKiroCliUninstall(
|
||||
prepared: PreparedManagedTransaction,
|
||||
renameFile?: RenameFile,
|
||||
): Promise<void> {
|
||||
await commitManagedTransaction(prepared, renameFile);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import {
|
||||
AGENT_KEY,
|
||||
createKiroCliV2Document,
|
||||
parseKiroCliV2Document,
|
||||
resolveKiroCliPaths,
|
||||
type KiroCliPaths,
|
||||
type KiroCliV2Document,
|
||||
} from './kirocli-contract.js';
|
||||
import {
|
||||
createKiroIdeDocument,
|
||||
parseKiroIdeDocument,
|
||||
type KiroIdeDocument,
|
||||
type KiroIdeRuntimeContract,
|
||||
} from './kiroide-contract.js';
|
||||
import { runtimeFilesExist } from './kiroide-io.js';
|
||||
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
|
||||
|
||||
const MAX_HOOK_BYTES = 512 * 1024;
|
||||
|
||||
export interface KiroCliSources {
|
||||
readonly paths: KiroCliPaths;
|
||||
readonly v2: KiroCliV2Document;
|
||||
readonly v3: KiroIdeDocument;
|
||||
}
|
||||
|
||||
async function inspectKiroCliDirectories(paths: KiroCliPaths): Promise<void> {
|
||||
await inspectPhysicalDirectory(paths.homeDirectory, 'Kiro CLI home directory');
|
||||
await inspectPhysicalDirectory(paths.kiroDirectory, 'Kiro CLI configuration directory');
|
||||
await Promise.all([
|
||||
inspectPhysicalDirectory(paths.agentsDirectory, 'Kiro CLI agents directory'),
|
||||
inspectPhysicalDirectory(paths.hooksDirectory, 'Kiro CLI hooks directory'),
|
||||
]);
|
||||
}
|
||||
|
||||
async function readV2Document(paths: KiroCliPaths): Promise<KiroCliV2Document> {
|
||||
const snapshot = await readPhysicalFile(
|
||||
paths.v2Path,
|
||||
'Kiro CLI v2 agent config',
|
||||
MAX_HOOK_BYTES,
|
||||
);
|
||||
return snapshot
|
||||
? parseKiroCliV2Document(paths.v2Path, snapshot.contents)
|
||||
: createKiroCliV2Document(paths.v2Path);
|
||||
}
|
||||
|
||||
async function readV3Document(paths: KiroCliPaths): Promise<KiroIdeDocument> {
|
||||
const snapshot = await readPhysicalFile(
|
||||
paths.v3Path,
|
||||
'Kiro CLI v3 global hooks',
|
||||
MAX_HOOK_BYTES,
|
||||
);
|
||||
return snapshot
|
||||
? parseKiroIdeDocument(paths.v3Path, snapshot.contents, 'Kiro CLI v3 global hooks')
|
||||
: createKiroIdeDocument(paths.v3Path);
|
||||
}
|
||||
|
||||
export async function readKiroCliSources(): Promise<KiroCliSources> {
|
||||
const paths = resolveKiroCliPaths();
|
||||
await inspectKiroCliDirectories(paths);
|
||||
const [v2, v3] = await Promise.all([readV2Document(paths), readV3Document(paths)]);
|
||||
return { paths, v2, v3 };
|
||||
}
|
||||
|
||||
export async function kiroCliRuntimeFilesExist(
|
||||
contract: KiroIdeRuntimeContract,
|
||||
): Promise<boolean> {
|
||||
return runtimeFilesExist(contract, AGENT_KEY);
|
||||
}
|
||||
+73
-335
@@ -1,359 +1,97 @@
|
||||
import fsp 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,
|
||||
buildKiroCliV2Hooks,
|
||||
buildKiroCliV3Hooks,
|
||||
commonKiroCliRuntimeContract,
|
||||
renderKiroCliV2Installation,
|
||||
renderKiroCliV2Uninstall,
|
||||
renderKiroCliV3Uninstall,
|
||||
requireAvailableKiroCliV2Document,
|
||||
requireAvailableKiroCliV3Hooks,
|
||||
withoutManagedKiroCliV2Hooks,
|
||||
withoutManagedKiroCliV3Hooks,
|
||||
} from './kirocli-contract.js';
|
||||
import {
|
||||
commitKiroCliInstallation,
|
||||
commitKiroCliUninstall,
|
||||
preflightKiroCliInstallation,
|
||||
prepareKiroCliInstallation,
|
||||
prepareKiroCliUninstall,
|
||||
} from './kirocli-installation.js';
|
||||
import { kiroCliRuntimeFilesExist, readKiroCliSources } from './kirocli-io.js';
|
||||
import { renderKiroIdeDocument } from './kiroide-contract.js';
|
||||
import { SUPPORTED_AGENTS } from './registry.js';
|
||||
|
||||
const AGENT_KEY = 'kirocli';
|
||||
const V2_AGENT_NAME = 'elydora-audit';
|
||||
const V2_DESCRIPTION = 'Kiro CLI with Elydora audit and freeze enforcement';
|
||||
const V3_GUARD_NAME = 'elydora-guard';
|
||||
const V3_AUDIT_NAME = 'elydora-audit';
|
||||
const entry = SUPPORTED_AGENTS.get(AGENT_KEY)!;
|
||||
|
||||
type JsonObject = Record<string, unknown>;
|
||||
|
||||
interface HookContract {
|
||||
readonly guard: string;
|
||||
readonly audit: string;
|
||||
readonly configPath: string;
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is JsonObject {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function resolveV2Path(): string {
|
||||
return path.join(os.homedir(), '.kiro', 'agents', `${V2_AGENT_NAME}.json`);
|
||||
}
|
||||
|
||||
function resolveV3Path(): string {
|
||||
const configDir = entry.configDir.replace(/^~/, os.homedir());
|
||||
return path.join(configDir, 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)}`;
|
||||
}
|
||||
|
||||
async function readJsonFile(configPath: string, label: string): Promise<JsonObject | undefined> {
|
||||
let raw: string;
|
||||
try {
|
||||
raw = await fsp.readFile(configPath, 'utf-8');
|
||||
} catch (error) {
|
||||
if (isObject(error) && error.code === 'ENOENT') return undefined;
|
||||
throw new Error(`Read ${label}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(raw);
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to parse ${label}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
if (!isObject(value)) throw new Error(`${label} must contain a JSON object`);
|
||||
return value;
|
||||
}
|
||||
|
||||
async function writeJsonFile(configPath: string, value: JsonObject, label: string): Promise<void> {
|
||||
await fsp.mkdir(path.dirname(configPath), { recursive: true });
|
||||
const tempPath = `${configPath}.${process.pid}.${Date.now()}.tmp`;
|
||||
try {
|
||||
await fsp.writeFile(tempPath, JSON.stringify(value, null, 2) + '\n', {
|
||||
encoding: 'utf-8',
|
||||
mode: 0o600,
|
||||
});
|
||||
await fsp.rename(tempPath, configPath);
|
||||
} catch (error) {
|
||||
await fsp.unlink(tempPath).catch(() => undefined);
|
||||
throw new Error(`Write ${label}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function removeFile(configPath: string, label: string): Promise<void> {
|
||||
try {
|
||||
await fsp.unlink(configPath);
|
||||
} catch (error) {
|
||||
if (isObject(error) && error.code === 'ENOENT') return;
|
||||
throw new Error(`Remove ${label}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
function hooksObject(settings: JsonObject, label: string): JsonObject {
|
||||
if (settings.hooks === undefined) return {};
|
||||
if (!isObject(settings.hooks)) throw new Error(`${label} field "hooks" must be an object`);
|
||||
return { ...settings.hooks };
|
||||
}
|
||||
|
||||
function hookEntries(hooks: JsonObject, event: string, label: string): JsonObject[] {
|
||||
const value = hooks[event];
|
||||
if (value === undefined) return [];
|
||||
if (!Array.isArray(value) || !value.every(isObject)) {
|
||||
throw new Error(`${label} field "hooks.${event}" must be an array of objects`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function isManagedCommand(command: unknown, scriptName: string, agentId?: string): command is string {
|
||||
if (typeof command !== 'string') return false;
|
||||
const normalized = command.toLowerCase();
|
||||
if (!normalized.includes('.elydora') || !normalized.includes(scriptName)) return false;
|
||||
return !agentId || command.includes(agentId);
|
||||
}
|
||||
|
||||
function withoutV2Hooks(entries: JsonObject[], agentId?: string): JsonObject[] {
|
||||
return entries.filter(
|
||||
(hook) => !isManagedCommand(hook.command, 'guard.js', agentId)
|
||||
&& !isManagedCommand(hook.command, 'hook.js', agentId),
|
||||
);
|
||||
}
|
||||
|
||||
function buildV2Hook(scriptPath: string): JsonObject {
|
||||
return {
|
||||
matcher: '*',
|
||||
command: buildCommand(scriptPath),
|
||||
timeout_ms: 5000,
|
||||
};
|
||||
}
|
||||
|
||||
function isOwnedV2Config(settings: JsonObject, hooks: JsonObject): boolean {
|
||||
const configKeys = new Set(['name', 'description', 'tools', 'includeMcpJson', 'hooks']);
|
||||
const hookKeys = new Set(['preToolUse', 'postToolUse']);
|
||||
return Object.keys(settings).every((key) => configKeys.has(key))
|
||||
&& settings.name === V2_AGENT_NAME
|
||||
&& settings.description === V2_DESCRIPTION
|
||||
&& Array.isArray(settings.tools)
|
||||
&& settings.tools.length === 1
|
||||
&& settings.tools[0] === '*'
|
||||
&& settings.includeMcpJson === true
|
||||
&& Object.keys(hooks).every((key) => hookKeys.has(key))
|
||||
&& Object.values(hooks).every((value) => Array.isArray(value) && value.length === 0);
|
||||
}
|
||||
|
||||
function v3Hooks(settings: JsonObject): JsonObject[] {
|
||||
if (settings.version !== undefined && settings.version !== 'v1') {
|
||||
throw new Error('Kiro CLI v3 hooks config field "version" must be "v1"');
|
||||
}
|
||||
if (settings.hooks === undefined) return [];
|
||||
if (!Array.isArray(settings.hooks) || !settings.hooks.every(isObject)) {
|
||||
throw new Error('Kiro CLI v3 hooks config field "hooks" must be an array of objects');
|
||||
}
|
||||
return settings.hooks;
|
||||
}
|
||||
|
||||
function v3ActionCommand(hook: JsonObject): unknown {
|
||||
return isObject(hook.action) ? hook.action.command : undefined;
|
||||
}
|
||||
|
||||
function isManagedV3Hook(hook: JsonObject, agentId?: string): boolean {
|
||||
if (hook.name === V3_GUARD_NAME) {
|
||||
return isManagedCommand(v3ActionCommand(hook), 'guard.js', agentId);
|
||||
}
|
||||
if (hook.name === V3_AUDIT_NAME) {
|
||||
return isManagedCommand(v3ActionCommand(hook), 'hook.js', agentId);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function buildV3Hook(
|
||||
name: string,
|
||||
description: string,
|
||||
trigger: 'PreToolUse' | 'PostToolUse',
|
||||
scriptPath: string,
|
||||
): JsonObject {
|
||||
return {
|
||||
name,
|
||||
description,
|
||||
trigger,
|
||||
matcher: '.*',
|
||||
action: { type: 'command', command: buildCommand(scriptPath) },
|
||||
timeout: 5,
|
||||
enabled: true,
|
||||
};
|
||||
}
|
||||
|
||||
function findV2Command(entries: JsonObject[], scriptName: string): string | undefined {
|
||||
return entries.find((hook) => isManagedCommand(hook.command, scriptName))?.command as string | undefined;
|
||||
}
|
||||
|
||||
function findV3Command(entries: JsonObject[], name: string, scriptName: string): string | undefined {
|
||||
const hook = entries.find(
|
||||
(candidate) => candidate.name === name && isManagedCommand(v3ActionCommand(candidate), scriptName),
|
||||
);
|
||||
return hook ? v3ActionCommand(hook) as string : undefined;
|
||||
}
|
||||
|
||||
async function runtimeScriptsExist(contracts: HookContract[]): 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 (isObject(error) && error.code === 'ENOENT') return false;
|
||||
throw new Error(`Read Elydora runtime directory: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
|
||||
for (const directory of entries) {
|
||||
if (!directory.isDirectory()) continue;
|
||||
const agentDir = path.join(root, directory.name);
|
||||
const guardPath = path.join(agentDir, 'guard.js');
|
||||
const hookPath = path.join(agentDir, 'hook.js');
|
||||
const referencesScripts = contracts.some(
|
||||
({ guard, audit }) => guard.includes(guardPath) && audit.includes(hookPath),
|
||||
);
|
||||
if (!referencesScripts) continue;
|
||||
|
||||
const configPath = path.join(agentDir, 'config.json');
|
||||
const config = await readJsonFile(configPath, `Elydora runtime config at ${configPath}`);
|
||||
if (!config || config.agent_name !== AGENT_KEY) continue;
|
||||
|
||||
for (const [scriptPath, label] of [
|
||||
[guardPath, 'Elydora guard runtime'],
|
||||
[hookPath, 'Elydora audit runtime'],
|
||||
] as const) {
|
||||
try {
|
||||
await fsp.access(scriptPath);
|
||||
} catch (error) {
|
||||
if (isObject(error) && error.code === 'ENOENT') return false;
|
||||
throw new Error(`${label} at ${scriptPath}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
function validateSources(
|
||||
sources: Awaited<ReturnType<typeof readKiroCliSources>>,
|
||||
): void {
|
||||
requireAvailableKiroCliV2Document(sources.v2);
|
||||
requireAvailableKiroCliV3Hooks(sources.v3.hooks);
|
||||
}
|
||||
|
||||
export const kirocliPlugin: AgentPlugin = {
|
||||
managesRuntime: true,
|
||||
|
||||
async preflightInstall(config: InstallConfig): Promise<void> {
|
||||
const sources = await readKiroCliSources();
|
||||
validateSources(sources);
|
||||
await preflightKiroCliInstallation(config, sources);
|
||||
},
|
||||
|
||||
async install(config: InstallConfig): Promise<void> {
|
||||
const v2Path = resolveV2Path();
|
||||
const v3Path = resolveV3Path();
|
||||
const v2Settings = (await readJsonFile(v2Path, 'Kiro CLI v2 agent config')) ?? {};
|
||||
const v3Settings = (await readJsonFile(v3Path, 'Kiro CLI v3 hooks config')) ?? {};
|
||||
const v2Hooks = hooksObject(v2Settings, 'Kiro CLI v2 agent config');
|
||||
const currentV3Hooks = v3Hooks(v3Settings);
|
||||
|
||||
v2Hooks.preToolUse = [
|
||||
...withoutV2Hooks(hookEntries(v2Hooks, 'preToolUse', 'Kiro CLI v2 agent config')),
|
||||
buildV2Hook(config.guardScriptPath),
|
||||
];
|
||||
v2Hooks.postToolUse = [
|
||||
...withoutV2Hooks(hookEntries(v2Hooks, 'postToolUse', 'Kiro CLI v2 agent config')),
|
||||
buildV2Hook(config.hookScriptPath),
|
||||
];
|
||||
|
||||
const nextV2Settings: JsonObject = {
|
||||
name: V2_AGENT_NAME,
|
||||
description: V2_DESCRIPTION,
|
||||
tools: ['*'],
|
||||
includeMcpJson: true,
|
||||
...v2Settings,
|
||||
hooks: v2Hooks,
|
||||
};
|
||||
const nextV3Settings: JsonObject = {
|
||||
...v3Settings,
|
||||
version: 'v1',
|
||||
hooks: [
|
||||
...currentV3Hooks.filter((hook) => !isManagedV3Hook(hook)),
|
||||
buildV3Hook(
|
||||
V3_GUARD_NAME,
|
||||
'Block tool use when the Elydora agent is frozen',
|
||||
'PreToolUse',
|
||||
config.guardScriptPath,
|
||||
),
|
||||
buildV3Hook(
|
||||
V3_AUDIT_NAME,
|
||||
'Record tool use in the Elydora audit trail',
|
||||
'PostToolUse',
|
||||
config.hookScriptPath,
|
||||
),
|
||||
],
|
||||
};
|
||||
|
||||
await writeJsonFile(v2Path, nextV2Settings, 'Kiro CLI v2 agent config');
|
||||
await writeJsonFile(v3Path, nextV3Settings, 'Kiro CLI v3 hooks config');
|
||||
console.log(' Kiro CLI v2: start with "kiro-cli --agent elydora-audit".');
|
||||
console.log(' Kiro CLI v3: start with "kiro-cli --v3"; global hooks load automatically.');
|
||||
const sources = await readKiroCliSources();
|
||||
validateSources(sources);
|
||||
const paths = await preflightKiroCliInstallation(config, sources);
|
||||
const v2 = renderKiroCliV2Installation(
|
||||
sources.v2,
|
||||
buildKiroCliV2Hooks(sources.v2, paths.guardPath, paths.auditPath),
|
||||
);
|
||||
const v3 = renderKiroIdeDocument(
|
||||
sources.v3,
|
||||
buildKiroCliV3Hooks(sources.v3.hooks, paths.guardPath, paths.auditPath),
|
||||
);
|
||||
const prepared = await prepareKiroCliInstallation(config, sources, v2, v3);
|
||||
await commitKiroCliInstallation(prepared);
|
||||
console.log(` Kiro CLI v2 agent: ${sources.paths.v2Path}`);
|
||||
console.log(' Kiro CLI v2 verification: run "kiro-cli agent validate --path <agent-file>".');
|
||||
console.log(' Kiro CLI v2 activation: start with "kiro-cli --agent elydora-audit".');
|
||||
console.log(` Kiro CLI v3 global hooks (2.13.0+): ${sources.paths.v3Path}`);
|
||||
console.log(' Kiro CLI v3 activation: start the TUI with "kiro-cli --v3".');
|
||||
},
|
||||
|
||||
async uninstall(agentId?: string): Promise<void> {
|
||||
const v2Path = resolveV2Path();
|
||||
const v3Path = resolveV3Path();
|
||||
const v2Settings = await readJsonFile(v2Path, 'Kiro CLI v2 agent config');
|
||||
const v3Settings = await readJsonFile(v3Path, 'Kiro CLI v3 hooks config');
|
||||
|
||||
if (v2Settings) {
|
||||
const hooks = hooksObject(v2Settings, 'Kiro CLI v2 agent config');
|
||||
hooks.preToolUse = withoutV2Hooks(
|
||||
hookEntries(hooks, 'preToolUse', 'Kiro CLI v2 agent config'),
|
||||
agentId,
|
||||
);
|
||||
hooks.postToolUse = withoutV2Hooks(
|
||||
hookEntries(hooks, 'postToolUse', 'Kiro CLI v2 agent config'),
|
||||
agentId,
|
||||
);
|
||||
if (isOwnedV2Config(v2Settings, hooks)) {
|
||||
await removeFile(v2Path, 'Kiro CLI v2 agent config');
|
||||
} else {
|
||||
await writeJsonFile(v2Path, { ...v2Settings, hooks }, 'Kiro CLI v2 agent config');
|
||||
}
|
||||
}
|
||||
|
||||
if (v3Settings) {
|
||||
const hooks = v3Hooks(v3Settings).filter((hook) => !isManagedV3Hook(hook, agentId));
|
||||
const owned = Object.keys(v3Settings).every((key) => key === 'version' || key === 'hooks');
|
||||
if (owned && hooks.length === 0) {
|
||||
await removeFile(v3Path, 'Kiro CLI v3 hooks config');
|
||||
} else {
|
||||
await writeJsonFile(v3Path, { ...v3Settings, hooks }, 'Kiro CLI v3 hooks config');
|
||||
}
|
||||
}
|
||||
const sources = await readKiroCliSources();
|
||||
const v2 = renderKiroCliV2Uninstall(
|
||||
sources.v2,
|
||||
withoutManagedKiroCliV2Hooks(sources.v2, agentId),
|
||||
agentId,
|
||||
);
|
||||
const v3 = renderKiroCliV3Uninstall(
|
||||
sources.v3,
|
||||
withoutManagedKiroCliV3Hooks(sources.v3.hooks, agentId),
|
||||
agentId,
|
||||
);
|
||||
const prepared = await prepareKiroCliUninstall(sources, v2, v3);
|
||||
await commitKiroCliUninstall(prepared);
|
||||
},
|
||||
|
||||
async status(): Promise<PluginStatus> {
|
||||
const v2Path = resolveV2Path();
|
||||
const v3Path = resolveV3Path();
|
||||
const v2Settings = await readJsonFile(v2Path, 'Kiro CLI v2 agent config');
|
||||
const v3Settings = await readJsonFile(v3Path, 'Kiro CLI v3 hooks config');
|
||||
const contracts: HookContract[] = [];
|
||||
|
||||
if (v2Settings) {
|
||||
const hooks = hooksObject(v2Settings, 'Kiro CLI v2 agent config');
|
||||
const guard = findV2Command(
|
||||
hookEntries(hooks, 'preToolUse', 'Kiro CLI v2 agent config'),
|
||||
'guard.js',
|
||||
);
|
||||
const audit = findV2Command(
|
||||
hookEntries(hooks, 'postToolUse', 'Kiro CLI v2 agent config'),
|
||||
'hook.js',
|
||||
);
|
||||
if (guard && audit) contracts.push({ guard, audit, configPath: v2Path });
|
||||
}
|
||||
|
||||
if (v3Settings) {
|
||||
const hooks = v3Hooks(v3Settings);
|
||||
const guard = findV3Command(hooks, V3_GUARD_NAME, 'guard.js');
|
||||
const audit = findV3Command(hooks, V3_AUDIT_NAME, 'hook.js');
|
||||
if (guard && audit) contracts.push({ guard, audit, configPath: v3Path });
|
||||
}
|
||||
|
||||
const hookConfigured = contracts.length > 0;
|
||||
const hookScriptExists = hookConfigured ? await runtimeScriptsExist(contracts) : false;
|
||||
const sources = await readKiroCliSources();
|
||||
validateSources(sources);
|
||||
const contract = commonKiroCliRuntimeContract(sources.v2, sources.v3.hooks);
|
||||
const hookConfigured = contract !== undefined;
|
||||
const hookScriptExists = contract !== undefined
|
||||
&& await kiroCliRuntimeFilesExist(contract);
|
||||
return {
|
||||
installed: hookConfigured && hookScriptExists,
|
||||
agentName: AGENT_KEY,
|
||||
displayName: entry.name,
|
||||
hookConfigured,
|
||||
hookScriptExists,
|
||||
configPath: contracts.at(-1)?.configPath ?? v3Path,
|
||||
configPath: sources.paths.v3Path,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -110,8 +110,8 @@ function validateAction(value: unknown, label: string): KiroIdeAction {
|
||||
throw new Error(`${label} action has unsupported type "${String(value.type)}"`);
|
||||
}
|
||||
|
||||
function validateHook(value: unknown, index: number): KiroIdeHook {
|
||||
const label = `Kiro IDE hook hooks[${index}]`;
|
||||
function validateHook(value: unknown, index: number, documentLabel: string): KiroIdeHook {
|
||||
const label = `${documentLabel} hooks[${index}]`;
|
||||
if (!isObject(value)) throw new Error(`${label} must be an object`);
|
||||
if (typeof value.name !== 'string' || !value.name) throw new Error(`${label} requires a name`);
|
||||
if (typeof value.trigger !== 'string' || !KIRO_TRIGGERS.has(value.trigger)) {
|
||||
@@ -133,15 +133,19 @@ function validateHook(value: unknown, index: number): KiroIdeHook {
|
||||
return { ...value, action: validateAction(value.action, label) } as KiroIdeHook;
|
||||
}
|
||||
|
||||
export function parseKiroIdeDocument(filePath: string, raw: string): KiroIdeDocument {
|
||||
const root = parseStrictJsonObject(raw, `Kiro IDE hooks at ${filePath}`);
|
||||
if (root.version !== 'v1') throw new Error(`Kiro IDE hooks version must be "v1": ${filePath}`);
|
||||
if (!Array.isArray(root.hooks)) throw new Error(`Kiro IDE hooks field "hooks" must be an array: ${filePath}`);
|
||||
export function parseKiroIdeDocument(
|
||||
filePath: string,
|
||||
raw: string,
|
||||
documentLabel = 'Kiro IDE hooks',
|
||||
): KiroIdeDocument {
|
||||
const root = parseStrictJsonObject(raw, `${documentLabel} at ${filePath}`);
|
||||
if (root.version !== 'v1') throw new Error(`${documentLabel} version must be "v1": ${filePath}`);
|
||||
if (!Array.isArray(root.hooks)) throw new Error(`${documentLabel} field "hooks" must be an array: ${filePath}`);
|
||||
return {
|
||||
exists: true,
|
||||
filePath,
|
||||
root,
|
||||
hooks: root.hooks.map((hook, index) => validateHook(hook, index)),
|
||||
hooks: root.hooks.map((hook, index) => validateHook(hook, index, documentLabel)),
|
||||
raw,
|
||||
};
|
||||
}
|
||||
@@ -191,10 +195,13 @@ function ownedReference(hook: KiroIdeHook) {
|
||||
return kiroIdeRuntimeReference(hook.action.command, specification.scriptName);
|
||||
}
|
||||
|
||||
export function requireAvailableKiroIdeHooks(hooks: readonly KiroIdeHook[]): void {
|
||||
export function requireAvailableKiroIdeHooks(
|
||||
hooks: readonly KiroIdeHook[],
|
||||
productLabel = 'Kiro IDE',
|
||||
): void {
|
||||
for (const hook of hooks) {
|
||||
if (managedSpecification(hook.name) && !ownedReference(hook)) {
|
||||
throw new Error(`Kiro IDE hook name "${hook.name}" conflicts with the Elydora contract`);
|
||||
throw new Error(`${productLabel} hook name "${hook.name}" conflicts with the Elydora contract`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -237,6 +244,11 @@ export function renderKiroIdeDocument(
|
||||
hooks: readonly KiroIdeHook[],
|
||||
): RenderedKiroIdeDocument {
|
||||
if (!document.exists && hooks.length === 0) return { document, changed: false };
|
||||
if (document.exists
|
||||
&& hooks.length === document.hooks.length
|
||||
&& hooks.every((hook, index) => hook === document.hooks[index])) {
|
||||
return { document, changed: false };
|
||||
}
|
||||
if (hooks.length === 0 && entirelyManaged(document)) return { document, changed: true };
|
||||
const next = `${JSON.stringify({ ...document.root, version: 'v1', hooks }, null, 2)}\n`;
|
||||
return { document, changed: next !== document.raw, next };
|
||||
@@ -248,8 +260,9 @@ export function kiroIdeRuntimeContracts(
|
||||
const guards = new Map<string, KiroIdeRuntimeReference[]>();
|
||||
const audits = new Map<string, KiroIdeRuntimeReference[]>();
|
||||
for (const hook of hooks) {
|
||||
if (!managedSpecification(hook.name)) continue;
|
||||
const reference = managedReference(hook);
|
||||
if (!reference) continue;
|
||||
if (!reference) return [];
|
||||
const key = process.platform === 'win32' ? reference.agentId.toLowerCase() : reference.agentId;
|
||||
const target = hook.name === GUARD_NAME ? guards : audits;
|
||||
const entries = target.get(key) ?? [];
|
||||
|
||||
@@ -95,6 +95,7 @@ function validateRuntimeConfig(
|
||||
config: JsonObject,
|
||||
contract: KiroIdeRuntimeContract,
|
||||
configPath: string,
|
||||
agentKey: 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));
|
||||
@@ -102,8 +103,8 @@ function validateRuntimeConfig(
|
||||
requireString(config.org_id, 'org_id', configPath);
|
||||
requireString(config.kid, 'kid', configPath);
|
||||
const agentId = requireString(config.agent_id, 'agent_id', configPath);
|
||||
if (!sameKiroIdeAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
|
||||
throw new Error(`Elydora runtime identity does not match Kiro IDE hooks: ${configPath}`);
|
||||
if (!sameKiroIdeAgentId(agentId, contract.agentId) || config.agent_name !== agentKey) {
|
||||
throw new Error(`Elydora runtime identity does not match ${agentKey} hooks: ${configPath}`);
|
||||
}
|
||||
if (config.token !== undefined) requireString(config.token, 'token', configPath);
|
||||
const rawBaseUrl = requireString(config.base_url, 'base_url', configPath);
|
||||
@@ -139,7 +140,10 @@ function validContractPaths(contract: KiroIdeRuntimeContract): boolean {
|
||||
&& sameKiroIdePath(contract.auditPath, path.join(agentDirectory, AUDIT_SCRIPT));
|
||||
}
|
||||
|
||||
export async function runtimeFilesExist(contract: KiroIdeRuntimeContract): Promise<boolean> {
|
||||
export async function runtimeFilesExist(
|
||||
contract: KiroIdeRuntimeContract,
|
||||
agentKey = AGENT_KEY,
|
||||
): Promise<boolean> {
|
||||
if (!validContractPaths(contract)) return false;
|
||||
const runtimeRoot = path.join(os.homedir(), '.elydora');
|
||||
const agentDirectory = path.dirname(contract.guardPath);
|
||||
@@ -158,8 +162,9 @@ export async function runtimeFilesExist(contract: KiroIdeRuntimeContract): Promi
|
||||
parseStrictJsonObject(config.contents, `Elydora runtime config at ${configPath}`),
|
||||
contract,
|
||||
configPath,
|
||||
agentKey,
|
||||
);
|
||||
validatePrivateKey(key.contents, keyPath);
|
||||
return guard.contents === generateGuardScript(AGENT_KEY, contract.agentId)
|
||||
&& audit.contents === generateHookScript(AGENT_KEY, contract.agentId, { nativePayload: true });
|
||||
return guard.contents === generateGuardScript(agentKey, contract.agentId)
|
||||
&& audit.contents === generateHookScript(agentKey, contract.agentId, { nativePayload: true });
|
||||
}
|
||||
@@ -60,7 +60,7 @@ export const kiroidePlugin: AgentPlugin = {
|
||||
const contracts = kiroIdeRuntimeContracts(sources.document.hooks);
|
||||
const hookConfigured = contracts.length > 0;
|
||||
const hookScriptExists = hookConfigured
|
||||
&& (await Promise.all(contracts.map(runtimeFilesExist))).every(Boolean);
|
||||
&& (await Promise.all(contracts.map((contract) => runtimeFilesExist(contract)))).every(Boolean);
|
||||
return {
|
||||
installed: hookConfigured && hookScriptExists,
|
||||
agentName: AGENT_KEY,
|
||||
|
||||
Reference in new issue
Block a user