diff --git a/cli/README.md b/cli/README.md index 21749222..ad75ef9d 100644 --- a/cli/README.md +++ b/cli/README.md @@ -42,15 +42,15 @@ Choose a supported coding agent from your terminal and control its sessions remo - `hapi dsh` - Start DeepSeek Harness through ACP. See `src/dsh/runDsh.ts`. DSH is remote-only and its ACP server must be configured separately. - `hapi resume [sessionId]` - List resumable sessions for this machine or resume one locally. -- `hapi ping-peer ` - Resume (if needed) and message another session. Prefer this or MCP `ping_peer` / `list_peers` over reinventing JWT+curl. Also `--message-file` / `--list`. +- `hapi ping-peer ` - Message another session. Inactive targets are refused (exit 5) unless `--wake` resumes them first. Prefer this or MCP `ping_peer` / `list_peers` over reinventing JWT+curl. Also `--message-file` / `--list [--all]` (active sessions with machine and cwd; `--all` includes inactive). - `hapi spawn-peer --dir PATH --name TITLE --message-file -` - Spawn a session and deliver a required first message. Optional `--machine ID|hostname` targets another runner (resolved via GET /api/machines); `--dir` must exist on the target. Machine spawn HTTP 200 is not a working peer; this command fails if the remit does not land. Prefer MCP `spawn_peer`. - `hapi usage [--since 24h|7d||] [--until …] [--json]` - When agents were working across every machine on the hub, from `GET /api/activity`. `--json` prints one `hapi.activity.v1` report for other tools (time trackers); errors go to stderr with exit codes 2 (arguments), 3 (no token or refused), 4 (hub too old), 1 (other). - `hapi inspect-peer ` - Read-only peer metadata + recent message text (no resume). Prefer this or MCP `inspect_peer` when a user cites `[title](/sessions/)` or Copy-reference `See session "…" (/sessions/) for context`. `/sessions/` is a hub path, not a local file. Optional `--limit`. - `hapi set-mode ` - Change the permission mode of an existing session, like the web permission picker. Active sessions switch immediately; inactive ones use it on next resume. An invalid mode prints the modes allowed for that agent. Peer messages default to `auto`: use the target's live state to steer an active -Codex turn when steering is available; otherwise queue, resuming an inactive -session if needed. Auto currently queues for all other agent flavors. Prefer +Codex turn when steering is available; otherwise queue. Auto currently queues +for all other agent flavors. Prefer auto for routine collaboration when queueing is an acceptable fallback. Use explicit `queue` for non-urgent updates that can wait. Use `steer` for important, time-sensitive findings the peer needs to know now, not after its @@ -61,6 +61,14 @@ turn; it does not abort that turn or guarantee an immediate response. MCP `ping_ the same optional `deliveryMode: "auto" | "queue" | "steer"` field. Auto is resolved by the peer sender; ordinary web/native chat delivery is unchanged. +Peer messages never wake an inactive session by default: `ping_peer` refuses +with `inactive` and sends nothing. Pass MCP `wake: true` (CLI `--wake`) only +when the user asked or the handed-off work requires that peer to act. Agents +should message only peers tied to their task (a cited session, their Parent, +peers they spawned or were handed off to), `inspect_peer` an unfamiliar peer's +machine, cwd, and recent work before messaging it, and never broadcast. +`list_peers` returns active sessions only unless `includeInactive: true`. + ```bash hapi ping-peer 'The dependency is ready' --delivery-mode auto hapi ping-peer 'Run the next check' --delivery-mode queue diff --git a/cli/src/claude/utils/startHappyServer.test.ts b/cli/src/claude/utils/startHappyServer.test.ts index fc456ce6..108a7339 100644 --- a/cli/src/claude/utils/startHappyServer.test.ts +++ b/cli/src/claude/utils/startHappyServer.test.ts @@ -158,7 +158,7 @@ describe('startHappyServer skill_lookup', () => { arguments: { sessionIdPrefix: 'peer-id', message: 'hello', ...(deliveryMode ? { deliveryMode } : {}) } }) as ToolResult expect(result.isError).toBe(false) - expect(ping).toHaveBeenCalledWith({ sessionIdPrefix: 'peer-id', message: 'hello', deliveryMode }) + expect(ping).toHaveBeenCalledWith({ sessionIdPrefix: 'peer-id', message: 'hello', deliveryMode, wake: false }) expect(result.content?.[0]?.text).toBe(delivery === 'accepted' ? 'Accepted for peer-id (Peer) localId=ping-peer-test — delivery shows in the recipient chat when its runtime consumes it' : `${delivery} to peer-id (Peer) localId=ping-peer-test`) @@ -167,6 +167,44 @@ describe('startHappyServer skill_lookup', () => { } }) + it('forwards ping_peer wake only when explicitly requested', async () => { + const ping = vi.spyOn(peerMessages, 'pingPeer').mockResolvedValue({ + sessionId: 'peer-id', name: 'Peer', resumed: true, + localId: 'ping-peer-test', delivery: 'accepted' + }) + try { + const mcp = await connect(false) + const tools = await mcp.listTools() + const tool = tools.tools.find((entry) => entry.name === 'ping_peer') + expect(tool?.inputSchema.properties?.wake).toMatchObject({ type: 'boolean' }) + expect(tool?.description).toContain('Never broadcast') + const result = await mcp.callTool({ + name: 'ping_peer', + arguments: { sessionIdPrefix: 'peer-id', message: 'take over the build', wake: true } + }) as ToolResult + expect(result.isError).toBe(false) + expect(ping).toHaveBeenCalledWith({ + sessionIdPrefix: 'peer-id', message: 'take over the build', deliveryMode: undefined, wake: true + }) + expect(result.content?.[0]?.text).toContain('(resumed)') + } finally { + ping.mockRestore() + } + }) + + it('lists active peers by default and forwards includeInactive', async () => { + const list = vi.spyOn(peerMessages, 'listPeerSessions').mockResolvedValue([]) + try { + const mcp = await connect(false) + await mcp.callTool({ name: 'list_peers', arguments: {} }) + expect(list).toHaveBeenLastCalledWith(expect.objectContaining({ includeInactive: false })) + await mcp.callTool({ name: 'list_peers', arguments: { includeInactive: true } }) + expect(list).toHaveBeenLastCalledWith(expect.objectContaining({ includeInactive: true })) + } finally { + list.mockRestore() + } + }) + it('rejects invalid ping_peer delivery modes at the MCP boundary', async () => { const ping = vi.spyOn(peerMessages, 'pingPeer') try { diff --git a/cli/src/claude/utils/startHappyServer.ts b/cli/src/claude/utils/startHappyServer.ts index 8fdbd63b..a498080e 100644 --- a/cli/src/claude/utils/startHappyServer.ts +++ b/cli/src/claude/utils/startHappyServer.ts @@ -26,7 +26,10 @@ import { SESSION_NAME_MAX_LENGTH, toSessionSummaryMetadata } from '@hapi/protoco import { isPeerToolsDisabled } from "@/modules/common/peerTools"; import { INSPECT_PEER_TOOL_DESCRIPTION, + LIST_PEERS_INCLUDE_INACTIVE_PARAM_DESCRIPTION, + LIST_PEERS_TOOL_DESCRIPTION, PEER_DELIVERY_MODE_DESCRIPTION, + PEER_WAKE_PARAM_DESCRIPTION, PING_PEER_TOOL_DESCRIPTION, SESSION_ID_PREFIX_PARAM_DESCRIPTION, SPAWN_PEER_TOOL_DESCRIPTION, @@ -168,6 +171,7 @@ function createHapiMcpServer( sessionIdPrefix: z.string().trim().min(1).describe(SESSION_ID_PREFIX_PARAM_DESCRIPTION), message: z.string().min(1).describe('Message text to deliver to the target session'), deliveryMode: PeerDeliveryModeSchema.optional().describe(PEER_DELIVERY_MODE_DESCRIPTION), + wake: z.boolean().optional().describe(PEER_WAKE_PARAM_DESCRIPTION), }); const spawnPeerInputSchema: z.ZodTypeAny = z.object({ @@ -212,6 +216,7 @@ function createHapiMcpServer( limit: z.number().int().min(1).max(100).optional().describe( 'Max sessions to return (default 30, max 100). Newest updatedAt first.' ), + includeInactive: z.boolean().optional().describe(LIST_PEERS_INCLUDE_INACTIVE_PARAM_DESCRIPTION), }); async function displayInlineMedia( @@ -383,13 +388,14 @@ function createHapiMcpServer( description: PING_PEER_TOOL_DESCRIPTION, title: 'Ping Peer Session', inputSchema: pingPeerInputSchema, - }, async (args: { sessionIdPrefix: string; message: string; deliveryMode?: PeerDeliveryMode }) => { + }, async (args: { sessionIdPrefix: string; message: string; deliveryMode?: PeerDeliveryMode; wake?: boolean }) => { logger.debug('[hapiMCP] ping_peer:', args.sessionIdPrefix); try { const result = await pingPeer({ sessionIdPrefix: args.sessionIdPrefix, message: args.message, deliveryMode: args.deliveryMode, + wake: args.wake === true, }); return { content: [ @@ -530,25 +536,28 @@ function createHapiMcpServer( }); mcp.registerTool('list_peers', { - description: 'List peer HAPI sessions on the same hub/namespace (id prefix, active, flavor, name). Uses this session\'s hub credentials - works from runner-spawned agents without being on the hub host. Prefer this over shelling `hapi ping-peer --list`. Then call inspect_peer / ping_peer with a listed id, or spawn_peer to create a new peer with a remit.', + description: LIST_PEERS_TOOL_DESCRIPTION, title: 'List Peer Sessions', inputSchema: listPeersInputSchema, - }, async (args: { limit?: number }) => { + }, async (args: { limit?: number; includeInactive?: boolean }) => { logger.debug('[hapiMCP] list_peers'); try { const limit = args.limit ?? 30; + const includeInactive = args.includeInactive === true; const sessions = await listPeerSessions({ limit: peerListFetchLimit(limit, { excludeCaller: true }), + includeInactive, }); - const peers = sessions.filter((session) => session.id !== client.sessionId); - const hasMore = peers.length > limit; + const peerCount = sessions.filter((session) => session.id !== client.sessionId).length; return { content: [ { type: 'text' as const, - text: formatPeerSessionsList(peers, { + text: formatPeerSessionsList(sessions, { maxRows: limit, - hasMore, + hasMore: peerCount > limit, + excludeSessionId: client.sessionId, + includeInactive, }), }, ], diff --git a/cli/src/codex/happyMcpStdioBridge.ts b/cli/src/codex/happyMcpStdioBridge.ts index 7ff0218d..69573cbc 100644 --- a/cli/src/codex/happyMcpStdioBridge.ts +++ b/cli/src/codex/happyMcpStdioBridge.ts @@ -20,7 +20,10 @@ import { PeerDeliveryModeSchema } from '@/modules/pingPeer/deliveryMode'; import { DISPLAY_IMAGE_PROMPT_CURSOR, DISPLAY_MEDIA_PROMPT_CURSOR, DISPLAY_VIDEO_PROMPT_CURSOR } from '@/modules/common/displayImagePrompt'; import { INSPECT_PEER_TOOL_DESCRIPTION, + LIST_PEERS_INCLUDE_INACTIVE_PARAM_DESCRIPTION, + LIST_PEERS_TOOL_DESCRIPTION, PEER_DELIVERY_MODE_DESCRIPTION, + PEER_WAKE_PARAM_DESCRIPTION, PING_PEER_TOOL_DESCRIPTION, SESSION_ID_PREFIX_PARAM_DESCRIPTION, SPAWN_PEER_TOOL_DESCRIPTION, @@ -219,6 +222,7 @@ export async function runHappyMcpStdioBridge(argv: string[]): Promise { sessionIdPrefix: z.string().trim().min(1).describe(SESSION_ID_PREFIX_PARAM_DESCRIPTION), message: z.string().min(1).describe('Message text to deliver to the target session'), deliveryMode: PeerDeliveryModeSchema.optional().describe(PEER_DELIVERY_MODE_DESCRIPTION), + wake: z.boolean().optional().describe(PEER_WAKE_PARAM_DESCRIPTION), }); if (toolNames.has('ping_peer')) { @@ -332,13 +336,14 @@ export async function runHappyMcpStdioBridge(argv: string[]): Promise { limit: z.number().int().min(1).max(100).optional().describe( 'Max sessions to return (default 30, max 100). Newest updatedAt first.' ), + includeInactive: z.boolean().optional().describe(LIST_PEERS_INCLUDE_INACTIVE_PARAM_DESCRIPTION), }); if (toolNames.has('list_peers')) { server.registerTool( 'list_peers', { - description: 'List peer HAPI sessions on the same hub/namespace (id prefix, active, flavor, name). Uses this session\'s hub credentials - works from runner-spawned agents without being on the hub host. Prefer this over shelling `hapi ping-peer --list`. Then call inspect_peer / ping_peer with a listed id, or spawn_peer to create a new peer with a remit.', + description: LIST_PEERS_TOOL_DESCRIPTION, title: 'List Peer Sessions', inputSchema: listPeersInputSchema, }, diff --git a/cli/src/commands/pingPeer.test.ts b/cli/src/commands/pingPeer.test.ts index a2921a75..18d4cb76 100644 --- a/cli/src/commands/pingPeer.test.ts +++ b/cli/src/commands/pingPeer.test.ts @@ -9,6 +9,8 @@ describe('parsePingPeerArgs', () => { expect(parsePingPeerArgs(['05d9f0f2', 'hello'])).toEqual({ help: false, list: false, + all: false, + wake: false, sessionIdPrefix: '05d9f0f2', message: 'hello' }) @@ -18,6 +20,8 @@ describe('parsePingPeerArgs', () => { expect(parsePingPeerArgs(['abc', '--message-file', 'brief.md', '--wait', '30'])).toEqual({ help: false, list: false, + all: false, + wake: false, sessionIdPrefix: 'abc', messageFile: 'brief.md', waitActiveSecs: 30 @@ -25,10 +29,16 @@ describe('parsePingPeerArgs', () => { }) it('parses --list and --help', () => { - expect(parsePingPeerArgs(['--list'])).toEqual({ help: false, list: true }) + expect(parsePingPeerArgs(['--list'])).toEqual({ help: false, list: true, all: false, wake: false }) + expect(parsePingPeerArgs(['--list', '--all']).all).toBe(true) expect(parsePingPeerArgs(['--help']).help).toBe(true) }) + it('parses --wake as an explicit opt-in', () => { + expect(parsePingPeerArgs(['abc', 'hello']).wake).toBe(false) + expect(parsePingPeerArgs(['abc', 'hello', '--wake']).wake).toBe(true) + }) + it('rejects unknown flags', () => { expect(() => parsePingPeerArgs(['--host', 'evil'])).toThrow(PingPeerError) }) diff --git a/cli/src/commands/pingPeer.ts b/cli/src/commands/pingPeer.ts index f8f2660b..47b2e71d 100644 --- a/cli/src/commands/pingPeer.ts +++ b/cli/src/commands/pingPeer.ts @@ -1,6 +1,7 @@ import { readFile } from 'node:fs/promises' import chalk from 'chalk' import { PeerDeliveryModeSchema, type PeerDeliveryMode } from '@/modules/pingPeer/deliveryMode' +import { HAPI_SESSION_ID_ENV } from '@/agent/hapiSessionEnv' import { initializeToken } from '@/ui/tokenInit' import { PingPeerError, @@ -15,6 +16,8 @@ import type { CommandDefinition } from './types' type ParsedPingPeerArgs = { help: boolean list: boolean + all: boolean + wake: boolean sessionIdPrefix?: string message?: string messageFile?: string @@ -24,21 +27,24 @@ type ParsedPingPeerArgs = { function showHelp(): void { console.log(` -${chalk.bold('hapi ping-peer')} - Resume a HAPI session (if needed) and send it a message +${chalk.bold('hapi ping-peer')} - Send a message to another HAPI session ${chalk.bold('Usage:')} hapi ping-peer hapi ping-peer --delivery-mode auto|queue|steer + hapi ping-peer --wake # resume if inactive hapi ping-peer --message-file hapi ping-peer --message-file - # read message from stdin - hapi ping-peer --list + hapi ping-peer --list [--all] # active sessions; --all includes inactive ${chalk.bold('Notes:')} Do not reinvent JWT + curl for peer handoffs. Prefer this command or MCP ping_peer / list_peers. Resolves by id prefix (8 chars OK). Same hub token/namespace as this CLI. - Inactive sessions are resumed via POST /api/sessions/:id/resume, then messaged. + Message only peers tied to your task; never broadcast to the --list output. + Inactive targets are refused (exit 5) unless --wake, which resumes them via + POST /api/sessions/:id/resume first. Wake only when the peer must act, not for FYI. Delivery defaults to auto: steer a steerable active Codex turn, otherwise queue. - Auto resumes inactive targets; other agent flavors currently queue in auto mode. + Other agent flavors currently queue in auto mode. Use auto for routine collaboration when queueing is an acceptable fallback. Use queue for non-urgent updates that can wait. Use steer for important findings the peer needs to know now to adjust its current work, not after its current turn. @@ -61,7 +67,9 @@ ${chalk.bold('Env:')} export function parsePingPeerArgs(args: string[]): ParsedPingPeerArgs { const result: ParsedPingPeerArgs = { help: false, - list: false + list: false, + all: false, + wake: false } for (let i = 0; i < args.length; i++) { @@ -74,6 +82,14 @@ export function parsePingPeerArgs(args: string[]): ParsedPingPeerArgs { result.list = true continue } + if (arg === '--all') { + result.all = true + continue + } + if (arg === '--wake') { + result.wake = true + continue + } if (arg === '--delivery-mode' || arg.startsWith('--delivery-mode=')) { const value = arg === '--delivery-mode' ? args[++i] : arg.slice('--delivery-mode='.length) const parsed = PeerDeliveryModeSchema.safeParse(value) @@ -164,14 +180,19 @@ function envWaitActiveSecs(): number | undefined { return value } -async function handleList(): Promise { +async function handleList(includeInactive: boolean): Promise { const maxRows = 30 + const callerSessionId = process.env[HAPI_SESSION_ID_ENV]?.trim() || undefined const sessions = await listPeerSessions({ - limit: peerListFetchLimit(maxRows) + limit: peerListFetchLimit(maxRows, { excludeCaller: Boolean(callerSessionId) }), + includeInactive }) + const peerCount = sessions.filter((session) => session.id !== callerSessionId).length console.log(formatPeerSessionsList(sessions, { maxRows, - hasMore: sessions.length > maxRows + hasMore: peerCount > maxRows, + excludeSessionId: callerSessionId, + includeInactive })) } @@ -185,7 +206,7 @@ export async function handlePingPeerCommand(args: string[]): Promise { await initializeToken() if (parsed.list) { - await handleList() + await handleList(parsed.all) return } @@ -206,6 +227,7 @@ export async function handlePingPeerCommand(args: string[]): Promise { sessionIdPrefix: parsed.sessionIdPrefix, message, deliveryMode: parsed.deliveryMode, + wake: parsed.wake, waitActiveSecs: parsed.waitActiveSecs ?? envWaitActiveSecs(), onProgress: (line) => console.log(`hapi ping-peer: ${line}`) }) diff --git a/cli/src/modules/pingPeer/inspectPeer.test.ts b/cli/src/modules/pingPeer/inspectPeer.test.ts index 2745f14c..6b1ed824 100644 --- a/cli/src/modules/pingPeer/inspectPeer.test.ts +++ b/cli/src/modules/pingPeer/inspectPeer.test.ts @@ -295,6 +295,7 @@ describe('formatInspectPeerReport', () => { thinking: false, flavor: 'cursor', path: '/tmp/x', + machine: 'studio', lifecycleState: null, updatedAt: 1_700_000_000_000, messages: [ diff --git a/cli/src/modules/pingPeer/pingPeer.test.ts b/cli/src/modules/pingPeer/pingPeer.test.ts index 07ba01f1..271fcd89 100644 --- a/cli/src/modules/pingPeer/pingPeer.test.ts +++ b/cli/src/modules/pingPeer/pingPeer.test.ts @@ -195,6 +195,7 @@ describe('pingPeer', () => { sessionIdPrefix: 'aaaaaaaa', message: 'wake up', deliveryMode, + wake: true, accessToken: 'tok', apiUrl: 'http://hub.test', waitActiveSecs: 10, @@ -265,6 +266,7 @@ describe('pingPeer', () => { const result = await pingPeer({ sessionIdPrefix: 'bbbbbbbb', message: 'still here?', + wake: true, accessToken: 'tok', apiUrl: 'http://hub.test', waitActiveSecs: 10, @@ -505,15 +507,44 @@ describe('pingPeer', () => { await expect(pingPeer({ sessionIdPrefix: 'deadbeef', message: 'nudge', + wake: true, accessToken: 'tok', apiUrl: 'http://hub.test', http: http as never })).rejects.toMatchObject({ code: 'resume_failed' }) }) + it.each([ + ['list snapshot inactive', false], + ['stale active list snapshot', true] + ] as const)('refuses an inactive target without wake (%s) and never resumes or sends', async (_label, listedActive) => { + const sessionId = 'cafecafe-1111-1111-1111-111111111111' + const http = createHttpMock({ + post: (url) => { + if (url.endsWith('/api/auth')) { + return { status: 200, data: { token: 'jwt' } } + } + throw new Error(`unexpected POST ${url}`) + }, + get: (url) => url.endsWith('/api/sessions') + ? { status: 200, data: { sessions: [{ id: sessionId, active: listedActive, metadata: { name: 'Old peer' } }] } } + : { status: 200, data: { session: { id: sessionId, active: false, metadata: { name: 'Old peer' } } } } + }) + + await expect(pingPeer({ + sessionIdPrefix: 'cafecafe', + message: 'fyi: done', + accessToken: 'tok', + apiUrl: 'http://hub.test', + http: http as never + })).rejects.toMatchObject({ code: 'inactive', message: expect.stringContaining('no message sent') }) + expect(http.post.mock.calls.map(([url]) => url)).toEqual(['http://hub.test/api/auth']) + }) + it('maps exit codes', () => { expect(exitCodeForPingPeerError(new PingPeerError('bad_args', 'x'))).toBe(2) expect(exitCodeForPingPeerError(new PingPeerError('resume_failed', 'x'))).toBe(3) + expect(exitCodeForPingPeerError(new PingPeerError('inactive', 'x'))).toBe(5) expect(exitCodeForPingPeerError(new PingPeerError('timeout', 'x'))).toBe(4) expect(exitCodeForPingPeerError(new PingPeerError('send_failed', 'x'))).toBe(4) }) @@ -637,7 +668,7 @@ describe('pingPeer delivery modes', () => { } }) const result = await pingPeer({ - sessionIdPrefix: sessionId, message: 'update', deliveryMode: 'auto', + sessionIdPrefix: sessionId, message: 'update', deliveryMode: 'auto', wake: true, apiUrl: 'http://hub.test', accessToken: 'tok', http: http as never }) expect(result.resumed).toBe(true) @@ -792,16 +823,36 @@ describe('formatPeerSessionsList', () => { { id: 'bbbbbbbb-2222-2222-2222-222222222222', active: true, + thinking: true, updatedAt: 200, - metadata: { name: 'Fresh', flavor: 'cursor' } + machineLabel: 'studio', + metadata: { name: 'Fresh', flavor: 'cursor', path: '/repo/app', machineId: 'm-1' } } - ]) + ], { includeInactive: true }) const lines = text.split('\n') expect(lines[0]).toContain('bbbbbbbb-2222-2222-2222-222222222222') - expect(lines[0]).toContain('active=true') + expect(lines[0]).toContain('busy') expect(lines[0]).toContain('flavor=cursor') + expect(lines[0]).toContain('machine=studio') + expect(lines[0]).toContain('cwd=/repo/app') expect(lines[0]).toContain('Fresh') expect(lines[1]).toContain('aaaaaaaa-1111-1111-1111-111111111111') + expect(lines[1]).toContain('inactive') + expect(lines.at(-1)).toMatch(/not a recipient list/) + }) + + it('marks peers sharing the caller machine and cwd', async () => { + const { formatPeerSessionsList } = await import('./pingPeer') + const selfId = 'cccccccc-3333-3333-3333-333333333333' + const text = formatPeerSessionsList([ + { id: selfId, active: true, updatedAt: 3, metadata: { machineId: 'm-1', path: '/repo' } }, + { id: 'aaaaaaaa-1111-1111-1111-111111111111', active: true, updatedAt: 2, metadata: { name: 'Same', machineId: 'm-1', path: '/repo' } }, + { id: 'bbbbbbbb-2222-2222-2222-222222222222', active: true, updatedAt: 1, metadata: { name: 'Elsewhere', machineId: 'm-2', path: '/repo' } } + ], { excludeSessionId: selfId }) + const lines = text.split('\n') + expect(lines[0]).toContain('[same-machine, same-cwd]') + expect(lines[1]).not.toContain('same-') + expect(text).not.toContain(selfId) }) it('emits full session ids so colliding 8-char prefixes stay resolvable', async () => { @@ -822,7 +873,7 @@ describe('formatPeerSessionsList', () => { ]) expect(text).toContain('aaaaaaaa-1111-1111-1111-111111111111') expect(text).toContain('aaaaaaaa-2222-2222-2222-222222222222') - expect(text.split('\n')).toHaveLength(2) + expect(text.split('\n')).toHaveLength(3) }) it('uses summary.text when name is unset and collapses multiline titles', async () => { @@ -840,7 +891,7 @@ describe('formatPeerSessionsList', () => { expect(resolvePeerSessionLabel(session)).toBe('Peer with tabs') const text = formatPeerSessionsList([session]) expect(text).toContain('Peer with tabs') - expect(text.split('\n')).toHaveLength(1) + expect(text.split('\n')).toHaveLength(2) expect(text).not.toContain('(unnamed)') }) @@ -865,7 +916,8 @@ describe('formatPeerSessionsList', () => { it('respects maxRows and empty list', async () => { const { formatPeerSessionsList } = await import('./pingPeer') - expect(formatPeerSessionsList([])).toContain('No peer sessions') + expect(formatPeerSessionsList([])).toContain('No active peer sessions') + expect(formatPeerSessionsList([], { includeInactive: true })).toContain('No peer sessions') const many = Array.from({ length: 5 }, (_, i) => ({ id: `${String(i).padStart(8, '0')}-0000-0000-0000-000000000000`, active: true, @@ -873,7 +925,7 @@ describe('formatPeerSessionsList', () => { metadata: { name: `S${i}`, flavor: 'pi' as string | null } })) const text = formatPeerSessionsList(many, { maxRows: 2 }) - expect(text.split('\n').filter((l) => l.includes('active='))).toHaveLength(2) + expect(text.split('\n').filter((l) => l.includes('flavor='))).toHaveLength(2) }) it('omits the calling session even when it is newest', async () => { @@ -993,19 +1045,32 @@ describe('listSessions query params', () => { listParams.push(config?.params) return { status: 200, - data: { sessions: [{ id: sessionId, active: true, updatedAt: 1, metadata: { name: 'Z' } }] } + data: { sessions: [{ id: sessionId, active: true, updatedAt: 1, metadata: { name: 'Z', machineId: 'machine-1234' } }] } } } + if (url.endsWith('/api/machines')) { + return { status: 200, data: { machines: [{ id: 'machine-1234', metadata: { host: 'studio.local' } }] } } + } throw new Error(`unexpected GET ${url}`) } }) - await listPeerSessions({ + const listed = await listPeerSessions({ apiUrl: 'http://hub.test', accessToken: 'tok', http: listHttp as never, limit: 40 }) - expect(listParams[0]).toEqual({ limit: 40, order: 'updatedAt' }) + expect(listParams[0]).toEqual({ limit: 40, order: 'updatedAt', active: 'true' }) + expect(listed[0]?.machineLabel).toBe('studio.local') + + await listPeerSessions({ + apiUrl: 'http://hub.test', + accessToken: 'tok', + http: listHttp as never, + limit: 40, + includeInactive: true + }) + expect(listParams[1]).toEqual({ limit: 40, order: 'updatedAt' }) const pingHttp = createHttpMock({ post: (url, body) => { diff --git a/cli/src/modules/pingPeer/pingPeer.ts b/cli/src/modules/pingPeer/pingPeer.ts index 4dbe4933..f2a33b51 100644 --- a/cli/src/modules/pingPeer/pingPeer.ts +++ b/cli/src/modules/pingPeer/pingPeer.ts @@ -1,5 +1,5 @@ /** - * Resume-if-inactive + wait-active + POST /api/sessions/:id/messages, + * Opt-in resume (wake) + wait-active + POST /api/sessions/:id/messages, * plus read-only inspectPeer (GET session + messages, never resume) * and setPeerPermissionMode (POST /api/sessions/:id/permission-mode). * @@ -31,6 +31,7 @@ export type PingPeerErrorCode = | 'auth_failed' | 'not_found' | 'ambiguous' + | 'inactive' | 'resume_failed' | 'timeout' | 'send_failed' @@ -70,6 +71,7 @@ export type PingPeerSessionSummary = { name?: string flavor?: string | null path?: string | null + machineId?: string | null lifecycleState?: string | null piSessionId?: string cursorSessionId?: string | null @@ -85,6 +87,11 @@ export type PingPeerOptions = { sessionId?: string message: string deliveryMode?: PeerDeliveryMode + /** + * Resume an inactive target before sending. Default false: inactive + * targets are refused so stale/unrelated peers are not relaunched. + */ + wake?: boolean waitActiveSecs?: number /** * Fresh spawn: poll until active instead of POST /resume on the first @@ -132,6 +139,13 @@ export type ListPeerSessionsOptions = { limit?: number /** Hub sort before limit truncation. Peer discovery defaults to newest updatedAt. */ order?: 'updatedAt' + /** Include inactive sessions (default false: hub filters to active before limit). */ + includeInactive?: boolean +} + +/** Peer list row: hub session summary plus the resolved machine label. */ +export type PeerSessionListEntry = PingPeerSessionSummary & { + machineLabel?: string } const DEFAULT_WAIT_ACTIVE_SECS = 60 @@ -253,7 +267,7 @@ async function listSessions( apiUrl: string, jwt: string, http: AxiosInstance, - options: { limit?: number; order?: 'updatedAt' } = {} + options: { limit?: number; order?: 'updatedAt'; activeOnly?: boolean } = {} ): Promise { const params: Record = {} if (options.limit !== undefined) { @@ -262,6 +276,9 @@ async function listSessions( if (options.order !== undefined) { params.order = options.order } + if (options.activeOnly) { + params.active = 'true' + } const response = await http.get( `${apiUrl}/api/sessions`, { @@ -467,25 +484,81 @@ async function sendMessage( throw new PingPeerError('send_failed', `send failed: ${detail}`) } +/** + * Best-effort machineId → hostname map from GET /api/machines (online + * machines only). Labels are decoration; failures leave rows unlabeled. + */ +async function fetchMachineLabels( + apiUrl: string, + jwt: string, + http: AxiosInstance +): Promise> { + const labels = new Map() + try { + const response = await http.get(`${apiUrl}/api/machines`, { + headers: authHeaders(jwt), + timeout: 10_000, + validateStatus: () => true + }) + if (response.status < 200 || response.status >= 300) { + return labels + } + const machines = Array.isArray(response.data?.machines) ? response.data.machines : [] + for (const machine of machines) { + if (!isObject(machine) || typeof machine.id !== 'string') continue + const metadata = isObject(machine.metadata) ? machine.metadata : null + const label = typeof metadata?.displayName === 'string' && metadata.displayName.trim() + ? metadata.displayName.trim() + : typeof metadata?.host === 'string' && metadata.host.trim() + ? metadata.host.trim() + : null + if (label) { + labels.set(machine.id, label) + } + } + } catch { + // Unlabeled rows still carry the machine id prefix. + } + return labels +} + +function resolveMachineLabel(machineId: string | null | undefined, labels: Map): string | undefined { + if (!machineId) return undefined + return labels.get(machineId) ?? machineId.slice(0, 8) +} + export async function listPeerSessions( options: ListPeerSessionsOptions = {} -): Promise { +): Promise { assertPeerToolsEnabled() const apiUrl = resolveApiUrl(options.apiUrl) const accessToken = resolveAccessToken(options.accessToken) const http = options.http ?? axios const jwt = await exchangeJwt(apiUrl, accessToken, http) - return listSessions(apiUrl, jwt, http, { - limit: options.limit ?? 200, - order: options.order ?? 'updatedAt' - }) + const [sessions, machineLabels] = await Promise.all([ + listSessions(apiUrl, jwt, http, { + limit: options.limit ?? 200, + order: options.order ?? 'updatedAt', + activeOnly: !options.includeInactive + }), + fetchMachineLabels(apiUrl, jwt, http) + ]) + return sessions.map((session) => ({ + ...session, + machineLabel: resolveMachineLabel(session.metadata?.machineId, machineLabels) + })) } export type FormatPeerSessionsListOptions = { /** Max rows to print (default 30). */ maxRows?: number - /** Omit this session id (the caller) from the shortlist. */ + /** + * Omit this session id (the caller) from the shortlist. When the caller + * row is present, peers on its machine / cwd are marked for conflict triage. + */ excludeSessionId?: string + /** The list was fetched with inactive sessions included. */ + includeInactive?: boolean /** * When the fetch was intentionally bounded, signal overflow without claiming * an exact omitted count from the sample. @@ -525,27 +598,43 @@ export function resolvePeerSessionLabel(session: PingPeerSessionSummary): string : collapsed } +const PEER_LIST_FOOTER = + 'Directory, not a recipient list: message only peers tied to your task; ' + + 'inspect_peer an unfamiliar peer before messaging it, and never broadcast.' + /** * Human/agent-readable shortlist for MCP `list_peers` and `hapi ping-peer --list`. * Newest `updatedAt` first. Same hub/namespace as the caller credentials. */ export function formatPeerSessionsList( - sessions: PingPeerSessionSummary[], + sessions: PeerSessionListEntry[], options: FormatPeerSessionsListOptions = {} ): string { const maxRows = options.maxRows ?? 30 const excludeId = options.excludeSessionId?.trim() ?? '' + const caller = excludeId ? sessions.find((session) => session.id === excludeId) : undefined const filtered = excludeId ? sessions.filter((session) => session.id !== excludeId) : sessions if (filtered.length === 0) { - return 'No peer sessions found on this hub/namespace.' + return options.includeInactive + ? 'No peer sessions found on this hub/namespace.' + : 'No active peer sessions found on this hub/namespace.' } + const callerMachineId = caller?.metadata?.machineId ?? null + const callerPath = caller?.metadata?.path ?? null const sorted = [...filtered].sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0)) const rows = sorted.slice(0, Math.max(1, maxRows)).map((session) => { - const flavor = session.metadata?.flavor ?? '?' + const meta = session.metadata + const flavor = meta?.flavor ?? '?' const name = resolvePeerSessionLabel(session) - return ` ${session.id} active=${session.active} flavor=${flavor} ${name}` + const state = session.active ? (session.thinking ? 'busy' : 'idle') : 'inactive' + const sameMachine = Boolean(callerMachineId) && meta?.machineId === callerMachineId + const machine = session.machineLabel ?? meta?.machineId?.slice(0, 8) ?? '?' + const sameCwd = sameMachine && Boolean(callerPath) && meta?.path === callerPath + const marks = [sameMachine ? 'same-machine' : null, sameCwd ? 'same-cwd' : null].filter(Boolean) + return ` ${session.id} ${state} flavor=${flavor} machine=${machine} cwd=${meta?.path ?? '?'}` + + `${marks.length > 0 ? ` [${marks.join(', ')}]` : ''} ${name}` }) const omitted = sorted.length - rows.length if (options.hasMore) { @@ -553,12 +642,13 @@ export function formatPeerSessionsList( } else if (omitted > 0) { rows.push(` … ${omitted} more (narrow with inspect_peer / ping_peer by id)`) } + rows.push(PEER_LIST_FOOTER) return rows.join('\n') } function getSteeringUnavailableReason(session: PingPeerSessionSummary): string | null { if (!session.active) { - return 'Steering requires an active turn; target is inactive, no message sent. Use queue to resume it' + return 'Steering requires an active turn; target is inactive, no message sent. Use queue with wake to resume it' } if (!isSteeringSupportedForSession(session.metadata)) { return 'Steering is only supported for Claude, Pi, Codex, and Cursor ACP sessions; no message sent' @@ -618,7 +708,15 @@ export async function pingPeer(options: PingPeerOptions): Promise # Start a supported agent directly (required in scripts) hapi runner start # Run background service for remote session spawning -hapi ping-peer --list # Shell peer shortlist (prefer MCP list_peers in-session) +hapi ping-peer --list # Active peers with machine and cwd (prefer MCP list_peers in-session) ``` -MCP peer tools (same hub/namespace as the session): `list_peers` (discover), `inspect_peer` (read), `ping_peer` (message), `spawn_peer` (create with a required remit). These work from runner-spawned sessions even when the hub is on another host - see [Installation → Split hub + remote runner](./installation.md#split-hub-remote-runner-peer-discovery). Never treat machine-spawn HTTP 200 as a working peer. In-session `spawn_peer` auto-stamps a durable Parent `[title](/sessions/)` chip onto the remit (UUID is identity; titles are decoration). Runners that must keep agents out of other sessions' contexts can hide all four with `HAPI_DISABLE_PEER_TOOLS=1` - see [Installation → Disabling peer tools](./installation.md#disabling-peer-tools-on-a-runner). +MCP peer tools (same hub/namespace as the session): `list_peers` (find active peers), `inspect_peer` (read), `ping_peer` (message), `spawn_peer` (create with a required remit). `ping_peer` refuses inactive sessions unless `wake: true` (CLI `--wake`), so finished or unrelated peers are not relaunched; agents are told to message only peers tied to their task and never broadcast. These work from runner-spawned sessions even when the hub is on another host - see [Installation → Split hub + remote runner](./installation.md#split-hub-remote-runner-peer-discovery). Never treat machine-spawn HTTP 200 as a working peer. In-session `spawn_peer` auto-stamps a durable Parent `[title](/sessions/)` chip onto the remit (UUID is identity; titles are decoration). Runners that must keep agents out of other sessions' contexts can hide all four with `HAPI_DISABLE_PEER_TOOLS=1` - see [Installation → Disabling peer tools](./installation.md#disabling-peer-tools-on-a-runner). ### HAPI Hub diff --git a/hub/src/web/routes/sessions.test.ts b/hub/src/web/routes/sessions.test.ts index f7f6697d..a138c45c 100644 --- a/hub/src/web/routes/sessions.test.ts +++ b/hub/src/web/routes/sessions.test.ts @@ -2179,4 +2179,30 @@ describe('sessions routes', () => { expect(body.sessions.map((s) => s.id)).toEqual(['new-inactive']) }) + it('active=true filters inactive sessions before limit truncation', async () => { + const sessions = [ + createSession({ id: 'old-active', active: true, updatedAt: 10 }), + createSession({ id: 'new-inactive', active: false, updatedAt: 50 }), + createSession({ id: 'mid-active', active: true, updatedAt: 20 }) + ] + const engine = { + getSessionsByNamespace: () => sessions, + getFutureScheduledMessageCounts: (ids: string[]) => new Map(ids.map((id) => [id, 0])), + getNextScheduledAtBySessionIds: (_ids: string[]) => new Map(), + resolveSessionAccess: () => ({ ok: false, reason: 'not-found' as const }) + } as unknown as Partial + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createSessionsRoutes(() => engine as SyncEngine)) + + const response = await app.request('/api/sessions?limit=1&order=updatedAt&active=true') + expect(response.status).toBe(200) + const body = await response.json() as { sessions: Array<{ id: string }> } + expect(body.sessions.map((s) => s.id)).toEqual(['mid-active']) + }) + }) diff --git a/hub/src/web/routes/sessions.ts b/hub/src/web/routes/sessions.ts index db70c5ed..999f8d54 100644 --- a/hub/src/web/routes/sessions.ts +++ b/hub/src/web/routes/sessions.ts @@ -98,8 +98,11 @@ export function createSessionsRoutes(getSyncEngine: () => SyncEngine | null): Ho ? Math.min(500, Math.max(1, Math.floor(parsedLimit))) : null const order = c.req.query('order') + // Peer discovery lists live sessions only, filtered before limit truncation. + const activeOnly = c.req.query('active') === 'true' let sessionRecords = engine.getSessionsByNamespace(namespace) + .filter((session) => !activeOnly || session.active) .sort((a, b) => { // Peer discovery wants newest activity first before limit truncation. if (order === 'updatedAt') { diff --git a/shared/src/sessionCitation.ts b/shared/src/sessionCitation.ts index edfa150a..57d0781e 100644 --- a/shared/src/sessionCitation.ts +++ b/shared/src/sessionCitation.ts @@ -22,7 +22,8 @@ export const INSPECT_PEER_TOOL_DESCRIPTION = 'Fires when the user cites a peer via markdown [title](/sessions/), Copy-reference prose ' + 'See session "…" (/sessions/) for context, or a bare /sessions/. ' + 'Extract and pass it as sessionIdPrefix. /sessions/ is a hub path - do NOT Grep, Glob, or Read it as a local filesystem path. ' + - 'Read-only: does not resume. Prefer this (or `hapi inspect-peer`) over JWT+curl. ' + + 'Read-only: does not resume. Shows machine, cwd, and recent work - call it before messaging a peer you are not already working with. ' + + 'Prefer this (or `hapi inspect-peer`) over JWT+curl. ' + 'Never invent peer titles; always use the /sessions/ from the citation.' /** @@ -49,9 +50,36 @@ export const SPAWN_PEER_TOOL_DESCRIPTION = 'In-session calls auto-stamp a durable Parent [title](/sessions/) chip for this session onto the remit (fail-closed if parent id is missing). ' + PEER_IDENTITY_UUID_RULE +/** + * Who a peer message may go to. Peers carry other agents' work: an unrelated + * ping derails that agent, and pinging an inactive peer relaunches it. + */ +export const PEER_CONTACT_RULE = + 'Message only peers tied to your current task: a session the user cited, your Parent, or peers you spawned or were handed off to. ' + + 'Never broadcast to a list of peers - not for status updates, and not to announce exclusive work (simulator, device, port, branch, release). ' + + 'For any other peer, call inspect_peer first to see its machine, cwd, and recent work, and message it only when that work actually conflicts with or depends on yours ' + + '(e.g. same machine and resource, same checkout). ' + + 'Do not wake inactive peers for FYI, status, or done notes.' + +/** Zod `.describe` for ping_peer `wake`. */ +export const PEER_WAKE_PARAM_DESCRIPTION = + 'Resume the target if it is inactive. Default false: an inactive target is refused and no message is sent. ' + + 'Set true only when the user asked you to wake that peer or the work you hand off requires it to act; never for FYI, status, or done notes.' + +/** Zod `.describe` for list_peers `includeInactive`. */ +export const LIST_PEERS_INCLUDE_INACTIVE_PARAM_DESCRIPTION = + 'Also list inactive sessions (default false: active only). Inactive rows are history, not recipients.' + +/** MCP `list_peers` tool description. */ +export const LIST_PEERS_TOOL_DESCRIPTION = + 'Find a specific peer HAPI session on the same hub/namespace: id, active, busy/idle, flavor, machine, cwd, name. ' + + 'Active sessions only unless includeInactive. Uses this session\'s hub credentials - works from runner-spawned agents without being on the hub host. ' + + 'Prefer this over shelling `hapi ping-peer --list`. This is a directory, not a recipient list: ' + + PEER_CONTACT_RULE + /** Shared delivery guidance for the peer MCP schemas, descriptions, and prompts. */ export const PEER_DELIVERY_MODE_DESCRIPTION = - 'auto (default): steer an active Codex turn when steering is available; otherwise queue, resuming inactive peers. ' + + 'auto (default): steer an active Codex turn when steering is available; otherwise queue. ' + 'Auto currently queues for other agent flavors. Prefer auto for routine collaboration when queueing is an acceptable fallback. ' + 'queue: explicitly defer non-urgent updates that can wait instead of steering. ' + 'steer: use for important, time-sensitive findings the peer needs to know now, not after finishing its current turn ' + @@ -63,11 +91,13 @@ export const PEER_DELIVERY_MODE_DESCRIPTION = /** MCP `ping_peer` tool description (same citation forms as inspect_peer). */ export const PING_PEER_TOOL_DESCRIPTION = - 'Send a message to another HAPI session (peer handoff / nudge). Resolves by session id prefix, resumes if inactive, then POSTs on the same hub/namespace. ' + + 'Send a message to another HAPI session (peer handoff / nudge). Resolves by session id prefix, then POSTs on the same hub/namespace. ' + + 'Inactive targets are refused unless wake=true. ' + 'When the user cites a peer via [title](/sessions/), Copy-reference prose See session "…" (/sessions/) for context, or a bare /sessions/, ' + 'extract and pass it as sessionIdPrefix. /sessions/ is a hub path - do NOT search the local filesystem for it. ' + 'Prefer this (or `hapi ping-peer`) over reinventing JWT+curl. Targets another session - not the current chat. ' + PEER_IDENTITY_UUID_RULE + ' ' + + PEER_CONTACT_RULE + ' ' + `Select deliveryMode: ${PEER_DELIVERY_MODE_DESCRIPTION}` /** Zod `.describe` for sessionIdPrefix on inspect_peer / ping_peer. */ @@ -200,12 +230,14 @@ export function buildSessionCitationSteerInstruction(tools: SessionCitationSteer `/sessions/ is a HAPI hub path, not a local filesystem path - do not Grep, Glob, or Read it as a file. ` + `Call "${tools.inspectTool}" with sessionIdPrefix= to read metadata and recent messages; ` + `call "${tools.pingTool}" with sessionIdPrefix= and a message to nudge or hand off. ` + + `${PEER_CONTACT_RULE} ` + + `An inactive peer is refused unless you pass wake=true; set it only when the user asked or the handed-off work requires that peer to act. ` + `Select deliveryMode: ${PEER_DELIVERY_MODE_DESCRIPTION} ` + - `Prefer these over JWT+curl. Shell fallbacks: hapi inspect-peer / hapi ping-peer --delivery-mode auto.` + `Prefer these over JWT+curl. Shell fallbacks: hapi inspect-peer / hapi ping-peer --delivery-mode auto [--wake].` if (tools.listPeersTool) { text += - ` To discover peers without a citation, call "${tools.listPeersTool}" ` + - `(same hub/namespace; works from runner-spawned sessions). ` + + ` To find a specific peer without a citation, call "${tools.listPeersTool}" ` + + `(active sessions on the same hub/namespace; works from runner-spawned sessions) - it is a directory, not a recipient list. ` + `Shell fallback: hapi ping-peer --list.` } if (tools.spawnTool) {