@rbbtsn0w/adg 0.4.0-beta.7 → 0.4.0-beta.9

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.
@@ -1,70 +1,84 @@
1
- import { cpSync, existsSync, rmSync, statSync, symlinkSync } from "node:fs";
1
+ import { cpSync, existsSync, lstatSync, rmSync, symlinkSync, unlinkSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
- import { dirname, join, relative } from "node:path";
3
+ import { dirname, join, relative, resolve } from "node:path";
4
4
  import { ensureDir, writeJson } from "../fsutil.js";
5
5
  import { readManifest } from "../manifest.js";
6
- import { resolveSkillEntries } from "../skills.js";
7
6
  import { isExposed } from "../components.js";
8
7
  import { installedPluginDir, lockPath } from "../paths.js";
9
8
  import { readLock } from "../lock.js";
10
- import { ANTIGRAVITY_PROJECTION_DIR } from "../adapters/antigravity.js";
11
- import { mcpConfigPath } from "../mcp.js";
12
- import { makeCli, skippedResult } from "./base.js";
9
+ import { toAntigravityManifest, writeAntigravityMcpConfig } from "../adapters/antigravity.js";
10
+ import { writeAntigravityHooks } from "../adapters/antigravity-hooks.js";
11
+ import { skippedResult } from "./base.js";
13
12
  /**
14
- * Antigravity (`agy`) agent.
13
+ * Antigravity (`agy`) agent — physical-directory model, no CLI.
15
14
  *
16
- * Antigravity discovers a plugin by convention relative to the directory handed
17
- * to `agy plugin install` — `plugin.json` plus sibling `skills/`, `agents/`,
18
- * `commands/`, `hooks/` dirs plus plugin.json path pointers. We therefore
19
- * project a self-contained agy plugin root under `<store>/.antigravity-plugin/`:
20
- * generated `plugin.json` + copied MCP config (when selected) and
21
- * *symlinks* to the real component dirs one level up, so nothing is duplicated
22
- * on disk. agy follows these symlinks; where the platform forbids them (e.g.
23
- * Windows without privilege) we fall back to a copy. We then drive
24
- * `agy plugin install/uninstall` (which owns `~/.gemini/antigravity-cli`).
15
+ * Antigravity discovers plugins by *scanning* designated directories; the
16
+ * directory itself carries the scope (the provenance), and there is no agy lock
17
+ * or marketplace:
18
+ * - Workspace: `<ws>/.agents/plugins/<name>` (ADG's own project store)
19
+ * - Global: `~/.gemini/config/plugins/<name>`
20
+ * A plugin folder is recognized by a root `plugin.json` plus sibling component
21
+ * dirs (`skills/ agents/ commands/ hooks/`).
22
+ *
23
+ * We therefore drive Antigravity purely by placing files, never by a CLI:
24
+ * - Project scope is *in place*: ADG's store folder already sits in the
25
+ * workspace scan dir, so we just write the agy `plugin.json` at its root.
26
+ * - Global scope (and remote-nested project plugins, which live two levels
27
+ * under the scan dir) get an exposure symlink `<scanDir>/<name>` -> the real
28
+ * store folder, with a copy fallback where symlinks are unavailable.
29
+ *
30
+ * Provenance is owned by ADG: `listInstalled` answers from the queried scope's
31
+ * own lock intersected with that scope's scan dir — never from the agent — so a
32
+ * project query can't surface globally-installed plugins (and vice versa).
33
+ *
34
+ * Tradeoff (in-place): partial installs are best-effort, and a `skills` value is
35
+ * read from the single convention dir `<plugin>/skills/`. Generated
36
+ * `mcp_config.json` honors the MCP selection, but an authored file already using
37
+ * that conventional name cannot be hidden without deleting canonical payload.
38
+ * The auto-scan model also does NOT honor: dir-level pruning (a narrowed skill
39
+ * subset, a dropped directory category), nor a multi-root skills path-list (e.g.
40
+ * `["./skills/one","./extra/two"]` — only the `skills/` root is exposed; `extra/`
41
+ * is not). These would require a separate self-contained projection dir, which the
42
+ * in-place model deliberately avoids; the full canonical dirs are read in place.
25
43
  */
26
44
  const ID = "antigravity";
45
+ /** The manifest filename Antigravity's auto-scan looks for at a plugin folder root. */
46
+ const ANTIGRAVITY_MANIFEST = "plugin.json";
27
47
  /**
28
- * Single-directory component fields: agy reads each as a sibling dir named by
29
- * convention. `skills` is handled separately because it can be a path-list and
30
- * supports per-skill subsetting.
48
+ * Component fields agy reads as a sibling dir named by convention. We ensure each
49
+ * resolves under its convention name, aliasing when the manifest declares a
50
+ * non-convention source dir.
31
51
  */
32
- const DIR_FIELDS = ["agents", "commands", "hooks"];
52
+ const CONVENTION_FIELDS = ["skills", "agents", "commands", "hooks"];
33
53
  function geminiHome(env) {
34
54
  return env.GEMINI_HOME?.trim() || join(homedir(), ".gemini");
35
55
  }
36
56
  /**
37
- * agy's config/store home: `<GEMINI_HOME>/antigravity-cli` (defaulting to
38
- * `~/.gemini/antigravity-cli`). Exported so the resolver itself is testable
39
- * without depending on the host filesystem state.
57
+ * Antigravity-specific markers under the Gemini home. `~/.gemini` itself is
58
+ * shared with the plain Gemini CLI, so detection keys on an `antigravity*` dir to
59
+ * avoid falsely registering a Gemini-CLI-only user (and writing into their home).
40
60
  */
41
- export function antigravityHome(env = process.env) {
42
- return join(geminiHome(env), "antigravity-cli");
61
+ const ANTIGRAVITY_MARKERS = ["antigravity", "antigravity-cli", "antigravity-ide"];
62
+ function antigravityPresent(env) {
63
+ const home = geminiHome(env);
64
+ return ANTIGRAVITY_MARKERS.some((marker) => existsSync(join(home, marker)));
43
65
  }
44
- // `--help` is rejected by `agy plugin install` (it parses it as a target), so
45
- // probe the plugin command group with its own `help` subcommand instead.
46
- // `echoStderr` surfaces the CLI's own diagnostics on failure.
47
- const { available, run } = makeCli("agy", { probeArgs: ["plugin", "help"], echoStderr: true });
48
- /** Resolve a plugin's on-disk store directory and selection from the lock's provenance. */
49
- function pluginStore(pluginsDir, name) {
50
- const entry = readLock(lockPath(pluginsDir)).plugins[name];
51
- if (!entry)
52
- return undefined;
53
- const dir = installedPluginDir(pluginsDir, name, entry.origin);
54
- return existsSync(dir) ? { dir, selection: entry.selection } : undefined;
66
+ /**
67
+ * Antigravity's global plugin scan dir: `<GEMINI_HOME>/config/plugins`
68
+ * (defaulting to `~/.gemini/config/plugins`). Exported so the resolver is
69
+ * testable without host filesystem state.
70
+ */
71
+ export function antigravityGlobalPluginsDir(env = process.env) {
72
+ return join(geminiHome(env), "config", "plugins");
55
73
  }
56
- /** First on-disk top segment of a declared component path (e.g. "./agents/" -> "agents"). */
57
- function componentSegment(value) {
58
- const first = Array.isArray(value) ? value[0] : value;
59
- if (typeof first !== "string")
60
- return undefined;
61
- const seg = first.replace(/^\.?[/\\]/, "").split(/[/\\]/)[0];
62
- return seg || undefined;
74
+ /** The scan dir Antigravity reads for a given scope: global home, or the project store itself. */
75
+ function antigravityScanDir(ctx, env = process.env) {
76
+ return ctx.scope === "user" ? antigravityGlobalPluginsDir(env) : ctx.pluginsDir;
63
77
  }
64
78
  /**
65
- * Symlink `linkPath` at `absTarget` (target stored relative so the projection
66
- * survives the whole plugin dir being moved), copying instead where symlinks are
67
- * unavailable (e.g. Windows without privilege). Idempotent.
79
+ * Symlink `linkPath` at `absTarget` (target stored relative so the link survives
80
+ * a move), copying instead where symlinks are unavailable (e.g. Windows without
81
+ * privilege). Idempotent.
68
82
  */
69
83
  function linkOrCopy(linkPath, absTarget) {
70
84
  rmSync(linkPath, { recursive: true, force: true });
@@ -76,115 +90,150 @@ function linkOrCopy(linkPath, absTarget) {
76
90
  cpSync(absTarget, linkPath, { recursive: true });
77
91
  }
78
92
  }
79
- /** Link a file with a relative symlink, copying instead when symlinks fail. */
80
- function linkFileOrCopy(linkPath, absTarget) {
81
- rmSync(linkPath, { force: true });
82
- ensureDir(dirname(linkPath));
93
+ /**
94
+ * Remove `path` when it is a symlink — including a *broken* one. `lstatSync` (in a
95
+ * `try`) is used rather than `existsSync`, which follows the link and reports false
96
+ * for a dangling alias, leaving it on disk. Removal uses `unlinkSync`, not
97
+ * `rmSync(..., { force: true })`: on Node < 24 the latter follows the link, hits
98
+ * `ENOENT`, and the `force` flag then swallows it without unlinking the symlink.
99
+ * A real file/dir is left untouched.
100
+ */
101
+ function rmIfSymlink(path) {
102
+ let st;
83
103
  try {
84
- symlinkSync(relative(dirname(linkPath), absTarget), linkPath, "file");
104
+ st = lstatSync(path);
85
105
  }
86
106
  catch {
87
- cpSync(absTarget, linkPath);
107
+ return; // absent
88
108
  }
109
+ if (st.isSymbolicLink())
110
+ unlinkSync(path);
111
+ }
112
+ /** First on-disk top segment of a declared component path (e.g. "./agents/" -> "agents"). */
113
+ function componentSegment(value) {
114
+ const first = Array.isArray(value) ? value[0] : value;
115
+ if (typeof first !== "string")
116
+ return undefined;
117
+ const seg = first.replace(/^\.?[/\\]/, "").split(/[/\\]/)[0];
118
+ return seg || undefined;
89
119
  }
90
120
  /**
91
- * Build the agy-native projection under `<dir>/.antigravity-plugin/`: a
92
- * `plugin.json`, an MCP config file copied verbatim from the manifest's
93
- * `mcpServers` pointer when present, an agy-conventional `mcp_config.json` link
94
- * to that file, and relative symlinks (copy fallback) to the declared component
95
- * dirs named for agy's convention.
96
- *
97
- * An optional `selection` (the plugin's partial install) narrows what is
98
- * projected: component categories outside it are dropped, and `skills` is pinned
99
- * to the selected subset. `skills` is also projected per-skill into a real
100
- * `skills/` dir, so a path-list spanning multiple roots is fully honored rather
101
- * than collapsing to its first root. Idempotent; safe to re-run.
121
+ * Make `dir` a valid agy plugin root in place: write the agy `plugin.json` at the
122
+ * root and ensure each exposed component resolves under its convention name
123
+ * (aliasing with a symlink/copy only when the manifest's source dir name differs).
124
+ * Idempotent; safe to re-run. Never deletes a real (non-symlink) component dir.
102
125
  */
103
- export function writeAntigravityProjection(dir, selection) {
126
+ export function ensureAntigravityRoot(dir, selection) {
104
127
  const manifest = readManifest(dir);
105
- const stage = join(dir, ANTIGRAVITY_PROJECTION_DIR);
106
- ensureDir(stage);
107
- rmSync(join(stage, "mcp_config.json"), { force: true });
108
- const mcp = mcpConfigPath(manifest);
109
- const pluginJson = { name: manifest.name };
110
- if (mcp && isExposed(selection, "mcp")) {
111
- pluginJson.mcpServers = mcp;
112
- const mcpFile = join(dir, mcp);
113
- const projectedMcp = join(stage, mcp);
114
- rmSync(projectedMcp, { force: true });
115
- ensureDir(dirname(projectedMcp));
116
- // Copy verbatim — preserving formatting and avoiding a parse/re-serialize round-trip.
117
- if (existsSync(mcpFile)) {
118
- cpSync(mcpFile, projectedMcp);
119
- linkFileOrCopy(join(stage, "mcp_config.json"), projectedMcp);
120
- }
121
- }
122
- else {
123
- rmSync(join(stage, mcp || ".mcp.json"), { force: true });
124
- }
125
- writeJson(join(stage, "plugin.json"), pluginJson);
126
- const skillsDir = join(stage, "skills");
127
- rmSync(skillsDir, { recursive: true, force: true });
128
- if (manifest.skills !== undefined && isExposed(selection, "skills")) {
129
- const pick = selection?.skills;
130
- for (const e of resolveSkillEntries(dir, manifest)) {
131
- if (pick && !pick.includes(e.name))
132
- continue;
133
- if (!e.skillMd)
134
- continue;
135
- const srcSkillDir = dirname(e.skillMd);
136
- if (existsSync(srcSkillDir) && statSync(srcSkillDir).isDirectory()) {
137
- linkOrCopy(join(skillsDir, e.name), srcSkillDir);
138
- }
139
- }
140
- }
141
- for (const field of DIR_FIELDS) {
142
- const link = join(stage, field);
143
- rmSync(link, { recursive: true, force: true });
128
+ const { manifest: pluginJson } = toAntigravityManifest(dir, manifest, selection);
129
+ writeJson(join(dir, ANTIGRAVITY_MANIFEST), pluginJson);
130
+ writeAntigravityMcpConfig(dir, manifest, selection);
131
+ writeAntigravityHooks(dir, manifest, selection);
132
+ for (const field of CONVENTION_FIELDS) {
133
+ const link = join(dir, field);
134
+ rmIfSymlink(link); // clear a stale alias (incl. a broken one); a real source dir is left untouched
144
135
  if (!isExposed(selection, field))
145
136
  continue;
146
137
  const seg = componentSegment(manifest[field]);
147
- if (!seg)
148
- continue;
149
- const srcDir = join(dir, seg);
150
- // agy reads the component by its convention name (`field`); point that at
151
- // the real source dir so a non-conventional source name still resolves.
152
- if (existsSync(srcDir))
153
- linkOrCopy(link, srcDir);
138
+ if (!seg || seg === field)
139
+ continue; // absent, or already convention-named in place
140
+ const src = join(dir, seg);
141
+ if (existsSync(src))
142
+ linkOrCopy(link, src);
154
143
  }
155
144
  }
145
+ /**
146
+ * Expose `realDir` to Antigravity at `<scanDir>/<name>`. No-op when the real dir
147
+ * already *is* that path (project, flat). Returns false without touching disk when
148
+ * the target is a real directory ADG didn't create (no agy manifest) — we never
149
+ * clobber a plugin slot we don't own. Replacing our own alias or a prior
150
+ * projection (which carries the manifest) is fine.
151
+ */
152
+ function exposeAt(scanDir, name, realDir) {
153
+ const target = join(scanDir, name);
154
+ if (resolve(target) === resolve(realDir))
155
+ return true; // project, flat: already in the scan dir
156
+ let existing;
157
+ try {
158
+ existing = lstatSync(target);
159
+ }
160
+ catch {
161
+ existing = undefined; // absent — safe to create
162
+ }
163
+ if (existing?.isDirectory() && !existing.isSymbolicLink() && !existsSync(join(target, ANTIGRAVITY_MANIFEST))) {
164
+ console.error(`antigravity: skipping "${name}" — ${target} already exists and is not ADG-managed. ` +
165
+ `Remove it to let ADG manage this plugin.`);
166
+ return false;
167
+ }
168
+ linkOrCopy(target, realDir);
169
+ return true;
170
+ }
171
+ /**
172
+ * Tear down a plugin's projection. When the real store dir is known, drop its agy
173
+ * manifest and any convention alias links (in-place cleanup). Remove the external
174
+ * exposure entry only when it is our own alias (a symlink) or a copy-fallback dir
175
+ * that carries the manifest — never recursively delete an unattributable dir, and
176
+ * never the in-place store folder itself.
177
+ */
178
+ function removeProjection(scanDir, name, realDir) {
179
+ const target = join(scanDir, name);
180
+ let st;
181
+ try {
182
+ st = lstatSync(target);
183
+ }
184
+ catch {
185
+ st = undefined;
186
+ }
187
+ if (realDir) {
188
+ // The real store dir is known: drop the in-place manifest + convention aliases.
189
+ rmSync(join(realDir, ANTIGRAVITY_MANIFEST), { force: true });
190
+ writeAntigravityMcpConfig(realDir, readManifest(realDir), { components: [] });
191
+ writeAntigravityHooks(realDir, readManifest(realDir), { components: [] });
192
+ for (const field of CONVENTION_FIELDS)
193
+ rmIfSymlink(join(realDir, field));
194
+ if (resolve(target) === resolve(realDir))
195
+ return; // in-place: target IS the store folder — never delete it
196
+ // Aliased exposure we created (symlink, or a copy-fallback dir): safe to drop wholesale.
197
+ if (st)
198
+ rmSync(target, { recursive: true, force: true });
199
+ return;
200
+ }
201
+ // Real dir unknown (e.g. the store entry is already gone): we cannot prove a real
202
+ // directory at `target` is our exposure vs. a store/foreign folder, so only ever
203
+ // remove a symlink alias — never recursively delete an unattributable directory.
204
+ if (st?.isSymbolicLink())
205
+ rmSync(target, { force: true });
206
+ }
207
+ /** Resolve a plugin's on-disk dir and selection from the lock, or undefined when not installed. */
208
+ function pluginRealDir(pluginsDir, name) {
209
+ const entry = readLock(lockPath(pluginsDir)).plugins[name];
210
+ if (!entry)
211
+ return undefined;
212
+ const dir = installedPluginDir(pluginsDir, name, entry.origin);
213
+ return existsSync(dir) ? { dir, selection: entry.selection } : undefined;
214
+ }
156
215
  export const antigravityAgent = {
157
216
  id: ID,
158
217
  displayName: "Antigravity",
159
218
  adaptTarget: "antigravity",
160
- detect: (env = process.env) => existsSync(antigravityHome(env)),
161
- available,
219
+ // The directory model needs no CLI: an `antigravity*` marker under the Gemini
220
+ // home is the signal that Antigravity is installed and its scan dirs are real.
221
+ detect: (env = process.env) => antigravityPresent(env),
222
+ available: () => antigravityPresent(process.env),
162
223
  activate(ctx) {
163
- if (!available())
224
+ if (!antigravityAgent.detect())
164
225
  return skippedResult(ID);
165
- // Query agy once up front so the pre-install uninstall below is issued only
166
- // for plugins that are actually present (a brand-new plugin has no residual
167
- // to clear). `undefined` (couldn't enumerate) falls back to always
168
- // uninstalling, preserving the clean-replace guarantee.
169
- const installed = antigravityInstalled();
226
+ const scanDir = antigravityScanDir(ctx);
227
+ ensureDir(scanDir);
170
228
  const affected = [];
171
229
  for (const p of ctx.plugins) {
172
- // Isolate each plugin: a malformed manifest or a filesystem error must not
173
- // abort activation of the remaining (valid) plugins.
230
+ // Isolate each plugin: a malformed manifest or fs error must not abort the rest.
174
231
  try {
175
- const store = pluginStore(ctx.pluginsDir, p);
176
- if (!store)
232
+ const real = pluginRealDir(ctx.pluginsDir, p);
233
+ if (!real)
177
234
  continue;
178
- writeAntigravityProjection(store.dir, store.selection);
179
- // `agy plugin install` *merges* into an existing `<store>/plugins/<name>`
180
- // rather than replacing it, so components dropped since the last sync (a
181
- // narrowed selection, or a skill removed upstream) would linger as
182
- // residual data. Uninstall an existing copy first to force a clean
183
- // re-import; skip it for a not-yet-installed plugin (nothing to clear).
184
- if (installed === undefined || installed.includes(p)) {
185
- run(["plugin", "uninstall", p]);
186
- }
187
- if (run(["plugin", "install", join(store.dir, ANTIGRAVITY_PROJECTION_DIR)]).ok)
235
+ ensureAntigravityRoot(real.dir, real.selection);
236
+ if (exposeAt(scanDir, p, real.dir))
188
237
  affected.push(p);
189
238
  }
190
239
  catch (err) {
@@ -194,55 +243,34 @@ export const antigravityAgent = {
194
243
  return { agent: ID, affected, skipped: false };
195
244
  },
196
245
  deactivate(ctx) {
197
- if (!available())
246
+ if (!antigravityAgent.detect())
198
247
  return skippedResult(ID);
248
+ const scanDir = antigravityScanDir(ctx);
249
+ const lock = readLock(lockPath(ctx.pluginsDir)).plugins;
199
250
  const affected = [];
200
251
  for (const p of ctx.plugins) {
201
- if (run(["plugin", "uninstall", p]).ok)
202
- affected.push(p);
252
+ const entry = lock[p];
253
+ const realDir = entry ? installedPluginDir(ctx.pluginsDir, p, entry.origin) : undefined;
254
+ removeProjection(scanDir, p, realDir);
255
+ affected.push(p);
203
256
  }
204
257
  return { agent: ID, affected, skipped: false };
205
258
  },
206
- // Re-running activate is the refresh: it uninstalls then re-imports the source
207
- // dir, so a shrunk component set replaces the stale copy instead of merging.
259
+ // Re-running activate is the refresh: it rewrites the manifest and re-exposes
260
+ // the store dir, so a changed plugin replaces its stale projection in place.
208
261
  refresh(ctx) {
209
262
  return antigravityAgent.activate(ctx);
210
263
  },
211
- // `agy plugin list` emits JSON (`{ imports: [{ name }] }`). agy has no
212
- // marketplace concept, so this returns *every* imported plugin — including
213
- // ones imported outside ADG; the caller treats agy-only names as "not managed
214
- // here" rather than asserting they are ADG orphans.
215
- // `available()` (stdio-ignored probe) gates the query, so an absent CLI is a
216
- // quiet `undefined` ("unknown") rather than echoing a spawn error to stderr.
217
- listInstalled: () => antigravityInstalled(),
264
+ // Provenance is ADG's, not the agent's: enumerate the queried scope's own lock
265
+ // and keep only plugins Antigravity actually sees in that scope's scan dir (a
266
+ // root `plugin.json`, reached directly or via the exposure link). A project
267
+ // query therefore can't surface globally-installed plugins. `undefined` only
268
+ // when Antigravity isn't present at all ("unknown"), never confused with empty.
269
+ listInstalled(ctx) {
270
+ if (!antigravityAgent.detect())
271
+ return undefined;
272
+ const scanDir = antigravityScanDir(ctx);
273
+ const names = Object.keys(readLock(lockPath(ctx.pluginsDir)).plugins);
274
+ return names.filter((name) => existsSync(join(scanDir, name, ANTIGRAVITY_MANIFEST)));
275
+ },
218
276
  };
219
- /**
220
- * The plugin names agy currently has imported, or `undefined` when the CLI is
221
- * absent or its output can't be parsed. Shared by `listInstalled` and by
222
- * `activate` (to skip the pre-install uninstall for brand-new plugins).
223
- */
224
- function antigravityInstalled() {
225
- if (!available())
226
- return undefined;
227
- const res = run(["plugin", "list"]);
228
- if (!res.ok)
229
- return undefined;
230
- return parseAntigravityPluginList(res.out);
231
- }
232
- /**
233
- * Parse `agy plugin list` JSON (`{ imports: [{ name }] }`) into deduped plugin
234
- * names, or `undefined` when the output isn't the expected JSON. Pure (no CLI)
235
- * so it is unit-testable against captured output.
236
- */
237
- export function parseAntigravityPluginList(out) {
238
- try {
239
- const parsed = JSON.parse(out);
240
- const names = (parsed.imports ?? [])
241
- .map((i) => i.name)
242
- .filter((n) => typeof n === "string");
243
- return [...new Set(names)];
244
- }
245
- catch {
246
- return undefined; // unparseable output — report "unknown", don't guess
247
- }
248
- }
@@ -1,9 +1,10 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { existsSync } from "node:fs";
2
3
  import { homedir } from "node:os";
3
- import { join, relative } from "node:path";
4
+ import { join, relative, resolve } from "node:path";
4
5
  import { toPosix, writeJson } from "../fsutil.js";
5
6
  import { readManifest } from "../manifest.js";
6
- import { installedPluginDir, lockPath } from "../paths.js";
7
+ import { globalPluginsDir, installedPluginDir, lockPath } from "../paths.js";
7
8
  import { readLock } from "../lock.js";
8
9
  import { makeCli, skippedResult } from "./base.js";
9
10
  /**
@@ -19,11 +20,24 @@ function claudeHome(env) {
19
20
  return env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), ".claude");
20
21
  }
21
22
  const { available, run } = makeCli("claude", { probeArgs: ["plugin", "--help"] });
23
+ /**
24
+ * Claude's marketplace registry is keyed only by marketplace name. Keep the
25
+ * historical global marketplace name stable, but give project/explicit stores a
26
+ * store-scoped name so a project install never updates or queries a stale global
27
+ * `adg` marketplace.
28
+ */
29
+ export function claudeMarketplaceName(pluginsDir) {
30
+ const normalized = resolve(pluginsDir);
31
+ if (normalized === resolve(globalPluginsDir()))
32
+ return MARKETPLACE;
33
+ const hash = createHash("sha1").update(toPosix(normalized)).digest("hex").slice(0, 8);
34
+ return `${MARKETPLACE}-${hash}`;
35
+ }
22
36
  /**
23
37
  * Write a Claude marketplace catalog listing every installed plugin, each
24
38
  * `source` pointing at its on-disk directory (relative to the catalog).
25
39
  */
26
- export function writeClaudeCatalog(pluginsDir, name = MARKETPLACE) {
40
+ export function writeClaudeCatalog(pluginsDir, name = claudeMarketplaceName(pluginsDir)) {
27
41
  const lock = readLock(lockPath(pluginsDir));
28
42
  const plugins = [];
29
43
  for (const [pname, entry] of Object.entries(lock.plugins)) {
@@ -61,11 +75,9 @@ export function writeClaudeCatalog(pluginsDir, name = MARKETPLACE) {
61
75
  return { file, name };
62
76
  }
63
77
  /** Register the ADG store as a Claude marketplace (add, or update if present). */
64
- function syncMarketplace(pluginsDir) {
65
- const list = run(["plugin", "marketplace", "list"]);
66
- if (list.ok && list.out.includes(MARKETPLACE))
67
- run(["plugin", "marketplace", "update", MARKETPLACE]);
68
- else
78
+ function syncMarketplace(pluginsDir, name) {
79
+ const update = run(["plugin", "marketplace", "update", name]);
80
+ if (!update.ok)
69
81
  run(["plugin", "marketplace", "add", pluginsDir]);
70
82
  }
71
83
  export const claudeAgent = {
@@ -77,18 +89,18 @@ export const claudeAgent = {
77
89
  activate(ctx) {
78
90
  if (!available())
79
91
  return skippedResult("claude");
80
- writeClaudeCatalog(ctx.pluginsDir);
81
- syncMarketplace(ctx.pluginsDir);
92
+ const { name: marketplace } = writeClaudeCatalog(ctx.pluginsDir);
93
+ syncMarketplace(ctx.pluginsDir, marketplace);
82
94
  const affected = [];
83
95
  for (const p of ctx.plugins) {
84
- const r = run(["plugin", "install", `${p}@${MARKETPLACE}`, "--scope", ctx.scope]);
96
+ const r = run(["plugin", "install", `${p}@${marketplace}`, "--scope", ctx.scope]);
85
97
  if (r.ok)
86
98
  affected.push(p);
87
99
  // Surface the CLI's reason instead of silently dropping the plugin — a
88
100
  // rejected manifest (e.g. `hooks: Invalid input`) otherwise looks like a
89
101
  // no-op "missing" with no diagnostic.
90
102
  else
91
- console.error(`claude: failed to install ${p}@${MARKETPLACE}: ${r.out.trim()}`);
103
+ console.error(`claude: failed to install ${p}@${marketplace}: ${r.out.trim()}`);
92
104
  }
93
105
  return { agent: "claude", affected, skipped: false };
94
106
  },
@@ -121,7 +133,7 @@ export const claudeAgent = {
121
133
  const res = run(["plugin", "list"]);
122
134
  if (!res.ok)
123
135
  return undefined;
124
- return parseClaudePluginList(res.out, MARKETPLACE, ctx.scope);
136
+ return parseClaudePluginList(res.out, claudeMarketplaceName(ctx.pluginsDir), ctx.scope);
125
137
  },
126
138
  };
127
139
  /**
@@ -1,23 +1,51 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { existsSync } from "node:fs";
2
3
  import { homedir } from "node:os";
3
- import { join } from "node:path";
4
- import { marketplacePath } from "../paths.js";
5
- import { readMarketplace } from "../marketplace.js";
4
+ import { join, resolve } from "node:path";
5
+ import { codexMarketplaceRoot, globalPluginsDir, marketplacePath } from "../paths.js";
6
+ import { readMarketplace, writeMarketplace } from "../marketplace.js";
6
7
  import { makeCli, skippedResult } from "./base.js";
7
8
  /**
8
9
  * Codex agent.
9
10
  *
10
- * Codex natively discovers the `.agents/plugins/marketplace.json` ADG writes, so
11
- * plugins show up as *available* — but aren't usable until installed with
12
- * `codex plugin add`. We drive that via the `codex` CLI (which owns ~/.codex).
11
+ * Codex consumes configured marketplace roots. For a project store at
12
+ * `<root>/.agents/plugins`, the configured root is `<root>`; the marketplace file
13
+ * remains at `.agents/plugins/marketplace.json`. Plugins are usable only after
14
+ * `codex plugin add`, so activation registers the root then installs the plugin.
13
15
  */
14
16
  function codexHome(env) {
15
17
  return env.CODEX_HOME?.trim() || join(homedir(), ".codex");
16
18
  }
17
19
  const { available, run } = makeCli("codex", { probeArgs: ["plugin", "--help"] });
18
- /** The marketplace name Codex sees, read from the generated marketplace.json. */
19
- function marketplaceName(pluginsDir) {
20
- return readMarketplace(marketplacePath(pluginsDir), "").name;
20
+ /**
21
+ * Codex's default global marketplace is historically named `plugins`. Project
22
+ * and explicit stores get a store-scoped name to avoid colliding with a global
23
+ * or another project's configured marketplace.
24
+ */
25
+ export function codexMarketplaceName(pluginsDir) {
26
+ const normalized = resolve(pluginsDir);
27
+ if (normalized === resolve(globalPluginsDir()))
28
+ return "plugins";
29
+ const hash = createHash("sha1").update(normalized.split("\\").join("/")).digest("hex").slice(0, 8);
30
+ return `adg-${hash}`;
31
+ }
32
+ /** Ensure the generated Codex marketplace export uses this store's scoped name. */
33
+ export function writeCodexMarketplaceName(pluginsDir) {
34
+ const file = marketplacePath(pluginsDir);
35
+ const marketplace = readMarketplace(file, codexMarketplaceName(pluginsDir));
36
+ const name = codexMarketplaceName(pluginsDir);
37
+ if (marketplace.name !== name) {
38
+ marketplace.name = name;
39
+ writeMarketplace(file, marketplace);
40
+ }
41
+ return name;
42
+ }
43
+ /** Register the local marketplace root Codex expects for this store. */
44
+ function syncMarketplace(pluginsDir, marketplace) {
45
+ const root = codexMarketplaceRoot(pluginsDir);
46
+ const add = run(["plugin", "marketplace", "add", root]);
47
+ if (!add.ok)
48
+ run(["plugin", "marketplace", "upgrade", marketplace]);
21
49
  }
22
50
  export const codexAgent = {
23
51
  id: "codex",
@@ -26,9 +54,10 @@ export const codexAgent = {
26
54
  detect: (env = process.env) => existsSync(codexHome(env)) || existsSync("/etc/codex"),
27
55
  available,
28
56
  activate(ctx) {
29
- const mp = marketplaceName(ctx.pluginsDir);
57
+ const mp = writeCodexMarketplaceName(ctx.pluginsDir);
30
58
  if (!available())
31
59
  return skippedResult("codex");
60
+ syncMarketplace(ctx.pluginsDir, mp);
32
61
  const affected = [];
33
62
  for (const p of ctx.plugins) {
34
63
  if (run(["plugin", "add", `${p}@${mp}`]).ok)
@@ -37,7 +66,7 @@ export const codexAgent = {
37
66
  return { agent: "codex", affected, skipped: false };
38
67
  },
39
68
  deactivate(ctx) {
40
- const mp = marketplaceName(ctx.pluginsDir);
69
+ const mp = writeCodexMarketplaceName(ctx.pluginsDir);
41
70
  if (!available())
42
71
  return skippedResult("codex");
43
72
  const affected = [];
@@ -60,15 +89,24 @@ export const codexAgent = {
60
89
  listInstalled(ctx) {
61
90
  if (!available())
62
91
  return undefined;
63
- const mp = marketplaceName(ctx.pluginsDir);
92
+ const mp = writeCodexMarketplaceName(ctx.pluginsDir);
64
93
  if (!mp)
65
94
  return undefined; // no generated marketplace → can't scope the query
66
95
  const res = run(["plugin", "list"]);
67
96
  if (!res.ok)
68
- return undefined;
97
+ return codexListFailure(res.out);
69
98
  return parseCodexPluginList(res.out, mp);
70
99
  },
71
100
  };
101
+ /** Preserve Codex's diagnostic and offer cleanup for a stale ADG project marketplace. */
102
+ export function codexListFailure(out) {
103
+ const detail = out.trim() || "codex plugin list failed without an error message";
104
+ const staleMarketplace = detail.match(/- `(adg-[0-9a-f]{8})` at .*marketplace root does not contain a supported manifest/);
105
+ return {
106
+ error: detail,
107
+ ...(staleMarketplace ? { recoveryCommand: `codex plugin marketplace remove ${staleMarketplace[1]}` } : {}),
108
+ };
109
+ }
72
110
  /**
73
111
  * Parse `codex plugin list` output into the *installed and enabled* plugin names
74
112
  * from a given marketplace. The listing is a whitespace-aligned table whose
@@ -9,4 +9,5 @@ registerAgent(codexAgent);
9
9
  registerAgent(antigravityAgent);
10
10
  export * from "./types.js";
11
11
  export { registerAgent, getAgent, allAgents, detectedAgents, resolveAgents, agentsForComponents } from "./registry.js";
12
- export { writeClaudeCatalog } from "./claude.js";
12
+ export { claudeMarketplaceName, writeClaudeCatalog } from "./claude.js";
13
+ export { codexMarketplaceName, writeCodexMarketplaceName } from "./codex.js";