From f34ff13fcef57598053e737693db8e661bf8b1ef Mon Sep 17 00:00:00 2001 From: SSU-WEI HUANG Date: Mon, 9 Nov 2026 12:33:20 +0800 Subject: [PATCH] feat(peer): forward peer replies back to the caller with waitForReply (#2167) * feat(peer): spawn_peer and reply forwarding for peer sessions Peer sessions could only fire messages at each other: the caller had to poll inspect_peer to learn that a peer finished, and nothing woke it once it ended its turn. There was also no way to start a peer for new work. - spawn_peer starts a session on the caller's machine (directory and agent default to the caller's) and sends it a task. - ping_peer gains waitForReply. - In both cases the caller's CLI watches the peer and, when its turn ends, posts the peer's latest reply into the caller session, which starts the caller's next turn. spawn_peer needs manual approval like ping_peer. No hub changes. * refactor(peer): drop own spawn_peer; add waitForReply to upstream spawn_peer Upstream #1922 ships spawn_peer (spawn, rename, remit delivery, fresh-child wait, manual approval). Remove this PR's duplicate spawnPeer and keep only reply forwarding: spawnPeer now returns the remit's ping-peer localId and resolved flavor, and MCP spawn_peer/ping_peer share one waitForReply hook. Add a steered-task attribution test. Co-Authored-By: Claude * fix(peer): keep waiting for a task an offline peer has not read The hub keeps unconsumed peer tasks for replay, so a peer that goes offline before reading the task can still run it after a resume. Only a stop after consumption ends the reply watch. Co-Authored-By: Claude --------- Co-authored-by: Claude --- cli/README.md | 4 + cli/src/claude/claudeRemote.test.ts | 43 ++++ cli/src/claude/claudeRemote.ts | 2 + cli/src/claude/utils/startHappyServer.test.ts | 21 +- cli/src/claude/utils/startHappyServer.ts | 28 ++- cli/src/codex/happyMcpStdioBridge.ts | 3 + cli/src/modules/pingPeer/peerReply.test.ts | 144 ++++++++++++ cli/src/modules/pingPeer/pingPeer.test.ts | 4 +- cli/src/modules/pingPeer/pingPeer.ts | 217 +++++++++++++++++- cli/src/modules/spawnPeer/spawnPeer.test.ts | 6 +- cli/src/modules/spawnPeer/spawnPeer.ts | 9 +- docs/guide/how-it-works.md | 2 +- shared/src/sessionCitation.ts | 4 + 13 files changed, 463 insertions(+), 24 deletions(-) create mode 100644 cli/src/modules/pingPeer/peerReply.test.ts diff --git a/cli/README.md b/cli/README.md index 0a53aafd..2a303e95 100644 --- a/cli/README.md +++ b/cli/README.md @@ -314,6 +314,10 @@ The first message is required and verified in the transcript before success; machine-spawn HTTP 200 alone does not prove the task was delivered. In-session spawns add a Parent `[title](/sessions/)` citation so parent renames do not change its identity. +With `waitForReply` on `ping_peer` or `spawn_peer`, the peer's reply is posted +back into the calling session when the peer's turn ends (Pi peers are not +supported). The caller's CLI process does the polling, so if that process exits +first, the reply is not posted back; it stays in the peer session. On a remote runner host, configure the matching hub URL and token so shell commands reach the same hub (`hapi auth login` saves the token). diff --git a/cli/src/claude/claudeRemote.test.ts b/cli/src/claude/claudeRemote.test.ts index 0fc5f097..6021f97f 100644 --- a/cli/src/claude/claudeRemote.test.ts +++ b/cli/src/claude/claudeRemote.test.ts @@ -125,6 +125,49 @@ describe('claudeRemote async message handling', () => { } }); + it('marks every follow-up turn as thinking until its result', async () => { + const querySpy = vi.spyOn(claudeSdk, 'query').mockImplementation(queryMock as typeof claudeSdk.query); + const { claudeRemote } = await import('./claudeRemote'); + const result = { type: 'result', subtype: 'success' } as unknown as SDKMessage; + queryMock.mockImplementationOnce(({ prompt }: { prompt: AsyncIterable }) => ({ + async *[Symbol.asyncIterator]() { + const promptIterator = prompt[Symbol.asyncIterator](); + await promptIterator.next(); + yield result; + await promptIterator.next(); + yield result; + } + })); + + const thinking: boolean[] = []; + let nextCallCount = 0; + try { + await claudeRemote({ + sessionId: 'session-1', + path: process.cwd(), + mcpServers: {}, + claudeEnvVars: {}, + claudeArgs: [], + allowedTools: [], + hookSettingsPath: '/tmp/hook.json', + canCallTool: async () => ({ behavior: 'allow', updatedInput: {} }), + nextMessage: async () => nextCallCount++ < 2 + ? { message: `turn ${nextCallCount}`, mode: { permissionMode: 'default' } } + : null, + onReady: () => {}, + isAborted: () => false, + onSessionFound: () => {}, + onMessage: () => {}, + onThinkingChange: (value) => thinking.push(value) + }); + + expect(thinking).toEqual([true, false, true, false]); + } finally { + queryMock.mockReset(); + querySpy.mockRestore(); + } + }); + it('waits for async onReady work before completing the result stream', async () => { const querySpy = vi.spyOn(claudeSdk, 'query').mockImplementation(queryMock as typeof claudeSdk.query); const { claudeRemote } = await import('./claudeRemote'); diff --git a/cli/src/claude/claudeRemote.ts b/cli/src/claude/claudeRemote.ts index 87536165..b5f64b50 100644 --- a/cli/src/claude/claudeRemote.ts +++ b/cli/src/claude/claudeRemote.ts @@ -509,6 +509,8 @@ export async function claudeRemote(opts: { specialCommand = nextSpecialCommand; pushUserMessage(next.message); setSteerable(nextSpecialCommand.type === null); + // A follow-up prompt starts a new turn; only the first turn gets system/init. + updateThinking(true); logger.debug( `${debugPrefix} nextMessage resolved fetchId=${fetchId} elapsedMs=${Date.now() - startedAt} ` + `messageLength=${next.message.length} permissionMode=${next.mode.permissionMode}` diff --git a/cli/src/claude/utils/startHappyServer.test.ts b/cli/src/claude/utils/startHappyServer.test.ts index bb369d66..575f5482 100644 --- a/cli/src/claude/utils/startHappyServer.test.ts +++ b/cli/src/claude/utils/startHappyServer.test.ts @@ -342,9 +342,28 @@ describe('startHappyServer skill_lookup', () => { } }) + it('forwards the spawned peer\'s reply when waitForReply is set', async () => { + const spawn = vi.spyOn(peerSpawn, 'spawnPeer').mockResolvedValue({ + sessionId: 'child-id', name: 'Worker', localId: 'ping-peer-1', flavor: 'codex' + }) + const forward = vi.spyOn(peerMessages, 'forwardPeerReply').mockResolvedValue() + try { + const mcp = await connect(false) + const result = await mcp.callTool({ + name: 'spawn_peer', + arguments: { directory: '/srv/project', message: 'Run the tests', waitForReply: true }, + }) as ToolResult + expect(result.content?.[0]?.text).toBe('Spawned child-id (Worker); its reply will be posted here') + expect(forward).toHaveBeenCalledWith({ peerSessionId: 'child-id', taskLocalId: 'ping-peer-1', callerSessionId: 'parent-id' }) + } finally { + spawn.mockRestore() + forward.mockRestore() + } + }) + it('forwards cross-machine spawn settings with the calling session identity and cwd', async () => { const spawn = vi.spyOn(peerSpawn, 'spawnPeer').mockResolvedValue({ - sessionId: 'child-id', name: 'Worker' + sessionId: 'child-id', name: 'Worker', flavor: 'codex' }) try { const mcp = await connect(false) diff --git a/cli/src/claude/utils/startHappyServer.ts b/cli/src/claude/utils/startHappyServer.ts index 6d5ef1ad..a3750f4e 100644 --- a/cli/src/claude/utils/startHappyServer.ts +++ b/cli/src/claude/utils/startHappyServer.ts @@ -29,6 +29,7 @@ import { LIST_PEERS_INCLUDE_INACTIVE_PARAM_DESCRIPTION, LIST_PEERS_TOOL_DESCRIPTION, PEER_DELIVERY_MODE_DESCRIPTION, + PEER_WAIT_FOR_REPLY_PARAM_DESCRIPTION, PEER_WAKE_PARAM_DESCRIPTION, PING_PEER_TOOL_DESCRIPTION, SESSION_ID_PREFIX_PARAM_DESCRIPTION, @@ -36,7 +37,7 @@ import { } from '@hapi/protocol/sessionCitation' import { CREATABLE_AGENT_FLAVORS } from '@hapi/protocol/modes' import { PermissionModeSchema } from '@hapi/protocol/schemas' -import { PingPeerError, formatInspectPeerReport, formatPeerSessionsList, inspectPeer, listPeerSessions, peerListFetchLimit, pingPeer } from "@/modules/pingPeer/pingPeer"; +import { PingPeerError, formatInspectPeerReport, formatPeerSessionsList, forwardPeerReply, inspectPeer, listPeerSessions, peerListFetchLimit, pingPeer, supportsPeerReply } from "@/modules/pingPeer/pingPeer"; import { applySessionDisplayRename, normalizeSessionDisplayTitle } from "@/agent/sessionDisplayRename"; import { SpawnPeerError, spawnPeer } from "@/modules/spawnPeer/spawnPeer"; @@ -200,11 +201,25 @@ function createHapiMcpServer( title: z.string().trim().min(1).max(255).optional().describe('Optional display title or filename'), }); + /** Start reply forwarding when asked; returns the note for the tool result. */ + const forwardReplyIfRequested = ( + waitForReply: boolean | undefined, + task: { sessionId: string; localId?: string; flavor?: string | null } + ): string => { + if (!waitForReply) return ''; + if (!task.localId) return '; the delivered message could not be identified, so check the reply with inspect_peer'; + if (!supportsPeerReply(task.flavor)) return `; ${task.flavor} peers do not report turn ends, so check the reply with inspect_peer`; + forwardPeerReply({ peerSessionId: task.sessionId, taskLocalId: task.localId, callerSessionId: client.sessionId }) + .catch((error) => logger.debug('[hapiMCP] peer reply forwarding failed:', error)); + return '; its reply will be posted here'; + }; + const pingPeerInputSchema: z.ZodTypeAny = z.object({ 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), + waitForReply: z.boolean().optional().describe(PEER_WAIT_FOR_REPLY_PARAM_DESCRIPTION), }); const spawnPeerInputSchema: z.ZodTypeAny = z.object({ @@ -230,6 +245,7 @@ function createHapiMcpServer( 'Permission mode for the new session. Omit to use hub/stock default (yolo). ' + 'Pass only to tighten or when the operator names a mode — do not clone the parent session.' ), + waitForReply: z.boolean().optional().describe(PEER_WAIT_FOR_REPLY_PARAM_DESCRIPTION), }); const maxInlineMediaBytes = 25 * 1024 * 1024; @@ -421,7 +437,7 @@ function createHapiMcpServer( description: PING_PEER_TOOL_DESCRIPTION, title: 'Ping Peer Session', inputSchema: pingPeerInputSchema, - }, async (args: { sessionIdPrefix: string; message: string; deliveryMode?: PeerDeliveryMode; wake?: boolean }) => { + }, async (args: { sessionIdPrefix: string; message: string; deliveryMode?: PeerDeliveryMode; wake?: boolean; waitForReply?: boolean }) => { logger.debug('[hapiMCP] ping_peer:', args.sessionIdPrefix); try { const result = await pingPeer({ @@ -430,13 +446,14 @@ function createHapiMcpServer( deliveryMode: args.deliveryMode, wake: args.wake === true, }); + const replyNote = forwardReplyIfRequested(args.waitForReply, result); return { content: [ { type: 'text' as const, text: result.delivery === 'accepted' - ? `Accepted for ${result.sessionId}${result.resumed ? ' (resumed)' : ''} (${result.name}) localId=${result.localId} — delivery shows in the recipient chat when its runtime consumes it${result.steerNote ? ` (${result.steerNote})` : ''}` - : `${result.delivery} to ${result.sessionId}${result.resumed ? ' (resumed)' : ''} (${result.name}) localId=${result.localId}`, + ? `Accepted for ${result.sessionId}${result.resumed ? ' (resumed)' : ''} (${result.name}) localId=${result.localId} — delivery shows in the recipient chat when its runtime consumes it${result.steerNote ? ` (${result.steerNote})` : ''}${replyNote}` + : `${result.delivery} to ${result.sessionId}${result.resumed ? ' (resumed)' : ''} (${result.name}) localId=${result.localId}${replyNote}`, }, ], isError: false, @@ -474,6 +491,7 @@ function createHapiMcpServer( effort?: string sessionType?: 'simple' | 'worktree' permissionMode?: string + waitForReply?: boolean }) => { logger.debug('[hapiMCP] spawn_peer:', args.directory, args.machine ? `machine=${args.machine}` : ''); try { @@ -505,7 +523,7 @@ function createHapiMcpServer( content: [ { type: 'text' as const, - text: `Spawned ${result.sessionId} (${result.name})`, + text: `Spawned ${result.sessionId} (${result.name})${forwardReplyIfRequested(args.waitForReply, result)}`, }, ], isError: false, diff --git a/cli/src/codex/happyMcpStdioBridge.ts b/cli/src/codex/happyMcpStdioBridge.ts index 69573cbc..e0ccdb95 100644 --- a/cli/src/codex/happyMcpStdioBridge.ts +++ b/cli/src/codex/happyMcpStdioBridge.ts @@ -24,6 +24,7 @@ import { LIST_PEERS_TOOL_DESCRIPTION, PEER_DELIVERY_MODE_DESCRIPTION, PEER_WAKE_PARAM_DESCRIPTION, + PEER_WAIT_FOR_REPLY_PARAM_DESCRIPTION, PING_PEER_TOOL_DESCRIPTION, SESSION_ID_PREFIX_PARAM_DESCRIPTION, SPAWN_PEER_TOOL_DESCRIPTION, @@ -223,6 +224,7 @@ export async function runHappyMcpStdioBridge(argv: string[]): Promise { 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), + waitForReply: z.boolean().optional().describe(PEER_WAIT_FOR_REPLY_PARAM_DESCRIPTION), }); if (toolNames.has('ping_peer')) { @@ -273,6 +275,7 @@ export async function runHappyMcpStdioBridge(argv: string[]): Promise { 'Permission mode for the new session. Omit to use hub/stock default (yolo). ' + 'Pass only to tighten or when the operator names a mode — do not clone the parent session.' ), + waitForReply: z.boolean().optional().describe(PEER_WAIT_FOR_REPLY_PARAM_DESCRIPTION), }); if (toolNames.has('spawn_peer')) { diff --git a/cli/src/modules/pingPeer/peerReply.test.ts b/cli/src/modules/pingPeer/peerReply.test.ts new file mode 100644 index 00000000..73bf973f --- /dev/null +++ b/cli/src/modules/pingPeer/peerReply.test.ts @@ -0,0 +1,144 @@ +import { describe, expect, it } from 'vitest' +import type { AxiosInstance } from 'axios' +import { forwardPeerReply } from './pingPeer' + +const peer = { id: 'peer-1', active: true, metadata: { name: 'Peer' } } + +type Poll = { + thinking: boolean + invoked: boolean + reply?: string + /** Output of the turn a steered task joined, before the task was picked up. */ + earlier?: string + replyAfterTask?: boolean + later?: string + batched?: boolean + ready?: boolean + active?: boolean +} + +function hub(options: { polls?: Poll[]; scheduled?: string; canceled?: boolean; offPage?: boolean } = {}) { + const posts: Array<{ url: string; body: any }> = [] + const polls = [...(options.polls ?? [])] + let current = polls[0] + const http = { + post: async (url: string, body: any) => { + posts.push({ url, body }) + if (url.endsWith('/api/auth')) return { status: 200, data: { token: 'jwt' } } + if (url.endsWith('/queued-state')) return { status: 200, data: { queuedLocalIds: [], indeterminateLocalIds: [], invokedLocalMessages: options.offPage ? [{ localId: 'task-1', invokedAt: 10 }] : [] } } + return { status: 200, data: { ok: true } } + }, + get: async (url: string, config?: { params?: Record }) => { + if (url.endsWith('/api/sessions')) return { status: 200, data: { sessions: [peer] } } + if (url.endsWith('/messages')) { + // Rows in hub position order (invokedAt ?? createdAt); the task sits at 10. + const text = (role: string, value: string) => ({ role, content: { type: 'text', text: value } }) + const c = current! + const before: any[] = [] + const after: any[] = [] + if (c.earlier) before.push({ id: 'u0', localId: 'task-0', invoked: true, content: text('user', 'earlier task') }, { id: 'r0', content: text('agent', c.earlier) }) + if (c.reply) (c.invoked || c.replyAfterTask ? after : before).push({ id: 'r', content: text('agent', c.reply) }) + if (c.batched) after.unshift({ id: 'u1', localId: 'task-1b', batched: true, content: text('user', 'and this') }) + if (c.later) after.push({ id: 'u2', localId: 'task-2', invoked: true, content: text('user', 'next task') }, { id: 'r2', content: text('agent', c.later) }) + if (c.ready) after.push({ id: 'e', content: { role: 'agent', content: { type: 'event', data: { type: 'ready' } } } }) + if (options.scheduled) after.push({ id: 's', scheduledAt: 1, content: text('user', options.scheduled) }) + const task = { id: 't', localId: 'task-1', invoked: c.invoked, content: text('user', 'task') } + const rows: any[] = [ + ...before.map((row, i) => ({ ...row, seq: i + 1 })), + ...(options.canceled ? [] : [{ ...task, seq: 10 }]), + ...after.map((row, i) => ({ ...row, seq: 11 + i })) + ].map(({ invoked, batched, ...row }) => ({ + ...row, + createdAt: row.seq, + invokedAt: batched ? (c.invoked ? 10 : null) : invoked ? row.seq : row.content.role === 'user' ? null : undefined + })) + const { afterAt, afterSeq } = config?.params ?? {} + if (afterSeq !== undefined && !(afterSeq >= 1 && afterAt >= 0)) return { status: 400, data: { error: 'Invalid query' } } + if (afterSeq === undefined) return { status: 200, data: { messages: options.offPage ? rows.filter((row) => row.seq > 10) : rows } } + // Two rows per page to exercise forward paging. + const page = rows.filter((row) => row.createdAt > afterAt || (row.createdAt === afterAt && row.seq > afterSeq)).slice(0, 2) + const tail = page.at(-1) + const hasMore = tail !== undefined && tail !== rows.at(-1) + return { status: 200, data: { messages: page, page: { hasMore, nextAfterAt: tail?.createdAt, nextAfterSeq: tail?.seq } } } + } + current = polls.shift() ?? current + return { status: 200, data: { session: { ...peer, active: current?.active ?? true, thinking: current?.thinking ?? false } } } + } + } as unknown as AxiosInstance + return { http, posts, auth: { apiUrl: 'http://hub.test', accessToken: 'token', http } } +} + +async function forwarded(polls: Poll[], scheduled?: string, canceled?: boolean, offPage?: boolean) { + const { posts, auth } = hub({ polls, scheduled, canceled, offPage }) + await forwardPeerReply({ ...auth, peerSessionId: 'peer-1', taskLocalId: 'task-1', callerSessionId: 'caller', sleep: async () => {} }) + return posts.filter((p) => p.url.endsWith('/sessions/caller/messages')).map((p) => p.body.text) +} + +describe('forwardPeerReply', () => { + const done = (reply?: string): Poll => ({ thinking: false, invoked: true, reply, ready: true }) + + it('posts the full reply once the turn after the task ends', async () => { + const long = `line 1\n\n${'x'.repeat(2_000)}` + expect(await forwarded([ + { thinking: false, invoked: false, reply: 'earlier answer', ready: true }, + { thinking: true, invoked: true, reply: 'working' }, + done(long), + done(long) + ])).toEqual([`Reply from peer [Peer](/sessions/peer-1):\n\n${long}`]) + }) + + it('does not treat idle text without a ready event as the end of the turn', async () => { + const idle = Array.from({ length: 10 }, () => ({ thinking: false, invoked: true, reply: 'partial' })) + expect(await forwarded([...idle, done('final'), done('final')])) + .toEqual(['Reply from peer [Peer](/sessions/peer-1):\n\nfinal']) + }) + + it('keeps the task\'s answer apart from the reply after a later message', async () => { + const both = { ...done('answer 1'), later: 'answer 2' } + expect(await forwarded([both, both])).toEqual([ + 'Reply from peer [Peer](/sessions/peer-1):\n\nanswer 1\n\n' + + 'The peer then took 1 more message(s), a steer or a later task, before its turn ended. Its latest reply:\n\nanswer 2' + ]) + }) + + it('forwards the end of the turn a steered task joined, not output from before it', async () => { + const steered = { ...done('answer with the steer'), earlier: 'progress on the earlier task' } + expect(await forwarded([steered, steered])).toEqual(['Reply from peer [Peer](/sessions/peer-1):\n\nanswer with the steer']) + }) + + it('treats prompts consumed with the task as one turn', async () => { + const both = { ...done('answer to both'), batched: true } + expect(await forwarded([both, both])).toEqual(['Reply from peer [Peer](/sessions/peer-1):\n\nanswer to both']) + }) + + it('finds a consumed task that is already off the latest page', async () => { + expect(await forwarded([done('done'), done('done')], undefined, false, true)) + .toEqual(['Reply from peer [Peer](/sessions/peer-1):\n\ndone']) + }) + + it('reports a turn that ended without a reply', async () => { + expect(await forwarded([done(), done()])).toEqual(['Peer [Peer](/sessions/peer-1) stopped without replying.']) + }) + + it('finishes when the peer session stops', async () => { + const stopped = { thinking: false, invoked: true, active: false } + expect(await forwarded([stopped, stopped])).toEqual(['Peer [Peer](/sessions/peer-1) stopped without replying.']) + }) + + it('keeps waiting when the peer goes offline before reading the task', async () => { + const offline = { thinking: false, invoked: false, active: false, reply: 'answer to an earlier task', replyAfterTask: true } + expect(await forwarded([offline, offline, offline, done('answer'), done('answer')])) + .toEqual(['Reply from peer [Peer](/sessions/peer-1):\n\nanswer']) + }) + + it('reports a canceled task instead of forwarding an unrelated answer', async () => { + expect(await forwarded([ + { thinking: false, invoked: false, reply: 'answer to an earlier task' } + ], undefined, true)).toEqual(['The task sent to peer [Peer](/sessions/peer-1) was canceled before it ran.']) + }) + + it('ignores a pending scheduled message after the reply', async () => { + expect(await forwarded([done('done'), done('done')], 'later')) + .toEqual(['Reply from peer [Peer](/sessions/peer-1):\n\ndone']) + }) +}) diff --git a/cli/src/modules/pingPeer/pingPeer.test.ts b/cli/src/modules/pingPeer/pingPeer.test.ts index 6f425347..8521709d 100644 --- a/cli/src/modules/pingPeer/pingPeer.test.ts +++ b/cli/src/modules/pingPeer/pingPeer.test.ts @@ -132,7 +132,8 @@ describe('pingPeer', () => { sessionId, name: 'Orchestrator', resumed: false, - delivery: 'accepted' + delivery: 'accepted', + flavor: 'cursor' }) expect(result.localId).toMatch(/^ping-peer-/) expect(http.post.mock.calls[1]?.[1]).toEqual({ text: 'hello peer', localId: result.localId }) @@ -394,6 +395,7 @@ describe('pingPeer', () => { name: 'Spawned', resumed: false, delivery: 'accepted', + flavor: 'cursor', steerNote: expect.stringMatching(/^steer not attempted: /), localId: expect.stringMatching(/^ping-peer-/), }) diff --git a/cli/src/modules/pingPeer/pingPeer.ts b/cli/src/modules/pingPeer/pingPeer.ts index b2fa6c91..a350bf61 100644 --- a/cli/src/modules/pingPeer/pingPeer.ts +++ b/cli/src/modules/pingPeer/pingPeer.ts @@ -126,6 +126,7 @@ export type PingPeerResult = { * HTTP success below means hub-accepted, which may race that ACK. */ localId: string + flavor?: string | null } /** @@ -818,6 +819,7 @@ export async function pingPeer(options: PingPeerOptions): Promise MAX_SNIPPET_CHARS + if (!text?.trim()) return null + const trimmed = full ? text.trim() : text.replace(/\s+/g, ' ').trim() + const snippet = !full && trimmed.length > MAX_SNIPPET_CHARS ? `${trimmed.slice(0, MAX_SNIPPET_CHARS)}…` : trimmed return { @@ -923,18 +927,26 @@ export function extractInspectMessageSnippet(content: unknown): InspectPeerMessa } } +/** Launchers post `{ type: 'event', data: { type: 'ready' } }` when a turn ends and their queue is empty. */ +function isReadyEvent(content: unknown): boolean { + return isObject(content) && isObject(content.content) && content.content.type === 'event' + && isObject(content.content.data) && content.content.data.type === 'ready' +} + async function fetchSessionMessages( apiUrl: string, jwt: string, sessionId: string, limit: number, - http: AxiosInstance -): Promise { + http: AxiosInstance, + watch = false, + after?: { at: number; seq: number } +): Promise<{ messages: InspectPeerMessage[]; next: { at: number; seq: number } | null }> { const response = await http.get( `${apiUrl}/api/sessions/${encodeURIComponent(sessionId)}/messages`, { headers: authHeaders(jwt), - params: { limit }, + params: after ? { limit, afterAt: after.at, afterSeq: after.seq } : { limit }, timeout: 20_000, validateStatus: () => true } @@ -949,15 +961,30 @@ async function fetchSessionMessages( const out: InspectPeerMessage[] = [] for (const row of rows) { if (!isObject(row)) continue - const snippet = extractInspectMessageSnippet(row.content) + // A future scheduled message is not part of the turn being watched. + if (watch && row.invokedAt == null && typeof row.scheduledAt === 'number') continue + const isUser = isObject(row.content) && row.content.role === 'user' + const snippet = watch && isReadyEvent(row.content) + ? { id: '', role: 'ready', text: '', createdAt: null } + // A text-less user row still bounds the watched turn. + : extractInspectMessageSnippet(row.content, watch) ?? (watch && isUser ? { id: '', role: 'user', text: '', createdAt: null } : null) if (!snippet) continue out.push({ ...snippet, id: typeof row.id === 'string' ? row.id : snippet.id, - createdAt: typeof row.createdAt === 'number' ? row.createdAt : null + createdAt: typeof row.createdAt === 'number' ? row.createdAt : null, + ...(watch ? { + seq: typeof row.seq === 'number' ? row.seq : undefined, + invokedAt: typeof row.invokedAt === 'number' ? row.invokedAt : null + } : {}), + ...(typeof row.localId === 'string' ? { localId: row.localId } : {}) }) } - return out + const page = response.data?.page + const next = after && page?.hasMore === true && typeof page.nextAfterAt === 'number' && typeof page.nextAfterSeq === 'number' + ? { at: page.nextAfterAt, seq: page.nextAfterSeq } + : null + return { messages: out, next } } /** @@ -981,7 +1008,7 @@ export async function inspectPeer(options: InspectPeerOptions): Promise { + const response = await http.post( + `${apiUrl}/api/sessions/${encodeURIComponent(sessionId)}/messages/queued-state`, + { localIds: [localId] }, + { headers: authHeaders(jwt), timeout: 20_000, validateStatus: () => true } + ) + if (response.status < 200 || response.status >= 300) { + throw new PingPeerError('not_found', `failed to load task state for ${sessionId} (HTTP ${response.status})`) + } + const list = (key: string): unknown[] => Array.isArray(response.data?.[key]) ? response.data[key] : [] + const invoked = list('invokedLocalMessages').find((entry: any) => entry?.localId === localId) as { invokedAt?: unknown } | undefined + if (typeof invoked?.invokedAt === 'number') return { state: 'invoked', invokedAt: invoked.invokedAt } + return [...list('queuedLocalIds'), ...list('indeterminateLocalIds')].includes(localId) ? { state: 'queued' } : { state: 'gone' } +} + +const ROWS_PAGE = 200 + +/** An after-cursor that includes every row positioned at `at` (the hub requires afterSeq >= 1). */ +function cursorBefore(at: number): { at: number; seq: number } { + return { at: at - 1, seq: Number.MAX_SAFE_INTEGER } +} + +async function fetchRowsAfter( + apiUrl: string, + jwt: string, + sessionId: string, + after: { at: number; seq: number }, + http: AxiosInstance +): Promise { + const rows: InspectPeerMessage[] = [] + for (let cursor: typeof after | null = after; cursor;) { + const page = await fetchSessionMessages(apiUrl, jwt, sessionId, ROWS_PAGE, http, true, cursor) + rows.push(...page.messages) + cursor = page.next + } + return rows +} + +export type ForwardPeerReplyOptions = { + peerSessionId: string + /** `PingPeerResult.localId` of the task whose reply is awaited. */ + taskLocalId: string + callerSessionId: string + apiUrl?: string + accessToken?: string + http?: AxiosInstance + sleep?: (ms: number) => Promise + now?: () => number +} + +/** + * Wait for the peer to finish its turn, then post its latest reply into the + * caller session. The caller wakes with the answer instead of polling. + * ponytail: polls from this CLI process; if it exits first, the reply stays only in the peer session. + */ +export async function forwardPeerReply(options: ForwardPeerReplyOptions): Promise { + const apiUrl = resolveApiUrl(options.apiUrl) + const accessToken = resolveAccessToken(options.accessToken) + const http = options.http ?? axios + const sleep = options.sleep ?? defaultSleep + const now = options.now ?? Date.now + const deadline = now() + REPLY_TIMEOUT_MS + let name = options.peerSessionId.slice(0, 8) + let reply: InspectPeerMessage | undefined + let latest: InspectPeerMessage | undefined + let laterPrompts = 0 + // Confirm on two polls in a row: a `ready` left by the previous turn can trail the task row. + let endedPolls = 0 + let idlePolls = 0 + let canceled = false + let consumed = false + let anchor: { at: number; seq: number } | undefined + const finished = () => endedPolls >= 2 || idlePolls >= IDLE_FALLBACK_POLLS + while (!canceled && !finished() && now() < deadline) { + await sleep(REPLY_POLL_MS) + try { + const jwt = await exchangeJwt(apiUrl, accessToken, http) + const session = await getSession(apiUrl, jwt, options.peerSessionId, http) + name = resolvePeerSessionLabel(session) + // Anchor once on the task row, then page forward from it. Queued rows are always on the latest + // page; a consumed row sits at its invokedAt. + if (!anchor) { + const { messages: latest } = await fetchSessionMessages(apiUrl, jwt, options.peerSessionId, 50, http, true) + const row = latest.find((m) => m.localId === options.taskLocalId) + if (row?.createdAt != null) anchor = cursorBefore(row.createdAt) + } + let rows = anchor ? await fetchRowsAfter(apiUrl, jwt, options.peerSessionId, anchor, http) : [] + let task = rows.find((m) => m.localId === options.taskLocalId) + if (!task) { + const state = await fetchTaskState(apiUrl, jwt, options.peerSessionId, options.taskLocalId, http) + // The hub deletes canceled rows. + canceled = state.state === 'gone' + if (state.state !== 'invoked') throw new PingPeerError('not_found', 'task row not found') + anchor = cursorBefore(state.invokedAt) + rows = await fetchRowsAfter(apiUrl, jwt, options.peerSessionId, anchor, http) + task = rows.find((m) => m.localId === options.taskLocalId) + if (!task) throw new PingPeerError('not_found', 'task row not found') + } + consumed = task.invokedAt != null + const after = rows.slice(rows.indexOf(task) + 1) + const last = after.filter((m) => m.role !== 'user').at(-1) + // Rows are ordered by consumption, so the answer ends at the next prompt the peer took on its own; + // prompts consumed together with the task share its turn. The hub does not persist whether that + // prompt steered this turn or started a new one, so the latest reply is reported alongside. + const isText = (m: InspectPeerMessage) => m.role !== 'user' && m.role !== 'ready' + const isLaterPrompt = (m: InspectPeerMessage) => m.role === 'user' && m.invokedAt != null && m.invokedAt !== task!.invokedAt + const next = after.findIndex(isLaterPrompt) + reply = consumed ? (next === -1 ? after : after.slice(0, next)).filter(isText).at(-1) : undefined + latest = consumed && next !== -1 ? after.slice(next).filter(isText).at(-1) : undefined + laterPrompts = after.filter(isLaterPrompt).length + const ended = consumed && !session.thinking && last?.role === 'ready' + // The hub keeps an unconsumed peer task for replay, so a peer that went offline before reading it + // may still run it after a resume: only a stop after consumption ends the watch. + endedPolls = consumed && (ended || !session.active) ? endedPolls + 1 : 0 + idlePolls = consumed && !session.thinking ? idlePolls + 1 : 0 + } catch { + endedPolls = 0 + idlePolls = 0 + } + } + const link = `[${name}](/sessions/${options.peerSessionId})` + const text = canceled + ? `The task sent to peer ${link} was canceled before it ran.` + : !finished() + ? `Peer ${link} has not finished after ${REPLY_TIMEOUT_MS / 3_600_000}h; check it with inspect_peer.` + : latest + ? `Reply from peer ${link}:\n\n${reply?.text ?? '(nothing before its next message)'}\n\n` + + `The peer then took ${laterPrompts} more message(s), a steer or a later task, before its turn ended. Its latest reply:\n\n${latest.text}` + : reply + ? `Reply from peer ${link}:\n\n${reply.text}` + : `Peer ${link} stopped without replying.` + // One localId across retries so a resend after a lost response is not stored twice. + const localId = createPeerMessageLocalId() + for (let attempt = 1; ; attempt++) { + try { + const jwt = await exchangeJwt(apiUrl, accessToken, http) + await sendMessage(apiUrl, jwt, options.callerSessionId, text, localId, http, 'queue') + return + } catch (error) { + if (attempt >= SEND_ATTEMPTS) throw error + await sleep(REPLY_POLL_MS) + } + } +} diff --git a/cli/src/modules/spawnPeer/spawnPeer.test.ts b/cli/src/modules/spawnPeer/spawnPeer.test.ts index 030ad0d9..a91949a1 100644 --- a/cli/src/modules/spawnPeer/spawnPeer.test.ts +++ b/cli/src/modules/spawnPeer/spawnPeer.test.ts @@ -627,7 +627,9 @@ it('resolves relative directory against cwd (MCP session working directory)', as expect(result).toEqual({ sessionId: SESSION_ID, - name: 'Peer #1509: spawn-peer remit' + name: 'Peer #1509: spawn-peer remit', + localId: (delivered as { localId?: string } | undefined)?.localId, + flavor: 'cursor' }) expect(spawnedBody).toMatchObject({ directory: '/home/u/coding/hapi/worktrees/spawn-peer-remit', @@ -972,7 +974,7 @@ it('resolves relative directory against cwd (MCP session working directory)', as http: http as never }) - expect(result).toEqual({ sessionId: SESSION_ID, name: SESSION_ID.slice(0, 8) }) + expect(result).toEqual({ sessionId: SESSION_ID, name: SESSION_ID.slice(0, 8), flavor: 'claude' }) }) it('does not report a requested name when rename failed and ping-peer threw', async () => { diff --git a/cli/src/modules/spawnPeer/spawnPeer.ts b/cli/src/modules/spawnPeer/spawnPeer.ts index 6a05056f..4310a85a 100644 --- a/cli/src/modules/spawnPeer/spawnPeer.ts +++ b/cli/src/modules/spawnPeer/spawnPeer.ts @@ -129,6 +129,9 @@ export type SpawnPeerOptions = { export type SpawnPeerResult = { sessionId: string name: string + /** The remit's ping-peer localId; unknown when its delivery call failed but the remit still landed. */ + localId?: string + flavor: AgentFlavor } const DEFAULT_WAIT_ACTIVE_SECS = 60 @@ -673,7 +676,7 @@ export async function spawnPeer(options: SpawnPeerOptions): Promise)` 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); with `waitForReply`, `ping_peer` and `spawn_peer` post the peer's reply back when its turn ends. `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/shared/src/sessionCitation.ts b/shared/src/sessionCitation.ts index e87ec67f..e8ae0001 100644 --- a/shared/src/sessionCitation.ts +++ b/shared/src/sessionCitation.ts @@ -66,6 +66,10 @@ 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 ping_peer / spawn_peer `waitForReply`. */ +export const PEER_WAIT_FOR_REPLY_PARAM_DESCRIPTION = + 'Post the peer\'s reply into this session when its turn ends (default false). End your turn after calling; do not poll.' + /** 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.'