Files
hapi/cli/src/pi/hapiExtension.ts
T
JeeandGitHub a7e472bb39 refactor(cli): move media guidance into tools and infer job countdowns (#2416)
* feat(cli): render local Markdown links as attachments

* fix(prompt): auto-infer sleep durations and deduplicate MCP media guidance

* fix(prompt): rely on tools and attachment fallback instead of injecting media guidance into system prompt

* fix(attachments): gate fallback by session permission mode and track denied paths

* fix(pr-review): track permission denials, exclude sidechains, and support multi-arg sleep

* fix(attachments): canonicalize denied paths, track local Claude & Codex approvals, exclude sidechain

* fix(attachments): canonicalize symlinks, hook Cursor PermissionAdapter, process Pi/ACP terminal snapshots

* fix(attachments): recognize ACP display titles, block file-read denials, document relative countdowns

* fix(attachments): normalize ACP read permissions, track native Claude denials, align sleep instruction

* fix(attachments): normalize AcpPermissionHandler read denials without rawInput

* fix(attachments): preserve SharedCodexPermissions file read/display denials

* fix(attachments): recognize qualified MCP read tools and preserve terminal-resolved Codex denials

* fix(attachments): support multi-file path extraction, avoid duplicate web markdown images, guard terminal resolution

* fix(attachments): multi-file denial tracking, guard terminal Codex approvals, conditionally suppress web cards

* fix(attachments): nested multi-file denial extraction, resolve terminal Codex approvals, parent-relative image card retention

* fix(attachments): recursive multi-file path extraction, native Codex approval reconciliation, decode percent-encoded targets

* fix(codex): reconcile native execution in root.ts, track webApproval vs terminal denial

* fix(codex): verify thread ownership and successful execution before clearing denials in root.ts

* fix(codex): validate MCP result error envelopes and retain web cards for non-image targets

* fix(cli): support underscored MCP server names, accept null error on Codex success, and deduplicate across cold resumes

* refactor(cli): keep media delivery in tool contracts and remove link fallback

* test(cli): avoid assuming a typed MCP config description

* fix(cli): anchor inferred sleep countdowns to child launch
2026-11-13 18:49:36 +08:00

419 lines
20 KiB
TypeScript

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,
INSPECT_PEER_TOOL_DESCRIPTION,
PING_PEER_TOOL_DESCRIPTION,
LIST_PEERS_TOOL_DESCRIPTION,
SPAWN_PEER_TOOL_DESCRIPTION,
SESSION_ID_PREFIX_PARAM_DESCRIPTION,
PEER_DELIVERY_MODE_DESCRIPTION,
PEER_WAKE_PARAM_DESCRIPTION,
PEER_WAIT_FOR_REPLY_PARAM_DESCRIPTION,
LIST_PEERS_INCLUDE_INACTIVE_PARAM_DESCRIPTION,
} from '@hapi/protocol/sessionCitation';
import packageJson from '../../package.json';
import { PI_DISPLAY_IMAGE_TOOL_DESCRIPTION } from '@/modules/common/displayToolDescriptions';
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.
*
* 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_EXTENSION_SOURCE = `// Generated by HAPI - bundled Pi integration.
import { Type } from '@sinclair/typebox';
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',
list: 'mcp__hapi__list_peers'
});
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 "' + 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');
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) {
if (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');
}
} else if (typeof pi.registerTool === 'function') {
try {
registerDirectPeerTools(pi, mcpUrl);
peerToolsAvailable = true;
} catch (error) {
process.stderr.write('[hapi] Failed to register peer tools via registerTool: ' + (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.' };
}
});
function registerDirectPeerTools(piInstance, serverUrl) {
let cachedMcpSessionId = null;
async function callMcpTool(toolName, args, signal) {
async function doCall(sessionId) {
const headers = {
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream'
};
if (sessionId) headers['mcp-session-id'] = sessionId;
return await fetch(serverUrl, {
method: 'POST',
headers,
body: JSON.stringify({
jsonrpc: '2.0',
method: 'tools/call',
params: {
name: toolName,
arguments: args || {}
},
id: Math.floor(Math.random() * 100000)
}),
signal
});
}
let res = null;
if (cachedMcpSessionId) {
res = await doCall(cachedMcpSessionId);
// Only clear session and re-initialize if the server explicitly rejected the session id
// with 404 before execution. Do not retry ambiguous transport/network errors.
if (res.status === 404) {
cachedMcpSessionId = null;
res = null;
}
}
if (!res) {
const initRes = await fetch(serverUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream'
},
body: JSON.stringify({
jsonrpc: '2.0',
method: 'initialize',
params: {
protocolVersion: '2024-11-05',
capabilities: {},
clientInfo: { name: 'hapi-pi-extension', version: '1.0.0' }
},
id: 1
}),
signal
});
if (!initRes.ok) {
throw new Error('MCP initialize failed (' + initRes.status + ' ' + initRes.statusText + ')');
}
cachedMcpSessionId = initRes.headers.get('mcp-session-id') || null;
res = await doCall(cachedMcpSessionId);
}
if (!res.ok) {
throw new Error('MCP tools/call failed (' + res.status + ' ' + res.statusText + ')');
}
const text = await res.text();
let data = null;
for (const line of text.split('\\n')) {
if (line.startsWith('data: ')) {
try {
data = JSON.parse(line.slice(6));
break;
} catch {}
}
}
if (!data && text.trim().startsWith('{')) {
try {
data = JSON.parse(text);
} catch {}
}
if (!data) {
throw new Error('Invalid MCP response format');
}
if (data.error) {
throw new Error(data.error.message || 'MCP tool error');
}
return data.result;
}
async function executePeerTool(toolName, params, signal) {
const result = await callMcpTool(toolName, params, signal);
if (result && result.isError) {
const errorText = Array.isArray(result.content)
? result.content.map((c) => (c && c.text) || '').join('\\n').trim()
: 'Tool reported failure';
throw new Error(errorText || 'Tool reported failure');
}
return {
content: result && Array.isArray(result.content) ? result.content : [{ type: 'text', text: String(result && result.content ? result.content : result) }],
details: {},
isError: false
};
}
function extractSignal(third, fifth) {
if (third && typeof third === 'object' && 'aborted' in third) return third;
if (fifth && typeof fifth === 'object' && 'aborted' in fifth) return fifth;
return undefined;
}
piInstance.registerTool({
name: PEER_TOOL_NAMES.inspect,
label: 'Inspect Peer Session',
description: ${JSON.stringify(INSPECT_PEER_TOOL_DESCRIPTION)},
parameters: Type.Object({
sessionIdPrefix: Type.String({ minLength: 1, description: ${JSON.stringify(SESSION_ID_PREFIX_PARAM_DESCRIPTION)} }),
messageLimit: Type.Optional(Type.Integer({ minimum: 1, maximum: 100, description: 'Recent message page size (default 30, max 100). Text snippets only.' }))
}),
async execute(_toolCallId, params, third, _fourth, fifth) {
return await executePeerTool('inspect_peer', params, extractSignal(third, fifth));
}
});
piInstance.registerTool({
name: PEER_TOOL_NAMES.ping,
label: 'Ping Peer Session',
description: ${JSON.stringify(PING_PEER_TOOL_DESCRIPTION)},
parameters: Type.Object({
sessionIdPrefix: Type.String({ minLength: 1, description: ${JSON.stringify(SESSION_ID_PREFIX_PARAM_DESCRIPTION)} }),
message: Type.String({ minLength: 1, description: 'Message text to deliver to the target session' }),
deliveryMode: Type.Optional(Type.String({ description: ${JSON.stringify(PEER_DELIVERY_MODE_DESCRIPTION)} })),
wake: Type.Optional(Type.Boolean({ description: ${JSON.stringify(PEER_WAKE_PARAM_DESCRIPTION)} })),
waitForReply: Type.Optional(Type.Boolean({ description: ${JSON.stringify(PEER_WAIT_FOR_REPLY_PARAM_DESCRIPTION)} }))
}),
async execute(_toolCallId, params, third, _fourth, fifth) {
return await executePeerTool('ping_peer', params, extractSignal(third, fifth));
}
});
piInstance.registerTool({
name: PEER_TOOL_NAMES.list,
label: 'List Peer Sessions',
description: ${JSON.stringify(LIST_PEERS_TOOL_DESCRIPTION)},
parameters: Type.Object({
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 100, description: 'Max sessions to return (default 30, max 100). Newest updatedAt first.' })),
includeInactive: Type.Optional(Type.Boolean({ description: ${JSON.stringify(LIST_PEERS_INCLUDE_INACTIVE_PARAM_DESCRIPTION)} }))
}),
async execute(_toolCallId, params, third, _fourth, fifth) {
return await executePeerTool('list_peers', params, extractSignal(third, fifth));
}
});
piInstance.registerTool({
name: PEER_TOOL_NAMES.spawn,
label: 'Spawn Peer Session',
description: ${JSON.stringify(SPAWN_PEER_TOOL_DESCRIPTION)},
parameters: Type.Object({
directory: Type.String({ minLength: 1, description: 'Working directory for the new session on the target machine (must exist there)' }),
message: Type.String({ minLength: 1, description: 'Required first user message (the remit). Empty spawn is a failed spawn.' }),
name: Type.Optional(Type.String({ description: 'Session display name' })),
machine: Type.Optional(Type.String({ description: 'Optional target runner machine UUID or hostname' })),
agent: Type.Optional(Type.String({ description: 'Agent flavor override' })),
model: Type.Optional(Type.String({ description: 'Model override' })),
effort: Type.Optional(Type.String({ description: 'Effort override' })),
sessionType: Type.Optional(Type.String({ description: 'simple or worktree' })),
permissionMode: Type.Optional(Type.String({ description: 'Permission mode for the new session' })),
waitForReply: Type.Optional(Type.Boolean({ description: ${JSON.stringify(PEER_WAIT_FOR_REPLY_PARAM_DESCRIPTION)} }))
}),
async execute(_toolCallId, params, third, _fourth, fifth) {
return await executePeerTool('spawn_peer', params, extractSignal(third, fifth));
}
});
}
// 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.registerTool({
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({
title: Type.String({ description: 'Short task title, ideally under 20 characters, no quotes or trailing punctuation.' })
}),
// Positional compatibility: current Pi calls
// (toolCallId, params, signal, onUpdate, ctx) while legacy releases
// called (toolCallId, params, onUpdate, ctx, signal). Normalize the
// context by looking for the object that carries the ui bridge.
async execute(_toolCallId, params, _third, fourth, fifth) {
const ctx = fifth && typeof fifth === 'object' && 'ui' in fifth ? fifth : fourth;
const title = String((params && params.title) || '').replace(/\\s+/g, ' ').trim().slice(0, 80);
if (!title) {
return { content: [{ type: 'text', text: 'Error: title must not be empty' }], details: {} };
}
// HAPI only launches this extension in RPC mode; do not gate on
// ctx.hasUI, which older RPC releases report as false even though
// ctx.ui.setTitle() emits the extension UI event.
if (ctx && ctx.ui) ctx.ui.setTitle(title);
// Pi's setTitle RPC is one-way: do not claim Hub persistence.
return { content: [{ type: 'text', text: 'Title update requested: ' + title + '. HAPI keeps the current title if the user has locked it.' }], details: {} };
}
});
pi.registerTool({
name: 'hapi_display_image',
label: 'Display Image',
promptSnippet: 'Show a local image to the user in the HAPI chat.',
description: ${JSON.stringify(PI_DISPLAY_IMAGE_TOOL_DESCRIPTION)},
parameters: Type.Object({
path: Type.String({ description: 'Absolute filesystem path of the local image to display (png, jpeg, gif or webp, up to 25 MiB).' })
}),
async execute(_toolCallId, params) {
const filePath = String((params && params.path) || '').trim();
if (!filePath) {
return { content: [{ type: 'text', text: 'Error: path must be non-empty' }], details: {}, isError: true };
}
const { constants, open } = await import('node:fs/promises');
let bytes;
try {
// One descriptor and a fixed buffer keep replacement/growth bounded.
const handle = await open(filePath, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
try {
const meta = await handle.stat();
if (!meta.isFile()) throw new Error('Path is not a regular file');
if (meta.size > 25 * 1024 * 1024) throw new Error('File exceeds the 25 MiB display limit');
bytes = Buffer.alloc(meta.size);
for (let offset = 0; offset < bytes.length;) {
const { bytesRead } = await handle.read(bytes, offset, bytes.length - offset, offset);
if (bytesRead === 0) throw new Error('File changed while reading');
offset += bytesRead;
}
if ((await handle.stat()).size !== meta.size) throw new Error('File changed while reading');
} finally {
await handle.close();
}
} catch (error) {
const detail = error && error.message ? error.message : String(error);
return { content: [{ type: 'text', text: 'Failed to read file: ' + detail }], details: {}, isError: true };
}
const mimeType = detectImageMime(bytes);
if (!mimeType) {
return { content: [{ type: 'text', text: 'Unsupported image content (png, jpeg, gif or webp only)' }], details: {}, isError: true };
}
return {
content: [{ type: 'image', data: bytes.toString('base64'), mimeType: mimeType }],
details: {}
};
}
});
}
function detectImageMime(bytes) {
if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47 && bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a) return 'image/png';
if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';
if (bytes.length >= 6 && bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38 && (bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) return 'image/gif';
if (bytes.length >= 12 && bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 && bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) return 'image/webp';
return null;
}
`;
async function fileExists(path: string): Promise<boolean> {
try {
await access(path);
return true;
} catch {
return false;
}
}
/**
* 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.
*/
export async function materializePiExtension(targetDir?: string): Promise<string> {
const dir = targetDir ?? join(configuration.happyHomeDir, 'runtime', packageJson.version, 'pi');
const file = join(dir, 'hapi-extension.ts');
await mkdir(dir, { recursive: true });
const temporaryFile = `${file}.${process.pid}.${randomUUID()}.tmp`;
await writeFile(temporaryFile, PI_EXTENSION_SOURCE, 'utf8');
try {
await rename(temporaryFile, file);
} catch (error) {
if (!(await fileExists(file))) throw error;
await unlink(temporaryFile).catch(() => {});
}
return file;
}