فهرست منبع

feat: advertise installed skills in ACP command menus

hetaoBackend 2 ماه پیش
والد
کامیت
5aef2fa1a3

+ 15 - 0
docs/tui-capabilities.md

@@ -21,6 +21,21 @@ The evidence column summarizes the historical TUI 0.3.11 restoration record from
 | Files, shell, subagents, sessions, headless, ACP | Actual runtime retained | BYOK, file reads, session resume, ACP, sandbox, and status protocol tests |
 | Built-in skills, MCP, plugin tools | Original TUI assets and activation conditions retained | Asset build, plugin, and MCP tests; no claim that every skill has passed a real task |
 
+## ACP Skill commands
+
+ACP clients receive enabled Skills alongside built-in slash commands when a session
+is created, loaded, resumed, or forked. Discovery uses the session's Agent and
+workspace, including installed plugin Skills. Command names come from the runtime
+Skill roster (for example, `/review` or `/plugin:review`), not the installation
+package name. Select a command and append instructions to invoke it through the
+normal Agent turn. `/skills [filter]` lists the session's available Skills.
+
+Built-in command names take priority over conflicting Skill names. Disabled,
+duplicate, and invalid command names are omitted. If Skill discovery fails,
+built-in commands remain available. Reopen the session after installing or enabling
+Skills to refresh its command menu. Protocol tests cover command discovery and
+prompt forwarding; this does not establish live Zed or model acceptance.
+
 ## Desktop boundary
 
 Background workspace indexing is removed from this distribution. Runtime startup and conversation turns do not collect workspace snapshots, create workspace ZIP archives, or upload/retry them for cloud indexing. The semantic workspace search tool and its enablement policy are also removed; a saved indexing preference cannot reactivate them. Existing indexing records are left inert. User-directed file reading, search, and Git operations remain available.

+ 42 - 19
packages/tui/src/acp/agent.ts

@@ -19,7 +19,7 @@ import type {
 import { buildTuiMessageParts } from '../runtime/stream-events.js';
 import type { TuiMessage, TuiStreamEvent } from '../runtime/stream-events.js';
 import type { TuiAcpRuntime } from './runtime.js';
-import { executeTuiAcpCommand, TUI_ACP_AVAILABLE_COMMANDS } from './commands.js';
+import { availableSkillCommands, executeTuiAcpCommand, TUI_ACP_AVAILABLE_COMMANDS } from './commands.js';
 import {
   ACP_CONFIG_MODEL,
   ACP_CONFIG_PERMISSION_MODE,
@@ -102,6 +102,46 @@ export function createTuiAcpAgent(options: CreateTuiAcpAgentOptions): acp.AgentA
   let permissionBroadcastRunning = false;
   const app = acp.agent({ name: 'minimax-code' });
 
+  const advertiseAvailableCommands = (client: acp.AgentContext, sessionId: string): void => {
+    const attachment = sessions.get(sessionId);
+    if (!attachment) return;
+    let commands: acp.AvailableCommand[] = [...TUI_ACP_AVAILABLE_COMMANDS];
+    const isCurrent = () =>
+      sessions.get(sessionId) === attachment && !attachment.attachmentController.signal.aborted;
+    const notify = () => {
+      if (!isCurrent()) return;
+      void client
+        .notify(acp.methods.client.session.update, {
+          sessionId,
+          update: {
+            sessionUpdate: 'available_commands_update',
+            availableCommands: commands,
+          },
+        })
+        .catch(() => undefined);
+    };
+
+    // Preserve immediate native command discovery even if Skill discovery fails or stalls.
+    setImmediate(() => {
+      if (!isCurrent()) return;
+      notify();
+      void (async () => {
+        const skills = await options.runtime.listSkills(
+          attachment.session.agentName,
+          undefined,
+          attachment.session.workspaceDir,
+        );
+        if (!isCurrent()) return;
+        commands = [...TUI_ACP_AVAILABLE_COMMANDS, ...availableSkillCommands(skills)];
+        notify();
+      })().catch(() => undefined);
+    });
+    // Some clients attach their notification listener after receiving the Session response.
+    // Retry the latest roster, so a late native-only update cannot erase discovered Skills.
+    const retry = setTimeout(notify, AVAILABLE_COMMANDS_RETRY_DELAY_MS);
+    retry.unref();
+  };
+
   const schedulePermissionBroadcast = (
     client: acp.AgentContext,
     attachments: readonly (readonly [string, AcpSession])[],
@@ -1051,6 +1091,7 @@ export function createTuiAcpAgent(options: CreateTuiAcpAgentOptions): acp.AgentA
         runtime: options.runtime,
         sessionId: active.session.sessionId,
         agentName: active.session.agentName,
+        workspaceDir: active.session.workspaceDir,
         prompt: context.params.prompt,
       });
       if (isCancelled()) return { cancelled: true as const };
@@ -1807,24 +1848,6 @@ function mapClientMcpServers(servers: readonly acp.McpServer[]): readonly TuiSes
   });
 }
 
