@agentclientprotocol/claude-agent-acp 0.112.1-preview.1 → 0.112.1-preview.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.
Files changed (46) hide show
  1. package/README.md +1 -0
  2. package/dist/adapter-command.d.ts +56 -0
  3. package/dist/adapter-command.d.ts.map +1 -0
  4. package/dist/adapter-command.js +74 -0
  5. package/dist/claude-cli.d.ts +2 -0
  6. package/dist/claude-cli.d.ts.map +1 -1
  7. package/dist/claude-cli.js +5 -1
  8. package/dist/mcp-command.d.ts.map +1 -1
  9. package/dist/mcp-command.js +1 -14
  10. package/dist/plugin-command.d.ts +94 -0
  11. package/dist/plugin-command.d.ts.map +1 -0
  12. package/dist/plugin-command.js +633 -0
  13. package/dist/slash-commands.d.ts +1 -1
  14. package/dist/slash-commands.d.ts.map +1 -1
  15. package/dist/slash-commands.js +5 -12
  16. package/dist/usage-markdown.d.ts +4 -0
  17. package/dist/usage-markdown.d.ts.map +1 -1
  18. package/dist/usage-markdown.js +13 -0
  19. package/dist/v1/acp-agent.d.ts +16 -10
  20. package/dist/v1/acp-agent.d.ts.map +1 -1
  21. package/dist/v1/acp-agent.js +125 -77
  22. package/dist/v1/adapter-commands.d.ts +78 -0
  23. package/dist/v1/adapter-commands.d.ts.map +1 -0
  24. package/dist/v1/adapter-commands.js +124 -0
  25. package/dist/v1/remote-control.d.ts +10 -34
  26. package/dist/v1/remote-control.d.ts.map +1 -1
  27. package/dist/v1/remote-control.js +6 -26
  28. package/dist/v2/{remote-control.d.ts → adapter-commands.d.ts} +34 -17
  29. package/dist/v2/adapter-commands.d.ts.map +1 -0
  30. package/dist/v2/adapter-commands.js +121 -0
  31. package/dist/v2/agent.d.ts.map +1 -1
  32. package/dist/v2/agent.js +3 -2
  33. package/dist/v2/commands.d.ts +5 -4
  34. package/dist/v2/commands.d.ts.map +1 -1
  35. package/dist/v2/commands.js +4 -2
  36. package/dist/v2/session.d.ts +14 -8
  37. package/dist/v2/session.d.ts.map +1 -1
  38. package/dist/v2/session.js +68 -38
  39. package/dist/v2/subscription-guard.d.ts +2 -1
  40. package/dist/v2/subscription-guard.d.ts.map +1 -1
  41. package/dist/v2/tasks.d.ts +9 -2
  42. package/dist/v2/tasks.d.ts.map +1 -1
  43. package/dist/v2/tasks.js +80 -15
  44. package/package.json +1 -1
  45. package/dist/v2/remote-control.d.ts.map +0 -1
  46. package/dist/v2/remote-control.js +0 -97
