5 Commits
Author SHA1 Message Date
雷电芽衣 eb95173015 chore(node-sdk): release 2.1.0
Claude-Session: https://claude.ai/code/session_01Agoc9bRVE9KL7mmWtey9Vq
2026-09-02 22:34:34 -04:00
雷电芽衣 9e1c0d9eb0 docs(node-sdk): audit package metadata, README, AGENTS
Drop the redundant .npmignore and publish dist only; README lists every client method and the real default key id; AGENTS.md records the shared plugin and test modules.

Claude-Session: https://claude.ai/code/session_01Agoc9bRVE9KL7mmWtey9Vq
2026-09-02 22:34:30 -04:00
雷电芽衣 90bea63eea chore(node-sdk): audit test-support and test
test-support/harness.mjs owns process, server, JSON, fixture, and plugin-runner helpers; provider helper files keep their APIs as thin wrappers. Guard fixtures write 0600 files and the CLI security test isolates XDG_CONFIG_HOME, so the suite passes on Linux.

Claude-Session: https://claude.ai/code/session_01Agoc9bRVE9KL7mmWtey9Vq
2026-09-02 22:22:45 -04:00
雷电芽衣 25bfa39fcf chore(node-sdk): audit providers kirocli kiroide opencode
Kiro and OpenCode files use common.ts, shell-command.ts, and managedScriptReference; exactKeys shared from kiroide-contract.

Claude-Session: https://claude.ai/code/session_01Agoc9bRVE9KL7mmWtey9Vq
2026-09-02 22:10:57 -04:00
雷电芽衣 3b5cbd6e17 chore(node-sdk): audit providers kimi grok qwen letta
Command files use shell-command and managedScriptReference; runtime checks use managed-runtime-status; jsonc-edit.ts and parseCommentedJsonObject replace copied JSONC helpers.

Claude-Session: https://claude.ai/code/session_01Agoc9bRVE9KL7mmWtey9Vq
2026-09-02 22:07:30 -04:00
56 changed files with 1088 additions and 3443 deletions

No files matched your search

