@rbbtsn0w/adg 0.4.0-beta.3 → 0.4.0-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/adapters/anthropic.js +51 -2
- package/dist/src/adapters/codex.js +33 -1
- package/dist/src/adapters/index.js +2 -2
- package/dist/src/agents/claude.js +7 -1
- package/dist/src/cli/handlers.js +14 -0
- package/dist/src/cli/index.js +11 -0
- package/dist/src/commands/adapt.js +8 -0
- package/dist/src/commands/install.js +30 -3
- package/dist/src/hooks.js +262 -0
- package/docs/authoring.md +58 -1
- package/package.json +1 -1
- package/schemas/adg-hooks.schema.json +70 -0
|
@@ -1,6 +1,52 @@
|
|
|
1
|
+
import { existsSync, readdirSync, statSync } from "node:fs";
|
|
1
2
|
import { join } from "node:path";
|
|
2
3
|
import { resolveProjectedSkills } from "../skills.js";
|
|
3
4
|
import { isExposed } from "../components.js";
|
|
5
|
+
/**
|
|
6
|
+
* Claude auto-loads this plugin-relative path; declaring it in `manifest.hooks`
|
|
7
|
+
* duplicates the load and fails ("Duplicate hooks file detected").
|
|
8
|
+
*/
|
|
9
|
+
const STANDARD_HOOKS = "hooks/hooks.json";
|
|
10
|
+
/**
|
|
11
|
+
* Translate ADG's `hooks` (a *directory*, per the universal manifest) into the
|
|
12
|
+
* value Claude's plugin.json expects, or undefined to omit the field.
|
|
13
|
+
*
|
|
14
|
+
* Two Claude rules drive this:
|
|
15
|
+
* - `hooks` must be a config *file*, not a directory — a bare `./hooks/` is
|
|
16
|
+
* rejected with `hooks: Invalid input`, breaking `claude plugin install`.
|
|
17
|
+
* - the standard `hooks/hooks.json` is loaded automatically, so `manifest.hooks`
|
|
18
|
+
* must reference only *additional* files — repeating the standard path fails
|
|
19
|
+
* to load with "Duplicate hooks file detected".
|
|
20
|
+
*
|
|
21
|
+
* So: resolve the directory to its config file (conventional `hooks.json`, else
|
|
22
|
+
* its sole `*.json`), pass an explicit `*.json` reference through, and return
|
|
23
|
+
* undefined when the result is unresolvable/ambiguous OR is the auto-loaded
|
|
24
|
+
* standard path — in every "undefined" case the caller omits `hooks`.
|
|
25
|
+
*/
|
|
26
|
+
export function resolveClaudeHooksFile(pluginDir, hooks) {
|
|
27
|
+
const rel = hooks.replace(/\/+$/, "");
|
|
28
|
+
const abs = join(pluginDir, rel);
|
|
29
|
+
let file;
|
|
30
|
+
if (existsSync(abs) && statSync(abs).isFile()) {
|
|
31
|
+
file = hooks.endsWith(".json") ? hooks : undefined;
|
|
32
|
+
}
|
|
33
|
+
else if (existsSync(abs) && statSync(abs).isDirectory()) {
|
|
34
|
+
if (existsSync(join(abs, "hooks.json")))
|
|
35
|
+
file = `${rel}/hooks.json`;
|
|
36
|
+
else {
|
|
37
|
+
const jsons = readdirSync(abs).filter((f) => f.endsWith(".json") && statSync(join(abs, f)).isFile());
|
|
38
|
+
file = jsons.length === 1 ? `${rel}/${jsons[0]}` : undefined;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
// Path missing on disk: only trust an explicit file reference.
|
|
43
|
+
file = hooks.endsWith(".json") ? hooks : undefined;
|
|
44
|
+
}
|
|
45
|
+
if (!file)
|
|
46
|
+
return undefined;
|
|
47
|
+
// Drop the auto-loaded standard path; only non-standard hook files belong here.
|
|
48
|
+
return file.replace(/^\.\//, "") === STANDARD_HOOKS ? undefined : file;
|
|
49
|
+
}
|
|
4
50
|
/**
|
|
5
51
|
* Generate a Claude (.claude-plugin/plugin.json) manifest from an ADG manifest.
|
|
6
52
|
*
|
|
@@ -27,8 +73,11 @@ export function toAnthropicManifest(pluginDir, manifest, selection) {
|
|
|
27
73
|
out.commands = manifest.commands;
|
|
28
74
|
if (manifest.agents && isExposed(selection, "agents"))
|
|
29
75
|
out.agents = manifest.agents;
|
|
30
|
-
if (manifest.hooks && isExposed(selection, "hooks"))
|
|
31
|
-
|
|
76
|
+
if (manifest.hooks && isExposed(selection, "hooks")) {
|
|
77
|
+
const hooksFile = resolveClaudeHooksFile(pluginDir, manifest.hooks);
|
|
78
|
+
if (hooksFile)
|
|
79
|
+
out.hooks = hooksFile;
|
|
80
|
+
}
|
|
32
81
|
if (manifest.mcp && isExposed(selection, "mcp"))
|
|
33
82
|
out.mcp = manifest.mcp;
|
|
34
83
|
if (manifest.apps && isExposed(selection, "apps"))
|
|
@@ -1,5 +1,30 @@
|
|
|
1
|
+
import { existsSync, readdirSync, statSync } from "node:fs";
|
|
1
2
|
import { join } from "node:path";
|
|
2
3
|
import { resolveProjectedSkills } from "../skills.js";
|
|
4
|
+
import { isExposed } from "../components.js";
|
|
5
|
+
/**
|
|
6
|
+
* Resolve the hooks config *file* Codex should reference. ADG declares `hooks` as
|
|
7
|
+
* a directory, but Codex (unlike Claude) has no auto-load — it needs an explicit
|
|
8
|
+
* file path. Prefer a Codex-specific variant (`hooks/hooks-codex.json`, the
|
|
9
|
+
* convention upstream plugins like superpowers use), then the standard
|
|
10
|
+
* `hooks/hooks.json`, else the directory's sole `*.json`. An explicit `*.json`
|
|
11
|
+
* reference passes through; an unresolvable/ambiguous directory yields undefined
|
|
12
|
+
* so the caller omits `hooks`.
|
|
13
|
+
*/
|
|
14
|
+
export function resolveCodexHooksFile(pluginDir, hooks) {
|
|
15
|
+
const rel = hooks.replace(/\/+$/, "");
|
|
16
|
+
const abs = join(pluginDir, rel);
|
|
17
|
+
if (existsSync(abs) && statSync(abs).isDirectory()) {
|
|
18
|
+
for (const candidate of ["hooks-codex.json", "hooks.json"]) {
|
|
19
|
+
if (existsSync(join(abs, candidate)))
|
|
20
|
+
return `${rel}/${candidate}`;
|
|
21
|
+
}
|
|
22
|
+
const jsons = readdirSync(abs).filter((f) => f.endsWith(".json") && statSync(join(abs, f)).isFile());
|
|
23
|
+
return jsons.length === 1 ? `${rel}/${jsons[0]}` : undefined;
|
|
24
|
+
}
|
|
25
|
+
// A file (or a path missing on disk): only trust an explicit *.json reference.
|
|
26
|
+
return hooks.endsWith(".json") ? hooks : undefined;
|
|
27
|
+
}
|
|
3
28
|
/**
|
|
4
29
|
* Generate a Codex (.codex-plugin/plugin.json) manifest from an ADG manifest.
|
|
5
30
|
*
|
|
@@ -10,7 +35,9 @@ import { resolveProjectedSkills } from "../skills.js";
|
|
|
10
35
|
* (an explicit `skills` array, a partial install `selection`, or `strict: false`)
|
|
11
36
|
* emits the bare skill-id array Codex expects: `manifest.skills` arrays are
|
|
12
37
|
* declared as *paths* (`./skills/foo`), so they are resolved to identifiers
|
|
13
|
-
* rather than passed through. Codex
|
|
38
|
+
* rather than passed through. Beyond skills, Codex also consumes `hooks` — but as
|
|
39
|
+
* an explicit config *file* (no auto-load), so a declared hooks directory is
|
|
40
|
+
* resolved to its Codex-variant file via `resolveCodexHooksFile`.
|
|
14
41
|
*/
|
|
15
42
|
export function toCodexManifest(pluginDir, manifest, selection) {
|
|
16
43
|
// Codex's array form is bare ids, so a strict skills *array* is resolved to
|
|
@@ -28,5 +55,10 @@ export function toCodexManifest(pluginDir, manifest, selection) {
|
|
|
28
55
|
out.homepage = manifest.homepage;
|
|
29
56
|
if (manifest.license)
|
|
30
57
|
out.license = manifest.license;
|
|
58
|
+
if (manifest.hooks && isExposed(selection, "hooks")) {
|
|
59
|
+
const hooksFile = resolveCodexHooksFile(pluginDir, manifest.hooks);
|
|
60
|
+
if (hooksFile)
|
|
61
|
+
out.hooks = hooksFile;
|
|
62
|
+
}
|
|
31
63
|
return { defaultPath: join(".codex-plugin", "plugin.json"), manifest: out };
|
|
32
64
|
}
|
|
@@ -16,7 +16,7 @@ export const ADAPTER_TARGETS = ["claude", "codex", "antigravity"];
|
|
|
16
16
|
/**
|
|
17
17
|
* Component categories each adapter target can actually express, mirroring what
|
|
18
18
|
* the adapters emit: the Claude manifest carries skills/agents/commands/hooks/mcp
|
|
19
|
-
* plus apps (`toAnthropicManifest`), while Codex
|
|
19
|
+
* plus apps (`toAnthropicManifest`), while Codex consumes skills and hooks
|
|
20
20
|
* (`toCodexManifest`). Antigravity (`agy`) discovers components by convention
|
|
21
21
|
* (skills/agents/commands/hooks dirs + mcp_config.json) and does not surface
|
|
22
22
|
* apps, so apps maps only to the Claude target. Used to derive which agents a
|
|
@@ -24,7 +24,7 @@ export const ADAPTER_TARGETS = ["claude", "codex", "antigravity"];
|
|
|
24
24
|
*/
|
|
25
25
|
export const ADAPTER_COMPONENTS = {
|
|
26
26
|
claude: ["skills", "agents", "commands", "hooks", "mcp", "apps"],
|
|
27
|
-
codex: ["skills"],
|
|
27
|
+
codex: ["skills", "hooks"],
|
|
28
28
|
antigravity: ["skills", "agents", "commands", "hooks", "mcp"],
|
|
29
29
|
};
|
|
30
30
|
export { toAnthropicManifest, toCodexManifest, toAntigravityManifest };
|
|
@@ -81,8 +81,14 @@ export const claudeAgent = {
|
|
|
81
81
|
syncMarketplace(ctx.pluginsDir);
|
|
82
82
|
const affected = [];
|
|
83
83
|
for (const p of ctx.plugins) {
|
|
84
|
-
|
|
84
|
+
const r = run(["plugin", "install", `${p}@${MARKETPLACE}`, "--scope", ctx.scope]);
|
|
85
|
+
if (r.ok)
|
|
85
86
|
affected.push(p);
|
|
87
|
+
// Surface the CLI's reason instead of silently dropping the plugin — a
|
|
88
|
+
// rejected manifest (e.g. `hooks: Invalid input`) otherwise looks like a
|
|
89
|
+
// no-op "missing" with no diagnostic.
|
|
90
|
+
else
|
|
91
|
+
console.error(`claude: failed to install ${p}@${MARKETPLACE}: ${r.out.trim()}`);
|
|
86
92
|
}
|
|
87
93
|
return { agent: "claude", affected, skipped: false };
|
|
88
94
|
},
|
package/dist/src/cli/handlers.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
2
|
import { resolve } from "node:path";
|
|
3
3
|
import { adaptPlugin } from "../commands/adapt.js";
|
|
4
|
+
import { liftHooksFromDisk } from "../hooks.js";
|
|
4
5
|
import { addPlugins } from "../commands/install.js";
|
|
5
6
|
import { validatePlugin } from "../commands/validate.js";
|
|
6
7
|
import { listPlugins } from "../commands/list.js";
|
|
@@ -184,6 +185,19 @@ async function runPluginsVerb(verb, rest, cmd) {
|
|
|
184
185
|
}
|
|
185
186
|
return;
|
|
186
187
|
}
|
|
188
|
+
case "lift-hooks": {
|
|
189
|
+
const { positionals } = parseVerb(verb, cmd.flags, rest);
|
|
190
|
+
const pluginDir = resolve(positionals[0] ?? process.cwd());
|
|
191
|
+
const res = liftHooksFromDisk(pluginDir);
|
|
192
|
+
if (!res) {
|
|
193
|
+
console.log(ui.meta(`no native hooks found in ${pluginDir} (looked for hooks/hooks.json, hooks/hooks-codex.json)`));
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
console.log(`${ui.ok("lifted")} ${ui.name(res.sources.join(" + "))} ${ui.meta(`-> ${res.file}`)}`);
|
|
197
|
+
for (const w of res.warnings)
|
|
198
|
+
console.error(ui.warn(` ${w}`));
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
187
201
|
case "validate": {
|
|
188
202
|
const { positionals } = parseVerb(verb, cmd.flags, rest);
|
|
189
203
|
const pluginDir = resolve(positionals[0] ?? process.cwd());
|
package/dist/src/cli/index.js
CHANGED
|
@@ -111,6 +111,17 @@ export const PLUGIN_COMMANDS = {
|
|
|
111
111
|
positional: "<dir> plugin directory (default: current directory)",
|
|
112
112
|
flags: [],
|
|
113
113
|
},
|
|
114
|
+
"lift-hooks": {
|
|
115
|
+
summary: "unify native hook files into a universal .agents/hooks.json",
|
|
116
|
+
synopsis: "adg plugins lift-hooks [<dir>]",
|
|
117
|
+
positional: "<dir> plugin directory (default: current directory)",
|
|
118
|
+
blurb: "The inverse of the hooks DSL compile: read a plugin's native hooks\n" +
|
|
119
|
+
"(hooks/hooks.json, hooks/hooks-codex.json), canonicalize the env token, and\n" +
|
|
120
|
+
"fold the per-agent differences (matcher/command) into one .agents/hooks.json\n" +
|
|
121
|
+
"(adg.hooks/v1) so you maintain a single source. The native files are left in\n" +
|
|
122
|
+
"place; a later `adapt` regenerates them from the DSL.",
|
|
123
|
+
flags: [],
|
|
124
|
+
},
|
|
114
125
|
"import-skills": {
|
|
115
126
|
summary: "wrap an existing skills/ dir as a plugin",
|
|
116
127
|
synopsis: "adg plugins import-skills <skills-dir> --as <name>",
|
|
@@ -2,6 +2,7 @@ import { join } from "node:path";
|
|
|
2
2
|
import { ADAPTERS } from "../adapters/index.js";
|
|
3
3
|
import { readManifest } from "../manifest.js";
|
|
4
4
|
import { writeJson } from "../fsutil.js";
|
|
5
|
+
import { compileHooksToDisk } from "../hooks.js";
|
|
5
6
|
/**
|
|
6
7
|
* Generate runtime-specific manifests for the given targets from a plugin's
|
|
7
8
|
* .agents/.plugin.json. The output path honors the manifest's `adapters`
|
|
@@ -11,6 +12,13 @@ import { writeJson } from "../fsutil.js";
|
|
|
11
12
|
export function adaptPlugin(pluginDir, targets, selection) {
|
|
12
13
|
const manifest = readManifest(pluginDir);
|
|
13
14
|
const results = [];
|
|
15
|
+
// Compile the universal hooks DSL (if any) to each target's native hook file
|
|
16
|
+
// first, so the adapters' hooks resolvers see the generated files. A no-op for
|
|
17
|
+
// plugins that ship hand-authored hooks. Warnings surface but never block.
|
|
18
|
+
for (const compiled of compileHooksToDisk(pluginDir, targets)) {
|
|
19
|
+
for (const w of compiled.warnings)
|
|
20
|
+
console.error(`hooks: ${w}`);
|
|
21
|
+
}
|
|
14
22
|
for (const target of targets) {
|
|
15
23
|
const adapter = ADAPTERS[target];
|
|
16
24
|
if (!adapter)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
1
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
|
|
2
2
|
import { tmpdir } from "node:os";
|
|
3
3
|
import { basename, join, relative, resolve } from "node:path";
|
|
4
4
|
import { ADAPTER_TARGETS } from "../adapters/index.js";
|
|
@@ -6,6 +6,7 @@ import { fromNativeManifest } from "../adapters/reverse.js";
|
|
|
6
6
|
import { adaptPlugin } from "./adapt.js";
|
|
7
7
|
import { copyPluginDir, toPosix, writeJson } from "../fsutil.js";
|
|
8
8
|
import { folderHash } from "../hash.js";
|
|
9
|
+
import { ADG_HOOKS_PATH, GENERATED_HOOK_FILES } from "../hooks.js";
|
|
9
10
|
import { packageFilter, PROJECTION_DIRS } from "../package.js";
|
|
10
11
|
import { lockPath, marketplacePath, marketplaceSourcePath, pluginDir } from "../paths.js";
|
|
11
12
|
import { readLock, upsertEntry, writeLock } from "../lock.js";
|
|
@@ -19,6 +20,23 @@ import { skillDescriptionLoader } from "../skills.js";
|
|
|
19
20
|
import { resolveAgents } from "../agents/index.js";
|
|
20
21
|
// Generated runtime projections never count toward a plugin's content hash.
|
|
21
22
|
const HASH_IGNORE = PROJECTION_DIRS;
|
|
23
|
+
/**
|
|
24
|
+
* Content hash over a plugin's packaged payload. Mirrors the projection rule for
|
|
25
|
+
* the hooks DSL: when a plugin opts in (`.agents/hooks.json` present), the
|
|
26
|
+
* compiled `hooks/*.json` outputs are generated, so they are excluded from the
|
|
27
|
+
* hash — letting an authoring source (no compiled files) and an installed copy
|
|
28
|
+
* (with them) hash identically, and keeping a compiler change from bumping the
|
|
29
|
+
* content hash.
|
|
30
|
+
*/
|
|
31
|
+
function contentHash(dir, manifest) {
|
|
32
|
+
const base = packageFilter(manifest, { includeProjections: false });
|
|
33
|
+
// `GENERATED_HOOK_FILES` keys are POSIX; normalize so a backslash path (Windows)
|
|
34
|
+
// still matches and the generated files are excluded from the hash there too.
|
|
35
|
+
const include = existsSync(join(dir, ADG_HOOKS_PATH))
|
|
36
|
+
? (rel) => base(rel) && !GENERATED_HOOK_FILES.has(toPosix(rel))
|
|
37
|
+
: base;
|
|
38
|
+
return folderHash(dir, HASH_IGNORE, include);
|
|
39
|
+
}
|
|
22
40
|
/**
|
|
23
41
|
* Install a single local plugin directory into a plugins directory: copy the
|
|
24
42
|
* source, generate adapter manifests, compute the folder hash, and update both
|
|
@@ -48,7 +66,7 @@ export function installPlugin(opts) {
|
|
|
48
66
|
// copy) and, when asked, short-circuit if it matches what's already recorded —
|
|
49
67
|
// so an unchanged upstream source is never re-copied, re-adapted, or re-locked.
|
|
50
68
|
if (opts.skipUnchanged && prev) {
|
|
51
|
-
const sourceHash =
|
|
69
|
+
const sourceHash = contentHash(source, manifest);
|
|
52
70
|
if (prev.folderHash === sourceHash && prev.version === manifest.version) {
|
|
53
71
|
return { name, installedTo: dest, folderHash: sourceHash, adapted: [], changed: false };
|
|
54
72
|
}
|
|
@@ -65,7 +83,7 @@ export function installPlugin(opts) {
|
|
|
65
83
|
const selection = opts.selection ?? prev?.selection;
|
|
66
84
|
const targets = opts.targets ?? [...ADAPTER_TARGETS];
|
|
67
85
|
const adapted = adaptPlugin(dest, targets, selection).map((r) => r.file);
|
|
68
|
-
const hash =
|
|
86
|
+
const hash = contentHash(dest, manifest);
|
|
69
87
|
const changed = !prev || prev.folderHash !== hash || prev.version !== manifest.version;
|
|
70
88
|
const entry = {
|
|
71
89
|
origin,
|
|
@@ -112,6 +130,15 @@ function discoverPlugins(root) {
|
|
|
112
130
|
continue;
|
|
113
131
|
const raw = JSON.parse(readFileSync(native.manifestFile, "utf8"));
|
|
114
132
|
const manifest = fromNativeManifest(raw, native.kind);
|
|
133
|
+
// A Claude manifest omits `hooks` (Claude auto-loads hooks/hooks.json), and
|
|
134
|
+
// `walkNative` prefers it over a sibling Codex manifest that *does* declare
|
|
135
|
+
// hooks — so the reverse-adapt would silently drop the hooks payload. Recover
|
|
136
|
+
// it from disk: a hooks/ directory means the ADG manifest must declare it, or
|
|
137
|
+
// packagedRoots won't copy it and every downstream projection loses hooks.
|
|
138
|
+
const hooksDir = join(native.dir, "hooks");
|
|
139
|
+
if (!manifest.hooks && existsSync(hooksDir) && statSync(hooksDir).isDirectory()) {
|
|
140
|
+
manifest.hooks = "./hooks/";
|
|
141
|
+
}
|
|
115
142
|
writeJson(join(native.dir, ADG_MANIFEST_PATH), manifest);
|
|
116
143
|
converted.push(manifest.name);
|
|
117
144
|
}
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { writeJson } from "./fsutil.js";
|
|
4
|
+
/**
|
|
5
|
+
* ADG universal hooks DSL (`adg.hooks/v1`) and its per-agent compiler.
|
|
6
|
+
*
|
|
7
|
+
* Agents do not share a hook format: Claude auto-loads `hooks/hooks.json` and
|
|
8
|
+
* uses `${CLAUDE_PLUGIN_ROOT}`; Codex references an explicit file and uses
|
|
9
|
+
* `${PLUGIN_ROOT}`; and real plugins (e.g. superpowers) genuinely diverge per
|
|
10
|
+
* agent — different matcher vocabularies (`clear|compact` vs `resume|clear`) and
|
|
11
|
+
* even different scripts. So the DSL is authored once with a canonical
|
|
12
|
+
* `${PLUGIN_ROOT}` token, and carries *optional* per-target overrides for the
|
|
13
|
+
* parts that truly differ. The compiler resolves overrides, translates the env
|
|
14
|
+
* token, and warns (never silently drops) on events a target may not support.
|
|
15
|
+
*
|
|
16
|
+
* The universal source lives at `.agents/hooks.json` and is opt-in: plugins that
|
|
17
|
+
* still ship hand-authored `hooks/*.json` keep working unchanged.
|
|
18
|
+
*/
|
|
19
|
+
export const ADG_HOOKS_SCHEMA_VERSION = "adg.hooks/v1";
|
|
20
|
+
/** Canonical location of the universal hooks document inside a plugin. */
|
|
21
|
+
export const ADG_HOOKS_PATH = ".agents/hooks.json";
|
|
22
|
+
/**
|
|
23
|
+
* Where each target's compiled hook file lands (plugin-relative, POSIX). Claude
|
|
24
|
+
* auto-loads `hooks/hooks.json`; Codex references `hooks/hooks-codex.json` from
|
|
25
|
+
* its manifest. These are generated outputs — shipped, but excluded from the
|
|
26
|
+
* content hash (see `GENERATED_HOOK_FILES`).
|
|
27
|
+
*/
|
|
28
|
+
export const HOOK_OUTPUT = {
|
|
29
|
+
claude: "hooks/hooks.json",
|
|
30
|
+
codex: "hooks/hooks-codex.json",
|
|
31
|
+
};
|
|
32
|
+
/** The set of generated hook files, treated like adapter projections (not hashed). */
|
|
33
|
+
export const GENERATED_HOOK_FILES = new Set(Object.values(HOOK_OUTPUT));
|
|
34
|
+
/** The plugin-root env variable each target expands. */
|
|
35
|
+
const ENV_TOKEN = {
|
|
36
|
+
claude: "CLAUDE_PLUGIN_ROOT",
|
|
37
|
+
codex: "PLUGIN_ROOT",
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Documented hook events. Used only to *warn* on an unfamiliar event — the
|
|
41
|
+
* compiler still emits it, so an event this list hasn't caught up with is never
|
|
42
|
+
* silently dropped. (Codex's vocabulary is not fully published; this is Claude's
|
|
43
|
+
* set, treated as the canonical baseline.)
|
|
44
|
+
*/
|
|
45
|
+
const KNOWN_EVENTS = new Set([
|
|
46
|
+
"PreToolUse",
|
|
47
|
+
"PostToolUse",
|
|
48
|
+
"UserPromptSubmit",
|
|
49
|
+
"Notification",
|
|
50
|
+
"Stop",
|
|
51
|
+
"SubagentStop",
|
|
52
|
+
"PreCompact",
|
|
53
|
+
"SessionStart",
|
|
54
|
+
"SessionEnd",
|
|
55
|
+
]);
|
|
56
|
+
/** Reserved object keys that must never be used as event names (prototype-pollution guard). */
|
|
57
|
+
const UNSAFE_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
|
58
|
+
const isUnsafeKey = (key) => UNSAFE_KEYS.has(key);
|
|
59
|
+
/** Replace the canonical `${PLUGIN_ROOT}` token with the target's env variable. */
|
|
60
|
+
function translateEnv(value, target) {
|
|
61
|
+
// Function replacement so `$` in the substitution is never treated specially.
|
|
62
|
+
return value.replaceAll("${PLUGIN_ROOT}", () => `\${${ENV_TOKEN[target]}}`);
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Compile the universal hooks document into one target's native `hooks.json`
|
|
66
|
+
* object, resolving per-target overrides and translating the env token. Returns
|
|
67
|
+
* the native object plus any non-fatal warnings (unknown events).
|
|
68
|
+
*/
|
|
69
|
+
export function compileHooks(src, target) {
|
|
70
|
+
const warnings = [];
|
|
71
|
+
const out = { hooks: {} };
|
|
72
|
+
for (const [event, entries] of Object.entries(src.hooks)) {
|
|
73
|
+
if (isUnsafeKey(event)) {
|
|
74
|
+
// Defensive: a reserved name (e.g. "__proto__") would mutate the map's
|
|
75
|
+
// prototype rather than add an event. parseAdgHooks rejects these at the
|
|
76
|
+
// authoring boundary; skip-with-warning covers direct callers.
|
|
77
|
+
warnings.push(`skipped reserved hook event name "${event}"`);
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (!KNOWN_EVENTS.has(event)) {
|
|
81
|
+
warnings.push(`unknown hook event "${event}" — emitted for ${target} but it may not fire`);
|
|
82
|
+
}
|
|
83
|
+
out.hooks[event] = entries.map((entry) => {
|
|
84
|
+
const matcher = entry.matcherByTarget?.[target] ?? entry.matcher;
|
|
85
|
+
const actions = entry.actions.map((a) => {
|
|
86
|
+
const command = translateEnv(a.commandByTarget?.[target] ?? a.command, target);
|
|
87
|
+
return { type: a.type, command, ...(a.async !== undefined ? { async: a.async } : {}) };
|
|
88
|
+
});
|
|
89
|
+
return { ...(matcher !== undefined ? { matcher } : {}), hooks: actions };
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
return { hooks: out, warnings };
|
|
93
|
+
}
|
|
94
|
+
/** Rewrite any agent's plugin-root token back to the canonical `${PLUGIN_ROOT}`. */
|
|
95
|
+
function canonicalizeEnv(value) {
|
|
96
|
+
return value.replaceAll("${CLAUDE_PLUGIN_ROOT}", () => "${PLUGIN_ROOT}");
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Lift native hook files into one universal document — the inverse of
|
|
100
|
+
* `compileHooks`. Where the targets agree, a single canonical value is emitted;
|
|
101
|
+
* where they genuinely diverge (matcher or command), the difference is captured
|
|
102
|
+
* as a per-target override, so recompiling reproduces each native file. Targets
|
|
103
|
+
* are aligned positionally per event; a shape mismatch is reported (not dropped)
|
|
104
|
+
* and the primary (Claude when present) is used as the structural base.
|
|
105
|
+
*/
|
|
106
|
+
export function liftHooks(natives) {
|
|
107
|
+
const warnings = [];
|
|
108
|
+
const present = Object.keys(natives).filter((t) => natives[t]);
|
|
109
|
+
const events = new Set(present.flatMap((t) => Object.keys(natives[t].hooks)));
|
|
110
|
+
const out = { schemaVersion: ADG_HOOKS_SCHEMA_VERSION, hooks: {} };
|
|
111
|
+
for (const event of events) {
|
|
112
|
+
if (isUnsafeKey(event)) {
|
|
113
|
+
warnings.push(`skipped reserved hook event name "${event}"`);
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
// An event only some targets define becomes a *shared* entry after compile —
|
|
117
|
+
// so it would start firing on agents that never had it. Surface that.
|
|
118
|
+
const definedIn = present.filter((t) => natives[t].hooks[event]);
|
|
119
|
+
if (present.length > 1 && definedIn.length < present.length) {
|
|
120
|
+
warnings.push(`hook event "${event}" is only defined for ${definedIn.join(", ")}; it will apply to every agent after compile`);
|
|
121
|
+
}
|
|
122
|
+
const primary = natives.claude?.hooks[event] ? "claude" : "codex";
|
|
123
|
+
const other = present.find((t) => t !== primary && natives[t].hooks[event]);
|
|
124
|
+
const baseEntries = natives[primary].hooks[event];
|
|
125
|
+
const otherEntries = other ? natives[other].hooks[event] : undefined;
|
|
126
|
+
if (other && otherEntries && otherEntries.length !== baseEntries.length) {
|
|
127
|
+
warnings.push(`hook event "${event}" has a different shape per target; lifted from ${primary}`);
|
|
128
|
+
}
|
|
129
|
+
out.hooks[event] = baseEntries.map((entry, i) => {
|
|
130
|
+
const oEntry = otherEntries?.[i];
|
|
131
|
+
const adg = { actions: [] };
|
|
132
|
+
if (entry.matcher !== undefined)
|
|
133
|
+
adg.matcher = entry.matcher;
|
|
134
|
+
if (other && oEntry && oEntry.matcher !== undefined && oEntry.matcher !== entry.matcher) {
|
|
135
|
+
adg.matcherByTarget = { [other]: oEntry.matcher };
|
|
136
|
+
}
|
|
137
|
+
adg.actions = entry.hooks.map((act, j) => {
|
|
138
|
+
const a = { type: "command", command: canonicalizeEnv(act.command) };
|
|
139
|
+
if (act.async !== undefined)
|
|
140
|
+
a.async = act.async;
|
|
141
|
+
const oAct = oEntry?.hooks[j];
|
|
142
|
+
if (other && oAct) {
|
|
143
|
+
const oCmd = canonicalizeEnv(oAct.command);
|
|
144
|
+
if (oCmd !== a.command)
|
|
145
|
+
a.commandByTarget = { [other]: oCmd };
|
|
146
|
+
}
|
|
147
|
+
return a;
|
|
148
|
+
});
|
|
149
|
+
return adg;
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
return { hooks: out, warnings };
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Read a plugin's native hook files (`hooks/hooks.json`, `hooks/hooks-codex.json`)
|
|
156
|
+
* and lift them into one universal `.agents/hooks.json`, the inverse of the
|
|
157
|
+
* compile step. Returns undefined when the plugin ships no native hooks (nothing
|
|
158
|
+
* to convert). The native files are left in place — a later adapt regenerates
|
|
159
|
+
* them from the DSL. Throws on a malformed native file rather than guessing.
|
|
160
|
+
*/
|
|
161
|
+
export function liftHooksFromDisk(pluginDir) {
|
|
162
|
+
const natives = {};
|
|
163
|
+
const sources = [];
|
|
164
|
+
for (const target of Object.keys(HOOK_OUTPUT)) {
|
|
165
|
+
const file = join(pluginDir, HOOK_OUTPUT[target]);
|
|
166
|
+
if (!existsSync(file))
|
|
167
|
+
continue;
|
|
168
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
169
|
+
const hooksMap = parsed?.hooks;
|
|
170
|
+
// `typeof null === "object"`, so guard the `hooks` map against null explicitly.
|
|
171
|
+
if (typeof parsed !== "object" || parsed === null || typeof hooksMap !== "object" || hooksMap === null) {
|
|
172
|
+
throw new Error(`${HOOK_OUTPUT[target]} is not a valid hooks file (missing \`hooks\` map)`);
|
|
173
|
+
}
|
|
174
|
+
natives[target] = parsed;
|
|
175
|
+
sources.push(target);
|
|
176
|
+
}
|
|
177
|
+
if (sources.length === 0)
|
|
178
|
+
return undefined;
|
|
179
|
+
const { hooks, warnings } = liftHooks(natives);
|
|
180
|
+
writeJson(join(pluginDir, ADG_HOOKS_PATH), hooks);
|
|
181
|
+
return { file: ADG_HOOKS_PATH, sources, warnings };
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* If `pluginDir` opts into the DSL (has `.agents/hooks.json`), compile it to each
|
|
185
|
+
* requested target's native hook file and write them under `hooks/`. A no-op
|
|
186
|
+
* (returns []) when the DSL source is absent — plugins shipping hand-authored
|
|
187
|
+
* `hooks/*.json` are left untouched. Only claude/codex are compiled today;
|
|
188
|
+
* targets without a `HOOK_OUTPUT` mapping (e.g. antigravity) are skipped.
|
|
189
|
+
*/
|
|
190
|
+
export function compileHooksToDisk(pluginDir, targets) {
|
|
191
|
+
const src = join(pluginDir, ADG_HOOKS_PATH);
|
|
192
|
+
if (!existsSync(src))
|
|
193
|
+
return [];
|
|
194
|
+
const doc = parseAdgHooks(JSON.parse(readFileSync(src, "utf8")));
|
|
195
|
+
const written = [];
|
|
196
|
+
for (const target of targets) {
|
|
197
|
+
if (!(target in HOOK_OUTPUT))
|
|
198
|
+
continue;
|
|
199
|
+
const t = target;
|
|
200
|
+
const { hooks, warnings } = compileHooks(doc, t);
|
|
201
|
+
const rel = HOOK_OUTPUT[t];
|
|
202
|
+
writeJson(join(pluginDir, rel), hooks);
|
|
203
|
+
written.push({ file: rel, warnings });
|
|
204
|
+
}
|
|
205
|
+
return written;
|
|
206
|
+
}
|
|
207
|
+
const VALID_TARGETS = new Set(["claude", "codex"]);
|
|
208
|
+
/** Reject an unknown target key in an override map — it would be silently ignored at compile time. */
|
|
209
|
+
function checkTargetKeys(value, where) {
|
|
210
|
+
if (value === undefined)
|
|
211
|
+
return;
|
|
212
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
213
|
+
throw new Error(`${where} must be an object keyed by target`);
|
|
214
|
+
}
|
|
215
|
+
for (const [key, val] of Object.entries(value)) {
|
|
216
|
+
if (!VALID_TARGETS.has(key))
|
|
217
|
+
throw new Error(`${where} has unknown target "${key}" (expected claude|codex)`);
|
|
218
|
+
// A non-string override would crash translateEnv (`.replaceAll` on a non-string).
|
|
219
|
+
if (typeof val !== "string")
|
|
220
|
+
throw new Error(`${where} value for target "${key}" must be a string`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Parse and shallowly validate a raw `.agents/hooks.json` payload. Throws with a
|
|
225
|
+
* pointed message rather than letting a malformed document surface as a deep
|
|
226
|
+
* runtime error during compilation.
|
|
227
|
+
*/
|
|
228
|
+
export function parseAdgHooks(raw) {
|
|
229
|
+
if (typeof raw !== "object" || raw === null)
|
|
230
|
+
throw new Error("hooks document must be a JSON object");
|
|
231
|
+
const d = raw;
|
|
232
|
+
if (d.schemaVersion !== ADG_HOOKS_SCHEMA_VERSION) {
|
|
233
|
+
throw new Error(`hooks document must declare schemaVersion "${ADG_HOOKS_SCHEMA_VERSION}"`);
|
|
234
|
+
}
|
|
235
|
+
if (typeof d.hooks !== "object" || d.hooks === null)
|
|
236
|
+
throw new Error("hooks document missing `hooks` map");
|
|
237
|
+
for (const [event, entries] of Object.entries(d.hooks)) {
|
|
238
|
+
if (isUnsafeKey(event))
|
|
239
|
+
throw new Error(`hook event name "${event}" is reserved and not allowed`);
|
|
240
|
+
if (!Array.isArray(entries))
|
|
241
|
+
throw new Error(`hook event "${event}" must be an array of entries`);
|
|
242
|
+
for (const entry of entries) {
|
|
243
|
+
if (typeof entry !== "object" || entry === null)
|
|
244
|
+
throw new Error(`hook event "${event}" entry must be an object`);
|
|
245
|
+
const e = entry;
|
|
246
|
+
if (!Array.isArray(e.actions))
|
|
247
|
+
throw new Error(`hook event "${event}" entry missing \`actions\` array`);
|
|
248
|
+
checkTargetKeys(e.matcherByTarget, `hook event "${event}" matcherByTarget`);
|
|
249
|
+
for (const action of e.actions) {
|
|
250
|
+
if (typeof action !== "object" || action === null)
|
|
251
|
+
throw new Error(`hook action in "${event}" must be an object`);
|
|
252
|
+
const a = action;
|
|
253
|
+
if (a.type !== "command")
|
|
254
|
+
throw new Error(`hook action in "${event}" must have type "command"`);
|
|
255
|
+
if (typeof a.command !== "string")
|
|
256
|
+
throw new Error(`hook action in "${event}" missing string \`command\``);
|
|
257
|
+
checkTargetKeys(a.commandByTarget, `hook action in "${event}" commandByTarget`);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
return raw;
|
|
262
|
+
}
|
package/docs/authoring.md
CHANGED
|
@@ -154,13 +154,70 @@ Two ways to declare them:
|
|
|
154
154
|
- **agents** — `"./agents/"`, a dir of sub-agent definition `.md` files.
|
|
155
155
|
- **mcp** — `"./mcp/.mcp.json"`, an MCP server config file (points at a *file*,
|
|
156
156
|
not a dir).
|
|
157
|
-
- **hooks**, **apps** — directories, same pattern.
|
|
157
|
+
- **hooks**, **apps** — directories, same pattern. For hooks, see **Hooks**
|
|
158
|
+
below — agents differ on the hook config format, so ADG can compile a single
|
|
159
|
+
universal definition into each agent's native file.
|
|
158
160
|
|
|
159
161
|
Declare only what you ship. Omit a field and that component is absent from both
|
|
160
162
|
the runtime projections and the installed package.
|
|
161
163
|
|
|
162
164
|
---
|
|
163
165
|
|
|
166
|
+
## Hooks
|
|
167
|
+
|
|
168
|
+
Agents do not share a hook format. Claude **auto-loads** `hooks/hooks.json` and
|
|
169
|
+
expands `${CLAUDE_PLUGIN_ROOT}`; Codex references an explicit
|
|
170
|
+
`hooks/hooks-codex.json` from its manifest and expands `${PLUGIN_ROOT}`; and the
|
|
171
|
+
matcher vocabularies differ (e.g. `startup|clear|compact` vs
|
|
172
|
+
`startup|resume|clear`). Two ways to author:
|
|
173
|
+
|
|
174
|
+
- **Hand-authored (passthrough)** — ship the native files yourself under
|
|
175
|
+
`hooks/`. ADG carries them as-is: Claude auto-loads `hooks/hooks.json`, and the
|
|
176
|
+
Codex projection references `hooks/hooks-codex.json` (falling back to
|
|
177
|
+
`hooks/hooks.json`). Nothing is rewritten.
|
|
178
|
+
|
|
179
|
+
- **Universal DSL (recommended, author once)** — add `.agents/hooks.json`
|
|
180
|
+
(`adg.hooks/v1`). Write the canonical command with the **braced** `${PLUGIN_ROOT}`
|
|
181
|
+
token (only `${PLUGIN_ROOT}` is translated — a bare `$PLUGIN_ROOT` is left
|
|
182
|
+
as-is); capture the parts that genuinely differ per agent as `matcherByTarget` /
|
|
183
|
+
`commandByTarget` overrides (keyed by `claude`/`codex`). On `adapt`/install ADG
|
|
184
|
+
compiles it to each target's native file (`hooks/hooks.json`,
|
|
185
|
+
`hooks/hooks-codex.json`), translating the env token and applying overrides. The
|
|
186
|
+
compiled files ship but do not count toward the content hash. An event ADG
|
|
187
|
+
doesn't recognize is still emitted, with a warning.
|
|
188
|
+
|
|
189
|
+
```json
|
|
190
|
+
{
|
|
191
|
+
"schemaVersion": "adg.hooks/v1",
|
|
192
|
+
"hooks": {
|
|
193
|
+
"SessionStart": [
|
|
194
|
+
{
|
|
195
|
+
"matcher": "startup|clear|compact",
|
|
196
|
+
"matcherByTarget": { "codex": "startup|resume|clear" },
|
|
197
|
+
"actions": [
|
|
198
|
+
{
|
|
199
|
+
"type": "command",
|
|
200
|
+
"command": "\"${PLUGIN_ROOT}/hooks/run-hook.cmd\" session-start",
|
|
201
|
+
"commandByTarget": { "codex": "\"${PLUGIN_ROOT}/hooks/run-hook.cmd\" session-start-codex" },
|
|
202
|
+
"async": false
|
|
203
|
+
}
|
|
204
|
+
]
|
|
205
|
+
}
|
|
206
|
+
]
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Schema: [adg-hooks.schema.json](../schemas/adg-hooks.schema.json).
|
|
212
|
+
|
|
213
|
+
**Migrating an existing plugin** — already maintain native `hooks/hooks.json` +
|
|
214
|
+
`hooks/hooks-codex.json` by hand? Run `adg plugins lift-hooks [<dir>]` to fold
|
|
215
|
+
both into one `.agents/hooks.json` (canonicalizing the env token and capturing
|
|
216
|
+
per-agent differences as overrides). The native files stay put; a later `adapt`
|
|
217
|
+
regenerates them from the DSL.
|
|
218
|
+
|
|
219
|
+
---
|
|
220
|
+
|
|
164
221
|
## Dependencies
|
|
165
222
|
|
|
166
223
|
```jsonc
|
package/package.json
CHANGED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "http://json-schema.org/draft-07/schema#",
|
|
3
|
+
"$id": "https://RbBtSn0w.dev/schemas/adg-hooks.schema.json",
|
|
4
|
+
"title": "ADG Universal Hooks",
|
|
5
|
+
"description": "Universal hooks document stored at .agents/hooks.json. Authored once with the canonical ${PLUGIN_ROOT} token and optional per-target overrides; compiled to each agent's native hook file (Claude hooks/hooks.json, Codex hooks/hooks-codex.json).",
|
|
6
|
+
"type": "object",
|
|
7
|
+
"required": ["schemaVersion", "hooks"],
|
|
8
|
+
"additionalProperties": false,
|
|
9
|
+
"properties": {
|
|
10
|
+
"schemaVersion": {
|
|
11
|
+
"type": "string",
|
|
12
|
+
"description": "Hooks schema version.",
|
|
13
|
+
"const": "adg.hooks/v1"
|
|
14
|
+
},
|
|
15
|
+
"hooks": {
|
|
16
|
+
"type": "object",
|
|
17
|
+
"description": "Map of event name (e.g. SessionStart) to its matcher/action groups.",
|
|
18
|
+
"additionalProperties": {
|
|
19
|
+
"type": "array",
|
|
20
|
+
"items": { "$ref": "#/definitions/entry" }
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"definitions": {
|
|
25
|
+
"target": {
|
|
26
|
+
"type": "string",
|
|
27
|
+
"enum": ["claude", "codex"]
|
|
28
|
+
},
|
|
29
|
+
"entry": {
|
|
30
|
+
"type": "object",
|
|
31
|
+
"required": ["actions"],
|
|
32
|
+
"additionalProperties": false,
|
|
33
|
+
"properties": {
|
|
34
|
+
"matcher": {
|
|
35
|
+
"type": "string",
|
|
36
|
+
"description": "Default matcher for this group."
|
|
37
|
+
},
|
|
38
|
+
"matcherByTarget": {
|
|
39
|
+
"type": "object",
|
|
40
|
+
"description": "Per-target matcher override (agents use different matcher vocabularies).",
|
|
41
|
+
"additionalProperties": { "type": "string" },
|
|
42
|
+
"propertyNames": { "$ref": "#/definitions/target" }
|
|
43
|
+
},
|
|
44
|
+
"actions": {
|
|
45
|
+
"type": "array",
|
|
46
|
+
"items": { "$ref": "#/definitions/action" }
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
"action": {
|
|
51
|
+
"type": "object",
|
|
52
|
+
"required": ["type", "command"],
|
|
53
|
+
"additionalProperties": false,
|
|
54
|
+
"properties": {
|
|
55
|
+
"type": { "type": "string", "const": "command" },
|
|
56
|
+
"command": {
|
|
57
|
+
"type": "string",
|
|
58
|
+
"description": "Canonical command line; reference the plugin root as ${PLUGIN_ROOT}."
|
|
59
|
+
},
|
|
60
|
+
"async": { "type": "boolean" },
|
|
61
|
+
"commandByTarget": {
|
|
62
|
+
"type": "object",
|
|
63
|
+
"description": "Per-target command override for genuine behavioral divergence (still using ${PLUGIN_ROOT}).",
|
|
64
|
+
"additionalProperties": { "type": "string" },
|
|
65
|
+
"propertyNames": { "$ref": "#/definitions/target" }
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|