mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-25 05:07:05 +00:00
feat(pi): expose peer session MCP tools (#2312)
This commit is contained in:
@@ -296,6 +296,25 @@ describe('startHappyServer skill_lookup', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('forwards inspect_peer through MCP and returns the formatted report', async () => {
|
||||
const inspect = vi.spyOn(peerMessages, 'inspectPeer').mockResolvedValue({} as Awaited<ReturnType<typeof peerMessages.inspectPeer>>)
|
||||
const format = vi.spyOn(peerMessages, 'formatInspectPeerReport').mockReturnValue('INSPECT REPORT')
|
||||
try {
|
||||
const mcp = await connect(false)
|
||||
const result = await mcp.callTool({
|
||||
name: 'inspect_peer',
|
||||
arguments: { sessionIdPrefix: 'peer-id', messageLimit: 12 },
|
||||
}) as ToolResult
|
||||
expect(inspect).toHaveBeenCalledWith({ sessionIdPrefix: 'peer-id', messageLimit: 12 })
|
||||
expect(format).toHaveBeenCalledOnce()
|
||||
expect(result.isError).toBe(false)
|
||||
expect(result.content?.[0]?.text).toBe('INSPECT REPORT')
|
||||
} finally {
|
||||
inspect.mockRestore()
|
||||
format.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('lists active peers by default and forwards includeInactive', async () => {
|
||||
const list = vi.spyOn(peerMessages, 'listPeerSessions').mockResolvedValue([])
|
||||
try {
|
||||
@@ -702,13 +721,13 @@ describe('startHappyServer peer tools kill switch', () => {
|
||||
}
|
||||
})
|
||||
|
||||
async function startServer(): Promise<{ url: string; toolNames: string[] }> {
|
||||
async function startServer(options: Parameters<typeof startHappyServer>[1] = {}): Promise<{ url: string; toolNames: string[] }> {
|
||||
const sessionClient = {
|
||||
updateMetadata: vi.fn(),
|
||||
sendAgentMessage: vi.fn(),
|
||||
sendClaudeSessionMessage: vi.fn()
|
||||
} as unknown as ApiSessionClient
|
||||
const server = await startHappyServer(sessionClient, {})
|
||||
const server = await startHappyServer(sessionClient, options)
|
||||
stopServer = server.stop
|
||||
client = new Client(
|
||||
{ name: 'hapi-peer-tools-test', version: '1.0.0' },
|
||||
@@ -718,6 +737,25 @@ describe('startHappyServer peer tools kill switch', () => {
|
||||
return { url: server.url, toolNames: server.toolNames }
|
||||
}
|
||||
|
||||
|
||||
it('supports a peer-only explicit tool allowlist', async () => {
|
||||
delete process.env.HAPI_DISABLE_PEER_TOOLS
|
||||
const { toolNames } = await startServer({
|
||||
enableChangeTitle: false,
|
||||
enabledTools: ['list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer'],
|
||||
})
|
||||
expect(toolNames).toEqual(['list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer'])
|
||||
const tools = await client!.listTools()
|
||||
expect(tools.tools.map((tool) => tool.name)).toEqual(expect.arrayContaining(['list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer']))
|
||||
})
|
||||
|
||||
it('does not let the allowlist bypass HAPI_DISABLE_PEER_TOOLS', async () => {
|
||||
process.env.HAPI_DISABLE_PEER_TOOLS = '1'
|
||||
await expect(startServer({
|
||||
enableChangeTitle: false,
|
||||
enabledTools: ['list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer'],
|
||||
})).rejects.toThrow('startHappyServer requires at least one enabled tool')
|
||||
})
|
||||
it('registers peer tools by default', async () => {
|
||||
delete process.env.HAPI_DISABLE_PEER_TOOLS
|
||||
const { toolNames } = await startServer()
|
||||
|
||||
@@ -40,6 +40,17 @@ import { PingPeerError, formatInspectPeerReport, formatPeerSessionsList, inspect
|
||||
import { applySessionDisplayRename, normalizeSessionDisplayTitle } from "@/agent/sessionDisplayRename";
|
||||
import { SpawnPeerError, spawnPeer } from "@/modules/spawnPeer/spawnPeer";
|
||||
|
||||
export type HapiMcpToolName =
|
||||
| 'change_title'
|
||||
| 'display_image'
|
||||
| 'display_video'
|
||||
| 'display_media'
|
||||
| 'list_peers'
|
||||
| 'ping_peer'
|
||||
| 'inspect_peer'
|
||||
| 'spawn_peer'
|
||||
| 'skill_lookup';
|
||||
|
||||
type StartHappyServerOptions = {
|
||||
/**
|
||||
* When true (default), change_title writes metadata.name (web rename
|
||||
@@ -59,6 +70,11 @@ type StartHappyServerOptions = {
|
||||
workingDirectory: string;
|
||||
flavor: string;
|
||||
};
|
||||
/**
|
||||
* Restrict the server to an explicit subset of HAPI tools. Omit to keep
|
||||
* the historical behavior where launchers choose through the other flags.
|
||||
*/
|
||||
enabledTools?: readonly HapiMcpToolName[];
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -107,8 +123,14 @@ function createHapiMcpServer(
|
||||
enableChangeTitle: boolean,
|
||||
skillLookup: StartHappyServerOptions['skillLookup'],
|
||||
workingDirectory: string | undefined,
|
||||
enabledTools: ReadonlySet<HapiMcpToolName>,
|
||||
onChangeTitle?: StartHappyServerOptions['onChangeTitle']
|
||||
): McpServer {
|
||||
const registerTool = (name: HapiMcpToolName, config: any, handler: any): void => {
|
||||
if (enabledTools.has(name)) {
|
||||
mcp.registerTool<any, any>(name, config, handler);
|
||||
}
|
||||
};
|
||||
const handler = async (title: string) => {
|
||||
logger.debug('[hapiMCP] Changing title to:', title);
|
||||
try {
|
||||
@@ -270,7 +292,7 @@ function createHapiMcpServer(
|
||||
return media;
|
||||
}
|
||||
if (enableChangeTitle) {
|
||||
mcp.registerTool<any, any>('change_title', {
|
||||
registerTool('change_title', {
|
||||
description: 'Change the title of the current HAPI chat session. Call once when the user\'s primary objective is clear; use a concise task title.',
|
||||
title: 'Change Chat Title',
|
||||
inputSchema: changeTitleInputSchema,
|
||||
@@ -303,7 +325,7 @@ function createHapiMcpServer(
|
||||
});
|
||||
}
|
||||
|
||||
mcp.registerTool<any, any>('display_image', {
|
||||
registerTool('display_image', {
|
||||
description: `Display a local image file to the human user inline in the current HAPI chat session. ${DISPLAY_IMAGE_PROMPT_CURSOR}`,
|
||||
title: 'Display Image',
|
||||
inputSchema: displayImageInputSchema,
|
||||
@@ -337,7 +359,7 @@ function createHapiMcpServer(
|
||||
}
|
||||
});
|
||||
|
||||
mcp.registerTool<any, any>('display_video', {
|
||||
registerTool('display_video', {
|
||||
description: `Display a local mp4 or webm file inline in the current HAPI chat session. ${DISPLAY_VIDEO_PROMPT_CURSOR}`,
|
||||
title: 'Display Video',
|
||||
inputSchema: displayVideoInputSchema,
|
||||
@@ -371,7 +393,7 @@ function createHapiMcpServer(
|
||||
}
|
||||
});
|
||||
|
||||
mcp.registerTool<any, any>('display_media', {
|
||||
registerTool('display_media', {
|
||||
description: `Send a local image, video, audio, or other file to the current HAPI chat session. Recognized media is shown inline; other files use a download card. ${DISPLAY_MEDIA_PROMPT_CURSOR}`,
|
||||
title: 'Display Media',
|
||||
inputSchema: displayMediaInputSchema,
|
||||
@@ -395,7 +417,7 @@ function createHapiMcpServer(
|
||||
});
|
||||
|
||||
if (!peerToolsDisabled) {
|
||||
mcp.registerTool<any, any>('ping_peer', {
|
||||
registerTool('ping_peer', {
|
||||
description: PING_PEER_TOOL_DESCRIPTION,
|
||||
title: 'Ping Peer Session',
|
||||
inputSchema: pingPeerInputSchema,
|
||||
@@ -438,7 +460,7 @@ function createHapiMcpServer(
|
||||
}
|
||||
});
|
||||
|
||||
mcp.registerTool<any, any>('spawn_peer', {
|
||||
registerTool('spawn_peer', {
|
||||
description: SPAWN_PEER_TOOL_DESCRIPTION,
|
||||
title: 'Spawn Peer Session',
|
||||
inputSchema: spawnPeerInputSchema,
|
||||
@@ -507,7 +529,7 @@ function createHapiMcpServer(
|
||||
}
|
||||
});
|
||||
|
||||
mcp.registerTool<any, any>('inspect_peer', {
|
||||
registerTool('inspect_peer', {
|
||||
description: INSPECT_PEER_TOOL_DESCRIPTION,
|
||||
title: 'Inspect Peer Session',
|
||||
inputSchema: inspectPeerInputSchema,
|
||||
@@ -546,7 +568,7 @@ function createHapiMcpServer(
|
||||
}
|
||||
});
|
||||
|
||||
mcp.registerTool<any, any>('list_peers', {
|
||||
registerTool('list_peers', {
|
||||
description: LIST_PEERS_TOOL_DESCRIPTION,
|
||||
title: 'List Peer Sessions',
|
||||
inputSchema: listPeersInputSchema,
|
||||
@@ -596,7 +618,7 @@ function createHapiMcpServer(
|
||||
|
||||
|
||||
if (skillLookup) {
|
||||
mcp.registerTool<any, any>('skill_lookup', {
|
||||
registerTool('skill_lookup', {
|
||||
description: 'Load a HAPI skill by exact name. When a user message starts with $name, call this tool with that name before acting.',
|
||||
title: 'Look Up Skill',
|
||||
inputSchema: skillLookupInputSchema,
|
||||
@@ -656,6 +678,26 @@ function readMcpSessionId(req: IncomingMessage): string | undefined {
|
||||
export async function startHappyServer(client: ApiSessionClient, options: StartHappyServerOptions = {}) {
|
||||
const emitTitleSummary = options.emitTitleSummary ?? true;
|
||||
const enableChangeTitle = options.enableChangeTitle ?? true;
|
||||
const requestedTools = options.enabledTools ? new Set(options.enabledTools) : null;
|
||||
const includeTool = (name: HapiMcpToolName): boolean =>
|
||||
requestedTools === null || requestedTools.has(name);
|
||||
const peerToolsDisabled = isPeerToolsDisabled();
|
||||
const toolNames: HapiMcpToolName[] = [];
|
||||
if (enableChangeTitle && includeTool('change_title')) toolNames.push('change_title');
|
||||
for (const name of ['display_image', 'display_video', 'display_media'] as const) {
|
||||
if (includeTool(name)) toolNames.push(name);
|
||||
}
|
||||
if (!peerToolsDisabled) {
|
||||
for (const name of ['list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer'] as const) {
|
||||
if (includeTool(name)) toolNames.push(name);
|
||||
}
|
||||
}
|
||||
if (options.skillLookup && includeTool('skill_lookup')) toolNames.push('skill_lookup');
|
||||
if (toolNames.length === 0) {
|
||||
throw new Error('startHappyServer requires at least one enabled tool');
|
||||
}
|
||||
const enabledTools = new Set(toolNames);
|
||||
|
||||
const transports = new Map<string, StreamableHTTPServerTransport>();
|
||||
const mcps = new Map<string, McpServer>();
|
||||
|
||||
@@ -666,6 +708,7 @@ export async function startHappyServer(client: ApiSessionClient, options: StartH
|
||||
enableChangeTitle,
|
||||
options.skillLookup,
|
||||
options.workingDirectory,
|
||||
enabledTools,
|
||||
options.onChangeTitle
|
||||
);
|
||||
const transport = new StreamableHTTPServerTransport({
|
||||
@@ -721,18 +764,6 @@ export async function startHappyServer(client: ApiSessionClient, options: StartH
|
||||
hapiMcpUrl: mcpUrl,
|
||||
}));
|
||||
|
||||
const peerToolsDisabled = isPeerToolsDisabled();
|
||||
const toolNames = [
|
||||
...(enableChangeTitle ? ['change_title'] : []),
|
||||
'display_image',
|
||||
'display_video',
|
||||
'display_media',
|
||||
...(peerToolsDisabled ? [] : (['list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer'] as const)),
|
||||
];
|
||||
if (options.skillLookup) {
|
||||
toolNames.push('skill_lookup');
|
||||
}
|
||||
|
||||
return {
|
||||
url: mcpUrl,
|
||||
toolNames,
|
||||
|
||||
@@ -3,66 +3,215 @@ import { mkdtemp, readdir, readFile, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { materializePiTitleExtension, PI_TITLE_EXTENSION_SOURCE } from './titleExtension';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { materializePiExtension, PI_EXTENSION_SOURCE } from './hapiExtension';
|
||||
|
||||
describe('pi title extension source', () => {
|
||||
describe('pi bundled extension source', () => {
|
||||
it('registers a namespaced hapi_change_title tool and applies it via setTitle', () => {
|
||||
expect(PI_TITLE_EXTENSION_SOURCE).toContain("name: TOOL_NAME");
|
||||
expect(PI_TITLE_EXTENSION_SOURCE).toContain("'hapi_change_title'");
|
||||
expect(PI_TITLE_EXTENSION_SOURCE).toContain('ctx.ui.setTitle');
|
||||
expect(PI_EXTENSION_SOURCE).toContain("name: TITLE_TOOL_NAME");
|
||||
expect(PI_EXTENSION_SOURCE).toContain("'hapi_change_title'");
|
||||
expect(PI_EXTENSION_SOURCE).toContain('ctx.ui.setTitle');
|
||||
});
|
||||
|
||||
it('uses the typebox specifier that old and new Pi loaders both resolve', () => {
|
||||
expect(PI_TITLE_EXTENSION_SOURCE).toContain("import { Type } from '@sinclair/typebox';");
|
||||
expect(PI_EXTENSION_SOURCE).toContain("import { Type } from '@sinclair/typebox';");
|
||||
});
|
||||
|
||||
it('injects the instruction on every turn, matching the persistent Claude/Codex rule', () => {
|
||||
expect(PI_TITLE_EXTENSION_SOURCE).toContain('## Session title');
|
||||
expect(PI_TITLE_EXTENSION_SOURCE).toContain('tool once');
|
||||
expect(PI_TITLE_EXTENSION_SOURCE).toContain('before_agent_start');
|
||||
expect(PI_TITLE_EXTENSION_SOURCE).not.toContain('titled');
|
||||
expect(PI_EXTENSION_SOURCE).toContain('## Session title');
|
||||
expect(PI_EXTENSION_SOURCE).toContain('tool once');
|
||||
expect(PI_EXTENSION_SOURCE).toContain('before_agent_start');
|
||||
expect(PI_EXTENSION_SOURCE).not.toContain('titled');
|
||||
});
|
||||
});
|
||||
|
||||
describe('materializePiTitleExtension', () => {
|
||||
it('writes the extension into the target dir and returns its path', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'hapi-pi-title-'));
|
||||
const file = await materializePiTitleExtension(dir);
|
||||
|
||||
expect(file).toBe(join(dir, 'hapi-title-extension.ts'));
|
||||
type ExtensionHarness = {
|
||||
handlers: Map<string, Array<(event: any, ctx?: any) => any>>;
|
||||
registerTool: ReturnType<typeof vi.fn>;
|
||||
registerMcpServer: ReturnType<typeof vi.fn> | null;
|
||||
prompt: () => string;
|
||||
};
|
||||
|
||||
function loadExtension(options: {
|
||||
registerMcpServer?: boolean | (() => void);
|
||||
} = {}): ExtensionHarness {
|
||||
const handlers = new Map<string, Array<(event: any, ctx?: any) => any>>();
|
||||
const registerTool = vi.fn();
|
||||
const registerMcpServer = options.registerMcpServer === false
|
||||
? null
|
||||
: vi.fn(typeof options.registerMcpServer === 'function' ? options.registerMcpServer : undefined);
|
||||
const pi: Record<string, unknown> = {
|
||||
on: (event: string, handler: (event: any, ctx?: any) => any) => {
|
||||
const current = handlers.get(event) ?? [];
|
||||
current.push(handler);
|
||||
handlers.set(event, current);
|
||||
},
|
||||
registerTool,
|
||||
};
|
||||
if (registerMcpServer) pi.registerMcpServer = registerMcpServer;
|
||||
|
||||
const load = new Function('Type', 'fs', PI_EXTENSION_SOURCE
|
||||
.replace("import { Type } from '@sinclair/typebox';", '')
|
||||
.replace('export default function', 'function')
|
||||
.replace("await import('node:fs/promises')", 'fs')
|
||||
+ '\nreturn hapiPiExtension;');
|
||||
load({ Object: (properties: unknown) => properties, String: (options: unknown) => options }, fs)(pi);
|
||||
|
||||
return {
|
||||
handlers,
|
||||
registerTool,
|
||||
registerMcpServer,
|
||||
prompt: () => {
|
||||
const handler = handlers.get('before_agent_start')?.[0];
|
||||
if (!handler) throw new Error('before_agent_start handler missing');
|
||||
return handler({ systemPrompt: 'base' }).systemPrompt as string;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('pi peer MCP integration', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('registers the HAPI MCP URL as a direct Pi MCP server', () => {
|
||||
vi.stubEnv('HAPI_PI_MCP_URL', 'http://127.0.0.1:12345/');
|
||||
const harness = loadExtension();
|
||||
|
||||
expect(harness.registerMcpServer).toHaveBeenCalledWith('hapi', {
|
||||
url: 'http://127.0.0.1:12345/',
|
||||
exposure: 'direct',
|
||||
description: 'HAPI peer-session tools for this HAPI session',
|
||||
});
|
||||
expect(harness.prompt()).toContain('mcp__hapi__inspect_peer');
|
||||
expect(harness.prompt()).toContain('mcp__hapi__ping_peer');
|
||||
expect(harness.prompt()).toContain('mcp__hapi__spawn_peer');
|
||||
expect(harness.prompt()).toContain('mcp__hapi__list_peers');
|
||||
expect(harness.prompt()).not.toContain('Peer session tools (inspect_peer / ping_peer / list_peers) are disabled');
|
||||
});
|
||||
|
||||
it('honors HAPI_DISABLE_PEER_TOOLS and injects the disabled steer', () => {
|
||||
vi.stubEnv('HAPI_PI_MCP_URL', 'http://127.0.0.1:12345/');
|
||||
vi.stubEnv('HAPI_DISABLE_PEER_TOOLS', 'yes');
|
||||
const harness = loadExtension();
|
||||
|
||||
expect(harness.registerMcpServer).not.toHaveBeenCalled();
|
||||
expect(harness.prompt()).toContain('Peer session tools (inspect_peer / ping_peer / list_peers) are disabled');
|
||||
expect(harness.prompt()).not.toContain('mcp__hapi__inspect_peer');
|
||||
});
|
||||
|
||||
it('falls back cleanly on older Pi versions without registerMcpServer', () => {
|
||||
vi.stubEnv('HAPI_PI_MCP_URL', 'http://127.0.0.1:12345/');
|
||||
const harness = loadExtension({ registerMcpServer: false });
|
||||
|
||||
expect(harness.registerMcpServer).toBeNull();
|
||||
expect(harness.prompt()).toContain('Peer session tools (inspect_peer / ping_peer / list_peers) are disabled');
|
||||
});
|
||||
|
||||
it('fails closed when MCP server registration throws', () => {
|
||||
vi.stubEnv('HAPI_PI_MCP_URL', 'http://127.0.0.1:12345/');
|
||||
vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
|
||||
const harness = loadExtension({
|
||||
registerMcpServer: () => {
|
||||
throw new Error('server name collision');
|
||||
},
|
||||
});
|
||||
|
||||
expect(harness.prompt()).toContain('Peer session tools (inspect_peer / ping_peer / list_peers) are disabled');
|
||||
});
|
||||
|
||||
it.each([
|
||||
'mcp__hapi__inspect_peer',
|
||||
'mcp__hapi__ping_peer',
|
||||
'mcp__hapi__spawn_peer',
|
||||
])('requires confirmation for %s', async (toolName) => {
|
||||
vi.stubEnv('HAPI_PI_MCP_URL', 'http://127.0.0.1:12345/');
|
||||
const harness = loadExtension();
|
||||
const toolCall = harness.handlers.get('tool_call')![0];
|
||||
const confirm = vi.fn(async () => false);
|
||||
|
||||
const result = await toolCall({ toolName, input: {} }, { ui: { confirm } });
|
||||
|
||||
expect(confirm).toHaveBeenCalledWith('Allow HAPI peer tool?', expect.stringContaining('HAPI session'));
|
||||
expect(result).toEqual({
|
||||
block: true,
|
||||
reason: 'The user did not approve this HAPI peer tool call.',
|
||||
});
|
||||
});
|
||||
|
||||
it('allows a confirmed sensitive peer tool and does not gate list_peers', async () => {
|
||||
vi.stubEnv('HAPI_PI_MCP_URL', 'http://127.0.0.1:12345/');
|
||||
const harness = loadExtension();
|
||||
const toolCall = harness.handlers.get('tool_call')![0];
|
||||
const confirm = vi.fn(async () => true);
|
||||
|
||||
expect(await toolCall({ toolName: 'mcp__hapi__ping_peer', input: {} }, { ui: { confirm } })).toBeUndefined();
|
||||
expect(confirm).toHaveBeenCalledTimes(1);
|
||||
expect(await toolCall({ toolName: 'mcp__hapi__list_peers', input: {} }, { ui: { confirm } })).toBeUndefined();
|
||||
expect(confirm).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('fails closed when confirmation is unavailable', async () => {
|
||||
vi.stubEnv('HAPI_PI_MCP_URL', 'http://127.0.0.1:12345/');
|
||||
vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
|
||||
const harness = loadExtension();
|
||||
const toolCall = harness.handlers.get('tool_call')![0];
|
||||
|
||||
expect(await toolCall({ toolName: 'mcp__hapi__inspect_peer', input: {} }, { ui: {} })).toMatchObject({
|
||||
block: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not gate peer tools when MCP registration did not succeed', async () => {
|
||||
vi.stubEnv('HAPI_PI_MCP_URL', 'http://127.0.0.1:12345/');
|
||||
const harness = loadExtension({ registerMcpServer: false });
|
||||
const toolCall = harness.handlers.get('tool_call')![0];
|
||||
const confirm = vi.fn(async () => true);
|
||||
|
||||
expect(await toolCall({ toolName: 'mcp__hapi__ping_peer', input: {} }, { ui: { confirm } })).toBeUndefined();
|
||||
expect(confirm).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
describe('materializePiExtension', () => {
|
||||
it('writes the extension into the target dir and returns its path', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'hapi-pi-extension-'));
|
||||
const file = await materializePiExtension(dir);
|
||||
|
||||
expect(file).toBe(join(dir, 'hapi-extension.ts'));
|
||||
const content = await readFile(file, 'utf8');
|
||||
expect(content).toContain('hapiTitleExtension');
|
||||
expect(content).toContain('hapiPiExtension');
|
||||
expect(content).toContain('hapi_change_title');
|
||||
});
|
||||
|
||||
it('creates missing directories and is idempotent', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'hapi-pi-title-'));
|
||||
const root = await mkdtemp(join(tmpdir(), 'hapi-pi-extension-'));
|
||||
const dir = join(root, 'runtime', '0.0.0-test', 'pi');
|
||||
|
||||
const first = await materializePiTitleExtension(dir);
|
||||
const second = await materializePiTitleExtension(dir);
|
||||
const first = await materializePiExtension(dir);
|
||||
const second = await materializePiExtension(dir);
|
||||
|
||||
expect(first).toBe(second);
|
||||
});
|
||||
|
||||
it('publishes atomically under concurrent launches', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'hapi-pi-title-'));
|
||||
const dir = await mkdtemp(join(tmpdir(), 'hapi-pi-extension-'));
|
||||
|
||||
const paths = await Promise.all(
|
||||
Array.from({ length: 8 }, () => materializePiTitleExtension(dir)),
|
||||
Array.from({ length: 8 }, () => materializePiExtension(dir)),
|
||||
);
|
||||
|
||||
expect(new Set(paths).size).toBe(1);
|
||||
const content = await readFile(join(dir, 'hapi-title-extension.ts'), 'utf8');
|
||||
expect(content).toBe(PI_TITLE_EXTENSION_SOURCE);
|
||||
const content = await readFile(join(dir, 'hapi-extension.ts'), 'utf8');
|
||||
expect(content).toBe(PI_EXTENSION_SOURCE);
|
||||
const entries = await readdir(dir);
|
||||
expect(entries.filter((name) => name.endsWith('.tmp'))).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps injecting the instruction on later turns so renames stay possible', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'hapi-pi-title-'));
|
||||
const file = await materializePiTitleExtension(dir);
|
||||
const dir = await mkdtemp(join(tmpdir(), 'hapi-pi-extension-'));
|
||||
const file = await materializePiExtension(dir);
|
||||
|
||||
// The materialized source only imports typebox, which cannot be
|
||||
// resolved from an arbitrary temp dir; stub it so the module loads as ESM.
|
||||
@@ -71,7 +220,7 @@ describe('materializePiTitleExtension', () => {
|
||||
"import { Type } from '@sinclair/typebox';",
|
||||
'const Type = { Object: (properties) => ({ properties }), String: (options) => options };',
|
||||
);
|
||||
const moduleFile = join(dir, 'hapi-title-extension.mjs');
|
||||
const moduleFile = join(dir, 'hapi-extension.mjs');
|
||||
await writeFile(moduleFile, testable, 'utf8');
|
||||
const mod = await import(pathToFileURL(moduleFile).href);
|
||||
|
||||
@@ -134,11 +283,11 @@ type ImageResult = { content: Array<{ type: string; text?: string; data?: string
|
||||
|
||||
function loadImageTool(fileSystem: unknown = fs) {
|
||||
// Execute the bundled source with only its external dependencies injected.
|
||||
const load = new Function('Type', 'fs', PI_TITLE_EXTENSION_SOURCE
|
||||
const load = new Function('Type', 'fs', PI_EXTENSION_SOURCE
|
||||
.replace("import { Type } from '@sinclair/typebox';", '')
|
||||
.replace('export default function', 'function')
|
||||
.replace("await import('node:fs/promises')", 'fs')
|
||||
+ '\nreturn hapiTitleExtension;');
|
||||
+ '\nreturn hapiPiExtension;');
|
||||
const registerTool = vi.fn();
|
||||
load({ Object: (properties: unknown) => properties, String: (options: unknown) => options }, fileSystem)({
|
||||
on: vi.fn(), registerTool,
|
||||
@@ -2,45 +2,107 @@ import { access, mkdir, rename, unlink, writeFile } from 'node:fs/promises';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { join } from 'node:path';
|
||||
import { configuration } from '@/configuration';
|
||||
import { buildSessionCitationSteerInstruction, SESSION_CITATION_DISABLED_STEER } from '@hapi/protocol/sessionCitation';
|
||||
import packageJson from '../../package.json';
|
||||
|
||||
const SESSION_CITATION_INSTRUCTION = buildSessionCitationSteerInstruction({
|
||||
inspectTool: 'mcp__hapi__inspect_peer',
|
||||
pingTool: 'mcp__hapi__ping_peer',
|
||||
listPeersTool: 'mcp__hapi__list_peers',
|
||||
spawnTool: 'mcp__hapi__spawn_peer',
|
||||
});
|
||||
|
||||
/**
|
||||
* Source of the bundled Pi extension that gives Pi sessions the same
|
||||
* auto-titling capability the Claude/Codex/OpenCode launchers already have:
|
||||
* a `hapi_change_title` tool callable by the model plus a persistent
|
||||
* system-prompt instruction. The title is applied via `ctx.ui.setTitle()`,
|
||||
* which the Pi extension UI bridge (`extensionUiHandler`) renames via
|
||||
* `metadata.name` (same field as web rename / MCP `change_title`).
|
||||
* Source of the bundled Pi extension.
|
||||
*
|
||||
* Pi's RPC mode does not support HAPI's MCP stdio bridge, but current Pi
|
||||
* releases expose built-in MCP support to extensions. This extension registers
|
||||
* HAPI's local streamable HTTP MCP server, gates the sensitive peer tools behind
|
||||
* the RPC confirmation UI, and injects the same title/citation instructions as
|
||||
* the other launchers.
|
||||
*
|
||||
* The source is kept as a string (plain JS, no template literals) so it can be
|
||||
* materialized to disk at launch time and passed to `pi --extension`, including
|
||||
* for Bun-compiled builds where virtual-fs module paths are not readable by the
|
||||
* child process.
|
||||
*/
|
||||
export const PI_TITLE_EXTENSION_SOURCE = `// Generated by HAPI - auto session titling for Pi sessions.
|
||||
export const PI_EXTENSION_SOURCE = `// Generated by HAPI - bundled Pi integration.
|
||||
import { Type } from '@sinclair/typebox';
|
||||
|
||||
const TOOL_NAME = 'hapi_change_title';
|
||||
const TITLE_TOOL_NAME = 'hapi_change_title';
|
||||
const MCP_SERVER_NAME = 'hapi';
|
||||
const PEER_TOOL_NAMES = Object.freeze({
|
||||
inspect: 'mcp__hapi__inspect_peer',
|
||||
ping: 'mcp__hapi__ping_peer',
|
||||
spawn: 'mcp__hapi__spawn_peer'
|
||||
});
|
||||
const PEER_TOOL_APPROVALS = Object.freeze({
|
||||
[PEER_TOOL_NAMES.inspect]: 'Read metadata and recent messages from another HAPI session?',
|
||||
[PEER_TOOL_NAMES.ping]: 'Send a message to another HAPI session?',
|
||||
[PEER_TOOL_NAMES.spawn]: 'Create a new HAPI session with an injected work request?'
|
||||
});
|
||||
|
||||
const TITLE_INSTRUCTION = [
|
||||
'',
|
||||
'',
|
||||
'## Session title',
|
||||
'For a new chat, call the "' + TOOL_NAME + '" tool once after the user\\'s initial request is clear - ideally as your very first action, before starting any work - and set a concise task title.',
|
||||
'For a new chat, call the "' + TITLE_TOOL_NAME + '" tool once after the user\\'s initial request is clear - ideally as your very first action, before starting any work - and set a concise task title.',
|
||||
'Do not rename the chat for routine progress, substeps, implementation details, or a slightly better wording.',
|
||||
'Rename only when the user\\'s primary objective changes substantially and the existing title would be misleading.'
|
||||
].join('\\n');
|
||||
|
||||
export default function hapiTitleExtension(pi) {
|
||||
const SESSION_CITATION_INSTRUCTION = ${JSON.stringify(SESSION_CITATION_INSTRUCTION)};
|
||||
const SESSION_CITATION_DISABLED_INSTRUCTION = ${JSON.stringify(SESSION_CITATION_DISABLED_STEER)};
|
||||
|
||||
export default function hapiPiExtension(pi) {
|
||||
const peerToolsDisabled = ['true', '1', 'yes'].includes(
|
||||
String(process.env.HAPI_DISABLE_PEER_TOOLS || '').toLowerCase()
|
||||
);
|
||||
const mcpUrl = String(process.env.HAPI_PI_MCP_URL || '').trim();
|
||||
let peerToolsAvailable = false;
|
||||
|
||||
if (!peerToolsDisabled && mcpUrl && typeof pi.registerMcpServer === 'function') {
|
||||
try {
|
||||
pi.registerMcpServer(MCP_SERVER_NAME, {
|
||||
url: mcpUrl,
|
||||
exposure: 'direct',
|
||||
description: 'HAPI peer-session tools for this HAPI session'
|
||||
});
|
||||
peerToolsAvailable = true;
|
||||
} catch (error) {
|
||||
// Fail closed: without a registered server the citation instruction
|
||||
// below must tell the model that peer tools are unavailable.
|
||||
process.stderr.write('[hapi] Failed to register peer MCP server: ' + (error && error.message ? error.message : String(error)) + '\\n');
|
||||
}
|
||||
}
|
||||
|
||||
pi.on('before_agent_start', function (event) {
|
||||
const citationInstruction = peerToolsAvailable
|
||||
? SESSION_CITATION_INSTRUCTION
|
||||
: SESSION_CITATION_DISABLED_INSTRUCTION;
|
||||
return { systemPrompt: event.systemPrompt + TITLE_INSTRUCTION + '\\n\\n' + citationInstruction };
|
||||
});
|
||||
|
||||
pi.on('tool_call', async function (event, ctx) {
|
||||
const approvalMessage = peerToolsAvailable ? PEER_TOOL_APPROVALS[event.toolName] : undefined;
|
||||
if (!approvalMessage) return;
|
||||
|
||||
let approved = false;
|
||||
try {
|
||||
approved = await ctx.ui.confirm('Allow HAPI peer tool?', approvalMessage);
|
||||
} catch (error) {
|
||||
process.stderr.write('[hapi] Peer tool confirmation failed closed: ' + (error && error.message ? error.message : String(error)) + '\\n');
|
||||
}
|
||||
if (!approved) {
|
||||
return { block: true, reason: 'The user did not approve this HAPI peer tool call.' };
|
||||
}
|
||||
});
|
||||
|
||||
// The tool name is namespaced ('hapi_change_title', matching the OpenCode
|
||||
// launcher convention) so user extensions registering their own tools
|
||||
// cannot collide with it.
|
||||
pi.on('before_agent_start', function (event) {
|
||||
return { systemPrompt: event.systemPrompt + TITLE_INSTRUCTION };
|
||||
});
|
||||
|
||||
pi.registerTool({
|
||||
name: TOOL_NAME,
|
||||
name: TITLE_TOOL_NAME,
|
||||
label: 'Change Chat Title',
|
||||
description: "Change the title of the current chat session. Call once when the user's primary objective is clear (usually right after the first exchange); use a concise task title. Do not rename for routine progress or substeps.",
|
||||
parameters: Type.Object({
|
||||
@@ -132,26 +194,21 @@ async function fileExists(path: string): Promise<boolean> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Materializes the bundled title extension under the HAPI runtime dir and
|
||||
* returns the path that should be passed to `pi --extension`.
|
||||
* Materializes the bundled HAPI extension under the HAPI runtime dir and
|
||||
* returns the path passed to `pi --extension`.
|
||||
*
|
||||
* The file is published atomically (write to a unique temp file, then rename):
|
||||
* concurrent Pi launches share the same versioned path, a plain write could be
|
||||
* observed half-written by another process, and Pi treats extension-load
|
||||
* errors as fatal. If `rename` loses a race against another launcher that
|
||||
* already published the file, the existing copy is kept.
|
||||
*
|
||||
* Layout mirrors `runtimePath()` in compiled builds
|
||||
* (`<happyHomeDir>/runtime/<version>/pi/`), but is derived from
|
||||
* `configuration.happyHomeDir` directly so dev runs (where `runtimePath()`
|
||||
* points into the repo) and test runs stay side-effect free.
|
||||
*/
|
||||
export async function materializePiTitleExtension(targetDir?: string): Promise<string> {
|
||||
export async function materializePiExtension(targetDir?: string): Promise<string> {
|
||||
const dir = targetDir ?? join(configuration.happyHomeDir, 'runtime', packageJson.version, 'pi');
|
||||
const file = join(dir, 'hapi-title-extension.ts');
|
||||
const file = join(dir, 'hapi-extension.ts');
|
||||
await mkdir(dir, { recursive: true });
|
||||
const temporaryFile = `${file}.${process.pid}.${randomUUID()}.tmp`;
|
||||
await writeFile(temporaryFile, PI_TITLE_EXTENSION_SOURCE, 'utf8');
|
||||
await writeFile(temporaryFile, PI_EXTENSION_SOURCE, 'utf8');
|
||||
try {
|
||||
await rename(temporaryFile, file);
|
||||
} catch (error) {
|
||||
@@ -1,6 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
type TransportOptions = { command: string; args: string[]; cwd: string };
|
||||
type TransportOptions = { command: string; args: string[]; cwd: string; env?: NodeJS.ProcessEnv };
|
||||
type LifecycleOptions = { stopKeepAlive: () => void };
|
||||
|
||||
const harness = vi.hoisted(() => ({
|
||||
@@ -12,6 +12,9 @@ const harness = vi.hoisted(() => ({
|
||||
rpcHandlers: new Map<string, (payload: unknown) => Promise<unknown>>(),
|
||||
killCount: 0,
|
||||
cleanupCount: 0,
|
||||
happyServerStartCount: 0,
|
||||
happyServerStopCount: 0,
|
||||
happyServerOptions: null as Record<string, unknown> | null,
|
||||
session: {
|
||||
sessionId: 'hapi-session-test',
|
||||
keepAlive: vi.fn(),
|
||||
@@ -60,8 +63,22 @@ vi.mock('@/ui/logger', () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('./titleExtension', () => ({
|
||||
materializePiTitleExtension: vi.fn(async () => '/materialized/hapi-title-extension.ts'),
|
||||
vi.mock('./hapiExtension', () => ({
|
||||
materializePiExtension: vi.fn(async () => '/materialized/hapi-extension.ts'),
|
||||
}));
|
||||
|
||||
vi.mock('@/claude/utils/startHappyServer', () => ({
|
||||
startHappyServer: vi.fn(async (_session: unknown, options: Record<string, unknown>) => {
|
||||
harness.happyServerStartCount += 1;
|
||||
harness.happyServerOptions = options;
|
||||
return {
|
||||
url: 'http://127.0.0.1:45678/',
|
||||
toolNames: ['list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer'],
|
||||
stop: () => {
|
||||
harness.happyServerStopCount += 1;
|
||||
},
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('./piTransport', () => ({
|
||||
@@ -99,8 +116,35 @@ import { buildPiCommandInventory, failPiHistoryOnRestoreError, formatPiUserMessa
|
||||
import { bootstrapExistingSession } from '@/agent/sessionFactory';
|
||||
import { PiSession } from './session';
|
||||
import { PiHistoryRestoreError } from './conversationHistory';
|
||||
import { startHappyServer } from '@/claude/utils/startHappyServer';
|
||||
|
||||
import { RPC_METHODS } from '@hapi/protocol/rpcMethods';
|
||||
|
||||
const originalDisablePeerTools = process.env.HAPI_DISABLE_PEER_TOOLS;
|
||||
const originalPiMcpUrl = process.env.HAPI_PI_MCP_URL;
|
||||
|
||||
beforeEach(() => {
|
||||
delete process.env.HAPI_DISABLE_PEER_TOOLS;
|
||||
delete process.env.HAPI_PI_MCP_URL;
|
||||
harness.happyServerStartCount = 0;
|
||||
harness.happyServerStopCount = 0;
|
||||
harness.happyServerOptions = null;
|
||||
vi.mocked(startHappyServer).mockClear();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
if (originalDisablePeerTools === undefined) {
|
||||
delete process.env.HAPI_DISABLE_PEER_TOOLS;
|
||||
} else {
|
||||
process.env.HAPI_DISABLE_PEER_TOOLS = originalDisablePeerTools;
|
||||
}
|
||||
if (originalPiMcpUrl === undefined) {
|
||||
delete process.env.HAPI_PI_MCP_URL;
|
||||
} else {
|
||||
process.env.HAPI_PI_MCP_URL = originalPiMcpUrl;
|
||||
}
|
||||
});
|
||||
|
||||
async function replyToHistoryCommand(type: 'get_entries' | 'get_fork_messages', occurrence: number, data: unknown): Promise<void> {
|
||||
await vi.waitFor(() => {
|
||||
expect(harness.sent.filter((item) => (item as { type?: string }).type === type)).toHaveLength(occurrence);
|
||||
@@ -182,6 +226,10 @@ describe('runPi startup', () => {
|
||||
harness.session.updateMetadata.mockReset();
|
||||
harness.killCount = 0;
|
||||
harness.cleanupCount = 0;
|
||||
harness.happyServerStartCount = 0;
|
||||
harness.happyServerStopCount = 0;
|
||||
harness.happyServerOptions = null;
|
||||
vi.mocked(startHappyServer).mockClear();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
@@ -190,7 +238,7 @@ describe('runPi startup', () => {
|
||||
|
||||
expect(harness.transportOptions).toMatchObject({
|
||||
command: 'pi',
|
||||
args: ['--mode', 'rpc', '--extension', '/materialized/hapi-title-extension.ts'],
|
||||
args: ['--mode', 'rpc', '--extension', '/materialized/hapi-extension.ts'],
|
||||
cwd: '/work',
|
||||
});
|
||||
expect(harness.sent).toEqual([
|
||||
@@ -200,6 +248,29 @@ describe('runPi startup', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('starts a peer-only HAPI MCP server and passes its URL to Pi', async () => {
|
||||
await runPi({ workingDirectory: '/work' });
|
||||
|
||||
expect(startHappyServer).toHaveBeenCalledWith(harness.session, {
|
||||
enableChangeTitle: false,
|
||||
enabledTools: ['list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer'],
|
||||
});
|
||||
expect(harness.transportOptions?.env).toMatchObject({
|
||||
HAPI_PI_MCP_URL: 'http://127.0.0.1:45678/',
|
||||
});
|
||||
expect(harness.happyServerStopCount).toBe(1);
|
||||
});
|
||||
|
||||
it('does not start the peer MCP server when HAPI_DISABLE_PEER_TOOLS is set', async () => {
|
||||
process.env.HAPI_DISABLE_PEER_TOOLS = '1';
|
||||
process.env.HAPI_PI_MCP_URL = 'http://127.0.0.1:1/stale';
|
||||
await runPi({ workingDirectory: '/work' });
|
||||
|
||||
expect(startHappyServer).not.toHaveBeenCalled();
|
||||
expect(harness.transportOptions?.env?.HAPI_PI_MCP_URL).toBeUndefined();
|
||||
expect(harness.happyServerStopCount).toBe(0);
|
||||
});
|
||||
|
||||
it('resumes with --session and keeps the session selected by Pi', async () => {
|
||||
await runPi({
|
||||
workingDirectory: '/work',
|
||||
@@ -208,7 +279,7 @@ describe('runPi startup', () => {
|
||||
|
||||
expect(harness.transportOptions).toMatchObject({
|
||||
command: 'pi',
|
||||
args: ['--mode', 'rpc', '--extension', '/materialized/hapi-title-extension.ts', '--session', 'pi-session-123'],
|
||||
args: ['--mode', 'rpc', '--extension', '/materialized/hapi-extension.ts', '--session', 'pi-session-123'],
|
||||
cwd: '/work',
|
||||
});
|
||||
expect(harness.sent).toEqual([
|
||||
|
||||
+19
-4
@@ -17,7 +17,9 @@ import type { PiImageContent, PiThinkingLevel } from './types';
|
||||
import { parsePiSpecialCommand, parseLeadingSlashName, type PiSpecialCommand } from './specialCommands';
|
||||
import { PiPromptQueue, isPiSpecialQueued, type PiPreparedPrompt } from './promptQueue';
|
||||
import { PiSteerDispatcher } from './steerDispatcher';
|
||||
import { materializePiTitleExtension } from './titleExtension';
|
||||
import { materializePiExtension } from './hapiExtension';
|
||||
import { startHappyServer } from '@/claude/utils/startHappyServer';
|
||||
import { isPeerToolsDisabled } from '@/modules/common/peerTools';
|
||||
import { getBuiltinSlashCommands, mergeSlashCommands } from '@hapi/protocol/slashCommands';
|
||||
import type { ListPiModelsResponse, PiCommandSummary, PiModelSummary, SlashCommand, SlashCommandsResponse } from '@hapi/protocol/apiTypes';
|
||||
import { RPC_METHODS } from '@hapi/protocol/rpcMethods';
|
||||
@@ -243,16 +245,28 @@ export async function runPi(opts: {
|
||||
expectedNativeSessionId: opts.resumeSessionId,
|
||||
});
|
||||
|
||||
const titleExtensionPath = await materializePiTitleExtension();
|
||||
const transportArgs = ['--mode', 'rpc', '--extension', titleExtensionPath];
|
||||
const extensionPath = await materializePiExtension();
|
||||
const peerMcpServer = isPeerToolsDisabled()
|
||||
? null
|
||||
: await startHappyServer(apiSession, {
|
||||
enableChangeTitle: false,
|
||||
enabledTools: ['list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer'],
|
||||
});
|
||||
const transportArgs = ['--mode', 'rpc', '--extension', extensionPath];
|
||||
if (opts.resumeSessionId) {
|
||||
transportArgs.push('--session', opts.resumeSessionId);
|
||||
}
|
||||
const transportEnv = { ...process.env };
|
||||
if (peerMcpServer) {
|
||||
transportEnv.HAPI_PI_MCP_URL = peerMcpServer.url;
|
||||
} else {
|
||||
delete transportEnv.HAPI_PI_MCP_URL;
|
||||
}
|
||||
const transport = new PiTransport({
|
||||
command: getAgentLaunchCommand('pi'),
|
||||
args: transportArgs,
|
||||
cwd: workingDirectory,
|
||||
env: process.env,
|
||||
env: transportEnv,
|
||||
});
|
||||
const conversationHistory = new PiConversationHistory(
|
||||
piSession,
|
||||
@@ -315,6 +329,7 @@ export async function runPi(opts: {
|
||||
cleanupInitiated = true;
|
||||
steerDispatcher?.stop();
|
||||
piSession.cancelReadyGate();
|
||||
peerMcpServer?.stop();
|
||||
await lifecycle.cleanupAndExit();
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user