mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-18 03:27:08 +00:00
feat(cli): add GitHub Copilot CLI agent support via ACP (#1245)
* feat(cli): add GitHub Copilot CLI agent support via ACP Wrap `copilot --acp --stdio` for remote sessions and spawn the native TUI locally, with full hub/web integration for spawn, resume, and permissions. Fixes tiann/hapi#362 Co-Authored-By: HAPI <noreply@hapi.run> Co-authored-by: Cursor <cursoragent@cursor.com> * feat(copilot): agent modes, models, slash/file UX, local session sync Add Interactive/Plan/Autopilot (fleet is slash-only), subscription-aware model discovery, web StatusBar/permission UX, @ file mentions, and fix local Safe Yolo plus session-id locator for handoff/resume. Co-authored-by: Cursor <cursoragent@cursor.com> * chore: re-trigger Codex PR review after auth outage Co-authored-by: Cursor <cursoragent@cursor.com> * chore: retry Codex PR review Co-authored-by: Cursor <cursoragent@cursor.com> * fix(copilot): preserve agent mode on resume and apply via ACP set_mode Resume was dropping copilotAgentMode so Plan/Autopilot reset to interactive. Also switch local/remote mode application to --mode / session set_mode instead of slash prompts. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(copilot): wake remote loop when agent mode changes Empty isolated queue tick lets setMode apply without inventing a user prompt. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(copilot): confirm mode changes before persisting Await Copilot mode changes and expose discovered models so session state reflects backend acceptance. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(copilot): guard mode discovery and slash updates Keep model probes within runner roots and preserve active sessions when mode switching is unavailable or rejected. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(copilot): preserve resume and auto semantics Deduplicate Copilot resume rows, apply Auto explicitly, and fail closed on denied permissions. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(copilot): close permission and model discovery gaps Keep write-capable commands pending in read-only mode, extend model probe RPCs, and preserve explicit model validation before session creation. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(copilot): persist runtime model and agent mode Fallback to ACP model options when direct model switching is unavailable and retain Copilot agent mode across hub restarts. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(copilot): normalize composer auto selection Use the null session sentinel for Copilot Auto so the composer selects and resets default models consistently. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(copilot): reject local permission mode changes * style(copilot): remove trailing blank line * fix(copilot): secure local config handoffs * fix(copilot): reject local agent mode slashes * fix(copilot): reject mode changes during turns * fix(copilot): consume rejected slash updates * fix(copilot): preserve thinking across slash handling * fix(copilot): stabilize async config changes * fix(copilot): roll back rejected startup model * fix(copilot): preserve cancellation and file mentions * fix(copilot): hide local permission controls * fix(deps): support clean workspace installs * test(copilot): account for spawn mode argument * fix(copilot): attribute usage to active model --------- Co-authored-by: HAPI <noreply@hapi.run> Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
co-authored by
Cursor
HAPI
parent
b67f4e56e5
commit
f10fbc7496
@@ -0,0 +1,268 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import { createMessageConnection, StreamMessageReader, StreamMessageWriter } from 'vscode-jsonrpc/node';
|
||||
import { asString, isObject } from '@hapi/protocol';
|
||||
import type { CopilotModelsResponse, CopilotModelSummary } from '@hapi/protocol/apiTypes';
|
||||
import { createCopilotBackend } from '@/copilot/utils/copilotBackend';
|
||||
import { getErrorMessage } from './rpcResponses';
|
||||
|
||||
export interface ListCopilotModelsForCwdRequest {
|
||||
cwd?: string;
|
||||
}
|
||||
|
||||
export type ListCopilotModelsForCwdResponse = CopilotModelsResponse;
|
||||
|
||||
interface CacheEntry {
|
||||
expiresAt: number;
|
||||
response: ListCopilotModelsForCwdResponse;
|
||||
}
|
||||
|
||||
const CACHE_TTL_MS = 60_000;
|
||||
const PROBE_TIMEOUT_MS = 30_000;
|
||||
const cache = new Map<string, CacheEntry>();
|
||||
const inflight = new Map<string, Promise<ListCopilotModelsForCwdResponse>>();
|
||||
|
||||
function normalizeAvailableModels(rawModels: unknown): CopilotModelSummary[] {
|
||||
if (!Array.isArray(rawModels)) return [];
|
||||
const out: CopilotModelSummary[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const entry of rawModels) {
|
||||
if (!isObject(entry)) continue;
|
||||
const modelId = asString(entry.modelId)
|
||||
?? asString(entry.id)
|
||||
?? asString(entry.value);
|
||||
if (!modelId || seen.has(modelId)) continue;
|
||||
seen.add(modelId);
|
||||
const name = asString(entry.name)
|
||||
?? (modelId === 'auto' ? 'Auto' : undefined);
|
||||
out.push(name ? { modelId, name } : { modelId });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function extractModelConfigOption(response: Record<string, unknown>): {
|
||||
currentValue: string | null;
|
||||
options: unknown[];
|
||||
} | null {
|
||||
if (!Array.isArray(response.configOptions)) return null;
|
||||
|
||||
for (const entry of response.configOptions) {
|
||||
if (!isObject(entry)) continue;
|
||||
if (asString(entry.category) !== 'model') continue;
|
||||
return {
|
||||
currentValue: asString(entry.currentValue),
|
||||
options: Array.isArray(entry.options) ? entry.options : []
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function extractModelsFromAcpResponse(response: unknown): {
|
||||
availableModels: CopilotModelSummary[];
|
||||
currentModelId: string | null;
|
||||
} {
|
||||
if (!isObject(response)) {
|
||||
return { availableModels: [], currentModelId: null };
|
||||
}
|
||||
|
||||
const meta = isObject(response._meta) ? response._meta : null;
|
||||
const modelState = meta && isObject(meta.modelState) ? meta.modelState : null;
|
||||
const configModelOption = extractModelConfigOption(response);
|
||||
const rawModels = Array.isArray(response.availableModels)
|
||||
? response.availableModels
|
||||
: modelState && Array.isArray(modelState.availableModels)
|
||||
? modelState.availableModels
|
||||
: configModelOption?.options ?? null;
|
||||
const rawCurrent = asString(response.currentModelId)
|
||||
?? (modelState ? asString(modelState.currentModelId) : null)
|
||||
?? configModelOption?.currentValue
|
||||
?? null;
|
||||
|
||||
return {
|
||||
availableModels: normalizeAvailableModels(rawModels),
|
||||
currentModelId: rawCurrent
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Copilot ACP session/new does not advertise a model catalog (only mode +
|
||||
* permissions). The SDK headless protocol exposes subscription-aware models
|
||||
* via `models.list` — Student plans typically return only `auto`.
|
||||
*/
|
||||
async function listModelsViaSdkHeadless(): Promise<CopilotModelSummary[]> {
|
||||
const command = process.env.COPILOT_CLI_PATH ?? 'copilot';
|
||||
const child = spawn(command, ['--headless', '--stdio', '--no-auto-update'], {
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
env: process.env
|
||||
});
|
||||
|
||||
if (!child.stdin || !child.stdout) {
|
||||
child.kill();
|
||||
throw new Error('Failed to open Copilot headless stdio pipes');
|
||||
}
|
||||
|
||||
const connection = createMessageConnection(
|
||||
new StreamMessageReader(child.stdout),
|
||||
new StreamMessageWriter(child.stdin)
|
||||
);
|
||||
connection.listen();
|
||||
|
||||
const exitPromise = new Promise<never>((_, reject) => {
|
||||
child.once('exit', (code) => {
|
||||
reject(new Error(`Copilot headless exited with code ${code ?? 'unknown'}`));
|
||||
});
|
||||
child.once('error', (error) => {
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await Promise.race([
|
||||
connection.sendRequest('models.list', {}),
|
||||
exitPromise,
|
||||
new Promise<never>((_, reject) => {
|
||||
setTimeout(() => reject(new Error('Timed out listing Copilot models')), PROBE_TIMEOUT_MS);
|
||||
})
|
||||
]);
|
||||
const models = isObject(result) && Array.isArray(result.models)
|
||||
? result.models
|
||||
: Array.isArray(result)
|
||||
? result
|
||||
: [];
|
||||
return normalizeAvailableModels(models);
|
||||
} finally {
|
||||
try {
|
||||
connection.dispose();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
if (!child.killed) {
|
||||
child.kill();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function listModelsViaAcpProbe(cwd: string): Promise<{
|
||||
availableModels: CopilotModelSummary[];
|
||||
currentModelId: string | null;
|
||||
}> {
|
||||
const backend = createCopilotBackend();
|
||||
try {
|
||||
await backend.initialize();
|
||||
const sessionId = await backend.newSession({ cwd, mcpServers: [] });
|
||||
const metadata = backend.getSessionModelsMetadata(sessionId);
|
||||
const modelOption = backend.getConfigOptionByCategory(sessionId, 'model');
|
||||
return extractModelsFromAcpResponse({
|
||||
availableModels: metadata?.availableModels,
|
||||
currentModelId: metadata?.currentModelId,
|
||||
configOptions: modelOption ? [{
|
||||
category: 'model',
|
||||
currentValue: modelOption.currentValue,
|
||||
options: modelOption.options
|
||||
}] : []
|
||||
});
|
||||
} finally {
|
||||
await backend.disconnect().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
async function runCopilotProbe(cwd: string): Promise<ListCopilotModelsForCwdResponse> {
|
||||
try {
|
||||
// Prefer SDK headless models.list — subscription-aware (Student → auto only).
|
||||
const sdkModels = await listModelsViaSdkHeadless();
|
||||
if (sdkModels.length > 0) {
|
||||
return {
|
||||
success: true,
|
||||
availableModels: sdkModels,
|
||||
currentModelId: sdkModels.find((model) => model.modelId === 'auto')?.modelId
|
||||
?? sdkModels[0]?.modelId
|
||||
?? null
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// Fall through to ACP probe; never invent a static catalog.
|
||||
}
|
||||
|
||||
try {
|
||||
const acp = await listModelsViaAcpProbe(cwd || process.cwd());
|
||||
return {
|
||||
success: true,
|
||||
availableModels: acp.availableModels,
|
||||
currentModelId: acp.currentModelId
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: getErrorMessage(error, 'Failed to list Copilot models'),
|
||||
availableModels: [],
|
||||
currentModelId: null
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function listCopilotModelsForCwd(cwd: string): Promise<ListCopilotModelsForCwdResponse> {
|
||||
const key = cwd || process.cwd();
|
||||
const cached = cache.get(key);
|
||||
if (cached && cached.expiresAt > Date.now()) {
|
||||
return cached.response;
|
||||
}
|
||||
|
||||
const pending = inflight.get(key);
|
||||
if (pending) {
|
||||
return pending;
|
||||
}
|
||||
|
||||
const promise = runCopilotProbe(key).then((response) => {
|
||||
cache.set(key, { expiresAt: Date.now() + CACHE_TTL_MS, response });
|
||||
inflight.delete(key);
|
||||
return response;
|
||||
}).catch((error) => {
|
||||
inflight.delete(key);
|
||||
throw error;
|
||||
});
|
||||
|
||||
inflight.set(key, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
export async function buildCopilotModelsResponseFromBackend(
|
||||
sessionId: string,
|
||||
backend: {
|
||||
getSessionModelsMetadata: (id: string) => {
|
||||
availableModels: CopilotModelSummary[];
|
||||
currentModelId: string | null;
|
||||
} | undefined;
|
||||
getConfigOptionByCategory: (id: string, category: string) => {
|
||||
currentValue?: string;
|
||||
options?: Array<{ value: string; name?: string }>;
|
||||
} | undefined;
|
||||
},
|
||||
cwd?: string
|
||||
): Promise<ListCopilotModelsForCwdResponse> {
|
||||
const metadata = backend.getSessionModelsMetadata(sessionId);
|
||||
const modelOption = backend.getConfigOptionByCategory(sessionId, 'model');
|
||||
const parsed = extractModelsFromAcpResponse({
|
||||
availableModels: metadata?.availableModels,
|
||||
currentModelId: metadata?.currentModelId,
|
||||
configOptions: modelOption ? [{
|
||||
category: 'model',
|
||||
currentValue: modelOption.currentValue,
|
||||
options: modelOption.options
|
||||
}] : []
|
||||
});
|
||||
|
||||
if (parsed.availableModels.length > 0) {
|
||||
return {
|
||||
success: true,
|
||||
availableModels: parsed.availableModels,
|
||||
currentModelId: parsed.currentModelId ?? metadata?.currentModelId ?? null
|
||||
};
|
||||
}
|
||||
|
||||
// ACP has no catalog — reuse subscription-aware SDK list (cached).
|
||||
const response = await listCopilotModelsForCwd(cwd ?? process.cwd());
|
||||
return {
|
||||
...response,
|
||||
currentModelId: parsed.currentModelId ?? response.currentModelId ?? null
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { logger } from '@/ui/logger';
|
||||
import { RPC_METHODS } from '@hapi/protocol/rpcMethods';
|
||||
import type { RpcHandlerManager } from '@/api/rpc/RpcHandlerManager';
|
||||
import {
|
||||
listCopilotModelsForCwd,
|
||||
type ListCopilotModelsForCwdRequest,
|
||||
type ListCopilotModelsForCwdResponse
|
||||
} from '../copilotModels';
|
||||
import { getErrorMessage, rpcError } from '../rpcResponses';
|
||||
|
||||
export function registerCopilotModelHandlers(rpcHandlerManager: RpcHandlerManager): void {
|
||||
rpcHandlerManager.registerHandler<ListCopilotModelsForCwdRequest, ListCopilotModelsForCwdResponse>(
|
||||
RPC_METHODS.ListCopilotModelsForCwd,
|
||||
async (data) => {
|
||||
try {
|
||||
return await listCopilotModelsForCwd(typeof data?.cwd === 'string' ? data.cwd : '');
|
||||
} catch (error) {
|
||||
logger.debug('Failed to list Copilot models:', error);
|
||||
return rpcError(getErrorMessage(error, 'Failed to list Copilot models'));
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { registerCodexModelHandlers } from './handlers/codexModels'
|
||||
import { registerCursorModelHandlers } from './handlers/cursorModels'
|
||||
import { registerOpencodeModelHandlers } from './handlers/opencodeModels'
|
||||
import { registerGrokModelHandlers } from './handlers/grokModels'
|
||||
import { registerCopilotModelHandlers } from './handlers/copilotModels'
|
||||
import { registerDirectoryHandlers } from './handlers/directories'
|
||||
import { registerDifftasticHandlers } from './handlers/difftastic'
|
||||
import { registerFileHandlers } from './handlers/files'
|
||||
@@ -19,6 +20,7 @@ export function registerCommonHandlers(rpcHandlerManager: RpcHandlerManager, wor
|
||||
registerCursorModelHandlers(rpcHandlerManager)
|
||||
registerOpencodeModelHandlers(rpcHandlerManager)
|
||||
registerGrokModelHandlers(rpcHandlerManager)
|
||||
registerCopilotModelHandlers(rpcHandlerManager)
|
||||
registerFileHandlers(rpcHandlerManager, workingDirectory)
|
||||
registerDirectoryHandlers(rpcHandlerManager, workingDirectory)
|
||||
registerRipgrepHandlers(rpcHandlerManager, workingDirectory)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { AgentFlavor } from '@hapi/protocol'
|
||||
import type { CopilotAgentMode } from '@hapi/protocol'
|
||||
|
||||
export interface SpawnSessionOptions {
|
||||
machineId?: string
|
||||
@@ -15,6 +16,7 @@ export interface SpawnSessionOptions {
|
||||
permissionMode?: string
|
||||
serviceTier?: string
|
||||
collaborationMode?: 'default' | 'plan'
|
||||
copilotAgentMode?: CopilotAgentMode
|
||||
token?: string
|
||||
sessionType?: 'simple' | 'worktree'
|
||||
worktreeName?: string
|
||||
|
||||
@@ -122,6 +122,18 @@ describe('listSkills', () => {
|
||||
expect(skills.map((skill) => skill.name)).toEqual(['grok-project', 'grok-user', 'shared'])
|
||||
})
|
||||
|
||||
it('lists Copilot user and project skills alongside shared .agents skills', async () => {
|
||||
const repoRoot = join(sandboxDir, 'copilot-repo')
|
||||
await mkdir(join(repoRoot, '.git'), { recursive: true })
|
||||
await writeSkill(join(homeDir, '.copilot', 'skills', 'copilot-user'), 'copilot-user', 'Copilot user skill')
|
||||
await writeSkill(join(homeDir, '.agents', 'skills', 'shared'), 'shared', 'Shared skill')
|
||||
await writeSkill(join(repoRoot, '.github', 'skills', 'github-skill'), 'github-skill', 'GitHub skill')
|
||||
|
||||
const skills = await listSkills(repoRoot, { flavor: 'copilot' })
|
||||
|
||||
expect(skills.map((skill) => skill.name)).toEqual(['copilot-user', 'github-skill', 'shared'])
|
||||
})
|
||||
|
||||
it('scopes user skills to the requested flavor', async () => {
|
||||
await writeSkill(join(homeDir, '.agents', 'skills', 'shared'), 'shared', 'Shared skill')
|
||||
await writeSkill(join(homeDir, '.claude', 'skills', 'claude-only'), 'claude-only', 'Claude skill')
|
||||
|
||||
@@ -73,6 +73,9 @@ function getUserSkillsRoots(flavor?: string): string[] {
|
||||
case 'grok':
|
||||
roots.push(join(getAgentConfigDir(flavor), 'skills'));
|
||||
break;
|
||||
case 'copilot':
|
||||
roots.push(join(getAgentConfigDir(flavor), 'skills'));
|
||||
break;
|
||||
}
|
||||
return roots;
|
||||
}
|
||||
@@ -93,6 +96,10 @@ function getProjectSkillsRoots(directory: string, flavor?: string): string[] {
|
||||
case 'grok':
|
||||
roots.push(join(directory, '.grok', 'skills'));
|
||||
break;
|
||||
case 'copilot':
|
||||
roots.push(join(directory, '.copilot', 'skills'));
|
||||
roots.push(join(directory, '.github', 'skills'));
|
||||
break;
|
||||
}
|
||||
return roots;
|
||||
}
|
||||
|
||||
@@ -8,7 +8,9 @@ describe('listSlashCommands', () => {
|
||||
const originalClaudeConfigDir = process.env.CLAUDE_CONFIG_DIR
|
||||
const originalCodexHome = process.env.CODEX_HOME
|
||||
const originalXdgConfigHome = process.env.XDG_CONFIG_HOME
|
||||
const originalHome = process.env.HOME
|
||||
let sandboxDir: string
|
||||
let homeDir: string
|
||||
let claudeConfigDir: string
|
||||
let codexHome: string
|
||||
let xdgConfigHome: string
|
||||
@@ -17,16 +19,19 @@ describe('listSlashCommands', () => {
|
||||
|
||||
beforeEach(async () => {
|
||||
sandboxDir = await mkdtemp(join(tmpdir(), 'hapi-slash-commands-'))
|
||||
homeDir = join(sandboxDir, 'home')
|
||||
claudeConfigDir = join(sandboxDir, 'global-claude')
|
||||
codexHome = join(sandboxDir, 'global-codex')
|
||||
xdgConfigHome = join(sandboxDir, 'xdg-config')
|
||||
opencodeUserDir = join(xdgConfigHome, 'opencode', 'command')
|
||||
projectDir = join(sandboxDir, 'project')
|
||||
|
||||
process.env.HOME = homeDir
|
||||
process.env.CLAUDE_CONFIG_DIR = claudeConfigDir
|
||||
process.env.CODEX_HOME = codexHome
|
||||
process.env.XDG_CONFIG_HOME = xdgConfigHome
|
||||
|
||||
await mkdir(homeDir, { recursive: true })
|
||||
await mkdir(join(claudeConfigDir, 'commands'), { recursive: true })
|
||||
await mkdir(join(codexHome, 'prompts'), { recursive: true })
|
||||
await mkdir(opencodeUserDir, { recursive: true })
|
||||
@@ -36,6 +41,11 @@ describe('listSlashCommands', () => {
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
if (originalHome === undefined) {
|
||||
delete process.env.HOME
|
||||
} else {
|
||||
process.env.HOME = originalHome
|
||||
}
|
||||
if (originalClaudeConfigDir === undefined) {
|
||||
delete process.env.CLAUDE_CONFIG_DIR
|
||||
} else {
|
||||
@@ -280,4 +290,21 @@ describe('listSlashCommands', () => {
|
||||
content: 'Local body',
|
||||
})
|
||||
})
|
||||
|
||||
it('exposes Copilot agent builtins (skills stay on $ autocomplete)', async () => {
|
||||
const commands = await listSlashCommands('copilot', projectDir)
|
||||
const names = commands.map((command) => command.name)
|
||||
|
||||
expect(names).toEqual(expect.arrayContaining([
|
||||
'rubber-duck',
|
||||
'security-review',
|
||||
'research',
|
||||
'review',
|
||||
'skills',
|
||||
'fleet',
|
||||
]))
|
||||
expect(names).not.toContain('fix-issue')
|
||||
expect(commands.find((command) => command.name === 'rubber-duck')?.source).toBe('builtin')
|
||||
expect(commands.find((command) => command.name === 'plan')?.source).toBe('builtin')
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user