@@ -0,0 +1,633 @@
1
+ /**
2
+ * `/plugin` (aliases `/plugins`, `/marketplace`), which the adapter serves
3
+ * itself. Claude Code's own `/plugin` is an interactive terminal screen and
4
+ * answers "/plugin isn't available in this environment." in a session without
5
+ * a terminal, which is every ACP session. The adapter instead runs the CLI's
6
+ * `claude plugin ...` commands, which have a `--json` form, and then reloads
7
+ * the live session so the new plugin's commands, skills and MCP servers appear.
8
+ *
9
+ * Plugins bring hooks and MCP servers that run as the user, so the set of
10
+ * commands and flags below is an allowlist, and it is the only guard. Anything
11
+ * outside it, such as `-y`, `--accept-command` or `--json`, gets the usage
12
+ * text and never reaches the CLI. Shared by the v1 core and the v2 core.
13
+ */
14
+ import { execFile } from "node:child_process";
15
+ import { codeSpan, escapeMarkdown } from "./usage-markdown.js";
16
+ export const PLUGIN_COMMAND_NAME = "plugin";
17
+ /** The `/plugin` entry of `available_commands_update`. */
18
+ export const PLUGIN_AVAILABLE_COMMAND = {
19
+ name: PLUGIN_COMMAND_NAME,
20
+ description: "Manage Claude Code plugins and marketplaces",
21
+ input: { hint: "[install|uninstall|enable|disable|update|list|marketplace …] …" },
22
+ };
23
+ const SCOPES = ["user", "project", "local"];
24
+ const SCOPE_FLAG = { names: ["-s", "--scope"], kind: "value", values: SCOPES };
25
+ /** Splits `tokens` into positionals and the flags of `specs`. Any other token
26
+ * that starts with `-` is an error, so no user text becomes a CLI option. */
27
+ function scan(tokens, specs) {
28
+ const positionals = [];
29
+ const flags = new Map();
30
+ for (let i = 0; i < tokens.length; i++) {
31
+ let token = tokens[i];
32
+ if (!token.startsWith("-")) {
33
+ positionals.push(token);
34
+ continue;
35
+ }
36
+ if (token === "-h" || token === "--help")
37
+ return { error: undefined };
38
+ let inline;
39
+ const equals = token.startsWith("--") ? token.indexOf("=") : -1;
40
+ if (equals > 0) {
41
+ inline = token.slice(equals + 1);
42
+ token = token.slice(0, equals);
43
+ if (inline.startsWith("-"))
44
+ return { error: `\`${token}\` needs a value.` };
45
+ }
46
+ const spec = specs.find((candidate) => candidate.names.includes(token));
47
+ if (!spec)
48
+ return { error: `\`${token}\` is not supported here.` };
49
+ const key = spec.names[0];
50
+ if (spec.kind === "bool") {
51
+ if (inline !== undefined)
52
+ return { error: `\`${token}\` takes no value.` };
53
+ flags.set(key, true);
54
+ continue;
55
+ }
56
+ const values = [];
57
+ if (inline !== undefined) {
58
+ values.push(inline);
59
+ }
60
+ else if (spec.kind === "variadic") {
61
+ while (i + 1 < tokens.length && !tokens[i + 1].startsWith("-"))
62
+ values.push(tokens[++i]);
63
+ }
64
+ else if (i + 1 < tokens.length && !tokens[i + 1].startsWith("-")) {
65
+ values.push(tokens[++i]);
66
+ }
67
+ if (values.length === 0 || values.some((value) => value === "")) {
68
+ return { error: `\`${token}\` needs a value.` };
69
+ }
70
+ if (spec.values && !values.every((value) => spec.values.includes(value))) {
71
+ return { error: `\`${token}\` takes one of ${spec.values.join(", ")}.` };
72
+ }
73
+ const previous = flags.get(key);
74
+ if (previous !== undefined && spec.kind !== "list" && spec.kind !== "variadic") {
75
+ return { error: `\`${token}\` is given twice.` };
76
+ }
77
+ flags.set(key, [...(Array.isArray(previous) ? previous : []), ...values]);
78
+ }
79
+ return { positionals, flags };
80
+ }
81
+ function flagArgs(scanned, specs) {
82
+ const args = [];
83
+ for (const spec of specs) {
84
+ const key = spec.names[0];
85
+ const value = scanned.flags.get(key);
86
+ if (value === undefined)
87
+ continue;
88
+ const flag = spec.names.find((name) => name.startsWith("--")) ?? key;
89
+ if (value === true)
90
+ args.push(flag);
91
+ else if (spec.kind === "list")
92
+ for (const item of value)
93
+ args.push(flag, item);
94
+ else
95
+ args.push(flag, ...value);
96
+ }
97
+ return args;
98
+ }
99
+ const USAGE_PLUGIN_ARGUMENT = "Give a plugin name, as `name` or `name@marketplace`.";
100
+ /** Parses the arguments of a CLI subcommand into a `cli` command. */
101
+ function parseSubcommand(operation, words, specs, prefix, options) {
102
+ const scanned = scan(words, specs);
103
+ if ("error" in scanned)
104
+ return { kind: "usage", reason: scanned.error };
105
+ const max = options.positional === "none" ? 0 : 1;
106
+ if (scanned.positionals.length > max) {
107
+ return { kind: "usage", reason: `Unexpected argument \`${scanned.positionals[max]}\`.` };
108
+ }
109
+ if (options.positional === "one" && scanned.positionals.length === 0) {
110
+ return { kind: "usage", reason: options.missing };
111
+ }
112
+ const target = scanned.positionals[0];
113
+ return {
114
+ kind: "cli",
115
+ operation,
116
+ argv: [...prefix, ...scanned.positionals, ...flagArgs(scanned, specs)],
117
+ ...(target === undefined ? {} : { target }),
118
+ };
119
+ }
120
+ const LIST_FLAGS = [{ names: ["--available"], kind: "bool" }];
121
+ const INSTALL_FLAGS = [
122
+ SCOPE_FLAG,
123
+ { names: ["--marketplace"], kind: "value" },
124
+ { names: ["--config"], kind: "list" },
125
+ ];
126
+ const UNINSTALL_FLAGS = [SCOPE_FLAG, { names: ["--keep-data"], kind: "bool" }];
127
+ const ENABLE_FLAGS = [SCOPE_FLAG];
128
+ const DISABLE_FLAGS = [SCOPE_FLAG, { names: ["-a", "--all"], kind: "bool" }];
129
+ const MARKETPLACE_ADD_FLAGS = [SCOPE_FLAG, { names: ["--sparse"], kind: "variadic" }];
130
+ function parseMarketplace(words) {
131
+ const [sub, ...rest] = words;
132
+ switch (sub) {
133
+ case "add":
134
+ return parseSubcommand("marketplace-add", rest, MARKETPLACE_ADD_FLAGS, ["marketplace", "add"], {
135
+ positional: "one",
136
+ missing: "Give a marketplace source: a GitHub `owner/repo`, a git URL, or a path.",
137
+ });
138
+ case "list":
139
+ case "ls":
140
+ return parseSubcommand("marketplace-list", rest, [], ["marketplace", "list"], {
141
+ positional: "none",
142
+ });
143
+ case "remove":
144
+ case "rm":
145
+ return parseSubcommand("marketplace-remove", rest, [SCOPE_FLAG], ["marketplace", "remove"], {
146
+ positional: "one",
147
+ missing: "Give the name of the marketplace to remove.",
148
+ });
149
+ case "update":
150
+ return parseSubcommand("marketplace-update", rest, [], ["marketplace", "update"], {
151
+ positional: "optional",
152
+ });
153
+ default:
154
+ return { kind: "usage" };
155
+ }
156
+ }
157
+ /**
158
+ * Parses `/plugin ...` (also `/plugins ...` and `/marketplace ...`, which are
159
+ * aliases: `/marketplace marketplace add x` is `/plugin marketplace add x`,
160
+ * and `/marketplace add x` is usage, like `/plugin add x`) from a single-text
161
+ * prompt. `null` for any other prompt, which goes to Claude Code.
162
+ */
163
+ export function parsePluginCommand(prompt) {
164
+ const [first] = prompt;
165
+ if (prompt.length !== 1 || first?.type !== "text" || typeof first.text !== "string")
166
+ return null;
167
+ // Check the first word before splitting, so a long prompt is not split into words.
168
+ const text = first.text.trim();
169
+ if (!/^\/(?:plugins?|marketplace)(?:\s|$)/.test(text))
170
+ return null;
171
+ const [, ...words] = text.split(/\s+/);
172
+ const [sub, ...rest] = words;
173
+ switch (sub) {
174
+ case undefined:
175
+ case "help":
176
+ return { kind: "overview" };
177
+ case "list":
178
+ case "ls":
179
+ return parseSubcommand("list", rest, LIST_FLAGS, ["list"], { positional: "none" });
180
+ case "install":
181
+ case "i":
182
+ return parseSubcommand("install", rest, INSTALL_FLAGS, ["install"], {
183
+ positional: "one",
184
+ missing: USAGE_PLUGIN_ARGUMENT,
185
+ });
186
+ case "uninstall":
187
+ case "remove":
188
+ case "rm":
189
+ return parseSubcommand("uninstall", rest, UNINSTALL_FLAGS, ["uninstall"], {
190
+ positional: "one",
191
+ missing: USAGE_PLUGIN_ARGUMENT,
192
+ });
193
+ case "enable":
194
+ return parseSubcommand("enable", rest, ENABLE_FLAGS, ["enable"], {
195
+ positional: "one",
196
+ missing: USAGE_PLUGIN_ARGUMENT,
197
+ });
198
+ case "disable": {
199
+ const command = parseSubcommand("disable", rest, DISABLE_FLAGS, ["disable"], {
200
+ positional: "optional",
201
+ });
202
+ if (command.kind !== "cli")
203
+ return command;
204
+ const all = command.argv.includes("--all");
205
+ if (all === (command.target !== undefined)) {
206
+ return {
207
+ kind: "usage",
208
+ reason: all
209
+ ? "Give either a plugin name or `--all`, not both."
210
+ : `${USAGE_PLUGIN_ARGUMENT} Or use \`--all\` to disable every plugin.`,
211
+ };
212
+ }
213
+ return command;
214
+ }
215
+ case "update":
216
+ return parseSubcommand("update", rest, [SCOPE_FLAG], ["update"], {
217
+ positional: "one",
218
+ missing: USAGE_PLUGIN_ARGUMENT,
219
+ });
220
+ case "marketplace":
221
+ case "market":
222
+ return parseMarketplace(rest);
223
+ default:
224
+ return { kind: "usage", reason: `Unknown subcommand \`${sub}\`.` };
225
+ }
226
+ }
227
+ /** The time that one CLI run can take. A git clone of a marketplace is the slow case. */
228
+ const PLUGIN_CLI_TIMEOUT_MS = 5 * 60_000;
229
+ const MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
230
+ const defaultExec = (file, args, options) => new Promise((resolve, reject) => {
231
+ const child = execFile(file, args, {
232
+ cwd: options.cwd,
233
+ env: options.env,
234
+ signal: options.signal,
235
+ timeout: options.timeoutMs,
236
+ maxBuffer: MAX_OUTPUT_BYTES,
237
+ encoding: "utf8",
238
+ }, (error, stdout, stderr) => {
239
+ if (!error)
240
+ return resolve({ stdout, stderr, code: 0 });
241
+ if (typeof error.code === "number")
242
+ return resolve({ stdout, stderr, code: error.code });
243
+ if (error.killed && !options.signal.aborted) {
244
+ return reject(new Error(`Timed out after ${options.timeoutMs / 60_000} minutes.`));
245
+ }
246
+ reject(error);
247
+ });
248
+ // The CLI must not wait on a terminal that does not exist.
249
+ child.stdin?.end();
250
+ });
251
+ /** The operations after which the live session reloads its plugins. */
252
+ const RELOADING_OPERATIONS = new Set([
253
+ "install",
254
+ "uninstall",
255
+ "enable",
256
+ "disable",
257
+ "update",
258
+ "marketplace-remove",
259
+ ]);
260
+ function isRecord(value) {
261
+ return typeof value === "object" && value !== null && !Array.isArray(value);
262
+ }
263
+ /** The result line of a `--json` run: the last non-empty line of stdout. The
264
+ * CLI can print human-readable lines before it. */
265
+ function lastJsonLine(stdout) {
266
+ const lines = stdout.split(/\r?\n/).filter((line) => line.trim() !== "");
267
+ const last = lines[lines.length - 1];
268
+ if (last === undefined)
269
+ return undefined;
270
+ try {
271
+ const parsed = JSON.parse(last);
272
+ return isRecord(parsed) ? parsed : undefined;
273
+ }
274
+ catch {
275
+ return undefined;
276
+ }
277
+ }
278
+ /** The whole of stdout as JSON: a list prints an indented array or object. */
279
+ function wholeJson(stdout) {
280
+ try {
281
+ return JSON.parse(stdout.trim());
282
+ }
283
+ catch {
284
+ return undefined;
285
+ }
286
+ }
287
+ const MAX_TEXT_LENGTH = 1500;
288
+ function plainText(text) {
289
+ // eslint-disable-next-line no-control-regex
290
+ const stripped = text.replace(/\u001b\[[0-9;]*[A-Za-z]/g, "").trim();
291
+ return stripped.length > MAX_TEXT_LENGTH ? `${stripped.slice(0, MAX_TEXT_LENGTH)}…` : stripped;
292
+ }
293
+ function isJsonOptionUnknown(run) {
294
+ return /unknown option.*--json/i.test(`${run.stderr}\n${run.stdout}`);
295
+ }
296
+ /** Whether the CLI takes `--json` for the command: `marketplace update` without a name does not. */
297
+ function takesJson(command) {
298
+ return !(command.operation === "marketplace-update" && command.target === undefined);
299
+ }
300
+ async function runCli(deps, exec, env, argv, json) {
301
+ if (deps.signal.aborted)
302
+ return { type: "cancelled" };
303
+ const run = async (args) => {
304
+ try {
305
+ const file = await deps.cliPath();
306
+ const output = await exec(file, args, {
307
+ cwd: deps.cwd,
308
+ env,
309
+ signal: deps.signal,
310
+ timeoutMs: PLUGIN_CLI_TIMEOUT_MS,
311
+ });
312
+ return { type: "done", ...output };
313
+ }
314
+ catch (error) {
315
+ if (deps.signal.aborted)
316
+ return { type: "cancelled" };
317
+ const message = error instanceof Error ? error.message : String(error);
318
+ deps.logError(`Failed to run \`claude plugin ${argv.join(" ")}\`: ${message}`);
319
+ return { type: "error", message: `Could not run the Claude CLI: ${message}` };
320
+ }
321
+ };
322
+ const first = await run(["plugin", ...argv, ...(json ? ["--json"] : [])]);
323
+ // A CLI named by CLAUDE_CODE_EXECUTABLE can predate `--json`. It rejects the
324
+ // flag before doing anything, so the run is repeated for its text and exit code.
325
+ if (json && first.type === "done" && first.code !== 0 && isJsonOptionUnknown(first)) {
326
+ return run(["plugin", ...argv]);
327
+ }
328
+ return first;
329
+ }
330
+ function cancelled(operation) {
331
+ return { ok: false, operation, message: "Cancelled." };
332
+ }
333
+ function failedToRun(operation, run) {
334
+ return run.type === "cancelled"
335
+ ? cancelled(operation)
336
+ : { ok: false, operation, message: run.type === "error" ? run.message : "" };
337
+ }
338
+ function describeCliRun(command, run) {
339
+ const { operation } = command;
340
+ const isList = operation === "list" || operation === "marketplace-list";
341
+ const json = lastJsonLine(run.stdout);
342
+ if (isList) {
343
+ const data = wholeJson(run.stdout);
344
+ if (run.code === 0 && data !== undefined && typeof data === "object" && data !== null) {
345
+ return { ok: true, operation, message: "", data };
346
+ }
347
+ }
348
+ if (!json || typeof json.outcome !== "string") {
349
+ const text = plainText(run.code === 0 ? run.stdout || run.stderr : run.stderr || run.stdout);
350
+ return {
351
+ ok: run.code === 0,
352
+ operation,
353
+ message: text || (run.code === 0 ? "Done." : `The Claude CLI exited with code ${run.code}.`),
354
+ };
355
+ }
356
+ const message = typeof json.message === "string" && json.message.trim() !== ""
357
+ ? plainText(json.message)
358
+ : run.code === 0
359
+ ? "Done."
360
+ : `The Claude CLI exited with code ${run.code}.`;
361
+ const ok = json.alreadyInGoalState === true || (json.outcome !== "failed" && run.code === 0);
362
+ const result = { ok, operation, message };
363
+ if (!ok && typeof json.failureCode === "string")
364
+ result.failureCode = json.failureCode;
365
+ if (!ok && isRecord(json.shownCommand) && typeof json.shownCommand.command === "string") {
366
+ result.shownCommand = json.shownCommand.command;
367
+ if (operation === "install" || operation === "update") {
368
+ result.terminalCommand = `claude plugin ${command.argv.map(shellQuote).join(" ")}`;
369
+ }
370
+ }
371
+ return result;
372
+ }
373
+ // terminalCommand is pasted into a POSIX shell, and argv values are arbitrary
374
+ // text: `&` would background, `*` glob and `$(x)` expand unless quoted.
375
+ function shellQuote(arg) {
376
+ return /^[A-Za-z0-9@%+=:,./_-]+$/.test(arg) ? arg : `'${arg.replaceAll("'", "'\\''")}'`;
377
+ }
378
+ async function reloadSession(deps) {
379
+ const query = deps.query();
380
+ if (!query)
381
+ return { status: "unavailable" };
382
+ try {
383
+ const response = await query.reloadPlugins({ refuseIfBusy: true });
384
+ return { status: "applied", plugins: response.plugins.map((plugin) => plugin.name) };
385
+ }
386
+ catch (error) {
387
+ if (error?.errorCode === "reload_plugins_busy") {
388
+ return { status: "busy" };
389
+ }
390
+ const message = error instanceof Error ? error.message : String(error);
391
+ deps.logError(`Failed to reload plugins after /plugin: ${message}`);
392
+ return { status: "failed", error: message };
393
+ }
394
+ }
395
+ /** Whether `plugin` (`name` or `name@marketplace`) is among the installed plugin ids. */
396
+ function isInstalled(installed, plugin) {
397
+ return installed.some((entry) => {
398
+ const id = isRecord(entry) ? entry.id : undefined;
399
+ if (typeof id !== "string")
400
+ return false;
401
+ return plugin.includes("@") ? id === plugin : id.split("@")[0] === plugin;
402
+ });
403
+ }
404
+ /**
405
+ * Runs a parsed `/plugin` command and, after a change, reloads the session's
406
+ * plugins. A failure is in the result: this never throws.
407
+ */
408
+ export async function runPluginCommand(command, deps) {
409
+ if (command.kind === "usage") {
410
+ return {
411
+ ok: false,
412
+ operation: "usage",
413
+ message: command.reason ?? "",
414
+ };
415
+ }
416
+ const exec = deps.exec ?? defaultExec;
417
+ const env = { ...deps.env };
418
+ delete env.CLAUDECODE;
419
+ delete env.CLAUDE_CODE_CHILD_SESSION;
420
+ if (command.kind === "overview") {
421
+ const [plugins, marketplaces] = await Promise.all([
422
+ runCli(deps, exec, env, ["list"], true),
423
+ runCli(deps, exec, env, ["marketplace", "list"], true),
424
+ ]);
425
+ if (plugins.type === "cancelled" || marketplaces.type === "cancelled") {
426
+ return cancelled("overview");
427
+ }
428
+ const read = (run) => {
429
+ if (run.type === "error")
430
+ return { error: run.message };
431
+ if (run.type === "done" && run.code === 0) {
432
+ const value = wholeJson(run.stdout);
433
+ return Array.isArray(value)
434
+ ? { value }
435
+ : { error: "The Claude CLI did not return a list." };
436
+ }
437
+ const text = run.type === "done" ? plainText(run.stderr || run.stdout) : "";
438
+ return {
439
+ error: text || `The Claude CLI exited with code ${run.type === "done" ? run.code : "?"}.`,
440
+ };
441
+ };
442
+ const listed = { plugins: read(plugins), marketplaces: read(marketplaces) };
443
+ const errors = [listed.plugins.error, listed.marketplaces.error].filter((e) => e !== undefined);
444
+ return {
445
+ ok: errors.length === 0,
446
+ operation: "overview",
447
+ message: errors.join("\n"),
448
+ data: {
449
+ plugins: listed.plugins.value,
450
+ marketplaces: listed.marketplaces.value,
451
+ pluginsError: listed.plugins.error,
452
+ marketplacesError: listed.marketplaces.error,
453
+ },
454
+ };
455
+ }
456
+ const { operation } = command;
457
+ if (operation === "enable" && command.target !== undefined) {
458
+ const listing = await runCli(deps, exec, env, ["list"], true);
459
+ if (listing.type === "cancelled")
460
+ return cancelled(operation);
461
+ // When the list cannot be read (an old CLI), the enable runs as typed.
462
+ const installed = listing.type === "done" && listing.code === 0 ? wholeJson(listing.stdout) : undefined;
463
+ if (Array.isArray(installed) && !isInstalled(installed, command.target)) {
464
+ return {
465
+ ok: false,
466
+ operation,
467
+ message: `Plugin ${command.target} is not installed, so it can't be enabled. Install it first.`,
468
+ failureCode: "not_installed",
469
+ };
470
+ }
471
+ }
472
+ const run = await runCli(deps, exec, env, command.argv, takesJson(command));
473
+ if (run.type !== "done")
474
+ return failedToRun(operation, run);
475
+ const result = describeCliRun(command, run);
476
+ if (result.ok && RELOADING_OPERATIONS.has(operation)) {
477
+ if (deps.signal.aborted)
478
+ return cancelled(operation);
479
+ result.reload = await reloadSession(deps);
480
+ }
481
+ return result;
482
+ }
483
+ const USAGE_LINES = [
484
+ "- `/plugin list [--available]`",
485
+ "- `/plugin install <plugin>[@marketplace] [--scope user|project|local] [--marketplace <source>] [--config key=value]`",
486
+ "- `/plugin uninstall <plugin> [--scope …] [--keep-data]`",
487
+ "- `/plugin enable <plugin> [--scope …]`",
488
+ "- `/plugin disable <plugin>|--all [--scope …]`",
489
+ "- `/plugin update <plugin> [--scope …]`",
490
+ "- `/plugin marketplace add <source> [--scope …] [--sparse <path>…]`",
491
+ "- `/plugin marketplace list`",
492
+ "- `/plugin marketplace remove <name> [--scope …]`",
493
+ "- `/plugin marketplace update [<name>]`",
494
+ ];
495
+ function usageMarkdown() {
496
+ return ["**Usage**", "", ...USAGE_LINES].join("\n");
497
+ }
498
+ /** Escapes CLI or plugin text. A `claude plugin X` hint in backticks becomes
499
+ * the `/plugin X` that works in this chat. */
500
+ function renderCliText(text) {
501
+ return text
502
+ .split(/\r?\n/)
503
+ .filter((line) => line.trim() !== "")
504
+ .map((line) => line
505
+ .split(/(`[^`\n]+`)/)
506
+ .map((part, index) => {
507
+ if (index % 2 === 0)
508
+ return escapeMarkdown(part);
509
+ const code = part.slice(1, -1).replace(/^claude plugins? /, "/plugin ");
510
+ return codeSpan(code);
511
+ })
512
+ .join(""))
513
+ .join("\n\n");
514
+ }
515
+ function str(value) {
516
+ return typeof value === "string" && value !== "" ? value : undefined;
517
+ }
518
+ function installedLine(entry) {
519
+ if (!isRecord(entry))
520
+ return undefined;
521
+ const id = str(entry.id);
522
+ if (!id)
523
+ return undefined;
524
+ const details = [
525
+ str(entry.version) && `v${str(entry.version)}`,
526
+ str(entry.scope) && `${str(entry.scope)} scope`,
527
+ entry.enabled === false ? "disabled" : "enabled",
528
+ ].filter((part) => typeof part === "string");
529
+ return `- ${codeSpan(id)} — ${escapeMarkdown(details.join(", "))}`;
530
+ }
531
+ function availableLine(entry) {
532
+ if (!isRecord(entry))
533
+ return undefined;
534
+ const id = str(entry.pluginId) ?? str(entry.name);
535
+ if (!id)
536
+ return undefined;
537
+ const description = str(entry.description);
538
+ return `- ${codeSpan(id)}${description ? ` — ${escapeMarkdown(description)}` : ""}`;
539
+ }
540
+ function marketplaceLine(entry) {
541
+ if (!isRecord(entry))
542
+ return undefined;
543
+ const name = str(entry.name);
544
+ if (!name)
545
+ return undefined;
546
+ const source = str(entry.repo) ?? str(entry.url) ?? str(entry.path) ?? str(entry.source);
547
+ return `- ${codeSpan(name)}${source ? ` — ${escapeMarkdown(source)}` : ""}`;
548
+ }
549
+ /** The most available plugins that a reply lists. The official directory has hundreds. */
550
+ const MAX_AVAILABLE_LISTED = 40;
551
+ function section(title, lines, empty) {
552
+ const shown = lines.filter((line) => line !== undefined);
553
+ return shown.length === 0 ? `**${title}**\n\n${empty}` : `**${title}**\n\n${shown.join("\n")}`;
554
+ }
555
+ function installedSection(data) {
556
+ return section("Installed plugins", Array.isArray(data) ? data.map(installedLine) : [], "None. Run `/plugin install <plugin>` to add one.");
557
+ }
558
+ function marketplacesSection(data) {
559
+ return section("Marketplaces", Array.isArray(data) ? data.map(marketplaceLine) : [], "None. Run `/plugin marketplace add <source>` to add one.");
560
+ }
561
+ function availableSection(entries) {
562
+ const lines = entries.map(availableLine).filter((line) => line !== undefined);
563
+ const more = lines.length - MAX_AVAILABLE_LISTED;
564
+ if (more > 0)
565
+ lines.splice(MAX_AVAILABLE_LISTED, more, `- … and ${more} more`);
566
+ return section("Available plugins", lines, "None.");
567
+ }
568
+ function reloadLine(reload) {
569
+ if (reload.status === "applied") {
570
+ const plugins = reload.plugins ?? [];
571
+ return plugins.length === 0
572
+ ? "Reloaded: the session now has no plugins."
573
+ : `Reloaded: the session now has ${plugins.map(codeSpan).join(", ")}.`;
574
+ }
575
+ if (reload.status === "busy") {
576
+ return "The session is busy, so the change was not loaded into it. It applies to new sessions.";
577
+ }
578
+ if (reload.status === "failed") {
579
+ return `Reloading the session's plugins failed${reload.error ? `: ${escapeMarkdown(reload.error)}` : ""}. The change applies to new sessions.`;
580
+ }
581
+ return "The change applies to new sessions.";
582
+ }
583
+ /** The chat reply for a result of {@link runPluginCommand}. */
584
+ export function pluginCommandMarkdown(result) {
585
+ const blocks = [];
586
+ const data = result.data;
587
+ switch (result.operation) {
588
+ case "usage":
589
+ if (result.message)
590
+ blocks.push(renderCliText(result.message));
591
+ blocks.push(usageMarkdown());
592
+ return blocks.join("\n\n");
593
+ case "overview": {
594
+ const parts = isRecord(data) ? data : {};
595
+ const failure = (title, error) => `**${title}**\n\nCould not list: ${renderCliText(String(error))}`;
596
+ return [
597
+ typeof parts.pluginsError === "string"
598
+ ? failure("Installed plugins", parts.pluginsError)
599
+ : installedSection(parts.plugins),
600
+ typeof parts.marketplacesError === "string"
601
+ ? failure("Marketplaces", parts.marketplacesError)
602
+ : marketplacesSection(parts.marketplaces),
603
+ usageMarkdown(),
604
+ ].join("\n\n");
605
+ }
606
+ case "list":
607
+ if (result.ok && isRecord(data)) {
608
+ blocks.push(installedSection(data.installed));
609
+ blocks.push(availableSection(Array.isArray(data.available) ? data.available : []));
610
+ }
611
+ else if (result.ok && data !== undefined) {
612
+ blocks.push(installedSection(data));
613
+ }
614
+ break;
615
+ case "marketplace-list":
616
+ if (result.ok && data !== undefined)
617
+ blocks.push(marketplacesSection(data));
618
+ break;
619
+ default:
620
+ break;
621
+ }
622
+ if (blocks.length === 0 && result.message)
623
+ blocks.push(renderCliText(result.message));
624
+ if (result.shownCommand !== undefined) {
625
+ blocks.push(`The marketplace declares that this plugin is installed by running a command. The adapter does not run it:\n\n${codeSpan(result.shownCommand)}`);
626
+ if (result.terminalCommand) {
627
+ blocks.push(`To confirm that command, run ${codeSpan(result.terminalCommand)} in a terminal.`);
628
+ }
629
+ }
630
+ if (result.reload)
631
+ blocks.push(reloadLine(result.reload));
632
+ return blocks.join("\n\n");
633
+ }
@@ -6,5 +6,5 @@ import type { AvailableCommand } from "@agentclientprotocol/sdk/unstable";
6
6
  import type { Query, SlashCommand } from "@anthropic-ai/claude-agent-sdk";
7
7
  export declare function getAvailableSlashCommands(commands: SlashCommand[], terminalCommands?: readonly string[], airSkillCwd?: string, skillPaths?: Map<string, string | undefined>, query?: Query, skillFiles?: ReadonlyMap<string, {
8
8
  path?: string;
9
- }>): AvailableCommand[];
9
+ }>, remoteSession?: boolean): AvailableCommand[];
10
10
  //# sourceMappingURL=slash-commands.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"slash-commands.d.ts","sourceRoot":"","sources":["../src/slash-commands.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AAC1E,OAAO,KAAK,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAU1E,wBAAgB,yBAAyB,CACvC,QAAQ,EAAE,YAAY,EAAE,EAIxB,gBAAgB,CAAC,EAAE,SAAS,MAAM,EAAE,EAGpC,WAAW,CAAC,EAAE,MAAM,EAEpB,UAAU,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,EAC5C,KAAK,CAAC,EAAE,KAAK,EAIb,UAAU,CAAC,EAAE,WAAW,CAAC,MAAM,EAAE;IAAE,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,GAClD,gBAAgB,EAAE,CA4FpB"}
1
+ {"version":3,"file":"slash-commands.d.ts","sourceRoot":"","sources":["../src/slash-commands.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AAC1E,OAAO,KAAK,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAM1E,wBAAgB,yBAAyB,CACvC,QAAQ,EAAE,YAAY,EAAE,EAIxB,gBAAgB,CAAC,EAAE,SAAS,MAAM,EAAE,EAGpC,WAAW,CAAC,EAAE,MAAM,EAEpB,UAAU,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,EAC5C,KAAK,CAAC,EAAE,KAAK,EAIb,UAAU,CAAC,EAAE,WAAW,CAAC,MAAM,EAAE;IAAE,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,EAEnD,aAAa,UAAQ,GACpB,gBAAgB,EAAE,CA8EpB"}