fix(copilot): mirror transactional Node hooks

This commit is contained in:
ZacharyZhang-NY committed 2026-07-20 12:09:24 -04:00
1 parent d0185887fa
commit af8d227b45
17 files changed
+1738 -651

No files matched your search

+111 -75
View File
@@ -1,5 +1,8 @@
import os from 'node:os';
import path from 'node:path';
import type { FileSnapshot } from './managed-files.js';
import { validateHooks, type CopilotHooks } from './copilot-schema.js';
import { parseStrictJsonObject, type JsonObject } from './strict-json.js';
export const AGENT_KEY = 'copilot';
export const GUARD_SCRIPT = 'guard.js';
@@ -7,20 +10,33 @@ export const AUDIT_SCRIPT = 'hook.js';
export const HOOK_TIMEOUT_SECONDS = 10;
export const CONFIG_FILE = 'elydora-audit.json';
export type JsonObject = Record<string, unknown>;
export type CopilotHooks = Record<string, JsonObject[]>;
const MANAGED_EVENTS = [
['preToolUse', GUARD_SCRIPT],
['postToolUse', AUDIT_SCRIPT],
['postToolUseFailure', AUDIT_SCRIPT],
] as const;
export interface CopilotDocument {
readonly exists: boolean;
readonly filePath: string;
readonly root: JsonObject;
readonly hooks: CopilotHooks;
readonly hooksDisabled: boolean;
readonly raw?: string;
readonly snapshot?: FileSnapshot;
}
export interface CopilotSources {
readonly user: CopilotDocument;
readonly legacy?: CopilotDocument;
readonly disabledBy?: string;
readonly settingsPreconditions: readonly CopilotSourcePrecondition[];
}
export interface CopilotSourcePrecondition {
readonly filePath: string;
readonly label: string;
readonly snapshot?: FileSnapshot;
}
export interface RenderedDocument {
@@ -40,11 +56,12 @@ interface ParsedArgument {
readonly next: number;
}
export function isObject(value: unknown): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
interface ManagedEntry {
readonly agentId: string;
readonly scriptPath: string;
}
function samePath(left: string, right: string): boolean {
export function samePath(left: string, right: string): boolean {
const normalizedLeft = path.resolve(left);
const normalizedRight = path.resolve(right);
return process.platform === 'win32'
@@ -52,8 +69,14 @@ function samePath(left: string, right: string): boolean {
: normalizedLeft === normalizedRight;
}
function sameAgentId(left: string, right: string): boolean {
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
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 {
@@ -126,82 +149,88 @@ function parseGeneratedPowerShell(command: unknown): readonly [string, string] |
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 (!bash || !powershell
|| !nodeExecutable(bash[0])
|| !samePath(bash[0], powershell[0])
|| !samePath(bash[1], powershell[1])) return undefined;
return bash[1];
}
function parseLegacyCommand(command: unknown): string | undefined {
if (typeof command !== 'string') return undefined;
return /^node(?:\.exe)?\s+"([^"]+)"$/i.exec(command)?.[1];
}
function managedScriptPath(handler: JsonObject): string | undefined {
if (handler.type !== 'command') return undefined;
const bash = parseGeneratedBash(handler.bash);
const powershell = parseGeneratedPowerShell(handler.powershell);
if (handler.timeoutSec === HOOK_TIMEOUT_SECONDS && bash && powershell) {
if (samePath(bash[0], process.execPath)
&& samePath(powershell[0], process.execPath)
&& samePath(bash[1], powershell[1])) return bash[1];
}
const legacyBash = parseLegacyCommand(handler.bash);
const legacyPowerShell = parseLegacyCommand(handler.powershell);
return legacyBash && legacyPowerShell && samePath(legacyBash, legacyPowerShell)
? legacyBash
: undefined;
function legacyManagedScriptPath(handler: JsonObject): string | undefined {
if (!exactHandlerKeys(handler)
|| handler.type !== 'command'
|| handler.timeoutSec !== 5) return undefined;
const bash = parseLegacyCommand(handler.bash);
const powershell = parseLegacyCommand(handler.powershell);
return bash && powershell && samePath(bash, powershell) ? bash : undefined;
}
function managedAgentId(handler: JsonObject, scriptName: string): string | undefined {
const scriptPath = managedScriptPath(handler);
if (!scriptPath || path.basename(scriptPath) !== scriptName) return undefined;
function managedEntry(handler: JsonObject, scriptName: string): ManagedEntry | undefined {
const scriptPath = currentManagedScriptPath(handler) ?? legacyManagedScriptPath(handler);
if (!scriptPath || path.basename(scriptPath).toLowerCase() !== scriptName.toLowerCase()) {
return undefined;
}
const agentDirectory = path.dirname(scriptPath);
if (!samePath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))) return undefined;
if (!samePath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))) {
return undefined;
}
const agentId = path.basename(agentDirectory);
return agentId && agentId !== '.' && agentId !== '..' ? agentId : undefined;
if (!agentId || agentId === '.' || agentId === '..') return undefined;
return { agentId, scriptPath };
}
function validateHooks(value: unknown, label: string): CopilotHooks {
if (value === undefined) return {};
if (!isObject(value)) throw new Error(`${label} field "hooks" must be an object`);
const hooks: CopilotHooks = {};
for (const [event, handlers] of Object.entries(value)) {
if (!Array.isArray(handlers)) throw new Error(`${label} field "hooks.${event}" must be an array`);
hooks[event] = handlers.map((handler, index) => {
if (!isObject(handler)) throw new Error(`${label} handler hooks.${event}[${index}] must be an object`);
return handler;
});
export function parseDocument(
filePath: string,
snapshot: FileSnapshot,
label: string,
): CopilotDocument {
const root = parseStrictJsonObject(snapshot.contents, `${label} at ${filePath}`);
if (root.version !== 1) throw new Error(`${label} at ${filePath} must declare version 1`);
if (root.disableAllHooks !== undefined && typeof root.disableAllHooks !== 'boolean') {
throw new Error(`${label} at ${filePath} field "disableAllHooks" must be a boolean`);
}
return hooks;
}
export function parseDocument(filePath: string, raw: string, label: string): CopilotDocument {
let value: unknown;
try {
value = JSON.parse(raw);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed to parse ${label} at ${filePath}: ${message}`, { cause: error });
}
if (!isObject(value)) throw new Error(`${label} at ${filePath} must contain a JSON object`);
if (value.version !== 1) throw new Error(`${label} at ${filePath} must declare version 1`);
return {
exists: true,
filePath,
root: value,
hooks: validateHooks(value.hooks, label),
raw,
root,
hooks: validateHooks(root.hooks, `${label} at ${filePath}`),
hooksDisabled: root.disableAllHooks === true,
raw: snapshot.contents,
snapshot,
};
}
export function createDocument(filePath: string): CopilotDocument {
return { exists: false, filePath, root: {}, hooks: {} };
return { exists: false, filePath, root: {}, hooks: {}, hooksDisabled: false };
}
export function removeManagedHooks(hooks: CopilotHooks, agentId?: string): CopilotHooks {
const next: CopilotHooks = { ...hooks };
for (const [event, scriptName] of [
['preToolUse', GUARD_SCRIPT],
['postToolUse', AUDIT_SCRIPT],
] as const) {
for (const [event, scriptName] of MANAGED_EVENTS) {
const handlers = (next[event] ?? []).filter((handler) => {
const managedId = managedAgentId(handler, scriptName);
return !managedId || (agentId !== undefined && !sameAgentId(managedId, agentId));
const owned = managedEntry(handler, scriptName);
return !owned || (agentId !== undefined && !sameAgentId(owned.agentId, agentId));
});
if (handlers.length > 0) next[event] = handlers;
else delete next[event];
@@ -227,26 +256,33 @@ export function renderDocument(
const root: JsonObject = { ...document.root, version: 1 };
if (Object.keys(hooks).length > 0) root.hooks = hooks;
else delete root.hooks;
const next = JSON.stringify(root, null, 2) + '\n';
const next = `${JSON.stringify(root, null, 2)}\n`;
return { document, changed: next !== document.raw, next };
}
function managedIds(handlers: JsonObject[], scriptName: string): Set<string> {
return new Set(handlers.flatMap((handler) => {
const agentId = managedAgentId(handler, scriptName);
return agentId ? [agentId] : [];
}));
function managedEntries(handlers: JsonObject[], scriptName: string): Map<string, ManagedEntry> {
const entries = new Map<string, ManagedEntry>();
for (const handler of handlers) {
const entry = managedEntry(handler, scriptName);
if (entry) entries.set(agentKey(entry.agentId), entry);
}
return entries;
}
export function runtimeContracts(hooks: CopilotHooks): RuntimeContract[] {
const guards = managedIds(hooks.preToolUse ?? [], GUARD_SCRIPT);
const audits = managedIds(hooks.postToolUse ?? [], AUDIT_SCRIPT);
const root = path.join(os.homedir(), '.elydora');
return [...guards]
.filter((agentId) => [...audits].some((auditId) => sameAgentId(agentId, auditId)))
.map((agentId) => ({
agentId,
guardPath: path.join(root, agentId, GUARD_SCRIPT),
auditPath: path.join(root, agentId, AUDIT_SCRIPT),
}));
const guards = managedEntries(hooks.preToolUse ?? [], GUARD_SCRIPT);
const successes = managedEntries(hooks.postToolUse ?? [], AUDIT_SCRIPT);
const failures = managedEntries(hooks.postToolUseFailure ?? [], AUDIT_SCRIPT);
const contracts: RuntimeContract[] = [];
for (const [key, guard] of guards) {
const success = successes.get(key);
const failure = failures.get(key);
if (!success || !failure || !samePath(success.scriptPath, failure.scriptPath)) continue;
contracts.push({
agentId: guard.agentId,
guardPath: guard.scriptPath,
auditPath: success.scriptPath,
});
}
return contracts;
}
@@ -0,0 +1,145 @@
import path from 'node:path';
import type { InstallConfig } from './base.js';
import {
AGENT_KEY,
AUDIT_SCRIPT,
GUARD_SCRIPT,
type CopilotSources,
type RenderedDocument,
samePath,
} from './copilot-contract.js';
import { requireHooksEnabled } from './copilot-io.js';
import {
commitManagedInstallation,
preflightManagedInstallation,
prepareManagedInstallation,
type ManagedRuntimePaths,
type PreparedManagedInstallation,
type RenameFile,
} from './managed-installation.js';
import {
commitManagedTransaction,
prepareManagedFileChange,
type PreparedManagedTransaction,
} from './managed-transaction.js';
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) => ({
directoryLabel: DIRECTORY_LABEL,
filePath: document.filePath,
}));
}
export async function preflightCopilotInstallation(
config: InstallConfig,
sources: CopilotSources,
): Promise<CopilotRuntimePaths> {
requireHooksEnabled(sources);
return preflightManagedInstallation({
agentKey: AGENT_KEY,
hookLocations: hookLocations(sources),
config,
}, GUARD_SCRIPT, AUDIT_SCRIPT);
}
function installationDocuments(
sources: CopilotSources,
rendered: readonly RenderedDocument[],
): readonly RenderedDocument[] {
return rendered.filter((item) => item.changed
|| samePath(item.document.filePath, sources.user.filePath));
}
export async function prepareCopilotInstallation(
config: InstallConfig,
sources: CopilotSources,
rendered: readonly RenderedDocument[],
): Promise<PreparedCopilotInstallation> {
await preflightCopilotInstallation(config, sources);
const documents = installationDocuments(sources, rendered);
const prepared = await prepareManagedInstallation({
agentKey: AGENT_KEY,
displayName: DISPLAY_NAME,
hookSources: documents.map((item) => ({
directoryLabel: DIRECTORY_LABEL,
label: SOURCE_LABEL,
filePath: item.document.filePath,
expectedSource: item.document.raw,
expectedSnapshot: item.document.snapshot,
source: item.changed ? item.next : item.document.raw,
})),
config,
auditOptions: { nativePayload: true },
}, GUARD_SCRIPT, AUDIT_SCRIPT);
const legacyPrecondition = sources.legacy
&& !documents.some((item) => samePath(item.document.filePath, sources.legacy!.filePath))
? [{
filePath: sources.legacy.filePath,
label: 'GitHub Copilot legacy project hooks',
maximumBytes: MAX_SOURCE_BYTES,
original: sources.legacy.snapshot,
}]
: [];
return {
...prepared,
transaction: {
...prepared.transaction,
preconditions: [
...sources.settingsPreconditions.map((condition) => ({
filePath: condition.filePath,
label: condition.label,
maximumBytes: MAX_SOURCE_BYTES,
original: condition.snapshot,
})),
...legacyPrecondition,
],
},
};
}
export async function commitCopilotInstallation(
prepared: PreparedCopilotInstallation,
renameFile?: RenameFile,
): Promise<void> {
await commitManagedInstallation(prepared, renameFile);
}
export async function prepareCopilotUninstall(
rendered: readonly RenderedDocument[],
): Promise<PreparedManagedTransaction> {
const changed = rendered.filter((item) => item.changed);
const changes = await Promise.all(changed.map((item) => prepareManagedFileChange({
filePath: item.document.filePath,
label: SOURCE_LABEL,
next: item.next,
mode: 0o600,
expectedSource: item.document.raw,
expectedSnapshot: item.document.snapshot,
verifyExpectedSource: true,
})));
return {
displayName: DISPLAY_NAME,
operation: 'uninstall',
directories: changed.map((item) => ({
path: path.dirname(item.document.filePath),
label: DIRECTORY_LABEL,
})),
changes: changes.filter((change) => change !== undefined),
};
}
export async function commitCopilotUninstall(
prepared: PreparedManagedTransaction,
renameFile?: RenameFile,
): Promise<void> {
await commitManagedTransaction(prepared, renameFile);
}
+204 -233
View File
@@ -1,281 +1,252 @@
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,
AUDIT_SCRIPT,
CONFIG_FILE,
GUARD_SCRIPT,
type CopilotDocument,
type CopilotSources,
type JsonObject,
type RenderedDocument,
type RuntimeContract,
createDocument,
isObject,
parseDocument,
sameAgentId,
samePath,
} from './copilot-contract.js';
import { generateGuardScript } from './guard-template.js';
import { generateHookScript } from './hook-template.js';
import {
inspectPhysicalDirectory,
readPhysicalFile,
type FileSnapshot,
} from './managed-files.js';
import {
parseStrictJsonObject,
parseStrictJsoncObject,
type JsonObject,
} from './strict-json.js';
interface FileChange {
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;
readonly userHookPath: string;
readonly legacyHookPath: string;
readonly settingsLayers: readonly SettingsLayer[];
readonly inspectedDirectories: readonly DirectoryLocation[];
}
interface DirectoryLocation {
readonly path: string;
readonly label: string;
}
interface SettingsLayer {
readonly filePath: string;
readonly label: string;
readonly original?: string;
readonly next?: string;
readonly jsonc: boolean;
}
interface StagedChange {
readonly change: FileChange;
readonly tempPath?: string;
readonly rollbackPath?: string;
committed: boolean;
interface ParsedSettingsLayer extends SettingsLayer {
readonly disableAllHooks?: boolean;
readonly snapshot?: FileSnapshot;
}
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;
}
function paths(): { readonly user: string; readonly legacy: string } {
const override = process.env.COPILOT_HOME?.trim();
const copilotHome = override || path.join(os.homedir(), '.copilot');
export function resolveCopilotPaths(): CopilotPaths {
const override = process.env.COPILOT_HOME;
const copilotHome = override ? override : path.join(os.homedir(), '.copilot');
const project = process.cwd();
const github = path.join(project, '.github');
const githubCopilot = path.join(github, 'copilot');
const githubHooks = path.join(github, 'hooks');
const claude = path.join(project, '.claude');
return {
user: path.join(copilotHome, 'hooks', CONFIG_FILE),
legacy: path.join(process.cwd(), '.github', 'hooks', 'hooks.json'),
copilotHome,
userHooksDirectory: path.join(copilotHome, 'hooks'),
userHookPath: path.join(copilotHome, 'hooks', CONFIG_FILE),
legacyHookPath: path.join(githubHooks, 'hooks.json'),
settingsLayers: [
{ filePath: path.join(copilotHome, 'config.json'), label: 'legacy Copilot user config', jsonc: false },
{ filePath: path.join(copilotHome, 'settings.json'), label: 'Copilot user settings', jsonc: true },
{ filePath: path.join(claude, 'settings.json'), label: 'Claude repository settings', jsonc: true },
{ filePath: path.join(claude, 'settings.local.json'), label: 'Claude local settings', jsonc: true },
{ filePath: path.join(githubCopilot, 'settings.json'), label: 'Copilot repository settings', jsonc: true },
{ filePath: path.join(githubCopilot, 'settings.local.json'), label: 'Copilot local settings', jsonc: true },
],
inspectedDirectories: [
{ path: project, label: 'Copilot working directory' },
{ path: copilotHome, label: 'COPILOT_HOME' },
{ path: path.join(copilotHome, 'hooks'), label: 'Copilot user hooks directory' },
{ path: github, label: 'GitHub configuration directory' },
{ path: githubHooks, label: 'GitHub repository hooks directory' },
{ path: githubCopilot, label: 'Copilot repository settings directory' },
{ path: claude, label: 'Claude repository settings directory' },
],
};
}
async function readOptional(filePath: string, label: string): Promise<string | undefined> {
try {
return await fsp.readFile(filePath, 'utf-8');
} catch (error) {
if (hasErrorCode(error, 'ENOENT')) return undefined;
throw new Error(`Read ${label} at ${filePath}: ${errorMessage(error)}`, {
cause: asError(error),
});
async function inspectDirectories(locations: readonly DirectoryLocation[]): Promise<void> {
for (const location of locations) {
await inspectPhysicalDirectory(location.path, location.label);
}
}
async function readDocument(filePath: string, label: string): Promise<CopilotDocument | undefined> {
const raw = await readOptional(filePath, label);
return raw === undefined ? undefined : parseDocument(filePath, raw, label);
async function readHookDocument(
filePath: string,
label: string,
): Promise<CopilotDocument | undefined> {
const snapshot = await readPhysicalFile(filePath, label, MAX_SETTINGS_BYTES);
return snapshot ? parseDocument(filePath, snapshot, label) : undefined;
}
function parseSettings(raw: string, layer: SettingsLayer): JsonObject {
if (raw.trim().length === 0) return {};
const label = `${layer.label} at ${layer.filePath}`;
return layer.jsonc
? parseStrictJsoncObject(raw, label)
: parseStrictJsonObject(raw, label);
}
async function readSettingsLayer(layer: SettingsLayer): Promise<ParsedSettingsLayer> {
const snapshot = await readPhysicalFile(layer.filePath, layer.label, MAX_SETTINGS_BYTES);
if (!snapshot) return layer;
const root = parseSettings(snapshot.contents, layer);
if (root.disableAllHooks !== undefined && typeof root.disableAllHooks !== 'boolean') {
throw new Error(
`${layer.label} at ${layer.filePath} field "disableAllHooks" must be a boolean`,
);
}
return {
...layer,
disableAllHooks: root.disableAllHooks as boolean | undefined,
snapshot,
};
}
function effectiveDisabledSource(layers: readonly ParsedSettingsLayer[]): string | undefined {
let disabledBy: string | undefined;
for (const layer of layers) {
if (layer.disableAllHooks === true) disabledBy = `${layer.label} at ${layer.filePath}`;
else if (layer.disableAllHooks === false) disabledBy = undefined;
}
return disabledBy;
}
export async function readSources(): Promise<CopilotSources> {
const configPaths = paths();
const paths = resolveCopilotPaths();
await inspectDirectories(paths.inspectedDirectories);
const [user, legacy] = await Promise.all([
readDocument(configPaths.user, 'GitHub Copilot user hooks'),
readDocument(configPaths.legacy, 'GitHub Copilot legacy project hooks'),
readHookDocument(paths.userHookPath, 'GitHub Copilot user hooks'),
readHookDocument(paths.legacyHookPath, 'GitHub Copilot legacy project hooks'),
]);
const layers = await Promise.all(paths.settingsLayers.map(readSettingsLayer));
const userDocument = user ?? createDocument(paths.userHookPath);
const disabledBy = userDocument.hooksDisabled
? `GitHub Copilot user hooks at ${paths.userHookPath}`
: effectiveDisabledSource(layers);
return {
user: user ?? createDocument(configPaths.user),
user: userDocument,
legacy,
disabledBy,
settingsPreconditions: layers.map((layer) => ({
filePath: layer.filePath,
label: layer.label,
snapshot: layer.snapshot,
})),
};
}
function changeFor(rendered: RenderedDocument): FileChange | undefined {
if (!rendered.changed) return undefined;
return {
filePath: rendered.document.filePath,
label: 'GitHub Copilot hook source',
original: rendered.document.raw,
next: rendered.next,
};
}
async function unlinkOptional(filePath: string): Promise<void> {
try {
await fsp.unlink(filePath);
} catch (error) {
if (!hasErrorCode(error, 'ENOENT')) throw error;
export function requireHooksEnabled(sources: CopilotSources): void {
if (sources.disabledBy) {
throw new Error(
`GitHub Copilot hooks are disabled by ${sources.disabledBy}; set disableAllHooks to false before installation`,
);
}
}
async function writeExclusive(filePath: string, contents: string, label: 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 ${label}`);
throw new Error(`Stage ${label}: ${errorMessage(error)}`, { cause: failures[0] });
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}`);
}
}
async function assertUnchanged(change: FileChange): Promise<void> {
const current = await readOptional(change.filePath, change.label);
if (current !== change.original) {
throw new Error(`${change.label} changed during Copilot hook update: ${change.filePath}`);
}
}
async function stage(change: FileChange): Promise<StagedChange> {
await assertUnchanged(change);
const directory = path.dirname(change.filePath);
await fsp.mkdir(directory, { recursive: true, mode: 0o700 });
const token = randomUUID();
const tempPath = change.next === undefined
? undefined
: path.join(directory, `.${path.basename(change.filePath)}.${token}.tmp`);
const rollbackPath = change.original === undefined
? undefined
: path.join(directory, `.${path.basename(change.filePath)}.${token}.rollback`);
try {
if (tempPath) await writeExclusive(tempPath, change.next!, change.label);
if (rollbackPath && change.next !== undefined) {
await writeExclusive(rollbackPath, change.original!, `${change.label} rollback`);
}
} catch (error) {
const failures = [asError(error)];
for (const stagedPath of [tempPath, rollbackPath]) {
if (!stagedPath) continue;
try {
await unlinkOptional(stagedPath);
} catch (cleanupError) {
failures.push(asError(cleanupError));
}
}
if (failures.length > 1) throw new AggregateError(failures, `Stage ${change.label}`);
throw error;
}
return { change, tempPath, rollbackPath, committed: false };
}
async function commit(staged: StagedChange): Promise<void> {
await assertUnchanged(staged.change);
if (staged.change.next === undefined) {
if (!staged.rollbackPath) throw new Error(`Missing rollback path for ${staged.change.label}`);
await fsp.rename(staged.change.filePath, staged.rollbackPath);
} else {
if (!staged.tempPath) throw new Error(`Missing staged file for ${staged.change.label}`);
await fsp.rename(staged.tempPath, staged.change.filePath);
}
staged.committed = true;
}
async function rollback(staged: StagedChange): Promise<void> {
if (!staged.committed) return;
if (staged.change.original === undefined) {
await unlinkOptional(staged.change.filePath);
return;
}
if (!staged.rollbackPath) throw new Error(`Missing rollback data for ${staged.change.label}`);
await fsp.rename(staged.rollbackPath, staged.change.filePath);
}
async function cleanup(staged: StagedChange): Promise<void> {
const files = [staged.tempPath, staged.rollbackPath].filter(
(filePath): filePath is string => filePath !== undefined,
);
await Promise.all(files.map(unlinkOptional));
}
export async function writeDocuments(rendered: RenderedDocument[]): Promise<void> {
const changes = rendered.flatMap((document) => {
const change = changeFor(document);
return change ? [change] : [];
});
const staged: StagedChange[] = [];
try {
for (const change of changes) staged.push(await stage(change));
for (const item of staged) await commit(item);
} catch (error) {
const failures = [asError(error)];
for (const item of [...staged].reverse()) {
try {
await rollback(item);
} catch (rollbackError) {
failures.push(asError(rollbackError));
}
}
for (const item of staged) {
try {
await cleanup(item);
} catch (cleanupError) {
failures.push(asError(cleanupError));
}
}
throw new AggregateError(failures, `Write GitHub Copilot hook sources: ${errorMessage(error)}`);
}
const cleanupErrors: Error[] = [];
for (const item of staged) {
try {
await cleanup(item);
} catch (error) {
cleanupErrors.push(asError(error));
}
}
if (cleanupErrors.length > 0) {
throw new AggregateError(cleanupErrors, 'Clean GitHub Copilot hook transaction files');
}
}
export async function regularFileExists(filePath: string, label: string): Promise<boolean> {
try {
return (await fsp.stat(filePath)).isFile();
} catch (error) {
if (hasErrorCode(error, 'ENOENT') || hasErrorCode(error, 'ENOTDIR')) return false;
throw new Error(`Read ${label} at ${filePath}: ${errorMessage(error)}`, {
cause: asError(error),
});
}
}
export async function requireRuntime(filePath: string, label: string): Promise<void> {
if (!filePath) throw new Error(`${label} path is required`);
if (!await regularFileExists(filePath, label)) throw new Error(`${label} is missing: ${filePath}`);
}
async function readRuntimeConfig(filePath: string): Promise<JsonObject | undefined> {
const raw = await readOptional(filePath, 'Elydora runtime config');
if (raw === undefined) return undefined;
let value: unknown;
try {
value = JSON.parse(raw);
} catch (error) {
throw new Error(`Failed to parse Elydora runtime config at ${filePath}: ${errorMessage(error)}`, {
cause: asError(error),
});
}
if (!isObject(value)) throw new Error(`Elydora runtime config at ${filePath} must contain a JSON object`);
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) {
const runtimeConfig = await readRuntimeConfig(
path.join(path.dirname(contract.guardPath), 'config.json'),
);
if (!runtimeConfig
|| runtimeConfig.agent_name !== AGENT_KEY
|| runtimeConfig.agent_id !== contract.agentId) continue;
const files = await Promise.all([
regularFileExists(contract.guardPath, 'Elydora guard runtime'),
regularFileExists(contract.auditPath, 'Elydora audit runtime'),
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 (files.every(Boolean)) return true;
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;
}
return false;
}
+162
View File
@@ -0,0 +1,162 @@
import { isObject, type JsonObject } from './strict-json.js';
export type CopilotHooks = Record<string, JsonObject[]>;
const SUPPORTED_EVENTS = new Set([
'agentStop',
'Stop',
'errorOccurred',
'ErrorOccurred',
'notification',
'Notification',
'permissionRequest',
'PermissionRequest',
'postToolUse',
'PostToolUse',
'postToolUseFailure',
'PostToolUseFailure',
'preCompact',
'PreCompact',
'preToolUse',
'PreToolUse',
'sessionEnd',
'SessionEnd',
'sessionStart',
'SessionStart',
'subagentStart',
'SubagentStart',
'subagentStop',
'SubagentStop',
'userPromptSubmitted',
'UserPromptSubmit',
'userPromptTransformed',
]);
function fieldLabel(label: string, field: string): string {
return `${label} field "${field}"`;
}
function requireString(value: unknown, label: string): string {
if (typeof value !== 'string' || value.length === 0) {
throw new Error(`${label} must be a non-empty string`);
}
return value;
}
function validateOptionalString(value: unknown, label: string): void {
if (value !== undefined && typeof value !== 'string') {
throw new Error(`${label} must be a string`);
}
}
function validateTimeout(handler: JsonObject, label: string): void {
for (const field of ['timeout', 'timeoutSec']) {
const value = handler[field];
if (value !== undefined && (typeof value !== 'number' || !Number.isFinite(value) || value <= 0)) {
throw new Error(`${fieldLabel(label, field)} must be a positive number`);
}
}
}
function validateMatcher(handler: JsonObject, event: string, label: string): void {
if (handler.matcher === undefined) return;
const matcher = requireString(handler.matcher, fieldLabel(label, 'matcher'));
if ((event === 'PreToolUse' || event === 'PermissionRequest')
&& (matcher === '*' || matcher === '**')) return;
try {
new RegExp(`^(?:${matcher})$`);
} catch (error) {
throw new Error(`${fieldLabel(label, 'matcher')} is not a valid regular expression`, {
cause: error instanceof Error ? error : new Error(String(error)),
});
}
}
function validateStringMap(value: unknown, label: string): void {
if (!isObject(value)) throw new Error(`${label} must be an object`);
for (const [key, item] of Object.entries(value)) {
requireString(item, `${label}.${key}`);
}
}
function validateCommand(handler: JsonObject, event: string, label: string): void {
const commands = ['bash', 'powershell', 'command']
.map((field) => handler[field])
.filter((value) => value !== undefined);
if (commands.length === 0) {
throw new Error(`${label} must define bash, powershell, or command`);
}
for (const field of ['bash', 'powershell', 'command', 'cwd']) {
validateOptionalString(handler[field], fieldLabel(label, field));
}
if (handler.env !== undefined) validateStringMap(handler.env, fieldLabel(label, 'env'));
validateTimeout(handler, label);
validateMatcher(handler, event, label);
}
function isLoopback(hostname: string): boolean {
return hostname === 'localhost'
|| hostname === '::1'
|| hostname.startsWith('127.');
}
function validateHttp(handler: JsonObject, event: string, label: string): void {
const rawUrl = requireString(handler.url, fieldLabel(label, 'url'));
let url: URL;
try {
url = new URL(rawUrl);
} catch (error) {
throw new Error(`${fieldLabel(label, 'url')} is invalid`, {
cause: error instanceof Error ? error : new Error(String(error)),
});
}
const localhostAllowed = process.env.COPILOT_HOOK_ALLOW_LOCALHOST === '1'
&& url.protocol === 'http:'
&& isLoopback(url.hostname);
if (url.protocol !== 'https:' && !localhostAllowed) {
throw new Error(`${fieldLabel(label, 'url')} must use HTTPS`);
}
if (handler.headers !== undefined) {
validateStringMap(handler.headers, fieldLabel(label, 'headers'));
}
if (handler.allowedEnvVars !== undefined) {
if (!Array.isArray(handler.allowedEnvVars)
|| handler.allowedEnvVars.some((value) => typeof value !== 'string' || !value)) {
throw new Error(`${fieldLabel(label, 'allowedEnvVars')} must be an array of strings`);
}
}
validateTimeout(handler, label);
validateMatcher(handler, event, label);
}
function validatePrompt(handler: JsonObject, event: string, label: string): void {
if (event !== 'sessionStart' && event !== 'SessionStart') {
throw new Error(`${label} prompt hooks are supported only for sessionStart`);
}
requireString(handler.prompt, fieldLabel(label, 'prompt'));
}
function validateHandler(handler: JsonObject, event: string, label: string): void {
const type = handler.type ?? 'command';
if (type === 'command') validateCommand(handler, event, label);
else if (type === 'http') validateHttp(handler, event, label);
else if (type === 'prompt') validatePrompt(handler, event, label);
else throw new Error(`${fieldLabel(label, 'type')} is unsupported`);
}
export function validateHooks(value: unknown, label: string): CopilotHooks {
if (value === undefined) return {};
if (!isObject(value)) throw new Error(`${label} field "hooks" must be an object`);
const hooks: CopilotHooks = {};
for (const [event, handlers] of Object.entries(value)) {
if (!SUPPORTED_EVENTS.has(event)) throw new Error(`${label} hook event "${event}" is unsupported`);
if (!Array.isArray(handlers)) throw new Error(`${label} field "hooks.${event}" must be an array`);
hooks[event] = handlers.map((handler, index) => {
const itemLabel = `${label} handler hooks.${event}[${index}]`;
if (!isObject(handler)) throw new Error(`${itemLabel} must be an object`);
validateHandler(handler, event, itemLabel);
return handler;
});
}
return hooks;
}
+68 -49
View File
@@ -1,81 +1,100 @@
import type { AgentPlugin, InstallConfig, PluginStatus } from './base.js';
import {
AGENT_KEY,
AUDIT_SCRIPT,
GUARD_SCRIPT,
buildHandler,
removeManagedHooks,
renderDocument,
runtimeContracts,
type CopilotSources,
type RenderedDocument,
} from './copilot-contract.js';
import {
readSources,
requireRuntime,
runtimeFilesExist,
writeDocuments,
} from './copilot-io.js';
commitCopilotInstallation,
commitCopilotUninstall,
preflightCopilotInstallation,
prepareCopilotInstallation,
prepareCopilotUninstall,
} from './copilot-installation.js';
import { readSources, runtimeFilesExist } from './copilot-io.js';
import { SUPPORTED_AGENTS } from './registry.js';
const entry = SUPPORTED_AGENTS.get(AGENT_KEY)!;
function mergedContracts(
userHooks: Parameters<typeof runtimeContracts>[0],
legacyHooks?: Parameters<typeof runtimeContracts>[0],
): ReturnType<typeof runtimeContracts> {
const contracts = [
...runtimeContracts(userHooks),
...runtimeContracts(legacyHooks ?? {}),
function renderInstallation(
sources: CopilotSources,
guardPath: string,
auditPath: string,
): RenderedDocument[] {
const userHooks = removeManagedHooks(sources.user.hooks);
userHooks.preToolUse = [...(userHooks.preToolUse ?? []), buildHandler(guardPath)];
userHooks.postToolUse = [...(userHooks.postToolUse ?? []), buildHandler(auditPath)];
userHooks.postToolUseFailure = [
...(userHooks.postToolUseFailure ?? []),
buildHandler(auditPath),
];
const unique = new Map(contracts.map((contract) => [contract.agentId, contract]));
const rendered = [renderDocument(sources.user, userHooks)];
if (sources.legacy) {
rendered.push(renderDocument(
sources.legacy,
removeManagedHooks(sources.legacy.hooks),
));
}
return rendered;
}
function renderUninstall(sources: CopilotSources, agentId?: string): RenderedDocument[] {
const rendered = [
renderDocument(sources.user, removeManagedHooks(sources.user.hooks, agentId)),
];
if (sources.legacy) {
rendered.push(renderDocument(
sources.legacy,
removeManagedHooks(sources.legacy.hooks, agentId),
));
}
return rendered;
}
function mergedContracts(sources: CopilotSources) {
const contracts = [
...runtimeContracts(sources.user.hooks),
...runtimeContracts(sources.legacy?.hooks ?? {}),
];
const unique = new Map(contracts.map((contract) => [
process.platform === 'win32' ? contract.agentId.toLowerCase() : contract.agentId,
contract,
]));
return [...unique.values()];
}
export const copilotPlugin: AgentPlugin = {
async install(config: InstallConfig): Promise<void> {
if (!config.agentId) throw new Error('agentId is required');
managesRuntime: true,
async preflightInstall(config: InstallConfig): Promise<void> {
const sources = await readSources();
await requireRuntime(config.guardScriptPath, 'Elydora guard runtime');
await requireRuntime(config.hookScriptPath, 'Elydora audit runtime');
await preflightCopilotInstallation(config, sources);
},
const userHooks = removeManagedHooks(sources.user.hooks);
userHooks.preToolUse = [
...(userHooks.preToolUse ?? []),
buildHandler(config.guardScriptPath),
];
userHooks.postToolUse = [
...(userHooks.postToolUse ?? []),
buildHandler(config.hookScriptPath),
];
const rendered = [renderDocument(sources.user, userHooks)];
if (sources.legacy) {
rendered.push(renderDocument(
sources.legacy,
removeManagedHooks(sources.legacy.hooks),
));
}
await writeDocuments(rendered);
async install(config: InstallConfig): Promise<void> {
const sources = await readSources();
const paths = await preflightCopilotInstallation(config, sources);
const rendered = renderInstallation(sources, paths.guardPath, paths.auditPath);
const prepared = await prepareCopilotInstallation(config, sources, rendered);
await commitCopilotInstallation(prepared);
console.log(` GitHub Copilot CLI hooks: ${sources.user.filePath}`);
console.log(' GitHub Copilot CLI: restart active sessions to load the updated hooks.');
},
async uninstall(agentId?: string): Promise<void> {
const sources = await readSources();
const rendered = [
renderDocument(sources.user, removeManagedHooks(sources.user.hooks, agentId)),
];
if (sources.legacy) {
rendered.push(renderDocument(
sources.legacy,
removeManagedHooks(sources.legacy.hooks, agentId),
));
}
await writeDocuments(rendered);
const prepared = await prepareCopilotUninstall(renderUninstall(sources, agentId));
await commitCopilotUninstall(prepared);
},
async status(): Promise<PluginStatus> {
const sources = await readSources();
const contracts = mergedContracts(sources.user.hooks, sources.legacy?.hooks);
const hookConfigured = contracts.length > 0;
const contracts = mergedContracts(sources);
const hookConfigured = sources.disabledBy === undefined && contracts.length > 0;
const hookScriptExists = hookConfigured && await runtimeFilesExist(contracts);
return {
installed: hookConfigured && hookScriptExists,
@@ -4,7 +4,11 @@ import { ensurePrivateDirectory, resolvePrivateChildDirectory } from '../runtime
import type { InstallConfig } from './base.js';
import { generateGuardScript, type GuardScriptOptions } from './guard-template.js';
import { generateHookScript, type HookScriptOptions } from './hook-template.js';
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
import {
inspectPhysicalDirectory,
readPhysicalFile,
type FileSnapshot,
} from './managed-files.js';
import {
commitManagedTransaction,
prepareManagedFileChange,
@@ -35,7 +39,8 @@ export interface ManagedHookLocation {
export interface ManagedHookSource extends ManagedHookLocation {
readonly label: string;
readonly expectedSource?: string;
readonly source: string;
readonly expectedSnapshot?: FileSnapshot;
readonly source?: string;
}
export interface ManagedRuntimeFile {
@@ -292,6 +297,7 @@ export async function prepareManagedInstallation(
next: source.source,
mode: 0o600,
expectedSource: source.expectedSource,
expectedSnapshot: source.expectedSnapshot,
verifyExpectedSource: true,
})),
]);
+44 -1
View File
@@ -17,6 +17,7 @@ export interface ManagedChangeSpec {
readonly mode: number;
readonly maximumBytes?: number;
readonly expectedSource?: string;
readonly expectedSnapshot?: FileSnapshot;
readonly verifyExpectedSource?: boolean;
}
@@ -34,11 +35,19 @@ export interface ManagedDirectory {
readonly label: string;
}
export interface ManagedFilePrecondition {
readonly filePath: string;
readonly label: string;
readonly maximumBytes: number;
readonly original?: FileSnapshot;
}
export interface PreparedManagedTransaction {
readonly displayName: string;
readonly operation?: 'install' | 'uninstall';
readonly directories: readonly ManagedDirectory[];
readonly changes: readonly ManagedFileChange[];
readonly preconditions?: readonly ManagedFilePrecondition[];
}
interface StagedChange {
@@ -88,6 +97,11 @@ export async function prepareManagedFileChange(
if (spec.verifyExpectedSource && original?.contents !== spec.expectedSource) {
throw new Error(`${spec.label} changed before installation: ${spec.filePath}`);
}
if (spec.expectedSnapshot && (!original
|| original.device !== spec.expectedSnapshot.device
|| original.inode !== spec.expectedSnapshot.inode)) {
throw new Error(`${spec.label} changed before installation: ${spec.filePath}`);
}
if (!original && spec.next === undefined) return undefined;
return {
filePath: spec.filePath,
@@ -112,6 +126,28 @@ async function assertUnchanged(change: ManagedFileChange, operationName: string)
}
}
async function assertPreconditions(
transaction: PreparedManagedTransaction,
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}`);
}
}
}
async function writeExclusive(
filePath: string,
contents: string,
@@ -336,13 +372,20 @@ export async function commitManagedTransaction(
}
targets.add(key);
}
await assertPreconditions(transaction, operationName);
for (const directory of transactionDirectories(transaction)) {
await ensureManagedDirectory(directory.path, directory.label);
}
await assertPreconditions(transaction, operationName);
const staged: StagedChange[] = [];
try {
for (const change of transaction.changes) staged.push(await stage(change, operationName));
for (const item of staged) await commit(item, operationName, renameFile);
await assertPreconditions(transaction, operationName);
for (const item of staged) {
await assertPreconditions(transaction, operationName);
await commit(item, operationName, renameFile);
}
await assertPreconditions(transaction, operationName);
} catch (error) {
const failures = [asError(error)];
for (const item of [...staged].reverse()) {
+26 -9
View File
@@ -8,6 +8,11 @@ import {
export type JsonObject = Record<string, unknown>;
interface JsonObjectParseOptions {
readonly allowTrailingComma: boolean;
readonly disallowComments: boolean;
}
export function isObject(value: unknown): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
@@ -36,12 +41,13 @@ function rejectDuplicateKeys(
}
}
export function parseStrictJsonObject(raw: string, label: string): JsonObject {
function parseJsonObject(
raw: string,
label: string,
options: JsonObjectParseOptions,
): JsonObject {
const errors: ParseError[] = [];
const value: unknown = parse(raw, errors, {
allowTrailingComma: false,
disallowComments: true,
});
const value: unknown = parse(raw, errors, options);
if (errors.length > 0) {
const details = errors
.map((error) => `${printParseErrorCode(error.error)} at offset ${error.offset}`)
@@ -49,9 +55,20 @@ export function parseStrictJsonObject(raw: string, label: string): JsonObject {
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: true,
}), label);
rejectDuplicateKeys(parseTree(raw, [], options), label);
return value;
}
export function parseStrictJsonObject(raw: string, label: string): JsonObject {
return parseJsonObject(raw, label, {
allowTrailingComma: false,
disallowComments: true,
});
}
export function parseStrictJsoncObject(raw: string, label: string): JsonObject {
return parseJsonObject(raw, label, {
allowTrailingComma: true,
disallowComments: false,
});
}