mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-25 05:07:05 +00:00
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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -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<string, number> }) => {
|
||||
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'])
|
||||
})
|
||||
})
|
||||
@@ -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-/),
|
||||
})
|
||||
|
||||
@@ -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<PingPeerResult
|
||||
resumed,
|
||||
localId,
|
||||
delivery: sent.delivery,
|
||||
flavor: live.metadata?.flavor ?? null,
|
||||
...(steerNote ? { steerNote } : {})
|
||||
}
|
||||
}
|
||||
@@ -859,6 +861,9 @@ export type InspectPeerMessage = {
|
||||
role: string
|
||||
text: string
|
||||
createdAt: number | null
|
||||
localId?: string
|
||||
seq?: number
|
||||
invokedAt?: number | null
|
||||
}
|
||||
|
||||
export type InspectPeerResult = {
|
||||
@@ -898,7 +903,7 @@ function extractUserPlainText(inner: unknown): string | null {
|
||||
}
|
||||
|
||||
/** Best-effort text from a hub message row; skip tool-call / empty noise. */
|
||||
export function extractInspectMessageSnippet(content: unknown): InspectPeerMessage | null {
|
||||
export function extractInspectMessageSnippet(content: unknown, full = false): InspectPeerMessage | null {
|
||||
if (!isObject(content)) return null
|
||||
const role = typeof content.role === 'string' ? content.role : 'unknown'
|
||||
const inner = content.content
|
||||
@@ -909,10 +914,9 @@ export function extractInspectMessageSnippet(content: unknown): InspectPeerMessa
|
||||
text = extractAssistantPlainText(inner)
|
||||
if (!text) text = extractUserPlainText(inner)
|
||||
}
|
||||
if (!text) return null
|
||||
const trimmed = text.replace(/\s+/g, ' ').trim()
|
||||
if (!trimmed) return null
|
||||
const snippet = trimmed.length > 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<InspectPeerMessage[]> {
|
||||
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<InspectP
|
||||
const matched = resolveSessionByPrefix(sessions, prefix)
|
||||
const live = await getSession(apiUrl, jwt, matched.id, http)
|
||||
const meta = live.metadata ?? matched.metadata ?? null
|
||||
const [messages, machineLabels] = await Promise.all([
|
||||
const [{ messages }, machineLabels] = await Promise.all([
|
||||
fetchSessionMessages(apiUrl, jwt, matched.id, messageLimit, http),
|
||||
fetchMachineLabels(apiUrl, jwt, http)
|
||||
])
|
||||
@@ -1106,3 +1133,169 @@ export async function setPeerPermissionMode(options: SetPeerPermissionModeOption
|
||||
active: live.active
|
||||
}
|
||||
}
|
||||
|
||||
// ── Peer reply forwarding ───────────────────────────────────────────
|
||||
|
||||
const REPLY_POLL_MS = 10_000
|
||||
const REPLY_TIMEOUT_MS = 6 * 60 * 60 * 1000
|
||||
// ponytail: fallback for a dropped `ready` event (sent droppable while the peer's socket is down).
|
||||
const IDLE_FALLBACK_POLLS = 60
|
||||
const SEND_ATTEMPTS = 3
|
||||
|
||||
/** Flavors whose remote launchers post a `ready` event at turn end; Pi does not. */
|
||||
const PEER_REPLY_FLAVORS = new Set(['claude', 'codex', 'cursor', 'opencode', 'copilot', 'kimi', 'grok', 'dsh', 'agy'])
|
||||
|
||||
export function supportsPeerReply(flavor: string | null | undefined): boolean {
|
||||
return PEER_REPLY_FLAVORS.has(flavor ?? 'claude')
|
||||
}
|
||||
|
||||
async function fetchTaskState(
|
||||
apiUrl: string,
|
||||
jwt: string,
|
||||
sessionId: string,
|
||||
localId: string,
|
||||
http: AxiosInstance
|
||||
): Promise<{ state: 'invoked'; invokedAt: number } | { state: 'queued' | 'gone' }> {
|
||||
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<InspectPeerMessage[]> {
|
||||
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<void>
|
||||
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<void> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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<SpawnPeerRes
|
||||
}
|
||||
|
||||
onProgress?.(`delivering remit (${message.length} chars) via ping-peer path...`)
|
||||
let pingResult: { sessionId: string; name: string } | undefined
|
||||
let pingResult: { sessionId: string; name: string; localId: string } | undefined
|
||||
let deliveryError: unknown
|
||||
try {
|
||||
pingResult = await pingPeer({
|
||||
@@ -707,7 +710,9 @@ export async function spawnPeer(options: SpawnPeerOptions): Promise<SpawnPeerRes
|
||||
sessionId,
|
||||
name: renamed
|
||||
? requestedName
|
||||
: pingResult?.name || sessionId.slice(0, 8)
|
||||
: pingResult?.name || sessionId.slice(0, 8),
|
||||
localId: pingResult?.localId,
|
||||
flavor: resolved.agent
|
||||
}
|
||||
}
|
||||
lastVerify = verify
|
||||
|
||||
Reference in New Issue
Block a user