-function advertiseAvailableCommands(client: acp.AgentContext, sessionId: string): void {
-  const notify = () => {
-    void client
-      .notify(acp.methods.client.session.update, {
-        sessionId,
-        update: {
-          sessionUpdate: 'available_commands_update',
-          availableCommands: [...TUI_ACP_AVAILABLE_COMMANDS],
-        },
-      })
-      .catch(() => undefined);
-  };
-
-  setImmediate(notify);
-  const retry = setTimeout(notify, AVAILABLE_COMMANDS_RETRY_DELAY_MS);
-  retry.unref();
-}
-
 interface KeyedSerialExecutor {
   <T>(key: string, task: (signal: AbortSignal) => Promise<T>): Promise<T>;
   reserved<T>(key: string, task: (signal: AbortSignal) => Promise<T>): Promise<T>;

+ 36 - 2
packages/tui/src/acp/commands.ts

@@ -1,7 +1,8 @@
 import * as acp from '@agentclientprotocol/sdk';
 
 import { TUI_COMMAND_DESCRIPTORS } from '../application/command-descriptors.js';
-import type { TuiModel } from '../runtime/port.js';
+import { sanitizeTerminalText } from '../tui/rendering/terminal-text.js';
+import type { TuiModel, TuiSkillList } from '../runtime/port.js';
 import type { TuiAcpRuntime } from './runtime.js';
 
 export const TUI_ACP_AVAILABLE_COMMANDS = [
@@ -41,6 +42,34 @@ export const TUI_ACP_AVAILABLE_COMMANDS = [
   },
 ] satisfies readonly acp.AvailableCommand[];
 
+/** Keep native commands authoritative and expose only invocable Skill names. */
+export function availableSkillCommands(result: TuiSkillList): acp.AvailableCommand[] {
+  const seen = new Set<string>(TUI_ACP_AVAILABLE_COMMANDS.map((command) => command.name));
+  return (result.skills ?? [])
+    .flatMap((skill): acp.AvailableCommand[] => {
+      const name = skill.name.trim().toLowerCase();
+      if (
+        skill.enabled === false ||
+        seen.has(name) ||
+        name.length > 128 ||
+        !/^[a-z0-9][a-z0-9._-]*(?::[a-z0-9][a-z0-9._-]*)?$/u.test(name)
+      )
+        return [];
+      seen.add(name);
+      const description = sanitizeTerminalText(
+        skill.displayDescription ?? skill.description ?? '',
+      ).trim();
+      return [
+        {
+          name,
+          description: description ? `[Skill] ${description}` : '[Skill]',
+          input: { hint: '[instructions]' },
+        },
+      ];
+    })
+    .sort((left, right) => left.name.localeCompare(right.name));
+}
+
 export type TuiAcpCommandResult =
   | { readonly handled: false }
   | {
@@ -63,6 +92,7 @@ export async function executeTuiAcpCommand(options: {
   >;
   readonly sessionId: string;
   readonly agentName?: string;
+  readonly workspaceDir?: string;
   readonly prompt: readonly acp.ContentBlock[];
 }): Promise<TuiAcpCommandResult> {
   const command = parseCommand(options.prompt);
@@ -112,7 +142,11 @@ export async function executeTuiAcpCommand(options: {
     return {
       handled: true,
       output: formatSkills(
-        await options.runtime.listSkills(options.agentName, command.input || undefined),
+        await options.runtime.listSkills(
+          options.agentName,
+          command.input || undefined,
+          options.workspaceDir,
+        ),
       ),
     };
   }

+ 6 - 2
packages/tui/src/runtime/adapter.ts

@@ -532,8 +532,12 @@ export class TuiRuntimeAdapter implements TuiRuntime {
   getActiveRun(sessionId: string): Promise<TuiActiveRunSnapshot> {
     return this.productAccess.getActiveRun(sessionId);
   }
-  listSkills(agentName?: string, keyword?: string): Promise<TuiSkillList> {
-    return this.productAccess.listSkills(agentName, keyword);
+  listSkills(
+    agentName?: string,
+    keyword?: string,
+    workspaceDir?: string,
+  ): Promise<TuiSkillList> {
+    return this.productAccess.listSkills(agentName, keyword, workspaceDir);
   }
   inspectProjectMcp(
     sessionId: string,

+ 2 - 1
packages/tui/src/runtime/adapters/product-access.ts

@@ -377,11 +377,12 @@ export class TuiProductAccess {
   async listSkills(
     agentName = this.defaultAgentName,
     keyword?: string,
+    workspaceDir = this.workspaceDir,
   ): Promise<TuiSkillList> {
     const service = this.context.service("skill.list");
     const result = await service.listRuntimeSkills({
       agentName,
-      ...(this.workspaceDir ? { workspaceDir: this.workspaceDir } : {}),
+      ...(workspaceDir ? { workspaceDir } : {}),
       includePluginSkills: true,
     });
     const normalizedKeyword = keyword?.trim().toLocaleLowerCase();

+ 1 - 1
packages/tui/src/runtime/port.ts

@@ -294,7 +294,7 @@ export interface TuiInspectionPort {
     agentName?: string,
     customInstructions?: string,
   ): Promise<TuiCompactionResult>;
-  listSkills(agentName?: string, keyword?: string): Promise<TuiSkillList>;
+  listSkills(agentName?: string, keyword?: string, workspaceDir?: string): Promise<TuiSkillList>;
   listMcpServers(keyword?: string, sessionId?: string): Promise<TuiMcpServer[]>;
   inspectProjectMcp(sessionId: string): Promise<TuiProjectMcpPreview | undefined>;
   getContextSnapshot(sessionId: string): Promise<TuiContextSnapshotResponse>;

+ 216 - 2
packages/tui/test/unit/acp-agent.test.ts

@@ -1,6 +1,7 @@
 import * as acp from '@agentclientprotocol/sdk';
 import { describe, expect, it, vi } from 'vitest';
 
+import { TUI_ACP_AVAILABLE_COMMANDS } from '../../src/acp/commands.js';
 import { createTuiAcpAgent } from '../../src/acp/agent.js';
 import { TuiAcpPromptContinuation } from '../../src/acp/prompt-continuation.js';
 import type { TuiAcpRuntime } from '../../src/acp/runtime.js';
@@ -79,7 +80,7 @@ function createRuntime(
     Promise.resolve(options.contextSnapshot ?? { status: 'empty' as const }),
   );
   const getSessionUsage = vi.fn(async () => options.sessionUsage ?? {});
-  const listSkills = vi.fn(async () => options.skills ?? {});
+  const listSkills = vi.fn<TuiAcpRuntime['listSkills']>(async () => options.skills ?? {});
   const listMcpServers = vi.fn(async () => [...(options.mcpServers ?? [])]);
   const requestCompaction = vi.fn(async () => ({ success: true }));
   const getPlanModeCapabilities = vi.fn(async () => ({ entryEnabled: true }));
@@ -267,6 +268,219 @@ function createRuntime(
 }
 
 describe('MiniMax Code ACP agent', () => {
+  it.each(['new', 'load', 'resume', 'fork'] as const)(
+    'advertises session Skills on %s and forwards Skill instructions to the Runtime',
+    async (method) => {
+      const { runtime, listSkills, sendMessage, getSession, forkSession } = createRuntime(
+        [{ type: 'session-status', status: 'finished' }],
+        {
+          skills: {
+            skills: [
+              {
+                name: 'matt:review',
+                description: 'Review changes',
+                enabled: true,
+              },
+              { name: 'repo-test', displayDescription: 'Test the project' },
+              { name: 'MATT:REVIEW', description: 'Duplicate' },
+              {
+                name: 'Compact',
+                description: 'Must not replace a native command',
+              },
+              { name: 'disabled', enabled: false },
+              { name: 'invalid/name' },
+              { name: 'invalid name' },
+              { name: '' },
+              { name: 'x'.repeat(129) },
+              { name: 'bad\u001b[31m' },
+            ],
+          },
+        },
+      );
+      getSession.mockImplementation(async (sessionId) => ({
+        sessionId,
+        workspaceDir: '/project',
+        agentName: 'reviewer',
+      }));
+      forkSession.mockResolvedValue({
+        session: {
+          sessionId: 'session-fork',
+          workspaceDir: '/project',
+          agentName: 'reviewer',
+        },
+      });
+      const updates: acp.SessionNotification[] = [];
+      const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
+      const client = acp
+        .client({ name: 'zed' })
+        .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
+      await client.connectWith(agent, async (connection) => {
+        await connection.request(acp.methods.agent.initialize, {
+          protocolVersion: acp.PROTOCOL_VERSION,
+          clientCapabilities: {},
+        });
+        const response = await connection.request(acp.methods.agent.session[method], {
+          sessionId: 'session-1',
+          cwd: '/project',
+          mcpServers: [],
+        });
+        const sessionId = 'sessionId' in response ? response.sessionId : 'session-1';
+        const roster = () =>
+          updates
+            .filter(
+              (update) =>
+                update.sessionId === sessionId &&
+                update.update.sessionUpdate === 'available_commands_update',
+            )
+            .at(-1)?.update;
+        const expected = {
+          sessionUpdate: 'available_commands_update',
+          availableCommands: [
+            ...TUI_ACP_AVAILABLE_COMMANDS,
+            {
+              name: 'matt:review',
+              description: '[Skill] Review changes',
+              input: { hint: '[instructions]' },
+            },
+            {
+              name: 'repo-test',
+              description: '[Skill] Test the project',
+              input: { hint: '[instructions]' },
+            },
+          ],
+        };
+        await vi.waitFor(() => expect(roster()).toEqual(expected));
+        expect(listSkills).toHaveBeenCalledWith(
+          method === 'new' ? undefined : 'reviewer',
+          undefined,
+          '/project',
+        );
+        // A delayed listener retry must retain the complete Skill roster.
+        await new Promise((resolve) => setTimeout(resolve, 130));
+        expect(roster()).toEqual(expected);
+        await expect(
+          connection.request(acp.methods.agent.session.prompt, {
+            sessionId,
+            prompt: [{ type: 'text', text: '/matt:review focus on error handling' }],
+          }),
+        ).resolves.toEqual({ stopReason: 'end_turn' });
+        expect(sendMessage).toHaveBeenCalledWith(
+          expect.objectContaining({
+            id: sessionId,
+            content: '/matt:review focus on error handling',
+          }),
+          expect.any(AbortSignal),
+        );
+      });
+    },
+  );
+
+  it.each(['reject', 'stall'] as const)(
+    'keeps native commands available when Skill discovery can %s',
+    async (failure) => {
+      const { runtime, listSkills } = createRuntime();
+      if (failure === 'reject') listSkills.mockRejectedValue(new Error('Unavailable'));
+      else listSkills.mockImplementation(() => new Promise(() => undefined));
+      const updates: acp.SessionNotification[] = [];
+      const client = acp
+        .client({ name: 'zed' })
+        .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
+      await client.connectWith(
+        createTuiAcpAgent({ runtime, version: '1.2.3' }),
+        async (connection) => {
+          await connection.request(acp.methods.agent.initialize, {
+            protocolVersion: acp.PROTOCOL_VERSION,
+            clientCapabilities: {},
+          });
+          const { sessionId } = await connection.request(acp.methods.agent.session.new, {
+            cwd: '/workspace',
+            mcpServers: [],
+          });
+          await vi.waitFor(() =>
+            expect(updates).toContainEqual({
+              sessionId,
+              update: {
+                sessionUpdate: 'available_commands_update',
+                availableCommands: TUI_ACP_AVAILABLE_COMMANDS,
+              },
+            }),
+          );
+          await expect(
+            connection.request(acp.methods.agent.session.prompt, {
+              sessionId,
+              prompt: [{ type: 'text', text: '/help' }],
+            }),
+          ).resolves.toEqual({ stopReason: 'end_turn' });
+        },
+      );
+    },
+  );
+
+  it.each(['close', 'resume'] as const)(
+    'ignores late Skill discovery after session %s',
+    async (method) => {
+      const { runtime, listSkills } = createRuntime([], {
+        skills: { skills: [{ name: 'current' }] },
+      });
+      let resolveSkills!: (skills: TuiSkillList) => void;
+      listSkills.mockImplementationOnce(
+        () =>
+          new Promise((resolve) => {
+            resolveSkills = resolve;
+          }),
+      );
+      const updates: acp.SessionNotification[] = [];
+      const client = acp
+        .client({ name: 'zed' })
+        .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
+      await client.connectWith(
+        createTuiAcpAgent({ runtime, version: '1.2.3' }),
+        async (connection) => {
+          await connection.request(acp.methods.agent.initialize, {
+            protocolVersion: acp.PROTOCOL_VERSION,
+            clientCapabilities: {},
+          });
+          const { sessionId } = await connection.request(acp.methods.agent.session.new, {
+            cwd: '/workspace',
+            mcpServers: [],
+          });
+          await vi.waitFor(() => expect(listSkills).toHaveBeenCalledOnce());
+          await connection.request(acp.methods.agent.session[method], {
+            sessionId,
+            cwd: '/workspace',
+            mcpServers: [],
+          });
+          if (method === 'resume') {
+            await vi.waitFor(() =>
+              expect(updates).toContainEqual({
+                sessionId,
+                update: {
+                  sessionUpdate: 'available_commands_update',
+                  availableCommands: [
+                    ...TUI_ACP_AVAILABLE_COMMANDS,
+                    {
+                      name: 'current',
+                      description: '[Skill]',
+                      input: { hint: '[instructions]' },
+                    },
+                  ],
+                },
+              }),
+            );
+          }
+          resolveSkills({ skills: [{ name: 'stale' }] });
+          const count = updates.length;
+          await new Promise((resolve) => setTimeout(resolve, 130));
+          const rosters = updates.flatMap(({ update }) =>
+            update.sessionUpdate === 'available_commands_update' ? update.availableCommands : [],
+          );
+          expect(rosters.some((command) => command.name === 'stale')).toBe(false);
+          if (method === 'close') expect(updates).toHaveLength(count);
+        },
+      );
+    },
+  );
+
   it('advertises and executes native help and model commands without starting an Agent turn', async () => {
     const { runtime, sendMessage, listModels, selectModel } = createRuntime([], {
       models: [
@@ -555,7 +769,7 @@ describe('MiniMax Code ACP agent', () => {
     });
 
     expect(getContextSnapshot).toHaveBeenCalledWith('session-1');
-    expect(listSkills).toHaveBeenCalledWith(undefined, 'review');
+    expect(listSkills).toHaveBeenCalledWith(undefined, 'review', '/workspace');
     expect(listMcpServers).toHaveBeenCalledWith('git', 'session-1');
     expect(getSessionUsage).toHaveBeenCalledWith('session-1');
     expect(sendMessage).not.toHaveBeenCalled();

+ 19 - 0
packages/tui/test/unit/runtime-product-access.test.ts

@@ -546,6 +546,25 @@ describe("TuiRuntimeAdapter product access", () => {
     expect(cliService.selectModel).toHaveBeenCalledWith(selection);
   });
 
+  it("discovers Skills in the requested Session workspace without changing the adapter default", async () => {
+    const cliService = cliServiceFixture();
+    const adapter = new TuiRuntimeAdapter(cliService, {
+      workspaceDir: "/default-workspace",
+    });
+    await adapter.listSkills("reviewer", undefined, "/session-workspace");
+    await adapter.listSkills("mavis");
+    expect(cliService.listRuntimeSkills).toHaveBeenNthCalledWith(1, {
+      agentName: "reviewer",
+      workspaceDir: "/session-workspace",
+      includePluginSkills: true,
+    });
+    expect(cliService.listRuntimeSkills).toHaveBeenNthCalledWith(2, {
+      agentName: "mavis",
+      workspaceDir: "/default-workspace",
+      includePluginSkills: true,
+    });
+  });
+
   it("registers installed Plugin Skills from the unified Runtime roster as slash commands", async () => {
     const cliService = cliServiceFixture();
     vi.mocked(cliService.listRuntimeSkills).mockImplementationOnce(