Compare commits
16
Commits
v2.0.0
...
528081bb88
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
528081bb88 | ||
|
|
6b0e8b8f77 | ||
|
|
a63c360539 | ||
|
|
89bdd6e3b8 | ||
|
|
909691328e | ||
|
|
eb95173015 | ||
|
|
9e1c0d9eb0 | ||
|
|
90bea63eea | ||
|
|
25bfa39fcf | ||
|
|
3b5cbd6e17 | ||
|
|
db4a6ffb62 | ||
|
|
81ecb372ba | ||
|
|
b7f14ba34b | ||
|
|
07f32a48d7 | ||
|
|
2101cb77e3 | ||
|
|
85c2d2d491 |
No files matched your search
@@ -1,5 +0,0 @@
|
||||
src/
|
||||
tsconfig.json
|
||||
.gitignore
|
||||
node_modules/
|
||||
*.tsbuildinfo
|
||||
@@ -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.
|
||||
- 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
|
||||
|
||||
Run the focused adapter test during development, then execute all release gates before commit:
|
||||
|
||||
@@ -124,7 +124,7 @@ const client = new ElydoraClient({
|
||||
baseUrl?: string, // API base URL (default: https://api.elydora.com)
|
||||
ttlMs?: number, // Operation TTL in ms (default: 30000)
|
||||
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
|
||||
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);
|
||||
client.setToken(token);
|
||||
|
||||
// Rotate the API token the client currently holds
|
||||
const rotated = await client.rotateApiToken();
|
||||
client.setToken(rotated.token);
|
||||
```
|
||||
|
||||
### Operations
|
||||
@@ -183,6 +188,9 @@ const agent = await client.registerAgent({
|
||||
// Get agent details
|
||||
const details = await client.getAgent(agentId);
|
||||
|
||||
// Change the integration type
|
||||
await client.updateAgent(agentId, 'cursor');
|
||||
|
||||
// Freeze an agent
|
||||
await client.freezeAgent(agentId, 'security review');
|
||||
|
||||
@@ -245,7 +253,21 @@ const { keys } = await client.getJWKS();
|
||||
```typescript
|
||||
// Check API health (no authentication required)
|
||||
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
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@elydora/sdk",
|
||||
"version": "2.0.0",
|
||||
"version": "2.1.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@elydora/sdk",
|
||||
"version": "2.0.0",
|
||||
"version": "2.1.1",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@decimalturn/toml-patch": "^2.0.0",
|
||||
|
||||
+2
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@elydora/sdk",
|
||||
"version": "2.0.0",
|
||||
"version": "2.1.1",
|
||||
"description": "Node.js/TypeScript SDK for the Elydora tamper-evident audit platform",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
@@ -8,8 +8,7 @@
|
||||
"elydora": "dist/cli.js"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"scripts"
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc && node scripts/postbuild.mjs",
|
||||
|
||||
+2
-19
@@ -13,7 +13,8 @@ import {
|
||||
import { writePrivateFile } from './secure-files.js';
|
||||
import { SUPPORTED_AGENTS } from './plugins/registry.js';
|
||||
import type { AgentPlugin, InstallConfig } from './plugins/base.js';
|
||||
import { generateHookScript, generateGuardScript } from './plugins/hook-template.js';
|
||||
import { generateGuardScript } from './plugins/guard-template.js';
|
||||
import { generateHookScript } from './plugins/hook-template.js';
|
||||
import { augmentPlugin } from './plugins/augment.js';
|
||||
import { claudecodePlugin } from './plugins/claudecode.js';
|
||||
import { cursorPlugin } from './plugins/cursor.js';
|
||||
@@ -50,10 +51,6 @@ const PLUGINS: ReadonlyMap<string, AgentPlugin> = new Map([
|
||||
['qwen', qwenPlugin],
|
||||
]);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function die(message: string): never {
|
||||
console.error(`Error: ${message}`);
|
||||
process.exit(1);
|
||||
@@ -137,10 +134,6 @@ Supported agents: ${Array.from(SUPPORTED_AGENTS.keys()).join(', ')}
|
||||
`);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Commands
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function cmdInstall(args: string[]): Promise<void> {
|
||||
const { values } = parseArgs({
|
||||
args,
|
||||
@@ -178,7 +171,6 @@ async function cmdInstall(args: string[]): Promise<void> {
|
||||
});
|
||||
const baseUrl = values.base_url ?? 'https://api.elydora.com';
|
||||
|
||||
// Validate private key by deriving public key
|
||||
let publicKey: string;
|
||||
try {
|
||||
publicKey = derivePublicKey(privateKey);
|
||||
@@ -255,7 +247,6 @@ async function cmdUninstall(args: string[]): Promise<void> {
|
||||
let agentDir: string;
|
||||
let agentDirectoryExists: boolean;
|
||||
|
||||
// If --agent_id not provided, scan ~/.elydora/*/config.json for matching agent_name
|
||||
if (agentId) {
|
||||
agentDir = resolvePrivateChildDirectory(ELYDORA_DIR, agentId);
|
||||
const runtimeRootExists = await requirePhysicalDirectory(ELYDORA_DIR);
|
||||
@@ -287,10 +278,8 @@ async function cmdUninstall(args: string[]): Promise<void> {
|
||||
const plugin = PLUGINS.get(agentName)!;
|
||||
const registryEntry = SUPPORTED_AGENTS.get(agentName)!;
|
||||
|
||||
// Uninstall agent-specific config
|
||||
await plugin.uninstall(agentId);
|
||||
|
||||
// Remove entire agent directory
|
||||
if (agentDirectoryExists) {
|
||||
await fsp.rm(agentDir, { recursive: true });
|
||||
}
|
||||
@@ -303,14 +292,12 @@ async function cmdStatus(): Promise<void> {
|
||||
|
||||
let anyInstalled = false;
|
||||
|
||||
// Scan ~/.elydora/*/config.json to discover installed agents
|
||||
const installedAgents = await discoverInstalledAgents();
|
||||
|
||||
for (const [name, plugin] of PLUGINS) {
|
||||
const st = await plugin.status();
|
||||
const statusIcon = st.installed ? '[installed]' : '[not installed]';
|
||||
|
||||
// Find matching installed agent(s) for this plugin
|
||||
const matching = installedAgents.filter((a) => a.agentName === name);
|
||||
|
||||
console.log(` ${st.displayName} (${name}) ${statusIcon}`);
|
||||
@@ -339,10 +326,6 @@ function cmdAgents(): void {
|
||||
console.log('\nUse "elydora install --agent <name>" to install an audit hook.');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Main
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
|
||||
+17
-92
@@ -74,34 +74,19 @@ export class ElydoraClient {
|
||||
this.prevChainHash = ZERO_CHAIN_HASH;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the API token used for authenticated API calls.
|
||||
*/
|
||||
setToken(token: string): void {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current chain hash (useful for debugging/inspection).
|
||||
*/
|
||||
getChainHash(): string {
|
||||
return this.prevChainHash;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the public key derived from the configured private key.
|
||||
*/
|
||||
getPublicKey(): string {
|
||||
return derivePublicKey(this.privateKey);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Auth (static methods — no instance needed)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* @deprecated Use Better Auth endpoints directly. See docs.
|
||||
*/
|
||||
/** @deprecated Password auth for the SDK CLI path; Console users sign in through Better Auth. */
|
||||
static async register(
|
||||
baseUrl: string,
|
||||
email: string,
|
||||
@@ -123,9 +108,7 @@ export class ElydoraClient {
|
||||
return handleResponse<AuthRegisterResponse>(res);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use Better Auth endpoints directly. See docs.
|
||||
*/
|
||||
/** @deprecated Password auth for the SDK CLI path; Console users sign in through Better Auth. */
|
||||
static async login(
|
||||
baseUrl: string,
|
||||
email: string,
|
||||
@@ -141,10 +124,6 @@ export class ElydoraClient {
|
||||
return handleResponse<AuthLoginResponse>(res);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Auth (instance methods — require token)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
async getMe(): Promise<GetMeResponse> {
|
||||
return this.request<GetMeResponse>('GET', '/v1/auth/me');
|
||||
}
|
||||
@@ -157,10 +136,6 @@ export class ElydoraClient {
|
||||
return this.request<RotateApiTokenResponse>('POST', '/v1/auth/rotate', {});
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Agent management
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
async registerAgent(request: RegisterAgentRequest): Promise<RegisterAgentResponse> {
|
||||
assertIntegrationType(request?.integration_type);
|
||||
return this.request<RegisterAgentResponse>('POST', '/v1/agents/register', request);
|
||||
@@ -195,31 +170,15 @@ export class ElydoraClient {
|
||||
await this.request<unknown>('POST', `/v1/agents/${encodeURIComponent(agentId)}/revoke`, { kid, reason });
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Operations (core)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Construct and sign an Elydora Operation Record (EOR) locally.
|
||||
*
|
||||
* 1. Generate UUIDv7 for operation_id
|
||||
* 2. Generate random nonce (16 bytes, base64url)
|
||||
* 3. Compute payload_hash (SHA-256 of JCS-canonicalized payload)
|
||||
* 4. Compute chain_hash from prev_chain_hash
|
||||
* 5. Construct canonical EOR (minus signature)
|
||||
* 6. Sign JCS-canonicalized EOR with Ed25519
|
||||
* 7. Update internal prev_chain_hash
|
||||
*/
|
||||
// Builds, hashes, chains, and signs an EOR locally, then advances prev_chain_hash.
|
||||
createOperation(params: CreateOperationParams): EOR {
|
||||
const operationId = uuidv7();
|
||||
const issuedAt = Date.now();
|
||||
const nonce = generateNonce();
|
||||
const payload = params.payload ?? null;
|
||||
|
||||
// Compute payload hash
|
||||
const payloadHash = computePayloadHash(payload);
|
||||
|
||||
// Compute chain hash
|
||||
const chainHash = computeChainHash(
|
||||
this.prevChainHash,
|
||||
payloadHash,
|
||||
@@ -227,7 +186,6 @@ export class ElydoraClient {
|
||||
issuedAt,
|
||||
);
|
||||
|
||||
// Construct the EOR without signature for signing
|
||||
const eorWithoutSig: Omit<EOR, 'signature'> = {
|
||||
op_version: '1.0',
|
||||
operation_id: operationId,
|
||||
@@ -245,11 +203,9 @@ export class ElydoraClient {
|
||||
agent_pubkey_kid: this.kid,
|
||||
};
|
||||
|
||||
// Sign the JCS-canonicalized EOR (without signature field)
|
||||
const canonical = jcsCanonicalise(eorWithoutSig);
|
||||
const signature = signEd25519(this.privateKey, Buffer.from(canonical, 'utf-8'));
|
||||
|
||||
// Update internal chain state
|
||||
this.prevChainHash = chainHash;
|
||||
|
||||
return {
|
||||
@@ -270,18 +226,10 @@ export class ElydoraClient {
|
||||
return this.request<VerifyOperationResponse>('POST', `/v1/operations/${encodeURIComponent(operationId)}/verify`, {});
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Audit
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
async queryAudit(params: AuditQueryRequest): Promise<AuditQueryResponse> {
|
||||
return this.request<AuditQueryResponse>('POST', '/v1/audit/query', params);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Epochs
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
async listEpochs(): Promise<ListEpochsResponse> {
|
||||
return this.request<ListEpochsResponse>('GET', '/v1/epochs');
|
||||
}
|
||||
@@ -290,10 +238,6 @@ export class ElydoraClient {
|
||||
return this.request<GetEpochResponse>('GET', `/v1/epochs/${encodeURIComponent(epochId)}`);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Exports
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
async createExport(params: CreateExportRequest): Promise<CreateExportResponse> {
|
||||
return this.request<CreateExportResponse>('POST', '/v1/exports', params);
|
||||
}
|
||||
@@ -323,10 +267,6 @@ export class ElydoraClient {
|
||||
return res.arrayBuffer();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// JWKS
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
async getJWKS(): Promise<JWKSResponse> {
|
||||
const url = `${this.baseUrl}/.well-known/elydora/jwks.json`;
|
||||
const res = await fetch(url, {
|
||||
@@ -336,10 +276,6 @@ export class ElydoraClient {
|
||||
return handleResponse<JWKSResponse>(res);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Health
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
async health(): Promise<HealthResponse> {
|
||||
const url = `${this.baseUrl}/v1/health`;
|
||||
const res = await fetch(url, {
|
||||
@@ -349,16 +285,16 @@ export class ElydoraClient {
|
||||
return handleResponse<HealthResponse>(res);
|
||||
}
|
||||
|
||||
/** 503 carries the degraded report, not an error. */
|
||||
async deepHealth(): Promise<DeepHealthResponse> {
|
||||
const url = `${this.baseUrl}/v1/health/deep`;
|
||||
const res = await fetch(url, { method: 'GET', headers: { 'Accept': 'application/json' } });
|
||||
if (res.status === 503) {
|
||||
return (await res.json()) as DeepHealthResponse;
|
||||
}
|
||||
return handleResponse<DeepHealthResponse>(res);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Webhooks
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
async listWebhooks(): Promise<ListWebhooksResponse> {
|
||||
return this.request<ListWebhooksResponse>('GET', '/v1/webhooks');
|
||||
}
|
||||
@@ -371,27 +307,15 @@ export class ElydoraClient {
|
||||
await this.request<unknown>('DELETE', `/v1/webhooks/${encodeURIComponent(webhookId)}`);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Members
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
async listMembers(): Promise<ListMembersResponse> {
|
||||
return this.request<ListMembersResponse>('GET', '/v1/members');
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Admin events
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
async listAdminEvents(limit?: number): Promise<ListAdminEventsResponse> {
|
||||
const query = limit ? `?limit=${limit}` : '';
|
||||
return this.request<ListAdminEventsResponse>('GET', `/v1/admin/events${query}`);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Internal HTTP helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private async request<T>(
|
||||
method: string,
|
||||
path: string,
|
||||
@@ -420,8 +344,7 @@ export class ElydoraClient {
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
|
||||
// Only retry on 429 or 5xx
|
||||
if (attempt < this.maxRetries && (res.status === 429 || res.status >= 500)) {
|
||||
if (attempt < this.maxRetries && isIdempotent(method) && (res.status === 429 || res.status >= 500)) {
|
||||
const retryAfter = res.headers.get('Retry-After');
|
||||
const delayMs = retryAfter
|
||||
? parseInt(retryAfter, 10) * 1000
|
||||
@@ -434,15 +357,15 @@ export class ElydoraClient {
|
||||
} catch (err) {
|
||||
lastError = err instanceof Error ? err : new Error(String(err));
|
||||
|
||||
// Only retry on network errors, not API errors
|
||||
if (err instanceof ElydoraError) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (attempt < this.maxRetries) {
|
||||
if (attempt < this.maxRetries && isIdempotent(method)) {
|
||||
await sleep(Math.min(1000 * 2 ** attempt, 10_000));
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -450,13 +373,15 @@ export class ElydoraClient {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
const IDEMPOTENT_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE']);
|
||||
|
||||
/** A lost response to a non-idempotent request must not be replayed. */
|
||||
function isIdempotent(method: string): boolean {
|
||||
return IDEMPOTENT_METHODS.has(method.toUpperCase());
|
||||
}
|
||||
|
||||
async function handleResponse<T>(res: Response): Promise<T> {
|
||||
if (res.ok) {
|
||||
// 204 No Content
|
||||
if (res.status === 204) {
|
||||
return undefined as T;
|
||||
}
|
||||
@@ -467,7 +392,7 @@ async function handleResponse<T>(res: Response): Promise<T> {
|
||||
try {
|
||||
errorBody = (await res.json()) as ErrorResponse;
|
||||
} catch {
|
||||
// Response body was not valid JSON
|
||||
// non-JSON error body: fall through to the status-only error
|
||||
}
|
||||
|
||||
if (errorBody?.error) {
|
||||
|
||||
+6
-70
@@ -1,18 +1,7 @@
|
||||
import crypto from 'node:crypto';
|
||||
import { base64urlEncode } from './utils.js';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// JCS Canonicalization (RFC 8785)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Canonicalize a JSON value according to JCS (RFC 8785).
|
||||
*
|
||||
* - Object keys sorted lexicographically by UTF-16 code units
|
||||
* - No whitespace
|
||||
* - Numbers serialized using ES2015 Number serialization
|
||||
* - Strings serialized with minimal escaping per JSON spec
|
||||
*/
|
||||
// RFC 8785 JSON Canonicalization Scheme
|
||||
export function jcsCanonicalise(value: unknown): string {
|
||||
if (value === null || value === undefined) {
|
||||
return 'null';
|
||||
@@ -46,30 +35,13 @@ export function jcsCanonicalise(value: unknown): string {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SHA-256
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Compute SHA-256 of a UTF-8 string or buffer and return base64url.
|
||||
*/
|
||||
export function sha256Base64url(data: string | Buffer): string {
|
||||
const input = typeof data === 'string' ? Buffer.from(data, 'utf-8') : data;
|
||||
const hash = crypto.createHash('sha256').update(input).digest();
|
||||
return base64urlEncode(hash);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Chain hash computation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Compute the chain hash for an operation.
|
||||
*
|
||||
* chain_hash = SHA-256(prev_chain_hash + "|" + payload_hash + "|" + operation_id + "|" + issued_at)
|
||||
*
|
||||
* All inputs concatenated as UTF-8 strings separated by '|'.
|
||||
*/
|
||||
// chain_hash = SHA-256("prev|payload_hash|operation_id|issued_at")
|
||||
export function computeChainHash(
|
||||
prevChainHash: string,
|
||||
payloadHash: string,
|
||||
@@ -80,13 +52,6 @@ export function computeChainHash(
|
||||
return sha256Base64url(input);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Payload hash
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Compute SHA-256 hash of JCS-canonicalized payload, returned as base64url.
|
||||
*/
|
||||
export function computePayloadHash(
|
||||
payload: Record<string, unknown> | string | null,
|
||||
): string {
|
||||
@@ -94,23 +59,11 @@ export function computePayloadHash(
|
||||
return sha256Base64url(canonical);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Ed25519 signing
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// PKCS8 prefix for wrapping a 32-byte Ed25519 seed
|
||||
// PKCS8 envelope: SEQUENCE { INTEGER 0, SEQUENCE { OID 1.3.101.112 }, OCTET STRING { OCTET STRING seed } }
|
||||
const PKCS8_ED25519_PREFIX = Buffer.from([
|
||||
0x30, 0x2e, // SEQUENCE (46 bytes)
|
||||
0x02, 0x01, 0x00, // INTEGER 0
|
||||
0x30, 0x05, // SEQUENCE (5 bytes)
|
||||
0x06, 0x03, 0x2b, 0x65, 0x70, // OID 1.3.101.112 (Ed25519)
|
||||
0x04, 0x22, // OCTET STRING (34 bytes)
|
||||
0x04, 0x20, // OCTET STRING (32 bytes)
|
||||
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,
|
||||
]);
|
||||
|
||||
/**
|
||||
* Import a base64url-encoded 32-byte Ed25519 seed as a Node.js KeyObject.
|
||||
*/
|
||||
function importPrivateKey(privateKeyBase64url: string): crypto.KeyObject {
|
||||
const seed = Buffer.from(privateKeyBase64url, 'base64url');
|
||||
const pkcs8 = Buffer.concat([PKCS8_ED25519_PREFIX, seed]);
|
||||
@@ -121,37 +74,20 @@ function importPrivateKey(privateKeyBase64url: string): crypto.KeyObject {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign data with Ed25519 using a base64url-encoded 32-byte seed.
|
||||
*
|
||||
* @returns base64url-encoded 64-byte signature
|
||||
*/
|
||||
export function signEd25519(privateKeyBase64url: string, data: Buffer): string {
|
||||
const keyObject = importPrivateKey(privateKeyBase64url);
|
||||
const signature = crypto.sign(null, data, keyObject);
|
||||
return base64urlEncode(signature);
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive the Ed25519 public key from a base64url-encoded 32-byte seed.
|
||||
*
|
||||
* @returns base64url-encoded 32-byte public key
|
||||
*/
|
||||
export function derivePublicKey(privateKeyBase64url: string): string {
|
||||
const keyObject = importPrivateKey(privateKeyBase64url);
|
||||
const publicKeyObject = crypto.createPublicKey(keyObject);
|
||||
const rawPublicKey = publicKeyObject.export({ type: 'spki', format: 'der' });
|
||||
// The raw 32-byte public key is the last 32 bytes of the SPKI DER encoding
|
||||
// The raw key is the last 32 bytes of the SPKI DER encoding.
|
||||
const publicKeyBytes = rawPublicKey.subarray(rawPublicKey.length - 32);
|
||||
return base64urlEncode(publicKeyBytes);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Zero chain hash (initial prev_chain_hash for the first operation)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The initial chain hash value: base64url encoding of 32 zero bytes.
|
||||
* Must match the backend's GENESIS_CHAIN_HASH constant exactly.
|
||||
*/
|
||||
// 32 zero bytes; equals the Backend GENESIS_CHAIN_HASH.
|
||||
export const ZERO_CHAIN_HASH: string = base64urlEncode(Buffer.alloc(32, 0));
|
||||
+1
-4
@@ -20,7 +20,6 @@ export {
|
||||
} from './utils.js';
|
||||
|
||||
export type {
|
||||
// Enums
|
||||
AgentStatus,
|
||||
KeyStatus,
|
||||
ExportStatus,
|
||||
@@ -29,7 +28,6 @@ export type {
|
||||
AdminAction,
|
||||
ErrorCode,
|
||||
|
||||
// Entities
|
||||
Agent,
|
||||
AgentKey,
|
||||
Operation,
|
||||
@@ -41,11 +39,9 @@ export type {
|
||||
User,
|
||||
Export,
|
||||
|
||||
// Protocol
|
||||
EOR,
|
||||
EAR,
|
||||
|
||||
// API request/response
|
||||
ElydoraClientConfig,
|
||||
CreateOperationParams,
|
||||
RegisterAgentRequest,
|
||||
@@ -75,6 +71,7 @@ export type {
|
||||
JWKSResponse,
|
||||
HealthResponse,
|
||||
DeepHealthResponse,
|
||||
Webhook,
|
||||
ListWebhooksResponse,
|
||||
RegisterWebhookResponse,
|
||||
ListMembersResponse,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { parseStrictJsonObject } from './strict-json.js';
|
||||
import { sameAgentId, samePath } from './common.js';
|
||||
import { quotePosix, readPosixArgument, type ParsedArgument } from './shell-command.js';
|
||||
import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
export const AGENT_KEY = 'augment';
|
||||
export const GUARD_SCRIPT = 'guard.js';
|
||||
@@ -20,8 +22,6 @@ const SESSION_EVENTS = new Set([
|
||||
'PromptSubmit',
|
||||
]);
|
||||
|
||||
export type JsonObject = Record<string, unknown>;
|
||||
|
||||
export interface AugmentHandler extends JsonObject {
|
||||
readonly type: 'command';
|
||||
readonly command: string;
|
||||
@@ -58,23 +58,10 @@ export interface RuntimeContract {
|
||||
readonly auditWrapperPath: string;
|
||||
}
|
||||
|
||||
interface ParsedArgument {
|
||||
readonly value: string;
|
||||
readonly next: number;
|
||||
}
|
||||
|
||||
export function isObject(value: unknown): value is JsonObject {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function hasOwn(value: JsonObject, key: string): boolean {
|
||||
return Object.prototype.hasOwnProperty.call(value, key);
|
||||
}
|
||||
|
||||
function quotePosix(value: string): string {
|
||||
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
||||
}
|
||||
|
||||
function quoteWindows(value: string): string {
|
||||
return `"${value.replaceAll('"', '\\"')}"`;
|
||||
}
|
||||
@@ -98,42 +85,12 @@ function readWindowsArgument(command: string, start: number): ParsedArgument | u
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const POSIX_APOSTROPHE = `'"'"'`;
|
||||
|
||||
function readPosixArgument(command: string, start: number): ParsedArgument | undefined {
|
||||
if (command[start] !== "'") return undefined;
|
||||
let value = '';
|
||||
for (let index = start + 1; index < command.length;) {
|
||||
if (command.startsWith(POSIX_APOSTROPHE, index)) {
|
||||
value += "'";
|
||||
index += POSIX_APOSTROPHE.length;
|
||||
continue;
|
||||
}
|
||||
if (command[index] === "'") return { value, next: index + 1 };
|
||||
value += command[index];
|
||||
index += 1;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function parseWrapperCommand(command: string): string | undefined {
|
||||
const readArgument = process.platform === 'win32' ? readWindowsArgument : readPosixArgument;
|
||||
const parsed = readArgument(command, 0);
|
||||
return parsed?.next === command.length && parsed.value ? parsed.value : undefined;
|
||||
}
|
||||
|
||||
function samePath(left: string, right: string): boolean {
|
||||
const normalizedLeft = path.resolve(left);
|
||||
const normalizedRight = path.resolve(right);
|
||||
return process.platform === 'win32'
|
||||
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
|
||||
: normalizedLeft === normalizedRight;
|
||||
}
|
||||
|
||||
function sameAgentId(left: string, right: string): boolean {
|
||||
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
|
||||
}
|
||||
|
||||
export function wrapperPaths(agentDirectory: string): {
|
||||
readonly guardPath: string;
|
||||
readonly auditPath: string;
|
||||
|
||||
@@ -22,18 +22,10 @@ const DISPLAY_NAME = 'Augment Code CLI';
|
||||
const SETTINGS_DIRECTORY_LABEL = 'Auggie configuration directory';
|
||||
const SETTINGS_LABEL = 'Auggie user settings';
|
||||
|
||||
export type AugmentRuntimePaths = ManagedRuntimePaths;
|
||||
export type PreparedAugmentInstallation = PreparedManagedInstallation;
|
||||
export type { RenameFile };
|
||||
|
||||
export function augmentRuntimePaths(config: InstallConfig): AugmentRuntimePaths {
|
||||
return managedRuntimePaths(config, AGENT_KEY, GUARD_SCRIPT, AUDIT_SCRIPT);
|
||||
}
|
||||
|
||||
export async function preflightAugmentInstallation(
|
||||
config: InstallConfig,
|
||||
settingsPath: string,
|
||||
): Promise<AugmentRuntimePaths> {
|
||||
): Promise<ManagedRuntimePaths> {
|
||||
return preflightManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
hookLocations: [{ directoryLabel: SETTINGS_DIRECTORY_LABEL, filePath: settingsPath }],
|
||||
@@ -44,13 +36,13 @@ export async function preflightAugmentInstallation(
|
||||
export async function prepareAugmentInstallation(
|
||||
config: InstallConfig,
|
||||
rendered: RenderedAugmentDocument,
|
||||
): Promise<PreparedAugmentInstallation> {
|
||||
): Promise<PreparedManagedInstallation> {
|
||||
if (!rendered.changed && rendered.document.raw === undefined) {
|
||||
throw new Error('Auggie hook installation did not produce a settings document');
|
||||
}
|
||||
const settingsSource = rendered.next ?? rendered.document.raw;
|
||||
if (settingsSource === undefined) throw new Error('Auggie hook settings are missing');
|
||||
const paths = augmentRuntimePaths(config);
|
||||
const paths = managedRuntimePaths(config, AGENT_KEY, GUARD_SCRIPT, AUDIT_SCRIPT);
|
||||
return prepareManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
displayName: DISPLAY_NAME,
|
||||
@@ -78,7 +70,7 @@ export async function prepareAugmentInstallation(
|
||||
}
|
||||
|
||||
export async function commitAugmentInstallation(
|
||||
prepared: PreparedAugmentInstallation,
|
||||
prepared: PreparedManagedInstallation,
|
||||
renameFile?: RenameFile,
|
||||
): Promise<void> {
|
||||
await commitManagedInstallation(prepared, renameFile);
|
||||
|
||||
+10
-95
@@ -2,9 +2,7 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
AGENT_KEY,
|
||||
AUDIT_SCRIPT,
|
||||
AUDIT_WRAPPER,
|
||||
GUARD_SCRIPT,
|
||||
GUARD_WRAPPER,
|
||||
buildWrapper,
|
||||
createAugmentDocument,
|
||||
@@ -13,15 +11,13 @@ import {
|
||||
type RenderedAugmentDocument,
|
||||
type RuntimeContract,
|
||||
} from './augment-contract.js';
|
||||
import { MAX_CONFIG_BYTES, samePath } from './common.js';
|
||||
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
|
||||
import { managedRuntimeFilesExist } from './managed-runtime-status.js';
|
||||
import {
|
||||
commitManagedTransaction,
|
||||
prepareManagedFileChange,
|
||||
} from './managed-transaction.js';
|
||||
import { parseStrictJsonObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
const MAX_SECRET_BYTES = 64 * 1024;
|
||||
const MAX_CONFIG_BYTES = 512 * 1024;
|
||||
|
||||
export function resolveConfigPath(): string {
|
||||
return path.join(os.homedir(), '.augment', 'settings.json');
|
||||
@@ -59,102 +55,21 @@ export async function writeAugmentDocument(rendered: RenderedAugmentDocument): P
|
||||
});
|
||||
}
|
||||
|
||||
function sameAgentId(left: string, right: string): boolean {
|
||||
return process.platform === 'win32'
|
||||
? left.toLowerCase() === right.toLowerCase()
|
||||
: left === right;
|
||||
}
|
||||
|
||||
function samePath(left: string, right: string): boolean {
|
||||
const normalizedLeft = path.resolve(left);
|
||||
const normalizedRight = path.resolve(right);
|
||||
return process.platform === 'win32'
|
||||
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
|
||||
: normalizedLeft === normalizedRight;
|
||||
}
|
||||
|
||||
function 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: RuntimeContract,
|
||||
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 (!sameAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
|
||||
throw new Error(`Elydora runtime identity does not match Auggie 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}`);
|
||||
}
|
||||
}
|
||||
|
||||
function validContractPaths(contract: RuntimeContract, agentDirectory: string): boolean {
|
||||
return samePath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))
|
||||
&& samePath(contract.guardPath, path.join(agentDirectory, GUARD_SCRIPT))
|
||||
&& samePath(contract.auditPath, path.join(agentDirectory, AUDIT_SCRIPT))
|
||||
&& samePath(contract.guardWrapperPath, path.join(agentDirectory, GUARD_WRAPPER))
|
||||
function wrappersValid(contract: RuntimeContract): boolean {
|
||||
const agentDirectory = path.dirname(contract.guardPath);
|
||||
return samePath(contract.guardWrapperPath, path.join(agentDirectory, GUARD_WRAPPER))
|
||||
&& samePath(contract.auditWrapperPath, path.join(agentDirectory, AUDIT_WRAPPER));
|
||||
}
|
||||
|
||||
async function runtimeContractExists(contract: RuntimeContract): Promise<boolean> {
|
||||
const runtimeRoot = path.join(os.homedir(), '.elydora');
|
||||
const agentDirectory = path.dirname(contract.guardPath);
|
||||
if (!validContractPaths(contract, agentDirectory)) 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, guardWrapper, auditWrapper] = await Promise.all([
|
||||
readPhysicalFile(configPath, 'Elydora runtime config', MAX_CONFIG_BYTES),
|
||||
readPhysicalFile(keyPath, 'Elydora private key', MAX_SECRET_BYTES),
|
||||
readPhysicalFile(contract.guardPath, 'Elydora guard runtime'),
|
||||
readPhysicalFile(contract.auditPath, 'Elydora audit runtime'),
|
||||
if (!wrappersValid(contract)) return false;
|
||||
if (!await managedRuntimeFilesExist(contract, AGENT_KEY)) return false;
|
||||
const [guardWrapper, auditWrapper] = await Promise.all([
|
||||
readPhysicalFile(contract.guardWrapperPath, 'Auggie guard wrapper'),
|
||||
readPhysicalFile(contract.auditWrapperPath, 'Auggie audit wrapper'),
|
||||
]);
|
||||
if (!config || !key || !guard || !audit || !guardWrapper || !auditWrapper) 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
|
||||
&& guardWrapper.contents === buildWrapper(contract.guardPath)
|
||||
&& auditWrapper.contents === buildWrapper(contract.auditPath);
|
||||
return guardWrapper?.contents === buildWrapper(contract.guardPath)
|
||||
&& auditWrapper?.contents === buildWrapper(contract.auditPath);
|
||||
}
|
||||
|
||||
export async function augmentRuntimeFilesExist(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { sameAgentId, samePath } from './common.js';
|
||||
import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
export const AGENT_KEY = 'claudecode';
|
||||
@@ -76,20 +77,6 @@ interface RuntimeReference {
|
||||
readonly scriptPath: string;
|
||||
}
|
||||
|
||||
function samePath(left: string, right: string): boolean {
|
||||
const normalizedLeft = path.resolve(left);
|
||||
const normalizedRight = path.resolve(right);
|
||||
return process.platform === 'win32'
|
||||
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
|
||||
: normalizedLeft === normalizedRight;
|
||||
}
|
||||
|
||||
function sameAgentId(left: string, right: string): boolean {
|
||||
return process.platform === 'win32'
|
||||
? left.toLowerCase() === right.toLowerCase()
|
||||
: left === right;
|
||||
}
|
||||
|
||||
function requireKnownKeys(value: JsonObject, allowed: readonly string[], label: string): void {
|
||||
const keys = new Set(allowed);
|
||||
const extra = Object.keys(value).find((key) => !keys.has(key));
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
} from './claudecode-contract.js';
|
||||
import {
|
||||
commitManagedInstallation,
|
||||
managedRuntimePaths,
|
||||
preflightManagedInstallation,
|
||||
prepareManagedInstallation,
|
||||
type ManagedRuntimePaths,
|
||||
@@ -19,18 +18,10 @@ const DISPLAY_NAME = 'Claude Code';
|
||||
const SETTINGS_DIRECTORY_LABEL = 'Claude Code configuration directory';
|
||||
const SETTINGS_LABEL = 'Claude Code user settings';
|
||||
|
||||
export type ClaudeRuntimePaths = ManagedRuntimePaths;
|
||||
export type PreparedClaudeInstallation = PreparedManagedInstallation;
|
||||
export type { RenameFile };
|
||||
|
||||
export function claudeRuntimePaths(config: InstallConfig): ClaudeRuntimePaths {
|
||||
return managedRuntimePaths(config, AGENT_KEY, GUARD_SCRIPT, AUDIT_SCRIPT);
|
||||
}
|
||||
|
||||
export async function preflightClaudeInstallation(
|
||||
config: InstallConfig,
|
||||
settingsPath: string,
|
||||
): Promise<ClaudeRuntimePaths> {
|
||||
): Promise<ManagedRuntimePaths> {
|
||||
return preflightManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
hookLocations: [{ directoryLabel: SETTINGS_DIRECTORY_LABEL, filePath: settingsPath }],
|
||||
@@ -41,7 +32,7 @@ export async function preflightClaudeInstallation(
|
||||
export async function prepareClaudeInstallation(
|
||||
config: InstallConfig,
|
||||
rendered: RenderedClaudeDocument,
|
||||
): Promise<PreparedClaudeInstallation> {
|
||||
): Promise<PreparedManagedInstallation> {
|
||||
if (!rendered.changed && rendered.document.raw === undefined) {
|
||||
throw new Error('Claude Code hook installation did not produce a settings document');
|
||||
}
|
||||
@@ -63,7 +54,7 @@ export async function prepareClaudeInstallation(
|
||||
}
|
||||
|
||||
export async function commitClaudeInstallation(
|
||||
prepared: PreparedClaudeInstallation,
|
||||
prepared: PreparedManagedInstallation,
|
||||
renameFile?: RenameFile,
|
||||
): Promise<void> {
|
||||
await commitManagedInstallation(prepared, renameFile);
|
||||
|
||||
@@ -10,11 +10,11 @@ import {
|
||||
type RenderedClaudeDocument,
|
||||
} from './claudecode-contract.js';
|
||||
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
|
||||
import { managedRuntimeFilesExist } from './managed-runtime-status.js';
|
||||
import {
|
||||
commitManagedTransaction,
|
||||
prepareManagedFileChange,
|
||||
} from './managed-transaction.js';
|
||||
import { parseStrictJsonObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
export function claudeConfigDirectory(): string {
|
||||
const configured = process.env.CLAUDE_CONFIG_DIR;
|
||||
@@ -58,96 +58,11 @@ export async function writeClaudeDocument(rendered: RenderedClaudeDocument): Pro
|
||||
});
|
||||
}
|
||||
|
||||
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 sameAgentId(left: string, right: string): boolean {
|
||||
return process.platform === 'win32'
|
||||
? left.toLowerCase() === right.toLowerCase()
|
||||
: left === right;
|
||||
}
|
||||
|
||||
function samePath(left: string, right: string): boolean {
|
||||
const normalizedLeft = path.resolve(left);
|
||||
const normalizedRight = path.resolve(right);
|
||||
return process.platform === 'win32'
|
||||
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
|
||||
: normalizedLeft === normalizedRight;
|
||||
}
|
||||
|
||||
function validateRuntimeConfig(
|
||||
config: JsonObject,
|
||||
contract: ClaudeRuntimeContract,
|
||||
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 (!sameAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
|
||||
throw new Error(`Elydora runtime identity does not match Claude 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: ClaudeRuntimeContract): Promise<boolean> {
|
||||
const runtimeRoot = path.join(os.homedir(), '.elydora');
|
||||
const agentDirectory = path.dirname(contract.guardPath);
|
||||
if (!samePath(path.dirname(agentDirectory), runtimeRoot)
|
||||
|| !samePath(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 claudeRuntimeFilesExist(
|
||||
contracts: readonly ClaudeRuntimeContract[],
|
||||
): Promise<boolean> {
|
||||
for (const contract of contracts) {
|
||||
if (await runtimeContractExists(contract)) return true;
|
||||
if (await managedRuntimeFilesExist(contract, AGENT_KEY)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { asError, errorMessage, sameAgentId, samePath } from './common.js';
|
||||
import { isObject } from './strict-json.js';
|
||||
|
||||
export const AGENT_KEY = 'cline';
|
||||
export const GUARD_SCRIPT = 'guard.js';
|
||||
@@ -33,32 +35,6 @@ export interface ClineRuntimeContract {
|
||||
readonly auditPath: string;
|
||||
}
|
||||
|
||||
type JsonObject = Record<string, unknown>;
|
||||
|
||||
function isObject(value: unknown): value is JsonObject {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function asError(error: unknown): Error {
|
||||
return error instanceof Error ? error : new Error(String(error));
|
||||
}
|
||||
|
||||
function samePath(left: string, right: string): boolean {
|
||||
const normalizedLeft = path.resolve(left);
|
||||
const normalizedRight = path.resolve(right);
|
||||
return process.platform === 'win32'
|
||||
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
|
||||
: normalizedLeft === normalizedRight;
|
||||
}
|
||||
|
||||
export function sameAgentId(left: string, right: string): boolean {
|
||||
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
|
||||
}
|
||||
|
||||
export function resolveHooksDirectory(): string {
|
||||
const configuredDirectory = process.env.CLINE_DIR?.trim();
|
||||
const clineDirectory = configuredDirectory
|
||||
|
||||
@@ -9,8 +9,8 @@ import {
|
||||
buildWrapper,
|
||||
type ClineHookFile,
|
||||
runtimeContract,
|
||||
sameAgentId,
|
||||
} from './cline-contract.js';
|
||||
import { sameAgentId } from './common.js';
|
||||
import {
|
||||
commitManagedInstallation,
|
||||
preflightManagedInstallation,
|
||||
@@ -28,10 +28,6 @@ import {
|
||||
const DISPLAY_NAME = 'Cline';
|
||||
const DIRECTORY_LABEL = 'Cline hooks directory';
|
||||
|
||||
export type ClineRuntimePaths = ManagedRuntimePaths;
|
||||
export type PreparedClineInstallation = PreparedManagedInstallation;
|
||||
export type { RenameFile };
|
||||
|
||||
function hookLocations(files: readonly ClineHookFile[]) {
|
||||
return files.map((file) => ({
|
||||
directoryLabel: DIRECTORY_LABEL,
|
||||
@@ -42,7 +38,7 @@ function hookLocations(files: readonly ClineHookFile[]) {
|
||||
export async function preflightClineInstallation(
|
||||
config: InstallConfig,
|
||||
files: readonly ClineHookFile[],
|
||||
): Promise<ClineRuntimePaths> {
|
||||
): Promise<ManagedRuntimePaths> {
|
||||
return preflightManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
hookLocations: hookLocations(files),
|
||||
@@ -54,7 +50,7 @@ export async function prepareClineInstallation(
|
||||
config: InstallConfig,
|
||||
guardFile: ClineHookFile,
|
||||
auditFile: ClineHookFile,
|
||||
): Promise<PreparedClineInstallation> {
|
||||
): Promise<PreparedManagedInstallation> {
|
||||
const paths = await preflightClineInstallation(config, [guardFile, auditFile]);
|
||||
const guardMetadata = buildMetadata('guard', config.agentId, paths.guardPath);
|
||||
const auditMetadata = buildMetadata('audit', config.agentId, paths.auditPath);
|
||||
@@ -86,7 +82,7 @@ export async function prepareClineInstallation(
|
||||
}
|
||||
|
||||
export async function commitClineInstallation(
|
||||
prepared: PreparedClineInstallation,
|
||||
prepared: PreparedManagedInstallation,
|
||||
renameFile?: RenameFile,
|
||||
): Promise<void> {
|
||||
await commitManagedInstallation(prepared, renameFile);
|
||||
|
||||
+2
-96
@@ -1,21 +1,12 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
AGENT_KEY,
|
||||
AUDIT_SCRIPT,
|
||||
GUARD_SCRIPT,
|
||||
type ClineHookFile,
|
||||
type ClineRuntimeContract,
|
||||
parseMetadata,
|
||||
sameAgentId,
|
||||
} from './cline-contract.js';
|
||||
import { generateGuardScript } from './guard-template.js';
|
||||
import { generateHookScript } from './hook-template.js';
|
||||
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
|
||||
import { parseStrictJsonObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
const MAX_SECRET_BYTES = 64 * 1024;
|
||||
const MAX_CONFIG_BYTES = 512 * 1024;
|
||||
import { managedRuntimeFilesExist } from './managed-runtime-status.js';
|
||||
|
||||
export async function readHookFile(filePath: string): Promise<ClineHookFile> {
|
||||
const directory = path.dirname(filePath);
|
||||
@@ -38,91 +29,6 @@ export function requireAvailableHookFile(file: ClineHookFile): void {
|
||||
}
|
||||
}
|
||||
|
||||
function samePath(left: string, right: string): boolean {
|
||||
const normalizedLeft = path.resolve(left);
|
||||
const normalizedRight = path.resolve(right);
|
||||
return process.platform === 'win32'
|
||||
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
|
||||
: normalizedLeft === normalizedRight;
|
||||
}
|
||||
|
||||
function requireString(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: ClineRuntimeContract,
|
||||
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}`);
|
||||
requireString(config.org_id, 'org_id', configPath);
|
||||
requireString(config.kid, 'kid', configPath);
|
||||
const agentId = requireString(config.agent_id, 'agent_id', configPath);
|
||||
if (!sameAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
|
||||
throw new Error(`Elydora runtime identity does not match Cline hooks: ${configPath}`);
|
||||
}
|
||||
if (config.token !== undefined) requireString(config.token, 'token', configPath);
|
||||
const rawBaseUrl = requireString(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}`);
|
||||
}
|
||||
}
|
||||
|
||||
function validContractPaths(contract: ClineRuntimeContract): boolean {
|
||||
return samePath(path.dirname(contract.agentDirectory), path.join(os.homedir(), '.elydora'))
|
||||
&& samePath(contract.guardPath, path.join(contract.agentDirectory, GUARD_SCRIPT))
|
||||
&& samePath(contract.auditPath, path.join(contract.agentDirectory, AUDIT_SCRIPT));
|
||||
}
|
||||
|
||||
export async function runtimeFilesExist(contract: ClineRuntimeContract): Promise<boolean> {
|
||||
if (!validContractPaths(contract)) return false;
|
||||
const runtimeRoot = path.join(os.homedir(), '.elydora');
|
||||
if (!await inspectPhysicalDirectory(runtimeRoot, 'Elydora runtime directory')) return false;
|
||||
if (!await inspectPhysicalDirectory(contract.agentDirectory, 'Elydora agent runtime directory')) {
|
||||
return false;
|
||||
}
|
||||
const configPath = path.join(contract.agentDirectory, 'config.json');
|
||||
const keyPath = path.join(contract.agentDirectory, 'private.key');
|
||||
const [config, key, guard, audit] = await Promise.all([
|
||||
readPhysicalFile(configPath, 'Elydora runtime config', MAX_CONFIG_BYTES),
|
||||
readPhysicalFile(keyPath, 'Elydora private key', MAX_SECRET_BYTES),
|
||||
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 },
|
||||
);
|
||||
return managedRuntimeFilesExist(contract, AGENT_KEY);
|
||||
}
|
||||
+15
-129
@@ -1,5 +1,14 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { sameAgentId, samePath } from './common.js';
|
||||
import {
|
||||
encodedWindowsCommand,
|
||||
isNodeExecutable,
|
||||
parseEncodedWindowsCommand,
|
||||
parseLegacyWindowsCommand,
|
||||
parsePosixCommand,
|
||||
posixSource,
|
||||
} from './shell-command.js';
|
||||
import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
export const AGENT_KEY = 'codex';
|
||||
@@ -33,142 +42,16 @@ export interface RuntimeContract {
|
||||
readonly auditPath: string;
|
||||
}
|
||||
|
||||
interface ParsedArgument {
|
||||
readonly value: string;
|
||||
readonly next: number;
|
||||
}
|
||||
|
||||
function samePath(left: string, right: string): boolean {
|
||||
const normalizedLeft = path.resolve(left);
|
||||
const normalizedRight = path.resolve(right);
|
||||
return process.platform === 'win32'
|
||||
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
|
||||
: normalizedLeft === normalizedRight;
|
||||
}
|
||||
|
||||
function sameAgentId(left: string, right: string): boolean {
|
||||
return process.platform === 'win32'
|
||||
? left.toLowerCase() === right.toLowerCase()
|
||||
: left === right;
|
||||
}
|
||||
|
||||
function 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 buildHandler(scriptPath: string, statusMessage: string): JsonObject {
|
||||
return {
|
||||
type: 'command',
|
||||
command: `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`,
|
||||
commandWindows: windowsCommand(scriptPath),
|
||||
command: posixSource(scriptPath),
|
||||
commandWindows: encodedWindowsCommand(scriptPath),
|
||||
timeout: HOOK_TIMEOUT_SECONDS,
|
||||
statusMessage,
|
||||
};
|
||||
}
|
||||
|
||||
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: unknown): readonly [string, string] | undefined {
|
||||
if (typeof command !== 'string') return 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: unknown): readonly [string, string] | undefined {
|
||||
if (typeof command !== 'string') return 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];
|
||||
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) return undefined;
|
||||
const buffer = Buffer.from(encoded, 'base64');
|
||||
if (buffer.toString('base64') !== encoded || buffer.length % 2 !== 0) return undefined;
|
||||
return parsePowerShellSource(buffer.toString('utf16le'));
|
||||
}
|
||||
|
||||
function parseLegacyWindowsCommand(command: unknown): readonly [string, string] | undefined {
|
||||
if (typeof command !== 'string') return 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);
|
||||
return basename === 'node' || basename.toLowerCase() === 'node.exe';
|
||||
}
|
||||
|
||||
function exactHandlerKeys(handler: JsonObject): boolean {
|
||||
return Object.keys(handler).sort().join('|')
|
||||
=== 'command|commandWindows|statusMessage|timeout|type';
|
||||
@@ -179,8 +62,11 @@ function managedScriptPath(handler: JsonObject, statusMessage: string): string |
|
||||
|| handler.type !== 'command'
|
||||
|| handler.timeout !== HOOK_TIMEOUT_SECONDS
|
||||
|| handler.statusMessage !== statusMessage) return undefined;
|
||||
if (typeof handler.command !== 'string' || typeof handler.commandWindows !== 'string') {
|
||||
return undefined;
|
||||
}
|
||||
const posix = parsePosixCommand(handler.command);
|
||||
const windows = parseWindowsCommand(handler.commandWindows)
|
||||
const windows = parseEncodedWindowsCommand(handler.commandWindows)
|
||||
?? parseLegacyWindowsCommand(handler.commandWindows);
|
||||
if (!posix || !windows
|
||||
|| !path.isAbsolute(posix[0])
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
} from './codex-contract.js';
|
||||
import {
|
||||
commitManagedInstallation,
|
||||
managedRuntimePaths,
|
||||
preflightManagedInstallation,
|
||||
prepareManagedInstallation,
|
||||
type ManagedRuntimePaths,
|
||||
@@ -19,18 +18,10 @@ const DISPLAY_NAME = 'Codex';
|
||||
const HOOKS_DIRECTORY_LABEL = 'Codex hooks directory';
|
||||
const HOOKS_LABEL = 'Codex user hooks';
|
||||
|
||||
export type CodexRuntimePaths = ManagedRuntimePaths;
|
||||
export type PreparedCodexInstallation = PreparedManagedInstallation;
|
||||
export type { RenameFile };
|
||||
|
||||
export function codexRuntimePaths(config: InstallConfig): CodexRuntimePaths {
|
||||
return managedRuntimePaths(config, AGENT_KEY, GUARD_SCRIPT, AUDIT_SCRIPT);
|
||||
}
|
||||
|
||||
export async function preflightCodexInstallation(
|
||||
config: InstallConfig,
|
||||
hooksPath: string,
|
||||
): Promise<CodexRuntimePaths> {
|
||||
): Promise<ManagedRuntimePaths> {
|
||||
return preflightManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
hookLocations: [{ directoryLabel: HOOKS_DIRECTORY_LABEL, filePath: hooksPath }],
|
||||
@@ -41,7 +32,7 @@ export async function preflightCodexInstallation(
|
||||
export async function prepareCodexInstallation(
|
||||
config: InstallConfig,
|
||||
rendered: RenderedDocument,
|
||||
): Promise<PreparedCodexInstallation> {
|
||||
): Promise<PreparedManagedInstallation> {
|
||||
if (!rendered.changed && rendered.document.raw === undefined) {
|
||||
throw new Error('Codex hook installation did not produce a configuration document');
|
||||
}
|
||||
@@ -63,7 +54,7 @@ export async function prepareCodexInstallation(
|
||||
}
|
||||
|
||||
export async function commitCodexInstallation(
|
||||
prepared: PreparedCodexInstallation,
|
||||
prepared: PreparedManagedInstallation,
|
||||
renameFile?: RenameFile,
|
||||
): Promise<void> {
|
||||
await commitManagedInstallation(prepared, renameFile);
|
||||
|
||||
+25
-138
@@ -1,6 +1,4 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import fsp from 'node:fs/promises';
|
||||
import type { FileHandle } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
@@ -12,20 +10,13 @@ import {
|
||||
createDocument,
|
||||
parseDocument,
|
||||
} from './codex-contract.js';
|
||||
import { asError, errorMessage } from './common.js';
|
||||
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
|
||||
import { parseStrictJsonObject } from './strict-json.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;
|
||||
}
|
||||
import { managedRuntimePresent } from './managed-runtime-status.js';
|
||||
import {
|
||||
commitManagedTransaction,
|
||||
prepareManagedFileChange,
|
||||
} from './managed-transaction.js';
|
||||
|
||||
async function codexHomePath(): Promise<string> {
|
||||
const configured = process.env.CODEX_HOME;
|
||||
@@ -63,135 +54,31 @@ export async function readDocument(): Promise<CodexDocument> {
|
||||
return snapshot ? parseDocument(filePath, snapshot.contents) : createDocument(filePath);
|
||||
}
|
||||
|
||||
async function unlinkOptional(filePath: string): Promise<void> {
|
||||
try {
|
||||
await fsp.unlink(filePath);
|
||||
} catch (error) {
|
||||
if (!hasCode(error, 'ENOENT')) throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function writeExclusive(filePath: string, contents: string): Promise<void> {
|
||||
let handle: FileHandle | undefined;
|
||||
try {
|
||||
handle = await fsp.open(filePath, 'wx', 0o600);
|
||||
await handle.writeFile(contents, 'utf-8');
|
||||
await handle.sync();
|
||||
await handle.close();
|
||||
handle = undefined;
|
||||
if (process.platform !== 'win32') await fsp.chmod(filePath, 0o600);
|
||||
} catch (error) {
|
||||
const failures = [asError(error)];
|
||||
if (handle) {
|
||||
try { await handle.close(); } catch (closeError) { failures.push(asError(closeError)); }
|
||||
}
|
||||
try { await unlinkOptional(filePath); } catch (cleanupError) {
|
||||
failures.push(asError(cleanupError));
|
||||
}
|
||||
if (failures.length > 1) throw new AggregateError(failures, 'Stage Codex user hooks');
|
||||
throw new Error(`Stage Codex user hooks: ${errorMessage(error)}`, { cause: failures[0] });
|
||||
}
|
||||
}
|
||||
|
||||
async function assertUnchanged(document: CodexDocument): Promise<void> {
|
||||
const current = await readPhysicalFile(document.filePath, 'Codex user hooks');
|
||||
if (current?.contents !== document.raw) {
|
||||
throw new Error(`Codex user hooks changed during update: ${document.filePath}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureHooksDirectory(directory: string): Promise<void> {
|
||||
try {
|
||||
await fsp.mkdir(directory, { recursive: true, mode: 0o700 });
|
||||
} catch (error) {
|
||||
throw new Error(`Create Codex hooks directory at ${directory}: ${errorMessage(error)}`, {
|
||||
cause: asError(error),
|
||||
});
|
||||
}
|
||||
if (!await inspectPhysicalDirectory(directory, 'Codex hooks directory')) {
|
||||
throw new Error(`Codex hooks directory is missing: ${directory}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeDocument(rendered: RenderedDocument): Promise<void> {
|
||||
if (!rendered.changed) return;
|
||||
await assertUnchanged(rendered.document);
|
||||
const directory = path.dirname(rendered.document.filePath);
|
||||
await ensureHooksDirectory(directory);
|
||||
if (rendered.next === undefined) {
|
||||
try {
|
||||
await fsp.unlink(rendered.document.filePath);
|
||||
} catch (error) {
|
||||
if (!hasCode(error, 'ENOENT')) {
|
||||
throw new Error(
|
||||
`Remove Codex user hooks at ${rendered.document.filePath}: ${errorMessage(error)}`,
|
||||
{ cause: asError(error) },
|
||||
);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const temporaryPath = path.join(
|
||||
directory,
|
||||
`.${path.basename(rendered.document.filePath)}.${randomUUID()}.tmp`,
|
||||
);
|
||||
let failure: Error | undefined;
|
||||
try {
|
||||
await writeExclusive(temporaryPath, rendered.next);
|
||||
await assertUnchanged(rendered.document);
|
||||
await fsp.rename(temporaryPath, rendered.document.filePath);
|
||||
} catch (error) {
|
||||
failure = new Error(
|
||||
`Write Codex user hooks at ${rendered.document.filePath}: ${errorMessage(error)}`,
|
||||
{ cause: asError(error) },
|
||||
);
|
||||
}
|
||||
let cleanupFailure: Error | undefined;
|
||||
try {
|
||||
await unlinkOptional(temporaryPath);
|
||||
} catch (error) {
|
||||
cleanupFailure = new Error(
|
||||
`Clean Codex hook staging file at ${temporaryPath}: ${errorMessage(error)}`,
|
||||
{ cause: asError(error) },
|
||||
);
|
||||
}
|
||||
if (failure && cleanupFailure) {
|
||||
throw new AggregateError([failure, cleanupFailure], 'Write Codex user hooks');
|
||||
}
|
||||
if (failure) throw failure;
|
||||
if (cleanupFailure) throw cleanupFailure;
|
||||
}
|
||||
|
||||
async function physicalFileExists(filePath: string, label: string): Promise<boolean> {
|
||||
return Boolean(await readPhysicalFile(filePath, label));
|
||||
}
|
||||
|
||||
function sameAgentId(left: unknown, right: string): boolean {
|
||||
return typeof left === 'string' && (process.platform === 'win32'
|
||||
? left.toLowerCase() === right.toLowerCase()
|
||||
: left === right);
|
||||
const change = await prepareManagedFileChange({
|
||||
filePath: rendered.document.filePath,
|
||||
label: 'Codex user hooks',
|
||||
next: rendered.next,
|
||||
mode: 0o600,
|
||||
expectedSource: rendered.document.raw,
|
||||
verifyExpectedSource: true,
|
||||
});
|
||||
if (!change) return;
|
||||
await commitManagedTransaction({
|
||||
displayName: 'Codex',
|
||||
operation: 'uninstall',
|
||||
directories: [{
|
||||
path: path.dirname(rendered.document.filePath),
|
||||
label: 'Codex hooks directory',
|
||||
}],
|
||||
changes: [change],
|
||||
});
|
||||
}
|
||||
|
||||
export async function runtimeFilesExist(contracts: RuntimeContract[]): Promise<boolean> {
|
||||
for (const contract of contracts) {
|
||||
const directory = path.dirname(contract.guardPath);
|
||||
const configPath = path.join(directory, 'config.json');
|
||||
const snapshot = await readPhysicalFile(configPath, 'Elydora runtime config');
|
||||
if (!snapshot) continue;
|
||||
const config = parseStrictJsonObject(
|
||||
snapshot.contents,
|
||||
`Elydora runtime config at ${configPath}`,
|
||||
);
|
||||
if (config.agent_name !== AGENT_KEY || !sameAgentId(config.agent_id, contract.agentId)) {
|
||||
continue;
|
||||
}
|
||||
const files = await Promise.all([
|
||||
physicalFileExists(contract.guardPath, 'Elydora guard runtime'),
|
||||
physicalFileExists(contract.auditPath, 'Elydora audit runtime'),
|
||||
physicalFileExists(path.join(directory, 'private.key'), 'Elydora private key'),
|
||||
]);
|
||||
if (files.every(Boolean)) return true;
|
||||
if (await managedRuntimePresent(contract, AGENT_KEY)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
export const MAX_SECRET_BYTES = 64 * 1024;
|
||||
export const MAX_CONFIG_BYTES = 512 * 1024;
|
||||
export const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
export function asError(error: unknown): Error {
|
||||
return error instanceof Error ? error : new Error(String(error));
|
||||
}
|
||||
|
||||
export function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
export function hasCode(error: unknown, code: string): boolean {
|
||||
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 {
|
||||
return pathKey(left) === pathKey(right);
|
||||
}
|
||||
|
||||
export function sameAgentId(left: unknown, right: string): boolean {
|
||||
return typeof left === 'string' && (process.platform === 'win32'
|
||||
? left.toLowerCase() === right.toLowerCase()
|
||||
: 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;
|
||||
}
|
||||
@@ -1,6 +1,14 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { sameAgentId, samePath } from './common.js';
|
||||
import type { FileSnapshot } from './managed-files.js';
|
||||
import {
|
||||
isNodeExecutable,
|
||||
parsePosixCommand,
|
||||
parsePowerShellSource,
|
||||
posixSource,
|
||||
powerShellSource,
|
||||
} from './shell-command.js';
|
||||
import { validateHooks, type CopilotHooks } from './copilot-schema.js';
|
||||
import { parseStrictJsonObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
@@ -51,122 +59,38 @@ export interface RuntimeContract {
|
||||
readonly auditPath: string;
|
||||
}
|
||||
|
||||
interface ParsedArgument {
|
||||
readonly value: string;
|
||||
readonly next: number;
|
||||
}
|
||||
|
||||
interface ManagedEntry {
|
||||
readonly agentId: string;
|
||||
readonly scriptPath: string;
|
||||
}
|
||||
|
||||
export function samePath(left: string, right: string): boolean {
|
||||
const normalizedLeft = path.resolve(left);
|
||||
const normalizedRight = path.resolve(right);
|
||||
return process.platform === 'win32'
|
||||
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
|
||||
: normalizedLeft === normalizedRight;
|
||||
}
|
||||
|
||||
export function sameAgentId(left: string, right: string): boolean {
|
||||
return process.platform === 'win32'
|
||||
? left.toLowerCase() === right.toLowerCase()
|
||||
: left === right;
|
||||
}
|
||||
|
||||
function agentKey(agentId: string): string {
|
||||
return process.platform === 'win32' ? agentId.toLowerCase() : agentId;
|
||||
}
|
||||
|
||||
function quotePosix(value: string): string {
|
||||
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
||||
}
|
||||
|
||||
function quotePowerShell(value: string): string {
|
||||
return `'${value.replaceAll("'", "''")}'`;
|
||||
}
|
||||
|
||||
export function buildHandler(scriptPath: string): JsonObject {
|
||||
return {
|
||||
type: 'command',
|
||||
bash: `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`,
|
||||
powershell: `& ${quotePowerShell(process.execPath)} ${quotePowerShell(scriptPath)}; exit $LASTEXITCODE`,
|
||||
bash: posixSource(scriptPath),
|
||||
powershell: powerShellSource(scriptPath),
|
||||
timeoutSec: HOOK_TIMEOUT_SECONDS,
|
||||
};
|
||||
}
|
||||
|
||||
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 parseGeneratedBash(command: unknown): readonly [string, string] | undefined {
|
||||
if (typeof command !== 'string') return 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 parseGeneratedPowerShell(command: unknown): readonly [string, string] | undefined {
|
||||
if (typeof command !== 'string' || !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 exactHandlerKeys(handler: JsonObject): boolean {
|
||||
return Object.keys(handler).sort().join(',') === 'bash,powershell,timeoutSec,type';
|
||||
}
|
||||
|
||||
function nodeExecutable(filePath: string): boolean {
|
||||
if (!path.isAbsolute(filePath)) return false;
|
||||
const name = path.basename(filePath).toLowerCase();
|
||||
return name === 'node' || name === 'node.exe';
|
||||
}
|
||||
|
||||
function currentManagedScriptPath(handler: JsonObject): string | undefined {
|
||||
if (!exactHandlerKeys(handler)
|
||||
|| handler.type !== 'command'
|
||||
|| handler.timeoutSec !== HOOK_TIMEOUT_SECONDS) return undefined;
|
||||
const bash = parseGeneratedBash(handler.bash);
|
||||
const powershell = parseGeneratedPowerShell(handler.powershell);
|
||||
if (typeof handler.bash !== 'string' || typeof handler.powershell !== 'string') return undefined;
|
||||
const bash = parsePosixCommand(handler.bash);
|
||||
const powershell = parsePowerShellSource(handler.powershell);
|
||||
if (!bash || !powershell
|
||||
|| !nodeExecutable(bash[0])
|
||||
|| !path.isAbsolute(bash[0])
|
||||
|| !isNodeExecutable(bash[0])
|
||||
|| !samePath(bash[0], powershell[0])
|
||||
|| !samePath(bash[1], powershell[1])) return undefined;
|
||||
return bash[1];
|
||||
|
||||
@@ -6,8 +6,8 @@ import {
|
||||
GUARD_SCRIPT,
|
||||
type CopilotSources,
|
||||
type RenderedDocument,
|
||||
samePath,
|
||||
} from './copilot-contract.js';
|
||||
import { MAX_SOURCE_BYTES, samePath } from './common.js';
|
||||
import { requireHooksEnabled } from './copilot-io.js';
|
||||
import {
|
||||
commitManagedInstallation,
|
||||
@@ -26,11 +26,6 @@ import {
|
||||
const DISPLAY_NAME = 'GitHub Copilot CLI';
|
||||
const DIRECTORY_LABEL = 'GitHub Copilot hooks directory';
|
||||
const SOURCE_LABEL = 'GitHub Copilot hook source';
|
||||
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
export type CopilotRuntimePaths = ManagedRuntimePaths;
|
||||
export type PreparedCopilotInstallation = PreparedManagedInstallation;
|
||||
export type { RenameFile };
|
||||
|
||||
function hookLocations(sources: CopilotSources) {
|
||||
return [sources.user, ...(sources.legacy ? [sources.legacy] : [])].map((document) => ({
|
||||
@@ -42,7 +37,7 @@ function hookLocations(sources: CopilotSources) {
|
||||
export async function preflightCopilotInstallation(
|
||||
config: InstallConfig,
|
||||
sources: CopilotSources,
|
||||
): Promise<CopilotRuntimePaths> {
|
||||
): Promise<ManagedRuntimePaths> {
|
||||
requireHooksEnabled(sources);
|
||||
return preflightManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
@@ -63,7 +58,7 @@ export async function prepareCopilotInstallation(
|
||||
config: InstallConfig,
|
||||
sources: CopilotSources,
|
||||
rendered: readonly RenderedDocument[],
|
||||
): Promise<PreparedCopilotInstallation> {
|
||||
): Promise<PreparedManagedInstallation> {
|
||||
await preflightCopilotInstallation(config, sources);
|
||||
const documents = installationDocuments(sources, rendered);
|
||||
const prepared = await prepareManagedInstallation({
|
||||
@@ -107,7 +102,7 @@ export async function prepareCopilotInstallation(
|
||||
}
|
||||
|
||||
export async function commitCopilotInstallation(
|
||||
prepared: PreparedCopilotInstallation,
|
||||
prepared: PreparedManagedInstallation,
|
||||
renameFile?: RenameFile,
|
||||
): Promise<void> {
|
||||
await commitManagedInstallation(prepared, renameFile);
|
||||
|
||||
@@ -2,34 +2,26 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
AGENT_KEY,
|
||||
AUDIT_SCRIPT,
|
||||
CONFIG_FILE,
|
||||
GUARD_SCRIPT,
|
||||
type CopilotDocument,
|
||||
type CopilotSources,
|
||||
type RuntimeContract,
|
||||
createDocument,
|
||||
parseDocument,
|
||||
sameAgentId,
|
||||
samePath,
|
||||
} from './copilot-contract.js';
|
||||
import { generateGuardScript } from './guard-template.js';
|
||||
import { generateHookScript } from './hook-template.js';
|
||||
import { MAX_SOURCE_BYTES } from './common.js';
|
||||
import {
|
||||
inspectPhysicalDirectory,
|
||||
readPhysicalFile,
|
||||
type FileSnapshot,
|
||||
} from './managed-files.js';
|
||||
import { managedRuntimeFilesExist } from './managed-runtime-status.js';
|
||||
import {
|
||||
parseStrictJsonObject,
|
||||
parseStrictJsoncObject,
|
||||
type JsonObject,
|
||||
} from './strict-json.js';
|
||||
|
||||
const MAX_SECRET_BYTES = 64 * 1024;
|
||||
const MAX_CONFIG_BYTES = 512 * 1024;
|
||||
const MAX_SETTINGS_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
export interface CopilotPaths {
|
||||
readonly copilotHome: string;
|
||||
readonly userHooksDirectory: string;
|
||||
@@ -98,7 +90,7 @@ async function readHookDocument(
|
||||
filePath: string,
|
||||
label: string,
|
||||
): Promise<CopilotDocument | undefined> {
|
||||
const snapshot = await readPhysicalFile(filePath, label, MAX_SETTINGS_BYTES);
|
||||
const snapshot = await readPhysicalFile(filePath, label, MAX_SOURCE_BYTES);
|
||||
return snapshot ? parseDocument(filePath, snapshot, label) : undefined;
|
||||
}
|
||||
|
||||
@@ -111,7 +103,7 @@ function parseSettings(raw: string, layer: SettingsLayer): JsonObject {
|
||||
}
|
||||
|
||||
async function readSettingsLayer(layer: SettingsLayer): Promise<ParsedSettingsLayer> {
|
||||
const snapshot = await readPhysicalFile(layer.filePath, layer.label, MAX_SETTINGS_BYTES);
|
||||
const snapshot = await readPhysicalFile(layer.filePath, layer.label, MAX_SOURCE_BYTES);
|
||||
if (!snapshot) return layer;
|
||||
const root = parseSettings(snapshot.contents, layer);
|
||||
if (root.disableAllHooks !== undefined && typeof root.disableAllHooks !== 'boolean') {
|
||||
@@ -167,86 +159,9 @@ export function requireHooksEnabled(sources: CopilotSources): void {
|
||||
}
|
||||
}
|
||||
|
||||
function requireString(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: RuntimeContract,
|
||||
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}`);
|
||||
requireString(config.org_id, 'org_id', configPath);
|
||||
requireString(config.kid, 'kid', configPath);
|
||||
const agentId = requireString(config.agent_id, 'agent_id', configPath);
|
||||
if (!sameAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
|
||||
throw new Error(`Elydora runtime identity does not match Copilot hooks: ${configPath}`);
|
||||
}
|
||||
if (config.token !== undefined) requireString(config.token, 'token', configPath);
|
||||
const rawBaseUrl = requireString(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}`);
|
||||
}
|
||||
}
|
||||
|
||||
function validContractPaths(contract: RuntimeContract): boolean {
|
||||
const agentDirectory = path.dirname(contract.guardPath);
|
||||
return samePath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))
|
||||
&& samePath(contract.guardPath, path.join(agentDirectory, GUARD_SCRIPT))
|
||||
&& samePath(contract.auditPath, path.join(agentDirectory, AUDIT_SCRIPT));
|
||||
}
|
||||
|
||||
export async function runtimeFilesExist(contracts: RuntimeContract[]): Promise<boolean> {
|
||||
for (const contract of contracts) {
|
||||
if (!validContractPaths(contract)) continue;
|
||||
const runtimeRoot = path.join(os.homedir(), '.elydora');
|
||||
const agentDirectory = path.dirname(contract.guardPath);
|
||||
if (!await inspectPhysicalDirectory(runtimeRoot, 'Elydora runtime directory')) continue;
|
||||
if (!await inspectPhysicalDirectory(agentDirectory, 'Elydora agent runtime directory')) continue;
|
||||
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', MAX_CONFIG_BYTES),
|
||||
readPhysicalFile(keyPath, 'Elydora private key', MAX_SECRET_BYTES),
|
||||
readPhysicalFile(contract.guardPath, 'Elydora guard runtime'),
|
||||
readPhysicalFile(contract.auditPath, 'Elydora audit runtime'),
|
||||
]);
|
||||
if (!config || !key || !guard || !audit) continue;
|
||||
const parsed = parseStrictJsonObject(config.contents, `Elydora runtime config at ${configPath}`);
|
||||
validateRuntimeConfig(parsed, contract, configPath);
|
||||
validatePrivateKey(key.contents, keyPath);
|
||||
if (guard.contents === generateGuardScript(AGENT_KEY, contract.agentId)
|
||||
&& audit.contents === generateHookScript(
|
||||
AGENT_KEY,
|
||||
contract.agentId,
|
||||
{ nativePayload: true },
|
||||
)) return true;
|
||||
if (await managedRuntimeFilesExist(contract, AGENT_KEY)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -1,15 +1,32 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { sameAgentId, samePath } from './common.js';
|
||||
import type { GuardScriptOptions } from './guard-template.js';
|
||||
import type { HookScriptOptions } from './hook-template.js';
|
||||
import {
|
||||
isNodeExecutable,
|
||||
parsePosixCommand,
|
||||
parsePowerShellSource,
|
||||
posixSource,
|
||||
powerShellSource,
|
||||
} from './shell-command.js';
|
||||
import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
export { isObject, parseStrictJsonObject };
|
||||
export type { JsonObject };
|
||||
|
||||
export const AGENT_KEY = 'cursor';
|
||||
export const CONFIG_FILE = 'hooks.json';
|
||||
export const GUARD_SCRIPT = 'guard.js';
|
||||
export const AUDIT_SCRIPT = 'hook.js';
|
||||
export const HOOK_TIMEOUT_SECONDS = 10;
|
||||
export const GUARD_OPTIONS: GuardScriptOptions = {
|
||||
failClosed: true,
|
||||
successOutput: '{"permission":"allow"}\n',
|
||||
denyProtocol: 'cursor',
|
||||
};
|
||||
export const AUDIT_OPTIONS: HookScriptOptions = {
|
||||
failClosed: true,
|
||||
nativePayload: true,
|
||||
successOutput: '{}\n',
|
||||
};
|
||||
|
||||
export type CursorHooks = Record<string, JsonObject[]>;
|
||||
|
||||
@@ -33,37 +50,10 @@ export interface RuntimeContract {
|
||||
readonly auditPath: string;
|
||||
}
|
||||
|
||||
interface ParsedArgument {
|
||||
readonly value: string;
|
||||
readonly next: number;
|
||||
}
|
||||
|
||||
export function samePath(left: string, right: string): boolean {
|
||||
const normalizedLeft = path.resolve(left);
|
||||
const normalizedRight = path.resolve(right);
|
||||
return process.platform === 'win32'
|
||||
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
|
||||
: normalizedLeft === normalizedRight;
|
||||
}
|
||||
|
||||
function sameAgentId(left: string, right: string): boolean {
|
||||
return process.platform === 'win32'
|
||||
? left.toLowerCase() === right.toLowerCase()
|
||||
: left === right;
|
||||
}
|
||||
|
||||
function quotePosix(value: string): string {
|
||||
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
||||
}
|
||||
|
||||
function quotePowerShell(value: string): string {
|
||||
return `'${value.replaceAll("'", "''")}'`;
|
||||
}
|
||||
|
||||
export function buildHandler(scriptPath: string): JsonObject {
|
||||
const command = process.platform === 'win32'
|
||||
? `& ${quotePowerShell(process.execPath)} ${quotePowerShell(scriptPath)}; exit $LASTEXITCODE`
|
||||
: `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`;
|
||||
? powerShellSource(scriptPath)
|
||||
: posixSource(scriptPath);
|
||||
return {
|
||||
command,
|
||||
timeout: HOOK_TIMEOUT_SECONDS,
|
||||
@@ -71,68 +61,11 @@ export function buildHandler(scriptPath: string): JsonObject {
|
||||
};
|
||||
}
|
||||
|
||||
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 parseLegacyCommand(command: string): readonly [string, string] | undefined {
|
||||
const match = /^(node(?:\.exe)?)\s+"([^"\r\n]+)"$/i.exec(command);
|
||||
return match ? [match[1], match[2]] : undefined;
|
||||
}
|
||||
|
||||
function isNodeExecutable(filePath: string): boolean {
|
||||
const basename = path.basename(filePath);
|
||||
return basename === 'node' || basename.toLowerCase() === 'node.exe';
|
||||
}
|
||||
|
||||
function managedScriptPath(handler: JsonObject): string | undefined {
|
||||
const keys = Object.keys(handler);
|
||||
if (keys.length === 3
|
||||
@@ -140,7 +73,7 @@ function managedScriptPath(handler: JsonObject): string | undefined {
|
||||
&& handler.timeout === HOOK_TIMEOUT_SECONDS
|
||||
&& handler.failClosed === true) {
|
||||
const parsed = process.platform === 'win32'
|
||||
? parsePowerShellCommand(handler.command)
|
||||
? parsePowerShellSource(handler.command)
|
||||
: parsePosixCommand(handler.command);
|
||||
if (parsed
|
||||
&& path.isAbsolute(parsed[0])
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { InstallConfig } from './base.js';
|
||||
import {
|
||||
commitManagedInstallation,
|
||||
managedRuntimePaths,
|
||||
preflightManagedInstallation,
|
||||
prepareManagedInstallation,
|
||||
type ManagedRuntimePaths,
|
||||
@@ -10,7 +9,9 @@ import {
|
||||
} from './managed-installation.js';
|
||||
import {
|
||||
AGENT_KEY,
|
||||
AUDIT_OPTIONS,
|
||||
AUDIT_SCRIPT,
|
||||
GUARD_OPTIONS,
|
||||
GUARD_SCRIPT,
|
||||
type RenderedDocument,
|
||||
} from './cursor-contract.js';
|
||||
@@ -20,17 +21,9 @@ const DISPLAY_NAME = 'Cursor';
|
||||
const HOOKS_DIRECTORY_LABEL = 'Cursor hooks directory';
|
||||
const HOOKS_LABEL = 'Cursor user hooks';
|
||||
|
||||
export type CursorRuntimePaths = ManagedRuntimePaths;
|
||||
export type PreparedCursorInstallation = PreparedManagedInstallation;
|
||||
export type { RenameFile };
|
||||
|
||||
export function cursorRuntimePaths(config: InstallConfig): CursorRuntimePaths {
|
||||
return managedRuntimePaths(config, AGENT_KEY, GUARD_SCRIPT, AUDIT_SCRIPT);
|
||||
}
|
||||
|
||||
export async function preflightCursorInstallation(
|
||||
config: InstallConfig,
|
||||
): Promise<CursorRuntimePaths> {
|
||||
): Promise<ManagedRuntimePaths> {
|
||||
return preflightManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
hookLocations: [{
|
||||
@@ -44,7 +37,7 @@ export async function preflightCursorInstallation(
|
||||
export async function prepareCursorInstallation(
|
||||
config: InstallConfig,
|
||||
rendered: RenderedDocument,
|
||||
): Promise<PreparedCursorInstallation> {
|
||||
): Promise<PreparedManagedInstallation> {
|
||||
if (!rendered.changed && rendered.document.raw === undefined) {
|
||||
throw new Error('Cursor hook installation did not produce a configuration document');
|
||||
}
|
||||
@@ -61,21 +54,13 @@ export async function prepareCursorInstallation(
|
||||
source: hooksSource,
|
||||
}],
|
||||
config,
|
||||
guardOptions: {
|
||||
failClosed: true,
|
||||
successOutput: '{"permission":"allow"}\n',
|
||||
denyProtocol: 'cursor',
|
||||
},
|
||||
auditOptions: {
|
||||
failClosed: true,
|
||||
nativePayload: true,
|
||||
successOutput: '{}\n',
|
||||
},
|
||||
guardOptions: GUARD_OPTIONS,
|
||||
auditOptions: AUDIT_OPTIONS,
|
||||
}, GUARD_SCRIPT, AUDIT_SCRIPT);
|
||||
}
|
||||
|
||||
export async function commitCursorInstallation(
|
||||
prepared: PreparedCursorInstallation,
|
||||
prepared: PreparedManagedInstallation,
|
||||
renameFile?: RenameFile,
|
||||
): Promise<void> {
|
||||
await commitManagedInstallation(prepared, renameFile);
|
||||
|
||||
+27
-208
@@ -1,237 +1,56 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import fsp from 'node:fs/promises';
|
||||
import type { FileHandle } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
AGENT_KEY,
|
||||
CONFIG_FILE,
|
||||
type CursorDocument,
|
||||
type JsonObject,
|
||||
type RenderedDocument,
|
||||
type RuntimeContract,
|
||||
createDocument,
|
||||
isObject,
|
||||
parseDocument,
|
||||
parseStrictJsonObject,
|
||||
} from './cursor-contract.js';
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function asError(error: unknown): Error {
|
||||
return error instanceof Error ? error : new Error(String(error));
|
||||
}
|
||||
|
||||
function hasErrorCode(error: unknown, code: string): boolean {
|
||||
return isObject(error) && error.code === code;
|
||||
}
|
||||
import { readPhysicalFile } from './managed-files.js';
|
||||
import { managedRuntimePresent } from './managed-runtime-status.js';
|
||||
import {
|
||||
commitManagedTransaction,
|
||||
prepareManagedFileChange,
|
||||
} from './managed-transaction.js';
|
||||
|
||||
export function cursorConfigPath(): string {
|
||||
return path.join(os.homedir(), '.cursor', CONFIG_FILE);
|
||||
}
|
||||
|
||||
async function readOptionalPhysical(filePath: string, label: string): Promise<string | undefined> {
|
||||
let metadata;
|
||||
try {
|
||||
metadata = await fsp.lstat(filePath);
|
||||
} catch (error) {
|
||||
if (hasErrorCode(error, 'ENOENT') || hasErrorCode(error, 'ENOTDIR')) return undefined;
|
||||
throw new Error(`Inspect ${label} at ${filePath}: ${errorMessage(error)}`, {
|
||||
cause: asError(error),
|
||||
});
|
||||
}
|
||||
if (!metadata.isFile() || metadata.isSymbolicLink()) {
|
||||
throw new Error(`${label} path is not a physical file: ${filePath}`);
|
||||
}
|
||||
try {
|
||||
return await fsp.readFile(filePath, 'utf-8');
|
||||
} catch (error) {
|
||||
throw new Error(`Read ${label} at ${filePath}: ${errorMessage(error)}`, {
|
||||
cause: asError(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function readDocument(): Promise<CursorDocument> {
|
||||
const filePath = cursorConfigPath();
|
||||
const raw = await readOptionalPhysical(filePath, 'Cursor user hooks');
|
||||
return raw === undefined ? createDocument(filePath) : parseDocument(filePath, raw);
|
||||
}
|
||||
|
||||
async function ensurePhysicalDirectory(directory: string): Promise<void> {
|
||||
try {
|
||||
await fsp.mkdir(directory, { recursive: true, mode: 0o700 });
|
||||
} catch (error) {
|
||||
throw new Error(`Create Cursor hooks directory at ${directory}: ${errorMessage(error)}`, {
|
||||
cause: asError(error),
|
||||
});
|
||||
}
|
||||
let metadata;
|
||||
try {
|
||||
metadata = await fsp.lstat(directory);
|
||||
} catch (error) {
|
||||
throw new Error(`Inspect Cursor hooks directory at ${directory}: ${errorMessage(error)}`, {
|
||||
cause: asError(error),
|
||||
});
|
||||
}
|
||||
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
|
||||
throw new Error(`Cursor hooks directory is not a physical directory: ${directory}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function unlinkOptional(filePath: string): Promise<void> {
|
||||
try {
|
||||
await fsp.unlink(filePath);
|
||||
} catch (error) {
|
||||
if (!hasErrorCode(error, 'ENOENT')) throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function writeExclusive(filePath: string, contents: string): Promise<void> {
|
||||
let handle: FileHandle | undefined;
|
||||
try {
|
||||
handle = await fsp.open(filePath, 'wx', 0o600);
|
||||
await handle.writeFile(contents, 'utf-8');
|
||||
await handle.sync();
|
||||
await handle.close();
|
||||
handle = undefined;
|
||||
} catch (error) {
|
||||
const failures = [asError(error)];
|
||||
if (handle) {
|
||||
try {
|
||||
await handle.close();
|
||||
} catch (closeError) {
|
||||
failures.push(asError(closeError));
|
||||
}
|
||||
}
|
||||
try {
|
||||
await unlinkOptional(filePath);
|
||||
} catch (cleanupError) {
|
||||
failures.push(asError(cleanupError));
|
||||
}
|
||||
if (failures.length > 1) {
|
||||
throw new AggregateError(failures, 'Stage Cursor user hooks');
|
||||
}
|
||||
throw new Error(`Stage Cursor user hooks: ${errorMessage(error)}`, { cause: failures[0] });
|
||||
}
|
||||
}
|
||||
|
||||
async function assertUnchanged(document: CursorDocument): Promise<void> {
|
||||
const current = await readOptionalPhysical(document.filePath, 'Cursor user hooks');
|
||||
if (current !== document.raw) {
|
||||
throw new Error(`Cursor user hooks changed during update: ${document.filePath}`);
|
||||
}
|
||||
const snapshot = await readPhysicalFile(filePath, 'Cursor user hooks');
|
||||
return snapshot ? parseDocument(filePath, snapshot.contents) : createDocument(filePath);
|
||||
}
|
||||
|
||||
export async function writeDocument(rendered: RenderedDocument): Promise<void> {
|
||||
if (!rendered.changed) return;
|
||||
await assertUnchanged(rendered.document);
|
||||
if (rendered.next === undefined) {
|
||||
try {
|
||||
await fsp.unlink(rendered.document.filePath);
|
||||
} catch (error) {
|
||||
if (!hasErrorCode(error, 'ENOENT')) {
|
||||
throw new Error(
|
||||
`Remove Cursor user hooks at ${rendered.document.filePath}: ${errorMessage(error)}`,
|
||||
{ cause: asError(error) },
|
||||
);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const directory = path.dirname(rendered.document.filePath);
|
||||
await ensurePhysicalDirectory(directory);
|
||||
const temporaryPath = path.join(
|
||||
directory,
|
||||
`.${path.basename(rendered.document.filePath)}.${randomUUID()}.tmp`,
|
||||
);
|
||||
let committed = false;
|
||||
let failure: Error | undefined;
|
||||
try {
|
||||
await writeExclusive(temporaryPath, rendered.next);
|
||||
await assertUnchanged(rendered.document);
|
||||
await fsp.rename(temporaryPath, rendered.document.filePath);
|
||||
committed = true;
|
||||
} catch (error) {
|
||||
failure = new Error(
|
||||
`Write Cursor user hooks at ${rendered.document.filePath}: ${errorMessage(error)}`,
|
||||
{ cause: asError(error) },
|
||||
);
|
||||
}
|
||||
let cleanupFailure: Error | undefined;
|
||||
if (!committed) {
|
||||
try {
|
||||
await unlinkOptional(temporaryPath);
|
||||
} catch (error) {
|
||||
cleanupFailure = new Error(
|
||||
`Clean Cursor hook staging file at ${temporaryPath}: ${errorMessage(error)}`,
|
||||
{ cause: asError(error) },
|
||||
);
|
||||
}
|
||||
}
|
||||
if (failure && cleanupFailure) {
|
||||
throw new AggregateError([failure, cleanupFailure], 'Write Cursor user hooks');
|
||||
}
|
||||
if (failure) throw failure;
|
||||
if (cleanupFailure) throw cleanupFailure;
|
||||
}
|
||||
|
||||
export async function physicalFileExists(filePath: string, label: string): Promise<boolean> {
|
||||
let metadata;
|
||||
try {
|
||||
metadata = await fsp.lstat(filePath);
|
||||
} catch (error) {
|
||||
if (hasErrorCode(error, 'ENOENT') || hasErrorCode(error, 'ENOTDIR')) return false;
|
||||
throw new Error(`Inspect ${label} at ${filePath}: ${errorMessage(error)}`, {
|
||||
cause: asError(error),
|
||||
});
|
||||
}
|
||||
if (!metadata.isFile() || metadata.isSymbolicLink()) {
|
||||
throw new Error(`${label} path is not a physical file: ${filePath}`);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function requireRuntime(filePath: string, label: string): Promise<void> {
|
||||
if (!filePath) throw new Error(`${label} path is required`);
|
||||
if (!await physicalFileExists(filePath, label)) {
|
||||
throw new Error(`${label} is missing: ${filePath}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function readRuntimeConfig(filePath: string): Promise<JsonObject | undefined> {
|
||||
const raw = await readOptionalPhysical(filePath, 'Elydora runtime config');
|
||||
if (raw === undefined) return undefined;
|
||||
return parseStrictJsonObject(raw, `Elydora runtime config at ${filePath}`);
|
||||
}
|
||||
|
||||
function sameAgentId(left: unknown, right: string): boolean {
|
||||
if (typeof left !== 'string') return false;
|
||||
return process.platform === 'win32'
|
||||
? left.toLowerCase() === right.toLowerCase()
|
||||
: left === right;
|
||||
const change = await prepareManagedFileChange({
|
||||
filePath: rendered.document.filePath,
|
||||
label: 'Cursor user hooks',
|
||||
next: rendered.next,
|
||||
mode: 0o600,
|
||||
expectedSource: rendered.document.raw,
|
||||
verifyExpectedSource: true,
|
||||
});
|
||||
if (!change) return;
|
||||
await commitManagedTransaction({
|
||||
displayName: 'Cursor',
|
||||
operation: 'uninstall',
|
||||
directories: [{
|
||||
path: path.dirname(rendered.document.filePath),
|
||||
label: 'Cursor hooks directory',
|
||||
}],
|
||||
changes: [change],
|
||||
});
|
||||
}
|
||||
|
||||
export async function runtimeFilesExist(contracts: RuntimeContract[]): Promise<boolean> {
|
||||
for (const contract of contracts) {
|
||||
const runtimeConfig = await readRuntimeConfig(
|
||||
path.join(path.dirname(contract.guardPath), 'config.json'),
|
||||
);
|
||||
if (!runtimeConfig
|
||||
|| runtimeConfig.agent_name !== AGENT_KEY
|
||||
|| !sameAgentId(runtimeConfig.agent_id, contract.agentId)) continue;
|
||||
const files = await Promise.all([
|
||||
physicalFileExists(contract.guardPath, 'Elydora guard runtime'),
|
||||
physicalFileExists(contract.auditPath, 'Elydora audit runtime'),
|
||||
physicalFileExists(
|
||||
path.join(path.dirname(contract.guardPath), 'private.key'),
|
||||
'Elydora private key',
|
||||
),
|
||||
]);
|
||||
if (files.every(Boolean)) return true;
|
||||
if (await managedRuntimePresent(contract, AGENT_KEY)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -1,9 +1,5 @@
|
||||
import {
|
||||
applyEdits,
|
||||
modify,
|
||||
type FormattingOptions,
|
||||
type JSONPath,
|
||||
} from 'jsonc-parser';
|
||||
import type { JSONPath } from 'jsonc-parser';
|
||||
import { changeJsonc } from './jsonc-edit.js';
|
||||
import type { FileSnapshot } from './managed-files.js';
|
||||
import type { DroidPolicyState } from './droid-policy.js';
|
||||
import {
|
||||
@@ -158,23 +154,6 @@ function eventPath(document: DroidDocument, event: string): JSONPath {
|
||||
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 {
|
||||
return parseDocument({
|
||||
exists: document.exists,
|
||||
@@ -194,17 +173,17 @@ function removeManagedEntries(document: DroidDocument, raw: string, agentId?: st
|
||||
for (const removal of eventRemovals) {
|
||||
const groupPath = [...eventPath(document, event), removal.groupIndex];
|
||||
if (removal.removeGroup) {
|
||||
raw = change(raw, groupPath, undefined);
|
||||
raw = changeJsonc(raw, groupPath, undefined);
|
||||
continue;
|
||||
}
|
||||
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) {
|
||||
const current = currentDocument(document, raw);
|
||||
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);
|
||||
if (Object.prototype.hasOwnProperty.call(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 {
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { sameAgentId, samePath } from './common.js';
|
||||
import {
|
||||
parseLegacyWindowsCommand,
|
||||
parsePosixCommand,
|
||||
parsePowerShellSource,
|
||||
posixSource,
|
||||
powerShellSource,
|
||||
} from './shell-command.js';
|
||||
import type { JsonObject } from './strict-json.js';
|
||||
|
||||
export const AGENT_KEY = 'droid';
|
||||
@@ -10,7 +18,6 @@ export const TOOL_EVENTS = ['PreToolUse', 'PostToolUse'] as const;
|
||||
|
||||
const HANDLER_KEYS = ['command', 'timeout', 'type'];
|
||||
const GROUP_KEYS = ['hooks', 'matcher'];
|
||||
const WINDOWS_EXIT_SUFFIX = '; exit $LASTEXITCODE';
|
||||
|
||||
export type ToolEvent = typeof TOOL_EVENTS[number];
|
||||
|
||||
@@ -44,26 +51,13 @@ export interface ManagedRemoval {
|
||||
readonly removeGroup: boolean;
|
||||
}
|
||||
|
||||
interface ParsedArgument {
|
||||
readonly value: string;
|
||||
readonly next: number;
|
||||
}
|
||||
|
||||
function quotePosix(value: string): string {
|
||||
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
||||
}
|
||||
|
||||
function quotePowerShell(value: string): string {
|
||||
return `'${value.replaceAll("'", "''")}'`;
|
||||
}
|
||||
|
||||
export function buildCommand(scriptPath: string): string {
|
||||
if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) {
|
||||
throw new Error('Factory Droid hook commands require absolute executable and script paths');
|
||||
}
|
||||
return process.platform === 'win32'
|
||||
? `& ${quotePowerShell(process.execPath)} ${quotePowerShell(scriptPath)}${WINDOWS_EXIT_SUFFIX}`
|
||||
: `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`;
|
||||
? powerShellSource(scriptPath)
|
||||
: posixSource(scriptPath);
|
||||
}
|
||||
|
||||
export function buildGroup(scriptPath: string): DroidGroup {
|
||||
@@ -150,90 +144,13 @@ export function readHookMap(value: unknown, label: string): DroidHookMap {
|
||||
return hooks;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
const POSIX_APOSTROPHE = `'"'"'`;
|
||||
|
||||
function readPosixArgument(command: string, start: number): ParsedArgument | undefined {
|
||||
if (command[start] !== "'") return undefined;
|
||||
let value = '';
|
||||
for (let index = start + 1; index < command.length;) {
|
||||
if (command.startsWith(POSIX_APOSTROPHE, index)) {
|
||||
value += "'";
|
||||
index += POSIX_APOSTROPHE.length;
|
||||
continue;
|
||||
}
|
||||
if (command[index] === "'") return { value, next: index + 1 };
|
||||
value += command[index];
|
||||
index += 1;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function parseTwoArguments(
|
||||
command: string,
|
||||
start: number,
|
||||
readArgument: (command: string, start: number) => ParsedArgument | undefined,
|
||||
): readonly [string, string] | undefined {
|
||||
const executable = readArgument(command, start);
|
||||
if (!executable || command[executable.next] !== ' ') return undefined;
|
||||
const script = readArgument(command, executable.next + 1);
|
||||
if (!script || script.next !== command.length || !executable.value || !script.value) return undefined;
|
||||
return [executable.value, script.value];
|
||||
}
|
||||
|
||||
function parseLegacyWindowsCommand(command: string): readonly [string, string] | undefined {
|
||||
const match = /^"([^"\r\n]+)" "([^"\r\n]+)"$/.exec(command);
|
||||
return match ? [match[1], match[2]] : 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) !== WINDOWS_EXIT_SUFFIX
|
||||
|| !executable.value
|
||||
|| !script.value) return undefined;
|
||||
return [executable.value, script.value];
|
||||
}
|
||||
|
||||
function parseGeneratedCommand(
|
||||
command: string,
|
||||
includeLegacy: boolean,
|
||||
): readonly [string, string] | undefined {
|
||||
if (process.platform !== 'win32') return parseTwoArguments(command, 0, readPosixArgument);
|
||||
const current = parsePowerShellCommand(command);
|
||||
return current ?? (includeLegacy ? parseLegacyWindowsCommand(command) : undefined);
|
||||
}
|
||||
|
||||
export function samePath(left: string, right: string): boolean {
|
||||
const normalizedLeft = path.resolve(left);
|
||||
const normalizedRight = path.resolve(right);
|
||||
return process.platform === 'win32'
|
||||
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
|
||||
: normalizedLeft === normalizedRight;
|
||||
}
|
||||
|
||||
export function sameAgentId(left: string, right: string): boolean {
|
||||
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
|
||||
if (process.platform !== 'win32') return parsePosixCommand(command);
|
||||
return parsePowerShellSource(command)
|
||||
?? (includeLegacy ? parseLegacyWindowsCommand(command) : undefined);
|
||||
}
|
||||
|
||||
export function managedAgentId(
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import path from 'node:path';
|
||||
import type { InstallConfig } from './base.js';
|
||||
import {
|
||||
AGENT_KEY,
|
||||
AUDIT_SCRIPT,
|
||||
GUARD_SCRIPT,
|
||||
samePath,
|
||||
} from './droid-contract.js';
|
||||
import { MAX_SOURCE_BYTES, samePath } from './common.js';
|
||||
import { AGENT_KEY, AUDIT_SCRIPT, GUARD_SCRIPT } from './droid-contract.js';
|
||||
import {
|
||||
activeDocument,
|
||||
installationDocuments,
|
||||
@@ -31,11 +27,6 @@ import {
|
||||
|
||||
const DISPLAY_NAME = 'Factory Droid';
|
||||
const DIRECTORY_LABEL = 'Factory Droid user configuration directory';
|
||||
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
export type DroidRuntimePaths = ManagedRuntimePaths;
|
||||
export type PreparedDroidInstallation = PreparedManagedInstallation;
|
||||
export type { RenameFile };
|
||||
|
||||
function sourceLabel(document: DroidDocument): string {
|
||||
if (document.kind === 'settings') return 'Factory Droid user settings';
|
||||
@@ -56,7 +47,7 @@ function hookLocations(sources: DroidSources) {
|
||||
export async function preflightDroidInstallation(
|
||||
config: InstallConfig,
|
||||
sources: DroidSources,
|
||||
): Promise<DroidRuntimePaths> {
|
||||
): Promise<ManagedRuntimePaths> {
|
||||
requireHooksEnabled(sources);
|
||||
return preflightManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
@@ -92,7 +83,7 @@ export async function prepareDroidInstallation(
|
||||
config: InstallConfig,
|
||||
sources: DroidSources,
|
||||
rendered: readonly RenderedDocument[],
|
||||
): Promise<PreparedDroidInstallation> {
|
||||
): Promise<PreparedManagedInstallation> {
|
||||
await preflightDroidInstallation(config, sources);
|
||||
const changed = installationChanges(sources, rendered);
|
||||
const prepared = await prepareManagedInstallation({
|
||||
@@ -124,7 +115,7 @@ export async function prepareDroidInstallation(
|
||||
}
|
||||
|
||||
export async function commitDroidInstallation(
|
||||
prepared: PreparedDroidInstallation,
|
||||
prepared: PreparedManagedInstallation,
|
||||
renameFile?: RenameFile,
|
||||
): Promise<void> {
|
||||
await commitManagedInstallation(prepared, renameFile);
|
||||
|
||||
+4
-93
@@ -1,13 +1,7 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
AGENT_KEY,
|
||||
AUDIT_SCRIPT,
|
||||
GUARD_SCRIPT,
|
||||
type RuntimeContract,
|
||||
sameAgentId,
|
||||
samePath,
|
||||
} from './droid-contract.js';
|
||||
import { MAX_SOURCE_BYTES } from './common.js';
|
||||
import { AGENT_KEY, type RuntimeContract } from './droid-contract.js';
|
||||
import {
|
||||
activeDocument,
|
||||
createLegacyHookDocument,
|
||||
@@ -19,15 +13,9 @@ import {
|
||||
type DroidDocumentKind,
|
||||
type DroidSources,
|
||||
} from './droid-config.js';
|
||||
import { generateGuardScript } from './guard-template.js';
|
||||
import { generateHookScript } from './hook-template.js';
|
||||
import { readDroidPolicy } from './droid-policy.js';
|
||||
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
|
||||
import { parseStrictJsonObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
const MAX_SECRET_BYTES = 64 * 1024;
|
||||
const MAX_CONFIG_BYTES = 512 * 1024;
|
||||
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
|
||||
import { managedRuntimeFilesExist } from './managed-runtime-status.js';
|
||||
|
||||
interface FactoryPaths {
|
||||
readonly directory: string;
|
||||
@@ -96,86 +84,9 @@ export function requireHooksEnabled(sources: DroidSources): void {
|
||||
}
|
||||
}
|
||||
|
||||
function requireString(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: RuntimeContract,
|
||||
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}`);
|
||||
requireString(config.org_id, 'org_id', configPath);
|
||||
requireString(config.kid, 'kid', configPath);
|
||||
const agentId = requireString(config.agent_id, 'agent_id', configPath);
|
||||
if (!sameAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
|
||||
throw new Error(`Elydora runtime identity does not match Factory Droid hooks: ${configPath}`);
|
||||
}
|
||||
if (config.token !== undefined) requireString(config.token, 'token', configPath);
|
||||
const rawBaseUrl = requireString(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}`);
|
||||
}
|
||||
}
|
||||
|
||||
function validContractPaths(contract: RuntimeContract): boolean {
|
||||
const agentDirectory = path.dirname(contract.guardPath);
|
||||
return samePath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))
|
||||
&& samePath(contract.guardPath, path.join(agentDirectory, GUARD_SCRIPT))
|
||||
&& samePath(contract.auditPath, path.join(agentDirectory, AUDIT_SCRIPT));
|
||||
}
|
||||
|
||||
export async function runtimeFilesExist(contracts: RuntimeContract[]): Promise<boolean> {
|
||||
for (const contract of contracts) {
|
||||
if (!validContractPaths(contract)) continue;
|
||||
const runtimeRoot = path.join(os.homedir(), '.elydora');
|
||||
const agentDirectory = path.dirname(contract.guardPath);
|
||||
if (!await inspectPhysicalDirectory(runtimeRoot, 'Elydora runtime directory')) continue;
|
||||
if (!await inspectPhysicalDirectory(agentDirectory, 'Elydora agent runtime directory')) continue;
|
||||
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', MAX_CONFIG_BYTES),
|
||||
readPhysicalFile(keyPath, 'Elydora private key', MAX_SECRET_BYTES),
|
||||
readPhysicalFile(contract.guardPath, 'Elydora guard runtime'),
|
||||
readPhysicalFile(contract.auditPath, 'Elydora audit runtime'),
|
||||
]);
|
||||
if (!config || !key || !guard || !audit) continue;
|
||||
const parsed = parseStrictJsonObject(config.contents, `Elydora runtime config at ${configPath}`);
|
||||
validateRuntimeConfig(parsed, contract, configPath);
|
||||
validatePrivateKey(key.contents, keyPath);
|
||||
if (guard.contents === generateGuardScript(AGENT_KEY, contract.agentId)
|
||||
&& audit.contents === generateHookScript(
|
||||
AGENT_KEY,
|
||||
contract.agentId,
|
||||
{ nativePayload: true },
|
||||
)) return true;
|
||||
if (await managedRuntimeFilesExist(contract, AGENT_KEY)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import fsp from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { hasCode, MAX_SOURCE_BYTES } from './common.js';
|
||||
import { inspectPhysicalDirectory, readPhysicalFile, type FileSnapshot } from './managed-files.js';
|
||||
import { parseStrictJsoncObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
interface PolicyLocation {
|
||||
readonly filePath: string;
|
||||
readonly label: string;
|
||||
@@ -37,10 +36,6 @@ export interface DroidPolicyState {
|
||||
readonly preconditions: readonly DroidPolicyPrecondition[];
|
||||
}
|
||||
|
||||
function hasCode(error: unknown, code: string): boolean {
|
||||
return typeof error === 'object' && error !== null && 'code' in error && error.code === code;
|
||||
}
|
||||
|
||||
function optionalBoolean(root: JsonObject, field: string, label: string): boolean | undefined {
|
||||
const value = root[field];
|
||||
if (value !== undefined && typeof value !== 'boolean') {
|
||||
|
||||
+20
-117
@@ -1,58 +1,25 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
interface ParsedArgument {
|
||||
readonly value: string;
|
||||
readonly next: number;
|
||||
}
|
||||
import { samePath } from './common.js';
|
||||
import {
|
||||
decodePowerShellSource,
|
||||
encodePowerShellSource,
|
||||
isNodeExecutable,
|
||||
isPowerShellExecutable,
|
||||
parsePosixCommand,
|
||||
parsePowerShellSource,
|
||||
posixSource,
|
||||
quotePowerShell,
|
||||
windowsPowerShellPath,
|
||||
} from './shell-command.js';
|
||||
|
||||
export interface GeminiRuntimeReference {
|
||||
readonly agentId: string;
|
||||
readonly scriptPath: string;
|
||||
}
|
||||
|
||||
export function sameGeminiPath(left: string, right: string): boolean {
|
||||
const normalizedLeft = path.resolve(left);
|
||||
const normalizedRight = path.resolve(right);
|
||||
return process.platform === 'win32'
|
||||
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
|
||||
: normalizedLeft === normalizedRight;
|
||||
}
|
||||
|
||||
export function sameGeminiAgentId(left: string, right: string): boolean {
|
||||
return process.platform === 'win32'
|
||||
? left.toLowerCase() === right.toLowerCase()
|
||||
: left === right;
|
||||
}
|
||||
|
||||
function quotePosix(value: string): string {
|
||||
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
||||
}
|
||||
|
||||
function quotePowerShell(value: string): string {
|
||||
return `'${value.replaceAll("'", "''")}'`;
|
||||
}
|
||||
|
||||
function windowsPowerShellPath(): string {
|
||||
const configuredRoot = process.env.SystemRoot;
|
||||
const systemRoot = configuredRoot
|
||||
&& path.win32.isAbsolute(configuredRoot)
|
||||
&& !/["%\r\n]/.test(configuredRoot)
|
||||
? configuredRoot
|
||||
: 'C:\\Windows';
|
||||
return path.win32.join(
|
||||
systemRoot,
|
||||
'System32',
|
||||
'WindowsPowerShell',
|
||||
'v1.0',
|
||||
'powershell.exe',
|
||||
);
|
||||
}
|
||||
|
||||
function windowsCommand(scriptPath: string): string {
|
||||
const source = `& ${quotePowerShell(process.execPath)} ${quotePowerShell(scriptPath)}; exit $LASTEXITCODE`;
|
||||
const encoded = Buffer.from(source, 'utf16le').toString('base64');
|
||||
return `& ${quotePowerShell(windowsPowerShellPath())} -NoLogo -NoProfile -NonInteractive -EncodedCommand ${encoded}`;
|
||||
return `& ${quotePowerShell(windowsPowerShellPath())} -NoLogo -NoProfile -NonInteractive -EncodedCommand ${encodePowerShellSource(scriptPath)}`;
|
||||
}
|
||||
|
||||
export function buildGeminiCommand(scriptPath: string): string {
|
||||
@@ -61,74 +28,15 @@ export function buildGeminiCommand(scriptPath: string): string {
|
||||
}
|
||||
return process.platform === 'win32'
|
||||
? windowsCommand(scriptPath)
|
||||
: `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`;
|
||||
}
|
||||
|
||||
function readPosixArgument(command: string, start: number): ParsedArgument | undefined {
|
||||
if (command[start] !== "'") return undefined;
|
||||
const apostrophe = `'"'"'`;
|
||||
let value = '';
|
||||
for (let index = start + 1; index < command.length;) {
|
||||
if (command.startsWith(apostrophe, index)) {
|
||||
value += "'";
|
||||
index += apostrophe.length;
|
||||
continue;
|
||||
}
|
||||
if (command[index] === "'") return { value, next: index + 1 };
|
||||
value += command[index];
|
||||
index += 1;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function parsePosixCommand(command: string): readonly [string, string] | undefined {
|
||||
const executable = readPosixArgument(command, 0);
|
||||
if (!executable || command[executable.next] !== ' ') return undefined;
|
||||
const script = readPosixArgument(command, executable.next + 1);
|
||||
if (!script || script.next !== command.length) return undefined;
|
||||
return [executable.value, script.value];
|
||||
}
|
||||
|
||||
function readPowerShellArgument(command: string, start: number): ParsedArgument | undefined {
|
||||
if (command[start] !== "'") return undefined;
|
||||
let value = '';
|
||||
for (let index = start + 1; index < command.length; index += 1) {
|
||||
if (command[index] !== "'") {
|
||||
value += command[index];
|
||||
continue;
|
||||
}
|
||||
if (command[index + 1] === "'") {
|
||||
value += "'";
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
return { value, next: index + 1 };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function parsePowerShellSource(source: string): readonly [string, string] | undefined {
|
||||
if (!source.startsWith('& ')) return undefined;
|
||||
const executable = readPowerShellArgument(source, 2);
|
||||
if (!executable || source[executable.next] !== ' ') return undefined;
|
||||
const script = readPowerShellArgument(source, executable.next + 1);
|
||||
if (!script || source.slice(script.next) !== '; exit $LASTEXITCODE') return undefined;
|
||||
return [executable.value, script.value];
|
||||
: posixSource(scriptPath);
|
||||
}
|
||||
|
||||
function parseWindowsCommand(command: string): readonly [string, string] | undefined {
|
||||
if (!command.startsWith('& ')) return undefined;
|
||||
const powershell = readPowerShellArgument(command, 2);
|
||||
if (!powershell
|
||||
|| !path.win32.isAbsolute(powershell.value)
|
||||
|| path.win32.basename(powershell.value).toLowerCase() !== 'powershell.exe') return undefined;
|
||||
const prefix = ' -NoLogo -NoProfile -NonInteractive -EncodedCommand ';
|
||||
if (!command.startsWith(prefix, powershell.next)) return undefined;
|
||||
const encoded = command.slice(powershell.next + prefix.length);
|
||||
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) return undefined;
|
||||
const buffer = Buffer.from(encoded, 'base64');
|
||||
if (buffer.length % 2 !== 0 || buffer.toString('base64') !== encoded) return undefined;
|
||||
return parsePowerShellSource(buffer.toString('utf16le'));
|
||||
const match = /^& ('(?:[^']|'')+') -NoLogo -NoProfile -NonInteractive -EncodedCommand ([A-Za-z0-9+/]+={0,2})$/.exec(command);
|
||||
if (!match) return undefined;
|
||||
const powershell = parsePowerShellSource(`& ${match[1]} ''; exit $LASTEXITCODE`);
|
||||
if (!powershell || !isPowerShellExecutable(powershell[0])) return undefined;
|
||||
return decodePowerShellSource(match[2]);
|
||||
}
|
||||
|
||||
function parseLegacyCommand(command: string): readonly [string, string] | undefined {
|
||||
@@ -136,11 +44,6 @@ function parseLegacyCommand(command: string): readonly [string, string] | undefi
|
||||
return match ? ['node', match[1]] : undefined;
|
||||
}
|
||||
|
||||
function isNodeExecutable(filePath: string): boolean {
|
||||
const basename = path.basename(filePath).toLowerCase();
|
||||
return basename === 'node' || basename === 'node.exe';
|
||||
}
|
||||
|
||||
export function geminiRuntimeReference(
|
||||
command: string,
|
||||
scriptName: string,
|
||||
@@ -155,7 +58,7 @@ export function geminiRuntimeReference(
|
||||
|| path.basename(parsed[1]) !== scriptName) return undefined;
|
||||
if (parsed[0] !== 'node' && !path.isAbsolute(parsed[0])) return undefined;
|
||||
const agentDirectory = path.dirname(parsed[1]);
|
||||
if (!sameGeminiPath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))) {
|
||||
if (!samePath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))) {
|
||||
return undefined;
|
||||
}
|
||||
const agentId = path.basename(agentDirectory);
|
||||
|
||||
@@ -1,14 +1,4 @@
|
||||
import {
|
||||
applyEdits,
|
||||
modify,
|
||||
parse,
|
||||
parseTree,
|
||||
printParseErrorCode,
|
||||
type FormattingOptions,
|
||||
type JSONPath,
|
||||
type Node,
|
||||
type ParseError,
|
||||
} from 'jsonc-parser';
|
||||
import type { JSONPath } from 'jsonc-parser';
|
||||
import {
|
||||
MANAGED_EVENTS,
|
||||
managedGeminiRemovals,
|
||||
@@ -19,7 +9,8 @@ import {
|
||||
type GeminiHooks,
|
||||
type ManagedGeminiEvent,
|
||||
} 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';
|
||||
|
||||
@@ -46,53 +37,9 @@ interface DocumentOptions {
|
||||
readonly raw: string;
|
||||
}
|
||||
|
||||
function rejectDuplicateKeys(
|
||||
node: Node | undefined,
|
||||
label: string,
|
||||
location: string[] = [],
|
||||
): void {
|
||||
if (!node) return;
|
||||
if (node.type === 'object') {
|
||||
const keys = new Set<string>();
|
||||
for (const property of node.children ?? []) {
|
||||
const key = String(property.children?.[0]?.value);
|
||||
const childLocation = [...location, key];
|
||||
if (keys.has(key)) {
|
||||
throw new Error(`${label} contains duplicate field "${childLocation.join('.')}"`);
|
||||
}
|
||||
keys.add(key);
|
||||
rejectDuplicateKeys(property.children?.[1], label, childLocation);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (node.type === 'array') {
|
||||
for (const child of node.children ?? []) rejectDuplicateKeys(child, label, location);
|
||||
}
|
||||
}
|
||||
|
||||
function parseJsoncObject(raw: string, label: string): JsonObject {
|
||||
const errors: ParseError[] = [];
|
||||
const value: unknown = parse(raw, errors, {
|
||||
allowTrailingComma: false,
|
||||
disallowComments: false,
|
||||
});
|
||||
if (errors.length > 0) {
|
||||
const details = errors
|
||||
.map((error) => `${printParseErrorCode(error.error)} at offset ${error.offset}`)
|
||||
.join(', ');
|
||||
throw new Error(`Failed to parse ${label}: ${details}`);
|
||||
}
|
||||
if (!isObject(value)) throw new Error(`${label} must contain a JSON object`);
|
||||
rejectDuplicateKeys(parseTree(raw, [], {
|
||||
allowTrailingComma: false,
|
||||
disallowComments: false,
|
||||
}), label);
|
||||
return value;
|
||||
}
|
||||
|
||||
export function parseGeminiDocument(options: DocumentOptions): GeminiDocument {
|
||||
const label = `Gemini CLI user settings at ${options.filePath}`;
|
||||
const root = parseJsoncObject(options.raw, label);
|
||||
const root = parseCommentedJsonObject(options.raw, label);
|
||||
const hasHooksContainer = Object.hasOwn(root, 'hooks');
|
||||
return {
|
||||
...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 {
|
||||
return parseGeminiDocument({
|
||||
exists: document.exists,
|
||||
@@ -155,25 +80,25 @@ function removeManagedEntries(
|
||||
for (const removal of eventRemovals) {
|
||||
const groupPath: JSONPath = ['hooks', event, removal.groupIndex];
|
||||
if (removal.removeGroup) {
|
||||
raw = change(raw, groupPath, undefined);
|
||||
raw = changeJsonc(raw, groupPath, undefined);
|
||||
continue;
|
||||
}
|
||||
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) {
|
||||
const current = currentDocument(document, raw);
|
||||
if ((current.hooks[event] ?? []).length === 0) {
|
||||
raw = change(raw, ['hooks', event], undefined);
|
||||
raw = changeJsonc(raw, ['hooks', event], undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
const current = currentDocument(document, raw);
|
||||
if (current.hasHooksContainer && Object.keys(current.hooks).length === 0) {
|
||||
raw = change(raw, ['hooks'], undefined);
|
||||
raw = changeJsonc(raw, ['hooks'], undefined);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
@@ -186,9 +111,9 @@ function appendGroup(
|
||||
): string {
|
||||
const current = currentDocument(document, raw);
|
||||
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(
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { sameAgentId } from './common.js';
|
||||
import {
|
||||
buildGeminiCommand,
|
||||
geminiRuntimeReference,
|
||||
sameGeminiAgentId,
|
||||
type GeminiRuntimeReference,
|
||||
} from './gemini-command.js';
|
||||
import type { GuardScriptOptions } from './guard-template.js';
|
||||
import type { HookScriptOptions } from './hook-template.js';
|
||||
import { isObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
export const AGENT_KEY = 'gemini';
|
||||
@@ -14,6 +16,8 @@ export const GUARD_HOOK_NAME = 'elydora-guard';
|
||||
export const AUDIT_HOOK_NAME = 'elydora-audit';
|
||||
export const HOOK_TIMEOUT_MS = 10_000;
|
||||
export const MANAGED_EVENTS = ['BeforeTool', 'AfterTool'] as const;
|
||||
export const GUARD_OPTIONS: GuardScriptOptions = { successOutput: '{}\n' };
|
||||
export const AUDIT_OPTIONS: HookScriptOptions = { nativePayload: true, successOutput: '{}\n' };
|
||||
|
||||
const KNOWN_EVENTS = new Set([
|
||||
'BeforeTool',
|
||||
@@ -248,7 +252,7 @@ export function managedGeminiRemovals(
|
||||
const handlerIndexes = group.hooks.flatMap((handler, handlerIndex) => {
|
||||
const reference = managedReference(handler, scriptName, hookName, true);
|
||||
return reference
|
||||
&& (agentId === undefined || sameGeminiAgentId(reference.agentId, agentId))
|
||||
&& (agentId === undefined || sameAgentId(reference.agentId, agentId))
|
||||
? [handlerIndex]
|
||||
: [];
|
||||
});
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { InstallConfig } from './base.js';
|
||||
import {
|
||||
AGENT_KEY,
|
||||
AUDIT_OPTIONS,
|
||||
AUDIT_SCRIPT,
|
||||
GUARD_OPTIONS,
|
||||
GUARD_SCRIPT,
|
||||
} from './gemini-contract.js';
|
||||
import type { RenderedGeminiDocument } from './gemini-config.js';
|
||||
@@ -18,14 +20,10 @@ const DISPLAY_NAME = 'Gemini CLI';
|
||||
const SETTINGS_DIRECTORY_LABEL = 'Gemini CLI configuration directory';
|
||||
const SETTINGS_LABEL = 'Gemini CLI user settings';
|
||||
|
||||
export type GeminiRuntimePaths = ManagedRuntimePaths;
|
||||
export type PreparedGeminiInstallation = PreparedManagedInstallation;
|
||||
export type { RenameFile };
|
||||
|
||||
export async function preflightGeminiInstallation(
|
||||
config: InstallConfig,
|
||||
settingsPath: string,
|
||||
): Promise<GeminiRuntimePaths> {
|
||||
): Promise<ManagedRuntimePaths> {
|
||||
return preflightManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
hookLocations: [{ directoryLabel: SETTINGS_DIRECTORY_LABEL, filePath: settingsPath }],
|
||||
@@ -36,7 +34,7 @@ export async function preflightGeminiInstallation(
|
||||
export async function prepareGeminiInstallation(
|
||||
config: InstallConfig,
|
||||
rendered: RenderedGeminiDocument,
|
||||
): Promise<PreparedGeminiInstallation> {
|
||||
): Promise<PreparedManagedInstallation> {
|
||||
const settingsSource = rendered.next ?? rendered.document.raw;
|
||||
if (settingsSource === undefined) throw new Error('Gemini CLI hook settings are missing');
|
||||
return prepareManagedInstallation({
|
||||
@@ -50,13 +48,13 @@ export async function prepareGeminiInstallation(
|
||||
source: settingsSource,
|
||||
}],
|
||||
config,
|
||||
guardOptions: { successOutput: '{}\n' },
|
||||
auditOptions: { nativePayload: true, successOutput: '{}\n' },
|
||||
guardOptions: GUARD_OPTIONS,
|
||||
auditOptions: AUDIT_OPTIONS,
|
||||
}, GUARD_SCRIPT, AUDIT_SCRIPT);
|
||||
}
|
||||
|
||||
export async function commitGeminiInstallation(
|
||||
prepared: PreparedGeminiInstallation,
|
||||
prepared: PreparedManagedInstallation,
|
||||
renameFile?: RenameFile,
|
||||
): Promise<void> {
|
||||
await commitManagedInstallation(prepared, renameFile);
|
||||
|
||||
@@ -2,7 +2,9 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
AGENT_KEY,
|
||||
AUDIT_OPTIONS,
|
||||
CONFIG_FILE,
|
||||
GUARD_OPTIONS,
|
||||
type GeminiRuntimeContract,
|
||||
} from './gemini-contract.js';
|
||||
import {
|
||||
@@ -11,13 +13,12 @@ import {
|
||||
type GeminiDocument,
|
||||
type RenderedGeminiDocument,
|
||||
} from './gemini-config.js';
|
||||
import { sameGeminiAgentId, sameGeminiPath } from './gemini-command.js';
|
||||
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
|
||||
import { managedRuntimeFilesExist } from './managed-runtime-status.js';
|
||||
import {
|
||||
commitManagedTransaction,
|
||||
prepareManagedFileChange,
|
||||
} from './managed-transaction.js';
|
||||
import { parseStrictJsonObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
export function geminiConfigurationDirectory(): string {
|
||||
const configuredHome = process.env.GEMINI_CLI_HOME;
|
||||
@@ -64,86 +65,15 @@ export async function writeGeminiDocument(rendered: RenderedGeminiDocument): Pro
|
||||
});
|
||||
}
|
||||
|
||||
function requireNonEmptyString(value: unknown, field: string, configPath: string): string {
|
||||
if (typeof value !== 'string' || value.trim().length === 0) {
|
||||
throw new Error(`Elydora runtime config ${field} is invalid: ${configPath}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function validateRuntimeConfig(
|
||||
config: JsonObject,
|
||||
contract: GeminiRuntimeContract,
|
||||
configPath: string,
|
||||
): void {
|
||||
const supported = new Set(['org_id', 'agent_id', 'kid', 'base_url', 'token', 'agent_name']);
|
||||
const extra = Object.keys(config).find((key) => !supported.has(key));
|
||||
if (extra) {
|
||||
throw new Error(`Elydora runtime config has unsupported field "${extra}": ${configPath}`);
|
||||
}
|
||||
requireNonEmptyString(config.org_id, 'org_id', configPath);
|
||||
requireNonEmptyString(config.kid, 'kid', configPath);
|
||||
const agentId = requireNonEmptyString(config.agent_id, 'agent_id', configPath);
|
||||
if (!sameGeminiAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
|
||||
throw new Error(`Elydora runtime identity does not match Gemini CLI hooks: ${configPath}`);
|
||||
}
|
||||
if (config.token !== undefined) requireNonEmptyString(config.token, 'token', configPath);
|
||||
const rawBaseUrl = requireNonEmptyString(config.base_url, 'base_url', configPath);
|
||||
let baseUrl: URL;
|
||||
try {
|
||||
baseUrl = new URL(rawBaseUrl);
|
||||
} catch (error) {
|
||||
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`, {
|
||||
cause: error instanceof Error ? error : new Error(String(error)),
|
||||
});
|
||||
}
|
||||
if (!['http:', 'https:'].includes(baseUrl.protocol)
|
||||
|| !baseUrl.hostname
|
||||
|| baseUrl.username
|
||||
|| baseUrl.password
|
||||
|| baseUrl.search
|
||||
|| baseUrl.hash) {
|
||||
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`);
|
||||
}
|
||||
}
|
||||
|
||||
function validatePrivateKey(contents: string, keyPath: string): void {
|
||||
const bytes = Buffer.from(contents, 'base64url');
|
||||
if (bytes.length !== 32 || bytes.toString('base64url') !== contents) {
|
||||
throw new Error(`Elydora private key is invalid: ${keyPath}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function runtimeContractExists(contract: GeminiRuntimeContract): Promise<boolean> {
|
||||
const runtimeRoot = path.join(os.homedir(), '.elydora');
|
||||
const agentDirectory = path.dirname(contract.guardPath);
|
||||
if (!sameGeminiPath(path.dirname(agentDirectory), runtimeRoot)
|
||||
|| !sameGeminiPath(contract.auditPath, path.join(agentDirectory, 'hook.js'))) return false;
|
||||
if (!await inspectPhysicalDirectory(runtimeRoot, 'Elydora runtime directory')) return false;
|
||||
if (!await inspectPhysicalDirectory(agentDirectory, 'Elydora agent runtime directory')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const configPath = path.join(agentDirectory, 'config.json');
|
||||
const keyPath = path.join(agentDirectory, 'private.key');
|
||||
const [config, key, guard, audit] = await Promise.all([
|
||||
readPhysicalFile(configPath, 'Elydora runtime config'),
|
||||
readPhysicalFile(keyPath, 'Elydora private key'),
|
||||
readPhysicalFile(contract.guardPath, 'Elydora guard runtime'),
|
||||
readPhysicalFile(contract.auditPath, 'Elydora audit runtime'),
|
||||
]);
|
||||
if (!config || !key || !guard || !audit) return false;
|
||||
const parsed = parseStrictJsonObject(config.contents, `Elydora runtime config at ${configPath}`);
|
||||
validateRuntimeConfig(parsed, contract, configPath);
|
||||
validatePrivateKey(key.contents, keyPath);
|
||||
return guard.contents.length > 0 && audit.contents.length > 0;
|
||||
}
|
||||
|
||||
export async function geminiRuntimeFilesExist(
|
||||
contracts: readonly GeminiRuntimeContract[],
|
||||
): Promise<boolean> {
|
||||
for (const contract of contracts) {
|
||||
if (await runtimeContractExists(contract)) return true;
|
||||
const exists = await managedRuntimeFilesExist(contract, AGENT_KEY, {
|
||||
guardOptions: GUARD_OPTIONS,
|
||||
auditOptions: AUDIT_OPTIONS,
|
||||
});
|
||||
if (exists) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
+14
-143
@@ -1,140 +1,21 @@
|
||||
import os from 'node:os';
|
||||
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 {
|
||||
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 type GrokRuntimeReference = ManagedScriptReference;
|
||||
|
||||
export function buildGrokCommand(scriptPath: string): string {
|
||||
if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) {
|
||||
throw new Error('Grok hook commands require absolute executable and script paths');
|
||||
}
|
||||
return process.platform === 'win32'
|
||||
? windowsCommand(scriptPath)
|
||||
: `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`;
|
||||
}
|
||||
|
||||
function readPosixArgument(command: string, start: number): ParsedArgument | undefined {
|
||||
if (command[start] !== "'") return undefined;
|
||||
const apostrophe = `'"'"'`;
|
||||
let value = '';
|
||||
for (let index = start + 1; index < command.length;) {
|
||||
if (command.startsWith(apostrophe, index)) {
|
||||
value += "'";
|
||||
index += apostrophe.length;
|
||||
continue;
|
||||
}
|
||||
if (command[index] === "'") return { value, next: index + 1 };
|
||||
value += command[index];
|
||||
index += 1;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function parsePosixCommand(command: string): readonly [string, string] | undefined {
|
||||
const executable = readPosixArgument(command, 0);
|
||||
if (!executable || command[executable.next] !== ' ') return undefined;
|
||||
const script = readPosixArgument(command, executable.next + 1);
|
||||
if (!script || script.next !== command.length) return undefined;
|
||||
return [executable.value, script.value];
|
||||
}
|
||||
|
||||
function readPowerShellArgument(command: string, start: number): ParsedArgument | undefined {
|
||||
if (command[start] !== "'") return undefined;
|
||||
let value = '';
|
||||
for (let index = start + 1; index < command.length; index += 1) {
|
||||
if (command[index] !== "'") {
|
||||
value += command[index];
|
||||
continue;
|
||||
}
|
||||
if (command[index + 1] === "'") {
|
||||
value += "'";
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
return { value, next: index + 1 };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function parsePowerShellSource(source: string): readonly [string, string] | undefined {
|
||||
if (!source.startsWith('& ')) return undefined;
|
||||
const executable = readPowerShellArgument(source, 2);
|
||||
if (!executable || source[executable.next] !== ' ') return undefined;
|
||||
const script = readPowerShellArgument(source, executable.next + 1);
|
||||
if (!script || source.slice(script.next) !== '; exit $LASTEXITCODE') return undefined;
|
||||
return [executable.value, script.value];
|
||||
}
|
||||
|
||||
function parseWindowsCommand(command: string): readonly [string, string] | undefined {
|
||||
const match = /^"([^"\r\n]+)" -NoLogo -NoProfile -NonInteractive -EncodedCommand ([A-Za-z0-9+/]+={0,2})$/.exec(command);
|
||||
if (!match
|
||||
|| !path.win32.isAbsolute(match[1])
|
||||
|| path.win32.basename(match[1]).toLowerCase() !== 'powershell.exe') return undefined;
|
||||
const encoded = match[2];
|
||||
const buffer = Buffer.from(encoded, 'base64');
|
||||
if (buffer.length % 2 !== 0 || buffer.toString('base64') !== encoded) return undefined;
|
||||
return parsePowerShellSource(buffer.toString('utf16le'));
|
||||
}
|
||||
|
||||
function parseLegacyWindowsCommand(command: string): readonly [string, string] | undefined {
|
||||
const match = /^"([^"\r\n]+)" "([^"\r\n]+)"$/.exec(command);
|
||||
return match ? [match[1], match[2]] : undefined;
|
||||
}
|
||||
|
||||
function isNodeExecutable(filePath: string): boolean {
|
||||
const basename = path.basename(filePath).toLowerCase();
|
||||
return basename === 'node' || basename === 'node.exe';
|
||||
return process.platform === 'win32' ? encodedWindowsCommand(scriptPath) : posixSource(scriptPath);
|
||||
}
|
||||
|
||||
export function grokRuntimeReference(
|
||||
@@ -142,18 +23,8 @@ export function grokRuntimeReference(
|
||||
scriptName: string,
|
||||
): GrokRuntimeReference | undefined {
|
||||
const parsed = parsePosixCommand(command)
|
||||
?? parseWindowsCommand(command)
|
||||
?? parseEncodedWindowsCommand(command)
|
||||
?? parseLegacyWindowsCommand(command);
|
||||
if (!parsed
|
||||
|| !path.isAbsolute(parsed[0])
|
||||
|| !path.isAbsolute(parsed[1])
|
||||
|| !isNodeExecutable(parsed[0])
|
||||
|| path.basename(parsed[1]) !== scriptName) return undefined;
|
||||
const agentDirectory = path.dirname(parsed[1]);
|
||||
if (!sameGrokPath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))) {
|
||||
return undefined;
|
||||
}
|
||||
const agentId = path.basename(agentDirectory);
|
||||
if (!agentId || agentId === '.' || agentId === '..') return undefined;
|
||||
return { agentId, scriptPath: parsed[1] };
|
||||
if (!parsed || !path.isAbsolute(parsed[0]) || !isNodeExecutable(parsed[0])) return undefined;
|
||||
return managedScriptReference(parsed[1], scriptName);
|
||||
}
|
||||
@@ -1,15 +1,19 @@
|
||||
import { sameAgentId } from './common.js';
|
||||
import {
|
||||
buildGrokCommand,
|
||||
grokRuntimeReference,
|
||||
sameGrokAgentId,
|
||||
type GrokRuntimeReference,
|
||||
} 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';
|
||||
|
||||
export const AGENT_KEY = 'grok';
|
||||
export const GUARD_SCRIPT = 'guard.js';
|
||||
export const AUDIT_SCRIPT = 'hook.js';
|
||||
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([
|
||||
'SessionStart',
|
||||
@@ -172,7 +176,7 @@ function removeFromGroups(
|
||||
const handlers = group.hooks.filter((handler) => {
|
||||
const reference = managedReference(handler, scriptName);
|
||||
return !reference
|
||||
|| (agentId !== undefined && !sameGrokAgentId(reference.agentId, agentId));
|
||||
|| (agentId !== undefined && !sameAgentId(reference.agentId, agentId));
|
||||
});
|
||||
if (handlers.length > 0) result.push({ hooks: handlers });
|
||||
}
|
||||
|
||||
@@ -2,7 +2,9 @@ import path from 'node:path';
|
||||
import type { InstallConfig } from './base.js';
|
||||
import {
|
||||
AGENT_KEY,
|
||||
AUDIT_OPTIONS,
|
||||
AUDIT_SCRIPT,
|
||||
GUARD_OPTIONS,
|
||||
GUARD_SCRIPT,
|
||||
type RenderedGrokDocument,
|
||||
} from './grok-contract.js';
|
||||
@@ -24,14 +26,10 @@ const DISPLAY_NAME = 'Grok Build';
|
||||
const HOOKS_DIRECTORY_LABEL = 'Grok hooks directory';
|
||||
const HOOKS_LABEL = 'Grok user hooks';
|
||||
|
||||
export type GrokRuntimePaths = ManagedRuntimePaths;
|
||||
export type PreparedGrokInstallation = PreparedManagedInstallation;
|
||||
export type { RenameFile };
|
||||
|
||||
export async function preflightGrokInstallation(
|
||||
config: InstallConfig,
|
||||
hooksPath: string,
|
||||
): Promise<GrokRuntimePaths> {
|
||||
): Promise<ManagedRuntimePaths> {
|
||||
return preflightManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
hookLocations: [{ directoryLabel: HOOKS_DIRECTORY_LABEL, filePath: hooksPath }],
|
||||
@@ -42,7 +40,7 @@ export async function preflightGrokInstallation(
|
||||
export async function prepareGrokInstallation(
|
||||
config: InstallConfig,
|
||||
rendered: RenderedGrokDocument,
|
||||
): Promise<PreparedGrokInstallation> {
|
||||
): Promise<PreparedManagedInstallation> {
|
||||
const hooksSource = rendered.next ?? rendered.document.raw;
|
||||
if (hooksSource === undefined) throw new Error('Grok hook configuration is missing');
|
||||
const prepared = await prepareManagedInstallation({
|
||||
@@ -56,8 +54,8 @@ export async function prepareGrokInstallation(
|
||||
source: hooksSource,
|
||||
}],
|
||||
config,
|
||||
guardOptions: { denyProtocol: 'grok' },
|
||||
auditOptions: { nativePayload: true },
|
||||
guardOptions: GUARD_OPTIONS,
|
||||
auditOptions: AUDIT_OPTIONS,
|
||||
}, GUARD_SCRIPT, AUDIT_SCRIPT);
|
||||
const hooksDirectory = path.dirname(rendered.document.filePath);
|
||||
return {
|
||||
@@ -73,7 +71,7 @@ export async function prepareGrokInstallation(
|
||||
}
|
||||
|
||||
export async function commitGrokInstallation(
|
||||
prepared: PreparedGrokInstallation,
|
||||
prepared: PreparedManagedInstallation,
|
||||
renameFile?: RenameFile,
|
||||
): Promise<void> {
|
||||
await commitManagedInstallation(prepared, renameFile);
|
||||
|
||||
+8
-74
@@ -2,14 +2,15 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
AGENT_KEY,
|
||||
AUDIT_OPTIONS,
|
||||
GUARD_OPTIONS,
|
||||
createGrokDocument,
|
||||
parseGrokDocument,
|
||||
type GrokDocument,
|
||||
type GrokRuntimeContract,
|
||||
} from './grok-contract.js';
|
||||
import { sameGrokAgentId, sameGrokPath } from './grok-command.js';
|
||||
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
|
||||
import { parseStrictJsonObject, type JsonObject } from './strict-json.js';
|
||||
import { managedRuntimeFilesExist } from './managed-runtime-status.js';
|
||||
|
||||
const CONFIG_FILE = 'elydora-audit.json';
|
||||
|
||||
@@ -36,82 +37,15 @@ export async function readGrokDocument(): Promise<GrokDocument> {
|
||||
: createGrokDocument(filePath);
|
||||
}
|
||||
|
||||
function requireNonEmptyString(value: unknown, field: string, configPath: string): string {
|
||||
if (typeof value !== 'string' || value.trim().length === 0) {
|
||||
throw new Error(`Elydora runtime config ${field} is invalid: ${configPath}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function validateRuntimeConfig(
|
||||
config: JsonObject,
|
||||
contract: GrokRuntimeContract,
|
||||
configPath: string,
|
||||
): void {
|
||||
const supported = new Set(['org_id', 'agent_id', 'kid', 'base_url', 'token', 'agent_name']);
|
||||
const extra = Object.keys(config).find((key) => !supported.has(key));
|
||||
if (extra) throw new Error(`Elydora runtime config has unsupported field "${extra}": ${configPath}`);
|
||||
requireNonEmptyString(config.org_id, 'org_id', configPath);
|
||||
requireNonEmptyString(config.kid, 'kid', configPath);
|
||||
const agentId = requireNonEmptyString(config.agent_id, 'agent_id', configPath);
|
||||
if (!sameGrokAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
|
||||
throw new Error(`Elydora runtime identity does not match Grok hooks: ${configPath}`);
|
||||
}
|
||||
if (config.token !== undefined) requireNonEmptyString(config.token, 'token', configPath);
|
||||
const rawBaseUrl = requireNonEmptyString(config.base_url, 'base_url', configPath);
|
||||
let baseUrl: URL;
|
||||
try {
|
||||
baseUrl = new URL(rawBaseUrl);
|
||||
} catch (error) {
|
||||
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`, {
|
||||
cause: error instanceof Error ? error : new Error(String(error)),
|
||||
});
|
||||
}
|
||||
if (!['http:', 'https:'].includes(baseUrl.protocol)
|
||||
|| !baseUrl.hostname
|
||||
|| baseUrl.username
|
||||
|| baseUrl.password
|
||||
|| baseUrl.search
|
||||
|| baseUrl.hash) {
|
||||
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`);
|
||||
}
|
||||
}
|
||||
|
||||
function validatePrivateKey(contents: string, keyPath: string): void {
|
||||
const bytes = Buffer.from(contents, 'base64url');
|
||||
if (bytes.length !== 32 || bytes.toString('base64url') !== contents) {
|
||||
throw new Error(`Elydora private key is invalid: ${keyPath}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function runtimeContractExists(contract: GrokRuntimeContract): Promise<boolean> {
|
||||
const runtimeRoot = path.join(os.homedir(), '.elydora');
|
||||
const agentDirectory = path.dirname(contract.guardPath);
|
||||
if (!sameGrokPath(path.dirname(agentDirectory), runtimeRoot)
|
||||
|| !sameGrokPath(contract.auditPath, path.join(agentDirectory, 'hook.js'))) return false;
|
||||
if (!await inspectPhysicalDirectory(runtimeRoot, 'Elydora runtime directory')) return false;
|
||||
if (!await inspectPhysicalDirectory(agentDirectory, 'Elydora agent runtime directory')) return false;
|
||||
|
||||
const configPath = path.join(agentDirectory, 'config.json');
|
||||
const keyPath = path.join(agentDirectory, 'private.key');
|
||||
const [config, key, guard, audit] = await Promise.all([
|
||||
readPhysicalFile(configPath, 'Elydora runtime config'),
|
||||
readPhysicalFile(keyPath, 'Elydora private key'),
|
||||
readPhysicalFile(contract.guardPath, 'Elydora guard runtime'),
|
||||
readPhysicalFile(contract.auditPath, 'Elydora audit runtime'),
|
||||
]);
|
||||
if (!config || !key || !guard || !audit) return false;
|
||||
const parsed = parseStrictJsonObject(config.contents, `Elydora runtime config at ${configPath}`);
|
||||
validateRuntimeConfig(parsed, contract, configPath);
|
||||
validatePrivateKey(key.contents, keyPath);
|
||||
return guard.contents.length > 0 && audit.contents.length > 0;
|
||||
}
|
||||
|
||||
export async function grokRuntimeFilesExist(
|
||||
contracts: readonly GrokRuntimeContract[],
|
||||
): Promise<boolean> {
|
||||
for (const contract of contracts) {
|
||||
if (await runtimeContractExists(contract)) return true;
|
||||
const exists = await managedRuntimeFilesExist(contract, AGENT_KEY, {
|
||||
guardOptions: GUARD_OPTIONS,
|
||||
auditOptions: AUDIT_OPTIONS,
|
||||
});
|
||||
if (exists) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
+145
-54
@@ -1,8 +1,5 @@
|
||||
import { PROTECTED_RUNTIME_READER } from './runtime-reader-template.js';
|
||||
|
||||
export { generateGuardScript } from './guard-template.js';
|
||||
export type { GuardScriptOptions } from './guard-template.js';
|
||||
|
||||
export interface HookScriptOptions {
|
||||
readonly failClosed?: boolean;
|
||||
readonly nativePayload?: boolean;
|
||||
@@ -38,6 +35,8 @@ const KEY_PATH = path.join(ELYDORA_DIR, AGENT_ID, 'private.key');
|
||||
const CHAIN_STATE_PATH = path.join(ELYDORA_DIR, AGENT_ID, 'chain-state.json');
|
||||
const ERROR_LOG_PATH = path.join(ELYDORA_DIR, AGENT_ID, 'error.log');
|
||||
const ZERO_CHAIN_HASH = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
|
||||
const MAX_CHAIN_ATTEMPTS = 5;
|
||||
const SUBMIT_BUDGET_MS = 4000;
|
||||
|
||||
${PROTECTED_RUNTIME_READER}
|
||||
|
||||
@@ -165,6 +164,81 @@ function writeChainState(chainHash) {
|
||||
writeProtectedJson(CHAIN_STATE_PATH, 'Chain state', { prev_chain_hash: chainHash });
|
||||
}
|
||||
|
||||
function lockOwnerAlive(lockPath) {
|
||||
let owner;
|
||||
try {
|
||||
owner = Number.parseInt(fs.readFileSync(lockPath, 'utf-8'), 10);
|
||||
} catch (error) {
|
||||
if (!hasRuntimeErrorCode(error, 'ENOENT')) throw error;
|
||||
return false;
|
||||
}
|
||||
if (!Number.isInteger(owner) || owner <= 0) return false;
|
||||
try {
|
||||
process.kill(owner, 0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (hasRuntimeErrorCode(error, 'ESRCH')) return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function withChainLock(update) {
|
||||
const lockPath = CHAIN_STATE_PATH + '.lock';
|
||||
const deadline = performance.now() + 1000;
|
||||
for (;;) {
|
||||
let descriptor;
|
||||
try {
|
||||
descriptor = fs.openSync(lockPath, 'wx', 0o600);
|
||||
fs.writeSync(descriptor, String(process.pid));
|
||||
} catch (error) {
|
||||
if (!hasRuntimeErrorCode(error, 'EEXIST')) throw error;
|
||||
if (lockOwnerAlive(lockPath)) {
|
||||
if (performance.now() > deadline) throw new Error('Chain state lock timed out: ' + lockPath);
|
||||
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
|
||||
continue;
|
||||
}
|
||||
let age = 0;
|
||||
try { age = Date.now() - fs.statSync(lockPath).mtimeMs; } catch (statError) {
|
||||
if (!hasRuntimeErrorCode(statError, 'ENOENT')) throw statError;
|
||||
}
|
||||
if (age > 5000) {
|
||||
const reclaimed = lockPath + '.' + process.pid + '.stale';
|
||||
try {
|
||||
fs.renameSync(lockPath, reclaimed);
|
||||
fs.unlinkSync(reclaimed);
|
||||
} catch (reclaimError) {
|
||||
if (!hasRuntimeErrorCode(reclaimError, 'ENOENT')) throw reclaimError;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (performance.now() > deadline) throw new Error('Chain state lock timed out: ' + lockPath);
|
||||
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
return update();
|
||||
} finally {
|
||||
let current = null;
|
||||
try {
|
||||
current = fs.lstatSync(lockPath);
|
||||
} catch (statError) {
|
||||
if (!hasRuntimeErrorCode(statError, 'ENOENT')) throw statError;
|
||||
}
|
||||
const own = fs.fstatSync(descriptor);
|
||||
fs.closeSync(descriptor);
|
||||
if (current && current.ino === own.ino && current.dev === own.dev) fs.unlinkSync(lockPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function advanceChainState(fromHash, toHash) {
|
||||
return withChainLock(() => {
|
||||
if (readChainState() !== fromHash) return false;
|
||||
writeChainState(toHash);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
function readConfigAndKey() {
|
||||
const raw = readProtectedFile(
|
||||
CONFIG_PATH,
|
||||
@@ -219,27 +293,43 @@ async function readHookInput() {
|
||||
return value;
|
||||
}
|
||||
|
||||
async function submitOperation(hookData, runtime) {
|
||||
const toolEvent = hookData.tool_result && typeof hookData.tool_result === 'object'
|
||||
? hookData.tool_result
|
||||
: hookData.tool_call && typeof hookData.tool_call === 'object'
|
||||
? hookData.tool_call
|
||||
: {};
|
||||
const toolName = hookData.tool_name || hookData.toolName || hookData.name ||
|
||||
toolEvent.name || 'unknown';
|
||||
const toolInput = hookData.tool_input || hookData.toolInput || hookData.input ||
|
||||
hookData.parameters || toolEvent.input || {};
|
||||
const sessionId = hookData.conversation_id || hookData.session_id || hookData.sessionId ||
|
||||
hookData.session || hookData.taskId || 'unknown';
|
||||
const previousHash = readChainState();
|
||||
async function postOperation(operation, runtime, deadline) {
|
||||
const remaining = deadline - performance.now();
|
||||
if (remaining <= 0) throw new Error('Audit API retry budget exhausted');
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), Math.min(5000, remaining));
|
||||
try {
|
||||
const headers = { 'Content-Type': 'application/json', Accept: 'application/json' };
|
||||
if (runtime.config.token) headers.Authorization = 'Bearer ' + runtime.config.token;
|
||||
const response = await fetch(runtime.baseUrl + '/v1/operations', {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(operation),
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (response.ok) return { accepted: true };
|
||||
const responseBody = await response.text();
|
||||
if (response.status === 400 && responseBody) {
|
||||
let failure;
|
||||
try { failure = JSON.parse(responseBody); } catch (error) {
|
||||
throw new Error('Audit API returned invalid error JSON: ' + error.message);
|
||||
}
|
||||
if (failure.error && failure.error.code === 'PREV_HASH_MISMATCH') {
|
||||
const match = String(failure.error.message || '').match(
|
||||
/Expected prev_chain_hash "([A-Za-z0-9_-]{43})"/,
|
||||
);
|
||||
if (match) return { accepted: false, expected: match[1] };
|
||||
}
|
||||
}
|
||||
throw new Error('Audit API returned HTTP ' + response.status);
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
function buildOperation(runtime, payload, payloadHash, toolName, sessionId, previousHash) {
|
||||
const operationId = uuidv7();
|
||||
const issuedAt = Date.now();
|
||||
const payload = NATIVE_PAYLOAD ? hookData : {
|
||||
tool_name: toolName,
|
||||
tool_input: toolInput,
|
||||
session_id: sessionId,
|
||||
};
|
||||
const payloadHash = computePayloadHash(payload);
|
||||
const chainHash = computeChainHash(previousHash, payloadHash, operationId, issuedAt);
|
||||
const unsigned = {
|
||||
op_version: '1.0',
|
||||
@@ -261,41 +351,42 @@ async function submitOperation(hookData, runtime) {
|
||||
runtime.privateKey,
|
||||
Buffer.from(jcsCanonicalise(unsigned), 'utf-8'),
|
||||
);
|
||||
const operation = { ...unsigned, chain_hash: chainHash, signature };
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 5000);
|
||||
try {
|
||||
const headers = { 'Content-Type': 'application/json', Accept: 'application/json' };
|
||||
if (runtime.config.token) headers.Authorization = 'Bearer ' + runtime.config.token;
|
||||
const response = await fetch(runtime.baseUrl + '/v1/operations', {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(operation),
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (response.ok) {
|
||||
writeChainState(chainHash);
|
||||
return { operation: { ...unsigned, chain_hash: chainHash, signature }, chainHash };
|
||||
}
|
||||
|
||||
async function submitOperation(hookData, runtime) {
|
||||
const toolEvent = hookData.tool_result && typeof hookData.tool_result === 'object'
|
||||
? hookData.tool_result
|
||||
: hookData.tool_call && typeof hookData.tool_call === 'object'
|
||||
? hookData.tool_call
|
||||
: {};
|
||||
const toolName = hookData.tool_name || hookData.toolName || hookData.name ||
|
||||
toolEvent.name || 'unknown';
|
||||
const toolInput = hookData.tool_input || hookData.toolInput || hookData.input ||
|
||||
hookData.parameters || toolEvent.input || {};
|
||||
const sessionId = hookData.conversation_id || hookData.session_id || hookData.sessionId ||
|
||||
hookData.session || hookData.taskId || 'unknown';
|
||||
const payload = NATIVE_PAYLOAD ? hookData : {
|
||||
tool_name: toolName,
|
||||
tool_input: toolInput,
|
||||
session_id: sessionId,
|
||||
};
|
||||
const payloadHash = computePayloadHash(payload);
|
||||
const deadline = performance.now() + SUBMIT_BUDGET_MS;
|
||||
let previousHash = readChainState();
|
||||
for (let attempt = 1; ; attempt += 1) {
|
||||
const built = buildOperation(runtime, payload, payloadHash, toolName, sessionId, previousHash);
|
||||
const result = await postOperation(built.operation, runtime, deadline);
|
||||
if (result.accepted) {
|
||||
advanceChainState(previousHash, built.chainHash);
|
||||
return;
|
||||
}
|
||||
const responseBody = await response.text();
|
||||
if (response.status === 400 && responseBody) {
|
||||
let failure;
|
||||
try { failure = JSON.parse(responseBody); } catch (error) {
|
||||
throw new Error('Audit API returned invalid error JSON: ' + error.message);
|
||||
}
|
||||
if (failure.error && failure.error.code === 'PREV_HASH_MISMATCH') {
|
||||
const match = String(failure.error.message || '').match(
|
||||
/Expected prev_chain_hash "([A-Za-z0-9_-]{43})"/,
|
||||
);
|
||||
if (match) {
|
||||
writeChainState(match[1]);
|
||||
logError(new Error('Chain hash resynced to server: ' + match[1]));
|
||||
}
|
||||
}
|
||||
advanceChainState(previousHash, result.expected);
|
||||
logError(new Error('Chain hash resynced to server: ' + result.expected));
|
||||
if (attempt >= MAX_CHAIN_ATTEMPTS) {
|
||||
throw new Error('Audit API rejected prev_chain_hash ' + attempt + ' times');
|
||||
}
|
||||
throw new Error('Audit API returned HTTP ' + response.status);
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
previousHash = readChainState();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
@@ -1,140 +1,21 @@
|
||||
import os from 'node:os';
|
||||
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 {
|
||||
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 type KimiRuntimeReference = ManagedScriptReference;
|
||||
|
||||
export function buildKimiCommand(scriptPath: string): string {
|
||||
if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) {
|
||||
throw new Error('Kimi hook commands require absolute executable and script paths');
|
||||
}
|
||||
return process.platform === 'win32'
|
||||
? windowsCommand(scriptPath)
|
||||
: `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`;
|
||||
}
|
||||
|
||||
function readPosixArgument(command: string, start: number): ParsedArgument | undefined {
|
||||
if (command[start] !== "'") return undefined;
|
||||
const apostrophe = `'"'"'`;
|
||||
let value = '';
|
||||
for (let index = start + 1; index < command.length;) {
|
||||
if (command.startsWith(apostrophe, index)) {
|
||||
value += "'";
|
||||
index += apostrophe.length;
|
||||
continue;
|
||||
}
|
||||
if (command[index] === "'") return { value, next: index + 1 };
|
||||
value += command[index];
|
||||
index += 1;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function parsePosixCommand(command: string): readonly [string, string] | undefined {
|
||||
const executable = readPosixArgument(command, 0);
|
||||
if (!executable || command[executable.next] !== ' ') return undefined;
|
||||
const script = readPosixArgument(command, executable.next + 1);
|
||||
if (!script || script.next !== command.length) return undefined;
|
||||
return [executable.value, script.value];
|
||||
}
|
||||
|
||||
function readPowerShellArgument(command: string, start: number): ParsedArgument | undefined {
|
||||
if (command[start] !== "'") return undefined;
|
||||
let value = '';
|
||||
for (let index = start + 1; index < command.length; index += 1) {
|
||||
if (command[index] !== "'") {
|
||||
value += command[index];
|
||||
continue;
|
||||
}
|
||||
if (command[index + 1] === "'") {
|
||||
value += "'";
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
return { value, next: index + 1 };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function parsePowerShellSource(source: string): readonly [string, string] | undefined {
|
||||
if (!source.startsWith('& ')) return undefined;
|
||||
const executable = readPowerShellArgument(source, 2);
|
||||
if (!executable || source[executable.next] !== ' ') return undefined;
|
||||
const script = readPowerShellArgument(source, executable.next + 1);
|
||||
if (!script || source.slice(script.next) !== '; exit $LASTEXITCODE') return undefined;
|
||||
return [executable.value, script.value];
|
||||
}
|
||||
|
||||
function parseWindowsCommand(command: string): readonly [string, string] | undefined {
|
||||
const match = /^"([^"\r\n]+)" -NoLogo -NoProfile -NonInteractive -EncodedCommand ([A-Za-z0-9+/]+={0,2})$/.exec(command);
|
||||
if (!match
|
||||
|| !path.win32.isAbsolute(match[1])
|
||||
|| path.win32.basename(match[1]).toLowerCase() !== 'powershell.exe') return undefined;
|
||||
const encoded = match[2];
|
||||
const buffer = Buffer.from(encoded, 'base64');
|
||||
if (buffer.length % 2 !== 0 || buffer.toString('base64') !== encoded) return undefined;
|
||||
return parsePowerShellSource(buffer.toString('utf16le'));
|
||||
}
|
||||
|
||||
function parseLegacyWindowsCommand(command: string): readonly [string, string] | undefined {
|
||||
const match = /^"([^"\r\n]+)" "([^"\r\n]+)"$/.exec(command);
|
||||
return match ? [match[1], match[2]] : undefined;
|
||||
}
|
||||
|
||||
function isNodeExecutable(filePath: string): boolean {
|
||||
const basename = path.basename(filePath).toLowerCase();
|
||||
return basename === 'node' || basename === 'node.exe';
|
||||
return process.platform === 'win32' ? encodedWindowsCommand(scriptPath) : posixSource(scriptPath);
|
||||
}
|
||||
|
||||
export function kimiRuntimeReference(
|
||||
@@ -142,18 +23,8 @@ export function kimiRuntimeReference(
|
||||
scriptName: string,
|
||||
): KimiRuntimeReference | undefined {
|
||||
const parsed = parsePosixCommand(command)
|
||||
?? parseWindowsCommand(command)
|
||||
?? parseEncodedWindowsCommand(command)
|
||||
?? parseLegacyWindowsCommand(command);
|
||||
if (!parsed
|
||||
|| !path.isAbsolute(parsed[0])
|
||||
|| !path.isAbsolute(parsed[1])
|
||||
|| !isNodeExecutable(parsed[0])
|
||||
|| path.basename(parsed[1]) !== scriptName) return undefined;
|
||||
const agentDirectory = path.dirname(parsed[1]);
|
||||
if (!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] };
|
||||
if (!parsed || !path.isAbsolute(parsed[0]) || !isNodeExecutable(parsed[0])) return undefined;
|
||||
return managedScriptReference(parsed[1], scriptName);
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
import { sameAgentId } from './common.js';
|
||||
import {
|
||||
buildKimiCommand,
|
||||
kimiRuntimeReference,
|
||||
sameKimiAgentId,
|
||||
type KimiRuntimeReference,
|
||||
} from './kimi-command.js';
|
||||
import { isObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
export const AGENT_KEY = 'kimi';
|
||||
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 type TomlObject = Record<string, unknown>;
|
||||
export type TomlObject = JsonObject;
|
||||
export type ManagedKimiEvent = 'PreToolUse' | 'PostToolUse' | 'PostToolUseFailure';
|
||||
|
||||
export interface KimiHook extends TomlObject {
|
||||
@@ -75,14 +76,6 @@ export interface KimiRuntimeContract {
|
||||
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 {
|
||||
return Object.keys(hook).sort().join('|') === 'command|event|timeout';
|
||||
}
|
||||
@@ -194,7 +187,7 @@ async function renderHookSource(
|
||||
if (document.usesHookTables) return patchToml(document.raw ?? '', nextRoot);
|
||||
|
||||
let base = document.raw ?? '';
|
||||
if (hasOwn(document.root, 'hooks')) {
|
||||
if (Object.hasOwn(document.root, 'hooks')) {
|
||||
const rootWithoutHooks = { ...document.root };
|
||||
delete rootWithoutHooks.hooks;
|
||||
base = patchToml(base, rootWithoutHooks);
|
||||
@@ -248,7 +241,7 @@ export function removeManagedKimiHooks(
|
||||
if (!expected) return true;
|
||||
const managedId = managedAgentId(hook, expected[0], expected[1]);
|
||||
if (!managedId) return true;
|
||||
return agentId !== undefined && !sameKimiAgentId(managedId, agentId);
|
||||
return agentId !== undefined && !sameAgentId(managedId, agentId);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -23,10 +23,6 @@ import {
|
||||
|
||||
const DISPLAY_NAME = 'Kimi';
|
||||
|
||||
export type KimiRuntimePaths = ManagedRuntimePaths;
|
||||
export type PreparedKimiInstallation = PreparedManagedInstallation;
|
||||
export type { RenameFile };
|
||||
|
||||
function hookLocations(documents: readonly KimiConfigDocument[]) {
|
||||
return documents.map((document) => ({
|
||||
directoryLabel: document.contract.directoryLabel,
|
||||
@@ -37,7 +33,7 @@ function hookLocations(documents: readonly KimiConfigDocument[]) {
|
||||
export async function preflightKimiInstallation(
|
||||
config: InstallConfig,
|
||||
documents: readonly KimiConfigDocument[],
|
||||
): Promise<KimiRuntimePaths> {
|
||||
): Promise<ManagedRuntimePaths> {
|
||||
return preflightManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
hookLocations: hookLocations(documents),
|
||||
@@ -56,7 +52,7 @@ function renderedSource(rendered: RenderedKimiDocument): string {
|
||||
export async function prepareKimiInstallation(
|
||||
config: InstallConfig,
|
||||
rendered: readonly RenderedKimiDocument[],
|
||||
): Promise<PreparedKimiInstallation> {
|
||||
): Promise<PreparedManagedInstallation> {
|
||||
return prepareManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
displayName: DISPLAY_NAME,
|
||||
@@ -73,7 +69,7 @@ export async function prepareKimiInstallation(
|
||||
}
|
||||
|
||||
export async function commitKimiInstallation(
|
||||
prepared: PreparedKimiInstallation,
|
||||
prepared: PreparedManagedInstallation,
|
||||
renameFile?: RenameFile,
|
||||
): Promise<void> {
|
||||
await commitManagedInstallation(prepared, renameFile);
|
||||
|
||||
+4
-88
@@ -1,6 +1,7 @@
|
||||
import fsp from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { asError, errorMessage, hasCode, samePath } from './common.js';
|
||||
import {
|
||||
AGENT_KEY,
|
||||
LEGACY_EVENTS,
|
||||
@@ -10,23 +11,9 @@ import {
|
||||
type KimiConfigDocument,
|
||||
type KimiContract,
|
||||
type KimiRuntimeContract,
|
||||
type TomlObject,
|
||||
} from './kimi-contract.js';
|
||||
import { sameKimiAgentId, sameKimiPath } from './kimi-command.js';
|
||||
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
|
||||
import { parseStrictJsonObject } from './strict-json.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;
|
||||
}
|
||||
import { managedRuntimeFilesExist } from './managed-runtime-status.js';
|
||||
|
||||
async function pathEntryExists(filePath: string, label: string): Promise<boolean> {
|
||||
try {
|
||||
@@ -72,7 +59,7 @@ export async function resolveKimiContracts(): Promise<KimiContract[]> {
|
||||
const legacyHome = path.join(home, '.kimi');
|
||||
const stable = stableContract(path.join(stableHome, '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
|
||||
|| await pathEntryExists(stableHome, 'Kimi Code home');
|
||||
@@ -96,82 +83,11 @@ export async function readKimiDocuments(): Promise<KimiConfigDocument[]> {
|
||||
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(
|
||||
contracts: readonly KimiRuntimeContract[],
|
||||
): Promise<boolean> {
|
||||
for (const contract of contracts) {
|
||||
if (await runtimeContractExists(contract)) return true;
|
||||
if (await managedRuntimeFilesExist(contract, AGENT_KEY)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { managedScriptReference, sameAgentId, samePath } from './common.js';
|
||||
import {
|
||||
buildKiroIdeCommand,
|
||||
kiroIdeRuntimeReference,
|
||||
sameKiroIdeAgentId,
|
||||
sameKiroIdePath,
|
||||
type KiroIdeRuntimeReference,
|
||||
} from './kiroide-command.js';
|
||||
import {
|
||||
buildKiroIdeHook,
|
||||
exactKeys,
|
||||
kiroIdeRuntimeContracts,
|
||||
renderKiroIdeDocument,
|
||||
type KiroIdeDocument,
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
type RenderedKiroIdeDocument,
|
||||
type KiroIdeRuntimeContract,
|
||||
} from './kiroide-contract.js';
|
||||
import { isNodeExecutable, parseLegacyWindowsCommand } from './shell-command.js';
|
||||
import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
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) ?? [];
|
||||
}
|
||||
|
||||
function exactKeys(value: JsonObject, keys: readonly string[]): boolean {
|
||||
return Object.keys(value).sort().join('|') === [...keys].sort().join('|');
|
||||
}
|
||||
|
||||
function legacyWindowsReference(
|
||||
command: unknown,
|
||||
scriptName: string,
|
||||
): KiroIdeRuntimeReference | undefined {
|
||||
if (typeof command !== 'string') return undefined;
|
||||
const match = /^"([^"\r\n]+)" "([^"\r\n]+)"$/.exec(command);
|
||||
if (!match
|
||||
|| !path.isAbsolute(match[1])
|
||||
|| !['node', 'node.exe'].includes(path.basename(match[1]).toLowerCase())
|
||||
|| !path.isAbsolute(match[2])
|
||||
|| path.basename(match[2]) !== scriptName) return undefined;
|
||||
const agentDirectory = path.dirname(match[2]);
|
||||
if (!sameKiroIdePath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))) {
|
||||
return undefined;
|
||||
}
|
||||
const agentId = path.basename(agentDirectory);
|
||||
return agentId ? { agentId, scriptPath: match[2] } : undefined;
|
||||
const parsed = parseLegacyWindowsCommand(command);
|
||||
if (!parsed || !path.isAbsolute(parsed[0]) || !isNodeExecutable(parsed[0])) return undefined;
|
||||
return managedScriptReference(parsed[1], scriptName);
|
||||
}
|
||||
|
||||
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) => {
|
||||
const reference = v2OwnedReference(hook, event);
|
||||
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']) {
|
||||
const remaining = eventHooks(document, event).filter((hook) => {
|
||||
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;
|
||||
else delete next[event];
|
||||
@@ -288,7 +276,7 @@ function entirelyManagedV2Document(document: KiroCliV2Document, agentId?: string
|
||||
const hooks = eventHooks(document, event);
|
||||
if (hooks.length !== 1) return false;
|
||||
const reference = v2OwnedReference(hooks[0], event);
|
||||
if (!reference || (agentId !== undefined && !sameKiroIdeAgentId(reference.agentId, agentId))) {
|
||||
if (!reference || (agentId !== undefined && !sameAgentId(reference.agentId, agentId))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -324,7 +312,7 @@ export function kiroCliV2RuntimeContracts(
|
||||
.map((hook) => v2ManagedReference(hook, 'postToolUse'))
|
||||
.filter((value): value is KiroIdeRuntimeReference => value !== undefined);
|
||||
if (guards.length !== 1 || audits.length !== 1
|
||||
|| !sameKiroIdeAgentId(guards[0].agentId, audits[0].agentId)) return [];
|
||||
|| !sameAgentId(guards[0].agentId, audits[0].agentId)) return [];
|
||||
return [{ agentId: guards[0].agentId, guardPath: guards[0].scriptPath, auditPath: audits[0].scriptPath }];
|
||||
}
|
||||
|
||||
@@ -355,7 +343,7 @@ export function withoutManagedKiroCliV3Hooks(
|
||||
): KiroIdeHook[] {
|
||||
return hooks.filter((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) => {
|
||||
const reference = v3OwnedReference(hook);
|
||||
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) => {
|
||||
const reference = v3OwnedReference(hook);
|
||||
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 v3 = kiroIdeRuntimeContracts(v3Hooks);
|
||||
if (v2.length !== 1 || v3.length !== 1
|
||||
|| !sameKiroIdeAgentId(v2[0].agentId, v3[0].agentId)
|
||||
|| !sameKiroIdePath(v2[0].guardPath, v3[0].guardPath)
|
||||
|| !sameKiroIdePath(v2[0].auditPath, v3[0].auditPath)) return undefined;
|
||||
|| !sameAgentId(v2[0].agentId, v3[0].agentId)
|
||||
|| !samePath(v2[0].guardPath, v3[0].guardPath)
|
||||
|| !samePath(v2[0].auditPath, v3[0].auditPath)) return undefined;
|
||||
return v2[0];
|
||||
}
|
||||
@@ -27,10 +27,6 @@ const DISPLAY_NAME = 'Kiro CLI';
|
||||
const V2_DIRECTORY_LABEL = 'Kiro CLI agents directory';
|
||||
const V3_DIRECTORY_LABEL = 'Kiro CLI global hooks directory';
|
||||
|
||||
export type KiroCliRuntimePaths = ManagedRuntimePaths;
|
||||
export type PreparedKiroCliInstallation = PreparedManagedInstallation;
|
||||
export type { RenameFile };
|
||||
|
||||
function hookLocations(sources: KiroCliSources) {
|
||||
return [
|
||||
{ directoryLabel: V2_DIRECTORY_LABEL, filePath: sources.paths.v2Path },
|
||||
@@ -41,7 +37,7 @@ function hookLocations(sources: KiroCliSources) {
|
||||
export async function preflightKiroCliInstallation(
|
||||
config: InstallConfig,
|
||||
sources: KiroCliSources,
|
||||
): Promise<KiroCliRuntimePaths> {
|
||||
): Promise<ManagedRuntimePaths> {
|
||||
return preflightManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
hookLocations: hookLocations(sources),
|
||||
@@ -54,7 +50,7 @@ export async function prepareKiroCliInstallation(
|
||||
sources: KiroCliSources,
|
||||
v2: RenderedKiroCliV2Document,
|
||||
v3: RenderedKiroIdeDocument,
|
||||
): Promise<PreparedKiroCliInstallation> {
|
||||
): Promise<PreparedManagedInstallation> {
|
||||
if (v2.next === undefined || v3.next === undefined) {
|
||||
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(
|
||||
prepared: PreparedKiroCliInstallation,
|
||||
prepared: PreparedManagedInstallation,
|
||||
renameFile?: RenameFile,
|
||||
): Promise<void> {
|
||||
await commitManagedInstallation(prepared, renameFile);
|
||||
|
||||
@@ -12,11 +12,10 @@ import {
|
||||
type KiroIdeDocument,
|
||||
type KiroIdeRuntimeContract,
|
||||
} from './kiroide-contract.js';
|
||||
import { MAX_CONFIG_BYTES } from './common.js';
|
||||
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
|
||||
import { managedRuntimeFilesExist } from './managed-runtime-status.js';
|
||||
|
||||
const MAX_HOOK_BYTES = 512 * 1024;
|
||||
|
||||
export interface KiroCliSources {
|
||||
readonly paths: KiroCliPaths;
|
||||
readonly v2: KiroCliV2Document;
|
||||
@@ -36,7 +35,7 @@ async function readV2Document(paths: KiroCliPaths): Promise<KiroCliV2Document> {
|
||||
const snapshot = await readPhysicalFile(
|
||||
paths.v2Path,
|
||||
'Kiro CLI v2 agent config',
|
||||
MAX_HOOK_BYTES,
|
||||
MAX_CONFIG_BYTES,
|
||||
);
|
||||
return snapshot
|
||||
? parseKiroCliV2Document(paths.v2Path, snapshot.contents)
|
||||
@@ -47,7 +46,7 @@ async function readV3Document(paths: KiroCliPaths): Promise<KiroIdeDocument> {
|
||||
const snapshot = await readPhysicalFile(
|
||||
paths.v3Path,
|
||||
'Kiro CLI v3 global hooks',
|
||||
MAX_HOOK_BYTES,
|
||||
MAX_CONFIG_BYTES,
|
||||
);
|
||||
return snapshot
|
||||
? parseKiroIdeDocument(paths.v3Path, snapshot.contents, 'Kiro CLI v3 global hooks')
|
||||
|
||||
+13
-136
@@ -1,132 +1,20 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { managedScriptReference, type ManagedScriptReference } from './common.js';
|
||||
import {
|
||||
encodedWindowsCommand,
|
||||
isNodeExecutable,
|
||||
parseEncodedWindowsCommand,
|
||||
parsePosixCommand,
|
||||
posixSource,
|
||||
} from './shell-command.js';
|
||||
|
||||
interface ParsedArgument {
|
||||
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 type KiroIdeRuntimeReference = ManagedScriptReference;
|
||||
|
||||
export function buildKiroIdeCommand(scriptPath: string): string {
|
||||
if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) {
|
||||
throw new Error('Kiro IDE hook commands require absolute executable and script paths');
|
||||
}
|
||||
return process.platform === 'win32'
|
||||
? windowsCommand(scriptPath)
|
||||
: `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`;
|
||||
}
|
||||
|
||||
function readPosixArgument(command: string, start: number): ParsedArgument | undefined {
|
||||
if (command[start] !== "'") return undefined;
|
||||
const apostrophe = `'"'"'`;
|
||||
let value = '';
|
||||
for (let index = start + 1; index < command.length;) {
|
||||
if (command.startsWith(apostrophe, index)) {
|
||||
value += "'";
|
||||
index += apostrophe.length;
|
||||
continue;
|
||||
}
|
||||
if (command[index] === "'") return { value, next: index + 1 };
|
||||
value += command[index];
|
||||
index += 1;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function parsePosixCommand(command: string): readonly [string, string] | undefined {
|
||||
const executable = readPosixArgument(command, 0);
|
||||
if (!executable || command[executable.next] !== ' ') return undefined;
|
||||
const script = readPosixArgument(command, executable.next + 1);
|
||||
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';
|
||||
return process.platform === 'win32' ? encodedWindowsCommand(scriptPath) : posixSource(scriptPath);
|
||||
}
|
||||
|
||||
export function kiroIdeRuntimeReference(
|
||||
@@ -134,19 +22,8 @@ export function kiroIdeRuntimeReference(
|
||||
scriptName: string,
|
||||
): KiroIdeRuntimeReference | undefined {
|
||||
const parsed = process.platform === 'win32'
|
||||
? parseWindowsCommand(command)
|
||||
? parseEncodedWindowsCommand(command)
|
||||
: parsePosixCommand(command);
|
||||
if (!parsed
|
||||
|| !path.isAbsolute(parsed[0])
|
||||
|| !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;
|
||||
if (!parsed || !path.isAbsolute(parsed[0]) || !isNodeExecutable(parsed[0])) return undefined;
|
||||
return managedScriptReference(parsed[1], scriptName);
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { managedScriptReference, sameAgentId } from './common.js';
|
||||
import {
|
||||
buildKiroIdeCommand,
|
||||
kiroIdeRuntimeReference,
|
||||
sameKiroIdeAgentId,
|
||||
sameKiroIdePath,
|
||||
type KiroIdeRuntimeReference,
|
||||
} from './kiroide-command.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: [] };
|
||||
}
|
||||
|
||||
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('|');
|
||||
}
|
||||
|
||||
@@ -228,7 +227,7 @@ export function withoutManagedKiroIdeHooks(
|
||||
): KiroIdeHook[] {
|
||||
return hooks.filter((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) {
|
||||
if (typeof command !== 'string') return undefined;
|
||||
const match = /^node "([^"\r\n]+)"$/.exec(command);
|
||||
if (!match || !path.isAbsolute(match[1]) || path.basename(match[1]) !== scriptName) return 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] };
|
||||
return match ? managedScriptReference(match[1], scriptName) : 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;
|
||||
const guard = legacyReference(guardHook.command, GUARD_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 };
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import path from 'node:path';
|
||||
import type { InstallConfig } from './base.js';
|
||||
import { sameKiroIdeAgentId } from './kiroide-command.js';
|
||||
import { sameAgentId } from './common.js';
|
||||
import {
|
||||
AGENT_KEY,
|
||||
AUDIT_SCRIPT,
|
||||
@@ -31,17 +31,13 @@ import {
|
||||
const DISPLAY_NAME = 'Kiro IDE';
|
||||
const DIRECTORY_LABEL = 'Kiro IDE hooks directory';
|
||||
|
||||
export type KiroIdeRuntimePaths = ManagedRuntimePaths;
|
||||
export type PreparedKiroIdeInstallation = PreparedManagedInstallation;
|
||||
export type { RenameFile };
|
||||
|
||||
function hookLocation(paths: KiroIdePaths) {
|
||||
return [{ directoryLabel: DIRECTORY_LABEL, filePath: paths.configPath }];
|
||||
}
|
||||
|
||||
function removesLegacy(legacy: LegacyKiroIdeDocument, agentId?: string): boolean {
|
||||
return legacy.contract !== undefined
|
||||
&& (agentId === undefined || sameKiroIdeAgentId(legacy.contract.agentId, agentId));
|
||||
&& (agentId === undefined || sameAgentId(legacy.contract.agentId, agentId));
|
||||
}
|
||||
|
||||
async function prepareLegacyRemoval(
|
||||
@@ -64,7 +60,7 @@ async function prepareLegacyRemoval(
|
||||
export async function preflightKiroIdeInstallation(
|
||||
config: InstallConfig,
|
||||
paths: KiroIdePaths,
|
||||
): Promise<KiroIdeRuntimePaths> {
|
||||
): Promise<ManagedRuntimePaths> {
|
||||
return preflightManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
hookLocations: hookLocation(paths),
|
||||
@@ -76,7 +72,7 @@ export async function prepareKiroIdeInstallation(
|
||||
config: InstallConfig,
|
||||
sources: KiroIdeSources,
|
||||
rendered: RenderedKiroIdeDocument,
|
||||
): Promise<PreparedKiroIdeInstallation> {
|
||||
): Promise<PreparedManagedInstallation> {
|
||||
if (rendered.next === undefined) throw new Error('Kiro IDE installation requires a hook document');
|
||||
const prepared = await prepareManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
@@ -107,7 +103,7 @@ export async function prepareKiroIdeInstallation(
|
||||
}
|
||||
|
||||
export async function commitKiroIdeInstallation(
|
||||
prepared: PreparedKiroIdeInstallation,
|
||||
prepared: PreparedManagedInstallation,
|
||||
renameFile?: RenameFile,
|
||||
): Promise<void> {
|
||||
await commitManagedInstallation(prepared, renameFile);
|
||||
|
||||
+14
-112
@@ -1,10 +1,12 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
interface ParsedArgument {
|
||||
readonly value: string;
|
||||
readonly next: number;
|
||||
}
|
||||
import { managedScriptReference } from './common.js';
|
||||
import {
|
||||
isNodeExecutable,
|
||||
parsePosixCommand,
|
||||
parsePowerShellSource,
|
||||
posixSource,
|
||||
powerShellSource,
|
||||
} from './shell-command.js';
|
||||
|
||||
export interface LettaRuntimeReference {
|
||||
readonly agentId: string;
|
||||
@@ -12,88 +14,11 @@ export interface LettaRuntimeReference {
|
||||
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 {
|
||||
if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) {
|
||||
throw new Error('Letta Code hook commands require absolute executable and script paths');
|
||||
}
|
||||
if (process.platform === 'win32') {
|
||||
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];
|
||||
return process.platform === 'win32' ? powerShellSource(scriptPath) : posixSource(scriptPath);
|
||||
}
|
||||
|
||||
function legacyScriptPath(command: string): string | undefined {
|
||||
@@ -102,39 +27,16 @@ function legacyScriptPath(command: string): string | undefined {
|
||||
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(
|
||||
command: string,
|
||||
scriptName: string,
|
||||
): LettaRuntimeReference | undefined {
|
||||
const parsed = process.platform === 'win32'
|
||||
? parsePowerShellCommand(command)
|
||||
? parsePowerShellSource(command)
|
||||
: parsePosixCommand(command);
|
||||
if (parsed
|
||||
&& path.isAbsolute(parsed[0])
|
||||
&& isNodeExecutable(parsed[0])) {
|
||||
return runtimeReference(parsed[1], scriptName, parsed[0]);
|
||||
}
|
||||
return undefined;
|
||||
if (!parsed || !path.isAbsolute(parsed[0]) || !isNodeExecutable(parsed[0])) return undefined;
|
||||
const reference = managedScriptReference(parsed[1], scriptName);
|
||||
return reference ? { ...reference, executablePath: parsed[0] } : undefined;
|
||||
}
|
||||
|
||||
export function lettaLegacyRuntimeReference(
|
||||
@@ -142,5 +44,5 @@ export function lettaLegacyRuntimeReference(
|
||||
scriptName: string,
|
||||
): LettaRuntimeReference | undefined {
|
||||
const legacy = legacyScriptPath(command);
|
||||
return legacy ? runtimeReference(legacy, scriptName) : undefined;
|
||||
return legacy ? managedScriptReference(legacy, scriptName) : undefined;
|
||||
}
|
||||
@@ -1,9 +1,5 @@
|
||||
import {
|
||||
applyEdits,
|
||||
modify,
|
||||
type FormattingOptions,
|
||||
type JSONPath,
|
||||
} from 'jsonc-parser';
|
||||
import type { JSONPath } from 'jsonc-parser';
|
||||
import { changeJsonc } from './jsonc-edit.js';
|
||||
import type { FileSnapshot } from './managed-files.js';
|
||||
import {
|
||||
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 {
|
||||
return parseLettaDocument({
|
||||
kind: document.kind,
|
||||
@@ -124,25 +98,25 @@ function removeManagedEntries(
|
||||
for (const removal of eventRemovals) {
|
||||
const groupPath: JSONPath = ['hooks', event, removal.groupIndex];
|
||||
if (removal.removeGroup) {
|
||||
raw = change(raw, groupPath, undefined);
|
||||
raw = changeJsonc(raw, groupPath, undefined);
|
||||
continue;
|
||||
}
|
||||
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) {
|
||||
const current = currentDocument(document, raw);
|
||||
if (groupsForEvent(current.hooks, event).length === 0) {
|
||||
raw = change(raw, ['hooks', event], undefined);
|
||||
raw = changeJsonc(raw, ['hooks', event], undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
const current = currentDocument(document, raw);
|
||||
if (current.hasHooksContainer && Object.keys(current.hooks).length === 0) {
|
||||
raw = change(raw, ['hooks'], undefined);
|
||||
raw = changeJsonc(raw, ['hooks'], undefined);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
@@ -156,9 +130,9 @@ function appendGroup(
|
||||
const current = currentDocument(document, raw);
|
||||
const groups = groupsForEvent(current.hooks, event);
|
||||
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(
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { sameAgentId, samePath } from './common.js';
|
||||
import {
|
||||
buildLettaCommand,
|
||||
lettaLegacyRuntimeReference,
|
||||
lettaRuntimeReference,
|
||||
sameLettaAgentId,
|
||||
sameLettaPath,
|
||||
type LettaRuntimeReference,
|
||||
} from './letta-command.js';
|
||||
import { isObject, type JsonObject } from './strict-json.js';
|
||||
@@ -220,7 +219,7 @@ export function managedLettaRemovals(
|
||||
eventGroups(hooks, event).forEach((group, groupIndex) => {
|
||||
const handlerIndexes = group.hooks.flatMap((handler, handlerIndex) => {
|
||||
const reference = managedReference(handler, scriptName);
|
||||
return reference && (agentId === undefined || sameLettaAgentId(reference.agentId, agentId))
|
||||
return reference && (agentId === undefined || sameAgentId(reference.agentId, agentId))
|
||||
? [handlerIndex]
|
||||
: [];
|
||||
});
|
||||
@@ -248,7 +247,7 @@ function referencesForEvent(
|
||||
const reference = exactCurrentReference(handler, scriptName);
|
||||
if (!reference
|
||||
|| !reference.executablePath
|
||||
|| !sameLettaPath(reference.executablePath, process.execPath)) continue;
|
||||
|| !samePath(reference.executablePath, process.execPath)) continue;
|
||||
const key = process.platform === 'win32'
|
||||
? reference.agentId.toLowerCase()
|
||||
: reference.agentId;
|
||||
@@ -270,7 +269,7 @@ export function lettaRuntimeContracts(hooks: LettaHooks): LettaRuntimeContract[]
|
||||
const post = posts.get(key);
|
||||
const failure = failures.get(key);
|
||||
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({
|
||||
agentId: guard[0].agentId,
|
||||
guardPath: guard[0].scriptPath,
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
GUARD_SCRIPT,
|
||||
LETTA_AUDIT_OPTIONS,
|
||||
} from './letta-contract.js';
|
||||
import { sameLettaPath } from './letta-command.js';
|
||||
import { MAX_SOURCE_BYTES, samePath } from './common.js';
|
||||
import {
|
||||
lettaDocumentLabel,
|
||||
type RenderedLettaDocument,
|
||||
@@ -31,16 +31,11 @@ import {
|
||||
|
||||
const DISPLAY_NAME = 'Letta Code';
|
||||
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(
|
||||
config: InstallConfig,
|
||||
sources: LettaSources,
|
||||
): Promise<LettaRuntimePaths> {
|
||||
): Promise<ManagedRuntimePaths> {
|
||||
requireLettaHooksEnabled(sources);
|
||||
return preflightManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
@@ -54,7 +49,7 @@ export async function preflightLettaInstallation(
|
||||
|
||||
function readOnlyPreconditions(sources: LettaSources, changedPath?: string) {
|
||||
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,
|
||||
sources: LettaSources,
|
||||
rendered: RenderedLettaDocument,
|
||||
): Promise<PreparedLettaInstallation> {
|
||||
): Promise<PreparedManagedInstallation> {
|
||||
await preflightLettaInstallation(config, sources);
|
||||
const settingsSource = rendered.next ?? rendered.document.raw;
|
||||
const prepared = await prepareManagedInstallation({
|
||||
@@ -89,7 +84,7 @@ export async function prepareLettaInstallation(
|
||||
}
|
||||
|
||||
export async function commitLettaInstallation(
|
||||
prepared: PreparedLettaInstallation,
|
||||
prepared: PreparedManagedInstallation,
|
||||
renameFile?: RenameFile,
|
||||
): Promise<void> {
|
||||
await commitManagedInstallation(prepared, renameFile);
|
||||
|
||||
@@ -9,14 +9,13 @@ import {
|
||||
type LettaDocument,
|
||||
type LettaDocumentKind,
|
||||
} from './letta-config.js';
|
||||
import { hasCode, MAX_SOURCE_BYTES, pathKey, samePath } from './common.js';
|
||||
import {
|
||||
inspectPhysicalDirectory,
|
||||
readPhysicalFile,
|
||||
type FileSnapshot,
|
||||
} from './managed-files.js';
|
||||
|
||||
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
export interface LettaSourcePrecondition {
|
||||
readonly filePath: string;
|
||||
readonly label: string;
|
||||
@@ -39,15 +38,6 @@ export interface LettaSources {
|
||||
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> {
|
||||
try {
|
||||
return await fsp.realpath(filePath);
|
||||
@@ -93,7 +83,7 @@ function deduplicatePreconditions(
|
||||
): LettaSourcePrecondition[] {
|
||||
const result = new Map<string, LettaSourcePrecondition>();
|
||||
for (const value of values) {
|
||||
const key = comparisonPath(value.filePath);
|
||||
const key = pathKey(value.filePath);
|
||||
if (!result.has(key)) result.set(key, value);
|
||||
}
|
||||
return [...result.values()];
|
||||
@@ -123,7 +113,7 @@ export async function readLettaSources(): Promise<LettaSources> {
|
||||
const projectDirectory = path.join(workspace, '.letta');
|
||||
await inspectPhysicalDirectory(homeDirectory, 'Letta Code home 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');
|
||||
}
|
||||
const globalPath = path.join(globalDirectory, 'settings.json');
|
||||
@@ -133,7 +123,7 @@ export async function readLettaSources(): Promise<LettaSources> {
|
||||
canonicalPath(workspace),
|
||||
canonicalPath(homeDirectory),
|
||||
]);
|
||||
const projectActive = comparisonPath(canonicalWorkspace) !== comparisonPath(canonicalHome);
|
||||
const projectActive = !samePath(canonicalWorkspace, canonicalHome);
|
||||
const global = await readDocument('global', globalPath);
|
||||
const project = projectActive
|
||||
? await readDocument('project', projectPath)
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { constants } from 'node:fs';
|
||||
import fsp from 'node:fs/promises';
|
||||
import type { FileHandle } from 'node:fs/promises';
|
||||
|
||||
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
|
||||
import { asError, errorMessage, hasCode, MAX_SOURCE_BYTES } from './common.js';
|
||||
|
||||
export interface FileSnapshot {
|
||||
readonly contents: string;
|
||||
@@ -11,18 +10,6 @@ export interface FileSnapshot {
|
||||
readonly mode: number;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
export async function readPhysicalFile(
|
||||
filePath: string,
|
||||
label: string,
|
||||
|
||||
@@ -2,6 +2,7 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { ensurePrivateDirectory, resolvePrivateChildDirectory } from '../runtime-paths.js';
|
||||
import type { InstallConfig } from './base.js';
|
||||
import { MAX_CONFIG_BYTES, MAX_SECRET_BYTES, sameAgentId, samePath } from './common.js';
|
||||
import { generateGuardScript, type GuardScriptOptions } from './guard-template.js';
|
||||
import { generateHookScript, type HookScriptOptions } from './hook-template.js';
|
||||
import {
|
||||
@@ -19,9 +20,6 @@ import {
|
||||
} from './managed-transaction.js';
|
||||
import { parseStrictJsonObject } from './strict-json.js';
|
||||
|
||||
const MAX_SECRET_BYTES = 64 * 1024;
|
||||
const MAX_CONFIG_BYTES = 512 * 1024;
|
||||
|
||||
export interface ManagedRuntimePaths {
|
||||
readonly runtimeRoot: string;
|
||||
readonly agentDirectory: string;
|
||||
@@ -79,14 +77,6 @@ interface RuntimeArtifactLocation {
|
||||
|
||||
export type { RenameFile };
|
||||
|
||||
export function samePath(left: string, right: string): boolean {
|
||||
const normalizedLeft = path.resolve(left);
|
||||
const normalizedRight = path.resolve(right);
|
||||
return process.platform === 'win32'
|
||||
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
|
||||
: normalizedLeft === normalizedRight;
|
||||
}
|
||||
|
||||
function validateInstallConfig(config: InstallConfig, agentKey: string): void {
|
||||
for (const [field, value] of [
|
||||
['agentName', config.agentName],
|
||||
@@ -146,12 +136,6 @@ export function managedRuntimePaths(
|
||||
};
|
||||
}
|
||||
|
||||
function sameAgentId(left: unknown, right: string): boolean {
|
||||
return typeof left === 'string' && (process.platform === 'win32'
|
||||
? left.toLowerCase() === right.toLowerCase()
|
||||
: left === right);
|
||||
}
|
||||
|
||||
async function validateRuntimeIdentity(
|
||||
paths: ManagedRuntimePaths,
|
||||
agentKey: string,
|
||||
|
||||
@@ -2,12 +2,10 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { generateGuardScript, type GuardScriptOptions } from './guard-template.js';
|
||||
import { generateHookScript, type HookScriptOptions } from './hook-template.js';
|
||||
import { MAX_CONFIG_BYTES, MAX_SECRET_BYTES, sameAgentId, samePath } from './common.js';
|
||||
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
|
||||
import { samePath } from './managed-installation.js';
|
||||
import { parseStrictJsonObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
const MAX_SECRET_BYTES = 64 * 1024;
|
||||
const MAX_CONFIG_BYTES = 512 * 1024;
|
||||
const GUARD_SCRIPT = 'guard.js';
|
||||
const AUDIT_SCRIPT = 'hook.js';
|
||||
|
||||
@@ -22,10 +20,6 @@ export interface ManagedRuntimeStatusOptions {
|
||||
readonly auditOptions?: HookScriptOptions;
|
||||
}
|
||||
|
||||
function sameAgentId(left: string, right: string): boolean {
|
||||
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
|
||||
}
|
||||
|
||||
function requireString(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}`);
|
||||
@@ -117,3 +111,24 @@ export async function managedRuntimeFilesExist(
|
||||
options.auditOptions ?? { nativePayload: true },
|
||||
);
|
||||
}
|
||||
|
||||
// Presence-only check: identity mismatch reports false; parse failures still throw.
|
||||
export async function managedRuntimePresent(
|
||||
contract: ManagedRuntimeContract,
|
||||
agentKey: string,
|
||||
): Promise<boolean> {
|
||||
const agentDirectory = path.dirname(contract.guardPath);
|
||||
const configPath = path.join(agentDirectory, 'config.json');
|
||||
const snapshot = await readPhysicalFile(configPath, 'Elydora runtime config', MAX_CONFIG_BYTES);
|
||||
if (!snapshot) return false;
|
||||
const config = parseStrictJsonObject(snapshot.contents, `Elydora runtime config at ${configPath}`);
|
||||
if (config.agent_name !== agentKey || !sameAgentId(config.agent_id, contract.agentId)) {
|
||||
return false;
|
||||
}
|
||||
const files = await Promise.all([
|
||||
readPhysicalFile(contract.guardPath, 'Elydora guard runtime'),
|
||||
readPhysicalFile(contract.auditPath, 'Elydora audit runtime'),
|
||||
readPhysicalFile(path.join(agentDirectory, 'private.key'), 'Elydora private key', MAX_SECRET_BYTES),
|
||||
]);
|
||||
return files.every(Boolean);
|
||||
}
|
||||
@@ -2,14 +2,13 @@ import { randomUUID } from 'node:crypto';
|
||||
import fsp from 'node:fs/promises';
|
||||
import type { FileHandle } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { asError, errorMessage, hasCode, MAX_SOURCE_BYTES } from './common.js';
|
||||
import {
|
||||
inspectPhysicalDirectory,
|
||||
readPhysicalFile,
|
||||
type FileSnapshot,
|
||||
} from './managed-files.js';
|
||||
|
||||
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
export interface ManagedChangeSpec {
|
||||
readonly filePath: string;
|
||||
readonly label: string;
|
||||
@@ -60,18 +59,6 @@ interface StagedChange {
|
||||
|
||||
export type RenameFile = (source: string, destination: string) => Promise<void>;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
function targetKey(filePath: string): string {
|
||||
const resolved = path.resolve(filePath);
|
||||
return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
|
||||
@@ -113,16 +100,20 @@ export async function prepareManagedFileChange(
|
||||
};
|
||||
}
|
||||
|
||||
async function assertUnchanged(change: ManagedFileChange, operationName: string): Promise<void> {
|
||||
const current = await readPhysicalFile(change.filePath, change.label, change.maximumBytes);
|
||||
if ((!current && change.original)
|
||||
|| (current && !change.original)
|
||||
|| (current && change.original && (
|
||||
current.contents !== change.original.contents
|
||||
|| current.device !== change.original.device
|
||||
|| current.inode !== change.original.inode
|
||||
))) {
|
||||
throw new Error(`${change.label} changed during ${operationName}: ${change.filePath}`);
|
||||
function sameSnapshot(current: FileSnapshot | undefined, original: FileSnapshot | undefined): boolean {
|
||||
if (!current || !original) return !current && !original;
|
||||
return current.contents === original.contents
|
||||
&& current.device === original.device
|
||||
&& current.inode === original.inode;
|
||||
}
|
||||
|
||||
async function assertUnchanged(
|
||||
target: ManagedFilePrecondition,
|
||||
operationName: string,
|
||||
): Promise<void> {
|
||||
const current = await readPhysicalFile(target.filePath, target.label, target.maximumBytes);
|
||||
if (!sameSnapshot(current, target.original)) {
|
||||
throw new Error(`${target.label} changed during ${operationName}: ${target.filePath}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,20 +122,7 @@ async function assertPreconditions(
|
||||
operationName: string,
|
||||
): Promise<void> {
|
||||
for (const condition of transaction.preconditions ?? []) {
|
||||
const current = await readPhysicalFile(
|
||||
condition.filePath,
|
||||
condition.label,
|
||||
condition.maximumBytes,
|
||||
);
|
||||
if ((!current && condition.original)
|
||||
|| (current && !condition.original)
|
||||
|| (current && condition.original && (
|
||||
current.contents !== condition.original.contents
|
||||
|| current.device !== condition.original.device
|
||||
|| current.inode !== condition.original.inode
|
||||
))) {
|
||||
throw new Error(`${condition.label} changed during ${operationName}: ${condition.filePath}`);
|
||||
}
|
||||
await assertUnchanged(condition, operationName);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -285,11 +263,7 @@ async function assertCommittedUnchanged(staged: StagedChange): Promise<void> {
|
||||
}
|
||||
return;
|
||||
}
|
||||
const committed = staged.committedSnapshot;
|
||||
if (!current || !committed
|
||||
|| current.contents !== committed.contents
|
||||
|| current.device !== committed.device
|
||||
|| current.inode !== committed.inode) {
|
||||
if (!current || !sameSnapshot(current, staged.committedSnapshot)) {
|
||||
throw new Error(
|
||||
`${staged.change.label} changed during transaction recovery: ${staged.change.filePath}`,
|
||||
);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import type { HookScriptOptions } from './hook-template.js';
|
||||
import { samePath } from './managed-installation.js';
|
||||
import { errorMessage, samePath } from './common.js';
|
||||
import { isNodeExecutable } from './shell-command.js';
|
||||
import { parseStrictJsonObject } from './strict-json.js';
|
||||
|
||||
export const AGENT_KEY = 'opencode';
|
||||
@@ -51,10 +52,6 @@ interface OpenCodePluginMetadata {
|
||||
readonly auditPath: string;
|
||||
}
|
||||
|
||||
export function sameOpenCodeAgentId(left: string, right: string): boolean {
|
||||
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
|
||||
}
|
||||
|
||||
export function resolveOpenCodePaths(
|
||||
homeDirectory = os.homedir(),
|
||||
xdgConfigHome = process.env.XDG_CONFIG_HOME,
|
||||
@@ -83,11 +80,6 @@ function validAgentSegment(agentId: string): boolean {
|
||||
&& 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 {
|
||||
if (!validAgentSegment(metadata.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(
|
||||
filePath: string,
|
||||
source: string,
|
||||
|
||||
@@ -7,8 +7,8 @@ import {
|
||||
OPENCODE_AUDIT_OPTIONS,
|
||||
buildOpenCodeMetadata,
|
||||
buildOpenCodePlugin,
|
||||
sameOpenCodeAgentId,
|
||||
} from './opencode-contract.js';
|
||||
import { sameAgentId } from './common.js';
|
||||
import type { OpenCodePluginFile, OpenCodeSources } from './opencode-io.js';
|
||||
import {
|
||||
commitManagedInstallation,
|
||||
@@ -29,14 +29,10 @@ import {
|
||||
const DISPLAY_NAME = 'OpenCode';
|
||||
const DIRECTORY_LABEL = 'OpenCode plugins directory';
|
||||
|
||||
export type OpenCodeRuntimePaths = ManagedRuntimePaths;
|
||||
export type PreparedOpenCodeInstallation = PreparedManagedInstallation;
|
||||
export type { RenameFile };
|
||||
|
||||
export async function preflightOpenCodeInstallation(
|
||||
config: InstallConfig,
|
||||
sources: OpenCodeSources,
|
||||
): Promise<OpenCodeRuntimePaths> {
|
||||
): Promise<ManagedRuntimePaths> {
|
||||
return preflightManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
hookLocations: [{
|
||||
@@ -50,7 +46,7 @@ export async function preflightOpenCodeInstallation(
|
||||
export async function prepareOpenCodeInstallation(
|
||||
config: InstallConfig,
|
||||
sources: OpenCodeSources,
|
||||
): Promise<PreparedOpenCodeInstallation> {
|
||||
): Promise<PreparedManagedInstallation> {
|
||||
const paths = await preflightOpenCodeInstallation(config, sources);
|
||||
const metadata = buildOpenCodeMetadata(
|
||||
config.agentId,
|
||||
@@ -85,7 +81,7 @@ export async function prepareOpenCodeInstallation(
|
||||
}
|
||||
|
||||
export async function commitOpenCodeInstallation(
|
||||
prepared: PreparedOpenCodeInstallation,
|
||||
prepared: PreparedManagedInstallation,
|
||||
renameFile?: RenameFile,
|
||||
): Promise<void> {
|
||||
await commitManagedInstallation(prepared, renameFile);
|
||||
@@ -96,7 +92,7 @@ function ownedByAgent<TContract extends { readonly agentId: string }>(
|
||||
agentId?: string,
|
||||
): boolean {
|
||||
return file.contract !== undefined
|
||||
&& (agentId === undefined || sameOpenCodeAgentId(file.contract.agentId, agentId));
|
||||
&& (agentId === undefined || sameAgentId(file.contract.agentId, agentId));
|
||||
}
|
||||
|
||||
export async function prepareOpenCodeUninstall(
|
||||
|
||||
@@ -9,11 +9,10 @@ import {
|
||||
type OpenCodePaths,
|
||||
type OpenCodeRuntimeContract,
|
||||
} from './opencode-contract.js';
|
||||
import { errorMessage, hasCode, MAX_CONFIG_BYTES } from './common.js';
|
||||
import { inspectPhysicalDirectory, readPhysicalFile, type FileSnapshot } from './managed-files.js';
|
||||
import { managedRuntimeFilesExist } from './managed-runtime-status.js';
|
||||
|
||||
const MAX_PLUGIN_BYTES = 512 * 1024;
|
||||
|
||||
export interface OpenCodePluginFile<TContract> {
|
||||
readonly exists: boolean;
|
||||
readonly filePath: string;
|
||||
@@ -40,7 +39,7 @@ async function readPluginFile<TContract>(
|
||||
label: string,
|
||||
parse: (filePath: string, source: string) => TContract | undefined,
|
||||
): 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 };
|
||||
return {
|
||||
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> {
|
||||
try {
|
||||
return (await fsp.stat(filePath)).isFile();
|
||||
} catch (error) {
|
||||
if (hasCode(error, 'ENOENT') || hasCode(error, 'ENOTDIR')) return false;
|
||||
throw new Error(`Inspect OpenCode Node.js runtime at ${filePath}: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`, { cause: error instanceof Error ? error : new Error(String(error)) });
|
||||
throw new Error(`Inspect OpenCode Node.js runtime at ${filePath}: ${errorMessage(error)}`, {
|
||||
cause: error instanceof Error ? error : new Error(String(error)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+13
-106
@@ -1,103 +1,20 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { managedScriptReference, type ManagedScriptReference } from './common.js';
|
||||
import {
|
||||
isNodeExecutable,
|
||||
parsePosixCommand,
|
||||
parsePowerShellSource,
|
||||
posixSource,
|
||||
powerShellSource,
|
||||
} from './shell-command.js';
|
||||
|
||||
interface ParsedArgument {
|
||||
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 type QwenRuntimeReference = ManagedScriptReference;
|
||||
|
||||
export function buildQwenCommand(scriptPath: string): string {
|
||||
if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) {
|
||||
throw new Error('Qwen Code hook commands require absolute executable and script paths');
|
||||
}
|
||||
if (process.platform === 'win32') {
|
||||
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';
|
||||
return process.platform === 'win32' ? powerShellSource(scriptPath) : posixSource(scriptPath);
|
||||
}
|
||||
|
||||
export function qwenRuntimeReference(
|
||||
@@ -105,18 +22,8 @@ export function qwenRuntimeReference(
|
||||
scriptName: string,
|
||||
): QwenRuntimeReference | undefined {
|
||||
const parsed = process.platform === 'win32'
|
||||
? parsePowerShellCommand(command)
|
||||
? parsePowerShellSource(command)
|
||||
: parsePosixCommand(command);
|
||||
if (!parsed
|
||||
|| !path.isAbsolute(parsed[0])
|
||||
|| !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] };
|
||||
if (!parsed || !path.isAbsolute(parsed[0]) || !isNodeExecutable(parsed[0])) return undefined;
|
||||
return managedScriptReference(parsed[1], scriptName);
|
||||
}
|
||||
+10
-86
@@ -1,25 +1,15 @@
|
||||
import {
|
||||
applyEdits,
|
||||
modify,
|
||||
parse,
|
||||
parseTree,
|
||||
printParseErrorCode,
|
||||
type FormattingOptions,
|
||||
type JSONPath,
|
||||
type Node,
|
||||
type ParseError,
|
||||
} from 'jsonc-parser';
|
||||
import type { JSONPath } from 'jsonc-parser';
|
||||
import type { FileSnapshot } from './managed-files.js';
|
||||
import { changeJsonc } from './jsonc-edit.js';
|
||||
import {
|
||||
MANAGED_EVENTS,
|
||||
managedQwenRemovals,
|
||||
readQwenHooks,
|
||||
type JsonObject,
|
||||
type ManagedQwenEvent,
|
||||
type QwenGroup,
|
||||
type QwenHooks,
|
||||
isObject,
|
||||
} from './qwen-contract.js';
|
||||
import { isObject, parseCommentedJsonObject, type JsonObject } from './strict-json.js';
|
||||
|
||||
export const QWEN_OWNED_FILE_MARKER = '// Managed by Elydora';
|
||||
|
||||
@@ -53,50 +43,6 @@ interface DocumentOptions {
|
||||
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 {
|
||||
switch (kind) {
|
||||
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 {
|
||||
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') {
|
||||
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 {
|
||||
return parseQwenDocument({
|
||||
kind: document.kind,
|
||||
@@ -195,25 +119,25 @@ function removeManagedEntries(
|
||||
for (const removal of eventRemovals) {
|
||||
const groupPath: JSONPath = ['hooks', event, removal.groupIndex];
|
||||
if (removal.removeGroup) {
|
||||
raw = change(raw, groupPath, undefined);
|
||||
raw = changeJsonc(raw, groupPath, undefined);
|
||||
continue;
|
||||
}
|
||||
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) {
|
||||
const current = currentDocument(document, raw);
|
||||
if ((current.hooks[event] ?? []).length === 0) {
|
||||
raw = change(raw, ['hooks', event], undefined);
|
||||
raw = changeJsonc(raw, ['hooks', event], undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
const current = currentDocument(document, raw);
|
||||
if (current.hasHooksContainer && Object.keys(current.hooks).length === 0) {
|
||||
raw = change(raw, ['hooks'], undefined);
|
||||
raw = changeJsonc(raw, ['hooks'], undefined);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
@@ -226,9 +150,9 @@ function appendGroup(
|
||||
): string {
|
||||
const current = currentDocument(document, raw);
|
||||
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(
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { sameAgentId, samePath } from './common.js';
|
||||
import {
|
||||
buildQwenCommand,
|
||||
qwenRuntimeReference,
|
||||
sameQwenAgentId,
|
||||
sameQwenPath,
|
||||
type QwenRuntimeReference,
|
||||
} from './qwen-command.js';
|
||||
import { isObject, type JsonObject } from './strict-json.js';
|
||||
@@ -283,7 +282,7 @@ export function managedQwenRemovals(
|
||||
(hooks[event] ?? []).forEach((group, groupIndex) => {
|
||||
const handlerIndexes = group.hooks.flatMap((handler, handlerIndex) => {
|
||||
const reference = managedReference(handler, scriptName, hookName, true);
|
||||
return reference && (agentId === undefined || sameQwenAgentId(reference.agentId, agentId))
|
||||
return reference && (agentId === undefined || sameAgentId(reference.agentId, agentId))
|
||||
? [handlerIndex]
|
||||
: [];
|
||||
});
|
||||
@@ -334,7 +333,7 @@ export function qwenRuntimeContracts(hooks: QwenHooks): QwenRuntimeContract[] {
|
||||
const post = posts.get(key);
|
||||
const failure = failures.get(key);
|
||||
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({
|
||||
agentId: guard[0].agentId,
|
||||
guardPath: guard[0].scriptPath,
|
||||
@@ -343,5 +342,3 @@ export function qwenRuntimeContracts(hooks: QwenHooks): QwenRuntimeContract[] {
|
||||
}
|
||||
return contracts;
|
||||
}
|
||||
|
||||
export { isObject, type JsonObject };
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
AUDIT_SCRIPT,
|
||||
GUARD_SCRIPT,
|
||||
} from './qwen-contract.js';
|
||||
import { sameQwenPath } from './qwen-command.js';
|
||||
import { MAX_SOURCE_BYTES, samePath } from './common.js';
|
||||
import {
|
||||
qwenDocumentLabel,
|
||||
type RenderedQwenDocument,
|
||||
@@ -30,16 +30,11 @@ import {
|
||||
|
||||
const DISPLAY_NAME = 'Qwen Code';
|
||||
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(
|
||||
config: InstallConfig,
|
||||
sources: QwenSources,
|
||||
): Promise<QwenRuntimePaths> {
|
||||
): Promise<ManagedRuntimePaths> {
|
||||
requireQwenHooksEnabled(sources);
|
||||
return preflightManagedInstallation({
|
||||
agentKey: AGENT_KEY,
|
||||
@@ -53,7 +48,7 @@ export async function preflightQwenInstallation(
|
||||
|
||||
function readOnlyPreconditions(sources: QwenSources, changedPath?: string) {
|
||||
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,
|
||||
sources: QwenSources,
|
||||
rendered: RenderedQwenDocument,
|
||||
): Promise<PreparedQwenInstallation> {
|
||||
): Promise<PreparedManagedInstallation> {
|
||||
await preflightQwenInstallation(config, sources);
|
||||
const settingsSource = rendered.next ?? rendered.document.raw;
|
||||
const prepared = await prepareManagedInstallation({
|
||||
@@ -88,7 +83,7 @@ export async function prepareQwenInstallation(
|
||||
}
|
||||
|
||||
export async function commitQwenInstallation(
|
||||
prepared: PreparedQwenInstallation,
|
||||
prepared: PreparedManagedInstallation,
|
||||
renameFile?: RenameFile,
|
||||
): Promise<void> {
|
||||
await commitManagedInstallation(prepared, renameFile);
|
||||
|
||||
+3
-91
@@ -1,99 +1,11 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
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 },
|
||||
);
|
||||
}
|
||||
import { AGENT_KEY, type QwenRuntimeContract } from './qwen-contract.js';
|
||||
import { managedRuntimeFilesExist } from './managed-runtime-status.js';
|
||||
|
||||
export async function qwenRuntimeFilesExist(
|
||||
contracts: readonly QwenRuntimeContract[],
|
||||
): Promise<boolean> {
|
||||
for (const contract of contracts) {
|
||||
if (await runtimeContractExists(contract)) return true;
|
||||
if (await managedRuntimeFilesExist(contract, AGENT_KEY)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -2,18 +2,17 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import fsp from 'node:fs/promises';
|
||||
import { parse as parseDotenv } from 'dotenv';
|
||||
import { MAX_SOURCE_BYTES, pathKey, samePath } from './common.js';
|
||||
import {
|
||||
createQwenDocument,
|
||||
parseQwenDocument,
|
||||
parseQwenJsoncObject,
|
||||
qwenDocumentLabel,
|
||||
qwenSourceLabel,
|
||||
type QwenDocument,
|
||||
type QwenDocumentKind,
|
||||
} from './qwen-config.js';
|
||||
import { readPhysicalFile, type FileSnapshot } from './managed-files.js';
|
||||
|
||||
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
|
||||
import { parseCommentedJsonObject } from './strict-json.js';
|
||||
const HOME_ENV_KEYS = ['QWEN_HOME', 'QWEN_RUNTIME_DIR'] as const;
|
||||
|
||||
export interface QwenSourcePrecondition {
|
||||
@@ -94,7 +93,7 @@ async function resolveQwenRouting(): Promise<RoutingResult> {
|
||||
|
||||
const readCandidate = async (filePath: string): Promise<void> => {
|
||||
const resolved = path.resolve(filePath);
|
||||
const key = process.platform === 'win32' ? resolved.toLowerCase() : resolved;
|
||||
const key = pathKey(resolved);
|
||||
if (visited.has(key)) return;
|
||||
visited.add(key);
|
||||
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 {
|
||||
const relative = path.relative(comparisonPath(parent), comparisonPath(child));
|
||||
const relative = path.relative(pathKey(parent), pathKey(child));
|
||||
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
|
||||
}
|
||||
|
||||
@@ -202,7 +196,7 @@ async function workspaceTrust(
|
||||
original: snapshot,
|
||||
};
|
||||
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)) {
|
||||
if (!['TRUST_FOLDER', 'TRUST_PARENT', 'DO_NOT_TRUST'].includes(String(level))) {
|
||||
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)) {
|
||||
if (level === 'DO_NOT_TRUST'
|
||||
&& comparisonPath(workspace) === comparisonPath(await canonicalPath(rulePath))) {
|
||||
&& samePath(workspace, await canonicalPath(rulePath))) {
|
||||
return { trusted: false, precondition };
|
||||
}
|
||||
}
|
||||
@@ -256,7 +250,7 @@ function deduplicatePreconditions(
|
||||
): QwenSourcePrecondition[] {
|
||||
const result = new Map<string, QwenSourcePrecondition>();
|
||||
for (const value of values) {
|
||||
const key = comparisonPath(value.filePath);
|
||||
const key = pathKey(value.filePath);
|
||||
if (!result.has(key)) result.set(key, value);
|
||||
}
|
||||
return [...result.values()];
|
||||
@@ -276,7 +270,7 @@ export async function readQwenSources(): Promise<QwenSources> {
|
||||
canonicalPath(process.cwd()),
|
||||
canonicalPath(os.homedir()),
|
||||
]);
|
||||
const workspaceActive = comparisonPath(canonicalWorkspace) !== comparisonPath(canonicalHome);
|
||||
const workspaceActive = !samePath(canonicalWorkspace, canonicalHome);
|
||||
const workspace = workspaceActive
|
||||
? await readDocument('workspace', workspacePath)
|
||||
: createQwenDocument('workspace', workspacePath);
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import path from 'node:path';
|
||||
import { samePath } from './common.js';
|
||||
|
||||
export interface ParsedArgument {
|
||||
readonly value: string;
|
||||
readonly next: number;
|
||||
}
|
||||
|
||||
export type CommandParts = readonly [executable: string, script: string];
|
||||
|
||||
const POSIX_APOSTROPHE = `'"'"'`;
|
||||
const POWERSHELL_EXIT_SUFFIX = '; exit $LASTEXITCODE';
|
||||
const ENCODED_COMMAND_FLAGS = '-NoLogo -NoProfile -NonInteractive -EncodedCommand';
|
||||
|
||||
export function quotePosix(value: string): string {
|
||||
return `'${value.replaceAll("'", POSIX_APOSTROPHE)}'`;
|
||||
}
|
||||
|
||||
export function quotePowerShell(value: string): string {
|
||||
return `'${value.replaceAll("'", "''")}'`;
|
||||
}
|
||||
|
||||
export 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');
|
||||
}
|
||||
|
||||
export function posixSource(scriptPath: string): string {
|
||||
return `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`;
|
||||
}
|
||||
|
||||
export function powerShellSource(scriptPath: string): string {
|
||||
return `& ${quotePowerShell(process.execPath)} ${quotePowerShell(scriptPath)}${POWERSHELL_EXIT_SUFFIX}`;
|
||||
}
|
||||
|
||||
export function encodePowerShellSource(scriptPath: string): string {
|
||||
return Buffer.from(powerShellSource(scriptPath), 'utf16le').toString('base64');
|
||||
}
|
||||
|
||||
export function encodedWindowsCommand(scriptPath: string): string {
|
||||
return `"${windowsPowerShellPath()}" ${ENCODED_COMMAND_FLAGS} ${encodePowerShellSource(scriptPath)}`;
|
||||
}
|
||||
|
||||
// The running executable, or a binary named node (node.exe case-insensitive on Windows).
|
||||
export function isNodeExecutable(filePath: string): boolean {
|
||||
if (samePath(filePath, process.execPath)) return true;
|
||||
const basename = path.basename(filePath);
|
||||
return basename === 'node' || basename.toLowerCase() === 'node.exe';
|
||||
}
|
||||
|
||||
export function isPowerShellExecutable(filePath: string): boolean {
|
||||
return path.win32.isAbsolute(filePath)
|
||||
&& path.win32.basename(filePath).toLowerCase() === 'powershell.exe';
|
||||
}
|
||||
|
||||
export function readPosixArgument(command: string, start: number): ParsedArgument | undefined {
|
||||
if (command[start] !== "'") return undefined;
|
||||
let value = '';
|
||||
for (let index = start + 1; index < command.length;) {
|
||||
if (command.startsWith(POSIX_APOSTROPHE, index)) {
|
||||
value += "'";
|
||||
index += POSIX_APOSTROPHE.length;
|
||||
continue;
|
||||
}
|
||||
if (command[index] === "'") return { value, next: index + 1 };
|
||||
value += command[index];
|
||||
index += 1;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function parsePosixCommand(command: string): CommandParts | 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;
|
||||
}
|
||||
|
||||
export function parsePowerShellSource(source: string): CommandParts | 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) !== POWERSHELL_EXIT_SUFFIX) return undefined;
|
||||
return [executable.value, script.value];
|
||||
}
|
||||
|
||||
export function decodePowerShellSource(encoded: string): CommandParts | undefined {
|
||||
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) return undefined;
|
||||
const buffer = Buffer.from(encoded, 'base64');
|
||||
if (buffer.toString('base64') !== encoded || buffer.length % 2 !== 0) return undefined;
|
||||
return parsePowerShellSource(buffer.toString('utf16le'));
|
||||
}
|
||||
|
||||
export function parseEncodedWindowsCommand(command: string): CommandParts | undefined {
|
||||
const match = /^"([^"\r\n]+)" -NoLogo -NoProfile -NonInteractive -EncodedCommand ([A-Za-z0-9+/]+={0,2})$/.exec(command);
|
||||
if (!match || !isPowerShellExecutable(match[1])) return undefined;
|
||||
return decodePowerShellSource(match[2]);
|
||||
}
|
||||
|
||||
export function parseLegacyWindowsCommand(command: string): CommandParts | undefined {
|
||||
const match = /^"([^"\r\n]+)" "([^"\r\n]+)"$/.exec(command);
|
||||
return match ? [match[1], match[2]] : undefined;
|
||||
}
|
||||
@@ -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 {
|
||||
return parseJsonObject(raw, label, {
|
||||
allowTrailingComma: true,
|
||||
|
||||
+34
-31
@@ -1,7 +1,3 @@
|
||||
// ---------------------------------------------------------------------------
|
||||
// Enums / status types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type AgentStatus = 'active' | 'frozen' | 'revoked';
|
||||
export type KeyStatus = 'active' | 'retired' | 'revoked';
|
||||
export type ExportStatus = 'queued' | 'running' | 'done' | 'failed';
|
||||
@@ -37,13 +33,16 @@ export type AdminAction =
|
||||
| 'agent.register' | 'agent.update' | 'agent.freeze' | 'agent.unfreeze'
|
||||
| 'agent.revoke' | 'agent.delete' | 'key.revoke' | 'export.create'
|
||||
| 'org.create' | 'org.update'
|
||||
| 'member.invite' | 'member.remove' | 'member.role_change'
|
||||
| 'agent.assign' | 'agent.unassign';
|
||||
| 'member.invite' | 'invitation.cancel' | 'member.remove' | 'member.role_change'
|
||||
| 'agent.assign' | 'agent.unassign'
|
||||
| 'webhook.register' | 'webhook.delete';
|
||||
export type ErrorCode =
|
||||
| 'INVALID_SIGNATURE'
|
||||
| 'UNKNOWN_AGENT'
|
||||
| 'KEY_REVOKED'
|
||||
| 'KEY_RETIRED'
|
||||
| 'AGENT_FROZEN'
|
||||
| 'AGENT_REVOKED'
|
||||
| 'TTL_EXPIRED'
|
||||
| 'REPLAY_DETECTED'
|
||||
| 'PREV_HASH_MISMATCH'
|
||||
@@ -55,10 +54,6 @@ export type ErrorCode =
|
||||
| 'NOT_FOUND'
|
||||
| 'VALIDATION_ERROR';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Entities
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface Agent {
|
||||
readonly agent_id: string;
|
||||
readonly org_id: string;
|
||||
@@ -168,10 +163,6 @@ export interface Export {
|
||||
readonly completed_at: number | null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Protocol types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface EOR {
|
||||
readonly op_version: '1.0';
|
||||
readonly operation_id: string;
|
||||
@@ -205,10 +196,6 @@ export interface EAR {
|
||||
readonly elydora_signature: string;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// API request/response types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface RegisterAgentRequest {
|
||||
readonly agent_id: string;
|
||||
readonly integration_type: IntegrationType;
|
||||
@@ -238,6 +225,7 @@ export interface SubmitOperationResponse {
|
||||
export interface GetOperationResponse {
|
||||
readonly operation: Operation;
|
||||
readonly receipt?: Receipt;
|
||||
readonly payload?: Record<string, unknown> | string;
|
||||
}
|
||||
|
||||
export interface VerifyOperationResponse {
|
||||
@@ -327,15 +315,22 @@ export interface DeleteAgentResponse {
|
||||
readonly deleted: boolean;
|
||||
}
|
||||
|
||||
export interface Webhook {
|
||||
readonly webhook_id: string;
|
||||
readonly org_id: string;
|
||||
readonly endpoint_url: string;
|
||||
readonly events: string[];
|
||||
readonly status: 'active' | 'disabled';
|
||||
readonly created_at: number;
|
||||
readonly updated_at: number;
|
||||
}
|
||||
|
||||
export interface ListWebhooksResponse {
|
||||
readonly webhooks: unknown[];
|
||||
readonly webhooks: Webhook[];
|
||||
}
|
||||
|
||||
export interface RegisterWebhookResponse {
|
||||
readonly webhook_id: string;
|
||||
readonly endpoint_url: string;
|
||||
readonly events: string[];
|
||||
readonly created_at: number;
|
||||
readonly webhook: Webhook;
|
||||
}
|
||||
|
||||
export interface ListMembersResponse {
|
||||
@@ -357,16 +352,26 @@ export interface DeepHealthResponse {
|
||||
readonly status: 'healthy' | 'degraded';
|
||||
readonly version: string;
|
||||
readonly protocol_version: string;
|
||||
readonly capabilities: Record<string, string>;
|
||||
readonly timestamp: number;
|
||||
readonly dependencies: {
|
||||
readonly d1: { status: 'ok' | 'failed'; latency_ms: number; error?: string };
|
||||
readonly r2: { status: 'ok' | 'failed'; latency_ms: number; error?: string };
|
||||
readonly kv: { status: 'ok' | 'failed'; latency_ms: number; error?: string };
|
||||
readonly d1: { status: 'ok' | 'failed'; latency_ms: number };
|
||||
readonly auth_storage: { status: 'ok' | 'failed'; latency_ms: number; contract_phase?: 'expand' | 'contract' };
|
||||
readonly r2: { status: 'ok' | 'failed'; latency_ms: number };
|
||||
readonly kv: { status: 'ok' | 'failed'; latency_ms: number };
|
||||
};
|
||||
}
|
||||
|
||||
export interface GetMeResponse {
|
||||
readonly user: User;
|
||||
readonly user: Omit<User, 'org_id'> & {
|
||||
readonly org_id: string | null;
|
||||
readonly onboarding_completed: boolean;
|
||||
};
|
||||
readonly current_organization: {
|
||||
readonly org_id: string | null;
|
||||
readonly ba_org_id: string | null;
|
||||
readonly role: RbacRole;
|
||||
};
|
||||
}
|
||||
|
||||
export interface IssueApiTokenResponse {
|
||||
@@ -379,12 +384,14 @@ export interface RotateApiTokenResponse {
|
||||
readonly token: string;
|
||||
readonly expires_at: number | null;
|
||||
readonly token_id: string;
|
||||
readonly previous_token_grace_until: number;
|
||||
}
|
||||
|
||||
export interface HealthResponse {
|
||||
readonly status: string;
|
||||
readonly version: string;
|
||||
readonly protocol_version: string;
|
||||
readonly capabilities: Record<string, string>;
|
||||
readonly timestamp: number;
|
||||
}
|
||||
|
||||
@@ -421,10 +428,6 @@ export interface ErrorResponse {
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Client configuration
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface ElydoraClientConfig {
|
||||
readonly orgId: string;
|
||||
readonly agentId: string;
|
||||
|
||||
+1
-19
@@ -1,17 +1,10 @@
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
/**
|
||||
* Generate a UUIDv7 (time-ordered UUID per RFC 9562).
|
||||
*
|
||||
* Layout (128 bits):
|
||||
* 48-bit Unix timestamp (ms) | 4-bit version (7) | 12-bit rand_a
|
||||
* 2-bit variant (10) | 62-bit rand_b
|
||||
*/
|
||||
// UUIDv7 (RFC 9562): 48-bit ms timestamp, version 7, variant 10, 74 random bits
|
||||
export function uuidv7(): string {
|
||||
const now = Date.now();
|
||||
const random = crypto.randomBytes(10);
|
||||
|
||||
// Bytes 0-5: 48-bit timestamp (ms)
|
||||
const bytes = Buffer.alloc(16);
|
||||
bytes[0] = (now / 2 ** 40) & 0xff;
|
||||
bytes[1] = (now / 2 ** 32) & 0xff;
|
||||
@@ -20,11 +13,9 @@ export function uuidv7(): string {
|
||||
bytes[4] = (now / 2 ** 8) & 0xff;
|
||||
bytes[5] = now & 0xff;
|
||||
|
||||
// Bytes 6-7: version (0111) + 12 bits random
|
||||
bytes[6] = 0x70 | (random[0]! & 0x0f);
|
||||
bytes[7] = random[1]!;
|
||||
|
||||
// Bytes 8-15: variant (10) + 62 bits random
|
||||
bytes[8] = 0x80 | (random[2]! & 0x3f);
|
||||
bytes[9] = random[3]!;
|
||||
bytes[10] = random[4]!;
|
||||
@@ -44,25 +35,16 @@ export function uuidv7(): string {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a random nonce: 16 random bytes, base64url encoded.
|
||||
*/
|
||||
export function generateNonce(): string {
|
||||
const bytes = crypto.randomBytes(16);
|
||||
return base64urlEncode(bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode a Buffer or Uint8Array to base64url (no padding, RFC 4648 section 5).
|
||||
*/
|
||||
export function base64urlEncode(data: Buffer | Uint8Array): string {
|
||||
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
|
||||
return buf.toString('base64url');
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode a base64url string (no padding) to a Buffer.
|
||||
*/
|
||||
export function base64urlDecode(input: string): Buffer {
|
||||
return Buffer.from(input, 'base64url');
|
||||
}
|
||||
@@ -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 { 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 const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/augment.js')).href;
|
||||
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href;
|
||||
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/augment-io.js')).href;
|
||||
export const installationModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/augment-installation.js'),
|
||||
).href;
|
||||
export const managedInstallationModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/managed-installation.js'),
|
||||
).href;
|
||||
export const cliPath = path.resolve('dist/cli.js');
|
||||
export {
|
||||
VALID_PRIVATE_KEY,
|
||||
cliPath,
|
||||
managedInstallationModuleUrl,
|
||||
readSettings,
|
||||
registryModuleUrl,
|
||||
runNode,
|
||||
runProcess,
|
||||
startApiServer,
|
||||
writeJson,
|
||||
} 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 guardWrapperName = `augment-guard${wrapperExtension}`;
|
||||
export const auditWrapperName = `augment-hook${wrapperExtension}`;
|
||||
|
||||
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);
|
||||
}
|
||||
const PLUGIN = { exportName: 'augmentPlugin', moduleUrl: pluginModuleUrl };
|
||||
|
||||
export function runHandler(handler, input, fixture) {
|
||||
return new Promise((resolve, reject) => {
|
||||
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 });
|
||||
return runShell(handler.command, homeEnvironment(fixture), fixture.projectDir, input);
|
||||
}
|
||||
|
||||
export function installConfig(fixture, overrides = {}) {
|
||||
return {
|
||||
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,
|
||||
};
|
||||
return baseInstallConfig('augment', fixture, overrides);
|
||||
}
|
||||
|
||||
export async function runPlugin(fixture, method, argument) {
|
||||
const source = `
|
||||
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 function runPlugin(fixture, method, argument) {
|
||||
return basePlugin(PLUGIN, fixture, method, argument);
|
||||
}
|
||||
|
||||
export async function createFixture({ baseUrl = 'http://127.0.0.1:9', settings } = {}) {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-augment-'));
|
||||
const homeDir = path.join(rootDir, "home with spaces and 'quote %AUGGIE%");
|
||||
const projectDir = path.join(rootDir, 'project with spaces');
|
||||
const settingsPath = path.join(homeDir, '.augment', 'settings.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 (settings !== undefined) await writeJson(settingsPath, settings);
|
||||
const fixture = {
|
||||
agentDir,
|
||||
auditWrapperPath: path.join(agentDir, auditWrapperName),
|
||||
const base = await createFixtureRoot('elydora-augment-', "home with spaces and 'quote %AUGGIE%");
|
||||
const settingsPath = path.join(base.homeDir, '.augment', 'settings.json');
|
||||
await writeOptionalJson(settingsPath, settings);
|
||||
return {
|
||||
...base,
|
||||
auditWrapperPath: path.join(base.agentDir, auditWrapperName),
|
||||
baseUrl,
|
||||
guardScriptPath,
|
||||
guardWrapperPath: path.join(agentDir, guardWrapperName),
|
||||
homeDir,
|
||||
hookScriptPath,
|
||||
projectDir,
|
||||
rootDir,
|
||||
guardWrapperPath: path.join(base.agentDir, guardWrapperName),
|
||||
settingsPath,
|
||||
install(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) {
|
||||
@@ -150,34 +70,3 @@ export function managedHandler(settings, event, wrapperPath) {
|
||||
}
|
||||
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());
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -1,38 +1,32 @@
|
||||
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 {
|
||||
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 const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/claudecode.js')).href;
|
||||
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href;
|
||||
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/claudecode-io.js')).href;
|
||||
export const installationModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/claudecode-installation.js'),
|
||||
).href;
|
||||
export const cliPath = path.resolve('dist/cli.js');
|
||||
export {
|
||||
VALID_PRIVATE_KEY,
|
||||
cliPath,
|
||||
readSettings,
|
||||
registryModuleUrl,
|
||||
startApiServer,
|
||||
writeJson,
|
||||
} 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 = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
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);
|
||||
});
|
||||
return baseProcess(command, 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.args,
|
||||
{
|
||||
HOME: fixture.homeDir,
|
||||
USERPROFILE: fixture.homeDir,
|
||||
...homeEnvironment(fixture),
|
||||
CLAUDE_CONFIG_DIR: fixture.claudeConfigOverride ?? '',
|
||||
...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 = {}) {
|
||||
return {
|
||||
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,
|
||||
};
|
||||
return baseInstallConfig('claudecode', fixture, overrides);
|
||||
}
|
||||
|
||||
export async function runPlugin(fixture, method, argument, environment = {}) {
|
||||
const source = `
|
||||
import { claudecodePlugin } from ${JSON.stringify(pluginModuleUrl)};
|
||||
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT);
|
||||
const result = await claudecodePlugin[process.env.ELYDORA_TEST_METHOD](argument);
|
||||
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 function runPlugin(fixture, method, argument, environment = {}) {
|
||||
const configDir = optionalEnvironment('CLAUDE_CONFIG_DIR', fixture.claudeConfigOverride);
|
||||
return basePlugin(PLUGIN, fixture, method, argument, {
|
||||
env: { ...environment, ...configDir.env },
|
||||
unset: configDir.unset,
|
||||
});
|
||||
}
|
||||
|
||||
export async function createFixture({
|
||||
@@ -106,42 +64,25 @@ export async function createFixture({
|
||||
settings,
|
||||
explicitClaudeConfig = true,
|
||||
} = {}) {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-claude-'));
|
||||
const homeDir = path.join(rootDir, "home with spaces and 'quote %CLAUDE_HOOK_EVENT%");
|
||||
const projectDir = path.join(rootDir, 'project with spaces');
|
||||
const base = await createFixtureRoot(
|
||||
'elydora-claude-',
|
||||
"home with spaces and 'quote %CLAUDE_HOOK_EVENT%",
|
||||
);
|
||||
const claudeConfigDir = explicitClaudeConfig
|
||||
? path.join(homeDir, 'custom claude')
|
||||
: path.join(homeDir, '.claude');
|
||||
? path.join(base.homeDir, 'custom claude')
|
||||
: path.join(base.homeDir, '.claude');
|
||||
const settingsPath = path.join(claudeConfigDir, 'settings.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 (settings !== undefined) await writeJson(settingsPath, settings);
|
||||
const fixture = {
|
||||
agentDir,
|
||||
await writeOptionalJson(settingsPath, settings);
|
||||
return {
|
||||
...base,
|
||||
baseUrl,
|
||||
claudeConfigDir,
|
||||
claudeConfigOverride: explicitClaudeConfig ? claudeConfigDir : undefined,
|
||||
guardScriptPath,
|
||||
homeDir,
|
||||
hookScriptPath,
|
||||
projectDir,
|
||||
rootDir,
|
||||
settingsPath,
|
||||
install(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) {
|
||||
@@ -173,34 +114,3 @@ export function assertManagedHandler(handler, scriptPath, statusMessage) {
|
||||
export function legacyHandler(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());
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -1,87 +1,39 @@
|
||||
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 { mkdir, writeFile } from 'node:fs/promises';
|
||||
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 const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/cline.js')).href;
|
||||
export const contractModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/cline-contract.js'),
|
||||
).href;
|
||||
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/cline-io.js')).href;
|
||||
export const installationModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/cline-installation.js'),
|
||||
).href;
|
||||
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href;
|
||||
export const cliPath = path.resolve('dist/cli.js');
|
||||
export {
|
||||
VALID_PRIVATE_KEY,
|
||||
cliPath,
|
||||
readJson,
|
||||
registryModuleUrl,
|
||||
runNode,
|
||||
runProcess,
|
||||
startApiServer,
|
||||
} from './harness.mjs';
|
||||
|
||||
export function runProcess(command, args, env, cwd, input = '') {
|
||||
return new Promise((resolve, reject) => {
|
||||
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,
|
||||
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 const pluginModuleUrl = distUrl('plugins/cline.js');
|
||||
export const contractModuleUrl = distUrl('plugins/cline-contract.js');
|
||||
export const ioModuleUrl = distUrl('plugins/cline-io.js');
|
||||
export const installationModuleUrl = distUrl('plugins/cline-installation.js');
|
||||
const PLUGIN = { exportName: 'clinePlugin', moduleUrl: pluginModuleUrl };
|
||||
|
||||
export function environment(fixture, clineDir = fixture.clineDir) {
|
||||
return {
|
||||
HOME: fixture.homeDir,
|
||||
USERPROFILE: fixture.homeDir,
|
||||
CLINE_DIR: clineDir === null ? undefined : clineDir,
|
||||
};
|
||||
return { ...homeEnvironment(fixture), CLINE_DIR: clineDir === null ? undefined : clineDir };
|
||||
}
|
||||
|
||||
export function installConfig(fixture, overrides = {}) {
|
||||
return {
|
||||
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,
|
||||
};
|
||||
return baseInstallConfig('cline', fixture, overrides);
|
||||
}
|
||||
|
||||
export async function runPlugin(fixture, method, argument, clineDir = fixture.clineDir) {
|
||||
const source = `
|
||||
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,
|
||||
);
|
||||
export function runPlugin(fixture, method, argument, clineDir = fixture.clineDir) {
|
||||
return basePlugin(PLUGIN, fixture, method, argument, { env: environment(fixture, clineDir) });
|
||||
}
|
||||
|
||||
async function writeOptional(filePath, contents) {
|
||||
@@ -96,66 +48,26 @@ export async function createFixture({
|
||||
existingAudit,
|
||||
existingGuard,
|
||||
} = {}) {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-cline-'));
|
||||
const homeDir = path.join(rootDir, "home with spaces and 'quote %CLINE%");
|
||||
const projectDir = path.join(rootDir, 'project with spaces');
|
||||
const clineDir = path.join(rootDir, 'custom-cline-home');
|
||||
const base = await createFixtureRoot(
|
||||
'elydora-cline-',
|
||||
"home with spaces and 'quote %CLINE%",
|
||||
{ agentId },
|
||||
);
|
||||
const clineDir = path.join(base.rootDir, 'custom-cline-home');
|
||||
const hooksDir = path.join(clineDir, 'hooks');
|
||||
const guardWrapperPath = path.join(hooksDir, 'PreToolUse.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(auditWrapperPath, existingAudit);
|
||||
const fixture = {
|
||||
agentDir,
|
||||
agentId,
|
||||
return {
|
||||
...base,
|
||||
auditWrapperPath,
|
||||
baseUrl,
|
||||
clineDir,
|
||||
guardScriptPath,
|
||||
guardWrapperPath,
|
||||
homeDir,
|
||||
hookScriptPath,
|
||||
hooksDir,
|
||||
projectDir,
|
||||
rootDir,
|
||||
install(overrides = {}, clineDirOverride = this.clineDir) {
|
||||
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());
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -1,139 +1,58 @@
|
||||
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 { 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 const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/codex.js')).href;
|
||||
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href;
|
||||
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/codex-io.js')).href;
|
||||
export const installationModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/codex-installation.js'),
|
||||
).href;
|
||||
export { VALID_PRIVATE_KEY, registryModuleUrl, startApiServer, writeJson } from './harness.mjs';
|
||||
|
||||
export const pluginModuleUrl = distUrl('plugins/codex.js');
|
||||
export const ioModuleUrl = distUrl('plugins/codex-io.js');
|
||||
export const installationModuleUrl = distUrl('plugins/codex-installation.js');
|
||||
const PLUGIN = { exportName: 'codexPlugin', moduleUrl: pluginModuleUrl };
|
||||
|
||||
export function runNode(args, env, cwd, input = '') {
|
||||
return new Promise((resolve, reject) => {
|
||||
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);
|
||||
});
|
||||
return baseNode(args, { CODEX_HOME: '', ...env }, cwd, input);
|
||||
}
|
||||
|
||||
export function runHook(handler, input, fixture, environment = {}) {
|
||||
const command = process.platform === 'win32' ? handler.commandWindows : handler.command;
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = process.platform === 'win32'
|
||||
? spawn(command, {
|
||||
shell: true,
|
||||
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 });
|
||||
const env = { CODEX_HOME: '', ...homeEnvironment(fixture), ...environment };
|
||||
return process.platform === 'win32'
|
||||
? runShell(command, env, fixture.projectDir, input)
|
||||
: runProcess('/bin/sh', ['-c', command], env, fixture.projectDir, input);
|
||||
}
|
||||
|
||||
export function installConfig(fixture, overrides = {}) {
|
||||
return {
|
||||
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,
|
||||
};
|
||||
return baseInstallConfig('codex', fixture, overrides);
|
||||
}
|
||||
|
||||
export async function runPlugin(fixture, method, argument, environment = {}) {
|
||||
const source = `
|
||||
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 function runPlugin(fixture, method, argument, environment = {}) {
|
||||
return basePlugin(PLUGIN, fixture, method, argument, { env: { CODEX_HOME: '', ...environment } });
|
||||
}
|
||||
|
||||
export async function createFixture({ existingConfig, baseUrl = 'http://127.0.0.1:9' } = {}) {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-codex-'));
|
||||
const homeDir = path.join(rootDir, "home with spaces and 'quote %ELYDORA_HOOK_PATH%");
|
||||
const projectDir = path.join(rootDir, 'project with spaces');
|
||||
const configPath = path.join(homeDir, '.codex', '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);
|
||||
const base = await createFixtureRoot(
|
||||
'elydora-codex-',
|
||||
"home with spaces and 'quote %ELYDORA_HOOK_PATH%",
|
||||
);
|
||||
const configPath = path.join(base.homeDir, '.codex', 'hooks.json');
|
||||
await writeOptionalJson(configPath, existingConfig);
|
||||
return {
|
||||
agentDir,
|
||||
...base,
|
||||
baseUrl,
|
||||
configPath,
|
||||
guardScriptPath,
|
||||
homeDir,
|
||||
hookScriptPath,
|
||||
projectDir,
|
||||
rootDir,
|
||||
install(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,
|
||||
};
|
||||
}
|
||||
|
||||
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,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 { 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 const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/copilot.js')).href;
|
||||
export const contractModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/copilot-contract.js'),
|
||||
).href;
|
||||
export const installationModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/copilot-installation.js'),
|
||||
).href;
|
||||
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/copilot-io.js')).href;
|
||||
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href;
|
||||
export const cliPath = path.resolve('dist/cli.js');
|
||||
export {
|
||||
VALID_PRIVATE_KEY,
|
||||
cliPath,
|
||||
readJson,
|
||||
registryModuleUrl,
|
||||
runNode,
|
||||
runProcess,
|
||||
startApiServer,
|
||||
writeJson,
|
||||
} from './harness.mjs';
|
||||
|
||||
export function runProcess(command, args, env, cwd, input = '') {
|
||||
return new Promise((resolve, reject) => {
|
||||
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,
|
||||
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 const pluginModuleUrl = distUrl('plugins/copilot.js');
|
||||
export const contractModuleUrl = distUrl('plugins/copilot-contract.js');
|
||||
export const installationModuleUrl = distUrl('plugins/copilot-installation.js');
|
||||
export const ioModuleUrl = distUrl('plugins/copilot-io.js');
|
||||
const PLUGIN = { exportName: 'copilotPlugin', moduleUrl: pluginModuleUrl };
|
||||
|
||||
export function environment(fixture, copilotHome = fixture.copilotHome) {
|
||||
return {
|
||||
HOME: fixture.homeDir,
|
||||
USERPROFILE: fixture.homeDir,
|
||||
...homeEnvironment(fixture),
|
||||
COPILOT_HOME: copilotHome === null ? undefined : copilotHome,
|
||||
};
|
||||
}
|
||||
|
||||
export function installConfig(fixture, overrides = {}) {
|
||||
return {
|
||||
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,
|
||||
};
|
||||
return baseInstallConfig('copilot', fixture, overrides);
|
||||
}
|
||||
|
||||
export async function runPlugin(fixture, method, argument, copilotHome = fixture.copilotHome) {
|
||||
const source = `
|
||||
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 runPlugin(fixture, method, argument, copilotHome = fixture.copilotHome) {
|
||||
return basePlugin(PLUGIN, fixture, method, argument, { env: environment(fixture, copilotHome) });
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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({
|
||||
agentId = 'agent-1',
|
||||
baseUrl = 'http://127.0.0.1:9',
|
||||
@@ -113,46 +60,36 @@ export async function createFixture({
|
||||
repositorySettings,
|
||||
localSettings,
|
||||
} = {}) {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-copilot-'));
|
||||
const homeDir = path.join(rootDir, "home with spaces and 'quote %COPILOT%");
|
||||
const projectDir = path.join(rootDir, 'project with spaces');
|
||||
const base = await createFixtureRoot(
|
||||
'elydora-copilot-',
|
||||
"home with spaces and 'quote %COPILOT%",
|
||||
{ agentId },
|
||||
);
|
||||
const { projectDir, rootDir } = base;
|
||||
const copilotHome = path.join(rootDir, "custom Copilot 'home");
|
||||
const hooksDir = path.join(copilotHome, 'hooks');
|
||||
const configPath = path.join(hooksDir, 'elydora-audit.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([
|
||||
writeOptional(configPath, userConfig),
|
||||
writeOptional(legacyPath, legacyConfig),
|
||||
writeOptional(path.join(copilotHome, 'settings.json'), userSettings),
|
||||
writeOptional(path.join(copilotHome, 'config.json'), legacyUserConfig),
|
||||
writeOptional(path.join(projectDir, '.claude', 'settings.json'), claudeSettings),
|
||||
writeOptional(path.join(projectDir, '.claude', 'settings.local.json'), claudeLocalSettings),
|
||||
writeOptional(path.join(projectDir, '.github', 'copilot', 'settings.json'), repositorySettings),
|
||||
writeOptional(path.join(projectDir, '.github', 'copilot', 'settings.local.json'), localSettings),
|
||||
writeOptionalJson(configPath, userConfig),
|
||||
writeOptionalJson(legacyPath, legacyConfig),
|
||||
writeOptionalJson(path.join(copilotHome, 'settings.json'), userSettings),
|
||||
writeOptionalJson(path.join(copilotHome, 'config.json'), legacyUserConfig),
|
||||
writeOptionalJson(path.join(projectDir, '.claude', 'settings.json'), claudeSettings),
|
||||
writeOptionalJson(path.join(projectDir, '.claude', 'settings.local.json'), claudeLocalSettings),
|
||||
writeOptionalJson(path.join(projectDir, '.github', 'copilot', 'settings.json'), repositorySettings),
|
||||
writeOptionalJson(path.join(projectDir, '.github', 'copilot', 'settings.local.json'), localSettings),
|
||||
]);
|
||||
return {
|
||||
agentDir,
|
||||
agentId,
|
||||
...base,
|
||||
baseUrl,
|
||||
configPath,
|
||||
copilotHome,
|
||||
guardScriptPath,
|
||||
homeDir,
|
||||
hookScriptPath,
|
||||
hooksDir,
|
||||
legacyPath,
|
||||
projectDir,
|
||||
rootDir,
|
||||
install(overrides = {}, copilotHomeOverride = this.copilotHome) {
|
||||
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());
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -1,127 +1,56 @@
|
||||
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 { 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 const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/cursor.js')).href;
|
||||
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href;
|
||||
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/cursor-io.js')).href;
|
||||
export const contractModuleUrl = pathToFileURL(path.resolve('dist/plugins/cursor-contract.js')).href;
|
||||
export const installationModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/cursor-installation.js'),
|
||||
).href;
|
||||
export {
|
||||
VALID_PRIVATE_KEY,
|
||||
registryModuleUrl,
|
||||
runNode,
|
||||
startApiServer,
|
||||
writeJson,
|
||||
} from './harness.mjs';
|
||||
|
||||
export function runNode(args, env, cwd, input = '') {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(process.execPath, args, {
|
||||
cwd,
|
||||
env: { ...process.env, ...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 const pluginModuleUrl = distUrl('plugins/cursor.js');
|
||||
export const ioModuleUrl = distUrl('plugins/cursor-io.js');
|
||||
export const contractModuleUrl = distUrl('plugins/cursor-contract.js');
|
||||
export const installationModuleUrl = distUrl('plugins/cursor-installation.js');
|
||||
const PLUGIN = { exportName: 'cursorPlugin', moduleUrl: pluginModuleUrl };
|
||||
|
||||
export function runHook(handler, input, fixture, environment = {}) {
|
||||
const executable = process.platform === 'win32' ? 'powershell.exe' : '/bin/sh';
|
||||
const args = process.platform === 'win32'
|
||||
? ['-NoProfile', '-NonInteractive', '-Command', handler.command]
|
||||
: ['-c', handler.command];
|
||||
return new Promise((resolve, reject) => {
|
||||
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 });
|
||||
return runProcess(executable, args, { ...homeEnvironment(fixture), ...environment }, undefined, input);
|
||||
}
|
||||
|
||||
export function installConfig(fixture, overrides = {}) {
|
||||
return {
|
||||
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,
|
||||
};
|
||||
return baseInstallConfig('cursor', fixture, overrides);
|
||||
}
|
||||
|
||||
export async function runPlugin(fixture, method, argument) {
|
||||
const source = `
|
||||
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 function runPlugin(fixture, method, argument) {
|
||||
return basePlugin(PLUGIN, fixture, method, argument);
|
||||
}
|
||||
|
||||
export async function createFixture({ existingConfig, baseUrl = 'http://127.0.0.1:9' } = {}) {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-cursor-'));
|
||||
const homeDir = path.join(rootDir, "home with spaces and 'quote");
|
||||
const projectDir = path.join(rootDir, 'project with spaces');
|
||||
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);
|
||||
const base = await createFixtureRoot('elydora-cursor-', "home with spaces and 'quote");
|
||||
const configPath = path.join(base.homeDir, '.cursor', 'hooks.json');
|
||||
await writeOptionalJson(configPath, existingConfig);
|
||||
return {
|
||||
agentDir,
|
||||
...base,
|
||||
baseUrl,
|
||||
configPath,
|
||||
guardScriptPath,
|
||||
homeDir,
|
||||
hookScriptPath,
|
||||
projectDir,
|
||||
rootDir,
|
||||
install(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) {
|
||||
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());
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -1,104 +1,58 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
|
||||
import http from 'node:http';
|
||||
import os from 'node:os';
|
||||
import { mkdir, readFile, readdir } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
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 const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/droid.js')).href;
|
||||
export const configModuleUrl = pathToFileURL(path.resolve('dist/plugins/droid-config.js')).href;
|
||||
export const contractModuleUrl = pathToFileURL(path.resolve('dist/plugins/droid-contract.js')).href;
|
||||
export const installationModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/droid-installation.js'),
|
||||
).href;
|
||||
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/droid-io.js')).href;
|
||||
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href;
|
||||
export const cliPath = path.resolve('dist/cli.js');
|
||||
export {
|
||||
VALID_PRIVATE_KEY,
|
||||
cliPath,
|
||||
homeEnvironment as environment,
|
||||
registryModuleUrl,
|
||||
runNode,
|
||||
startApiServer,
|
||||
writeJson as writeConfig,
|
||||
} from './harness.mjs';
|
||||
|
||||
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) {
|
||||
return new Promise((resolve, reject) => {
|
||||
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 };
|
||||
return baseProcess(command, args, env, cwd, input, { shell });
|
||||
}
|
||||
|
||||
export function installConfig(fixture, overrides = {}) {
|
||||
return {
|
||||
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,
|
||||
};
|
||||
return baseInstallConfig('droid', fixture, overrides);
|
||||
}
|
||||
|
||||
export async function runPlugin(fixture, method, argument) {
|
||||
const source = `
|
||||
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 runPlugin(fixture, method, argument) {
|
||||
return basePlugin(PLUGIN, fixture, method, argument, { cwd: fixture.workspaceDir });
|
||||
}
|
||||
|
||||
export function runHook(command, fixture, input) {
|
||||
const env = homeEnvironment(fixture);
|
||||
if (process.platform === 'win32') {
|
||||
return runProcess(
|
||||
'powershell.exe',
|
||||
['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', command],
|
||||
environment(fixture),
|
||||
env,
|
||||
fixture.workspaceDir,
|
||||
input,
|
||||
);
|
||||
}
|
||||
return runProcess('/bin/sh', ['-c', command], environment(fixture), 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);
|
||||
return runProcess('/bin/sh', ['-c', command], env, fixture.workspaceDir, input);
|
||||
}
|
||||
|
||||
export async function createFixture({
|
||||
@@ -111,51 +65,44 @@ export async function createFixture({
|
||||
projectSettings,
|
||||
projectLocalSettings,
|
||||
} = {}) {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-droid-'));
|
||||
const homeDir = path.join(rootDir, "home with spaces and 'quote %DROID%");
|
||||
const workspaceDir = path.join(rootDir, 'workspace with spaces');
|
||||
const factoryDir = path.join(homeDir, '.factory');
|
||||
const base = await createFixtureRoot(
|
||||
'elydora-droid-',
|
||||
"home with spaces and 'quote %DROID%",
|
||||
{ agentId, projectName: 'workspace with spaces' },
|
||||
);
|
||||
const workspaceDir = base.projectDir;
|
||||
const factoryDir = path.join(base.homeDir, '.factory');
|
||||
const rootPath = path.join(factoryDir, 'hooks.json');
|
||||
const legacyPath = path.join(factoryDir, 'hooks', 'hooks.json');
|
||||
const settingsPath = path.join(factoryDir, 'settings.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 projectSettingsPath = path.join(projectFactoryDir, 'settings.json');
|
||||
const projectLocalSettingsPath = path.join(projectFactoryDir, 'settings.local.json');
|
||||
await mkdir(path.join(workspaceDir, '.git'), { recursive: true });
|
||||
await Promise.all([
|
||||
writeOptional(rootPath, rootConfig),
|
||||
writeOptional(legacyPath, legacyConfig),
|
||||
writeOptional(settingsPath, settings),
|
||||
writeOptional(localSettingsPath, localSettings),
|
||||
writeOptional(projectSettingsPath, projectSettings),
|
||||
writeOptional(projectLocalSettingsPath, projectLocalSettings),
|
||||
writeOptionalJson(rootPath, rootConfig),
|
||||
writeOptionalJson(legacyPath, legacyConfig),
|
||||
writeOptionalJson(settingsPath, settings),
|
||||
writeOptionalJson(localSettingsPath, localSettings),
|
||||
writeOptionalJson(projectSettingsPath, projectSettings),
|
||||
writeOptionalJson(projectLocalSettingsPath, projectLocalSettings),
|
||||
]);
|
||||
const { projectDir: _projectDir, ...fixture } = base;
|
||||
return {
|
||||
agentDir,
|
||||
agentId,
|
||||
...fixture,
|
||||
baseUrl,
|
||||
factoryDir,
|
||||
guardScriptPath,
|
||||
homeDir,
|
||||
hookScriptPath,
|
||||
legacyPath,
|
||||
localSettingsPath,
|
||||
projectLocalSettingsPath,
|
||||
projectSettingsPath,
|
||||
rootDir,
|
||||
rootPath,
|
||||
settingsPath,
|
||||
workspaceDir,
|
||||
install(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));
|
||||
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());
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -1,65 +1,49 @@
|
||||
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';
|
||||
import {
|
||||
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 const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/gemini.js')).href;
|
||||
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href;
|
||||
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/gemini-io.js')).href;
|
||||
export const installationModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/gemini-installation.js'),
|
||||
).href;
|
||||
export const cliPath = path.resolve('dist/cli.js');
|
||||
export {
|
||||
VALID_PRIVATE_KEY,
|
||||
cliPath,
|
||||
parseJsonc as parseSettings,
|
||||
readJsoncSettings as readSettings,
|
||||
registryModuleUrl,
|
||||
startApiServer,
|
||||
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 = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
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);
|
||||
});
|
||||
return baseProcess(command, args, env, cwd, input, { unset });
|
||||
}
|
||||
|
||||
export function runNode(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 = {}) {
|
||||
const env = {
|
||||
HOME: fixture.homeDir,
|
||||
USERPROFILE: fixture.homeDir,
|
||||
...homeEnvironment(fixture),
|
||||
GEMINI_CLI_HOME: fixture.geminiCliHomeOverride ?? '',
|
||||
...environment,
|
||||
};
|
||||
if (process.platform === 'win32') {
|
||||
return runProcess(
|
||||
windowsPowerShell(),
|
||||
windowsPowerShellPath(),
|
||||
[
|
||||
'-NoLogo',
|
||||
'-NoProfile',
|
||||
@@ -75,66 +59,16 @@ export function runGeminiHook(handler, input, fixture, environment = {}) {
|
||||
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 = {}) {
|
||||
return {
|
||||
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,
|
||||
};
|
||||
return baseInstallConfig('gemini', fixture, overrides);
|
||||
}
|
||||
|
||||
export async function runPlugin(fixture, method, argument, environment = {}) {
|
||||
const source = `
|
||||
import { geminiPlugin } from ${JSON.stringify(pluginModuleUrl)};
|
||||
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT);
|
||||
const result = await geminiPlugin[process.env.ELYDORA_TEST_METHOD](argument);
|
||||
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 function runPlugin(fixture, method, argument, environment = {}) {
|
||||
const home = optionalEnvironment('GEMINI_CLI_HOME', fixture.geminiCliHomeOverride);
|
||||
return basePlugin(PLUGIN, fixture, method, argument, {
|
||||
env: { ...environment, ...home.env },
|
||||
unset: home.unset,
|
||||
});
|
||||
}
|
||||
|
||||
export async function createFixture({
|
||||
@@ -142,38 +76,23 @@ export async function createFixture({
|
||||
settings,
|
||||
explicitGeminiHome = true,
|
||||
} = {}) {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-gemini-'));
|
||||
const homeDir = path.join(
|
||||
rootDir,
|
||||
const base = await createFixtureRoot(
|
||||
'elydora-gemini-',
|
||||
"home with spaces and 'quote $GEMINI_CWD %GEMINI_CWD%",
|
||||
);
|
||||
const projectDir = path.join(rootDir, 'project with spaces');
|
||||
const geminiCliHome = homeDir;
|
||||
const geminiCliHome = base.homeDir;
|
||||
const settingsPath = path.join(geminiCliHome, '.gemini', 'settings.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 (settings !== undefined) await writeSettings(settingsPath, settings);
|
||||
const fixture = {
|
||||
agentDir,
|
||||
await writeOptionalJson(settingsPath, settings);
|
||||
return {
|
||||
...base,
|
||||
baseUrl,
|
||||
geminiCliHome,
|
||||
geminiCliHomeOverride: explicitGeminiHome ? geminiCliHome : undefined,
|
||||
guardScriptPath,
|
||||
homeDir,
|
||||
hookScriptPath,
|
||||
projectDir,
|
||||
rootDir,
|
||||
settingsPath,
|
||||
install(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) {
|
||||
@@ -202,34 +121,3 @@ export function assertManagedHandler(handler, name) {
|
||||
export function legacyHandler(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());
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -1,39 +1,27 @@
|
||||
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 { mkdir, readFile, writeFile } from 'node:fs/promises';
|
||||
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 const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/grok.js')).href;
|
||||
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href;
|
||||
export const contractModuleUrl = pathToFileURL(path.resolve('dist/plugins/grok-contract.js')).href;
|
||||
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/grok-io.js')).href;
|
||||
export const installationModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/grok-installation.js'),
|
||||
).href;
|
||||
export const cliPath = path.resolve('dist/cli.js');
|
||||
export { VALID_PRIVATE_KEY, cliPath, registryModuleUrl, startApiServer } from './harness.mjs';
|
||||
|
||||
export const pluginModuleUrl = distUrl('plugins/grok.js');
|
||||
export const contractModuleUrl = distUrl('plugins/grok-contract.js');
|
||||
export const ioModuleUrl = distUrl('plugins/grok-io.js');
|
||||
export const installationModuleUrl = distUrl('plugins/grok-installation.js');
|
||||
const PLUGIN = { exportName: 'grokPlugin', moduleUrl: pluginModuleUrl };
|
||||
|
||||
export function runProcess(command, args, env, cwd, input = '', unset = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
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);
|
||||
});
|
||||
return baseProcess(command, 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 = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(command, {
|
||||
shell: true,
|
||||
cwd: fixture.projectDir,
|
||||
env: {
|
||||
...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);
|
||||
});
|
||||
return runShell(command, {
|
||||
...homeEnvironment(fixture),
|
||||
GROK_HOME: fixture.grokHomeOverride ?? '',
|
||||
...environment,
|
||||
}, fixture.projectDir, input);
|
||||
}
|
||||
|
||||
export function installConfig(fixture, overrides = {}) {
|
||||
return {
|
||||
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,
|
||||
};
|
||||
return baseInstallConfig('grok', fixture, overrides);
|
||||
}
|
||||
|
||||
export async function runPlugin(fixture, method, argument, environment = {}) {
|
||||
const source = `
|
||||
import { grokPlugin } from ${JSON.stringify(pluginModuleUrl)};
|
||||
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT);
|
||||
const result = await grokPlugin[process.env.ELYDORA_TEST_METHOD](argument);
|
||||
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,
|
||||
);
|
||||
export function runPlugin(fixture, method, argument, environment = {}) {
|
||||
const home = optionalEnvironment('GROK_HOME', fixture.grokHomeOverride);
|
||||
return basePlugin(PLUGIN, fixture, method, argument, {
|
||||
env: { ...environment, ...home.env },
|
||||
unset: home.unset,
|
||||
});
|
||||
}
|
||||
|
||||
async function writeOptional(filePath, contents) {
|
||||
@@ -116,37 +59,25 @@ export async function createFixture({
|
||||
config,
|
||||
explicitGrokHome = true,
|
||||
} = {}) {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-grok-'));
|
||||
const homeDir = path.join(rootDir, "home with spaces and 'quote %GROK_HOOK_EVENT%");
|
||||
const projectDir = path.join(rootDir, 'project with spaces');
|
||||
const base = await createFixtureRoot(
|
||||
'elydora-grok-',
|
||||
"home with spaces and 'quote %GROK_HOOK_EVENT%",
|
||||
);
|
||||
const grokHome = explicitGrokHome
|
||||
? path.join(homeDir, 'custom grok')
|
||||
: path.join(homeDir, '.grok');
|
||||
? path.join(base.homeDir, 'custom grok')
|
||||
: path.join(base.homeDir, '.grok');
|
||||
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);
|
||||
const fixture = {
|
||||
agentDir,
|
||||
return {
|
||||
...base,
|
||||
baseUrl,
|
||||
configPath,
|
||||
grokHome,
|
||||
grokHomeOverride: explicitGrokHome ? grokHome : undefined,
|
||||
guardScriptPath,
|
||||
homeDir,
|
||||
hookScriptPath,
|
||||
projectDir,
|
||||
rootDir,
|
||||
install(overrides = {}) {
|
||||
return runPlugin(this, 'install', installConfig(this, overrides));
|
||||
},
|
||||
async close() {
|
||||
await rm(rootDir, { recursive: true, force: true });
|
||||
},
|
||||
};
|
||||
return fixture;
|
||||
}
|
||||
|
||||
export async function readGrokConfig(filePath) {
|
||||
@@ -184,34 +115,3 @@ export function legacyCommand(scriptPath) {
|
||||
const quote = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
|
||||
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());
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -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());
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -1,104 +1,48 @@
|
||||
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 { mkdir, readFile, writeFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
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 const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/kimi.js')).href;
|
||||
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href;
|
||||
export const contractModuleUrl = pathToFileURL(path.resolve('dist/plugins/kimi-contract.js')).href;
|
||||
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/kimi-io.js')).href;
|
||||
export const installationModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/kimi-installation.js'),
|
||||
).href;
|
||||
export const cliPath = path.resolve('dist/cli.js');
|
||||
export { VALID_PRIVATE_KEY, cliPath, registryModuleUrl, startApiServer } from './harness.mjs';
|
||||
|
||||
export const pluginModuleUrl = distUrl('plugins/kimi.js');
|
||||
export const contractModuleUrl = distUrl('plugins/kimi-contract.js');
|
||||
export const ioModuleUrl = distUrl('plugins/kimi-io.js');
|
||||
export const installationModuleUrl = distUrl('plugins/kimi-installation.js');
|
||||
const PLUGIN = { exportName: 'kimiPlugin', moduleUrl: pluginModuleUrl };
|
||||
|
||||
export function runNode(args, env, cwd, input = '', unset = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
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);
|
||||
});
|
||||
return baseNode(args, env, cwd, input, { unset });
|
||||
}
|
||||
|
||||
export function runKimiHook(command, input, fixture, environment = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(command, {
|
||||
shell: true,
|
||||
cwd: fixture.projectDir,
|
||||
env: {
|
||||
...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);
|
||||
});
|
||||
return runShell(command, {
|
||||
...homeEnvironment(fixture),
|
||||
KIMI_CODE_HOME: fixture.kimiHomeOverride ?? '',
|
||||
...environment,
|
||||
}, fixture.projectDir, input);
|
||||
}
|
||||
|
||||
export function installConfig(fixture, overrides = {}) {
|
||||
return {
|
||||
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,
|
||||
};
|
||||
return baseInstallConfig('kimi', fixture, overrides);
|
||||
}
|
||||
|
||||
export async function runPlugin(fixture, method, argument, environment = {}) {
|
||||
const source = `
|
||||
import { kimiPlugin } from ${JSON.stringify(pluginModuleUrl)};
|
||||
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT);
|
||||
const result = await kimiPlugin[process.env.ELYDORA_TEST_METHOD](argument);
|
||||
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,
|
||||
);
|
||||
export function runPlugin(fixture, method, argument, environment = {}) {
|
||||
const home = optionalEnvironment('KIMI_CODE_HOME', fixture.kimiHomeOverride);
|
||||
return basePlugin(PLUGIN, fixture, method, argument, {
|
||||
env: { ...environment, ...home.env },
|
||||
unset: home.unset,
|
||||
});
|
||||
}
|
||||
|
||||
async function writeOptional(filePath, contents) {
|
||||
@@ -115,50 +59,37 @@ export async function createFixture({
|
||||
legacyDetected = true,
|
||||
explicitKimiHome = true,
|
||||
} = {}) {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-kimi-'));
|
||||
const homeDir = path.join(rootDir, "home with spaces and 'quote %ELYDORA_HOOK_PATH%");
|
||||
const projectDir = path.join(rootDir, 'project with spaces');
|
||||
const base = await createFixtureRoot(
|
||||
'elydora-kimi-',
|
||||
"home with spaces and 'quote %ELYDORA_HOOK_PATH%",
|
||||
);
|
||||
const kimiHome = explicitKimiHome
|
||||
? path.join(homeDir, 'custom kimi-code')
|
||||
: path.join(homeDir, '.kimi-code');
|
||||
? path.join(base.homeDir, 'custom kimi-code')
|
||||
: path.join(base.homeDir, '.kimi-code');
|
||||
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 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 (legacyDetected) await mkdir(legacyHome, { recursive: true });
|
||||
await writeOptional(stablePath, stableConfig);
|
||||
await writeOptional(legacyPath, legacyConfig);
|
||||
const fixture = {
|
||||
agentDir,
|
||||
return {
|
||||
...base,
|
||||
baseUrl,
|
||||
guardScriptPath,
|
||||
homeDir,
|
||||
hookScriptPath,
|
||||
kimiHome,
|
||||
kimiHomeOverride: explicitKimiHome ? kimiHome : undefined,
|
||||
legacyHome,
|
||||
legacyPath,
|
||||
projectDir,
|
||||
rootDir,
|
||||
stablePath,
|
||||
install(overrides = {}) {
|
||||
return runPlugin(this, 'install', installConfig(this, overrides));
|
||||
},
|
||||
async close() {
|
||||
await rm(rootDir, { recursive: true, force: true });
|
||||
},
|
||||
};
|
||||
return fixture;
|
||||
}
|
||||
|
||||
export function readKimiConfig(filePath) {
|
||||
return import('node:fs/promises')
|
||||
.then(({ readFile }) => readFile(filePath, 'utf-8'))
|
||||
.then((raw) => ({ raw, config: parseToml(raw) }));
|
||||
export async function readKimiConfig(filePath) {
|
||||
const raw = await readFile(filePath, 'utf-8');
|
||||
return { raw, config: parseToml(raw) };
|
||||
}
|
||||
|
||||
export function managedHook(config, event) {
|
||||
@@ -182,39 +113,3 @@ export function legacyCommand(scriptPath) {
|
||||
const quote = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
|
||||
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());
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -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 { 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 const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/kirocli.js')).href;
|
||||
export const contractModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/kirocli-contract.js'),
|
||||
).href;
|
||||
export const installationModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/kirocli-installation.js'),
|
||||
).href;
|
||||
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/kirocli-io.js')).href;
|
||||
export const kiroV1ModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/kiroide-contract.js'),
|
||||
).href;
|
||||
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href;
|
||||
export const cliPath = path.resolve('dist/cli.js');
|
||||
export {
|
||||
VALID_PRIVATE_KEY,
|
||||
cliPath,
|
||||
homeEnvironment as environment,
|
||||
readJson,
|
||||
registryModuleUrl,
|
||||
runNode,
|
||||
runShell,
|
||||
startApiServer,
|
||||
} from './harness.mjs';
|
||||
|
||||
export const pluginModuleUrl = distUrl('plugins/kirocli.js');
|
||||
export const contractModuleUrl = distUrl('plugins/kirocli-contract.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) {
|
||||
return new Promise((resolve, reject) => {
|
||||
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 };
|
||||
return baseProcess(command, args, env, cwd, input, { shell });
|
||||
}
|
||||
|
||||
export function installConfig(fixture, overrides = {}) {
|
||||
return {
|
||||
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,
|
||||
};
|
||||
return baseInstallConfig('kirocli', fixture, overrides);
|
||||
}
|
||||
|
||||
export async function runPlugin(fixture, method, argument) {
|
||||
const source = `
|
||||
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 runPlugin(fixture, method, argument) {
|
||||
return basePlugin(PLUGIN, fixture, method, argument);
|
||||
}
|
||||
|
||||
export function managedV2Document(overrides = {}) {
|
||||
@@ -112,71 +55,26 @@ export async function createFixture({
|
||||
existingV2,
|
||||
existingV3,
|
||||
} = {}) {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-kirocli-'));
|
||||
const homeDir = path.join(rootDir, "home with spaces and 'quote %KIRO%");
|
||||
const projectDir = path.join(rootDir, 'workspace with spaces');
|
||||
const v2Path = path.join(homeDir, '.kiro', 'agents', 'elydora-audit.json');
|
||||
const v3Path = path.join(homeDir, '.kiro', 'hooks', 'elydora-audit.json');
|
||||
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(v2Path, existingV2);
|
||||
await writeOptional(v3Path, existingV3);
|
||||
const base = await createFixtureRoot(
|
||||
'elydora-kirocli-',
|
||||
"home with spaces and 'quote %KIRO%",
|
||||
{ agentId, projectName: 'workspace with spaces', createHome: true },
|
||||
);
|
||||
const v2Path = path.join(base.homeDir, '.kiro', 'agents', 'elydora-audit.json');
|
||||
const v3Path = path.join(base.homeDir, '.kiro', 'hooks', 'elydora-audit.json');
|
||||
await writeOptionalJson(v2Path, existingV2);
|
||||
await writeOptionalJson(v3Path, existingV3);
|
||||
return {
|
||||
agentDir,
|
||||
agentId,
|
||||
...base,
|
||||
baseUrl,
|
||||
guardScriptPath,
|
||||
homeDir,
|
||||
hookScriptPath,
|
||||
projectDir,
|
||||
rootDir,
|
||||
v2Path,
|
||||
v3Path,
|
||||
install(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) {
|
||||
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());
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -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 { 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 const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/kiroide.js')).href;
|
||||
export const contractModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/kiroide-contract.js'),
|
||||
).href;
|
||||
export const installationModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/kiroide-installation.js'),
|
||||
).href;
|
||||
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/kiroide-io.js')).href;
|
||||
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href;
|
||||
export const cliPath = path.resolve('dist/cli.js');
|
||||
export {
|
||||
VALID_PRIVATE_KEY,
|
||||
cliPath,
|
||||
homeEnvironment as environment,
|
||||
readJson,
|
||||
registryModuleUrl,
|
||||
runNode,
|
||||
runShell,
|
||||
startApiServer,
|
||||
} from './harness.mjs';
|
||||
|
||||
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) {
|
||||
return new Promise((resolve, reject) => {
|
||||
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 };
|
||||
return baseProcess(command, args, env, cwd, input, { shell });
|
||||
}
|
||||
|
||||
export function installConfig(fixture, overrides = {}) {
|
||||
return {
|
||||
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,
|
||||
};
|
||||
return baseInstallConfig('kiroide', fixture, overrides);
|
||||
}
|
||||
|
||||
export async function runPlugin(fixture, method, argument) {
|
||||
const source = `
|
||||
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 function runPlugin(fixture, method, argument) {
|
||||
return basePlugin(PLUGIN, fixture, method, argument);
|
||||
}
|
||||
|
||||
export async function createFixture({
|
||||
@@ -98,73 +43,28 @@ export async function createFixture({
|
||||
existingConfig,
|
||||
existingLegacy,
|
||||
} = {}) {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-kiroide-'));
|
||||
const homeDir = path.join(rootDir, "home with spaces and 'quote %KIRO%");
|
||||
const projectDir = path.join(rootDir, 'workspace with spaces');
|
||||
const hooksDir = path.join(projectDir, '.kiro', 'hooks');
|
||||
const base = await createFixtureRoot(
|
||||
'elydora-kiroide-',
|
||||
"home with spaces and 'quote %KIRO%",
|
||||
{ agentId, projectName: 'workspace with spaces' },
|
||||
);
|
||||
const hooksDir = path.join(base.projectDir, '.kiro', 'hooks');
|
||||
const configPath = path.join(hooksDir, 'elydora-audit.json');
|
||||
const legacyConfigPath = path.join(homeDir, '.kiro', 'hooks', 'elydora-audit.kiro.hook');
|
||||
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(configPath, existingConfig);
|
||||
await writeOptional(legacyConfigPath, existingLegacy);
|
||||
const fixture = {
|
||||
agentDir,
|
||||
agentId,
|
||||
const legacyConfigPath = path.join(base.homeDir, '.kiro', 'hooks', 'elydora-audit.kiro.hook');
|
||||
await writeOptionalJson(configPath, existingConfig);
|
||||
await writeOptionalJson(legacyConfigPath, existingLegacy);
|
||||
return {
|
||||
...base,
|
||||
baseUrl,
|
||||
configPath,
|
||||
guardScriptPath,
|
||||
homeDir,
|
||||
hookScriptPath,
|
||||
hooksDir,
|
||||
legacyConfigPath,
|
||||
projectDir,
|
||||
rootDir,
|
||||
install(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) {
|
||||
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
@@ -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 { 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 const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/letta.js')).href;
|
||||
export const configModuleUrl = pathToFileURL(path.resolve('dist/plugins/letta-config.js')).href;
|
||||
export const contractModuleUrl = pathToFileURL(path.resolve('dist/plugins/letta-contract.js')).href;
|
||||
export const installationModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/letta-installation.js'),
|
||||
).href;
|
||||
export const sourcesModuleUrl = pathToFileURL(path.resolve('dist/plugins/letta-sources.js')).href;
|
||||
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href;
|
||||
export const cliPath = path.resolve('dist/cli.js');
|
||||
export {
|
||||
VALID_PRIVATE_KEY,
|
||||
cliPath,
|
||||
homeEnvironment as environment,
|
||||
readJson as readSettings,
|
||||
registryModuleUrl,
|
||||
runNode,
|
||||
runProcess,
|
||||
startApiServer,
|
||||
} from './harness.mjs';
|
||||
|
||||
export function runProcess(command, args, env, cwd, input = '') {
|
||||
return new Promise((resolve, reject) => {
|
||||
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,
|
||||
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 const pluginModuleUrl = distUrl('plugins/letta.js');
|
||||
export const configModuleUrl = distUrl('plugins/letta-config.js');
|
||||
export const contractModuleUrl = distUrl('plugins/letta-contract.js');
|
||||
export const installationModuleUrl = distUrl('plugins/letta-installation.js');
|
||||
export const sourcesModuleUrl = distUrl('plugins/letta-sources.js');
|
||||
const PLUGIN = { exportName: 'lettaPlugin', moduleUrl: pluginModuleUrl };
|
||||
|
||||
export function installConfig(fixture, overrides = {}) {
|
||||
return {
|
||||
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,
|
||||
};
|
||||
return baseInstallConfig('letta', fixture, overrides);
|
||||
}
|
||||
|
||||
export async function runPlugin(fixture, method, argument) {
|
||||
const source = `
|
||||
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 function runPlugin(fixture, method, argument) {
|
||||
return basePlugin(PLUGIN, fixture, method, argument);
|
||||
}
|
||||
|
||||
export async function createFixture({
|
||||
@@ -96,45 +42,29 @@ export async function createFixture({
|
||||
projectSettings,
|
||||
localSettings,
|
||||
} = {}) {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-letta-'));
|
||||
const homeDir = path.join(rootDir, "home with spaces and 'quote %HOME%");
|
||||
const projectDir = path.join(rootDir, 'workspace with spaces');
|
||||
const globalPath = path.join(homeDir, '.letta', 'settings.json');
|
||||
const projectPath = path.join(projectDir, '.letta', 'settings.json');
|
||||
const localPath = path.join(projectDir, '.letta', 'settings.local.json');
|
||||
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(globalPath, globalSettings);
|
||||
await writeOptional(projectPath, projectSettings);
|
||||
await writeOptional(localPath, localSettings);
|
||||
const base = await createFixtureRoot(
|
||||
'elydora-letta-',
|
||||
"home with spaces and 'quote %HOME%",
|
||||
{ agentId, projectName: 'workspace with spaces', createHome: true },
|
||||
);
|
||||
const globalPath = path.join(base.homeDir, '.letta', 'settings.json');
|
||||
const projectPath = path.join(base.projectDir, '.letta', 'settings.json');
|
||||
const localPath = path.join(base.projectDir, '.letta', 'settings.local.json');
|
||||
await writeOptionalJson(globalPath, globalSettings);
|
||||
await writeOptionalJson(projectPath, projectSettings);
|
||||
await writeOptionalJson(localPath, localSettings);
|
||||
return {
|
||||
agentDir,
|
||||
agentId,
|
||||
...base,
|
||||
baseUrl,
|
||||
globalPath,
|
||||
guardScriptPath,
|
||||
homeDir,
|
||||
hookScriptPath,
|
||||
localPath,
|
||||
projectDir,
|
||||
projectPath,
|
||||
rootDir,
|
||||
install(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) {
|
||||
return settings.hooks[event].find((group) => (
|
||||
group.matcher === '*'
|
||||
@@ -148,40 +78,5 @@ export function runLettaHook(handler, input, fixture) {
|
||||
const args = process.platform === 'win32'
|
||||
? ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', handler.command]
|
||||
: ['-c', handler.command];
|
||||
return runProcess(shell, args, environment(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());
|
||||
}),
|
||||
};
|
||||
return runProcess(shell, args, homeEnvironment(fixture), fixture.projectDir, input);
|
||||
}
|
||||
@@ -1,87 +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 { mkdir, writeFile } from 'node:fs/promises';
|
||||
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, 19).toString('base64url');
|
||||
export const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/opencode.js')).href;
|
||||
export const contractModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/opencode-contract.js'),
|
||||
).href;
|
||||
export const installationModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/opencode-installation.js'),
|
||||
).href;
|
||||
export const ioModuleUrl = pathToFileURL(path.resolve('dist/plugins/opencode-io.js')).href;
|
||||
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href;
|
||||
export const cliPath = path.resolve('dist/cli.js');
|
||||
export {
|
||||
VALID_PRIVATE_KEY,
|
||||
cliPath,
|
||||
readJson,
|
||||
registryModuleUrl,
|
||||
runNode,
|
||||
runProcess,
|
||||
startApiServer,
|
||||
} from './harness.mjs';
|
||||
|
||||
export function runProcess(command, args, env, cwd, input = '') {
|
||||
return new Promise((resolve, reject) => {
|
||||
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,
|
||||
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 const pluginModuleUrl = distUrl('plugins/opencode.js');
|
||||
export const contractModuleUrl = distUrl('plugins/opencode-contract.js');
|
||||
export const installationModuleUrl = distUrl('plugins/opencode-installation.js');
|
||||
export const ioModuleUrl = distUrl('plugins/opencode-io.js');
|
||||
const PLUGIN = { exportName: 'opencodePlugin', moduleUrl: pluginModuleUrl };
|
||||
|
||||
export function environment(fixture) {
|
||||
return {
|
||||
HOME: fixture.homeDir,
|
||||
USERPROFILE: fixture.homeDir,
|
||||
XDG_CONFIG_HOME: fixture.configRoot,
|
||||
};
|
||||
return { ...homeEnvironment(fixture), XDG_CONFIG_HOME: fixture.configRoot };
|
||||
}
|
||||
|
||||
export function installConfig(fixture, overrides = {}) {
|
||||
return {
|
||||
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,
|
||||
};
|
||||
return baseInstallConfig('opencode', fixture, overrides);
|
||||
}
|
||||
|
||||
export async function runPlugin(fixture, method, argument) {
|
||||
const source = `
|
||||
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,
|
||||
);
|
||||
export function runPlugin(fixture, method, argument) {
|
||||
return basePlugin(PLUGIN, fixture, method, argument, { env: environment(fixture) });
|
||||
}
|
||||
|
||||
async function writeOptional(filePath, value) {
|
||||
@@ -96,33 +49,24 @@ export async function createFixture({
|
||||
existingPlugin,
|
||||
existingLegacy,
|
||||
} = {}) {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-opencode-'));
|
||||
const homeDir = path.join(rootDir, "home with spaces and 'quote %OPEN%");
|
||||
const configRoot = path.join(rootDir, 'xdg config');
|
||||
const projectDir = path.join(rootDir, 'workspace with spaces');
|
||||
const base = await createFixtureRoot(
|
||||
'elydora-opencode-',
|
||||
"home with spaces and 'quote %OPEN%",
|
||||
{ agentId, projectName: 'workspace with spaces', createHome: true },
|
||||
);
|
||||
const configRoot = path.join(base.rootDir, 'xdg config');
|
||||
const pluginsDir = path.join(configRoot, 'opencode', 'plugins');
|
||||
const pluginPath = path.join(pluginsDir, 'elydora-audit.js');
|
||||
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(legacyPluginPath, existingLegacy);
|
||||
return {
|
||||
agentDir,
|
||||
agentId,
|
||||
...base,
|
||||
baseUrl,
|
||||
configRoot,
|
||||
guardScriptPath,
|
||||
homeDir,
|
||||
hookScriptPath,
|
||||
legacyPluginPath,
|
||||
pluginPath,
|
||||
pluginsDir,
|
||||
projectDir,
|
||||
rootDir,
|
||||
install(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()}`);
|
||||
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
@@ -1,28 +1,32 @@
|
||||
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';
|
||||
import {
|
||||
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 const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/qwen.js')).href;
|
||||
export const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href;
|
||||
export const sourcesModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/qwen-sources.js'),
|
||||
).href;
|
||||
export const installationModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/qwen-installation.js'),
|
||||
).href;
|
||||
export const configModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/qwen-config.js'),
|
||||
).href;
|
||||
export const contractModuleUrl = pathToFileURL(
|
||||
path.resolve('dist/plugins/qwen-contract.js'),
|
||||
).href;
|
||||
export const cliPath = path.resolve('dist/cli.js');
|
||||
export {
|
||||
VALID_PRIVATE_KEY,
|
||||
cliPath,
|
||||
parseJsonc as parseSettings,
|
||||
readJsoncSettings as readSettings,
|
||||
registryModuleUrl,
|
||||
startApiServer,
|
||||
writeJson as writeSettings,
|
||||
} from './harness.mjs';
|
||||
|
||||
export const pluginModuleUrl = distUrl('plugins/qwen.js');
|
||||
export const sourcesModuleUrl = distUrl('plugins/qwen-sources.js');
|
||||
export const installationModuleUrl = distUrl('plugins/qwen-installation.js');
|
||||
export const configModuleUrl = distUrl('plugins/qwen-config.js');
|
||||
export const contractModuleUrl = distUrl('plugins/qwen-contract.js');
|
||||
const PLUGIN = { exportName: 'qwenPlugin', moduleUrl: pluginModuleUrl };
|
||||
|
||||
const QWEN_ENV_KEYS = [
|
||||
'QWEN_HOME',
|
||||
@@ -33,48 +37,18 @@ const QWEN_ENV_KEYS = [
|
||||
];
|
||||
|
||||
export function runProcess(command, args, env, cwd, input = '', unset = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
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);
|
||||
});
|
||||
return baseProcess(command, args, env, cwd, input, { unset });
|
||||
}
|
||||
|
||||
export function runNode(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 = {}) {
|
||||
const env = {
|
||||
HOME: fixture.homeDir,
|
||||
USERPROFILE: fixture.homeDir,
|
||||
...environment,
|
||||
};
|
||||
const env = { ...homeEnvironment(fixture), ...environment };
|
||||
if (process.platform === 'win32') {
|
||||
return runProcess(
|
||||
windowsPowerShell(),
|
||||
windowsPowerShellPath(),
|
||||
['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', handler.command],
|
||||
env,
|
||||
fixture.projectDir,
|
||||
@@ -84,109 +58,36 @@ export function runQwenHook(handler, input, fixture, environment = {}) {
|
||||
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 = {}) {
|
||||
return {
|
||||
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,
|
||||
};
|
||||
return baseInstallConfig('qwen', fixture, overrides);
|
||||
}
|
||||
|
||||
function qwenEnvironment(fixture, environment) {
|
||||
export function runPlugin(fixture, method, argument, environment = {}) {
|
||||
const env = {
|
||||
HOME: fixture.homeDir,
|
||||
USERPROFILE: fixture.homeDir,
|
||||
QWEN_CODE_SYSTEM_DEFAULTS_PATH: path.join(fixture.rootDir, 'system-defaults.json'),
|
||||
QWEN_CODE_SYSTEM_SETTINGS_PATH: path.join(fixture.rootDir, 'system-settings.json'),
|
||||
...environment,
|
||||
};
|
||||
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 = {}) {
|
||||
const source = `
|
||||
import { qwenPlugin } from ${JSON.stringify(pluginModuleUrl)};
|
||||
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,
|
||||
export async function createFixture({ baseUrl = 'http://127.0.0.1:9', settings } = {}) {
|
||||
const base = await createFixtureRoot(
|
||||
'elydora-qwen-',
|
||||
"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(homeDir, '.qwen', 'settings.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(homeDir, { recursive: true });
|
||||
await mkdir(projectDir, { recursive: true });
|
||||
if (settings !== undefined) await writeSettings(settingsPath, settings);
|
||||
const fixture = {
|
||||
agentDir,
|
||||
const settingsPath = path.join(base.homeDir, '.qwen', 'settings.json');
|
||||
await writeOptionalJson(settingsPath, settings);
|
||||
return {
|
||||
...base,
|
||||
baseUrl,
|
||||
guardScriptPath,
|
||||
homeDir,
|
||||
hookScriptPath,
|
||||
projectDir,
|
||||
rootDir,
|
||||
settingsPath,
|
||||
install(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) {
|
||||
@@ -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,5 +1,7 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { existsSync, utimesSync, writeFileSync } from 'node:fs';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import http from 'node:http';
|
||||
import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
@@ -143,3 +145,196 @@ test('Claude runtime failures stay observable while guard and audit delivery rem
|
||||
await fixture.close();
|
||||
}
|
||||
});
|
||||
|
||||
function mismatchServer(respond) {
|
||||
const submissions = [];
|
||||
const server = http.createServer((request, response) => {
|
||||
let raw = '';
|
||||
request.on('data', (chunk) => { raw += chunk; });
|
||||
request.on('end', () => {
|
||||
if (request.url !== '/v1/operations') {
|
||||
response.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
response.end(JSON.stringify({ agent: { status: 'active' } }));
|
||||
return;
|
||||
}
|
||||
submissions.push(JSON.parse(raw));
|
||||
const reply = respond(submissions) ?? mismatch(String(submissions.length).padStart(43, 'A'), 'x');
|
||||
const send = () => {
|
||||
response.writeHead(reply.status, { 'Content-Type': 'application/json' });
|
||||
response.end(JSON.stringify(reply.body));
|
||||
};
|
||||
if (api.slow) setTimeout(send, 2600); else send();
|
||||
});
|
||||
});
|
||||
const api = { submissions, slow: false };
|
||||
return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(Object.assign(api, {
|
||||
baseUrl: 'http://127.0.0.1:' + server.address().port,
|
||||
close: () => new Promise((done) => { server.closeAllConnections?.(); server.close(done); }),
|
||||
}))));
|
||||
}
|
||||
|
||||
function mismatch(expected, actual) {
|
||||
return {
|
||||
status: 400,
|
||||
body: { error: { code: 'PREV_HASH_MISMATCH', message: 'Expected prev_chain_hash "' + expected + '", got "' + actual + '".' } },
|
||||
};
|
||||
}
|
||||
|
||||
test('Claude audit retries a rejected prev_chain_hash with the server value', async () => {
|
||||
const expected = 'Rxlf4j36C3KvIQ3hWuOkX698BR5iDypUFuB70JjEuvM';
|
||||
const api = await mismatchServer((submissions) => (submissions.length === 1
|
||||
? mismatch(expected, submissions[0].prev_chain_hash)
|
||||
: { status: 202, body: { receipt: { seq_no: 2 } } }));
|
||||
const fixture = await createFixture({ baseUrl: api.baseUrl });
|
||||
try {
|
||||
assert.equal((await fixture.install()).code, 0);
|
||||
const { settings } = await readSettings(fixture.settingsPath);
|
||||
const audit = managedHandler(settings, 'PostToolUse');
|
||||
const result = await runClaudeHook(
|
||||
audit,
|
||||
JSON.stringify(officialPayload('PostToolUse', { tool_response: { stdout: 'ok' } })),
|
||||
fixture,
|
||||
);
|
||||
assert.equal(result.code, 0, result.stderr);
|
||||
assert.equal(api.submissions.length, 2);
|
||||
assert.equal(api.submissions[1].prev_chain_hash, expected);
|
||||
assert.notEqual(api.submissions[1].operation_id, api.submissions[0].operation_id);
|
||||
assert.notEqual(api.submissions[1].nonce, api.submissions[0].nonce);
|
||||
const state = JSON.parse(await readFile(path.join(fixture.agentDir, 'chain-state.json'), 'utf-8'));
|
||||
assert.equal(state.prev_chain_hash, api.submissions[1].chain_hash);
|
||||
assert.match(await readFile(path.join(fixture.agentDir, 'error.log'), 'utf-8'), /resynced to server: Rxlf/);
|
||||
} finally {
|
||||
await fixture.close();
|
||||
await api.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('Claude audit stops after five rejected prev_chain_hash attempts', async () => {
|
||||
const api = await mismatchServer((submissions) => (
|
||||
mismatch(String(submissions.length).padStart(43, 'A'), submissions.at(-1).prev_chain_hash)
|
||||
));
|
||||
const fixture = await createFixture({ baseUrl: api.baseUrl });
|
||||
try {
|
||||
assert.equal((await fixture.install()).code, 0);
|
||||
const { settings } = await readSettings(fixture.settingsPath);
|
||||
const audit = managedHandler(settings, 'PostToolUse');
|
||||
const result = await runClaudeHook(
|
||||
audit,
|
||||
JSON.stringify(officialPayload('PostToolUse', { tool_response: { stdout: 'ok' } })),
|
||||
fixture,
|
||||
);
|
||||
assert.equal(result.code, 0, result.stderr);
|
||||
assert.equal(api.submissions.length, 5);
|
||||
assert.equal(api.submissions[4].prev_chain_hash, '4'.padStart(43, 'A'));
|
||||
assert.match(await readFile(path.join(fixture.agentDir, 'error.log'), 'utf-8'), /rejected prev_chain_hash 5 times/);
|
||||
} finally {
|
||||
await fixture.close();
|
||||
await api.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('Claude audit stops retrying when the submit budget is spent', async () => {
|
||||
const api = await mismatchServer(() => null);
|
||||
api.slow = true;
|
||||
const fixture = await createFixture({ baseUrl: api.baseUrl });
|
||||
try {
|
||||
assert.equal((await fixture.install()).code, 0);
|
||||
const { settings } = await readSettings(fixture.settingsPath);
|
||||
const audit = managedHandler(settings, 'PostToolUse');
|
||||
const started = Date.now();
|
||||
const result = await runClaudeHook(
|
||||
audit,
|
||||
JSON.stringify(officialPayload('PostToolUse', { tool_response: { stdout: 'ok' } })),
|
||||
fixture,
|
||||
);
|
||||
const elapsed = Date.now() - started;
|
||||
assert.equal(result.code, 0, result.stderr);
|
||||
assert.ok(elapsed < 7000, `hook ran ${elapsed}ms`);
|
||||
assert.ok(api.submissions.length >= 2 && api.submissions.length <= 3, `${api.submissions.length} submissions`);
|
||||
assert.match(await readFile(path.join(fixture.agentDir, 'error.log'), 'utf-8'), /aborted|retry budget exhausted/i);
|
||||
} finally {
|
||||
await fixture.close();
|
||||
await api.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('Claude audit does not regress a chain head advanced by a concurrent hook', async () => {
|
||||
const newerHead = 'B'.repeat(43);
|
||||
let statePath;
|
||||
const api = await mismatchServer(() => {
|
||||
writeFileSync(statePath, JSON.stringify({ prev_chain_hash: newerHead }), { mode: 0o600 });
|
||||
return { status: 202, body: { receipt: { seq_no: 1 } } };
|
||||
});
|
||||
const fixture = await createFixture({ baseUrl: api.baseUrl });
|
||||
try {
|
||||
assert.equal((await fixture.install()).code, 0);
|
||||
statePath = path.join(fixture.agentDir, 'chain-state.json');
|
||||
const { settings } = await readSettings(fixture.settingsPath);
|
||||
const audit = managedHandler(settings, 'PostToolUse');
|
||||
const result = await runClaudeHook(
|
||||
audit,
|
||||
JSON.stringify(officialPayload('PostToolUse', { tool_response: { stdout: 'ok' } })),
|
||||
fixture,
|
||||
);
|
||||
assert.equal(result.code, 0, result.stderr);
|
||||
assert.equal(api.submissions[0].prev_chain_hash, 'A'.repeat(43));
|
||||
const state = JSON.parse(await readFile(statePath, 'utf-8'));
|
||||
assert.equal(state.prev_chain_hash, newerHead);
|
||||
} finally {
|
||||
await fixture.close();
|
||||
await api.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('Claude audit clears a stale chain-state lock and proceeds', async () => {
|
||||
const api = await mismatchServer(() => ({ status: 202, body: { receipt: { seq_no: 1 } } }));
|
||||
const fixture = await createFixture({ baseUrl: api.baseUrl });
|
||||
try {
|
||||
assert.equal((await fixture.install()).code, 0);
|
||||
const lockPath = path.join(fixture.agentDir, 'chain-state.json.lock');
|
||||
writeFileSync(lockPath, '', { mode: 0o600 });
|
||||
const stale = new Date(Date.now() - 10_000);
|
||||
utimesSync(lockPath, stale, stale);
|
||||
const { settings } = await readSettings(fixture.settingsPath);
|
||||
const audit = managedHandler(settings, 'PostToolUse');
|
||||
const result = await runClaudeHook(
|
||||
audit,
|
||||
JSON.stringify(officialPayload('PostToolUse', { tool_response: { stdout: 'ok' } })),
|
||||
fixture,
|
||||
);
|
||||
assert.equal(result.code, 0, result.stderr);
|
||||
assert.equal(api.submissions.length, 1);
|
||||
assert.equal(existsSync(lockPath), false);
|
||||
const state = JSON.parse(await readFile(path.join(fixture.agentDir, 'chain-state.json'), 'utf-8'));
|
||||
assert.equal(state.prev_chain_hash, api.submissions[0].chain_hash);
|
||||
} finally {
|
||||
await fixture.close();
|
||||
await api.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('Claude audit does not reclaim a chain-state lock whose owner is alive', async () => {
|
||||
const api = await mismatchServer(() => ({ status: 202, body: { receipt: { seq_no: 1 } } }));
|
||||
const fixture = await createFixture({ baseUrl: api.baseUrl });
|
||||
try {
|
||||
assert.equal((await fixture.install()).code, 0);
|
||||
const lockPath = path.join(fixture.agentDir, 'chain-state.json.lock');
|
||||
writeFileSync(lockPath, String(process.pid), { mode: 0o600 });
|
||||
const stale = new Date(Date.now() - 10_000);
|
||||
utimesSync(lockPath, stale, stale);
|
||||
const { settings } = await readSettings(fixture.settingsPath);
|
||||
const audit = managedHandler(settings, 'PostToolUse');
|
||||
const result = await runClaudeHook(
|
||||
audit,
|
||||
JSON.stringify(officialPayload('PostToolUse', { tool_response: { stdout: 'ok' } })),
|
||||
fixture,
|
||||
);
|
||||
assert.equal(result.code, 0, result.stderr);
|
||||
assert.equal(api.submissions.length, 1);
|
||||
assert.equal(existsSync(lockPath), true);
|
||||
assert.match(await readFile(path.join(fixture.agentDir, 'error.log'), 'utf-8'), /lock timed out/);
|
||||
} finally {
|
||||
await fixture.close();
|
||||
await api.close();
|
||||
}
|
||||
});
|
||||
@@ -18,6 +18,7 @@ async function runCli(args, homeDir) {
|
||||
...process.env,
|
||||
HOME: homeDir,
|
||||
USERPROFILE: homeDir,
|
||||
XDG_CONFIG_HOME: path.join(homeDir, '.config'),
|
||||
},
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
|
||||
@@ -6,7 +6,7 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
|
||||
import { generateGuardScript } from '../dist/plugins/hook-template.js';
|
||||
import { generateGuardScript } from '../dist/plugins/guard-template.js';
|
||||
|
||||
const AGENT_ID = 'agent-1';
|
||||
|
||||
@@ -26,6 +26,7 @@ async function createFixture(status) {
|
||||
await writeFile(
|
||||
path.join(agentDir, 'config.json'),
|
||||
JSON.stringify({ agent_id: AGENT_ID, base_url: `http://127.0.0.1:${address.port}` }),
|
||||
{ mode: 0o600 },
|
||||
);
|
||||
|
||||
const scriptPath = path.join(homeDir, 'guard.cjs');
|
||||
@@ -91,6 +92,7 @@ test('cached frozen status keeps the blocking exit code', async () => {
|
||||
await writeFile(
|
||||
path.join(fixture.homeDir, '.elydora', AGENT_ID, 'status-cache.json'),
|
||||
JSON.stringify({ status: 'frozen', cached_at: Date.now() }),
|
||||
{ mode: 0o600 },
|
||||
);
|
||||
|
||||
const result = await runGuard(fixture.scriptPath, fixture.homeDir);
|
||||
|
||||
@@ -60,7 +60,7 @@ async function installedHandlers(fixture) {
|
||||
}
|
||||
|
||||
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 });
|
||||
try {
|
||||
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) => {
|
||||
for (const status of ['frozen', 'revoked']) {
|
||||
await t.test(status, async () => {
|
||||
const api = await startApiServer(status);
|
||||
const api = await startApiServer({ status });
|
||||
const fixture = await createFixture({ baseUrl: api.baseUrl });
|
||||
try {
|
||||
assert.equal((await fixture.install()).code, 0);
|
||||
|
||||
Reference in new issue
Block a user