@rbbtsn0w/adg 0.4.0-beta.1 → 0.4.0-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.
@@ -8,7 +8,7 @@ import { isExposed } from "../components.js";
8
8
  import { installedPluginDir, lockPath } from "../paths.js";
9
9
  import { readLock } from "../lock.js";
10
10
  import { ANTIGRAVITY_PROJECTION_DIR } from "../adapters/antigravity.js";
11
- import { makeCli } from "./base.js";
11
+ import { makeCli, skippedResult } from "./base.js";
12
12
  /**
13
13
  * Antigravity (`agy`) agent.
14
14
  *
@@ -140,7 +140,7 @@ export const antigravityAgent = {
140
140
  available,
141
141
  activate(ctx) {
142
142
  if (!available())
143
- return { agent: ID, affected: [], skipped: true };
143
+ return skippedResult(ID);
144
144
  // Query agy once up front so the pre-install uninstall below is issued only
145
145
  // for plugins that are actually present (a brand-new plugin has no residual
146
146
  // to clear). `undefined` (couldn't enumerate) falls back to always
@@ -174,7 +174,7 @@ export const antigravityAgent = {
174
174
  },
175
175
  deactivate(ctx) {
176
176
  if (!available())
177
- return { agent: ID, affected: [], skipped: true };
177
+ return skippedResult(ID);
178
178
  const affected = [];
179
179
  for (const p of ctx.plugins) {
180
180
  if (run(["plugin", "uninstall", p]).ok)
@@ -1,4 +1,13 @@
1
1
  import { spawnSync } from "node:child_process";
2
+ /**
3
+ * The canonical "CLI absent, so nothing was touched" lifecycle result. Every
4
+ * agent's activate/deactivate guard returns this shape; centralizing it keeps
5
+ * the agent id the single thing that varies and rules out a hand-typed drift
6
+ * (e.g. a wrong `agent` field or a missing `skipped`).
7
+ */
8
+ export function skippedResult(agent) {
9
+ return { agent, affected: [], skipped: true };
10
+ }
2
11
  /**
3
12
  * Build the shared `available()` / `run()` pair for an agent that drives an
4
13
  * external plugin CLI. Centralizing the `spawnSync` here keeps error handling,
@@ -6,8 +15,14 @@ import { spawnSync } from "node:child_process";
6
15
  * rather than copied across every agent.
7
16
  */