-5
View File
@@ -1,5 +0,0 @@
src/
tsconfig.json
.gitignore
node_modules/
*.tsbuildinfo
+10
View File
@@ -51,6 +51,16 @@ This repository owns the published `@elydora/sdk` package, its `elydora` CLI, lo
- Read runtime config, private keys, status cache, chain state, and error logs through physical-file descriptors with identity checks. Write cache and validated chain state atomically, and append error logs through no-follow owner-only descriptors. Preserve rollback artifacts when recovery cannot safely restore an original file and include the recovery path in the surfaced error. - Read runtime config, private keys, status cache, chain state, and error logs through physical-file descriptors with identity checks. Write cache and validated chain state atomically, and append error logs through no-follow owner-only descriptors. Preserve rollback artifacts when recovery cannot safely restore an original file and include the recovery path in the surfaced error.
- Resolve every agent runtime directory as one physical child of `~/.elydora`; reject separators, traversal segments, cross-platform reserved names, symbolic-link directories, and linked identity configs before writes or recursive removal. Validate stored directory identity before changing host CLI configuration, and require an explicit agent ID when discovery is ambiguous. - Resolve every agent runtime directory as one physical child of `~/.elydora`; reject separators, traversal segments, cross-platform reserved names, symbolic-link directories, and linked identity configs before writes or recursive removal. Validate stored directory identity before changing host CLI configuration, and require an explicit agent ID when discovery is ambiguous.
## Shared Modules
- `src/plugins/common.ts`: path and agent-id comparison, error helpers, size limits, `managedScriptReference`.
- `src/plugins/shell-command.ts`: POSIX and PowerShell quoting, encoded Windows commands, command parsers, `isNodeExecutable`.
- `src/plugins/managed-installation.ts` and `managed-transaction.ts`: preflight, prepare, and rollback-capable commit.
- `src/plugins/managed-runtime-status.ts`: runtime config and key validation; `managedRuntimeFilesExist` and `managedRuntimePresent`.
- `src/plugins/strict-json.ts` and `jsonc-edit.ts`: strict parsing and formatting-preserving JSONC edits.
- `test-support/harness.mjs`: process runner, fake API server, fixture root, plugin runner; provider helper files wrap it.
- Put logic used by two providers in a shared module; keep provider-specific rules in `<provider>-*.ts`.
## Verification ## Verification
Run the focused adapter test during development, then execute all release gates before commit: Run the focused adapter test during development, then execute all release gates before commit:
+25 -3
View File
@@ -124,7 +124,7 @@ const client = new ElydoraClient({
baseUrl?: string, // API base URL (default: https://api.elydora.com) baseUrl?: string, // API base URL (default: https://api.elydora.com)
ttlMs?: number, // Operation TTL in ms (default: 30000) ttlMs?: number, // Operation TTL in ms (default: 30000)
maxRetries?: number, // Max retries on transient failures (default: 3) maxRetries?: number, // Max retries on transient failures (default: 3)
kid?: string, // Key ID (default: {agentId}-key-v1) kid?: string, // Key ID (default: {agentId}-key-1)
}); });
``` ```
@@ -143,8 +143,13 @@ client.setToken(auth.token);
// Get current authenticated user profile // Get current authenticated user profile
const { user } = await client.getMe(); const { user } = await client.getMe();
// Issue a new API token (with optional TTL in seconds) // Issue an API token (optional TTL in seconds) and use it for later calls
const { token, expires_at } = await client.issueApiToken(3600); const { token, expires_at } = await client.issueApiToken(3600);
client.setToken(token);
// Rotate the API token the client currently holds
const rotated = await client.rotateApiToken();
client.setToken(rotated.token);
``` ```
### Operations ### Operations
@@ -183,6 +188,9 @@ const agent = await client.registerAgent({
// Get agent details // Get agent details
const details = await client.getAgent(agentId); const details = await client.getAgent(agentId);
// Change the integration type
await client.updateAgent(agentId, 'cursor');
// Freeze an agent // Freeze an agent
await client.freezeAgent(agentId, 'security review'); await client.freezeAgent(agentId, 'security review');
@@ -245,7 +253,21 @@ const { keys } = await client.getJWKS();
```typescript ```typescript
// Check API health (no authentication required) // Check API health (no authentication required)
const health = await client.health(); const health = await client.health();
// health.status, health.version, health.protocol_version, health.timestamp // health.status, health.version, health.protocol_version, health.capabilities, health.timestamp
// Check dependency health (D1, auth storage, R2, KV)
const deep = await client.deepHealth();
```
### Webhooks, Members, Admin Events
```typescript
const { webhooks } = await client.listWebhooks();
const { webhook } = await client.registerWebhook(url, ['agent.status_changed'], secret);
await client.deleteWebhook(webhook.webhook_id);
const { members } = await client.listMembers();
const { events } = await client.listAdminEvents(50);
``` ```
### Client State ### Client State
+2 -3
View File
@@ -1,6 +1,6 @@
{ {
"name": "@elydora/sdk", "name": "@elydora/sdk",
"version": "2.0.1", "version": "2.1.0",
"description": "Node.js/TypeScript SDK for the Elydora tamper-evident audit platform", "description": "Node.js/TypeScript SDK for the Elydora tamper-evident audit platform",
"main": "dist/index.js", "main": "dist/index.js",
"types": "dist/index.d.ts", "types": "dist/index.d.ts",
@@ -8,8 +8,7 @@
"elydora": "dist/cli.js" "elydora": "dist/cli.js"
}, },
"files": [ "files": [
"dist", "dist"
"scripts"
], ],
"scripts": { "scripts": {
"build": "tsc && node scripts/postbuild.mjs", "build": "tsc && node scripts/postbuild.mjs",
+24 -5
View File
@@ -1,3 +1,4 @@
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
export const MAX_SECRET_BYTES = 64 * 1024; export const MAX_SECRET_BYTES = 64 * 1024;
@@ -16,12 +17,13 @@ export function hasCode(error: unknown, code: string): boolean {
return typeof error === 'object' && error !== null && 'code' in error && error.code === code; return typeof error === 'object' && error !== null && 'code' in error && error.code === code;
} }
export function pathKey(filePath: string): string {
const resolved = path.resolve(filePath);
return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
}
export function samePath(left: string, right: string): boolean { export function samePath(left: string, right: string): boolean {
const normalizedLeft = path.resolve(left); return pathKey(left) === pathKey(right);
const normalizedRight = path.resolve(right);
return process.platform === 'win32'
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
: normalizedLeft === normalizedRight;
} }
export function sameAgentId(left: unknown, right: string): boolean { export function sameAgentId(left: unknown, right: string): boolean {
@@ -29,3 +31,20 @@ export function sameAgentId(left: unknown, right: string): boolean {
? left.toLowerCase() === right.toLowerCase() ? left.toLowerCase() === right.toLowerCase()
: left === right); : left === right);
} }
export interface ManagedScriptReference {
readonly agentId: string;
readonly scriptPath: string;
}
// Accepts only ~/.elydora/<agentId>/<scriptName>.
export function managedScriptReference(
scriptPath: string,
scriptName: string,
): ManagedScriptReference | undefined {
if (!path.isAbsolute(scriptPath) || path.basename(scriptPath) !== scriptName) return undefined;
const agentDirectory = path.dirname(scriptPath);
if (!samePath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))) return undefined;
const agentId = path.basename(agentDirectory);
return agentId && agentId !== '.' && agentId !== '..' ? { agentId, scriptPath } : undefined;
}
+7 -28
View File
@@ -1,9 +1,5 @@
import { import type { JSONPath } from 'jsonc-parser';
applyEdits, import { changeJsonc } from './jsonc-edit.js';
modify,
type FormattingOptions,
type JSONPath,
} from 'jsonc-parser';
import type { FileSnapshot } from './managed-files.js'; import type { FileSnapshot } from './managed-files.js';
import type { DroidPolicyState } from './droid-policy.js'; import type { DroidPolicyState } from './droid-policy.js';
import { import {
@@ -158,23 +154,6 @@ function eventPath(document: DroidDocument, event: string): JSONPath {
return [...document.basePath, event]; return [...document.basePath, event];
} }
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, path: JSONPath, value: unknown, isArrayInsertion = false): string {
return applyEdits(raw, modify(raw, path, value, {
formattingOptions: formatting(raw),
isArrayInsertion,
}));
}
function currentDocument(document: DroidDocument, raw: string): DroidDocument { function currentDocument(document: DroidDocument, raw: string): DroidDocument {
return parseDocument({ return parseDocument({
exists: document.exists, exists: document.exists,
@@ -194,17 +173,17 @@ function removeManagedEntries(document: DroidDocument, raw: string, agentId?: st
for (const removal of eventRemovals) { for (const removal of eventRemovals) {
const groupPath = [...eventPath(document, event), removal.groupIndex]; const groupPath = [...eventPath(document, event), removal.groupIndex];
if (removal.removeGroup) { if (removal.removeGroup) {
raw = change(raw, groupPath, undefined); raw = changeJsonc(raw, groupPath, undefined);
continue; continue;
} }
for (const handlerIndex of [...removal.handlerIndexes].sort((left, right) => right - left)) { for (const handlerIndex of [...removal.handlerIndexes].sort((left, right) => right - left)) {
raw = change(raw, [...groupPath, 'hooks', handlerIndex], undefined); raw = changeJsonc(raw, [...groupPath, 'hooks', handlerIndex], undefined);
} }
} }
if (eventRemovals.length > 0) { if (eventRemovals.length > 0) {
const current = currentDocument(document, raw); const current = currentDocument(document, raw);
if ((current.hooks[event] ?? []).length === 0) { if ((current.hooks[event] ?? []).length === 0) {
raw = change(raw, eventPath(document, event), undefined); raw = changeJsonc(raw, eventPath(document, event), undefined);
} }
} }
} }
@@ -220,9 +199,9 @@ function appendGroup(
const current = currentDocument(document, raw); const current = currentDocument(document, raw);
if (Object.prototype.hasOwnProperty.call(current.hooks, event)) { if (Object.prototype.hasOwnProperty.call(current.hooks, event)) {
const groups = current.hooks[event] ?? []; const groups = current.hooks[event] ?? [];
return change(raw, [...eventPath(document, event), groups.length], group, true); return changeJsonc(raw, [...eventPath(document, event), groups.length], group, true);
} }
return change(raw, eventPath(document, event), [group]); return changeJsonc(raw, eventPath(document, event), [group]);
} }
function hookFileIsEmpty(document: DroidDocument, raw: string): boolean { function hookFileIsEmpty(document: DroidDocument, raw: string): boolean {
+10 -85
View File
@@ -1,14 +1,4 @@
import { import type { JSONPath } from 'jsonc-parser';
applyEdits,
modify,
parse,
parseTree,
printParseErrorCode,
type FormattingOptions,
type JSONPath,
type Node,
type ParseError,
} from 'jsonc-parser';
import { import {
MANAGED_EVENTS, MANAGED_EVENTS,
managedGeminiRemovals, managedGeminiRemovals,
@@ -19,7 +9,8 @@ import {
type GeminiHooks, type GeminiHooks,
type ManagedGeminiEvent, type ManagedGeminiEvent,
} from './gemini-contract.js'; } from './gemini-contract.js';
import { isObject, type JsonObject } from './strict-json.js'; import { changeJsonc } from './jsonc-edit.js';
import { parseCommentedJsonObject, type JsonObject } from './strict-json.js';
export const GEMINI_OWNED_FILE_MARKER = '// Managed by Elydora'; export const GEMINI_OWNED_FILE_MARKER = '// Managed by Elydora';
@@ -46,53 +37,9 @@ interface DocumentOptions {
readonly raw: 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 { export function parseGeminiDocument(options: DocumentOptions): GeminiDocument {
const label = `Gemini CLI user settings at ${options.filePath}`; const label = `Gemini CLI user settings at ${options.filePath}`;
const root = parseJsoncObject(options.raw, label); const root = parseCommentedJsonObject(options.raw, label);
const hasHooksContainer = Object.hasOwn(root, 'hooks'); const hasHooksContainer = Object.hasOwn(root, 'hooks');
return { return {
...options, ...options,
@@ -112,28 +59,6 @@ export function createGeminiDocument(filePath: string): GeminiDocument {
}); });
} }
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 { function currentDocument(document: GeminiDocument, raw: string): GeminiDocument {
return parseGeminiDocument({ return parseGeminiDocument({
exists: document.exists, exists: document.exists,
@@ -155,25 +80,25 @@ function removeManagedEntries(
for (const removal of eventRemovals) { for (const removal of eventRemovals) {
const groupPath: JSONPath = ['hooks', event, removal.groupIndex]; const groupPath: JSONPath = ['hooks', event, removal.groupIndex];
if (removal.removeGroup) { if (removal.removeGroup) {
raw = change(raw, groupPath, undefined); raw = changeJsonc(raw, groupPath, undefined);
continue; continue;
} }
for (const handlerIndex of [...removal.handlerIndexes].sort( for (const handlerIndex of [...removal.handlerIndexes].sort(
(left, right) => right - left, (left, right) => right - left,
)) { )) {
raw = change(raw, [...groupPath, 'hooks', handlerIndex], undefined); raw = changeJsonc(raw, [...groupPath, 'hooks', handlerIndex], undefined);
} }
} }
if (eventRemovals.length > 0) { if (eventRemovals.length > 0) {
const current = currentDocument(document, raw); const current = currentDocument(document, raw);
if ((current.hooks[event] ?? []).length === 0) { if ((current.hooks[event] ?? []).length === 0) {
raw = change(raw, ['hooks', event], undefined); raw = changeJsonc(raw, ['hooks', event], undefined);
} }
} }
} }
const current = currentDocument(document, raw); const current = currentDocument(document, raw);
if (current.hasHooksContainer && Object.keys(current.hooks).length === 0) { if (current.hasHooksContainer && Object.keys(current.hooks).length === 0) {
raw = change(raw, ['hooks'], undefined); raw = changeJsonc(raw, ['hooks'], undefined);
} }
return raw; return raw;
} }
@@ -186,9 +111,9 @@ function appendGroup(
): string { ): string {
const current = currentDocument(document, raw); const current = currentDocument(document, raw);
if (current.hooks[event]) { if (current.hooks[event]) {
return change(raw, ['hooks', event, current.hooks[event].length], group, true); return changeJsonc(raw, ['hooks', event, current.hooks[event].length], group, true);
} }
return change(raw, ['hooks', event], [group]); return changeJsonc(raw, ['hooks', event], [group]);
} }
export function renderGeminiDocument( export function renderGeminiDocument(
+14 -143
View File
@@ -1,140 +1,21 @@
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { managedScriptReference, type ManagedScriptReference } from './common.js';
import {
encodedWindowsCommand,
isNodeExecutable,
parseEncodedWindowsCommand,
parseLegacyWindowsCommand,
parsePosixCommand,
posixSource,
} from './shell-command.js';
interface ParsedArgument { export type GrokRuntimeReference = ManagedScriptReference;
readonly value: string;
readonly next: number;
}
export interface GrokRuntimeReference {
readonly agentId: string;
readonly scriptPath: string;
}
export function sameGrokPath(left: string, right: string): boolean {
const normalizedLeft = path.resolve(left);
const normalizedRight = path.resolve(right);
return process.platform === 'win32'
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
: normalizedLeft === normalizedRight;
}
export function sameGrokAgentId(left: string, right: string): boolean {
return process.platform === 'win32'
? left.toLowerCase() === right.toLowerCase()
: left === right;
}
function quotePosix(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}
function quotePowerShell(value: string): string {
return `'${value.replaceAll("'", "''")}'`;
}
function windowsPowerShellPath(): string {
const configuredRoot = process.platform === 'win32' ? process.env.SystemRoot : undefined;
const systemRoot = configuredRoot
&& path.win32.isAbsolute(configuredRoot)
&& !/["%\r\n]/.test(configuredRoot)
? configuredRoot
: 'C:\\Windows';
return path.win32.join(
systemRoot,
'System32',
'WindowsPowerShell',
'v1.0',
'powershell.exe',
);
}
function windowsCommand(scriptPath: string): string {
const source = `& ${quotePowerShell(process.execPath)} ${quotePowerShell(scriptPath)}; exit $LASTEXITCODE`;
const encoded = Buffer.from(source, 'utf16le').toString('base64');
return `"${windowsPowerShellPath()}" -NoLogo -NoProfile -NonInteractive -EncodedCommand ${encoded}`;
}
export function buildGrokCommand(scriptPath: string): string { export function buildGrokCommand(scriptPath: string): string {
if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) { if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) {
throw new Error('Grok hook commands require absolute executable and script paths'); throw new Error('Grok hook commands require absolute executable and script paths');
} }
return process.platform === 'win32' return process.platform === 'win32' ? encodedWindowsCommand(scriptPath) : posixSource(scriptPath);
? windowsCommand(scriptPath)
: `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`;
}
function readPosixArgument(command: string, start: number): ParsedArgument | undefined {
if (command[start] !== "'") return undefined;
const apostrophe = `'"'"'`;
let value = '';
for (let index = start + 1; index < command.length;) {
if (command.startsWith(apostrophe, index)) {
value += "'";
index += apostrophe.length;
continue;
}
if (command[index] === "'") return { value, next: index + 1 };
value += command[index];
index += 1;
}
return undefined;
}
function parsePosixCommand(command: string): readonly [string, string] | undefined {
const executable = readPosixArgument(command, 0);
if (!executable || command[executable.next] !== ' ') return undefined;
const script = readPosixArgument(command, executable.next + 1);
if (!script || script.next !== command.length) return undefined;
return [executable.value, script.value];
}
function readPowerShellArgument(command: string, start: number): ParsedArgument | undefined {
if (command[start] !== "'") return undefined;
let value = '';
for (let index = start + 1; index < command.length; index += 1) {
if (command[index] !== "'") {
value += command[index];
continue;
}
if (command[index + 1] === "'") {
value += "'";
index += 1;
continue;
}
return { value, next: index + 1 };
}
return undefined;
}
function parsePowerShellSource(source: string): readonly [string, string] | undefined {
if (!source.startsWith('& ')) return undefined;
const executable = readPowerShellArgument(source, 2);
if (!executable || source[executable.next] !== ' ') return undefined;
const script = readPowerShellArgument(source, executable.next + 1);
if (!script || source.slice(script.next) !== '; exit $LASTEXITCODE') return undefined;
return [executable.value, script.value];
}
function parseWindowsCommand(command: string): readonly [string, string] | undefined {
const match = /^"([^"\r\n]+)" -NoLogo -NoProfile -NonInteractive -EncodedCommand ([A-Za-z0-9+/]+={0,2})$/.exec(command);
if (!match
|| !path.win32.isAbsolute(match[1])
|| path.win32.basename(match[1]).toLowerCase() !== 'powershell.exe') return undefined;
const encoded = match[2];
const buffer = Buffer.from(encoded, 'base64');
if (buffer.length % 2 !== 0 || buffer.toString('base64') !== encoded) return undefined;
return parsePowerShellSource(buffer.toString('utf16le'));
}
function parseLegacyWindowsCommand(command: string): readonly [string, string] | undefined {
const match = /^"([^"\r\n]+)" "([^"\r\n]+)"$/.exec(command);
return match ? [match[1], match[2]] : undefined;
}
function isNodeExecutable(filePath: string): boolean {
const basename = path.basename(filePath).toLowerCase();
return basename === 'node' || basename === 'node.exe';
} }
export function grokRuntimeReference( export function grokRuntimeReference(
@@ -142,18 +23,8 @@ export function grokRuntimeReference(
scriptName: string, scriptName: string,
): GrokRuntimeReference | undefined { ): GrokRuntimeReference | undefined {
const parsed = parsePosixCommand(command) const parsed = parsePosixCommand(command)
?? parseWindowsCommand(command) ?? parseEncodedWindowsCommand(command)
?? parseLegacyWindowsCommand(command); ?? parseLegacyWindowsCommand(command);
if (!parsed if (!parsed || !path.isAbsolute(parsed[0]) || !isNodeExecutable(parsed[0])) return undefined;
|| !path.isAbsolute(parsed[0]) return managedScriptReference(parsed[1], scriptName);
|| !path.isAbsolute(parsed[1])
|| !isNodeExecutable(parsed[0])
|| path.basename(parsed[1]) !== scriptName) return undefined;
const agentDirectory = path.dirname(parsed[1]);
if (!sameGrokPath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))) {
return undefined;
}
const agentId = path.basename(agentDirectory);
if (!agentId || agentId === '.' || agentId === '..') return undefined;
return { agentId, scriptPath: parsed[1] };
} }
+6 -2
View File
@@ -1,15 +1,19 @@
import { sameAgentId } from './common.js';
import { import {
buildGrokCommand, buildGrokCommand,
grokRuntimeReference, grokRuntimeReference,
sameGrokAgentId,
type GrokRuntimeReference, type GrokRuntimeReference,
} from './grok-command.js'; } from './grok-command.js';
import type { GuardScriptOptions } from './guard-template.js';
import type { HookScriptOptions } from './hook-template.js';
import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js'; import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js';
export const AGENT_KEY = 'grok'; export const AGENT_KEY = 'grok';
export const GUARD_SCRIPT = 'guard.js'; export const GUARD_SCRIPT = 'guard.js';
export const AUDIT_SCRIPT = 'hook.js'; export const AUDIT_SCRIPT = 'hook.js';
export const HOOK_TIMEOUT_SECONDS = 10; export const HOOK_TIMEOUT_SECONDS = 10;
export const GUARD_OPTIONS: GuardScriptOptions = { denyProtocol: 'grok' };
export const AUDIT_OPTIONS: HookScriptOptions = { nativePayload: true };
const MATCHER_REJECTING_EVENTS = new Set([ const MATCHER_REJECTING_EVENTS = new Set([
'SessionStart', 'SessionStart',
@@ -172,7 +176,7 @@ function removeFromGroups(
const handlers = group.hooks.filter((handler) => { const handlers = group.hooks.filter((handler) => {
const reference = managedReference(handler, scriptName); const reference = managedReference(handler, scriptName);
return !reference return !reference
|| (agentId !== undefined && !sameGrokAgentId(reference.agentId, agentId)); || (agentId !== undefined && !sameAgentId(reference.agentId, agentId));
}); });
if (handlers.length > 0) result.push({ hooks: handlers }); if (handlers.length > 0) result.push({ hooks: handlers });
} }
+7 -9
View File
@@ -2,7 +2,9 @@ import path from 'node:path';
import type { InstallConfig } from './base.js'; import type { InstallConfig } from './base.js';
import { import {
AGENT_KEY, AGENT_KEY,
AUDIT_OPTIONS,
AUDIT_SCRIPT, AUDIT_SCRIPT,
GUARD_OPTIONS,
GUARD_SCRIPT, GUARD_SCRIPT,
type RenderedGrokDocument, type RenderedGrokDocument,
} from './grok-contract.js'; } from './grok-contract.js';
@@ -24,14 +26,10 @@ const DISPLAY_NAME = 'Grok Build';
const HOOKS_DIRECTORY_LABEL = 'Grok hooks directory'; const HOOKS_DIRECTORY_LABEL = 'Grok hooks directory';
const HOOKS_LABEL = 'Grok user hooks'; const HOOKS_LABEL = 'Grok user hooks';
export type GrokRuntimePaths = ManagedRuntimePaths;
export type PreparedGrokInstallation = PreparedManagedInstallation;
export type { RenameFile };
export async function preflightGrokInstallation( export async function preflightGrokInstallation(
config: InstallConfig, config: InstallConfig,
hooksPath: string, hooksPath: string,
): Promise<GrokRuntimePaths> { ): Promise<ManagedRuntimePaths> {
return preflightManagedInstallation({ return preflightManagedInstallation({
agentKey: AGENT_KEY, agentKey: AGENT_KEY,
hookLocations: [{ directoryLabel: HOOKS_DIRECTORY_LABEL, filePath: hooksPath }], hookLocations: [{ directoryLabel: HOOKS_DIRECTORY_LABEL, filePath: hooksPath }],
@@ -42,7 +40,7 @@ export async function preflightGrokInstallation(
export async function prepareGrokInstallation( export async function prepareGrokInstallation(
config: InstallConfig, config: InstallConfig,
rendered: RenderedGrokDocument, rendered: RenderedGrokDocument,
): Promise<PreparedGrokInstallation> { ): Promise<PreparedManagedInstallation> {
const hooksSource = rendered.next ?? rendered.document.raw; const hooksSource = rendered.next ?? rendered.document.raw;
if (hooksSource === undefined) throw new Error('Grok hook configuration is missing'); if (hooksSource === undefined) throw new Error('Grok hook configuration is missing');
const prepared = await prepareManagedInstallation({ const prepared = await prepareManagedInstallation({
@@ -56,8 +54,8 @@ export async function prepareGrokInstallation(
source: hooksSource, source: hooksSource,
}], }],
config, config,
guardOptions: { denyProtocol: 'grok' }, guardOptions: GUARD_OPTIONS,
auditOptions: { nativePayload: true }, auditOptions: AUDIT_OPTIONS,
}, GUARD_SCRIPT, AUDIT_SCRIPT); }, GUARD_SCRIPT, AUDIT_SCRIPT);
const hooksDirectory = path.dirname(rendered.document.filePath); const hooksDirectory = path.dirname(rendered.document.filePath);
return { return {
@@ -73,7 +71,7 @@ export async function prepareGrokInstallation(
} }
export async function commitGrokInstallation( export async function commitGrokInstallation(
prepared: PreparedGrokInstallation, prepared: PreparedManagedInstallation,
renameFile?: RenameFile, renameFile?: RenameFile,
): Promise<void> { ): Promise<void> {
await commitManagedInstallation(prepared, renameFile); await commitManagedInstallation(prepared, renameFile);
+8 -74
View File
@@ -2,14 +2,15 @@ import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { import {
AGENT_KEY, AGENT_KEY,
AUDIT_OPTIONS,
GUARD_OPTIONS,
createGrokDocument, createGrokDocument,
parseGrokDocument, parseGrokDocument,
type GrokDocument, type GrokDocument,
type GrokRuntimeContract, type GrokRuntimeContract,
} from './grok-contract.js'; } from './grok-contract.js';
import { sameGrokAgentId, sameGrokPath } from './grok-command.js';
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js'; import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
import { parseStrictJsonObject, type JsonObject } from './strict-json.js'; import { managedRuntimeFilesExist } from './managed-runtime-status.js';
const CONFIG_FILE = 'elydora-audit.json'; const CONFIG_FILE = 'elydora-audit.json';
@@ -36,82 +37,15 @@ export async function readGrokDocument(): Promise<GrokDocument> {
: createGrokDocument(filePath); : createGrokDocument(filePath);
} }
function requireNonEmptyString(value: unknown, field: string, configPath: string): string {
if (typeof value !== 'string' || value.trim().length === 0) {
throw new Error(`Elydora runtime config ${field} is invalid: ${configPath}`);
}
return value;
}
function validateRuntimeConfig(
config: JsonObject,
contract: GrokRuntimeContract,
configPath: string,
): void {
const supported = new Set(['org_id', 'agent_id', 'kid', 'base_url', 'token', 'agent_name']);
const extra = Object.keys(config).find((key) => !supported.has(key));
if (extra) throw new Error(`Elydora runtime config has unsupported field "${extra}": ${configPath}`);
requireNonEmptyString(config.org_id, 'org_id', configPath);
requireNonEmptyString(config.kid, 'kid', configPath);
const agentId = requireNonEmptyString(config.agent_id, 'agent_id', configPath);
if (!sameGrokAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
throw new Error(`Elydora runtime identity does not match Grok hooks: ${configPath}`);
}
if (config.token !== undefined) requireNonEmptyString(config.token, 'token', configPath);
const rawBaseUrl = requireNonEmptyString(config.base_url, 'base_url', configPath);
let baseUrl: URL;
try {
baseUrl = new URL(rawBaseUrl);
} catch (error) {
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`, {
cause: error instanceof Error ? error : new Error(String(error)),
});
}
if (!['http:', 'https:'].includes(baseUrl.protocol)
|| !baseUrl.hostname
|| baseUrl.username
|| baseUrl.password
|| baseUrl.search
|| baseUrl.hash) {
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`);
}
}
function validatePrivateKey(contents: string, keyPath: string): void {
const bytes = Buffer.from(contents, 'base64url');
if (bytes.length !== 32 || bytes.toString('base64url') !== contents) {
throw new Error(`Elydora private key is invalid: ${keyPath}`);
}
}
async function runtimeContractExists(contract: GrokRuntimeContract): Promise<boolean> {
const runtimeRoot = path.join(os.homedir(), '.elydora');
const agentDirectory = path.dirname(contract.guardPath);
if (!sameGrokPath(path.dirname(agentDirectory), runtimeRoot)
|| !sameGrokPath(contract.auditPath, path.join(agentDirectory, 'hook.js'))) return false;
if (!await inspectPhysicalDirectory(runtimeRoot, 'Elydora runtime directory')) return false;
if (!await inspectPhysicalDirectory(agentDirectory, 'Elydora agent runtime directory')) return false;
const configPath = path.join(agentDirectory, 'config.json');
const keyPath = path.join(agentDirectory, 'private.key');
const [config, key, guard, audit] = await Promise.all([
readPhysicalFile(configPath, 'Elydora runtime config'),
readPhysicalFile(keyPath, 'Elydora private key'),
readPhysicalFile(contract.guardPath, 'Elydora guard runtime'),
readPhysicalFile(contract.auditPath, 'Elydora audit runtime'),
]);
if (!config || !key || !guard || !audit) return false;
const parsed = parseStrictJsonObject(config.contents, `Elydora runtime config at ${configPath}`);
validateRuntimeConfig(parsed, contract, configPath);
validatePrivateKey(key.contents, keyPath);
return guard.contents.length > 0 && audit.contents.length > 0;
}
export async function grokRuntimeFilesExist( export async function grokRuntimeFilesExist(
contracts: readonly GrokRuntimeContract[], contracts: readonly GrokRuntimeContract[],
): Promise<boolean> { ): Promise<boolean> {
for (const contract of contracts) { for (const contract of contracts) {
if (await runtimeContractExists(contract)) return true; const exists = await managedRuntimeFilesExist(contract, AGENT_KEY, {
guardOptions: GUARD_OPTIONS,
auditOptions: AUDIT_OPTIONS,
});
if (exists) return true;
} }
return false; return false;
} }
+23
View File
@@ -0,0 +1,23 @@
import { applyEdits, modify, type FormattingOptions, type JSONPath } from 'jsonc-parser';
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,
};
}
export function changeJsonc(
raw: string,
jsonPath: JSONPath,
value: unknown,
isArrayInsertion = false,
): string {
return applyEdits(raw, modify(raw, jsonPath, value, {
formattingOptions: formatting(raw),
isArrayInsertion,
}));
}
+14 -143
View File
@@ -1,140 +1,21 @@
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { managedScriptReference, type ManagedScriptReference } from './common.js';
import {
encodedWindowsCommand,
isNodeExecutable,
parseEncodedWindowsCommand,
parseLegacyWindowsCommand,
parsePosixCommand,
posixSource,
} from './shell-command.js';
interface ParsedArgument { export type KimiRuntimeReference = ManagedScriptReference;
readonly value: string;
readonly next: number;
}
export interface KimiRuntimeReference {
readonly agentId: string;
readonly scriptPath: string;
}
export function sameKimiPath(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 sameKimiAgentId(left: string, right: string): boolean {
return process.platform === 'win32'
? left.toLowerCase() === right.toLowerCase()
: left === right;
}
function quotePosix(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}
function quotePowerShell(value: string): string {
return `'${value.replaceAll("'", "''")}'`;
}
function windowsPowerShellPath(): string {
const configuredRoot = process.platform === 'win32' ? process.env.SystemRoot : undefined;
const systemRoot = configuredRoot
&& path.win32.isAbsolute(configuredRoot)
&& !/["%\r\n]/.test(configuredRoot)
? configuredRoot
: 'C:\\Windows';
return path.win32.join(
systemRoot,
'System32',
'WindowsPowerShell',
'v1.0',
'powershell.exe',
);
}
function windowsCommand(scriptPath: string): string {
const source = `& ${quotePowerShell(process.execPath)} ${quotePowerShell(scriptPath)}; exit $LASTEXITCODE`;
const encoded = Buffer.from(source, 'utf16le').toString('base64');
return `"${windowsPowerShellPath()}" -NoLogo -NoProfile -NonInteractive -EncodedCommand ${encoded}`;
}
export function buildKimiCommand(scriptPath: string): string { export function buildKimiCommand(scriptPath: string): string {
if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) { if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) {
throw new Error('Kimi hook commands require absolute executable and script paths'); throw new Error('Kimi hook commands require absolute executable and script paths');
} }
return process.platform === 'win32' return process.platform === 'win32' ? encodedWindowsCommand(scriptPath) : posixSource(scriptPath);
? windowsCommand(scriptPath)
: `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`;
}
function readPosixArgument(command: string, start: number): ParsedArgument | undefined {
if (command[start] !== "'") return undefined;
const apostrophe = `'"'"'`;
let value = '';
for (let index = start + 1; index < command.length;) {
if (command.startsWith(apostrophe, index)) {
value += "'";
index += apostrophe.length;
continue;
}
if (command[index] === "'") return { value, next: index + 1 };
value += command[index];
index += 1;
}
return undefined;
}
function parsePosixCommand(command: string): readonly [string, string] | undefined {
const executable = readPosixArgument(command, 0);
if (!executable || command[executable.next] !== ' ') return undefined;
const script = readPosixArgument(command, executable.next + 1);
if (!script || script.next !== command.length) return undefined;
return [executable.value, script.value];
}
function readPowerShellArgument(command: string, start: number): ParsedArgument | undefined {
if (command[start] !== "'") return undefined;
let value = '';
for (let index = start + 1; index < command.length; index += 1) {
if (command[index] !== "'") {
value += command[index];
continue;
}
if (command[index + 1] === "'") {
value += "'";
index += 1;
continue;
}
return { value, next: index + 1 };
}
return undefined;
}
function parsePowerShellSource(source: string): readonly [string, string] | undefined {
if (!source.startsWith('& ')) return undefined;
const executable = readPowerShellArgument(source, 2);
if (!executable || source[executable.next] !== ' ') return undefined;
const script = readPowerShellArgument(source, executable.next + 1);
if (!script || source.slice(script.next) !== '; exit $LASTEXITCODE') return undefined;
return [executable.value, script.value];
}
function parseWindowsCommand(command: string): readonly [string, string] | undefined {
const match = /^"([^"\r\n]+)" -NoLogo -NoProfile -NonInteractive -EncodedCommand ([A-Za-z0-9+/]+={0,2})$/.exec(command);
if (!match
|| !path.win32.isAbsolute(match[1])
|| path.win32.basename(match[1]).toLowerCase() !== 'powershell.exe') return undefined;
const encoded = match[2];
const buffer = Buffer.from(encoded, 'base64');
if (buffer.length % 2 !== 0 || buffer.toString('base64') !== encoded) return undefined;
return parsePowerShellSource(buffer.toString('utf16le'));
}
function parseLegacyWindowsCommand(command: string): readonly [string, string] | undefined {
const match = /^"([^"\r\n]+)" "([^"\r\n]+)"$/.exec(command);
return match ? [match[1], match[2]] : undefined;
}
function isNodeExecutable(filePath: string): boolean {
const basename = path.basename(filePath).toLowerCase();
return basename === 'node' || basename === 'node.exe';
} }
export function kimiRuntimeReference( export function kimiRuntimeReference(
@@ -142,18 +23,8 @@ export function kimiRuntimeReference(
scriptName: string, scriptName: string,
): KimiRuntimeReference | undefined { ): KimiRuntimeReference | undefined {
const parsed = parsePosixCommand(command) const parsed = parsePosixCommand(command)
?? parseWindowsCommand(command) ?? parseEncodedWindowsCommand(command)
?? parseLegacyWindowsCommand(command); ?? parseLegacyWindowsCommand(command);
if (!parsed if (!parsed || !path.isAbsolute(parsed[0]) || !isNodeExecutable(parsed[0])) return undefined;
|| !path.isAbsolute(parsed[0]) return managedScriptReference(parsed[1], scriptName);
|| !path.isAbsolute(parsed[1])
|| !isNodeExecutable(parsed[0])
|| path.basename(parsed[1]) !== scriptName) return undefined;
const agentDirectory = path.dirname(parsed[1]);
if (!sameKimiPath(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] };
} }
+5 -12
View File
@@ -1,9 +1,10 @@
import { sameAgentId } from './common.js';
import { import {
buildKimiCommand, buildKimiCommand,
kimiRuntimeReference, kimiRuntimeReference,
sameKimiAgentId,
type KimiRuntimeReference, type KimiRuntimeReference,
} from './kimi-command.js'; } from './kimi-command.js';
import { isObject, type JsonObject } from './strict-json.js';
export const AGENT_KEY = 'kimi'; export const AGENT_KEY = 'kimi';
export const GUARD_SCRIPT = 'guard.js'; export const GUARD_SCRIPT = 'guard.js';
@@ -34,7 +35,7 @@ export const STABLE_EVENTS = new Set<string>([
]); ]);
export const LEGACY_EVENTS = new Set<string>(SHARED_EVENTS); export const LEGACY_EVENTS = new Set<string>(SHARED_EVENTS);
export type TomlObject = Record<string, unknown>; export type TomlObject = JsonObject;
export type ManagedKimiEvent = 'PreToolUse' | 'PostToolUse' | 'PostToolUseFailure'; export type ManagedKimiEvent = 'PreToolUse' | 'PostToolUse' | 'PostToolUseFailure';
export interface KimiHook extends TomlObject { export interface KimiHook extends TomlObject {
@@ -75,14 +76,6 @@ export interface KimiRuntimeContract {
readonly configPath: string; readonly configPath: string;
} }
function isObject(value: unknown): value is TomlObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function hasOwn(value: TomlObject, key: string): boolean {
return Object.prototype.hasOwnProperty.call(value, key);
}
function exactManagedKeys(hook: KimiHook): boolean { function exactManagedKeys(hook: KimiHook): boolean {
return Object.keys(hook).sort().join('|') === 'command|event|timeout'; return Object.keys(hook).sort().join('|') === 'command|event|timeout';
} }
@@ -194,7 +187,7 @@ async function renderHookSource(
if (document.usesHookTables) return patchToml(document.raw ?? '', nextRoot); if (document.usesHookTables) return patchToml(document.raw ?? '', nextRoot);
let base = document.raw ?? ''; let base = document.raw ?? '';
if (hasOwn(document.root, 'hooks')) { if (Object.hasOwn(document.root, 'hooks')) {
const rootWithoutHooks = { ...document.root }; const rootWithoutHooks = { ...document.root };
delete rootWithoutHooks.hooks; delete rootWithoutHooks.hooks;
base = patchToml(base, rootWithoutHooks); base = patchToml(base, rootWithoutHooks);
@@ -248,7 +241,7 @@ export function removeManagedKimiHooks(
if (!expected) return true; if (!expected) return true;
const managedId = managedAgentId(hook, expected[0], expected[1]); const managedId = managedAgentId(hook, expected[0], expected[1]);
if (!managedId) return true; if (!managedId) return true;
return agentId !== undefined && !sameKimiAgentId(managedId, agentId); return agentId !== undefined && !sameAgentId(managedId, agentId);
}); });
} }
+3 -7
View File
@@ -23,10 +23,6 @@ import {
const DISPLAY_NAME = 'Kimi'; const DISPLAY_NAME = 'Kimi';
export type KimiRuntimePaths = ManagedRuntimePaths;
export type PreparedKimiInstallation = PreparedManagedInstallation;
export type { RenameFile };
function hookLocations(documents: readonly KimiConfigDocument[]) { function hookLocations(documents: readonly KimiConfigDocument[]) {
return documents.map((document) => ({ return documents.map((document) => ({
directoryLabel: document.contract.directoryLabel, directoryLabel: document.contract.directoryLabel,
@@ -37,7 +33,7 @@ function hookLocations(documents: readonly KimiConfigDocument[]) {
export async function preflightKimiInstallation( export async function preflightKimiInstallation(
config: InstallConfig, config: InstallConfig,
documents: readonly KimiConfigDocument[], documents: readonly KimiConfigDocument[],
): Promise<KimiRuntimePaths> { ): Promise<ManagedRuntimePaths> {
return preflightManagedInstallation({ return preflightManagedInstallation({
agentKey: AGENT_KEY, agentKey: AGENT_KEY,
hookLocations: hookLocations(documents), hookLocations: hookLocations(documents),
@@ -56,7 +52,7 @@ function renderedSource(rendered: RenderedKimiDocument): string {
export async function prepareKimiInstallation( export async function prepareKimiInstallation(
config: InstallConfig, config: InstallConfig,
rendered: readonly RenderedKimiDocument[], rendered: readonly RenderedKimiDocument[],
): Promise<PreparedKimiInstallation> { ): Promise<PreparedManagedInstallation> {
return prepareManagedInstallation({ return prepareManagedInstallation({
agentKey: AGENT_KEY, agentKey: AGENT_KEY,
displayName: DISPLAY_NAME, displayName: DISPLAY_NAME,
@@ -73,7 +69,7 @@ export async function prepareKimiInstallation(
} }
export async function commitKimiInstallation( export async function commitKimiInstallation(
prepared: PreparedKimiInstallation, prepared: PreparedManagedInstallation,
renameFile?: RenameFile, renameFile?: RenameFile,
): Promise<void> { ): Promise<void> {
await commitManagedInstallation(prepared, renameFile); await commitManagedInstallation(prepared, renameFile);
+4 -88
View File
@@ -1,6 +1,7 @@
import fsp from 'node:fs/promises'; import fsp from 'node:fs/promises';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { asError, errorMessage, hasCode, samePath } from './common.js';
import { import {
AGENT_KEY, AGENT_KEY,
LEGACY_EVENTS, LEGACY_EVENTS,
@@ -10,23 +11,9 @@ import {
type KimiConfigDocument, type KimiConfigDocument,
type KimiContract, type KimiContract,
type KimiRuntimeContract, type KimiRuntimeContract,
type TomlObject,
} from './kimi-contract.js'; } from './kimi-contract.js';
import { sameKimiAgentId, sameKimiPath } from './kimi-command.js';
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js'; import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
import { parseStrictJsonObject } from './strict-json.js'; import { managedRuntimeFilesExist } from './managed-runtime-status.js';
function asError(error: unknown): Error {
return error instanceof Error ? error : new Error(String(error));
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function hasCode(error: unknown, code: string): boolean {
return typeof error === 'object' && error !== null && 'code' in error && error.code === code;
}
async function pathEntryExists(filePath: string, label: string): Promise<boolean> { async function pathEntryExists(filePath: string, label: string): Promise<boolean> {
try { try {
@@ -72,7 +59,7 @@ export async function resolveKimiContracts(): Promise<KimiContract[]> {
const legacyHome = path.join(home, '.kimi'); const legacyHome = path.join(home, '.kimi');
const stable = stableContract(path.join(stableHome, 'config.toml')); const stable = stableContract(path.join(stableHome, 'config.toml'));
const legacy = legacyContract(path.join(legacyHome, 'config.toml')); const legacy = legacyContract(path.join(legacyHome, 'config.toml'));
if (sameKimiPath(stable.configPath, legacy.configPath)) return [stable]; if (samePath(stable.configPath, legacy.configPath)) return [stable];
const stableDetected = explicitHome !== undefined const stableDetected = explicitHome !== undefined
|| await pathEntryExists(stableHome, 'Kimi Code home'); || await pathEntryExists(stableHome, 'Kimi Code home');
@@ -96,82 +83,11 @@ export async function readKimiDocuments(): Promise<KimiConfigDocument[]> {
return documents; return documents;
} }
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: TomlObject,
contract: KimiRuntimeContract,
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 (!sameKimiAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
throw new Error(`Elydora runtime identity does not match Kimi 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: asError(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: KimiRuntimeContract): Promise<boolean> {
const runtimeRoot = path.join(os.homedir(), '.elydora');
const agentDirectory = path.dirname(contract.guardPath);
if (!sameKimiPath(path.dirname(agentDirectory), runtimeRoot)
|| !sameKimiPath(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 kimiRuntimeFilesExist( export async function kimiRuntimeFilesExist(
contracts: readonly KimiRuntimeContract[], contracts: readonly KimiRuntimeContract[],
): Promise<boolean> { ): Promise<boolean> {
for (const contract of contracts) { for (const contract of contracts) {
if (await runtimeContractExists(contract)) return true; if (await managedRuntimeFilesExist(contract, AGENT_KEY)) return true;
} }
return false; return false;
} }
+16 -28
View File
@@ -1,14 +1,14 @@
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { managedScriptReference, sameAgentId, samePath } from './common.js';
import { import {
buildKiroIdeCommand, buildKiroIdeCommand,
kiroIdeRuntimeReference, kiroIdeRuntimeReference,
sameKiroIdeAgentId,
sameKiroIdePath,
type KiroIdeRuntimeReference, type KiroIdeRuntimeReference,
} from './kiroide-command.js'; } from './kiroide-command.js';
import { import {
buildKiroIdeHook, buildKiroIdeHook,
exactKeys,
kiroIdeRuntimeContracts, kiroIdeRuntimeContracts,
renderKiroIdeDocument, renderKiroIdeDocument,
type KiroIdeDocument, type KiroIdeDocument,
@@ -16,6 +16,7 @@ import {
type RenderedKiroIdeDocument, type RenderedKiroIdeDocument,
type KiroIdeRuntimeContract, type KiroIdeRuntimeContract,
} from './kiroide-contract.js'; } from './kiroide-contract.js';
import { isNodeExecutable, parseLegacyWindowsCommand } from './shell-command.js';
import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js'; import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js';
export const AGENT_KEY = 'kirocli'; export const AGENT_KEY = 'kirocli';
@@ -162,27 +163,14 @@ function eventHooks(document: KiroCliV2Document, event: string): readonly KiroCl
return (document.hooks[event] as readonly KiroCliV2Hook[] | undefined) ?? []; 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( function legacyWindowsReference(
command: unknown, command: unknown,
scriptName: string, scriptName: string,
): KiroIdeRuntimeReference | undefined { ): KiroIdeRuntimeReference | undefined {
if (typeof command !== 'string') return undefined; if (typeof command !== 'string') return undefined;
const match = /^"([^"\r\n]+)" "([^"\r\n]+)"$/.exec(command); const parsed = parseLegacyWindowsCommand(command);
if (!match if (!parsed || !path.isAbsolute(parsed[0]) || !isNodeExecutable(parsed[0])) return undefined;
|| !path.isAbsolute(match[1]) return managedScriptReference(parsed[1], scriptName);
|| !['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 { function ownedReference(command: unknown, scriptName: string): KiroIdeRuntimeReference | undefined {
@@ -219,7 +207,7 @@ function hasOwnedV2Hooks(document: KiroCliV2Document, agentId?: string): boolean
return ['preToolUse', 'postToolUse'].some((event) => eventHooks(document, event).some((hook) => { return ['preToolUse', 'postToolUse'].some((event) => eventHooks(document, event).some((hook) => {
const reference = v2OwnedReference(hook, event); const reference = v2OwnedReference(hook, event);
return reference !== undefined return reference !== undefined
&& (agentId === undefined || sameKiroIdeAgentId(reference.agentId, agentId)); && (agentId === undefined || sameAgentId(reference.agentId, agentId));
})); }));
} }
@@ -237,7 +225,7 @@ export function withoutManagedKiroCliV2Hooks(
for (const event of ['preToolUse', 'postToolUse']) { for (const event of ['preToolUse', 'postToolUse']) {
const remaining = eventHooks(document, event).filter((hook) => { const remaining = eventHooks(document, event).filter((hook) => {
const reference = v2OwnedReference(hook, event); const reference = v2OwnedReference(hook, event);
return !reference || (agentId !== undefined && !sameKiroIdeAgentId(reference.agentId, agentId)); return !reference || (agentId !== undefined && !sameAgentId(reference.agentId, agentId));
}); });
if (remaining.length > 0) next[event] = remaining; if (remaining.length > 0) next[event] = remaining;
else delete next[event]; else delete next[event];
@@ -288,7 +276,7 @@ function entirelyManagedV2Document(document: KiroCliV2Document, agentId?: string
const hooks = eventHooks(document, event); const hooks = eventHooks(document, event);
if (hooks.length !== 1) return false; if (hooks.length !== 1) return false;
const reference = v2OwnedReference(hooks[0], event); const reference = v2OwnedReference(hooks[0], event);
if (!reference || (agentId !== undefined && !sameKiroIdeAgentId(reference.agentId, agentId))) { if (!reference || (agentId !== undefined && !sameAgentId(reference.agentId, agentId))) {
return false; return false;
} }
} }
@@ -324,7 +312,7 @@ export function kiroCliV2RuntimeContracts(
.map((hook) => v2ManagedReference(hook, 'postToolUse')) .map((hook) => v2ManagedReference(hook, 'postToolUse'))
.filter((value): value is KiroIdeRuntimeReference => value !== undefined); .filter((value): value is KiroIdeRuntimeReference => value !== undefined);
if (guards.length !== 1 || audits.length !== 1 if (guards.length !== 1 || audits.length !== 1
|| !sameKiroIdeAgentId(guards[0].agentId, audits[0].agentId)) return []; || !sameAgentId(guards[0].agentId, audits[0].agentId)) return [];
return [{ agentId: guards[0].agentId, guardPath: guards[0].scriptPath, auditPath: audits[0].scriptPath }]; return [{ agentId: guards[0].agentId, guardPath: guards[0].scriptPath, auditPath: audits[0].scriptPath }];
} }
@@ -355,7 +343,7 @@ export function withoutManagedKiroCliV3Hooks(
): KiroIdeHook[] { ): KiroIdeHook[] {
return hooks.filter((hook) => { return hooks.filter((hook) => {
const reference = v3OwnedReference(hook); const reference = v3OwnedReference(hook);
return !reference || (agentId !== undefined && !sameKiroIdeAgentId(reference.agentId, agentId)); return !reference || (agentId !== undefined && !sameAgentId(reference.agentId, agentId));
}); });
} }
@@ -363,7 +351,7 @@ function hasOwnedV3Hooks(hooks: readonly KiroIdeHook[], agentId?: string): boole
return hooks.some((hook) => { return hooks.some((hook) => {
const reference = v3OwnedReference(hook); const reference = v3OwnedReference(hook);
return reference !== undefined return reference !== undefined
&& (agentId === undefined || sameKiroIdeAgentId(reference.agentId, agentId)); && (agentId === undefined || sameAgentId(reference.agentId, agentId));
}); });
} }
@@ -374,7 +362,7 @@ function entirelyManagedV3Document(document: KiroIdeDocument, agentId?: string):
&& document.hooks.every((hook) => { && document.hooks.every((hook) => {
const reference = v3OwnedReference(hook); const reference = v3OwnedReference(hook);
return reference !== undefined return reference !== undefined
&& (agentId === undefined || sameKiroIdeAgentId(reference.agentId, agentId)); && (agentId === undefined || sameAgentId(reference.agentId, agentId));
}); });
} }
@@ -409,8 +397,8 @@ export function commonKiroCliRuntimeContract(
const v2 = kiroCliV2RuntimeContracts(v2Document); const v2 = kiroCliV2RuntimeContracts(v2Document);
const v3 = kiroIdeRuntimeContracts(v3Hooks); const v3 = kiroIdeRuntimeContracts(v3Hooks);
if (v2.length !== 1 || v3.length !== 1 if (v2.length !== 1 || v3.length !== 1
|| !sameKiroIdeAgentId(v2[0].agentId, v3[0].agentId) || !sameAgentId(v2[0].agentId, v3[0].agentId)
|| !sameKiroIdePath(v2[0].guardPath, v3[0].guardPath) || !samePath(v2[0].guardPath, v3[0].guardPath)
|| !sameKiroIdePath(v2[0].auditPath, v3[0].auditPath)) return undefined; || !samePath(v2[0].auditPath, v3[0].auditPath)) return undefined;
return v2[0]; return v2[0];
} }
+3 -7
View File
@@ -27,10 +27,6 @@ const DISPLAY_NAME = 'Kiro CLI';
const V2_DIRECTORY_LABEL = 'Kiro CLI agents directory'; const V2_DIRECTORY_LABEL = 'Kiro CLI agents directory';
const V3_DIRECTORY_LABEL = 'Kiro CLI global hooks 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) { function hookLocations(sources: KiroCliSources) {
return [ return [
{ directoryLabel: V2_DIRECTORY_LABEL, filePath: sources.paths.v2Path }, { directoryLabel: V2_DIRECTORY_LABEL, filePath: sources.paths.v2Path },
@@ -41,7 +37,7 @@ function hookLocations(sources: KiroCliSources) {
export async function preflightKiroCliInstallation( export async function preflightKiroCliInstallation(
config: InstallConfig, config: InstallConfig,
sources: KiroCliSources, sources: KiroCliSources,
): Promise<KiroCliRuntimePaths> { ): Promise<ManagedRuntimePaths> {
return preflightManagedInstallation({ return preflightManagedInstallation({
agentKey: AGENT_KEY, agentKey: AGENT_KEY,
hookLocations: hookLocations(sources), hookLocations: hookLocations(sources),
@@ -54,7 +50,7 @@ export async function prepareKiroCliInstallation(
sources: KiroCliSources, sources: KiroCliSources,
v2: RenderedKiroCliV2Document, v2: RenderedKiroCliV2Document,
v3: RenderedKiroIdeDocument, v3: RenderedKiroIdeDocument,
): Promise<PreparedKiroCliInstallation> { ): Promise<PreparedManagedInstallation> {
if (v2.next === undefined || v3.next === undefined) { if (v2.next === undefined || v3.next === undefined) {
throw new Error('Kiro CLI installation requires both v2 and v3 hook documents'); throw new Error('Kiro CLI installation requires both v2 and v3 hook documents');
} }
@@ -83,7 +79,7 @@ export async function prepareKiroCliInstallation(
} }
export async function commitKiroCliInstallation( export async function commitKiroCliInstallation(
prepared: PreparedKiroCliInstallation, prepared: PreparedManagedInstallation,
renameFile?: RenameFile, renameFile?: RenameFile,
): Promise<void> { ): Promise<void> {
await commitManagedInstallation(prepared, renameFile); await commitManagedInstallation(prepared, renameFile);
+3 -4
View File
@@ -12,11 +12,10 @@ import {
type KiroIdeDocument, type KiroIdeDocument,
type KiroIdeRuntimeContract, type KiroIdeRuntimeContract,
} from './kiroide-contract.js'; } from './kiroide-contract.js';
import { MAX_CONFIG_BYTES } from './common.js';
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js'; import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
import { managedRuntimeFilesExist } from './managed-runtime-status.js'; import { managedRuntimeFilesExist } from './managed-runtime-status.js';
const MAX_HOOK_BYTES = 512 * 1024;
export interface KiroCliSources { export interface KiroCliSources {
readonly paths: KiroCliPaths; readonly paths: KiroCliPaths;
readonly v2: KiroCliV2Document; readonly v2: KiroCliV2Document;
@@ -36,7 +35,7 @@ async function readV2Document(paths: KiroCliPaths): Promise<KiroCliV2Document> {
const snapshot = await readPhysicalFile( const snapshot = await readPhysicalFile(
paths.v2Path, paths.v2Path,
'Kiro CLI v2 agent config', 'Kiro CLI v2 agent config',
MAX_HOOK_BYTES, MAX_CONFIG_BYTES,
); );
return snapshot return snapshot
? parseKiroCliV2Document(paths.v2Path, snapshot.contents) ? parseKiroCliV2Document(paths.v2Path, snapshot.contents)
@@ -47,7 +46,7 @@ async function readV3Document(paths: KiroCliPaths): Promise<KiroIdeDocument> {
const snapshot = await readPhysicalFile( const snapshot = await readPhysicalFile(
paths.v3Path, paths.v3Path,
'Kiro CLI v3 global hooks', 'Kiro CLI v3 global hooks',
MAX_HOOK_BYTES, MAX_CONFIG_BYTES,
); );
return snapshot return snapshot
? parseKiroIdeDocument(paths.v3Path, snapshot.contents, 'Kiro CLI v3 global hooks') ? parseKiroIdeDocument(paths.v3Path, snapshot.contents, 'Kiro CLI v3 global hooks')
+13 -136
View File
@@ -1,132 +1,20 @@
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { managedScriptReference, type ManagedScriptReference } from './common.js';
import {
encodedWindowsCommand,
isNodeExecutable,
parseEncodedWindowsCommand,
parsePosixCommand,
posixSource,
} from './shell-command.js';
interface ParsedArgument { export type KiroIdeRuntimeReference = ManagedScriptReference;
readonly value: string;
readonly next: number;
}
export interface KiroIdeRuntimeReference {
readonly agentId: string;
readonly scriptPath: string;
}
export function sameKiroIdePath(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 sameKiroIdeAgentId(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 `"${windowsPowerShellPath()}" -NoLogo -NoProfile -NonInteractive -EncodedCommand ${encoded}`;
}
export function buildKiroIdeCommand(scriptPath: string): string { export function buildKiroIdeCommand(scriptPath: string): string {
if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) { if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) {
throw new Error('Kiro IDE hook commands require absolute executable and script paths'); throw new Error('Kiro IDE hook commands require absolute executable and script paths');
} }
return process.platform === 'win32' return process.platform === 'win32' ? encodedWindowsCommand(scriptPath) : posixSource(scriptPath);
? 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);
return script && script.next === command.length ? [executable.value, script.value] : undefined;
}
function readPowerShellArgument(command: string, start: number): ParsedArgument | undefined {
if (command[start] !== "'") return undefined;
let value = '';
for (let index = start + 1; index < command.length; index += 1) {
if (command[index] !== "'") {
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);
return script && source.slice(script.next) === '; exit $LASTEXITCODE'
? [executable.value, script.value]
: undefined;
}
function parseWindowsCommand(command: string): readonly [string, string] | undefined {
const match = /^"([^"\r\n]+)" -NoLogo -NoProfile -NonInteractive -EncodedCommand ([A-Za-z0-9+/]+={0,2})$/.exec(command);
if (!match
|| !path.win32.isAbsolute(match[1])
|| path.win32.basename(match[1]).toLowerCase() !== 'powershell.exe') return undefined;
const buffer = Buffer.from(match[2], 'base64');
if (buffer.length % 2 !== 0 || buffer.toString('base64') !== match[2]) return undefined;
return parsePowerShellSource(buffer.toString('utf16le'));
}
function isNodeExecutable(filePath: string): boolean {
const basename = path.basename(filePath).toLowerCase();
return basename === 'node' || basename === 'node.exe';
} }
export function kiroIdeRuntimeReference( export function kiroIdeRuntimeReference(
@@ -134,19 +22,8 @@ export function kiroIdeRuntimeReference(
scriptName: string, scriptName: string,
): KiroIdeRuntimeReference | undefined { ): KiroIdeRuntimeReference | undefined {
const parsed = process.platform === 'win32' const parsed = process.platform === 'win32'
? parseWindowsCommand(command) ? parseEncodedWindowsCommand(command)
: parsePosixCommand(command); : parsePosixCommand(command);
if (!parsed if (!parsed || !path.isAbsolute(parsed[0]) || !isNodeExecutable(parsed[0])) return undefined;
|| !path.isAbsolute(parsed[0]) return managedScriptReference(parsed[1], scriptName);
|| !isNodeExecutable(parsed[0])
|| !path.isAbsolute(parsed[1])
|| path.basename(parsed[1]) !== scriptName) return undefined;
const agentDirectory = path.dirname(parsed[1]);
if (!sameKiroIdePath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))) {
return undefined;
}
const agentId = path.basename(agentDirectory);
return agentId && agentId !== '.' && agentId !== '..'
? { agentId, scriptPath: parsed[1] }
: undefined;
} }
+5 -11
View File
@@ -1,10 +1,9 @@
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { managedScriptReference, sameAgentId } from './common.js';
import { import {
buildKiroIdeCommand, buildKiroIdeCommand,
kiroIdeRuntimeReference, kiroIdeRuntimeReference,
sameKiroIdeAgentId,
sameKiroIdePath,
type KiroIdeRuntimeReference, type KiroIdeRuntimeReference,
} from './kiroide-command.js'; } from './kiroide-command.js';
import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js'; import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js';
@@ -154,7 +153,7 @@ export function createKiroIdeDocument(filePath: string): KiroIdeDocument {
return { exists: false, filePath, root: {}, hooks: [] }; return { exists: false, filePath, root: {}, hooks: [] };
} }
function exactKeys(value: JsonObject, keys: readonly string[]): boolean { export function exactKeys(value: JsonObject, keys: readonly string[]): boolean {
return Object.keys(value).sort().join('|') === [...keys].sort().join('|'); return Object.keys(value).sort().join('|') === [...keys].sort().join('|');
} }
@@ -228,7 +227,7 @@ export function withoutManagedKiroIdeHooks(
): KiroIdeHook[] { ): KiroIdeHook[] {
return hooks.filter((hook) => { return hooks.filter((hook) => {
const reference = ownedReference(hook); const reference = ownedReference(hook);
return !reference || (agentId !== undefined && !sameKiroIdeAgentId(reference.agentId, agentId)); return !reference || (agentId !== undefined && !sameAgentId(reference.agentId, agentId));
}); });
} }
@@ -285,12 +284,7 @@ export function kiroIdeRuntimeContracts(
function legacyReference(command: unknown, scriptName: string) { function legacyReference(command: unknown, scriptName: string) {
if (typeof command !== 'string') return undefined; if (typeof command !== 'string') return undefined;
const match = /^node "([^"\r\n]+)"$/.exec(command); const match = /^node "([^"\r\n]+)"$/.exec(command);
if (!match || !path.isAbsolute(match[1]) || path.basename(match[1]) !== scriptName) return undefined; return match ? managedScriptReference(match[1], scriptName) : undefined;
const agentDirectory = path.dirname(match[1]);
if (!sameKiroIdePath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))) {
return undefined;
}
return { agentId: path.basename(agentDirectory), scriptPath: match[1] };
} }
export function legacyKiroIdeRuntimeContract(raw: string, filePath: string): KiroIdeRuntimeContract | undefined { export function legacyKiroIdeRuntimeContract(raw: string, filePath: string): KiroIdeRuntimeContract | undefined {
@@ -311,6 +305,6 @@ export function legacyKiroIdeRuntimeContract(raw: string, filePath: string): Kir
|| auditHook.timeout_ms !== 5000) return undefined; || auditHook.timeout_ms !== 5000) return undefined;
const guard = legacyReference(guardHook.command, GUARD_SCRIPT); const guard = legacyReference(guardHook.command, GUARD_SCRIPT);
const audit = legacyReference(auditHook.command, AUDIT_SCRIPT); const audit = legacyReference(auditHook.command, AUDIT_SCRIPT);
if (!guard || !audit || !sameKiroIdeAgentId(guard.agentId, audit.agentId)) return undefined; if (!guard || !audit || !sameAgentId(guard.agentId, audit.agentId)) return undefined;
return { agentId: guard.agentId, guardPath: guard.scriptPath, auditPath: audit.scriptPath }; return { agentId: guard.agentId, guardPath: guard.scriptPath, auditPath: audit.scriptPath };
} }
+5 -9
View File
@@ -1,6 +1,6 @@
import path from 'node:path'; import path from 'node:path';
import type { InstallConfig } from './base.js'; import type { InstallConfig } from './base.js';
import { sameKiroIdeAgentId } from './kiroide-command.js'; import { sameAgentId } from './common.js';
import { import {
AGENT_KEY, AGENT_KEY,
AUDIT_SCRIPT, AUDIT_SCRIPT,
@@ -31,17 +31,13 @@ import {
const DISPLAY_NAME = 'Kiro IDE'; const DISPLAY_NAME = 'Kiro IDE';
const DIRECTORY_LABEL = 'Kiro IDE hooks directory'; const DIRECTORY_LABEL = 'Kiro IDE hooks directory';
export type KiroIdeRuntimePaths = ManagedRuntimePaths;
export type PreparedKiroIdeInstallation = PreparedManagedInstallation;
export type { RenameFile };
function hookLocation(paths: KiroIdePaths) { function hookLocation(paths: KiroIdePaths) {
return [{ directoryLabel: DIRECTORY_LABEL, filePath: paths.configPath }]; return [{ directoryLabel: DIRECTORY_LABEL, filePath: paths.configPath }];
} }
function removesLegacy(legacy: LegacyKiroIdeDocument, agentId?: string): boolean { function removesLegacy(legacy: LegacyKiroIdeDocument, agentId?: string): boolean {
return legacy.contract !== undefined return legacy.contract !== undefined
&& (agentId === undefined || sameKiroIdeAgentId(legacy.contract.agentId, agentId)); && (agentId === undefined || sameAgentId(legacy.contract.agentId, agentId));
} }
async function prepareLegacyRemoval( async function prepareLegacyRemoval(
@@ -64,7 +60,7 @@ async function prepareLegacyRemoval(
export async function preflightKiroIdeInstallation( export async function preflightKiroIdeInstallation(
config: InstallConfig, config: InstallConfig,
paths: KiroIdePaths, paths: KiroIdePaths,
): Promise<KiroIdeRuntimePaths> { ): Promise<ManagedRuntimePaths> {
return preflightManagedInstallation({ return preflightManagedInstallation({
agentKey: AGENT_KEY, agentKey: AGENT_KEY,
hookLocations: hookLocation(paths), hookLocations: hookLocation(paths),
@@ -76,7 +72,7 @@ export async function prepareKiroIdeInstallation(
config: InstallConfig, config: InstallConfig,
sources: KiroIdeSources, sources: KiroIdeSources,
rendered: RenderedKiroIdeDocument, rendered: RenderedKiroIdeDocument,
): Promise<PreparedKiroIdeInstallation> { ): Promise<PreparedManagedInstallation> {
if (rendered.next === undefined) throw new Error('Kiro IDE installation requires a hook document'); if (rendered.next === undefined) throw new Error('Kiro IDE installation requires a hook document');
const prepared = await prepareManagedInstallation({ const prepared = await prepareManagedInstallation({
agentKey: AGENT_KEY, agentKey: AGENT_KEY,
@@ -107,7 +103,7 @@ export async function prepareKiroIdeInstallation(
} }
export async function commitKiroIdeInstallation( export async function commitKiroIdeInstallation(
prepared: PreparedKiroIdeInstallation, prepared: PreparedManagedInstallation,
renameFile?: RenameFile, renameFile?: RenameFile,
): Promise<void> { ): Promise<void> {
await commitManagedInstallation(prepared, renameFile); await commitManagedInstallation(prepared, renameFile);
+14 -112
View File
@@ -1,10 +1,12 @@
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { managedScriptReference } from './common.js';
interface ParsedArgument { import {
readonly value: string; isNodeExecutable,
readonly next: number; parsePosixCommand,
} parsePowerShellSource,
posixSource,
powerShellSource,
} from './shell-command.js';
export interface LettaRuntimeReference { export interface LettaRuntimeReference {
readonly agentId: string; readonly agentId: string;
@@ -12,88 +14,11 @@ export interface LettaRuntimeReference {
readonly scriptPath: string; readonly scriptPath: string;
} }
export function sameLettaPath(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 sameLettaAgentId(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("'", "''")}'`;
}
export function buildLettaCommand(scriptPath: string): string { export function buildLettaCommand(scriptPath: string): string {
if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) { if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) {
throw new Error('Letta Code hook commands require absolute executable and script paths'); throw new Error('Letta Code hook commands require absolute executable and script paths');
} }
if (process.platform === 'win32') { return process.platform === 'win32' ? powerShellSource(scriptPath) : posixSource(scriptPath);
return `& ${quotePowerShell(process.execPath)} ${quotePowerShell(scriptPath)}; exit $LASTEXITCODE`;
}
return `${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 parsePowerShellCommand(command: string): readonly [string, string] | undefined {
if (!command.startsWith('& ')) return undefined;
const executable = readPowerShellArgument(command, 2);
if (!executable || command[executable.next] !== ' ') return undefined;
const script = readPowerShellArgument(command, executable.next + 1);
if (!script || command.slice(script.next) !== '; exit $LASTEXITCODE') return undefined;
return [executable.value, script.value];
} }
function legacyScriptPath(command: string): string | undefined { function legacyScriptPath(command: string): string | undefined {
@@ -102,39 +27,16 @@ function legacyScriptPath(command: string): string | undefined {
return scriptPath.includes('"') ? undefined : scriptPath; return scriptPath.includes('"') ? undefined : scriptPath;
} }
function isNodeExecutable(filePath: string): boolean {
const basename = path.basename(filePath).toLowerCase();
return basename === 'node' || basename === 'node.exe';
}
function runtimeReference(
scriptPath: string,
scriptName: string,
executablePath?: string,
): LettaRuntimeReference | undefined {
if (!path.isAbsolute(scriptPath) || path.basename(scriptPath) !== scriptName) return undefined;
const agentDirectory = path.dirname(scriptPath);
if (!sameLettaPath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))) {
return undefined;
}
const agentId = path.basename(agentDirectory);
if (!agentId || agentId === '.' || agentId === '..') return undefined;
return { agentId, executablePath, scriptPath };
}
export function lettaRuntimeReference( export function lettaRuntimeReference(
command: string, command: string,
scriptName: string, scriptName: string,
): LettaRuntimeReference | undefined { ): LettaRuntimeReference | undefined {
const parsed = process.platform === 'win32' const parsed = process.platform === 'win32'
? parsePowerShellCommand(command) ? parsePowerShellSource(command)
: parsePosixCommand(command); : parsePosixCommand(command);
if (parsed if (!parsed || !path.isAbsolute(parsed[0]) || !isNodeExecutable(parsed[0])) return undefined;
&& path.isAbsolute(parsed[0]) const reference = managedScriptReference(parsed[1], scriptName);
&& isNodeExecutable(parsed[0])) { return reference ? { ...reference, executablePath: parsed[0] } : undefined;
return runtimeReference(parsed[1], scriptName, parsed[0]);
}
return undefined;
} }
export function lettaLegacyRuntimeReference( export function lettaLegacyRuntimeReference(
@@ -142,5 +44,5 @@ export function lettaLegacyRuntimeReference(
scriptName: string, scriptName: string,
): LettaRuntimeReference | undefined { ): LettaRuntimeReference | undefined {
const legacy = legacyScriptPath(command); const legacy = legacyScriptPath(command);
return legacy ? runtimeReference(legacy, scriptName) : undefined; return legacy ? managedScriptReference(legacy, scriptName) : undefined;
} }
+8 -34
View File
@@ -1,9 +1,5 @@
import { import type { JSONPath } from 'jsonc-parser';
applyEdits, import { changeJsonc } from './jsonc-edit.js';
modify,
type FormattingOptions,
type JSONPath,
} from 'jsonc-parser';
import type { FileSnapshot } from './managed-files.js'; import type { FileSnapshot } from './managed-files.js';
import { import {
MANAGED_EVENTS, MANAGED_EVENTS,
@@ -73,28 +69,6 @@ export function createLettaDocument(
}); });
} }
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: LettaDocument, raw: string): LettaDocument { function currentDocument(document: LettaDocument, raw: string): LettaDocument {
return parseLettaDocument({ return parseLettaDocument({
kind: document.kind, kind: document.kind,
@@ -124,25 +98,25 @@ function removeManagedEntries(
for (const removal of eventRemovals) { for (const removal of eventRemovals) {
const groupPath: JSONPath = ['hooks', event, removal.groupIndex]; const groupPath: JSONPath = ['hooks', event, removal.groupIndex];
if (removal.removeGroup) { if (removal.removeGroup) {
raw = change(raw, groupPath, undefined); raw = changeJsonc(raw, groupPath, undefined);
continue; continue;
} }
for (const handlerIndex of [...removal.handlerIndexes].sort( for (const handlerIndex of [...removal.handlerIndexes].sort(
(left, right) => right - left, (left, right) => right - left,
)) { )) {
raw = change(raw, [...groupPath, 'hooks', handlerIndex], undefined); raw = changeJsonc(raw, [...groupPath, 'hooks', handlerIndex], undefined);
} }
} }
if (eventRemovals.length > 0) { if (eventRemovals.length > 0) {
const current = currentDocument(document, raw); const current = currentDocument(document, raw);
if (groupsForEvent(current.hooks, event).length === 0) { if (groupsForEvent(current.hooks, event).length === 0) {
raw = change(raw, ['hooks', event], undefined); raw = changeJsonc(raw, ['hooks', event], undefined);
} }
} }
} }
const current = currentDocument(document, raw); const current = currentDocument(document, raw);
if (current.hasHooksContainer && Object.keys(current.hooks).length === 0) { if (current.hasHooksContainer && Object.keys(current.hooks).length === 0) {
raw = change(raw, ['hooks'], undefined); raw = changeJsonc(raw, ['hooks'], undefined);
} }
return raw; return raw;
} }
@@ -156,9 +130,9 @@ function appendGroup(
const current = currentDocument(document, raw); const current = currentDocument(document, raw);
const groups = groupsForEvent(current.hooks, event); const groups = groupsForEvent(current.hooks, event);
if (groups.length > 0) { if (groups.length > 0) {
return change(raw, ['hooks', event, groups.length], group, true); return changeJsonc(raw, ['hooks', event, groups.length], group, true);
} }
return change(raw, ['hooks', event], [group]); return changeJsonc(raw, ['hooks', event], [group]);
} }
export function renderLettaDocument( export function renderLettaDocument(
+4 -5
View File
@@ -1,9 +1,8 @@
import { sameAgentId, samePath } from './common.js';
import { import {
buildLettaCommand, buildLettaCommand,
lettaLegacyRuntimeReference, lettaLegacyRuntimeReference,
lettaRuntimeReference, lettaRuntimeReference,
sameLettaAgentId,
sameLettaPath,
type LettaRuntimeReference, type LettaRuntimeReference,
} from './letta-command.js'; } from './letta-command.js';
import { isObject, type JsonObject } from './strict-json.js'; import { isObject, type JsonObject } from './strict-json.js';
@@ -220,7 +219,7 @@ export function managedLettaRemovals(
eventGroups(hooks, event).forEach((group, groupIndex) => { eventGroups(hooks, event).forEach((group, groupIndex) => {
const handlerIndexes = group.hooks.flatMap((handler, handlerIndex) => { const handlerIndexes = group.hooks.flatMap((handler, handlerIndex) => {
const reference = managedReference(handler, scriptName); const reference = managedReference(handler, scriptName);
return reference && (agentId === undefined || sameLettaAgentId(reference.agentId, agentId)) return reference && (agentId === undefined || sameAgentId(reference.agentId, agentId))
? [handlerIndex] ? [handlerIndex]
: []; : [];
}); });
@@ -248,7 +247,7 @@ function referencesForEvent(
const reference = exactCurrentReference(handler, scriptName); const reference = exactCurrentReference(handler, scriptName);
if (!reference if (!reference
|| !reference.executablePath || !reference.executablePath
|| !sameLettaPath(reference.executablePath, process.execPath)) continue; || !samePath(reference.executablePath, process.execPath)) continue;
const key = process.platform === 'win32' const key = process.platform === 'win32'
? reference.agentId.toLowerCase() ? reference.agentId.toLowerCase()
: reference.agentId; : reference.agentId;
@@ -270,7 +269,7 @@ export function lettaRuntimeContracts(hooks: LettaHooks): LettaRuntimeContract[]
const post = posts.get(key); const post = posts.get(key);
const failure = failures.get(key); const failure = failures.get(key);
if (guard.length !== 1 || post?.length !== 1 || failure?.length !== 1) continue; if (guard.length !== 1 || post?.length !== 1 || failure?.length !== 1) continue;
if (!sameLettaPath(post[0].scriptPath, failure[0].scriptPath)) continue; if (!samePath(post[0].scriptPath, failure[0].scriptPath)) continue;
contracts.push({ contracts.push({
agentId: guard[0].agentId, agentId: guard[0].agentId,
guardPath: guard[0].scriptPath, guardPath: guard[0].scriptPath,
+5 -10
View File
@@ -6,7 +6,7 @@ import {
GUARD_SCRIPT, GUARD_SCRIPT,
LETTA_AUDIT_OPTIONS, LETTA_AUDIT_OPTIONS,
} from './letta-contract.js'; } from './letta-contract.js';
import { sameLettaPath } from './letta-command.js'; import { MAX_SOURCE_BYTES, samePath } from './common.js';
import { import {
lettaDocumentLabel, lettaDocumentLabel,
type RenderedLettaDocument, type RenderedLettaDocument,
@@ -31,16 +31,11 @@ import {
const DISPLAY_NAME = 'Letta Code'; const DISPLAY_NAME = 'Letta Code';
const SETTINGS_DIRECTORY_LABEL = 'Letta Code global configuration directory'; const SETTINGS_DIRECTORY_LABEL = 'Letta Code global configuration directory';
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
export type LettaRuntimePaths = ManagedRuntimePaths;
export type PreparedLettaInstallation = PreparedManagedInstallation;
export type { RenameFile };
export async function preflightLettaInstallation( export async function preflightLettaInstallation(
config: InstallConfig, config: InstallConfig,
sources: LettaSources, sources: LettaSources,
): Promise<LettaRuntimePaths> { ): Promise<ManagedRuntimePaths> {
requireLettaHooksEnabled(sources); requireLettaHooksEnabled(sources);
return preflightManagedInstallation({ return preflightManagedInstallation({
agentKey: AGENT_KEY, agentKey: AGENT_KEY,
@@ -54,7 +49,7 @@ export async function preflightLettaInstallation(
function readOnlyPreconditions(sources: LettaSources, changedPath?: string) { function readOnlyPreconditions(sources: LettaSources, changedPath?: string) {
return sources.preconditions.filter((condition) => ( return sources.preconditions.filter((condition) => (
changedPath === undefined || !sameLettaPath(condition.filePath, changedPath) changedPath === undefined || !samePath(condition.filePath, changedPath)
)); ));
} }
@@ -62,7 +57,7 @@ export async function prepareLettaInstallation(
config: InstallConfig, config: InstallConfig,
sources: LettaSources, sources: LettaSources,
rendered: RenderedLettaDocument, rendered: RenderedLettaDocument,
): Promise<PreparedLettaInstallation> { ): Promise<PreparedManagedInstallation> {
await preflightLettaInstallation(config, sources); await preflightLettaInstallation(config, sources);
const settingsSource = rendered.next ?? rendered.document.raw; const settingsSource = rendered.next ?? rendered.document.raw;
const prepared = await prepareManagedInstallation({ const prepared = await prepareManagedInstallation({
@@ -89,7 +84,7 @@ export async function prepareLettaInstallation(
} }
export async function commitLettaInstallation( export async function commitLettaInstallation(
prepared: PreparedLettaInstallation, prepared: PreparedManagedInstallation,
renameFile?: RenameFile, renameFile?: RenameFile,
): Promise<void> { ): Promise<void> {
await commitManagedInstallation(prepared, renameFile); await commitManagedInstallation(prepared, renameFile);
+4 -14
View File
@@ -9,14 +9,13 @@ import {
type LettaDocument, type LettaDocument,
type LettaDocumentKind, type LettaDocumentKind,
} from './letta-config.js'; } from './letta-config.js';
import { hasCode, MAX_SOURCE_BYTES, pathKey, samePath } from './common.js';
import { import {
inspectPhysicalDirectory, inspectPhysicalDirectory,
readPhysicalFile, readPhysicalFile,
type FileSnapshot, type FileSnapshot,
} from './managed-files.js'; } from './managed-files.js';
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
export interface LettaSourcePrecondition { export interface LettaSourcePrecondition {
readonly filePath: string; readonly filePath: string;
readonly label: string; readonly label: string;
@@ -39,15 +38,6 @@ export interface LettaSources {
readonly preconditions: readonly LettaSourcePrecondition[]; readonly preconditions: readonly LettaSourcePrecondition[];
} }
function comparisonPath(filePath: string): string {
const resolved = path.resolve(filePath);
return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
}
function hasCode(error: unknown, code: string): boolean {
return typeof error === 'object' && error !== null && 'code' in error && error.code === code;
}
async function canonicalPath(filePath: string): Promise<string> { async function canonicalPath(filePath: string): Promise<string> {
try { try {
return await fsp.realpath(filePath); return await fsp.realpath(filePath);
@@ -93,7 +83,7 @@ function deduplicatePreconditions(
): LettaSourcePrecondition[] { ): LettaSourcePrecondition[] {
const result = new Map<string, LettaSourcePrecondition>(); const result = new Map<string, LettaSourcePrecondition>();
for (const value of values) { for (const value of values) {
const key = comparisonPath(value.filePath); const key = pathKey(value.filePath);
if (!result.has(key)) result.set(key, value); if (!result.has(key)) result.set(key, value);
} }
return [...result.values()]; return [...result.values()];
@@ -123,7 +113,7 @@ export async function readLettaSources(): Promise<LettaSources> {
const projectDirectory = path.join(workspace, '.letta'); const projectDirectory = path.join(workspace, '.letta');
await inspectPhysicalDirectory(homeDirectory, 'Letta Code home directory'); await inspectPhysicalDirectory(homeDirectory, 'Letta Code home directory');
await inspectPhysicalDirectory(globalDirectory, 'Letta Code global configuration directory'); await inspectPhysicalDirectory(globalDirectory, 'Letta Code global configuration directory');
if (comparisonPath(projectDirectory) !== comparisonPath(globalDirectory)) { if (!samePath(projectDirectory, globalDirectory)) {
await inspectPhysicalDirectory(projectDirectory, 'Letta Code project configuration directory'); await inspectPhysicalDirectory(projectDirectory, 'Letta Code project configuration directory');
} }
const globalPath = path.join(globalDirectory, 'settings.json'); const globalPath = path.join(globalDirectory, 'settings.json');
@@ -133,7 +123,7 @@ export async function readLettaSources(): Promise<LettaSources> {
canonicalPath(workspace), canonicalPath(workspace),
canonicalPath(homeDirectory), canonicalPath(homeDirectory),
]); ]);
const projectActive = comparisonPath(canonicalWorkspace) !== comparisonPath(canonicalHome); const projectActive = !samePath(canonicalWorkspace, canonicalHome);
const global = await readDocument('global', globalPath); const global = await readDocument('global', globalPath);
const project = projectActive const project = projectActive
? await readDocument('project', projectPath) ? await readDocument('project', projectPath)
+2 -14
View File
@@ -1,7 +1,8 @@
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import type { HookScriptOptions } from './hook-template.js'; import type { HookScriptOptions } from './hook-template.js';
import { samePath } from './common.js'; import { errorMessage, samePath } from './common.js';
import { isNodeExecutable } from './shell-command.js';
import { parseStrictJsonObject } from './strict-json.js'; import { parseStrictJsonObject } from './strict-json.js';
export const AGENT_KEY = 'opencode'; export const AGENT_KEY = 'opencode';
@@ -51,10 +52,6 @@ interface OpenCodePluginMetadata {
readonly auditPath: string; readonly auditPath: string;
} }
export function sameOpenCodeAgentId(left: string, right: string): boolean {
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
}
export function resolveOpenCodePaths( export function resolveOpenCodePaths(
homeDirectory = os.homedir(), homeDirectory = os.homedir(),
xdgConfigHome = process.env.XDG_CONFIG_HOME, xdgConfigHome = process.env.XDG_CONFIG_HOME,
@@ -83,11 +80,6 @@ function validAgentSegment(agentId: string): boolean {
&& path.basename(agentId) === agentId; && path.basename(agentId) === agentId;
} }
function isNodeExecutable(filePath: string): boolean {
const basename = path.basename(filePath).toLowerCase();
return basename === 'node' || basename === 'node.exe';
}
function validateRuntimePaths(metadata: OpenCodePluginMetadata): void { function validateRuntimePaths(metadata: OpenCodePluginMetadata): void {
if (!validAgentSegment(metadata.agentId)) { if (!validAgentSegment(metadata.agentId)) {
throw new Error('OpenCode plugin metadata contains an invalid agentId'); throw new Error('OpenCode plugin metadata contains an invalid agentId');
@@ -287,10 +279,6 @@ export const ElydoraAuditPlugin = async () => ({
`); `);
} }
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
export function parseOpenCodePlugin( export function parseOpenCodePlugin(
filePath: string, filePath: string,
source: string, source: string,
+5 -9
View File
@@ -7,8 +7,8 @@ import {
OPENCODE_AUDIT_OPTIONS, OPENCODE_AUDIT_OPTIONS,
buildOpenCodeMetadata, buildOpenCodeMetadata,
buildOpenCodePlugin, buildOpenCodePlugin,
sameOpenCodeAgentId,
} from './opencode-contract.js'; } from './opencode-contract.js';
import { sameAgentId } from './common.js';
import type { OpenCodePluginFile, OpenCodeSources } from './opencode-io.js'; import type { OpenCodePluginFile, OpenCodeSources } from './opencode-io.js';
import { import {
commitManagedInstallation, commitManagedInstallation,
@@ -29,14 +29,10 @@ import {
const DISPLAY_NAME = 'OpenCode'; const DISPLAY_NAME = 'OpenCode';
const DIRECTORY_LABEL = 'OpenCode plugins directory'; const DIRECTORY_LABEL = 'OpenCode plugins directory';
export type OpenCodeRuntimePaths = ManagedRuntimePaths;
export type PreparedOpenCodeInstallation = PreparedManagedInstallation;
export type { RenameFile };
export async function preflightOpenCodeInstallation( export async function preflightOpenCodeInstallation(
config: InstallConfig, config: InstallConfig,
sources: OpenCodeSources, sources: OpenCodeSources,
): Promise<OpenCodeRuntimePaths> { ): Promise<ManagedRuntimePaths> {
return preflightManagedInstallation({ return preflightManagedInstallation({
agentKey: AGENT_KEY, agentKey: AGENT_KEY,
hookLocations: [{ hookLocations: [{
@@ -50,7 +46,7 @@ export async function preflightOpenCodeInstallation(
export async function prepareOpenCodeInstallation( export async function prepareOpenCodeInstallation(
config: InstallConfig, config: InstallConfig,
sources: OpenCodeSources, sources: OpenCodeSources,
): Promise<PreparedOpenCodeInstallation> { ): Promise<PreparedManagedInstallation> {
const paths = await preflightOpenCodeInstallation(config, sources); const paths = await preflightOpenCodeInstallation(config, sources);
const metadata = buildOpenCodeMetadata( const metadata = buildOpenCodeMetadata(
config.agentId, config.agentId,
@@ -85,7 +81,7 @@ export async function prepareOpenCodeInstallation(
} }
export async function commitOpenCodeInstallation( export async function commitOpenCodeInstallation(
prepared: PreparedOpenCodeInstallation, prepared: PreparedManagedInstallation,
renameFile?: RenameFile, renameFile?: RenameFile,
): Promise<void> { ): Promise<void> {
await commitManagedInstallation(prepared, renameFile); await commitManagedInstallation(prepared, renameFile);
@@ -96,7 +92,7 @@ function ownedByAgent<TContract extends { readonly agentId: string }>(
agentId?: string, agentId?: string,
): boolean { ): boolean {
return file.contract !== undefined return file.contract !== undefined
&& (agentId === undefined || sameOpenCodeAgentId(file.contract.agentId, agentId)); && (agentId === undefined || sameAgentId(file.contract.agentId, agentId));
} }
export async function prepareOpenCodeUninstall( export async function prepareOpenCodeUninstall(
+5 -10
View File
@@ -9,11 +9,10 @@ import {
type OpenCodePaths, type OpenCodePaths,
type OpenCodeRuntimeContract, type OpenCodeRuntimeContract,
} from './opencode-contract.js'; } from './opencode-contract.js';
import { errorMessage, hasCode, MAX_CONFIG_BYTES } from './common.js';
import { inspectPhysicalDirectory, readPhysicalFile, type FileSnapshot } from './managed-files.js'; import { inspectPhysicalDirectory, readPhysicalFile, type FileSnapshot } from './managed-files.js';
import { managedRuntimeFilesExist } from './managed-runtime-status.js'; import { managedRuntimeFilesExist } from './managed-runtime-status.js';
const MAX_PLUGIN_BYTES = 512 * 1024;
export interface OpenCodePluginFile<TContract> { export interface OpenCodePluginFile<TContract> {
readonly exists: boolean; readonly exists: boolean;
readonly filePath: string; readonly filePath: string;
@@ -40,7 +39,7 @@ async function readPluginFile<TContract>(
label: string, label: string,
parse: (filePath: string, source: string) => TContract | undefined, parse: (filePath: string, source: string) => TContract | undefined,
): Promise<OpenCodePluginFile<TContract>> { ): Promise<OpenCodePluginFile<TContract>> {
const snapshot = await readPhysicalFile(filePath, label, MAX_PLUGIN_BYTES); const snapshot = await readPhysicalFile(filePath, label, MAX_CONFIG_BYTES);
if (!snapshot) return { exists: false, filePath }; if (!snapshot) return { exists: false, filePath };
return { return {
exists: true, exists: true,
@@ -73,18 +72,14 @@ export function requireAvailableOpenCodePlugin(
} }
} }
function hasCode(error: unknown, code: string): boolean {
return typeof error === 'object' && error !== null && 'code' in error && error.code === code;
}
async function executableExists(filePath: string): Promise<boolean> { async function executableExists(filePath: string): Promise<boolean> {
try { try {
return (await fsp.stat(filePath)).isFile(); return (await fsp.stat(filePath)).isFile();
} catch (error) { } catch (error) {
if (hasCode(error, 'ENOENT') || hasCode(error, 'ENOTDIR')) return false; if (hasCode(error, 'ENOENT') || hasCode(error, 'ENOTDIR')) return false;
throw new Error(`Inspect OpenCode Node.js runtime at ${filePath}: ${ throw new Error(`Inspect OpenCode Node.js runtime at ${filePath}: ${errorMessage(error)}`, {
error instanceof Error ? error.message : String(error) cause: error instanceof Error ? error : new Error(String(error)),
}`, { cause: error instanceof Error ? error : new Error(String(error)) }); });
} }
} }
+13 -106
View File
@@ -1,103 +1,20 @@
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { managedScriptReference, type ManagedScriptReference } from './common.js';
import {
isNodeExecutable,
parsePosixCommand,
parsePowerShellSource,
posixSource,
powerShellSource,
} from './shell-command.js';
interface ParsedArgument { export type QwenRuntimeReference = ManagedScriptReference;
readonly value: string;
readonly next: number;
}
export interface QwenRuntimeReference {
readonly agentId: string;
readonly scriptPath: string;
}
export function sameQwenPath(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 sameQwenAgentId(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("'", "''")}'`;
}
export function buildQwenCommand(scriptPath: string): string { export function buildQwenCommand(scriptPath: string): string {
if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) { if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) {
throw new Error('Qwen Code hook commands require absolute executable and script paths'); throw new Error('Qwen Code hook commands require absolute executable and script paths');
} }
if (process.platform === 'win32') { return process.platform === 'win32' ? powerShellSource(scriptPath) : posixSource(scriptPath);
return `& ${quotePowerShell(process.execPath)} ${quotePowerShell(scriptPath)}; exit $LASTEXITCODE`;
}
return `${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 parsePowerShellCommand(command: string): readonly [string, string] | undefined {
if (!command.startsWith('& ')) return undefined;
const executable = readPowerShellArgument(command, 2);
if (!executable || command[executable.next] !== ' ') return undefined;
const script = readPowerShellArgument(command, executable.next + 1);
if (!script || command.slice(script.next) !== '; exit $LASTEXITCODE') return undefined;
return [executable.value, script.value];
}
function isNodeExecutable(filePath: string): boolean {
const basename = path.basename(filePath).toLowerCase();
return basename === 'node' || basename === 'node.exe';
} }
export function qwenRuntimeReference( export function qwenRuntimeReference(
@@ -105,18 +22,8 @@ export function qwenRuntimeReference(
scriptName: string, scriptName: string,
): QwenRuntimeReference | undefined { ): QwenRuntimeReference | undefined {
const parsed = process.platform === 'win32' const parsed = process.platform === 'win32'
? parsePowerShellCommand(command) ? parsePowerShellSource(command)
: parsePosixCommand(command); : parsePosixCommand(command);
if (!parsed if (!parsed || !path.isAbsolute(parsed[0]) || !isNodeExecutable(parsed[0])) return undefined;
|| !path.isAbsolute(parsed[0]) return managedScriptReference(parsed[1], scriptName);
|| !isNodeExecutable(parsed[0])
|| !path.isAbsolute(parsed[1])
|| path.basename(parsed[1]) !== scriptName) return undefined;
const agentDirectory = path.dirname(parsed[1]);
if (!sameQwenPath(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] };
} }
+10 -86
View File
@@ -1,25 +1,15 @@
import { import type { JSONPath } from 'jsonc-parser';
applyEdits,
modify,
parse,
parseTree,
printParseErrorCode,
type FormattingOptions,
type JSONPath,
type Node,
type ParseError,
} from 'jsonc-parser';
import type { FileSnapshot } from './managed-files.js'; import type { FileSnapshot } from './managed-files.js';
import { changeJsonc } from './jsonc-edit.js';
import { import {
MANAGED_EVENTS, MANAGED_EVENTS,
managedQwenRemovals, managedQwenRemovals,
readQwenHooks, readQwenHooks,
type JsonObject,
type ManagedQwenEvent, type ManagedQwenEvent,
type QwenGroup, type QwenGroup,
type QwenHooks, type QwenHooks,
isObject,
} from './qwen-contract.js'; } from './qwen-contract.js';
import { isObject, parseCommentedJsonObject, type JsonObject } from './strict-json.js';
export const QWEN_OWNED_FILE_MARKER = '// Managed by Elydora'; export const QWEN_OWNED_FILE_MARKER = '// Managed by Elydora';
@@ -53,50 +43,6 @@ interface DocumentOptions {
readonly snapshot?: FileSnapshot; readonly snapshot?: FileSnapshot;
} }
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);
}
}
export function parseQwenJsoncObject(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 qwenSourceLabel(kind: QwenDocumentKind): string { export function qwenSourceLabel(kind: QwenDocumentKind): string {
switch (kind) { switch (kind) {
case 'system-defaults': return 'Qwen Code system defaults'; case 'system-defaults': return 'Qwen Code system defaults';
@@ -122,7 +68,7 @@ function readFolderTrustEnabled(root: JsonObject, label: string): boolean | unde
export function parseQwenDocument(options: DocumentOptions): QwenDocument { export function parseQwenDocument(options: DocumentOptions): QwenDocument {
const label = `${qwenSourceLabel(options.kind)} at ${options.filePath}`; const label = `${qwenSourceLabel(options.kind)} at ${options.filePath}`;
const root = parseQwenJsoncObject(options.raw, label); const root = parseCommentedJsonObject(options.raw, label);
if (root.disableAllHooks !== undefined && typeof root.disableAllHooks !== 'boolean') { if (root.disableAllHooks !== undefined && typeof root.disableAllHooks !== 'boolean') {
throw new Error(`${label} field "disableAllHooks" must be a boolean`); throw new Error(`${label} field "disableAllHooks" must be a boolean`);
} }
@@ -150,28 +96,6 @@ export function createQwenDocument(
}); });
} }
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: QwenDocument, raw: string): QwenDocument { function currentDocument(document: QwenDocument, raw: string): QwenDocument {
return parseQwenDocument({ return parseQwenDocument({
kind: document.kind, kind: document.kind,
@@ -195,25 +119,25 @@ function removeManagedEntries(
for (const removal of eventRemovals) { for (const removal of eventRemovals) {
const groupPath: JSONPath = ['hooks', event, removal.groupIndex]; const groupPath: JSONPath = ['hooks', event, removal.groupIndex];
if (removal.removeGroup) { if (removal.removeGroup) {
raw = change(raw, groupPath, undefined); raw = changeJsonc(raw, groupPath, undefined);
continue; continue;
} }
for (const handlerIndex of [...removal.handlerIndexes].sort( for (const handlerIndex of [...removal.handlerIndexes].sort(
(left, right) => right - left, (left, right) => right - left,
)) { )) {
raw = change(raw, [...groupPath, 'hooks', handlerIndex], undefined); raw = changeJsonc(raw, [...groupPath, 'hooks', handlerIndex], undefined);
} }
} }
if (eventRemovals.length > 0) { if (eventRemovals.length > 0) {
const current = currentDocument(document, raw); const current = currentDocument(document, raw);
if ((current.hooks[event] ?? []).length === 0) { if ((current.hooks[event] ?? []).length === 0) {
raw = change(raw, ['hooks', event], undefined); raw = changeJsonc(raw, ['hooks', event], undefined);
} }
} }
} }
const current = currentDocument(document, raw); const current = currentDocument(document, raw);
if (current.hasHooksContainer && Object.keys(current.hooks).length === 0) { if (current.hasHooksContainer && Object.keys(current.hooks).length === 0) {
raw = change(raw, ['hooks'], undefined); raw = changeJsonc(raw, ['hooks'], undefined);
} }
return raw; return raw;
} }
@@ -226,9 +150,9 @@ function appendGroup(
): string { ): string {
const current = currentDocument(document, raw); const current = currentDocument(document, raw);
if (current.hooks[event]) { if (current.hooks[event]) {
return change(raw, ['hooks', event, current.hooks[event].length], group, true); return changeJsonc(raw, ['hooks', event, current.hooks[event].length], group, true);
} }
return change(raw, ['hooks', event], [group]); return changeJsonc(raw, ['hooks', event], [group]);
} }
export function renderQwenDocument( export function renderQwenDocument(
+3 -6
View File
@@ -1,8 +1,7 @@
import { sameAgentId, samePath } from './common.js';
import { import {
buildQwenCommand, buildQwenCommand,
qwenRuntimeReference, qwenRuntimeReference,
sameQwenAgentId,
sameQwenPath,
type QwenRuntimeReference, type QwenRuntimeReference,
} from './qwen-command.js'; } from './qwen-command.js';
import { isObject, type JsonObject } from './strict-json.js'; import { isObject, type JsonObject } from './strict-json.js';
@@ -283,7 +282,7 @@ export function managedQwenRemovals(
(hooks[event] ?? []).forEach((group, groupIndex) => { (hooks[event] ?? []).forEach((group, groupIndex) => {
const handlerIndexes = group.hooks.flatMap((handler, handlerIndex) => { const handlerIndexes = group.hooks.flatMap((handler, handlerIndex) => {
const reference = managedReference(handler, scriptName, hookName, true); const reference = managedReference(handler, scriptName, hookName, true);
return reference && (agentId === undefined || sameQwenAgentId(reference.agentId, agentId)) return reference && (agentId === undefined || sameAgentId(reference.agentId, agentId))
? [handlerIndex] ? [handlerIndex]
: []; : [];
}); });
@@ -334,7 +333,7 @@ export function qwenRuntimeContracts(hooks: QwenHooks): QwenRuntimeContract[] {
const post = posts.get(key); const post = posts.get(key);
const failure = failures.get(key); const failure = failures.get(key);
if (guard.length !== 1 || post?.length !== 1 || failure?.length !== 1) continue; if (guard.length !== 1 || post?.length !== 1 || failure?.length !== 1) continue;
if (!sameQwenPath(post[0].scriptPath, failure[0].scriptPath)) continue; if (!samePath(post[0].scriptPath, failure[0].scriptPath)) continue;
contracts.push({ contracts.push({
agentId: guard[0].agentId, agentId: guard[0].agentId,
guardPath: guard[0].scriptPath, guardPath: guard[0].scriptPath,
@@ -343,5 +342,3 @@ export function qwenRuntimeContracts(hooks: QwenHooks): QwenRuntimeContract[] {
} }
return contracts; return contracts;
} }
export { isObject, type JsonObject };
+5 -10
View File
@@ -5,7 +5,7 @@ import {
AUDIT_SCRIPT, AUDIT_SCRIPT,
GUARD_SCRIPT, GUARD_SCRIPT,
} from './qwen-contract.js'; } from './qwen-contract.js';
import { sameQwenPath } from './qwen-command.js'; import { MAX_SOURCE_BYTES, samePath } from './common.js';
import { import {
qwenDocumentLabel, qwenDocumentLabel,
type RenderedQwenDocument, type RenderedQwenDocument,
@@ -30,16 +30,11 @@ import {
const DISPLAY_NAME = 'Qwen Code'; const DISPLAY_NAME = 'Qwen Code';
const SETTINGS_DIRECTORY_LABEL = 'Qwen Code user configuration directory'; const SETTINGS_DIRECTORY_LABEL = 'Qwen Code user configuration directory';
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
export type QwenRuntimePaths = ManagedRuntimePaths;
export type PreparedQwenInstallation = PreparedManagedInstallation;
export type { RenameFile };
export async function preflightQwenInstallation( export async function preflightQwenInstallation(
config: InstallConfig, config: InstallConfig,
sources: QwenSources, sources: QwenSources,
): Promise<QwenRuntimePaths> { ): Promise<ManagedRuntimePaths> {
requireQwenHooksEnabled(sources); requireQwenHooksEnabled(sources);
return preflightManagedInstallation({ return preflightManagedInstallation({
agentKey: AGENT_KEY, agentKey: AGENT_KEY,
@@ -53,7 +48,7 @@ export async function preflightQwenInstallation(
function readOnlyPreconditions(sources: QwenSources, changedPath?: string) { function readOnlyPreconditions(sources: QwenSources, changedPath?: string) {
return sources.preconditions.filter((condition) => ( return sources.preconditions.filter((condition) => (
changedPath === undefined || !sameQwenPath(condition.filePath, changedPath) changedPath === undefined || !samePath(condition.filePath, changedPath)
)); ));
} }
@@ -61,7 +56,7 @@ export async function prepareQwenInstallation(
config: InstallConfig, config: InstallConfig,
sources: QwenSources, sources: QwenSources,
rendered: RenderedQwenDocument, rendered: RenderedQwenDocument,
): Promise<PreparedQwenInstallation> { ): Promise<PreparedManagedInstallation> {
await preflightQwenInstallation(config, sources); await preflightQwenInstallation(config, sources);
const settingsSource = rendered.next ?? rendered.document.raw; const settingsSource = rendered.next ?? rendered.document.raw;
const prepared = await prepareManagedInstallation({ const prepared = await prepareManagedInstallation({
@@ -88,7 +83,7 @@ export async function prepareQwenInstallation(
} }
export async function commitQwenInstallation( export async function commitQwenInstallation(
prepared: PreparedQwenInstallation, prepared: PreparedManagedInstallation,
renameFile?: RenameFile, renameFile?: RenameFile,
): Promise<void> { ): Promise<void> {
await commitManagedInstallation(prepared, renameFile); await commitManagedInstallation(prepared, renameFile);
+3 -91
View File
@@ -1,99 +1,11 @@
import os from 'node:os'; import { AGENT_KEY, type QwenRuntimeContract } from './qwen-contract.js';
import path from 'node:path'; import { managedRuntimeFilesExist } from './managed-runtime-status.js';
import { generateGuardScript } from './guard-template.js';
import { generateHookScript } from './hook-template.js';
import {
AGENT_KEY,
type QwenRuntimeContract,
} from './qwen-contract.js';
import { sameQwenAgentId, sameQwenPath } from './qwen-command.js';
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
import { parseStrictJsonObject, type JsonObject } from './strict-json.js';
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: QwenRuntimeContract,
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 (!sameQwenAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
throw new Error(`Elydora runtime identity does not match Qwen Code 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: QwenRuntimeContract): Promise<boolean> {
const runtimeRoot = path.join(os.homedir(), '.elydora');
const agentDirectory = path.dirname(contract.guardPath);
if (!sameQwenPath(path.dirname(agentDirectory), runtimeRoot)
|| !sameQwenPath(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 === generateGuardScript(AGENT_KEY, contract.agentId)
&& audit.contents === generateHookScript(
AGENT_KEY,
contract.agentId,
{ nativePayload: true },
);
}
export async function qwenRuntimeFilesExist( export async function qwenRuntimeFilesExist(
contracts: readonly QwenRuntimeContract[], contracts: readonly QwenRuntimeContract[],
): Promise<boolean> { ): Promise<boolean> {
for (const contract of contracts) { for (const contract of contracts) {
if (await runtimeContractExists(contract)) return true; if (await managedRuntimeFilesExist(contract, AGENT_KEY)) return true;
} }
return false; return false;
} }
+8 -14
View File
@@ -2,18 +2,17 @@ import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import fsp from 'node:fs/promises'; import fsp from 'node:fs/promises';
import { parse as parseDotenv } from 'dotenv'; import { parse as parseDotenv } from 'dotenv';
import { MAX_SOURCE_BYTES, pathKey, samePath } from './common.js';
import { import {
createQwenDocument, createQwenDocument,
parseQwenDocument, parseQwenDocument,
parseQwenJsoncObject,
qwenDocumentLabel, qwenDocumentLabel,
qwenSourceLabel, qwenSourceLabel,
type QwenDocument, type QwenDocument,
type QwenDocumentKind, type QwenDocumentKind,
} from './qwen-config.js'; } from './qwen-config.js';
import { readPhysicalFile, type FileSnapshot } from './managed-files.js'; import { readPhysicalFile, type FileSnapshot } from './managed-files.js';
import { parseCommentedJsonObject } from './strict-json.js';
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
const HOME_ENV_KEYS = ['QWEN_HOME', 'QWEN_RUNTIME_DIR'] as const; const HOME_ENV_KEYS = ['QWEN_HOME', 'QWEN_RUNTIME_DIR'] as const;
export interface QwenSourcePrecondition { export interface QwenSourcePrecondition {
@@ -94,7 +93,7 @@ async function resolveQwenRouting(): Promise<RoutingResult> {
const readCandidate = async (filePath: string): Promise<void> => { const readCandidate = async (filePath: string): Promise<void> => {
const resolved = path.resolve(filePath); const resolved = path.resolve(filePath);
const key = process.platform === 'win32' ? resolved.toLowerCase() : resolved; const key = pathKey(resolved);
if (visited.has(key)) return; if (visited.has(key)) return;
visited.add(key); visited.add(key);
const snapshot = await readPhysicalFile(resolved, 'Qwen Code home environment'); const snapshot = await readPhysicalFile(resolved, 'Qwen Code home environment');
@@ -172,13 +171,8 @@ async function canonicalPath(filePath: string): Promise<string> {
} }
} }
function comparisonPath(filePath: string): string {
const resolved = path.resolve(filePath);
return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
}
function isWithin(child: string, parent: string): boolean { function isWithin(child: string, parent: string): boolean {
const relative = path.relative(comparisonPath(parent), comparisonPath(child)); const relative = path.relative(pathKey(parent), pathKey(child));
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative)); return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
} }
@@ -202,7 +196,7 @@ async function workspaceTrust(
original: snapshot, original: snapshot,
}; };
if (!snapshot) return { trusted: true, precondition }; if (!snapshot) return { trusted: true, precondition };
const rules = parseQwenJsoncObject(snapshot.contents, `Qwen Code trusted folders at ${filePath}`); const rules = parseCommentedJsonObject(snapshot.contents, `Qwen Code trusted folders at ${filePath}`);
for (const [rulePath, level] of Object.entries(rules)) { for (const [rulePath, level] of Object.entries(rules)) {
if (!['TRUST_FOLDER', 'TRUST_PARENT', 'DO_NOT_TRUST'].includes(String(level))) { if (!['TRUST_FOLDER', 'TRUST_PARENT', 'DO_NOT_TRUST'].includes(String(level))) {
throw new Error(`Qwen Code trusted folders has invalid trust level for "${rulePath}"`); throw new Error(`Qwen Code trusted folders has invalid trust level for "${rulePath}"`);
@@ -217,7 +211,7 @@ async function workspaceTrust(
} }
for (const [rulePath, level] of Object.entries(rules)) { for (const [rulePath, level] of Object.entries(rules)) {
if (level === 'DO_NOT_TRUST' if (level === 'DO_NOT_TRUST'
&& comparisonPath(workspace) === comparisonPath(await canonicalPath(rulePath))) { && samePath(workspace, await canonicalPath(rulePath))) {
return { trusted: false, precondition }; return { trusted: false, precondition };
} }
} }
@@ -256,7 +250,7 @@ function deduplicatePreconditions(
): QwenSourcePrecondition[] { ): QwenSourcePrecondition[] {
const result = new Map<string, QwenSourcePrecondition>(); const result = new Map<string, QwenSourcePrecondition>();
for (const value of values) { for (const value of values) {
const key = comparisonPath(value.filePath); const key = pathKey(value.filePath);
if (!result.has(key)) result.set(key, value); if (!result.has(key)) result.set(key, value);
} }
return [...result.values()]; return [...result.values()];
@@ -276,7 +270,7 @@ export async function readQwenSources(): Promise<QwenSources> {
canonicalPath(process.cwd()), canonicalPath(process.cwd()),
canonicalPath(os.homedir()), canonicalPath(os.homedir()),
]); ]);
const workspaceActive = comparisonPath(canonicalWorkspace) !== comparisonPath(canonicalHome); const workspaceActive = !samePath(canonicalWorkspace, canonicalHome);
const workspace = workspaceActive const workspace = workspaceActive
? await readDocument('workspace', workspacePath) ? await readDocument('workspace', workspacePath)
: createQwenDocument('workspace', workspacePath); : createQwenDocument('workspace', workspacePath);
+7
View File
@@ -66,6 +66,13 @@ export function parseStrictJsonObject(raw: string, label: string): JsonObject {
}); });
} }
export function parseCommentedJsonObject(raw: string, label: string): JsonObject {
return parseJsonObject(raw, label, {
allowTrailingComma: false,
disallowComments: false,
});
}
export function parseStrictJsoncObject(raw: string, label: string): JsonObject { export function parseStrictJsoncObject(raw: string, label: string): JsonObject {
return parseJsonObject(raw, label, { return parseJsonObject(raw, label, {
allowTrailingComma: true, allowTrailingComma: true,
+36 -147
View File
@@ -1,140 +1,60 @@
import { spawn } from 'node:child_process';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { pathToFileURL } from 'node:url'; import {
createFixtureRoot,
distUrl,
homeEnvironment,
installConfig as baseInstallConfig,
runPlugin as basePlugin,
runShell,
writeOptionalJson,
} from './harness.mjs';
export const VALID_PRIVATE_KEY = Buffer.alloc(32).toString('base64url'); export {
export const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/augment.js')).href; VALID_PRIVATE_KEY,
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href; cliPath,
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/augment-io.js')).href; managedInstallationModuleUrl,
export const installationModuleUrl = pathToFileURL( readSettings,
path.resolve('dist/plugins/augment-installation.js'), registryModuleUrl,
).href; runNode,
export const managedInstallationModuleUrl = pathToFileURL( runProcess,
path.resolve('dist/plugins/managed-installation.js'), startApiServer,
).href; writeJson,
export const cliPath = path.resolve('dist/cli.js'); } from './harness.mjs';
export const pluginModuleUrl = distUrl('plugins/augment.js');
export const ioModuleUrl = distUrl('plugins/augment-io.js');
export const installationModuleUrl = distUrl('plugins/augment-installation.js');
export const wrapperExtension = process.platform === 'win32' ? '.cmd' : '.sh'; export const wrapperExtension = process.platform === 'win32' ? '.cmd' : '.sh';
export const guardWrapperName = `augment-guard${wrapperExtension}`; export const guardWrapperName = `augment-guard${wrapperExtension}`;
export const auditWrapperName = `augment-hook${wrapperExtension}`; export const auditWrapperName = `augment-hook${wrapperExtension}`;
const PLUGIN = { exportName: 'augmentPlugin', moduleUrl: pluginModuleUrl };
export function runProcess(command, args, env, cwd, input = '') {
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
cwd,
env: { ...process.env, ...env },
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
}
export function runNode(args, env, cwd, input = '') {
return runProcess(process.execPath, args, env, cwd, input);
}
export function runHandler(handler, input, fixture) { export function runHandler(handler, input, fixture) {
return new Promise((resolve, reject) => { return runShell(handler.command, homeEnvironment(fixture), fixture.projectDir, input);
const child = spawn(handler.command, {
cwd: fixture.projectDir,
env: { ...process.env, HOME: fixture.homeDir, USERPROFILE: fixture.homeDir },
shell: true,
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
}
export async function writeJson(filePath, value) {
await mkdir(path.dirname(filePath), { recursive: true });
const contents = typeof value === 'string' ? value : `${JSON.stringify(value, null, 2)}\n`;
await writeFile(filePath, contents, { encoding: 'utf-8', mode: 0o600 });
} }
export function installConfig(fixture, overrides = {}) { export function installConfig(fixture, overrides = {}) {
return { return baseInstallConfig('augment', fixture, overrides);
agentName: 'augment',
orgId: 'org-1',
agentId: 'agent-1',
privateKey: VALID_PRIVATE_KEY,
kid: 'kid-1',
token: 'token-1',
baseUrl: fixture.baseUrl,
guardScriptPath: fixture.guardScriptPath,
hookScriptPath: fixture.hookScriptPath,
...overrides,
};
} }
export async function runPlugin(fixture, method, argument) { export function runPlugin(fixture, method, argument) {
const source = ` return basePlugin(PLUGIN, fixture, method, argument);
import { augmentPlugin } from ${JSON.stringify(pluginModuleUrl)};
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT);
const result = await augmentPlugin[process.env.ELYDORA_TEST_METHOD](argument);
if (result !== undefined) console.log(JSON.stringify(result));
`;
return runNode(
['--input-type=module', '--eval', source],
{
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
ELYDORA_TEST_ARGUMENT: JSON.stringify(argument),
ELYDORA_TEST_METHOD: method,
},
fixture.projectDir,
);
} }
export async function createFixture({ baseUrl = 'http://127.0.0.1:9', settings } = {}) { export async function createFixture({ baseUrl = 'http://127.0.0.1:9', settings } = {}) {
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-augment-')); const base = await createFixtureRoot('elydora-augment-', "home with spaces and 'quote %AUGGIE%");
const homeDir = path.join(rootDir, "home with spaces and 'quote %AUGGIE%"); const settingsPath = path.join(base.homeDir, '.augment', 'settings.json');
const projectDir = path.join(rootDir, 'project with spaces'); await writeOptionalJson(settingsPath, settings);
const settingsPath = path.join(homeDir, '.augment', 'settings.json'); return {
const agentDir = path.join(homeDir, '.elydora', 'agent-1'); ...base,
const guardScriptPath = path.join(agentDir, 'guard.js'); auditWrapperPath: path.join(base.agentDir, auditWrapperName),
const hookScriptPath = path.join(agentDir, 'hook.js');
await mkdir(projectDir, { recursive: true });
if (settings !== undefined) await writeJson(settingsPath, settings);
const fixture = {
agentDir,
auditWrapperPath: path.join(agentDir, auditWrapperName),
baseUrl, baseUrl,
guardScriptPath, guardWrapperPath: path.join(base.agentDir, guardWrapperName),
guardWrapperPath: path.join(agentDir, guardWrapperName),
homeDir,
hookScriptPath,
projectDir,
rootDir,
settingsPath, settingsPath,
install(overrides = {}) { install(overrides = {}) {
return runPlugin(this, 'install', installConfig(this, overrides)); return runPlugin(this, 'install', installConfig(this, overrides));
}, },
async close() {
await rm(rootDir, { recursive: true, force: true });
},
}; };
return fixture;
}
export async function readSettings(filePath) {
const raw = await readFile(filePath, 'utf-8');
return { raw, settings: JSON.parse(raw) };
} }
export function generatedCommand(wrapperPath) { export function generatedCommand(wrapperPath) {
@@ -150,34 +70,3 @@ export function managedHandler(settings, event, wrapperPath) {
} }
return undefined; return undefined;
} }
export async function startApiServer({ status = 'active', operationStatus = 201 } = {}) {
const requests = [];
const server = http.createServer(async (request, response) => {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
const raw = Buffer.concat(chunks).toString('utf-8');
requests.push({ headers: request.headers, method: request.method, url: request.url, raw });
if (request.method === 'GET') {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify({ agent: { status } }));
return;
}
response.writeHead(operationStatus, { 'Content-Type': 'application/json' });
response.end(operationStatus >= 200 && operationStatus < 300
? JSON.stringify({ operation: { accepted: true } })
: JSON.stringify({ error: { code: 'UPSTREAM_FAILURE', message: 'failed' } }));
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const address = server.address();
return {
baseUrl: `http://127.0.0.1:${address.port}`,
requests,
close: () => new Promise((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}),
};
}
+41 -131
View File
@@ -1,38 +1,32 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { pathToFileURL } from 'node:url'; import {
createFixtureRoot,
distUrl,
homeEnvironment,
installConfig as baseInstallConfig,
optionalEnvironment,
runPlugin as basePlugin,
runProcess as baseProcess,
writeOptionalJson,
} from './harness.mjs';
export const VALID_PRIVATE_KEY = Buffer.alloc(32).toString('base64url'); export {
export const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/claudecode.js')).href; VALID_PRIVATE_KEY,
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href; cliPath,
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/claudecode-io.js')).href; readSettings,
export const installationModuleUrl = pathToFileURL( registryModuleUrl,
path.resolve('dist/plugins/claudecode-installation.js'), startApiServer,
).href; writeJson,
export const cliPath = path.resolve('dist/cli.js'); } from './harness.mjs';
export const pluginModuleUrl = distUrl('plugins/claudecode.js');
export const ioModuleUrl = distUrl('plugins/claudecode-io.js');
export const installationModuleUrl = distUrl('plugins/claudecode-installation.js');
const PLUGIN = { exportName: 'claudecodePlugin', moduleUrl: pluginModuleUrl };
export function runProcess(command, args, env, cwd, input = '', unset = []) { export function runProcess(command, args, env, cwd, input = '', unset = []) {
return new Promise((resolve, reject) => { return baseProcess(command, args, env, cwd, input, { unset });
const childEnv = { ...process.env, ...env };
for (const key of unset) delete childEnv[key];
const child = spawn(command, args, {
cwd,
env: childEnv,
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
} }
export function runNode(args, env, cwd, input = '', unset = []) { export function runNode(args, env, cwd, input = '', unset = []) {
@@ -44,8 +38,7 @@ export function runClaudeHook(handler, input, fixture, environment = {}) {
handler.command, handler.command,
handler.args, handler.args,
{ {
HOME: fixture.homeDir, ...homeEnvironment(fixture),
USERPROFILE: fixture.homeDir,
CLAUDE_CONFIG_DIR: fixture.claudeConfigOverride ?? '', CLAUDE_CONFIG_DIR: fixture.claudeConfigOverride ?? '',
...environment, ...environment,
}, },
@@ -54,51 +47,16 @@ export function runClaudeHook(handler, input, fixture, environment = {}) {
); );
} }
export async function writeJson(filePath, value) {
await mkdir(path.dirname(filePath), { recursive: true });
const contents = typeof value === 'string' ? value : `${JSON.stringify(value, null, 2)}\n`;
await writeFile(filePath, contents, { encoding: 'utf-8', mode: 0o600 });
}
export function installConfig(fixture, overrides = {}) { export function installConfig(fixture, overrides = {}) {
return { return baseInstallConfig('claudecode', fixture, overrides);
agentName: 'claudecode',
orgId: 'org-1',
agentId: 'agent-1',
privateKey: VALID_PRIVATE_KEY,
kid: 'kid-1',
token: 'token-1',
baseUrl: fixture.baseUrl,
guardScriptPath: fixture.guardScriptPath,
hookScriptPath: fixture.hookScriptPath,
...overrides,
};
} }
export async function runPlugin(fixture, method, argument, environment = {}) { export function runPlugin(fixture, method, argument, environment = {}) {
const source = ` const configDir = optionalEnvironment('CLAUDE_CONFIG_DIR', fixture.claudeConfigOverride);
import { claudecodePlugin } from ${JSON.stringify(pluginModuleUrl)}; return basePlugin(PLUGIN, fixture, method, argument, {
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT); env: { ...environment, ...configDir.env },
const result = await claudecodePlugin[process.env.ELYDORA_TEST_METHOD](argument); unset: configDir.unset,
if (result !== undefined) console.log(JSON.stringify(result)); });
`;
const env = {
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
ELYDORA_TEST_ARGUMENT: JSON.stringify(argument),
ELYDORA_TEST_METHOD: method,
...environment,
};
const unset = [];
if (fixture.claudeConfigOverride === undefined) unset.push('CLAUDE_CONFIG_DIR');
else env.CLAUDE_CONFIG_DIR = fixture.claudeConfigOverride;
return runNode(
['--input-type=module', '--eval', source],
env,
fixture.projectDir,
'',
unset,
);
} }
export async function createFixture({ export async function createFixture({
@@ -106,42 +64,25 @@ export async function createFixture({
settings, settings,
explicitClaudeConfig = true, explicitClaudeConfig = true,
} = {}) { } = {}) {
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-claude-')); const base = await createFixtureRoot(
const homeDir = path.join(rootDir, "home with spaces and 'quote %CLAUDE_HOOK_EVENT%"); 'elydora-claude-',
const projectDir = path.join(rootDir, 'project with spaces'); "home with spaces and 'quote %CLAUDE_HOOK_EVENT%",
);
const claudeConfigDir = explicitClaudeConfig const claudeConfigDir = explicitClaudeConfig
? path.join(homeDir, 'custom claude') ? path.join(base.homeDir, 'custom claude')
: path.join(homeDir, '.claude'); : path.join(base.homeDir, '.claude');
const settingsPath = path.join(claudeConfigDir, 'settings.json'); const settingsPath = path.join(claudeConfigDir, 'settings.json');
const agentDir = path.join(homeDir, '.elydora', 'agent-1'); await writeOptionalJson(settingsPath, settings);
const guardScriptPath = path.join(agentDir, 'guard.js'); return {
const hookScriptPath = path.join(agentDir, 'hook.js'); ...base,
await mkdir(projectDir, { recursive: true });
if (settings !== undefined) await writeJson(settingsPath, settings);
const fixture = {
agentDir,
baseUrl, baseUrl,
claudeConfigDir, claudeConfigDir,
claudeConfigOverride: explicitClaudeConfig ? claudeConfigDir : undefined, claudeConfigOverride: explicitClaudeConfig ? claudeConfigDir : undefined,
guardScriptPath,
homeDir,
hookScriptPath,
projectDir,
rootDir,
settingsPath, settingsPath,
install(overrides = {}) { install(overrides = {}) {
return runPlugin(this, 'install', installConfig(this, overrides)); return runPlugin(this, 'install', installConfig(this, overrides));
}, },
async close() {
await rm(rootDir, { recursive: true, force: true });
},
}; };
return fixture;
}
export async function readSettings(filePath) {
const raw = await readFile(filePath, 'utf-8');
return { raw, settings: JSON.parse(raw) };
} }
export function managedHandler(settings, event) { export function managedHandler(settings, event) {
@@ -173,34 +114,3 @@ export function assertManagedHandler(handler, scriptPath, statusMessage) {
export function legacyHandler(scriptPath) { export function legacyHandler(scriptPath) {
return { type: 'command', command: `node "${scriptPath}"` }; return { type: 'command', command: `node "${scriptPath}"` };
} }
export async function startApiServer({ status = 'active', operationStatus = 201 } = {}) {
const requests = [];
const server = http.createServer(async (request, response) => {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
const raw = Buffer.concat(chunks).toString('utf-8');
requests.push({ headers: request.headers, method: request.method, url: request.url, raw });
if (request.method === 'GET') {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify({ agent: { status } }));
return;
}
response.writeHead(operationStatus, { 'Content-Type': 'application/json' });
response.end(operationStatus >= 200 && operationStatus < 300
? JSON.stringify({ operation: { accepted: true } })
: JSON.stringify({ error: { code: 'UPSTREAM_FAILURE', message: 'failed' } }));
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const address = server.address();
return {
baseUrl: `http://127.0.0.1:${address.port}`,
requests,
close: () => new Promise((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}),
};
}
+34 -122
View File
@@ -1,87 +1,39 @@
import { spawn } from 'node:child_process'; import { mkdir, writeFile } from 'node:fs/promises';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { pathToFileURL } from 'node:url'; import {
createFixtureRoot,
distUrl,
homeEnvironment,
installConfig as baseInstallConfig,
runPlugin as basePlugin,
} from './harness.mjs';
export const VALID_PRIVATE_KEY = Buffer.alloc(32, 7).toString('base64url'); export {
export const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/cline.js')).href; VALID_PRIVATE_KEY,
export const contractModuleUrl = pathToFileURL( cliPath,
path.resolve('dist/plugins/cline-contract.js'), readJson,
).href; registryModuleUrl,
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/cline-io.js')).href; runNode,
export const installationModuleUrl = pathToFileURL( runProcess,
path.resolve('dist/plugins/cline-installation.js'), startApiServer,
).href; } from './harness.mjs';
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href;
export const cliPath = path.resolve('dist/cli.js');
export function runProcess(command, args, env, cwd, input = '') { export const pluginModuleUrl = distUrl('plugins/cline.js');
return new Promise((resolve, reject) => { export const contractModuleUrl = distUrl('plugins/cline-contract.js');
const childEnvironment = { ...process.env, ...env }; export const ioModuleUrl = distUrl('plugins/cline-io.js');
for (const [name, value] of Object.entries(env)) { export const installationModuleUrl = distUrl('plugins/cline-installation.js');
if (value === undefined) delete childEnvironment[name]; const PLUGIN = { exportName: 'clinePlugin', moduleUrl: pluginModuleUrl };
}
const child = spawn(command, args, {
cwd,
env: childEnvironment,
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
}
export function runNode(args, env, cwd, input = '') {
return runProcess(process.execPath, args, env, cwd, input);
}
export function environment(fixture, clineDir = fixture.clineDir) { export function environment(fixture, clineDir = fixture.clineDir) {
return { return { ...homeEnvironment(fixture), CLINE_DIR: clineDir === null ? undefined : clineDir };
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
CLINE_DIR: clineDir === null ? undefined : clineDir,
};
} }
export function installConfig(fixture, overrides = {}) { export function installConfig(fixture, overrides = {}) {
return { return baseInstallConfig('cline', fixture, overrides);
agentName: 'cline',
orgId: 'org-1',
agentId: fixture.agentId,
privateKey: VALID_PRIVATE_KEY,
kid: 'kid-1',
token: 'token-1',
baseUrl: fixture.baseUrl,
guardScriptPath: fixture.guardScriptPath,
hookScriptPath: fixture.hookScriptPath,
...overrides,
};
} }
export async function runPlugin(fixture, method, argument, clineDir = fixture.clineDir) { export function runPlugin(fixture, method, argument, clineDir = fixture.clineDir) {
const source = ` return basePlugin(PLUGIN, fixture, method, argument, { env: environment(fixture, clineDir) });
import { clinePlugin } from ${JSON.stringify(pluginModuleUrl)};
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT);
const result = await clinePlugin[process.env.ELYDORA_TEST_METHOD](argument);
if (result !== undefined) console.log(JSON.stringify(result));
`;
return runNode(
['--input-type=module', '--eval', source],
{
...environment(fixture, clineDir),
ELYDORA_TEST_ARGUMENT: JSON.stringify(argument),
ELYDORA_TEST_METHOD: method,
},
fixture.projectDir,
);
} }
async function writeOptional(filePath, contents) { async function writeOptional(filePath, contents) {
@@ -96,66 +48,26 @@ export async function createFixture({
existingAudit, existingAudit,
existingGuard, existingGuard,
} = {}) { } = {}) {
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-cline-')); const base = await createFixtureRoot(
const homeDir = path.join(rootDir, "home with spaces and 'quote %CLINE%"); 'elydora-cline-',
const projectDir = path.join(rootDir, 'project with spaces'); "home with spaces and 'quote %CLINE%",
const clineDir = path.join(rootDir, 'custom-cline-home'); { agentId },
);
const clineDir = path.join(base.rootDir, 'custom-cline-home');
const hooksDir = path.join(clineDir, 'hooks'); const hooksDir = path.join(clineDir, 'hooks');
const guardWrapperPath = path.join(hooksDir, 'PreToolUse.mjs'); const guardWrapperPath = path.join(hooksDir, 'PreToolUse.mjs');
const auditWrapperPath = path.join(hooksDir, 'PostToolUse.mjs'); const auditWrapperPath = path.join(hooksDir, 'PostToolUse.mjs');
const agentDir = path.join(homeDir, '.elydora', agentId);
const guardScriptPath = path.join(agentDir, 'guard.js');
const hookScriptPath = path.join(agentDir, 'hook.js');
await mkdir(projectDir, { recursive: true });
await writeOptional(guardWrapperPath, existingGuard); await writeOptional(guardWrapperPath, existingGuard);
await writeOptional(auditWrapperPath, existingAudit); await writeOptional(auditWrapperPath, existingAudit);
const fixture = { return {
agentDir, ...base,
agentId,
auditWrapperPath, auditWrapperPath,
baseUrl, baseUrl,
clineDir, clineDir,
guardScriptPath,
guardWrapperPath, guardWrapperPath,
homeDir,
hookScriptPath,
hooksDir, hooksDir,
projectDir,
rootDir,
install(overrides = {}, clineDirOverride = this.clineDir) { install(overrides = {}, clineDirOverride = this.clineDir) {
return runPlugin(this, 'install', installConfig(this, overrides), clineDirOverride); return runPlugin(this, 'install', installConfig(this, overrides), clineDirOverride);
}, },
async close() {
await rm(rootDir, { recursive: true, force: true });
},
};
return fixture;
}
export async function readJson(filePath) {
return JSON.parse(await readFile(filePath, 'utf-8'));
}
export async function startApiServer() {
const requests = [];
const server = http.createServer(async (request, response) => {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
const raw = Buffer.concat(chunks).toString('utf-8');
requests.push({ method: request.method, url: request.url, raw });
response.writeHead(201, { 'Content-Type': 'application/json' });
response.end('{"operation":{"accepted":true}}');
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const address = server.address();
return {
baseUrl: `http://127.0.0.1:${address.port}`,
requests,
close: () => new Promise((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}),
}; };
} }
+32 -149
View File
@@ -1,139 +1,58 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { pathToFileURL } from 'node:url'; import {
createFixtureRoot,
distUrl,
homeEnvironment,
installConfig as baseInstallConfig,
runNode as baseNode,
runPlugin as basePlugin,
runProcess,
runShell,
writeOptionalJson,
} from './harness.mjs';
export const VALID_PRIVATE_KEY = Buffer.alloc(32).toString('base64url'); export { VALID_PRIVATE_KEY, registryModuleUrl, startApiServer, writeJson } from './harness.mjs';
export const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/codex.js')).href;
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href; export const pluginModuleUrl = distUrl('plugins/codex.js');
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/codex-io.js')).href; export const ioModuleUrl = distUrl('plugins/codex-io.js');
export const installationModuleUrl = pathToFileURL( export const installationModuleUrl = distUrl('plugins/codex-installation.js');
path.resolve('dist/plugins/codex-installation.js'), const PLUGIN = { exportName: 'codexPlugin', moduleUrl: pluginModuleUrl };
).href;
export function runNode(args, env, cwd, input = '') { export function runNode(args, env, cwd, input = '') {
return new Promise((resolve, reject) => { return baseNode(args, { CODEX_HOME: '', ...env }, cwd, input);
const child = spawn(process.execPath, args, {
cwd,
env: { ...process.env, CODEX_HOME: '', ...env },
stdio: ['pipe', 'pipe', 'pipe'],
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
} }
export function runHook(handler, input, fixture, environment = {}) { export function runHook(handler, input, fixture, environment = {}) {
const command = process.platform === 'win32' ? handler.commandWindows : handler.command; const command = process.platform === 'win32' ? handler.commandWindows : handler.command;
return new Promise((resolve, reject) => { const env = { CODEX_HOME: '', ...homeEnvironment(fixture), ...environment };
const child = process.platform === 'win32' return process.platform === 'win32'
? spawn(command, { ? runShell(command, env, fixture.projectDir, input)
shell: true, : runProcess('/bin/sh', ['-c', command], env, fixture.projectDir, input);
cwd: fixture.projectDir,
env: {
...process.env,
CODEX_HOME: '',
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
...environment,
},
stdio: ['pipe', 'pipe', 'pipe'],
})
: spawn('/bin/sh', ['-c', command], {
cwd: fixture.projectDir,
env: {
...process.env,
CODEX_HOME: '',
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
...environment,
},
stdio: ['pipe', 'pipe', 'pipe'],
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
}
export async function writeJson(filePath, value) {
await mkdir(path.dirname(filePath), { recursive: true });
const contents = typeof value === 'string' ? value : `${JSON.stringify(value, null, 2)}\n`;
await writeFile(filePath, contents, { encoding: 'utf-8', mode: 0o600 });
} }
export function installConfig(fixture, overrides = {}) { export function installConfig(fixture, overrides = {}) {
return { return baseInstallConfig('codex', fixture, overrides);
agentName: 'codex',
orgId: 'org-1',
agentId: 'agent-1',
privateKey: VALID_PRIVATE_KEY,
kid: 'kid-1',
token: 'token-1',
baseUrl: fixture.baseUrl,
guardScriptPath: fixture.guardScriptPath,
hookScriptPath: fixture.hookScriptPath,
...overrides,
};
} }
export async function runPlugin(fixture, method, argument, environment = {}) { export function runPlugin(fixture, method, argument, environment = {}) {
const source = ` return basePlugin(PLUGIN, fixture, method, argument, { env: { CODEX_HOME: '', ...environment } });
import { codexPlugin } from ${JSON.stringify(pluginModuleUrl)};
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT);
const result = await codexPlugin[process.env.ELYDORA_TEST_METHOD](argument);
if (result !== undefined) console.log(JSON.stringify(result));
`;
return runNode(
['--input-type=module', '--eval', source],
{
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
ELYDORA_TEST_ARGUMENT: JSON.stringify(argument),
ELYDORA_TEST_METHOD: method,
...environment,
},
fixture.projectDir,
);
} }
export async function createFixture({ existingConfig, baseUrl = 'http://127.0.0.1:9' } = {}) { export async function createFixture({ existingConfig, baseUrl = 'http://127.0.0.1:9' } = {}) {
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-codex-')); const base = await createFixtureRoot(
const homeDir = path.join(rootDir, "home with spaces and 'quote %ELYDORA_HOOK_PATH%"); 'elydora-codex-',
const projectDir = path.join(rootDir, 'project with spaces'); "home with spaces and 'quote %ELYDORA_HOOK_PATH%",
const configPath = path.join(homeDir, '.codex', 'hooks.json'); );
const agentDir = path.join(homeDir, '.elydora', 'agent-1'); const configPath = path.join(base.homeDir, '.codex', 'hooks.json');
const guardScriptPath = path.join(agentDir, 'guard.js'); await writeOptionalJson(configPath, existingConfig);
const hookScriptPath = path.join(agentDir, 'hook.js');
await mkdir(projectDir, { recursive: true });
if (existingConfig !== undefined) await writeJson(configPath, existingConfig);
return { return {
agentDir, ...base,
baseUrl, baseUrl,
configPath, configPath,
guardScriptPath,
homeDir,
hookScriptPath,
projectDir,
rootDir,
install(overrides = {}) { install(overrides = {}) {
return runPlugin(this, 'install', installConfig(this, overrides)); return runPlugin(this, 'install', installConfig(this, overrides));
}, },
async close() {
await rm(rootDir, { recursive: true, force: true });
},
}; };
} }
@@ -170,39 +89,3 @@ export function legacyHandler(scriptPath, statusMessage) {
statusMessage, statusMessage,
}; };
} }
export async function startApiServer({ status = 'active', operationStatus = 201 } = {}) {
const requests = [];
const server = http.createServer(async (request, response) => {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
const raw = Buffer.concat(chunks).toString('utf-8');
requests.push({
headers: request.headers,
method: request.method,
url: request.url,
raw,
});
if (request.method === 'GET') {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify({ agent: { status } }));
return;
}
response.writeHead(operationStatus, { 'Content-Type': 'application/json' });
response.end(operationStatus >= 200 && operationStatus < 300
? JSON.stringify({ operation: { accepted: true } })
: JSON.stringify({ error: { code: 'UPSTREAM_FAILURE', message: 'failed' } }));
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const address = server.address();
return {
baseUrl: `http://127.0.0.1:${address.port}`,
requests,
close: () => new Promise((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}),
};
}
+43 -138
View File
@@ -1,87 +1,44 @@
import { spawn } from 'node:child_process';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { pathToFileURL } from 'node:url'; import {
createFixtureRoot,
distUrl,
homeEnvironment,
installConfig as baseInstallConfig,
runPlugin as basePlugin,
runProcess,
writeOptionalJson,
} from './harness.mjs';
export const VALID_PRIVATE_KEY = Buffer.alloc(32, 11).toString('base64url'); export {
export const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/copilot.js')).href; VALID_PRIVATE_KEY,
export const contractModuleUrl = pathToFileURL( cliPath,
path.resolve('dist/plugins/copilot-contract.js'), readJson,
).href; registryModuleUrl,
export const installationModuleUrl = pathToFileURL( runNode,
path.resolve('dist/plugins/copilot-installation.js'), runProcess,
).href; startApiServer,
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/copilot-io.js')).href; writeJson,
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href; } from './harness.mjs';
export const cliPath = path.resolve('dist/cli.js');
export function runProcess(command, args, env, cwd, input = '') { export const pluginModuleUrl = distUrl('plugins/copilot.js');
return new Promise((resolve, reject) => { export const contractModuleUrl = distUrl('plugins/copilot-contract.js');
const childEnvironment = { ...process.env, ...env }; export const installationModuleUrl = distUrl('plugins/copilot-installation.js');
for (const [name, value] of Object.entries(env)) { export const ioModuleUrl = distUrl('plugins/copilot-io.js');
if (value === undefined) delete childEnvironment[name]; const PLUGIN = { exportName: 'copilotPlugin', moduleUrl: pluginModuleUrl };
}
const child = spawn(command, args, {
cwd,
env: childEnvironment,
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
}
export function runNode(args, env, cwd, input = '') {
return runProcess(process.execPath, args, env, cwd, input);
}
export function environment(fixture, copilotHome = fixture.copilotHome) { export function environment(fixture, copilotHome = fixture.copilotHome) {
return { return {
HOME: fixture.homeDir, ...homeEnvironment(fixture),
USERPROFILE: fixture.homeDir,
COPILOT_HOME: copilotHome === null ? undefined : copilotHome, COPILOT_HOME: copilotHome === null ? undefined : copilotHome,
}; };
} }
export function installConfig(fixture, overrides = {}) { export function installConfig(fixture, overrides = {}) {
return { return baseInstallConfig('copilot', fixture, overrides);
agentName: 'copilot',
orgId: 'org-1',
agentId: fixture.agentId,
privateKey: VALID_PRIVATE_KEY,
kid: 'kid-1',
token: 'token-1',
baseUrl: fixture.baseUrl,
guardScriptPath: fixture.guardScriptPath,
hookScriptPath: fixture.hookScriptPath,
...overrides,
};
} }
export async function runPlugin(fixture, method, argument, copilotHome = fixture.copilotHome) { export function runPlugin(fixture, method, argument, copilotHome = fixture.copilotHome) {
const source = ` return basePlugin(PLUGIN, fixture, method, argument, { env: environment(fixture, copilotHome) });
import { copilotPlugin } from ${JSON.stringify(pluginModuleUrl)};
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT);
const result = await copilotPlugin[process.env.ELYDORA_TEST_METHOD](argument);
if (result !== undefined) console.log(JSON.stringify(result));
`;
return runNode(
['--input-type=module', '--eval', source],
{
...environment(fixture, copilotHome),
ELYDORA_TEST_ARGUMENT: JSON.stringify(argument),
ELYDORA_TEST_METHOD: method,
},
fixture.projectDir,
);
} }
export function runHook(handler, fixture, input) { export function runHook(handler, fixture, input) {
@@ -91,16 +48,6 @@ export function runHook(handler, fixture, input) {
return runProcess(command[0], command[1], environment(fixture), fixture.projectDir, input); return runProcess(command[0], command[1], environment(fixture), fixture.projectDir, input);
} }
export async function writeJson(filePath, value) {
await mkdir(path.dirname(filePath), { recursive: true });
const source = typeof value === 'string' ? value : `${JSON.stringify(value, null, 2)}\n`;
await writeFile(filePath, source, { mode: 0o600 });
}
async function writeOptional(filePath, value) {
if (value !== undefined) await writeJson(filePath, value);
}
export async function createFixture({ export async function createFixture({
agentId = 'agent-1', agentId = 'agent-1',
baseUrl = 'http://127.0.0.1:9', baseUrl = 'http://127.0.0.1:9',
@@ -113,46 +60,36 @@ export async function createFixture({
repositorySettings, repositorySettings,
localSettings, localSettings,
} = {}) { } = {}) {
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-copilot-')); const base = await createFixtureRoot(
const homeDir = path.join(rootDir, "home with spaces and 'quote %COPILOT%"); 'elydora-copilot-',
const projectDir = path.join(rootDir, 'project with spaces'); "home with spaces and 'quote %COPILOT%",
{ agentId },
);
const { projectDir, rootDir } = base;
const copilotHome = path.join(rootDir, "custom Copilot 'home"); const copilotHome = path.join(rootDir, "custom Copilot 'home");
const hooksDir = path.join(copilotHome, 'hooks'); const hooksDir = path.join(copilotHome, 'hooks');
const configPath = path.join(hooksDir, 'elydora-audit.json'); const configPath = path.join(hooksDir, 'elydora-audit.json');
const legacyPath = path.join(projectDir, '.github', 'hooks', 'hooks.json'); const legacyPath = path.join(projectDir, '.github', 'hooks', 'hooks.json');
const agentDir = path.join(homeDir, '.elydora', agentId);
const guardScriptPath = path.join(agentDir, 'guard.js');
const hookScriptPath = path.join(agentDir, 'hook.js');
await mkdir(projectDir, { recursive: true });
await Promise.all([ await Promise.all([
writeOptional(configPath, userConfig), writeOptionalJson(configPath, userConfig),
writeOptional(legacyPath, legacyConfig), writeOptionalJson(legacyPath, legacyConfig),
writeOptional(path.join(copilotHome, 'settings.json'), userSettings), writeOptionalJson(path.join(copilotHome, 'settings.json'), userSettings),
writeOptional(path.join(copilotHome, 'config.json'), legacyUserConfig), writeOptionalJson(path.join(copilotHome, 'config.json'), legacyUserConfig),
writeOptional(path.join(projectDir, '.claude', 'settings.json'), claudeSettings), writeOptionalJson(path.join(projectDir, '.claude', 'settings.json'), claudeSettings),
writeOptional(path.join(projectDir, '.claude', 'settings.local.json'), claudeLocalSettings), writeOptionalJson(path.join(projectDir, '.claude', 'settings.local.json'), claudeLocalSettings),
writeOptional(path.join(projectDir, '.github', 'copilot', 'settings.json'), repositorySettings), writeOptionalJson(path.join(projectDir, '.github', 'copilot', 'settings.json'), repositorySettings),
writeOptional(path.join(projectDir, '.github', 'copilot', 'settings.local.json'), localSettings), writeOptionalJson(path.join(projectDir, '.github', 'copilot', 'settings.local.json'), localSettings),
]); ]);
return { return {
agentDir, ...base,
agentId,
baseUrl, baseUrl,
configPath, configPath,
copilotHome, copilotHome,
guardScriptPath,
homeDir,
hookScriptPath,
hooksDir, hooksDir,
legacyPath, legacyPath,
projectDir,
rootDir,
install(overrides = {}, copilotHomeOverride = this.copilotHome) { install(overrides = {}, copilotHomeOverride = this.copilotHome) {
return runPlugin(this, 'install', installConfig(this, overrides), copilotHomeOverride); return runPlugin(this, 'install', installConfig(this, overrides), copilotHomeOverride);
}, },
async close() {
await rm(rootDir, { recursive: true, force: true });
},
}; };
} }
@@ -193,35 +130,3 @@ export function legacyManagedConfig(fixture, extraHooks = {}) {
}, },
}; };
} }
export async function readJson(filePath) {
return JSON.parse(await readFile(filePath, 'utf-8'));
}
export async function startApiServer() {
const requests = [];
const server = http.createServer(async (request, response) => {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
const raw = Buffer.concat(chunks).toString('utf-8');
requests.push({ method: request.method, url: request.url, raw });
response.writeHead(request.method === 'POST' ? 201 : 200, {
'Content-Type': 'application/json',
});
response.end(request.method === 'POST'
? '{"operation":{"accepted":true}}'
: '{"agent":{"status":"active"}}');
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const address = server.address();
return {
baseUrl: `http://127.0.0.1:${address.port}`,
requests,
close: () => new Promise((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}),
};
}
+29 -131
View File
@@ -1,127 +1,56 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { pathToFileURL } from 'node:url'; import {
createFixtureRoot,
distUrl,
homeEnvironment,
installConfig as baseInstallConfig,
runPlugin as basePlugin,
runProcess,
writeOptionalJson,
} from './harness.mjs';
export const VALID_PRIVATE_KEY = Buffer.alloc(32).toString('base64url'); export {
export const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/cursor.js')).href; VALID_PRIVATE_KEY,
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href; registryModuleUrl,
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/cursor-io.js')).href; runNode,
export const contractModuleUrl = pathToFileURL(path.resolve('dist/plugins/cursor-contract.js')).href; startApiServer,
export const installationModuleUrl = pathToFileURL( writeJson,
path.resolve('dist/plugins/cursor-installation.js'), } from './harness.mjs';
).href;
export function runNode(args, env, cwd, input = '') { export const pluginModuleUrl = distUrl('plugins/cursor.js');
return new Promise((resolve, reject) => { export const ioModuleUrl = distUrl('plugins/cursor-io.js');
const child = spawn(process.execPath, args, { export const contractModuleUrl = distUrl('plugins/cursor-contract.js');
cwd, export const installationModuleUrl = distUrl('plugins/cursor-installation.js');
env: { ...process.env, ...env }, const PLUGIN = { exportName: 'cursorPlugin', moduleUrl: pluginModuleUrl };
stdio: ['pipe', 'pipe', 'pipe'],
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
}
export function runHook(handler, input, fixture, environment = {}) { export function runHook(handler, input, fixture, environment = {}) {
const executable = process.platform === 'win32' ? 'powershell.exe' : '/bin/sh'; const executable = process.platform === 'win32' ? 'powershell.exe' : '/bin/sh';
const args = process.platform === 'win32' const args = process.platform === 'win32'
? ['-NoProfile', '-NonInteractive', '-Command', handler.command] ? ['-NoProfile', '-NonInteractive', '-Command', handler.command]
: ['-c', handler.command]; : ['-c', handler.command];
return new Promise((resolve, reject) => { return runProcess(executable, args, { ...homeEnvironment(fixture), ...environment }, undefined, input);
const child = spawn(executable, args, {
env: {
...process.env,
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
...environment,
},
stdio: ['pipe', 'pipe', 'pipe'],
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
}
export async function writeJson(filePath, value) {
await mkdir(path.dirname(filePath), { recursive: true });
const contents = typeof value === 'string' ? value : `${JSON.stringify(value, null, 2)}\n`;
await writeFile(filePath, contents, { encoding: 'utf-8', mode: 0o600 });
} }
export function installConfig(fixture, overrides = {}) { export function installConfig(fixture, overrides = {}) {
return { return baseInstallConfig('cursor', fixture, overrides);
agentName: 'cursor',
orgId: 'org-1',
agentId: 'agent-1',
privateKey: VALID_PRIVATE_KEY,
kid: 'kid-1',
token: 'token-1',
baseUrl: fixture.baseUrl,
guardScriptPath: fixture.guardScriptPath,
hookScriptPath: fixture.hookScriptPath,
...overrides,
};
} }
export async function runPlugin(fixture, method, argument) { export function runPlugin(fixture, method, argument) {
const source = ` return basePlugin(PLUGIN, fixture, method, argument);
import { cursorPlugin } from ${JSON.stringify(pluginModuleUrl)};
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT);
const result = await cursorPlugin[process.env.ELYDORA_TEST_METHOD](argument);
if (result !== undefined) console.log(JSON.stringify(result));
`;
return runNode(
['--input-type=module', '--eval', source],
{
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
ELYDORA_TEST_ARGUMENT: JSON.stringify(argument),
ELYDORA_TEST_METHOD: method,
},
fixture.projectDir,
);
} }
export async function createFixture({ existingConfig, baseUrl = 'http://127.0.0.1:9' } = {}) { export async function createFixture({ existingConfig, baseUrl = 'http://127.0.0.1:9' } = {}) {
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-cursor-')); const base = await createFixtureRoot('elydora-cursor-', "home with spaces and 'quote");
const homeDir = path.join(rootDir, "home with spaces and 'quote"); const configPath = path.join(base.homeDir, '.cursor', 'hooks.json');
const projectDir = path.join(rootDir, 'project with spaces'); await writeOptionalJson(configPath, existingConfig);
const configPath = path.join(homeDir, '.cursor', 'hooks.json');
const agentDir = path.join(homeDir, '.elydora', 'agent-1');
const guardScriptPath = path.join(agentDir, 'guard.js');
const hookScriptPath = path.join(agentDir, 'hook.js');
await mkdir(projectDir, { recursive: true });
if (existingConfig !== undefined) await writeJson(configPath, existingConfig);
return { return {
agentDir, ...base,
baseUrl, baseUrl,
configPath, configPath,
guardScriptPath,
homeDir,
hookScriptPath,
projectDir,
rootDir,
install(overrides = {}) { install(overrides = {}) {
return runPlugin(this, 'install', installConfig(this, overrides)); return runPlugin(this, 'install', installConfig(this, overrides));
}, },
async close() {
await rm(rootDir, { recursive: true, force: true });
},
}; };
} }
@@ -145,34 +74,3 @@ export function assertNativeHandler(handler) {
export function legacyHandler(scriptPath) { export function legacyHandler(scriptPath) {
return { command: `node "${scriptPath}"` }; return { command: `node "${scriptPath}"` };
} }
export async function startApiServer({ status = 'active', operationStatus = 201 } = {}) {
const requests = [];
const server = http.createServer(async (request, response) => {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
const raw = Buffer.concat(chunks).toString('utf-8');
requests.push({ method: request.method, url: request.url, raw });
if (request.method === 'GET') {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify({ agent: { status } }));
return;
}
response.writeHead(operationStatus, { 'Content-Type': 'application/json' });
response.end(operationStatus >= 200 && operationStatus < 300
? JSON.stringify({ operation: { accepted: true } })
: JSON.stringify({ error: { code: 'UPSTREAM_FAILURE', message: 'failed' } }));
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const address = server.address();
return {
baseUrl: `http://127.0.0.1:${address.port}`,
requests,
close: () => new Promise((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}),
};
}
+48 -129
View File
@@ -1,104 +1,58 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { spawn } from 'node:child_process'; import { mkdir, readFile, readdir } from 'node:fs/promises';
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { parse } from 'jsonc-parser'; import { parse } from 'jsonc-parser';
import {
createFixtureRoot,
distUrl,
homeEnvironment,
installConfig as baseInstallConfig,
runPlugin as basePlugin,
runProcess as baseProcess,
writeOptionalJson,
} from './harness.mjs';
export const VALID_PRIVATE_KEY = Buffer.alloc(32, 13).toString('base64url'); export {
export const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/droid.js')).href; VALID_PRIVATE_KEY,
export const configModuleUrl = pathToFileURL(path.resolve('dist/plugins/droid-config.js')).href; cliPath,
export const contractModuleUrl = pathToFileURL(path.resolve('dist/plugins/droid-contract.js')).href; homeEnvironment as environment,
export const installationModuleUrl = pathToFileURL( registryModuleUrl,
path.resolve('dist/plugins/droid-installation.js'), runNode,
).href; startApiServer,
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/droid-io.js')).href; writeJson as writeConfig,
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href; } from './harness.mjs';
export const cliPath = path.resolve('dist/cli.js');
export const pluginModuleUrl = distUrl('plugins/droid.js');
export const configModuleUrl = distUrl('plugins/droid-config.js');
export const contractModuleUrl = distUrl('plugins/droid-contract.js');
export const installationModuleUrl = distUrl('plugins/droid-installation.js');
export const ioModuleUrl = distUrl('plugins/droid-io.js');
const PLUGIN = { exportName: 'droidPlugin', moduleUrl: pluginModuleUrl };
export function runProcess(command, args, env, cwd, input = '', shell = false) { export function runProcess(command, args, env, cwd, input = '', shell = false) {
return new Promise((resolve, reject) => { return baseProcess(command, args, env, cwd, input, { shell });
const child = spawn(command, args, {
cwd,
env: { ...process.env, ...env },
shell,
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
}
export function runNode(args, env, cwd, input = '') {
return runProcess(process.execPath, args, env, cwd, input);
}
export function environment(fixture) {
return { HOME: fixture.homeDir, USERPROFILE: fixture.homeDir };
} }
export function installConfig(fixture, overrides = {}) { export function installConfig(fixture, overrides = {}) {
return { return baseInstallConfig('droid', fixture, overrides);
agentName: 'droid',
orgId: 'org-1',
agentId: fixture.agentId,
privateKey: VALID_PRIVATE_KEY,
kid: 'kid-1',
token: 'token-1',
baseUrl: fixture.baseUrl,
guardScriptPath: fixture.guardScriptPath,
hookScriptPath: fixture.hookScriptPath,
...overrides,
};
} }
export async function runPlugin(fixture, method, argument) { export function runPlugin(fixture, method, argument) {
const source = ` return basePlugin(PLUGIN, fixture, method, argument, { cwd: fixture.workspaceDir });
import { droidPlugin } from ${JSON.stringify(pluginModuleUrl)};
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT);
const result = await droidPlugin[process.env.ELYDORA_TEST_METHOD](argument);
if (result !== undefined) console.log(JSON.stringify(result));
`;
return runNode(
['--input-type=module', '--eval', source],
{
...environment(fixture),
ELYDORA_TEST_ARGUMENT: JSON.stringify(argument),
ELYDORA_TEST_METHOD: method,
},
fixture.workspaceDir,
);
} }
export function runHook(command, fixture, input) { export function runHook(command, fixture, input) {
const env = homeEnvironment(fixture);
if (process.platform === 'win32') { if (process.platform === 'win32') {
return runProcess( return runProcess(
'powershell.exe', 'powershell.exe',
['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', command], ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', command],
environment(fixture), env,
fixture.workspaceDir, fixture.workspaceDir,
input, input,
); );
} }
return runProcess('/bin/sh', ['-c', command], environment(fixture), fixture.workspaceDir, input); return runProcess('/bin/sh', ['-c', command], env, fixture.workspaceDir, input);
}
export async function writeConfig(filePath, value) {
await mkdir(path.dirname(filePath), { recursive: true });
const source = typeof value === 'string' ? value : `${JSON.stringify(value, null, 2)}\n`;
await writeFile(filePath, source, { mode: 0o600 });
}
async function writeOptional(filePath, value) {
if (value !== undefined) await writeConfig(filePath, value);
} }
export async function createFixture({ export async function createFixture({
@@ -111,51 +65,44 @@ export async function createFixture({
projectSettings, projectSettings,
projectLocalSettings, projectLocalSettings,
} = {}) { } = {}) {
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-droid-')); const base = await createFixtureRoot(
const homeDir = path.join(rootDir, "home with spaces and 'quote %DROID%"); 'elydora-droid-',
const workspaceDir = path.join(rootDir, 'workspace with spaces'); "home with spaces and 'quote %DROID%",
const factoryDir = path.join(homeDir, '.factory'); { agentId, projectName: 'workspace with spaces' },
);
const workspaceDir = base.projectDir;
const factoryDir = path.join(base.homeDir, '.factory');
const rootPath = path.join(factoryDir, 'hooks.json'); const rootPath = path.join(factoryDir, 'hooks.json');
const legacyPath = path.join(factoryDir, 'hooks', 'hooks.json'); const legacyPath = path.join(factoryDir, 'hooks', 'hooks.json');
const settingsPath = path.join(factoryDir, 'settings.json'); const settingsPath = path.join(factoryDir, 'settings.json');
const localSettingsPath = path.join(factoryDir, 'settings.local.json'); const localSettingsPath = path.join(factoryDir, 'settings.local.json');
const agentDir = path.join(homeDir, '.elydora', agentId);
const guardScriptPath = path.join(agentDir, 'guard.js');
const hookScriptPath = path.join(agentDir, 'hook.js');
const projectFactoryDir = path.join(workspaceDir, '.factory'); const projectFactoryDir = path.join(workspaceDir, '.factory');
const projectSettingsPath = path.join(projectFactoryDir, 'settings.json'); const projectSettingsPath = path.join(projectFactoryDir, 'settings.json');
const projectLocalSettingsPath = path.join(projectFactoryDir, 'settings.local.json'); const projectLocalSettingsPath = path.join(projectFactoryDir, 'settings.local.json');
await mkdir(path.join(workspaceDir, '.git'), { recursive: true }); await mkdir(path.join(workspaceDir, '.git'), { recursive: true });
await Promise.all([ await Promise.all([
writeOptional(rootPath, rootConfig), writeOptionalJson(rootPath, rootConfig),
writeOptional(legacyPath, legacyConfig), writeOptionalJson(legacyPath, legacyConfig),
writeOptional(settingsPath, settings), writeOptionalJson(settingsPath, settings),
writeOptional(localSettingsPath, localSettings), writeOptionalJson(localSettingsPath, localSettings),
writeOptional(projectSettingsPath, projectSettings), writeOptionalJson(projectSettingsPath, projectSettings),
writeOptional(projectLocalSettingsPath, projectLocalSettings), writeOptionalJson(projectLocalSettingsPath, projectLocalSettings),
]); ]);
const { projectDir: _projectDir, ...fixture } = base;
return { return {
agentDir, ...fixture,
agentId,
baseUrl, baseUrl,
factoryDir, factoryDir,
guardScriptPath,
homeDir,
hookScriptPath,
legacyPath, legacyPath,
localSettingsPath, localSettingsPath,
projectLocalSettingsPath, projectLocalSettingsPath,
projectSettingsPath, projectSettingsPath,
rootDir,
rootPath, rootPath,
settingsPath, settingsPath,
workspaceDir, workspaceDir,
install(overrides = {}) { install(overrides = {}) {
return runPlugin(this, 'install', installConfig(this, overrides)); return runPlugin(this, 'install', installConfig(this, overrides));
}, },
async close() {
await rm(rootDir, { recursive: true, force: true });
},
}; };
} }
@@ -208,31 +155,3 @@ export async function assertNoTransactionFiles(fixture) {
const leaked = names.filter((name) => /\.(tmp|rollback)$/.test(name)); const leaked = names.filter((name) => /\.(tmp|rollback)$/.test(name));
if (leaked.length > 0) throw new Error(`Leaked transaction files: ${leaked.join(', ')}`); if (leaked.length > 0) throw new Error(`Leaked transaction files: ${leaked.join(', ')}`);
} }
export async function startApiServer() {
const requests = [];
const server = http.createServer(async (request, response) => {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
const raw = Buffer.concat(chunks).toString('utf-8');
requests.push({ method: request.method, url: request.url, raw });
response.writeHead(request.method === 'POST' ? 201 : 200, {
'Content-Type': 'application/json',
});
response.end(request.method === 'POST'
? '{"operation":{"accepted":true}}'
: '{"agent":{"status":"active"}}');
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const address = server.address();
return {
baseUrl: `http://127.0.0.1:${address.port}`,
requests,
close: () => new Promise((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}),
};
}
+41 -153
View File
@@ -1,65 +1,49 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { pathToFileURL } from 'node:url'; import {
import { parse } from 'jsonc-parser'; createFixtureRoot,
distUrl,
homeEnvironment,
installConfig as baseInstallConfig,
optionalEnvironment,
runPlugin as basePlugin,
runProcess as baseProcess,
windowsPowerShellPath,
writeOptionalJson,
} from './harness.mjs';
export const VALID_PRIVATE_KEY = Buffer.alloc(32).toString('base64url'); export {
export const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/gemini.js')).href; VALID_PRIVATE_KEY,
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href; cliPath,
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/gemini-io.js')).href; parseJsonc as parseSettings,
export const installationModuleUrl = pathToFileURL( readJsoncSettings as readSettings,
path.resolve('dist/plugins/gemini-installation.js'), registryModuleUrl,
).href; startApiServer,
export const cliPath = path.resolve('dist/cli.js'); writeJson as writeSettings,
} from './harness.mjs';
export const pluginModuleUrl = distUrl('plugins/gemini.js');
export const ioModuleUrl = distUrl('plugins/gemini-io.js');
export const installationModuleUrl = distUrl('plugins/gemini-installation.js');
const PLUGIN = { exportName: 'geminiPlugin', moduleUrl: pluginModuleUrl };
export function runProcess(command, args, env, cwd, input = '', unset = []) { export function runProcess(command, args, env, cwd, input = '', unset = []) {
return new Promise((resolve, reject) => { return baseProcess(command, args, env, cwd, input, { unset });
const childEnv = { ...process.env, ...env };
for (const key of unset) delete childEnv[key];
const child = spawn(command, args, {
cwd,
env: childEnv,
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
} }
export function runNode(args, env, cwd, input = '', unset = []) { export function runNode(args, env, cwd, input = '', unset = []) {
return runProcess(process.execPath, args, env, cwd, input, unset); return runProcess(process.execPath, args, env, cwd, input, unset);
} }
function windowsPowerShell() {
return path.win32.join(
process.env.SystemRoot || 'C:\\Windows',
'System32',
'WindowsPowerShell',
'v1.0',
'powershell.exe',
);
}
export function runGeminiHook(handler, input, fixture, environment = {}) { export function runGeminiHook(handler, input, fixture, environment = {}) {
const env = { const env = {
HOME: fixture.homeDir, ...homeEnvironment(fixture),
USERPROFILE: fixture.homeDir,
GEMINI_CLI_HOME: fixture.geminiCliHomeOverride ?? '', GEMINI_CLI_HOME: fixture.geminiCliHomeOverride ?? '',
...environment, ...environment,
}; };
if (process.platform === 'win32') { if (process.platform === 'win32') {
return runProcess( return runProcess(
windowsPowerShell(), windowsPowerShellPath(),
[ [
'-NoLogo', '-NoLogo',
'-NoProfile', '-NoProfile',
@@ -75,66 +59,16 @@ export function runGeminiHook(handler, input, fixture, environment = {}) {
return runProcess('/bin/bash', ['-c', handler.command], env, fixture.projectDir, input); return runProcess('/bin/bash', ['-c', handler.command], env, fixture.projectDir, input);
} }
export async function writeSettings(filePath, value) {
await mkdir(path.dirname(filePath), { recursive: true });
const contents = typeof value === 'string' ? value : `${JSON.stringify(value, null, 2)}\n`;
await writeFile(filePath, contents, { encoding: 'utf-8', mode: 0o600 });
}
export function parseSettings(raw) {
const errors = [];
const value = parse(raw, errors, {
allowTrailingComma: false,
disallowComments: false,
});
assert.deepEqual(errors, []);
return value;
}
export async function readSettings(filePath) {
const raw = await readFile(filePath, 'utf-8');
return { raw, settings: parseSettings(raw) };
}
export function installConfig(fixture, overrides = {}) { export function installConfig(fixture, overrides = {}) {
return { return baseInstallConfig('gemini', fixture, overrides);
agentName: 'gemini',
orgId: 'org-1',
agentId: 'agent-1',
privateKey: VALID_PRIVATE_KEY,
kid: 'kid-1',
token: 'token-1',
baseUrl: fixture.baseUrl,
guardScriptPath: fixture.guardScriptPath,
hookScriptPath: fixture.hookScriptPath,
...overrides,
};
} }
export async function runPlugin(fixture, method, argument, environment = {}) { export function runPlugin(fixture, method, argument, environment = {}) {
const source = ` const home = optionalEnvironment('GEMINI_CLI_HOME', fixture.geminiCliHomeOverride);
import { geminiPlugin } from ${JSON.stringify(pluginModuleUrl)}; return basePlugin(PLUGIN, fixture, method, argument, {
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT); env: { ...environment, ...home.env },
const result = await geminiPlugin[process.env.ELYDORA_TEST_METHOD](argument); unset: home.unset,
if (result !== undefined) console.log(JSON.stringify(result)); });
`;
const env = {
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
ELYDORA_TEST_ARGUMENT: JSON.stringify(argument),
ELYDORA_TEST_METHOD: method,
...environment,
};
const unset = [];
if (fixture.geminiCliHomeOverride === undefined) unset.push('GEMINI_CLI_HOME');
else env.GEMINI_CLI_HOME = fixture.geminiCliHomeOverride;
return runNode(
['--input-type=module', '--eval', source],
env,
fixture.projectDir,
'',
unset,
);
} }
export async function createFixture({ export async function createFixture({
@@ -142,38 +76,23 @@ export async function createFixture({
settings, settings,
explicitGeminiHome = true, explicitGeminiHome = true,
} = {}) { } = {}) {
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-gemini-')); const base = await createFixtureRoot(
const homeDir = path.join( 'elydora-gemini-',
rootDir,
"home with spaces and 'quote $GEMINI_CWD %GEMINI_CWD%", "home with spaces and 'quote $GEMINI_CWD %GEMINI_CWD%",
); );
const projectDir = path.join(rootDir, 'project with spaces'); const geminiCliHome = base.homeDir;
const geminiCliHome = homeDir;
const settingsPath = path.join(geminiCliHome, '.gemini', 'settings.json'); const settingsPath = path.join(geminiCliHome, '.gemini', 'settings.json');
const agentDir = path.join(homeDir, '.elydora', 'agent-1'); await writeOptionalJson(settingsPath, settings);
const guardScriptPath = path.join(agentDir, 'guard.js'); return {
const hookScriptPath = path.join(agentDir, 'hook.js'); ...base,
await mkdir(projectDir, { recursive: true });
if (settings !== undefined) await writeSettings(settingsPath, settings);
const fixture = {
agentDir,
baseUrl, baseUrl,
geminiCliHome, geminiCliHome,
geminiCliHomeOverride: explicitGeminiHome ? geminiCliHome : undefined, geminiCliHomeOverride: explicitGeminiHome ? geminiCliHome : undefined,
guardScriptPath,
homeDir,
hookScriptPath,
projectDir,
rootDir,
settingsPath, settingsPath,
install(overrides = {}, environment = {}) { install(overrides = {}, environment = {}) {
return runPlugin(this, 'install', installConfig(this, overrides), environment); return runPlugin(this, 'install', installConfig(this, overrides), environment);
}, },
async close() {
await rm(rootDir, { recursive: true, force: true });
},
}; };
return fixture;
} }
export function managedHandler(settings, event, name) { export function managedHandler(settings, event, name) {
@@ -202,34 +121,3 @@ export function assertManagedHandler(handler, name) {
export function legacyHandler(scriptPath) { export function legacyHandler(scriptPath) {
return { type: 'command', command: `node "${scriptPath}"` }; return { type: 'command', command: `node "${scriptPath}"` };
} }
export async function startApiServer({ status = 'active', operationStatus = 201 } = {}) {
const requests = [];
const server = http.createServer(async (request, response) => {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
const raw = Buffer.concat(chunks).toString('utf-8');
requests.push({ headers: request.headers, method: request.method, url: request.url, raw });
if (request.method === 'GET') {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify({ agent: { status } }));
return;
}
response.writeHead(operationStatus, { 'Content-Type': 'application/json' });
response.end(operationStatus >= 200 && operationStatus < 300
? JSON.stringify({ operation: { accepted: true } })
: JSON.stringify({ error: { code: 'UPSTREAM_FAILURE', message: 'failed' } }));
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const address = server.address();
return {
baseUrl: `http://127.0.0.1:${address.port}`,
requests,
close: () => new Promise((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}),
};
}
+39 -139
View File
@@ -1,39 +1,27 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { spawn } from 'node:child_process'; import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { pathToFileURL } from 'node:url'; import {
createFixtureRoot,
distUrl,
homeEnvironment,
installConfig as baseInstallConfig,
optionalEnvironment,
runPlugin as basePlugin,
runProcess as baseProcess,
runShell,
} from './harness.mjs';
export const VALID_PRIVATE_KEY = Buffer.alloc(32).toString('base64url'); export { VALID_PRIVATE_KEY, cliPath, registryModuleUrl, startApiServer } from './harness.mjs';
export const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/grok.js')).href;
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href; export const pluginModuleUrl = distUrl('plugins/grok.js');
export const contractModuleUrl = pathToFileURL(path.resolve('dist/plugins/grok-contract.js')).href; export const contractModuleUrl = distUrl('plugins/grok-contract.js');
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/grok-io.js')).href; export const ioModuleUrl = distUrl('plugins/grok-io.js');
export const installationModuleUrl = pathToFileURL( export const installationModuleUrl = distUrl('plugins/grok-installation.js');
path.resolve('dist/plugins/grok-installation.js'), const PLUGIN = { exportName: 'grokPlugin', moduleUrl: pluginModuleUrl };
).href;
export const cliPath = path.resolve('dist/cli.js');
export function runProcess(command, args, env, cwd, input = '', unset = []) { export function runProcess(command, args, env, cwd, input = '', unset = []) {
return new Promise((resolve, reject) => { return baseProcess(command, args, env, cwd, input, { unset });
const childEnv = { ...process.env, ...env };
for (const key of unset) delete childEnv[key];
const child = spawn(command, args, {
cwd,
env: childEnv,
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
} }
export function runNode(args, env, cwd, input = '', unset = []) { export function runNode(args, env, cwd, input = '', unset = []) {
@@ -41,68 +29,23 @@ export function runNode(args, env, cwd, input = '', unset = []) {
} }
export function runGrokHook(command, input, fixture, environment = {}) { export function runGrokHook(command, input, fixture, environment = {}) {
return new Promise((resolve, reject) => { return runShell(command, {
const child = spawn(command, { ...homeEnvironment(fixture),
shell: true, GROK_HOME: fixture.grokHomeOverride ?? '',
cwd: fixture.projectDir, ...environment,
env: { }, fixture.projectDir, input);
...process.env,
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
GROK_HOME: fixture.grokHomeOverride ?? '',
...environment,
},
stdio: ['pipe', 'pipe', 'pipe'],
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
} }
export function installConfig(fixture, overrides = {}) { export function installConfig(fixture, overrides = {}) {
return { return baseInstallConfig('grok', fixture, overrides);
agentName: 'grok',
orgId: 'org-1',
agentId: 'agent-1',
privateKey: VALID_PRIVATE_KEY,
kid: 'kid-1',
token: 'token-1',
baseUrl: fixture.baseUrl,
guardScriptPath: fixture.guardScriptPath,
hookScriptPath: fixture.hookScriptPath,
...overrides,
};
} }
export async function runPlugin(fixture, method, argument, environment = {}) { export function runPlugin(fixture, method, argument, environment = {}) {
const source = ` const home = optionalEnvironment('GROK_HOME', fixture.grokHomeOverride);
import { grokPlugin } from ${JSON.stringify(pluginModuleUrl)}; return basePlugin(PLUGIN, fixture, method, argument, {
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT); env: { ...environment, ...home.env },
const result = await grokPlugin[process.env.ELYDORA_TEST_METHOD](argument); unset: home.unset,
if (result !== undefined) console.log(JSON.stringify(result)); });
`;
const env = {
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
ELYDORA_TEST_ARGUMENT: JSON.stringify(argument),
ELYDORA_TEST_METHOD: method,
...environment,
};
const unset = [];
if (fixture.grokHomeOverride === undefined) unset.push('GROK_HOME');
else env.GROK_HOME = fixture.grokHomeOverride;
return runNode(
['--input-type=module', '--eval', source],
env,
fixture.projectDir,
'',
unset,
);
} }
async function writeOptional(filePath, contents) { async function writeOptional(filePath, contents) {
@@ -116,37 +59,25 @@ export async function createFixture({
config, config,
explicitGrokHome = true, explicitGrokHome = true,
} = {}) { } = {}) {
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-grok-')); const base = await createFixtureRoot(
const homeDir = path.join(rootDir, "home with spaces and 'quote %GROK_HOOK_EVENT%"); 'elydora-grok-',
const projectDir = path.join(rootDir, 'project with spaces'); "home with spaces and 'quote %GROK_HOOK_EVENT%",
);
const grokHome = explicitGrokHome const grokHome = explicitGrokHome
? path.join(homeDir, 'custom grok') ? path.join(base.homeDir, 'custom grok')
: path.join(homeDir, '.grok'); : path.join(base.homeDir, '.grok');
const configPath = path.join(grokHome, 'hooks', 'elydora-audit.json'); const configPath = path.join(grokHome, 'hooks', 'elydora-audit.json');
const agentDir = path.join(homeDir, '.elydora', 'agent-1');
const guardScriptPath = path.join(agentDir, 'guard.js');
const hookScriptPath = path.join(agentDir, 'hook.js');
await mkdir(projectDir, { recursive: true });
await writeOptional(configPath, config); await writeOptional(configPath, config);
const fixture = { return {
agentDir, ...base,
baseUrl, baseUrl,
configPath, configPath,
grokHome, grokHome,
grokHomeOverride: explicitGrokHome ? grokHome : undefined, grokHomeOverride: explicitGrokHome ? grokHome : undefined,
guardScriptPath,
homeDir,
hookScriptPath,
projectDir,
rootDir,
install(overrides = {}) { install(overrides = {}) {
return runPlugin(this, 'install', installConfig(this, overrides)); return runPlugin(this, 'install', installConfig(this, overrides));
}, },
async close() {
await rm(rootDir, { recursive: true, force: true });
},
}; };
return fixture;
} }
export async function readGrokConfig(filePath) { export async function readGrokConfig(filePath) {
@@ -184,34 +115,3 @@ export function legacyCommand(scriptPath) {
const quote = (value) => `'${value.replaceAll("'", `'"'"'`)}'`; const quote = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
return `${quote(process.execPath)} ${quote(scriptPath)}`; return `${quote(process.execPath)} ${quote(scriptPath)}`;
} }
export async function startApiServer({ status = 'active', operationStatus = 201 } = {}) {
const requests = [];
const server = http.createServer(async (request, response) => {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
const raw = Buffer.concat(chunks).toString('utf-8');
requests.push({ headers: request.headers, method: request.method, url: request.url, raw });
if (request.method === 'GET') {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify({ agent: { status } }));
return;
}
response.writeHead(operationStatus, { 'Content-Type': 'application/json' });
response.end(operationStatus >= 200 && operationStatus < 300
? JSON.stringify({ operation: { accepted: true } })
: JSON.stringify({ error: { code: 'UPSTREAM_FAILURE', message: 'failed' } }));
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const address = server.address();
return {
baseUrl: `http://127.0.0.1:${address.port}`,
requests,
close: () => new Promise((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}),
};
}
+202
View File
@@ -0,0 +1,202 @@
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { parse } from 'jsonc-parser';
export const VALID_PRIVATE_KEY = Buffer.alloc(32).toString('base64url');
export const cliPath = path.resolve('dist/cli.js');
export function distUrl(relativePath) {
return pathToFileURL(path.resolve('dist', relativePath)).href;
}
export const registryModuleUrl = distUrl('plugins/registry.js');
export const managedInstallationModuleUrl = distUrl('plugins/managed-installation.js');
export function runProcess(command, args, env, cwd, input = '', { unset = [], shell = false } = {}) {
return new Promise((resolve, reject) => {
const childEnvironment = { ...process.env, ...env };
for (const [name, value] of Object.entries(env)) {
if (value === undefined) delete childEnvironment[name];
}
for (const name of unset) delete childEnvironment[name];
const child = spawn(command, args, {
cwd,
env: childEnvironment,
shell,
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
}
export function runNode(args, env, cwd, input = '', options = {}) {
return runProcess(process.execPath, args, env, cwd, input, options);
}
export function runShell(command, env, cwd, input = '') {
return runProcess(command, [], env, cwd, input, { shell: true });
}
export function windowsPowerShellPath() {
return path.win32.join(
process.env.SystemRoot || 'C:\\Windows',
'System32',
'WindowsPowerShell',
'v1.0',
'powershell.exe',
);
}
export function homeEnvironment(fixture) {
return { HOME: fixture.homeDir, USERPROFILE: fixture.homeDir };
}
// Sets NAME when a value is configured, otherwise removes it from the child environment.
export function optionalEnvironment(name, value) {
return value === undefined ? { env: {}, unset: [name] } : { env: { [name]: value }, unset: [] };
}
export function installConfig(agentName, fixture, overrides = {}) {
return {
agentName,
orgId: 'org-1',
agentId: fixture.agentId,
privateKey: VALID_PRIVATE_KEY,
kid: 'kid-1',
token: 'token-1',
baseUrl: fixture.baseUrl,
guardScriptPath: fixture.guardScriptPath,
hookScriptPath: fixture.hookScriptPath,
...overrides,
};
}
export function runPlugin(
plugin,
fixture,
method,
argument,
{ env = {}, unset = [], cwd = fixture.projectDir } = {},
) {
const source = `
import { ${plugin.exportName} } from ${JSON.stringify(plugin.moduleUrl)};
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT);
const result = await ${plugin.exportName}[process.env.ELYDORA_TEST_METHOD](argument);
if (result !== undefined) console.log(JSON.stringify(result));
`;
return runNode(
['--input-type=module', '--eval', source],
{
...homeEnvironment(fixture),
ELYDORA_TEST_ARGUMENT: JSON.stringify(argument),
ELYDORA_TEST_METHOD: method,
...env,
},
cwd,
'',
{ unset },
);
}
export async function createFixtureRoot(
prefix,
homeName,
{ agentId = 'agent-1', projectName = 'project with spaces', createHome = false } = {},
) {
const rootDir = await mkdtemp(path.join(os.tmpdir(), prefix));
const homeDir = path.join(rootDir, homeName);
const projectDir = path.join(rootDir, projectName);
const agentDir = path.join(homeDir, '.elydora', agentId);
if (createHome) await mkdir(homeDir, { recursive: true });
await mkdir(projectDir, { recursive: true });
return {
agentDir,
agentId,
guardScriptPath: path.join(agentDir, 'guard.js'),
homeDir,
hookScriptPath: path.join(agentDir, 'hook.js'),
projectDir,
rootDir,
async close() {
await rm(rootDir, { recursive: true, force: true });
},
};
}
export async function writeJson(filePath, value) {
await mkdir(path.dirname(filePath), { recursive: true });
const contents = typeof value === 'string' ? value : `${JSON.stringify(value, null, 2)}\n`;
await writeFile(filePath, contents, { encoding: 'utf-8', mode: 0o600 });
}
export async function writeOptionalJson(filePath, value) {
if (value !== undefined) await writeJson(filePath, value);
}
export async function readJson(filePath) {
return JSON.parse(await readFile(filePath, 'utf-8'));
}
export async function readSettings(filePath) {
const raw = await readFile(filePath, 'utf-8');
return { raw, settings: JSON.parse(raw) };
}
export function parseJsonc(raw) {
const errors = [];
const value = parse(raw, errors, { allowTrailingComma: false, disallowComments: false });
assert.deepEqual(errors, []);
return value;
}
export async function readJsoncSettings(filePath) {
const raw = await readFile(filePath, 'utf-8');
return { raw, settings: parseJsonc(raw) };
}
export async function startApiServer({ status: initialStatus = 'active', operationStatus: initialOperationStatus = 201 } = {}) {
const requests = [];
let status = initialStatus;
let operationStatus = initialOperationStatus;
const server = http.createServer(async (request, response) => {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
const raw = Buffer.concat(chunks).toString('utf-8');
requests.push({ headers: request.headers, method: request.method, url: request.url, raw });
if (request.method === 'GET') {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify({ agent: { status } }));
return;
}
response.writeHead(operationStatus, { 'Content-Type': 'application/json' });
response.end(operationStatus >= 200 && operationStatus < 300
? JSON.stringify({ operation: { accepted: true } })
: JSON.stringify({ error: { code: 'UPSTREAM_FAILURE', message: 'failed' } }));
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const address = server.address();
return {
baseUrl: `http://127.0.0.1:${address.port}`,
requests,
setStatus(value) { status = value; },
setOperationStatus(value) { operationStatus = value; },
close: () => new Promise((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}),
};
}
+43 -148
View File
@@ -1,104 +1,48 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { spawn } from 'node:child_process'; import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { parse as parseToml } from '@decimalturn/toml-patch'; import { parse as parseToml } from '@decimalturn/toml-patch';
import {
createFixtureRoot,
distUrl,
homeEnvironment,
installConfig as baseInstallConfig,
optionalEnvironment,
runNode as baseNode,
runPlugin as basePlugin,
runShell,
} from './harness.mjs';
export const VALID_PRIVATE_KEY = Buffer.alloc(32).toString('base64url'); export { VALID_PRIVATE_KEY, cliPath, registryModuleUrl, startApiServer } from './harness.mjs';
export const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/kimi.js')).href;
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href; export const pluginModuleUrl = distUrl('plugins/kimi.js');
export const contractModuleUrl = pathToFileURL(path.resolve('dist/plugins/kimi-contract.js')).href; export const contractModuleUrl = distUrl('plugins/kimi-contract.js');
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/kimi-io.js')).href; export const ioModuleUrl = distUrl('plugins/kimi-io.js');
export const installationModuleUrl = pathToFileURL( export const installationModuleUrl = distUrl('plugins/kimi-installation.js');
path.resolve('dist/plugins/kimi-installation.js'), const PLUGIN = { exportName: 'kimiPlugin', moduleUrl: pluginModuleUrl };
).href;
export const cliPath = path.resolve('dist/cli.js');
export function runNode(args, env, cwd, input = '', unset = []) { export function runNode(args, env, cwd, input = '', unset = []) {
return new Promise((resolve, reject) => { return baseNode(args, env, cwd, input, { unset });
const childEnv = { ...process.env, ...env };
for (const key of unset) delete childEnv[key];
const child = spawn(process.execPath, args, {
cwd,
env: childEnv,
stdio: ['pipe', 'pipe', 'pipe'],
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
} }
export function runKimiHook(command, input, fixture, environment = {}) { export function runKimiHook(command, input, fixture, environment = {}) {
return new Promise((resolve, reject) => { return runShell(command, {
const child = spawn(command, { ...homeEnvironment(fixture),
shell: true, KIMI_CODE_HOME: fixture.kimiHomeOverride ?? '',
cwd: fixture.projectDir, ...environment,
env: { }, fixture.projectDir, input);
...process.env,
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
KIMI_CODE_HOME: fixture.kimiHomeOverride ?? '',
...environment,
},
stdio: ['pipe', 'pipe', 'pipe'],
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
} }
export function installConfig(fixture, overrides = {}) { export function installConfig(fixture, overrides = {}) {
return { return baseInstallConfig('kimi', fixture, overrides);
agentName: 'kimi',
orgId: 'org-1',
agentId: 'agent-1',
privateKey: VALID_PRIVATE_KEY,
kid: 'kid-1',
token: 'token-1',
baseUrl: fixture.baseUrl,
guardScriptPath: fixture.guardScriptPath,
hookScriptPath: fixture.hookScriptPath,
...overrides,
};
} }
export async function runPlugin(fixture, method, argument, environment = {}) { export function runPlugin(fixture, method, argument, environment = {}) {
const source = ` const home = optionalEnvironment('KIMI_CODE_HOME', fixture.kimiHomeOverride);
import { kimiPlugin } from ${JSON.stringify(pluginModuleUrl)}; return basePlugin(PLUGIN, fixture, method, argument, {
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT); env: { ...environment, ...home.env },
const result = await kimiPlugin[process.env.ELYDORA_TEST_METHOD](argument); unset: home.unset,
if (result !== undefined) console.log(JSON.stringify(result)); });
`;
const env = {
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
ELYDORA_TEST_ARGUMENT: JSON.stringify(argument),
ELYDORA_TEST_METHOD: method,
...environment,
};
const unset = [];
if (fixture.kimiHomeOverride === undefined) unset.push('KIMI_CODE_HOME');
else env.KIMI_CODE_HOME = fixture.kimiHomeOverride;
return runNode(
['--input-type=module', '--eval', source],
env,
fixture.projectDir,
'',
unset,
);
} }
async function writeOptional(filePath, contents) { async function writeOptional(filePath, contents) {
@@ -115,50 +59,37 @@ export async function createFixture({
legacyDetected = true, legacyDetected = true,
explicitKimiHome = true, explicitKimiHome = true,
} = {}) { } = {}) {
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-kimi-')); const base = await createFixtureRoot(
const homeDir = path.join(rootDir, "home with spaces and 'quote %ELYDORA_HOOK_PATH%"); 'elydora-kimi-',
const projectDir = path.join(rootDir, 'project with spaces'); "home with spaces and 'quote %ELYDORA_HOOK_PATH%",
);
const kimiHome = explicitKimiHome const kimiHome = explicitKimiHome
? path.join(homeDir, 'custom kimi-code') ? path.join(base.homeDir, 'custom kimi-code')
: path.join(homeDir, '.kimi-code'); : path.join(base.homeDir, '.kimi-code');
const stablePath = path.join(kimiHome, 'config.toml'); const stablePath = path.join(kimiHome, 'config.toml');
const legacyHome = path.join(homeDir, '.kimi'); const legacyHome = path.join(base.homeDir, '.kimi');
const legacyPath = path.join(legacyHome, 'config.toml'); const legacyPath = path.join(legacyHome, 'config.toml');
const agentDir = path.join(homeDir, '.elydora', 'agent-1');
const guardScriptPath = path.join(agentDir, 'guard.js');
const hookScriptPath = path.join(agentDir, 'hook.js');
await mkdir(projectDir, { recursive: true });
if (stableDetected && !explicitKimiHome) await mkdir(kimiHome, { recursive: true }); if (stableDetected && !explicitKimiHome) await mkdir(kimiHome, { recursive: true });
if (legacyDetected) await mkdir(legacyHome, { recursive: true }); if (legacyDetected) await mkdir(legacyHome, { recursive: true });
await writeOptional(stablePath, stableConfig); await writeOptional(stablePath, stableConfig);
await writeOptional(legacyPath, legacyConfig); await writeOptional(legacyPath, legacyConfig);
const fixture = { return {
agentDir, ...base,
baseUrl, baseUrl,
guardScriptPath,
homeDir,
hookScriptPath,
kimiHome, kimiHome,
kimiHomeOverride: explicitKimiHome ? kimiHome : undefined, kimiHomeOverride: explicitKimiHome ? kimiHome : undefined,
legacyHome, legacyHome,
legacyPath, legacyPath,
projectDir,
rootDir,
stablePath, stablePath,
install(overrides = {}) { install(overrides = {}) {
return runPlugin(this, 'install', installConfig(this, overrides)); return runPlugin(this, 'install', installConfig(this, overrides));
}, },
async close() {
await rm(rootDir, { recursive: true, force: true });
},
}; };
return fixture;
} }
export function readKimiConfig(filePath) { export async function readKimiConfig(filePath) {
return import('node:fs/promises') const raw = await readFile(filePath, 'utf-8');
.then(({ readFile }) => readFile(filePath, 'utf-8')) return { raw, config: parseToml(raw) };
.then((raw) => ({ raw, config: parseToml(raw) }));
} }
export function managedHook(config, event) { export function managedHook(config, event) {
@@ -182,39 +113,3 @@ export function legacyCommand(scriptPath) {
const quote = (value) => `'${value.replaceAll("'", `'"'"'`)}'`; const quote = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
return `${quote(process.execPath)} ${quote(scriptPath)}`; return `${quote(process.execPath)} ${quote(scriptPath)}`;
} }
export async function startApiServer({ status = 'active', operationStatus = 201 } = {}) {
const requests = [];
const server = http.createServer(async (request, response) => {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
const raw = Buffer.concat(chunks).toString('utf-8');
requests.push({
headers: request.headers,
method: request.method,
url: request.url,
raw,
});
if (request.method === 'GET') {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify({ agent: { status } }));
return;
}
response.writeHead(operationStatus, { 'Content-Type': 'application/json' });
response.end(operationStatus >= 200 && operationStatus < 300
? JSON.stringify({ operation: { accepted: true } })
: JSON.stringify({ error: { code: 'UPSTREAM_FAILURE', message: 'failed' } }));
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const address = server.address();
return {
baseUrl: `http://127.0.0.1:${address.port}`,
requests,
close: () => new Promise((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}),
};
}
+39 -141
View File
@@ -1,98 +1,41 @@
import { spawn } from 'node:child_process';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { pathToFileURL } from 'node:url'; import {
createFixtureRoot,
distUrl,
installConfig as baseInstallConfig,
runPlugin as basePlugin,
runProcess as baseProcess,
writeOptionalJson,
} from './harness.mjs';
export const VALID_PRIVATE_KEY = Buffer.alloc(32, 17).toString('base64url'); export {
export const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/kirocli.js')).href; VALID_PRIVATE_KEY,
export const contractModuleUrl = pathToFileURL( cliPath,
path.resolve('dist/plugins/kirocli-contract.js'), homeEnvironment as environment,
).href; readJson,
export const installationModuleUrl = pathToFileURL( registryModuleUrl,
path.resolve('dist/plugins/kirocli-installation.js'), runNode,
).href; runShell,
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/kirocli-io.js')).href; startApiServer,
export const kiroV1ModuleUrl = pathToFileURL( } from './harness.mjs';
path.resolve('dist/plugins/kiroide-contract.js'),
).href; export const pluginModuleUrl = distUrl('plugins/kirocli.js');
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href; export const contractModuleUrl = distUrl('plugins/kirocli-contract.js');
export const cliPath = path.resolve('dist/cli.js'); export const installationModuleUrl = distUrl('plugins/kirocli-installation.js');
export const ioModuleUrl = distUrl('plugins/kirocli-io.js');
export const kiroV1ModuleUrl = distUrl('plugins/kiroide-contract.js');
const PLUGIN = { exportName: 'kirocliPlugin', moduleUrl: pluginModuleUrl };
export function runProcess(command, args, env, cwd, input = '', shell = false) { export function runProcess(command, args, env, cwd, input = '', shell = false) {
return new Promise((resolve, reject) => { return baseProcess(command, args, env, cwd, input, { shell });
const childEnvironment = { ...process.env, ...env };
for (const [name, value] of Object.entries(env)) {
if (value === undefined) delete childEnvironment[name];
}
const child = spawn(command, args, {
cwd,
env: childEnvironment,
shell,
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
}
export function runNode(args, env, cwd, input = '') {
return runProcess(process.execPath, args, env, cwd, input);
}
export function runShell(command, env, cwd, input = '') {
return runProcess(command, [], env, cwd, input, true);
}
export function environment(fixture) {
return { HOME: fixture.homeDir, USERPROFILE: fixture.homeDir };
} }
export function installConfig(fixture, overrides = {}) { export function installConfig(fixture, overrides = {}) {
return { return baseInstallConfig('kirocli', fixture, overrides);
agentName: 'kirocli',
orgId: 'org-1',
agentId: fixture.agentId,
privateKey: VALID_PRIVATE_KEY,
kid: 'kid-1',
token: 'token-1',
baseUrl: fixture.baseUrl,
guardScriptPath: fixture.guardScriptPath,
hookScriptPath: fixture.hookScriptPath,
...overrides,
};
} }
export async function runPlugin(fixture, method, argument) { export function runPlugin(fixture, method, argument) {
const source = ` return basePlugin(PLUGIN, fixture, method, argument);
import { kirocliPlugin } from ${JSON.stringify(pluginModuleUrl)};
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT);
const result = await kirocliPlugin[process.env.ELYDORA_TEST_METHOD](argument);
if (result !== undefined) console.log(JSON.stringify(result));
`;
return runNode(
['--input-type=module', '--eval', source],
{
...environment(fixture),
ELYDORA_TEST_ARGUMENT: JSON.stringify(argument),
ELYDORA_TEST_METHOD: method,
},
fixture.projectDir,
);
}
async function writeOptional(filePath, value) {
if (value === undefined) return;
await mkdir(path.dirname(filePath), { recursive: true });
const source = typeof value === 'string' ? value : `${JSON.stringify(value, null, 2)}\n`;
await writeFile(filePath, source, { mode: 0o600 });
} }
export function managedV2Document(overrides = {}) { export function managedV2Document(overrides = {}) {
@@ -112,71 +55,26 @@ export async function createFixture({
existingV2, existingV2,
existingV3, existingV3,
} = {}) { } = {}) {
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-kirocli-')); const base = await createFixtureRoot(
const homeDir = path.join(rootDir, "home with spaces and 'quote %KIRO%"); 'elydora-kirocli-',
const projectDir = path.join(rootDir, 'workspace with spaces'); "home with spaces and 'quote %KIRO%",
const v2Path = path.join(homeDir, '.kiro', 'agents', 'elydora-audit.json'); { agentId, projectName: 'workspace with spaces', createHome: true },
const v3Path = path.join(homeDir, '.kiro', 'hooks', 'elydora-audit.json'); );
const agentDir = path.join(homeDir, '.elydora', agentId); const v2Path = path.join(base.homeDir, '.kiro', 'agents', 'elydora-audit.json');
const guardScriptPath = path.join(agentDir, 'guard.js'); const v3Path = path.join(base.homeDir, '.kiro', 'hooks', 'elydora-audit.json');
const hookScriptPath = path.join(agentDir, 'hook.js'); await writeOptionalJson(v2Path, existingV2);
await mkdir(homeDir, { recursive: true }); await writeOptionalJson(v3Path, existingV3);
await mkdir(projectDir, { recursive: true });
await writeOptional(v2Path, existingV2);
await writeOptional(v3Path, existingV3);
return { return {
agentDir, ...base,
agentId,
baseUrl, baseUrl,
guardScriptPath,
homeDir,
hookScriptPath,
projectDir,
rootDir,
v2Path, v2Path,
v3Path, v3Path,
install(overrides = {}) { install(overrides = {}) {
return runPlugin(this, 'install', installConfig(this, overrides)); return runPlugin(this, 'install', installConfig(this, overrides));
}, },
async close() {
await rm(rootDir, { recursive: true, force: true });
},
}; };
} }
export async function readJson(filePath) {
return JSON.parse(await readFile(filePath, 'utf-8'));
}
export function findV3Hook(document, name) { export function findV3Hook(document, name) {
return document.hooks.find((hook) => hook.name === name); return document.hooks.find((hook) => hook.name === name);
} }
export async function startApiServer() {
const requests = [];
const server = http.createServer(async (request, response) => {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
const raw = Buffer.concat(chunks).toString('utf-8');
requests.push({ method: request.method, url: request.url, raw });
if (request.method === 'GET') {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end('{"agent":{"status":"active"}}');
return;
}
response.writeHead(201, { 'Content-Type': 'application/json' });
response.end('{"operation":{"accepted":true}}');
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const address = server.address();
return {
baseUrl: `http://127.0.0.1:${address.port}`,
requests,
close: () => new Promise((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}),
};
}
+39 -139
View File
@@ -1,95 +1,40 @@
import { spawn } from 'node:child_process';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { pathToFileURL } from 'node:url'; import {
createFixtureRoot,
distUrl,
installConfig as baseInstallConfig,
runPlugin as basePlugin,
runProcess as baseProcess,
writeOptionalJson,
} from './harness.mjs';
export const VALID_PRIVATE_KEY = Buffer.alloc(32, 11).toString('base64url'); export {
export const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/kiroide.js')).href; VALID_PRIVATE_KEY,
export const contractModuleUrl = pathToFileURL( cliPath,
path.resolve('dist/plugins/kiroide-contract.js'), homeEnvironment as environment,
).href; readJson,
export const installationModuleUrl = pathToFileURL( registryModuleUrl,
path.resolve('dist/plugins/kiroide-installation.js'), runNode,
).href; runShell,
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/kiroide-io.js')).href; startApiServer,
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href; } from './harness.mjs';
export const cliPath = path.resolve('dist/cli.js');
export const pluginModuleUrl = distUrl('plugins/kiroide.js');
export const contractModuleUrl = distUrl('plugins/kiroide-contract.js');
export const installationModuleUrl = distUrl('plugins/kiroide-installation.js');
export const ioModuleUrl = distUrl('plugins/kiroide-io.js');
const PLUGIN = { exportName: 'kiroidePlugin', moduleUrl: pluginModuleUrl };
export function runProcess(command, args, env, cwd, input = '', shell = false) { export function runProcess(command, args, env, cwd, input = '', shell = false) {
return new Promise((resolve, reject) => { return baseProcess(command, args, env, cwd, input, { shell });
const childEnvironment = { ...process.env, ...env };
for (const [name, value] of Object.entries(env)) {
if (value === undefined) delete childEnvironment[name];
}
const child = spawn(command, args, {
cwd,
env: childEnvironment,
shell,
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
}
export function runNode(args, env, cwd, input = '') {
return runProcess(process.execPath, args, env, cwd, input);
}
export function runShell(command, env, cwd, input = '') {
return runProcess(command, [], env, cwd, input, true);
}
export function environment(fixture) {
return { HOME: fixture.homeDir, USERPROFILE: fixture.homeDir };
} }
export function installConfig(fixture, overrides = {}) { export function installConfig(fixture, overrides = {}) {
return { return baseInstallConfig('kiroide', fixture, overrides);
agentName: 'kiroide',
orgId: 'org-1',
agentId: fixture.agentId,
privateKey: VALID_PRIVATE_KEY,
kid: 'kid-1',
token: 'token-1',
baseUrl: fixture.baseUrl,
guardScriptPath: fixture.guardScriptPath,
hookScriptPath: fixture.hookScriptPath,
...overrides,
};
} }
export async function runPlugin(fixture, method, argument) { export function runPlugin(fixture, method, argument) {
const source = ` return basePlugin(PLUGIN, fixture, method, argument);
import { kiroidePlugin } from ${JSON.stringify(pluginModuleUrl)};
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT);
const result = await kiroidePlugin[process.env.ELYDORA_TEST_METHOD](argument);
if (result !== undefined) console.log(JSON.stringify(result));
`;
return runNode(
['--input-type=module', '--eval', source],
{
...environment(fixture),
ELYDORA_TEST_ARGUMENT: JSON.stringify(argument),
ELYDORA_TEST_METHOD: method,
},
fixture.projectDir,
);
}
async function writeOptional(filePath, value) {
if (value === undefined) return;
await mkdir(path.dirname(filePath), { recursive: true });
const source = typeof value === 'string' ? value : `${JSON.stringify(value, null, 2)}\n`;
await writeFile(filePath, source, { mode: 0o600 });
} }
export async function createFixture({ export async function createFixture({
@@ -98,73 +43,28 @@ export async function createFixture({
existingConfig, existingConfig,
existingLegacy, existingLegacy,
} = {}) { } = {}) {
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-kiroide-')); const base = await createFixtureRoot(
const homeDir = path.join(rootDir, "home with spaces and 'quote %KIRO%"); 'elydora-kiroide-',
const projectDir = path.join(rootDir, 'workspace with spaces'); "home with spaces and 'quote %KIRO%",
const hooksDir = path.join(projectDir, '.kiro', 'hooks'); { agentId, projectName: 'workspace with spaces' },
);
const hooksDir = path.join(base.projectDir, '.kiro', 'hooks');
const configPath = path.join(hooksDir, 'elydora-audit.json'); const configPath = path.join(hooksDir, 'elydora-audit.json');
const legacyConfigPath = path.join(homeDir, '.kiro', 'hooks', 'elydora-audit.kiro.hook'); const legacyConfigPath = path.join(base.homeDir, '.kiro', 'hooks', 'elydora-audit.kiro.hook');
const agentDir = path.join(homeDir, '.elydora', agentId); await writeOptionalJson(configPath, existingConfig);
const guardScriptPath = path.join(agentDir, 'guard.js'); await writeOptionalJson(legacyConfigPath, existingLegacy);
const hookScriptPath = path.join(agentDir, 'hook.js'); return {
await mkdir(projectDir, { recursive: true }); ...base,
await writeOptional(configPath, existingConfig);
await writeOptional(legacyConfigPath, existingLegacy);
const fixture = {
agentDir,
agentId,
baseUrl, baseUrl,
configPath, configPath,
guardScriptPath,
homeDir,
hookScriptPath,
hooksDir, hooksDir,
legacyConfigPath, legacyConfigPath,
projectDir,
rootDir,
install(overrides = {}) { install(overrides = {}) {
return runPlugin(this, 'install', installConfig(this, overrides)); return runPlugin(this, 'install', installConfig(this, overrides));
}, },
async close() {
await rm(rootDir, { recursive: true, force: true });
},
}; };
return fixture;
}
export async function readJson(filePath) {
return JSON.parse(await readFile(filePath, 'utf-8'));
} }
export function findHook(document, name) { export function findHook(document, name) {
return document.hooks.find((hook) => hook.name === name); return document.hooks.find((hook) => hook.name === name);
} }
export async function startApiServer() {
const requests = [];
const server = http.createServer(async (request, response) => {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
const raw = Buffer.concat(chunks).toString('utf-8');
requests.push({ method: request.method, url: request.url, raw });
if (request.method === 'GET') {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end('{"agent":{"status":"active"}}');
return;
}
response.writeHead(201, { 'Content-Type': 'application/json' });
response.end('{"operation":{"accepted":true}}');
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const address = server.address();
return {
baseUrl: `http://127.0.0.1:${address.port}`,
requests,
close: () => new Promise((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}),
};
}
+41 -146
View File
@@ -1,92 +1,38 @@
import { spawn } from 'node:child_process';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { pathToFileURL } from 'node:url'; import {
createFixtureRoot,
distUrl,
homeEnvironment,
installConfig as baseInstallConfig,
runPlugin as basePlugin,
runProcess,
writeOptionalJson,
} from './harness.mjs';
export const VALID_PRIVATE_KEY = Buffer.alloc(32, 23).toString('base64url'); export {
export const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/letta.js')).href; VALID_PRIVATE_KEY,
export const configModuleUrl = pathToFileURL(path.resolve('dist/plugins/letta-config.js')).href; cliPath,
export const contractModuleUrl = pathToFileURL(path.resolve('dist/plugins/letta-contract.js')).href; homeEnvironment as environment,
export const installationModuleUrl = pathToFileURL( readJson as readSettings,
path.resolve('dist/plugins/letta-installation.js'), registryModuleUrl,
).href; runNode,
export const sourcesModuleUrl = pathToFileURL(path.resolve('dist/plugins/letta-sources.js')).href; runProcess,
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href; startApiServer,
export const cliPath = path.resolve('dist/cli.js'); } from './harness.mjs';
export function runProcess(command, args, env, cwd, input = '') { export const pluginModuleUrl = distUrl('plugins/letta.js');
return new Promise((resolve, reject) => { export const configModuleUrl = distUrl('plugins/letta-config.js');
const childEnvironment = { ...process.env, ...env }; export const contractModuleUrl = distUrl('plugins/letta-contract.js');
for (const [name, value] of Object.entries(env)) { export const installationModuleUrl = distUrl('plugins/letta-installation.js');
if (value === undefined) delete childEnvironment[name]; export const sourcesModuleUrl = distUrl('plugins/letta-sources.js');
} const PLUGIN = { exportName: 'lettaPlugin', moduleUrl: pluginModuleUrl };
const child = spawn(command, args, {
cwd,
env: childEnvironment,
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
}
export function runNode(args, env, cwd, input = '') {
return runProcess(process.execPath, args, env, cwd, input);
}
export function environment(fixture) {
return {
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
};
}
export function installConfig(fixture, overrides = {}) { export function installConfig(fixture, overrides = {}) {
return { return baseInstallConfig('letta', fixture, overrides);
agentName: 'letta',
orgId: 'org-1',
agentId: fixture.agentId,
privateKey: VALID_PRIVATE_KEY,
kid: 'kid-1',
token: 'token-1',
baseUrl: fixture.baseUrl,
guardScriptPath: fixture.guardScriptPath,
hookScriptPath: fixture.hookScriptPath,
...overrides,
};
} }
export async function runPlugin(fixture, method, argument) { export function runPlugin(fixture, method, argument) {
const source = ` return basePlugin(PLUGIN, fixture, method, argument);
import { lettaPlugin } from ${JSON.stringify(pluginModuleUrl)};
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT);
const result = await lettaPlugin[process.env.ELYDORA_TEST_METHOD](argument);
if (result !== undefined) console.log(JSON.stringify(result));
`;
return runNode(
['--input-type=module', '--eval', source],
{
...environment(fixture),
ELYDORA_TEST_ARGUMENT: JSON.stringify(argument),
ELYDORA_TEST_METHOD: method,
},
fixture.projectDir,
);
}
async function writeOptional(filePath, value) {
if (value === undefined) return;
await mkdir(path.dirname(filePath), { recursive: true });
const source = typeof value === 'string' ? value : `${JSON.stringify(value, null, 2)}\n`;
await writeFile(filePath, source, { mode: 0o600 });
} }
export async function createFixture({ export async function createFixture({
@@ -96,45 +42,29 @@ export async function createFixture({
projectSettings, projectSettings,
localSettings, localSettings,
} = {}) { } = {}) {
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-letta-')); const base = await createFixtureRoot(
const homeDir = path.join(rootDir, "home with spaces and 'quote %HOME%"); 'elydora-letta-',
const projectDir = path.join(rootDir, 'workspace with spaces'); "home with spaces and 'quote %HOME%",
const globalPath = path.join(homeDir, '.letta', 'settings.json'); { agentId, projectName: 'workspace with spaces', createHome: true },
const projectPath = path.join(projectDir, '.letta', 'settings.json'); );
const localPath = path.join(projectDir, '.letta', 'settings.local.json'); const globalPath = path.join(base.homeDir, '.letta', 'settings.json');
const agentDir = path.join(homeDir, '.elydora', agentId); const projectPath = path.join(base.projectDir, '.letta', 'settings.json');
const guardScriptPath = path.join(agentDir, 'guard.js'); const localPath = path.join(base.projectDir, '.letta', 'settings.local.json');
const hookScriptPath = path.join(agentDir, 'hook.js'); await writeOptionalJson(globalPath, globalSettings);
await mkdir(homeDir, { recursive: true }); await writeOptionalJson(projectPath, projectSettings);
await mkdir(projectDir, { recursive: true }); await writeOptionalJson(localPath, localSettings);
await writeOptional(globalPath, globalSettings);
await writeOptional(projectPath, projectSettings);
await writeOptional(localPath, localSettings);
return { return {
agentDir, ...base,
agentId,
baseUrl, baseUrl,
globalPath, globalPath,
guardScriptPath,
homeDir,
hookScriptPath,
localPath, localPath,
projectDir,
projectPath, projectPath,
rootDir,
install(overrides = {}) { install(overrides = {}) {
return runPlugin(this, 'install', installConfig(this, overrides)); return runPlugin(this, 'install', installConfig(this, overrides));
}, },
async close() {
await rm(rootDir, { recursive: true, force: true });
},
}; };
} }
export async function readSettings(filePath) {
return JSON.parse(await readFile(filePath, 'utf-8'));
}
export function managedHandler(settings, event) { export function managedHandler(settings, event) {
return settings.hooks[event].find((group) => ( return settings.hooks[event].find((group) => (
group.matcher === '*' group.matcher === '*'
@@ -148,40 +78,5 @@ export function runLettaHook(handler, input, fixture) {
const args = process.platform === 'win32' const args = process.platform === 'win32'
? ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', handler.command] ? ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', handler.command]
: ['-c', handler.command]; : ['-c', handler.command];
return runProcess(shell, args, environment(fixture), fixture.projectDir, input); return runProcess(shell, args, homeEnvironment(fixture), fixture.projectDir, input);
}
export async function startApiServer(initialStatus = 'active') {
const requests = [];
let status = initialStatus;
let operationStatus = 201;
const server = http.createServer(async (request, response) => {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
const raw = Buffer.concat(chunks).toString('utf-8');
requests.push({ method: request.method, url: request.url, raw });
if (request.method === 'GET') {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify({ agent: { status } }));
return;
}
response.writeHead(operationStatus, { 'Content-Type': 'application/json' });
response.end(operationStatus < 400
? '{"operation":{"accepted":true}}'
: '{"error":{"code":"AUDIT_UNAVAILABLE"}}');
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const address = server.address();
return {
baseUrl: `http://127.0.0.1:${address.port}`,
requests,
setStatus(value) { status = value; },
setOperationStatus(value) { operationStatus = value; },
close: () => new Promise((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}),
};
} }
+33 -135
View File
@@ -1,87 +1,40 @@
import { spawn } from 'node:child_process'; import { mkdir, writeFile } from 'node:fs/promises';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { pathToFileURL } from 'node:url'; import { pathToFileURL } from 'node:url';
import {
createFixtureRoot,
distUrl,
homeEnvironment,
installConfig as baseInstallConfig,
runPlugin as basePlugin,
} from './harness.mjs';
export const VALID_PRIVATE_KEY = Buffer.alloc(32, 19).toString('base64url'); export {
export const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/opencode.js')).href; VALID_PRIVATE_KEY,
export const contractModuleUrl = pathToFileURL( cliPath,
path.resolve('dist/plugins/opencode-contract.js'), readJson,
).href; registryModuleUrl,
export const installationModuleUrl = pathToFileURL( runNode,
path.resolve('dist/plugins/opencode-installation.js'), runProcess,
).href; startApiServer,
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/opencode-io.js')).href; } from './harness.mjs';
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href;
export const cliPath = path.resolve('dist/cli.js');
export function runProcess(command, args, env, cwd, input = '') { export const pluginModuleUrl = distUrl('plugins/opencode.js');
return new Promise((resolve, reject) => { export const contractModuleUrl = distUrl('plugins/opencode-contract.js');
const childEnvironment = { ...process.env, ...env }; export const installationModuleUrl = distUrl('plugins/opencode-installation.js');
for (const [name, value] of Object.entries(env)) { export const ioModuleUrl = distUrl('plugins/opencode-io.js');
if (value === undefined) delete childEnvironment[name]; const PLUGIN = { exportName: 'opencodePlugin', moduleUrl: pluginModuleUrl };
}
const child = spawn(command, args, {
cwd,
env: childEnvironment,
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
}
export function runNode(args, env, cwd, input = '') {
return runProcess(process.execPath, args, env, cwd, input);
}
export function environment(fixture) { export function environment(fixture) {
return { return { ...homeEnvironment(fixture), XDG_CONFIG_HOME: fixture.configRoot };
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
XDG_CONFIG_HOME: fixture.configRoot,
};
} }
export function installConfig(fixture, overrides = {}) { export function installConfig(fixture, overrides = {}) {
return { return baseInstallConfig('opencode', fixture, overrides);
agentName: 'opencode',
orgId: 'org-1',
agentId: fixture.agentId,
privateKey: VALID_PRIVATE_KEY,
kid: 'kid-1',
token: 'token-1',
baseUrl: fixture.baseUrl,
guardScriptPath: fixture.guardScriptPath,
hookScriptPath: fixture.hookScriptPath,
...overrides,
};
} }
export async function runPlugin(fixture, method, argument) { export function runPlugin(fixture, method, argument) {
const source = ` return basePlugin(PLUGIN, fixture, method, argument, { env: environment(fixture) });
import { opencodePlugin } from ${JSON.stringify(pluginModuleUrl)};
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT);
const result = await opencodePlugin[process.env.ELYDORA_TEST_METHOD](argument);
if (result !== undefined) console.log(JSON.stringify(result));
`;
return runNode(
['--input-type=module', '--eval', source],
{
...environment(fixture),
ELYDORA_TEST_ARGUMENT: JSON.stringify(argument),
ELYDORA_TEST_METHOD: method,
},
fixture.projectDir,
);
} }
async function writeOptional(filePath, value) { async function writeOptional(filePath, value) {
@@ -96,33 +49,24 @@ export async function createFixture({
existingPlugin, existingPlugin,
existingLegacy, existingLegacy,
} = {}) { } = {}) {
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-opencode-')); const base = await createFixtureRoot(
const homeDir = path.join(rootDir, "home with spaces and 'quote %OPEN%"); 'elydora-opencode-',
const configRoot = path.join(rootDir, 'xdg config'); "home with spaces and 'quote %OPEN%",
const projectDir = path.join(rootDir, 'workspace with spaces'); { agentId, projectName: 'workspace with spaces', createHome: true },
);
const configRoot = path.join(base.rootDir, 'xdg config');
const pluginsDir = path.join(configRoot, 'opencode', 'plugins'); const pluginsDir = path.join(configRoot, 'opencode', 'plugins');
const pluginPath = path.join(pluginsDir, 'elydora-audit.js'); const pluginPath = path.join(pluginsDir, 'elydora-audit.js');
const legacyPluginPath = path.join(pluginsDir, 'elydora-audit.mjs'); const legacyPluginPath = path.join(pluginsDir, 'elydora-audit.mjs');
const agentDir = path.join(homeDir, '.elydora', agentId);
const guardScriptPath = path.join(agentDir, 'guard.js');
const hookScriptPath = path.join(agentDir, 'hook.js');
await mkdir(homeDir, { recursive: true });
await mkdir(projectDir, { recursive: true });
await writeOptional(pluginPath, existingPlugin); await writeOptional(pluginPath, existingPlugin);
await writeOptional(legacyPluginPath, existingLegacy); await writeOptional(legacyPluginPath, existingLegacy);
return { return {
agentDir, ...base,
agentId,
baseUrl, baseUrl,
configRoot, configRoot,
guardScriptPath,
homeDir,
hookScriptPath,
legacyPluginPath, legacyPluginPath,
pluginPath, pluginPath,
pluginsDir, pluginsDir,
projectDir,
rootDir,
install(overrides = {}) { install(overrides = {}) {
return runPlugin(this, 'install', installConfig(this, overrides)); return runPlugin(this, 'install', installConfig(this, overrides));
}, },
@@ -130,51 +74,5 @@ export async function createFixture({
const module = await import(`${pathToFileURL(this.pluginPath).href}?test=${Date.now()}`); const module = await import(`${pathToFileURL(this.pluginPath).href}?test=${Date.now()}`);
return module.ElydoraAuditPlugin({}); return module.ElydoraAuditPlugin({});
}, },
async close() {
await rm(rootDir, { recursive: true, force: true });
},
};
}
export async function readJson(filePath) {
return JSON.parse(await readFile(filePath, 'utf-8'));
}
export async function startApiServer(initialStatus = 'active') {
const requests = [];
let status = initialStatus;
let operationStatus = 201;
const server = http.createServer(async (request, response) => {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
const raw = Buffer.concat(chunks).toString('utf-8');
requests.push({ method: request.method, url: request.url, raw });
if (request.method === 'GET') {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify({ agent: { status } }));
return;
}
response.writeHead(operationStatus, { 'Content-Type': 'application/json' });
response.end(operationStatus < 400
? '{"operation":{"accepted":true}}'
: '{"error":{"code":"AUDIT_UNAVAILABLE"}}');
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const address = server.address();
return {
baseUrl: `http://127.0.0.1:${address.port}`,
requests,
setStatus(value) {
status = value;
},
setOperationStatus(value) {
operationStatus = value;
},
close: () => new Promise((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}),
}; };
} }
+40 -170
View File
@@ -1,28 +1,32 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { pathToFileURL } from 'node:url'; import {
import { parse } from 'jsonc-parser'; createFixtureRoot,
distUrl,
homeEnvironment,
installConfig as baseInstallConfig,
runPlugin as basePlugin,
runProcess as baseProcess,
windowsPowerShellPath,
writeOptionalJson,
} from './harness.mjs';
export const VALID_PRIVATE_KEY = Buffer.alloc(32).toString('base64url'); export {
export const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/qwen.js')).href; VALID_PRIVATE_KEY,
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href; cliPath,
export const sourcesModuleUrl = pathToFileURL( parseJsonc as parseSettings,
path.resolve('dist/plugins/qwen-sources.js'), readJsoncSettings as readSettings,
).href; registryModuleUrl,
export const installationModuleUrl = pathToFileURL( startApiServer,
path.resolve('dist/plugins/qwen-installation.js'), writeJson as writeSettings,
).href; } from './harness.mjs';
export const configModuleUrl = pathToFileURL(
path.resolve('dist/plugins/qwen-config.js'), export const pluginModuleUrl = distUrl('plugins/qwen.js');
).href; export const sourcesModuleUrl = distUrl('plugins/qwen-sources.js');
export const contractModuleUrl = pathToFileURL( export const installationModuleUrl = distUrl('plugins/qwen-installation.js');
path.resolve('dist/plugins/qwen-contract.js'), export const configModuleUrl = distUrl('plugins/qwen-config.js');
).href; export const contractModuleUrl = distUrl('plugins/qwen-contract.js');
export const cliPath = path.resolve('dist/cli.js'); const PLUGIN = { exportName: 'qwenPlugin', moduleUrl: pluginModuleUrl };
const QWEN_ENV_KEYS = [ const QWEN_ENV_KEYS = [
'QWEN_HOME', 'QWEN_HOME',
@@ -33,48 +37,18 @@ const QWEN_ENV_KEYS = [
]; ];
export function runProcess(command, args, env, cwd, input = '', unset = []) { export function runProcess(command, args, env, cwd, input = '', unset = []) {
return new Promise((resolve, reject) => { return baseProcess(command, args, env, cwd, input, { unset });
const childEnv = { ...process.env, ...env };
for (const key of unset) delete childEnv[key];
const child = spawn(command, args, {
cwd,
env: childEnv,
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
} }
export function runNode(args, env, cwd, input = '', unset = []) { export function runNode(args, env, cwd, input = '', unset = []) {
return runProcess(process.execPath, args, env, cwd, input, unset); return runProcess(process.execPath, args, env, cwd, input, unset);
} }
function windowsPowerShell() {
return path.win32.join(
process.env.SystemRoot || 'C:\\Windows',
'System32',
'WindowsPowerShell',
'v1.0',
'powershell.exe',
);
}
export function runQwenHook(handler, input, fixture, environment = {}) { export function runQwenHook(handler, input, fixture, environment = {}) {
const env = { const env = { ...homeEnvironment(fixture), ...environment };
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
...environment,
};
if (process.platform === 'win32') { if (process.platform === 'win32') {
return runProcess( return runProcess(
windowsPowerShell(), windowsPowerShellPath(),
['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', handler.command], ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', handler.command],
env, env,
fixture.projectDir, fixture.projectDir,
@@ -84,109 +58,36 @@ export function runQwenHook(handler, input, fixture, environment = {}) {
return runProcess('/bin/bash', ['-c', handler.command], env, fixture.projectDir, input); return runProcess('/bin/bash', ['-c', handler.command], env, fixture.projectDir, input);
} }
export async function writeSettings(filePath, value) {
await mkdir(path.dirname(filePath), { recursive: true });
const contents = typeof value === 'string' ? value : `${JSON.stringify(value, null, 2)}\n`;
await writeFile(filePath, contents, { encoding: 'utf-8', mode: 0o600 });
}
export function parseSettings(raw) {
const errors = [];
const value = parse(raw, errors, {
allowTrailingComma: false,
disallowComments: false,
});
assert.deepEqual(errors, []);
return value;
}
export async function readSettings(filePath) {
const raw = await readFile(filePath, 'utf-8');
return { raw, settings: parseSettings(raw) };
}
export function installConfig(fixture, overrides = {}) { export function installConfig(fixture, overrides = {}) {
return { return baseInstallConfig('qwen', fixture, overrides);
agentName: 'qwen',
orgId: 'org-1',
agentId: 'agent-1',
privateKey: VALID_PRIVATE_KEY,
kid: 'kid-1',
token: 'token-1',
baseUrl: fixture.baseUrl,
guardScriptPath: fixture.guardScriptPath,
hookScriptPath: fixture.hookScriptPath,
...overrides,
};
} }
function qwenEnvironment(fixture, environment) { export function runPlugin(fixture, method, argument, environment = {}) {
const env = { const env = {
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
QWEN_CODE_SYSTEM_DEFAULTS_PATH: path.join(fixture.rootDir, 'system-defaults.json'), QWEN_CODE_SYSTEM_DEFAULTS_PATH: path.join(fixture.rootDir, 'system-defaults.json'),
QWEN_CODE_SYSTEM_SETTINGS_PATH: path.join(fixture.rootDir, 'system-settings.json'), QWEN_CODE_SYSTEM_SETTINGS_PATH: path.join(fixture.rootDir, 'system-settings.json'),
...environment, ...environment,
}; };
const unset = QWEN_ENV_KEYS.filter((key) => !Object.hasOwn(env, key)); const unset = QWEN_ENV_KEYS.filter((key) => !Object.hasOwn(env, key));
return { env, unset }; return basePlugin(PLUGIN, fixture, method, argument, { env, unset });
} }
export async function runPlugin(fixture, method, argument, environment = {}) { export async function createFixture({ baseUrl = 'http://127.0.0.1:9', settings } = {}) {
const source = ` const base = await createFixtureRoot(
import { qwenPlugin } from ${JSON.stringify(pluginModuleUrl)}; 'elydora-qwen-',
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT);
const result = await qwenPlugin[process.env.ELYDORA_TEST_METHOD](argument);
if (result !== undefined) console.log(JSON.stringify(result));
`;
const configured = qwenEnvironment(fixture, {
ELYDORA_TEST_ARGUMENT: JSON.stringify(argument),
ELYDORA_TEST_METHOD: method,
...environment,
});
return runNode(
['--input-type=module', '--eval', source],
configured.env,
fixture.projectDir,
'',
configured.unset,
);
}
export async function createFixture({
baseUrl = 'http://127.0.0.1:9',
settings,
} = {}) {
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-qwen-'));
const homeDir = path.join(
rootDir,
"home with spaces and 'quote $QWEN_PROJECT_DIR %QWEN_PROJECT_DIR%", "home with spaces and 'quote $QWEN_PROJECT_DIR %QWEN_PROJECT_DIR%",
{ createHome: true },
); );
const projectDir = path.join(rootDir, 'project with spaces'); const settingsPath = path.join(base.homeDir, '.qwen', 'settings.json');
const settingsPath = path.join(homeDir, '.qwen', 'settings.json'); await writeOptionalJson(settingsPath, settings);
const agentDir = path.join(homeDir, '.elydora', 'agent-1'); return {
const guardScriptPath = path.join(agentDir, 'guard.js'); ...base,
const hookScriptPath = path.join(agentDir, 'hook.js');
await mkdir(homeDir, { recursive: true });
await mkdir(projectDir, { recursive: true });
if (settings !== undefined) await writeSettings(settingsPath, settings);
const fixture = {
agentDir,
baseUrl, baseUrl,
guardScriptPath,
homeDir,
hookScriptPath,
projectDir,
rootDir,
settingsPath, settingsPath,
install(overrides = {}, environment = {}) { install(overrides = {}, environment = {}) {
return runPlugin(this, 'install', installConfig(this, overrides), environment); return runPlugin(this, 'install', installConfig(this, overrides), environment);
}, },
async close() {
await rm(rootDir, { recursive: true, force: true });
},
}; };
return fixture;
} }
export function managedHandler(settings, event, name) { export function managedHandler(settings, event, name) {
@@ -243,34 +144,3 @@ export function legacyGroup(scriptPath) {
}], }],
}; };
} }
export async function startApiServer({ status = 'active', operationStatus = 201 } = {}) {
const requests = [];
const server = http.createServer(async (request, response) => {
const chunks = [];
for await (const chunk of request) chunks.push(chunk);
const raw = Buffer.concat(chunks).toString('utf-8');
requests.push({ headers: request.headers, method: request.method, url: request.url, raw });
if (request.method === 'GET') {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify({ agent: { status } }));
return;
}
response.writeHead(operationStatus, { 'Content-Type': 'application/json' });
response.end(operationStatus >= 200 && operationStatus < 300
? JSON.stringify({ operation: { accepted: true } })
: JSON.stringify({ error: { code: 'UPSTREAM_FAILURE', message: 'failed' } }));
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const address = server.address();
return {
baseUrl: `http://127.0.0.1:${address.port}`,
requests,
close: () => new Promise((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}),
};
}
+1
View File
@@ -18,6 +18,7 @@ async function runCli(args, homeDir) {
...process.env, ...process.env,
HOME: homeDir, HOME: homeDir,
USERPROFILE: homeDir, USERPROFILE: homeDir,
XDG_CONFIG_HOME: path.join(homeDir, '.config'),
}, },
stdio: ['ignore', 'pipe', 'pipe'], stdio: ['ignore', 'pipe', 'pipe'],
}); });
+2
View File
@@ -26,6 +26,7 @@ async function createFixture(status) {
await writeFile( await writeFile(
path.join(agentDir, 'config.json'), path.join(agentDir, 'config.json'),
JSON.stringify({ agent_id: AGENT_ID, base_url: `http://127.0.0.1:${address.port}` }), JSON.stringify({ agent_id: AGENT_ID, base_url: `http://127.0.0.1:${address.port}` }),
{ mode: 0o600 },
); );
const scriptPath = path.join(homeDir, 'guard.cjs'); const scriptPath = path.join(homeDir, 'guard.cjs');
@@ -91,6 +92,7 @@ test('cached frozen status keeps the blocking exit code', async () => {
await writeFile( await writeFile(
path.join(fixture.homeDir, '.elydora', AGENT_ID, 'status-cache.json'), path.join(fixture.homeDir, '.elydora', AGENT_ID, 'status-cache.json'),
JSON.stringify({ status: 'frozen', cached_at: Date.now() }), JSON.stringify({ status: 'frozen', cached_at: Date.now() }),
{ mode: 0o600 },
); );
const result = await runGuard(fixture.scriptPath, fixture.homeDir); const result = await runGuard(fixture.scriptPath, fixture.homeDir);
+2 -2
View File
@@ -60,7 +60,7 @@ async function installedHandlers(fixture) {
} }
test('Letta guard accepts active agents with native exit semantics', async () => { test('Letta guard accepts active agents with native exit semantics', async () => {
const api = await startApiServer('active'); const api = await startApiServer({ status: 'active' });
const fixture = await createFixture({ baseUrl: api.baseUrl }); const fixture = await createFixture({ baseUrl: api.baseUrl });
try { try {
assert.equal((await fixture.install()).code, 0); assert.equal((await fixture.install()).code, 0);
@@ -82,7 +82,7 @@ test('Letta guard accepts active agents with native exit semantics', async () =>
test('Letta guard propagates frozen and revoked states through exit code 2', async (t) => { test('Letta guard propagates frozen and revoked states through exit code 2', async (t) => {
for (const status of ['frozen', 'revoked']) { for (const status of ['frozen', 'revoked']) {
await t.test(status, async () => { await t.test(status, async () => {
const api = await startApiServer(status); const api = await startApiServer({ status });
const fixture = await createFixture({ baseUrl: api.baseUrl }); const fixture = await createFixture({ baseUrl: api.baseUrl });
try { try {
assert.equal((await fixture.install()).code, 0); assert.equal((await fixture.install()).code, 0);