@rbbtsn0w/adg 0.8.1-beta.1 → 0.8.1-beta.3

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.
@@ -41,7 +41,9 @@ export function annotateCliRun(span, bin, args, r) {
41
41
  return;
42
42
  }
43
43
  if (r.error) {
44
- const errCode = r.error.code;
44
+ const errCode = typeof r.error === "object" && r.error !== null && "code" in r.error
45
+ ? r.error.code
46
+ : undefined;
45
47
  span.setAttribute("process.exit.code", -1);
46
48
  span.setAttribute("error.type", (typeof errCode === "string" || typeof errCode === "number" ? String(errCode) : null) || r.error.name || "SpawnError");
47
49
  span.setStatus({
@@ -0,0 +1,55 @@
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { basename, join } from "node:path";
4
+ import { copyPluginDir, writeJson } from "../../fsutil.js";
5
+ import { ADG_MANIFEST_PATH } from "../../manifest.js";
6
+ import { githubRepositoryDescription, scanPlugins } from "../../sources.js";
7
+ import { resolveDefaultDsl } from "../../default-dsl.js";
8
+ /**
9
+ * Synthesize a single Default DSL plugin from a source that holds no explicit
10
+ * ADG/native manifest: generate a manifest for the whole tree, stage a copy
11
+ * with it written in, and scan that staging copy as the sole candidate.
12
+ */
13
+ export async function synthesizeDefaultDslPlugin(opts, parsed, workRoot, resolvedRevision) {
14
+ const defaultDescription = parsed.kind === "github" && !opts.preparedSourceDir && !opts.defaultDescription
15
+ ? await githubRepositoryDescription(parsed.source)
16
+ : undefined;
17
+ const structuralIdentity = opts.as ?? opts.structuralIdentity ?? (parsed.kind === "github" ? parsed.source : basename(workRoot));
18
+ const generated = resolveDefaultDsl(workRoot, {
19
+ name: structuralIdentity,
20
+ description: defaultDescription ?? opts.defaultDescription ?? structuralIdentity,
21
+ }, {
22
+ ...(parsed.kind === "github" && resolvedRevision ? { resolvedRevision } : {}),
23
+ });
24
+ const authorized = opts.authorizedComponents;
25
+ const unauthorizedRisk = generated.components.some((c) => (c === "hooks" || c === "mcp") && !authorized?.includes(c));
26
+ if (opts.nonInteractive && unauthorizedRisk && opts.only === undefined) {
27
+ throw new Error("default source exposes hooks or MCP; pass --only to explicitly authorize selected components");
28
+ }
29
+ const staging = mkdtempSync(join(tmpdir(), "adg-default-plugin-"));
30
+ let candidates;
31
+ try {
32
+ copyPluginDir(workRoot, staging);
33
+ writeJson(join(staging, ADG_MANIFEST_PATH), generated.manifest);
34
+ candidates = scanPlugins(staging);
35
+ }
36
+ catch (error) {
37
+ rmSync(staging, { recursive: true, force: true });
38
+ throw error;
39
+ }
40
+ return {
41
+ candidates,
42
+ converted: [],
43
+ structuralName: generated.manifest.name,
44
+ originDirOverride: workRoot,
45
+ definition: {
46
+ kind: "default-dsl/v1",
47
+ root: ".",
48
+ ...(opts.as ? { as: generated.manifest.name } : {}),
49
+ description: generated.manifest.description,
50
+ fingerprint: generated.fingerprint,
51
+ authorizedComponents: authorized ?? (opts.only ?? generated.components),
52
+ },
53
+ cleanup: () => rmSync(staging, { recursive: true, force: true }),
54
+ };
55
+ }
@@ -0,0 +1,143 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { fromNativeManifest } from "../../adapters/reverse.js";
4
+ import { writeJson } from "../../fsutil.js";
5
+ import { lockPath } from "../../paths.js";
6
+ import { readLock } from "../../lock.js";
7
+ import { ADG_MANIFEST_PATH } from "../../manifest.js";
8
+ import { scanNativePlugins, scanPlugins } from "../../sources.js";
9
+ import { COMPONENT_TYPES, } from "../../types.js";
10
+ import { pluginContents, presentComponents } from "../../components.js";
11
+ import { skillDescriptionLoader } from "../../skills.js";
12
+ import { resolveAgents } from "../../agents/index.js";
13
+ import { removePlugin } from "../remove.js";
14
+ /**
15
+ * Reverse-adapt any native (Claude/Codex) manifests under `root` into
16
+ * `.agents/.plugin.json`, then return every ADG plugin found. After this the
17
+ * whole source speaks ADG, so selection and install treat all plugins uniformly.
18
+ */
19
+ export function discoverPlugins(root) {
20
+ const converted = [];
21
+ for (const native of scanNativePlugins(root)) {
22
+ if (native.kind === "adg")
23
+ continue;
24
+ const raw = JSON.parse(readFileSync(native.manifestFile, "utf8"));
25
+ const manifest = fromNativeManifest(raw, native.kind, native.dir);
26
+ writeJson(join(native.dir, ADG_MANIFEST_PATH), manifest);
27
+ converted.push(manifest.name);
28
+ }
29
+ return { candidates: scanPlugins(root), converted };
30
+ }
31
+ /** Resolve which discovered plugins to install from the selection options. */
32
+ export async function selectPluginNames(opts, candidates, converted) {
33
+ const names = [...candidates.keys()];
34
+ if (opts.plugins?.length) {
35
+ const missing = opts.plugins.filter((p) => !candidates.has(p));
36
+ if (missing.length && opts.missingPlugins !== "skip") {
37
+ throw new Error(`plugin(s) not found in source: ${missing.join(", ")}.\nAvailable: ${names.join(", ")}`);
38
+ }
39
+ return opts.plugins.filter((p) => candidates.has(p));
40
+ }
41
+ if (opts.all || candidates.size === 1)
42
+ return names;
43
+ if (opts.selectPlugins) {
44
+ const convertedSet = new Set(converted);
45
+ const choices = [...candidates.values()].map((c) => ({
46
+ name: c.manifest.name,
47
+ description: c.manifest.description,
48
+ native: convertedSet.has(c.manifest.name),
49
+ }));
50
+ return opts.selectPlugins(choices);
51
+ }
52
+ throw new Error(`source "${opts.spec}" contains ${candidates.size} plugins: ${names.join(", ")}.\n` +
53
+ `Pick with --plugin <name> (repeatable), --all for everything, or run in a terminal to choose interactively.`);
54
+ }
55
+ /**
56
+ * Decide a partial-install selection for each user-chosen plugin.
57
+ *
58
+ * Precedence: explicit flags (--only / --skill) win and apply to every chosen
59
+ * plugin; otherwise an interactive gate asks whether to install in full, and if
60
+ * not, a per-plugin component picker runs (skipped for plugins with nothing
61
+ * meaningful to choose). No selection for a plugin = expose everything.
62
+ */
63
+ export async function resolveSelections(opts, selected, candidates) {
64
+ const selections = new Map();
65
+ if (opts.only || opts.skillsSubset || opts.mcpSubset) {
66
+ const flagSelection = {
67
+ components: opts.only ?? [...COMPONENT_TYPES],
68
+ ...(opts.skillsSubset ? { skills: opts.skillsSubset } : {}),
69
+ ...(opts.mcpSubset ? { mcp: opts.mcpSubset } : {}),
70
+ };
71
+ for (const name of selected)
72
+ selections.set(name, flagSelection);
73
+ return selections;
74
+ }
75
+ if (opts.replaySelection) {
76
+ for (const name of selected)
77
+ selections.set(name, opts.replaySelection);
78
+ return selections;
79
+ }
80
+ if (!opts.confirmFull || !opts.selectComponents)
81
+ return selections; // non-interactive default: full
82
+ if (await opts.confirmFull(selected))
83
+ return selections; // user kept everything
84
+ for (const name of selected) {
85
+ const cand = candidates.get(name);
86
+ if (!cand)
87
+ continue;
88
+ const contents = pluginContents(cand.dir, cand.manifest);
89
+ const present = presentComponents(contents);
90
+ // Nothing meaningful to pick: a lone category with at most one member.
91
+ if (present.length <= 1 && contents.skills.length <= 1 && contents.mcp.length <= 1)
92
+ continue;
93
+ const skillDescription = skillDescriptionLoader(cand.dir, cand.manifest);
94
+ selections.set(name, await opts.selectComponents({ name, contents, present, skillDescription }));
95
+ }
96
+ return selections;
97
+ }
98
+ /** True when a locked plugin belongs to the same remote checkout currently being reconciled. */
99
+ export function sameRemoteSource(entry, parsed, ref) {
100
+ if (parsed.kind === "local")
101
+ return false;
102
+ if (entry.type !== "github")
103
+ return false;
104
+ return entry.repo === parsed.source && entry.ref === ref;
105
+ }
106
+ /**
107
+ * Remove plugins from the same remote source that disappeared from the latest
108
+ * desired set. This handles both source layout changes (one plugin splitting
109
+ * into several differently named plugins) and an explicit narrowed reinstall
110
+ * (`--plugin one` after previously installing `--all`) without leaving stale
111
+ * runtime exports behind.
112
+ */
113
+ export function reconcileRemotePlugins(opts, parsed, ref, desired) {
114
+ if (parsed.kind === "local")
115
+ return [];
116
+ // A sparse checkout does not prove the full source shape, so it must not
117
+ // prune sibling plugins from the same repo that were intentionally excluded.
118
+ if (opts.sparse?.length)
119
+ return [];
120
+ const lock = readLock(lockPath(opts.pluginsDir));
121
+ const stale = Object.entries(lock.plugins)
122
+ .filter(([name, entry]) => sameRemoteSource(entry.origin, parsed, ref) && !desired.has(name))
123
+ .map(([name]) => name)
124
+ .sort();
125
+ if (stale.length === 0)
126
+ return [];
127
+ // Removing from the ADG store is target-agnostic: once a plugin is no longer
128
+ // desired, every agent that may have cached it must be asked to drop it. The
129
+ // install/refresh pass below still honors `targets`; this broader deactivation
130
+ // only applies to removed store entries.
131
+ const agents = opts.activate ? (opts.deactivationAgents ?? resolveAgents()) : undefined;
132
+ for (const name of stale) {
133
+ removePlugin({
134
+ pluginsDir: opts.pluginsDir,
135
+ name,
136
+ force: true,
137
+ deactivate: opts.activate,
138
+ scope: opts.scope,
139
+ agents,
140
+ });
141
+ }
142
+ return stale;
143
+ }
@@ -0,0 +1,148 @@
1
+ import { existsSync } from "node:fs";
2
+ import { basename, join, relative, resolve } from "node:path";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import { ADAPTER_TARGETS } from "../../adapters/index.js";
5
+ import { adaptPlugin } from "../adapt.js";
6
+ import { folderHash } from "../../hash.js";
7
+ import { packageFilter, PROJECTION_DIRS } from "../../package.js";
8
+ import { lockPath, marketplacePath, marketplaceSourcePath, pluginDir, pluginSourceCacheDir } from "../../paths.js";
9
+ import { readLock, upsertEntry, writeLock } from "../../lock.js";
10
+ import { readManifest } from "../../manifest.js";
11
+ import { recordTelemetryEvent } from "../../telemetry.js";
12
+ import { readMarketplace, upsertMarketplacePlugin, writeMarketplace } from "../../marketplace.js";
13
+ import { normalizePluginSelection, resolveSelectionDependencies, sameSource, } from "../../types.js";
14
+ import { pluginContents } from "../../components.js";
15
+ import { effectivePackageFilter, materializePlugin, withPluginSourceCache } from "../../materialize.js";
16
+ // Generated runtime projections never count toward a plugin's content hash.
17
+ const HASH_IGNORE = PROJECTION_DIRS;
18
+ /** Content hash over a plugin's packaged payload (hooks files are authored content, not generated). */
19
+ export function contentHash(dir, manifest) {
20
+ return folderHash(dir, HASH_IGNORE, packageFilter(manifest, { includeProjections: false }));
21
+ }
22
+ function describe(s) {
23
+ switch (s.type) {
24
+ case "local": return `local:${s.path}`;
25
+ case "github": return `github:${s.repo}${s.path ? `/${s.path}` : ""}`;
26
+ case "git": return `git:${s.url}${s.path ? `/${s.path}` : ""}`;
27
+ }
28
+ }
29
+ /**
30
+ * Install a single local plugin directory into a plugins directory: copy the
31
+ * source, generate adapter manifests, compute the folder hash, and update both
32
+ * .plugin-lock.json and marketplace.json (with denormalized discovery metadata
33
+ * and an integrity digest).
34
+ *
35
+ * Refuses to overwrite a same-named plugin that came from a different upstream
36
+ * source (cross-marketplace name collision). Only files under `pluginsDir` are
37
+ * written — sibling files such as AGENTS.md or a global skills/ are untouched.
38
+ */
39
+ export function installPlugin(opts) {
40
+ const source = resolve(opts.source);
41
+ const manifest = readManifest(source, opts.telemetrySpan);
42
+ const name = manifest.name;
43
+ // Local installs stay flat; remote sources derive a per-marketplace dir from
44
+ // their origin. The default (no origin) is a flat local copy-in.
45
+ const origin = opts.origin ?? { type: "local", path: source };
46
+ const dest = pluginDir(opts.pluginsDir, name, origin);
47
+ const lockFile = lockPath(opts.pluginsDir);
48
+ const lock = readLock(lockFile);
49
+ const prev = lock.plugins[name];
50
+ if (prev && !sameSource(prev.origin, origin)) {
51
+ throw new Error(`name collision: "${name}" is already installed from a different source ` +
52
+ `(${describe(prev.origin)} vs ${describe(origin)}). Rename one to avoid the conflict.`);
53
+ }
54
+ // A new selection wins; otherwise keep whatever a prior install recorded so
55
+ // partial installs survive re-install / `marketplace upgrade`.
56
+ const desiredSelection = normalizePluginSelection(opts.selection ?? prev?.selection);
57
+ const selection = resolveSelectionDependencies(manifest, desiredSelection);
58
+ if (selection) {
59
+ const contents = pluginContents(source, manifest);
60
+ if (selection.skills) {
61
+ const invalid = selection.skills.filter((s) => !contents.skills.includes(s));
62
+ if (invalid.length > 0) {
63
+ throw new Error(`selected skill(s) not declared: ${invalid.join(", ")}`);
64
+ }
65
+ }
66
+ if (selection.mcp) {
67
+ const invalid = selection.mcp.filter((s) => !contents.mcp.includes(s));
68
+ if (invalid.length > 0) {
69
+ throw new Error(`selected mcp server(s) not declared: ${invalid.join(", ")}`);
70
+ }
71
+ }
72
+ recordTelemetryEvent("adg.install.selection", {
73
+ plugin: name,
74
+ "components.count": selection.components.length,
75
+ "skills.count": selection.skills ? selection.skills.length : -1,
76
+ "mcp.count": selection.mcp ? selection.mcp.length : -1,
77
+ }, opts.telemetrySpan);
78
+ }
79
+ const sourceHash = contentHash(source, manifest);
80
+ const cacheDir = pluginSourceCacheDir(opts.pluginsDir, name);
81
+ return withPluginSourceCache(source, cacheDir, manifest, (snapshot) => {
82
+ // Detect-then-update compares the complete source snapshot, never the
83
+ // selection-pruned runtime installation.
84
+ if (!opts.forceMaterialize && opts.skipUnchanged && prev
85
+ && prev.sourceHash === sourceHash && prev.version === manifest.version) {
86
+ const installedIntact = existsSync(dest)
87
+ && folderHash(dest, PROJECTION_DIRS, effectivePackageFilter(manifest, selection)) === prev.installedHash;
88
+ if (installedIntact) {
89
+ return {
90
+ name,
91
+ version: manifest.version,
92
+ installedTo: dest,
93
+ sourceHash,
94
+ installedHash: prev.installedHash,
95
+ adapted: [],
96
+ changed: false,
97
+ };
98
+ }
99
+ }
100
+ const targets = opts.targets ?? [...ADAPTER_TARGETS];
101
+ const adapted = [];
102
+ let installedHash = "";
103
+ materializePlugin({
104
+ source: snapshot,
105
+ destination: dest,
106
+ manifest,
107
+ selection,
108
+ build: (staging) => {
109
+ adapted.push(...adaptPlugin(staging, targets, selection).map((r) => relative(staging, r.file)));
110
+ installedHash = folderHash(staging, PROJECTION_DIRS, effectivePackageFilter(manifest, selection));
111
+ },
112
+ });
113
+ const adaptedFiles = adapted.map((file) => join(dest, file));
114
+ const entry = {
115
+ origin,
116
+ version: manifest.version,
117
+ sourceHash,
118
+ installedHash,
119
+ ...(opts.resolvedRevision ? { resolvedRevision: opts.resolvedRevision } : {}),
120
+ };
121
+ if (manifest.dependencies?.length) {
122
+ entry.dependencies = Object.fromEntries(manifest.dependencies.map((d) => [d.name, d.version]));
123
+ }
124
+ if (desiredSelection)
125
+ entry.selection = desiredSelection;
126
+ if (prev?.state)
127
+ entry.state = prev.state;
128
+ if (opts.definition)
129
+ entry.definition = opts.definition;
130
+ const previousEntry = prev && Object.fromEntries(Object.entries(prev).filter(([key]) => key !== "installedAt" && key !== "updatedAt"));
131
+ const changed = !prev || !isDeepStrictEqual(previousEntry, entry);
132
+ if (changed) {
133
+ upsertEntry(lock, name, entry, opts.now);
134
+ writeLock(lockFile, lock);
135
+ }
136
+ const marketFile = marketplacePath(opts.pluginsDir);
137
+ const fallbackName = opts.marketplaceName ?? basename(opts.pluginsDir);
138
+ const market = readMarketplace(marketFile, fallbackName);
139
+ upsertMarketplacePlugin(market, {
140
+ name,
141
+ source: { source: "local", path: marketplaceSourcePath(opts.pluginsDir, dest) },
142
+ policy: { installation: "AVAILABLE", authentication: "ON_INSTALL" },
143
+ ...(manifest.category ? { category: manifest.category } : {}),
144
+ });
145
+ writeMarketplace(marketFile, market);
146
+ return { name, version: manifest.version, installedTo: dest, sourceHash, installedHash, adapted: adaptedFiles, changed };
147
+ });
148
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,314 +1,17 @@
1
- import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
- import { basename, join, relative, resolve } from "node:path";
4
- import { isDeepStrictEqual } from "node:util";
5
- import { ADAPTER_TARGETS } from "../adapters/index.js";
6
- import { fromNativeManifest } from "../adapters/reverse.js";
7
- import { adaptPlugin } from "./adapt.js";
8
- import { removePlugin } from "./remove.js";
9
- import { copyPluginDir, toPosix, writeJson } from "../fsutil.js";
10
- import { folderHash } from "../hash.js";
11
- import { packageFilter, PROJECTION_DIRS } from "../package.js";
12
- import { lockPath, marketplacePath, marketplaceSourcePath, pluginDir, pluginSourceCacheDir } from "../paths.js";
13
- import { readLock, upsertEntry, writeLock } from "../lock.js";
14
- import { ADG_MANIFEST_PATH, readManifest } from "../manifest.js";
15
- import { recordTelemetryEvent } from "../telemetry.js";
16
- import { readMarketplace, upsertMarketplacePlugin, writeMarketplace } from "../marketplace.js";
3
+ import { join, relative, resolve } from "node:path";
4
+ import { toPosix } from "../fsutil.js";
5
+ import { lockPath } from "../paths.js";
6
+ import { readLock } from "../lock.js";
17
7
  import { resolveInstallOrder } from "../deps.js";
18
- import { cloneGitHub, gitRevision, githubRepositoryDescription, parseGitHubSource, parseSource, scanNativePlugins, scanPlugins } from "../sources.js";
19
- import { normalizePluginSelection, pluginState, resolveSelectionDependencies, sameSource, COMPONENT_TYPES } from "../types.js";
20
- import { pluginContents, presentComponents } from "../components.js";
21
- import { skillDescriptionLoader } from "../skills.js";
8
+ import { cloneGitHub, gitRevision, parseGitHubSource, parseSource } from "../sources.js";
9
+ import { pluginState } from "../types.js";
22
10
  import { resolveAgents } from "../agents/index.js";
23
- import { effectivePackageFilter, materializePlugin, withPluginSourceCache } from "../materialize.js";
24
- import { resolveDefaultDsl } from "../default-dsl.js";
25
- // Generated runtime projections never count toward a plugin's content hash.
26
- const HASH_IGNORE = PROJECTION_DIRS;
27
- /** Content hash over a plugin's packaged payload (hooks files are authored content, not generated). */
28
- function contentHash(dir, manifest) {
29
- return folderHash(dir, HASH_IGNORE, packageFilter(manifest, { includeProjections: false }));
30
- }
31
- /**
32
- * Install a single local plugin directory into a plugins directory: copy the
33
- * source, generate adapter manifests, compute the folder hash, and update both
34
- * .plugin-lock.json and marketplace.json (with denormalized discovery metadata
35
- * and an integrity digest).
36
- *
37
- * Refuses to overwrite a same-named plugin that came from a different upstream
38
- * source (cross-marketplace name collision). Only files under `pluginsDir` are
39
- * written — sibling files such as AGENTS.md or a global skills/ are untouched.
40
- */
41
- export function installPlugin(opts) {
42
- const source = resolve(opts.source);
43
- const manifest = readManifest(source, opts.telemetrySpan);
44
- const name = manifest.name;
45
- // Local installs stay flat; remote sources derive a per-marketplace dir from
46
- // their origin. The default (no origin) is a flat local copy-in.
47
- const origin = opts.origin ?? { type: "local", path: source };
48
- const dest = pluginDir(opts.pluginsDir, name, origin);
49
- const lockFile = lockPath(opts.pluginsDir);
50
- const lock = readLock(lockFile);
51
- const prev = lock.plugins[name];
52
- if (prev && !sameSource(prev.origin, origin)) {
53
- throw new Error(`name collision: "${name}" is already installed from a different source ` +
54
- `(${describe(prev.origin)} vs ${describe(origin)}). Rename one to avoid the conflict.`);
55
- }
56
- // A new selection wins; otherwise keep whatever a prior install recorded so
57
- // partial installs survive re-install / `marketplace upgrade`.
58
- const desiredSelection = normalizePluginSelection(opts.selection ?? prev?.selection);
59
- const selection = resolveSelectionDependencies(manifest, desiredSelection);
60
- if (selection) {
61
- const contents = pluginContents(source, manifest);
62
- if (selection.skills) {
63
- const invalid = selection.skills.filter((s) => !contents.skills.includes(s));
64
- if (invalid.length > 0) {
65
- throw new Error(`selected skill(s) not declared: ${invalid.join(", ")}`);
66
- }
67
- }
68
- if (selection.mcp) {
69
- const invalid = selection.mcp.filter((s) => !contents.mcp.includes(s));
70
- if (invalid.length > 0) {
71
- throw new Error(`selected mcp server(s) not declared: ${invalid.join(", ")}`);
72
- }
73
- }
74
- recordTelemetryEvent("adg.install.selection", {
75
- plugin: name,
76
- "components.count": selection.components.length,
77
- "skills.count": selection.skills ? selection.skills.length : -1,
78
- "mcp.count": selection.mcp ? selection.mcp.length : -1,
79
- }, opts.telemetrySpan);
80
- }
81
- const sourceHash = contentHash(source, manifest);
82
- const cacheDir = pluginSourceCacheDir(opts.pluginsDir, name);
83
- return withPluginSourceCache(source, cacheDir, manifest, (snapshot) => {
84
- // Detect-then-update compares the complete source snapshot, never the
85
- // selection-pruned runtime installation.
86
- if (!opts.forceMaterialize && opts.skipUnchanged && prev
87
- && prev.sourceHash === sourceHash && prev.version === manifest.version) {
88
- const installedIntact = existsSync(dest)
89
- && folderHash(dest, PROJECTION_DIRS, effectivePackageFilter(manifest, selection)) === prev.installedHash;
90
- if (installedIntact) {
91
- return {
92
- name,
93
- version: manifest.version,
94
- installedTo: dest,
95
- sourceHash,
96
- installedHash: prev.installedHash,
97
- adapted: [],
98
- changed: false,
99
- };
100
- }
101
- }
102
- const targets = opts.targets ?? [...ADAPTER_TARGETS];
103
- const adapted = [];
104
- let installedHash = "";
105
- materializePlugin({
106
- source: snapshot,
107
- destination: dest,
108
- manifest,
109
- selection,
110
- build: (staging) => {
111
- adapted.push(...adaptPlugin(staging, targets, selection).map((r) => relative(staging, r.file)));
112
- installedHash = folderHash(staging, PROJECTION_DIRS, effectivePackageFilter(manifest, selection));
113
- },
114
- });
115
- const adaptedFiles = adapted.map((file) => join(dest, file));
116
- const entry = {
117
- origin,
118
- version: manifest.version,
119
- sourceHash,
120
- installedHash,
121
- ...(opts.resolvedRevision ? { resolvedRevision: opts.resolvedRevision } : {}),
122
- };
123
- if (manifest.dependencies?.length) {
124
- entry.dependencies = Object.fromEntries(manifest.dependencies.map((d) => [d.name, d.version]));
125
- }
126
- if (desiredSelection)
127
- entry.selection = desiredSelection;
128
- if (prev?.state)
129
- entry.state = prev.state;
130
- if (opts.definition)
131
- entry.definition = opts.definition;
132
- const previousEntry = prev && Object.fromEntries(Object.entries(prev).filter(([key]) => key !== "installedAt" && key !== "updatedAt"));
133
- const changed = !prev || !isDeepStrictEqual(previousEntry, entry);
134
- if (changed) {
135
- upsertEntry(lock, name, entry, opts.now);
136
- writeLock(lockFile, lock);
137
- }
138
- const marketFile = marketplacePath(opts.pluginsDir);
139
- const fallbackName = opts.marketplaceName ?? basename(opts.pluginsDir);
140
- const market = readMarketplace(marketFile, fallbackName);
141
- upsertMarketplacePlugin(market, {
142
- name,
143
- source: { source: "local", path: marketplaceSourcePath(opts.pluginsDir, dest) },
144
- policy: { installation: "AVAILABLE", authentication: "ON_INSTALL" },
145
- ...(manifest.category ? { category: manifest.category } : {}),
146
- });
147
- writeMarketplace(marketFile, market);
148
- return { name, version: manifest.version, installedTo: dest, sourceHash, installedHash, adapted: adaptedFiles, changed };
149
- });
150
- }
151
- function describe(s) {
152
- switch (s.type) {
153
- case "local": return `local:${s.path}`;
154
- case "github": return `github:${s.repo}${s.path ? `/${s.path}` : ""}`;
155
- case "git": return `git:${s.url}${s.path ? `/${s.path}` : ""}`;
156
- }
157
- }
158
- /**
159
- * Reverse-adapt any native (Claude/Codex) manifests under `root` into
160
- * `.agents/.plugin.json`, then return every ADG plugin found. After this the
161
- * whole source speaks ADG, so selection and install treat all plugins uniformly.
162
- */
163
- function discoverPlugins(root) {
164
- const converted = [];
165
- for (const native of scanNativePlugins(root)) {
166
- if (native.kind === "adg")
167
- continue;
168
- const raw = JSON.parse(readFileSync(native.manifestFile, "utf8"));
169
- const manifest = fromNativeManifest(raw, native.kind, native.dir);
170
- writeJson(join(native.dir, ADG_MANIFEST_PATH), manifest);
171
- converted.push(manifest.name);
172
- }
173
- return { candidates: scanPlugins(root), converted };
174
- }
175
- /** Resolve which discovered plugins to install from the selection options. */
176
- async function selectPluginNames(opts, candidates, converted) {
177
- const names = [...candidates.keys()];
178
- if (opts.plugins?.length) {
179
- const missing = opts.plugins.filter((p) => !candidates.has(p));
180
- if (missing.length && opts.missingPlugins !== "skip") {
181
- throw new Error(`plugin(s) not found in source: ${missing.join(", ")}.\nAvailable: ${names.join(", ")}`);
182
- }
183
- return opts.plugins.filter((p) => candidates.has(p));
184
- }
185
- if (opts.all || candidates.size === 1)
186
- return names;
187
- if (opts.selectPlugins) {
188
- const convertedSet = new Set(converted);
189
- const choices = [...candidates.values()].map((c) => ({
190
- name: c.manifest.name,
191
- description: c.manifest.description,
192
- native: convertedSet.has(c.manifest.name),
193
- }));
194
- return opts.selectPlugins(choices);
195
- }
196
- throw new Error(`source "${opts.spec}" contains ${candidates.size} plugins: ${names.join(", ")}.\n` +
197
- `Pick with --plugin <name> (repeatable), --all for everything, or run in a terminal to choose interactively.`);
198
- }
199
- /**
200
- * Decide a partial-install selection for each user-chosen plugin.
201
- *
202
- * Precedence: explicit flags (--only / --skill) win and apply to every chosen
203
- * plugin; otherwise an interactive gate asks whether to install in full, and if
204
- * not, a per-plugin component picker runs (skipped for plugins with nothing
205
- * meaningful to choose). No selection for a plugin = expose everything.
206
- */
207
- async function resolveSelections(opts, selected, candidates) {
208
- const selections = new Map();
209
- if (opts.only || opts.skillsSubset || opts.mcpSubset) {
210
- const flagSelection = {
211
- components: opts.only ?? [...COMPONENT_TYPES],
212
- ...(opts.skillsSubset ? { skills: opts.skillsSubset } : {}),
213
- ...(opts.mcpSubset ? { mcp: opts.mcpSubset } : {}),
214
- };
215
- for (const name of selected)
216
- selections.set(name, flagSelection);
217
- return selections;
218
- }
219
- if (opts.replaySelection) {
220
- for (const name of selected)
221
- selections.set(name, opts.replaySelection);
222
- return selections;
223
- }
224
- if (!opts.confirmFull || !opts.selectComponents)
225
- return selections; // non-interactive default: full
226
- if (await opts.confirmFull(selected))
227
- return selections; // user kept everything
228
- for (const name of selected) {
229
- const cand = candidates.get(name);
230
- const contents = pluginContents(cand.dir, cand.manifest);
231
- const present = presentComponents(contents);
232
- // Nothing meaningful to pick: a lone category with at most one member.
233
- if (present.length <= 1 && contents.skills.length <= 1 && contents.mcp.length <= 1)
234
- continue;
235
- const skillDescription = skillDescriptionLoader(cand.dir, cand.manifest);
236
- selections.set(name, await opts.selectComponents({ name, contents, present, skillDescription }));
237
- }
238
- return selections;
239
- }
240
- /** True when a locked plugin belongs to the same remote checkout currently being reconciled. */
241
- function sameRemoteSource(entry, parsed, ref) {
242
- if (parsed.kind === "local")
243
- return false;
244
- if (entry.type !== "github")
245
- return false;
246
- return entry.repo === parsed.source && entry.ref === ref;
247
- }
248
- /**
249
- * Remove plugins from the same remote source that disappeared from the latest
250
- * desired set. This handles both source layout changes (one plugin splitting
251
- * into several differently named plugins) and an explicit narrowed reinstall
252
- * (`--plugin one` after previously installing `--all`) without leaving stale
253
- * runtime exports behind.
254
- */
255
- function reconcileRemotePlugins(opts, parsed, ref, desired) {
256
- if (parsed.kind === "local")
257
- return [];
258
- // A sparse checkout does not prove the full source shape, so it must not
259
- // prune sibling plugins from the same repo that were intentionally excluded.
260
- if (opts.sparse?.length)
261
- return [];
262
- const lock = readLock(lockPath(opts.pluginsDir));
263
- const stale = Object.entries(lock.plugins)
264
- .filter(([name, entry]) => sameRemoteSource(entry.origin, parsed, ref) && !desired.has(name))
265
- .map(([name]) => name)
266
- .sort();
267
- if (stale.length === 0)
268
- return [];
269
- // Removing from the ADG store is target-agnostic: once a plugin is no longer
270
- // desired, every agent that may have cached it must be asked to drop it. The
271
- // install/refresh pass below still honors `targets`; this broader deactivation
272
- // only applies to removed store entries.
273
- const agents = opts.activate ? (opts.deactivationAgents ?? resolveAgents()) : undefined;
274
- for (const name of stale) {
275
- removePlugin({
276
- pluginsDir: opts.pluginsDir,
277
- name,
278
- force: true,
279
- deactivate: opts.activate,
280
- scope: opts.scope,
281
- agents,
282
- });
283
- }
284
- return stale;
285
- }
286
- function activateInstalled(opts, targets, installed, existingPlugins) {
287
- const updatedLock = readLock(lockPath(opts.pluginsDir));
288
- const eligible = installed.filter((result) => pluginState(updatedLock.plugins[result.name]) === "enabled");
289
- const toActivate = opts.skipUnchanged ? eligible.filter((result) => result.changed) : eligible;
290
- if (!opts.activate || toActivate.length === 0)
291
- return undefined;
292
- const resolved = opts.agents ?? resolveAgents(targets);
293
- const scope = opts.scope ?? "project";
294
- const ctxFor = (names) => ({ pluginsDir: opts.pluginsDir, plugins: names, scope });
295
- return resolved.map((agent) => {
296
- opts.onProgress?.({ kind: "activate", agent: agent.id, count: toActivate.length });
297
- const queryResult = agent.listInstalled?.(ctxFor([]));
298
- const agentInstalled = Array.isArray(queryResult) ? queryResult : undefined;
299
- const alreadyInstalled = (name) => agentInstalled !== undefined
300
- ? agentInstalled.includes(name)
301
- : existingPlugins.has(name);
302
- const activateNames = toActivate.filter((result) => !alreadyInstalled(result.name)).map((result) => result.name);
303
- const refreshNames = toActivate.filter((result) => alreadyInstalled(result.name)).map((result) => result.name);
304
- const parts = [];
305
- if (activateNames.length > 0)
306
- parts.push(agent.activate(ctxFor(activateNames)));
307
- if (refreshNames.length > 0)
308
- parts.push(agent.refresh(ctxFor(refreshNames)));
309
- return parts.reduce((acc, result) => ({ agent: result.agent, affected: [...acc.affected, ...result.affected], skipped: acc.skipped && result.skipped }), { agent: agent.id, affected: [], skipped: true });
310
- });
311
- }
11
+ import { installPlugin } from "./install/install-one.js";
12
+ import { discoverPlugins, reconcileRemotePlugins, resolveSelections, selectPluginNames } from "./install/discovery.js";
13
+ import { synthesizeDefaultDslPlugin } from "./install/default-dsl.js";
14
+ export { installPlugin, contentHash } from "./install/install-one.js";
312
15
  /**
313
16
  * Resolve `opts.spec` to a local working directory plus an origin builder and
314
17
  * cleanup, covering the three source kinds: a prepared checkout (remote
@@ -360,53 +63,31 @@ function prepareSource(opts, parsed, sourceRef) {
360
63
  throw error;
361
64
  }
362
65
  }
363
- /**
364
- * Synthesize a single Default DSL plugin from a source that holds no explicit
365
- * ADG/native manifest: generate a manifest for the whole tree, stage a copy
366
- * with it written in, and scan that staging copy as the sole candidate.
367
- */
368
- async function synthesizeDefaultDslPlugin(opts, parsed, workRoot, resolvedRevision) {
369
- const defaultDescription = parsed.kind === "github" && !opts.preparedSourceDir && !opts.defaultDescription
370
- ? await githubRepositoryDescription(parsed.source)
371
- : undefined;
372
- const structuralIdentity = opts.as ?? opts.structuralIdentity ?? (parsed.kind === "github" ? parsed.source : basename(workRoot));
373
- const generated = resolveDefaultDsl(workRoot, {
374
- name: structuralIdentity,
375
- description: defaultDescription ?? opts.defaultDescription ?? structuralIdentity,
376
- }, {
377
- ...(parsed.kind === "github" && resolvedRevision ? { resolvedRevision } : {}),
66
+ function activateInstalled(opts, targets, installed, existingPlugins) {
67
+ const updatedLock = readLock(lockPath(opts.pluginsDir));
68
+ const eligible = installed.filter((result) => pluginState(updatedLock.plugins[result.name]) === "enabled");
69
+ const toActivate = opts.skipUnchanged ? eligible.filter((result) => result.changed) : eligible;
70
+ if (!opts.activate || toActivate.length === 0)
71
+ return undefined;
72
+ const resolved = opts.agents ?? resolveAgents(targets);
73
+ const scope = opts.scope ?? "project";
74
+ const ctxFor = (names) => ({ pluginsDir: opts.pluginsDir, plugins: names, scope });
75
+ return resolved.map((agent) => {
76
+ opts.onProgress?.({ kind: "activate", agent: agent.id, count: toActivate.length });
77
+ const queryResult = agent.listInstalled?.(ctxFor([]));
78
+ const agentInstalled = Array.isArray(queryResult) ? queryResult : undefined;
79
+ const alreadyInstalled = (name) => agentInstalled !== undefined
80
+ ? agentInstalled.includes(name)
81
+ : existingPlugins.has(name);
82
+ const activateNames = toActivate.filter((result) => !alreadyInstalled(result.name)).map((result) => result.name);
83
+ const refreshNames = toActivate.filter((result) => alreadyInstalled(result.name)).map((result) => result.name);
84
+ const parts = [];
85
+ if (activateNames.length > 0)
86
+ parts.push(agent.activate(ctxFor(activateNames)));
87
+ if (refreshNames.length > 0)
88
+ parts.push(agent.refresh(ctxFor(refreshNames)));
89
+ return parts.reduce((acc, result) => ({ agent: result.agent, affected: [...acc.affected, ...result.affected], skipped: acc.skipped && result.skipped }), { agent: agent.id, affected: [], skipped: true });
378
90
  });
379
- const authorized = opts.authorizedComponents;
380
- const unauthorizedRisk = generated.components.some((c) => (c === "hooks" || c === "mcp") && !authorized?.includes(c));
381
- if (opts.nonInteractive && unauthorizedRisk && opts.only === undefined) {
382
- throw new Error("default source exposes hooks or MCP; pass --only to explicitly authorize selected components");
383
- }
384
- const staging = mkdtempSync(join(tmpdir(), "adg-default-plugin-"));
385
- let candidates;
386
- try {
387
- copyPluginDir(workRoot, staging);
388
- writeJson(join(staging, ADG_MANIFEST_PATH), generated.manifest);
389
- candidates = scanPlugins(staging);
390
- }
391
- catch (error) {
392
- rmSync(staging, { recursive: true, force: true });
393
- throw error;
394
- }
395
- return {
396
- candidates,
397
- converted: [],
398
- structuralName: generated.manifest.name,
399
- originDirOverride: workRoot,
400
- definition: {
401
- kind: "default-dsl/v1",
402
- root: ".",
403
- ...(opts.as ? { as: generated.manifest.name } : {}),
404
- description: generated.manifest.description,
405
- fingerprint: generated.fingerprint,
406
- authorizedComponents: authorized ?? (opts.only ?? generated.components),
407
- },
408
- cleanup: () => rmSync(staging, { recursive: true, force: true }),
409
- };
410
91
  }
411
92
  /**
412
93
  * The unified install entrypoint. Treats any source as a marketplace: clone or
@@ -417,7 +98,7 @@ async function synthesizeDefaultDslPlugin(opts, parsed, workRoot, resolvedRevisi
417
98
  export async function addPlugins(opts) {
418
99
  // Prepared checkouts are used only by remote marketplace update. Parse their
419
100
  // persisted owner/repo key as GitHub even when the caller's CWD shadows it.
420
- const parsed = opts.preparedSourceDir ? parseGitHubSource(opts.spec) : parseSource(opts.spec);
101
+ const parsed = opts.preparedSourceDir ? parseGitHubSource(opts.spec) : parseSource(opts.spec, opts.cwd);
421
102
  const sourceRef = parsed.kind === "local" ? undefined : (opts.ref ?? parsed.ref);
422
103
  if (parsed.kind === "github" && parsed.path) {
423
104
  throw new Error("GitHub subdirectory sources are not supported; define a marketplace and select with --plugin or --all");
@@ -447,7 +128,14 @@ export async function addPlugins(opts) {
447
128
  originDirOverride = synthesized.originDirOverride;
448
129
  definition = synthesized.definition;
449
130
  const priorCleanup = cleanup;
450
- cleanup = () => { synthesized.cleanup(); priorCleanup?.(); };
131
+ cleanup = () => {
132
+ try {
133
+ synthesized.cleanup();
134
+ }
135
+ finally {
136
+ priorCleanup?.();
137
+ }
138
+ };
451
139
  }
452
140
  const selected = structuralName ? [structuralName] : await selectPluginNames(opts, candidates, converted);
453
141
  // Resolve adapter targets after the plugin choice (lets a CLI agent picker
@@ -500,6 +188,9 @@ export async function addPlugins(opts) {
500
188
  const installed = [];
501
189
  for (const name of order) {
502
190
  const candidate = candidates.get(name);
191
+ if (!candidate) {
192
+ throw new Error(`candidate "${name}" not found in resolved candidates`);
193
+ }
503
194
  installed.push(installPlugin({
504
195
  source: candidate.dir,
505
196
  pluginsDir: opts.pluginsDir,
@@ -190,6 +190,7 @@ export async function updatePlugins(opts) {
190
190
  now,
191
191
  preparedSourceDir: checkout,
192
192
  preparedResolvedRevision: resolvedRevision,
193
+ ...(opts.cwd ? { cwd: opts.cwd } : {}),
193
194
  ...(opts.onProgress ? { onProgress: opts.onProgress } : {}),
194
195
  });
195
196
  installed.push(...result.installed);
@@ -1,6 +1,6 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { existsSync, readdirSync } from "node:fs";
3
- import { join } from "node:path";
3
+ import { join, resolve } from "node:path";
4
4
  import { readManifest, findManifestFile } from "./manifest.js";
5
5
  import { SpanKind, SpanStatusCode } from "@opentelemetry/api";
6
6
  import { getTracer, sanitizeArgs } from "./telemetry.js";
@@ -53,9 +53,10 @@ function decodeGitHubUrlPart(value) {
53
53
  * An existing local directory always wins; otherwise the spec is matched
54
54
  * against `owner/repo[@ref]` shorthand or a github.com URL.
55
55
  */
56
- export function parseSource(spec) {
57
- if (existsSync(spec))
58
- return { kind: "local", dir: spec };
56
+ export function parseSource(spec, cwd) {
57
+ const local = cwd ? resolve(cwd, spec) : spec;
58
+ if (existsSync(local))
59
+ return { kind: "local", dir: local };
59
60
  try {
60
61
  return parseGitHubSource(spec);
61
62
  }
@@ -179,10 +180,11 @@ export function runGit(args, captureOutput = false, timeoutMs) {
179
180
  return captureOutput ? String(output).trimEnd() : undefined;
180
181
  }
181
182
  catch (error) {
182
- const exitCode = typeof error.status === "number" ? error.status : 1;
183
+ const err = typeof error === "object" && error !== null ? error : undefined;
184
+ const exitCode = typeof err?.status === "number" ? err.status : 1;
183
185
  span.setAttribute("process.exit.code", exitCode);
184
- if (typeof error.pid === "number") {
185
- span.setAttribute("process.pid", error.pid);
186
+ if (typeof err?.pid === "number") {
187
+ span.setAttribute("process.pid", err.pid);
186
188
  }
187
189
  span.setAttribute("error.type", gitErrorType(error, exitCode));
188
190
  span.setStatus({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rbbtsn0w/adg",
3
- "version": "0.8.1-beta.1",
3
+ "version": "0.8.1-beta.3",
4
4
  "description": "Agent Directory Group (ADG) toolkit — two domains: plugins and skills.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -23,7 +23,7 @@
23
23
  },
24
24
  "scripts": {
25
25
  "adg": "node ./bin/adg.ts",
26
- "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json --noCheck && node -e \"require('fs').cpSync('src/adapters/antigravity-hook-runner.mjs','dist/src/adapters/antigravity-hook-runner.mjs')\" && node -e \"require('fs').chmodSync('dist/bin/adg.js',0o755)\"",
26
+ "build": "node scripts/build.mjs",
27
27
  "test": "node scripts/run-tests.mjs \"test/**/*.test.ts\" test/cache-sandbox.test.mjs",
28
28
  "test:codex-sandbox": "node --test test/codex-sandbox.test.mjs",
29
29
  "test:cache-sandbox": "node --test test/cache-sandbox.test.mjs",
@@ -48,17 +48,17 @@
48
48
  "dependencies": {
49
49
  "@clack/prompts": "^1.2.0",
50
50
  "@opentelemetry/api": "^1.9.0",
51
- "@opentelemetry/exporter-trace-otlp-http": "^0.219.0",
52
- "@opentelemetry/resources": "^2.8.0",
53
- "@opentelemetry/sdk-trace-base": "^2.8.0",
54
- "@opentelemetry/sdk-trace-node": "^2.8.0",
55
- "@opentelemetry/semantic-conventions": "^1.28.0",
56
- "@vercel/detect-agent": "^1.2.3",
51
+ "@opentelemetry/exporter-trace-otlp-http": "^0.222.0",
52
+ "@opentelemetry/resources": "^2.11.0",
53
+ "@opentelemetry/sdk-trace-base": "^2.11.0",
54
+ "@opentelemetry/sdk-trace-node": "^2.11.0",
55
+ "@opentelemetry/semantic-conventions": "^1.43.0",
56
+ "@vercel/detect-agent": "^1.2.5",
57
57
  "picocolors": "^1.1.1",
58
58
  "simple-git": "^3.36.0",
59
59
  "tar": "^7.5.20",
60
60
  "xdg-basedir": "^5.1.0",
61
- "yaml": "^2.8.3"
61
+ "yaml": "^2.9.1"
62
62
  },
63
63
  "devDependencies": {
64
64
  "@semantic-release/changelog": "^6.0.3",