8
17
  export function makeCli(bin, opts) {
18
+ // A CLI's presence can't change within a single `adg` run, yet `available()`
19
+ // is called as a guard on every agent lifecycle op (and once per plugin in
20
+ // some loops). Memoize the first probe so one `plugins update --both` can't
21
+ // re-shell the same `--help` many times. Cached on first call, not eagerly,
22
+ // so importing an agent module never spawns a subprocess.
23
+ let probed;
9
24
  return {
10
- available: () => spawnSync(bin, opts.probeArgs, { stdio: "ignore" }).status === 0,
25
+ available: () => (probed ??= spawnSync(bin, opts.probeArgs, { stdio: "ignore" }).status === 0),
11
26
  run: (args) => {
12
27
  const r = spawnSync(bin, args, { encoding: "utf8" });
13
28
  // A launch failure (e.g. ENOENT for a missing binary, EACCES) leaves
@@ -5,7 +5,7 @@ import { toPosix, writeJson } from "../fsutil.js";
5
5
  import { readManifest } from "../manifest.js";
6
6
  import { installedPluginDir, lockPath } from "../paths.js";
7
7
  import { readLock } from "../lock.js";
8
- import { makeCli } from "./base.js";
8
+ import { makeCli, skippedResult } from "./base.js";
9
9
  /**
10
10
  * Claude Code agent.
11
11
  *
@@ -76,7 +76,7 @@ export const claudeAgent = {
76
76
  available,
77
77
  activate(ctx) {
78
78
  if (!available())
79
- return { agent: "claude", affected: [], skipped: true };
79
+ return skippedResult("claude");
80
80
  writeClaudeCatalog(ctx.pluginsDir);
81
81
  syncMarketplace(ctx.pluginsDir);
82
82
  const affected = [];
@@ -88,7 +88,7 @@ export const claudeAgent = {
88
88
  },
89
89
  deactivate(ctx) {
90
90
  if (!available())
91
- return { agent: "claude", affected: [], skipped: true };
91
+ return skippedResult("claude");
92
92
  const affected = [];
93
93
  for (const p of ctx.plugins) {
94
94
  if (run(["plugin", "uninstall", p, "--scope", ctx.scope]).ok)
@@ -98,7 +98,7 @@ export const claudeAgent = {
98
98
  },
99
99
  refresh(ctx) {
100
100
  if (!available())
101
- return { agent: "claude", affected: [], skipped: true };
101
+ return skippedResult("claude");
102
102
  // Claude caches a copy on install and won't re-pull from a local marketplace,
103
103
  // so uninstall (keeping data) then re-install to force a fresh copy.
104
104
  for (const p of ctx.plugins)
@@ -3,7 +3,7 @@ import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { marketplacePath } from "../paths.js";
5
5
  import { readMarketplace } from "../marketplace.js";
6
- import { makeCli } from "./base.js";
6
+ import { makeCli, skippedResult } from "./base.js";
7
7
  /**
8
8
  * Codex agent.
9
9
  *
@@ -28,7 +28,7 @@ export const codexAgent = {
28
28
  activate(ctx) {
29
29
  const mp = marketplaceName(ctx.pluginsDir);
30
30
  if (!available())
31
- return { agent: "codex", affected: [], skipped: true };
31
+ return skippedResult("codex");
32
32
  const affected = [];
33
33
  for (const p of ctx.plugins) {
34
34
  if (run(["plugin", "add", `${p}@${mp}`]).ok)
@@ -39,7 +39,7 @@ export const codexAgent = {
39
39
  deactivate(ctx) {
40
40
  const mp = marketplaceName(ctx.pluginsDir);
41
41
  if (!available())
42
- return { agent: "codex", affected: [], skipped: true };
42
+ return skippedResult("codex");
43
43
  const affected = [];
44
44
  for (const p of ctx.plugins) {
45
45
  if (run(["plugin", "remove", `${p}@${mp}`]).ok)
@@ -0,0 +1,544 @@
1
+ import { existsSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { adaptPlugin } from "../commands/adapt.js";
4
+ import { addPlugins } from "../commands/install.js";
5
+ import { validatePlugin } from "../commands/validate.js";
6
+ import { listPlugins } from "../commands/list.js";
7
+ import { importSkills } from "../commands/import.js";
8
+ import { linkPlugins } from "../commands/link.js";
9
+ import { unlinkPlugins } from "../commands/unlink.js";
10
+ import { syncPlugins } from "../commands/sync.js";
11
+ import { removePlugin } from "../commands/remove.js";
12
+ import { migrateLayout } from "../commands/migrate.js";
13
+ import { pluginStatus } from "../commands/status.js";
14
+ import { marketplaceList, marketplaceRemove, marketplaceSync, updatePlugins } from "../commands/marketplace.js";
15
+ import { initScaffold } from "../commands/init.js";
16
+ import { confirmFullInstall, selectComponentsInteractive } from "../commands/select-components.js";
17
+ import { selectPluginsInteractive } from "../commands/select-plugins.js";
18
+ import { selectTargetsInteractive } from "../commands/select-agents.js";
19
+ import { selectScopeInteractive, selectUpdateScopeInteractive } from "../commands/select-scope.js";
20
+ import { globalPluginsDir, projectPluginsDir, lockPath } from "../paths.js";
21
+ import { getAgent } from "../agents/index.js";
22
+ import { ui } from "../render/ui.js";
23
+ import { renderAgentReport, renderMarketplaceList, renderPluginList, renderStatus, renderUpdateReport, } from "../render/plugins.js";
24
+ import { MARKETPLACE_USAGE, PLUGIN_ALIASES, PLUGIN_COMMANDS, SCOPE, fail, parseVerb, renderPluginsHelp, renderVerbHelp, requireSingleTarget, resolveComponents, resolveScopeDir, resolveTargets, scopeOf, wantsHelp, } from "./index.js";
25
+ /**
26
+ * Resolve which scope(s) `plugins update` should refresh, mirroring
27
+ * `adg skills update`: an explicit --dir is a single ad-hoc location; otherwise
28
+ * --project/--global (or both) win, a terminal prompts for project/global/both,
29
+ * and a non-interactive run defaults to project when a project lock exists.
30
+ */
31
+ async function resolveUpdateScopes(values) {
32
+ if (typeof values.dir === "string") {
33
+ const dir = resolve(values.dir);
34
+ return [{ dir, agentScope: "project", label: dir }];
35
+ }
36
+ const project = { dir: projectPluginsDir(), agentScope: "project", label: "project" };
37
+ const global = { dir: globalPluginsDir(), agentScope: "user", label: "global" };
38
+ let choice;
39
+ if (values.global && values.project)
40
+ choice = "both";
41
+ else if (values.global)
42
+ choice = "global";
43
+ else if (values.project)
44
+ choice = "project";
45
+ else if (process.stdin.isTTY)
46
+ choice = await selectUpdateScopeInteractive();
47
+ else
48
+ choice = existsSync(lockPath(projectPluginsDir())) ? "project" : "global";
49
+ // Home==global trap: a "project" (or "both") scope whose store resolves to the
50
+ // global store would re-pin global plugins to the cwd. Collapse to global.
51
+ // Reuse the dirs already resolved above instead of walking the filesystem again.
52
+ if (choice !== "global" && project.dir === global.dir) {
53
+ console.error(ui.warn(`note: the project store resolves to the global store (${global.dir}); updating global only so plugins aren't pinned to a project (cwd) scope.`));
54
+ choice = "global";
55
+ }
56
+ if (choice === "both") {
57
+ return [{ ...project, heading: "Project plugins" }, { ...global, heading: "Global plugins" }];
58
+ }
59
+ return [choice === "global" ? global : project];
60
+ }
61
+ /** Render an update/upgrade result: per-source changes, then per-agent re-sync. */
62
+ function printUpdateReport(result) {
63
+ for (const line of renderUpdateReport(result))
64
+ console.log(line);
65
+ for (const line of renderAgentReport(result.agents, "re-synced"))
66
+ console.log(line);
67
+ }
68
+ /**
69
+ * A "project" store that resolves to the *global* store path is a trap: running
70
+ * a mutating verb there reads the global plugin set but writes the agent install
71
+ * at project scope, pinning it to the cwd (e.g. the home directory). Promote
72
+ * such a case to global. Pure so it is unit-testable.
73
+ */
74
+ export function projectStoreIsGlobalTrap(global, projectDir, globalDir) {
75
+ return !global && projectDir === globalDir;
76
+ }
77
+ /**
78
+ * Apply the home==global guard to a chosen scope: a project scope whose store
79
+ * resolves to the global store would pin plugins to the cwd (e.g. the home
80
+ * directory), so warn and promote it to global. Returns the effective global
81
+ * flag. Shared by every scope-resolving verb (add/update plus resolveActionScope)
82
+ * so the guard can't be forgotten on one path. Callers that already resolved the
83
+ * store dirs may pass them in to avoid recomputing the (filesystem-walking)
84
+ * `projectPluginsDir`. Exported for unit testing the promotion side effect.
85
+ */
86
+ export function promoteGlobalTrap(global, projectDir = projectPluginsDir(), globalDir = globalPluginsDir()) {
87
+ if (!projectStoreIsGlobalTrap(global, projectDir, globalDir))
88
+ return global;
89
+ console.error(ui.warn(`note: the project store resolves to the global store (${globalDir}); using --global so plugins aren't pinned to a project (cwd) scope.`));
90
+ return true;
91
+ }
92
+ /**
93
+ * Resolve scope for a mutating verb (sync/link/unlink/remove/migrate/…). Unlike
94
+ * the silent `resolveScopeDir`/`scopeOf`, this:
95
+ * - honors an explicit --dir/--global/--project,
96
+ * - rejects a contradictory --global + --project (a single-scope projection),
97
+ * - prompts (project/global) in a terminal when none was given,
98
+ * - fails in a non-interactive run rather than silently defaulting to project,
99
+ * - promotes the home==global trap to global with a warning.
100
+ */
101
+ async function resolveActionScope(values, verb) {
102
+ if (typeof values.dir === "string") {
103
+ // --dir is an explicit ad-hoc store; --global still selects the user agent
104
+ // scope (matching the old scopeOf behavior), the trap guard doesn't apply.
105
+ const dir = resolve(values.dir);
106
+ const global = Boolean(values.global);
107
+ return { pluginsDir: dir, global, agentScope: global ? "user" : "project", info: { label: dir, globalDir: globalPluginsDir() } };
108
+ }
109
+ if (values.global && values.project)
110
+ fail(`plugins ${verb} takes only one of --global / --project`);
111
+ let global;
112
+ if (values.global)
113
+ global = true;
114
+ else if (values.project)
115
+ global = false;
116
+ else if (process.stdin.isTTY)
117
+ global = await selectScopeInteractive();
118
+ else
119
+ fail(`plugins ${verb} needs an explicit scope in a non-interactive run: pass --global or --project`);
120
+ // Resolve the store dirs once (projectPluginsDir walks the filesystem) and
121
+ // reuse them for the trap guard, the store path, and the info label.
122
+ const projectDir = projectPluginsDir();
123
+ const globalDir = globalPluginsDir();
124
+ global = promoteGlobalTrap(global, projectDir, globalDir);
125
+ return {
126
+ pluginsDir: global ? globalDir : projectDir,
127
+ global,
128
+ agentScope: global ? "user" : "project",
129
+ info: { label: global ? "global" : "project", globalDir },
130
+ };
131
+ }
132
+ /**
133
+ * Top-level dispatcher for `adg plugins <verb>`: render help, resolve aliases,
134
+ * look the verb up in the command table, then hand off to the per-verb handler
135
+ * (or the marketplace sub-dispatcher). Kept free of `spawnSync` so the whole
136
+ * dispatch surface is unit-testable.
137
+ */
138
+ export async function runPlugins(rawVerb, rest) {
139
+ // `adg plugins` (no verb) or an explicit help request → the L1 overview.
140
+ if (rawVerb === undefined || rawVerb === "-h" || rawVerb === "--help" || rawVerb === "help") {
141
+ console.log(renderPluginsHelp());
142
+ return;
143
+ }
144
+ const verb = PLUGIN_ALIASES[rawVerb] ?? rawVerb;
145
+ const cmd = PLUGIN_COMMANDS[verb];
146
+ if (!cmd) {
147
+ console.error(`${ui.err("error:")} unknown plugins subcommand: ${rawVerb}\n`);
148
+ console.error(renderPluginsHelp());
149
+ process.exit(1);
150
+ }
151
+ // `adg plugins <verb> -h` → just this command's help. (marketplace handles
152
+ // its own sub-help, so let it through.)
153
+ if (!cmd.delegated && wantsHelp(rest)) {
154
+ console.log(renderVerbHelp(verb));
155
+ return;
156
+ }
157
+ if (verb === "marketplace")
158
+ return runMarketplace(rest);
159
+ return runPluginsVerb(verb, rest, cmd);
160
+ }
161
+ async function runPluginsVerb(verb, rest, cmd) {
162
+ switch (verb) {
163
+ case "init": {
164
+ const { values, positionals } = parseVerb(verb, cmd.flags, rest);
165
+ const name = positionals[0];
166
+ if (!name)
167
+ fail("plugins init requires a <name>");
168
+ const dir = values.dir ? resolve(values.dir) : resolve(process.cwd(), "plugins");
169
+ const type = (values.type ?? "plugin");
170
+ if (type !== "plugin" && type !== "marketplace" && type !== "all") {
171
+ fail(`invalid --type "${values.type}" (expected plugin|marketplace|all)`);
172
+ }
173
+ const res = initScaffold({ name, dir, type, description: values.description, author: values.author, skill: values.skill?.[0] });
174
+ console.log(`${ui.ok(`created ${type}`)} at ${ui.name(res.pluginDir)}`);
175
+ for (const f of res.created)
176
+ console.log(ui.meta(` + ${f}`));
177
+ return;
178
+ }
179
+ case "adapt": {
180
+ const { values, positionals } = parseVerb(verb, cmd.flags, rest);
181
+ const pluginDir = resolve(positionals[0] ?? process.cwd());
182
+ for (const r of adaptPlugin(pluginDir, resolveTargets(values.target))) {
183
+ console.log(`${ui.ok("adapted")} ${ui.name(r.target)} ${ui.meta(`-> ${r.file}`)}`);
184
+ }
185
+ return;
186
+ }
187
+ case "validate": {
188
+ const { positionals } = parseVerb(verb, cmd.flags, rest);
189
+ const pluginDir = resolve(positionals[0] ?? process.cwd());
190
+ const res = validatePlugin(pluginDir);
191
+ if (res.ok) {
192
+ console.log(`${ui.ok("ok:")} ${ui.name(pluginDir)} is a valid ADG plugin`);
193
+ }
194
+ else {
195
+ console.error(`${ui.err("invalid:")} ${ui.name(pluginDir)}`);
196
+ for (const i of res.issues)
197
+ console.error(ui.warn(` - ${i}`));
198
+ process.exit(1);
199
+ }
200
+ return;
201
+ }
202
+ case "add": {
203
+ const { values, positionals } = parseVerb(verb, cmd.flags, rest);
204
+ const spec = positionals[0];
205
+ if (!spec)
206
+ fail("plugins add requires a <plugin-dir | owner/repo[@ref] | github-url>");
207
+ const tty = process.stdin.isTTY;
208
+ // Scope: honor an explicit --dir/--global/--project, else ask in a terminal
209
+ // (defaulting to project non-interactively).
210
+ let global = Boolean(values.global);
211
+ if (!values.dir && values.global === undefined && values.project === undefined && tty) {
212
+ global = await selectScopeInteractive();
213
+ }
214
+ // Guard the home==global trap: installing global plugins at project scope
215
+ // would pin them to the cwd. Skip for an explicit --dir store.
216
+ if (!values.dir)
217
+ global = promoteGlobalTrap(global);
218
+ const pluginsDir = values.dir
219
+ ? resolve(values.dir)
220
+ : global
221
+ ? globalPluginsDir()
222
+ : projectPluginsDir();
223
+ // A source may hold one plugin or a whole marketplace. addPlugins discovers
224
+ // all of them; in a terminal the user picks scope, then plugins, then agents,
225
+ // then (unless --only/--skill narrow it) chooses what to install per plugin.
226
+ // --all / --plugin / --path / --only / --skill narrow non-interactively.
227
+ const only = resolveComponents(values.only);
228
+ const skillsSubset = values.skill && values.skill.length > 0 ? values.skill : undefined;
229
+ const narrowed = only !== undefined || skillsSubset !== undefined;
230
+ const { order, installed, converted, agents } = await addPlugins({
231
+ spec,
232
+ pluginsDir,
233
+ ref: values.ref,
234
+ sparse: values.sparse,
235
+ path: values.path,
236
+ all: values.all,
237
+ plugins: values.plugin,
238
+ only,
239
+ skillsSubset,
240
+ withDeps: !values["no-deps"],
241
+ marketplaceName: values["marketplace-name"],
242
+ targets: values.target !== undefined ? resolveTargets(values.target) : undefined,
243
+ selectPlugins: tty ? selectPluginsInteractive : undefined,
244
+ selectTargets: tty && values.target === undefined ? selectTargetsInteractive : undefined,
245
+ confirmFull: tty && !narrowed ? confirmFullInstall : undefined,
246
+ selectComponents: tty && !narrowed ? selectComponentsInteractive : undefined,
247
+ // Make the install actually usable in the chosen agents, not just stored.
248
+ activate: true,
249
+ scope: global ? "user" : "project",
250
+ });
251
+ for (const name of converted)
252
+ console.log(ui.meta(`converted native manifest -> .agents/.plugin.json: ${name}`));
253
+ if (order.length > 1)
254
+ console.log(ui.meta(`install order: ${order.join(" -> ")}`));
255
+ for (const res of installed) {
256
+ console.log(`${ui.ok("added")} ${ui.name(res.name)} ${ui.meta(`-> ${res.installedTo}`)}`);
257
+ console.log(ui.meta(` folderHash: ${res.folderHash}`));
258
+ for (const f of res.adapted)
259
+ console.log(ui.meta(` adapted: ${f}`));
260
+ }
261
+ for (const line of renderAgentReport(agents, "enabled"))
262
+ console.log(line);
263
+ return;
264
+ }
265
+ case "import-skills": {
266
+ const { values, positionals } = parseVerb(verb, cmd.flags, rest);
267
+ const dir = positionals[0];
268
+ if (!dir)
269
+ fail("plugins import-skills requires a <skills-dir>");
270
+ if (!values.as)
271
+ fail("plugins import-skills requires --as <plugin-name>");
272
+ const sc = await resolveActionScope(values, "import-skills");
273
+ const res = importSkills({
274
+ skillsDir: resolve(dir),
275
+ as: values.as,
276
+ prefix: values.prefix,
277
+ pluginsDir: sc.pluginsDir,
278
+ description: values.description,
279
+ });
280
+ console.log(`${ui.ok("imported skills into")} ${ui.name(res.name)} ${ui.meta(`-> ${res.installedTo}`)}`);
281
+ return;
282
+ }
283
+ case "link": {
284
+ const { values, positionals } = parseVerb(verb, cmd.flags, rest);
285
+ const targets = values.target === "all"
286
+ ? resolveTargets("all")
287
+ : [requireSingleTarget(values.target, "link")];
288
+ const sc = await resolveActionScope(values, "link");
289
+ const names = positionals.length > 0 ? positionals : undefined;
290
+ for (const target of targets) {
291
+ const res = linkPlugins({ pluginsDir: sc.pluginsDir, target, global: sc.global, names });
292
+ for (const a of res.actions) {
293
+ console.log(`${ui.ok("linked")} ${ui.name(a.name)} ${ui.meta(`[${res.target}]`)}${a.linkedTo ? ui.meta(` -> ${a.linkedTo}`) : ""}`);
294
+ for (const f of a.adapted)
295
+ console.log(ui.meta(` adapted: ${f}`));
296
+ }
297
+ if (res.cliSkipped) {
298
+ console.log(ui.warn(`note: \`${target}\` CLI not found — manifests were generated, but nothing was enabled in ${target}.`));
299
+ }
300
+ }
301
+ return;
302
+ }
303
+ case "unlink": {
304
+ const { values, positionals } = parseVerb(verb, cmd.flags, rest);
305
+ const targets = values.target === "all"
306
+ ? resolveTargets("all")
307
+ : [requireSingleTarget(values.target, "unlink")];
308
+ const sc = await resolveActionScope(values, "unlink");
309
+ const names = positionals.length > 0 ? positionals : undefined;
310
+ for (const target of targets) {
311
+ const res = unlinkPlugins({ pluginsDir: sc.pluginsDir, target, global: sc.global, names });
312
+ for (const name of res.unlinked)
313
+ console.log(`${ui.ok("unlinked")} ${ui.name(name)} ${ui.meta(`[${res.target}]`)}`);
314
+ if (res.cliSkipped) {
315
+ console.log(ui.warn(`note: \`${target}\` CLI not found — nothing was unlinked from ${target}.`));
316
+ }
317
+ else if (res.unlinked.length === 0) {
318
+ if (targets.length === 1) {
319
+ console.log(ui.meta(`nothing to unlink from ${target}`));
320
+ }
321
+ }
322
+ }
323
+ return;
324
+ }
325
+ case "sync": {
326
+ const { values, positionals } = parseVerb(verb, cmd.flags, rest);
327
+ const targets = values.target === "all"
328
+ ? resolveTargets("all")
329
+ : [requireSingleTarget(values.target, "sync")];
330
+ const sc = await resolveActionScope(values, "sync");
331
+ const names = positionals.length > 0 ? positionals : undefined;
332
+ for (const target of targets) {
333
+ const res = syncPlugins({ pluginsDir: sc.pluginsDir, target, global: sc.global, names });
334
+ for (const a of res.actions) {
335
+ const tail = a.synced ? ui.meta(` -> ${res.target}`) : "";
336
+ console.log(`${ui.ok("synced")} ${ui.name(a.name)} ${ui.meta(`[${res.target}]`)}${tail}`);
337
+ }
338
+ if (res.cliSkipped) {
339
+ console.log(ui.warn(`note: \`${target}\` CLI not found — manifests were regenerated, but nothing was re-synced in ${target}.`));
340
+ }
341
+ }
342
+ return;
343
+ }
344
+ case "update": {
345
+ const { values, positionals } = parseVerb(verb, cmd.flags, rest);
346
+ const source = positionals[0];
347
+ for (const sc of await resolveUpdateScopes(values)) {
348
+ if (sc.heading)
349
+ console.log(`${ui.name(sc.heading)}`);
350
+ try {
351
+ const result = await updatePlugins({
352
+ pluginsDir: sc.dir,
353
+ source,
354
+ all: values.all,
355
+ activate: true,
356
+ agentScope: sc.agentScope,
357
+ scope: { label: sc.label, globalDir: globalPluginsDir() },
358
+ });
359
+ printUpdateReport(result);
360
+ }
361
+ catch (err) {
362
+ console.error(`${ui.err("error:")} ${err instanceof Error ? err.message : String(err)}`);
363
+ }
364
+ }
365
+ return;
366
+ }
367
+ case "remove": {
368
+ const { values, positionals } = parseVerb(verb, cmd.flags, rest);
369
+ const name = positionals[0];
370
+ if (!name)
371
+ fail("plugins remove requires a <name>");
372
+ const sc = await resolveActionScope(values, "remove");
373
+ const res = removePlugin({
374
+ pluginsDir: sc.pluginsDir,
375
+ name,
376
+ force: values.force,
377
+ deactivate: true,
378
+ scope: sc.agentScope,
379
+ });
380
+ if (res.removedDir)
381
+ console.log(`${ui.ok("removed")} ${ui.name(res.name)} ${ui.meta(`-> ${res.removedDir}`)}`);
382
+ else
383
+ console.log(`${ui.ok("removed")} ${ui.name(res.name)} ${ui.meta("(no directory on disk)")}`);
384
+ for (const link of res.unlinked)
385
+ console.log(ui.meta(` unlinked: ${link}`));
386
+ for (const r of res.agents ?? []) {
387
+ const display = getAgent(r.agent)?.displayName ?? r.agent;
388
+ if (r.affected.length > 0)
389
+ console.log(ui.meta(` disabled in ${display}`));
390
+ // CLI absent → the plugin may still be enabled there; surface the precise
391
+ // repair so a store-deleted plugin can't silently linger in that agent.
392
+ else if (r.skipped) {
393
+ console.log(ui.warn(` ${r.agent} CLI not found — if enabled there, run \`adg plugins unlink --target ${r.agent} ${res.name}\``));
394
+ }
395
+ }
396
+ if (!res.removedFromLock && !res.removedDir) {
397
+ console.log(ui.warn(` ${res.name} was not recorded in the lock`));
398
+ }
399
+ return;
400
+ }
401
+ case "list": {
402
+ const { values } = parseVerb(verb, cmd.flags, rest);
403
+ const pluginsDir = resolveScopeDir(values);
404
+ const plugins = listPlugins(pluginsDir);
405
+ for (const line of renderPluginList(plugins, pluginsDir, { verbose: values.verbose })) {
406
+ console.log(line);
407
+ }
408
+ return;
409
+ }
410
+ case "status": {
411
+ const { values } = parseVerb(verb, cmd.flags, rest);
412
+ const targets = values.target !== undefined ? resolveTargets(values.target) : undefined;
413
+ const statuses = pluginStatus({ pluginsDir: resolveScopeDir(values), scope: scopeOf(values), targets });
414
+ for (const line of renderStatus(statuses))
415
+ console.log(line);
416
+ return;
417
+ }
418
+ case "migrate": {
419
+ const { values } = parseVerb(verb, cmd.flags, rest);
420
+ const sc = await resolveActionScope(values, "migrate");
421
+ const res = migrateLayout(sc.pluginsDir);
422
+ for (const m of res.moved)
423
+ console.log(`${ui.ok("moved")} ${ui.name(m.name)}: ${ui.meta(`${m.from} -> ${m.to}`)}`);
424
+ for (const m of res.missing)
425
+ console.error(ui.warn(` ! missing directory for locked plugin: ${m}`));
426
+ if (res.moved.length === 0)
427
+ console.log(ui.meta(`nothing to migrate (${res.unchanged.length} already in place)`));
428
+ return;
429
+ }
430
+ // A verb present in PLUGIN_COMMANDS but missing here (other than `marketplace`,
431
+ // routed before this point) is a wiring bug, not user error — fail loudly
432
+ // rather than silently no-op.
433
+ default:
434
+ fail(`unhandled plugins verb: ${verb}`);
435
+ }
436
+ }
437
+ async function runMarketplace(args) {
438
+ const [sub, ...rest] = args;
439
+ // `marketplace <sub> -h` → the marketplace help (it documents every sub + flags).
440
+ if (sub !== undefined && wantsHelp(rest)) {
441
+ console.log(MARKETPLACE_USAGE);
442
+ return;
443
+ }
444
+ switch (sub) {
445
+ case undefined:
446
+ case "-h":
447
+ case "--help":
448
+ case "help":
449
+ console.log(MARKETPLACE_USAGE);
450
+ return;
451
+ case "list": {
452
+ const { values } = parseVerb("marketplace", ["verbose", ...SCOPE], rest);
453
+ const dir = resolveScopeDir(values);
454
+ const groups = marketplaceList({ pluginsDir: dir });
455
+ // Verbose: drill each plugin down to its components (reuses `plugins list -v`).
456
+ const byName = values.verbose ? new Map(listPlugins(dir).map((p) => [p.name, p])) : undefined;
457
+ for (const line of renderMarketplaceList(groups, byName))
458
+ console.log(line);
459
+ return;
460
+ }
461
+ case "upgrade": {
462
+ // Deprecated: a thin alias for `adg plugins update`. It runs the exact same
463
+ // update path (re-fetch + refresh, with the richer changed/unchanged/deleted
464
+ // report) so there is no second implementation to drift.
465
+ console.error(ui.warn("note: `marketplace upgrade` is a deprecated alias for `adg plugins update`."));
466
+ const { values, positionals } = parseVerb("marketplace", ["all", "target", ...SCOPE], rest);
467
+ // Drive the exact same scope resolution + per-scope loop as `plugins update`
468
+ // (project/global/both, with the home==global trap guard) so the deprecated
469
+ // alias can't drift from the verb it aliases. `--target` narrows the runtimes.
470
+ const targets = values.target !== undefined ? resolveTargets(values.target) : undefined;
471
+ for (const sc of await resolveUpdateScopes(values)) {
472
+ if (sc.heading)
473
+ console.log(`${ui.name(sc.heading)}`);
474
+ // Mirror `plugins update`'s error handling: report a failed re-fetch and
475
+ // exit cleanly rather than throwing to the top-level catch.
476
+ try {
477
+ const result = await updatePlugins({
478
+ pluginsDir: sc.dir,
479
+ scope: { label: sc.label, globalDir: globalPluginsDir() },
480
+ activate: true,
481
+ agentScope: sc.agentScope,
482
+ source: positionals[0],
483
+ all: values.all,
484
+ targets,
485
+ });
486
+ printUpdateReport(result);
487
+ }
488
+ catch (err) {
489
+ console.error(`${ui.err("error:")} ${err instanceof Error ? err.message : String(err)}`);
490
+ }
491
+ }
492
+ return;
493
+ }
494
+ case "remove":
495
+ case "rm": {
496
+ const { values, positionals } = parseVerb("marketplace", ["force", ...SCOPE], rest);
497
+ const source = positionals[0];
498
+ if (!source)
499
+ fail("marketplace remove requires a <source>");
500
+ const sc = await resolveActionScope(values, "marketplace remove");
501
+ const res = marketplaceRemove({
502
+ pluginsDir: sc.pluginsDir,
503
+ scope: sc.info,
504
+ agentScope: sc.agentScope,
505
+ source,
506
+ force: values.force,
507
+ deactivate: true,
508
+ });
509
+ console.log(`${ui.ok("removed")} ${res.removed.length} plugin(s) from ${ui.name(res.source)}: ${res.removed.join(", ")}`);
510
+ return;
511
+ }
512
+ case "sync": {
513
+ const { values, positionals } = parseVerb("marketplace", ["target", ...SCOPE], rest);
514
+ const source = positionals[0];
515
+ if (!source)
516
+ fail("marketplace sync requires a <source>");
517
+ const targets = values.target === "all"
518
+ ? resolveTargets("all")
519
+ : [requireSingleTarget(values.target, "marketplace sync")];
520
+ const sc = await resolveActionScope(values, "marketplace sync");
521
+ for (const target of targets) {
522
+ const res = marketplaceSync({
523
+ pluginsDir: sc.pluginsDir,
524
+ scope: sc.info,
525
+ source,
526
+ target,
527
+ global: sc.global,
528
+ });
529
+ for (const a of res.actions) {
530
+ console.log(`${ui.ok("synced")} ${ui.name(a.name)} ${ui.meta(`[${res.target}]`)}${a.synced ? ui.meta(` -> ${res.target}`) : ""}`);
531
+ }
532
+ if (res.cliSkipped) {
533
+ console.log(ui.warn(`note: \`${target}\` CLI not found — manifests were regenerated, but nothing was re-synced in ${target}.`));
534
+ }
535
+ }
536
+ return;
537
+ }
538
+ default: {
539
+ console.error(`${ui.err("error:")} unknown marketplace subcommand: ${sub}\n`);
540
+ console.error(MARKETPLACE_USAGE);
541
+ process.exit(1);
542
+ }
543
+ }
544
+ }